diff --git "a/134.jsonl" "b/134.jsonl" new file mode 100644--- /dev/null +++ "b/134.jsonl" @@ -0,0 +1,653 @@ +{"seq_id":"247219504","text":"import requests\n# 指定搜索关键字\nword = input('enter a word you want to search:')\n# 自定义请求头信息:UA伪装,将包含了User-Agent的字典作用到请求方法的headers参数中即可\nheaders={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',\n }\n# 指定url,原始url可能是https://www.sogou.com/web?query=撩妹,发现该url携带了参数\nurl = 'https://www.sogou.com/web'\n# 封装get请求参数:如果请求携带了参数,则可以将参数封装到字典中结合这requests请求方法中的data/params参数进行url参数的处理\nparam = {\n 'query':word,\n}\n# 发起请求\nresponse = requests.get(url=url,params=param,headers=headers)\n# 获取响应数据\npage_text = response.text\n# 持久化存储\nfileName = word+'.html'\nwith open(fileName,'w',encoding='utf-8') as fp:\n fp.write(page_text)","sub_path":"requests/指定关键字.py","file_name":"指定关键字.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"608414027","text":"import os, cv2, csv, json, sys, io\nimport operator, argparse, requests\nimport pandas as pd\nimport sqlite3\nfrom datetime import datetime\nfrom utils.server_utils import get_sites_movies_species\nimport utils.db_utils as db_utils\nimport utils.koster_utils as koster_utils\nimport utils.spyfish_utils as spyfish_utils\nimport utils.movie_utils as movie_utils\n\n\ndef add_sites(sites_csv, db_path):\n\n # Load the csv with sites information\n sites_df = pd.read_csv(sites_csv)\n \n \n # Select relevant fields\n sites_df = sites_df[\n [\"site_id\", \"siteName\", \"decimalLatitude\", \"decimalLongitude\", \"geodeticDatum\", \"countryCode\"]\n ]\n \n # Roadblock to prevent empty lat/long/datum/countrycode\n db_utils.test_table(\n sites_df, \"sites\", sites_df.columns\n )\n\n # Add values to sites table\n db_utils.add_to_table(\n db_path, \"sites\", [tuple(i) for i in sites_df.values], 6\n )\n\n \ndef add_movies(movies_csv, movies_path, project_name, db_path):\n\n # Load the csv with movies information\n movies_df = pd.read_csv(movies_csv)\n \n # Check if the project is the Spyfish Aotearoa\n if project_name == \"Spyfish_Aotearoa\":\n # Specify the key (path in S3 of the object)\n movies_df[\"Fpath\"] = movies_df[\"prefix\"] + \"/\" + movies_df[\"filename\"]\n \n # Remove extension from the filename\n movies_df[\"filename\"] = movies_df[\"filename\"].str.split('.',1).str[0]\n \n # Check if the project is the KSO\n if project_name == \"Koster_Seafloor_Obs\":\n movies_df = koster_utils.process_koster_movies_csv(movies_df, movies_path)\n \n # Ensure all videos have fps, duration, starting and ending time of the survey\n movies_df = movie_utils.get_movie_parameters(movies_df, movies_csv, project_name)\n \n # Ensure date is ISO 8601:2004(E) compatible with Darwin Data standards\n #try:\n # date.fromisoformat(movies_df['eventDate'])\n #except ValueError:\n # print(\"Invalid eventDate column\")\n\n # Connect to database\n conn = db_utils.create_connection(db_path)\n \n # Reference movies with their respective sites\n sites_df = pd.read_sql_query(\"SELECT id, siteName FROM sites\", conn)\n sites_df = sites_df.rename(columns={\"id\": \"Site_id\"})\n\n # Merge movies and sites dfs\n movies_df = pd.merge(\n movies_df, sites_df, how=\"left\", on=\"siteName\"\n )\n \n # Select only those fields of interest\n movies_db = movies_df[\n [\"movie_id\", \"filename\", \"created_on\", \"fps\", \"duration\", \"survey_start\", \"survey_end\", \"Author\", \"Site_id\", \"Fpath\"]\n ]\n\n # Roadblock to prevent empty information\n db_utils.test_table(\n movies_db, \"movies\", movies_db.columns\n )\n \n # Add values to movies table\n db_utils.add_to_table(\n db_path, \"movies\", [tuple(i) for i in movies_db.values], 10\n )\n\n\ndef add_species(species_csv, db_path):\n\n # Load the csv with species information\n species_df = pd.read_csv(species_csv)\n \n # Select relevant fields\n species_df = species_df[\n [\"species_id\", \"commonName\", \"scientificName\", \"taxonRank\", \"kingdom\"]\n ]\n \n # Roadblock to prevent empty information\n db_utils.test_table(\n species_df, \"species\", species_df.columns\n )\n \n # Add values to species table\n db_utils.add_to_table(\n db_path, \"species\", [tuple(i) for i in species_df.values], 5\n )\n \n\ndef static_setup(movies_path: str,\n project_name: str,\n db_path: str): \n \n # Get the location of the csv files with initial info to populate the db\n sites_csv, movies_csv, species_csv = get_sites_movies_species()\n \n add_sites(sites_csv, db_path)\n add_movies(movies_csv, movies_path, project_name, db_path)\n add_species(species_csv, db_path)\n","sub_path":"db_starter/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"443939698","text":"import numpy as np\nimport keras\nfrom keras.layers import Dense\nimport logging\n\n\nclass DQNAgent():\n def __init__(self, player, actions, state_space, train_start=0, exploration_prob_init=1, exploration_prob_train=0.2,\n exporation_prop_decay=0.9, y=0.95, log_level=logging.WARNING):\n self.exploration_prob_train = exploration_prob_train\n self.player = player\n self.id = player.id\n self.state_space = state_space\n self.action_keys = actions.keys()\n self.actions = actions.values()\n self.rewards = []\n self.last_state = None\n self.last_action = None\n\n self.train_start = train_start\n self.y = y\n self.exploration_prob = exploration_prob_init\n self.exploration_prob_decay = exporation_prop_decay\n\n self.logger = logging.Logger(\"P%i\" % self.id)\n self.logger.setLevel(log_level)\n\n self.q_list = []\n\n # create console handler and set level to debug\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n\n # create formatter\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n # add formatter to ch\n ch.setFormatter(formatter)\n\n # add ch to logger\n self.logger.addHandler(ch)\n\n self.nn = self._buildNN()\n\n def pick_action(self, state, rewards, time):\n\n if time > 0 and time % 10000 == 0:\n self.exploration_prob = self.exploration_prob * self.exploration_prob_decay\n self.logger.info(\"Exploration prob decreased to %f\" % self.exploration_prob)\n\n if self.player.alive == 2 and not self.player.spawning:\n qAll, action_idx = self._predict_action(state)\n self.logger.debug(\"Predicted action: %s\" % self.action_keys[action_idx])\n if np.random.uniform() < self.exploration_prob:\n action_idx = np.random.randint(0, len(self.actions))\n\n self.q_list.append([state, qAll, action_idx])\n\n self.last_state = state\n self.last_action = action_idx\n self.alive_last_round = True\n return self.actions[action_idx]\n else:\n self.alive_last_round = False\n self.last_state = None\n self.last_action = None\n return self.actions[self.action_keys.index(\"p%i_noop\" % self.id)]\n\n def _buildNN(self):\n nn = keras.Sequential()\n nn.add(Dense(units=len(self.actions), activation=\"softmax\", input_dim=self.state_space[1]))\n nn.compile(loss='mse',\n optimizer='adam')\n\n return nn\n\n def _predict_action(self, state):\n q_all = self.nn.predict(state)[0]\n return q_all, np.argmax(q_all)\n\n def store_reward(self, rewards):\n self.rewards.append(rewards[self.id - 1])\n\n def train(self, rewards, new_state):\n if self.last_state is not None and self.alive_last_round:\n # get own reward\n r = rewards[self.id - 1]\n\n target = r + self.y * np.max(self.nn.predict(new_state)) - self.nn.predict(self.last_state)[0][\n self.last_action]\n target_vec = self.nn.predict(self.last_state)[0]\n target_vec[self.last_action] = target\n self.nn.fit(self.last_state, target_vec.reshape(-1, len(self.actions)), epochs=1, verbose=False)\n\n def replay_memories(self, final_reward1):\n X = np.zeros([len(self.q_list), self.state_space[1]])\n Y = np.zeros([len(self.q_list), len(self.actions)])\n for index, (state, qAll, a_i) in enumerate(self.q_list):\n qAll[a_i] = final_reward1\n Y[index, :] = qAll\n X[index] = state\n\n self.nn.fit(X, Y, epochs=1, verbose=False)\n self.q_list = []\n","sub_path":"test_agent.py","file_name":"test_agent.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"575153100","text":"PROJECT_ATTRIBUTE_KEY_URL = 'project_attribute_keys/'\nPROJECT_URL = 'projects/'\nPROJECT_ATTRIBUTE_URL = 'project_attributes/'\nCONSUMPTION_METADATA_URL = 'consumption_metadatas/'\nCONSUMPTION_RECORD_URL = 'consumption_records/'\nCONSUMPTION_RECORD_SYNC_URL = 'consumption_records/sync/'\n\nSTANDARD_PROJECT_DATA_COLUMN_NAMES = [\n \"project_id\",\n \"zipcode\",\n \"weather_station\",\n \"latitude\",\n \"longitude\",\n \"baseline_period_start\", # handle this specially? it won't appear in most project dataframes\n \"baseline_period_end\",\n \"reporting_period_start\",\n \"reporting_period_end\", # handle this specially? it won't appear in most project dataframes\n]\n\nSTANDARD_PROJECT_ATTRIBUTE_KEYS = {\n \"predicted_electricity_savings\": {\n \"name\": \"predicted_electricity_savings\",\n \"display_name\": \"Estimated Electricity Savings\",\n \"data_type\": \"FLOAT\",\n },\n \"predicted_natural_gas_savings\": {\n \"name\": \"predicted_natural_gas_savings\",\n \"display_name\": \"Estimated Natural Gas Savings\",\n \"data_type\": \"FLOAT\",\n },\n \"project_cost\": {\n \"name\": \"project_cost\",\n \"display_name\": \"Project Cost\",\n \"data_type\": \"FLOAT\",\n },\n}\n\nFUEL_TYPES = {\n \"electricity\": \"E\",\n \"natural_gas\": \"NG\",\n}\n\nENERGY_UNIT = {\n \"kWh\": \"KWH\",\n \"therms\": \"THM\",\n}\n","sub_path":"eemeter/uploader/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"31220968","text":"# -coding: UTF-8 -*-\n# @Time : 2020/06/24 20:01\n# @Author: Liangping_Chen\n# @E-mail: chenliangping_2018@foxmail.com\n\n\nfrom openpyxl import load_workbook\ndef read_data(file_name,sheet_name):\n wb=load_workbook(file_name)\n sheet=wb[sheet_name]\n all_case=[]#储存所有行的测试用例数据\n for i in range(2,sheet.max_row+1):\n case=[]#某一行测试用例数据\n for j in range(1,sheet.max_column-1):\n case.append(sheet.cell(row=i,column=j).value)\n all_case.append(case)\n print(sheet.max_row)\n return all_case#返回所有测试用例数据\n\n #print(all_case)\nread_data('test_case.xlsx', 'recharge')\n\n\n\n\n\n\ndef write_data(file_name,sheet_name,row,column,value):#此函数为写入结果到Excel中\n #开始写入结果\n wb=load_workbook(file_name)\n sheet=wb[sheet_name]\n #定位单元格存值 行,列,值\n sheet.cell(row=row,column=column).value=value\n #进行判断,期望值与实际值是否相等,判断用例是否执行通过\n wb.save('test_case.xlsx')\n","sub_path":"R_W_excel.py","file_name":"R_W_excel.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"600010240","text":"from django.shortcuts import render, redirect\nfrom django.views import generic\nfrom django.views.generic import TemplateView\n\nfrom northwind.models import Order\nfrom orders.forms import OrderCreateForm, OrderDetailFormSet\n\n\ndef orders(request):\n return render(request, 'orders/order_list.html',\n {\"orders\": Order.objects.all().order_by('order_id')})\n\n\nclass DetailView(generic.DetailView):\n model = Order\n template_name = 'orders/order_detail.html'\n\n def totalPrice(self):\n total = 0\n for i in self.get_object().orderdetail_set.values():\n total += (1 - i.get('discount')) * i.get('quantity') * i.get('unit_price')\n return total + self.get_object().freight\n\n\nclass OrderAddView(TemplateView):\n template_name = \"orders/order_upload.html\"\n\n def get(self, *args, **kwargs):\n order = Order()\n form_order = OrderCreateForm(instance=order)\n formset_prod = OrderDetailFormSet(instance=order)\n return self.render_to_response({'prod_formset': formset_prod, 'order_form': form_order})\n\n def post(self, *args, **kwargs):\n order = Order()\n form_order = OrderCreateForm(data=self.request.POST)\n formset_prod = OrderDetailFormSet(data=self.request.POST, instance=order)\n if form_order.is_valid() and formset_prod.is_valid():\n a = form_order.save(commit=False)\n a.save()\n prods = formset_prod.save(commit=False)\n for prod in prods:\n prod.order_id = a.order_id\n prod.unit_price = prod.product.unit_price\n prod.discount /= 100\n prod.save()\n prod.product.units_in_stock -= prod.quantity\n prod.product.save()\n\n return redirect('orders')\n\n return self.render_to_response({'prod_formset': formset_prod, 'order_form': form_order})\n","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"395395579","text":"class Logger(object):\n\n def __init__(self, file_name):\n self.file_name = file_name\n\n # https://www.pythonforbeginners.com/cheatsheet/python-file-handling\n # Also got help from Nolen Kovacik for this one:\n def write_metadata(self, pop_size, vacc_percentage, virus_name, mortality_rate,\n basic_repro_num, ):\n with open(self.file_name, \"w\") as file:\n file.write(\"==============METADATA=====================\\n\")\n file.write(f\"{pop_size}\\t {vacc_percentage}\\t {virus_name}\\t {mortality_rate}\\t\")\n file.write(\"\\n========================================================\\n\")\n file.write(f\" Population Size: {pop_size}\\n\")\n file.write(f\" Vaccination Rate: {vacc_percentage}\\n\")\n file.write(f\" Virus Name: {virus_name}\\n\" )\n file.write(f\" Mortality Rate: {mortality_rate}\\n\")\n file.write(\"\\n========================================================\\n\")\n # file.write(f\" # of interactions: {interactions}\\n\")\n file.close()\n\n\n def log_interaction(self, person1, person2):\n with open(self.file_name, \"a\") as file:\n # if person1 has the virus then person1 infects person2\n if person1.infection != None:\n file.write(f\" {person1._id} infects {person2._id} because already sick. \\n\")\n # if person2 has the virus then person1 infects person2\n if person2.infection != None:\n file.write(f\" {person2._id} infects {person1._id} because already sick. \\n\")\n if person1.is_vaccinated == True:\n file.write(f\" {person1._id} didn't infect {person2._id} because vaccinated. \\n\")\n if person2.is_vaccinated == True:\n file.write(f\" {person2._id} didn't infect {person1._id} because vaccinated. \\n\")\n file.close()\n\n def log_infection_survival(self, person, population):\n did_die_from_infection = None\n with open(self.file_name, \"a\") as file:\n for person in population:\n if person.is_alive == True:\n did_die_from_infection == False\n file.write(f\" Person ID: {person._id} survived infection and is now immune\\n\")\n else:\n did_die_from_infection = True\n file.write(f\" Person ID: {person._id} died from infection.\\n\")\n file.close()\n\n def log_time_step(self, time_step_number):\n next_step = int(time_step_number + 1)\n with open(self.file_name, \"a\") as file:\n file.write(\"==============TIME STEP==========================\\n\")\n file.write(\"\\n ==============================================\\n\")\n file.write(f\"\\n Time step {time_step_number} has ended, starting time step {next_step}\\n\")\n # file.write(f\"Total Deaths: {death_counter}\")\n file.write(\"\\n ==============================================\\n\")\n file.close()\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"300392721","text":"\"\"\"The plotext package allows you to plot data directly on terminal.\"\"\"\nimport platform\n\nif platform.system() == \"Windows\":\n try:\n import ctypes\n\n kernel32 = ctypes.windll.kernel32\n kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)\n except Exception:\n print(\"Cannot set color support, use show(color=False)\")\n\nfrom plotext import plot\nname=\"plotext\"\n__version__ = \"0.1.16\"","sub_path":"plotext/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"385517155","text":"#!/usr/bin/python3\r\n#-*- coding:utf-8 -*-\r\n\r\nimport base64\r\nimport os\r\nimport sys\r\n\r\ndef encode_string(string):\r\n encoded = base64.encodestring(string.encode(\"UTF-16-LE\"))\r\n s = encoded.split(\"\\n\")\r\n return \"\".join(s)\r\n\r\ndef build_payload(payload):\r\n string = payload.encode(\"hex\")\r\n new_payload = []\r\n i = 0\r\n\r\n while i < len(string):\r\n if i % 2 ==0:\r\n new_payload.append(\"0x\")\r\n new_payload.append(string[i])\r\n i = i+1\r\n \r\n elif i == len(string)-1:\r\n new_payload.append(string[i])\r\n break\r\n \r\n else:\r\n new_payload.append(string[i])\r\n new_payload.append(\", \")\r\n i = i+1\r\n \r\n return \"\".join(new_payload)\r\n\r\ntemplate = \"\"\"\r\n$buffer = [cHAR[]] (%s);$buffer -JOIN \"\" | iex\r\n\"\"\"\r\n\r\nexec_encode_powershell = \"\"\"powershell.exe -EncodedCommand %s\"\"\"\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) < 2:\r\n print(\"PowerCode v0.1 By Unam3dd\")\r\n print(\"usage : %s -h/--help\" % (sys.argv[0]))\r\n else:\r\n\r\n if sys.argv[1] ==\"-ps\":\r\n payload_string = sys.argv[2]\r\n if len(sys.argv) <4:\r\n build_malware = build_payload(payload_string)\r\n template = \"\"\"$buffer = [cHAR[]] (%s);$buffer -JOIN \"\" | iex\"\"\" % (build_malware)\r\n print(template)\r\n else:\r\n build_malware = build_payload(payload_string)\r\n template = \"\"\"$buffer = [cHAR[]] (%s);$buffer -JOIN \"\" | iex\"\"\" % (build_malware)\r\n enc = encode_string(template)\r\n exec_encode_powershell = \"\"\"powershell.exe -EncodedCommand %s\"\"\" % (enc)\r\n print(exec_encode_powershell)\r\n \r\n elif sys.argv[1] ==\"-pf\":\r\n payload_file = sys.argv[2]\r\n check_file = os.path.exists(payload_file)\r\n if check_file ==True:\r\n print(\"[*] %s Found...\" % (sys.argv[2]))\r\n print(\"[*] Generate Payload\")\r\n f=open(payload_file,\"r\")\r\n content = f.read()\r\n build_malware = build_payload(content)\r\n template = \"\"\"$buffer = [cHAR[]] (%s);$buffer -JOIN \"\" | iex\"\"\" % (build_malware)\r\n if len(sys.argv) ==5:\r\n if sys.argv[3] ==\"-o\":\r\n out_file = sys.argv[4]\r\n f=open(out_file,\"w\")\r\n f.write(template)\r\n f.close()\r\n print(\"[*] Payload Writed Save As %s \" % (out_file))\r\n else:\r\n print(\"[!] Options Not Found !\")\r\n else:\r\n print(\"[!] %s Not Found !\" % (payload_file))\r\n \r\n elif sys.argv[1] ==\"-h\" or sys.argv[1] ==\"--help\":\r\n print(\"PowerCode v0.1 By Unam3dd\")\r\n print(\"usage : %s -h/--help\" % (sys.argv[0]))\r\n print(\" -ps payload string\")\r\n print(\" -e Encode String Command\")\r\n print(\" -pf Payload File\")\r\n print(\" -o Output File\")\r\n print(\"exemple:\")\r\n print(\" %s -ps \" % (sys.argv[0]))\r\n print(\" %s -ps -e\" % (sys.argv[0]))\r\n print(\" %s -pf \" % (sys.argv[0]))\r\n print(\" %s -pf -o out.ps1\" % (sys.argv[0]))\r\n \r\n else:\r\n print(\"[!] Options Invalid enter %s -h/--help for show options\" % (sys.argv[0]))","sub_path":"powercode.py","file_name":"powercode.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"376476367","text":"# De Anza College, CIS 22C, Summer 2019\n# Instructor: Kamren Eftekhari\n# Project 2: Facebook Friend Graph\n# Team Python: Michael Fan, Cameron Gao, Afshar Kiana, Zixi Luo\n# Detail: This file will create a graph of people and friendships, and run various test searches on them\n\nfrom queue import Queue\nfrom stack import Stack\n\n# constants\nINFILE_NETWORK=\"facebook_network.txt\"\nINFILE_USERS=\"find_friends.txt\"\n\nclass AdjacencyList:\n '''Adjacency List to be used for Graph to represent adjacent connections of a vertex using a Double Linked List data structure.''' \n class _Node:\n '''Nested class for a node in the AdjacencyList. Each node includes the reference to the vertex.'''\n def __init__(self,v):\n self.vertex=v\n self.prev=None\n self.next=None \n \n def __init__(self):\n self._head=self._Node(None)\n self._head.next=self._head\n self._head.prev=self._head\n self._n=0\n \n def __repr__(self):\n return \"Vertex \"+self.vertex.key+\" Adjacency List\"\n \n def __iter__(self):\n self._indexNode=self._head.next\n return self\n \n def __next__(self):\n if self._indexNode is not self._head:\n result=self._indexNode.vertex\n self._indexNode=self._indexNode.next\n return result\n else:\n raise StopIteration\n def __len__(self):\n return self._n\n \n def insertSorted(self,v):\n ''' Add a new node for the vertex, v, if it does not already exists. Return True if added, otherwise False.\n The node is inserted at a position in the list according to the sort order of vertices.''' \n current=self._head.next\n found=False\n while not found and current is not self._head:\n if current.vertex < v: \n current=current.next\n else:\n found=True\n # Sort order is determined; to insert if the vertex already exists.\n if current.vertex is not v:\n newNode=self._Node(v) \n # newNode inserted before current node\n newNode.prev=current.prev \n newNode.next=current \n \n if self._head.prev is self._head:\n # list is empty\n self._head.prev=newNode\n self._head.next=newNode\n else:\n # list is not empty\n current.prev.next=newNode\n current.prev=newNode\n self._n+=1 \n return True\n return False\n \nclass Vertex:\n ''' Vertex to be used in a Graph.'''\n def __init__(self,name):\n self.name=name\n self.ajcList=AdjacencyList() \n \n def __repr__(self):\n return self.name\n \n def __lt__(self,other):\n return self.name0:\n lwithCommonFriends.append((len(commonFriends),u,commonFriends))\n \n print(f\"\\n{user} has friends: {', '.join(sorted(sfriends))}\")\n print(f\"\\nTop 10 users who are not already {user}'s friend but have the most mutual friends with him/her:\")\n \n for x in sorted(lwithCommonFriends, reverse=True)[:10]:\n print(f\"{x[1]} has {x[0]} mutual friend(s).\")\n \n def chain(self, name1, name2):\n ''' To obtain the shortest path between name1 and name2 in the network.'''\n try:\n return self._graph.chain_bfs(name1,name2)\n except KeyError as eObj:\n print(\"Name not found: \"+str(eObj))\n except RecursionError as eObj:\n print(str(eObj))\n \n \n\ndef main(): \n # Load network:\n g=FacebookNetwork()\n with open(INFILE_NETWORK) as fh:\n for line in fh:\n g.addAdjacency(*line.strip().split())\n \n # Load users to be considered:\n lusers=[]\n with open(INFILE_USERS) as fh:\n for line in fh:\n lusers.extend(line.strip().split()) \n\n print(\"Recomending friends of friend to a user:\")\n for user in lusers:\n srecommand={ p for friend in g.friends(user) for p in g.friends(friend)}.difference(set(g.friends(user))).difference([user])\n \n print(f\"Recommended for {user}, {len(srecommand)} total.\") \n print() \n \n for user in lusers:\n g.recommendFriends(user) \n print()\n \n for i in range(0,len(lusers),2):\n lchain=list(g.chain(lusers[i],lusers[i+1]))\n print(\" - \".join(lchain)+\" :\")\n print()\n for p in lchain:\n print(f\"Friends of {p}:\\n\"+\", \".join(list(g.friends(p))))\n print()\n \nif __name__==\"__main__\":\n main()\n","sub_path":"2/project-2.py","file_name":"project-2.py","file_ext":"py","file_size_in_byte":9526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"513826012","text":"#Q1\r\nl=[17,38,10,25,72,45,14]\r\nfor p in l: \r\n p=p+1\r\n print(p)\r\n#Q2\r\nl.append(13)\r\nl.append(12)\r\nprint(l)\r\n#Q3\r\nz=l.index(72)\r\nprint(z)\r\n\r\n#Q4\r\npaire, impaire=[],[]\r\nfor nombre in l:\r\n if nombre%2:\r\n impaire.append(nombre)\r\n else:\r\n paire.append(nombre)\r\nprint (\"nombres impaires: %s\" % \", \".join([str(nb) for nb in impaire]))\r\nprint (\"nombres paires: %s\" % \", \".join([str(nb) for nb in paire]))\r\n#for nombre in l:\r\n #if nombre%2==0:\r\n #print(\"impaires\",nombre)\r\n #else:\r\n #print(\"paires\", nombre) \r\n#Q5\r\nl.insert(4,30)\r\nprint(l)\r\n#Q6\r\nl.remove(30)\r\nprint(l)\r\n#Q7\r\nl.reverse()\r\nprint(l)\r\n#Q8\r\na=input(\"donner un nombre \")\r\nif a==l:\r\n print(\"ce nombre est existe\",l)\r\n \r\nelse:\r\n print(\"ce nombre n'existe pas \")\r\n\r\n#Q9-10\r\na=l[2:4]\r\nprint(\"2 eme element au 3 eme element\",a)\r\nb=l[:3]\r\nprint(\"debut au 2 eme\", b)\r\n#Q11\r\nprint(\"la position du dernier element avec l'indice inverse\",l[-1])\r\n\r\n \r\n\r\n \r\n\r\n\r\n\r\n \r\n \r\n","sub_path":"Ex1.py","file_name":"Ex1.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"39025951","text":"import re\nimport numpy as np\n\n\n#open a the file\nfileHandler = open('from_1989.txt')\narrayOfTyphoons = list()\ncurrentRow = list()\ncurrentKey = \"\"\ndataIndex = 0;\nnameIndex = 0;\ndataMatrix = list()\nlineMatrix = None\nresult = None\nlineCount = 0\ntyPhoonDict = dict()\nstackedMatrix = None\n\nfor line in fileHandler:\n lineStripped = line.strip()\n lineCount = lineCount + 1\n \n if re.search(r'^66666',lineStripped):\n #dealing with name row\n nameIndex = nameIndex + 1\n dataMatrix_np = np.zeros([1, 6])\n if len(lineStripped.split()) == 7:\n currentKey = str(nameIndex) + \"_NULL\"\n #print(currentKey)\n tyPhoonDict[currentKey] = dataMatrix_np\n\n elif len(lineStripped.split()) == 8:\n currentKey = str(nameIndex) + \"_\"+ lineStripped.split()[6]\n #print(currentKey)\n tyPhoonDict[currentKey] = dataMatrix_np\n elif len(lineStripped.split()) == 9:\n #print(currentKey)\n currentKey = str(nameIndex) + \"_\" + lineStripped.split()[7]\n tyPhoonDict[currentKey] = dataMatrix_np\n \n\n else:\n #dealing with data rows\n lineMatrix = np.array([lineStripped.split()[ : 6]])\n lineMatrix = lineMatrix.astype(np.integer)\n stackedMatrix = tyPhoonDict[currentKey]\n result = np.concatenate([stackedMatrix, lineMatrix], axis=0)\n #print(result.shape)\n tyPhoonDict[currentKey] = result\n\n \n# Headlines \nfor name in tyPhoonDict:\n tyPhoonDict[name] = tyPhoonDict[name][1:, :]\n \ncolumns = np.array([\"date/time\", \"Indicator\", \"grade\", \"latitude\", \"longitude\", \"central_pressure\"])\n\n# testing\nprint(tyPhoonDict[\"1_OWEN\"][:])\n\nfor k in tyPhoonDict.keys():\n print(tyPhoonDict[k][:])\n\n","sub_path":"parsing_typhoon_data.py","file_name":"parsing_typhoon_data.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"515208119","text":"#You will have to initialize your dict as OrderedDict. Create a new empty\r\n#OrderedDict,\r\n#go through all keys of the original dictionary and insert before/after\r\n#when the key name matches.\r\n\r\n\r\nfrom pprint import pprint\r\nfrom collections import OrderedDict\r\n\r\n\r\ndef insert_key_value(a_dict, key, pos_key, value):\r\n new_dict = OrderedDict()\r\n for k, v in a_dict.items():\r\n if k==pos_key:\r\n new_dict[key] = value # insert new key\r\n new_dict[k] = v\r\n return new_dict\r\n\r\n\r\nmydict = OrderedDict([('Name', 'Zara'), ('Age', 7), ('Class', 'First')])\r\nmy_new_dict = insert_key_value(mydict, \"Phone\", \"Name\", \"1234\")\r\npprint(my_new_dict)\r\n","sub_path":"orderddict.py","file_name":"orderddict.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"149813294","text":"\r\n\r\nimport numpy as np\r\nimport cv2\r\nfrom keras.layers import Input\r\nfrom keras.layers.convolutional import Conv2D\r\nfrom keras.models import Model\r\nfrom os.path import dirname as up_one_dir\r\n\r\nfrom os import listdir\r\nfrom os.path import isfile, join, abspath\r\n\r\ndef create_model(img, img_txt, dir_of_images, dir_save_to):\r\n\timg_path = dir_of_images + img\r\n\timg_txt_path = dir_of_images + img_txt\r\n\tsample_inp = cv2.imread(img_path,cv2.IMREAD_GRAYSCALE)\r\n\tsample_out = np.loadtxt(img_txt_path, dtype=np.float32)\r\n\trows,cols = sample_inp.shape\r\n\tsample_inp = np.array(sample_inp).reshape((rows,cols,1))\r\n\tsample_out = np.array(sample_out).reshape((rows,cols,1))\r\n\tsample_inp.shape\r\n\tsample_out.shape\r\n\tsamples_inp = np.array([sample_inp])\r\n\tsamples_out = np.array([sample_out])\r\n\r\n\tinp = Input(shape=(None,None,1))\r\n\tout = Conv2D(1, (3, 3), kernel_initializer='normal', use_bias=False, padding='same')(inp)\r\n\tmodel = Model(inputs=inp, outputs=out)\r\n\tmodel.summary()\r\n\r\n\tmodel.compile(optimizer='rmsprop', loss='mse', metrics=['mse', 'mae'])\t#kompilovanie modelu, mse = mean squared error, optimizer -> ako hladat spravne vahy\r\n\tnum_epochs = 100\r\n\t\r\n\t\r\n\tfor i in range(10,30,40):\r\n\t\tnum_epochs = i\r\n\t\tmodel.fit(samples_inp, samples_out, batch_size=1, epochs = num_epochs)\r\n\r\n\t\tmodel.layers[1].get_weights()\r\n\r\n\t\tmodel.evaluate(samples_inp, samples_out, verbose=True)\r\n\t\tmodel.metrics_names\r\n\r\n\t\toutput_images = model.predict(samples_inp)\r\n\r\n\t\toutput_image = output_images[0].reshape((rows,cols))\r\n\r\n\t\toutput_image = abs(output_image);\r\n\t\toutput_image = cv2.normalize(output_image,None,0,255,cv2.NORM_MINMAX)\r\n\t\toutput_image = np.uint8(output_image)\r\n\t\tname = img[:-4] + str(num_epochs) + '_grayscale.jpg'\r\n\t\tprint('saving in ', join(dir_save_to, name))\r\n\t\tprint(name)\r\n\t\tprint(dir_save_to)\r\n\t\tcv2.imwrite(join(dir_save_to, name), output_image)\r\n\t#model.save('sobel.h5')\r\n\r\n\t#quit()\r\n","sub_path":"conv_net/ker3.py","file_name":"ker3.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"124347532","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom math import *\nimport cmath\nfrom random import randint\n\nx = [0, 1]\ny = [0, 1]\n\n\n\n\n# for i in xrange(1000):\n# \tn = randint(0, 99)\n# \tdx = x[-1] - x[-2]\n# \tdy = y[-1] - y[-2]\n# \tif n < 50:\n# \t\tx.append(x[-1] - dy) # anti-clocwise\n# \t\ty.append(y[-1] + dx)\n# \telse:\n# \t\tx.append(x[-1] + dy) # clockwise\n# \t\ty.append(y[-1] - dx)\n\n\nl = np.linspace(1, 3, 200000)\nfor i in l:\n\tr = sin(i)\n\tn = randint(0, 99)\n\tdx = np.sign(x[-1] - x[-2]) * r\n\tdy = np.sign(y[-1] - y[-2]) * r\n\tif n < 50:\n\t\tx.append(x[-1] - dy)\n\t\ty.append(y[-1] + dx)\n\telse:\n\t\tx.append(x[-1] + dy)\n\t\ty.append(y[-1] - dx)\n\n\n\n\n\n\n\n\nplt.plot(x, y, 'k-')\nplt.axis('equal')\nplt.grid()\nplt.show()\n","sub_path":"numberstheory/complex-lane-walk/rand_walk.py","file_name":"rand_walk.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"500717441","text":"# Copyright (C) 2017 Tran Quan Pham\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 logging as l\nimport warnings\n\nfrom voice.command import VoiceCommand\nfrom sound import amixer\n\nfrom apps import kodi, youtube\nfrom apps import mps_youtube as mpsyt\n\nFORMAT = \"[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s\"\nl.basicConfig(level=l.WARN, format=FORMAT)\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module='urllib')\n\n# search param\n_cmd = ''\n_searchType = None\n_searchParam1 = ''\n\n# last search\n_shownArtists = []\n_shownSongs = []\n_lastSearchType = None\n\n\ndef init_conversation():\n global _searchType, _searchParam1\n _searchType = None\n _searchParam1 = None\n\n\ndef is_valid_command(spoken_text):\n global _cmd, _searchType, _searchParam1\n _cmd = spoken_text\n init_conversation()\n\n (_searchType, _searchParam1) = VoiceCommand.extract_data(spoken_text)\n\n return _searchType is not None\n\n\ndef execute_command():\n\n global _shownArtists, _shownSongs, _lastSearchType\n\n l.info([_searchType, _searchParam1])\n\n if _searchType == VoiceCommand.ALBUM:\n if kodi.search_play_album(_searchParam1):\n return\n\n if _searchType == VoiceCommand.ARTIST:\n if kodi.search_play_artist(_searchParam1):\n return\n\n if _searchType == VoiceCommand.SHOW_ARTIST:\n _lastSearchType = _searchType\n return kodi.show_artist()\n\n if _searchType == VoiceCommand.SHOW_ALBUM:\n _lastSearchType = _searchType\n return kodi.show_albums()\n\n if _searchType == VoiceCommand.PLAY_NUMBER:\n if _lastSearchType == VoiceCommand.SHOW_ALBUM:\n return kodi.play_number_from_album_list(_searchParam1)\n elif _lastSearchType == VoiceCommand.SHOW_ARTIST:\n return kodi.play_number_from_artist_list(_searchParam1)\n\n if _searchType == VoiceCommand.PLAY_RANDOM:\n return kodi.play_random()\n\n if _searchType == VoiceCommand.PLAY_NEXT:\n return kodi.play_next()\n\n if _searchType == VoiceCommand.STOP_PLAY:\n return kodi.stop_audio()\n\n if _searchType == VoiceCommand.VOLUME_UP:\n amixer.volume_up()\n return\n\n if _searchType == VoiceCommand.VOLUME_MAX:\n amixer.volume_max()\n return\n\n if _searchType == VoiceCommand.VOLUME_DOWN:\n amixer.volume_down()\n return\n\n if _searchType == VoiceCommand.YT_PLAY:\n mpsyt.search_play_song(_searchParam1)\n\n if _searchType == VoiceCommand.YT_PLAY_SONG:\n return youtube.search_play_song(_searchParam1)\n\n if _searchType == VoiceCommand.YT_PLAY_LIST:\n return youtube.search_play_album(_searchParam1)\n\n if _searchType == VoiceCommand.HELP:\n VoiceCommand.print_voice_command()\n return\n\n if _searchType == VoiceCommand.KD_INIT_DB:\n kodi.init_database()\n\n print(\"Cannot execute: {}\".format(_cmd))\n\n\ndef init_database():\n kodi.init_database()\n\n\ndef main():\n kodi.init_database()\n cmds = \"\"\"help\nshow me some songs\nplay number 2\"\"\".split('\\n')\n for cmd in cmds:\n print(cmd)\n if is_valid_command(cmd):\n execute_command()\n\nif __name__ == '__main__':\n main()\n","sub_path":"apps/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"229922500","text":"from __future__ import print_function\n\nimport os\nimport orca\nimport pandas as pd\nfrom urbansim.utils import misc\n\n\n@orca.step()\ndef hazards_slr_summary(run_setup, year):\n\n if not run_setup['run_slr']:\n return\n \n if len(orca.get_table(\"slr_demolish\")) < 1:\n return\n \n slr_summary = pd.DataFrame(index=[0])\n\n # impacted parcels\n slr_summary[\"impacted_parcels\"] = len(orca.get_table(\"destroy_parcels\"))\n\n # impacted buildings\n if year == 2035:\n slr_demolish_tot = orca.get_table(\"slr_demolish\").to_frame()\n orca.add_table(\"slr_demolish_tot\", slr_demolish_tot)\n else:\n slr_demolish_tot = orca.get_table(\"slr_demolish_tot\").to_frame()\n slr_demolish_tot.append(orca.get_table(\"slr_demolish\").to_frame())\n\n slr_summary[\"impacted_units\"] = slr_demolish_tot['residential_units'].sum()\n slr_summary[\"impacted_sqft\"] = slr_demolish_tot['building_sqft'].sum()\n\n # impacted households\n if year == 2035:\n unplaced_hh_tot = orca.get_injectable(\"hh_unplaced_slr\")\n orca.add_injectable(\"unplaced_hh_tot\", unplaced_hh_tot)\n else:\n unplaced_hh_tot = orca.get_injectable(\"unplaced_hh_tot\")\n unplaced_hh_tot.append(orca.get_injectable(\"hh_unplaced_slr\"))\n\n slr_summary[\"impacted_hh\"] = unplaced_hh_tot.size\n for quartile in [1, 2, 3, 4]:\n slr_summary[\"impacted_hhq\"+str(quartile)] = (unplaced_hh_tot[\"base_income_quartile\"] == quartile).sum()\n\n # employees by sector\n if year == 2035:\n unplaced_jobs_tot = orca.get_injectable(\"jobs_unplaced_slr\")\n orca.add_injectable(\"unplaced_jobs_tot\", unplaced_jobs_tot)\n else:\n unplaced_jobs_tot = orca.get_injectable(\"unplaced_jobs_tot\")\n unplaced_jobs_tot.append(orca.get_injectable(\"jobs_unplaced_slr\"))\n\n for empsix in ['AGREMPN', 'MWTEMPN', 'RETEMPN', 'FPSEMPN', 'HEREMPN', 'OTHEMPN']:\n slr_summary[\"impacted_jobs_\"+str(empsix)] = (unplaced_jobs_tot[\"empsix\"] == empsix).sum()\n\n slr_summary.to_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"hazards_summaries/slr_summary_%d.csv\" % (year)))\n\n\n@orca.step()\ndef hazards_eq_summary(run_setup, year, parcels, buildings):\n\n if not run_setup['run_eq']:\n return\n \n if year != 2035:\n return\n \n code = orca.get_injectable(\"code\").to_frame()\n code.value_counts().to_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"hazards_summaries/eq_codes_summary_%d.csv\"\n % (year)))\n\n fragilities = orca.get_injectable(\"fragilities\").to_frame()\n fragilities.value_counts().to_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"hazards_summaries/eq_fragilities_summary_%d.csv\"\n % (year)))\n\n eq_summary = pd.DataFrame(index=[0])\n\n eq_buildings = orca.get_injectable(\"eq_buildings\").to_frame()\n eq_summary[\"buildings_impacted\"] = eq_buildings.size\n eq_demolish = orca.get_table(\"eq_demolish\").to_frame()\n eq_summary['res_units_impacted'] = eq_demolish['residential_units'].sum()\n eq_summary['sqft_impacted'] = eq_demolish['building_sqft'].sum()\n\n existing_buildings = orca.get_injectable(\"existing_buildings\").to_frame()\n eq_summary[\"existing_buildings_impacted\"] = existing_buildings.size\n new_buildings = orca.get_injectable(\"new_buildings\").to_frame()\n eq_summary[\"new_buildings_impacted\"] = new_buildings.size\n\n fire_buildings = orca.get_injectable(\"fire_buildings\").to_frame()\n eq_summary[\"fire_buildings_impacted\"] = fire_buildings.size\n\n # income quartile counts\n hh_unplaced_eq = orca.get_injectable(\"hh_unplaced_eq\").to_frame()\n for quartile in [1, 2, 3, 4]:\n eq_summary[\"impacted_hhq\"+str(quartile)] = (hh_unplaced_eq[\"base_income_quartile\"] == quartile).sum()\n\n # employees by sector\n jobs_unplaced_eq = orca.get_injectable(\"jobs_unplaced_eq\").to_frame()\n for empsix in ['AGREMPN', 'MWTEMPN', 'RETEMPN', 'FPSEMPN', 'HEREMPN', 'OTHEMPN']:\n eq_summary[\"impacted_jobs_\"+str(empsix)] = (jobs_unplaced_eq[\"empsix\"] == empsix).sum()\n \n eq_summary.to_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"hazards_summaries/eq_summary_%d.csv\"\n % (year)))\n\n # print out demolished buildings by TAZ\n eq_demolish_taz = misc.reindex(parcels.zone_id, eq_demolish.parcel_id)\n eq_demolish['taz'] = eq_demolish_taz\n eq_demolish['count'] = 1\n eq_demolish = eq_demolish.drop(['parcel_id', 'year_built', 'redfin_sale_year'], axis=1)\n eq_demolish = eq_demolish.groupby(['taz']).sum()\n eq_demolish.to_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"hazards_summaries/eq_demolish_buildings_%d.csv\"\n % (year)))\n\n # print out retrofit buildings by TAZ\n if not run_setup['eq_mitigation']:\n return\n retrofit_bldgs_tot = orca.get_table(\"retrofit_bldgs_tot\").to_frame()\n retrofit_bldgs_tot['taz'] = misc.reindex(parcels.zone_id, retrofit_bldgs_tot.parcel_id)\n retrofit_bldgs_tot['count'] = 1\n retrofit_bldgs_tot = retrofit_bldgs_tot.groupby(['taz']).sum()\n retrofit_bldgs_tot = retrofit_bldgs_tot[['taz', 'residential_units', 'residential_sqft',\n 'non_residential_sqft', 'building_sqft', 'stories','redfin_sale_price', 'non_residential_rent',\n 'deed_restricted_units', 'residential_price', 'count']]\n retrofit_bldgs_tot.to_csv(os.path.join(\n orca.get_injectable(\"outputs_dir\"), \"hazards_summaries/eq_retrofit_buildings_%d.csv\" % (year)))\n\n # print out buildings by TAZ around earthquake years\n if year not in [2030, 2035, 2050]:\n return\n buildings = buildings.to_frame()\n buildings['taz'] = misc.reindex(parcels.zone_id, buildings.parcel_id)\n buildings['count'] = 1\n buildings = buildings.groupby(['taz']).sum()\n buildings = buildings[['taz', 'count', 'residential_units', 'residential_sqft', 'non_residential_sqft',\n 'building_sqft', 'stories', 'redfin_sale_price', 'non_residential_rent', 'deed_restricted_units',\n 'residential_price']]\n buildings.to_csv(os.path.join(\n orca.get_injectable(\"outputs_dir\"), \"hazards_summaries/eq_buildings_list_%d.csv\" % (year)))","sub_path":"baus/summaries/hazards_summaries.py","file_name":"hazards_summaries.py","file_ext":"py","file_size_in_byte":6207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"33127638","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.views import View\nfrom .models import Post\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nimport json\n# Create your views here.\n\n\nclass Posts(View):\n def get(self, request):\n\n if(request.user.is_authenticated):\n # print(request.user, \"request.user\")\n user = User.objects.get(id=request.user.id)\n # print(user, \"----user\", dir(user))\n post_list = list(Post.objects.values())\n\n return JsonResponse({\n 'Content-Type': 'application/json',\n 'status': 200,\n 'data': post_list\n }, safe=False)\n else:\n return JsonResponse({\n 'Content-Type': 'application/json',\n 'status': 200,\n 'message': 'Must be logged in to see the data'\n }, safe=False)\n\n\n\n # @method_decorator(login_required)\n def post(self, request):\n data = request.body.decode('utf-8')\n data = json.loads(data)\n\n try:\n new_post = Post.objects.create(title=data[\"title\"], author=request.user, commentBody=data[\"commentBody\"])\n print(new_post, \"this is new post\")\n\n new_post.author = request.user\n new_post.save()\n data[\"id\"] = new_post.id\n print(data, \"<----this is the data\")\n return JsonResponse({\"data\": data}, safe=False)\n except Exception as problem:\n print(problem)\n return JsonResponse({\"error\": \"Data is Not Valid\"},safe=False)\n \n\n\nclass Post_Detail(View):\n # @method_decorator(csrf_exempt)\n # def dispatch(self, request, *args, **kwargs):\n # return super(Book_Detail, self).dispatch(request, *args, **kwargs)\n\n def get(self, request, pk):\n post_list = list(Post.objects.filter(pk=pk).values())\n return JsonResponse({\"data\": post_list}, safe=False)\n def put(self, request, pk):\n data = request.body.decode('utf-8')\n data = json.loads(data)\n\n try:\n edit_post = Post.objects.get(pk=pk)\n data_key = list(data.keys())\n\n for key in data_key:\n if key == \"title\":\n edit_post.title = data[key]\n if key == \"author\":\n edit_post.author = data[key]\n if key == \"commentBody\":\n edit_post.commentBody = data[key]\n edit_post.save()\n data[\"id\"] = edit_post.id\n return JsonResponse({\"data\": data}, safe=False)\n except:\n return JsonResponse({\"error\": \"Something Went Wrong\"}, safe=False)\n\n def delete(self, request, pk):\n try:\n post_to_delete = Post.objects.get(pk=pk)\n print(post_to_delete, \"<----this is post to delete\")\n post_to_delete.delete()\n return JsonResponse({\"data\": \"deleted\"}, safe=False)\n except:\n return JsonResponse({\"error\": \"Something Went Wrong\"}, safe=False)","sub_path":"django-backend/noScalpersProject/noscalpersapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"581618411","text":"#1\nx[1][0] = 15\n\nstudents[0]['last_name'] = Bryant\n\nsports_directory['soccer'][0] = 'Andres'\n\nz[0]['y'] = 30\n\n#2\nstudents = [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n]\ndef iterate_dictionary(list):\n for item in list:\n key_value_tmp_list = []\n for key, value in item.items():\n dict_join = key, '-', value\n key_value_tmp_list.append(' '.join(dict_join))\n print(', '.join(key_value_tmp_list))\n\niterate_dictionary(students)\n\n#3\ndef iterate_dictionary2(key_search,list):\n for item in list:\n key_value_tmp_list = []\n for key, value in item.items():\n if key == key_search:\n print(value)\n\niterate_dictionary2('first_name',students)\n\n#4\ndojo = {\n 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'],\n 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon']\n}\ndef say_that(dict):\n for key, value in dict.items():\n print(len(value), key.upper())\n for item in value:\n print(item)\n print('\\n')\n\nsay_that(dojo)\n","sub_path":"PythonFundAssignments/functions_internediate2.py","file_name":"functions_internediate2.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"25121644","text":"import pandas as pd\nimport sys\nimport matplotlib.pyplot as plt\n\ncoln=[ 'nc','rho1','rho2',\n\t'N1','N2','N11','N12', \n\t'v1','v2', \n\t'nb1_11', 'nb1_12', 'nb1_22', #number of bonds in phase 1 (_11= btw specie 1 and specie 1)\n\t'nb2_11', 'nb2_12', 'nb2_22', #number of bonds in phase 2\n\t'e1','e2', \n\t'mu11','mu21', #chemical potential in phase 1 (for each species)\n\t'mu12','mu22', #chemical potential in phase 2 (for each species) \n ]\n\ndef get_total_densities(df, KbT):\n #average total density\n\t#r1 = (df[['rho1', 'rho2']]).min(axis=1).mean()\n\t#r2 = (df[['rho1', 'rho2']]).max(axis=1).mean()\n\trho1= df['rho1'].mean()\n\trho2= df['rho2'].mean()\n\treturn rho1, rho2\n\ndef swap(x,y):\n\ttmp = x\n\tx = y\n\ty = tmp\n\treturn x, y\n\ndef get_gas_phase(df):\n\t\"\"\"check which of box1 or box2 is the high density phase\"\"\"\n\tbox1s = (df['rho1'] < df['rho2']).astype(int).sum()\n\tbox2s = (df['rho1'] > df['rho2']).astype(int).sum()\n\tres = 'Gas1'\n\t#print(\"sum box1 = {}, sum box2 = {}\".format(box1s, box2s) )\n\tif box1s < box2s:\n\t\tres = 'Gas2'\n\treturn res\n\ndef get_avg_volume(df, KbT):\n\trho1, rho2 = get_total_densities(df, KbT)\n\n\ttotal_volume = df['v1'] + df['v2']\n\tvt = total_volume.mean()\n\n\tv_gas = ( df['v1'].divide(total_volume) ).mean()\n\tv_liq = ( df['v2'].divide(total_volume) ).mean()\n\n\terr_gas = ( df['v1'].divide(total_volume) ).std()\t\n\terr_liq = ( df['v2'].divide(total_volume) ).std()\n\t\n\tif rho1 > rho2:\n\t\tv_gas, v_liq = swap(v_gas,v_liq)\n\t\terr_gas, err_liq = swap(err_gas, err_liq)\n\twith open(\"data-avg-frac-volume.dat\", \"a\") as myfile:\n\t\tmyfile.write(\"{:3.2f} {:8.4f} +/- {:6.4f} {:8.4f} +/- {:6.4f} {:8.4f}\\n\".\n\t\t\tformat(KbT, v_gas, err_gas, v_liq, err_liq, vt))\n\treturn v_gas, v_liq\n\ndef get_avg_densities(df, KbT):\n\t#average density of specie 1 (protein) and specie 2 (crowder) \n\trho1, rho2 = get_total_densities(df, KbT)\n\trho1_gas = ( df['N11'].divide(df['v1']) ).mean()\n\trho1_liq = ( df['N12'].divide(df['v2']) ).mean()\t\n\trho2_gas = ( (df['N1'] - df['N11']).divide(df['v1']) ).mean()\n\trho2_liq = ( (df['N2'] - df['N12']).divide(df['v2']) ).mean()\n\n\trho1_gas_err = ( df['N11'].divide(df['v1']) ).std()\n\trho1_liq_err = ( df['N12'].divide(df['v2']) ).std()\n\n\tif rho1 > rho2:\n\t\trho1, rho2 = swap(rho1, rho2) \n\t\trho1_gas_err, rho1_liq_err = swap(rho1_gas_err, rho1_liq_err) \n\t\trho1_gas, rho1_liq = swap(rho1_gas, rho1_liq)\n\t\trho2_gas, rho2_liq = swap(rho2_gas, rho2_liq)\n\t\t\n\twith open(\"data-avg-densities.dat\", \"a\") as myfile:\n\t\tmyfile.write(\"{:3.2f} {:8.4f} +/- {:6.4f} {:8.4f} +/- {:6.4f} {:8.4f}{:8.4f} {:8.4f}{:8.4f}\\n\".\n\t\t\tformat(KbT, rho1_gas, rho1_gas_err, rho1_liq, rho1_liq_err, rho2_gas, rho2_liq, rho1, rho2))\n\treturn rho1_gas, rho1_liq\n\ndef get_frac_specie(df, KbT):\n\trho1, rho2 = get_total_densities(df, KbT)\n\t\"\"\"Of all particles of species 1, what fraction is found in phase 1 and 2?\"\"\"\n\tNtype1_df = df['N11'] + df['N12']\n\tntype1_gas = ( df['N11'].divide(Ntype1_df) ).mean()\n\tntype1_liq = ( df['N12'].divide(Ntype1_df) ).mean()\n\n\tN21 = df['N1'] - df['N11']\n\tN22 = df['N2'] - df['N12']\n\tntype2_gas = ( N21.divide( N21+N22) ).mean()\n\tntype2_liq = ( N22.divide( N21+N22) ).mean() \n\n\t#swap variable if rho1 is liquid instead of rho2\n\tif rho1 > rho2:\n\t\tntype1_gas, ntype1_liq = swap(ntype1_gas, ntype1_liq)\n\t\tntype2_gas, ntype2_liq = swap(ntype2_gas, ntype2_liq)\n\t\n\treturn ntype1_gas,ntype1_liq,ntype2_gas,ntype2_liq\n\ndef get_frac_species(df, KbT):\n\trho1, rho2 = get_total_densities(df, KbT)\n\t\"\"\"Of all particles in gas phase, what fraction is of type 1?\"\"\"\n\tx1_gas = ( df['N11'].divide(df['N1']) ).mean() \n\tN21 = df['N1'] - df['N11']\n\tx2_gas = ( N21.divide(df['N1']) ).mean()\n\n\tx1_liq = ( df['N12'].divide(df['N2']) ).mean()\n\tN22 = df['N2'] - df['N12'] \n\tx2_liq = ( N22.divide(df['N2']) ).mean() \n\n\t#get number of particles in each phase\n\tNgas = df['N1'].mean()\n\tNliq = df['N2'].mean()\n\tN11,N12 = df['N11'].mean(), df['N12'].mean() \n\tN21,N22 = N21.mean(), N22.mean()\n\t#swap variable if rho1 is liquid instead of rho2\t\n\tif rho1 > rho2:\n\t\tx1_gas, x1_liq = swap(x1_gas, x1_liq)\n\t\tx2_gas, x2_liq = swap(x2_gas, x2_liq)\t\n\t\tNgas, Nliq = swap(Ngas, Nliq)\n\t\tN11,N12 = swap(N11,N12)\n\t\tN21,N22 = swap(N21,N22)\n\n\tn1_gas,n1_liq,n2_gas,n2_liq = get_frac_specie(df, KbT) \n\n\twith open(\"data-avg-frac-specie.dat\", \"a\") as myfile:\n\t\tmyfile.write(\"{:3.2f} {:8.4f}{:8.4f}{:8.4f}{:8.4f} {:8.4f}{:8.4f}{:8.4f}{:8.4f} {:8.2f}{:8.2f} {:8.2f}{:8.2f}{:8.2f}{:8.2f}\\n\".\n\t\t\tformat(KbT, x1_gas, x2_gas, x1_liq, x2_liq, n1_gas,n1_liq,n2_gas,n2_liq, Ngas, Nliq, N11,N21, N12,N22))\n\n\treturn x1_gas, x2_gas, x1_liq, x2_liq\n\n\ndef get_mu(df, KbT=0.74):\n\t#average chemical potential\n\tmu11 = df['mu11'].mean() #specie 1 in phase 1\n\tmu21 = df['mu21'].mean() #specie 2 in phase 1\n\tmu12 = df['mu12'].mean() #specie 1 in phase 2\n\tmu22 = df['mu22'].mean() #specie 2 in phase 2\n\twith open(\"data-avg-Mu.dat\", \"a\") as myfile:\n\t\tmyfile.write(\"{:3.2f} {:8.4f}{:8.4f} {:8.4f}{:8.4f}\\n\".\n\t\t\tformat(KbT, mu11, mu21, mu12, mu22))\n\treturn mu11, mu21, mu12, mu22 \n\ndef get_avg_nbonds(df, KbT=0.74):\n\trho1, rho2 = get_total_densities(df, KbT)\n\t\"\"\"type1-type1 average number of bonds per particle\"\"\"\n\tnbonds_gas = ( df['nb1_11'] ).mean()\n\tnbonds_liq = ( df['nb2_11'] ).mean()\n\terr1_gas = ( df['nb1_11'] ).std()\n\terr1_liq = ( df['nb2_11'] ).std()\n\n\t\"\"\"type2-type2 average number of bonds per particle\"\"\"\t\n\tnbonds2_gas = ( df['nb1_22'] ).mean()\n\tnbonds2_liq = ( df['nb2_22'] ).mean() \n\terr2_gas = ( df['nb1_22'] ).std()\n\terr2_liq = ( df['nb2_22'] ).std()\n\n\tif rho1 > rho2:\n\t\tnbonds_gas, nbonds_liq = swap(nbonds_gas,nbonds_liq)\n\t\tnbonds2_gas,nbonds2_liq= swap(nbonds2_gas,nbonds2_liq) \n\n\twith open(\"data-avg-nbonds-species.dat\", \"a\") as myfile:\n\t\tmyfile.write(\"{:3.2f} {:8.4f} +/- {:6.4f} {:8.4f} +/- {:6.4f} {:8.4f} +/- {:6.4f} {:8.4f} +/- {:6.4f}\\n\".\n\t\t\tformat(KbT, nbonds_gas, err1_gas, nbonds_liq, err1_liq, nbonds2_gas, err2_gas, nbonds2_liq, err2_liq))\n\treturn nbonds_gas, nbonds_liq\n\n\ndef get_Avg_nbonds(df, KbT=0.74):\n\trho1, rho2 = get_total_densities(df, KbT)\n\ttotal_nbs_gas_df = df['nb1_11'] + df['nb1_12'] + df['nb1_22']\n\ttotal_nbs_liq_df = df['nb2_11'] + df['nb2_12'] + df['nb2_22']\n\n\t\"\"\"Total average number of bonds per particle in each phase\"\"\"\n\tnbs_gas = ( (df['nb1_11'] + df['nb1_12']).divide(df['N1']) ).mean()\n\tnbs_liq = ( (df['nb2_11'] + df['nb2_12']).divide(df['N2']) ).mean()\n\n\tnbs_gas_err = ( (df['nb1_11'] + df['nb1_12']).divide(df['N1']) ).std()\n\tnbs_liq_err = ( (df['nb2_11'] + df['nb2_12']).divide(df['N2']) ).std()\n\n\t\"\"\"Fraction of total bonds between 1-1, 1-2, and between 2-2 in gas phase\"\"\"\n\tnbs11_gas = ( df['nb1_11'].divide(total_nbs_gas_df) ).mean()\n\tnbs12_gas = ( df['nb1_12'].divide(total_nbs_gas_df) ).mean() \n\tnbs22_gas = ( df['nb1_22'].divide(total_nbs_gas_df) ).mean() \n\n\t\"\"\"Fraction of total bonds between 1-1, 1-2, and between 1-2 in liq phase\"\"\"\n\tnbs11_liq = ( df['nb2_11'].divide(total_nbs_liq_df) ).mean()\n\tnbs12_liq = ( df['nb2_12'].divide(total_nbs_liq_df) ).mean()\n\tnbs22_liq = ( df['nb2_22'].divide(total_nbs_liq_df) ).mean() \n\n\tif rho1 > rho2:\n\t\tnbs_gas, nbs_liq = swap(nbs_gas, nbs_liq)\n\t\tnbs_gas_err, nbs_liq_err = swap(nbs_gas_err, nbs_liq_err)\n\t\tnbs11_gas, nbs11_liq = swap(nbs11_gas, nbs11_liq)\n\t\tnbs12_gas, nbs12_liq = swap(nbs12_gas, nbs12_liq)\n\t\tnbs22_gas, nbs22_liq = swap(nbs22_gas, nbs22_liq)\n\t\t\n\twith open(\"data-avg-nbonds.dat\", \"a\") as myfile:\n\t\tmyfile.write(\"{:3.2f} {:8.4f} +/- {:6.4f} {:8.4f} +/- {:6.4f} {:8.4f}{:8.4f}{:8.4f} {:8.4f}{:8.4f}{:8.4f}\\n\".\n\t\t\tformat(KbT, nbs_gas, nbs_gas_err, nbs_liq, nbs_liq_err, nbs11_gas, nbs12_gas, nbs22_gas, nbs11_liq, nbs12_liq, nbs22_liq ))\n\n\treturn nbs_gas, nbs_liq\n\ndef get_averages(fileName, nEquil, KbT):\n\t\n\tColumnNames = coln\t\n\tdata = pd.read_csv(fileName, \n\t\t\tdelim_whitespace=True, \n\t\t\theader=None, \n\t\t\tnames=ColumnNames, \n\t\t\tindex_col='nc')\n\n\n\tncycle = data.shape[0]\n\tnprod = ncycle - nEquil\n\tdf = data.iloc[nEquil:ncycle,0:]\n\t\n\t#average density of specie 1 (protein)\n\trho1_gas,rho1_liq = get_avg_densities(df, KbT)\n\n\t#average total density\n\trho_gas, rho_liq = get_total_densities(df, KbT)\n\n\t#average number of particle of each species in each phase\n\tx1_phase1, x2_phase1, x1_phase2, x2_phase2 = get_frac_species(df, KbT) \n\n\t#fraction of volume occupied by each species\n\tv1, v2, = get_avg_volume(df, KbT)\n\n\t#average chemical potential\n\tmu11, mu21, mu12, mu22 = get_mu(df, KbT)\n\n\t#type1-type1 average number of bonds per particle \n\te11_1, e11_2 = get_avg_nbonds(df, KbT)\n\n\t#Total average number of bonds per particle \n\te1T, e2T = get_Avg_nbonds(df, KbT)\n\tgas = get_gas_phase(df)\n\n\tprint(\"%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f %s\"%(rho1_gas, rho1_liq, rho_gas, rho_liq, x1_phase1, x2_phase1, x1_phase2, x2_phase2, v1,v2, e11_1,e11_2,e1T, e2T, mu11,mu21,mu12,mu22, gas) )\n \nif __name__==\"__main__\":\n\t\n\tget_averages( sys.argv[1], int(sys.argv[2]), float(sys.argv[3]) ) \n","sub_path":"utils/ensembleAvg.py","file_name":"ensembleAvg.py","file_ext":"py","file_size_in_byte":8830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"50928975","text":"list_tohoku = [5349, 5478, 5344, 4644, 4968, 6259]\nlist_shikoku = [3148, 2991, 2966, 2457]\n\navg_tohoku = 0\n\nfor val in list_tohoku:\n #print(val)\n avg_tohoku += val\n\navg_tohoku /= len(list_tohoku)\n\navg_shikoku = 0\n\nfor val in list_shikoku:\n avg_shikoku += val\n\navg_shikoku /= len(list_shikoku)\n\nprint(avg_tohoku)\nprint(avg_shikoku)\n\ndict_tohoku = {'aomori':5349, 'akita':4644, 'sendai':5344,'yamagata':4968, 'hukushima':6259, 'morioka':5478}\n\navg_tohoku = 0\n\nfor val in dict_tohoku:\n #print(val)\n avg_tohoku += dict_tohoku[val]\n\navg_tohoku /= len(dict_tohoku)\nprint(avg_tohoku)\n","sub_path":"start_for.py","file_name":"start_for.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"176647288","text":"import os\nimport supervisely_lib as sly\nfrom supervisely_lib.video_annotation.video_tag import VideoTag\n\napi = sly.Api(server_address=os.environ['SERVER_ADDRESS'], token=os.environ['API_TOKEN'])\n#or\n#api = sly.Api.from_env()\n\n\nproject_id = 1432\nproject = api.project.get_info_by_id(project_id)\nif project is None:\n raise RuntimeError(f\"Project id={project.id} not found\")\nif project.type != str(sly.ProjectType.VIDEOS):\n raise TypeError(\"Not a video project\")\n\nmeta_json = api.project.get_meta(project.id)\nmeta = sly.ProjectMeta.from_json(meta_json)\nprint(meta)\n\ntag = meta.get_tag_meta('vehicle_colour')\nprint(tag.sly_id)\n\ndataset = api.dataset.create(project.id, \"test_dataset\", change_name_if_conflict=True)\n\nlocal_path = \"/my_data/car.mp4\"\n\n# metadata is optional\nvideo_metadata = {\n \"field1\": \"value1\",\n \"field2\": \"value2\"\n}\n\n#smart upload - if video already uploaded to server, it will be added by hash to dataset withoud direct upload\nvideo_infos = api.video.upload_paths(dataset.id, [\"car.mp4\"], [local_path], metas=[video_metadata])\nvideo_info = video_infos[0]\n\nprint(video_info)\nprint(\"uploaded video id: \", video_info.id)\n\ntags_to_assign = [\n VideoTag(tag, value=\"red\", frame_range=[3, 17]),\n VideoTag(tag, value=\"orange\", frame_range=[22, 30]),\n]\napi.video.tag.append_to_entity(video_info.id, project.id, tags=sly.TagCollection(tags_to_assign))\n\n# see screenshot with result\n# https://i.imgur.com/eVtfY1k.png","sub_path":"plugins/python/src/examples/unsorted/upload_video_assign_tags.py","file_name":"upload_video_assign_tags.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"650036316","text":"from __future__ import annotations\n\nimport logging\nimport os\nimport struct\nimport unittest\n\nimport pytest\nfrom monty.io import zopen\n\nfrom pymatgen.io.qchem.utils import lower_and_check_unique, process_parsed_HESS\nfrom pymatgen.util.testing import PymatgenTest\n\n__author__ = \"Ryan Kingsbury, Samuel Blau\"\n__copyright__ = \"Copyright 2018-2022, The Materials Project\"\n\nlogger = logging.getLogger(__name__)\n\n\ntest_dir = os.path.join(PymatgenTest.TEST_FILES_DIR, \"molecules\", \"new_qchem_files\")\n\n\nclass UtilTest(PymatgenTest):\n \"\"\"\n test utils\n \"\"\"\n\n def test_lower_and_check_unique(self):\n d = {\"sVp\": {\"RHOISO\": 0.0009}, \"jobType\": \"SP\"}\n d2 = lower_and_check_unique(d)\n assert d2 == {\"svp\": {\"RHOISO\": 0.0009}, \"job_type\": \"sp\"}\n d3 = lower_and_check_unique(d2[\"svp\"])\n assert d3 == {\"rhoiso\": \"0.0009\"}\n d4 = {\"jobType\": \"SP\", \"JOBtype\": \"SP\"}\n # should not raise an exception\n assert lower_and_check_unique(d4) == {\"job_type\": \"sp\"}\n d4.update({\"jobType\": \"opt\"})\n with pytest.raises(ValueError, match=\"Multiple instances of key\"):\n lower_and_check_unique(d4)\n\n def test_process_parsed_HESS(self):\n data_132 = []\n with zopen(os.path.join(test_dir, \"parse_hess\", \"132.0\"), mode=\"rb\") as file:\n binary = file.read()\n for ii in range(int(len(binary) / 8)):\n data_132.append(struct.unpack(\"d\", binary[ii * 8 : (ii + 1) * 8])[0])\n\n data_HESS = []\n with zopen(\n os.path.join(test_dir, \"parse_hess\", \"HESS\"),\n mode=\"rt\",\n encoding=\"ISO-8859-1\",\n ) as f:\n data_HESS = f.readlines()\n\n processed_data_HESS = process_parsed_HESS(data_HESS)\n\n assert len(data_132) == len(processed_data_HESS)\n for ii, val in enumerate(data_132):\n diff = abs(val - processed_data_HESS[ii])\n assert diff < 1e-15\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"pymatgen/io/qchem/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"463882882","text":"from google.appengine.ext import db\n\n\nclass Problem(db.Model):\n name = db.StringProperty(required=True)\n categories = db.StringListProperty()\n description = db.TextProperty()\n examples = db.TextProperty()\n skeleton = db.TextProperty()\n tests = db.TextProperty()\n other_tests = db.TextProperty(required=False)\n solution = db.TextProperty(required=False)\n author = db.UserProperty()\n created = db.DateTimeProperty(auto_now_add=True)\n modified = db.DateTimeProperty(auto_now=True)\n\n\nclass ProblemUser(db.Model):\n problem = db.ReferenceProperty(Problem)\n user = db.UserProperty()\n solution = db.TextProperty()\n solved = db.BooleanProperty()\n def classname(self):\n return \"ProblemUser\"\n\n","sub_path":"pywhip/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"63369255","text":"import matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport numpy as np\nimport math\n\nrc('text', usetex=True);\nrc('font', family='serif', serif='Times');\n\na = np.arange(-6.0, 6.0, 0.1)\nsigmoid = 1.0 / (1.0 + np.exp(-1.0*a))\ntanh = np.tanh(a)\nstep = np.sign(a)\n\n\n\nplt.plot(a, sigmoid, 'r', label=r\"$f(a) = \\sigma(a)$\");\nplt.plot(a, tanh, 'b', label=r\"$f(a) = \\tanh(a)$\");\nplt.plot(a, step, 'g', label=r\"\\rmfamily $f(a) = $ sign$(a)$\");\nplt.grid(True);\nplt.xlabel(r\"Activation $a$\");\nplt.ylabel(r\"$f(a)$\");\nplt.legend(loc=2);\nplt.savefig(filename='activFunc.eps', transparent=True);\nplt.show();\n\n\n","sub_path":"prepReport/figures/activFunc.py","file_name":"activFunc.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"221978199","text":"import warnings\n\nimport datajoint as dj\n\nfrom .common_device import CameraDevice, DataAcquisitionDevice, Probe\nfrom .common_lab import Institution, Lab, LabMember\nfrom .common_nwbfile import Nwbfile\nfrom .common_subject import Subject\nfrom .nwb_helper_fn import get_nwb_file\n\nschema = dj.schema(\"common_session\")\n\n# TODO: figure out what to do about ExperimenterList\n\n\n@schema\nclass Session(dj.Imported):\n definition = \"\"\"\n # Table for holding experimental sessions.\n -> Nwbfile\n ---\n -> Subject\n -> Institution\n -> Lab\n session_id: varchar(80)\n session_description: varchar(80)\n session_start_time: datetime\n timestamps_reference_time: datetime\n experiment_description: varchar(80)\n \"\"\"\n\n def make(self, key):\n # These imports must go here to avoid cyclic dependencies\n # from .common_task import Task, TaskEpoch\n from .common_interval import IntervalList\n\n # from .common_ephys import Unit\n\n nwb_file_name = key['nwb_file_name']\n nwb_file_abspath = Nwbfile.get_abs_path(nwb_file_name)\n nwbf = get_nwb_file(nwb_file_abspath)\n\n print('Institution...')\n Institution().insert_from_nwbfile(nwbf)\n\n print('Lab...')\n Lab().insert_from_nwbfile(nwbf)\n\n print('LabMember...')\n LabMember().insert_from_nwbfile(nwbf)\n\n print('Subject...')\n Subject().insert_from_nwbfile(nwbf)\n\n print('DataAcquisitionDevice...')\n DataAcquisitionDevice().insert_from_nwbfile(nwbf)\n\n print('CameraDevice...')\n CameraDevice().insert_from_nwbfile(nwbf)\n\n print('Probe...')\n Probe().insert_from_nwbfile(nwbf)\n\n self.insert1({\n 'nwb_file_name': nwb_file_name,\n 'subject_id': nwbf.subject.subject_id,\n 'institution_name': nwbf.institution,\n 'lab_name': nwbf.lab,\n 'session_id': nwbf.session_id if nwbf.session_id is not None else 'tmp_id',\n 'session_description': nwbf.session_description,\n 'session_start_time': nwbf.session_start_time,\n 'timestamps_reference_time': nwbf.timestamps_reference_time,\n 'experiment_description': nwbf.experiment_description\n }, skip_duplicates=True)\n\n print('Skipping Apparatus for now...')\n # Apparatus().insert_from_nwbfile(nwbf)\n\n print('IntervalList...')\n IntervalList().insert_from_nwbfile(nwbf, nwb_file_name=nwb_file_name)\n\n # print('Unit...')\n # Unit().insert_from_nwbfile(nwbf, nwb_file_name=nwb_file_name)\n\n\n@schema\nclass ExperimenterList(dj.Imported):\n definition = \"\"\"\n -> Session\n \"\"\"\n\n class Experimenter(dj.Part):\n definition = \"\"\"\n -> ExperimenterList\n -> LabMember\n \"\"\"\n\n def make(self, key):\n nwb_file_name = key['nwb_file_name']\n nwb_file_abspath = Nwbfile().get_abs_path(nwb_file_name)\n self.insert1({'nwb_file_name': nwb_file_name}, skip_duplicates=True)\n nwbf = get_nwb_file(nwb_file_abspath)\n\n for e in nwbf.experimenter:\n # check to see if the experimenter is in the lab member list, and if not add her / him\n if {'lab_member_name': e} not in LabMember():\n names = [x.strip() for x in e.split(' ')]\n labmember_dict = dict()\n labmember_dict['lab_member_name'] = e\n if len(names) == 2:\n labmember_dict['first_name'] = names[0]\n labmember_dict['last_name'] = names[1]\n else:\n warnings.warn(\n f'Experimenter {e} does not seem to have a first and last name')\n labmember_dict['first_name'] = 'unknown'\n labmember_dict['last_name'] = 'unknown'\n LabMember().insert1(labmember_dict)\n # now insert the experimenter, which is a combination of the nwbfile and the name\n key = dict(\n nwb_file_name=nwb_file_name,\n lab_member_name=e\n )\n ExperimenterList().Experimenter().insert1(key)\n","sub_path":"src/nwb_datajoint/common/common_session.py","file_name":"common_session.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"81755723","text":"import requests\nimport json\nimport pandas as pd\n\nheaders = {\n 'Ocp-Apim-Subscription-Key': '0a5782c351ba49909e7de6fe63d06960',\n}\n\nscraped_company_data, temp = [], []\nlist_of_companies = ['Microsoft', 'Intel', 'Cisco']\n\nfor company in list_of_companies:\n list_of_queries = [f'disabled employees at {company}', f'employee accessibility stories {company}',\n f'{company} name erg disability', f'disabled employee blogs {company}',\n f'accessibility statement {company}', f'accommodation statement {company}',\n f'interview accommodations {company}']\n for query in list_of_queries:\n params = (\n ('q', query),\n ('count', '50'),\n )\n response = requests.get('https://api.bing.microsoft.com/v7.0/search', headers=headers, params=params)\n loaded_dict = (json.loads(response.content.decode(\"utf-8\")))\n\n for key, value in loaded_dict.items():\n if key == 'webPages':\n for k, v in value.items():\n if k == 'value':\n list_urls = v\n\n for i, element in enumerate(list_urls):\n scraped_company_data.append([company, query, element['url'], element['name'], element['snippet']])\n\nscraped_company_df = pd.DataFrame(scraped_company_data, columns=['Company Name', 'Query', 'URL', 'Name of Web Page',\n 'Web Page Snippet'])\nscraped_company_df.to_csv('search-output-python-first.csv')","sub_path":"Bing-Search/search-python-first.py","file_name":"search-python-first.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"475364459","text":"from ray import tune\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n#from sklearn.model_selection import cross_validate, cross_val_score\nfrom sklearn.preprocessing import StandardScaler\n#import sklearn.preprocessing as skl_pre\nfrom sklearn.metrics import r2_score, mean_squared_error\n\nimport ray\nray.init(address='auto', _redis_password='5241590000000000')\n\n\nseed = 67\n#Collect the preprossesed data. \ndata = pd.read_csv('preprosessedData.csv')\nX = data.drop(columns=['stargazers_count'])\ny = data['stargazers_count'].astype(int)\nX = StandardScaler().fit_transform(X)\n#splitting the data in a testset and a training set \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=seed)\n\ndef train_RF(config):\n n_estimators = config['n_estimators']\n criterion = config['criterion']\n max_depth = config['max_depth']\n min_samples_leaf = config['min_samples_leaf']\n min_samples_split = config['min_samples_split']\n for step in range(5):\n rfc = RandomForestRegressor(n_estimators= n_estimators,criterion = criterion,max_depth=max_depth, n_jobs = -1, random_state=seed)\n rfc.fit(X_train,y_train)\n \n test_predRFC = rfc.predict(X_test)\n test_scoreRFC = mean_squared_error(y_test, test_predRFC,squared=False)\n tune.report(mean_loss = test_scoreRFC)\n \n\nanalysis = tune.run(\n train_RF,\n config={\n \"n_estimators\": tune.grid_search([90,100]),\n \"criterion\": tune.grid_search(['mse']), \n 'max_depth': tune.grid_search([7,8,9]),\n 'min_samples_leaf': tune.grid_search([1,2]),\n 'min_samples_split' : tune.grid_search([2,3])\n })\n\n\n\nprint(\"Best config: \", analysis.get_best_config(\n metric=\"mean_loss\", mode=\"min\"))\n\n# Get a dataframe for analyzing trial results.\ndf = analysis.results_df\n\n","sub_path":"ci_cd/development_server/rayTuneRF.py","file_name":"rayTuneRF.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"317444991","text":"\"\"\"scraping info I need from url on EVs\"\"\"\n\nfrom bs4 import BeautifulSoup\nimport requests\n\nurl = \"http://bulbapedia.bulbagarden.net/wiki/List_of_Pok%C3%A9mon_by_effort_value_yield\"\nresponse = requests.get(url)\nhtml = response.content\nsoup = BeautifulSoup(html, 'html.parser')\ntable = soup.find('table')\n\n\ndef scrape(pokeNum, attr, tableArg=table):\n \"\"\"scraping info I need from url on EVs\"\"\"\n pNum = 0\n \n for row in tableArg.findAll('tr')[pokeNum:pokeNum+1]:\n pNum += 1\n if pNum > 151:\n break\n hpEv = row.findAll('td')[4].text.strip('\\n').strip(' ')\n attackEv = row.findAll('td')[5].text.strip('\\n').strip(' ')\n defenseEv = row.findAll('td')[6].text.strip('\\n').strip(' ')\n spAtkEv = row.findAll('td')[7].text.strip('\\n').strip(' ')\n spDefEv = row.findAll('td')[8].text.strip('\\n').strip(' ')\n speedEv = row.findAll('td')[9].text.strip('\\n').strip(' ')\n if attr == 1:\n return hpEv\n elif attr == 2:\n return attackEv\n elif attr == 3:\n return defenseEv\n elif attr == 4:\n return spDefEv\n elif attr == 5:\n return spAtkEv\n elif attr == 6:\n return speedEv\n","sub_path":"pokemonScrape/evScrape.py","file_name":"evScrape.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"431448275","text":"import os\r\nimport sys\r\nimport csv\r\nimport time\r\nimport glob\r\nimport os.path\r\nimport itertools\r\nimport serial\r\n\r\nimport PyQt5\r\n\r\nfrom PyQt5 import QtCore\r\nfrom PyQt5.QtGui import (\r\n QPixmap\r\n)\r\nfrom PyQt5.QtWidgets import (\r\n QLCDNumber,\r\n QLabel,\r\n QComboBox,\r\n QCheckBox,\r\n QSplashScreen,\r\n QPushButton,\r\n QFileDialog,\r\n QLineEdit,\r\n QGridLayout,\r\n QHBoxLayout,\r\n QVBoxLayout,\r\n QApplication,\r\n QFrame,\r\n QDialog\r\n)\r\n\r\nfrom bitstring import BitArray\r\n\r\nPACKET_LENGTH = 32\r\nLCD_DIGIT_COUNT = 6\r\nDELAY_CNT = 15\r\n\r\nPACKET_HEADER = '0x55'\r\nACCEL_PREFIX = '0x51'\r\nVEL_PREFIX = '0x52'\r\nANGLE_PREFIX = '0x53'\r\n\r\nDEFAULT_PORT = 'COM14'\r\nDEFAULT_BAUDRATE = '115200'\r\nBAUDRATES = (\r\n '110',\r\n '300',\t\r\n '600',\r\n '1200',\t\r\n '2400',\r\n '4800',\r\n '9600',\r\n '14400',\t\r\n '19200',\r\n '28800',\t\r\n '38400',\r\n '56000',\t\r\n '57600',\r\n '115200'\r\n)\r\n\r\nSTYLE = \"\"\"\r\nQLCDNumber {\r\n background: black;\r\n color:green;\r\n}\r\n\r\nQLCDNumber:flat {\r\n border: none;\r\n}\r\n\r\nQLabel {\r\n color: black;\r\n font: bold\r\n}\r\n\r\nMargin {\r\n font: bold 60px;\r\n qproperty-alignment: AlignCenter;\r\n}\r\n\r\nHeader {\r\n font: 20px; \r\n qproperty-alignment: 'AlignBottom | AlignCenter';\r\n}\r\n\r\nConnectButton {\r\n font: bold 14px;\r\n padding-top: 0px;\r\n padding-bottom: 0px;\r\n padding-right: 2px;\r\n padding-left: 2px;\r\n}\r\n\r\nConnectButton:checked {\r\n color: red\r\n}\r\n\r\nBrowseButton {\r\n font: 14px;\r\n padding-top: 2px;\r\n padding-bottom: 2px;\r\n padding-right: 4px;\r\n padding-left: 4px;\r\n}\r\n\r\nAngleButton {\r\n font: bold 14px;\r\n padding-top: 1px;\r\n padding-bottom: 1px;\r\n padding-right: 3px;\r\n padding-left: 3px;\r\n}\r\n\"\"\"\r\n\r\ndef get_ports():\r\n \"\"\" Lists serial port names\r\n\r\n :raises EnvironmentError:\r\n On unsupported or unknown platforms\r\n :returns:\r\n A list of the serial ports available on the system\r\n \"\"\"\r\n if sys.platform.startswith('win'):\r\n import winreg \r\n \r\n path = 'HARDWARE\\\\DEVICEMAP\\\\SERIALCOMM'\r\n key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)\r\n ports = []\r\n \r\n for i in itertools.count():\r\n try:\r\n param, value, _ = winreg.EnumValue(key, i)\r\n if 'BthModem' not in param:\r\n ports.append(value)\r\n except EnvironmentError:\r\n break\r\n return ports\r\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\r\n # this excludes your current terminal \"/dev/tty\"\r\n ports = glob.glob('/dev/tty[A-Za-z]*')\r\n elif sys.platform.startswith('darwin'):\r\n ports = glob.glob('/dev/tty.*')\r\n else:\r\n raise EnvironmentError('Unsupported platform')\r\n\r\n result = []\r\n for port in ports:\r\n try:\r\n s = serial.Serial(port)\r\n s.close()\r\n result.append(port)\r\n except (OSError, serial.SerialException):\r\n pass\r\n return result\r\n\r\n\r\nclass ImuSignal(QtCore.QObject): \r\n angle_x = QtCore.pyqtSignal(str)\r\n angle_y = QtCore.pyqtSignal(str)\r\n angle_z = QtCore.pyqtSignal(str)\r\n \r\n accel_x = QtCore.pyqtSignal(str)\r\n accel_y = QtCore.pyqtSignal(str)\r\n accel_z = QtCore.pyqtSignal(str)\r\n \r\n vel_x = QtCore.pyqtSignal(str)\r\n vel_y = QtCore.pyqtSignal(str)\r\n vel_z = QtCore.pyqtSignal(str)\r\n \r\n \r\nclass SerialReadThread(QtCore.QThread):\r\n def __init__(self):\r\n super().__init__()\r\n \r\n self.signal = ImuSignal()\r\n \r\n self.imu_data = {\r\n 'accel_x': 0.0, 'accel_y': 0.0, 'accel_z': 0.0, 'accel_t': 0.0,\r\n 'vel_x' : 0.0, 'vel_y' : 0.0, 'vel_z' : 0.0, 'vel_t' : 0.0,\r\n 'angle_x': 0.0, 'angle_y': 0.0, 'angle_z': 0.0, 'angle_t': 0.0\r\n }\r\n \r\n self.start_angle_x = 0\r\n self.start_angle_y = 0\r\n self.start_angle_z = 0\r\n \r\n self.record_state = False\r\n \r\n def open_port(self, port, baudrate):\r\n self.ser = serial.Serial(port, baudrate)\r\n \r\n def create_file(self, path):\r\n ext = '.csv'\r\n fname = os.path.join(\r\n path,\r\n time.strftime('%Y%m%d%H%M%S') + ext\r\n )\r\n self.fobject = open(fname, 'w', newline='')\r\n \r\n fieldnames = sorted(self.imu_data.keys())\r\n self.file_writer = csv.DictWriter(self.fobject, fieldnames=fieldnames)\r\n self.file_writer.writeheader()\r\n \r\n self.record_state = True\r\n \r\n def read_ser_data(self):\r\n ser_data = BitArray()\r\n \r\n while True:\r\n packet_header = BitArray(self.ser.read())\r\n if packet_header == PACKET_HEADER:\r\n ser_data += packet_header\r\n break\r\n \r\n ser_data += BitArray(self.ser.read(PACKET_LENGTH))\r\n return ser_data\r\n \r\n def decode_imu_data(self, ser_data):\r\n chunks = ser_data.unpack('bytes:11, bytes:11, bytes:11')\r\n \r\n for chunk in chunks:\r\n _, prefix, *bs = BitArray(chunk).unpack(\r\n 'bytes:1, bytes:1, intle:16, intle:16, intle:16, intle:16'\r\n ) \r\n if BitArray(prefix) == ACCEL_PREFIX:\r\n self.imu_data['accel_x'] = bs[0] / 32768 * 16\r\n self.imu_data['accel_y'] = bs[1] / 32768 * 16\r\n self.imu_data['accel_z'] = bs[2] / 32768 * 16\r\n self.imu_data['accel_t'] = bs[3] / 340 + 36.25\r\n elif BitArray(prefix) == VEL_PREFIX:\r\n self.imu_data['vel_x'] = bs[0] / 32768 * 2000\r\n self.imu_data['vel_y'] = bs[1] / 32768 * 2000\r\n self.imu_data['vel_z'] = bs[2] / 32768 * 2000\r\n self.imu_data['vel_t'] = bs[3] / 340 + 36.25\r\n elif BitArray(prefix) == ANGLE_PREFIX:\r\n self.imu_data['angle_x'] = bs[0] / 32768 * 180\r\n self.imu_data['angle_y'] = bs[1] / 32768 * 180\r\n self.imu_data['angle_z'] = bs[2] / 32768 * 180\r\n self.imu_data['angle_t'] = bs[3] / 340 + 36.25\r\n else:\r\n pass # TODO: error handling here\r\n \r\n def set_relative_angle(self):\r\n self.start_angle_x = self.imu_data['angle_x']\r\n self.start_angle_y = self.imu_data['angle_y']\r\n self.start_angle_z = self.imu_data['angle_z']\r\n \r\n def set_absolute_angle(self):\r\n self.start_angle_x = 0\r\n self.start_angle_y = 0\r\n self.start_angle_z = 0\r\n \r\n def run(self):\r\n delay_cnt = DELAY_CNT\r\n \r\n while True:\r\n self.decode_imu_data(self.read_ser_data())\r\n \r\n if self.record_state:\r\n self.file_writer.writerow(self.imu_data)\r\n \r\n if delay_cnt:\r\n delay_cnt -= 1\r\n else:\r\n delay_cnt = DELAY_CNT\r\n \r\n self.signal.angle_x.emit(\r\n '{:=6.1f}'.format(\r\n self.imu_data['angle_x'] - self.start_angle_x\r\n )\r\n )\r\n self.signal.angle_y.emit(\r\n '{:=6.1f}'.format(\r\n self.imu_data['angle_y'] - self.start_angle_y\r\n )\r\n )\r\n self.signal.angle_z.emit(\r\n '{:=6.1f}'.format(\r\n self.imu_data['angle_z'] - self.start_angle_z\r\n )\r\n )\r\n self.signal.accel_x.emit(\r\n '{:=6.2f}'.format(self.imu_data['accel_x'])\r\n )\r\n self.signal.accel_y.emit(\r\n '{:=6.2f}'.format(self.imu_data['accel_y'])\r\n )\r\n self.signal.accel_z.emit(\r\n '{:=6.2f}'.format(self.imu_data['accel_z'])\r\n )\r\n self.signal.vel_x.emit(\r\n '{:=5.0f}'.format(self.imu_data['vel_x'])\r\n )\r\n self.signal.vel_y.emit(\r\n '{:=5.0f}'.format(self.imu_data['vel_y'])\r\n )\r\n self.signal.vel_z.emit(\r\n '{:=5.0f}'.format(self.imu_data['vel_z'])\r\n )\r\n \r\n \r\nclass Margin(QLabel):\r\n \r\n def __init__(self, txt):\r\n super().__init__(txt)\r\n \r\n \r\nclass Header(QLabel):\r\n \r\n def __init__(self, txt):\r\n super().__init__(txt)\r\n \r\n \r\nclass ConnectButton(QPushButton):\r\n \r\n def __init__(self, txt):\r\n super().__init__(txt)\r\n \r\n \r\nclass BrowseButton(QPushButton):\r\n \r\n def __init__(self, txt):\r\n super().__init__(txt)\r\n \r\n \r\nclass AngleButton(QPushButton):\r\n \r\n def __init__(self, txt):\r\n super().__init__(txt)\r\n \r\n \r\nclass ImuInterface(QDialog):\r\n \r\n def __init__(self):\r\n super().__init__(\r\n None,\r\n QtCore.Qt.Window |\r\n QtCore.Qt.WindowTitleHint |\r\n QtCore.Qt.WindowCloseButtonHint\r\n )\r\n \r\n self.connection_state = False\r\n# self.ports = (DEFAULT_PORT,) # get_ports()\r\n self.ports = get_ports()\r\n self.imu_thread = SerialReadThread()\r\n self.imu_thread.finished.connect(self.close_port)\r\n \r\n self.initUI()\r\n \r\n def connect_serial(self):\r\n \r\n if not self.connection_state:\r\n self.imu_thread.open_port(\r\n self.ports_list.currentText(),\r\n int(self.baudrates_list.currentText())\r\n )\r\n self.record_box.setEnabled(False) \r\n \r\n if self.record_box.isChecked():\r\n self.imu_thread.create_file(self.file_path.text())\r\n \r\n self.imu_thread.start()\r\n self.imu_thread.set_absolute_angle()\r\n self.connection_state = True\r\n else:\r\n self.imu_thread.terminate()\r\n self.connection_state = False\r\n self.record_box.setEnabled(True)\r\n self.clear_lcds()\r\n \r\n def close_port(self):\r\n self.imu_thread.ser.flush()\r\n self.imu_thread.ser.close()\r\n \r\n if self.record_box.isChecked():\r\n self.imu_thread.fobject.flush()\r\n self.imu_thread.fobject.close()\r\n \r\n def create_lcd(self, signal):\r\n lcd = QLCDNumber(self)\r\n \r\n lcd.setDigitCount(LCD_DIGIT_COUNT)\r\n lcd.setSegmentStyle(QLCDNumber.Flat)\r\n signal.connect(lcd.display)\r\n \r\n return lcd\r\n \r\n def clear_lcds(self):\r\n for lcd in self.findChildren(QLCDNumber):\r\n lcd.display(0)\r\n \r\n def show_select_dir_dialog(self):\r\n path = QFileDialog.getExistingDirectory(\r\n self,\r\n 'Выберите директорию',\r\n os.getcwd(),\r\n QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks\r\n )\r\n if path:\r\n self.file_path.setText(str(path))\r\n \r\n def create_vline(self):\r\n vline = QFrame()\r\n vline.setFrameShape(QFrame.VLine)\r\n vline.setFrameShadow(QFrame.Sunken)\r\n \r\n return vline\r\n \r\n def initUI(self):\r\n \r\n menu = QHBoxLayout()\r\n \r\n rel_angle_button = AngleButton('0')\r\n rel_angle_button.setToolTip('Относительные значения угла')\r\n rel_angle_button.clicked.connect(self.imu_thread.set_relative_angle)\r\n menu.addWidget(rel_angle_button)\r\n \r\n abs_angle_button = AngleButton('A')\r\n abs_angle_button.setToolTip('Абсолютные значения угла')\r\n abs_angle_button.clicked.connect(self.imu_thread.set_absolute_angle)\r\n menu.addWidget(abs_angle_button)\r\n \r\n menu.addWidget(self.create_vline())\r\n \r\n connect_button = ConnectButton('\\U0001F50C')\r\n connect_button.setToolTip('Подключить/отключить')\r\n connect_button.setCheckable(True)\r\n connect_button.clicked.connect(self.connect_serial)\r\n menu.addWidget(connect_button)\r\n \r\n menu.addWidget(QLabel('Порт:'))\r\n \r\n self.ports_list = QComboBox(self)\r\n for port in self.ports:\r\n self.ports_list.addItem(port)\r\n menu.addWidget(self.ports_list)\r\n \r\n menu.addWidget(QLabel('Скорость:'))\r\n \r\n self.baudrates_list = QComboBox(self)\r\n for baudrate in BAUDRATES:\r\n self.baudrates_list.addItem(baudrate)\r\n self.baudrates_list.setCurrentIndex(BAUDRATES.index(DEFAULT_BAUDRATE))\r\n menu.addWidget(self.baudrates_list)\r\n \r\n menu.addWidget(self.create_vline())\r\n \r\n menu.addWidget(QLabel('Запись:'))\r\n \r\n self.record_box = QCheckBox()\r\n menu.addWidget(self.record_box)\r\n\r\n menu.addWidget(QLabel('��уть:'))\r\n \r\n self.file_path = QLineEdit(os.getcwd())\r\n self.file_path.setReadOnly(True)\r\n menu.addWidget(self.file_path)\r\n \r\n select_path_button = BrowseButton('...')\r\n select_path_button.setToolTip('Выбрать директорию')\r\n select_path_button.clicked.connect(self.show_select_dir_dialog)\r\n menu.addWidget(select_path_button)\r\n \r\n table = QGridLayout()\r\n \r\n table.addWidget(Margin('X'), 1, 0)\r\n table.addWidget(Margin('Y'), 2, 0)\r\n table.addWidget(Margin('Z'), 3, 0)\r\n \r\n table.addWidget(Header('Угол (гр.)'), 0, 1)\r\n table.addWidget(Header('Ускорение (g)'), 0, 2)\r\n table.addWidget(Header('Скорость (гр./сек.)'), 0, 3)\r\n \r\n table.addWidget(self.create_lcd(self.imu_thread.signal.angle_x), 1, 1)\r\n table.addWidget(self.create_lcd(self.imu_thread.signal.angle_y), 2, 1)\r\n table.addWidget(self.create_lcd(self.imu_thread.signal.angle_z), 3, 1)\r\n \r\n table.addWidget(self.create_lcd(self.imu_thread.signal.accel_x), 1, 2)\r\n table.addWidget(self.create_lcd(self.imu_thread.signal.accel_y), 2, 2)\r\n table.addWidget(self.create_lcd(self.imu_thread.signal.accel_z), 3, 2)\r\n \r\n table.addWidget(self.create_lcd(self.imu_thread.signal.vel_x), 1, 3)\r\n table.addWidget(self.create_lcd(self.imu_thread.signal.vel_y), 2, 3)\r\n table.addWidget(self.create_lcd(self.imu_thread.signal.vel_z), 3, 3)\r\n \r\n table.setColumnStretch(0, 2)\r\n table.setColumnStretch(1, 5)\r\n table.setColumnStretch(2, 5)\r\n table.setColumnStretch(3, 5)\r\n \r\n table.setRowStretch(0, 1)\r\n table.setRowStretch(1, 10)\r\n table.setRowStretch(2, 10)\r\n table.setRowStretch(3, 10)\r\n \r\n hline = QFrame()\r\n hline.setFrameShape(QFrame.HLine)\r\n hline.setFrameShadow(QFrame.Sunken)\r\n \r\n layout = QVBoxLayout()\r\n layout.addLayout(menu)\r\n layout.addWidget(hline)\r\n layout.addLayout(table)\r\n\r\n self.setLayout(layout)\r\n \r\n self.setFixedSize(700, 300)\r\n self.setWindowTitle('MPU6050')\r\n self.show()\r\n\r\n \r\ndef main():\r\n pyqt = os.path.dirname(PyQt5.__file__)\r\n QApplication.addLibraryPath(os.path.join(pyqt, 'plugins'))\r\n \r\n app = QApplication(sys.argv)\r\n app.setStyleSheet(STYLE)\r\n \r\n ex = ImuInterface()\r\n \r\n sys.exit(app.exec_())\r\n \r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"mpu6050-qt.py","file_name":"mpu6050-qt.py","file_ext":"py","file_size_in_byte":15661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"534343147","text":"\"\"\"\nFile: anagram.py\nName:\n----------------------------------\nThis program recursively finds all the anagram(s)\nfor the word input by user and terminates when the\ninput string matches the EXIT constant defined\nat line 19\n\nIf you correctly implement this program, you should see the\nnumber of anagrams for each word listed below:\n * arm -> 3 anagrams\n * contains -> 5 anagrams\n * stop -> 6 anagrams\n * tesla -> 10 anagrams\n * spear -> 12 anagrams\n\"\"\"\n\n# Constants\nFILE = 'dictionary.txt' # This is the filename of an English dictionary\nEXIT = '-1' # Controls when to stop the loop\ndict_list = []\n\n\ndef main():\n print('Welcome to stanCode \"Anagram Generator\" (or -1 to quit)')\n read_dictionary()\n while True:\n search = input('Find anagrams for: ')\n if search == EXIT:\n break\n else:\n find_anagrams(search)\n\n\ndef read_dictionary():\n with open(FILE, 'r') as f:\n for line in f:\n word = line.strip()\n dict_list.append(word)\n\n\ndef find_anagrams(s):\n \"\"\"\n :param s:\n :return:\n \"\"\"\n ans_lst = []\n count_lst = []\n ans = ''\n s_length = len(s)\n ans_index = []\n s_index = []\n for i in range(len(s)):\n s_index.append(i)\n print('Searching...')\n find_anagrams_helper(s, s_length, s_index, ans, ans_index, ans_lst, count_lst)\n print(sum(count_lst), 'anagrams:', ans_lst)\n\n\ndef find_anagrams_helper(s, s_length, s_index, ans, ans_index, ans_lst, count_lst):\n if len(ans_index) == s_length or has_prefix(ans) is False:\n if ans in dict_list and ans not in ans_lst:\n print('Found:', ans)\n ans_lst.append(ans)\n count_lst.append(1)\n print('Searching...')\n else:\n for ele in s_index:\n if ele not in ans_index:\n ans_index.append(ele)\n ans = ''\n for i in ans_index:\n ans += s[i]\n find_anagrams_helper(s, s_length, s_index, ans, ans_index, ans_lst, count_lst)\n ans_index.pop()\n\n\ndef has_prefix(sub_s):\n \"\"\"\n :param sub_s:\n :return: boolean\n \"\"\"\n for word in dict_list:\n if word.startswith(sub_s) is True:\n return True\n return False\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sc-projects/find_anagrams/anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"170768815","text":"from helper import *\nfrom Transformation import *\nfrom collections import defaultdict\n\n# These methods will be necessary for the project's main method to run.\nclass Agent1:\n # The default constructor for your Agent. Make sure to execute any\n # processing necessary before your Agent starts solving problems here.\n #\n # Do not add any variables to this signature; they will not be used by\n # main().\n def __init__(self):\n pass\n\n\n\n def Solve(self,problem):\n\n\n AtoB = Transformation(problem.getFigures().get(\"A\").getObjects(),problem.getFigures().get(\"B\").getObjects())\n\n AtoBMatrix = AtoB.get_matrix()\n\n #Get matrix of relationship scores\n result = get_matrix(problem.getFigures().get(\"A\").getObjects(),problem.getFigures().get(\"B\").getObjects())\n\n\n\n changeListAB = get_changeList(result,problem.getFigures().get(\"A\").getObjects(),problem.getFigures().get(\"B\").getObjects())\n normalize(changeListAB)\n\n\n sameListAB = get_sameList(result,problem.getFigures().get(\"A\").getObjects(),problem.getFigures().get(\"B\").getObjects())\n winner='none'\n\n sharedct=[]\n score=0\n #default winner to 1\n winner='1'\n tie=[]\n simScore=[]\n\n #need number of objects in picture (the difference) to be consistent\n aObjectCt=len(problem.getFigures().get(\"A\").getObjects())\n bObjectCt=len(problem.getFigures().get(\"B\").getObjects())\n cObjectCt=len(problem.getFigures().get(\"C\").getObjects())\n\n abDIFF=bObjectCt - aObjectCt\n\n\n\n #eligible\n\n\n for i in range(1,7):\n\n # if len(problem.getFigures().get(\"%s\"%i).getObjects() )==0:\n # continue\n\n\n dObjectCt = len(problem.getFigures().get(\"%s\"%i).getObjects())\n cdDIFF = dObjectCt - cObjectCt\n\n #print \" AB DIFF: \", abDIFF, \" CD DIFF: \", cdDIFF\n\n bonus=0\n\n if cdDIFF != abDIFF:\n bonus=-10000\n\n\n\n result2 = get_matrix(problem.getFigures().get(\"C\").getObjects(),problem.getFigures().get(\"%s\" %i).getObjects())\n\n\n changeListCD = get_changeList(result2,problem.getFigures().get(\"C\").getObjects(),problem.getFigures().get(\"%s\" %i).getObjects())\n\n\n shared_attr_ct = len(get_shared_attributes(changeListAB,changeListCD))\n\n normalize(changeListCD)\n\n\n\n sameListCD = get_sameList(result2,problem.getFigures().get(\"C\").getObjects(),problem.getFigures().get(\"%s\" %i).getObjects())\n\n #compare ChangeListCD with ChangeListAB\n shared_items = get_similar_items(changeListAB,changeListCD)\n\n shared_similarities = get_similar_items(sameListAB,sameListCD)\n\n\n unchanged_BUMP=0\n\n #get similar items between C and Answer\n # print \"ALMOST DONNNEEEE \" , \\\n get_same_attrValPAIRS(problem.getFigures().get(\"C\").getObjects(),problem.getFigures().get(\"%s\"%i).getObjects())\n\n\n ##here we add a bonus for the same shape present\n #from C to Ans\n samePairsofShapes = len(get_same_attrValPAIRS(problem.getFigures().get(\"C\").getObjects(),problem.getFigures().get(\"%s\"%i).getObjects()))\n\n bonus+=samePairsofShapes\n\n # print \"Shared attribute ct is %s\"%shared_attr_ct, \"problem %s \" %problem.getName() , \"Lenshared: %s\" %len(shared_items), shared_items\n # print 'AB Transforms are ', changeListAB, ' CD are ', changeListCD\n\n # if the number of changes is equal between a:b c:ans\n #then add a bonus\n\n #as a default take answer with max shared items\n sharedct.append(len(shared_items))\n\n # print len(shared_similarities), \" SHARED SIMILARITIES!!!!!\"\n\n # print '\\n'\n\n simScore.append(len(shared_similarities))\n\n bonus+=simScore[i-1]\n\n total=0\n bdMatrix = get_matrix(problem.getFigures().get(\"B\").getObjects(),problem.getFigures().get(\"%s\" %i).getObjects())\n for row in bdMatrix:\n if row!=[]:total=+max(row)\n\n\n\n\n\n\n if len(changeListAB)==len(changeListCD):\n bonus+=5\n\n #if shape stays the same we weight the highest\n if 'shape' not in changeListAB and 'shape' not in changeListCD:\n bonus+=4\n\n\n if 'angle' in changeListAB and ('180' or 180 in changeListAB['angle']) \\\n and ('vertical-flip' in changeListCD) and (changeListCD['vertical-flip']==['yes']):\n bonus+=10\n\n for items in shared_items:\n if items[0]=='shape':\n bonus+=3\n if items[0]=='angle':\n bonus+=2\n if items[0]=='fill':\n bonus+=1\n if items[0]=='vertical-flip':\n bonus+=5\n\n\n\n\n\n #the final score is going to be number of precisely exact transformations\n #plus an added bonus if the quantity of transformations is equal\n\n\n if len(shared_items)+bonus+shared_attr_ct >= score:\n if len(shared_items)+bonus+shared_attr_ct > score:\n score = len(shared_items)+bonus+shared_attr_ct\n winner= \"%s\" %i\n\n else:\n #append current winner and the current problem\n tie.append(i)\n if (i-1) not in tie and i-1!=0 : tie.append(i-1)\n winner='tie'\n\n\n\n\n\n #if there is a unique max which has more shared\n #transformations than any other choice, take that one.\n m = max(sharedct)\n if len([i for i, j in enumerate(sharedct) if j == m])==1:\n return str(sharedct.index(m)+1)\n\n\n #now we break the tie by taking whatever object has the most\n #transformations (not object specific this time)\n #\n if winner == 'tie':\n #print \"WE NEED TO GO TO TIE BREAKER\"\n #has matrix of relations between B and D\n #The objects between B and D that are related we want to maximize the total score\n #we are taking the answer choice that maximizes the magnitude of the relationship\n tmpWinner=('0',0)\n for i in range(1,7):\n total=0\n\n dObjectCt = len(problem.getFigures().get(\"%s\"%i).getObjects())\n cdDIFF = dObjectCt - cObjectCt\n if cdDIFF != abDIFF:\n continue\n\n\n bdMatrix = get_matrix(problem.getFigures().get(\"B\").getObjects(),problem.getFigures().get(\"%s\" %i).getObjects())\n for row in bdMatrix:\n total=+max(row)\n\n if .82*total+(int(simScore[i-1])) >= tmpWinner[1]:\n if .82*total+(int(simScore[i-1])) > tmpWinner[1]:\n #print \"TOTAL \", total, i\n tmpWinner=(i,total)\n else:\n tmpWinner=('tie',0)\n\n\n return str(tmpWinner[0])\n\n if winner is None:\n return \"Fail\"\n\n return winner\n\n\n","sub_path":"Project2-jfalkson3-Python/Agent1.py","file_name":"Agent1.py","file_ext":"py","file_size_in_byte":7095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"230494768","text":"'''\nEdit Distance\nhttps://leetcode.com/problems/edit-distance/\n\nGiven two words word1 and word2, find the minimum number of operations required to convert word1 to word2.\n\nYou have the following 3 operations permitted on a word:\n\n Insert a character\n Delete a character\n Replace a character\n\nExample 1:\n\nInput: word1 = \"horse\", word2 = \"ros\"\nOutput: 3\nExplanation: \nhorse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')\n\nExample 2:\n\nInput: word1 = \"intention\", word2 = \"execution\"\nOutput: 5\n\nExplanation: \nintention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')\n'''\n\n#**********************************\n#*********** VERSION 1 ************\n#**********************************\n#Dynamic programming\n\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n if word1 == \"\" or word2 == \"\":\n return max(len(word1), len(word2))\n matrix = [[0] * (len(word1) + 1) for i in range(len(word2) + 1)]\n for i in range(len(word2) + 1):\n matrix[i][0] = i\n for j in range(len(word1) + 1):\n matrix[0][j] = j \n for i in range(1, len(word2) + 1):\n for j in range(1, len(word1) + 1):\n if word1[j-1] == word2[i-1]:\n matrix[i][j] = matrix[i-1][j-1]\n else:\n matrix[i][j] = min(matrix[i-1][j-1], matrix[i-1][j], matrix[i][j-1]) + 1\n return matrix[-1][-1]\n\n#**********************************\n#*********** VERSION 2 ************\n#**********************************\n#Dynamic programming, recursion\n\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n @lru_cache(None)\n def dp(i, j):\n if i < 0 or j < 0:\n return max(i, j) + 1\n return dp(i-1, j-1) if word1[j] == word2[i] \\\n else min(dp(i-1, j-1), dp(i-1, j), dp(i, j-1)) + 1\n return dp(len(word2) - 1, len(word1) - 1)\n","sub_path":"LeetCoding Challenge/May/31.py","file_name":"31.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"299417727","text":"# string = input('Hows it going today?\\n')\n\n# copy = True\n# while copy == True:\n# print(string)\n# string = input()\n# if string == 'stop copying me':\n# copy = False\n# print('Fine, I guess ill stop')\n\n#First Colt Solution\n\n# msg = input('Say something\\n')\n\n# while msg != 'stop copying me':\n# print(msg)\n# msg = input()\n# print('UGH FINE')\n\n# best solution\n\nwhile msg != 'stop copying me':\n msg = input(f'{msg}\\n')\nprint('UGH FINE')\n","sub_path":"10_loops/exersises/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"619387742","text":"from django.contrib.postgres.fields import JSONField\nfrom django.db import models\n\nfrom api.models import AppUser\n\n\n# Create your models here.\n\n\nclass StudentDetails(models.Model):\n\tuser = models.OneToOneField(AppUser, on_delete=models.CASCADE, primary_key=True)\n\tstudent_id = models.CharField(max_length=50, null=False)\n\tfull_name = models.CharField(max_length=100, null=False)\n\temail = models.EmailField(null=False)\n\tphone = models.CharField(max_length=20)\n\tcgpa = models.FloatField(null=False)\n\tgraduation_status = models.BooleanField(editable=True, default=False)\n\tdegree = models.CharField(max_length=50)\n\t# graduation_year = models.CharField(max_length=5, null=False)\n\tupdated_at = models.DateTimeField(auto_now=True, null=False)\n\n\nclass StudentProfilePicture(models.Model):\n\tpicture = models.ImageField(upload_to='student_profile_pics', blank=True)\n\tpicture_url_google = models.URLField(blank=True, editable=True)\n\tuser = models.OneToOneField(AppUser, on_delete=models.CASCADE, primary_key=True)\n\n\nclass Lor(models.Model):\n\tid = models.AutoField(primary_key=True)\n\tuser = models.ForeignKey(AppUser, on_delete=models.CASCADE)\n\tpurpose = models.CharField(max_length=250, null=False)\n\tothers_details = models.CharField(max_length=250, null=True, blank=True)\n\tuniversity_name = models.CharField(max_length=250)\n\tprogram_name = models.CharField(max_length=250)\n\tdeadline = models.DateTimeField()\n\texpired = models.BooleanField(editable=True, default=False)\n\thidden = models.BooleanField(editable=True, default=False)\n\tcreated_at = models.DateTimeField(auto_now_add=True, null=False)\n\tupdated_at = models.DateTimeField(auto_now=True, null=False)\n\n\nclass FacultyListLor(models.Model):\n\tclass Meta:\n\t\tunique_together = ((\"lor\", \"faculty\"),)\n\n\tlor = models.ForeignKey(Lor, on_delete=models.CASCADE)\n\tfaculty = models.ForeignKey(AppUser, on_delete=models.CASCADE)\n\tcourses_done = JSONField()\n\tprojects_done = JSONField()\n\tthesis_done = JSONField()\n\tstatus = models.BooleanField(editable=True, default=False)\n\tapplication_status = models.CharField(max_length=15,\n\t\t\t\t\t\t\t\t\t\t choices=[('AP', 'Applied'), ('AC', 'Accepted'), ('RE', 'Rejected'), ('CO', 'Completed'), ('EX', 'Expired')],\n\t\t\t\t\t\t\t\t\t\t default='AP')\n\tothers = models.CharField(max_length=500, blank=True)\n\tcreated_at = models.DateTimeField(auto_now_add=True, null=False)\n\tupdated_at = models.DateTimeField(auto_now=True, null=False)\n\tdays_15 = models.BooleanField(editable=True, default=False)\n\tdays_7 = models.BooleanField(editable=True, default=False)\n\tdays_3 = models.BooleanField(editable=True, default=False)\n\tdays_1 = models.BooleanField(editable=True, default=False)\n\n\n","sub_path":"student_lor/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"202035172","text":"#!/usr/local/bin/python -d\n# encoding: utf-8\n\n'''\nName: physicselog.py\nAuthor: Matt Gibbs, based heavily on code by Shawn Alverson (he did all the hard work)\nCreated: 9/13/2016\n\nphysicselog.py provides tools to programatically write to the physics elog.\n'''\nfrom urllib import urlopen, URLError, HTTPError\nfrom xml.etree.ElementTree import Element, SubElement\nfrom xml.etree import ElementTree\nfrom datetime import datetime\nimport json\nimport subprocess\nimport shutil\nimport os\nimport re\nimport sys\n\ndef submit_entry(logbook, username, title, entry_text=None, attachment=None, thumbnail=None):\n\t\"\"\" Submit a new logbook entry. \"\"\"\n\tif logbook not in [\"lcls\", \"facet\"]:\n\t\tsend_to_printer(attachment, \"physics-{name}log\".format(name=logbook))\n\t\treturn\n\tfileName = write_entry_xml(username, title, entry_text, attachment, thumbnail)\n\tif fileName == None:\n\t\traise Exception(\"Could not write XML file.\")\n\tsuccess = send_to_logbook(fileName, logbook)\n\tif not success:\n\t\traise Exception(\"Entry submission failed.\")\n\treturn success\n\ndef write_entry_xml(username, title, text=None, attachment=None, thumbnail=None):\n\t\"\"\"Create xml file for the entry.\"\"\"\n\tcurr_time = datetime.now()\n\t# Set up xml tags\n\tlog_entry = Element(None)\n\tseverity = SubElement(log_entry, 'severity')\n\tlocation = SubElement(log_entry, 'location')\n\tkeywords = SubElement(log_entry, 'keywords')\n\ttime = SubElement(log_entry, 'time')\n\tisodate = SubElement(log_entry, 'isodate')\n\tlog_user = SubElement(log_entry, 'author')\n\tcategory = SubElement(log_entry, 'category')\n\ttitle_tag = SubElement(log_entry, 'title')\n\tmetainfo = SubElement(log_entry, 'metainfo')\n\t\n\ttime_string = curr_time.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\t\n\t# Take care of unchanging tags first\n\tlog_entry.attrib['type'] = \"LOGENTRY\"\n\tcategory.text = \"USERLOG\"\n\tlocation.text = \"not set\"\n\tseverity.text = \"NONE\"\n\tkeywords.text = \"none\"\n\ttime.text = curr_time.strftime(\"%H:%M:%S\")\n\tisodate.text = curr_time.strftime(\"%Y-%m-%d\")\n\tmetainfo.text = time_string + \"-00.xml\"\n\t\n\t# Handle attachment\n\tif attachment is not None:\n\t\tattached_file_tag = SubElement(log_entry, 'link')\n\t\tattached_file_name = time_string + \"-00.ps\"\n\t\ttemp_file = \"/tmp/\" + attached_file_name\n\t\tshutil.copyfile(attachment, temp_file)\n\t\tattached_file_tag.text = attached_file_name\n\t\tif thumbnail is not None:\n\t\t\ttemp_thumbnail_name = time_string + \"-00.png\"\n\t\t\ttemp_thumbnail = \"/tmp/\" + temp_thumbnail_name\n\t\t\tshutil.copyfile(thumbnail, temp_thumbnail)\n\t\t\tthumbnail_tag = SubElement(log_entry, 'file')\n\t\t\tthumbnail_tag.text = temp_thumbnail_name\n\t\telse:\n\t\t\ttemp_thumbnail_name = time_string + \"-00.png\"\n\t\t\ttemp_thumbnail_file = \"/tmp/\" + temp_thumbnail_name\n\t\t\tcommand = \"convert {inp} {out}\".format(inp=attachment, out=temp_thumbnail_file)\n\t\t\tp = subprocess.Popen(command, shell=True)\n\t\t\tp.wait()\n\t\t\tthumbnail_tag = SubElement(log_entry, 'file')\n\t\t\tthumbnail_tag.text = temp_thumbnail_name\n\n\t# For some stupid reason the physics logbook needs the text tag to come last.\n\ttext_tag = SubElement(log_entry, 'text') \n\n\tfileName = \"/tmp/\" + metainfo.text\n\t\n\t# Fill in user inputs\n\tlog_user.text = username\n\ttitle_tag.text = title\n\tif title_tag.text == \"\":\n\t\traise Exception(\"Cannot submit an entry without a title.\")\n\tif text is None or text == \"\":\n\t\ttext = \" \" #Strangely, you can't have a completely blank string or ElementTree leaves off the text tag entirely, which will cause logbook parser to fail.\n\ttext_tag.text = text\n\t\n\t# Create xml file\n\txmlFile = open(fileName,\"w\")\n\trawString = ElementTree.tostring(log_entry, 'utf-8')\n\tparsedString = re.sub(r'(?=<[^/].*>)','\\n',rawString)\n\txmlString = parsedString[1:]\n\txmlFile.write(xmlString)\n\txmlFile.write(\"\\n\") # Close with newline so cron job parses correctly\n\txmlFile.close()\n\t\t\n\treturn fileName.rstrip(\".xml\")\n\ndef send_to_logbook(fileName, location='lcls'):\n\t\"\"\" Copies an xml file into the logbook 'new entry' directory. \"\"\"\n\tpath = os.path.join(\"/u1/\", location, \"physics/logbook/data\")\n\ttry:\n\t\tshutil.copy(fileName + \".png\", path)\n\texcept IOError:\n\t\tprint(\"Copying thumbnail failed!\")\n\ttry:\n\t\tshutil.copy(fileName + \".ps\", path)\n\texcept IOError:\n\t\tprint(\"Copying attachment failed!\")\n\tshutil.copy(fileName + \".xml\", path)\n\treturn True\n\ndef send_to_printer(filename, printer):\n\t\tprint(\"Printing to {}\".format(printer))\n\t\tmakePostScript = \"convert \" + filename + \" \" + filename + \".ps\"\n\t\tos.system(makePostScript)\n\t\tprintFile = \"lpr -P \" + printer + \" \" + filename + \".ps\"\n\t\tos.system(printFile)\n\nif __name__ == '__main__':\n\tlogbook = sys.argv[1]\n\tusername = sys.argv[2]\n\tattachment = sys.argv[3]\n\tthumbnail = attachment\n\ttitle = sys.argv[4]\n\ttry:\n\t\tentry_text = sys.argv[5]\n\texcept:\n\t\tentry_text = None\n\tsubmit_entry(logbook, username, title, entry_text, attachment, thumbnail)\n","sub_path":"utilities/physicselog.py","file_name":"physicselog.py","file_ext":"py","file_size_in_byte":4736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"556632636","text":"import torch.nn as nn\r\nfrom torch import optim\r\n\r\nfrom graphgallery.nn.models import TorchEngine\r\nfrom graphgallery.nn.layers.dgl import DAGNNConv\r\nfrom graphgallery.nn.layers.pytorch import activations\r\nfrom graphgallery.nn.metrics.pytorch import Accuracy\r\n\r\n\r\nclass DAGNN(TorchEngine):\r\n def __init__(self, in_features, out_features, *,\r\n hids=[64], acts=['relu'],\r\n dropout=0.5, weight_decay=5e-4,\r\n lr=0.01, bias=False, K=10):\r\n super().__init__()\r\n\r\n lin = []\r\n for hid, act in zip(hids, acts):\r\n lin.append(nn.Dropout(dropout))\r\n lin.append(nn.Linear(in_features,\r\n hid,\r\n bias=bias))\r\n lin.append(activations.get(act))\r\n in_features = hid\r\n lin.append(nn.Linear(in_features, out_features, bias=bias))\r\n lin.append(activations.get(act))\r\n lin.append(nn.Dropout(dropout))\r\n lin = nn.Sequential(*lin)\r\n self.lin = lin\r\n self.conv = DAGNNConv(out_features, K=K, bias=bias)\r\n self.compile(loss=nn.CrossEntropyLoss(),\r\n optimizer=optim.Adam(self.parameters(),\r\n weight_decay=weight_decay, lr=lr),\r\n metrics=[Accuracy()])\r\n\r\n def reset_parameters(self):\r\n for lin in self.lin:\r\n lin.reset_parameters()\r\n self.conv.reset_parameters()\r\n\r\n def forward(self, x, g):\r\n x = self.lin(x)\r\n return self.conv(g, x)\r\n","sub_path":"graphgallery/nn/models/dgl/dagnn.py","file_name":"dagnn.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"241947782","text":"from django.conf.urls import patterns, include, url\nfrom webapp.views import *\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import *\n\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'^$', 'unibet.views.home', name='home'),\n # url(r'^unibet/', include('unibet.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n \t#url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n\n url(r'^$', HomeView.as_view(), name=\"root\"),\n url(r'^products/$', ProductListView.as_view(), name=\"productlistnoargument\"),\n url(r'^products/(?P\\d+)/$', ProductListView.as_view(), name=\"productlist\"),\n url(r'^products/id/(?P\\d+)/$', ProductView.as_view(), name=\"id\"),\n url(r'^products/kids/$', KidsListView.as_view(), name=\"kidslistnoargument\"),\n url(r'^products/kids/(?P\\d+)/$', KidsListView.as_view(), name=\"kidslist\"),\n)\n","sub_path":"unibet/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"218792707","text":"####\n### Codigo hecho por Adriana Feliza\n###\n\nfrom matplotlib.widgets import Slider, Button #Importar la propiedad de histograma y mostrar, desde la libreria matplotlib\nimport matplotlib.pyplot as plt\nimport numpy #Libreria para matematicas (numeros) en Python\nimport random \n\n\nA = 0.5\nNoA = 1-A\nprob =[A,NoA]\n\n\nfig, ax = plt.subplots()\nplt.subplots_adjust(left=0.15, bottom=0.25)\n\nb1 = ax.bar(0.6, prob[0], facecolor='#9999FF')\nb2 = ax.bar(1.6, prob[1], facecolor='#4846FF')\n\nax.text(1.0, prob[0]+0.05, '%.4f' %prob[0], ha='center', va='bottom')\nax.text(2.0, prob[1]+0.05, '%.4f' %prob[1], ha='center', va='bottom')\n\nlabels = ['Evento A','Evento B']\nax.set_xticks([1, 2], labels)\n\nax.set_title('Probabilidad Posterior')\nax.set_xlabel('Escenarios Posibles')\nax.set_ylabel('Probabilidad')\n\nax.axis([0.0, 3.0, 0.0, 1.5])\n\nax_probA = plt.axes([0.15, 0.1, 0.65, 0.03], axisbg='lightgoldenrodyellow')\ns_prob = Slider(ax_probA, 'Prior(A)', 0.01, 1.0, valinit=A)\n\ndef update(var):\n\tprob[0] = s_prob.val\n\tprob[1] = 1-prob[0]\n\tax.clear()\n\tax.bar(0.6, prob[0], facecolor='#9999FF')\n\tax.bar(1.6, prob[1], facecolor='#4846FF')\n\tax.text(1.0, prob[0]+0.05, '%.4f' %prob[0], ha='center', va='bottom')\n\tax.text(2.0, prob[1]+0.05, '%.4f' %prob[1], ha='center', va='bottom')\n\tax.axis([0.0, 3.0, 0.0, 1.5])\n\tax.set_xticks([1, 2], labels)\n\tax.set_title('Edgar')\n\tax.set_xlabel('Lo que sea')\n\tax.set_ylabel('Hola')\ns_prob.on_changed(update)\n\nplt.show()\n","sub_path":"Lab25/PAPIME_avancesFeli/Bayes - Papime/AdriEdgar_Histogramas_interac.py","file_name":"AdriEdgar_Histogramas_interac.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"623976005","text":"import os\nimport sys\nimport xml.etree.ElementTree as ET\n\n# Singleton Config\nconfig = None\n\ndef get(key):\n if key == None or config == None or config.get(str(key)) == None:\n print(\"Invalid config get request: \" + str(key))\n sys.exit(1)\n \n return config.get(str(key))\n\ndef generate_config(config_path):\n global config\n pbsync_version = \"0.1.13\"\n\n if config_path != None and os.path.isfile(config_path):\n tree = ET.parse(config_path)\n if tree == None:\n return False\n root = tree.getroot()\n if root == None:\n return False\n\n # Read config xml\n try:\n config = {\n 'pbsync_version': pbsync_version,\n 'engine_base_version': root.find('enginebaseversion').text,\n 'supported_git_version': root.find('git/version').text,\n 'supported_lfs_version': root.find('git/lfsversion').text,\n 'expected_branch_name': root.find('git/expectedbranch').text,\n 'git_hooks_path': root.find('git/hooksfoldername').text,\n 'watchman_executable_name': root.find('git/watchmanexecname').text,\n 'lfs_lock_url': root.find('git/lfslockurl').text,\n 'git_url': root.find('git/url').text,\n 'log_file_path': root.find('log/file').text,\n 'max_log_size': int(root.find('log/maximumsize').text),\n 'ddc_version_path': root.find('ddc/versionfilepath').text,\n 'ddc_version': int(root.find('ddc/version').text),\n 'ddc_expected_min_size': int(root.find('ddc/expectedminsize').text),\n 'uproject_path': root.find('project/uprojectname').text,\n 'uproject_version_key': root.find('project/uprojectversionkey').text,\n 'engine_version_prefix': root.find('project/engineversionprefix').text,\n 'defaultgame_path': root.find('project/defaultgameinipath').text,\n 'defaultgame_version_key': root.find('project/projectversionkey').text,\n 'versionator_config_path': root.find('project/versionatorconfigpath').text,\n 'error_file': root.find('project/errorfile'),\n 'pbget_url': root.find('pbget/url').text,\n 'dispatch_executable': root.find('dispatch/executable').text,\n 'dispatch_config': root.find('dispatch/config').text,\n 'dispatch_drm': root.find('dispatch/drm').text,\n 'dispatch_stagedir': root.find('dispatch/stagedir').text\n }\n except:\n return False\n\n return True\n \n return False","sub_path":"PBConfig.py","file_name":"PBConfig.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"273294637","text":"#Luana Nogueira da Silva\n#N1 Linguagem de Programação Parte 2\n\ndef reference(name):\n renamed = name[-1] + ', ' #pega o ultimo nome e concatena com ', '\n for i in range(len(name) - 1):\n name2 = name[i]\n if name2 not in ['DA', 'DE', 'DO', 'DAS', 'DOS']: #validação para remoção de conectivos\n renamed += name2[0] + \". \" #concatena com as iniciais\n i += 1\n return renamed\n\n\nname = input(\"Digite o nome a ser convertido:\").upper().split()\n\nreferencia = reference(name)\nprint(referencia)\n","sub_path":"NomeABNT.py","file_name":"NomeABNT.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"550295232","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nimport collections\r\nimport copy\r\n\r\n'''\r\n数据结构定义\r\n'''\r\nclass Cars:\r\n # def __init__(self, car_id, from_id, to_id, road_id, speed, departure_time, state, dist, next_road, dir, state, plan):\r\n def __init__(self, car_id, from_id, to_id, speed, planTime, plan, priority, preset):\r\n self.id = car_id\r\n self.start = from_id\r\n self.end = to_id\r\n # self.road_id = road_id # 当前所处道路\r\n self.speed = speed\r\n self.planTime = planTime \r\n # self.dist = dist # 与路口的距离\r\n # self.dir = dir # 到达路口后的方向\r\n # self.state = state # 当前车辆状态\r\n self.plan = plan\r\n self.priority = priority\r\n self.preset = preset\r\n # 当前车辆的规划路径,dict类型,存储第i时刻所处的道路id,同时表示当前车辆的规划路径。 \r\n # (补充:如果死锁,plan将一直增加)\r\n\r\nclass Road:\r\n '''\r\n lanes:车道数量\r\n isDuplex:是否双向(bool类型)\r\n '''\r\n # def __init__(self, road_id, length, speed_limit, lanes, start_point, end_point, isDuplex, forward_congestion, reverse_congestion):\r\n def __init__(self, road_id, length, speed_limit, lanes, start_point, end_point, isDuplex):\r\n self.id = road_id\r\n self.length = length\r\n self.speed = speed_limit\r\n self.lanes = lanes\r\n self.start = start_point\r\n self.end = end_point\r\n self.isDuplex = isDuplex\r\n # self.fcong = forward_congestion\r\n # self.rcong = reverse_congestion\r\n # fcong(rcong):t时间道路拥塞情况,dict类型:rcong[t]=i, i为t时刻道路上的行驶车辆数\r\n\r\nclass Cross:\r\n '''\r\n 题目里顺时针记录路口的道路,值为-1则表示丁字路口\r\n '''\r\n def __init__(self, cross_id, up, right, down, left, value):\r\n self.cross_id = cross_id\r\n self.up = up\r\n self.right = right\r\n self.down = down\r\n self.left = left\r\n # self.wait = wait # t时间步路口等待车辆数(只考虑转弯的情况?)dict类型\r\n self.value = value # cross.value 路口的拥挤程度\r\n\r\nclass Graph:\r\n def __init__(self, roads, crosses):\r\n '''\r\n adj:[cross_i] = [cross_j, road_k] 存储路口i到路口j的道路k实例\r\n 道路正/反向表示\r\n '''\r\n self.adj = collections.defaultdict(list)\r\n self.road_list = dict()\r\n self.cross_list = dict()\r\n self.cross_value = dict()\r\n self.road_value = collections.defaultdict(np.array) # 方便后面利用广播机制\r\n self.cross_neibor = collections.defaultdict(np.array)\r\n self.road_value_t = collections.defaultdict(list)\r\n self.cross_value_t = collections.defaultdict(list)\r\n self.road_value_copy = collections.defaultdict(np.array)\r\n self.cross_value_copy = collections.defaultdict(np.array)\r\n # road拥挤度量 \r\n for index, road in roads.iterrows():\r\n self.road_list[road['id']] = Road(road['id'], road['length'], road['speed'],\\\r\n road['channel'], road['from'], road['to'], road['isDuplex'])\r\n # congestion = Congestion(road['id'], 0, 0)\r\n if road['isDuplex'] == 1:\r\n self.adj[road['to']].append((road['from'], self.road_list[road['id']]))\r\n # self.dist[road['to']].append((road['from'], road['length']))\r\n self.adj[road['from']].append((road['to'], self.road_list[road['id']]))\r\n self.road_value[road['id']] = np.array([0., 0.]) # append进去的向量[i, j]代表当前时刻i道路上正向和反向的车辆数 float方便后面广播\r\n # self.road_value_copy[road['id']] = np.array([0, 0])\r\n # road_value时间片初始化\r\n self.road_value_t[1].append(self.road_value)\r\n\r\n # cross拥挤度量\r\n for index, cross in crosses.iterrows():\r\n cross_road = []\r\n cross_nb = []\r\n # road_cong = 0\r\n for i in cross[1:]:\r\n if i == -1:\r\n cross_road.append(-1)\r\n continue\r\n else:\r\n cross_road.append(self.road_list[i])\r\n # 邻居cross\r\n if self.road_list[i].start == cross['id']:\r\n cross_nb.append(self.road_list[i].end)\r\n else:\r\n cross_nb.append(self.road_list[i].start)\r\n self.cross_list[cross['id']] = cross_road # 存放路口处道路的实例\r\n self.cross_value[cross['id']] = 0. # 初始化cross_value\r\n self.cross_neibor[cross['id']] = cross_nb\r\n # self.cross_value_copy[cross['id']] = 0\r\n # cross_value时间片初始化\r\n self.cross_value_t[1].append(self.cross_value)","sub_path":"复赛/CodeCraft-python(图2 2948 时空信息结合)/CodeCraft-2019/src/Class.py","file_name":"Class.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173354708","text":"import os\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets,transforms,models\nfrom collections import OrderedDict\nfrom PIL import Image\nimport numpy as np\nimport seaborn as sns\nfrom torch.autograd import Variable\n\n\ndef main():\n \n args = get_args()\n model = load_checkpoint(args.checkpoint)\n model.to(args.gpu)\n cat_to_name = load_category_list(args.category_names)\n plot_solution(cat_to_name,args.input_image, model,args.top_k)\n\ndef get_args():\n import argparse\n parser = argparse.ArgumentParser()\n \n parser.add_argument('input_image',type = str , help = 'image path')\n parser.add_argument('checkpoint',type = str , help = 'checkpoint path')\n parser.add_argument('--top_k',type = int , default = 5 , help = 'the number of top_k')\n parser.add_argument('--category_names' , type = str , default = '/home/workspace/aipnd-project/cat_to_name.json' \n ,help = 'category list path ')\n parser.add_argument('--gpu', type = str , default = 'cuda',help = 'Use GPU or CPU ')\n \n return parser.parse_args()\n\ndef load_checkpoint(checkpoint):\n check_p =torch.load(checkpoint)\n hidden_size = check_p['hidden_size']\n if check_p['arch'] == 'vgg16':\n model = models.vgg16(pretrained = True)\n for param in model.parameters():\n param.requires_grad = False\n if len(hidden_size) > 1:\n h1 , h2 = hidden_size[0],hidden_size[1]\n classifier = nn.Sequential(OrderedDict([('fc1',nn.Linear(25088,h1)),\n ('relu1',nn.ReLU()),\n ('fc2',nn.Linear(h1,h2)),\n ('relu2',nn.ReLU()),\n ('fc3',nn.Linear(h2,102)),\n ('output',nn.LogSoftmax(dim = 1))]))\n else : \n h1 = hidden_size\n classifier = nn.Sequential(OrderedDict([('fc1',nn.Linear(25088,h1)),\n ('relu1',nn.ReLU()),\n ('fc2',nn.Linear(h1,102)),\n ('output',nn.LogSoftmax(dim = 1))])) \n \n elif check_p['arch'] == 'densenet121':\n model = models.densenet121(pretrained = True)\n for param in model.parameters():\n param.requires_grad = False \n if len(hidden_size) > 1:\n h1 , h2 = hidden_size[0],hidden_size[1]\n classifier = nn.Sequential(OrderedDict([('fc1',nn.Linear(1024,h1)),\n ('relu1',nn.ReLU()),\n ('fc2',nn.Linear(h1,h2)),\n ('relu2',nn.ReLU()),\n ('fc3',nn.Linear(h2,102)),\n ('output',nn.LogSoftmax(dim = 1))]))\n else : \n h1 = hidden_size\n classifier = nn.Sequential(OrderedDict([('fc1',nn.Linear(1024,h1)),\n ('relu1',nn.ReLU()),\n ('fc2',nn.Linear(h1,102)),\n ('output',nn.LogSoftmax(dim = 1))]))\n \n else :\n print(\"it's a undefined architecture\")\n \n \n \n model.classifier = classifier\n model.load_state_dict(check_p['state_dict'])\n model.class_to_idx = check_p['class_to_idx']\n return model\n \n \n\ndef load_category_list(category_names):\n import json\n with open(category_names,'r') as f:\n cat_to_name = json.load(f)\n return cat_to_name\n\ndef process_image(image):\n \n image_path = image\n img = Image.open(image)\n if img.size[0] > img.size[1]:\n img.thumbnail((10000, 256))\n else:\n img.thumbnail((256, 10000))\n \n left_margin = (img.width-224)/2\n bottom_margin = (img.height-224)/2\n right_margin = left_margin + 224\n top_margin = bottom_margin + 224\n img = img.crop((left_margin, bottom_margin, right_margin, \n top_margin))\n \n img = np.array(img)/255\n mean = np.array([0.485, 0.456, 0.406]) \n std = np.array([0.229, 0.224, 0.225]) \n img = (img - mean)/std\n \n # Move color channels to first dimension as expected by PyTorch\n img = img.transpose((2, 0, 1))\n \n return img\n\n\ndef imshow(image, ax=None, title=None):\n if ax is None:\n fig, ax = plt.subplots()\n \n # PyTorch tensors assume the color channel is the first dimension\n # but matplotlib assumes is the third dimension\n image = image.transpose((1, 2, 0))\n \n # Undo preprocessing\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = std * image + mean\n \n # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n image = np.clip(image, 0, 1)\n \n ax.imshow(image)\n \n return ax\n\n\ndef predict(name_list,image_path, model, topk):\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n model.to(device)\n img = process_image(image_path)\n image_tensor = torch.from_numpy(img).type(torch.FloatTensor)\n model_input = image_tensor.unsqueeze(0)\n output = model.forward(model_input)\n probs = torch.exp(output)\n #model.to('cuda')\n top_probs, top_labs = probs.topk(topk)\n #top_probs , top_labs = top_probs.to('cpu') , top_labs.to('cpu')\n top_probs = top_probs.detach().numpy().tolist()[0] \n top_labs = top_labs.detach().numpy().tolist()[0]\n \n \n idx_to_class = {val: key for key, val in model.class_to_idx.items()}\n top_labels = [idx_to_class[lab] for lab in top_labs]\n top_flowers = [name_list[idx_to_class[lab]] for lab in top_labs]\n return top_probs, top_labels,top_flowers\n\n\ndef plot_solution(name_list,image_path, model,topk):\n \n image_path = str(image_path)\n flower_num = (image_path.split('/'))[-2]\n \n img = process_image(image_path)\n\n probs, labs,flowers= predict(name_list,image_path, model,topk)\n for prob, flower_name in zip(probs, flowers):\n print('%20s : %.4f' % (flower_name, prob))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"terminal/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":6382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"647171197","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.optim as optim\nN, D_in, H, D_out = 64, 1000, 100, 10\n\nx = Variable(torch.randn(N, D_in))\ny = Variable(torch.randn(N, D_out))\n\ntwoLayerNet = nn.Sequential(nn.Linear(D_in, H), nn.ReLU(), nn.Linear(H, D_out))\nloss_fn = nn.MSELoss(size_average=False)\nlr = 1e-4\noptimizer = optim.Adam(twoLayerNet.parameters(), lr)\nfor t in range(500):\n y_pre = twoLayerNet(x)\n loss = loss_fn(y_pre, y)\n print(t, loss.data[0])\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\ndummy = 0\n\n\n\n\n","sub_path":"nn/two_layer_net_optim_exercise.py","file_name":"two_layer_net_optim_exercise.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"526634677","text":"import bson\n\nfrom kombu.mixins import ConsumerMixin\nfrom kombu.log import get_logger\nfrom kombu.utils.functional import reprcall\n\nfrom .tasks import app\nfrom .mqtt_queues import connect_queue\n\nlogger = get_logger(__name__)\n\n\nclass Worker(ConsumerMixin):\n\n def __init__(self, connection):\n self.connection = connection\n\n def get_consumers(self, Consumer, channel):\n return [Consumer(queues=connect_queue,\n on_message = self.handle_message)]\n\n def handle_message(self, msg):\n app.do(msg, \"connect\")\n msg.ack()\n\ndef monitor():\n from kombu import Connection\n from kombu.utils.debug import setup_logging\n # setup root logger\n setup_logging(loglevel='INFO', loggers=[''])\n\n with Connection('amqp://guest:guest@localhost:5672//') as conn:\n try:\n worker = Worker(conn)\n worker.run()\n except KeyboardInterrupt:\n print('bye bye')\n\nif __name__ == '__main__':\n monitor()\n\n","sub_path":"apps/mq/connect_monitor.py","file_name":"connect_monitor.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"411869518","text":"import asyncio\n\nfrom copy import copy\nimport sys\n\nimport requests\nimport aiohttp\nfrom bs4 import BeautifulSoup\n\nfrom birthdays import BIRTHDAYS\n\nENDPOINT = \"https://livingat.wsu.edu/cardinfo/deposit/default.aspx?mode=CC\"\n\n\nclass Student:\n def __init__(self, wsu_id, name, birthday):\n self.wsu_id = wsu_id\n self.name = name\n self.birthday = birthday\n\n def __str__(self):\n return f\"{self.wsu_id} -> {self.name} {self.birthday}\"\n\n\ndef get_inputs():\n \"\"\"\n # Get hidden inputs to create a valid POST request later\n \"\"\"\n text = requests.get(ENDPOINT).text\n bs = BeautifulSoup(text, 'html.parser')\n\n view_state = bs.find(id=\"__VIEWSTATE\").get('value')\n event_val = bs.find(id=\"__EVENTVALIDATION\").get('value') # Is this a CSRF?\n\n # Hidden fields\n params = {\n \"__EVENTTARGET\": \"ctl00$mainContent$btnContinue\",\n \"__VIEWSTATE\": view_state,\n \"__EVENTVALIDATION\": event_val,\n }\n\n return params\n\n\nasync def check_birthday(form_data, wsu_id, birthday):\n form_data.update({\n \"ctl00$mainContent$txtWSUID\": wsu_id,\n \"ctl00$mainContent$DropDownListMonth\": birthday.month,\n \"ctl00$mainContent$DropDownListDay\": birthday.day,\n })\n\n async with aiohttp.ClientSession() as session:\n async with session.post(ENDPOINT, data=form_data) as response:\n text = await response.text()\n\n if \"Birthday is incorrect\" in text:\n # Give up on this task\n await asyncio.sleep(float('inf'))\n else:\n # We hit the jackpot\n bs = BeautifulSoup(text, 'html.parser')\n name = bs.find(id=\"ctl00_mainContent_lblName\").text.lstrip(\" - \")\n\n student = Student(wsu_id, name, birthday)\n print(student)\n\n return\n\n\nasync def lookup_wsu_id(wsu_id):\n form_data = get_inputs() # Get hidden fields from page with GET\n\n checks = [\n check_birthday(copy(form_data), wsu_id, birthday)\n for birthday in BIRTHDAYS\n ]\n await asyncio.wait(checks, return_when=asyncio.FIRST_COMPLETED)\n\n\ndef main():\n sys.argv.append('11525552')\n\n for wsu_id in sys.argv[1:]:\n print(f\"Looking up {wsu_id}\")\n asyncio.run(lookup_wsu_id(wsu_id))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"wsu_finder.py","file_name":"wsu_finder.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"251714281","text":"import Universe\r\nimport wx\r\nimport copy\r\n\r\n########################################################################################\r\n#\"Picker\" classes\r\n########################################################################################\r\n\r\nclass DestinationPicker(wx.Dialog):\r\n #fields\r\n universe = []\r\n destination1 = 0\r\n destination2 = 0\r\n\r\n def __init__(self, parent, id, universe, destination1, destination2):\r\n\r\n wx.Dialog.__init__(self, parent, id)\r\n self.SetTitle(\"Destination Picker\")\r\n\r\n self.universe = universe\r\n\r\n self.lblDestination1 = wx.StaticText(self, -1, \"Starting location\")\r\n self.lblDestination2 = wx.StaticText(self, -1, \"Final location\")\r\n self.Destination1Picker = wx.ListBox(self, -1, choices=self.universe.destination_menu, size=(300,-1), style=wx.LB_SINGLE)\r\n self.Destination2Picker = wx.ListBox(self, -1, choices=self.universe.destination_menu, size=(300,-1), style=wx.LB_SINGLE)\r\n\r\n self.btnOK = wx.Button(self, -1, \"OK\")\r\n self.btnCancel = wx.Button(self, -1, \"Cancel\")\r\n\r\n maingrid = wx.FlexGridSizer(2, 2, 5, 5)\r\n \r\n maingrid.AddMany([self.lblDestination1, self.lblDestination2,\r\n self.Destination1Picker, self.Destination2Picker,\r\n self.btnOK, self.btnCancel])\r\n\r\n self.SetSizerAndFit(maingrid)\r\n\r\n if destination1 == -1:\r\n destination1 = 0\r\n if destination2 == -1:\r\n destination2 = 0\r\n\r\n self.destination1 = destination1\r\n self.destination2 = destination2\r\n self.Destination1Picker.SetSelection(destination1)\r\n self.Destination2Picker.SetSelection(destination2)\r\n\r\n font = self.GetFont()\r\n font.SetWeight(wx.FONTWEIGHT_BOLD)\r\n self.lblDestination1.SetFont(font)\r\n self.lblDestination2.SetFont(font)\r\n\r\n self.btnOK.Bind(wx.EVT_BUTTON, self.ClickOK)\r\n self.btnCancel.Bind(wx.EVT_BUTTON, self.ClickCancel)\r\n\r\n def ClickOK(self, e):\r\n self.destination1 = self.Destination1Picker.GetSelection()\r\n self.destination2 = self.Destination2Picker.GetSelection()\r\n \r\n if self.destination1 == 0:\r\n self.destination1 = -1\r\n if self.destination2 == 0:\r\n self.destination2 = -1\r\n\r\n self.Close()\r\n\r\n def ClickCancel(self, e):\r\n if self.destination1 == 0:\r\n self.destination1 = -1\r\n if self.destination2 == 0:\r\n self.destination2 = -1\r\n\r\n self.Close()\r\n\r\n\r\nclass SequencePicker(wx.Dialog):\r\n #fields\r\n universe = []\r\n missionoptions = []\r\n ActiveJourney = []\r\n ActiveSequence = []\r\n ActivePhase = []\r\n ListOfSequences = []\r\n CurrentSequence = []\r\n SaveOldSequence = []\r\n\r\n def __init__(self, parent, id, universe, missionoptions, ActiveJourney):\r\n\r\n wx.Dialog.__init__(self, parent, id)\r\n\r\n self.SetSize((800,500))\r\n self.SetTitle(\"Flyby Picker\")\r\n\r\n self.universe = universe\r\n\r\n self.lblAvailableBodies = wx.StaticText(self, -1, \"Available flyby bodies\")\r\n self.lblChooseSequence = wx.StaticText(self, -1, \"Select a sequence\")\r\n self.lblCurrentSequence = wx.StaticText(self, -1, \"Current sequence\")\r\n font = self.GetFont()\r\n font.SetWeight(wx.FONTWEIGHT_BOLD)\r\n self.lblAvailableBodies.SetFont(font)\r\n self.lblChooseSequence.SetFont(font)\r\n self.lblCurrentSequence.SetFont(font)\r\n\r\n self.universe = universe\r\n self.missionoptions = missionoptions\r\n self.ActiveJourney = ActiveJourney\r\n self.ActiveSequence = 0\r\n self.ActivePhase = 0\r\n self.SaveOldSequence = copy.deepcopy(self.missionoptions.Journeys[self.ActiveJourney].sequence)\r\n \r\n self.AvailableBodiesPicker = wx.ListBox(self, -1, choices=self.universe.flyby_menu, size=(300,-1), style=wx.LB_SINGLE)\r\n \r\n self.UpdateLists()\r\n\r\n self.SequencePicker = wx.ListBox(self, -1, choices=self.ListOfSequences, size=(500,-1), style=wx.LB_SINGLE)\r\n\r\n self.CurrentSequencePicker = wx.ListBox(self, -1, choices=self.CurrentSequence, size=(500,300), style=wx.LB_SINGLE)\r\n\r\n self.btnAddNewTrialSequence = wx.Button(self, -1, \"Add new trial sequence\")\r\n self.btnRemoveTrialSequence = wx.Button(self, -1, \"Remove trial sequence\", size=self.btnAddNewTrialSequence.GetSize())\r\n self.btnAddFlyby = wx.Button(self, -1, \"Add flyby\", size=self.btnAddNewTrialSequence.GetSize())\r\n self.btnRemoveFlyby = wx.Button(self, -1, \"Remove flyby\", size=self.btnAddNewTrialSequence.GetSize())\r\n self.btnMoveFlybyUp = wx.Button(self, -1, \"Move flyby up\", size=self.btnAddNewTrialSequence.GetSize())\r\n self.btnMoveFlybyDown = wx.Button(self, -1, \"Move flyby down\", size=self.btnAddNewTrialSequence.GetSize())\r\n buttongrid = wx.GridSizer(6,1,0,0)\r\n buttongrid.AddMany([self.btnAddNewTrialSequence, self.btnRemoveTrialSequence, self.btnAddFlyby, self.btnRemoveFlyby, self.btnMoveFlybyUp, self.btnMoveFlybyDown])\r\n\r\n selectorstacker = wx.BoxSizer(wx.VERTICAL)\r\n selectorstacker.AddMany([self.lblChooseSequence, self.SequencePicker, self.lblCurrentSequence, self.CurrentSequencePicker])\r\n\r\n availablebodiesstacker = wx.BoxSizer(wx.VERTICAL)\r\n availablebodiesstacker.AddMany([self.lblAvailableBodies, self.AvailableBodiesPicker])\r\n\r\n pickerbox = wx.BoxSizer(wx.HORIZONTAL)\r\n pickerbox.AddMany([availablebodiesstacker, buttongrid, selectorstacker])\r\n\r\n self.btnOK = wx.Button(self, -1, \"OK\")\r\n self.btnCancel = wx.Button(self, -1, \"Cancel\")\r\n\r\n bottombox = wx.BoxSizer(wx.HORIZONTAL)\r\n bottombox.AddMany([self.btnOK, self.btnCancel])\r\n\r\n mainbox = wx.BoxSizer(wx.VERTICAL)\r\n \r\n mainbox.AddMany([pickerbox, bottombox])\r\n\r\n self.btnOK.Bind(wx.EVT_BUTTON, self.ClickOK)\r\n self.btnCancel.Bind(wx.EVT_BUTTON, self.ClickCancel)\r\n self.btnAddNewTrialSequence.Bind(wx.EVT_BUTTON, self.ClickAddNewTrialSequence)\r\n self.btnRemoveTrialSequence.Bind(wx.EVT_BUTTON, self.ClickRemoveTrialSequence)\r\n self.btnAddFlyby.Bind(wx.EVT_BUTTON, self.ClickAddFlyby)\r\n self.btnRemoveFlyby.Bind(wx.EVT_BUTTON, self.ClickRemoveFlyby)\r\n self.btnMoveFlybyUp.Bind(wx.EVT_BUTTON, self.ClickMoveFlybyUp)\r\n self.btnMoveFlybyDown.Bind(wx.EVT_BUTTON, self.ClickMoveFlybyDown)\r\n self.SequencePicker.Bind(wx.EVT_LISTBOX, self.PickDifferentSequence)\r\n\r\n self.AvailableBodiesPicker.SetSelection(0)\r\n self.SequencePicker.SetSelection(self.ActiveSequence)\r\n if len(self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence]) > 0:\r\n self.CurrentSequencePicker.SetSelection(self.ActivePhase)\r\n self.SetSizerAndFit(mainbox)\r\n\r\n def UpdateLists(self):\r\n self.ListOfSequences = []\r\n self.CurrentSequence = []\r\n\r\n for seq in range(0, len(self.missionoptions.Journeys[self.ActiveJourney].sequence)):\r\n ThisSequence = []\r\n while 0 in self.missionoptions.Journeys[self.ActiveJourney].sequence[seq]:\r\n self.missionoptions.Journeys[self.ActiveJourney].sequence[seq].remove(0)\r\n for b in self.missionoptions.Journeys[self.ActiveJourney].sequence[seq]:\r\n if b > 0:\r\n ThisSequence.append(self.universe.flyby_menu[b-1])\r\n if ThisSequence == []:\r\n self.ListOfSequences.append(\"No flybys\")\r\n else:\r\n self.ListOfSequences.append(str(ThisSequence))\r\n \r\n if len(self.missionoptions.Journeys[self.ActiveJourney].sequence) > 0:\r\n for b in self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence]:\r\n if b > 0:\r\n self.CurrentSequence.append(self.universe.flyby_menu[b-1])\r\n\r\n def UpdateListBoxes(self):\r\n self.SequencePicker.SetItems(self.ListOfSequences)\r\n self.CurrentSequencePicker.SetItems(self.CurrentSequence)\r\n\r\n self.SequencePicker.SetSelection(self.ActiveSequence)\r\n\r\n def ClickOK(self, e):\r\n #save current information\r\n\r\n #first we need to increate max_phases_per_journey to match the longest sequence\r\n for seq in range(0, len(self.missionoptions.Journeys[self.ActiveJourney].sequence)):\r\n if self.missionoptions.max_phases_per_journey < len(self.missionoptions.Journeys[self.ActiveJourney].sequence[seq]):\r\n self.missionoptions.max_phases_per_journey = len(self.missionoptions.Journeys[self.ActiveJourney].sequence[seq])\r\n\r\n #then we need to pad all \"short\" sequences in all journeys with trailing zeros\r\n for j in range(0, self.missionoptions.number_of_journeys):\r\n for seq in range(0, len(self.missionoptions.Journeys[j].sequence)):\r\n while len(self.missionoptions.Journeys[j].sequence[seq]) < self.missionoptions.max_phases_per_journey:\r\n self.missionoptions.Journeys[j].sequence[seq].append(0)\r\n\r\n #the number of trial sequences for the mission must equal the number of trial sequences entered here\r\n #similarly we must add or remove trial decision vectors\r\n #if this journey has too many trial sequences, add additional sequences to the other journeys\r\n if len(self.missionoptions.Journeys[self.ActiveJourney].sequence) > self.missionoptions.number_of_trial_sequences:\r\n #sequences\r\n self.missionoptions.number_of_trial_sequences = len(self.missionoptions.Journeys[self.ActiveJourney].sequence)\r\n for j in range(0, self.missionoptions.number_of_journeys):\r\n if j != self.ActiveJourney:\r\n while len(self.missionoptions.Journeys[j].sequence) < self.missionoptions.number_of_trial_sequences:\r\n self.missionoptions.Journeys[j].sequence.append([0]*self.missionoptions.max_phases_per_journey)\r\n\r\n #trial decision vectors\r\n while len(self.missionoptions.trialX) < self.missionoptions.number_of_trial_sequences:\r\n self.missionoptions.trialX.append([0.0])\r\n while len(self.missionoptions.trialX) > self.missionoptions.number_of_trial_sequences:\r\n self.missionoptions.trialX.pop()\r\n\r\n #if this journey has fewer sequences than the others, truncate the sequence lists of the other journeys\r\n elif len(self.missionoptions.Journeys[self.ActiveJourney].sequence) < self.missionoptions.number_of_trial_sequences:\r\n #sequences\r\n self.missionoptions.number_of_trial_sequences = len(self.missionoptions.Journeys[self.ActiveJourney].sequence)\r\n for j in range(0, self.missionoptions.number_of_journeys):\r\n if j != self.ActiveJourney:\r\n while len(self.missionoptions.Journeys[j].sequence) > self.missionoptions.number_of_trial_sequences:\r\n self.missionoptions.Journeys[j].sequence.pop()\r\n\r\n #trial decision vectors\r\n while len(self.missionoptions.trialX) < self.missionoptions.number_of_trial_sequences:\r\n self.missionoptions.trialX.append([0.0])\r\n while len(self.missionoptions.trialX) > self.missionoptions.number_of_trial_sequences:\r\n self.missionoptions.trialX.pop()\r\n\r\n self.Close()\r\n\r\n def ClickCancel(self, e):\r\n #restore old information\r\n self.missionoptions.Journeys[self.ActiveJourney].sequence = copy.deepcopy(self.SaveOldSequence)\r\n self.Close()\r\n\r\n def ClickAddNewTrialSequence(self, e):\r\n self.missionoptions.Journeys[self.ActiveJourney].sequence.append([0]*self.missionoptions.max_phases_per_journey)\r\n self.UpdateLists()\r\n self.UpdateListBoxes()\r\n self.ActiveSequence = len(self.missionoptions.Journeys[self.ActiveJourney].sequence) - 1\r\n\r\n def ClickRemoveTrialSequence(self, e):\r\n if len(self.missionoptions.Journeys[self.ActiveJourney].sequence) > 1:\r\n self.ActiveSequence = self.SequencePicker.GetSelection()\r\n self.missionoptions.Journeys[self.ActiveJourney].sequence.pop(self.ActiveSequence)\r\n\r\n if self.ActiveSequence > len(self.missionoptions.Journeys[self.ActiveJourney].sequence) - 1:\r\n self.ActiveSequence -= 1\r\n\r\n self.UpdateLists()\r\n self.UpdateListBoxes()\r\n\r\n self.SequencePicker.SetSelection(self.ActiveSequence)\r\n\r\n def PickDifferentSequence(self, e):\r\n self.ActiveSequence = self.SequencePicker.GetSelection()\r\n self.UpdateLists()\r\n self.UpdateListBoxes()\r\n self.ActivePhase = 0\r\n if len(self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence]) > 0:\r\n self.CurrentSequencePicker.SetSelection(self.ActivePhase)\r\n\r\n def ClickAddFlyby(self, e):\r\n BodyChoice = self.AvailableBodiesPicker.GetSelection() + 1\r\n if BodyChoice == 0:\r\n BodyChoice = 1\r\n\r\n self.ActiveSequence = self.SequencePicker.GetSelection()\r\n self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence].append(BodyChoice)\r\n\r\n self.UpdateLists()\r\n self.UpdateListBoxes()\r\n\r\n def ClickRemoveFlyby(self, e):\r\n self.ActivePhase = self.CurrentSequencePicker.GetSelection()\r\n self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence].pop(self.ActivePhase)\r\n self.UpdateLists()\r\n self.UpdateListBoxes()\r\n\r\n def ClickMoveFlybyUp(self, e):\r\n self.ActivePhase = self.CurrentSequencePicker.GetSelection()\r\n self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence][self.ActivePhase], self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence][self.ActivePhase - 1] = self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence][self.ActivePhase - 1], self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence][self.ActivePhase]\r\n\r\n if self.ActivePhase > 0:\r\n self.missionoptions.Journeys[self.missionoptions.ActiveJourney], self.missionoptions.Journeys[self.missionoptions.ActiveJourney-1] = self.missionoptions.Journeys[self.missionoptions.ActiveJourney-1], self.missionoptions.Journeys[self.missionoptions.ActiveJourney]\r\n self.ActivePhase = 1\r\n \r\n self.UpdateLists()\r\n self.UpdateListBoxes()\r\n self.CurrentSequencePicker.SetSelection(self.ActivePhase)\r\n\r\n def ClickMoveFlybyDown(self, e):\r\n self.ActivePhase = self.CurrentSequencePicker.GetSelection()\r\n\r\n if self.ActivePhase < len(self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence]):\r\n self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence][self.ActivePhase], self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence][self.ActivePhase + 1] = self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence][self.ActivePhase + 1], self.missionoptions.Journeys[self.ActiveJourney].sequence[self.ActiveSequence][self.ActivePhase]\r\n self.ActivePhase += 1\r\n\r\n self.UpdateLists()\r\n self.UpdateListBoxes()\r\n self.CurrentSequencePicker.SetSelection(self.ActivePhase)","sub_path":"branch/EMTG_student/PyEMTG/BodyPicker.py","file_name":"BodyPicker.py","file_ext":"py","file_size_in_byte":15373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"343190454","text":"'''\n#### Name: Construct BST from preorder traversal\nLink: [link]()\n\n#### Sub_question_name: Optimal Iterative \nLink: [link]()\n\n'''\n\n\n\ndef create_bst(values):\n \n stack = []\n root = Node(values[0])\n stack.append(root)\n\n curr = root\n for v in values[1:]:\n temp = None\n\n while len(stack) > 0 and v > stack[-1].val: # find the place to place right val\n temp = stack.pop()\n\n if temp: # Found a place\n temp.right = Node(v)\n stack.append(temp.right)\n\n else: # Didn't find the place\n temp = stack[-1]\n temp.left = Node(v)\n stack.append(temp.left)\n \n return root\n\n \n\n\n## Driver\nclass Node:\n def __init__(self, data):\n self.val = data\n self.left = None\n self.right = None\n\n\ndef show(root):\n if root == None:\n return\n show(root.left)\n print(root.val, end=\" \")\n show(root.right)\n\n\n# 10\n# / \\\n# 5 40\n# / \\ \\\n# 1 7 50\npo = [10, 5, 1, 7, 40, 50]\nr = create_bst(po)\nshow(r)\n","sub_path":"Data/BST/Construct BST from preorder traversal/Optimal Iterative.py","file_name":"Optimal Iterative.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"160594978","text":"############################################################\n# -*- coding: utf-8 -*-\n#\n# # # # # # #\n# ## ## # ## # #\n# # # # # # # # # # #\n# # ## # ## ## ######\n# # # # # # #\n#\n# Python-based Tool for interaction with the 10micron mounts\n# GUI with PyQT5 for python\n#\n# written in python3, (c) 2019-2021 by mworion\n#\n# Licence APL2.0\n#\n###########################################################\n# standard libraries\nimport unittest.mock as mock\nimport pytest\n# external packages\nfrom PyQt5.QtCore import QObject\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtCore import QThreadPool\nfrom PyQt5.QtCore import pyqtSignal\nfrom gui.mainWmixin.tabSettRelay import SettRelay\n\n# local import\nfrom logic.powerswitch.kmRelay import KMRelay\nfrom gui.widgets.main_ui import Ui_MainWindow\nfrom gui.utilities.toolsQtWidget import MWidget\n\n\n@pytest.fixture(autouse=True, scope='function')\ndef module_setup_teardown(qtbot):\n global ui, widget, Test, app\n\n class Test(QObject):\n config = {'mainW': {}}\n threadPool = QThreadPool()\n update1s = pyqtSignal()\n message = pyqtSignal(str, int)\n relay = KMRelay()\n\n widget = QWidget()\n ui = Ui_MainWindow()\n ui.setupUi(widget)\n\n app = SettRelay(app=Test(), ui=ui,\n clickable=MWidget().clickable)\n\n app.changeStyleDynamic = MWidget().changeStyleDynamic\n app.close = MWidget().close\n\n app.deleteLater = MWidget().deleteLater\n qtbot.addWidget(app)\n\n yield\n\n\ndef test_initConfig_1():\n app.app.config['mainW'] = {}\n suc = app.initConfig()\n assert suc\n\n\ndef test_storeConfig_1():\n app.ui.relayDevice.setCurrentIndex(0)\n app.storeConfig()\n\n\ndef test_setupRelayGui(qtbot):\n assert 8 == len(app.relayDropDowns)\n assert 8 == len(app.relayButtonTexts)\n assert 8 == len(app.relayButtons)\n for dropDown in app.relayDropDowns:\n val = dropDown.count()\n assert 2 == val\n\n\ndef test_toggleRelay_1(qtbot):\n def Sender():\n return ui.relayButton0\n app.sender = Sender\n\n app.ui.relayDevice.setCurrentIndex(0)\n with qtbot.waitSignal(app.app.message) as blocker:\n suc = app.relayButtonPressed()\n assert not suc\n assert ['Relay action cannot be performed', 2] == blocker.args\n\n\ndef test_toggleRelay_2(qtbot):\n def Sender():\n return ui.relayButton0\n app.sender = Sender\n app.ui.relayDevice.setCurrentIndex(1)\n with mock.patch.object(app.app.relay,\n 'switch',\n return_value=False):\n with qtbot.waitSignal(app.app.message) as blocker:\n suc = app.relayButtonPressed()\n assert not suc\n assert ['Relay action cannot be performed', 2] == blocker.args\n\n\ndef test_doRelayAction_1(qtbot):\n app.relayDropDowns[7].setCurrentIndex(0)\n with mock.patch.object(app.app.relay,\n 'switch',\n return_value=False):\n suc = app.doRelayAction(7)\n assert not suc\n\n\ndef test_doRelayAction_2(qtbot):\n app.relayDropDowns[7].setCurrentIndex(0)\n with mock.patch.object(app.app.relay,\n 'switch',\n return_value=True):\n suc = app.doRelayAction(7)\n assert suc\n\n\ndef test_doRelayAction_3(qtbot):\n app.relayDropDowns[7].setCurrentIndex(2)\n suc = app.doRelayAction(7)\n assert not suc\n\n\ndef test_doRelayAction_4(qtbot):\n app.relayDropDowns[7].setCurrentIndex(1)\n with mock.patch.object(app.app.relay,\n 'pulse',\n return_value=False):\n suc = app.doRelayAction(7)\n assert not suc\n\n\ndef test_doRelayAction_5(qtbot):\n app.relayDropDowns[7].setCurrentIndex(1)\n with mock.patch.object(app.app.relay,\n 'pulse',\n return_value=True):\n suc = app.doRelayAction(7)\n assert suc\n\n\ndef test_relayButtonPressed_1(qtbot):\n def Sender():\n return ui.relayButton0\n app.sender = Sender\n\n with mock.patch.object(app,\n 'doRelayAction',\n return_value=False):\n suc = app.relayButtonPressed()\n assert not suc\n\n\ndef test_relayButtonPressed_2(qtbot):\n def Sender():\n return ui.relayButton0\n app.sender = Sender\n\n with mock.patch.object(app,\n 'doRelayAction',\n return_value=True):\n suc = app.relayButtonPressed()\n assert suc\n","sub_path":"tests/unit_tests/gui/mainWmixin/test_tabSettRelay.py","file_name":"test_tabSettRelay.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"157263950","text":"#!/usr/bin/env python3\n\n'''\nFeedforward Neural Network implementation\n'''\n\nimport tensorflow as tf\n\nfrom neuralnetwork import base as nn\n\n\nclass FeedForward(nn.NeuralNetwork):\n '''\n '''\n\n def __init__(self,\n layers,\n functions,\n initialization_method='nw'):\n \"\"\"Constructor method\n\n Args:\n layers (list): Neural Network layers\n functions (list): Activation functions for layers\n initialization_method (str, optional): Method for adjusting\n weights and bias. Default: 'nw' (nyugen-widrow)\n \"\"\"\n # Save user parameters\n self.functions = functions\n self.layers = layers\n self.initialization_method = initialization_method\n\n # NN weights and bias...\n self.weights = []\n self.bias = []\n # ... and initilize them\n self.set_nn_parameters()\n\n # Set layers activation functions\n self.activationFunctions = []\n self.set_activation_functions()\n\n self.initialize_layers()\n\n def set_nn_parameters(self):\n \"\"\"Set Neural Network weights and bias.\n \"\"\"\n for i in range(len(self.layers) - 1):\n self.weights.append(\n tf.Variable(\n tf.random_uniform(\n [self.layers[i], self.layers[i + 1]], -1, 1\n ),\n name='WeightLayer' + str(i)\n )\n )\n self.bias.append(\n tf.Variable(\n tf.random_uniform(\n [self.layers[i + 1]], -1, 1\n ),\n name='BiasLayer' + str(i)\n )\n )\n\n self._adjust_parameters()\n\n def _adjust_parameters(self):\n \"\"\"Adjust NN weights and bias.\n Currently, only nyugen-widrow method is implemented.\n \"\"\"\n if self.initialization_method == 'nw':\n for i in range(len(self.layers) - 1):\n\n beta = .7 * pow(self.layers[i], pow(self.layers[0], -1))\n\n # Applying nyugen-widrow algorithm\n self.weights[i] *= beta\n self.bias[i] *= beta\n\n # Normalizing parameters\n tf.nn.l2_normalize(self.weights[i], 1)\n tf.nn.l2_normalize(self.bias[i], 0)\n\n def set_activation_functions(self):\n '''Maps user options to TensorFlow implementations.\n\n Raises:\n KeyError: if user enters and invalid function.\n '''\n # This dictionary holds the activation functions\n activationFunctionsMap = {\n 'tanh': tf.nn.tanh,\n 'relu': tf.nn.relu,\n 'sigmoid': tf.nn.sigmoid,\n 'softplus': tf.nn.softplus,\n 'softsign': tf.nn.softsign,\n 'softmax': tf.nn.softmax,\n }\n\n # Set activation functions\n for function in self.functions:\n\n try:\n act_function = activationFunctionsMap[function]\n self.activationFunctions.append(act_function)\n except KeyError as e:\n fopt = list(activationFunctionsMap.keys())\n exc_msg = 'Invalid activation function. Options are: %s' % fopt\n raise KeyError(exc_msg) from e\n\n def initialize_layers(self):\n \"\"\"Create Neural Network layers.\n \"\"\"\n\n # Input placeholder\n self.input = tf.placeholder(\n 'float',\n [None, self.layers[0]],\n name='symbolic_input'\n )\n\n # Output placeholder\n self.output = tf.placeholder(\n 'float',\n [None, self.layers[len(self.layers) - 1]],\n name='symbolic_output'\n )\n\n # Initializing model\n self.model = self.activationFunctions[0](\n tf.matmul(self.input, self.weights[0]) + self.bias[0])\n\n for i in range(1, len(self.layers) - 1):\n self.model = self.activationFunctions[i](\n tf.matmul(self.model, self.weights[i]) + self.bias[i]\n )\n","sub_path":"neuralnetwork/feedforward.py","file_name":"feedforward.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238793979","text":"import matplotlib.pyplot as plt\n\nfrom Taylor import taylor\nfrom RK4 import ruku4\nimport numpy as np\n\n\ndef derivs(t, _x):\n k, x = _x\n\n res_k = [x - k]\n res_k.append(k - res_k[0])\n res_k.append(res_k[0] - res_k[1])\n res_k.append(res_k[1] - res_k[2])\n\n res_x = [k, res_k[0], res_k[1], res_k[2]]\n\n return [res_k, res_x]\n\ndef func(t, _x):\n k, x = _x\n return [x - k, k]\n\nif __name__ == '__main__':\n t_0, t_f = 0, 3\n delta_t = 1e-3\n x_0 = [1, 1]\n\n t_taylor, _x_taylor = taylor(derivs, t_0, t_f, delta_t, x_0)\n k_t, x_t = _x_taylor.T\n\n t_rk4, _x_rk4 = ruku4(func, t_0, t_f, delta_t, x_0)\n k_rk4, x_rk4 = _x_rk4.T\n\n real_expos = np.roots([1, 1, -1])\n real_coefs = np.linalg.solve([real_expos, [1, 1]], x_0)\n real = real_coefs[0] * np.exp(t_rk4 * real_expos[0]) + real_coefs[1] * np.exp(t_rk4 * real_expos[1])\n\n plt.plot(t_taylor, x_t, label = 'Taylor')\n plt.plot(t_rk4, x_rk4, label = 'RK4')\n plt.plot(t_rk4, real, label = 'Real')\n plt.legend()\n plt.grid()\n plt.tight_layout()\n\n fig = plt.figure()\n plt.plot(t_taylor, real - x_t, label = 'Taylor')\n plt.plot(t_rk4, real - x_rk4, label = 'RK4')\n plt.legend()\n plt.grid()\n plt.title('Errores')\n plt.tight_layout()\n\n plt.show()","sub_path":"Parciales/Code/Algorithms/EDOs/Test2.py","file_name":"Test2.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"504999239","text":"# 56-Merge_Intervals_MEDIUM.py\n\n# https://leetcode.com/problems/merge-intervals/\n\n# Given a collection of intervals, merge all overlapping intervals.\n\n# Example 1:\n\n# Input: [[1,3],[2,6],[8,10],[15,18]]\n# Output: [[1,6],[8,10],[15,18]]\n# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].\n# Example 2:\n\n# Input: [[1,4],[4,5]]\n# Output: [[1,5]]\n# Explanation: Intervals [1,4] and [4,5] are considered overlapping.\n# NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.\n\nfrom typing import List\n\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n\n # Assumptions\n # intervals are ints\n # overlapping if end equals start\n # all data fits on a single machine or api is consistent for multiple\n # machines\n # Assume intervals are not sorted, even though all examples are.\n\n # Approach, Complexity, Tradeoffs, Potential Improvements\n # should we first sort? O(nlogn)\n # 1. Brute force for each interval iterate through the rest of the\n # intervals and if overlap modify the current and restart the iteration\n # intervals overlap if the end of the first is greater or equal to the\n # second. Then the resulting interval is the min of the first elements\n # and the max of the next elements.\n # or if one completely encloses another then the start is less and\n # the end is greater\n # This is O(N^2) time for each combination O(1) space\n # 2. Can we do it in O(N) time? Maybe.\n # I can't think of a good solution right now\n\n # Edge cases\n # end equals start overlapping\n # fully overlapped items\n # no items\n # single item\n\n # Handle small edge cases\n if len(intervals) <= 1:\n return intervals\n\n # Brute force\n def overlap(interval1: List, interval2: List) -> bool:\n \"\"\"Return whether two intervals overlap.\"\"\"\n start_1 = interval1[0]\n start_2 = interval2[0]\n end_1 = interval1[1]\n end_2 = interval2[1]\n\n # Surely the below can be combined, just trying to be exhaustive\n # before optimizing.\n\n # e.g. [1, 4] [3, 5] or [0, 1] [1, 3]\n if start_1 <= start_2 and end_1 >= start_2:\n return True\n\n # e.g. [1, 2] [3, 4]\n if start_1 <= start_2 and end_1 < start_2:\n return False\n\n\n # e.g. [3, 5] [1, 4] or [1, 3] [0, 1]\n if start_2 <= start_1 and end_2 >= start_1:\n return True\n\n # e.g. [3, 4] [1, 2]\n if start_2 <= start_1 and end_2 < start_1:\n return False\n\n\n\n # e.g. [1, 9] [3, 4]\n if start_1 <= start_2 and end_1 >= end_2:\n return True\n\n # e.g. [4, 9] [3, 5]\n if start_1 >= start_2 and end_1 >= end_2:\n return True\n\n\n # e.g. [3, 4] [1, 9]\n if start_2 <= start_1 and end_2 >= end_1:\n return True\n\n # e.g. [3, 5] [4, 9]\n if start_2 >= start_1 and end_2 >= end_1:\n return True\n\n\n\n def _merge(interval1: List, interval2: List) -> List:\n \"\"\"Merge two intervals that overlap.\"\"\"\n start_1 = interval1[0]\n start_2 = interval2[0]\n end_1 = interval1[1]\n end_2 = interval2[1]\n\n return [min(start_1, start_2), max(end_1, end_2)]\n\n\n i = 0\n j = 1\n\n while i < len(intervals):\n while j < len(intervals):\n if overlap(intervals[i], intervals[j]):\n merged = _merge(intervals[i], intervals[j])\n intervals[i] = merged\n intervals.pop(j)\n # Start over\n i = 0\n j = 1\n\n else:\n j += 1\n i += 1\n j = i + 1\n\n return intervals\n\n\nimport unittest\n\nclass TestMerge(unittest.TestCase):\n\n def setUp(self):\n self.solution = Solution()\n\n def test_example_1(self):\n i = [[1,3],[2,6],[8,10],[15,18]]\n o = [[1,6],[8,10],[15,18]]\n self.assertEqual(\n sorted(o),\n self.solution.merge(i)\n )\n\n def test_example_2(self):\n i = [[1,4],[4,5]]\n o = [[1,5]]\n self.assertEqual(\n sorted(o),\n self.solution.merge(i)\n )\n\n\n def test_failing_case_1(self):\n i = [[2,3],[4,5],[6,7],[8,9],[1,10]]\n o = [[1, 10]]\n self.assertEqual(\n sorted(o),\n self.solution.merge(i)\n )\n\n\n\n def test_failing_case_2(self):\n i = [[2,3],[2,2],[3,3],[1,3],[5,7],[2,2],[4,6]]\n o = [[1,3],[4,7]]\n\n self.assertEqual(\n sorted(o),\n self.solution.merge(i)\n )\n\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"leetcode/56-Merge_Intervals_MEDIUM.py","file_name":"56-Merge_Intervals_MEDIUM.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"92664211","text":"from elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Search, Q\n\n\n\n\n\n\ndef search_es(host, index, doc_type, **kwargs):\n \"\"\"\n 需要查询的名称和字段键值对\n :param host: 主机名\n :param index: 索引名\n :param doc_type: 类型名\n :param kwargs: 查询键值对 {'api_value.data.singer.name':'刘德华', 'api_value.data.album.name':'如果你是我的传说'}\n :return: 返回文档列表\n \"\"\"\n\n if not host or not index or not doc_type:\n assert \"参数不能为空\"\n\n client = Elasticsearch(host)\n search = Search(index=index, doc_type=doc_type, using=client)\n\n\n\n # 通过kwargs构造查询条件\n qs = list()\n for item in kwargs.items():\n q = Q('match', **dict((item,)))\n qs.append(q)\n final_q = Q('bool', must=qs)\n s = search.query(final_q)\n\n\n # 返回查询结果\n ret = list()\n responses = s.execute()\n for item in responses:\n ret.append(item.to_dict)\n\n return ret\n\n\n\n\n\nif __name__ == '__main__':\n field_value = {'api_value.data.singer.name':'刘德华', 'api_value.data.album.name':'如果你是我的传说'}\n search_es('192.168.1.211:9200', 'tencent_store', 'tencent_song_api', **field_value)","sub_path":"elsearch/elsearch.py","file_name":"elsearch.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"159837410","text":"# coding: utf-8\n# __author__ = 'charles'\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom app_core.models import School\nfrom app_core.utils import httputils\nfrom app_core.serializer import SchoolSerializer\nfrom app_core.result_code import ResultCode\n\n\n@api_view(['GET'])\ndef school_list(request):\n \"\"\"\n 机构列表\n search -- 搜索关键字\n page -- 页码\n page_size -- 一页多少条数据\n city_id -- 城市id\n parent_id -- 有此选项意为:查询分校\n \"\"\"\n params = httputils.get_request_param(request)\n page = params.get('page', 1)\n page_size = params.get('page_size', 15)\n query_set = School.objects.filter(is_deleted=False)\n if params.get('search'):\n query_set = query_set.filter(name__contains=params.get('search'))\n if params.get('city_id'):\n query_set = query_set.filter(city_id=params.get('city_id'))\n if params.get('parent_id'):\n query_set = query_set.filter(parent_id=params.get('parent_id'))\n results = httputils.page_query_set(query_set=query_set, page=page, page_size=int(page_size))\n serializer = SchoolSerializer(results.get('entries'), many=True)\n\n return Response(httputils.json_message(data=serializer.data,\n pages={'total': results.get('total'),\n 'pageCount': results.get('pageCount')},\n code=ResultCode.success))\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef school_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n ---\n # YAML (must be separated by `---`)\n serializer: SchoolSerializer\n \"\"\"\n try:\n school = School.objects.get(pk=pk)\n except:\n return Response(httputils.json_message(code=ResultCode.pk_not_object, success=False))\n if request.method == 'GET':\n serializer = SchoolSerializer(school)\n\n return Response(httputils.json_message(data=serializer.data, code=ResultCode.success))\n elif request.method == 'PUT':\n serializer = SchoolSerializer(school, data=request.data)\n if serializer.is_valid():\n # serializer.save()\n # return Response(httputils.json_message(data=serializer.data, code=ResultCode.success))\n rs = serializer.save()\n if isinstance(rs, int):\n return Response(httputils.json_message(success=False, code=rs, msg='False'))\n return Response(httputils.json_message(success=True, data=serializer.data, msg='Success'))\n return Response(httputils.json_message(msg=serializer.errors, success=False,\n code=ResultCode.parameter_valid_fail))\n elif request.method == 'DELETE':\n School.objects.filter(pk=pk).update(is_deleted=True)\n return Response(httputils.json_message(code=ResultCode.no_data))\n\n\n@api_view(['POST'])\ndef school_create(request):\n \"\"\"\n Create school\n ---\n # YAML (must be separated by `---`)\n serializer: SchoolSerializer\n \"\"\"\n params = httputils.get_request_param(request)\n serializer = SchoolSerializer(data=params)\n if serializer.is_valid():\n rs = serializer.save()\n if isinstance(rs, int):\n return Response(httputils.json_message(success=False, code=rs, msg='False'))\n return Response(httputils.json_message(data=serializer.data, code=ResultCode.success))\n return Response(httputils.json_message(success=False,\n msg=serializer.errors, code=ResultCode.parameter_valid_fail))\n","sub_path":"api_master_v2/app_school/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"237274431","text":"# 2018/6/21 23:02 in TJU-409\n# When i want to prove the Gauss-Lucas theorem in complex analysis, I try to know what the funcion F = a^2 's nth derivate is...\n# but i have no idea, what i can only do is write a program to display it...in python\nimport numpy as np\nfrom math import log\n\n\ndef Cal(now):\n tmp = np.zeros((now.shape[0]*2, 2))\n for i in range(now.shape[0]):\n tmp[i * 2][0] = now[i][0] + 1\n tmp[i * 2][1] = now[i][1]\n tmp[i * 2 + 1 ][0] = now[i][0]\n tmp[i * 2 + 1][1] = now[i][1] + 1\n for i in range(len(tmp)):\n if tmp[i][0]>tmp[i][1]:\n t = tmp[i][0]\n tmp[i][0] = tmp[i][1]\n tmp[i][1] = t\n return tmp\n\ndef disp(now):\n print(\"N=%d:\" % (log(now.shape[0], 2)+1), end=\"\")\n resstr = \"\"\n for i in range(now.shape[0]):\n resstr = resstr + \"%d%d \" % (now[i][0], now[i][1])\n print(resstr)\n tmp = resstr.split()\n array = []\n for i in tmp:\n if 0 == array.count((i, tmp.count(i))):\n array.append((i, tmp.count(i)))\n print(array)\n\nnow = np.array([[0,1]])\nN = 12\n\nres = []\nres.append(now)\n\nfor i in range(1,N):\n now = Cal(now)\n res.append(now)\n disp(now)\n #print(now)\n","sub_path":"a^2's derivate/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"576762706","text":"temp_output = \"\"\nisFinished = False\n\ndef dinnerEntry():\n val = input(\"Please enter you dinner item: \")\n return val\n \nwhile not isFinished:\n strValue = dinnerEntry()\n with open(\"text_files/dinner_menu.txt\",\"a\") as dinner_txt:\n dinner_txt.write(strValue + \"\\n\")\n \n strFinished = input(\"Do you want to continue? Yes or No: \")\n if strFinished == \"Yes\" or strFinished == \"Y\":\n continue\n else:\n isFinished = True \n\n ","sub_path":"IT - 412/Week1-2/Week2-PracticeProblems/problem2/problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"60444708","text":"from npc.npc1 import Npc\nfrom npc.player import Player\nprint(\"NPC可选:\")\np1=Npc(\"阿尔萨斯\",\"1\",\"使用霜之哀伤攻击敌人\")\np2=Npc(\"吉安娜\",\"2\",\"使用奥数法术远程攻击敌人\")\np3=Npc(\"乌瑟尔\",\"3\",\"使用圣光力量治愈盟友\")\nfor i in Npc.jianjce:\n print(i)\ndef fun():\n import sys\n p = Player()\n while True:\n p.show()\n bh = input(\"请选择您进行的操作:\")\n if bh == \"1\":\n p.add_npc()\n if bh == \"2\":\n p.del_npc()\n if bh == \"o\":\n sys.exit()\nfun()","sub_path":"npc/测试.py","file_name":"测试.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"222927517","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\nfrom __future__ import print_function\nimport sys\nfrom openeye import oechem\nfrom openeye import oegrid\nfrom openeye import oespicoli\n\n\ndef main(args):\n if len(args) != 3:\n oechem.OEThrow.Usage(\"%s \" % args[0])\n\n refifs = oechem.oemolistream()\n if not refifs.open(args[1]):\n oechem.OEThrow.Fatal(\"Unable to open %s for reading\" % args[1])\n\n refmol = oechem.OEGraphMol()\n oechem.OEReadMolecule(refifs, refmol)\n oechem.OEAssignBondiVdWRadii(refmol)\n\n fitifs = oechem.oemolistream()\n if not fitifs.open(args[2]):\n oechem.OEThrow.Fatal(\"Unable to open %s for reading\" % args[2])\n\n fitmol = oechem.OEGraphMol()\n oechem.OEReadMolecule(fitifs, fitmol)\n oechem.OEAssignBondiVdWRadii(fitmol)\n\n # Map the reference molecule onto a grid\n grd = oegrid.OEScalarGrid()\n oegrid.OEMakeMolecularGaussianGrid(grd, refmol, 0.5)\n\n # Get the total volume of the reference molecule\n refsrf = oespicoli.OESurface()\n oespicoli.OEMakeSurfaceFromGrid(refsrf, grd, 1.0)\n totalv = oespicoli.OESurfaceVolume(refsrf)\n\n # Mask out the fit molecule\n oegrid.OEMaskGridByMolecule(grd, fitmol)\n\n # Find how much of the reference volume is remaining\n fitsrf = oespicoli.OESurface()\n oespicoli.OEMakeSurfaceFromGrid(fitsrf, grd, 1.0)\n remaining = oespicoli.OESurfaceVolume(fitsrf)\n\n print(\"Percent overlap: %f\" % ((1 - remaining/totalv) * 100))\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","sub_path":"venv/Scripts/overlap.py","file_name":"overlap.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"336549373","text":"# Save Model Using joblib\n#More efficient than pickle\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.externals import joblib\n\nimport warnings\nwarnings.filterwarnings(action='ignore')\nfilename = 'indians-diabetes.data.csv'\nnames=['preg', 'plas', 'pres', 'skin', 'test',\n 'mass', 'pedi', 'age', 'class']\ndataframe = pd.read_csv(filename, names=names)\narray = dataframe.values\nX = array[:,0:8]\nY = array[:,8]\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y,\n test_size=0.33, random_state=7)\n# Fit the model on 67% data\nmodel = LogisticRegression()\nmodel.fit(X_train, Y_train)\n\n# save the model to disk\nfilename = \"finalized_model.sav\"\njoblib.dump(model, filename)\nprint( \"Model dumped successfully into a file by Joblib\")\nprint(\"\\n....\\n...\\n...\\n...\")\n\n# some time later...\nprint(\"-----------------------\\n\\n\\n\")\nprint(\"some time later... \")\nprint(\"\\n\\n\\n-----------------------\")\n\n\n# load the model from disk\nloaded_model = joblib.load(filename)\nprint( \"Model loaded successfully from file by Joblib\")\nresult = loaded_model.score(X_test, Y_test)\nprint( \"Accuracy Result : \" , result)\n\n\n#these are used to create a file in which the trained model is loaded\n# so that it can be used in future by various users.","sub_path":"5. machine learning/5. Save Model/2. Dump Model By Joblib.py","file_name":"2. Dump Model By Joblib.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"281679572","text":"# encoding: utf-8\n\nimport pandas as pd\n\n\ndef save_submission_from_file(oldfile, submissionfile, preds, tag):\n \"\"\"\n oldfile: 已有提交文件,首行为字段名,其中有一列为结果标签列\n submissionfile: 待生成提交文件,将和 oldfile 保持同一格式\n preds: 预测结果列表\n tag: 标签字段\n \"\"\"\n sample = pd.read_csv(oldfile)\n sample[tag] = preds\n sample.to_csv(submissionfile, index=False)\n\n\ndef save_submission_from_data(submissionfile, headers, data, delimiter=','):\n \"\"\"\n submissionfile: 待生成提交文件\n headers: header line 文字\n data: 各列数据列表的列表\n delimiter: 分隔符\n \"\"\"\n assert len(headers) == len(data)\n with open(submissionfile) as f:\n f.write(delimiter.join(headers) + '\\n')\n for i, no in enumerate(list(data[0])):\n f.write(delimiter.join([str(d[i]) for d in data]) + '\\n')\n","sub_path":"src/armory/postproc.py","file_name":"postproc.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"561432500","text":"from django.urls import path\nfrom .views import landingview, supplierlistview, addsupplier, deletesupplier, productlistview, addproduct, deleteproduct, edit_supplier_get, edit_supplier_post, edit_product_get, edit_product_post, products_filtered, loginview, login_action, logout_action, searchsuppliers\n\nurlpatterns = [\n\n path('landing/', landingview),\n\n # LOGIN\n path('', loginview),\n path('login/', login_action),\n path('logout/', logout_action),\n\n # SUPPLIERS\n path('suppliers/', supplierlistview),\n path('add-supplier/', addsupplier),\n path('delete-supplier//', deletesupplier),\n path('edit-supplier-get//', edit_supplier_get),\n path('edit-supplier-post//', edit_supplier_post),\n path('search-suppliers/', searchsuppliers),\n\n\n # PRODUCTS\n path('products/', productlistview),\n path('add-product/', addproduct),\n path('delete-product//', deleteproduct),\n path('edit-product-get//', edit_product_get),\n path('edit-product-post//', edit_product_post),\n path('products-by-supplier//', products_filtered),\n\n]\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"566427837","text":"#!/usr/bin/env python\n\nfrom . import data\n\nfrom app.tools import home_url\nfrom app.data.tools import ExportUserData, RestoreUserData\nfrom app.data.forms import RestoreDataForm\n\nfrom flask import redirect, url_for, request, flash, render_template, \\\n current_app\nfrom flask_login import login_required, current_user\n\n\n@data.route(\"/download_user_data\")\n@login_required\ndef download_user_data():\n\n app = current_app._get_current_object()\n\n export = ExportUserData(user=current_user, context=app)\n\n return export.download()\n\n\n@data.route(\"/email_user_data\")\n@login_required\ndef email_user_data():\n\n app = current_app._get_current_object()\n\n export = ExportUserData(user=current_user, context=app)\n\n export.email()\n\n flash(\"e-mailed HLTS data to {0}\".format(current_user.email), \"flashSuccess\")\n\n return redirect(url_for(\"main.tools\"))\n\n\n@data.route(\"/restore_user_data\", methods=[\"GET\", \"POST\"])\n@login_required\ndef restore_user_data():\n\n # WIPASYNC\n\n app = current_app._get_current_object()\n\n form_restore = RestoreDataForm()\n\n if request.method == \"POST\":\n\n data = request.files[\"hlts_file\"]\n\n restore = RestoreUserData(user=current_user, context=app)\n\n try:\n restore.validate(data)\n except Exception as error:\n flash(error.message, \"flashWarning\")\n return redirect(url_for(\"data.restore_user_data\"))\n\n else:\n\n try:\n restore.execute()\n except Exception as error:\n flash(error.message, \"flashWarning\")\n return redirect(url_for(\"data.restore_user_data\"))\n\n else:\n flash(\"restored user settings\", \"flashSuccess\")\n flash(\"{0} annotations currently restoring in the background\"\n .format(restore.annotation_count), \"flashSuccess\")\n return redirect(home_url())\n\n return render_template(\"data/restore.html\", form_restore=form_restore)\n","sub_path":"app/data/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"607560531","text":"\"\"\"\n The reverse of queryToName.py\n This script removes any characters that cannot be used in a search query string in a\n url and replaces it with the appropriate sequence of characters.\n The query strings created in this script will be catenated to the url of the website\n being scraped from to get the full url.\n\"\"\"\n\nimport os\npathToHere = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + \"/assets/\"\n\nf = open(pathToHere+\"anime_list.txt\", 'r')\nnames = f.readlines()\n\nqueries = []\nfor name in names:\n name = name.replace(\" \", \"%20\")\n name = name.replace(\":\", \"%3A\")\n name = name.replace(\";\", \"%3B\")\n name = name.replace(\"=\", \"%3D\")\n name = name.replace(\"?\", \"%3F\")\n\n queries.append(\"?q=\"+name)\n\nfo = open(pathToHere+\"queries.txt\", \"w\")\nfo.writelines(queries)\n\nf.close()\nfo.close()\n","sub_path":"pyscripts/nameToQuery.py","file_name":"nameToQuery.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"388695806","text":"import sys\r\nfrom PyQt4 import QtCore, QtGui\r\nfrom PyQt4.QtCore import pyqtSlot\r\nfrom Thread_Strength_Calculator.thread_strength_run import ThreadCalculator\r\nfrom Lug_Calculator.lug_strength_run import LugCalculator\r\nfrom Interference_Stress_Calculator.interference_calculator_run import InterferenceCalculator\r\n\r\n# This is where we actually get the module creted by Qt\r\nfrom main_window import Ui_main_form\r\n\r\nclass MainWindow(QtGui.QMainWindow, Ui_main_form):\r\n def __init__(self, parent=None):\r\n QtGui.QWidget.__init__(self, parent)\r\n self.ui = Ui_main_form()\r\n self.ui.setupUi(self)\r\n\r\n # Make Signal/Slot connections\r\n # Connect the button to the function below\r\n QtCore.QObject.connect(self.ui.thread_strength, \r\n QtCore.SIGNAL(\"clicked()\"),\r\n self.launch_thread_calc)\r\n\r\n QtCore.QObject.connect(self.ui.lug_strength,\r\n QtCore.SIGNAL(\"clicked()\"),\r\n self.launch_lug_calc)\r\n\r\n QtCore.QObject.connect(self.ui.interference_calculator,\r\n QtCore.SIGNAL(\"clicked()\"),\r\n self.launch_interference_calc)\r\n\r\n\r\n @pyqtSlot(int)\r\n def launch_thread_calc(self):\r\n window = ThreadCalculator(self)\r\n window.show()\r\n\r\n @pyqtSlot(int)\r\n def launch_lug_calc(self):\r\n window = LugCalculator(self)\r\n window.show()\r\n\r\n @pyqtSlot(int)\r\n def launch_interference_calc(self):\r\n window = InterferenceCalculator(self)\r\n window.show()\r\n\r\nif __name__ == \"__main__\":\r\n app = QtGui.QApplication(sys.argv)\r\n myform = MainWindow()\r\n myform.show()\r\n sys.exit(app.exec_())","sub_path":"Engineering_Tools/main_window_run.py","file_name":"main_window_run.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"417256314","text":"from smbus2 import SMBus\nimport time\n#/sys/bus/i2c/devices/i2c-1/bus_clk_rate - can change clock rate at this file if need be\n\ni2c_channel = 1\ni2c_address = 0x0a\nbyteLength = 18\ndelay = 0.25\n\ndef Thermal_Values():\n\n #read a block of data\n with SMBus(i2c_channel) as bus:\n #read a block of bytes from address 0x0a, offset 0\n block = bus.read_i2c_block_data(i2c_address, 0, byteLength)\n temps = []\n for i in range(2,17,2):\n if block[i+1] == 2:\n #time.sleep(delay)\n return True\n elif block[i] >= 245 and block[i+1] == 1:\n #time.sleep(delay)\n return True\n #time.sleep(delay)\n return False\n\n","sub_path":"Final/10.24/i2c_trigger_Final.py","file_name":"i2c_trigger_Final.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"330300828","text":"\nprobe_id = \"test01\"\nlog_name = \"/var/log/suricata/files-json.log\"\n\nmysql_host = \"db_host\"\nmysql_db = \"db_files\"\nmysql_user = \"db_user\"\nmysql_pwd = \"db_pwd\"\n\ngraylog_host = \"192.168.1.3\"\ngraylog_port = 12201\n\ndb = True\nlog = True\n\nmisp_url = \"http://192.168.1.5/\"\nmisp_key = \"XXXXXXX\" # The MISP auth key can be found on the MISP web interface under the automation section\nmisp_verifycert = False","sub_path":"src/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"626004450","text":"import os\n\ndef main():\n os.system('pip3 install -U pip')\n content = os.popen('echo $(pip3 list)')\n content = content.readlines()[0].split(' ')[4:]\n\n pkg = []\n for i in range(int(len(content)/2)):\n pkg.append(content[2 * i])\n \n L = len(pkg)\n for i, pkgname in enumerate(pkg):\n print(\"Updating %d of %d packages: %s\" % (i + 1, L, pkgname))\n os.system('pip3 install -U ' + pkgname)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"PIPUPDATEALL.py","file_name":"PIPUPDATEALL.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"402995200","text":"from datetime import datetime\nfrom . import entities\n\nDATE_TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'\nDATE_FORMAT = '%Y-%m-%d'\n\nclass FormRegisterRequest(object):\n def __init__(self, steps=None, include_archived=False, filters=None, modified_before=None, modified_after=None):\n if steps:\n if not isinstance(steps, list):\n raise TypeError('steps must be a list of int')\n for item in steps:\n if not isinstance(item, int):\n raise TypeError('steps must be a list of int')\n self.steps = steps\n\n if not isinstance(include_archived, bool):\n raise TypeError('include_archived must be bool')\n self.include_archived = include_archived\n\n if modified_before:\n if not isinstance(modified_before, datetime):\n raise TypeError('modified_before must be a date')\n self.modified_before = datetime.strftime(modified_before, DATE_TIME_FORMAT)\n\n if modified_after:\n if not isinstance(modified_after, datetime):\n raise TypeError('modified_after must be a date')\n self.modified_after = datetime.strftime(modified_after, DATE_TIME_FORMAT)\n\n if filters:\n if not isinstance(filters, list):\n raise TypeError('filters must be a list of entities.FormRegisterFilter')\n for fltr in filters:\n if not isinstance(fltr, entities.FormRegisterFilter):\n raise TypeError('filters must be a list of entities.FormRegisterFilter')\n if fltr.operator == 'equals':\n setattr(self, 'fld{}'.format(fltr.field_id), fltr.values)\n if fltr.operator == 'greater_than':\n setattr(self, 'fld{}'.format(fltr.field_id), 'gt{}'.format(fltr.values))\n if fltr.operator == 'less_than':\n setattr(self, 'fld{}'.format(fltr.field_id), 'lt{}'.format(fltr.values))\n if fltr.operator == 'range':\n setattr(self, 'fld{}'.format(fltr.field_id), 'gt{},lt{}'.format(*fltr.values))\n if fltr.operator == 'is_in':\n setattr(self, 'fld{}'.format(fltr.field_id), \",\".join(fltr.values))\n\nclass TaskCommentRequest(object):\n def __init__(self, text=None, approval_choice=None, approval_steps=None, action=None,\n attachments=None, field_updates=None, approvals_added=None,\n participants_added=None, reassign_to=None, due=None,\n due_date=None, duration=None, scheduled_date=None,\n cancel_schedule=None, added_list_ids=None, removed_list_ids=None,\n approvals_removed=None, approvals_rerequested=None, subject = None):\n self.text = text\n self.subject = subject\n if approval_choice:\n if approval_choice not in ['approved', 'rejected', 'revoked', 'acknowledged']:\n raise TypeError('approval_choice can only be \\'approved\\', \\'rejected\\', \\'acknowledged\\', or \\'revoked\\'')\n self.approval_choice = approval_choice\n if action:\n if action not in ['finished', 'reopened']:\n raise TypeError('action can only be \\'finished\\' or \\'reopened\\'')\n self.action = action\n if reassign_to:\n if isinstance(reassign_to, entities.Person):\n self.reassign_to = reassign_to\n elif isinstance(reassign_to, int):\n self.reassign_to = entities.Person(id=reassign_to)\n else:\n self.reassign_to = entities.Person(email=reassign_to)\n if attachments:\n if not isinstance(attachments, list):\n raise TypeError('attachments must be a list of guids')\n self.attachments = []\n for attachment in attachments:\n self.attachments.append(attachment)\n if approvals_added:\n if not isinstance(approvals_added, list):\n raise TypeError('approvals_added must be a list')\n self.approvals_added = []\n for idx, approval_step in enumerate(approvals_added):\n if not isinstance(approval_step, list):\n raise TypeError('approval_step must be a list of persons, person ids'\n ', or person emails')\n self.approvals_added.append([])\n for person in approval_step:\n if isinstance(person, entities.Person):\n self.approvals_added[idx].append(person)\n elif isinstance(person, int):\n self.approvals_added[idx].append(entities.Person(id=person))\n else:\n self.approvals_added[idx].append(entities.Person(email=person))\n if approvals_removed:\n if not isinstance(approvals_removed, list):\n raise TypeError('approvals_removed must be a list')\n self.approvals_removed = []\n for idx, approval_step in enumerate(approvals_removed):\n if not isinstance(approval_step, list):\n raise TypeError('approval_step must be a list of persons, person ids'\n ', or person emails')\n self.approvals_removed.append([])\n for person in approval_step:\n if isinstance(person, entities.Person):\n self.approvals_removed[idx].append(person)\n elif isinstance(person, int):\n self.approvals_removed[idx].append(entities.Person(id=person))\n else:\n self.approvals_removed[idx].append(entities.Person(email=person))\n if approvals_rerequested:\n if not isinstance(approvals_rerequested, list):\n raise TypeError('approvals_rerequested must be a list')\n self.approvals_rerequested = []\n for idx, approval_step in enumerate(approvals_rerequested):\n if not isinstance(approval_step, list):\n raise TypeError('approval_step must be a list of persons, person ids'\n ', or person emails')\n self.approvals_rerequested.append([])\n for person in approval_step:\n if isinstance(person, entities.Person):\n self.approvals_rerequested[idx].append(person)\n elif isinstance(person, int):\n self.approvals_rerequested[idx].append(entities.Person(id=person))\n else:\n self.approvals_rerequested[idx].append(entities.Person(email=person))\n if participants_added:\n if not isinstance(participants_added, list):\n raise TypeError('participants_added must be a list')\n self.participants_added = []\n for person in participants_added:\n try:\n int(person)\n self.participants_added.append(entities.Person(id=person))\n except ValueError:\n self.participants_added.append(entities.Person(email=person))\n if field_updates:\n self.field_updates = []\n for field_update in field_updates:\n if isinstance(field_update, entities.FormField):\n self.field_updates.append(field_update)\n else:\n if 'name' not in field_update and 'id' not in field_update:\n raise TypeError('each field_update in field_updates '\n 'must contain field id or name')\n if 'value' not in field_update:\n raise TypeError('each field_update in field_updates must '\n 'contain field value')\n self.field_updates.append(field_update)\n if due_date:\n if not isinstance(due_date, datetime):\n raise TypeError('due_date must be a date')\n self.due_date = datetime.strftime(due_date, DATE_FORMAT)\n if due:\n if not isinstance(due, datetime):\n raise TypeError('due must be a date')\n self.due = datetime.strftime(due, DATE_TIME_FORMAT)\n if duration:\n if not isinstance(due, int):\n raise TypeError('duration must be an int')\n self.duration = duration\n if scheduled_date:\n if not isinstance(scheduled_date, datetime):\n raise TypeError('scheduled_date must be a date')\n self.scheduled_date = datetime.strftime(scheduled_date, DATE_FORMAT)\n if cancel_schedule:\n if not isinstance(cancel_schedule, bool):\n raise TypeError('cancel_schedule must be a bool')\n self.cancel_schedule = datetime.strftime(cancel_schedule, DATE_FORMAT)\n if added_list_ids:\n if not isinstance(added_list_ids, list):\n raise TypeError('added_list_ids must be a list of int')\n for item in added_list_ids:\n if not isinstance(item, int):\n raise TypeError('added_list_ids must be a list of int')\n self.added_list_ids = added_list_ids\n if removed_list_ids:\n if not isinstance(removed_list_ids, list):\n raise TypeError('removed_list_ids must be a list of int')\n for item in removed_list_ids:\n if not isinstance(item, int):\n raise TypeError('removed_list_ids must be a list of int')\n self.removed_list_ids = removed_list_ids\n if approval_steps:\n if not isinstance(approval_steps, list):\n raise TypeError('approval_steps must be a list of int')\n for item in approval_steps:\n if not isinstance(item, int):\n raise TypeError('approval_steps must be a list of int')\n self.approval_steps = approval_steps\n\nclass CreateTaskRequest(object):\n def __init__(self, text=None, subject=None, parent_task_id=None,\n due_date=None, form_id=None, attachments=None, responsible=None,\n fields=None, approvals=None, participants=None, list_ids=None,\n due=None, duration=None, scheduled_date=None, fill_defaults = None):\n if text:\n self.text = text\n if subject:\n self.subject = subject\n if parent_task_id:\n if not isinstance(parent_task_id, int):\n raise TypeError('parent_task_id must be an int')\n self.parent_task_id = parent_task_id\n if due_date:\n if not isinstance(due_date, datetime):\n raise TypeError('due_date must be a date')\n self.due_date = datetime.strftime(due_date, DATE_FORMAT)\n if due:\n if not isinstance(due, datetime):\n raise TypeError('due must be a date')\n self.due = datetime.strftime(due, DATE_TIME_FORMAT)\n if duration:\n if not isinstance(duration, int):\n raise TypeError('duration must be an int')\n self.duration = duration\n if scheduled_date:\n if not isinstance(scheduled_date, datetime):\n raise TypeError('scheduled_date must be a date')\n self.scheduled_date = datetime.strftime(scheduled_date, DATE_FORMAT)\n if form_id:\n if not isinstance(form_id, int):\n raise TypeError('form_id must be int')\n self.form_id = form_id\n if attachments:\n if not isinstance(attachments, list):\n raise TypeError('attachments must be a list of guids')\n self.attachments = []\n for attachment in attachments:\n self.attachments.append(attachment)\n if responsible:\n if isinstance(responsible, entities.Person):\n self.responsible = responsible\n elif isinstance(responsible, int):\n self.responsible = entities.Person(id=responsible)\n else:\n self.responsible = entities.Person(email=responsible)\n if fields:\n self.fields = []\n for field in fields:\n if isinstance(field, entities.FormField):\n self.fields.append(field)\n else:\n if 'name' not in field and 'id' not in field:\n raise TypeError('each field in fields '\n 'must contain field id or name')\n if 'value' not in field:\n raise TypeError('each field in fields must '\n 'contain field value')\n self.fields.append(field)\n if approvals:\n if not isinstance(approvals, list):\n raise TypeError('approvals must be a list')\n self.approvals = []\n for idx, approval_step in enumerate(approvals):\n if not isinstance(approval_step, list):\n raise TypeError('approval_step must be a list of persons, person ids'\n ', or person emails')\n self.approvals.append([])\n for person in approval_step:\n if isinstance(person, entities.Person):\n self.approvals[idx].append(person)\n elif isinstance(person, int):\n self.approvals[idx].append(entities.Person(id=person))\n else:\n self.approvals[idx].append(entities.Person(email=person))\n if participants:\n if not isinstance(participants, list):\n raise TypeError('approvals_added must be a list')\n self.participants = []\n for person in participants:\n try:\n int(person)\n self.participants.append(entities.Person(id=person))\n except ValueError:\n self.participants.append(entities.Person(email=person))\n if list_ids:\n if not isinstance(list_ids, list):\n raise TypeError('list_ids must be a list of int')\n for item in list_ids:\n if not isinstance(item, int):\n raise TypeError('list_ids must be a list of int')\n self.list_ids = list_ids\n if fill_defaults:\n if not isinstance(fill_defaults, bool):\n raise TypeError(\"fill_defaults must be a boolean\")\n self.fill_defaults = fill_defaults\n\nclass SyncCatalogRequest(object):\n def __init__(self, apply=None, catalog_headers=None, items=None):\n if apply:\n if not isinstance(apply, bool):\n raise TypeError('apply must be a bool')\n self.apply = apply\n if catalog_headers:\n _validata_catalog_headers(catalog_headers)\n self.catalog_headers = catalog_headers\n if items:\n self.items = _get_catalog_items(items)\n\nclass CreateCatalogRequest(object):\n def __init__(self, name=None, catalog_headers=None, items=None):\n if name:\n if not isinstance(name, str):\n raise TypeError('name must be a str')\n self.name = name\n if catalog_headers:\n _validata_catalog_headers(catalog_headers)\n self.catalog_headers = catalog_headers\n if items:\n self.items = _get_catalog_items(items)\n\ndef _validata_catalog_headers(catalog_headers):\n if not isinstance(catalog_headers, list):\n raise TypeError('catalog_headers must be a list of str')\n for item in catalog_headers:\n if not isinstance(item, str):\n raise TypeError('list_ids must be a list of str')\n\ndef _get_catalog_items(catalog_items):\n if not isinstance(catalog_items, list):\n raise TypeError('catalog_items must be a list')\n \n items = []\n for item in catalog_items:\n try:\n items.append(entities.CatalogItem.fromliststr(item))\n except TypeError:\n if not isinstance(item, entities.CatalogItem):\n raise TypeError('catalog_items must be a list of CatalogItems')\n items.append(item)\n return items\n","sub_path":"pyrus/models/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":16414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"512899345","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt \n\nimg = cv2.imread('road5.png')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\nprint(img.shape)\nheight = img.shape[0]\nwidth = img.shape[1]\n\n# vertices of the masked part of the image\nregion_of_interest_vertices = [\n (0, height),\n (width/2,height/2),\n (width, height)\n]\n\n# A function for the region_of_interest mask's the image with the vertices\ndef region_of_interest(img, vertices):\n mask = np.zeros_like(img)\n match_mask_color = 255\n cv2.fillPoly(mask, vertices, match_mask_color)\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n# this function is used to draw the lines\ndef draw_the_lines(img, lines):\n img = np.copy(img)\n blank_image = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n\n for line in lines:\n for x1, y1, x2, y2 in line:\n cv2.line(blank_image, (x1, y1), (x2, y2), (255, 0, 0), thickness=3)\n \n img = cv2.addWeighted(img, 0.8, blank_image, 1, 0.0)\n return img\n\n# convert to gray-scale image and apply canny edge detection\ngray_image = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\ncanny_image = cv2.Canny(gray_image, 100, 200)\ncropped_image = region_of_interest(canny_image, \n np.array([region_of_interest_vertices], np.int32))\n\nlines = cv2.HoughLinesP(cropped_image, \n rho = 6,\n theta = np.pi/60,\n threshold = 160,\n lines=np.array([]), \n minLineLength = 40, \n maxLineGap = 25)\n\nimage_with_lines = draw_the_lines(img, lines)\n\nplt.figure(figsize = (10, 10))\nplt.imshow(image_with_lines)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"30.py","file_name":"30.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"321007335","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nparams = {'backend': 'ps',\n 'axes.labelsize': 20,\n 'axes.unicode_minus': False,\n 'text.fontsize': 20,\n 'legend.fontsize': 20,\n 'xtick.labelsize': 20,\n 'ytick.labelsize': 20,\n \"figure.subplot.right\": 0.96,\n \"figure.subplot.top\": 0.96,\n \"figure.subplot.left\": 0.12,\n \"figure.subplot.bottom\": 0.15,\n 'figure.figsize': [7, 4.5],\n 'ps.useafm': True,\n 'pdf.use14corefonts': True,\n 'text.usetex': True\n }\nplt.rcParams.update(params)\n\nw = 0.04\n\n# Y1 = np.array([3,1,4])\n# Y2 = np.array([1,5,9])\n# X = np.array([1,2,3])\nimport plot_dat as pd\n\nplt.bar(pd.X - w/2, pd.Y1, color='b', width=w, label=\"Torque Gradient\", align=\"center\")\nplt.bar(pd.X + w/2, pd.Y2, color='g', width=w, label=\"Pseudo Gradient\", align=\"center\")\n\nplt.legend(loc=\"best\")\nplt.ylabel(\"Frequency\")\nplt.xlabel(\"$\\|Optimal Torque\\|$/$\\|Intial Torque\\|$\")\n\nplt.xticks(pd.X, pd.X)\n\nplt.show()\n","sub_path":"euslisp/torque-gradient/hist.py","file_name":"hist.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"124939778","text":"from operator import attrgetter\nimport pytest\nfrom dbhelpers.address import DbAddress\nfrom pages.account import AccountPage\nfrom pages.addressbook import AddressBookPage\nfrom pages.addaddress import AddAddressPage\nfrom helpers.constants import Returns\nfrom helpers.settings import TEST_DATA\nfrom helpers.data import load_from_json_file\n\n\n@pytest.allure.testcase('https://ssu-jira.softserveinc.com/browse/OPENCARTPY-38')\n@pytest.mark.parametrize(\"address_data\", load_from_json_file(TEST_DATA[\"addressbook_valid\"]))\ndef test_add_correctly_address(init_driver, address_data):\n driver = init_driver\n AccountPage(driver)\\\n .goto_address_book_page()\n with pytest.allure.step(\"Collect address book list from Address Book page.\"):\n previous_address_list = AddressBookPage(driver).get_content_info_from_list()\n with pytest.allure.step(\"Collect id's list from Address Book page.\"):\n previous_ui_ids_list = AddressBookPage(driver).get_list_of_ids()\n with pytest.allure.step(\"Create new address book record.\"):\n AddressBookPage(driver)\\\n .goto_add_address_page()\\\n .fill_address_form(address_data)\n with pytest.allure.step(\"Collect address book list from Address Book page with new record.\"):\n updated_address_list = AddressBookPage(driver).get_content_info_from_list()\n with pytest.allure.step(\"Take information from new address record.\"):\n info_from_new_address = AddressBookPage(driver).get_content_info_from_form(address_data)\n with pytest.allure.step(\"Append info from new record into old list.\"):\n previous_address_list.append(info_from_new_address)\n with pytest.allure.step(\"Collect id's list from Address Book page.\"):\n updated_ui_ids_list = AddressBookPage(driver).get_list_of_ids()\n with pytest.allure.step(\"Collect id's list from db.\"):\n updated_db_ids_list = DbAddress.get_id_list_from_db()\n with pytest.allure.step(\"Compare id's lists.\"):\n assert updated_ui_ids_list == updated_db_ids_list\n with pytest.allure.step(\"Compare len of id's lists.\"):\n assert len(previous_ui_ids_list) + 1 == len(updated_ui_ids_list)\n with pytest.allure.step(\"Retrieving info about successfully added address.\"):\n assert AddressBookPage(\n driver).get_alert_message_text() == Returns.TEXT_SUCCESS_ADDRESS_ADDED\n with pytest.allure.step(\"Compare old and new content lists.\"):\n assert sorted(previous_address_list, key=attrgetter(\n 'content')) == sorted(updated_address_list, key=attrgetter('content'))\n\n\n@pytest.allure.testcase('https://ssu-jira.softserveinc.com/browse/OPENCARTPY-43')\n@pytest.mark.parametrize(\"data\", load_from_json_file(TEST_DATA[\"addressbook_invalid\"]))\ndef test_add_incorrectly_address(init_driver, data):\n driver = init_driver\n with pytest.allure.step(\"Collect id's list from db.\"):\n previous_db_ids_list = DbAddress.get_id_list_from_db()\n AccountPage(driver)\\\n .goto_address_book_page()\\\n .goto_add_address_page()\\\n .fill_address_form(data)\n with pytest.allure.step(\"Collect new id's list from db.\"):\n updated_db_ids_list = DbAddress.get_id_list_from_db()\n with pytest.allure.step(\"Compare id's lists.\"):\n assert previous_db_ids_list == updated_db_ids_list\n with pytest.allure.step(\"Check error message in the 'First Name' field.\"):\n assert AddAddressPage(\n driver).get_firstname_error() == Returns.TEXT_DANGER_FIRST_NAME_INVALID\n with pytest.allure.step(\"Check error message in the 'Last Name' field.\"):\n assert AddAddressPage(\n driver).get_lastname_error() == Returns.TEXT_DANGER_LAST_NAME_INVALID\n with pytest.allure.step(\"Check error message in the 'Address 1' field.\"):\n assert AddAddressPage(\n driver).get_address1_error() == Returns.TEXT_DANGER_ADDRESS1_INVALID\n with pytest.allure.step(\"Check error message in the 'City' field.\"):\n assert AddAddressPage(\n driver).get_city_error() == Returns.TEXT_DANGER_CITY_INVALID\n with pytest.allure.step(\"Check error message in the 'Post Code' field.\"):\n assert AddAddressPage(\n driver).get_postcode_error() == Returns.TEXT_DANGER_POSTCODE_INVALID\n with pytest.allure.step(\"Check error message in the 'Country' drop down option.\"):\n assert AddAddressPage(\n driver).get_region_error() == Returns.TEXT_DANGER_REGION_STATE_INVALID\n","sub_path":"tests/user/test_add_address.py","file_name":"test_add_address.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"324585046","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\n\n# Data for a three-dimensional line\nzline = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nxline = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nyline = [1, 2, 3, 4, 1, 6, 7, 8, 9]\nax.plot3D(xline, yline, zline)\n\n# Data for three-dimensional scattered points\n# zdata = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n# xdata = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n# ydata = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n# zdata = []\n# xdata = []\n# ydata = []\n# ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens');\n\nfig.show()\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"369652626","text":"import sys\nfrom data_check import *\n\ntxt_file = sys.argv[1]\n# txt_file = 'test_3.txt'\nwith open(txt_file, 'r') as file:\n data = file.read()\n if syntax_correct(data):\n lines = create_line_dict(data)\n for line in lines.values():\n if not line.check_data():\n print(f'There is no start or end stop for the line: {line.line_nr}.')\n break\n else:\n stops = create_stop_dict(data)\n get_statistics(stops)\n try:\n arrival_time_test(data)\n except TypeError:\n pass\n else:\n get_invalid_stops(create_stop_dict(data))\n else:\n exit(0)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"34990808","text":"import torch\nimport random\nimport torch.nn.functional as F\n\ndef softmax(x):\n e = torch.exp(x - torch.max(x))\n return e / torch.sum(e)\ndef my_sigmoid(x): # Производная в нуле равна 1\n return 40 / (1 + torch.exp(-0.1 * x))\n\nclass Network:\n def __init__(self, nominals, layersCount, alpha):\n self.nominals = torch.tensor(nominals, dtype=torch.float64, requires_grad=True)\n self.layers = [torch.tensor([10] * len(nominals), dtype=torch.float64, requires_grad=True) for i in range(layersCount)]\n self.alpha = alpha\n def clear_gradient(self):\n self.nominals.detach()\n self.nominals.requires_grad_(True)\n for i in range(len(self.layers)):\n self.layers[i].detach()\n self.layers[i].requires_grad_(True)\n def get_p(self, x):\n return softmax(self.layers[0] + torch.sigmoid(x * self.layers[1]) * self.layers[2])\n def update_layers(self):\n with torch.no_grad():\n for i in range(len(self.layers)):\n self.layers[i] = self.layers[i] - self.alpha * self.layers[i].grad\n def teach(self, x):\n self.clear_gradient()\n x1 = x\n p = self.get_p(x)\n while True:\n p = self.get_p(x1)\n const_alpha = 1\n delta = torch.sum(self.nominals * (p ** const_alpha)) / torch.sum(p ** const_alpha)\n if x1 - delta <= 0:\n break\n x1 = x1 - delta\n loss = 1 / len(self.nominals) * torch.sum((x1 - self.nominals) ** 2 * p)\n loss.backward()\n self.update_layers()\n return loss.item()\n\nif __name__ == \"__main__\":\n random.seed(1)\n result = []\n nominals = [1, 2, 5, 10]\n network = Network(nominals, 3, 0.01)\n for i in range(1000):\n x = random.randint(0, 100)\n if (x == 50):\n result.append((i, network.teach(x)))\n else:\n network.teach(x)\n # if i % 100 == 0:\n # print(network.layers)\n print(result)\n print(network.get_p(5000))\n print(nominals)\n test = 1\n while (test != -100):\n test = int(input())\n while test > 0:\n print(network.get_p(test))\n test -= nominals[int(input())]\n print(test)\n","sub_path":"Practice/SecondTask.py","file_name":"SecondTask.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"216859979","text":"import pygame, time\npygame.init()\n\nwin = pygame.display.set_mode((1920,1080))\n\npygame.display.set_caption(\"Escape the building!\")\n\nwalkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'), pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'), pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]\nwalkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'), pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'), pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]\nsmallkey = pygame.image.load('smallkey.jpeg')\nchar = pygame.image.load('standing.png')\n\nclock = pygame.time.Clock()\n\nx = 1300\ny = 700\nwidth = 64\nheight = 64\nisJump = False\njumpCount = 10\nleft = False\nright = False\nwalkCount = 0\nkey_found = False\npwr = 0\nmyfont = pygame.font.SysFont(\"Times New Roman\", 50)\ntext = myfont.render(f'x {key_found}', 1, (10,10,10))\nrun = True\nbg = pygame.image.load(\"walls_base_img.jpg\")\nbg = pygame.transform.scale(bg, (1900, 1060))\ng = pygame.image.load(\"floor.jpeg\")\ng = pygame.transform.scale(g, (1500, 760))\nld = pygame.image.load(\"locked-door.png\")\nld = pygame.transform.scale(ld, (770,440))\nd = pygame.image.load(\"door.png\")\nd = pygame.transform.scale(d, (770,440))\nsmallkey = pygame.transform.scale(smallkey, (70, 70))\npleft = False\npright = False\npstanding = True\nroom = 1\nvel = 5\nwalkCount = 0\ndct = {\"1\" : \"k n n 1l n\"} # keys = room numbers, values = \"object up right down left\")\"\ndct2 = {\"1l\": \"l\"}\n#mainloop\n\n\n\ndef redrawGameWindow(walkCount, key_found, x, y, room):\n \n win.blit(bg, (0,0))\n win.blit(g, (210, 170))\n #keys2 = myfont.render(f\" x {keys}\", False, (0, 0, 0))\n #win.blit(keys2, (0, 780))\n if room != 15:\n parts = dct[str(room)].split()\n if parts[0] == \"k\":\n# print(ll)\n# \n if not key_found:\n print(\"yeahblit\")\n win.blit(smallkey, (410, 410))\n if x > 360 and x < 460 and y > 360 and y < 460: \n #print(\"flag\")\n key_found = True\n \n if parts[1] == \"d\":\n win.blit(d, (750, 50))\n elif parts[1] in dct2.keys():\n win.blit(ld, (750, 50))\n if parts[2] == \"d\":\n win.blit(d, (1800, 450))\n elif parts[2] in dct2.keys():\n win.blit(ld, (1800, 450))\n if parts[3] == \"d\":\n win.blit(d, (750, 950))\n elif \"1l\" in dct2.keys():\n i = parts[3]\n c = dct2[i]\n #print(c)\n if c == \"l\":\n win.blit(ld, (600, 700))\n print(x, y)\n if x > 700 and x < 800 and y > 700 and y < 800 and key_found:\n print(\"Sharp\")\n dct2[\"1l\"] = \"o\"\n key_found = False\n if c == \"o\":\n win.blit(d, (600, 700))\n if x > 550 and x < 650 and y > 650 and y < 750:\n pass\n # room += 3\n # y -= 300\n if parts[4] == \"d\":\n win.blit(d, (1800, 50))\n elif parts[4] in dct2.keys():\n win.blit(ld, (1800, 50))\n\n #if room == 1: # Bring to front\n # win.blit(ld, (600,700))\n if pleft: \n r = pygame.transform.scale(walkLeft[int((walkCount % 27)/3)], (128, 128))\n win.blit(r, (x,y))\n walkCount += 1 \n elif pright:\n r = pygame.transform.scale(walkRight[int((walkCount % 27)/3)], (128, 128))\n win.blit(r, (x,y))\n walkCount += 1\n else:\n r = pygame.transform.scale(char, (128, 128))\n win.blit(r, (x, y))\n pygame.display.update()\n #print(f\"{key_found=}\")\n return key_found\n\n\nrun = True\nwhile run:\n #print(f\"ks: {key_found}\")\n clock.tick(27)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n key = pygame.key.get_pressed()\n if key[pygame.K_LEFT] and x > vel:\n x -= vel\n pleft = True\n pright = False\n walkCount += 1\n elif key[pygame.K_RIGHT] and x < 1720 - width - vel:\n x += vel\n pright = True\n pleft = False\n walkCount += 1\n elif key[pygame.K_DOWN] and y < 980 - height - vel:\n y += vel\n pright = False\n pleft = False \n elif key[pygame.K_UP] and y > vel:\n y -= vel\n pright = False\n pleft = False\n #print(f\"3, {key_found}\") \n key_found = redrawGameWindow(walkCount, key_found, x, y, room)\n\n","sub_path":"EscapeBuilding/walk2d.py","file_name":"walk2d.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"119505505","text":"numbers = input().split()\r\nnumbers = [int(x) for x in numbers]\r\n\r\n\r\ndef check(a):\r\n while a > 0:\r\n if (a%100)%11 == 0:\r\n return 1\r\n else:\r\n a = int(a/10)\r\n return 0\r\n\r\ncount = 0\r\n\r\nfor x in range (numbers[0],numbers[1]+1):\r\n count += check(x)\r\n \r\nprint (count)\r\n\r\n\r\n","sub_path":"albert.py","file_name":"albert.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"284721049","text":"##\nimport os, sys, subprocess as sp\n\n##\ndirs = [o for o in os.listdir() if os.path.isdir(o)]\nfs = [(d,f) for d in dirs for f in os.listdir(d) if f.endswith('.lif')]\n\n##\n\nbfconvert_path = '/Users/ben/code/klm/project2/lif2tif/bftools/bfconvert'\n\nfor d,f in fs:\n rootname = os.path.splitext(f)[0]\n inpath = os.path.join(d,f)\n outname = '{}_%s.tif'.format(rootname)\n outpath = os.path.join(d, outname)\n print(inpath, outpath)\n sp.call([\"sh\", bfconvert_path, inpath, outpath])\n\n##\n","sub_path":"project3/lif2tif.py","file_name":"lif2tif.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"336319529","text":"import re\r\nimport tweepy #python client for Twitter API\r\nfrom tweepy import OAuthHandler\r\nfrom textblob import TextBlob # processing textual data\r\n\r\nclass TwitterClient(object):\r\n def __init__(self):\r\n consumer_key = 'FMU7zw9hzxaFDPLi9jUcfJqVj'\r\n consumer_secret = 'TdMAAOVKvgIoKthKdYLez8mRY7IeBLP6yHGGvp0P1TvGIwHcns'\r\n access_token = '912060138600697856-UMJSMQyntuI3t5Hfjgvk7STpwD9mPiH'\r\n access_token_secret = '45FgXJV5YwSFayKZwvU196VhEPOYlzpTiCPkTvbinQkQq'\r\n \r\n # attempt authentication\r\n try:\r\n # create OAuthHandler object\r\n self.auth = OAuthHandler(consumer_key,consumer_secret)\r\n self.auth.set_access_token(access_token,access_token_secret)\r\n \r\n # create tweepy API object to fetch tweets\r\n self.api = tweepy.API(self.auth)\r\n except:\r\n print(\"Error: Authentication Failed\")\r\n \r\n def clean_tweet(self,tweet):\r\n \r\n # utility function to clean tweets text by removing links, special characters\r\n return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\",\r\n \" \",tweet).split())\r\n \r\n def get_tweet_sentiment(self,tweet):\r\n analysis = TextBlob(self.clean_tweet(tweet))\r\n \r\n if analysis.sentiment.polarity > 0:\r\n return 'positive'\r\n elif analysis.sentiment.polarity == 0:\r\n return 'neutral'\r\n else:\r\n return 'negative'\r\n \r\n def get_tweets(self,query,count = 10):\r\n \r\n tweets = []\r\n \r\n try:\r\n fetched_tweets = self.api.search(q=query,count = count)\r\n \r\n # parsing tweets one by one\r\n for tweet in fetched_tweets:\r\n \r\n # dict to store the params of a tweet\r\n parsed_tweet = {}\r\n parsed_tweet['text'] = tweet.text\r\n parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)\r\n \r\n # appending parsed tweet to tweets list\r\n if tweet.retweet_count > 0:\r\n # if tweet has retweets, ensure that it is appended only once\r\n if parsed_tweet not in tweets:\r\n tweets.append(parsed_tweet)\r\n else:\r\n tweets.append(parsed_tweet)\r\n return tweets\r\n except tweepy.TweepError as e:\r\n print(\"Error:\" + str(e))\r\n \r\n \r\ndef main():\r\n api = TwitterClient()\r\n \r\n tweets = api.get_tweets(query = 'Donald Trump', count = 200)\r\n \r\n # picking positive tweets from tweets\r\n ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']\r\n print(\"Positive tweets percentage:{}%\".format(100*len(ptweets)/len(tweets)))\r\n \r\n ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']\r\n print(\"Negative tweets percentage:{}%\".format(100*len(ntweets)/len(tweets)))\r\n \r\n print(\"Neutral tweets percentage:{}%\".format(100*(len(tweets)- len(ptweets) - len(ntweets))/len(tweets)))\r\n \r\n # printing the five positive and negative tweets\r\n print(\"\\n\\nPositive tweets:\")\r\n for tweet in ptweets[:5]:\r\n print(tweet['text'])\r\n \r\n print(\"\\n\\nNegative tweets:\")\r\n for tweet in ntweets[:5]:\r\n print(tweet['text'])\r\n \r\n \r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"pythoncode/sentiment_analysis_twitter_2017.py","file_name":"sentiment_analysis_twitter_2017.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"578263273","text":"# Binary search - Search a sorted array by repeatedly dividing the \n# search interval in half.\n# Time complexity - O(logn)\n\n# 1. Recursive Binary Search\ndef binary_search(arr, left, right, num):\n\n # Check base case\n if right >= left:\n\n mid = int(left + (right - left)/2)\n\n # If element is present at the middle itself\n if arr[mid] == num:\n return mid\n\n # If element is smaller than mid, then it can only\n # be presennt in left subarray\n elif arr[mid] > num:\n return binary_search(arr, left, mid - 1, num)\n\n # Else the element can only be present in right subarray\n else:\n return binary_search(arr, mid + 1, right, num)\n\n else:\n # Element is not present in the array\n return -1\n\n# Test array\narr1 = [2, 3, 4, 10, 40]\nx1 = 10\n\n# Function call\nresult = binary_search(arr1, 0, len(arr1) - 1, x1)\n\nif result != -1:\n print(\"Element is present at index {}\".format(result))\nelse:\n print(\"Element is not present in array\")\n","sub_path":"searching_and_sorting/binary_search_recursive.py","file_name":"binary_search_recursive.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"9041107","text":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport os\n\ndef readData(path):\n for filename in os.listdir(path):\n if filename == 'X.csv':\n fileX = np.genfromtxt(path+'/'+filename, delimiter=',')\n elif filename == 'Y.csv':\n fileY = np.genfromtxt(path+'/'+filename, delimiter=',')\n\n return fileX, fileY\n\n\n\n#### LOAD THE DATA ####\n\n# Get the path to load the data in\nPATH = os.getcwd()\npath_train = PATH + '/train'\npath_test = PATH + '/test'\n\ntrainX, trainY = readData(path_train)\ntestX, testY = readData(path_test)\nnum_samples = trainX.shape[0]\nnum_features = trainX.shape[1]","sub_path":"scripts/update_contact_duration.py","file_name":"update_contact_duration.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"555224736","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/arrows_esolang/Statement.py\n# Compiled at: 2019-10-31 01:48:48\n# Size of source mod 2**32: 701 bytes\nfrom enum import Enum\nimport arrows_esolang.Action as A\n__statement_label__ = 0\n\nclass NodeType(Enum):\n ACTION = 0\n CONDITIONAL = 1\n\n\nclass Statement(object):\n\n def __init__(self):\n global __statement_label__\n self.kind = None\n self.if_zero = None\n self.if_else = None\n self.next = None\n self.actions = []\n self.label = __statement_label__\n __statement_label__ += 1\n\n def add_add(self, register):\n if register > 0:\n self.actions.append(A.Action(A.ActionType.ADD, register))\n\n def add_action(self, kind, register):\n self.add_add(register)\n self.actions.append(A.Action(kind))","sub_path":"pycfiles/arrows_esolang-1.0.2-py3.7/Statement.cpython-37.py","file_name":"Statement.cpython-37.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"193529916","text":"from django.urls import path\nfrom . import views\n\n\napp_name = 'stock'\n\nurlpatterns = [\n path('', views.MainView.index, name='index'),\n path('create/', views.AddView.create, name='create'),\n path('add_product/', views.MainView.add_product, name='add_product'),\n path('delete//', views.delete, name='delete'),\n path('edit//', views.MainView.edit, name='edit'),\n path('update//', views.EditView.update, name='update'),\n\n]\n\n","sub_path":"LAB7/app/stock/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"305613397","text":"from src.date import Date\n\n\ndef get_dates_diff(date1, date2):\n try:\n log(date1)\n log(date2)\n d1 = Date(date1)\n d2 = Date(date2)\n return d1 - d2, ''\n except Exception as e:\n log(e)\n return -1, e\n\n\ndef log(msg):\n print(msg)\n","sub_path":"src/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"443291453","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nlength=0.2\nm=1\nsiguma=0.05\n\n\n\nclass GPIS:\n def __init__(self):\n self.X = np.load(\"X_250.npy\")\n self.Y = np.load(\"Y_250.npy\")\n\n self.X = np.delete(self.X, -1, 0)\n\n print(self.X)\n print(self.X.max())\n\n\n # print self.X.T[0]\n # print max(self.X.T[2])\n # print min(self.X.T[2])\n # self.X = self.X[:50]\n # self.Y = self.Y[:50]\n\n # self.x = np.array([X[X.shape[0]-1]]).T\n self.zeros = np.zeros((self.X.shape[0],self. X.shape[0]))\n # print(self.X.shape)\n # print(np.shape(self.X))\n # print(np.shape(self.Y))\n \"\"\"カーネル行列の作成\"\"\"\n Kernel_x = np.zeros((self.X.shape[0], self.X.shape[0]))\n for i in range(self.zeros.shape[0]):\n for j in range(self.zeros.shape[0]):\n Kernel_x[i][j] = self.kernel_func(self.X[i], self.X[j]) #K\n\n # print Kernel_x\n G = Kernel_x + siguma*siguma * np.identity(self.zeros.shape[0])\n self.invG = np.linalg.inv(G)\n\n self.b = np.dot(self.invG, self.Y - m)\n\n\n\n def kernel_func(self, x1, x2): #kernel\n norumu2 = np.linalg.norm(x1-x2)\n kernel = pow(norumu2*norumu2 + length*length, -1/2)\n return kernel\n\n def predict_func(self,x):\n self.x = x\n\n \"\"\"カーネルとカーネルの微分の列ベクト作成\"\"\"\n kernel_x = np.zeros((self.X.shape[0]))\n for i in range(self.zeros.shape[0]):\n kernel_x[i] = self.kernel_func(self.X[i], self.x) #k(x)\n kernel_x = np.array([kernel_x]).T\n # print \"kernel:\", kernel_x\n\n \"\"\"平均と分散\"\"\"\n mean = m + np.dot(kernel_x.T, self.b)\n # var = 1/length - np.dot(np.dot(kernel_x.T, self.invG), kernel_x)\n\n # if np.round((mean), 2) == 0:\n # gp_mean = 0\n # else:\n # gp_mean = -1\n\n # return gp_mean\n return mean\n\n\nif __name__ == '__main__':\n # x = np.array([1,1,1])\n gpis = GPIS()\n num = 100\n\n mean_zero = np.array([])\n # positions = []\n # mean_zero_position = []\n\n x = np.linspace(0.34, 0.46, num)\n y = np.linspace(-0.06, 0.06, num)\n z = np.linspace(1.3, 1.33, num)\n # X, Y, Z = np.meshgrid(x, y, z)\n X, Y = np.meshgrid(x, y)\n\n # x_lim = []\n # y_lim = []\n # z_lim = []\n #\n # for i in range(num):\n # for j in range(num):\n # if (x[i]-0.4)**2 + y[j]**2 < 0.0025:\n # x_lim.append(x[i])\n # y_lim.append(y[i])\n # z_lim.append(z[i])\n\n Z = np.zeros((num, num))\n\n count = 0\n cnt = 0\n for i in range(num):\n for j in range(num):\n for k in range(num):\n # po = np.array([x[i],y[j],z[k]])\n po = np.array([X[i][j],Y[i][j],z[k]])\n\n mean_value = abs(gpis.predict_func(po))\n\n\n mean_zero = np.append(mean_zero,mean_value)\n count += 1\n print(\"count:\", count)\n # print(\"mean_value\", mean_value)\n\n # print(mean_zero)\n n = np.argmin(mean_zero)\n # print(n)\n # print z[n]\n Z[i][j] = z[n]\n # print z_lim\n\n mean_zero = np.array([])\n\n\n mean_zero_position = np.array([X,Y,Z])\n print(mean_zero_position)\n np.save(\"mean_zero_250\", mean_zero_position)\n\n\n\n\n\n # mean_zero_position.append(positions[n])\n # positions = []\n # mean_zero = np.array([])\n\n # print(\"zero_num\", cnt)\n\n # print np.shape(mean_zero_position)\n # # for i in range(num):\n # for j in range(num):\n # for k in range(num):\n # po = np.array([X[i][j][k], Y[i][j][k], Z[i][j][k]])\n # gpis = GPIS(po)\n # mean_value = gpis.predict_func()\n # if mean_value == 0:\n # mean_zero.append(po)\n\n\n # print(mean_zero)\n # print(X.shape)\n #\n\n # gpis = GPIS(x)\n # mean_value = gpis.predict_func()\n # print(mean_value)\n","sub_path":"ur5/example/sliding_sim_11_25/gpis250/gpis_surpace.py","file_name":"gpis_surpace.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"195882496","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\n@author: zhaogao\n@license: (C) Copyright 2013-2018.\n@contact: 449628536@qq.com\n@software: learn-py\n@file: len91_序列化python对象.py\n@time: 05/03/2018 11:13 AM\n'''\n\n# 你需要将一个python对象序列化为一个字节流, 以便将它保存到一个文件、存储 到数据库或者通过网络传输它\n# 对于序列化最普遍的做法就是使用 pickle 模块\n\nimport pickle\n\npath_value = '/Users/zhaogao/PycharmProjects/learn-py/cook/data/len91_somefile'\n\ndata = {'name': ['v1', 'v2']}\nf = open(path_value, 'wb')\npickle.dump(data, f)\n\ns = pickle.dumps(data)\nprint(s)\n\n# restore from a file\nf = open(path_value, 'rb')\ndata = pickle.load(f)\nprint(data)\n\n# restore from a string\ndata = pickle.loads(s)\nprint(data)\n\n# 通过自描述,被序列化后的数据 包含每个对象开始和结束以及它的类型信息\n\nf = open(path_value, 'wb')\npickle.dump([1, 2, 3, 4], f)\npickle.dump('hello', f)\npickle.dump({'Apple', 'Pear', 'Banana'}, f)\nf.close()\n\nf = open(path_value, 'rb')\nvalue = pickle.load(f)\nprint(value)\n\nvalue = pickle.load(f)\nprint(value)\n\nvalue = pickle.load(f)\nprint(value)\n\nimport math\nvalue=pickle.dumps(math.cos)\nprint(value)","sub_path":"cook/len91_序列化python对象.py","file_name":"len91_序列化python对象.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"261518886","text":"import numpy as np\nfrom time import sleep\n\nclass OhmLaw:\n def __init__(self):\n self.data = np.zeros(0)\n self.step = 0\n self.running = False\n self.stop = False\n\n def make_measurement(self, start, stop, num_points, delay):\n if self.running:\n raise Exception(\"Can't make more than one measurement simultaneously\")\n\n x_axis = np.linspace(start, stop, num_points)\n self.data = np.zeros(num_points)\n self.step = 0\n self.running = True\n for i in x_axis:\n if self.stop:\n print(\"Stopping\")\n break\n self.data[self.step] = np.random.random()\n self.step += 1\n sleep(delay)\n\n self.running = False\n return self.data\n\nif __name__ == \"__main__\":\n ohm = OhmLaw()\n result = ohm.make_measurement(0, 1, 11, 1)\n print(result)","sub_path":"threadsForMeasurements/simpleMeasurementClass.py","file_name":"simpleMeasurementClass.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"190544812","text":"##################################################################################\r\n# This code fit the ANN model\r\n# Provide various plots of the model \r\n##################################################################################\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\nimport matplotlib.cm as cm\r\nimport matplotlib as mpl\r\nimport matplotlib.gridspec as gridspec\r\nfrom scipy import ndimage\r\nimport numpy as np\r\nimport os\r\nfrom scipy import stats#.linregress\r\nimport pickle\r\nfrom sklearn import decomposition\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.datasets import make_moons, make_circles, make_classification\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn.neural_network import MLPRegressor\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.svm import SVR\r\nfrom sklearn.kernel_ridge import KernelRidge\r\nfrom sklearn.gaussian_process import GaussianProcessClassifier\r\nfrom sklearn.gaussian_process.kernels import RBF\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\r\nfrom matplotlib.colors import ListedColormap\r\nfrom mpl_toolkits.mplot3d import axes3d\r\nfrom . import LoadImagFiles\r\nimport sys\r\n\r\n\r\nis_three = False\r\nif (sys.version_info > (3, 0)):\r\n\tis_three = True\r\n\t\r\n\t\r\nfontsize = 18\r\nis_raw_data = True\r\nis_trained_data = True\r\nsig = 1\r\n\r\n\r\nX = []\r\n\r\ndef run(params, absFilePath):\r\n\tglobal sequence, channels, W, solv, data_sub, base, date\r\n\tglobal dirs, folder, folder_correct\r\n\tglobal S, list_pH\r\n\r\n\tprint (\"----------------------------------\")\r\n\tprint (\"TRAIN NEURAL NET FOR PH PREDICTION: \")\r\n\tprint (\" \")\r\n\tprint (\"-----------------------------------\")\r\n\tprint (\"\")\r\n\r\n\t############################################################################\r\n\t# Model parameters\r\n\t############################################################################\r\n\tsequence = params[\"sequence\"] \r\n\t\t\t\t\t\t\t\t\t# change only x / y to check if it improves\r\n\tchannels = params[\"channels\"]\t#[\"a\",\"b\",\"c\",\"d\"]\t# names of the channels: do not changes\r\n\t\r\n\tW = params[\"W\"]\t\t\t\t\t#100 \t\t\t\t\t\t# number of hidden layers\r\n\tsolv = params[\"solv\"]\t\t\t#'lbfgs' #'adam'#\t\t\t# type of solver 'sgd', \r\n\tdata_sub = params[\"data_sub\"]\t#5\t\t\t\t\t# sub sampling of the data to save time\r\n\r\n\t# Base files\r\n\tbase = params[\"base\"]\t\t\t#\"E:\\\\PROGRAMS\\\\SENSOILs\\\\calibration\\\\\"\r\n\tdate = params[\"date calibration\"]\t\t\t#\"20190626\" \t\t\t\t#\"20190822\"\r\n\t\r\n\t############################################################################\r\n\t# Get info from files\r\n\t###########################################################################\r\n\r\n\tfolder = base + date+\"_Daniel_pHContr\\\\\"\r\n\t\r\n\tdirs = os.listdir(folder)\r\n\tdirs.sort()\r\n\tdel dirs[-1]\t\t\t\t\t\t\t\t# remove the last pH (because it's weird)\r\n\r\n\t# Model\r\n\tmodel_code = solv\r\n\txy = []\r\n\tif 0 in sequence: xy.append(\"X\")\r\n\tif 1 in sequence: xy.append(\"Y\")\r\n\tmodel_code += str(len(sequence) - len(xy)) + \"F_\"\r\n\tfor s in xy: model_code += s\r\n\tmodel_code += \"_W\" + str(W)\r\n\r\n\tfolder_correct = absFilePath + \"histograms\\\\\"\r\n\tdir_models = absFilePath + \"models\\\\\" + date + \"\\\\\" + model_code + \"\\\\\"\r\n\tprint( dir_models)\r\n\tif not os.path.isdir(dir_models):\r\n\t\tos.mkdir(dir_models)\r\n\r\n\t# ROI\r\n\tdir_ROI = absFilePath + \"ROI\\\\\" + date + \"\\\\\"\r\n\r\n\r\n\r\n\t#############################################################################\r\n\t# Initiate data structure\r\n\t#############################################################################\r\n\tn_input = len(sequence)\r\n\tdir0 = \"\"\r\n\tDATA = []\r\n\tDATA_TOT = np.array([])\r\n\tPH = np.array([])\r\n\tlist_pH = []\r\n\r\n\t#--------------------------------------------------------------------------------------\r\n\t# Get image size\r\n\tfile = folder + dirs[0] + \"\\\\LOOP_0\\\\Z_Window_z1\\\\\"+channels[0]+\"_0.tif\"\r\n\timg=LoadImagFiles.Load(file, folder_correct)#mpimg.imread(file)\r\n\tS = np.shape(img)\r\n\r\n\t#--------------------------------------------------------------------------------------\r\n\t# Get pH values\r\n\t\r\n\tfor d in dirs:\r\n\t\tblock_c = []\r\n\t\tnum = (d.split(\"pH\")[2]).split(\"_\")\r\n\t\tpH = float(num[0]) + 0.01*float(num[1]) \r\n\t\tprint (\" pH found: \", pH)\r\n\t\t\r\n\t\tlist_pH.append(pH)\t\r\n\r\n\t############################################################################\r\n\t# Read data\r\n\t###########################################################################\r\n\tcsv_files = os.listdir(dir_ROI)\r\n\tfor j in range(len(csv_files)):\r\n\t\tprint (\"Get Calibration data \", j)\r\n\t\t\r\n\t\t#--------------------------------------------------------------------------------------\r\n\t\t# Read maxima points\r\n\t\tPTS_X = [() for i in range(len(dirs))]\r\n\t\tPTS_Y = [() for i in range(len(dirs))]\r\n\r\n\t\tf = open(dir_ROI + \"Point_Selection_on_coating\" +str(j+1) + \".csv\")\r\n\t\tfor line in f:\r\n\t\t\trow = line.split(\",\")\r\n\t\t\tif \"Slice\" in row[3]:\r\n\t\t\t\tpass\r\n\t\t\telif int(row[3]) == 0 or int(row[3]) == 11 :\r\n\t\t\t\tpass\r\n\t\t\telse:\r\n\t\t\t\tind = int(row[3]) - 1\r\n\t\t\t\tPTS_X[ind] = PTS_X[ind] + (int(row[1]),)\r\n\t\t\t\tPTS_Y[ind] = PTS_Y[ind] + (int(row[2]),)\r\n\r\n\t\t#--------------------------------------------------------------------------------------\r\n\t\tfor i in range(len(dirs)):\r\n\t\t\td = dirs[i]\r\n\t\t\tblock_c = []\r\n\t\t\tnum = (d.split(\"pH\")[2]).split(\"_\")\r\n\t\t\tpH = float(num[0]) + 0.01*float(num[1]) \r\n\t\t\t\r\n\r\n\t\t\tptsX = np.array(PTS_X[i])#[index]\r\n\t\t\tptsY = np.array(PTS_Y[i])#[index]\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tD = []\r\n\t\t\tD.append(np.array(ptsX))\r\n\t\t\tD.append(np.array(ptsY))\r\n\t\t\tfor c in channels:\r\n\t\t\t\tfile = folder + d + \"\\\\LOOP_0\\\\Z_Window_z\" + str(j + 1) + \"\\\\\"+c+\"_0.tif\"\r\n\t\t\t\timg = LoadImagFiles.Load(file, folder_correct,c)\r\n\t\t\t\t#img=mpimg.imread(file)\r\n\t\t\t\t##img = ndimage.median_filter(img, size=10)\r\n\t\t\t\t#img = ndimage.gaussian_filter(img, sigma=sig)\r\n\t\t\t\tD.append(np.array(img[(ptsX,ptsY)]))\r\n\t\t\tD.append(np.array((ptsX))*0+pH)\r\n\t\t\tD = np.array(D)\r\n\t\t\t\r\n\t\t\tif pH < 7.2:\r\n\t\t\t\tif len(DATA_TOT) == 0:\r\n\t\t\t\t\trng = [0]\r\n\t\t\t\t\tDATA_TOT = D\r\n\t\t\t\telse:\r\n\t\t\t\t\trng = [len(DATA_TOT[0,:])]\r\n\t\t\t\t\tDATA_TOT = np.concatenate((DATA_TOT,D),axis = 1)\r\n\t\t\t\trng.append(len(DATA_TOT[0,:]) - 1)\r\n\t\t\t\tDATA.append(rng)\r\n\t\t\t##############################################################################\r\n\t\t\t#np.save (\"X\", DATA)\r\n\t\t\t#np.save (\"Y\", PH)\r\n\t\t\t#np.save (\"list_pH\", list_pH)\r\n\t\t\t#np.save (\"s_im_smpl\", s_im_smpl)\r\n\t\t\t#DATA = np.array(DATA)\r\n\t\tf.close()\r\n\t\t\r\n\r\n\r\n\r\n\t############################################################################\r\n\t# Ratiometric Analysis\r\n\t###########################################################################\r\n\t# from sklearn.linear_model import LinearRegression\t\r\n\t# Xr = DATA_TOT[2,::data_sub]/DATA_TOT[5,::data_sub]\r\n\r\n\t##model = SVR(C=0.01)## KernelRidge(alpha=1.0)# LinearRegression() #\r\n\t# model = MLPRegressor(alpha=1.0, max_iter=1000, hidden_layer_sizes = (9,9,9), activation = 'tanh')\r\n\t# model.fit(Xr.reshape(1,-1).transpose(), Y)\r\n\t# y_pred = model.predict(Xr.reshape(1,-1).transpose())\r\n\r\n\t# plt.figure(1)\r\n\t# ax = plt.subplot(1, 1, 1)\r\n\t# ax.plot(Xr, DATA_TOT[6,::data_sub] ,'+')\r\n\t# xx = np.arange(0.3,1.5,0.01).reshape(1,-1).transpose()\r\n\t# ax.plot(xx, model.predict(xx),'r-', linewidth = 3)\r\n\t# ax.set_xlabel(\"wavelength ratio\",fontsize=fontsize)\r\n\t# ax.set_ylabel(\"pH\",fontsize=fontsize)\r\n\t# for ii in range(2):\r\n\t\t# for tick in ax.xaxis.get_major_ticks():\r\n\t\t\t# tick.label1.set_fontsize(fontsize)\r\n\t\t# for tick in ax.yaxis.get_major_ticks():\r\n\t\t\t# tick.label1.set_fontsize(fontsize)\r\n\r\n\t# plt.figure(2)\r\n\t# ax = plt.subplot(1, 1, 1)\r\n\t# plot_actual_predict(ax, Y, y_pred, X)\r\n\t# for ii in range(2):\r\n\t\t# for tick in ax.xaxis.get_major_ticks():\r\n\t\t\t# tick.label1.set_fontsize(fontsize)\r\n\t\t# for tick in ax.yaxis.get_major_ticks():\r\n\t\t\t# tick.label1.set_fontsize(fontsize)\r\n\r\n\t# plt.show()\r\n\t# plot_maps_ratio(dirs,model, None, None,[2,5])\r\n\t# ############################################################################\r\n\t# # Learning\r\n\t# ###########################################################################\r\n\t# DATA_TOT indices\r\n\r\n\r\n\tX = DATA_TOT[sequence,::data_sub].transpose()\r\n\tY = DATA_TOT[6,::data_sub]\r\n \r\n \r\n\tif is_trained_data == False:\r\n\t\t# Pre-process (PCA + normalisation)\r\n\t\tpca = decomposition.PCA(n_components=n_input)\r\n\r\n\t\tif n_input == 2:\r\n\t\t\tXp = X\r\n\t\t\tpca.fit(Xp)\r\n\t\t\tpickle.dump(pca, open( dir_models + \"pca.p\", \"wb\" ) )\r\n\t\t\tXp = pca.transform(Xp)\r\n\t\telse:\r\n\t\t\tXp = X\r\n\t\t\tpca.fit(Xp)\r\n\t\t\tpickle.dump(pca, open( dir_models + \"pca.p\", \"wb\" ) )\r\n\t\t\tXp = pca.transform(Xp)\r\n\t\ty = (Y - Y.min()) / (Y.max() - Y.min())\r\n\t\tsc = StandardScaler()\r\n\t\tsc.fit(Xp)\r\n\t\tpickle.dump(sc, open( dir_models + \"transform.p\", \"wb\" ) )\r\n\r\n\t\tX_train = sc.transform(Xp)\t\r\n\t\ty_train = Y.astype('str')\r\n\t\ty_train = Y.astype('float')\t\r\n\t\tX_test = X_train\t\r\n\t\ty_test = Y.astype('str')\t\t\r\n\r\n\t\t# Learn model\r\n\t\tnames = [ \"Neural Net\", ]\r\n\t\tclassifiers = [ MLPRegressor(alpha=0., max_iter=2000, hidden_layer_sizes = (W,W,W), learning_rate_init = 0.001, solver = solv,learning_rate = 'adaptive'),]\r\n\r\n\t\tx_min, x_max = X_train[:, 0].min() - .5, X_train[:, 0].max() + .5\r\n\t\ty_min, y_max = X_train[:, 1].min() - .5, X_train[:, 1].max() + .5\r\n\t\th = .1\r\n\t\txx, yy = np.meshgrid(np.arange(x_min, x_max, h),\r\n\t\t\t\t\t\t\t\t np.arange(y_min, y_max, h))\r\n\t\tcm_RdBu = plt.cm.RdBu\r\n\t\tcm_bright = ListedColormap(['#FF0000', '#0000FF'])\t\t\r\n\t\ti = 1\t\t\t\t \r\n\t\tfor name, clf in zip(names, classifiers):\r\n\t\t\t#######################################################################################################\r\n\t\t\t# Fit and Save model\r\n\t\t\tclf.fit(X_train, y_train)\r\n\t\t\t#score = clf.score(X_test, y_test)\r\n\t\t\t\r\n\t\t\tpickle.dump(clf, open(dir_models + name,'wb'))\r\n\t\t\t\r\n\t\t\t# Plot the data is n == 2\r\n\r\n\t\t\tax = plt.subplot(1, len(classifiers), i)\r\n\t\t\ty_data = Y.astype(float) #+ (np.random.rand(np.shape(Y)[0]) - 0.5) * 0.15\r\n\t\t\ty_pred = clf.predict(X_train).astype(float)\r\n\t\t\tplot_actual_predict(ax, y_data, y_pred, X)\r\n\r\n\t\ti += 1\r\n\t\tplt.show()\r\n\r\n\r\n\r\n\r\n\t# ############################################################################\r\n\t# # Test predictions\r\n\t# ###########################################################################\r\n # data vs prediction plot\r\n\tclf = pickle.load(open(dir_models + \"Neural Net_p3.pkl\", \"rb\"))\r\n\tpca = pickle.load(open(dir_models + \"pca_p3.pkl\", \"rb\"))\r\n\tsc = pickle.load(open(dir_models + \"transform_p3.pkl\", \"rb\"))\r\n \r\n\tax = plt.subplot(1, 1, 1)\r\n\r\n\tif n_input == 2:\r\n\t\tXp = X\r\n\t\tpca.fit(Xp)\r\n\t\tpickle.dump(pca, open( dir_models + \"pca.p\", \"wb\" ) )\r\n\t\tXp = pca.transform(Xp)\r\n\telse:\r\n\t\tXp = X\r\n\t\tpca.fit(Xp)\r\n\t\tpickle.dump(pca, open( dir_models + \"pca.p\", \"wb\" ) )\r\n\t\tXp = pca.transform(Xp)\r\n\tsc = StandardScaler()\r\n\tsc.fit(Xp)\r\n\tpickle.dump(sc, open( dir_models + \"transform.p\", \"wb\" ) )\r\n\r\n\tX_train = sc.transform(Xp)\t\r\n\ty_train = Y.astype('str')\r\n\ty_train = Y.astype('float')\t\r\n\ty_data = Y.astype(float) #+ (np.random.rand(np.shape(Y)[0]) - 0.5) * 0.15\r\n\ty_pred = clf.predict(X_train).astype(float)\r\n\t#export_predictions(y_data, y_pred)\r\n\tplot_actual_predict(ax, y_data, y_pred, X)\r\n\r\n # map\r\n\tplot_maps_pH(dirs, clf,pca,sc,sequence)\r\n\r\n############################################################################\r\n# Plot Functions\r\n###########################################################################\r\ndef make_ticklabels_invisible(fig):\r\n for i, ax in enumerate(fig.axes):\r\n ax.text(0.5, 0.5, \"ax%d\" % (i+1), va=\"center\", ha=\"center\")\r\n for tl in ax.get_xticklabels() + ax.get_yticklabels():\r\n tl.set_visible(False)\r\ndef plot_actual_predict(ax, y_data, y_pred, X):\r\n\t\tz_pred = np.polyfit(y_data, y_pred,1)\r\n\t\tp = np.poly1d(z_pred)\r\n\t\tfit = p(y_data)\r\n\t\t\t\r\n\t\t# get the coordinates for the fit curve\r\n\t\tc_y = [np.min(fit),np.max(fit)]\r\n\t\tc_x = [np.min(y_data),np.max(y_data)]\r\n\t\t\t \r\n\t\t# predict y values of origional data using the fit\r\n\t\tp_y = z_pred[0] * y_data + z_pred[1]\r\n\t\t \r\n\t\t# calculate the y-error (residuals)\r\n\t\ty_err = y_pred -p_y\r\n\t\t \r\n\t\t# create series of new test x-values to predict for\r\n\t\tp_x = np.arange(np.min(y_data),np.max(y_data)+1,1)\r\n\t\t \r\n\t\t# now calculate confidence intervals for new test x-series\r\n\t\tmean_x = np.mean(y_data) # mean of x\r\n\t\tn = len(y_data) # number of samples in origional fit\r\n\t\tt = 2.31 # appropriate t value (where n=9, two tailed 95%)\r\n\t\ts_err = np.sum(np.power(y_err,2)) # sum of the squares of the residuals\r\n\t\t \r\n\t\tconfs = t * np.sqrt((s_err/(n-2))*(1.0/n + (np.power((p_x-mean_x),2)/\r\n\t\t\t\t\t((np.sum(np.power(y_data,2)))-n*(np.power(mean_x,2))))))\r\n\t\tconfs = t * np.sqrt( (s_err/(n-2)))\r\n\t\t\t\t\t\r\n\t\t# now predict y based on test x-values\r\n\t\tp_y = z_pred[0]*p_x+z_pred[1]\r\n\t\t \r\n\t\t# get lower and upper confidence limits based on predicted y and confidence intervals\r\n\t\tlower = p_y - abs(confs)\r\n\t\tupper = p_y + abs(confs)\r\n\t\t \r\n\t\t \r\n\t\t# plot sample data\r\n\t\tcolor = ( X[:,1] - np.min(X[:,1]) ) / ( np.max(X[:,1]) - np.min(X[:,1]) )\r\n\t\t\r\n\t\tax.scatter(y_data,y_pred,c=cm.rainbow(color), marker = '+', linewidth = 7, s = 10, edgecolors=None, alpha = 0.3)\r\n\t\tax.set_xlabel(\"Data\",fontsize=fontsize)\r\n\t\tax.set_ylabel(\"Predicted\",fontsize=fontsize)\r\n\t\t# plot line of best fit\r\n\t\tax.plot(c_x,c_y,'r-', linewidth = 3)\r\n\t\t#ax.plot([5,7],[5,7],'g:', linewidth = 3, alpha = 0.7)\r\n\t\t#ax.axis('equal')\r\n\t\t\t\r\n\t\tax.set_xlim((4.9, 7))\r\n\t\tax.set_ylim((4.9, 7))\r\n\t\tax.set_aspect('equal', 'box')\t\t\r\n\t\t# plot confidence limits\r\n\t\tax.plot(p_x,lower,'b--', linewidth = 3)\r\n\t\tax.plot(p_x,upper,'b--', linewidth = 3)\t\r\n\t\t\t\t\t\r\n\t\tfor ii in range(2):\r\n\t\t\tfor tick in ax.xaxis.get_major_ticks():\r\n\t\t\t\ttick.label1.set_fontsize(fontsize)\r\n\t\t\tfor tick in ax.yaxis.get_major_ticks():\r\n\t\t\t\ttick.label1.set_fontsize(fontsize)\r\n \r\ndef export_predictions(Y_exp, Y_pred):\r\n DAT = np.transpose(np.array([Y_exp, Y_pred]))\r\n np.savetxt(\"Exp_Pred_ANN.txt\", DAT, delimiter=',')#, fmt='%d' \r\ndef plot_maps_pH(dirs, clf,pca,sc, sequence):\r\n\t\r\n\tsub = 3\r\n\tindices = np.arange(0,len(dirs),sub)\r\n\r\n\t#fig, ax = plt.subplots(1, len(indices))\r\n\tf = plt.figure()\r\n\tgs = gridspec.GridSpec(3, len(indices), height_ratios=[10,10,1], hspace=0.15)\r\n\t#gs1.update(left=0.05, right=0.48, wspace=0.05)\r\n\tfor i in indices:\r\n\t\td = dirs[i]\r\n\t\t# load the model\r\n\t\tIM = []\r\n\t\t\t\r\n\t\t\r\n\t\t# Add x and y coordinates as input variables\r\n\t\txx, yy = np.meshgrid(np.arange(S[0]),\r\n\t\t\t\t\t\t\t\t np.arange(S[1]))\r\n\t\tIM.append(xx.ravel())\r\n\t\tIM.append(yy.ravel())\r\n\t\t\t\r\n\t\t# Add wavelength as input variables\r\n\t\tfor c in channels:\r\n\t\t\tfile = folder + d + \"\\\\LOOP_0\\\\Z_Window_z2\\\\\"+c+\"_0.tif\"\r\n\t\t\timg = LoadImagFiles.Load(file, folder_correct)#mpimg.imread(file)\r\n\t\t\t#img = ndimage.median_filter(img, size=10)\r\n\t\t\timg = ndimage.gaussian_filter(img, sigma=sig)\r\n\t\t\tIM.append(img.ravel())\r\n\r\n\t\tX = np.array(IM).transpose()\r\n\r\n\t\t# transform the data\r\n\t\tXp2 = X[:,sequence]\r\n\t\tif pca != None:\r\n\t\t\tXp2 = pca.transform(Xp2)\t\t\t\t\t\t# PCA\r\n\t\tif sc!= None:\r\n\t\t\tXp2 = sc.transform(Xp2)\t\t\t\t\t\t# Normalise\r\n\t\t\r\n\t\t# Prediction by block to avoid memory errors\r\n\t\tX_pred = X[:,0]*0.\r\n\t\tX_pred_prob = X[:,0]*0.\r\n\t\tnn = len(X_pred)\r\n\t\tSUB = 10\r\n\t\t#X_pred = clf.predict(Xp2).astype(float)\t\t\r\n\t\tfor kk in range(SUB):\r\n\t\t\tX_pred[int(kk*nn/SUB):int((kk+1)*nn/SUB)] = clf.predict(Xp2[int(kk*nn/SUB):int((kk+1)*nn/SUB),:]).astype(float) # [kk*nn/SUB:(kk+1)*nn/SUB,:]\r\n\r\n\t\t#X_pred = ndimage.median_filter(X_pred.reshape(S), size=10).ravel()\r\n\t\tX_pred = ndimage.gaussian_filter(X_pred.reshape(S), sigma=10).ravel()\r\n\t\t\r\n\t\t# predict pH\r\n\t\t#X_pred_masked = X_pred * (X[:,3] > 3200.*(1. + float(i)/9.5))\r\n\t\t#X_pred_masked = np.ma.masked_where(X_pred_masked < 1. , X_pred_masked, copy = True) # X[:,1] < 5000. and X_pred_prob > 0.3\r\n\t\t#X_pred_masked = X_pred_masked.reshape(S)\r\n\t\t\r\n\t\tRGB = plt.cm.rainbow((np.clip(X_pred.reshape(S),5,7)-5.)/2.)\r\n\t\tX3 = X[:,3].reshape(S)\r\n\t\tdI = 0.5\r\n\t\tdi = 0.07\r\n\t\tRGB[:,:,3] = ( np.clip(X3 / float(np.max(np.max(X3))),di,1.-dI) - di ) / (1. - dI - di) \r\n\r\n\t\tii = int(i/sub)\r\n\t\t# Plot predicted pH\r\n\t\tax = plt.Subplot(f, gs[1, ii])\r\n\t\tax.set_title(\"pH \" + str(list_pH[i]), fontsize=fontsize)\r\n\t\tif i 3200.*(1. + float(i)/9.5))\r\n\t\t#X_pred_masked = np.ma.masked_where(X_pred_masked < 1. , X_pred_masked, copy = True) # X[:,1] < 5000. and X_pred_prob > 0.3\r\n\t\t#X_pred_masked = X_pred_masked.reshape(S)\r\n\t\t\r\n\t\tRGB = plt.cm.rainbow((np.clip(X_pred.reshape(S),5,7)-5.)/2.)\r\n\t\tX3 = X[:,3].reshape(S)\r\n\t\tdI = 0.5\r\n\t\tdi = 0.07\r\n\t\tRGB[:,:,3] = ( np.clip(X3 / float(np.max(np.max(X3))),di,1.-dI) - di ) / (1. - dI - di) \r\n\r\n\t\tii = i/sub\r\n\t\t# Plot predicted pH\r\n\t\tax = plt.Subplot(f, gs[1, ii])\r\n\t\tax.set_title(\"pH \" + str(list_pH[i]), fontsize=fontsize)\r\n\t\tif i>> Shape of raw predictions ({}): {}\\n{}\".format(\"logits\" if use_logits else \"probability\",\n raw_preds.shape,\n raw_preds))\n print()\n\n # get the final predictions\n preds = athena.predict(x=x_bs) # raw is False by default\n print(\">>> Shape of predictions ({}): {}\\n{}\".format(\"logits\" if use_logits else \"probability\",\n preds.shape,\n preds))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"\")\n\n \"\"\"\n configurations under ``configs/demo`` are for demo.\n \"\"\"\n\n parser.add_argument('-t', '--trans-configs', required=False,\n default='../configs/demo/athena-mnist.json',\n help='Configuration file for transformations.')\n parser.add_argument('-m', '--model-configs', required=False,\n default='../configs/demo/model-mnist.json',\n help='Folder where models stored in.')\n parser.add_argument('-d', '--data-configs', required=False,\n default='../configs/demo/data-mnist.json',\n help='Folder where test data stored in.')\n parser.add_argument('-o', '--output-root', required=False,\n default='results',\n help='Folder for outputs.')\n parser.add_argument('--debug', required=False, default=True)\n\n args = parser.parse_args()\n\n print('------AUGMENT SUMMARY-------')\n print('TRANSFORMATION CONFIGS:', args.trans_configs)\n print('MODEL CONFIGS:', args.model_configs)\n print('DATA CONFIGS:', args.data_configs)\n print('OUTPUT ROOT:', args.output_root)\n print('DEBUGGING MODE:', args.debug)\n print('----------------------------\\n')\n\n # parse configurations (into a dictionary) from json file\n trans_configs = load_from_json(args.trans_configs)\n model_configs = load_from_json(args.model_configs)\n data_configs = load_from_json(args.data_configs)\n\n # collect probabilites\n collect_raw_prediction(trans_configs=trans_configs,\n model_configs=model_configs,\n data_configs=data_configs)\n # collect logits\n collect_raw_prediction(trans_configs=trans_configs,\n model_configs=model_configs,\n data_configs=data_configs,\n use_logits=True)","sub_path":"src/tutorials/collect_raws.py","file_name":"collect_raws.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"75217711","text":"# MenuTitle: Apply UFO Layer Colors With Mapping\n# -*- coding: utf-8 -*-\nfrom __future__ import (\n absolute_import,\n division,\n print_function,\n unicode_literals,\n)\n\nfrom AppKit import NSColor\n\ncolor_map = {\n # RGBA to Glyphs color index, see https://docu.glyphsapp.com/#GSLayer.color\n (1.0, 0.6, 0.647, 1.0): 0, # red\n (1.0, 0.6, 0.6, 1.0): 0, # red\n (1.0, 0.873, 0.6, 1.0): 1, # orange\n (1.0, 0.666, 0.6, 1.0): 2, # brown\n (1.0, 0.976, 0.6, 1.0): 3, # yellow\n (0.656, 1.0, 0.6, 1.0): 4, # light green\n (0.619, 1.0, 0.6, 1.0): 4, # dark green\n (0.6, 0.995, 1.0, 1.0): 6, # light blue\n (0.6, 0.986, 1.0, 1.0): 6, # light blue\n (0.6, 0.741, 1.0, 1.0): 7, # dark blue\n (0.6, 0.609, 1.0, 1.0): 8, # purple\n (0.967, 0.6, 1.0, 1.0): 9, # magenta\n (0, 0, 0, 0): 9223372036854775807, # not colored, white\n}\n\nset_colors = True\nunset_userdata_colors = False\nused_colors = set()\n\nfor glyph in Font.glyphs:\n for layer in glyph.layers:\n rgba = layer.userData.get(\n \"com.typemytype.robofont.mark\", # Actually also used by vfb2ufo\n None,\n )\n if rgba is None:\n if set_colors:\n layer.color = 9223372036854775807\n else:\n r, g, b, a = rgba\n if set_colors:\n color = color_map.get((r, g, b, a), None)\n if color is None:\n layer.colorObject = NSColor.colorWithDeviceRed_green_blue_alpha_(\n r, g, b, a\n )\n if (r, g, b, a) not in used_colors:\n print(\n \"INFO: Unknown color (%g, %g, %g, %g) was applied directly, you may want to add a mapping for it in the script.\"\n % (r, g, b, a)\n )\n else:\n layer.color = color\n used_colors |= set([(r, g, b, a)])\n if unset_userdata_colors:\n del layer.userData[\"com.typemytype.robofont.mark\"]\n\n # print(glyph.name, layer, r, g, b, a)\n\nprint(\"Colors used in font:\", list(used_colors))\n","sub_path":"Layers/Apply UFO Layer Colors.py","file_name":"Apply UFO Layer Colors.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"45930747","text":"import os\n\nimport flopy\nimport numpy as np\nimport pytest\nfrom framework import TestFramework\nfrom simulation import TestSimulation\n\nex = [\"tvk05\"]\ntime_varying_k = [1.0, 10.0]\n\n\ndef build_model(idx, dir):\n nlay, nrow, ncol = 3, 3, 3\n perlen = [100.0, 100.0]\n nper = len(perlen)\n nstp = nper * [1]\n tsmult = nper * [1.0]\n delr = 1.0\n delc = 1.0\n delz = 1.0\n top = 1.0\n laytyp = 0\n botm = [0.0, -1.0, -2.0]\n strt = 1.0\n hk = 0.1\n\n nouter, ninner = 100, 300\n hclose, rclose, relax = 1e-6, 1e-6, 1.0\n\n tdis_rc = []\n for i in range(nper):\n tdis_rc.append((perlen[i], nstp[i], tsmult[i]))\n\n name = ex[idx]\n\n # build MODFLOW 6 files\n ws = dir\n sim = flopy.mf6.MFSimulation(\n sim_name=name, version=\"mf6\", exe_name=\"mf6\", sim_ws=ws\n )\n # create tdis package\n tdis = flopy.mf6.ModflowTdis(\n sim, time_units=\"DAYS\", nper=nper, perioddata=tdis_rc\n )\n\n # create gwf model\n gwfname = \"gwf_\" + name\n gwf = flopy.mf6.MFModel(\n sim,\n model_type=\"gwf6\",\n modelname=gwfname,\n model_nam_file=f\"{gwfname}.nam\",\n )\n gwf.name_file.save_flows = True\n\n # create iterative model solution and register the gwf model with it\n imsgwf = flopy.mf6.ModflowIms(\n sim,\n print_option=\"SUMMARY\",\n outer_dvclose=hclose,\n outer_maximum=nouter,\n under_relaxation=\"NONE\",\n inner_maximum=ninner,\n inner_dvclose=hclose,\n rcloserecord=rclose,\n linear_acceleration=\"CG\",\n scaling_method=\"NONE\",\n reordering_method=\"NONE\",\n relaxation_factor=relax,\n filename=f\"{gwfname}.ims\",\n )\n sim.register_ims_package(imsgwf, [gwf.name])\n\n dis = flopy.mf6.ModflowGwfdis(\n gwf,\n nlay=nlay,\n nrow=nrow,\n ncol=ncol,\n delr=delr,\n delc=delc,\n top=top,\n botm=botm,\n idomain=np.ones((nlay, nrow, ncol), dtype=int),\n filename=f\"{gwfname}.dis\",\n )\n\n # initial conditions\n ic = flopy.mf6.ModflowGwfic(gwf, strt=strt, filename=f\"{gwfname}.ic\")\n\n # node property flow\n tvk_filename = f\"{gwfname}.npf.tvk\"\n npf = flopy.mf6.ModflowGwfnpf(\n gwf,\n save_specific_discharge=True,\n icelltype=laytyp,\n k=hk,\n k22=hk,\n )\n\n # tvk\n # k33 not originally specified in NPF, but specifying an\n # alternate value in the 2nd stress period to test MF6\n tvkspd = {}\n kper = 1\n hydraulic_conductivity = time_varying_k[kper]\n spd = []\n for k in range(nlay):\n for i in range(nrow):\n for j in range(ncol):\n spd.append([(k, i, j), \"K33\", hydraulic_conductivity])\n tvkspd[kper] = spd\n\n tvk = flopy.mf6.ModflowUtltvk(\n npf, print_input=True, perioddata=tvkspd, filename=tvk_filename\n )\n\n # chd files\n chdspd = []\n for i in range(nrow):\n chdspd.append([(0, i, 0), top + 1])\n\n chd = flopy.mf6.ModflowGwfchd(\n gwf,\n stress_period_data=chdspd,\n save_flows=False,\n print_flows=True,\n pname=\"CHD-1\",\n )\n\n # ghb files\n ghbspd = []\n ghbcond = time_varying_k[1] * delz * delc / (0.5 * delr)\n for i in range(nrow):\n ghbspd.append([(nlay - 1, i, ncol - 1), top, ghbcond])\n\n ghb = flopy.mf6.ModflowGwfghb(\n gwf,\n stress_period_data=ghbspd,\n save_flows=False,\n print_flows=True,\n pname=\"GHB-1\",\n )\n\n # output control\n oc = flopy.mf6.ModflowGwfoc(\n gwf,\n budget_filerecord=f\"{gwfname}.cbc\",\n head_filerecord=f\"{gwfname}.hds\",\n headprintrecord=[(\"COLUMNS\", 10, \"WIDTH\", 15, \"DIGITS\", 6, \"GENERAL\")],\n saverecord=[(\"HEAD\", \"LAST\"), (\"BUDGET\", \"LAST\")],\n printrecord=[(\"HEAD\", \"LAST\"), (\"BUDGET\", \"LAST\")],\n )\n\n return sim, None\n\n\ndef eval_model(sim):\n print(\"evaluating model...\")\n\n # budget\n try:\n fname = f\"gwf_{sim.name}.lst\"\n ws = sim.simpath\n fname = os.path.join(ws, fname)\n lst = flopy.utils.Mf6ListBudget(\n fname, budgetkey=\"VOLUME BUDGET FOR ENTIRE MODEL\"\n )\n lstra = lst.get_incremental()\n except:\n assert False, f'could not load data from \"{fname}\"'\n\n # This is the answer to this problem.\n sp_x = []\n for kper, bud in enumerate(lstra):\n sp_x.append(bud)\n\n # comment when done testing\n print(f\"Total outflow in stress period 1 is {str(sp_x[0][8])}\")\n print(\n f\"Total outflow in stress period 2 after increasing K33 is {str(sp_x[1][8])}\"\n )\n errmsg = f\"Expect higher flow rate in period 2 compared to period 1, but found equal or higher flow rate in period 1\"\n assert 2.0 * sp_x[0][8] < sp_x[1][8], errmsg\n\n\n@pytest.mark.parametrize(\n \"name\",\n ex,\n)\ndef test_mf6model(name, function_tmpdir, targets):\n ws = str(function_tmpdir)\n test = TestFramework()\n test.build(build_model, 0, ws)\n test.run(\n TestSimulation(\n name=name, exe_dict=targets, exfunc=eval_model, idxsim=0\n ),\n ws,\n )\n","sub_path":"autotest/test_gwf_npf_tvk04.py","file_name":"test_gwf_npf_tvk04.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"571787782","text":"#!/usr/bin/env python\nimport os\nimport json\nimport torch\nimport pprint\nimport argparse\nimport importlib\nimport numpy as np\nimport cv2, tqdm\n\nimport matplotlib\nmatplotlib.use(\"Agg\")\n\nfrom config import system_configs\nfrom nnet.py_factory import NetworkFactory\n\nfrom config import system_configs\nfrom utils import crop_image, normalize_\nfrom external.nms import soft_nms_with_points as soft_nms\nfrom utils.color_map import colormap\nfrom utils.visualize import vis_mask, vis_octagon, vis_ex, vis_class, vis_bbox\nfrom dextr import Dextr\nfrom db.datasets import datasets\n\ntorch.backends.cudnn.benchmark = False\n\n#\n# class_name = ['__background__', \"probe_right\", \"spin_cord\"]\nclass_name = ['__background__', \"probe\", \"scissor\",\"probe\"]\nimage_ext = ['jpg', 'jpeg', 'png', 'webp']\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Demo CornerNet\")\n parser.add_argument(\"--cfg_file\", help=\"config file\", \n default='medical_ExtremeNet', type=str)\n parser.add_argument(\"--demo\", help=\"demo image path or folders\",\n default=\"data/medical_img/test2017\", type=str)\n parser.add_argument(\"--model_path\",\n default='cache/nnet/medical_ExtremeNet/medical_ExtremeNet_27600.pkl')\n parser.add_argument(\"--show_mask\", action='store_true',\n help=\"Run Deep extreme cut to obtain accurate mask\")\n\n args = parser.parse_args()\n return args\n\ndef _rescale_dets(detections, ratios, borders, sizes):\n xs, ys = detections[..., 0:4:2], detections[..., 1:4:2]\n xs /= ratios[:, 1][:, None, None]\n ys /= ratios[:, 0][:, None, None]\n xs -= borders[:, 2][:, None, None]\n ys -= borders[:, 0][:, None, None]\n np.clip(xs, 0, sizes[:, 1][:, None, None], out=xs)\n np.clip(ys, 0, sizes[:, 0][:, None, None], out=ys)\n\ndef _rescale_ex_pts(detections, ratios, borders, sizes):\n xs, ys = detections[..., 5:13:2], detections[..., 6:13:2]\n xs /= ratios[:, 1][:, None, None]\n ys /= ratios[:, 0][:, None, None]\n xs -= borders[:, 2][:, None, None]\n ys -= borders[:, 0][:, None, None]\n np.clip(xs, 0, sizes[:, 1][:, None, None], out=xs)\n np.clip(ys, 0, sizes[:, 0][:, None, None], out=ys)\n\ndef _box_inside(box2, box1):\n inside = (box2[0] >= box1[0] and box2[1] >= box1[1] and \\\n box2[2] <= box1[2] and box2[3] <= box1[3])\n return inside \n\ndef kp_decode(nnet, images, K, kernel=3, aggr_weight=0.1, \n scores_thresh=0.1, center_thresh=0.1, debug=False):\n detections = nnet.test(\n [images], kernel=kernel, aggr_weight=aggr_weight, \n scores_thresh=scores_thresh, center_thresh=center_thresh, debug=debug)\n detections = detections.data.cpu().numpy()\n return detections\n\nif __name__ == \"__main__\":\n args = parse_args()\n cfg_file = os.path.join(\n system_configs.config_dir, args.cfg_file + \".json\")\n print(\"[demo] cfg_file: {}\".format(cfg_file))\n\n with open(cfg_file, \"r\") as f:\n configs = json.load(f)\n \n configs[\"system\"][\"snapshot_name\"] = args.cfg_file\n system_configs.update_config(configs[\"system\"])\n print(\"system config...\")\n pprint.pprint(system_configs.full)\n \n print(\"loading parameters: {}\".format(args.model_path))\n print(\"building neural network...\")\n train_split = system_configs.train_split\n dataset = system_configs.dataset\n training_db = datasets[dataset](configs[\"db\"], train_split)\n nnet = NetworkFactory(training_db, configs[\"cuda_flag\"])\n print(\"loading parameters...\")\n nnet.load_pretrained_params(args.model_path)\n if torch.cuda.is_available() and configs[\"cuda_flag\"]:\n nnet.cuda()\n nnet.eval_mode()\n\n K = configs[\"db\"][\"top_k\"]\n aggr_weight = configs[\"db\"][\"aggr_weight\"]\n scores_thresh = configs[\"db\"][\"scores_thresh\"]\n center_thresh = configs[\"db\"][\"center_thresh\"]\n suppres_ghost = True\n nms_kernel = 3\n \n scales = configs[\"db\"][\"test_scales\"]\n weight_exp = 8\n categories = configs[\"db\"][\"categories\"]\n print('''[demo] configs[\"db\"]''', configs[\"db\"])\n nms_threshold = configs[\"db\"][\"nms_threshold\"]\n max_per_image = configs[\"db\"][\"max_per_image\"]\n nms_algorithm = {\n \"nms\": 0,\n \"linear_soft_nms\": 1, \n \"exp_soft_nms\": 2\n }[\"exp_soft_nms\"]\n if args.show_mask:\n dextr = Dextr()\n\n\n mean = np.array([0.40789654, 0.44719302, 0.47026115], dtype=np.float32)\n std = np.array([0.28863828, 0.27408164, 0.27809835], dtype=np.float32)\n top_bboxes = {}\n # print(\"[demo] args.demo\", args.demo, \"os.path.isdir(args.demo)\", os.path.isdir(args.demo))\n if os.path.isdir(args.demo):\n image_names = []\n ls = os.listdir(args.demo)\n # print(\"os.listdir(args.demo)\", ls)\n for file_name in sorted(ls):\n ext = file_name[file_name.rfind('.') + 1:].lower()\n if ext in image_ext:\n image_names.append(os.path.join(args.demo, file_name))\n else:\n args.demo = \"../../medical_img/data/test/img\"\n image_names = []\n ls = os.listdir(args.demo)\n # print(\"os.listdir(args.demo)\", ls)\n for file_name in sorted(ls):\n ext = file_name[file_name.rfind('.') + 1:].lower()\n if ext in image_ext:\n image_names.append(os.path.join(args.demo, file_name))\n # print(\"[demo] image_names\", image_names, \"args.demo\", args.demo,\n # \"os.path.isdir(args.demo)\", os.path.isdir(args.demo),\"args\", args)\n for image_id in tqdm.tqdm(range(len(image_names))):\n image_name = image_names[image_id]\n # print(\"image_name.split('.')[-2][-6:]\", image_name.split('.')[-2][-6:])\n # if 1310 >= int(image_name.split('.')[-2][-6:]):\n # continue\n print('Running ', image_name)\n \n image = cv2.imread(image_name)\n\n height, width = image.shape[0:2]\n\n detections = []\n\n for scale in scales:\n new_height = int(height * scale)\n new_width = int(width * scale)\n new_center = np.array([new_height // 2, new_width // 2])\n\n inp_height = new_height | 127\n inp_width = new_width | 127\n\n images = np.zeros((1, 3, inp_height, inp_width), dtype=np.float32)\n ratios = np.zeros((1, 2), dtype=np.float32)\n borders = np.zeros((1, 4), dtype=np.float32)\n sizes = np.zeros((1, 2), dtype=np.float32)\n\n out_height, out_width = (inp_height + 1) // 4, (inp_width + 1) // 4\n height_ratio = out_height / inp_height\n width_ratio = out_width / inp_width\n\n resized_image = cv2.resize(image, (new_width, new_height))\n resized_image, border, offset = crop_image(\n resized_image, new_center, [inp_height, inp_width])\n\n resized_image = resized_image / 255.\n normalize_(resized_image, mean, std)\n\n images[0] = resized_image.transpose((2, 0, 1))\n borders[0] = border\n sizes[0] = [int(height * scale), int(width * scale)]\n ratios[0] = [height_ratio, width_ratio]\n\n images = np.concatenate((images, images[:, :, :, ::-1]), axis=0)\n images = torch.from_numpy(images)\n # print(\"[demo] scales\", scales)\n dets = kp_decode(\n nnet, images, K, aggr_weight=aggr_weight, \n scores_thresh=scores_thresh, center_thresh=center_thresh,\n kernel=nms_kernel, debug=True)\n \n dets = dets.reshape(2, -1, 14)\n dets[1, :, [0, 2]] = out_width - dets[1, :, [2, 0]]\n dets[1, :, [5, 7, 9, 11]] = out_width - dets[1, :, [5, 7, 9, 11]]\n dets[1, :, [7, 8, 11, 12]] = dets[1, :, [11, 12, 7, 8]].copy()\n dets = dets.reshape(1, -1, 14)\n\n _rescale_dets(dets, ratios, borders, sizes)\n _rescale_ex_pts(dets, ratios, borders, sizes)\n dets[:, :, 0:4] /= scale\n dets[:, :, 5:13] /= scale\n detections.append(dets)\n\n detections = np.concatenate(detections, axis=1)\n\n classes = detections[..., -1]\n classes = classes[0]\n detections = detections[0]\n\n # reject detections with negative scores\n keep_inds = (detections[:, 4] > 0)\n detections = detections[keep_inds]\n classes = classes[keep_inds]\n\n top_bboxes[image_id] = {}\n for j in range(categories):\n keep_inds = (classes == j)\n top_bboxes[image_id][j + 1] = \\\n detections[keep_inds].astype(np.float32)\n soft_nms(top_bboxes[image_id][j + 1], \n Nt=nms_threshold, method=nms_algorithm)\n\n scores = np.hstack([\n top_bboxes[image_id][j][:, 4] \n for j in range(1, categories + 1)\n ])\n if len(scores) > max_per_image:\n kth = len(scores) - max_per_image\n thresh = np.partition(scores, kth)[kth]\n for j in range(1, categories + 1):\n keep_inds = (top_bboxes[image_id][j][:, 4] >= thresh)\n top_bboxes[image_id][j] = top_bboxes[image_id][j][keep_inds]\n\n if suppres_ghost:\n for j in range(1, categories + 1):\n n = len(top_bboxes[image_id][j])\n for k in range(n):\n inside_score = 0\n if top_bboxes[image_id][j][k, 4] > 0.2:\n for t in range(n):\n if _box_inside(top_bboxes[image_id][j][t], \n top_bboxes[image_id][j][k]):\n inside_score += top_bboxes[image_id][j][t, 4]\n if inside_score > top_bboxes[image_id][j][k, 4] * 3:\n top_bboxes[image_id][j][k, 4] /= 2\n\n\n if 1: # visualize\n color_list = colormap(rgb=True)\n mask_color_id = 0\n image = cv2.imread(image_name)\n input_image = image.copy()\n mask_image = image.copy()\n bboxes = {}\n # print(\"[demo] categories\", categories)\n Threshold= {1:0.3, 2:0.0, 3:0.3}\n for j in range(1, categories +1):\n keep_inds = (top_bboxes[image_id][j][:, 4] > 0.3) #yezheng: this threshold is important\n cat_name = class_name[j]\n for bbox in top_bboxes[image_id][j][keep_inds]:\n sc = bbox[4]\n ex = bbox[5:13].astype(np.int32).reshape(4, 2)\n bbox = bbox[0:4].astype(np.int32)\n txt = '{}{:.2f}'.format(cat_name, sc)\n color_mask = color_list[mask_color_id % len(color_list), :3]\n mask_color_id += 1\n # image = vis_bbox(image, \n # (bbox[0], bbox[1], \n # bbox[2] - bbox[0], bbox[3] - bbox[1]))\n image = vis_class(image, \n (bbox[0], bbox[1] - 2), txt)\n # image = vis_octagon( image, ex, color_mask)\n image = vis_ex(image, ex, color_mask)\n\n # if args.show_mask:\n mask = dextr.segment(input_image[:, :, ::-1], ex) # BGR to RGB\n mask = np.asfortranarray(mask.astype(np.uint8))\n mask_image = vis_bbox(mask_image, \n (bbox[0], bbox[1], \n bbox[2] - bbox[0], \n bbox[3] - bbox[1]))\n mask_image = vis_class(mask_image, \n (bbox[0], bbox[1] - 2), txt)\n mask_image = vis_mask(mask_image, mask, color_mask)\n #yezheng: comment out\n if args.show_mask:\n cv2.imshow('mask', mask_image)\n # cv2.imshow('out', image)\n # cv2.waitKey()\n # cv2.imwrite(\"out_images/\"+ image_name.split('/')[-1].split('.')[0]+\"_out.png\", image)\n cv2.imwrite(\"out_images/\"+ image_name.split('/')[-1].split('.')[0]+\"_out.png\", mask_image)\n\n\n\n","sub_path":"medical_demo.py","file_name":"medical_demo.py","file_ext":"py","file_size_in_byte":12268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"537620042","text":"#!/usr/bin/env python3\n\n\n# a sketch that will run a main thread and another one responsible to \n# read some GPIO values.\n\nimport threading, readchar, time, sys\nimport RPi.GPIO as GPIO\n\ngpios = []\n\nsharedVar = False\n\ndef checkInput():\n\tglobal sharedVar\n\twhile True:\n\t\tprint(\"Reading a char:\")\n\t\tc = readchar.readchar()\n\t\tprint( c )\n\t\tif c == ' ':\n\t\t\tsharedVar = True\n\t\t\t# exit thread execution\n\t\t\treturn\n\n\ndef main():\n\tmyThread = threading.Thread( target=checkInput )\n\tmyThread.start()\n\twhile True:\n\t\tif sharedVar:\n\t\t\tprint(\"Trying to quit\")\n\t\t\tquit()\n\t\telse:\n\t\t\tprint( \"main thread\" )\n\t\t\ttime.sleep(1)\n\t\n\t\nif __name__ == \"__main__\":\n\tsys.exit( main() )\n","sub_path":"_wip/_old/GPIO_and_threading/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"77435146","text":"\"\"\"\nPatch the content-type of error responses.\n\nDue to the changes between Swagger 2.0 and OpenAPI 3.0, we cannot handle\nthis at the Python level.\n\"\"\"\nfrom django.core.management import BaseCommand\n\nimport oyaml as yaml\n\nfrom ...views import ERROR_CONTENT_TYPE\n\n\nclass Command(BaseCommand):\n help = \"Patch the error-response content types in the OAS 3 spec\"\n\n def add_arguments(self, parser):\n parser.add_argument('api-spec', help=\"Path to the openapi spec. Will be overwritten!\")\n\n def handle(self, **options):\n source = options['api-spec']\n with open(source, 'r') as infile:\n spec = yaml.safe_load(infile)\n\n for path, methods in spec['paths'].items():\n for method in methods.values():\n if 'responses' not in method:\n continue\n\n for status, response in method['responses'].items():\n if not (400 <= int(status) < 600):\n continue\n\n content = {}\n for contenttype, _response in response['content'].items():\n if contenttype == 'application/json':\n contenttype = ERROR_CONTENT_TYPE\n content[contenttype] = _response\n\n response['content'] = content\n\n with open(source, 'w') as outfile:\n yaml.dump(spec, outfile, default_flow_style=False)\n","sub_path":"zds_schema/management/commands/patch_error_contenttypes.py","file_name":"patch_error_contenttypes.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"204528925","text":"#coding:utf-8\n'''\nCreated on 2016/05/01\n\n@author: ryuu\n'''\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport psycopg2\nimport os\nimport csv\n\nFILE_DIR = os.path.dirname(os.path.abspath(__file__))\nbaseFilePath=os.path.abspath('..')+os.sep+ 'data'\n\ndef jpn_year(ad):\n ymd = ad.split('.')\n y=int(ymd[0][1:])+1988\n return str(y)+'/'+ymd[1]+'/'+ymd[2]\n\ndef jpnNumToEngNum(num):\n return num.replace('0','0').replace('1','1').replace('2','2').replace('3','3').replace('4','4').replace('5','5').replace('6','6').replace('7','7').replace('8','8').replace('9','9')\ndef conndb(): \n try:\n return psycopg2.connect(\"dbname='takarakuji' user='postgres' host='localhost' password='President@1225'\")\n except:\n print(\"I am unable to connect to the database\")\ndef closedb(conn):\n conn.close()\n \ndef writeData(sql,cur,url):\n with urllib.request.urlopen(url) as page:\n soup=BeautifulSoup(page.read(),'html.parser')\n for node in soup.findAll(\"section\",{\"class\":\"bg tousenno\"}):\n tmparr=[]\n for ki in node.select('div'):\n listword = ki.get_text().split() \n tmparr.append(jpnNumToEngNum(listword[0].replace('第','').replace('回','')))\n if listword[1].startswith('H'): \n tmparr.append(jpnNumToEngNum(jpn_year(listword[1])))\n elif listword[1].startswith('H'):\n tmparr.append(jpnNumToEngNum(jpn_year(listword[1])))\n else:\n tmparr.append(jpnNumToEngNum(jpn_year(listword[3])))\n \n for tdvalue in node.select(\"table tr td\"):\n for imgvalue in tdvalue.select(\"img\"):\n tmparr.append(imgvalue['alt'])\n for levelValue in node.findAll(attrs={\"class\":\"al_right\"}):\n if levelValue.get_text()=='該当なし' or levelValue.get_text():\n tmparr.append('0')\n else:\n tmparr.append(levelValue.get_text().replace('口','').replace('円','').replace(',','').replace('-','').replace('.',''))\n print(tmparr)\n# cur.execute(sqlstr,tmparr)\n with open(baseFilePath + os.sep + 'data.csv', 'a+') as csvfile:\n writer = csv.writer(csvfile,delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(tmparr)\n \nif __name__=='__main__':\n sqlstr='INSERT INTO LOTO7 VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'\n burl='http://www.takarakuji-loto.jp/loto7/result'\n conn=conndb()\n cur = conn.cursor()\n for i in range(1,162,10):\n url = burl +str(i).zfill(4)+ '.html'\n writeData(sqlstr,cur,url)\n conn.commit()\n closedb(conn)\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"com/ana/scapy.py","file_name":"scapy.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"361077430","text":"'''\n @Author: Ritika Patidar\n @Date: 2021-02-22 21:15:10\n @Last Modified by: Ritika Patidar\n @Last Modified time: 2021-02-22 21:15:38 \n @Title : patient program for clinique Management Program\n'''\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath('LogFile'))\nimport loggerfile\nimport json_operation\nimport re\n\nclass patient_management:\n def __init__(self):\n self.data_patient=json_operation.load_data_patient()\n def patient_search(self,search_type,search_detail):\n check=False\n for search in self.data_patient:\n if(search[search_type]==search_detail):\n check=True\n print(\"#### PATIENT DETAIL #### \\n name : {0} \\n id : {1} \\n mobilenumber: {2}\".format(tuple(search.values())[0],tuple(search.values())[1],tuple(search.values())[2]))\n loggerfile.Logger(\"debug\",\"searched successfully\")\n if(check==True):\n return \"detail searched\"\n else:\n print(\"detail not found\")\n return \"detail not match\"\n\n\ndef user_search():\n while True:\n try:\n search_mode=int(input(\"enter \\n 0 : name \\n 1 : id \\n 2 : mobile number \\n 3 : Quit() : \"))\n if(search_mode==0):\n name=str(input(\"enter patient name: \")).lower()\n if(re.match(\"^[A-Za-z A-Za-z]*$\",name)):\n return \"name\",name\n else:\n print(\"invalid name\")\n elif(search_mode==1):\n id=str(input(\"enter patient id: \")).lower()\n if(re.match(r'^[0-9]{4}$',id)):\n return \"id\",id\n else:\n print(\"invalid id\")\n elif(search_mode==2):\n mobile_number=str(input(\"enter patient mobile number: \")).lower()\n if(re.match(r'^[7-9]{1}[0-9]{9}$',mobile_number)):\n return \"phone_number\",mobile_number\n elif(search_mode==3):\n sys.exit()\n except ValueError as error:\n loggerfile.Logger(\"error\",\"invalid mode entered\")\n","sub_path":"Object-oriented-program/Clinique_Management_Programme/code/main/patient.py","file_name":"patient.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"511798413","text":"from Connection import Connection\n\nclass ApplicationFindValueByCodeDao(Connection):\n\n\tdef __inint__(self):\n\t\tsuper(ApplicationFindValueByCodeDao, self).__init__()\n\n\tdef find (self, code):\n\t\tquery = \" select value from cat_application where code = '\" + code + \"' ;\"\n\n\t\tself.cursor.execute(query)\n\n\t\tresult = self.getResultQuery()\n\n\t\tself.closeConnection()\n\n\t\treturn result","sub_path":"mavenManagement/dataAccess/ApplicationFindValueByCodeDao.py","file_name":"ApplicationFindValueByCodeDao.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"612893465","text":"import csv\n\ndecoded_sentences = {}\ntrain_sentences = {}\no_train_sentences = {}\noutput = {}\ntemp = {}\n\nwhitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n\nwith open('Competitors.csv','rt')as f:\n data = csv.reader(f)\n for row in data:\n #print (row)\n row[2] = str(row[2]).strip()\n #print (row[2])\n transformed = ''.join(filter(whitelist.__contains__, row[2]))\n if row[5] in decoded_sentences:\n #print (row[5])\n decoded_sentences[row[5]].append(transformed)\n else:\n decoded_sentences[row[5]] = [] \n decoded_sentences[row[5]].append(transformed)\n #print(decoded_sentences)\n\nwith open('competitors_train.csv','rt')as f:\n data = csv.reader(f)\n for row in data:\n #print (row)\n row[1] = str(row[1]).strip()\n #print(row[1])\n transformed = ''.join(filter(whitelist.__contains__, row[1]))\n if row[2] in train_sentences:\n o_train_sentences[row[2]].append(row[1])\n train_sentences[row[2]].append(transformed)\n else:\n o_train_sentences[row[2]] = []\n train_sentences[row[2]] = []\n o_train_sentences[row[2]].append(row[1])\n #print(o_train_sentences)\n train_sentences[row[2]].append(transformed)\n\ndef addSentCount(sent, train, o_sent):\n if sent in temp[train]:\n return\n else:\n if train in decoded_sentences:\n temp[train].append(sent)\n output[train].append({o_sent: decoded_sentences[train].count(sent)})\n\nfor train in train_sentences:\n #print(train_sentences[train])\n index = 0\n for sent in train_sentences[train]:\n #print(sent)\n o_sent = o_train_sentences[train][index]\n index = index + 1\n if train in output:\n addSentCount(sent, train, o_sent)\n else:\n output[train] = []\n temp[train] = []\n addSentCount(sent, train, o_sent)\n\n# Get Complete dictinary\n# print (output)\n\n# Get Train Per\ntrainPer = []\nfor cat in output:\n count = 0\n index = 0\n for sent in output[cat]:\n if output[cat][index][list(output[cat][index].keys())[0]] > 0:\n count = count + 1\n index = index + 1\n trainPer.append({cat: \"\".join([str(count), \"/\", str(index)])})\n#print (trainPer)\n\n\n# Get Test Per\ntestPer = []\nfor cat in output:\n count = 0\n index = 0\n for sent in output[cat]:\n if output[cat][index][list(output[cat][index].keys())[0]] > 0:\n count = count + output[cat][index][list(output[cat][index].keys())[0]]\n index = index + 1\n if cat in decoded_sentences:\n testPer.append({cat: \"\".join([str(count), \"/\", str(len(decoded_sentences[cat]))])})\nprint (testPer)","sub_path":"Python/PreProcessingScripts/train_competitors.py","file_name":"train_competitors.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"496676845","text":"\r\nfrom settings import *\r\nfrom db import Redis\r\nfrom crawler import Crawler\r\n\r\n\r\nclass Getter(object):\r\n def __init__(self):\r\n self.redis = Redis()\r\n self.crawler = Crawler()\r\n def is_to_max_pool(self):\r\n if self.redis.return_proxy_number() <= PROXY_MAX:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n def run(self):\r\n print(\"获取器正在运行:\")\r\n if self.is_to_max_pool():\r\n for proxy in self.crawler.run():\r\n self.redis.add(proxy)\r\n print(proxy,\"添加redis成功!\")\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n g = Getter()\r\n g.run()","sub_path":"Proxy/getter.py","file_name":"getter.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"127128292","text":"#定义一个空列表\r\ncard_list=[]\r\ndef show_menu():\r\n print(\"*\" * 50)\r\n print(\"欢迎使用【名片管理系统】V1.0\")\r\n print(\"\")\r\n print(\"1.新增名片\")\r\n print(\"2.显示全部\")\r\n print(\"3.查找名片\")\r\n print(\"\")\r\n print(\"0.退出系统\")\r\n print(\"*\" * 50)\r\n\r\n\r\n\r\ndef new_card():\r\n print(\"-\"*50)\r\n print(\"新增名片\")\r\n\r\n #1.提示用户输入名片的详细信息\r\n name=input(\"请输入姓名:\")\r\n phon_str=input(\"请输入电话:\")\r\n qq_str=input(\"请输入qq:\")\r\n email_str=input(\"请输入邮箱:\")\r\n\r\n #2.使用用户输入的信息建立一个字典\r\n\r\n card_dict = {\"name\":name,\r\n \"phone\":phon_str,\r\n \"qq\":qq_str,\r\n \"email\":email_str\r\n }\r\n #3.将名片添加到字典中\r\n card_list.append(card_dict)\r\n print(card_dict)\r\n #4.提示用户添加成功\r\n print(\"添加 %s 的名片成功\" %name)\r\n\r\n\r\ndef show_all():\r\n print(\"-\"*50)\r\n print(\"显示所有名片\")\r\n if len(card_list)==0:\r\n print(\"当前没有任何名片记录,请使用新增功能添加名片\")\r\n return\r\n #打印表头\r\n for name in [\"姓名\",\"电话\",\"QQ\",\"E-mail\"]:\r\n print(name,end=\"\\t\\t\")\r\n print(\"\")\r\n print(\"=\"*50)\r\n\r\n #遍历名片列表,依次输出字典信息\r\n for card_dict in card_list:\r\n print(\"%s\\t\\t%s\\t\\t%s\\t\\t%s\" % (card_dict[\"name\"],\r\n card_dict[\"phone\"],\r\n card_dict[\"qq\"],\r\n card_dict[\"email\"]))\r\n\r\n\r\n\r\n\r\ndef search_card():\r\n print(\"-\"*50)\r\n print(\"搜索名片\")\r\n#1.提示用户输入要搜索的姓名\r\n find_name = input(\"请输入要搜索的姓名:\")\r\n#2.便利名片列表,查询要搜索的姓名,如果没有找到,要提示用户\r\n for card_dict in card_list:\r\n if card_dict[\"name\"]==find_name:\r\n print(\"找到了\")\r\n print(\"姓名\\t\\t电话\\t\\tQQ\\t\\t邮箱\\t\\t\")\r\n print(\"=\"*50)\r\n print(\"%s\\t\\t%s\\t\\t%s\\t\\t%s\" % (card_dict[\"name\"],\r\n card_dict[\"phone\"],\r\n card_dict[\"qq\"],\r\n card_dict[\"email\"]))\r\n #针对找到的名片记录执行参数修改和删除的操作\r\n deal_card(card_dict)\r\n break\r\n else:\r\n print(\"没找到%s\"%find_name)\r\n\r\n\r\n\r\ndef deal_card(find_dict):\r\n print(find_dict)\r\n action_str=input(\"请选择要执行的操作 \"\r\n \"[1]修改 [2]删除 [0]返回上级菜单\")\r\n if action_str==\"1\":\r\n print(\"请输入要修改的内容\")\r\n find_dict[\"name\"]=input_card_info(find_dict[\"name\"],\"姓名:\")\r\n find_dict[\"phone\"]=input_card_info(find_dict[\"phone\"],\"电话:\")\r\n find_dict[\"qq\"]=input_card_info(find_dict[\"qq\"],\"QQ:\")\r\n find_dict[\"email\"]=input_card_info(find_dict[\"email\"],\"邮箱:\")\r\n\r\n print(\"修改名片成功\")\r\n\r\n elif action_str==\"2\":\r\n card_list.remove(find_dict)\r\n print(\"删除名片\")\r\n\r\n\r\ndef input_card_info(dict_value,tip_message):\r\n \"\"\"输入名片信息\r\n :param dict_value:字典中原有值\r\n :param tip_message:输入提示文字\r\n :return:如果有输入值,就返回输入值,如果为空,返回原有值\r\n \"\"\"\r\n #1.提示用户输入内容\r\n result_str=input(tip_message)\r\n #2.针对用户输入的内容进行判断,如果用户输入了内容,直接返回结果\r\n if len(result_str)>0:\r\n return result_str\r\n #3.如果用户没有输入内容,返回字典中原有的值\r\n else:\r\n return dict_value\r\n","sub_path":"Study/名片管理/cards_tools.py","file_name":"cards_tools.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"81057353","text":"# Hall, Micky S\n# 172412\n\nimport sys\n\n#Gets the point value of the board\ndef eval(array):\n score = 0\n for i in range(5,-1,-1):\n for j in range(7):\n score += up_again(array,i,j)\n score += horizontal_again(array,i,j)\n score += up_right_again(array,i,j)\n score += up_left_again(array,i,j)\n return score\n\n#Counts points possible in upward direction\ndef up_again(array,x,y):\n user = 'R'\n op = 'B'\n count = 0\n bad_count = 0\n if(x>=2):\n if(array[x][y] == user):\n count += 1\n elif(array[x][y] == op):\n bad_count += 1\n if(array[x-1][y] == user):\n count += 1\n elif(array[x-1][y] == op):\n bad_count += 1\n if(array[x-2][y] == user):\n count += 1\n elif(array[x-2][y] == op):\n bad_count += 1\n if(array[x-3][y] == user):\n count += 1\n elif(array[x-3][y] == op):\n bad_count += 1\n\n if(count > 0 and bad_count == 0):\n return 10**count\n elif(bad_count > 0 and count == 0):\n return -1*(10**count+1)\n else:\n return 0\n return 0\n\n#Counts points possible in horizontal direction\ndef horizontal_again(array,x,y):\n user = 'R'\n op = 'B'\n count = 0\n bad_count = 0\n if(y <= 3):\n if(array[x][y] == user):\n count += 1\n elif(array[x][y] == op):\n bad_count += 1\n if(array[x][y+1] == user):\n count += 1\n elif(array[x][y+1] == op):\n bad_count += 1\n if(array[x][y+2] == user):\n count += 1\n elif(array[x][y+2] == op):\n bad_count += 1\n if(array[x][y+3] == user):\n count += 1\n elif(array[x][y+3] == op):\n bad_count += 1\n\n if(count > 0 and bad_count == 0):\n return 10**count\n elif(bad_count > 0 and count == 0):\n return -1*(10**count+1)\n else:\n return 0\n return 0\n\n#Counts points possible in a right/upward direction\ndef up_right_again(array,x,y):\n user = 'R'\n op = 'B'\n count = 0\n bad_count = 0\n if(x > 2 and y <= 3):\n if(array[x][y] == user):\n count += 1\n elif(array[x][y] == op):\n bad_count += 1\n if(array[x-1][y+1] == user):\n count += 1\n elif(array[x-1][y+1] == op):\n bad_count += 1\n if(array[x-2][y+2] == user):\n count += 1\n elif(array[x-2][y+2] == op):\n bad_count += 1\n if(array[x-3][y+3] == user):\n count += 1\n elif(array[x-3][y+3] == op):\n bad_count += 1\n\n if(count > 0 and bad_count == 0):\n return 10**count\n elif(bad_count > 0 and count == 0):\n return -1*(10**count+1)\n else:\n return 0\n return 0\n\n#Coutns points possible in a left/upward direction\ndef up_left_again(array,x,y):\n user = 'R'\n op = 'B'\n count = 0\n bad_count = 0\n if(x > 2 and y <= 3):\n if(array[x][y] == user):\n count += 1\n elif(array[x][y] == op):\n bad_count += 1\n if(array[x-1][y-1] == user):\n count += 1\n elif(array[x-1][y-1] == op):\n bad_count += 1\n if(array[x-2][y-2] == user):\n count += 1\n elif(array[x-2][y-2] == op):\n bad_count += 1\n if(array[x-3][y-3] == user):\n count += 1\n elif(array[x-3][y-3] == op):\n bad_count += 1\n\n if(count > 0 and bad_count == 0):\n return 10**count\n elif(bad_count > 0 and count == 0):\n return -1*(10**count+1)\n else:\n return 0\n return 0\n\n#Returns points and node of the maximum answer\ndef maxi(board,alpha,beta,depth=1):\n if(depth == 0):\n return [eval(board),1]\n for i in range(7):\n new_board = Board(True,board)\n move_stay = new_board.move(i+1,user)\n if(move_stay == 1):\n continue\n v = mini(new_board.get_array(),alpha,beta,depth-1)\n if v[0] > alpha[0]:\n alpha = [v[0],i+1]\n if beta[0] <= alpha[0]:\n return alpha\n return alpha\n\n#Returns points and node of the minimum answer\ndef mini(board,alpha,beta,depth=1):\n if(depth == 0):\n return [eval(board),1]\n for i in range(7):\n new_board = Board(True,board)\n move_stay = new_board.move(i+1,user)\n if(move_stay == 1):\n continue\n v = maxi(new_board.get_array(),alpha,beta,depth-1)\n if v[0] < beta[0]:\n beta = [v[0],i+1]\n if beta[0] <= alpha[0]:\n return beta\n return beta\n\n#The class that will hold all past moves\nclass Board:\n\n #init a new board, or init it to an older board\n def __init__(self,old=False,bard=False):\n self.board = []\n for i in range(6):\n self.board.append([])\n for j in range(7):\n if old:\n self.board[i].append(bard[i][j])\n else:\n self.board[i].append('*')\n\n #returns an array of the board\n def get_array(self):\n return self.board\n\n #prints the board in a visually pleasing manner\n def pretty_print(self):\n print()\n for i in range (7):\n for j in range(7):\n if(i < 6):\n print(str(self.board[i][j]),end=\"\")\n if(j == 6):\n print(i+1,end=\"\")\n else:\n print(str((j+1)),end=\"\")\n print()\n print()\n\n #applies the users input to the board in a meaningful way\n def move(self,move,user):\n if(int(move) > 7 or int(move) < 1):\n print(\"Please enter a valid move between 1 and 7\")\n else:\n for i in range(5,-1,-1):\n if(self.board[i][int(move)-1] == '*'):\n self.board[i][int(move)-1]= user\n return 0\n if(i == 0):\n #print(\"This column is full, please choose a valid move\")\n return 1\n\n #tests for a win condition in the board\n def won(self,user):\n for i in range(5,-1,-1):\n for j in range(7):\n self.up(user,i,j)\n self.right(user,i,j)\n self.up_left(user,i,j)\n self.up_right(user,i,j)\n\n #Tests for a win condition in the upward direction\n def up(self,user,x,y):\n if(x>=3):\n if(self.board[x][y] == user):\n if(self.board[x-1][y] == user):\n if(self.board[x-2][y] == user):\n if(self.board[x-3][y] == user):\n self.pretty_print()\n print()\n if(user == 'B'):\n print(\"Black player wins!\")\n else:\n print(\"Red player wins!\")\n print()\n sys.exit()\n\n #Tests for a win condition in the right direction\n def right(self,user,x,y):\n if(y <= 3):\n if(self.board[x][y] == user):\n if(self.board[x][y+1] == user):\n if(self.board[x][y+2] == user):\n if(self.board[x][y+3] == user):\n self.pretty_print()\n print()\n if(user == 'B'):\n print(\"Black player wins!\")\n else:\n print(\"Red player wins!\")\n print()\n sys.exit()\n\n #Tests for a win condition in the upward/left direction\n def up_left(self,user,x,y):\n if(x >= 2 and y >= 3):\n if(self.board[x][y] == user):\n if(self.board[x-1][y-1] == user):\n if(self.board[x-2][y-2] == user):\n if(self.board[x-3][y-3] == user):\n self.pretty_print()\n print()\n if(user == 'B'):\n print(\"Black player wins!\")\n else:\n print(\"Red player wins!\")\n print()\n sys.exit()\n\n #Tests for a win condition in the upward/right direction\n def up_right(self,user,x,y):\n if(x >= 2 and y <= 3):\n if(self.board[x][y] == user):\n if(self.board[x-1][y+1] == user):\n if(self.board[x-2][y+2] == user):\n if(self.board[x-3][y+3] == user):\n self.pretty_print()\n print()\n if(user == 'B'):\n print(\"Black player wins!\")\n else:\n print(\"Red player wins!\")\n print()\n sys.exit()\n\n#initialize the board\nboard = Board()\n\n#decides who will go first, you or the computer\nwho = input(\"Who will be the first to go? \")\n\n#Sets the user to the correct initial value\nif(who == 'h'):\n user = 'B'\nelse:\n user = 'R'\n\n#If a command argument for the depth isn't given start with depth of 1\nif(len(sys.argv) == 1):\n depth = 1;\nelse:\n depth = int(sys.argv[1])\n\n#If 42 moves have been made then the game will end\nmoves = 0\n\n#Run the game until a victory or a draw\nwhile True:\n #Print our board\n board.pretty_print()\n\n #If B then human goes, else computer goes\n if(user == 'B'):\n #Read in users move\n where = input(\"Black player, what's your move? \")\n else:\n #decides the computers move\n move = maxi(board.get_array(),[-10**10,1],[10**10,1],depth)\n #move[0] = score of the node, move[1] = nodes postion\n where = move[1]\n print(\"Red Player, what's your move? \"+str(move[1]))\n #Checks if the move you just attempted was valid\n good_move = board.move(where,user)\n\n # If it was a valid move\n if(good_move == 0):\n #check for a winning condition\n board.won(user)\n #increment our move counter\n moves = moves +1\n if(moves == 42):\n print(\"All possible moves have been made. This is a draw\")\n sys.exit()\n\n # Let the other person move\n if(user == 'B'):\n user = 'R'\n else:\n user = 'B'\n","sub_path":"AI/Projects/prj2/working_connect_four_ab.py","file_name":"working_connect_four_ab.py","file_ext":"py","file_size_in_byte":10558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"455591221","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n#\n# Copyright 2014 Measurement Lab\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 socket\n\nclass DNSResolutionError(Exception):\n def __init__(self, hostname):\n Exception.__init__(self, 'Failed to resolve hostname `%s\\'' % hostname)\n\nclass MLabSiteResolver(object):\n def __init__(self):\n self._cache = {}\n\n def get_site_ips(self, site_id, mlab_project):\n \"\"\" Get a list of a Measurement Lab site and slice's addresses.\n\n Args:\n site_id (str): M-Lab site identifier, should be an airport code and\n a two-digit number.\n mlab_project (str): Name of the tool.\n\n Returns:\n list: List of the IP addresses associated with the slices for a tool\n running on the location's M-Lab nodes.\n\n Notes:\n * Different tools generally have their own IP addresses per node. Where\n they do not, the difference should be handled transparently by this\n function.\n \"\"\"\n node_addresses_to_return = []\n\n for node_id in ['mlab1', 'mlab2', 'mlab3']:\n slice_hostname = self._generate_hostname(site_id, node_id, mlab_project)\n ip_address = self._resolve_hostname(slice_hostname)\n node_addresses_to_return.append(ip_address)\n\n return node_addresses_to_return\n\n def _generate_hostname(self, site_id, node_id, mlab_project):\n if mlab_project == 'ndt':\n slice_prefix = \"ndt.iupui\"\n elif mlab_project == 'paris-traceroute':\n slice_prefix = \"npad.iupui\"\n else:\n raise ValueError('UnknownMLabProject')\n\n hostname_format = \"{slice_prefix}.{node_id}.{site_id}.measurement-lab.org\"\n hostname = hostname_format.format(slice_prefix = slice_prefix,\n node_id = node_id,\n site_id = site_id)\n return hostname\n\n def _resolve_hostname(self, hostname):\n if hostname in self._cache:\n return self._cache[hostname]\n\n try:\n ip_address = socket.gethostbyname(hostname)\n except socket.gaierror:\n raise DNSResolutionError(hostname)\n self._cache[hostname] = ip_address\n return ip_address\n\n\ndef parse_pt_data(input_data):\n \"\"\" Takes in all paris-traceroute data returned from a query and transforms\n measurements into a more easily usable data structure.\n\n Args:\n input_data (list): List of dicts with Measurement Lab and web100\n variables for per paris-traceroute hop.\n\n Returns:\n list: List of dictionaries with two keys 'log_time' -- a unixtimestamp\n string -- and 'hops' -- a list of unique hop addresses.\n\n Note:\n * This function is not fully validated, and we caution against its use.\n Path data may include loops or unresponsive hops, which would skew\n the results. Resulting hop set may also be out of original path order.\n\n \"\"\"\n input_data_dict = {}\n\n for data_row in input_data:\n data_row_key = (data_row['connection_spec_server_ip'], data_row['connection_spec_client_ip'], data_row['test_id'])\n\n if not input_data_dict.has_key(data_row_key):\n input_data_dict[data_row_key] = {'log_time': data_row['log_time'], 'hops': [] }\n input_data_dict[data_row_key]['hops'] = [data_row['connection_spec_server_ip'], data_row['connection_spec_client_ip']]\n\n path_position_prior_to_client = len(input_data_dict[data_row_key]['hops']) - 1\n\n if data_row['paris_traceroute_hop_src_ip'] not in input_data_dict[data_row_key]['hops']:\n input_data_dict[data_row_key]['hops'].insert(path_position_prior_to_client, data_row['paris_traceroute_hop_src_ip'])\n path_position_prior_to_client += 1\n\n if data_row['paris_traceroute_hop_dest_ip'] not in input_data_dict[data_row_key]['hops']:\n input_data_dict[data_row_key]['hops'].insert(path_position_prior_to_client, data_row['paris_traceroute_hop_dest_ip'])\n\n return input_data_dict.values()\n","sub_path":"telescope/mlab.py","file_name":"mlab.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"59800379","text":"class Car (object):\n def __init__ (self, price, speed, fuel, mileage):\n self.price = price\n self.speed = speed\n self.fuel = fuel\n self.mileage = mileage\n if price>10000:\n self.tax = 0.15\n else:\n self.tax = 0.12\n print(self.displayAll())\n def displayAll (self):\n info = 'Price: ' + str(self.price) + \"\\nSpeed: \" + str(self.speed) + \"mph\\nFuel: \" + self.fuel + \"\\nMileage: \" + str(self.mileage) + \"mpg\\nTax: \" + str(self.tax) + \"\\n\"\n return info\n\ncar1 = Car (2000, 35, 'Full', 15)\ncar2 = Car (3000, 50, 'Full', 16)\ncar3 = Car (5000, 70, 'Full', 18)\ncar4 = Car (10000, 100, 'Half-way full', 30)\ncar5 = Car (20000, 150, 'Kind of empty', 24)\ncar6 = Car (500000, 200, 'Empty', 100)","sub_path":"car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"294863336","text":"import numpy as np\n\n\n\nclass dataObject():\n '''\n\n '''\n def __init__(self, filepath):\n self.t = 't'\n self.filepath = filepath\n\n self.data = None\n self.rows = None\n self.columns = None\n self.rowRange = None\n self.colRange = None\n self.headerDict = {}\n\n def fillDataArray(self):\n ''' self.data : self.data[row][col] '''\n self.data = np.genfromtxt(self.filepath, delimiter = ';', dtype = None)\n\n self.rows = len(self.data)\n self.columns = len(self.data[0])\n self.rowRange = range(0,self.rows)\n self.colRange = range(0,self.columns)\n\n def decodeData(self):\n ''' Creating self.data with dtype = None, elements byte format, use .decode('UTF-8') '''\n for row in self.rowRange:\n for col in self.colRange:\n self.data[row][col] = self.data[row][col].decode('UTF-8')\n\n def createHeaderDict(self):\n ''' Make dict that connects column title to their column index '''\n for col in self.colRange:\n self.headerDict.append\n\n\n def printFirstRow(self):\n print(self.data[0])\n","sub_path":"dataOrganizer.py","file_name":"dataOrganizer.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"446833414","text":"'''\nfor debug understand dequeue which is only take O(1) time compleixty \n-> LRU, pratice more slidewodown , 2 pointer\n\nhttps://leetcode.com/problems/sliding-window-maximum/discuss/500582/Python-solution-using-deque-with-two-pointer-templates\n\n\n\n'''\n\nimport collections\nif __name__ == '__main__':\n \n def maxSlidingWindow( nums,k):\n \n begin = 0\n q = collections.deque([])\n output = []\n for end in range(len(nums)):\n #######\n\t\t\t## This make sures that the leftmost element must be the largest\n\t\t\t## Note that we are not adding the element but its index\n while q and nums[end] > nums[q[-1]]:\n q.pop()\n\t\t\t#######\n\t\t\t## This makes sure every element will be added into queue\n q.append(end)\n \n\t\t\t## This makes sure that for every sliding window\n\t\t\t## the leftmost element will be removed from the queue \n\t\t\t#### if it is not within the sliding window\n while end - begin + 1 > k:\n begin +=1\n if q[0] < begin:\n print('herere')\n q.popleft()\n \n\t\t\t### for every sliding window\n\t\t\t### we add the leftmost element (maxium within the sliding window) into the output\n if end - begin + 1 == k:\n output.append(nums[q[0]])\n \n return output\n nums = [5,3,4]\n k = 1\n rst = maxSlidingWindow(nums, k)\n print(rst)","sub_path":"Draft/window-sliding.py","file_name":"window-sliding.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"144705906","text":"# IrisTL-PAD solution\n# Created by Cunjian Chen (cunjian@msu.edu)\nfrom ctypes import *\nimport math\nimport random\nimport glob\nimport cv2\nimport os\nimport pickle\nimport sys\nimport datetime\ndef sample(probs):\n s = sum(probs)\n probs = [a/s for a in probs]\n r = random.uniform(0, 1)\n for i in range(len(probs)):\n r = r - probs[i]\n if r <= 0:\n return i\n return len(probs)-1\n\ndef c_array(ctype, values):\n arr = (ctype*len(values))()\n arr[:] = values\n return arr\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\nclass IMAGE(Structure):\n _fields_ = [(\"w\", c_int),\n (\"h\", c_int),\n (\"c\", c_int),\n (\"data\", POINTER(c_float))]\n\nclass METADATA(Structure):\n _fields_ = [(\"classes\", c_int),\n (\"names\", POINTER(c_char_p))]\n\n \n\nlib = CDLL(\"libdarknet.so\", RTLD_GLOBAL)\nlib.network_width.argtypes = [c_void_p]\nlib.network_width.restype = c_int\nlib.network_height.argtypes = [c_void_p]\nlib.network_height.restype = c_int\n\npredict = lib.network_predict\npredict.argtypes = [c_void_p, POINTER(c_float)]\npredict.restype = POINTER(c_float)\n\nset_gpu = lib.cuda_set_device\nset_gpu.argtypes = [c_int]\n\nmake_image = lib.make_image\nmake_image.argtypes = [c_int, c_int, c_int]\nmake_image.restype = IMAGE\n\nmake_boxes = lib.make_boxes\nmake_boxes.argtypes = [c_void_p]\nmake_boxes.restype = POINTER(BOX)\n\nfree_ptrs = lib.free_ptrs\nfree_ptrs.argtypes = [POINTER(c_void_p), c_int]\n\nnum_boxes = lib.num_boxes\nnum_boxes.argtypes = [c_void_p]\nnum_boxes.restype = c_int\n\nmake_probs = lib.make_probs\nmake_probs.argtypes = [c_void_p]\nmake_probs.restype = POINTER(POINTER(c_float))\n\ndetect = lib.network_predict\ndetect.argtypes = [c_void_p, IMAGE, c_float, c_float, c_float, POINTER(BOX), POINTER(POINTER(c_float))]\n\nreset_rnn = lib.reset_rnn\nreset_rnn.argtypes = [c_void_p]\n\nload_net = lib.load_network\nload_net.argtypes = [c_char_p, c_char_p, c_int]\nload_net.restype = c_void_p\n\nfree_image = lib.free_image\nfree_image.argtypes = [IMAGE]\n\nletterbox_image = lib.letterbox_image\nletterbox_image.argtypes = [IMAGE, c_int, c_int]\nletterbox_image.restype = IMAGE\n\nload_meta = lib.get_metadata\nlib.get_metadata.argtypes = [c_char_p]\nlib.get_metadata.restype = METADATA\n\nload_image = lib.load_image_color\nload_image.argtypes = [c_char_p, c_int, c_int]\nload_image.restype = IMAGE\n\nrgbgr_image = lib.rgbgr_image\nrgbgr_image.argtypes = [IMAGE]\n\npredict_image = lib.network_predict_image\npredict_image.argtypes = [c_void_p, IMAGE]\npredict_image.restype = POINTER(c_float)\n\nnetwork_detect = lib.network_detect\nnetwork_detect.argtypes = [c_void_p, IMAGE, c_float, c_float, c_float, POINTER(BOX), POINTER(POINTER(c_float))]\n\ndef classify(net, meta, im):\n out = predict_image(net, im)\n res = []\n for i in range(meta.classes):\n res.append((meta.names[i], out[i]))\n res = sorted(res, key=lambda x: -x[1])\n return res\n\ndef detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45):\n im = load_image(image, 0, 0)\n boxes = make_boxes(net)\n probs = make_probs(net)\n num = num_boxes(net)\n network_detect(net, im, thresh, hier_thresh, nms, boxes, probs)\n res = []\n for j in range(num):\n for i in range(meta.classes):\n if probs[j][i] > 0:\n res.append((meta.names[i], probs[j][i], (boxes[j].x, boxes[j].y, boxes[j].w, boxes[j].h)))\n res = sorted(res, key=lambda x: -x[1])\n free_image(im)\n free_ptrs(cast(probs, POINTER(c_void_p)), num)\n return res\n \nif __name__ == \"__main__\":\n #https://drive.google.com/file/d/1W-UJmD5yJgMKAiPBoSLRV04BR8XuED9c/view?usp=sharing\n net_det = load_net(b\"cfg/detection.cfg\", b\"backup_det/yolo-final.weights\", 0)\n meta_det = load_meta(b\"data/iris_det.data\")\n #https://drive.google.com/file/d/1KF-XhmBIz1EC4LuhBhxB6_VcuiyDhpu3/view?usp=sharing\n net = load_net(b\"cfg/classification.cfg\", b\"backup_crop/classification_60.weights\", 0)\n meta = load_meta(b\"data/LivDet-crop.data\")\n\n test_filenames=glob.glob(sys.argv[1]+'/*.png')\n for filename in test_filenames:\n print(filename)\n path, img_filename = os.path.split(filename)\n # Switch the filename and save the score\n score_filename=img_filename\n score_filename=score_filename[:-4]+'.txt'\n textfile_score=open(path+'/'+score_filename,'w')\n r = detect(net_det, meta_det, bytes(filename,encoding='utf-8'))\n if not r:\n pd_score=1 \n textfile_score.write(\"%s\\n\" % pd_score)\n else:\n box_iris=r[0][2]\n img=cv2.imread(filename)\n height, width, channels = img.shape\n \n center_x=int(box_iris[0])\n center_y=int(box_iris[1])\n box_width=int(box_iris[2])\n box_height=int(box_iris[3]) \n crop_im = img[center_y-int(box_height/2):center_y+int(box_height/2), center_x-int(box_width/2):center_x+int(box_width/2)]\n cv2.imwrite('Evaluation/temp.png',crop_im)\n im = load_image(b'Evaluation/temp.png', 0, 0)\n r = classify(net, meta, im)\n\n if r[0][0]=='Live': \n pd_score=1-r[0][1]\n textfile_score.write(\"%s\\n\" % (1-r[0][1]))\n else:\n pd_score=r[0][1]\n textfile_score.write(\"%s\\n\" % r[0][1])\n \n textfile_score.close() \n","sub_path":"IrisTLPAD_Darknet/IrisTL_PAD_python3.py","file_name":"IrisTL_PAD_python3.py","file_ext":"py","file_size_in_byte":5450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"81251060","text":"import os\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport threading\n\n\ndef track_neace_score():\n print(\"Currently tracking wins...\")\n threading.Timer(1200.0, track_neace_score).start() # called every minute\n ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root\n\n options = Options()\n options.add_argument('--headless')\n options.add_argument('--disable-gpu') # Last I checked this was necessary.\n\n driver = webdriver.Chrome(chrome_options=options)\n driver.get(\"https://fortnitestats.net/stats/n-e-a-c-e\")\n solo_wins = driver.find_element_by_class_name(\"panel-main\").text.splitlines()[0]\n\n with open(ROOT_DIR + \"/wins.txt\", \"w\") as text_file:\n text_file.write(solo_wins)\n\n\ntrack_neace_score()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"611846900","text":"from typing import Dict\n\ndata_structure: Dict[str, str] = {\n 'Вид объекта': 'object_type',\n 'Этажей в доме': 'floors_in_house',\n 'Материал стен': 'wall_material',\n 'Расстояние до города': 'distance_to_city',\n 'Площадь дома': 'house_area',\n 'Площадь участка': 'land_area'\n}\n\n\nclass Cottages:\n id_realty: int\n object_type: str\n floors_in_house: str\n wall_material: str\n distance_to_city: str\n house_area: str\n land_area: str\n\n def __init__(self, id_realty: int, object_type: str, floors_in_house: str, wall_material: str,\n distance_to_city: str, house_area: str, land_area: str) -> None:\n self.id_realty = id_realty\n self.object_type = object_type\n self.floors_in_house = floors_in_house\n self.wall_material = wall_material\n self.distance_to_city = distance_to_city\n self.house_area = house_area\n self.land_area = land_area\n\n def __repr__(self) -> str:\n return f\"\"\"NULL, {self.id_realty}, '{self.object_type}', '{self.floors_in_house}', '{self.wall_material}', \n '{self.distance_to_city}', '{self.house_area}', '{self.land_area}'\"\"\"\n","sub_path":"models/Cottages.py","file_name":"Cottages.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"633791210","text":"__author__ = 'DavidKMYang'\n\n#given a grid and time, average results of multiple models\nimport h5py\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy\nimport os\nimport scipy.io\nimport csv\nimport numpy as np\nimport glob\nimport pandas as pd\nfrom numpy import genfromtxt\nimport math\n\n\n\n\n\ndef BoundSearch():\n\n path_temp = '/Users/DavidKMYang/ClimateResearch/WBGT/corrected_gfdl_tasmax_nh/'\n os.chdir(path_temp)\n file_names_temp = glob.glob(\"*.mat\")\n\n path_wetbulb = '/Users/DavidKMYang/ClimateResearch/WBGT/gfdl_wetbulb/'\n os.chdir(path_wetbulb)\n file_names_wetbulb = glob.glob(\"*.mat\")\n\n path_globe = '/Users/DavidKMYang/ClimateResearch/WBGT/gfdl_globe/'\n os.chdir(path_globe)\n file_names_globe = glob.glob(\"*.mat\")\n\n\n\n for i in range(len(file_names_temp)):\n print (i)\n tempData_temp = scipy.io.loadmat(path_temp + file_names_temp[i])\n\n tempData_Lat_temp = tempData_temp[file_names_temp[i][:-4]+\"_Lat\"]\n tempData_Long_temp = tempData_temp[file_names_temp[i][:-4] + \"_Long\"]\n tempData_Val_temp = tempData_temp[file_names_temp[i][:-4] + \"_Val\"]\n\n tempData_globe = scipy.io.loadmat(path_globe + file_names_globe[i])\n\n tempData_Lat_globe = tempData_globe[file_names_globe[i][:-4]+\"_Lat\"]\n tempData_Long_globe = tempData_globe[file_names_globe[i][:-4] + \"_Long\"]\n tempData_Val_globe = tempData_globe[file_names_globe[i][:-4] + \"_Val\"]\n\n tempData_wetbulb = scipy.io.loadmat(path_wetbulb + file_names_wetbulb[i])\n\n tempData_Lat_wetbulb = tempData_wetbulb[file_names_wetbulb[i][:-4]+\"_Lat\"]\n tempData_Long_wetbulb = tempData_wetbulb[file_names_wetbulb[i][:-4] + \"_Long\"]\n tempData_Val_wetbulb = tempData_wetbulb[file_names_wetbulb[i][:-4] + \"_Val\"]\n\n\n\n globeT = tempData_Val_wetbulb\n\n for k in range(len(tempData_Val_wetbulb)): #lat\n for j in range(len(tempData_Val_wetbulb[0])): #long\n for s in range(len(tempData_Val_wetbulb[0][0])): #day\n print (tempData_Val_temp[k][j][s])\n print (tempData_Val_wetbulb[k][j][s])\n print (tempData_Val_globe[k][j][s])\n break\n # print (\"hi\")\n # print (tempData_Val_temp[k][j][s])\n # print (tempData_rh[2][k][j][s])\n # print (tempData_Val_windspeed[k][j][s])\n # print (tempData_Val_dewpoint[k][j][s])\n globeT[k][j][s] = 0.1* tempData_Val_temp[k][j][s] + 0.7* tempData_Val_wetbulb[k][j][s] + 0.2 * tempData_Val_globe[k][j][s]\n break\n break\n\n final_Lat_List = np.asarray(tempData_Lat_temp)\n final_Long_List = np.asarray(tempData_Long_temp)\n final_Val_List = np.asarray(globeT)\n\n # final_Total_List = np.asarray(final_Lat_List, final_Long_List, final_Val_List)\n scipy.io.savemat('/Users/DavidKMYang/ClimateResearch/WBGT/gfdl_wbgt/' + \"wbgt\" + file_names_globe[i][5:], mdict={\"wbgt\" + file_names_globe[i][5:][:-4] + \"_Lat\" : final_Lat_List, \"wbgt\" + file_names_globe[i][5:][:-4] + \"_Long\" : final_Long_List, \"wbgt\" + file_names_globe[i][5:][:-4] + \"_Val\" : final_Val_List})\n\n\n\nBoundSearch()\n\n","sub_path":"WBGT/WBGT_calc.py","file_name":"WBGT_calc.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"246826463","text":"#!/usr/bin/python\n\nimport math\nimport random\n\ndef tm98_fraction(pulsar):\n \"\"\"\n Tauris and Manchester 1998 beaming fraction\n \"\"\"\n periodterm = math.log10(pulsar.period / 1000.) - 1.0\n\n return 0.03 + 0.09 * periodterm**2.0\n\ndef wj08_fraction(pulsar):\n \"\"\" \n Weltevrede & Johnston 2008 beaming model\n \"\"\"\n if pulsar.chi < 1.0E-5:\n pulsar.chi = 0.\n\n rho = 5.4 * (pulsar.period/1000.)**(-0.5)\n beta_temp = math.degrees(math.acos(random.random()))\n if beta_temp <= rho:\n fraction = 1.\n else:\n fraction = 0.\n\n # get rho and chi in radians for simplicity\n chi_rad = math.radians(pulsar.chi)\n rho_rad = math.radians(rho)\n\n if pulsar.chi > rho and (pulsar.chi + rho)<90.:\n fraction = 2.0 * math.sin(chi_rad) * math.sin(rho_rad)\n elif pulsar.chi>rho and (pulsar.chi + rho) > 90.:\n fraction= math.cos(chi_rad - rho_rad)\n elif pulsar.chi <= rho and (pulsar.chi + rho) < 90.:\n fraction = 1.0 - math.cos(chi_rad + rho_rad)\n else:\n fraction = 1.\n\n\n return fraction\n","sub_path":"lib/python/beaming.py","file_name":"beaming.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"479146232","text":"import pandas as pd\nfrom pathlib import Path\nfrom scipy import misc\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport glob\nfrom sklearn import manifold\n\n# Look pretty...\n\n#img = misc.imread('D:\\\\learning\\\\DAT210x-master\\\\Module4\\\\Datasets\\\\ALOI\\\\32\\\\32_r0.png')\n\nmatplotlib.style.use('ggplot')\n\nspl=glob.glob(\"D:\\\\learning\\\\DAT210x-master\\\\Module4\\\\Datasets\\\\ALOI\\\\32\\*.png\")\n\n\n#\n# TODO: Start by creating a regular old, plain, \"vanilla\"\n# python list. You can call it 'samples'.\n#\n# .. your code here .. \nsamples=[]\n\n# Open a file\n#import os, sys\n\n#path = \"D:\\\\learning\\\\DAT210x-master\\\\Module4\\\\Datasets\\\\ALOI\\\\32\"\n#dirs = os.listdir( path )\n#dirs\n\n#\n# TODO: Write a for-loop that iterates over the images in the\n# Module4/Datasets/ALOI/32/ folder, appending each of them to\n# your list. Each .PNG image should first be loaded into a\n# temporary NDArray, just as shown in the Feature\n# Representation reading.\n#\n# Optional: Resample the image down by a factor of two if you\n# have a slower computer. You can also convert the image from\n# 0-255 to 0.0-1.0 if you'd like, but that will have no\n# effect on the algorithm's results.\n#\n# .. your code here .. \nfor i in range(len(spl)):\n img=misc.imread(spl[i])\n img = img[::2, ::2]\n X = (img / 255.0).reshape(-1)\n samples.append(X)\nsamples\n\n#path = \"D:\\learning\\DAT210x-master\\Module4\\Datasets\\ALOI\\32\"\n#glob.glob('D:\\learning\\DAT210x-master\\Module4\\Datasets\\ALOI\\32\\*.xlsx')\n\n\n#\n# TODO: Once you're done answering the first three questions,\n# right before you converted your list to a dataframe, add in\n# additional code which also appends to your list the images\n# in the Module4/Datasets/ALOI/32_i directory. Re-run your\n# assignment and answer the final question below.\n#\n# .. your code here .. \n\n\n#\n# TODO: Convert the list to a dataframe\n#\n# .. your code here .. \ndf = pd.DataFrame(samples)\ndf\n\n\n#\n# TODO: Implement Isomap here. Reduce the dataframe df down\n# to three components, using K=6 for your neighborhood size\n#\n# .. your code here .. \niso = manifold.Isomap(n_neighbors=2, n_components=3)\niso.fit(df)\nmanifold.Isomap(eigen_solver='auto', max_iter=None, n_components=2, n_neighbors=2,\n neighbors_algorithm='auto', path_method='auto', tol=0)\nT = iso.transform(df)\nab=pd.DataFrame(T)\n\n\n\n#\n# TODO: Create a 2D Scatter plot to graph your manifold. You\n# can use either 'o' or '.' as your marker. Graph the first two\n# isomap components\n#\n# .. your code here .. \n\nab.plot.scatter(x=0, y=1)\n\n\n#\n# TODO: Create a 3D Scatter plot to graph your manifold. You\n# can use either 'o' or '.' as your marker:\n#\n# .. your code here .. \nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.set_xlabel('Final Grade')\nax.set_ylabel('First Grade')\nax.set_zlabel('Daily Alcohol')\n\nax.scatter(ab[0], ab[1],ab[2], c='r', marker='.')\nplt.show()\n\n","sub_path":"assignment5.py","file_name":"assignment5.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"152187523","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Juan Pardo Palazón\n\n# Importacion de librerias\nimport numpy as np\nimport pandas as pd\nimport datetime\n\n\n# In[2]:\n\n\n# Constantes\nDIRECTORIO_BASE = 'D:/anaconda/data/'\nFECHA_MINIMA = '2014-02-01'\nFECHA_MAXIMA = '2015-07-01'\nNOMBRE_FICHERO_ORIGEN = 'CLEAN_House' \nTAMANO_VENTANA = 60 # Ventana de rolling\nCAMPO = 'Aggregate'\nDECIMALES = 2\n\n\n# In[3]:\n\n\ndef obtenerDatosFiltrados(fichero, columna):\n \"\"\"Filtrar por fechas dadas y filtrar los datos de la columna pasada\n por parametro. Se devuelve los datos filtrado de la columna\n \n Argumentos:\n file -- fichero de entrada \n column -- columna a seleccionar\n \"\"\"\n # Leer fichero origen, seleccionar columna consumo total ()\n datos_hogar = pd.read_csv(DIRECTORIO_BASE + fichero +'.csv', delimiter = ',', parse_dates=[0], index_col=0)\n datos_hogar = datos_hogar[[columna]]\n \n # Filtrardo de fechas. Rango de fechas con menor rango datos faltantes\n df_filtrado_fechas = datos_hogar[(datos_hogar.index > FECHA_MINIMA) & (datos_hogar.index < FECHA_MAXIMA)]\n return df_filtrado_fechas\n\n\n# In[4]:\n\n\ndef limpiarDatos(dt_filtrado, rango):\n \"\"\"Limpia los valores NA. para un rango dado\n \n Argumentos:\n dt_filtrado -- tabla con todos los datos \n rango -- rango a filtrar\n \"\"\"\n # Se seleccionan aquellos valores del rango hora\n # pasado por parámetro (0, 6, 12 ó 18)\n dt_filtrado_Rango = dt_filtrado[dt_filtrado_6H.Hora == rango]\n \n # Limpieza de NA\n dt_filtrado_Rango = dt_filtrado_Rango.interpolate(method ='linear', limit_direction ='forward')\n \n return dt_filtrado_Rango\n\n\n# In[5]:\n\n\ndef dfTransform6HFile(fichero, columna):\n \"\"\"Agrupa los datos obtenidos del fichero file\n por rangos de 6H\n \n Argumentos:\n file -- fichero de entrada \n column -- columna a seleccionar\n \"\"\"\n # Obtener data frame filtrado por fechas y con la columna pasada por parametro \n df_filtrado = obtenerDatosFiltrados(fichero, columna)\n \n # Se agrupa por rangos de 6 horas en un día\n dt_filtrado_muestreo6H = df_filtrado.resample('6H').mean()\n \n # Se inserta la columna hora\n hora = dt_filtrado_muestreo6H.index.hour\n dt_filtrado_muestreo6H = pd.concat([dt_filtrado_muestreo6H, pd.DataFrame(hora, index=dt_filtrado_muestreo6H.index)], axis = 1)\n\n # Se renombran columnas\n dt_filtrado_muestreo6H.columns = [columna,'Hora'] \n \n return dt_filtrado_muestreo6H\n\n\n# In[6]:\n\n\ndef generarFicheroSemanal(dt_filtrado_6H, campo):\n \"\"\"Genera para esa semana los valores de consumo\n por los 4 rangos horarios (0, 6, 12, 18)\n \n Argumentos:\n dt_filtrado_6H -- datos a transformar \n campo -- campo a seleccionar\n \"\"\"\n # Limpiar datos\n datos_filtrar_0 = limpiarDatos(dt_filtrado_6H, 0)\n datos_filtrar_6 = limpiarDatos(dt_filtrado_6H, 6)\n datos_filtrar_12 = limpiarDatos(dt_filtrado_6H, 12)\n datos_filtrar_18 = limpiarDatos(dt_filtrado_6H, 18)\n\n # Filtrar por hora y obtener los datos agrupados por semana\n dt_filtrado_6H_Semana = datos_filtrar_0.resample(\"W\").mean().apply(lambda x: round(x, DECIMALES))\n w6 = datos_filtrar_6.resample(\"W\").mean().apply(lambda x: round(x, DECIMALES))\n w12 = datos_filtrar_12.resample(\"W\").mean().apply(lambda x: round(x, DECIMALES))\n w18 = datos_filtrar_18.resample(\"W\").mean().apply(lambda x: round(x, DECIMALES))\n \n # Preparar fichero por rangos\n dt_filtrado_6H_Semana['Rango 06-12'] = w6[campo]\n dt_filtrado_6H_Semana['Rango 12-18'] = w12[campo]\n dt_filtrado_6H_Semana['Rango 18-00'] = w18[campo]\n dt_filtrado_6H_Semana = dt_filtrado_6H_Semana.drop(columns=['Hora'])\n dt_filtrado_6H_Semana = dt_filtrado_6H_Semana.rename(columns={campo: 'Rango 00-06'})\n\n return dt_filtrado_6H_Semana\n\n\n# In[7]:\n\n\n# Generar los ficheros con los datos filtrados\nfor num_hogar in range(1, 22):\n if num_hogar != 14:\n \n fichero = NOMBRE_FICHERO_ORIGEN + str(num_hogar)\n \n # Filtrar por fechas los datos del campo seleccionado\n dt_filtrado_6H = dfTransform6HFile(fichero, CAMPO)\n \n # Generar fichero con los valores energéticos agrupados por fechas\n dt_filtrado_6H_Semana = generarFicheroSemanal(dt_filtrado_6H, CAMPO)\n \n # Se ajustan los datos agrupados\n if num_hogar in [6]:\n dt_filtrado_6H_Semana.iloc[9:-4, :].to_csv('Hogar_' + str(num_hogar) + '_filtro_semanal_rango_NR.csv', sep=',', encoding='utf-8')\n \n if num_hogar in [3, 11]:\n dt_filtrado_6H_Semana.iloc[4:-5, :].to_csv('Hogar_' + str(num_hogar) + '_filtro_semanal_rango_NR.csv', sep=',', encoding='utf-8')\n \n if num_hogar in [4, 5, 12, 15, 16, 18, 21]:\n dt_filtrado_6H_Semana.iloc[5:-4, :].to_csv('Hogar_' + str(num_hogar) + '_filtro_semanal_rango_NR.csv', sep=',', encoding='utf-8')\n \n if num_hogar in [10]:\n dt_filtrado_6H_Semana.iloc[6:-5, :].to_csv('Hogar_' + str(num_hogar) + '_filtro_semanal_rango_NR.csv', sep=',', encoding='utf-8')\n \n if num_hogar in [1, 2, 7, 8, 9, 13, 14, 17, 19, 20]:\n dt_filtrado_6H_Semana.iloc[4:-4, :].to_csv('Hogar_' + str(num_hogar) + '_filtro_semanal_rango_NR.csv', sep=',', encoding='utf-8')\n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"CODE/01b_Generar_datos_limpiados_semanal_rango_horario.py","file_name":"01b_Generar_datos_limpiados_semanal_rango_horario.py","file_ext":"py","file_size_in_byte":5286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"615827810","text":"import datetime\r\nimport os\r\ntoday=datetime.date.today()\r\nnet_records = []\r\nerror_list=[]\r\n\r\n\r\ntry:\r\n \r\n from sony import *\r\n net_records = net_records + records\r\nexcept:\r\n error_list.append(\"SONY\")\r\ntry:\r\n from maze import *\r\n net_records = net_records + records\r\nexcept:\r\n error_list.append(\"MAZE\")\r\ntry:\r\n from panasonic import *\r\n net_records = net_records + records\r\nexcept:\r\n error_list.append(\"PANASONIC\")\r\n\r\n\r\nimport pandas as pd\r\n\r\npath='C:\\\\LavaWebScraper\\\\countrywise\\\\'\r\ndf = pd.DataFrame(net_records, columns = ['COUNTRY', 'COMPANY', 'MODEL', 'USP', 'DISPLAY', 'CAMERA', 'MEMORY', 'BATTERY', 'THICKNESS', 'PROCESSOR', 'EXTRAS/ LINKS'])\r\ndf.to_csv(os.path.join(path,str(today)+'(JAPAN).csv'), index=False, encoding='utf-8')\r\n\r\n","sub_path":"japan.py","file_name":"japan.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"81118892","text":"import os.path\nimport networkx as nx\nfrom networkx.algorithms.traversal.depth_first_search import dfs_tree\nimport json\nimport glob\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom os.path import join\nimport math\nfrom collections import OrderedDict\nfrom operator import itemgetter\nimport csv\nimport time\nfrom datetime import timedelta\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom datetime import datetime\n\nanalyser = SentimentIntensityAnalyzer()\n\nPath=\"C:\\dataset\\Politifact\\\\temp2\"\n\ndatetimeFormat = \"%a %b %d %H:%M:%S %Y\"\n\ninterval=14\n\nconst=24\n\ndef calBaseTime(times):\n\n sortedDictT = sorted(\n times.items(),\n key=lambda x: datetime.strptime(x[1], '%a %b %d %H:%M:%S %Y'), reverse=False\n )\n t = next(iter(sortedDictT))\n return(t[1])\n\ndef ComputeFtlr(G):\n\n hours=0\n dictTweet={}\n dictRetweet={}\n for node in G.nodes(data=True):\n if(node[1]['id']==2):\n dictTweet[node[0]]=node[1]['CreatedAt']\n for node in G.nodes(data=True):\n if(node[1]['id']==3):\n dictRetweet[node[0]]=node[1]['CreatedAt']\n if(len(dictTweet) > 0 and len(dictRetweet)> 0):\n sortedDictT = sorted(\n dictTweet.items(),\n key=lambda x: datetime.strptime(x[1], '%a %b %d %H:%M:%S %Y'), reverse=False\n )\n sortedDictR = sorted(\n dictRetweet.items(),\n key=lambda x: datetime.strptime(x[1], '%a %b %d %H:%M:%S %Y'), reverse=True\n )\n tw = next(iter(sortedDictT))\n rw = next(iter(sortedDictR))\n diff = datetime.strptime(rw[1], datetimeFormat) - datetime.strptime(tw[1], datetimeFormat)\n hours = (diff.days) * 24 + (diff.seconds) / 3600\n\n return hours\n\ndef calTime(tid):\n ctime=\"\"\n with open ('retweets.json') as ReFile:\n rdata=json.load(ReFile)\n if(len(rdata[tid])>0):\n ctime=rdata[tid][0]['retweeted_status']['created_at']\n return ctime\n\ndef UsrInfo(data):\n list=[]\n flag=\"normal\"\n followers=data['followers_count']\n friends=data['friends_count']\n if(friends>0):\n result = followers / friends\n if (result > 1):\n flag = \"leader\"\n vfi=data['verified']\n favorit_count=data['favourites_count']\n sts_count=data['statuses_count']\n list.append(flag)\n list.append(vfi)\n list.append(favorit_count)\n list.append(sts_count)\n return list\n\ndef totalNode(G):\n tnode=len(G.nodes())-1\n return tnode\n\ndef findTtw(G):\n counter=0\n for node in G.nodes(data=True):\n if(node[1]['id']==2):\n counter+=1\n return counter\n\ndef findTrw(G):\n counter=0\n for node in G.nodes(data=True):\n if(node[1]['id']==3):\n counter+=1\n return counter\n\ndef findTrp(G):\n counter=0\n for node in G.nodes(data=True):\n if(node[1]['id']==4):\n counter+=1\n return counter\n\ndef findTws(G):\n counter=0\n for node in G.nodes(data=True):\n if (node[1]['id'] == 2):\n print(node[0])\n li = list(G.successors())\n if(len(li) == 0 ):\n counter+=1\n return counter\n\ndef NumOutDegree(G):\n dict={}\n for n in G.nodes(data=True):\n if(n[1]['id'] == 2):\n if (len(list(G.successors(n[0]))) > 0):\n sum = len(list(G.successors(n[0])))\n dict[n[0]] = sum\n return dict\n\ndef NumMaxOutStsRe(dict,max,G):\n usrSts={}\n usrSts['normal']=0\n usrSts['leader']=0\n if(max>0):\n li = list(dict.keys())[list(dict.values()).index(max)]\n Gtemp = dfs_tree(G, li)\n Gtemp.add_nodes_from((i, G.nodes[i]) for i in Gtemp.nodes)\n for node in Gtemp.nodes(data=True):\n if(node[1]['id']==3):\n if (node[1]['usrType'] == \"normal\"):\n usrSts['normal'] += 1\n elif (node[1]['usrType'] == \"leader\"):\n usrSts['leader'] += 1\n return usrSts\n\ndef NumEngageTwMOut(dict,max,G):\n engage=0\n if(max>0):\n li = list(dict.keys())[list(dict.values()).index(max)]\n Gtemp = dfs_tree(G, li)\n engage += len(Gtemp.nodes()) - 1\n return engage\n\ndef MaxOutDegree(dict):\n li=[]\n max=0\n for x in dict.values():\n li.append(x)\n arr=np.array(li)\n if(len(arr)>0):\n max=np.max(arr)\n return(max)\n\ndef NumVrfRe(G):\n counter=0\n for node in G.nodes(data=True):\n if(node[1]['id']==3):\n if(node[1]['user'][1]!= False):\n counter+=1\n return counter\n\ndef NumStsRe(G):\n dict={}\n dict['normal']=0\n dict['leader']=0\n for node in G.nodes(data=True):\n if(node[1]['id']==3):\n if(node[1]['user'][0]==\"normal\"):\n dict['normal']+=1\n elif(node[1]['user'][0]==\"leader\"):\n dict['leader'] += 1\n return dict\n\ndef totalHeight(G):\n finalList=[]\n finalResult=0\n for node in G.nodes(data=True):\n if (node[1]['id']==2):\n li=[]\n dict=nx.shortest_path_length(G,node[0])\n for val in dict.values():\n li.append(val)\n arr=np.array(li)\n if(len(arr)>0):\n max=np.max(arr)\n finalList.append(max)\n f_arr=np.array(finalList)\n if(len(f_arr) > 0):\n finalResult=np.max(f_arr)\n return (finalResult+1)\n\ndef calFrequency(G):\n hours = 0\n dictEngage = {}\n for node in G.nodes(data=True):\n if (node[1]['id'] != 1):\n dictEngage[node[0]] = node[1]['CreatedAt']\n if (len(dictEngage) >0 ):\n sortedDictT = sorted(\n dictEngage.items(),\n key=lambda x: datetime.strptime(x[1], '%a %b %d %H:%M:%S %Y'), reverse=False\n )\n\n sortedDictR = sorted(\n dictEngage.items(),\n key=lambda x: datetime.strptime(x[1], '%a %b %d %H:%M:%S %Y'), reverse=True\n )\n tw = next(iter(sortedDictT))\n rw = next(iter(sortedDictR))\n # print(tw)\n # print(rw)\n diff = datetime.strptime(rw[1], datetimeFormat) - datetime.strptime(tw[1], datetimeFormat)\n hours = (diff.days) * 24 + (diff.seconds) / 3600\n return hours\n\ndef meanPuser(G):\n counter = 1\n total=0\n for node in G.nodes(data=True):\n if (node[1]['id'] == 3):\n counter+=1\n total += node[1]['user'][3]\n return total/counter\n\ndef sentiment_analyzer_scores(sentence):\n\n score = analyser.polarity_scores(sentence)\n return score\n\ndef crtStanceNet(G):\n Gp=nx.Graph()\n for node in G.nodes(data=True):\n if node[1]['id']==4:\n pid=node[0]\n sentence=node[1]['text']\n score=sentiment_analyzer_scores(sentence)\n s = score['compound']\n Gp.add_node(pid,score=s)\n n_list = list(Gp.nodes(data=True))\n for i in range(len(n_list)):\n sen1 = n_list[i][1]['score']\n for j in range(len(n_list)):\n sen2 = n_list[j][1]['score']\n if i != j and nodes_connected(Gp,n_list[i][0],n_list[j][0]) == False and abs(sen1 - sen2) < .5:\n Gp.add_edge(n_list[i][0], n_list[j][0], weight = 1 / (abs(sen1 - sen2) + .01))\n return Gp\n\ndef nodes_connected(Gp,u, v):\n return u in Gp.neighbors(v)\n\ndef TotalSen(Gp):\n score=0\n for node in Gp.nodes(data=True):\n score+=node[1]['score']\n return score\n\ndef DicSen(Gp):\n dic={}\n for node in Gp.nodes(data=True):\n dic[node[0]]=node[1]['score']\n return dic\n\ndef key_func(x):\n return x[-9:]\nfor news in sorted(os.listdir(Path),key=lambda x: int(x.split('.')[0][0:3])):\n\n print(news)\n data=[]\n G = nx.read_gpickle(join(Path,news))\n #emptyTw = findTws(G)\n #list.append(emptyTw)\n total=totalNode(G)\n data.append(total)\n totalTweet=findTtw(G)\n data.append(totalTweet)\n totalRetweet=findTrw(G)\n data.append(totalRetweet)\n totalReply=findTrp(G)\n data.append(totalReply)\n #dict=NumOutDegree(G)\n #maxOutDeg=MaxOutDegree(dict)\n #list.append(maxOutDeg)\n height=totalHeight(G)\n data.append(height)\n H=calFrequency(G)\n frequency=H/total\n frequency=round(frequency,2)\n data.append(frequency)\n vrfUsr=NumVrfRe(G)\n data.append(vrfUsr)\n dict=NumStsRe(G)\n numofNormal=dict['normal']\n numofLeader=dict['leader']\n data.append(numofNormal)\n data.append(numofLeader)\n Gp=crtStanceNet(G)\n totalSentiment=TotalSen(Gp)\n totalSentiment=round(totalSentiment,2)\n data.append(totalSentiment)\n # diameter=0\n # if(len(Gp.nodes())>0):\n # diameter=nx.diameter(Gp)\n # data.append(diameter)\n dicSen=DicSen(Gp)\n cent=0\n if(len(Gp)>0):\n centDic=nx.betweenness_centrality(Gp)\n pid=next(iter(centDic))\n cent=dicSen[pid]\n cent=round(cent,2)\n data.append(cent)\n #arr=np.array(data)\n #print(data)\n with open(\"temp_real.csv\", \"a\",newline='') as fp:\n wr = csv.writer(fp)\n wr.writerow(data)\n","sub_path":"Fakeds.py","file_name":"Fakeds.py","file_ext":"py","file_size_in_byte":8921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"509588247","text":"class powtwo:\r\n\t\"\"\"class to implement the power of two\"\"\"\r\n\tdef __init__(self,max):\r\n\t\tself.max=max\r\n\r\n\tdef __iter__(self):\r\n\t\tself.n=0\r\n\t\treturn self\r\n\r\n\tdef __next__(self):\r\n\t\tif self.n<=self.max:\r\n\t\t\tr=2**self.n\r\n\t\t\tself.n+=1\r\n\t\t\treturn r\r\n\t\telse:\r\n\t\t\traise StopIteration\r\n\r\na=powtwo(4)\r\ni=iter(a)\r\n\r\nprint(next(i))\r\nprint(next(i))\r\nprint(next(i))\r\n\r\n\r\n","sub_path":"python/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"405040154","text":"import re\nimport sys\n\nimport ir\nimport spirv\n\n\ndef output_instruction(stream, module, inst, is_raw_mode, indent=' '):\n \"\"\"Output one instruction.\"\"\"\n line = indent\n if inst.result_id is not None:\n result_id = inst.result_id\n if result_id in module.id_to_symbol_name:\n result_id = module.id_to_symbol_name[result_id]\n line = line + result_id + ' = '\n line = line + inst.op_name\n if inst.type_id is not None:\n line = line + ' ' + module.type_id_to_name[inst.type_id]\n\n if not is_raw_mode:\n line = line + format_decorations_for_inst(module, inst)\n\n if inst.operands:\n line = line + ' '\n for operand in inst.operands:\n if operand in module.id_to_symbol_name:\n operand = module.id_to_symbol_name[operand]\n if operand in module.type_id_to_name:\n operand = module.type_id_to_name[operand]\n line = line + operand + ', '\n line = line[:-2]\n\n stream.write(line + '\\n')\n\n\ndef get_decorations(module, inst_id):\n decorations = []\n for inst in module.global_insts:\n if inst.op_name == 'OpDecorate' and inst.operands[0] == inst_id:\n decorations.append(inst)\n return decorations\n\n\ndef get_symbol_name(module, symbol_id):\n if symbol_id in module.id_to_symbol_name:\n return module.id_to_symbol_name[symbol_id]\n\n for inst in module.global_insts:\n if inst.op_name == 'OpName' and inst.operands[0] == symbol_id:\n name = inst.operands[1]\n name = name[1:-1]\n\n # glslang tend to add type information to function names.\n # E.g. \"foo(vec4)\" get the symbol name \"foo(vf4;\"\n # Truncate such names to fit our IL.\n regex = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*')\n match = regex.match(name)\n new_name = match.group(0)\n if new_name != name:\n sys.stderr.write('warning: truncated symbol name \"'\n + name + '\" to \"' + new_name + '\"\\n')\n\n symbol_name = '%' + new_name\n break\n else:\n symbol_name = '%' + symbol_id[1:]\n\n module.id_to_symbol_name[symbol_id] = symbol_name\n\n return symbol_name\n\n\ndef format_decoration(decoration_inst):\n res = decoration_inst.operands[1]\n if decoration_inst.operands[2:]:\n res = res + '('\n for param in decoration_inst.operands[2:]:\n res = res + param + ', '\n res = res[:-2] + ')'\n return res\n\n\ndef format_decorations_for_inst(module, inst):\n line = ''\n decorations = get_decorations(module, inst.result_id)\n for decoration in decorations:\n line = line + ' ' + format_decoration(decoration)\n return line\n\n\ndef add_type_if_needed(module, inst, needed_types):\n if inst.op_name in spirv.TYPE_DECLARATION_INSTRUCTIONS:\n if inst.op_name != 'OpTypeFunction':\n if module.type_id_to_name[inst.result_id] == inst.result_id:\n needed_types.add(inst.result_id)\n for operand in inst.operands:\n if operand[0] == '%':\n type_inst = module.id_to_inst[operand]\n add_type_if_needed(module, type_inst, needed_types)\n if inst.type_id is not None:\n if module.type_id_to_name[inst.type_id] == inst.type_id:\n needed_types.add(inst.type_id)\n\n\ndef get_needed_types(module):\n needed_types = set()\n for inst in module.instructions():\n if inst.op_name not in spirv.TYPE_DECLARATION_INSTRUCTIONS:\n add_type_if_needed(module, inst, needed_types)\n return needed_types\n\n\ndef output_global_instructions(stream, module, is_raw_mode, names, newline=True):\n for inst in module.global_insts:\n if inst.op_name in names:\n if newline:\n stream.write('\\n')\n newline = False\n output_instruction(stream, module, inst, is_raw_mode, indent='')\n\n\ndef output_basic_block(stream, module, basic_block):\n \"\"\"Output one basic block.\"\"\"\n stream.write(basic_block.inst.result_id + ':\\n')\n for inst in basic_block.insts:\n output_instruction(stream, module, inst, False)\n\n\ndef output_function_raw(stream, module, func):\n \"\"\"Output one function (raw mode).\"\"\"\n stream.write('\\n')\n noindent_names = ['OpFunction', 'OpLabel', 'OpFunctionParameter',\n 'OpFunctionEnd']\n for inst in func.instructions():\n if inst.op_name in noindent_names:\n indent = ''\n else:\n indent = ' '\n output_instruction(stream, module, inst, True, indent=indent)\n\n\ndef output_function(stream, module, func):\n \"\"\"Output one function (pretty-printed mode).\"\"\"\n stream.write('\\n')\n symbol_name = get_symbol_name(module, func.inst.result_id)\n line = 'define ' + module.type_id_to_name[func.inst.type_id] + ' '\n line = line + symbol_name + '('\n for inst in func.arguments:\n line = line + module.type_id_to_name[inst.type_id]\n line = line + ' ' + inst.result_id + ', '\n if line[-2:] == ', ':\n line = line[:-2]\n line = line + ') {\\n'\n stream.write(line)\n\n for basic_block in func.basic_blocks:\n if basic_block != func.basic_blocks[0]:\n stream.write('\\n')\n output_basic_block(stream, module, basic_block)\n\n stream.write('}\\n')\n\n\ndef output_functions(stream, module, is_raw_mode):\n \"\"\"Output all functions.\"\"\"\n for func in module.functions:\n if is_raw_mode:\n output_function_raw(stream, module, func)\n else:\n output_function(stream, module, func)\n\n\ndef generate_global_symbols(module):\n \"\"\"Add function/global varible names to the symbol table.\"\"\"\n for func in module.functions:\n get_symbol_name(module, func.inst.result_id)\n for inst in module.global_insts:\n if inst.op_name == 'OpVariable':\n get_symbol_name(module, inst.result_id)\n\n\ndef add_type_name(module, inst):\n if inst.op_name == 'OpTypeVoid':\n type_name = 'void'\n elif inst.op_name == 'OpTypeBool':\n type_name = 'bool'\n elif inst.op_name == 'OpTypeInt':\n width = inst.operands[0]\n if width not in ['8', '16', '32', '64']:\n raise ir.IRError(\"Invalid OpTypeInt width \" + width)\n signedness = inst.operands[1]\n if not signedness in ['0', '1']:\n error = \"Invalid OpTypeInt signedness \" + str(signedness)\n raise ir.IRError(error)\n type_name = 's' if signedness else 'u'\n type_name = type_name + width\n elif inst.op_name == 'OpTypeFloat':\n width = inst.operands[0]\n if width not in ['16', '32', '64']:\n raise ir.IRError(\"Invalid OpTypeFloat width \" + width)\n type_name = 'f' + width\n elif inst.op_name == 'OpTypeVector':\n component_type = module.type_id_to_name[inst.operands[0]]\n count = inst.operands[1]\n if int(count) not in range(2, 16):\n error = \"Invalid OpTypeVector component count \" + str(count)\n raise ir.IRError(error)\n type_name = '<' + str(count) + ' x ' + component_type + '>'\n else:\n type_name = inst.result_id\n\n module.type_id_to_name[inst.result_id] = type_name\n\n\ndef add_type_names(module):\n for inst in module.global_insts:\n if inst.op_name in spirv.TYPE_DECLARATION_INSTRUCTIONS:\n add_type_name(module, inst)\n\n\ndef write_module(stream, module, is_raw_mode=False):\n module.id_to_symbol_name = {}\n module.type_id_to_name = {}\n try:\n module.finalize()\n\n add_type_names(module)\n if not is_raw_mode:\n generate_global_symbols(module)\n\n for name in spirv.INITIAL_INSTRUCTIONS:\n if name != 'OpExtInstImport':\n output_global_instructions(stream, module, is_raw_mode, [name],\n newline=False)\n output_global_instructions(stream, module, is_raw_mode,\n ['OpExtInstImport'])\n\n if is_raw_mode:\n output_global_instructions(stream, module, is_raw_mode,\n spirv.DEBUG_INSTRUCTIONS)\n output_global_instructions(stream, module, is_raw_mode,\n spirv.DECORATION_INSTRUCTIONS)\n output_global_instructions(stream, module, is_raw_mode,\n spirv.TYPE_DECLARATION_INSTRUCTIONS)\n else:\n needed_types = get_needed_types(module)\n if needed_types:\n stream.write('\\n')\n for inst in module.global_insts:\n if inst.result_id in needed_types:\n output_instruction(stream, module, inst, is_raw_mode,\n indent='')\n\n output_global_instructions(stream, module, is_raw_mode,\n spirv.CONSTANT_INSTRUCTIONS)\n output_global_instructions(stream, module, is_raw_mode,\n spirv.GLOBAL_VARIABLE_INSTRUCTIONS)\n output_functions(stream, module, is_raw_mode)\n finally:\n del module.type_id_to_name\n del module.id_to_symbol_name\n","sub_path":"write_il.py","file_name":"write_il.py","file_ext":"py","file_size_in_byte":9201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"279572265","text":"import random\nimport math\nfrom strategy import Strategy, Candidate\nfrom output import format_dance\n\nclass Genetic(Strategy):\n def __init__(self, name, population_size, random_dance_generator, scoring):\n super(Genetic, self).__init__(name, random_dance_generator, scoring)\n self.population_size = population_size\n self.population = self.generate_population() # List of candidates\n scores = [c.scores.total_score for c in self.population]\n self.sumn = sum(scores)\n self.sumn2 = sum([x * x for x in scores])\n\n def iterate(self):\n pass\n\n def replace(self, index, new_dance):\n old_candidate = self.population[index]\n new_candidate = self.create_and_track_candidate(new_dance)\n self.population[index] = new_candidate\n\n # Update stats\n self.sumn = self.sumn - old_candidate.scores.total_score + new_candidate.scores.total_score\n self.sumn2 = self.sumn2 - (old_candidate.scores.total_score * old_candidate.scores.total_score) + (new_candidate.scores.total_score * new_candidate.scores.total_score)\n\n def crossover_single_gene(self, dance1, dance2):\n \"\"\"Creates two children by switching a single gene between the parents\"\"\"\n index = random.randrange(len(dance1))\n child1 = dance1[: index] + dance2[index : index + 1] + dance1[index+1 :]\n child2 = dance2[: index] + dance1[index : index + 1] + dance2[index+1 :]\n return child1, child2\n\n def crossover_gene_range(self, dance1, dance2):\n \"\"\"Creates two children by switching a set of genes between the parents\"\"\"\n index1 = random.randrange(len(dance1))\n index2 = index1 + random.randrange(len(dance1) - index1)\n child1 = dance1[: index1] + dance2[index1 : index2] + dance1[index2 :]\n child2 = dance2[: index1] + dance1[index1 : index2] + dance2[index2 :]\n return child1, child2\n\n def crossover_random_genes(self, dance1, dance2):\n \"\"\"Creates two children by randomly selecting between the parents for each gene\"\"\"\n dance_size = len(dance1)\n bitmask = random.getrandbits(dance_size)\n child1=[None] * dance_size\n child2=[None] * dance_size\n for i in range(dance_size):\n if bitmask & 1 == 0:\n child1[i] = dance1[i]\n child2[i] = dance2[i]\n else:\n child1[i] = dance2[i]\n child2[i] = dance1[i]\n bitmask = bitmask >> 1\n return child1, child2\n\n def mutate_single_gene(self, dance):\n random_dance = self.random_dance_generator()\n child1, child2 = self.crossover_single_gene(dance, random_dance)\n return child1\n\n def mutate_gene_range(self, dance):\n random_dance = self.generate_dance()\n child1, child2 = self.crossover_gene_range(dance, random_dance)\n return child1\n\n def output_stats(self, count, file):\n \"\"\"Override the default to also include stddev\"\"\"\n mean = self.sumn / self.population_size\n var = (self.sumn2 - (self.sumn * self.sumn / self.population_size)) / (self.population_size - 1)\n std_dev = math.sqrt(var)\n print(count, self._best_candidate.scores.total_score, mean, std_dev, file=file)\n\n def find_best_index(self, num_selections):\n \"\"\"Finds the fittest amongst a sample of n\"\"\"\n best_index = -1\n best_scores = None\n for i in range(num_selections):\n index = random.randrange(self.population_size)\n scores = self.population[index].scores\n if best_index == -1 or scores.total_score > best_scores.total_score:\n best_index = index\n best_scores = scores\n return best_index\n\n def find_worst_index(self, num_selections):\n \"\"\"Finds the least fit amongst a sample of n\"\"\"\n best_index = -1\n best_scores = None\n for i in range(num_selections):\n index = random.randrange(self.population_size)\n scores = self.population[index].scores\n if best_index == -1 or scores.total_score < best_scores.total_score:\n best_index = index\n best_scores = scores\n return best_index\n\n def generate_population(self):\n print(\"Generating initial population of size %s\" % self.population_size)\n return [self.create_and_track_candidate(self.generate_dance()) for i in range(self.population_size)]\n\n","sub_path":"genetic.py","file_name":"genetic.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"259472664","text":"import SurviveActions, SurviveAuto, SurviveGame\r\nimport copy, random, threading\r\n\r\nmutation_chance = 0.05\r\npopulation = 100\r\ngenerations = 30\r\ntries = 10\r\n\r\nclass Individual(object):\r\n def __init__(self, generation=0):\r\n self.hiscore = (0, 0)\r\n self.generation = generation\r\n self.DNA = []\r\n permutation = list(range(len(SurviveActions.functions)))\r\n random.shuffle(permutation)\r\n for i in permutation:\r\n fun, params, chfun = SurviveActions.functions[i]\r\n params = params()\r\n self.DNA += [(fun, params, chfun)]\r\n\r\n def __str__(self):\r\n string = \"\"\r\n string += \"Generation: \" + repr(self.generation) + '\\n'\r\n string += \"DNA:\\n\"\r\n for gene in self.DNA:\r\n string += '\\t' + gene[0].__name__ + \"\\t=\\t\" + repr(gene[1]) + '\\n'\r\n return string\r\n\r\n def mate(self, other):\r\n \"\"\"\r\n Mating works by taking the function order from self, and the parameter values from other, with some chance of mutation.\r\n \"\"\"\r\n child = Individual(self.generation+1)\r\n child.DNA = copy.copy(self.DNA)\r\n for i in range(len(child.DNA)):\r\n child_gene = child.DNA[i]\r\n for other_gene in other.DNA:\r\n if child_gene[0].__name__ == other_gene[0].__name__:\r\n new_params = other_gene[1]\r\n if random.random() < mutation_chance:\r\n chfun = child_gene[2]\r\n new_params = chfun(new_params)\r\n child_gene = (child_gene[0], new_params, child_gene[2])\r\n child.DNA[i] = child_gene\r\n return child\r\n\r\nif __name__ == '__main__':\r\n players = [Individual() for _ in range(population)]\r\n for i in range(2):\r\n for player in players:\r\n game_scores = []\r\n for j in range(tries):\r\n game = SurviveGame.Game(ticks_per_second=SurviveAuto.tps, zombies=SurviveAuto.zombies)\r\n gamethread = threading.Thread(target=SurviveAuto.game_loop, args=(game,))\r\n #gamethread.daemon = True\r\n gamethread.start()\r\n SurviveAuto.auto_loop(game, player)\r\n game_scores += [(game.score, game.max_score)]\r\n gamethread.join()\r\n gamethread = None\r\n scores, max_scores = zip(*game_scores)\r\n score = round(sum(scores)/len(scores))\r\n max_score = round(sum(max_scores)/len(max_scores))\r\n player.hiscore = (score, max_score)\r\n print(\"player\", i, \"has\", player.hiscore)\r\n","sub_path":"SurviveEvolve.py","file_name":"SurviveEvolve.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"504949037","text":"import click\nimport sys\n\n\n@click.group()\ndef cli():\n \"\"\"Command line interface for template plugin\"\"\"\n pass\n\n\n@cli.command()\ndef list(): # pylint: disable=redefined-builtin\n \"\"\"\n Display all KkrstructureData nodes\n \"\"\"\n from aiida import is_dbenv_loaded, load_dbenv\n if not is_dbenv_loaded():\n load_dbenv()\n\n from aiida.orm.querybuilder import QueryBuilder\n from aiida.orm import DataFactory\n KKrStructure = DataFactory('kkr.kkrstructure')\n\n qb = QueryBuilder()\n qb.append(KkrStructure)\n results = qb.all()\n\n s = \"\"\n for result in results:\n obj = result[0]\n s += \"{}, pk: {}\\n\".format(str(obj), obj.pk)\n sys.stdout.write(s)\n","sub_path":"aiida_kkr/cmdline/data_cli.py","file_name":"data_cli.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"382958550","text":"# noinspection PyPackageRequirements\nimport datawrangler as dw\nimport numpy as np\nimport pandas as pd\n\nfrom .common import Manipulator\n\n\n# noinspection PyShadowingBuiltins\ndef fitter(data, axis=0):\n if axis == 1:\n return dw.core.update_dict(fitter(data.T, axis=0), {'transpose': True})\n elif axis != 0:\n raise ValueError('axis must be either 0 or 1')\n\n mean = pd.Series(index=data.columns)\n std = pd.Series(index=data.columns)\n\n for c in data.columns:\n mean[c] = data[c].mean(axis=0)\n std[c] = data[c].std(axis=0)\n\n return {'mean': mean, 'std': std, 'axis': axis, 'transpose': False}\n\n\n# noinspection DuplicatedCode\ndef transformer(data, **kwargs):\n transpose = kwargs.pop('transpose', False)\n assert 'axis' in kwargs.keys(), ValueError('Must specify axis')\n\n if transpose:\n return transformer(data.T, **dw.core.update_dict(kwargs, {'axis': int(not kwargs['axis'])})).T\n\n assert kwargs['axis'] == 0, ValueError('invalid transformation')\n\n z = data.copy()\n for c in z.columns:\n z[c] -= kwargs['mean'][c]\n z[c] /= kwargs['std'][c]\n return z\n\n\nclass ZScore(Manipulator):\n # noinspection PyShadowingBuiltins\n def __init__(self, axis=0):\n required = ['transpose', 'mean', 'std', 'axis']\n super().__init__(axis=axis, fitter=fitter, transformer=transformer, data=None,\n required=required)\n\n self.axis = axis\n self.fitter = fitter\n self.transformer = transformer\n self.data = None\n self.required = required\n","sub_path":"hypertools/manip/zscore.py","file_name":"zscore.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"220078333","text":"from zope.interface import implements\n\nfrom twisted.internet import defer\nfrom twisted.plugin import IPlugin\n\nfrom apiserver.interfaces import IService\nfrom apiserver.db import dbpool\nfrom apiserver.cache import cache\n\nclass HistoryService(object):\n implements(IPlugin, IService)\n name = 'history'\n \n def stream_result(self, user, path, url):\n item = path.split('/')[-1]\n def set_watched(txn):\n count = txn.execute(\"SELECT count(*) as num FROM history WHERE watch_date > datetime('now', '-1 days') AND user = ? AND item = ?\", (user.username, item, )).fetchone()['num']\n if not count:\n txn.execute(\"INSERT INTO history (user, item, watch_date) VALUES (:user, :item, datetime('now'))\", {\n 'user': user.username,\n 'item': item,\n })\n dbpool.runInteraction(set_watched)\n \n @defer.inlineCallbacks\n def listing_result_item(self, section, user, path, item):\n key = 'history:%s' % user.username\n \n if item['rel'] == 'file':\n if key not in cache:\n result = yield dbpool.runQuery(\"SELECT item, watch_date FROM history WHERE user = ?\", (user.username, ))\n cache[key] = dict((r['item'], r['watch_date']) for r in result)\n \n history = cache[key]\n item['watched'] = item['name'] in history\n defer.returnValue(item)\n \nhistoryservice = HistoryService()\n\ndef check_or_create_tables():\n dbpool.runOperation(\"\"\"CREATE TABLE IF NOT EXISTS history (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n user VARCHAR(50) NOT NULL,\n item VARCHAR(255) NOT NULL,\n watch_date DATETIME NOT NULL\n )\"\"\")\n\ncheck_or_create_tables()","sub_path":"apiserver/services/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"24881361","text":"# https://leetcode.com/problems/valid-palindrome/\nimport collections\nimport re\n\n\ndef isPalindromeUsingList(self, s: str) -> bool:\n strs = []\n for char in s:\n if char.isalnum():\n strs.append(char.lower())\n while len(strs) > 1:\n if strs.pop(0) != strs.pop():\n return False\n return True\n\n\ndef isPalindromeUsingDeque(self, s: str) -> bool:\n strs = collections.deque()\n for char in s:\n if char.isalnum():\n strs.append(char.lower())\n while len(strs) > 1:\n if strs.popleft() != strs.pop():\n return False\n return True\n\n\ndef isPalindromeUsingSlicing(self, s: str) -> bool:\n s = s.lower()\n s = re.sub('[^a-z0-9]', '', s)\n return s == s[::-1]\n","sub_path":"PythonAlgorithmInterview/06_문자열조작/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"289048063","text":"import numpy as np \nimport random\n\nROUND_ROBIN_SIZE = 10\n\ndef _getRoundRobinSize():\n return ROUND_ROBIN_SIZE\n\ndef mapping():\n\tfunction_mappings = {'tsp_genitor': tsp_genitor,'tsp_randomReplacement': tsp_randomReplacement,\n 'tsp_roundRobin':tsp_roundRobin,'tsp_simpleMuCommaAlpha': tsp_simpleMuCommaAlpha,\n 'tsp_simpleMuPlusAlpha':tsp_simpleMuPlusAlpha}\n\treturn function_mappings\n\ndef tsp_genitor(parents,offspring, parentFitness, offspringFitness, elitePercentage=0.0):\n # the genitor algorithm simply replaces the worst N parents with the best N offspring\n # this is effectively a proportional form of elitism as the best members are never lost\n # as long as complete replacement is not selected\n # BUT is not true elitism\n\n # elite percentage defines the minimum fraction of the parent population to be preserved\n nParents,tmp = parents.shape\n nOffspring,tmp = offspring.shape \n nElite = int(np.ceil(elitePercentage*nParents))\n\n nToReplace = nParents - nElite # preserve nElite numbers and replace nToReplace children\n if nToReplace > nOffspring:\n # if there are fewer offspring than \n raise Warning('number of offspring too small for specified elitism percentage')\n nToReplace = nOffspring \n\n worstParentIndices = np.argsort(-parentFitness)[0:nToReplace]\n bestOffspringIndices = np.argsort(offspringFitness)[0:nToReplace]\n\n newChrom = parents[:]\n newChrom[worstParentIndices] = offspring[bestOffspringIndices]\n\n newObjV = parentFitness[:]\n newObjV[worstParentIndices] = offspringFitness[bestOffspringIndices]\n\n return newChrom.tolist(), newObjV.tolist()\n\ndef tsp_randomReplacement(parents,offspring, parentFitness, offspringFitness, elitePercentage=0.0):\n # randomly replace N members of the parents with N members of the offspring\n # doesnt consider elitism\n\n # elite percentage defines the minimum fraction of the parent population to be preserved\n nParents,tmp = parents.shape\n nOffspring,tmp = offspring.shape \n\n nToReplace = nParents\n\n if nToReplace > nOffspring:\n # if there are fewer offspring than parents randomly insert all the offspring into the population\n raise Warning('poplation is larger than number of offspring')\n nToReplace = nOffspring \n\n randomParentIndices = np.argsort(np.array([ random.random() for item in range(nParents)]))[0:nToReplace]\n randomOffspringIndices = np.argsort(np.array([ random.random() for item in range(nOffspring) ]))[0:nToReplace]\n\n newChrom = parents[:]\n newChrom[randomParentIndices] = offspring[randomOffspringIndices]\n\n newObjV = parentFitness[:]\n newObjV[randomParentIndices] = offspringFitness[randomOffspringIndices]\n\n return newChrom.tolist(), newObjV.tolist()\n\ndef _randomIndices(num, numRange): # a random set of indices\n return random.sample(range(numRange),num)\n\n\ndef _tallyWinner(item, competitors):\n tally = [1 for competitor in competitors if item < competitor ] # if smaller than the item is more fit\n return sum(tally)\n\n\ndef tsp_roundRobin(parents,offspring,parentFitness,offspringFitness,elitePercentage=0.0):\n # elite percentage doesn't factor in here\n\n # princple of selection is as follows:\n # combine parents and offspring\n # compare each member to ~10 other random members\n # record how many that member was better than\n # extract the N members with the best win percentages \n\n (nParents,tmp) = parents.shape\n (nOffspring,tmp) = offspring.shape\n\n combinedFitness = parentFitness.tolist()+offspringFitness.tolist()\n combinedFitness = np.array(combinedFitness)\n numCompetitions = _getRoundRobinSize()\n resultsVector = [_tallyWinner(combinedFitness[i], combinedFitness[_randomIndices(numCompetitions,len(combinedFitness))] ) for i in range(len(combinedFitness))]\n rankings = np.argsort(-np.array(resultsVector))[0:nParents]\n indexParents = [i for i in rankings if i < nParents]\n indexOffspring = [i - nParents for i in rankings if i >= nParents ] \n newChrom = parents[indexParents].tolist() + offspring[indexOffspring].tolist()\n newObjV = parentFitness[indexParents].tolist() + offspringFitness[indexOffspring].tolist()\n\n return newChrom, newObjV\n\ndef tsp_simpleMuPlusAlpha(parents,offspring,parentFitness,offspringFitness,elitePercentage=0.0):\n # combines the parents and the offspring\n # take the best N from combination\n # always preserves elites\n nParents,tmp = parents.shape\n\n combinedFitness = parentFitness.tolist() + offspringFitness.tolist()\n combinedFitness = np.array(combinedFitness)\n ranking = np.argsort(combinedFitness)[0:nParents]\n\n indexParents = [i for i in ranking if i < nParents]\n indexOffspring = [i - nParents for i in ranking if i >= nParents ] \n\n newChrom = parents[indexParents].tolist() + offspring[indexOffspring].tolist()\n newObjV = parentFitness[indexParents].tolist() + offspringFitness[indexOffspring].tolist()\n\n return newChrom, newObjV\n\n\n\ndef tsp_simpleMuCommaAlpha(parents,offspring,parentFitness,offspringFitness,elitePercentage=0.0):\n # consider only the children take the best N\n # this is the similar to genitor with no elitism i think\n nParents,tmp = parents.shape\n nOffspring,tmp = offspring.shape \n\n if nParents > nOffspring:\n raise AttributeError('Offspring population must be larger than parent population')\n\n ranking = np.argsort(offspringFitness)[0:nParents] # only consider the N best ones\n\n newChrom = offspring[ranking].tolist()\n newObjV = offspringFitness[ranking].tolist()\n\n return newChrom, newObjV \n\n","sub_path":"src/tsp_reinsMethods.py","file_name":"tsp_reinsMethods.py","file_ext":"py","file_size_in_byte":5649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"216873130","text":"# noqa: TYP001\nfrom django.conf import settings as django_settings\nfrom django.core.exceptions import ImproperlyConfigured\n\nimport pytest\nfrom tests.utils import patch_response_validation_middleware_settings\n\nfrom django_swagger_tester.configuration import SwaggerTesterSettings\n\n\ndef test_bad_regular_expressions(monkeypatch) -> None:\n \"\"\"\n Make sure values are rejected when they cannot be compiled using re.compile.\n \"\"\"\n for value in [None, 2]:\n with pytest.raises(\n ImproperlyConfigured, match='Failed to compile the passed VALIDATION_EXEMPT_URLS as regular expressions'\n ):\n monkeypatch.setattr(\n django_settings,\n 'SWAGGER_TESTER',\n patch_response_validation_middleware_settings('VALIDATION_EXEMPT_URLS', [{'url': value}]),\n )\n SwaggerTesterSettings()\n\n\ndef test_accepted_regexp(monkeypatch) -> None:\n \"\"\"\n Make sure normal regular expressions pass.\n \"\"\"\n for value in ['^api/v1/test$', '']:\n monkeypatch.setattr(\n django_settings,\n 'SWAGGER_TESTER',\n patch_response_validation_middleware_settings(\n 'VALIDATION_EXEMPT_URLS', [{'url': value, 'status_codes': [200]}]\n ),\n )\n SwaggerTesterSettings()\n","sub_path":"tests/test_configuration/test_middleware_settings/test_response_validation_middleware_settings/test_validation_exempt_urls.py","file_name":"test_validation_exempt_urls.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"229352559","text":"import json\nfrom django.shortcuts import render\nfrom django.http import HttpResponse,JsonResponse\n\nfrom .forms import ImageForm\nfrom .models import Image,Category\nfrom django.core import serializers\n\n\ndef index(request):\n \"\"\"This renders the home page\n \"\"\"\n categories = Category.objects.all()\n return render(request,'photohtml/index.html',{\"categories\":categories})\n\ndef images(request):\n \"\"\"This will render the images page\n\n Args:\n request ([type]): [description]\n \"\"\"\n categories = Category.objects.all()\n images = Image.objects.all()\n return render(request,'photohtml/images.html',{'images':images,\"categories\":categories})\n\ndef image_spec(request,pk):\n \"\"\"This will render the page containing a specific image\n\n Args:\n request ([type]): [description]\n pk ([int]): [This is the primary key of the image]\n \"\"\"\n categories = Category.objects.all()\n image = Image.get_image_by_id(pk)\n return render(request,\"photohtml/image.html\",{\"image\":image,\"categories\":categories})\n\ndef image_category(request,pk):\n \"\"\"This will render a page containing the specific category asked for\n\n Args:\n request ([type]): [description]\n pk ([type]): [description]\n \"\"\"\n categories = Category.objects.all()\n images = Image.get_image_by_category(pk)\n\n return render(request,'photohtml/image_category.html',{\"images\":images,\"categories\":categories})\n\ndef search_images(request):\n \"\"\"This will return the \n\n Args:\n request ([type]): [description]\n search_term ([type]): [description]\n \"\"\"\n if 'image' in request.GET and request.GET['image']:\n search_term = request.GET.get(\"image\")\n images = Image.get_image_by_name(search_term)\n\n message = f\"{search_term}\"\n\n return render(request,'photohtml/search.html',{\"message\":message,\"images\":images})\n\n else:\n message = \"You have not searched for an image\"\n return render(request,'photohtml/search.html',{\"message\":message})","sub_path":"photo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"351863359","text":"#!/usr/bin/python3\n\n# Let's not reinvent the wheel here\nimport num2words\n\ns = 0\nfor i in range(1, 1001):\n s += len(num2words.num2words(i, lang='en_GB').replace(\" \", \"\").replace(\"-\", \"\"))\n\nprint(s)\n","sub_path":"pe0017.py","file_name":"pe0017.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"424938901","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom echomesh.util import Registry\n\n_REGISTRY = Registry.Registry('command')\n\nget = _REGISTRY.get\nget_or_none = _REGISTRY.get_or_none\nget_help = _REGISTRY.get_help\nregister = _REGISTRY.register\nregister_all = _REGISTRY.register_all\njoin_keys = _REGISTRY.join_keys\n\n","sub_path":"code/python/echomesh/command/Register.py","file_name":"Register.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"189220108","text":"from . import rest_api\nfrom . import config\nfrom . import client\nfrom . import cloudarray\nfrom . import tiledb_cloud_error\nfrom .rest_api import ApiException as GenApiException\nfrom .rest_api import rest\nfrom . import udf\nfrom . import utils\n\nimport zlib\nimport multiprocessing\nimport cloudpickle\nimport urllib\nimport base64\nimport sys\n\n\nclass UDFResult(multiprocessing.pool.ApplyResult):\n def __init__(self, response):\n self.response = response\n self.task_id = None\n\n def get(self, timeout=None):\n try:\n response = rest.RESTResponse(self.response.get(timeout=timeout))\n\n self.task_id = response.getheader(client.TASK_ID_HEADER)\n cloudarray.last_udf_task_id = self.task_id\n\n res = response.data\n\n except GenApiException as exc:\n raise tiledb_cloud_error.check_udf_exc(exc) from None\n except multiprocessing.TimeoutError as exc:\n raise tiledb_cloud_error.check_udf_exc(exc) from None\n\n if res[:2].hex() in [\"7801\", \"785e\", \"789c\", \"78da\"]:\n try:\n res = zlib.decompress(res)\n except zlib.error:\n raise tiledb_cloud_error.TileDBCloudError(\n \"Failed to decompress (zlib) result object\"\n )\n\n try:\n res = cloudpickle.loads(res)\n except:\n raise tiledb_cloud_error.TileDBCloudError(\n \"Failed to load cloudpickle result object\"\n )\n\n return res\n\n\ndef info(uri):\n \"\"\"\n Returns the cloud metadata\n\n :return: metadata object\n \"\"\"\n (namespace, array_name) = split_uri(uri)\n api_instance = client.client.array_api\n\n try:\n return api_instance.get_array_metadata(namespace=namespace, array=array_name)\n except GenApiException as exc:\n raise tiledb_cloud_error.check_exc(exc) from None\n\n\ndef list_shared_with(uri):\n \"\"\"Return array sharing policies\"\"\"\n (namespace, array_name) = split_uri(uri)\n api_instance = client.client.array_api\n\n try:\n return api_instance.get_array_sharing_policies(\n namespace=namespace, array=array_name\n )\n except GenApiException as exc:\n raise tiledb_cloud_error.check_exc(exc) from None\n\n\ndef share_array(uri, namespace, permissions):\n \"\"\"\n Shares array with give namespace and permissions\n\n :param str namespace:\n :param list(str) permissions:\n :return:\n \"\"\"\n\n if not isinstance(permissions, list):\n permissions = [permissions]\n\n for perm in permissions:\n if (\n not perm.lower() == rest_api.models.ArrayActions.READ\n and not perm.lower() == rest_api.models.ArrayActions.WRITE\n ):\n raise Exception(\"Only read or write permissions are accepted\")\n\n (array_namespace, array_name) = split_uri(uri)\n api_instance = client.client.array_api\n\n try:\n return api_instance.share_array(\n namespace=array_namespace,\n array=array_name,\n array_sharing=rest_api.models.ArraySharing(\n namespace=namespace, actions=permissions\n ),\n )\n except GenApiException as exc:\n raise tiledb_cloud_error.check_exc(exc) from None\n\n\ndef unshare_array(uri, namespace):\n \"\"\"\n Removes sharing of an array from given namespace\n\n :param str namespace: namespace to remove shared access to the array\n :return:\n :raises: :py:exc:\n \"\"\"\n return share_array(uri, namespace, list())\n\n\ndef update_info(\n uri,\n array_name=None,\n description=None,\n access_credentials_name=None,\n tags=None,\n):\n \"\"\"\n Update an array's info\n :param str namespace: optional username or organization array should be registered under. If unset will default to the user\n :param str array_name: name of array to rename to\n :param str description: optional description\n :param str access_credentials_name: optional name of access credentials to use, if left blank default for namespace will be used\n :param list tags to update to\n \"\"\"\n api_instance = client.client.array_api\n (namespace, current_array_name) = split_uri(uri)\n\n try:\n return api_instance.update_array_metadata(\n namespace=namespace,\n array=current_array_name,\n array_metadata=rest_api.models.ArrayInfoUpdate(\n description=description,\n name=array_name,\n uri=uri,\n access_credentials_name=access_credentials_name,\n tags=tags,\n ),\n )\n except GenApiException as exc:\n raise tiledb_cloud_error.check_exc(exc) from None\n\n\ndef register_array(\n uri, namespace=None, array_name=None, description=None, access_credentials_name=None\n):\n \"\"\"\n Register this array with the tiledb cloud service\n :param str namespace: optional username or organization array should be registered under. If unset will default to the user\n :param str array_name: name of array\n :param str description: optional description\n :param str access_credentials_name: optional name of access credentials to use, if left blank default for namespace will be used\n \"\"\"\n api_instance = client.client.array_api\n\n if namespace is None:\n if config.user is None:\n config.user = client.user_profile()\n\n namespace = config.user.username\n\n try:\n return api_instance.register_array(\n namespace=namespace,\n array=uri,\n array_metadata=rest_api.models.ArrayInfoUpdate(\n description=description,\n name=array_name,\n uri=uri,\n access_credentials_name=access_credentials_name,\n ),\n )\n except GenApiException as exc:\n raise tiledb_cloud_error.check_exc(exc) from None\n\n\ndef deregister_array(uri):\n \"\"\"\n Deregister the from the tiledb cloud service. This does not physically delete the array, it will remain\n in your bucket. All access to the array and cloud metadata will be removed.\n \"\"\"\n (namespace, array_name) = split_uri(uri)\n\n api_instance = client.client.array_api\n\n try:\n return api_instance.deregister_array(namespace=namespace, array=array_name)\n except GenApiException as exc:\n raise tiledb_cloud_error.check_exc(exc) from None\n\n\ndef array_activity(uri):\n \"\"\"\n Fetch array activity\n :param uri:\n :return:\n \"\"\"\n (namespace, array_name) = split_uri(uri)\n\n api_instance = client.client.array_api\n\n try:\n return api_instance.array_activity_log(namespace=namespace, array=array_name)\n except GenApiException as exc:\n raise tiledb_cloud_error.check_exc(exc) from None\n\n\ndef split_uri(uri):\n \"\"\"\n Split a URI into namespace and array name\n\n :param uri: uri to split into namespace and array name\n :return: tuple (namespace, array_name)\n \"\"\"\n parsed = urllib.parse.urlparse(uri)\n if not parsed.scheme == \"tiledb\":\n raise Exception(\"Incorrect array uri, must be in tiledb:// scheme\")\n return parsed.netloc, parsed.path[1:]\n\n\ndef parse_ranges(ranges):\n \"\"\"\n Takes a list of the following objects per dimension:\n\n - scalar index\n - (start,end) tuple\n - list of either of the above types\n\n :param ranges: list of (scalar, tuple, list)\n :param builder: function taking arguments (dim_idx, start, end)\n :return:\n \"\"\"\n\n def make_range(dim_range):\n if isinstance(dim_range, (int, float)):\n start, end = dim_range, dim_range\n elif isinstance(dim_range, (tuple, list)):\n start, end = dim_range[0], dim_range[1]\n elif isinstance(dim_range, slice):\n assert dim_range.step is None, \"slice steps are not supported!\"\n start, end = dim_range.start, dim_range.stop\n else:\n raise ValueError(\"Unknown index type! (type: '{}')\".format(type(dim_range)))\n return [start, end]\n\n result = list()\n for dim_idx, dim_range in enumerate(ranges):\n dim_list = []\n # TODO handle numpy scalars here?\n if isinstance(dim_range, (int, float, tuple, slice)):\n dim_list.extend(make_range(dim_range))\n elif isinstance(dim_range, list):\n for r in dim_range:\n dim_list.extend(make_range(r))\n else:\n raise ValueError(\n \"Unknown subarray/index type! (type: '{}', \"\n \", idx: '{}', value: '{}')\".format(type(dim_range), dim_idx, dim_range)\n )\n result.append(dim_list)\n\n return result\n\n\ndef apply_async(\n uri,\n func=None,\n ranges=None,\n name=None,\n attrs=None,\n layout=None,\n image_name=None,\n http_compressor=\"deflate\",\n include_source_lines=True,\n task_name=None,\n):\n \"\"\"\n Apply a user defined function to an array asynchronous\n\n :param func: user function to run\n :param ranges: ranges to issue query on\n :param attrs: list of attributes or dimensions to fetch in query\n :param layout: tiledb query layout\n :param image_name: udf image name to use, useful for testing beta features\n :param http_compressor: set http compressor for results\n :param include_source_lines: disables sending sources lines of function along with udf\n :param str task_name: optional name to assign the task for logging and audit purposes\n :return: UDFResult object which is a future containing the results of the UDF\n\n **Example**\n >>> import tiledb, tiledb.cloud, numpy\n >>> def median(df):\n ... return numpy.median(df[\"a\"])\n >>> # Open the array then run the UDF\n >>> tiledb.cloud.array.apply_async(\"tiledb://TileDB-Inc/quickstart_dense\", median, [(0,5), (0,5)], attrs=[\"a\", \"b\", \"c\"]).get()\n 2.0\n \"\"\"\n\n (namespace, array_name) = split_uri(uri)\n api_instance = client.client.udf_api\n\n if func is not None and not callable(func):\n raise TypeError(\"func argument to `apply` must be callable!\")\n elif func is None and name is None or name == \"\":\n raise TypeError(\"name argument to `apply` must be set if no function is passed\")\n\n pickledUDF = None\n source_lines = None\n if func is not None:\n source_lines = utils.getsourcelines(func) if include_source_lines else None\n pickledUDF = cloudpickle.dumps(func, protocol=udf.tiledb_cloud_protocol)\n pickledUDF = base64.b64encode(pickledUDF).decode(\"ascii\")\n\n ranges = parse_ranges(ranges)\n\n converted_layout = \"row-major\"\n\n if layout is None:\n converted_layout = \"unordered\"\n elif layout.upper() == \"R\":\n converted_layout = \"row-major\"\n elif layout.upper() == \"C\":\n converted_layout = \"col-major\"\n elif layout.upper() == \"G\":\n converted_layout = \"global-order\"\n\n ranges = rest_api.models.UDFRanges(layout=converted_layout, ranges=ranges)\n\n if image_name is None:\n image_name = \"default\"\n try:\n\n kwargs = {\"_preload_content\": False, \"async_req\": True}\n if http_compressor is not None:\n kwargs[\"accept_encoding\"] = http_compressor\n\n udf_model = rest_api.models.UDF(\n language=rest_api.models.UDFLanguage.PYTHON,\n _exec=pickledUDF,\n ranges=ranges,\n buffers=attrs,\n version=\"{}.{}.{}\".format(\n sys.version_info.major,\n sys.version_info.minor,\n sys.version_info.micro,\n ),\n image_name=image_name,\n task_name=task_name,\n )\n\n if pickledUDF is not None:\n udf_model._exec = pickledUDF\n elif name is not None:\n udf_model.udf_info_name = name\n\n if source_lines is not None:\n udf_model.exec_raw = source_lines\n\n # _preload_content must be set to false to avoid trying to decode binary data\n response = api_instance.submit_udf(\n namespace=namespace, array=array_name, udf=udf_model, **kwargs\n )\n\n return UDFResult(response)\n\n except GenApiException as exc:\n raise tiledb_cloud_error.check_sql_exc(exc) from None\n\n\ndef apply(\n uri,\n func=None,\n ranges=None,\n name=None,\n attrs=None,\n layout=None,\n image_name=None,\n http_compressor=\"deflate\",\n task_name=None,\n):\n \"\"\"\n Apply a user defined function to an array synchronous\n\n :param func: user function to run\n :param ranges: ranges to issue query on\n :param attrs: list of attributes or dimensions to fetch in query\n :param layout: tiledb query layout\n :param image_name: udf image name to use, useful for testing beta features\n :param http_compressor: set http compressor for results\n :param str task_name: optional name to assign the task for logging and audit purposes\n :return: UDFResult object which is a future containing the results of the UDF\n\n **Example**\n >>> import tiledb, tiledb.cloud, numpy\n >>> def median(df):\n ... return numpy.median(df[\"a\"])\n >>> # Open the array then run the UDF\n >>> tiledb.cloud.array.apply(\"tiledb://TileDB-Inc/quickstart_dense\", median, [(0,5), (0,5)], attrs=[\"a\", \"b\", \"c\"])\n 2.0\n \"\"\"\n return apply_async(\n uri=uri,\n func=func,\n ranges=ranges,\n name=name,\n attrs=attrs,\n layout=layout,\n image_name=image_name,\n http_compressor=http_compressor,\n task_name=task_name,\n ).get()\n","sub_path":"tiledb/cloud/array.py","file_name":"array.py","file_ext":"py","file_size_in_byte":13403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"3769665","text":"from PyQt5 import QtCore, QtWidgets\n\nclass Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n Form.resize(512, 512)\n self.label = QtWidgets.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(0, 0, 512, 512))\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\", \"CVDL2019_HW1_AR\"))\n\n","sub_path":"Ui_ar.py","file_name":"Ui_ar.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"494375031","text":"import os.path\nimport random\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\nfrom data.image_folder import make_dataset\n\n\nclass MMHandDataset(Dataset):\n def __init__(self, opt):\n self.opt = opt\n self.dir_H = os.path.join(opt.imageroot, opt.phase) # hand images\n self.dir_P = os.path.join(opt.poseroot, opt.phase + 'P') # hand poses\n\n self.init_categories(opt.pairLst)\n self.transform = self.get_transform()\n\n def init_categories(self, pairLst):\n\n pairs_file = pd.read_csv(pairLst)\n self.size = len(pairs_file)\n self.pairs = []\n print('Loading data pairs ...')\n for i in range(self.size):\n pair = [pairs_file.iloc[i]['from'], pairs_file.iloc[i]['to']]\n self.pairs.append(pair)\n\n print('Loading data pairs finished ...')\n\n def get_transform(self):\n transform_list = []\n\n transform_list += [\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]\n return transforms.Compose(transform_list)\n\n def __getitem__(self, index):\n if self.opt.phase == 'train':\n index = random.randint(0, self.size - 1)\n\n H1_name, H2_name = self.pairs[index]\n '''Added for Depth Map'''\n # hand 1 and its pose and depth\n if '.png' not in H1_name:\n H1_path = os.path.join(self.dir_H, H1_name + '.png')\n else:\n H1_path = os.path.join(self.dir_H, H1_name)\n P1_path = os.path.join(self.dir_P,\n H1_name + '.npy') # bone of person 1\n D1_path = H1_path.replace('color', 'depth')\n\n # hand 2 and its pose and depth\n if '.png' not in H2_name:\n H2_path = os.path.join(self.dir_H, H2_name + '.png') # person 2\n else:\n H2_path = os.path.join(self.dir_H, H2_name) # person 2\n P2_path = os.path.join(self.dir_P,\n H2_name + '.npy') # bone of person 2\n D2_path = H2_path.replace('color', 'depth')\n\n H1_img = Image.open(H1_path).convert('RGB')\n H2_img = Image.open(H2_path).convert('RGB')\n\n P1_img = np.load(P1_path) # h, w, c\n P2_img = np.load(P2_path)\n\n D1_img = Image.open(D1_path).convert('RGB')\n D2_img = Image.open(D2_path).convert('RGB')\n\n # use flip\n if self.opt.phase == 'train' and self.opt.use_flip:\n # print ('use_flip ...')\n flip_random = random.uniform(0, 1)\n\n if flip_random > 0.5:\n # print('fliped ...')\n H1_img = H1_img.transpose(Image.FLIP_LEFT_RIGHT)\n H2_img = H2_img.transpose(Image.FLIP_LEFT_RIGHT)\n\n P1_img = np.array(P1_img[:, ::-1, :]) # flip\n P2_img = np.array(P2_img[:, ::-1, :]) # flip\n\n D1_img = D1_img.transpose(Image.FLIP_LEFT_RIGHT)\n D2_img = D2_img.transpose(Image.FLIP_LEFT_RIGHT)\n\n P1 = torch.from_numpy(P1_img).float() #h, w, c\n P1 = P1.transpose(2, 0) #c,w,h\n P1 = P1.transpose(2, 1) #c,h,w\n\n P2 = torch.from_numpy(P2_img).float()\n P2 = P2.transpose(2, 0) #c,w,h\n P2 = P2.transpose(2, 1) #c,h,w\n\n H1 = self.transform(H1_img)\n H2 = self.transform(H2_img)\n '''Added for Depth Map'''\n D1 = self.transform(D1_img)\n D2 = self.transform(D2_img)\n return {\n 'H1': H1,\n 'P1': P1,\n 'D1': D1,\n 'H1_path': H1_name,\n 'H2': H2,\n 'P2': P2,\n 'D2': D2,\n 'H2_path': H2_name\n }\n\n def __len__(self):\n return self.size\n","sub_path":"data/mmhand_dataset.py","file_name":"mmhand_dataset.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"409790152","text":"import numpy as np\n\ndef f_XOR(inputArr):\n\toutput = []\n\tfor i in range(inputArr.shape[0]):\n\t\tres = inputArr[i][1]\n\t\ttemp = []\n\t\tfor j in range(2, inputArr[i].shape[0]):\n\t\t\tres = bool(res) ^ bool(inputArr[i][j])\n\t\ttemp.append(int(res))\n\t\toutput.append(np.array(temp))\n\treturn np.array(output)","sub_path":"ANN/src/xor/xor.py","file_name":"xor.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"41677053","text":"import os\nfrom random import random\nimport shutil\nfrom tqdm import tqdm\n\n\ndef check_folder(ff):\n if not os.path.exists(ff):\n os.mkdir(ff)\n\n\nmidi_dir = 'C:/dataset/midis/'\n\nimage_dir = 'C:/dataset/train'\nimage_classes = os.listdir(image_dir)\ntarget_dir = 'C:/dataset/ready_to_use/'\ncheck_folder(target_dir)\nimage_sets = ['train', 'valid']\nemotion_mapping = {\n 'happy': 'Q1',\n 'surprise': 'Q1',\n 'angry': 'Q2',\n 'disgust': 'Q2',\n 'fear': 'Q2',\n 'sad': 'Q3',\n 'neutral': 'Q4',\n}\n\n\ndef fer_data():\n for sets in image_sets:\n this_dir = os.path.join(target_dir, sets)\n check_folder(this_dir)\n for ic in image_classes:\n this_ic_dir = os.path.join(this_dir, ic)\n check_folder(this_ic_dir)\n\n for ic in image_classes:\n this_image_dir = os.path.join(image_dir, ic)\n print('-'*10, ic, '-'*10)\n for images in tqdm(os.listdir(this_image_dir)):\n this_set = 'train' if random() > 0.1 else 'valid'\n this_dir = os.path.join(target_dir, this_set, emotion_mapping[ic])\n check_folder(this_dir)\n shutil.copy2(os.path.join(this_image_dir, images), os.path.join(this_dir, images))\n check_folder(f'C:/dataset/emotion_image/{emotion_mapping[ic]}')\n\n if random() > 0.95:\n shutil.copy2(os.path.join(this_image_dir, images),\n f'C:/dataset/emotion_image/{emotion_mapping[ic]}/{emotion_mapping[ic]}_{images}')\n\n\nfer_data()\n\n","sub_path":"apps/EmotionalMusicGenerator/.ipynb_checkpoints/data_processing-checkpoint.py","file_name":"data_processing-checkpoint.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"556406192","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom random import randint\n\nActivePlayer = 1\np1 = []\np2 = []\n\nroot = Tk()\nroot.title(f'Jogo da velha: Jogador 1')\nstyle = ttk.Style()\nstyle.theme_use('classic')\nstyle.configure(\"my.TButton\", fg='blue', font='Verdana 22 bold')\n\nbu1 = ttk.Button(root, text=' ', style='my.TButton')\nbu1.grid(row=0, column=0, sticky='snew', ipadx=40, ipady=40)\nbu1.config(command=lambda: ButtonClick(1))\n\nbu2 = ttk.Button(root, text=' ', style='my.TButton')\nbu2.grid(row=0, column=1, sticky='snew', ipadx=40, ipady=40)\nbu2.config(command=lambda: ButtonClick(2))\n\nbu3 = ttk.Button(root, text=' ', style='my.TButton')\nbu3.grid(row=0, column=2, sticky='snew', ipadx=40, ipady=40)\nbu3.config(command=lambda: ButtonClick(3))\n\nbu4 = ttk.Button(root, text=' ', style='my.TButton')\nbu4.grid(row=1, column=0, sticky='snew', ipadx=40, ipady=40)\nbu4.config(command=lambda: ButtonClick(4))\n\nbu5 = ttk.Button(root, text=' ', style='my.TButton')\nbu5.grid(row=1, column=1, sticky='snew', ipadx=40, ipady=40)\nbu5.config(command=lambda: ButtonClick(5))\n\nbu6 = ttk.Button(root, text=' ', style='my.TButton')\nbu6.grid(row=1, column=2, sticky='snew', ipadx=40, ipady=40)\nbu6.config(command=lambda: ButtonClick(6))\n\nbu7 = ttk.Button(root, text=' ', style='my.TButton')\nbu7.grid(row=2, column=0, sticky='snew', ipadx=40, ipady=40)\nbu7.config(command=lambda: ButtonClick(7))\n\nbu8 = ttk.Button(root, text=' ', style='my.TButton')\nbu8.grid(row=2, column=1, sticky='snew', ipadx=40, ipady=40)\nbu8.config(command=lambda: ButtonClick(8))\n\nbu9 = ttk.Button(root, text=' ', style='my.TButton')\nbu9.grid(row=2, column=2, sticky='snew', ipadx=40, ipady=40)\nbu9.config(command=lambda: ButtonClick(9))\n\n\ndef ButtonClick(id):\n global ActivePlayer\n global p1\n global p2\n if ActivePlayer == 1:\n\n SetLayout(id, \"X\")\n p1.append(id)\n root.title(\"Jogo da velha: Jogador 2\")\n ActivePlayer = 2\n AutoPlay()\n elif ActivePlayer == 2:\n SetLayout(id, \"O\")\n p2.append(id)\n root.title(\"Jogo da velha: Jogador 1\")\n ActivePlayer = 1\n CheckWiner()\n\n\ndef SetLayout(id,PlayerSymbol):\n if id == 1:\n bu1.config(text=PlayerSymbol)\n bu1.state(['disabled'])\n elif id == 2:\n bu2.config(text=PlayerSymbol)\n bu2.state(['disabled'])\n elif id == 3:\n bu3.config(text=PlayerSymbol)\n bu3.state(['disabled'])\n elif id == 4:\n bu4.config(text=PlayerSymbol)\n bu4.state(['disabled'])\n elif id == 5:\n bu5.config(text=PlayerSymbol)\n bu5.state(['disabled'])\n elif id == 6:\n bu6.config(text=PlayerSymbol)\n bu6.state(['disabled'])\n elif id == 7:\n bu7.config(text=PlayerSymbol)\n bu7.state(['disabled'])\n elif id == 8:\n bu8.config(text=PlayerSymbol)\n bu8.state(['disabled'])\n elif id == 9:\n bu9.config(text=PlayerSymbol)\n bu9.state(['disabled'])\n\n\ndef CheckWiner():\n winer = -1\n if 1 in p1 and 2 in p1 and 3 in p1:\n winer = 1\n if 1 in p2 and 2 in p2 and 3 in p2:\n winer = 2\n\n if 4 in p1 and 5 in p1 and 6 in p1:\n winer = 1\n if 4 in p2 and 5 in p2 and 6 in p2:\n winer = 2\n\n if 7 in p1 and 8 in p1 and 9 in p1:\n winer = 1\n if 7 in p2 and 8 in p2 and 9 in p2:\n winer = 2\n\n if 1 in p1 and 4 in p1 and 7 in p1:\n winer = 1\n if 1 in p2 and 4 in p2 and 7 in p2:\n winer = 2\n\n if 2 in p1 and 5 in p1 and 8 in p1:\n winer = 1\n if 2 in p2 and 5 in p2 and 8 in p2:\n winer = 2\n\n if 3 in p1 and 6 in p1 and 9 in p1:\n winer = 1\n if 3 in p2 and 6 in p2 and 9 in p2:\n winer = 2\n\n if winer == 1:\n messagebox.showinfo(title='Parabéns!', message='Jogador 1 venceu!')\n elif winer == 2:\n messagebox.showinfo(title='Parabéns!', message='Jogador 2 venceu')\n\n\ndef AutoPlay():\n global p1\n global p2\n empty_cells = []\n for cell in range(9):\n if not (cell + 1 in p1 or cell + 1 in p2):\n empty_cells.append(cell + 1)\n rand_index = randint(0, len(empty_cells) - 1)\n ButtonClick(empty_cells[rand_index])\n\n\nroot.mainloop()\n","sub_path":"jogo_da_velha_v2.py","file_name":"jogo_da_velha_v2.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"609625285","text":"from constants import *\nimport entity\nimport os\nimport pygame as pg\nimport random\nimport sys\n\n\n# Simple snake game created in pygame\nclass Game:\n def __init__(self, display_width, display_height):\n # initializing pygame window\n self.display_width = display_width\n self.display_height = display_height\n self.display_name = DISPLAY_TITLE\n\n pg.init()\n pg.mixer.init()\n self.gameDisplay = pg.display.set_mode((self.display_width, self.display_height))\n pg.display.set_caption(self.display_name)\n\n # game assets\n self.snake_head_texture = None\n\n self.pickup_sound = None\n self.crash_sound = None\n\n\n # game vars\n self.apples_eaten = 0\n self.max_length = 0\n self.last_movement_time = 0\n self.movement_interval = 0 # how fast the snake will be moving\n self.restart = False\n\n # game objects\n self.snake_head = None\n self.snake = []\n\n # sprite groups\n self.snake_sprites = pg.sprite.Group()\n self.snake_body_sprites = pg.sprite.Group()\n self.apple_sprite = pg.sprite.Group()\n\n self.clock = pg.time.Clock()\n self.running = False\n\n # initializes all game variables before game starts\n def init_game_vars(self):\n pg.mixer.music.load(\"sounds/Bonkers-for-Arcades.mp3\")\n self.pickup_sound = pg.mixer.Sound(\"sounds/Pickup.wav\")\n self.crash_sound = pg.mixer.Sound(\"sounds/Crash.wav\")\n\n # create text file that records high score if it does not exist\n if not os.path.isfile(\"highscore.txt\"):\n self.record_highscore(0)\n\n self.snake_head = entity.SnakeHead(int(self.display_width/TILE_SIZE/2) * TILE_SIZE, int(self.display_height/TILE_SIZE/2) * TILE_SIZE, GREEN)\n self.snake_sprites.add(self.snake_head)\n self.snake.append(self.snake_head)\n\n self.max_length += 1\n self.movement_interval = PLAYER_SPEED\n self.render()\n\n def update(self):\n if not self.apple_sprite:\n self.generate_new_apple()\n\n t_now = pg.time.get_ticks()\n\n # regulate snake's movement speed\n if t_now - self.last_movement_time > self.movement_interval:\n self.last_movement_time = t_now\n self.snake_sprites.update()\n self.snake_body_sprites.update()\n\n # check if snake has collided with itself\n if pg.sprite.spritecollide(self.snake_head, self.snake_body_sprites, False):\n self.running = False\n\n # check if snake has collided with an apple\n apple_collision = pg.sprite.spritecollide(self.snake_head, self.apple_sprite, False)\n for apple in apple_collision:\n pg.mixer.Sound.play(self.pickup_sound)\n\n apple.kill()\n self.grow_snake()\n\n # increment stat tracker\n self.apples_eaten += 1\n self.max_length += 1\n\n # increase game difficulty\n if self.movement_interval > PLAYER_SPEED_CAP:\n self.movement_interval += PLAYER_SPEED_INCREASE_RATE\n\n # update the snake's body\n if len(self.snake) > 1:\n for i in range(1, len(self.snake), 1):\n self.snake[i].last_posx = self.snake[i].rect.topleft[0]\n self.snake[i].last_posy = self.snake[i].rect.topleft[1]\n self.snake[i].rect.topleft = (self.snake[i - 1].last_posx, self.snake[i - 1].last_posy)\n\n # check if player is going out of bounds\n if self.boundary_check():\n self.running = False\n\n def render(self):\n # rendering the game background\n self.gameDisplay.fill(WHITE)\n\n # render player\n self.snake_sprites.draw(self.gameDisplay)\n self.snake_body_sprites.draw(self.gameDisplay)\n\n # render apple\n self.apple_sprite.draw(self.gameDisplay)\n\n # draw game grid\n for x in range(0, DISPLAY_WIDTH, TILE_SIZE):\n pg.draw.line(self.gameDisplay, BLACK, (x, 0), (x, DISPLAY_HEIGHT))\n for y in range(0, DISPLAY_HEIGHT, TILE_SIZE):\n pg.draw.line(self.gameDisplay, BLACK, (0, y), (DISPLAY_WIDTH, y))\n\n # handles intro menu\n def game_intro_event_handler(self):\n keys = pg.key.get_pressed()\n in_menu = True\n start_btn_col = BLACK\n\n # processing player inputs\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.exit()\n\n if keys[pg.K_RETURN]:\n in_menu = False\n\n self.display_text(pg.font.SysFont(TEXT_FONT, int(TEXT_SIZE/2)), \"Use arrow keys to move\", BLACK, DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 - 25)\n self.display_text(pg.font.SysFont(TEXT_FONT, int(TEXT_SIZE/1.4)), \"Press [ENTER] to start\", start_btn_col, DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 + 25)\n\n return in_menu\n\n # handles ingame events\n def game_event_handler(self):\n keys = pg.key.get_pressed()\n\n # processing player inputs\n for event in pg.event.get():\n # game window closed\n if event.type == pg.QUIT:\n self.exit()\n\n # player movement\n if keys[pg.K_LEFT] and self.snake_head.dx == 0:\n self.snake_head.dy = 0\n self.snake_head.dx = -TILE_SIZE\n if keys[pg.K_RIGHT] and self.snake_head.dx == 0:\n self.snake_head.dy = 0\n self.snake_head.dx = TILE_SIZE\n if keys[pg.K_UP] and self.snake_head.dy == 0:\n self.snake_head.dx = 0\n self.snake_head.dy = -TILE_SIZE\n if keys[pg.K_DOWN] and self.snake_head.dy == 0:\n self.snake_head.dx = 0\n self.snake_head.dy = TILE_SIZE\n\n # handles game over menu\n def game_over_event_handler(self):\n mouse_pos = pg.mouse.get_pos()\n in_menu = True\n restart_btn_col = BLACK\n quit_btn_col = BLACK\n\n # record new highscore if player has beaten the previous highscore\n if self.apples_eaten > self.get_highscore():\n self.record_highscore(self.apples_eaten)\n\n restart_btn = self.display_text(pg.font.SysFont(TEXT_FONT, int(TEXT_SIZE / 1.2)), \"RESTART\", restart_btn_col, DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2 + 50)\n quit_btn = self.display_text(pg.font.SysFont(TEXT_FONT, int(TEXT_SIZE / 1.2)), \"QUIT\", quit_btn_col, DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2 + 100)\n\n # processing player inputs\n for event in pg.event.get():\n # game window closed\n if event.type == pg.QUIT:\n self.exit()\n\n # menu button hover for restart\n if restart_btn.collidepoint(mouse_pos):\n restart_btn_col = LIGHTERBLACK\n if pg.mouse.get_pressed()[0] == 1:\n in_menu = False\n self.restart = True\n\n # menu button hover for quit\n if quit_btn.collidepoint(mouse_pos):\n quit_btn_col = LIGHTERBLACK\n if pg.mouse.get_pressed()[0] == 1:\n in_menu = False\n\n self.display_text(pg.font.SysFont(TEXT_FONT, TEXT_SIZE), \"GAME OVER\", BLACK, DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2 - 100)\n self.display_text(pg.font.SysFont(TEXT_FONT, int(TEXT_SIZE / 1.5)), \"HIGHSCORE: \" + str(self.get_highscore()), BLACK, DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2 - 50)\n self.display_text(pg.font.SysFont(TEXT_FONT, int(TEXT_SIZE / 1.5)), \"APPLES: \" + str(self.apples_eaten), RED, DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2 - 20)\n\n restart_btn = self.display_text(pg.font.SysFont(TEXT_FONT, int(TEXT_SIZE / 1.2)), \"RESTART\", restart_btn_col, DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2 + 50)\n quit_btn = self.display_text(pg.font.SysFont(TEXT_FONT, int(TEXT_SIZE / 1.2)), \"QUIT\", quit_btn_col, DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2 + 100)\n\n return in_menu\n\n def game_intro(self):\n print(\"Intro\")\n is_game_over = True\n menu_box = pg.Rect(0, 0, GAME_OVER_MENU_SIZE, GAME_OVER_MENU_SIZE/2)\n menu_box.center = (DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2)\n menu_box2 = pg.Rect(0, 0, GAME_OVER_MENU_SIZE - 2, GAME_OVER_MENU_SIZE/2 - 2)\n menu_box2.center = (DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2)\n\n pg.display.flip()\n\n while is_game_over:\n pg.draw.rect(self.gameDisplay, BLACK, menu_box, 1)\n pg.draw.rect(self.gameDisplay, WHITE, menu_box2)\n\n is_game_over = self.game_intro_event_handler()\n\n pg.display.flip()\n\n # GAME LOOP\n def game_loop(self):\n print(\"Game Running!\")\n pg.mixer.music.play(-1)\n\n self.running = True\n while self.running:\n # event handling\n self.game_event_handler()\n\n # update\n self.update()\n\n # draw/render\n self.render()\n\n # pygame double buffering\n pg.display.flip()\n\n # defining the fps of game\n self.clock.tick(FPS)\n\n def game_over(self):\n print(\"Game Over\")\n pg.mixer.music.stop()\n pg.mixer.Sound.play(self.crash_sound)\n\n is_game_over = True\n menu_box = pg.Rect(0, 0, GAME_OVER_MENU_SIZE, GAME_OVER_MENU_SIZE)\n menu_box.center = (DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2)\n menu_box2 = pg.Rect(0, 0, GAME_OVER_MENU_SIZE - 2, GAME_OVER_MENU_SIZE - 2)\n menu_box2.center = (DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2)\n\n pg.display.flip()\n\n while is_game_over:\n pg.draw.rect(self.gameDisplay, BLACK, menu_box, 1)\n pg.draw.rect(self.gameDisplay, WHITE, menu_box2)\n\n is_game_over = self.game_over_event_handler()\n\n pg.display.flip()\n\n # Returns a Pygame Rect object centered at (x,y) with text displayed on top\n def display_text(self, font, text, color, x, y):\n display_text = font.render(text, True, color)\n btn = display_text.get_rect()\n btn.center = (x, y)\n self.gameDisplay.blit(display_text, btn)\n return btn\n\n # returns true/false depending on whether the player has exceeded the game window\n def boundary_check(self):\n return self.snake_head.rect.top < 0 or self.snake_head.rect.bottom > DISPLAY_HEIGHT \\\n or self.snake_head.rect.left < 0 or self.snake_head.rect.right > DISPLAY_WIDTH\n\n # creates a new random position for an apple\n def generate_new_apple(self):\n posy = random.randint(0, int((DISPLAY_HEIGHT - TILE_SIZE)/TILE_SIZE))\n posx = random.randint(0, int((DISPLAY_WIDTH - TILE_SIZE)/TILE_SIZE))\n apple = entity.Apple(posx * TILE_SIZE, posy * TILE_SIZE, RED)\n self.apple_sprite.add(apple)\n\n # increases the length of the snake upon consuming an apple\n def grow_snake(self):\n # add new snake body to the end of the snake\n snake_body = entity.SnakeBody(self.snake[-1].last_posx, self.snake[-1].last_posy, GREEN)\n self.snake_body_sprites.add(snake_body)\n self.snake.append(snake_body)\n\n # writes a highscore to file\n def record_highscore(self, score):\n file = open(\"highscore.txt\", \"w\")\n file.write(str(score))\n file.close()\n\n # returns current highscore\n def get_highscore(self):\n highscore = 0\n\n if os.path.isfile(\"highscore.txt\"):\n file = open(\"highscore.txt\", \"r\")\n line = file.readline()\n\n if line.isdigit():\n highscore = int(line)\n file.close()\n\n return highscore\n\n def run(self):\n self.init_game_vars()\n self.game_intro()\n self.game_loop()\n self.game_over()\n\n if self.restart:\n self.restart_game()\n self.run()\n else:\n self.exit()\n\n def restart_game(self):\n # resetting game vars\n self.snake_sprites = pg.sprite.Group()\n self.snake_body_sprites = pg.sprite.Group()\n self.apple_sprite = pg.sprite.Group()\n\n self.last_movement_time = 0\n self.movement_interval = 0\n self.snake = []\n\n self.apples_eaten = 0\n self.max_length = 0\n self.restart = False\n\n def exit(self):\n print(\"Quitting\")\n pg.quit()\n sys.exit()\n\n\n# -------------------------------------------------------------------------------------------------------------------- #\nif __name__ == \"__main__\":\n game = Game(DISPLAY_WIDTH, DISPLAY_HEIGHT)\n game.run()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":12443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"427750662","text":"import sys\n\nimport math\n\n\ndef digits_to_number(digits, base):\n number = 0\n for d in digits:\n number = base * number + int(d)\n return number\n\n\ndef nontrivial_divisors(n):\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n\n\ndef generate_jamcoin_candidate(hash, length):\n bin_hash = bin(hash)[2:]\n zero_prefix = '0' * (length - 2 - len(bin_hash))\n return '1{}{}1'.format(zero_prefix, bin_hash)\n\n\ndef find_jamcoin_divs(jamcoin):\n divs = {}\n for base in range(2, 11):\n number = digits_to_number(list(jamcoin), base)\n div = next(nontrivial_divisors(number), -1)\n if div < 0:\n return None\n divs['base{}div'.format(base)] = div\n return divs\n\n\ndef generate_jamcoins(length, count):\n jamcoins = []\n hash = 0\n while len(jamcoins) < count:\n candidate = generate_jamcoin_candidate(hash, length)\n divs = find_jamcoin_divs(candidate)\n if divs:\n divs['value'] = candidate\n jamcoins.append(divs)\n print('{} jamcoins'.format(len(jamcoins)))\n hash += 1\n return jamcoins\n\n\ndef main():\n task_input = open(sys.argv[1], 'r')\n task_output = open(sys.argv[1] + '.out', 'w')\n cases_count = int(task_input.readline())\n for case in range(1, cases_count + 1):\n case_strings = task_input.readline().rstrip().split(' ')\n length = int(case_strings[0])\n count = int(case_strings[1])\n jamcoins = generate_jamcoins(length, count)\n task_output.write('Case #{}:\\n'.format(case))\n for jamcoin in jamcoins:\n task_output.write(jamcoin['value'])\n for base in range(2, 11):\n task_output.write(' {}'.format(jamcoin['base{}div'.format(base)]))\n task_output.write('\\n')\n task_input.close()\n task_output.close()\n\n\nmain()\n","sub_path":"codes/CodeJamCrawler/16_0_3/ua.taras/QC.py","file_name":"QC.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"568469172","text":"# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nimport json\nfrom frappe import _\nfrom iot.iot.doctype.iot_user.iot_user import add_user\n\n\ndef is_enterprise_admin(user, enterprise):\n\treturn frappe.db.get_value(\"IOT Enterprise\", {\"name\": enterprise, \"admin\": user}, \"admin\")\n\n\ndef list_users_by_domain(domain):\n\treturn frappe.get_all(\"User\",\n\t\tfilters={\"email\": (\"like\", \"%@{0}\".format(domain))},\n\t\tfields=[\"name\", \"full_name\", \"enabled\", \"email\", \"creation\"])\n\n\ndef list_possible_users(enterprise):\n\tdomain = frappe.db.get_value(\"IOT Enterprise\", enterprise, \"domain\")\n\tusers = list_users_by_domain(domain)\n\treturn [user for user in users if not frappe.get_value('IOT User', {\"user\": user.name, \"enterprise\": enterprise})]\n\n\ndef get_context(context):\n\tenterprise = frappe.form_dict.enterprise\n\tif frappe.form_dict.user:\n\t\tadd_user(frappe.form_dict.user, enterprise)\n\n\tuser = frappe.session.user\n\n\tif not enterprise:\n\t\traise frappe.ValidationError(_(\"You need specified IOT Enterprise\"))\n\n\tuser_roles = frappe.get_roles(frappe.session.user)\n\tif 'IOT User' not in user_roles or frappe.session.user == 'Guest':\n\t\traise frappe.PermissionError(\"Your account is not an IOT User!\")\n\n\tif not (is_enterprise_admin(user, enterprise) or 'IOT Manager' in user_roles):\n\t\traise frappe.PermissionError\n\n\tcontext.no_cache = 1\n\tcontext.show_sidebar = True\n\n\tpossible_users = list_possible_users(enterprise)\n\n\tcontext.parents = [{\"label\": enterprise, \"route\": \"/iot_enterprises/\" + enterprise}]\n\tcontext.doc = {\n\t\t\"enterprise\": enterprise,\n\t\t\"possible_users\": possible_users\n\t}\n","sub_path":"iot/templates/pages/iot_add_user.py","file_name":"iot_add_user.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"554238479","text":"# Voting with delegation and delegation-cycle breaking\n# This is based on @DavidKnott's viper/examples/voting/ballot.v.py and\n# https://solidity.readthedocs.io/en/develop/solidity-by-example.html#voting\n# but diverges significantly due to the constraint of bounded gas cost.\n\n# NOT YET TESTED AND PROBALY HAS BUGS.\n\n# Information about voters\nvoters: public({\n # `chairperson` called `give_right_to_vote` for this voter\n can_vote : bool,\n # if true, this voter's direct or delegated vote has been counted. initially False.\n counted : bool,\n # person delegated to, if they called `delegate`. the initial value of\n # '0x0000000000000000000000000000000000000000' means they have not delegated.\n delegate: address,\n # index of the voted proposal, _if_ they directly voted by calling `vote`.\n # -1 means they haven't directly voted, but possibly they delegated.\n direct_vote: num\n}[address])\n\n# This is a type for a list of proposals.\nproposals: public({\n # short name (up to 32 bytes)\n name: bytes32,\n # number of accumulated votes\n vote_count: num\n}[num])\n\nvoter_count: public(num)\nchairperson: public(address)\n\n# Setup global variables\ndef __init__(_proposalNames: bytes32[5]):\n self.chairperson = msg.sender\n self.voter_count = 0\n for i in range(5):\n self.proposals[i] = {\n name: _proposalNames[i],\n vote_count: 0\n }\n\n@constant\ndef hasDirectlyVoted(addr: address) -> bool:\n return self.voters[addr].direct_vote != -1\n\n@constant\ndef hasDelegated(addr: address) -> bool:\n return self.voters[addr].delegate != 0x0000000000000000000000000000000000000000\n\n@constant\ndef hasActed(addr: address) -> bool:\n return self.hasDirectlyVoted(addr) or self.hasDelegated(addr)\n\n\n# Give an address the right to vote on this ballot.\n# May only be called by `chairperson`.\ndef give_right_to_vote(addr_of_new_voter: address):\n # Throws if sender is not chairperson\n assert msg.sender == self.chairperson\n # We use 0x0000000000000000000000000000000000000000 as a flag, so\n # throw if try to give voting right to it\n assert addr_of_new_voter != 0x0000000000000000000000000000000000000000\n # Throws if already voted or delegated\n assert not self.hasActed(addr_of_new_voter)\n self.voter_count += 1\n self.voters[addr_of_new_voter].can_vote = True\n # This means they haven't directly voted. The default inital value\n # of 0 (for num type) would mean they directly voted for proposal 0.\n self.voters[addr_of_new_voter].direct_vote = -1\n\n\n# Delegate your vote to the voter at `to_addr`.\n# *With the condition* that to_addr either has already voted or (has already delegated\n# and had their vote counted)\ndef delegate(to_addr: address):\n # Throws if delegate or sender has not been given the right to vote\n assert self.voters[to_addr].can_vote and self.voters[msg.sender].can_vote\n # Throws if sender has already directly voted or delegated\n assert not self.hasActed(msg.sender)\n # Throws if sender tries to delegate their vote to themselves\n assert not msg.sender == to_addr\n\n assert self.hasDirectlyVoted(to_addr) or (\n self.hasDelegated(to_addr) and self.voters[to_addr].counted)\n\n self.voters[msg.sender].delegate = to_addr\n\n# Directly vote on `proposals[proposal_ind].name`. _Eventually_ this\n# will result in votes delegated to `msg.sender` being counted also.\ndef vote(proposal_ind: num):\n # Throws if delegate or sender has not been given the right to vote\n assert self.voters[to_addr].can_vote and self.voters[msg.sender].can_vote\n # Throws if sender has already voted or delegated\n assert not self.hasActed(msg.sender)\n\n self.voters[msg.sender].counted = True\n self.voters[msg.sender].direct_vote = proposal_ind\n # If `proposal_ind` is out of the range of the array,\n # this will throw automatically and revert all changes.\n self.proposals[proposal_ind].vote_count += 1\n\n\n# If voter u has delegated to v, and v has\n# directly voted, and u has not had their vote counted,\n# then this will count's u's vote.\n# Note that this can be called by anyone to move the contract forward.\ndef count_delegated_vote(u_addr:address):\n assert self.hasDelegated(u_addr)\n u = self.voters[u_addr]\n assert not u.counted\n v_addr = u.delegate\n assert self.hasDirectlyVoted(v_addr)\n v = self.voters[v_addr]\n # If `v.ballot_ind` is out of the range of the array,\n # this will throw automatically and revert all\n # changes.\n proposal = self.proposals[v.direct_vote]\n u.counted = True\n proposal.vote_count += 1\n\n\n# Computes the winning proposal taking only counted votes into account.\n@constant\ndef winning_proposal_from_counted_votes() -> num:\n winning_vote_count = 0\n for i in range(5):\n if self.proposals[i].vote_count > winning_vote_count:\n winning_vote_count = self.proposals[i].vote_count\n winning_proposal = i\n return winning_proposal\n\n# Calls winning_proposal() function to get the index\n# of the winner contained in the proposals array and then\n# returns the name of the winner\n@constant\ndef current_winner_name() -> bytes32:\n return self.proposals[self.winning_proposal_from_counted_votes()].name","sub_path":"blockchain/viper_examples/ballot2_in_order.v.py","file_name":"ballot2_in_order.v.py","file_ext":"py","file_size_in_byte":5227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"624327868","text":"# Nama : Willy Wilsen\n# NIM : 16520145\n# Tanggal : 18 November 2020\n# Deskripsi : Membuat program yang mencari panjang dari substring terpanjang yang merupakan palindrom.\n\n# KAMUS\n# N : int (Asumsikan lebih dari 0)\n# X : str\n# cek : str\n# panjang : int\n# max_palindrom : int\n# sum_palindrom : int\n# i : int\n# j : int\n\n# ALGORITMA\nN = int(input(\"Masukkan panjang string: \")) # input N\nX = str(input(\"Masukkan string: \")) # input X\npanjang = 1\nmax_palindrom = 0\n\nif (len(X) == N): # saat sesuai\n while (panjang <= len(X)):\n i = 0\n while (i <= (len(X)-panjang)):\n palindrom = True\n cek = \"\"\n j = i\n while (j < (panjang + i)):\n cek += X[j]\n j += 1\n j = 0\n while (j < len(cek) and palindrom):\n if (cek[j] != cek[len(cek)-j-1]):\n palindrom = False\n j += 1\n if (palindrom):\n sum_palindrom = len(cek)\n if (sum_palindrom > max_palindrom):\n max_palindrom = sum_palindrom\n i += 1\n panjang += 1\n print(\"Panjang palindrom string adalah\", max_palindrom)\nelse: # saat tidak sesuai\n print(\"Maaf, panjang string tidak sesuai\")\n","sub_path":"src/Tugas Praktikum/P03_16520145_03.py","file_name":"P03_16520145_03.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"376806667","text":"import matplotlib.pyplot as plt\nimport networkx as nx\nimport dgl\n\n\nimport grakel\nfrom grakel.utils import graph_from_networkx\nfrom grakel.kernels import GraphletSampling\n\ndef compare_graphlets(g_list):\n gl_kernel = GraphletSampling(normalize=True,sampling={'n_samples': 10000})\n grakels = dgl_grakel(g_list)\n #print(\"converted...\")\n grak_list = []\n for i, gr in enumerate(grakels):\n grak_list.append(gr)\n # initialise kernel\n gl_kernel.fit_transform([grak_list[0]])\n matching = gl_kernel.transform(grak_list)\n # matching = []\n # for grak in grak_list[1:]:\n # matching.append(gl_kernel.transform([grak]))\n return matching\n\ndef print_graph(g,filename=\"graph.png\"):\n # save graph to image file,\n plot_size = (5,5)\n plt.figure(3,figsize=plot_size)\n # if g.device == 'cuda':\n g=g.cpu()\n if g.is_homogeneous:\n nx.draw(dgl.to_networkx(g))\n else:\n nx.draw(dgl.to_networkx(dgl.to_homogeneous(g)))\n #plt.show()\n plt.savefig(filename)\n plt.close()\n \ndef dgl_grakel(g):\n # convert dgl graph to grakel graph\n nx_list = []\n for graph in g:\n # 1. dgl to networkx\n graph=graph.cpu()\n nx_graph = dgl.to_networkx(graph)\n # 2. networkx to grakel\n for node in nx_graph.nodes():\n nx_graph.nodes[node]['label'] = node\n nx_list.append(nx_graph)\n \n krakel_graphs = graph_from_networkx(nx_list,as_Graph=True,node_labels_tag='label')\n # print(\"grakel:\",g)\n return krakel_graphs\n \n\ndef graphlet_pair_compare(graph_1,graph_2):\n graph_list = [graph_1,graph_2]\n #print(\"converting graphs..\")\n match_score = compare_graphlets(graph_list)\n #print(\"match_score\",match_score[0])\n return match_score[0][1][0]","sub_path":"redundant/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"640545928","text":"# 2018年刑侦科推理试题\n# from collections import namedtuple\n# ans = namedtuple\n\n\ndef check2():\n if (b2 + 2) % 4 == e5:\n return True\n return False\n\n\ndef if_same(ls):\n for i in ls[1:]:\n if i != ls[0]:\n return False\n return True\n\n\ndef check3():\n if c3 == 0 and c3 != f6 and if_same((f6, b2, d4)):\n return True\n if c3 == 1 and f6 != c3 and if_same((c3, b2, d4)):\n return True\n if c3 == 2 and b2 != c3 and if_same((c3, f6, d4)):\n return True\n if c3 == 3 and d4 != c3 and if_same((c3, f6, b2)):\n return True\n return False\n\n\ndef check4():\n if (d4 == 0 and a1 == e5) or (d4 == 1 and b2 == g7) or \\\n (d4 == 2 and a1 == i9) or (d4 == 3 and f6 == j10):\n return True\n return False\n\n\ndef check5():\n if e5 == h8 == 0 or e5 == d4 == 1 or e5 == i9 == 2 or e5 == g7 == 3:\n return True\n return False\n\n\ndef check6():\n if b2 == d4 == h8 or a1 == f6 == h8 or c3 == j10 == h8 or e5 == i9 == h8:\n return True\n return False\n\n\ndef min_max():\n ls = [0] * 4\n for i in (a1, b2, c3, d4, e5, f6, g7, h8, i9, j10):\n ls[i] += 1\n m, M = min(ls), max(ls)\n p, q = 0, 0\n for i in range(4):\n if ls[i] == m:\n p = i\n if ls[i] == M:\n q = i\n return p, q\n\n\ndef check7():\n m, n = min_max()\n if (g7 == 0 and m == 2) or g7 == m == 1 or \\\n (g7 == 2 and m == 0) or g7 == m == 3:\n return True\n return False\n\n\ndef check8():\n if (h8 == 0 and abs(g7 - a1) > 1) or (h8 == 1 and abs(e5 - a1) > 1) or\\\n (h8 == 2 and abs(b2 - a1) > 1) or (h8 == 3 and abs(j10 - a1) > 1):\n return True\n return False\n\n\ndef check9():\n b1 = a1 == f6\n if (i9 == 0 and (f6 == e5 ^ b1)) or (i9 == 1 and (j10 == e5 ^ b1)) or\\\n (i9 == 2 and (b2 == e5 ^ b1)) or (i9 == 3 and (i9 == e5 ^ b1)):\n return True\n return False\n\n\nfor a1 in (0, 1, 2, 3):\n for b2 in (0, 1, 2, 3):\n for c3 in (0, 1, 2, 3):\n for d4 in (0, 1, 2, 3):\n for e5 in (0, 1, 2, 3):\n # b2:0123,e2301\n if check2():\n for f6 in (0, 1, 2, 3):\n if check3():\n for g7 in (0, 1, 2, 3):\n for h8 in (0, 1, 2, 3):\n for i9 in (0, 1, 2, 3):\n if check5():\n for j10 in (0, 1, 2, 3):\n if check4() and check7() and check8() and check9():\n print(\n a1, b2, c3, d4, e5, f6, g7, h8, i9, j10)\n # break\n","sub_path":"python/2018f_exe/detective2018.py","file_name":"detective2018.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"87080224","text":"\"\"\"\r\nPrivate Variable cannot be accessed outside of the class\r\nits mentioned as \"__privateVariable\"\r\n\"\"\"\r\n\r\nclass PrivateVariable:\r\n\r\n __a = 10\r\n\r\n def display(self):\r\n print(f\"Private Variable : {PrivateVariable.__a}\")\r\n\r\nprint(PrivateVariable.__a) # AttributeError: type object 'PrivateVariable' has no attribute '__a'\r\nobj = PrivateVariable()\r\nobj.display() # Private Variable : 10\r\n\r\n","sub_path":"Oops_Concepts/Encapsulation/PrivateVariable.py","file_name":"PrivateVariable.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"597865276","text":"import dmsh\nfrom helpers import assert_norm_equality, save\n\n\ndef test_pacman(show=False):\n geo = dmsh.Difference(\n dmsh.Circle([0.0, 0.0], 1.0),\n dmsh.Polygon([[0.0, 0.0], [1.5, 0.4], [1.5, -0.4]]),\n )\n X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-10)\n\n ref_norms = [3.0385105041432689e02, 1.3644964912810719e01, 1.0]\n assert_norm_equality(X.flatten(), ref_norms, 1.0e-12)\n return X, cells\n\n\nif __name__ == \"__main__\":\n X, cells = test_pacman(show=False)\n save(\"pacman.png\", X, cells)\n","sub_path":"test/test_pacman.py","file_name":"test_pacman.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"599079474","text":"import json\nfrom infoeducatie.users.tests.base_user_test import TestWithUser\n\nfrom nose.tools import eq_\n\nfrom infoeducatie.extensions import db\n\nfrom utils.tests import fixtures\n\nload_fixture = fixtures(\"alumni\", \"alumnus.create\")\n\n\nclass AlumniCreationTest(TestWithUser):\n db = db\n\n def test_alumnus_creation_with_valid_data(self):\n data = load_fixture('create_alumnus_valid_data')\n\n response = self.client.post(\"/api/1/alumni/\", data=json.dumps(data),\n content_type='application/json')\n\n assert_response = load_fixture('response_alumnus_valid_data')\n\n response_data = json.loads(response.data)\n eq_(response_data['user']['id'], 1)\n\n del response_data['user']\n eq_(response_data, assert_response)\n eq_(response.status_code, 200)\n\n def test_alumnus_creation_with_missing_data(self):\n data = load_fixture('create_alumnus_missing_data')\n response = self.client.post(\"/api/1/alumni/\", data=json.dumps(data),\n content_type='application/json')\n\n assert_response = load_fixture('response_alumnus_missing_data')\n eq_(response.status_code, 400)\n","sub_path":"infoeducatie/alumni/tests/test_create_alumni.py","file_name":"test_create_alumni.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"54493516","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: edwardahn\n\nUtility functions for reading bag files for the Assured Autonomy\nProject.\n\"\"\"\n\nimport numpy as np\n\n\ndef parse_bag(bag):\n start_time = None\n num_messages = bag.get_message_count()\n t = []\n x = []\n y = []\n yaw = []\n x_dot = []\n y_dot = []\n yaw_dot = []\n steer = []\n vel = []\n\n first_message_read = False\n recorded_topics = [\"/ekf_localization/odom\", \"/commands/keyboard\"]\n for topic, msg, ros_t in bag.read_messages(topics=recorded_topics):\n if not first_message_read:\n first_message_read = True\n start_time = 10**9 * ros_t.secs + ros_t.nsecs\n current_time = 10**9 * ros_t.secs + ros_t.nsecs\n index = int(current_time - start_time)\n t.append(current_time)\n if topic == \"/ekf_localization/odom/\" or \\\n topic == \"/ekf_localization/odom\":\n x.append(msg.pose.pose.position.x)\n y.append(msg.pose.pose.position.y)\n yaw.append(msg.pose.pose.orientation.z)\n x_dot.append(msg.twist.twist.linear.x)\n y_dot.append(msg.twist.twist.linear.y)\n yaw_dot.append(msg.twist.twist.angular.z)\n\n # Interpolate\n if len(steer) > 0:\n steer.append(steer[-1])\n vel.append(vel[-1])\n else:\n steer.append(0)\n vel.append(0)\n\n elif topic == \"/commands/keyboard/\" or \\\n topic == \"/commands/keyboard\":\n steer.append(msg.drive.steering_angle)\n vel.append(msg.drive.speed)\n\n # Interpolate\n if len(x) > 0:\n x.append(x[-1])\n y.append(y[-1])\n yaw.append(yaw[-1])\n x_dot.append(x_dot[-1])\n y_dot.append(y_dot[-1])\n yaw_dot.append(yaw_dot[-1])\n else:\n x.append(0)\n y.append(0)\n yaw.append(0)\n x_dot.append(0)\n y_dot.append(0)\n yaw_dot.append(0)\n else:\n raise RuntimeError(\"Unknown message read\")\n\n bag.close()\n\n t = np.array(t)\n x = np.array(x)\n y = np.array(y)\n yaw = np.array(yaw)\n x_dot = np.array(x_dot)\n y_dot = np.array(y_dot)\n yaw_dot = np.array(yaw_dot)\n steer = np.array(steer)\n vel = np.array(vel)\n return t, x, y, yaw, x_dot, y_dot, yaw_dot, steer, vel\n","sub_path":"aa_metrics/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"420087282","text":"\"\"\"Module for creating, storing and editing tensors.\"\"\"\n\nimport os\nimport os.path\nimport copy\nimport json\nimport logging\n\nfrom utils import marker_cell_identifier\n\n\nclass Tensor(object):\n \"\"\"Class for managing individual tensors.\"\"\"\n\n def __init__(self, tensor_id, centroid, marker, creation_type):\n self._data = dict(tensor_id=tensor_id,\n centroid=list(centroid),\n marker=list(marker),\n creation_type=creation_type,\n active=True)\n\n def __eq__(self, other):\n return self._data == other._data\n\n def __repr__(self):\n prefix = \"\"\n info = []\n for key in Tensor.keys():\n info.append(\"{}={}\".format(key, self._data[key]))\n return prefix + \", \".join(info) + suffix\n\n @staticmethod\n def keys():\n return [\"tensor_id\", \"centroid\", \"marker\", \"creation_type\", \"active\"]\n\n @staticmethod\n def extended_keys():\n return [\"tensor_id\", \"centroid_row\", \"centroid_col\", \"marker_row\", \"marker_col\", \"creation_type\", \"active\"]\n\n @staticmethod\n def from_json(line):\n \"\"\"Create Tensor from json string.\"\"\"\n d = json.loads(line)\n tensor = Tensor(tensor_id=d[\"tensor_id\"],\n centroid=list(d[\"centroid\"]),\n marker=list(d[\"marker\"]),\n creation_type=d[\"creation_type\"])\n tensor._data[\"active\"] = d[\"active\"]\n return tensor\n\n @staticmethod\n def csv_header():\n return \",\".join(Tensor.extended_keys())\n\n @property\n def csv_line(self):\n return \",\".join([str(getattr(self, k)) for k in Tensor.extended_keys()])\n\n @property\n def json(self):\n return json.dumps(self._data)\n\n @property\n def tensor_id(self):\n \"\"\"Return the tensor identifier.\"\"\"\n return self._data[\"tensor_id\"]\n\n @property\n def centroid(self):\n \"\"\"Return the cell centroid position.\"\"\"\n return self._data[\"centroid\"]\n\n @property\n def centroid_row(self):\n \"\"\"Return the cell centroid row.\"\"\"\n return self._data[\"centroid\"][0]\n\n @property\n def centroid_col(self):\n \"\"\"Return the cell centroid column.\"\"\"\n return self._data[\"centroid\"][1]\n\n @property\n def marker(self):\n \"\"\"Return the membrane marker position.\"\"\"\n return self._data[\"marker\"]\n\n @property\n def marker_row(self):\n \"\"\"Return the membrane marker row.\"\"\"\n return self._data[\"marker\"][0]\n\n @property\n def marker_col(self):\n \"\"\"Return the membrane marker column.\"\"\"\n return self._data[\"marker\"][1]\n\n @property\n def creation_type(self):\n \"\"\"Return the creation type (automated/manual).\"\"\"\n return self._data[\"creation_type\"]\n\n @property\n def active(self):\n \"\"\"Return the active status of the tensor (True/False).\"\"\"\n return self._data[\"active\"]\n\n def update(self, name, value):\n \"\"\"Update a property of the tensor.\n\n :returns: json string describing update\n \"\"\"\n self._data[name] = value\n d = dict(tensor_id=self.tensor_id, action=\"update\")\n d[name] = value\n logging.debug(json.dumps(d))\n return json.dumps(d)\n\n\nclass Command(object):\n \"\"\"Command class to enable undo/redo functionality.\"\"\"\n\n def __init__(self, do_method, undo_method, do_args, undo_args):\n self.do_method = do_method\n self.do_args = do_args\n self.undo_method = undo_method\n self.undo_args = undo_args\n self.audit_log = None\n\n def do(self):\n \"\"\"Execute a command.\"\"\"\n self.audit_log = self.do_method(*self.do_args)\n return self.audit_log\n\n def undo(self):\n \"\"\"Reverse the effect of a command.\"\"\"\n return self.undo_method(*self.undo_args)\n\n\nclass TensorManager(dict):\n \"\"\"Class for creating, storing and editing tensors.\"\"\"\n\n def __init__(self):\n self.commands = []\n self.command_offset = 0\n\n def __eq__(self, other):\n if len(self) != len(other):\n return False\n for key, value in self.items():\n if key not in other:\n return False\n if not value == other[key]:\n return False\n return True\n\n @property\n def identifiers(self):\n \"\"\"Return sorted list of identifiers.\"\"\"\n ids = self.keys()\n return sorted(ids)\n\n @property\n def audit_log(self):\n \"\"\"Return list of commands excluding undone ones.\"\"\"\n num_commands = len(self.commands) + self.command_offset\n return [self.commands[i] for i in range(num_commands)]\n\n @property\n def csv(self):\n \"\"\"Return list of csv lines.\"\"\"\n lines = []\n lines.append(Tensor.csv_header())\n for tensor_id in self.identifiers:\n tensor = self[tensor_id]\n lines.append(tensor.csv_line)\n return lines\n\n def run_command(self, cmd):\n \"\"\"Add command to command list and run it.\"\"\"\n # Clip future if running a new command.\n if self.command_offset != 0:\n self.commands = self.commands[:self.command_offset]\n self.command_offset = 0\n\n # Add the command to the history and run it.\n self.commands.append(cmd)\n self.commands[-1].do()\n\n def undo(self):\n \"\"\"Undo the last action.\"\"\"\n logging.debug(\"Undoing...\")\n # Command offset will be negative if we have already undone things.\n cmd_index = -1 + self.command_offset\n # Basic checking to ensure that there is something to undo.\n if len(self.commands) + cmd_index < 0:\n logging.debug(\"Nothing to undo...\")\n return None\n\n info = self.commands[cmd_index].undo()\n self.command_offset -= 1\n return info\n\n def redo(self):\n \"\"\"Redo the last action.\"\"\"\n logging.debug(\"Redoing...\")\n # Basic checking to ensure that there is something to redo.\n if self.command_offset >= 0:\n logging.debug(\"Nothing to redo...\")\n return None\n cmd_index = self.command_offset\n info = self.commands[cmd_index].do()\n self.command_offset += 1\n return info\n\n def create_tensor(self, tensor_id, centroid, marker,\n creation_type=\"automated\"):\n \"\"\"Create a tensor and store it.\n\n Not for manual editing.\n \"\"\"\n self[tensor_id] = Tensor(tensor_id, centroid, marker, creation_type)\n d = copy.deepcopy(self[tensor_id]._data)\n d[\"action\"] = \"create\"\n logging.debug(json.dumps(d))\n return json.dumps(d)\n\n def _delete_tensor(self, tensor_id):\n \"\"\"Never call this directly.\"\"\"\n d = dict(tensor_id=tensor_id, action=\"delete\")\n del self[tensor_id]\n logging.debug(json.dumps(d))\n\n def add_tensor(self, centroid, marker):\n \"\"\"Add a tensor manually.\n\n For manual editing with undo.\n \"\"\"\n tensor_id = max(self.identifiers) + 1\n cmd = Command(do_method=self.create_tensor,\n undo_method=self._delete_tensor,\n do_args=[tensor_id, centroid, marker, \"manual\"],\n undo_args=[tensor_id])\n self.run_command(cmd)\n return cmd.audit_log\n\n def inactivate_tensor(self, tensor_id):\n \"\"\"Mark a tensor as inactive.\"\"\"\n tensor = self[tensor_id]\n cmd = Command(do_method=tensor.update,\n undo_method=tensor.update,\n do_args=[\"active\", False],\n undo_args=[\"active\", True])\n self.run_command(cmd)\n return cmd.audit_log\n\n def update_centroid(self, tensor_id, new_position):\n \"\"\"Update the position of a centroid.\"\"\"\n tensor = self[tensor_id]\n prev_position = tensor.centroid\n cmd = Command(do_method=tensor.update,\n undo_method=tensor.update,\n do_args=[\"centroid\", list(new_position)],\n undo_args=[\"centroid\", prev_position])\n self.run_command(cmd)\n return cmd.audit_log\n\n def update_marker(self, tensor_id, new_position):\n \"\"\"Update the position of a marker.\"\"\"\n tensor = self[tensor_id]\n prev_position = tensor.marker\n cmd = Command(do_method=tensor.update,\n undo_method=tensor.update,\n do_args=[\"marker\", list(new_position)],\n undo_args=[\"marker\", prev_position])\n self.run_command(cmd)\n return cmd.audit_log\n\n def read_raw_tensors(self, fh):\n \"\"\"Read in raw tensors from file.\"\"\"\n for line in fh:\n tensor = Tensor.from_json(line)\n self[tensor.tensor_id] = tensor\n\n def write_raw_tensors(self, fh):\n \"\"\"Write out raw tensors to file.\"\"\"\n for tensor_id in self.identifiers:\n tensor = self[tensor_id]\n if tensor.creation_type == \"automated\":\n fh.write(\"{}\\n\".format(tensor.json))\n\n def write_audit_log(self, fh):\n \"\"\"Write out an audit log.\"\"\"\n for cmd in self.audit_log:\n fh.write(\"{}\\n\".format(cmd.audit_log))\n\n def apply_json(self, line):\n \"\"\"Apply a line of json.\"\"\"\n d = json.loads(line)\n action = d.pop(\"action\")\n if action == \"update\":\n tensor_id = d.pop(\"tensor_id\")\n for key, value in d.items():\n self[tensor_id]._data[key] = value\n elif action == \"create\":\n tensor_id = d[\"tensor_id\"]\n self[tensor_id] = Tensor.from_json(json.dumps(d))\n else:\n raise(RuntimeError)\n\n def apply_audit_log(self, fh):\n \"\"\"Apply an audit log.\"\"\"\n for json_line in fh:\n self.apply_json(json_line)\n\n\ndef get_tensors(cells, markers):\n \"\"\"Return TensorManager instance.\"\"\"\n tensor_manager = TensorManager()\n for tensor_id, marker_id in enumerate(markers.identifiers):\n m_region = markers.region_by_identifier(marker_id)\n marker_position = m_region.convex_hull.centroid\n cell_id = marker_cell_identifier(m_region, cells)\n if cell_id == 0:\n logging.debug(\"Skipping tensor from cell_id 0\")\n continue\n c_region = cells.region_by_identifier(cell_id)\n centroid = c_region.centroid\n tensor_manager.create_tensor(tensor_id, centroid, marker_position)\n return tensor_manager\n\n\ndef test_overall_api():\n\n # Test the creation of a tensor.\n tensor_manager = TensorManager()\n tensor_manager.create_tensor(1, (0, 0), (3, 5))\n tensor1 = tensor_manager[1]\n assert isinstance(tensor1, Tensor)\n assert tensor1.tensor_id == 1\n assert tensor1.centroid == [0, 0]\n assert tensor1.marker == [3, 5]\n assert tensor1.creation_type == \"automated\"\n\n # Test inactivate tensor and undo/redo.\n assert tensor_manager.command_offset == 0\n assert tensor1.active is True\n tensor_manager.inactivate_tensor(1)\n assert tensor1.active is False\n tensor_manager.undo()\n assert tensor1.active is True\n\n # Test using undo when already nothing left to undo.\n assert tensor_manager.undo() is None\n\n assert tensor_manager.command_offset == -1\n tensor_manager.redo()\n assert tensor1.active is False\n assert tensor_manager.command_offset == 0\n\n # Test using redo when already at present.\n assert tensor_manager.redo() is None\n\n # Test update_centroid and undo/redo.\n tensor_manager.update_centroid(1, (1, 10))\n assert tensor1.centroid == [1, 10]\n tensor_manager.undo()\n assert tensor1.centroid == [0, 0]\n tensor_manager.redo()\n assert tensor1.centroid == [1, 10]\n\n # Test update_marker and undo/redo.\n tensor_manager.update_marker(1, (100, 8))\n assert tensor1.marker == [100, 8]\n tensor_manager.undo()\n assert tensor1.marker == [3, 5]\n tensor_manager.redo()\n assert tensor1.marker == [100, 8]\n\n # Test TensorManager.identifiers property.\n assert tensor_manager.identifiers == [1]\n tensor_manager.create_tensor(5, (4, 0), (7, 5))\n assert tensor_manager.identifiers == [1, 5]\n tensor_manager.create_tensor(2, (2, 8), (1, 6))\n assert tensor_manager.identifiers == [1, 2, 5]\n\n # Test add_tensor undo/redo.\n tensor_id = tensor_manager.add_tensor((3, 4), (5, 6))\n assert tensor_id == 6\n tensor = tensor_manager[tensor_id]\n assert tensor.tensor_id == tensor_id\n assert tensor.centroid == [3, 4]\n assert tensor.marker == [5, 6]\n assert tensor.creation_type == \"manual\"\n assert tensor_manager.identifiers == [1, 2, 5, 6]\n tensor_manager.undo()\n assert (6 in tensor_manager) is False\n assert tensor_manager.identifiers == [1, 2, 5]\n tensor_manager.redo()\n assert (6 in tensor_manager) is True\n assert tensor_manager.identifiers == [1, 2, 5, 6]\n\n # Test undo followed by new action and audit_log property.\n assert len(tensor_manager.commands) == 4\n assert len(tensor_manager.audit_log) == 4\n tensor_manager.undo()\n assert (6 in tensor_manager) is False\n tensor_manager.undo()\n assert len(tensor_manager.commands) == 4\n assert tensor_manager.command_offset == -2\n assert len(tensor_manager.audit_log) == 2\n assert tensor1.marker == [3, 5]\n assert tensor_manager[2].centroid == [2, 8]\n tensor_manager.update_centroid(2, (1, 1))\n assert tensor_manager[2].centroid == [1, 1]\n assert len(tensor_manager.commands) == 3\n assert tensor_manager.command_offset == 0\n\n # Manually create another tenor.\n tensor_id = tensor_manager.add_tensor((3, 4), (5, 6))\n\n # Test tensor json property and from_json static method.\n t1_copy = Tensor.from_json(tensor1.json)\n assert t1_copy == tensor1\n\n # Test writing of raw tensor data.\n raw_tensor_file = \"test_raw_tensors.txt\"\n with open(raw_tensor_file, \"w\") as fh:\n tensor_manager.write_raw_tensors(fh)\n assert os.path.isfile(raw_tensor_file)\n\n # Test writing of audit log.\n audit_file = \"test_audit.log\"\n with open(audit_file, \"w\") as fh:\n tensor_manager.write_audit_log(fh)\n assert os.path.isfile(audit_file)\n\n # Test recreation from an audit file.\n new_tensor_manager = TensorManager()\n with open(raw_tensor_file, \"r\") as fh:\n new_tensor_manager.read_raw_tensors(fh)\n with open(audit_file) as fh:\n new_tensor_manager.apply_audit_log(fh)\n assert tensor_manager == new_tensor_manager\n\n # Test csv functionality.\n assert Tensor.extended_keys() == [\"tensor_id\", \"centroid_row\", \"centroid_col\", \"marker_row\", \"marker_col\", \"creation_type\", \"active\"]\n assert Tensor.csv_header() == \"tensor_id,centroid_row,centroid_col,marker_row,marker_col,creation_type,active\"\n assert tensor1.csv_line == \"1,1,10,3,5,automated,False\"\n\n # Clean up.\n os.unlink(audit_file)\n os.unlink(raw_tensor_file)\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG)\n test_overall_api()\n","sub_path":"scripts/tensor.py","file_name":"tensor.py","file_ext":"py","file_size_in_byte":15034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"630854638","text":"from app.models import Intervention\nfrom app.schemas import InterventionCreate, InterventionUpdate\nfrom app.crud.base import CRUDBase\nimport sqlalchemy as sa\nfrom sqlalchemy.orm import Session\n\n\nclass CRUDIntervention(CRUDBase[Intervention, InterventionCreate, InterventionUpdate]):\n def get_by_year(self, db: Session, organization_id: int, year: int):\n return (\n db.query(self.model)\n .filter(self.model.organization_id == organization_id)\n .filter(\n sa.or_(\n sa.extract(\"year\", self.model.intervention_start_date) == year,\n sa.extract(\"year\", self.model.intervention_end_date) == year,\n )\n )\n .all()\n )\n def get_by_intervention_type_and_year(self, db: Session, organization_id: int, intervention_type: str, year: int):\n return (\n db.query(self.model)\n .filter(self.model.organization_id == organization_id)\n .filter(self.model.intervention_type == intervention_type)\n .filter(\n sa.or_(\n sa.extract(\"year\", self.model.intervention_start_date) == year,\n sa.extract(\"year\", self.model.intervention_end_date) == year,\n )\n )\n .all()\n )\n def get_planned_by_year(self, db: Session, organization_id: int, year: int):\n return (\n db.query(self.model)\n .filter(self.model.organization_id == organization_id)\n .filter(\n sa.or_(\n sa.extract(\"year\", self.model.intervention_start_date) == year,\n sa.extract(\"year\", self.model.intervention_end_date) == year,\n )\n )\n .all()\n )\n def get_scheduled_by_year(self, db: Session, organization_id: int, year: int):\n return (\n db.query(self.model)\n .filter(self.model.organization_id == organization_id)\n .filter(sa.extract(\"year\", self.model.date) == year)\n .all()\n )\n\n def get_by_tree(self, db: Session, tree_id: int):\n return db.query(self.model).filter(self.model.tree_id == tree_id).all()\n\n\nintervention = CRUDIntervention(Intervention)\n","sub_path":"backend/app/app/crud/crud_intervention.py","file_name":"crud_intervention.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"54140808","text":"#!/usr/bin/env python\n\nfrom BeautifulSoup import BeautifulSoup as BS\nimport urllib2\n\nclass munich_ort():\n \n def __init__(self,html=None):\n if (html):\n self.html=html\n else:\n self.html=\"https://www.muenchen.de/stadtteile.html\" #default\n self.names=[]\n \n def extract(self):\n html_i = urllib2.urlopen(self.html)\n soup = BS(html_i)\n ort_munchen = soup.findAll('h3')\n\n for i in range(len(ort_munchen)):\n ort=ort_munchen[i].text #.encode(\"ascii\",\"ignore\")\n ort=ort.replace(u\" \", \"-\").encode('utf-8')\n self.names.append(ort)\n if (i==43): # As we know that there are only 44\n break;\n return self.names\n \n def write_file(self,filename): \n fp=open(filename,mode='w')\n for i in range(len(self.names)):\n fp.write(self.names[i]+\"\\n\")\n fp.close()\n\n","sub_path":"brahma/house_prices/munich_ort.py","file_name":"munich_ort.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"137267159","text":"from flask import Flask, jsonify, request, render_template\n\napp = Flask(__name__)\n\n\nstores = [\n {\n 'name': 'Christina\\'s Store',\n 'items': [\n {\n 'name': 'Kitten',\n 'price': 19.99\n }\n ]\n },\n {\n 'name': 'Danny\\'s Store',\n 'items': [\n {\n 'name': 'Bear',\n 'price': 119.99\n }\n ]\n }\n]\n\n# We are not a browser, we are thinking from the server side\n# POST - used to recieve data\n# GET - used to send data back only\n\n# Endpoint being created:\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n# POST /store data: {name:} - create a store with a given name\n@app.route('/store', methods=['POST'])\ndef create_store():\n # request here is the request that was made to this ('/store') endpoint\n # get_json - this will convert the json string into a python dict\n request_data = request.get_json()\n new_store = {\n 'name': request_data['name'],\n 'items': []\n }\n stores.append(new_store)\n return jsonify(new_store)\n\n\n# GET /store/ - get a store with a given name, return data about it\n@app.route('/store/')\ndef get_store(name):\n for item in stores:\n if item['name']==name:\n return jsonify(item)\n return jsonify({'message': 'Store not found'.format(name)})\n\n# GET /store - return list of all stores\n@app.route('/store')\ndef get_stores():\n return jsonify({'stores': stores}) # convert the stores variable into JSON\n\n\n# POST /store//item {name:, price} - create item for a specific store\n@app.route('/store//item', methods=['POST'])\ndef create_item_in_store(name):\n request_data = request.get_json()\n for store in stores:\n if store['name']==name:\n new_item = {\n 'name': request_data['name'],\n 'price': request_data['price']\n }\n store['items'].append(new_item)\n return jsonify(new_item)\n return jsonify({'message': 'Store not found'})\n\n\n# GET /store//item - get all items in specific store\n@app.route('/store//items')\ndef get_items_in_store(name):\n for store in stores:\n if store['name']==name:\n return jsonify({'items': store['items']})\n return jsonify({'message': 'Store not found'})\n\napp.run(port=5000)\n\n","sub_path":"section4_flask_rest/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"155396844","text":"import csv\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom collections import OrderedDict\n\n\n\n'''function to get list of incident links from each mass shooting (or other report or query) page (http://www.gunviolencearchive.org/reports/mass-shooting)'''\n\ndef get_urls(url):\n\tresponse = requests.get(url, timeout = 10)\n\tsoup = BeautifulSoup(response.content, 'html.parser')\n\ttable = soup.find('table', class_=\"responsive sticky-enabled\")\n\trows = table.select('tbody > tr')\n\n\turlList = ['http://www.gunviolencearchive.org' + row.find('a').attrs['href'] for row in rows]\n\n\treturn urlList\n\n\n\n'''get_all_urls function gets all incident links from a mass shooting page, as well as the incident links from all the following mass shooting pages. Works for \"Reports\" pages, as well as \"Search Database\" results. Call the function with url input for the first page of any of these results, and function will return longUrlList with all the incident links from the first page and all the subsequent pages. '''\n\n#initiate empty list to fill with multiple links from multiple pages\nlongUrlList = []\n\ndef get_all_urls(url):\n\t#get all \"View Incident\" links from one page, as done in get_urls function\n\tresponse = requests.get(url, timeout = 10)\n\tsoup = BeautifulSoup(response.content, 'html.parser')\n\ttable = soup.find('table', class_=\"responsive sticky-enabled\")\n\trows = table.select('tbody > tr')\n\t\n\t#add the \"View Incident\" links to a list\n\turlList = ['http://www.gunviolencearchive.org' + row.find('a').attrs['href'] for row in rows]\n\t#add links from urlList to the bigger list of links\n\tfor link in urlList:\n\t\tlongUrlList.append(link)\n\t\n\t#find out if there is another \"next\" page of incidents\n\tnextPageLink = soup.find_all('li', {'class':\"pager-next\"})\n\n\t#if a \"next\" page exists, call function on the link to that \"next\" page\n\tif nextPageLink != []:\n\t\taddToUrl = nextPageLink[0].find('a').attrs['href']\n\t\tnewUrl = 'https://www.gunviolencearchive.org' + addToUrl\n\t\tget_all_urls(newUrl)\n\t#when there are no more pages of links, return the longUrlList, for use with scrape_urls function\n\telse:\n\t\treturn longUrlList\n\n\n\n\n\n\t\n\n'''function to add list of dictionaries (data) to certain csv (category) with headers (fields)'''\n\ndef write_to_csv(category, data, fields):\n\tdf = pd.DataFrame.from_dict(data)\n\twith open(category + '.csv', 'a') as f:\n\t\tdf.to_csv(f, header=False, index=False, columns = fields)\n\n\n'''function creates 4 csv files: Basics, Participants, IncidentCharacteristics, Guns to fill with data'''\n\ndef create_csv():\n\tbasics = OrderedDict([('Incident', None), ('Date', None), ('Place Name', None), ('Address', None), ('City', None), ('State', None), ('Latitude', None), ('Longitude', None), ('Congressional District', None), ('State Senate District', None), ('State House District', None), ('Participant Count', None), ('Victim Count', None), ('Subject Count', None), ('Gun Count', None), ('Notes', None)])\n\tparticipantCharacteristics = OrderedDict([('Incident', None), ('Type', None), ('Relationship', None), ('Name', None), ('Age', None), ('Age Group', None), ('Gender', None), ('Status', None)])\n\tiC = OrderedDict([('Incident', None), ('Incident Characteristic', None)])\n\tgunCharacteristics = OrderedDict([('Incident', None), ('Gun Type', None), ('Stolen', None)])\n\t\n\twith open('Basics.csv', 'w') as csvFile:\n\t\tbasicsHeaders = csv.DictWriter(csvFile, fieldnames = basics)\n\t\tbasicsHeaders.writeheader()\n\t\tcsvFile.write('\\n')\n\n\twith open('Participants.csv', 'w') as csvFile:\n\t\tparticipantHeaders = csv.DictWriter(csvFile, fieldnames = participantCharacteristics)\n\t\tparticipantHeaders.writeheader()\n\t\tcsvFile.write('\\n')\n\n\twith open('IncidentCharacteristics.csv', 'w') as csvFile:\n\t\tiCHeaders = csv.DictWriter(csvFile, fieldnames = iC)\n\t\tiCHeaders.writeheader()\n\t\tcsvFile.write('\\n')\n\n\twith open('Guns.csv', 'w') as csvFile:\n\t\tgunHeaders = csv.DictWriter(csvFile, fieldnames = gunCharacteristics)\n\t\tgunHeaders.writeheader()\n\t\tcsvFile.write('\\n')\n\n\n\n\t\n'''function to get the information from each incident page (ex. http://www.gunviolencearchive.org/incident/604762), puts all data into one of 4 csv files created by create_csv()'''\n\ndef scrape_urls(url):\n\t\n\t# checking that user provided valid link\n\tif url.startswith(\"http://www.gunviolencearchive.org/incident/\"):\n\t\tiD = url.split(\"http://www.gunviolencearchive.org/incident/\")\n\t\tincidentString = iD[1]\n\t\tincidentNumber = int(incidentString)\n\telse:\n\t\tprint('URL not valid')\n\t\treturn\n\n\tresponse = requests.get(url, timeout = 10)\n\tsoup = BeautifulSoup(response.content, 'html.parser')\n\theaders = soup.find_all('h2')\n\n\tbasicInfo = [{'Incident' : incidentNumber, 'Date': None, 'Place Name': None, 'Address': None, 'City': None, 'State': None, 'Latitude': None, 'Longitude': None, 'Congressional District': None, 'State Senate District': None, 'State House District': None, 'Participant Count': None, 'Victim Count': None, 'Subject Count': None, 'Gun Count': None, 'Notes': None}]\n\tbasicsHeaders = [x for x in basicInfo[0]] #create list of headers\n\n\t#going through all headers in link to find information\n\tfor h in headers:\n\n\t\tif \"Location\" in h.text:\n\n\t\t\tlocationInfo = h.findNextSibling('h3')\n\t\t\tlocation = []\n\t\t\tbasicInfo[0]['Date'] = locationInfo.text\n\t\t\twhile locationInfo is not None:\n\t\t\t\tlocationInfo = locationInfo.findNextSibling('span')\n\t\t\t\tif locationInfo is None:\n\t\t\t\t\tbreak\n\t\t\t\tlocation.append(locationInfo.text)\n\t\t\tlocationLength = len(location)\n\n\t\t\t# some incidents just provide street address (length is 3), others also have a place name which means there is one more 'span' element (length is 4)\n\t\t\tif locationLength == 4:\n\t\t\t\tgeolocation = location[3].split(\"Geolocation: \")[1]\n\t\t\t\tbasicInfo[0]['Latitude'] = geolocation.split(\",\")[0]\n\t\t\t\tbasicInfo[0]['Longitude'] = geolocation.split(\",\")[1]\n\t\t\t\tbasicInfo[0]['City'] = location[2].split(\", \")[0]\n\t\t\t\tbasicInfo[0]['State'] = location[2].split(\", \")[1]\n\t\t\t\tbasicInfo[0]['Address'] = location[1]\n\t\t\t\tbasicInfo[0]['Place Name'] = location[0]\n\t\t\telif locationLength == 3:\n\t\t\t\tgeolocation = location[2].split(\"Geolocation: \")[1]\n\t\t\t\tbasicInfo[0]['Latitude'] = geolocation.split(\",\")[0]\n\t\t\t\tbasicInfo[0]['Longitude'] = geolocation.split(\",\")[1]\n\t\t\t\tbasicInfo[0]['City'] = location[1].split(\", \")[0]\n\t\t\t\tbasicInfo[0]['State'] = location[1].split(\", \")[1]\n\t\t\t\tbasicInfo[0]['Address'] = location[0]\n\t\t\telse: \t#if locationLength < 3 or > 4\n\t\t\t\tprint('Unexpected number of location items for incident ' + incidentString)\n\t\t\t\tcontinue\n\n\t\telif \"Participant\" in h.text:\n\t\t\t\n\t\t\tpartDiv = h.findNextSibling('div')\n\t\t\tuls = partDiv.findChildren('ul')\n\t\t\tparticipantList = []\n\t\t\tvictimCount = 0\n\t\t\tsubjectCount = 0\n\t\t\tparticipantCount = 0\n\n\t\t\t# creates a dictionary for each participant with all of their info and adds it to participantList\n\t\t\tfor ul in uls:\n\t\t\t\tparticipant = {'Incident' : incidentNumber, 'Type': None, 'Relationship': None, 'Name': None, 'Age': None, 'Age Group': None, 'Gender': None, 'Status': None}\n\t\t\t\tfor li in ul:\n\t\t\t\t\tdata = str(li)\t\t#change each li entry to string\n\t\t\t\t\tfact = data[4:-5]\t#remove
  • and
  • from beginning and end\n\t\t\t\t\t\n\t\t\t\t\t#for each fact, split at colon and modify key value pair in participant dictionary\n\t\t\t\t\tif len(fact) > 0: #to account for li of empty string\n\n\t\t\t\t\t\tsplitFact = fact.split(\": \")\n\t\t\t\t\t\tkey, value = splitFact[0], splitFact[1]\n\t\t\t\t\t\tparticipant[key] = value\n\t\t\t\t\n\t\t\t\t#counter variables for numbers of victims and subjects\n\t\t\t\tif participant['Type'] == \"Victim\":\n\t\t\t\t\tvictimCount += 1\n\t\t\t\telif participant['Type'] == \"Subject-Suspect\":\n\t\t\t\t\tsubjectCount += 1\n\t\t\t\t\n\t\t\t\tparticipantList.append(participant)\n\n\t\t\tparticipantCount = victimCount + subjectCount #counter variable for total number of participants\n\t\t\tbasicInfo[0]['Participant Count'] = participantCount\n\t\t\tbasicInfo[0]['Victim Count'] = victimCount\n\t\t\tbasicInfo[0]['Subject Count'] = subjectCount\n\n\t\t\tparticipantsHeaders = [x for x in participantList[0]] #create list of headers\n\t\t\twrite_to_csv('Participants', participantList, participantsHeaders) #add all dictionaries in participantList to Participants.csv\n\t\t\t\n\t\telif \"Incident Characteristics\" in h.text:\n\n\t\t\tICinfo = h.findNextSibling('ul')\n\t\t\tli = ICinfo.findChildren('li')\n\t\t\tincidentCharacteristics = [{'Incident': incidentNumber, 'Incident Characteristic': child.text} for child in li]\n\t\t\t\n\t\t\tiCHeaders = [x for x in incidentCharacteristics[0]] #create list of headers\n\t\t\twrite_to_csv('IncidentCharacteristics', incidentCharacteristics, iCHeaders) #add incident characteristics to IncidentCharacteristics.csv\n\n\t\telif \"Notes\" in h.text:\n\n\t\t\ttxt = h.findNextSibling('p').text\n\t\t\tbasicInfo[0]['Notes'] = txt\n\n\t\telif \"Guns Involved\" in h.text:\n\n\t\t\tgunInfo = h.findNextSibling('ul')\n\t\t\tgunList = []\n\t\t\tgunCount = 0\n\n\t\t\tfor guns in h:\n\t\t\t\twhile gunInfo is not None:\n\t\t\t\t\tgunFacts = gunInfo.findChildren('li', recursive = False)\n\t\t\t\t\tgun = {'Incident' : incidentNumber, 'Gun Type': None, 'Stolen': None}\n\t\t\t\t\tgunCount += 1\n\t\t\t\t\tfor child in gunFacts:\n\t\t\t\t\t\tif \"Type:\" in child.text:\n\t\t\t\t\t\t\tgun['Gun Type'] = child.text.split(\"Type: \")[1]\n\t\t\t\t\t\telif \"Stolen:\" in child.text:\n\t\t\t\t\t\t\tgun['Stolen'] = child.text.split(\"Stolen: \")[1]\n\t\t\t\t\tgunList.append(gun)\n\t\t\t\t\tgunInfo = gunInfo.findNextSibling('ul')\n\n\t\t\tbasicInfo[0]['Gun Count'] = gunCount\n\t\t\t\n\t\t\tgunsHeaders = [x for x in gunList[0]] #create list of headers\n\t\t\twrite_to_csv('Guns', gunList, gunsHeaders) #add guns to Guns.csv\n\n\t\telif \"District\" in h.text:\n\t\t\tdistrictText = h.parent.text\n\t\t\tdistrictText = districtText.splitlines()\n\t\t\t\n\t\t\tfor item in districtText:\n\t\t\t\tdistrictFact = item.split(\": \")\n\t\t\t\tif len(districtFact) == 2:\n\t\t\t\t\tkey, value = districtFact[0], districtFact[1]\n\t\t\t\t\tbasicInfo[0][key] = value\n\n\t#add basic info to Basics.csv\n\twrite_to_csv('Basics', basicInfo, basicsHeaders)\n\t\n\nif __name__==\"__main__\":\n\t\n\t# to create csvs to start collecting data\n\tcreate_csv()\n\n\t# for just one url, use scrape_urls function\n\turl = \"http://www.gunviolencearchive.org/incident/604762\" #using incident 604762 as an example\n\tscrape_urls(url)\n\n\t# for many urls, use get_urls to get a list of urls first\n\t#links = get_urls(\"https://www.gunviolencearchive.org/query/83c968ab-971c-4bb0-8bac-1d08f396095f\")\n\t#for URL in links:\n\t#\tscrape_urls(URL)\n\n\t#gets all urls from results of the query, can then loop over list to scrape data as demonstrated in example above\n\t#get_all_urls('https://www.gunviolencearchive.org/query/a8aef44c-ca1e-43a5-a40c-ffe766853cde')\n\t\n\n\n\n","sub_path":"gunViolenceData.py","file_name":"gunViolenceData.py","file_ext":"py","file_size_in_byte":10406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"442468054","text":"from math import sqrt\n\nfrom Core.esi import find_type, get_system_info\nfrom Navigation.config import METERS_TO_LIGHT_YEARS, JUMPDRIVE, SUBCAP\n\n\ndef get_dotlan_map(args):\n \"\"\"\n Get a dotlan URL for the specific ship, system, and jdc level. Faster, but requires strict ordering of parameters.\n :param args: a list of strings containing the ship name, system name, and jdc level\n :return: a dotlan URL\n \"\"\"\n jdc = _set_jdc(args[1])\n system_info = get_system_info(args[0])\n ship_info = find_type(args[2])\n if system_info and ship_info:\n return _create_dotlan_url(ship_info, system_info, jdc)\n\n return None\n\n\ndef get_jump_dist(arg):\n \"\"\"\n Get the direct LY distance between 2 systems. Does not calculate LY traveled when using mids.\n :param arg: List of 2 systems to calculate the distance between\n :return: Distance between 2 systems\n \"\"\"\n system_one = get_system_info(arg[0])\n system_two = get_system_info(arg[1])\n if system_two and system_one:\n return _get_distance(system_one, system_two)\n\n return None\n\n\ndef _get_distance(system_one, system_two):\n \"\"\"\n Get coordinates of 2 systems and calculate their distance in light years\n :param system_one:\n :param system_two:\n :return: distance between 2 systems\n \"\"\"\n x1, y1, z1 = _get_coordinates(system_one)\n x2, y2, z2 = _get_coordinates(system_two)\n distance_in_meters = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2)\n distance = float(distance_in_meters * METERS_TO_LIGHT_YEARS)\n\n return distance\n\n\ndef _get_coordinates(system_info):\n \"\"\"\n Get the coordinates of a system\n :param system_info:\n :return: a list containing the xyz coordinates of a system\n \"\"\"\n x = system_info['position']['x']\n y = system_info['position']['y']\n z = system_info['position']['z']\n\n return x, y, z\n\n\ndef _create_dotlan_url(ship_info, system_info, jdc):\n \"\"\"\n Craft a dotlan jump planner url using the provided parameters\n :param ship_info: json object containing all the ship info\n :param system_info: json object containing all the system info\n :param jdc: integer representing the jdc level\n :return: a dotlan url\n \"\"\"\n jump_capable = _jump_capable(ship_info)\n if jump_capable:\n return JUMPDRIVE.format(ship=ship_info['name'], jdc=jdc, system=system_info['name'])\n else:\n return SUBCAP.format(jdc=jdc, system=system_info['name'])\n\n\ndef _jump_capable(ship_info):\n \"\"\"\n Determine whether the ship is a jump drive capable ship. Note: attribute 869 is 'jump drive spool time'.\n All jump drive capable ships have this attribute to the best of my knowledge.\n :param ship_info: json object containing all the ship info\n :return: a boolean on whether or not the ship is jump drive capable\n \"\"\"\n for attribute in ship_info['dogma_attributes']:\n if attribute['attribute_id'] == 869:\n return True\n\n return False\n\n\ndef _set_jdc(jdc):\n \"\"\"\n Validate the jdc level\n :param jdc: a string representing the jdc level\n :return: an integer representing the jdc level\n \"\"\"\n try:\n if 1 <= int(jdc) <= 5:\n return jdc\n else: # if jdc is int but out of range\n raise ValueError\n except ValueError:\n return 5\n","sub_path":"Navigation/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"192361443","text":"__author__ = 'mpletty'\nimport numpy as np\n\nfrom cluster import Cluster\n\n\nclass BayesianCluster(Cluster):\n maxClusterSize = 5 # ?\n\n def __init__(self, classifier):\n super(BayesianCluster, self).__init__(classifier)\n\n @staticmethod\n def reduce(F):\n assert type(F) == np.ndarray\n F_ = F.copy()\n\n nr_cols = F.shape[1]\n cols_to_delete = []\n for i in range(nr_cols):\n i_related = np.inner(F_[:, i], F_[:, i])\n for j in range(nr_cols):\n if i == j:\n continue\n else:\n if np.inner(F_[:, i], F_[:, j]) >= i_related:\n # col j contains col i\n cols_to_delete.append(i)\n\n # remove from last col - the other way is mistake\n F_ = np.delete(F_, cols_to_delete, 1)\n\n return F_\n\n @staticmethod\n def get_gtr(F, confusion):\n nr_classes, nr_clusters = F.shape\n out = 0\n for i in range(nr_classes):\n numerator = 0\n denominator = 0\n for k in range(nr_classes):\n numerator += confusion[i, k] * np.sum([F[i, l] * F[k, l] for l in range(nr_clusters)])\n denominator += confusion[i, k] * np.sum([F[k, l] for l in range(nr_clusters)])\n if denominator != 0:\n out += numerator / denominator\n return out\n\n def cluster(self, dataset):\n confusion = self.classifier.confusion\n nr_of_classes = len(self.classifier.classes)\n F = np.eye(nr_of_classes)\n gtr = np.sum([confusion[i, i] for i in range(nr_of_classes)])\n\n pairs = []\n # ((classified, original), value)\n for i in range(nr_of_classes):\n for j in range(nr_of_classes):\n pairs.append(((i, j), confusion[i, j]))\n\n sorted_pairs = sorted(pairs, key=lambda entry: entry[1], reverse=True)\n for (i, j), p_i_j in sorted_pairs:\n if p_i_j == 0:\n continue\n nr_of_clusters = F.shape[1]\n mx = np.sum([F[i, l] for l in range(nr_of_clusters)])\n if i != j and mx <= BayesianCluster.maxClusterSize:\n F_ = F.copy()\n clusters_with_i = [True if F[i, l] == 1 else False for l in range(nr_of_clusters)]\n F_[j, np.array(clusters_with_i)] = 1\n F_ = BayesianCluster.reduce(F_)\n gtr_ = BayesianCluster.get_gtr(F_, confusion)\n if gtr_ >= gtr:\n F = F_\n\n clusters = []\n F = BayesianCluster.reduce(F)\n nr_of_clusters = F.shape[1]\n for j in range(nr_of_clusters):\n cluster = []\n for i in range(nr_of_classes):\n if F[i, j] == 1:\n label = self.classifier.classes[i]\n cluster.append(label)\n\n if len(cluster) == nr_of_classes:\n for k in cluster:\n copy = cluster.copy()\n copy.remove(k)\n clusters.append(copy)\n elif len(cluster) > 0:\n clusters.append(cluster)\n\n return clusters","sub_path":"cluster/BayesianCluster.py","file_name":"BayesianCluster.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"480488270","text":"import sys\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt('dist.dat')\nx = data[:,0]\ny = data[:,1]\n\ndef S(x):\n ps = 0.75*np.exp(-np.abs(x-0.25))\n return ps/np.sum(ps)\n\n\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(x, y, label='P_part(x)')\nax.plot(x, S(x), '--', label='S(x)')\nplt.xlabel('x')\nplt.ylabel('Probability')\nplt.title('Stationary PMF of particle position (N=200, BIAS=0.001)')\nplt.grid(True)\nax.legend()\nplt.show()","sub_path":"Homework/hw6/code/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"89428494","text":"import os\nimport yaml\nimport pytest\nimport task_17_2a\nimport sys\nsys.path.append('..')\n\nfrom common_functions import check_function_exists, check_function_params, get_func_params_default_value\n\n\ndef test_function_created():\n check_function_exists(task_17_2a, 'generate_topology_from_cdp')\n\n\ndef test_function_params():\n check_function_params(function=task_17_2a.generate_topology_from_cdp,\n param_count=2,\n param_names=['list_of_files', 'save_to_filename'])\n default_values = get_func_params_default_value(task_17_2a.generate_topology_from_cdp)\n assert default_values.get('save_to_filename') == None, \"У параметра save_to_filename значение по умолчанию должно быть None\"\n\n\ndef test_function_return_value(list_of_cdp_files, sh_cdp_topology_dicts):\n correct_return_value = sh_cdp_topology_dicts\n\n return_value = task_17_2a.generate_topology_from_cdp(list_of_cdp_files)\n assert return_value != None, \"Функция ничего не возвращает\"\n assert type(return_value) == dict, \"Функция должна возвращать словарь\"\n assert return_value == correct_return_value, \"Функция возвращает неправильное значение\"\n\n\ndef test_writing_to_yaml_file(list_of_cdp_files, sh_cdp_topology_dicts, tmpdir):\n dest_filename = tmpdir.mkdir(\"test_tasks\").join(\"topology.yaml\")\n return_value = task_17_2a.generate_topology_from_cdp(list_of_cdp_files,\n save_to_filename=dest_filename)\n assert os.path.exists(dest_filename), \"YAML файл не создан\"\n with open(dest_filename) as f:\n yaml_file_content = yaml.load(f)\n assert yaml_file_content == sh_cdp_topology_dicts, \"Топология не записана в YAML файл\"\n\n","sub_path":"exercises/17_serialization/tests/test_task_17_2a.py","file_name":"test_task_17_2a.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"1549877","text":"from misc.callback import callback\nfrom generic.switcher import Switcher\n\n\nclass CallbackTest():\n\n class TestClassEmit():\n\n @callback\n def emit_func(self):\n return self.emit_func.emit()\n\n\n @callback\n def emit_self_func(self):\n self.emit_self_func.emit(self)\n\n \n @callback\n def emit_data_func(self, data):\n return self.emit_data_func.emit(data)\n\n\n @callback\n def emit_self_data_func(self, data):\n self.emit_self_data_func.emit(self, data)\n\n\n class TestClassRead():\n\n def __init__(self, data=None):\n self.data = data\n #print('__init__')\n pass\n\n\n def __del__(self):\n #print('__del__')\n pass\n\n\n def return_self_data_func(self):\n return self.data\n\n\n def return_func(self, data):\n return data\n\n\n def return_func_self_data(self, data):\n return self.data, data\n\n\n\n @staticmethod\n def run_tests():\n CallbackTest.instance_connect_disconnect_test()\n CallbackTest.multi_instance_connect_disconnect_test()\n CallbackTest.static_connect_disconnect_test()\n CallbackTest.interconnect_self_ref_test()\n CallbackTest.multi_instance_emit_test()\n CallbackTest.instance_to_instance_callback()\n\n\n @staticmethod\n def instance_connect_disconnect_test():\n print('instance_connect_disconnect_test')\n\n emit = CallbackTest.TestClassEmit()\n read = CallbackTest.TestClassRead()\n\n emit.emit_data_func.connect(read.return_func)\n \n emit.emit_data_func('test_123')\n data = emit.emit_data_func.ret(read.return_func)\n assert data == 'test_123', 'Data is not what expected; Expected: %s, Result: %s' % ('test_123', str(data))\n\n emit.emit_data_func.disconnect(read.return_func)\n\n emit.emit_data_func('test_123')\n data = emit.emit_data_func.ret(read.return_func)\n assert data == None, 'Data is not what expected; Expected: %s, Result: %s' % (str(None), str(data))\n\n\n @staticmethod\n def multi_instance_connect_disconnect_test():\n print('multi_instance_connect_disconnect_test')\n\n read1_data = 'testinst1'\n read2_data = 'testinst2'\n\n emit = CallbackTest.TestClassEmit()\n read1 = CallbackTest.TestClassRead(read1_data)\n read2 = CallbackTest.TestClassRead(read2_data)\n\n emit.emit_func.connect(read1.return_self_data_func)\n emit.emit_func.connect(read2.return_self_data_func)\n \n emit.emit_func()\n data = emit.emit_func.ret(read1.return_self_data_func)\n assert data == read1_data, 'Data is not what expected; Expected: %s, Result: %s' % (read1_data, str(data))\n data = emit.emit_func.ret(read2.return_self_data_func)\n assert data == read2_data, 'Data is not what expected; Expected: %s, Result: %s' % (read2_data, str(data))\n\n emit.emit_func.disconnect(read1.return_self_data_func)\n\n emit.emit_func()\n data = emit.emit_func.ret(read1.return_self_data_func)\n assert data == None, 'Data is not what expected; Expected: %s, Result: %s' % (str(None), str(data))\n data = emit.emit_func.ret(read2.return_self_data_func)\n assert data == read2_data, 'Data is not what expected; Expected: %s, Result: %s' % (read2_data, str(data))\n\n emit.emit_func.connect(read1.return_self_data_func)\n emit.emit_func.disconnect(read2.return_self_data_func)\n\n emit.emit_func()\n data = emit.emit_func.ret(read1.return_self_data_func)\n assert data == read1_data, 'Data is not what expected; Expected: %s, Result: %s' % (read1_data, str(data))\n data = emit.emit_func.ret(read2.return_self_data_func)\n assert data == None, 'Data is not what expected; Expected: %s, Result: %s' % (str(None), str(data))\n\n emit.emit_func.disconnect(read1.return_self_data_func)\n emit.emit_func.disconnect(read2.return_self_data_func)\n\n emit.emit_func()\n data = emit.emit_func.ret(read1.return_self_data_func)\n assert data == None, 'Data is not what expected; Expected: %s, Result: %s' % (str(None), str(data))\n data = emit.emit_func.ret(read2.return_self_data_func)\n assert data == None, 'Data is not what expected; Expected: %s, Result: %s' % (str(None), str(data))\n\n\n @staticmethod\n def static_connect_disconnect_test():\n print('static_connect_disconnect_test')\n\n emit = CallbackTest.TestClassEmit()\n emit.emit_self_data_func.connect(CallbackTest.TestClassRead.return_func)\n \n emit.emit_self_data_func('test_123')\n data = emit.emit_self_data_func.ret(CallbackTest.TestClassRead.return_func)\n assert data == 'test_123', 'Data is not what expected; Expected: %s, Result: %s' % ('test_123', str(data))\n\n emit.emit_self_data_func.disconnect(CallbackTest.TestClassRead.return_func)\n\n emit.emit_self_data_func('test_123')\n data = emit.emit_self_data_func.ret(CallbackTest.TestClassRead.return_func)\n assert data == None, 'Data is not what expected; Expected: %s, Result: %s' % (str(None), str(data))\n\n\n @staticmethod\n def interconnect_self_ref_test():\n print('interconnect_test')\n\n emit1 = CallbackTest.TestClassEmit()\n emit2 = CallbackTest.TestClassEmit()\n \n emit1.emit_func.connect(emit2.emit_func)\n emit2.emit_func.connect(emit1.emit_func)\n \n emit1.emit_func()\n emit2.emit_func()\n\n emit1.emit_func.disconnect(emit2.emit_func)\n emit2.emit_func.disconnect(emit1.emit_func)\n\n\n @staticmethod\n def multi_instance_emit_test():\n '''\n This tests and demonstrates that functions that are being connected to other functions\n apply to all instances of the function's class\n '''\n print('multi_instance_emit_test')\n\n read1_data = 'testinst1'\n read2_data = 'testinst2'\n\n emit1 = CallbackTest.TestClassEmit()\n emit2 = CallbackTest.TestClassEmit()\n\n read1 = CallbackTest.TestClassRead(read1_data)\n read2 = CallbackTest.TestClassRead(read2_data)\n \n # Connect emit1 -> read1 and emit2 -> read2\n emit1.emit_func.connect(read1.return_self_data_func)\n emit2.emit_func.connect(read2.return_self_data_func)\n \n # Emit only emit1\n emit1.emit_func()\n\n # This is expected\n data = emit1.emit_func.ret(read1.return_self_data_func)\n assert data == read1_data, 'Data is not what expected; Expected: %s, Result: %s' % (str(read1_data), str(data))\n\n # Even though emit2 did not emit, and we are getting data only from emit1, there should be data from read2 in there\n data = emit1.emit_func.ret(read2.return_self_data_func)\n assert data == read2_data, 'Data is not what expected; Expected: %s, Result: %s' % (str(read2_data), str(data))\n\n # Let's attempt to disconnect both on the emit1 side\n emit1.emit_func.disconnect(read1.return_self_data_func)\n emit1.emit_func.disconnect(read2.return_self_data_func)\n\n # Now lets emit from emit2\n emit2.emit_func()\n\n # Data should be None\n data = emit2.emit_func.ret(read2.return_self_data_func)\n assert data == None, 'Data is not what expected; Expected: %s, Result: %s' % (str(None), str(data))\n\n # Ergo, it does not matter from which instance being used to connect or disconnect from\n # It behaves as static. In fact, it would make more sense to do:\n # CallbackTest.TestClassEmit.connect(read1.return_self_data_func)\n # Instead of using instances\n\n\n @staticmethod\n def instance_to_instance_callback():\n '''\n In this tests a 2 switchers are set up to switch between two elements\n Each element contains a string which indicates which reader instance the\n switcher is meant to be connect to. This test is successful if the \n switchers only invoke the reader they are meant to be connected to. \n Since the callbacks are connected from a static instance by default, this \n tests the ability to connect from an instatiated instance.\n '''\n switcher_1 = Switcher()\n switcher_2 = Switcher()\n\n reader_1 = CallbackTest.TestClassRead('reader_1')\n reader_2 = CallbackTest.TestClassRead('reader_2')\n\n switcher_1.switch.connect(lambda old, new: reader_1.return_func_self_data(new), inst=switcher_1)\n switcher_2.switch.connect(lambda old, new: reader_2.return_func_self_data(new), inst=switcher_2)\n\n switcher_1.add('elem1', 'to_reader_1')\n switcher_2.add('elem2', 'to_reader_2')\n\n switcher_1.switch('elem1')\n \n data = switcher_1.switch.returns\n assert len(data) == 1, 'Data is not what expected; Expected: %s, Result: %s' % ('Size: 1', 'Size: ' + str(len(data)))\n\n data = list(data.values())[0]\n assert data[0] == 'reader_1', 'Data is not what expected; Expected: %s, Result: %s' % (str('reader_1'), str(data[0]))\n assert data[1] == 'to_reader_1', 'Data is not what expected; Expected: %s, Result: %s' % (str('to_reader_1'), str(data[1]))\n\n switcher_2.switch('elem2')\n \n data = switcher_2.switch.returns\n assert len(data) == 1, 'Data is not what expected; Expected: %s, Result: %s' % ('Size: 1', 'Size: ' + str(len(data)))\n\n data = list(data.values())[0]\n assert data[0] == 'reader_2', 'Data is not what expected; Expected: %s, Result: %s' % (str('reader_2'), str(data[0]))\n assert data[1] == 'to_reader_2', 'Data is not what expected; Expected: %s, Result: %s' % (str('to_reader_2'), str(data[1]))\n","sub_path":"unit_tests/callback_test.py","file_name":"callback_test.py","file_ext":"py","file_size_in_byte":9804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"20947513","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Codec:\n\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n \"\"\"\n if not root: return \"\"\n q = [root]\n res = []\n while q:\n cur = q.pop(0)\n if cur!=None:\n res += str(cur.val),\n q += cur.left,\n q += cur.right,\n else:\n res += \"n\",\n while res and res[-1] == \"n\":\n res.pop()\n return \",\".join(res)\n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n \"\"\"\n if data == \"\": return None\n values = data.split(\",\")\n if not values: return None\n root = TreeNode(int(values.pop(0)))\n is_left = True\n parents = [root]\n for v in values:\n cur = None\n if v != \"n\":\n cur = TreeNode(int(v))\n parents += cur,\n if is_left:\n parents[0].left = cur\n is_left = False\n else:\n parents[0].right = cur\n is_left = True\n parents.pop(0)\n return root\n \n \n \n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))","sub_path":"python/leetcode/tree/297_Serialize_and_Deserialize_Binary_Tree.py","file_name":"297_Serialize_and_Deserialize_Binary_Tree.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"545732156","text":"class base:\n \"\"\"\n Member methods perform base conversion for us.\n \"\"\"\n \n \n BASE2 = \"01\"\n BASE10 = \"0123456789\"\n BASE16 = \"0123456789ABCDEF\"\n BASE58 = \"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\"\n BASE62 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz\"\n \n @staticmethod\n def convert(number,fromdigits,todigits):\n \"\"\" \n Converts a \"number\" between two bases of arbitrary digits\n \n The input number is assumed to be a string of digits from the\n fromdigits string (which is in order of smallest to largest\n digit). The return value is a string of elements from todigits\n (ordered in the same way). The input and output bases are\n determined from the lengths of the digit strings. Negative\n signs are passed through.\n \n This is modified source from http://pastebin.com/f54dd69d6#\n \n decimal to binary\n >>> baseconvert(555,BASE10,BASE2)\n '1000101011'\n \n binary to decimal\n >>> convert('1000101011',BASE2,BASE10)\n '555'\n \n \"\"\"\n \n if str(number)[0]=='-':\n number = str(number)[1:]\n neg=1\n else:\n neg=0\n \n # make an integer out of the number\n x=0\n for digit in str(number):\n x = x*len(fromdigits) + fromdigits.index(digit)\n \n # create the result in base 'len(todigits)'\n if x == 0:\n res = todigits[0]\n else:\n res=\"\"\n while x>0:\n digit = x % len(todigits)\n res = todigits[digit] + res\n x = int(x / len(todigits))\n if neg:\n res = \"-\"+res\n \n return res\n\n \nclass favicon:\n \n def get_favicon(target_url, parsed_html, link_guid, disk_path, url_details):\n \"\"\" Given a URL and the markup, see if we can find a favicon.\n TODO: this is a rough draft. cleanup and move to an appropriate place. \"\"\"\n\n # We already have the parsed HTML, let's see if there is a favicon in the META elements\n favicons = parsed_html.xpath('//link[@rel=\"icon\"]/@href')\n\n favicon = False\n\n if len(favicons) > 0:\n favicon = favicons[0]\n\n if not favicon:\n favicons = parsed_html.xpath('//link[@rel=\"shortcut\"]/@href')\n if len(favicons) > 0:\n favicon = favicons[0]\n\n if not favicon:\n favicons = parsed_html.xpath('//link[@rel=\"shortcut icon\"]/@href')\n if len(favicons) > 0:\n favicon = favicons[0]\n\n if favicon:\n\n if re.match(r'^//', favicon):\n favicon = url_details.scheme + ':' + favicon\n elif not re.match(r'^http', favicon):\n favicon = url_details.scheme + '://' + url_details.netloc + '/' + favicon\n\n try:\n f = urllib2.urlopen(favicon)\n data = f.read()\n\n with open(disk_path + 'fav.png', \"wb\") as asset:\n asset.write(data)\n\n return 'fav.png'\n except urllib2.HTTPError:\n pass\n\n # If we haven't returned True above, we didn't find a favicon in the markup.\n # let's try the favicon convention: http://example.com/favicon.ico\n target_favicon_url = url_details.scheme + '://' + url_details.netloc + '/favicon.ico'\n\n try:\n f = urllib2.urlopen(target_favicon_url)\n data = f.read()\n with open(disk_path + 'fav.ico' , \"wb\") as asset:\n asset.write(data)\n\n return 'fav' + '.ico'\n except urllib2.HTTPError:\n pass\n\n\n return False","sub_path":"perma_web/perma/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"106225930","text":"from hfqPaNet import hfqRequest\nfrom bs4 import BeautifulSoup\nimport os\n\n\nclass mzitu():\n\n def all_url(self, url):\n html = hfqRequest.get(url, 3)\n all_a = BeautifulSoup(html.text, 'lxml').find('div', class_='all').find_all('a')\n for a in all_a:\n title = a.get_text()\n print(u'开始保存:', title)\n path = str(title).replace(\"?\", '_')\n self.mkdir(\"/Users/liuyuhao/meizitu\", path)\n os.chdir(\"D:/Users/liuyuhao/meizitu/\" + path)\n href = a['href']\n self.html(href)\n\n def html(self, href):\n html = hfqRequest.get(href, 3)\n max_span = BeautifulSoup(html.text, 'lxml').find_all('span')[10].get_text()\n for page in range(1, int(max_span) + 1):\n page_url = href + '/' + str(page)\n self.img(page_url)\n\n def img(self, page_url):\n img_html = hfqRequest.get(page_url, 3)\n img_url = BeautifulSoup(img_html.text, 'lxml').find('div', class_='main-image').find('img')['src']\n self.save(img_url)\n\n def save(self, img_url):\n name = img_url[-9:-4]\n print(u'开始保存:', img_url)\n img = hfqRequest.get(img_url, 3)\n f = open(name + '.jpg', 'ab')\n f.write(img.content)\n f.close()\n\n def mkdir(self, dirpath, filename):\n filename = filename.strip()\n nowpath = os.filename.join(dirpath, filename)\n isExists = os.filename.exists(nowpath)\n if not isExists:\n print(u'在', nowpath, '建了一个名字叫做', filename, u'的文件夹!')\n os.makedirs(nowpath)\n return True\n else:\n print(u'名字叫做', filename, u'的文件夹已经存在了!')\n return False\n\n\nMzitu = mzitu() ##实例化\nMzitu.all_url('http://www.mzitu.com/all') ##给函数all_url传入参数 你可以当作启动爬虫(就是入口)","sub_path":"paMeizi.py","file_name":"paMeizi.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"433142502","text":"# Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\nimport ctypes\nimport logging.config\nimport os\nimport random\nimport subprocess\nimport sys\nimport time\nfrom contextlib import contextmanager\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.nn.init as init\nimport torch.utils.collect_env\nfrom mlperf_logging.mllog import constants\nfrom mlperf_logging import mllog\n\n\nmllogger = mllog.get_mllogger()\n\ndef log_start(*args, **kwargs):\n _log_print(mllogger.start, *args, **kwargs)\ndef log_end(*args, **kwargs):\n _log_print(mllogger.end, *args, **kwargs)\ndef log_event(*args, **kwargs):\n _log_print(mllogger.event, *args, **kwargs)\ndef _log_print(logger, *args, **kwargs):\n \"\"\"\n Wrapper for MLPerf compliance logging calls.\n All arguments but 'sync' and 'log_all_ranks' are passed to\n mlperf_logging.mllog.\n If 'sync' is set to True then the wrapper will synchronize all distributed\n workers. 'sync' should be set to True for all compliance tags that require\n accurate timing (RUN_START, RUN_STOP etc.)\n If 'log_all_ranks' is set to True then all distributed workers will print\n logging message, if set to False then only worker with rank=0 will print\n the message.\n \"\"\"\n if kwargs.pop('sync', False):\n barrier()\n if 'stack_offset' not in kwargs:\n kwargs['stack_offset'] = 3\n if 'value' not in kwargs:\n kwargs['value'] = None\n\n if kwargs.pop('log_all_ranks', False):\n log = True\n else:\n log = (get_rank() == 0)\n\n if log:\n logger(*args, **kwargs)\n\n\ndef mlperf_submission_log(benchmark):\n required_dist_init = ['RANK', 'WORLD_SIZE', 'MASTER_ADDR', 'MASTER_PORT']\n\n if all(var in os.environ for var in required_dist_init):\n torch.distributed.init_process_group(backend='nccl', init_method='env://')\n\n num_nodes = os.environ.get('SLURM_NNODES', 1)\n\n mllog.config(filename=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'transformer.log'))\n mllogger = mllog.get_mllogger()\n mllogger.logger.propagate = False\n\n log_event(\n key=constants.SUBMISSION_BENCHMARK,\n value=benchmark,\n )\n\n log_event(\n key=constants.SUBMISSION_ORG,\n value='Dell EMC')\n\n log_event(\n key=constants.SUBMISSION_DIVISION,\n value='closed')\n\n log_event(\n key=constants.SUBMISSION_STATUS,\n value='onprem')\n\n log_event(\n key=constants.SUBMISSION_PLATFORM,\n value=f'{num_nodes}xSUBMISSION_PLATFORM_PLACEHOLDER')\n\ndef barrier():\n \"\"\"\n Works as a temporary distributed barrier, currently pytorch\n doesn't implement barrier for NCCL backend.\n Calls all_reduce on dummy tensor and synchronizes with GPU.\n \"\"\"\n if torch.distributed.is_available() and torch.distributed.is_initialized():\n torch.distributed.all_reduce(torch.cuda.FloatTensor(1))\n torch.cuda.synchronize()\n\n\ndef get_rank():\n \"\"\"\n Gets distributed rank or returns zero if distributed is not initialized.\n \"\"\"\n if torch.distributed.is_available() and torch.distributed.is_initialized():\n rank = torch.distributed.get_rank()\n else:\n rank = 0\n return rank\n\n","sub_path":"DellEMC/benchmarks/transformer/implementation/pytorch/mlperf_log_utils.py","file_name":"mlperf_log_utils.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"196884247","text":"\"\"\"\n Goods are defined by :\n Generic Information\n - Their type (Immovable, Capital, Service, Consumption, Resource)\n - Their Name (the good itself)\n - The value paid to acquire them (second hand) or computed (production)\n\"\"\"\n\nimport logging\nfrom collections import namedtuple\n\nimport attr\n\n\nlog = logging.getLogger(__name__)\n\n# Definition of all the resources types. Will be fed as init arguments to the ResourceType class\nresource_type_data = {\n 'Food':\n {'res_type': 'FinalGood',\n 'need': (1.5, 2.0, 2.5, 3.0, 1.0),\n 'stats': (6.0, 4.0, 2.0, 1.0, ['Cropland', 1], 0)},\n 'Water':\n {'res_type': 'FinalGood',\n 'need': (1.75, 2.0, 2.25, 4.0, 1.0),\n 'stats': (12.0, 9.0, 1.0, 1.0, ['Freshwater', 1], 0)},\n 'Cons. Goods':\n {'res_type': 'FinalGood',\n 'need': (0.5, 1.5, 3.0, 2.0, 0.75),\n 'stats': (5.0, 5.0, 2.5, 1.5, ['Metal', .02], 0)},\n 'Cons. Durables':\n {'res_type': 'FinalGood',\n 'need': (0.5, 1.5, 2.5, 2.0, 0.25),\n 'stats': (4.0, 6.0, 3.0, 1.5, ['Hydrocarbons', .08], 0)},\n 'Infrastructure':\n {'res_type': 'FinalGood',\n 'need': (0.5, 1.5, 2.5, 2.0, 0.25),\n 'stats': (4.0, 6.0, 3.0, 1.5, ['Metal', .05], 1)},\n 'Healthcare':\n {'res_type': 'FinalGood',\n 'need': (0.7, 1.0, 1.5, 1.8, 0.85),\n 'stats': (6.0, 1.2, 3.0, 2.2, [None, 0], 0)},\n 'Tourism':\n {'res_type': 'FinalGood',\n 'need': (0.25, 1.0, 2.0, 1.5, 1.0),\n 'stats': (6.0, 1.2, 3.0, 1.8, [None, 0], 0)},\n 'Services':\n {'res_type': 'FinalGood',\n 'need': (0.25, 0.5, 1.0, 1.5, 1.0),\n 'stats': (6.0, 1.2, 3.0, 1.8, [None, 0], 0)},\n 'Transportation':\n {'res_type': 'FinalGood',\n 'need': (0.5, 1.0, 2.0, 1.5, 1.0),\n 'stats': (4.0, 8.0, 1.0, 1.5, ['Metal', .06], 1)},\n 'Orbital Construction':\n {'res_type': 'FinalGood',\n 'need': (0.0, 0.1, 0.5, 0.7, 0.1),\n 'stats': (1.0, 8.0, 1.0, 2.0, ['Metal', .08], 2)},\n 'Luxury':\n {'res_type': 'FinalGood',\n 'need': (0.1, 0.5, 6.0, 0.7, 0.35),\n 'stats': (3.0, 1.5, 3.0, 2.5, [None, 0], 0)},\n 'Light Machinery':\n {'res_type': 'CapitalGood',\n 'stats': (3.0, 2.0, 1.0, 1.0, ['Metal', .04], 0)},\n 'Heavy Machinery':\n {'res_type': 'CapitalGood',\n 'stats': (3.0, 2.0, 1.0, 1.0, ['Metal', .04], 0)},\n 'Space Industry':\n {'res_type': 'CapitalGood',\n 'stats': (1.0, 6.0, 1.0, 2.5, ['Metal', .16], 0)},\n 'Metal':\n {'res_type': 'Finite'},\n 'Hydrocarbons':\n {'res_type': 'Finite'},\n 'Cropland':\n {'res_type': 'Renewable'},\n 'Freshwater':\n {'res_type': 'Renewable'},\n\n}\n\n\ndef existing_good(instance, attribute, value):\n if value not in resource_type_data.keys():\n raise ValueError(\"%s is not a proper good\", value)\n\nRES_TYPE = ('Renewable', 'Finite', 'CapitalGood', 'FinalGood')\n\ndef existing_type(instance, attribute, value):\n if value not in RES_TYPE:\n raise ValueError('%s is not a proper resource type', value)\n\n\n# # Need levels. How many units of good are necessary to get a given level of satisfaction\n# 0-Min, 1-Need, 2-Max, 3-Necessity\n# 4 - Consumption Rate [% of Need]\nntGoodsNeeds = namedtuple('GoodsNeeds', 'min need max necessity rate')\n# Final Goods Statistics\n# 0- Base Prod/Emp, 1-K efficiency (multiplies the base prod per employee),\n# 2- Maximum Employee for one unit of K, 3-Base Salary\n# 4- List with Resource needed (0) and the quantity needed (1)\n# 5- Type of capital goods\nntGoodsStats = namedtuple('GoodsStats', 'baseprod k_eff max_employee_per_k salary resource_need capital_type')\n\n\n@attr.s(slots=True)\nclass ResourceType(object):\n \"\"\"\n Describes a resource type. Only one instance needed by resource type.\n Like a configuration of the resource.\n Actual data should be in dict or files\n \"\"\"\n name = attr.ib(validator=existing_good, convert=str)\n res_type = attr.ib(validator=existing_type, convert=str)\n\n need = attr.ib(default=None)\n stats = attr.ib(default=None)\n\n def __attrs_post_init__(self):\n if not self.need and self.res_type == 'FinalGood':\n raise ValueError('res_type FinalGood require a need tuple')\n\n if self.res_type == 'FinalGood':\n self.need = ntGoodsNeeds(*self.need)\n\n if not self.stats and self.res_type in ('FinalGood', 'CapitalGood'):\n raise ValueError('res_type CapitalGood require a need tuple')\n\n if self.res_type in ('FinalGood', 'CapitalGood'):\n self.stats = ntGoodsStats(*self.stats)\n\n @property\n def is_finite(self):\n if self.res_type == 'Finite':\n return True\n\n return False\n\n @property\n def is_final_good(self):\n if self.res_type == 'FinalGood':\n return True\n\n return False\n\n @property\n def is_renewable(self):\n if self.res_type == 'Renewable':\n return True\n\n return False\n\n @property\n def is_good(self):\n if self.res_type in ('FinalGood', 'CapitalGood', 'Finite'):\n return True\n\n return False\n\n @property\n def is_resource(self):\n if self.res_type in ('Renewable', 'Finite'):\n return True\n\n return False\n\n @property\n def resource_need(self):\n return self.stats.resource_need[0]\n\n# Global variable that will hold one instance ResourceType. Used as a standard source of information on each resource.\nRESOURCE_TYPES = {}\nfor name, data in resource_type_data.items():\n data['name'] = name\n RESOURCE_TYPES[name] = ResourceType(**data)\n\n\ndef get_good_type(good):\n if good in RESOURCE_TYPES:\n return RESOURCE_TYPES[good]\n\n raise ValueError('{} : unknown good (get_good_type)'.format(good))\n\n\n@attr.s(slots=True)\nclass Good(object):\n \"\"\"\n Represent a Good belonging to a single entity\n Created with a good name, a value, and a quantity.\n ex: Good('Food', value=20, qty=3)\n\n In most circumstances, goods should only be created by producers.\n Purchasers should acquire existing instances of Goods through the market.\n \"\"\"\n name = attr.ib(validator=existing_good, convert=str)\n total_value = attr.ib(validator=attr.validators.instance_of(float), convert=float)\n qty = attr.ib(validator=attr.validators.instance_of(float), convert=float)\n\n _good_type = attr.ib(default=None, init=False)\n _ppu = attr.ib(default=0., init=False)\n\n @property\n def good_type(self):\n if not self._good_type:\n self._good_type = get_good_type(self.name)\n\n return self._good_type\n\n @property\n def ppu(self):\n \"\"\"\n Price per unit of this good\n :return: float. price per unit\n \"\"\"\n if self.qty > 0:\n self._ppu = self.total_value / self.qty\n else:\n self._ppu = 0.\n\n return self._ppu\n\n def _reduce_qty_and_value(self, qty: float):\n \"\"\"\n Recomputes total value based on a qty. No checks done.\n\n :param qty: float: qty that has been removed\n :return:\n \"\"\"\n expense = self.ppu * qty\n self.total_value -= expense\n self.qty -= qty\n return expense\n\n def get_one(self):\n \"\"\"\n Take one unit quantity from this good. creates new good out of it.\n\n :return: New good instance or None\n \"\"\"\n if self.qty >= 1:\n self._reduce_qty_and_value(qty=1)\n return Good(self.name, self.ppu, 1)\n else:\n log.critical('Can not get one if qty is below one ')\n return None\n\n def consume(self, *, qty: float):\n \"\"\" Consumes a certain qty of a good. Value is decreased proportionally\n\n :param qty: float. Quantity to be consumed\n :return: tuple( float: quantity consumed, float: value of that quantity)\n \"\"\"\n if qty <= self.qty:\n qty_consumed = qty\n else:\n qty_consumed = self.qty\n\n expense = self._reduce_qty_and_value(qty=qty_consumed)\n\n return qty_consumed, expense\n\n def __add__(self, other: object):\n \"\"\" Adds two goods instances. Returns a new instance\n \"\"\"\n if self.name == other.name:\n price = self.total_value + other.total_value\n qty = self.qty + other.qty\n return Good(self.name, price, qty)\n else:\n raise ValueError('Can\\'t add those goods ({} and {})'.format(self.name, other.name))\n\n","sub_path":"secomodel/ecoactors/goods.py","file_name":"goods.py","file_ext":"py","file_size_in_byte":8567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"338350921","text":"\"\"\"\nGet the bounding rectangle and the pathology of every abnormality of every\nmammogram and save the data in a JSON file.\n\"\"\"\n\nimport json\nimport os\nimport sys\nfrom collections import namedtuple\n\nimport cv2\nimport pandas as pd\nimport pydicom\n\ntry:\n from tqdm import tqdm\nexcept ImportError:\n tqdm = lambda iterable, *args, **kwargs: iter(iterable)\n\nimport conf\n\n\nRect = namedtuple('Rect', ('x', 'y', 'w', 'h'))\nRect.area = lambda rect: rect.w * rect.h\n\n\ndef get_bounding_rect(mask_path):\n mask = pydicom.dcmread(mask_path).pixel_array\n # The mask has a depth of 16 bit. We convert it to 8 bits so OpenCV can\n # work with it:\n mask = (mask // 255).astype('uint8')\n contours, hierarchy = cv2.findContours(\n mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n rects = (Rect(*cv2.boundingRect(contour)) for contour in contours)\n return max(rects, key=Rect.area)\n\n\ndef get_abnormalities():\n descriptions = pd.read_csv(conf.DESCRIPTIONS_PATH)\n colnames = {'image file path': 'im_path', 'ROI mask file path': 'mask_path'}\n grouped = (descriptions.rename(columns=colnames)\n .loc[:, ('im_path', 'mask_path', 'pathology')]\n .groupby('im_path', sort=False))\n return {\n im_path: [\n {\n 'bounding_rect': get_bounding_rect(abnormality.mask_path),\n 'pathology': abnormality.pathology\n } for abnormality in im_abnormalities.itertuples()\n ] for im_path, im_abnormalities in tqdm(grouped)\n }\n\n\ndef show_abnormalities(im, im_abnormalities):\n color = int(im.max())\n thickness = max(im.shape) // 200\n fontScale = 5\n for abnormality in im_abnormalities:\n x, y, w, h = abnormality['bounding_rect']\n cv2.rectangle(im, (x, y), (x + w, y + h), color, thickness)\n cv2.putText(im, abnormality['pathology'], (x, y - 2 * thickness),\n cv2.FONT_HERSHEY_SIMPLEX, fontScale, color, thickness)\n import matplotlib.pyplot as plt\n plt.imshow(im, cmap='gray')\n plt.show()\n\n\ndef read_im_and_abnormalities(im_path):\n root, ext = os.path.splitext(im_path)\n if ext == '.dcm':\n im = pydicom.dcmread(im_path).pixel_array\n abnormalities_path = conf.ABNORMALITIES_PATH\n else:\n im = cv2.imread(im_path)\n abnormalities_path = conf.AUGMENTED_DB_PATH\n with open(abnormalities_path) as f:\n abnormalities = json.load(f)\n return im, abnormalities[im_path]\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2: # usage: get_abnormalities.py IM_PATH\n im, abnormalities = read_im_and_abnormalities(im_path=sys.argv[1])\n show_abnormalities(im, abnormalities)\n else:\n abnormalities = get_abnormalities()\n with open(conf.ABNORMALITIES_PATH, 'w') as f:\n json.dump(abnormalities, f, indent=4)\n","sub_path":"get_abnormalities.py","file_name":"get_abnormalities.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"650470821","text":"import json\nimport numpy as np\nimport scipy.stats\n\nfrom functools import partial, update_wrapper\n\nfrom keras import backend as K\nfrom keras.layers import Input, Dense, Lambda, Reshape, concatenate\nfrom keras.models import Model\nfrom keras.losses import binary_crossentropy, categorical_crossentropy\nfrom keras.losses import mean_squared_error\n\n# from ..utils.midi_utils import write_sample\n\ntry:\n # Python 2 \n range \nexcept: \n # Python 3\n def range(tmp): return iter(range(tmp))\n\n'''HERE WHERE I STARTED'''\ndef wrapped_partial(func, *args, **kwargs):\n ''' from: http://louistiao.me/posts/\n adding-__name__-and-__doc__-attributes-to-functoolspartial-objects/\n '''\n partial_func = partial(func, *args, **kwargs)\n update_wrapper(partial_func, func)\n return partial_func\n\ndef build_hidden_layers(hidden_dims, input_layer, layer_name, activation,\n Layer = Dense):\n '''Need to remove all leading zeros for the Decoder \n to be properly established'''\n\n hidden_dims = list(hidden_dims)\n while 0 in hidden_dims: hidden_dims.remove(0)\n \n # Establish hidden layer structure\n for k, layer_size in enumerate(hidden_dims):\n name = '{}{}'.format(layer_name, k)\n '''If this is the 1st hidden layer, then input as input_w_pred;\n else, input the previous hidden_layer'''\n input_now = input_layer if k is 0 else hidden_layer\n\n hidden_layer = Layer(layer_size, activation = activation, name = name)\n hidden_layer = hidden_layer(input_now)\n \n return hidden_layer\n\nclass VAEPredictor(object):\n def __init__(self, original_dim, vae_hidden_dims, dnn_hidden_dims, \n vae_latent_dim, dnn_out_dim = None, \n dnn_latent_dim = None, batch_size = 128, \n dnn_log_var_prior = 0.0, optimizer = 'adam-wn', \n use_prev_input = False, dnn_type = 'classification'):\n \n self.predictor_type = predictor_type\n self.original_dim = original_dim\n \n self.vae_hidden_dims = vae_hidden_dims\n self.vae_latent_dim = vae_latent_dim\n\n self.dnn_hidden_dims = dnn_hidden_dims\n self.dnn_out_dim = dnn_out_dim\n \n \"\"\"FINDME: Why is this dnn_out_dim-1(??)\"\"\"\n if dnn_latent_dim is not None:\n self.dnn_latent_dim = self.dnn_out_dim - 1\n\n self.dnn_log_var_prior = dnn_log_var_prior\n self.optimizer = optimizer\n self.batch_size = batch_size\n self.use_prev_input = use_prev_input\n \n def build_predictor(self):\n if bool(sum(self.dnn_hidden_dims)):\n ''' Establish VAE Encoder layer structure '''\n dnn_hidden_layer = build_hidden_layers(\n self.dnn_hidden_dims, \n self.input_layer, \n layer_name='predictor_hidden_layer', \n activation=self.hidden_activation)\n else:\n '''if there are no hidden layers, then the input to the \n dnn latent layers is the input_layer'''\n dnn_hidden_layer = self.input_layer\n \n # Process the predictor layer through a latent layer\n dnn_latent_mean = Dense(self.dnn_latent_dim, \n name = 'predictor_latent_mean')\n self.dnn_latent_mean = dnn_latent_mean(dnn_hidden_layer)\n dnn_latent_log_var = Dense(self.dnn_latent_dim, \n name = 'predictor_latent_log_var')\n \n self.dnn_latent_log_var = dnn_latent_log_var(\n dnn_hidden_layer)\n \n dnn_latent_layer = Lambda(self.dnn_sampling, \n name = 'predictor_latent_layer')\n self.dnn_latent_layer = dnn_latent_layer(\n [self.dnn_latent_mean, self.dnn_latent_log_var])\n \n # Add some wiggle to the dnn predictions \n # to avoid division by zero\n dnn_latent_mod = Lambda(lambda tmp: tmp+1e-10, \n name = 'predictor_latent_mod')\n self.dnn_latent_mod = dnn_latent_mod(self.dnn_latent_layer)\n \n def build_latent_decoder(self):\n if bool(sum(self.vae_hidden_dims)):\n vae_dec_hid_layer = build_hidden_layers(self.vae_hidden_dims[::-1],\n input_layer = self.dnn_w_latent,\n layer_name = 'vae_dec_hidden_layer', \n activation = self.hidden_activation)\n else:\n vae_dec_hid_layer = self.dnn_w_latent\n \n vae_reconstruction = Dense(self.original_dim, \n activation = self.output_activation, \n name = 'vae_reconstruction')\n self.vae_reconstruction = vae_reconstruction(vae_dec_hid_layer)\n\n def bak_build_latent_decoder_1stpass(self):\n if bool(sum(self.vae_hidden_dims)):\n vae_dec_hid_layer = build_hidden_layers(# reverse order for decoder\n self.vae_hidden_dims[::-1],\n self.dnn_w_latent, \n layer_name = 'vae_dec_hidden_layer', \n activation = self.hidden_activation)\n else:\n vae_dec_hid_layer = self.dnn_w_latent\n\n vae_reconstruction = Dense(self.original_dim, \n activation = self.output_activation, \n name = 'vae_reconstruction')\n\n self.vae_reconstruction = vae_reconstruction(vae_dec_hid_layer)\n\n def build_latent_encoder(self):\n if bool(sum(self.vae_hidden_dims)):\n ''' Establish VAE Encoder layer structure '''\n vae_enc_hid_layer = build_hidden_layers(self.vae_hidden_dims, \n self.input_w_pred, \n layer_name='vae_enc_hidden_layer', \n activation=self.hidden_activation)\n else:\n '''if there are no hidden layers, then the input to the \n vae latent layers is the input_w_pred layer'''\n vae_enc_hid_layer = self.input_w_pred\n \n vae_latent_mean = Dense(self.vae_latent_dim,name='vae_latent_mean')\n self.vae_latent_mean = vae_latent_mean(vae_enc_hid_layer)\n \n vae_latent_log_var =Dense(self.vae_latent_dim,\n name = 'vae_latent_log_var')\n self.vae_latent_log_var = vae_latent_log_var(vae_enc_hid_layer)\n \n vae_latent_layer = Lambda(self.vae_sampling, name = 'vae_latent_layer')\n self.vae_latent_layer = vae_latent_layer([self.vae_latent_mean, \n self.vae_latent_log_var])\n\n self.vae_latent_args = concatenate([self.vae_latent_mean, \n self.vae_latent_log_var], \n axis = -1, \n name = 'vae_latent_args')\n \n def dnn_kl_loss(self, labels, preds):\n vs = 1 - self.dnn_log_var_prior + self.dnn_latent_log_var\n vs = vs - K.exp(self.dnn_latent_log_var)/K.exp(self.dnn_log_var_prior)\n vs = vs - K.square(self.dnn_latent_mean)/K.exp(self.dnn_log_var_prior)\n\n return -0.5*K.sum(vs, axis = -1)\n\n def dnn_rec_loss(self, labels, preds):\n if self.predictor_type is 'classification':\n rec_loss = categorical_crossentropy(labels, preds)\n # rec_loss = self.dnn_latent_dim * rec_loss\n if self.predictor_type is 'regression':\n rec_loss = mean_squared_error(labels, preds)\n return rec_loss\n\n def dnn_sampling(self, args):\n ''' sample from a logit-normal with params dnn_latent_mean \n and dnn_latent_log_var\n (n.b. this is very similar to a logistic-normal distribution)\n '''\n batch_shape = (self.batch_size, self.dnn_latent_dim)\n eps = K.random_normal(shape = batch_shape, mean = 0., stddev = 1.0)\n\n gamma_ = K.exp(self.dnn_latent_log_var/2)*eps\n dnn_norm = self.dnn_latent_mean + gamma_\n \n # need to add 0's so we can sum it all to 1\n padding = K.tf.zeros(self.batch_size, 1)[:,None]\n dnn_norm = concatenate([dnn_norm, padding], \n name='dnn_norm')\n sum_exp_dnn_norm = K.sum(K.exp(dnn_norm), axis = -1)[:,None]\n return K.exp(dnn_norm)/sum_exp_dnn_norm\n\n def get_model(self, batch_size = None, original_dim = None, \n vae_hidden_dims = None, vae_latent_dim = None, \n dnn_hidden_dims = None, use_prev_input = False, \n dnn_weight = 1.0, vae_kl_weight = 1.0, \n dnn_kl_weight = 1.0, dnn_log_var_prior = 0.0, \n hidden_activation = 'relu', output_activation = 'sigmoid'):\n \n self.hidden_activation = hidden_activation\n self.output_activation = output_activation\n if dnn_log_var_prior is not None:\n self.dnn_log_var_prior = dnn_log_var_prior\n \n # update new input values from local args\n if batch_size is not None: self.batch_size = batch_size\n if original_dim is not None: self.original_dim = original_dim\n if vae_hidden_dims is not None: self.vae_hidden_dims = vae_hidden_dims\n if vae_latent_dim is not None: self.vae_latent_dim = vae_latent_dim\n\n if dnn_hidden_dims is not None: \n self.dnn_hidden_dims = dnn_hidden_dims\n \n if use_prev_input is not None: self.use_prev_input = use_prev_input\n\n batch_shape = (self.batch_size, self.original_dim)\n # batch_shape = (self.original_dim,)\n self.input_layer = Input(batch_shape = batch_shape, name='input_layer')\n\n if use_prev_input or self.use_prev_input:\n self.prev_input_layer = Input(batch_shape = batch_shape, \n name = 'previous_input_layer')\n self.build_predictor()\n \n self.input_w_pred = concatenate([self.input_layer, \n self.dnn_latent_layer], \n axis = -1,\n name = 'data_input_w_dnn_latent_out')\n\n self.build_latent_encoder()\n \n if use_prev_input or self.use_prev_input:\n self.prev_w_vae_latent = concatenate(\n [self.prev_input_layer, self.vae_latent_layer], \n axis = -1, name = 'prev_inp_w_vae_lat_layer')\n else:\n self.prev_w_vae_latent = self.vae_latent_layer\n \n self.dnn_w_latent = concatenate(\n [self.dnn_latent_layer, self.prev_w_vae_latent],\n axis = -1, name = 'dnn_latent_out_w_prev_w_vae_lat'\n )\n \n self.build_latent_decoder()\n \n if use_prev_input or self.use_prev_input:\n input_stack = [self.input_layer, self.prev_input_layer]\n out_stack = [self.vae_reconstruction, self.dnn_latent_layer, \n self.dnn_latent_mod, self.vae_latent_args]\n enc_stack = [self.vae_latent_mean, self.dnn_latent_mean]\n else:\n input_stack = [self.input_layer]\n out_stack = [self.vae_reconstruction, self.dnn_latent_layer, \n self.dnn_latent_mod, self.vae_latent_args]\n enc_stack = [self.vae_latent_mean, self.dnn_latent_mean]\n\n self.model = Model(input_stack, out_stack)\n self.enc_model = Model(input_stack, enc_stack)\n \n self.model.compile( \n optimizer = self.optimizer,\n\n loss = {'vae_reconstruction': self.vae_loss,\n 'predictor_latent_layer': self.dnn_kl_loss,\n 'predictor_latent_mod': self.dnn_rec_loss,\n 'vae_latent_args': self.vae_kl_loss},\n\n loss_weights = {'vae_reconstruction': 1.0,\n 'predictor_latent_layer': dnn_kl_weight,\n 'predictor_latent_mod':dnn_weight,\n 'vae_latent_args': vae_kl_weight},\n\n # metrics=['acc', 'mse'])\n metrics = {'predictor_latent_layer': ['acc', 'mse']})\n \n def vae_sampling(self, args):\n eps = K.random_normal(shape = (self.batch_size, self.vae_latent_dim), \n mean = 0., stddev = 1.0)\n \n return self.vae_latent_mean + K.exp(self.vae_latent_log_var/2) * eps\n\n def vae_loss(self, input_layer, vae_reconstruction):\n if self.predictor_type is 'binary':\n '''This case is specific to binary input sequences\n i.e. [0,1,1,0,0,0,....,0,1,1,1]'''\n inp_vae_loss = binary_crossentropy(input_layer, vae_reconstruction)\n inp_vae_loss = self.original_dim * inp_vae_loss\n \n if self.predictor_type is 'classification':\n ''' I am left to assume that the vae_reconstruction_loss for a \n non-binary data source (i.e. *not* piano keys) should be \n a regression problem. \n The prediction loss is still categorical crossentropy because \n the features being compared are discrete classes'''\n inp_vae_loss = mean_squared_error(input_layer, vae_reconstruction)\n \n if self.predictor_type is 'regression':\n inp_vae_loss = mean_squared_error(input_layer, vae_reconstruction)\n \n return inp_vae_loss\n\n def vae_kl_loss(self, ztrue, zpred):\n Z_mean = self.vae_latent_args[:,:self.vae_latent_dim]\n Z_log_var = self.vae_latent_args[:,self.vae_latent_dim:]\n k_summer = 1 + Z_log_var - K.square(Z_mean) - K.exp(Z_log_var)\n return -0.5*K.sum(k_summer, axis = -1)\n\n def load_model(self, model_file):\n ''' there's a currently bug in the way keras loads models \n from `.yaml` files that has to do with `Lambda` calls\n ... so this is a hack for now\n '''\n self.get_model()\n self.model.load_weights(model_file)\n\n def make_dnn_predictor(self):\n batch_shape = (self.batch_size, self.original_dim)\n # batch_shape = (self.original_dim,)\n input_layer = Input(batch_shape = batch_shape, name = 'input_layer')\n\n # build label encoder\n enc_hidden_layer = self.model.get_layer('predictor_hidden_layer')\n enc_hidden_layer = enc_hidden_layer(input_layer)\n \n dnn_latent_mean = self.model.get_layer('predictor_latent_mean')\n dnn_latent_mean = dnn_latent_mean(enc_hidden_layer)\n\n dnn_latent_log_var = self.model.get_layer('predictor_latent_log_var')\n dnn_latent_log_var = dnn_latent_log_var(enc_hidden_layer)\n\n return Model(input_layer, [dnn_latent_mean, dnn_latent_log_var])\n\n def make_latent_encoder(self):\n orig_batch_shape = (self.batch_size, self.original_dim)\n predictor_batch_shape = (self.batch_size, self.dnn_out_dim)\n # orig_batch_shape = (self.original_dim,)\n # predictor_batch_shape = (self.predictor_out_dim,)\n\n input_layer = Input(batch_shape = orig_batch_shape, \n name = 'input_layer')\n dnn_input_layer = Input(batch_shape = predictor_batch_shape, \n name = 'predictor_input_layer')\n\n input_w_pred = concatenate([input_layer, dnn_input_layer], \n axis = -1, name = 'input_w_dnn_layer')\n \n # build latent encoder\n if self.vae_hidden_dim > 0:\n vae_enc_hid_layer = self.model.get_layer('vae_enc_hid_layer')\n vae_enc_hid_layer = vae_enc_hid_layer(input_w_pred)\n\n vae_latent_mean = self.model.get_layer('vae_latent_mean')\n vae_latent_mean = vae_latent_mean(vae_enc_hid_layer)\n\n vae_latent_log_var = self.model.get_layer('vae_latent_log_var')\n vae_latent_log_var = vae_latent_log_var(vae_enc_hid_layer)\n else:\n vae_latent_mean = self.model.get_layer('vae_latent_mean')\n vae_latent_mean = vae_latent_mean(input_w_pred)\n vae_latent_log_var= self.model.get_layer('vae_latent_log_var')\n vae_latent_log_var = vae_latent_log_var(input_w_pred)\n \n latent_enc_input = [input_layer, dnn_input_layer]\n latent_enc_output = [vae_latent_mean, vae_latent_log_var]\n\n return Model(latent_enc_input, latent_enc_output)\n\n def make_latent_decoder(self, use_prev_input=False):\n\n input_batch_shape = (self.batch_size, self.original_dim)\n predictor_batch_shape = (self.batch_size, self.dnn_out_dim)\n vae_batch_shape = (self.batch_size, self.vae_latent_dim)\n # input_batch_shape = (self.original_dim,)\n # predictor_batch_shape = (self.dnn_out_dim,)\n # vae_batch_shape = (self.vae_latent_dim,)\n\n dnn_input_layer = Input(batch_shape = predictor_batch_shape, \n name = 'predictor_layer')\n vae_latent_layer = Input(batch_shape = vae_batch_shape, \n name = 'vae_latent_layer')\n\n if use_prev_input or self.use_prev_input:\n prev_input_layer = Input(batch_shape = input_batch_shape, \n name = 'prev_input_layer')\n\n if use_prev_input or self.use_prev_input:\n prev_vae_stack = [prev_input_layer, vae_latent_layer]\n prev_w_vae_latent = concatenate(prev_vae_stack, axis = -1)\n else:\n prev_w_vae_latent = vae_latent_layer\n\n dnn_w_latent = concatenate([dnn_input_layer,prev_w_vae_latent],\n axis = -1)\n\n # build physical decoder\n vae_reconstruction = self.model.get_layer('vae_reconstruction')\n if self.vae_hidden_dim > 0:\n vae_dec_hid_layer = self.model.get_layer('vae_dec_hid_layer')\n vae_dec_hid_layer = vae_dec_hid_layer(dnn_w_latent)\n vae_reconstruction = vae_reconstruction(vae_dec_hid_layer)\n else:\n vae_reconstruction = vae_reconstruction(dnn_w_latent)\n\n if use_prev_input or self.use_prev_input:\n dec_input_stack = [dnn_input_layer, \n vae_latent_layer, \n prev_input_layer]\n else:\n dec_input_stack = [dnn_input_layer, vae_latent_layer]\n\n return Model(dec_input_stack, vae_reconstruction)\n\n def sample_predictor(self, dnn_latent_mean, \n dnn_latent_log_var, \n nsamps=1, nrm_samp=False, \n add_noise=True):\n \n if nsamps == 1:\n eps_shape = dnn_latent_mean.flatten().shape[0]\n eps = np.random.randn(*((1, eps_shape)))\n else:\n eps = np.random.randn(*((nsamps,) + dnn_latent_mean.shape))\n if eps.T.shape == dnn_latent_mean.shape:\n eps = eps.T\n\n gamma_ = np.exp(dnn_latent_log_var/2)\n if add_noise:\n dnn_norm = dnn_latent_mean + gamma_*eps\n else:\n dnn_norm = dnn_latent_mean + 0*gamma_*eps\n\n if nrm_samp: return dnn_norm\n\n if nsamps == 1:\n padding = np.zeros((dnn_norm.shape[0], 1))\n dnn_norm = np.hstack([dnn_norm, padding])\n out = np.exp(dnn_norm)/np.sum(np.exp(dnn_norm),axis=-1)\n return out[:,None]\n else:\n padding = np.zeros(dnn_norm.shape[:-1]+(1,))\n dnn_norm = np.dstack([dnn_norm,padding])\n out = np.exp(dnn_norm)/np.sum(np.exp(dnn_norm),axis=-1)\n return out[:,:,None]\n\n def sample_latent(self, Z_mean, Z_log_var, nsamps = 1):\n if nsamps == 1:\n eps = np.random.randn(*Z_mean.squeeze().shape)\n else:\n eps = np.random.randn(*((nsamps,) + Z_mean.squeeze().shape))\n return Z_mean + np.exp(Z_log_var/2) * eps\n\n def sample_vae(self, dnn_latent_mean):\n rando = np.random.rand(len(dnn_latent_mean.squeeze()))\n\n return np.float32(rando <= dnn_latent_mean)\n","sub_path":"vaelstmpredictor/vae_predictor/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":20434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"410133024","text":"\"\"\"\n======================================================================\nFind largest palindrome, which is product of two prime 5-digit numbers\n======================================================================\n\"\"\"\n\nimport time\nfrom itertools import count, islice\nfrom math import sqrt\n\n\ndef time_it(pattern):\n def decorator(func):\n def wrapper(*args, **kwargs):\n start_time = time.time()\n res = func(*args, **kwargs)\n print(pattern.format(time.time() - start_time))\n return res\n return wrapper\n\n return decorator\n\n\ndef is_prime(n):\n return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n) - 1)))\n\n\ndef primes(lower=10000, upper=99999):\n for number in range(upper, lower, -2):\n if is_prime(number):\n yield number\n\n\n@time_it('elapsed time {:.3f} seconds')\ndef find_palindrome():\n primes_list = list(primes())\n max_palindrome = 0\n palindromes_list = []\n for p in primes_list:\n for q in primes_list:\n product = p * q\n if product > max_palindrome:\n str_product = str(product)\n if str_product[0] == str_product[-1] \\\n and str_product[1] == str_product[-2] \\\n and str_product[2] == str_product[-3] \\\n and str_product[3] == str_product[-4] \\\n and str_product[4] == str_product[-5]:\n max_palindrome = product\n palindromes_list.append((product, p, q))\n del primes_list[primes_list.index(q):]\n break\n else:\n del primes_list[primes_list.index(q):]\n break\n primes_list.remove(p)\n\n return palindromes_list[-1]\n\n\nprint(find_palindrome())\n","sub_path":"intetics/faster_solution.py","file_name":"faster_solution.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"301538549","text":"# pylint: disable=wrong-import-position\n\nAPP_NAME = \"fb_post\"\nOPERATION_NAME = \"reaction_metrics\"\nREQUEST_METHOD = \"get\"\nURL_SUFFIX = \"post/{postid}/reaction/metrics/\"\n\nfrom .test_case_01 import TestCase01ReactionMetricsAPITestCase\nfrom .test_case_02 import TestCase02ReactionMetricsAPITestCase\n\n__all__ = [\n \"TestCase01ReactionMetricsAPITestCase\",\n \"TestCase02ReactionMetricsAPITestCase\"\n]\n","sub_path":"fb_post/views/reaction_metrics/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"338591183","text":"import math\n\ndef k(n):\n return int(round(n/math.e, 0)+.5)\n\ndef d(n):\n t = k(n)\n t = t // math.gcd(t, n)\n while t % 2 == 0:\n t = t // 2\n while t % 5 == 0:\n t = t // 5\n if t == 1:\n return -n\n return n\n\nprint(sum(d(n) for n in range(5, 10**4+1)))\n","sub_path":"p183.py","file_name":"p183.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"364814943","text":"from Manager.models import BlogManager\n\n\ndef is_logged(request):\n username = request.session.get('username', '')\n name = request.session.get('name', '')\n\n try:\n user = BlogManager.objects.get(user_name=username)\n if not user:\n user = False\n except:\n user = False\n\n return username, name, user\n\n","sub_path":"Manager/is_logged.py","file_name":"is_logged.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"56298176","text":"#Playing from a file:\nimport numpy as np\nimport cv2\n\ncap = cv2.VideoCapture('file:///home/victoria/rescuebot_bagfiles/images_3/output.avi')\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n\n #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n cv2.imshow('frame',frame)\n if cv2.waitKey(120) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()","sub_path":"rescuebot/scripts/sample_code/play_from_file.py","file_name":"play_from_file.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"36084304","text":"import re\n\nclass TrieNode():\n def __init__(self):\n # Initialising one node for trie\n self.children = {}\n self.last = False\n\n\nclass Trie():\n def __init__(self):\n\n # Initialising the trie structure. \n self.root = TrieNode()\n self.word_list = []\n\n def formTrie(self, keys):\n for key in keys:\n self.insert(key) # inserting one key to the trie.\n\n def insert(self, key):\n\n # Inserts a key into trie if it does not exist already. \n # And if the key is a prefix of the trie node, just \n # marks it as leaf node. \n node = self.root\n\n for a in list(key):\n if not node.children.get(a):\n node.children[a] = TrieNode()\n\n node = node.children[a]\n\n node.last = True\n\n def search(self, key):\n node = self.root\n found = True\n\n for a in list(key):\n if not node.children.get(a):\n found = False\n break\n\n node = node.children[a]\n\n return node and node.last and found\n\n def getAll(self, node, word):\n if node.last:\n self.word_list.append(word)\n\n for a, n in node.children.items():\n self.getAll(n, word + a)\n\n def miniEngine(self, key, trie_path):\n\n node = self.root\n not_found = False\n temp_word = ''\n\n for a in list(key):\n if not node.children.get(a):\n not_found = True\n break\n\n temp_word += a\n node = node.children[a]\n\n if not_found:\n return 0\n\n print(\"Result in \", trie_path)\n self.getAll(node, temp_word)\n print(\"Found words : \", self.word_list)\n for s in self.word_list:\n\n self.get_position(word=s,trie_path=trie_path)\n print()\n return 1\n\n def get_position(self,word,trie_path):\n # Get the position of the word\n # from selected file location\n print(\"Position of the \\\" \",word,\"\\\" in the File \",trie_path)\n text = open(trie_path, \"r\")\n i = 1\n for line in text:\n line = re.sub(\"[,.]\", \"\", line)\n line = line.lower()\n if word in line:\n print(\"Index of first character : \",line.index(word) ,\" Line of the word : \",i)\n i = i+1\n","sub_path":"trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"29526691","text":"#!/usr/bin/env python\n\nimport csv\nimport math\nfrom .Interfaces import hAMRonizedResultIterator\n\nrequired_metadata = ['analysis_software_version',\n 'reference_database_version',\n 'input_file_name']\n\n\nclass RgiIterator(hAMRonizedResultIterator):\n\n def __init__(self, source, metadata):\n metadata['analysis_software_name'] = 'rgi'\n metadata['reference_database_id'] = 'CARD'\n self.metadata = metadata\n\n with open(source) as fh:\n header = next(fh)\n # i.e. RGI-bwt\n if 'Resistomes & Variants: Observed in Genome(s)' in \\\n header.strip().split('\\t'):\n self.field_mapping = {\n 'ARO Term': 'gene_symbol',\n 'ARO Accession': 'reference_accession',\n 'Reference Model Type': None,\n 'Reference DB': 'reference_database_id',\n 'Alleles with Mapped Reads': None,\n 'Reference Allele(s) Identity '\n 'to CARD Reference Protein (%)': 'sequence_identity',\n 'Resistomes & Variants: Observed in Genome(s)': None,\n 'Resistomes & Variants: Observed in Plasmid(s)': None,\n 'Resistomes & Variants: Observed Pathogen(s)': None,\n 'Completely Mapped Reads': None,\n 'Mapped Reads with Flanking Sequence': None,\n 'All Mapped Reads': None,\n 'Average Percent Coverage': 'coverage_percentage',\n 'Average Length Coverage (bp)': 'target_gene_length',\n 'Average MAPQ (Completely Mapped Reads)': None,\n 'Number of Mapped Baits': None,\n 'Number of Mapped Baits with Reads': None,\n 'Average Number of reads per Bait': None,\n 'Number of reads per Bait '\n 'Coefficient of Variation (%)': None,\n 'Number of reads mapping to baits '\n 'and mapping to complete gene': None,\n 'Number of reads mapping to baits and '\n 'mapping to complete gene (%)': None,\n 'Mate Pair Linkage (# reads)': None,\n 'Reference Length': 'reference_gene_length',\n 'AMR Gene Family': 'gene_name',\n 'Drug Class': 'drug_class',\n 'Resistance Mechanism': 'resistance_mechanism'\n # '': 'input_file_name',\n # '': 'contig_id',\n # '': 'query_start_aa',\n # '': 'query_stop_aa',\n # '': 'query_start_nt',\n # '': 'query_stop_nt',\n # '': 'subject_start_aa',\n # '': 'subject_stop_aa',\n # '': 'subject_start_nt',\n # '': 'subject_stop_nt',\n # '': 'strand_orientation',\n # '': 'coverage_depth',\n # '': 'coverage_ratio',\n # '': 'reference_database_id',\n # '': 'reference_database_version',\n # '': 'reference_protein_length',\n # '': 'target_protein_length',\n # '': 'antimicrobial_agent',\n # '': 'analysis_software_name',\n # '': 'analysis_software_version'\n }\n else:\n # normal RGI mode\n self.field_mapping = {\n 'ORF_ID': None,\n 'Contig': 'contig_id',\n 'Start': 'query_start_nt',\n 'Stop': 'query_stop_nt',\n 'Orientation': 'strand_orientation',\n 'Cut_Off': None,\n 'Pass_Bitscore': None,\n 'Best_Hit_Bitscore': None,\n 'Best_Hit_ARO': 'gene_symbol',\n 'Best_Identities': 'sequence_identity',\n 'ARO': 'reference_accession',\n 'Model_type': None,\n 'SNPs_in_Best_Hit_ARO': None,\n 'Other_SNPs': None,\n 'Drug Class': 'drug_class',\n 'Resistance Mechanism': 'resistance_mechanism',\n 'AMR Gene Family': 'gene_name',\n 'Predicted_DNA': None,\n 'Predicted_Protein': None,\n 'CARD_Protein_Sequence': None,\n 'Percentage Length of '\n 'Reference Sequence': 'coverage_percentage',\n 'ID': None,\n 'Model_ID': None,\n 'Nudged': None,\n 'Note': None,\n # '': 'input_file_name',\n # '': 'query_start_aa',\n # '': 'query_stop_aa',\n # '': 'subject_start_aa',\n # '': 'subject_stop_aa',\n # '': 'subject_start_nt',\n # '': 'subject_stop_nt',\n # '': 'coverage_depth',\n # '': 'coverage_ratio',\n # '': 'reference_database_id',\n # '': 'reference_database_version',\n # '': 'reference_gene_length',\n # '': 'reference_protein_length',\n # '': 'target_gene_length',\n # '': 'target_protein_length',\n # '': 'antimicrobial_agent',\n # '': 'analysis_software_name',\n # '': 'analysis_software_version'\n }\n\n super().__init__(source, self.field_mapping, self.metadata)\n\n def parse(self, handle):\n \"\"\"\n Read each and return it\n \"\"\"\n # skip any manually specified fields for later\n reader = csv.DictReader(handle, delimiter='\\t')\n for result in reader:\n # round down average length of coverage so its comparable to other\n # target lengths\n if 'Average Length Coverage (bp)' in result:\n result['Average Length Coverage (bp)'] = \\\n math.floor(float(result['Average Length Coverage (bp)']))\n yield self.hAMRonize(result, self.metadata)\n","sub_path":"hAMRonization/RgiIO.py","file_name":"RgiIO.py","file_ext":"py","file_size_in_byte":6305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"490191717","text":"# Given a binary tree, print nodes at each depth:\n\n# all tests should start with test_\n\nimport unittest\nimport collections\n\n\nclass BNode(object):\n\n def __init__(self, data, left=None, right=None):\n self.data = data\n self.left = left\n self.right = right\n\n\n# Like postorder traversal, append left, append right and then print self\n# Called as Level-Order traversal\n\n def make_ll_of_all_depths(self):\n\n q = collections.deque()\n\n current = self\n q.append(None)\n\n while len(q) != 0:\n if current == None:\n print()\n q.append(None)\n else:\n if current.left:\n q.append(current.left)\n if current.right:\n q.append(current.right)\n print(current.data, \" \", end=\"\")\n current = q.popleft()\n\n\nclass MyTreeTestCases(unittest.TestCase):\n\n def test_list_of_depths(self):\n\n tree = BNode(1,\n BNode(2,\n BNode(4),\n BNode(5,\n BNode(8)\n )\n ),\n BNode(3,\n BNode(6,\n None,\n BNode(9)\n ),\n BNode(7,\n BNode(10))\n )\n )\n tree.make_ll_of_all_depths()\n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"Trees/print_nodes_atall_depths.py","file_name":"print_nodes_atall_depths.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"270737505","text":"from openexchangelib import util\nfrom openexchangelib.types import OEBaseException\nimport os\n\n\ndef ensure_dir(dir_path):\n \"\"\"\n :type dir_path: str\n \"\"\"\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n\ndata_path = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'data')\nASSET_FOLDER = os.path.join(data_path, 'assets')\nBLOCK_FOLDER = os.path.join(data_path, 'block')\n\nensure_dir(ASSET_FOLDER)\nensure_dir(BLOCK_FOLDER)\n\n\nclass FileNotExistError(OEBaseException):\n pass\n\n\ndef load_data(file_name, base):\n \"\"\"\n :type file_name: str\n :type base: str\n \"\"\"\n full_name = os.path.join(base, file_name)\n if not os.path.isfile(full_name):\n raise FileNotExistError(fname=file_name)\n return util.load_obj(full_name)\n\n\ndef save_data(obj, file_name, base):\n \"\"\"\n :type file_name: str\n :type base: str\n \"\"\"\n assert isinstance(file_name, str)\n assert isinstance(base, str)\n\n full_name = os.path.join(base, file_name)\n return util.save_obj(obj, full_name)\n\n\ndef remove_data(file_name, base, silent=True):\n \"\"\"\n :type file_name: str\n :type base: str\n \"\"\"\n full_name = os.path.join(base, file_name)\n if not os.path.isfile(full_name):\n if not silent:\n raise FileNotExistError(fname=file_name)\n return False\n else:\n os.remove(full_name)\n return True\n\n\ndef data_file_max_index(base):\n indexes = [int(f) for f in os.listdir(base) if os.path.isfile(os.path.join(base, f)) and f.isdigit()]\n if not indexes:\n return None\n else:\n return max(indexes)\n\n\ndef pop_chained_state(remove=False):\n \"\"\"\n :rtype: ChainedState\n \"\"\"\n max_index = data_file_max_index(BLOCK_FOLDER)\n if max_index is None:\n return None\n else:\n data = load_data(str(max_index), BLOCK_FOLDER)\n if remove:\n remove_data(str(max_index), BLOCK_FOLDER)\n return data\n\n\ndef push_chained_state(chained_state):\n \"\"\"\n :type chained_state: ChainedState\n \"\"\"\n height = chained_state.exchange.processed_block_height\n save_data(chained_state, str(height), BLOCK_FOLDER)\n\n\ndef load_static_data():\n return load_data('static_data', data_path)\n\n\ndef save_static_data(static_data):\n return save_data(static_data, 'static_data', data_path)\n\n\ndef assets_data(chained_state):\n indexes = [int(f) for f in os.listdir(ASSET_FOLDER)\n if os.path.isfile(os.path.join(ASSET_FOLDER, f)) and f.isdigit()]\n return {i: util.load_obj(os.path.join(ASSET_FOLDER, str(i))) for i in set(indexes)-chained_state.used_asset_init_ids}\n\n\ndef save_asset_data(obj, index):\n return save_data(obj, str(index), ASSET_FOLDER)","sub_path":"DjangoWebServer/server/data_management.py","file_name":"data_management.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"85338674","text":"class Database:\n\n def __init__(self, cluster):\n self.cluster = cluster\n\n def get_injection(self, id_inj, inj=None):\n db = self.cluster[\"drivers\"]\n collection = db[\"injection\"]\n for i in collection.find({\"_id\": id_inj}, {\"_id\": 0, \"inj\": 1}):\n for x in i:\n inj = i[x]\n if inj:\n return inj\n else:\n return False\n\n def get_turbo(self, id_trb, trb=None):\n db = self.cluster[\"drivers\"]\n collection = db[\"injection\"]\n for i in collection.find({\"_id\": id_trb}, {\"_id\": 0, \"turbo\": 1}):\n for x in i:\n trb = i[x]\n if trb:\n return trb\n else:\n return False\n\n def get_rail(self, id_rail, ril=None):\n db = self.cluster[\"drivers\"]\n collection = db[\"injection\"]\n for i in collection.find({\"_id\": id_rail}, {\"_id\": 0, \"rail\": 1}):\n for x in i:\n ril = i[x]\n if ril:\n return ril\n else:\n return False\n\n def get_injection_pos(self, id_inj_pos):\n inj_pos = []\n db = self.cluster[\"drivers\"]\n collection = db[\"injection\"]\n for i in collection.find({\"_id\": id_inj_pos}, {\"_id\": 0, \"inj_pos1\": 1, \"inj_pos2\": 1}):\n for x in i:\n inj_pos.append(i[x])\n return inj_pos[0], inj_pos[1]\n\n def get_turbo_pos(self, id_trb_pos):\n trb_pos = []\n db = self.cluster[\"drivers\"]\n collection = db[\"injection\"]\n for i in collection.find({\"_id\": id_trb_pos}, {\"_id\": 0, \"turbo_pos1\": 1, \"turbo_pos2\": 1}):\n for x in i:\n trb_pos.append(i[x])\n return trb_pos[0], trb_pos[1]\n\n def get_rail_pos(self, id_rail_pos):\n rail_pos = []\n db = self.cluster[\"drivers\"]\n collection = db[\"injection\"]\n for i in collection.find({\"_id\": id_rail_pos}, {\"_id\": 0, \"rail_pos1\": 1, \"rail_pos2\": 1}):\n for x in i:\n rail_pos.append(i[x])\n return rail_pos[0], rail_pos[1]\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"202983866","text":"from rest_framework import serializers\nfrom adminapp.models import Comments\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n text = serializers.CharField(max_length=1000)\n type = serializers.CharField(max_length=20)\n file_type = serializers.JSONField()\n user = serializers.SerializerMethodField()\n created_at = serializers.CharField(max_length=100, read_only=True)\n\n class Meta:\n model = Comments\n fields = ('id', 'text', 'type', 'file_type', 'user', 'created_at')\n\n def get_user(self, comment):\n if comment.user.is_staff:\n user_info = {\n \"name\": comment.user.get_full_name(),\n \"avatar\": comment.user.avatar.url if comment.user.avatar else ''\n }\n else:\n user_info = {\n \"name\": comment.user.handworker.company_name,\n \"avatar\": comment.user.avatar.url if comment.user.avatar else ''\n }\n return user_info\n","sub_path":"serviceapp/serializers/comment_serializer.py","file_name":"comment_serializer.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"256923822","text":"\n\nfrom xai.brain.wordbase.nouns._tightrope import _TIGHTROPE\n\n#calss header\nclass _TIGHTROPES(_TIGHTROPE, ):\n\tdef __init__(self,): \n\t\t_TIGHTROPE.__init__(self)\n\t\tself.name = \"TIGHTROPES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tightrope\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tightropes.py","file_name":"_tightropes.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"588824612","text":"#!/usr/bin/python3\n\nimport sys\nimport heapq\n\nclass QNode:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.done = False\n \n def __lt__(self, other):\n return self.key < other.key\n\nclass BiDij:\n def __init__(self, n):\n self.n = n # Number of nodes\n self.inf = float(\"inf\") # All distances in the graph are smaller\n self.d = [[self.inf]*n, [self.inf]*n] # Initialize distances for forward and backward searches\n self.visited = [[False]*n, [False]*n] # visited[v] == True iff v was visited by forward or backward search\n self.workset = set() # All the nodes visited by forward or backward search\n\n def clear(self):\n \"\"\"Reinitialize the data structures for the next query after the previous query.\"\"\"\n for v in self.workset:\n self.d[0][v] = self.d[1][v] = self.inf\n self.visited[0][v] = False\n self.visited[1][v] = False\n\n self.workset = set()\n\n def visit(self, q, side, v, dist, qdict):\n \"\"\"Try to relax the distance to node v from direction side by value dist.\"\"\"\n if self.d[side][v] > dist:\n self.d[side][v] = dist\n self.visited[side][v] = True\n self.workset.add(v)\n\n # change priority\n if v in qdict[side]:\n qdict[side][v].done = True\n\n node = QNode(self.d[side][v], v)\n qdict[side][v] = node\n heapq.heappush(q[side], node)\n \n pass\n \n def shortestPath(self, s, t):\n distance = self.inf\n for u in self.workset:\n if self.d[0][u] + self.d[1][u] < distance:\n distance = self.d[0][u] + self.d[1][u]\n \n return distance\n\n def query(self, adj, cost, s, t):\n self.clear()\n q = [[], []]\n qdict = [dict(), dict()]\n self.visit(q, 0, s, 0, qdict)\n self.visit(q, 1, t, 0, qdict)\n\n while q[0] and q[1]:\n if q[0]:\n u = heapq.heappop(q[0])\n if not u.done:\n for vi in range(len(adj[0][u.value])):\n v = adj[0][u.value][vi]\n vcost = cost[0][u.value][vi]\n self.visit(q, 0, v, u.key+vcost, qdict)\n if self.visited[1][u.value]:\n return self.shortestPath(s, t)\n if q[1]:\n u = heapq.heappop(q[1])\n if not u.done:\n for vi in range(len(adj[1][u.value])):\n v = adj[1][u.value][vi]\n vcost = cost[1][u.value][vi]\n self.visit(q, 1, v, u.key+vcost, qdict)\n\n return -1\n\n\ndef readl():\n return map(int, sys.stdin.readline().split())\n\n\nif __name__ == '__main__':\n n,m = readl()\n adj = [[[] for _ in range(n)], [[] for _ in range(n)]]\n cost = [[[] for _ in range(n)], [[] for _ in range(n)]]\n for e in range(m):\n u,v,c = readl()\n adj[0][u-1].append(v-1)\n cost[0][u-1].append(c)\n adj[1][v-1].append(u-1)\n cost[1][v-1].append(c)\n t, = readl()\n bidij = BiDij(n)\n for i in range(t):\n s, t = readl()\n print(bidij.query(adj, cost, s-1, t-1))\n","sub_path":"algorithms_on_graphs/6.1_friend_suggestion.py3","file_name":"6.1_friend_suggestion.py3","file_ext":"py3","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"79929572","text":"# importing the required libraries\nimport pygame as pg\nimport sys\nimport time\nfrom pygame.locals import *\n\n# set width and height of the game window\nw = 800\nh = 800\n\n# set offset and game board size\nos = 50\ngw = w-os\ngh = h-os\nogw = (gw-os)\nogh = (gh-os)\n\n# colors\nwhite = (255, 255, 255)\nboardColor = (255, 235, 179)\nblack = (0, 0, 0)\ngray = (100,100,100)\nred = (173, 54, 54)\nblue = (87, 117, 140)\nyellow = (255, 255, 0)\n\n# initializing necessities\npg.init()\nfps = 30\nCLOCK = pg.time.Clock()\nscreen = pg.display.set_mode((w, h), 0, 32)\npg.display.set_caption(\"Six Men's Morris\")\n\n\n# Coordinates of tiles\ncoordDict={\n\t\"a\" : (os, os),\n\t\"b\" : (os+ogw/2, os),\n\t\"c\" : (gw, os),\n\t\"d\" : (gw, os+ogh/2),\n\t\"e\" : (gw, gh),\n\t\"f\" : (os+ogw/2, gh),\n\t\"g\" : (os, gh),\n\t\"h\" : (os, os+ogh/2),\n\t\"i\" : (os+ogw/4, os+ogh/2),\n\t\"j\" : (os+ogw/4, os+ogh/4),\n\t\"k\" : (os+ogw/2, os+ogh/4),\n\t\"l\" : (os+3*ogw/4, os+ogh/4),\n\t\"m\" : (os+3*ogw/4, os+ogh/2),\n\t\"n\" : (os+3*ogw/4, os+3*ogh/4),\n\t\"o\" : (os+ogw/2, os+3*ogh/4),\n\t\"p\" : (os+ogw/4, os+3*ogh/4),\n}\n\n#list of tiles and what color player is currently occupying that spot\ntiles={\n\t\"a\" : \"none\",\n\t\"b\" : \"none\",\n\t\"c\" : \"none\",\n\t\"d\" : \"none\",\n\t\"e\" : \"none\",\n\t\"f\" : \"none\",\n\t\"g\" : \"none\",\n\t\"h\" : \"none\",\n\t\"i\" : \"none\",\n\t\"j\" : \"none\",\n\t\"k\" : \"none\",\n\t\"l\" : \"none\",\n\t\"m\" : \"none\",\n\t\"n\" : \"none\",\n\t\"o\" : \"none\",\n\t\"p\" : \"none\",\n}\n\n#This function draws everything every game loop\ndef draw():\n\tscreen.fill(boardColor)\n\n\tif(turn % 2 == 1):\n\t\tplayer = \"Red\"\n\telse:\n\t\tplayer = \"Blue\"\n\n\t#This is all for displaying text in the center of the screen\n\twinCheck = winner()\n\tif winCheck == \"none\" or turn < 12:\n\t\tfont = pg.font.Font('freesansbold.ttf', 32)\n\t\ttext1 = font.render('Turn = ' + str(turn + 1), True, black, boardColor)\n\t\ttext2 = font.render('It is ' + player + '\\'s turn' , True, black, boardColor)\n\t\ttextRect1 = text1.get_rect()\n\t\ttextRect2 = text2.get_rect()\n\t\ttextRect1.center = ((w // 2) + 17, (h // 2) + 17)\n\t\ttextRect2.center = ((w // 2) - 17, (h // 2) - 17)\n\n\t\tscreen.blit(text1, textRect1)\n\t\tscreen.blit(text2, textRect2)\n\telse:\n\t\tfont = pg.font.Font('freesansbold.ttf', 32)\n\t\ttext3 = font.render(winCheck + ' wins!', True, black, boardColor)\n\t\ttextRect3 = text3.get_rect()\n\t\ttextRect3.center = ((w // 2) + 17, (h // 2) + 17)\n\t\tscreen.blit(text3, textRect3)\n\n\n\t# drawing outter Box\n\tpg.draw.line(screen, black, coordDict[\"a\"], coordDict[\"c\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"c\"], coordDict[\"e\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"e\"], coordDict[\"g\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"g\"], coordDict[\"a\"], 7)\n\t#drawing connecting lines\n\tpg.draw.line(screen, black, coordDict[\"b\"], coordDict[\"k\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"d\"], coordDict[\"m\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"f\"], coordDict[\"o\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"h\"], coordDict[\"i\"], 7)\n\t# drawing inner box\n\tpg.draw.line(screen, black, coordDict[\"j\"], coordDict[\"l\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"l\"], coordDict[\"n\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"n\"], coordDict[\"p\"], 7)\n\tpg.draw.line(screen, black, coordDict[\"p\"], coordDict[\"j\"], 7)\n\n\tx, y = pg.mouse.get_pos()\n\n\t#This is for drawing the tiles in their correct positions\n\tfor tile in tiles:\n\t\tif(tiles[tile] == \"Blue\"):\n\t\t\tpg.draw.circle(screen, blue, coordDict[tile], 40)\n\t\telif(tiles[tile] == \"Red\"):\n\t\t\tpg.draw.circle(screen, red, coordDict[tile], 40)\n\n\t#This is for highlighting the selected tile\n\tif(selected != \"none\"):\n\t\tpg.draw.circle(screen, yellow, selected, 40, width = 10)\n\ncurr = \"none\"\nturn = 0\n#This function is for placing down tiles\ndef place():\n\tglobal curr\n\tglobal turn\n\tfor key in coordDict:\n\t\tif tiles[key] == \"none\":\n\t\t\tif coordDict[key][0]-40 <= x <= coordDict[key][0]+40 and coordDict[key][1]-40 <= y <= coordDict[key][1]+40:\n\t\t\t\tcurr = (list(coordDict.keys())[list(coordDict.values()).index(coordDict[key])])\n\t\t\t\tif(turn % 2 == 0):\n\t\t\t\t\ttiles[key] = \"Blue\"\n\t\t\t\telse:\n\t\t\t\t\ttiles[key] = \"Red\"\n\t\t\t\tif morrisChecker(curr) == False:\n\t\t\t\t\tturn = turn + 1\n\n\nselected = \"none\"\n#This function picks which tile the user has selected\ndef moveSelecter():\n\tglobal selected\n\tx, y = pg.mouse.get_pos()\n\tfor key in coordDict:\n\t\tif tiles[key] != \"none\":\n\t\t\tif coordDict[key][0]-40 <= x <= coordDict[key][0]+40 and coordDict[key][1]-40 <= y <= coordDict[key][1]+40:\n\t\t\t\tglobal turn\n\t\t\t\tif(turn % 2 == 1):\n\t\t\t\t\tif(tiles[key]) == \"Red\":\n\t\t\t\t\t\tselected = coordDict[key]\n\t\t\t\telse:\n\t\t\t\t\tif(tiles[key]) == \"Blue\":\n\t\t\t\t\t\tselected = coordDict[key]\n\n\n#This function draws a tile where the user chooses to move to as well as removing the tile from the old spot\ndef moveHelper():\n\tglobal selected\n\tglobal turn\n\tif(selected != \"none\"):\n\t\tx, y = pg.mouse.get_pos()\n\t\tfor key in coordDict:\n\t\t\tif tiles[key] == \"none\":\n\t\t\t\tif coordDict[key][0]-40 <= x <= coordDict[key][0]+40 and coordDict[key][1]-40 <= y <= coordDict[key][1]+40:\n\t\t\t\t\tglobal curr\n\t\t\t\t\tcurr = (list(coordDict.keys())[list(coordDict.values()).index(coordDict[key])])\n\t\t\t\t\tprev = (list(coordDict.keys())[list(coordDict.values()).index(selected)])\n\t\t\t\t\tif key in moveOptions(prev):\n\t\t\t\t\t\tfor coord in coordDict:\n\t\t\t\t\t\t\tif(selected == coordDict[coord]):\n\t\t\t\t\t\t\t\ttiles[coord] = \"none\"\n\t\t\t\t\t\tif(turn % 2 == 0):\n\t\t\t\t\t\t\ttiles[key] = \"Blue\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttiles[key] = \"Red\"\n\n\t\t\t\t\t\tselected = \"none\"\n\t\t\t\t\t\tif morrisChecker(curr) == False:\n\t\t\t\t\t\t\tturn = turn + 1\n\n\n#This functions return whether or not a move is valid or not\ndef moveOptions(prev):\n\tvalidMoves={\n\t\t\"a\" : [\"b\", \"h\"],\n\t\t\"b\" : [\"a\", \"c\", \"k\"],\n\t\t\"c\" : [\"b\", \"d\"],\n\t\t\"d\" : [\"c\", \"e\", \"m\"],\n\t\t\"e\" : [\"d\", \"f\"],\n\t\t\"f\" : [\"e\", \"g\", \"o\"],\n\t\t\"g\" : [\"f\", \"h\"],\n\t\t\"h\" : [\"a\", \"g\", \"i\"],\n\t\t\"i\" : [\"h\", \"j\", \"p\"],\n\t\t\"j\" : [\"i\", \"k\"],\n\t\t\"k\" : [\"b\", \"j\", \"l\"],\n\t\t\"l\" : [\"k\", \"m\"],\n\t\t\"m\" : [\"d\", \"l\", \"n\"],\n\t\t\"n\" : [\"m\", \"o\"],\n\t\t\"o\" : [\"f\", \"n\", \"p\"],\n\t\t\"p\" : [\"i\", \"o\"],\n\t}\n\treturn validMoves[prev]\n\n\n#This function picks which tile the user has selected\ndef deletion():\n\tglobal curr\n\tglobal turn\n\tx, y = pg.mouse.get_pos()\n\tfor key in coordDict:\n\t\tif tiles[key] != \"none\":\n\t\t\tif coordDict[key][0]-40 <= x <= coordDict[key][0]+40 and coordDict[key][1]-40 <= y <= coordDict[key][1]+40:\n\t\t\t\tglobal turn\n\t\t\t\tif(turn % 2 == 1):\n\t\t\t\t\tif(tiles[key]) == \"Blue\":\n\t\t\t\t\t\ttiles[key] = \"none\"\n\t\t\t\t\t\tcurr = \"none\"\n\t\t\t\t\t\tturn = turn + 1\n\t\t\t\telse:\n\t\t\t\t\tif(tiles[key]) == \"Red\":\n\t\t\t\t\t\ttiles[key] = \"none\"\n\t\t\t\t\t\tcurr = \"none\"\n\t\t\t\t\t\tturn = turn + 1\n\n\n#[WORK IN PROGRESS]\ndef morrisChecker(tile):\n\tpiece = tile\n\tline = []\n\tglobal curr\n\n\tif tiles[\"a\"] == tiles[\"b\"] == tiles[\"c\"] and tiles[\"a\"] != \"none\":\n\t\tline = [\"a\", \"b\", \"c\"]\n\t\tif curr in line:\n\t\t\treturn True\n\n\tif tiles[\"a\"] == tiles[\"h\"] == tiles[\"g\"] and tiles[\"a\"] != \"none\":\n\t\tline = [\"a\", \"h\", \"g\"]\n\t\tif curr in line:\n\t\t\treturn True\n\n\tif tiles[\"c\"] == tiles[\"d\"] == tiles[\"e\"] and tiles[\"e\"] != \"none\":\n\t\tline = [\"c\", \"d\", \"e\"]\n\t\tif curr in line:\n\t\t\treturn True\n\n\tif tiles[\"e\"] == tiles[\"f\"] == tiles[\"g\"] and tiles[\"e\"] != \"none\":\n\t\tline = [\"e\", \"f\", \"g\"]\n\t\tif curr in line:\n\t\t\treturn True\n\n\tif tiles[\"j\"] == tiles[\"k\"] == tiles[\"l\"] and tiles[\"j\"] != \"none\":\n\t\tline = [\"j\", \"k\", \"l\"]\n\t\tif curr in line:\n\t\t\treturn True\n\n\tif tiles[\"j\"] == tiles[\"i\"] == tiles[\"p\"] and tiles[\"j\"] != \"none\":\n\t\tline = [\"j\", \"i\", \"p\"]\n\t\tif curr in line:\n\t\t\treturn True\n\n\tif tiles[\"l\"] == tiles[\"m\"] == tiles[\"n\"] and tiles[\"n\"] != \"none\":\n\t\tline = [\"l\", \"m\", \"n\"]\n\t\tif curr in line:\n\t\t\treturn True\n\n\tif tiles[\"n\"] == tiles[\"o\"] == tiles[\"p\"] and tiles[\"n\"] != \"none\":\n\t\tline = [\"n\", \"o\", \"p\"]\n\t\tif curr in line:\n\t\t\treturn True\n\n\treturn False\n\n\ndef winner():\n\tblueTotal = 0\n\tredTotal = 0\n\tvictor = \"none\"\n\tfor x in coordDict:\n\t\tif tiles[x] == \"Blue\":\n\t\t\tblueTotal = blueTotal + 1\n\t\telif tiles[x] == \"Red\":\n\t\t\tredTotal = redTotal + 1\n\tif blueTotal == 2 or redTotal == 2:\n\t\tif blueTotal == 2:\n\t\t\tvictor = \"Red\"\n\t\telse:\n\n\t\t\tvictor = \"Blue\"\n\treturn victor\n\n\nwhile(True):\n\tfor event in pg.event.get():\n\t\tif event.type == QUIT:\n\t\t\tpg.quit()\n\t\t\tsys.exit()\n\n\tx, y = pg.mouse.get_pos()\n\n\tdraw()\n\n\tif morrisChecker(curr):\n\t\tif event.type == pg.MOUSEBUTTONUP:\n\t\t\tdeletion()\n\telif event.type == pg.MOUSEBUTTONDOWN:\n\t\tif(turn < 12):\n\t\t\tplace()\n\t\telse:\n\t\t\twinCheck = winner()\n\t\t\tif winCheck == \"none\":\n\t\t\t\tmoveSelecter()\n\t\t\t\tmoveHelper()\n\t\t\telse:\n\t\t\t\tscreen.fill(boardColor)\n\n\t# This is drawing black dots and making them gray when hovered\n\tfor key in coordDict:\n\t\tif tiles[key] == \"none\":\n\t\t\tif coordDict[key][0]-40 <= x <= coordDict[key][0]+40 and coordDict[key][1]-40 <= y <= coordDict[key][1]+40:\n\t\t\t\tpg.draw.circle(screen, gray, coordDict[key], 16)\n\t\t\telse:\n\t\t\t\tpg.draw.circle(screen, black, coordDict[key], 16)\n\n\n\tpg.display.update()\n\tCLOCK.tick(fps)\n","sub_path":"PvPsmm.py","file_name":"PvPsmm.py","file_ext":"py","file_size_in_byte":8606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"222363676","text":"\nwords = [\"@coolguy35\", \"#nofilter\", \"@kewldawg54\", \"reply\", \"timestamp\", \"@matchamom\", \"follow\", \"#updog\"]\nusernames = []\n\nfor word in words:\n if word[0] == '@':\n usernames.append(word)\n\nusername2=[word for word in words if word[0]=='@']\n\nprint(usernames)\nprint(username2)\n\n\n#2. Turn the follwoing conditional loop list creation to List comprehension:\n\nheights = [161, 164, 156, 144, 158, 170, 163, 163, 157]\ncan_ride_coaster1=[]\nfor height in heights:\n if height>161:\n can_ride_coaster1.append(height)\nprint(can_ride_coaster1)\n\n\ncan_ride_coaster=[height for height in heights if height>161]\nprint(can_ride_coaster)\n\n\n#3\nfollowme=[name + \" please follow me!\" for name in usernames ]\nprint(followme)\n\n\n#f-->c\ncelsius = [0, 10, 15, 32, -5, 27, 3]\n\nkashi=[temp*9/5+32 for temp in celsius]\nprint(kashi)\n\n\n#5\nsingle_digits=list(range(10))\nsquares=[]\nfor i in single_digits:\n value=i*i\n squares.append(value)\nprint(squares)\n\nsquareslc=[i*i for i in single_digits]\nprint(squareslc)\n\n\n#6\ncube=[]\nfor i in single_digits:\n value=i**3\n cube.append(value)\nprint(cube)\n\ncubelc=[i**3 for i in single_digits]\nprint(cubelc)\n\n#7\n\nhairstyles = [\"bouffant\", \"pixie\", \"dreadlocks\", \"crew\", \"bowl\", \"bob\", \"mohawk\", \"flattop\"]\nprices = [30, 25, 40, 20, 20, 35, 50, 35]\nlast_week = [2, 3, 5, 8, 4, 4, 6, 2]\n\nnew_price=[price-5 for price in prices]\nprint(new_price)\n\ntotal_revenu=[prices[i]*last_week[i] for i in range(len(hairstyles))]\ntotal_revenu=sum(total_revenu)\nprint(\"Total revenue: $%.2f\" %(total_revenu))\n\ncuts_under_30=[hairstyles[i] for i in range(len(hairstyles)) if new_price[i]<30]\nprint(cuts_under_30)\n\n\n\ndef delete_starting_evens(lst):\n while True: \n if len(lst)>1 and lst[0]%2==0: \n lst.pop(0) \n elif len(lst)==1 and lst[0]%2==0: \n emptylst=[]\n return emptylst \n else: \n return lst \n \n","sub_path":"sonohoka/renshuLC.py","file_name":"renshuLC.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"616021834","text":"import scrapy\nimport sys\nsys.path.append('../')\nfrom selenium import webdriver\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\nclass LivespiderItem(scrapy.Item):\n width = scrapy.Field()\n height = scrapy.Field()\n top = scrapy.Field()\n left = scrapy.Field()\n frameWidth = scrapy.Field()\n frameHeight = scrapy.Field()\nclass DouyuSpider(scrapy.Spider):\n start_urls = ['http://www.douyu.tv/cms/zt/lpl.html#a']\n name = 'douyuspider'\n def parse(self,response):\n driver = webdriver.Chrome()\n driver.get('http://www.douyu.tv/cms/zt/lpl.html#a')\n source = driver.page_source\n with open('G:/live/lovelive/templates/moban.html','w') as fp:\n fp.write(source)\n fp.close()\n line = open('G:/live/lovelive/templates/moban.html').readlines()\n line[-1:1] = ['\\n\\n\\n']\n open('G:/live/lovelive/templates/moban.html','w').writelines(line)\n driver.maximize_window()\n driver.get('G:/live/lovelive/templates/moban.html')\n source = driver.page_source\n with open('G:/live/lovelive/templates/moban.html','w') as fp:\n fp.write(source)\n fp.close()\n return scrapy.Request('http://127.0.0.1:8000/moban',callback = self.parse2)\n def parse2(self,response):\n filename = \"G:/live/lovelive/static/moban.json\"\n item = LivespiderItem()\n item['width'] = response.css('object[id*=\"room\"]::attr(data-width)').extract()\n item['height'] = response.css('object[id*=\"room\"]::attr(data-height)').extract()\n item['top'] = response.css('object[id*=\"room\"]::attr(data-top)').extract()\n item['left'] = response.css('object[id*=\"room\"]::attr(data-left)').extract()\n item['frameWidth'] = response.css('object[id*=\"room\"]::attr(data-frame-width)').extract()\n item['frameHeight'] = response.css('object[id*=\"room\"]::attr(data-frame-height)').extract()\n with open('G:/live/lovelive/templates/bridge frame.html')as fp:\n line = fp.readlines()\n line[10] = ' src=\"'+self.start_urls[0]+'\"\\n'\n line[11] =' style=\"position: absolute;top: -'+item[\"top\"][0]+'px;left: -'+item[\"left\"][0]+'px;width:'+item[\"width\"][0]+'px;height:'+item[\"height\"][0]+'px;\"\\n'\n open('G:/live/lovelive/templates/bridge frame.html','w+').writelines(line)\n st = str(dict(item))\n with open(filename,'wb') as fp:\n fp.write(st)\n\n","sub_path":"lovelive/static/douyuspider.py","file_name":"douyuspider.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"619486343","text":"#!/usr/bin/python\n\n\"\"\"\nLikhi Ondov - 28 August 2016\nThis code doesn't really do anything other than some basic programming shit.\n\"\"\"\n\n# import modules used here -- sys is a very standard one\nimport sys\nimport random\nfrom datetime import datetime\n\n# Gather our code in a main() function\ndef main():\n\n print(random_range(10));\n print(\"%.2f\" % meal_example());\n string_ex();\n escaped();\n index_string();\n string_length();\n demo_UL_case();\n makeStr(43.12);\n formatter();\n #rawinput();\n dates();\n make_booleans();\n six_and();\n seven_or();\n eight_not();\n nine_this_and_that();\n ten();\n\n\ndef six_and():\n bool_one = False and False;\n bool_two = -(-(-(-2))) == -2 and 4 >= 16**0.5;\n bool_three = 19 % 4 != 300 / 10 / 10 and False;\n bool_four = -(1**2) < 2**0 and 10 % 10 <= 20 - 10 * 2;\n bool_five = True and True;\n\ndef seven_or():\n bool_one = 2**3 == 108 % 100 or 'Cleese' == 'King Arthur';\n bool_two = True or False;\n bool_three = 100**0.5 >= 50 or False;\n bool_four = True or True;\n bool_five = 1**100 == 100**1 or 3 * 2 * 1 != 3 + 2 + 1;\n\ndef eight_not():\n bool_one = not True;\n bool_two = not 3**4 < 4**3;\n bool_three = not 10 % 3 <= 10 % 2;\n bool_four = not 3**2 + 4**2 != 5**2;\n bool_five = not not False;\n\ndef nine_this_and_that():\n bool_one = False or not True and True;\n bool_two = False and not True or True;\n bool_three = True and not (False or False);\n bool_four = not not True or False and not True;\n bool_five = False or not (True and True);\n\ndef ten():\n # Use boolean expressions as appropriate on the lines below!\n\n # Make me false!\n bool_one = (2 <= 2) and \"Alpha\" == \"Bravo\" # We did this one for you!\n\n # Make me true!\n bool_two = (2 <= 5) or (1<=1.5);\n\n # Make me false!\n bool_three = (\"batt\" == \"fruit cake\");\n print(bool_three);\n\n # Make me true!\n bool_four = not (0xFF < 0xAB);\n\n # Make me true!\n bool_five = not (\"turtle\" == \"tortoise\")\n\ndef make_booleans():\n bool_one = 3<5;\n print(bool_one);\n\ndef spam():\n eggs = 12;\n return eggs;\n\ndef random_range(max):\n return max*random.random()\n\ndef meal_example():\n meal = 44.50;\n tax = 6.75/100;\n tip = 15.0/100;\n\n meal = meal + meal * tax;\n meal = meal + meal * tip;\n\n return meal;\n\ndef string_ex():\n caesar = \"Graham\";\n praline = \"John\";\n viking = \"Teresa\";\n\n print(caesar);\n print(praline);\n print(viking);\n\ndef escaped():\n print('This isn\\'t flying, this is falling with style!');\n\ndef index_string():\n fifth_letter = \"MONTY\"[4];\n print(fifth_letter);\n\ndef string_length():\n myStr = \"dick butt\";\n print(len(myStr));\n\ndef demo_UL_case():\n myStr = \"IM YELLING\"\n print(myStr.lower()); # note that lower() is a method of the string class\n print(myStr.upper());\n\ndef makeStr(s):\n print(str(s));\n\ndef formatter():\n string_1 = \"Camelot\";\n string_2 = \"place\";\n\n print(\"Let's not go to %s. 'Tis a silly %s.\" % (string_1, string_2));\n\ndef rawinput():\n name = input(\"What is your name?\")\n quest = input(\"What is your quest?\")\n color = input(\"What is your favorite color?\")\n\n print(\"Ah, so your name is %s, your quest is %s, \" \\\n \"and your favorite color is %s.\" % (name, quest, color));\n\ndef dates():\n now = datetime.now();\n print(now);\n print(now.year);\n print(now.month);\n print(now.day);\n print(\"%s/%s/%s %s:%s:%s\" % (now.month,now.day,now.year,\\\n now.hour,now.minute,now.second));\n\n# Standard boilerplate to call the main() function to begin\n# the program.\nif __name__ == '__main__':\n main()\n","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"227288284","text":"import numpy as np\nimport pyccl as ccl\n\nfrom ..wl import (\n _mag_to_lum, _compute_red_frac_z_Az, KEBNLASystematic,\n DESCSRDv1MultiplicativeShearBias)\n\nCOSMO = ccl.Cosmology(\n Omega_b=0.0492,\n Omega_c=0.26639999999999997, # = 0.3156 - 0.0492\n w0=-1.0,\n wa=0.0,\n h=0.6727,\n A_s=2.12655e-9, # has sigma8 = 0.8310036\n n_s=0.9645)\n\n\nclass DummySource(object):\n pass\n\n\ndef test_mult_shear_bias():\n src = DummySource()\n src.z_ = np.linspace(0.0, 1.0, 100)\n src.dndz_ = src.z_**2 / 10 + src.z_\n src.scale_ = 1.0\n m = 0.05\n params = {'blah': m}\n\n nrm = np.sum(src.dndz_)\n fac = np.sum(src.dndz_ * (2 * src.z_ - 1.33) / 1.33) / nrm\n\n sys = DESCSRDv1MultiplicativeShearBias(m='blah')\n sys.apply(None, params, src)\n\n assert np.allclose(src.scale_, 1.0 + fac * 0.05)\n\n\ndef test_compute_red_frac_z_Az_redfrac():\n z = np.linspace(0.05, 3.55, 10)\n lpiv_beta_ia = _mag_to_lum(-22)\n beta_ia = 1.0\n vals = [_compute_red_frac_z_Az(\n _z, ccl.luminosity_distance(COSMO, 1 / (1.0 + _z)),\n beta_ia, lpiv_beta_ia)\n for _z in z]\n rf, _ = zip(*vals)\n rf = np.array(rf)\n\n # max red frac is always small for LSST depths\n assert np.max(rf) < 0.10\n\n # the red fraction is alwasy small at high redshift\n msk = z > 2.0\n assert np.all(rf[msk] < 0.01)\n\n\ndef test_ia_bias():\n src = DummySource()\n src.z_ = np.linspace(0.05, 3.55, 10)\n src.ia_bias_ = np.ones_like(src.z_)\n src.red_frac_ = np.ones_like(src.z_)\n\n eta_ia = 1.0\n eta_ia_highz = 4.0\n beta_ia = 1.0\n Omega_b = 0.05\n Omega_c = 0.25\n\n lpiv_beta_ia = _mag_to_lum(-22)\n vals = [_compute_red_frac_z_Az(\n _z, ccl.luminosity_distance(COSMO, 1 / (1.0 + _z)),\n beta_ia, lpiv_beta_ia)\n for _z in src.z_]\n rf, az = zip(*vals)\n\n params = {\n 'a': eta_ia,\n 'b': eta_ia_highz,\n 'c': beta_ia,\n 'd': Omega_b,\n 'e': Omega_c}\n\n sys = KEBNLASystematic(\n eta_ia='a',\n eta_ia_highz='b',\n beta_ia='c',\n Omega_b='d',\n Omega_c='e')\n sys.apply(COSMO, params, src)\n\n # make sure it did something\n assert not np.allclose(src.ia_bias_, 1.0)\n assert not np.allclose(src.red_frac_, 1.0)\n\n # check the red frac\n assert np.allclose(src.red_frac_, rf)\n\n # check the IA signal\n fac = (\n (Omega_b + Omega_c) * 0.0134 /\n ccl.growth_factor(COSMO, 1.0 / (1.0 + src.z_)) *\n np.power((1 + src.z_) / (1 + 0.3), eta_ia))\n fac *= (\n 1.0 * (src.z_ < 0.7) +\n np.power((1 + src.z_) / (1 + 0.7), eta_ia_highz) * (src.z_ > 0.7))\n fac *= az\n assert np.allclose(src.ia_bias_, fac)\n","sub_path":"examples/desc_srd_v1/srd_models/tests/test_wl.py","file_name":"test_wl.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569603910","text":"from django import forms\nfrom django.conf import settings\n\nfrom django.utils.safestring import mark_safe\nfrom django.utils.html import escape, conditional_escape\nfrom django.utils.encoding import force_unicode\n\nfrom django.forms.utils import flatatt\nfrom urlparse import urljoin \n\nclass CodeMirrorEditor( forms.Textarea ):\n \"\"\"\n CodeMirror rich-editor in HTML (provides syntax highlight and\n other some basic things.)\n\n http://marijn.haverbeke.nl/codemirror/manual.html\n \"\"\"\n\n CODEEDITOR_JS = \"\"\"\n\n\"\"\" \n\n SYNTAXES = {\n 'css': (('parsecss.js',),('csscolors.css',)),\n 'html': ((\"parsexml.js\", \"parsecss.js\", \"tokenizejavascript.js\", \"parsejavascript.js\", \"parsehtmlmixed.js\"), ('xmlcolors.css','jscolors.css','csscolors.css',)),\n 'js': ((\"parsejavascript.js\",\"tokenizejavascript.js\"), ('jscolors.css',)),\n 'dummy': ((\"parsedummy.js\",), ('dummy.css',))\n }\n\n editor_attrs = {\n 'CODEEDITOR_MEDIA_URL': urljoin( settings.STATIC_URL , 'templatesadmin/codemirror/' ),\n 'syntax': 'html',\n 'indentUnit': '4',\n 'autoMatchParens': 'True', \n 'lineNumbers': 'True',\n 'tabMode': 'shift',\n 'width': '240px',\n 'height': '300px'\n }\n\n def __init__(self, attrs=None):\n if attrs:\n self.editor_attrs.update(attrs)\n \n super(CodeMirrorEditor, self).__init__({'rows': '10','cols': '40'})\n\n def render(self, name, value, attrs=None):\n # Build textarea first\n if value is None: value = ''\n text_attrs = self.build_attrs( attrs , name=name )\n textarea_html = u'%s' % (flatatt(text_attrs), conditional_escape(force_unicode(value)))\n\n # Build the codemirror widget\n (parserFile,stylesheets) = self.syntax;\n codeeditor_html = self.CODEEDITOR_JS % dict(name=name , parserFiles=parserFile, stylesheets=stylesheets, **self.editor_attrs )\n\n return mark_safe( '\\n'.join([textarea_html , codeeditor_html ]) )\n\n\n def _syntax(self):\n \"\"\"\n Given a regular language, return the appropriate files\n (parserFiles + stylesheets ) in a js-dict-friendly format (remove u'str' formts)\n \"\"\"\n syntax = self.editor_attrs['syntax']\n if syntax not in self.SYNTAXES:\n syntax = u'dummy'\n\n codemedia_url = self.editor_attrs['CODEEDITOR_MEDIA_URL']\n parserfiles = unicode([str(conditional_escape(f)) for f in self.SYNTAXES[syntax][0] ])\n stylesheets = unicode([str(conditional_escape(urljoin(codemedia_url, \"css/%s\" % f))) for f in self.SYNTAXES[syntax][1] ])\n\n return parserfiles , stylesheets\n\n def _media(self):\n return forms.Media( js=( urljoin(self.editor_attrs['CODEEDITOR_MEDIA_URL'] , 'js/codemirror.js') ,),\n css={ 'all': (urljoin(self.editor_attrs['CODEEDITOR_MEDIA_URL'] , 'css/codemirror.css'), )})\n\n syntax = property(_syntax)\n media = property(_media)\n","sub_path":"templatesadmin/widgets/codemirror.py","file_name":"codemirror.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"256615462","text":"import pytest\nfrom ansible.errors import AnsibleOptionsError\nfrom ansible.release import __version__ as ansible_version\n\nfrom ansibleplaybookgrapher import __prog__, __version__\nfrom ansibleplaybookgrapher.cli import get_cli_class\n\n\n@pytest.mark.parametrize(\"help_option\", ['-h', '--help'])\ndef test_cli_help(help_option, capfd):\n \"\"\"\n Test for the help option : -h, --help\n :param help_option:\n :param capfd:\n :return:\n \"\"\"\n args = [__prog__, help_option]\n\n cli = get_cli_class()(args)\n\n with pytest.raises(SystemExit) as exception_info:\n cli.parse()\n\n out, err = capfd.readouterr()\n\n assert \"Make graph from your Playbook.\" in out\n\n\ndef test_cli_version(capfd):\n \"\"\"\n Test version printing\n :return:\n \"\"\"\n cli = get_cli_class()([__prog__, '--version'])\n with pytest.raises(SystemExit) as exception_info:\n cli.parse()\n\n out, err = capfd.readouterr()\n assert out == \"%s %s (with ansible %s)\\n\" % (__prog__, __version__, ansible_version)\n\n\n@pytest.mark.parametrize(\"save_dot_file_option, expected\",\n [(['--'], False), (['-s'], True), (['--save-dot-file'], True)],\n ids=['default', 'save-dot-file-short-option', 'save-dot-file-long-option'])\ndef test_cli_save_dot_file(save_dot_file_option, expected):\n \"\"\"\n Test for the save dot file option: -s, --save-dot-file\n :param save_dot_file_option:\n :param expected:\n :return:\n \"\"\"\n args = [__prog__] + save_dot_file_option + ['playbook.yml']\n\n cli = get_cli_class()(args)\n\n cli.parse()\n\n assert cli.options.save_dot_file == expected\n\n\n@pytest.mark.parametrize(\"output_filename_option, expected\",\n [(['--'], \"playbook\"), (['-o', 'output'], 'output'),\n (['--ouput-file-name', 'output'], 'output')],\n ids=['default', 'output-filename-short-option', 'output-filename-long-option'])\ndef test_cli_output_filename(output_filename_option, expected):\n \"\"\"\n Test for the output filename option: -o, --ouput-file-name\n :param output_filename_option:\n :param expected:\n :return:\n \"\"\"\n args = [__prog__] + output_filename_option + ['playbook.yml']\n\n cli = get_cli_class()(args)\n\n cli.parse()\n\n assert cli.options.output_filename == expected\n\n\n@pytest.mark.parametrize(\"include_role_tasks_option, expected\", [(['--'], False), (['--include-role-tasks'], True)],\n ids=['default', 'include'])\ndef test_cli_include_role_tasks(include_role_tasks_option, expected):\n \"\"\"\n Test for the include role tasks option: --include-role-tasks\n :param include_role_tasks_option:\n :param expected:\n :return:\n \"\"\"\n\n args = [__prog__] + include_role_tasks_option + ['playboook.yml']\n\n cli = get_cli_class()(args)\n\n cli.parse()\n\n assert cli.options.include_role_tasks == expected\n\n\n@pytest.mark.parametrize(\"tags_option, expected\",\n [(['--'], ['all']), (['-t', 'tag1'], ['tag1']),\n (['-t', 'tag1', '-t', 'tag2'], ['tag1', 'tag2']),\n (['-t', 'tag1,tag2'], ['tag1', 'tag2'])],\n ids=['no_tags_provided', 'one-tag', 'multiple-tags', 'multiple-tags2'])\ndef test_cli_tags(tags_option, expected):\n \"\"\"\n\n :param tags_option:\n :param expected:\n :return:\n \"\"\"\n args = [__prog__] + tags_option + ['playbook.yml']\n\n cli = get_cli_class()(args)\n\n cli.parse()\n\n # Ansible uses a set to construct the tags list. It may happen that the order of tags changes between two runs. As\n # the order of tags doesn't matter, I sorted them to avoid the test to fail\n assert sorted(cli.options.tags) == sorted(expected)\n\n\n@pytest.mark.parametrize(\"skip_tags_option, expected\",\n [(['--'], []), (['--skip-tags', 'tag1'], ['tag1']),\n (['--skip-tags', 'tag1', '--skip-tags', 'tag2'], ['tag1', 'tag2']),\n (['--skip-tags', 'tag1,tag2'], ['tag1', 'tag2'])],\n ids=['no_skip_tags_provided', 'one-skip-tag', 'multiple-skip-tags', 'multiple-skip-tags2'])\ndef test_skip_tags(skip_tags_option, expected):\n \"\"\"\n\n :param tags_option:\n :param expected:\n :return:\n \"\"\"\n args = [__prog__] + skip_tags_option + ['playbook.yml']\n\n cli = get_cli_class()(args)\n\n cli.parse()\n\n # Ansible uses a set to construct the tags list. It may happen that the order of tags changes between two runs. As\n # the order of tags doesn't matter, I sorted them to avoid the test to fail\n assert sorted(cli.options.skip_tags) == sorted(expected)\n\n\ndef test_cli_no_playbook():\n \"\"\"\n Test with no playbook provided\n :return:\n \"\"\"\n args = [__prog__]\n\n cli = get_cli_class()(args)\n\n with pytest.raises(AnsibleOptionsError) as exception_info:\n cli.parse()\n\n assert \"You must specify a playbook file to graph.\" in exception_info.value.message\n\n\ndef test_cli_multiple_playbooks():\n \"\"\"\n Test with multiple playbooks provided\n :return:\n \"\"\"\n args = [__prog__, 'playbook1.yml', 'playbook2.yml']\n\n cli = get_cli_class()(args)\n\n with pytest.raises(AnsibleOptionsError) as exception_info:\n cli.parse()\n\n assert \"You must specify only one playbook file to graph\" in exception_info.value.message\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"109359751","text":"# Author:zhang\n# -*- coding:utf-8 -*-\nclass School(object):\n def __init__(self, name, addr):\n self.name = name\n self.addr = addr\n self.students = []\n self.staffs = []\n self.course = []\n self.gradge = []\n\n def hire(self, staff_obj):\n print(\"雇佣新员工 %s\" % staff_obj.name)\n print(\"XXXXXXXXXXXXXX\")\n self.staffs.append(staff_obj)\n\n def enroll(self, stu_obj):\n print(\"为 %s 办理注册额手续\" % stu_obj.name)\n self.students.append(stu_obj)\n\n def create_course(self, course_type, price, time):\n self.course.append(Course(course_type, price, time))\n\n def creart_gradge(self, gradge_level):\n self.gradge.append(Gradge(gradge_level))\n\n\nclass SchoolMember(object):\n def __init__(self, name, age, sex):\n self.name = name\n self.age = age\n self.sex = sex\n\n def tell(self):\n pass\n\n\nclass Teache(SchoolMember):\n def __init__(self, name, age, sex, salary, course):\n super(Teache, self).__init__(name, age, sex)\n self.salary = salary\n self.course = course\n\n def tell(self):\n print('''\n --- info_testint---\n name,%s\n age,%s\n sex,%s\n salary,%s\n course,%s\n ''' % (self.name, self.age, self.sex, self.salary, self.course)\n )\n\n def teach(self):\n print(\"%s is teaching course [%s]\" % (self.name, self.course))\n\n\nclass Student(SchoolMember):\n def __init__(self, name, age, sex, gradge_obj):\n super(Student, self).__init__(name, age, sex)\n self.gradeg_obj = gradge_obj\n\n def tell(self, school_obj):\n print('''\n ---info---\n name,%s\n age,%s\n sex,%s\n\n ''' % (school_obj.name, self.gradeg_obj.name, self.name, self.age, self.sex,)\n )\n\n def pay_tuiton(self, amount):\n print(\"%s has paid tution for %s\" % (self.name, amount))\n\n\nclass Course(School):\n def __init__(self, type, price, time):\n self.type = type\n self.price = price\n self.time = time\n\n\nclass Gradge(object):\n def __init__(self, gradge_level, couser_type):\n self.gradge_level = gradge_level\n self.couser_type = couser_type\n\n def student_entroll(self,student_obj):\n print()\n\n\nschool = School(\"老男孩\", \"沙河\")\nt1 = Teache(\"老男孩\", \"55\", \"MF\", \"20000\", \"linux\")\nt2 = Teache(\"Alex\", \"22\", \"M\", \"300\", \"PythonDelovps\")\n\ns1 = Student(\"陈荣华\", \"36\", \"MF\", \"1001\", \"Pythondevlops\")\ns2 = Student(\"xulianwei\", \"22\", \"M\", \"1002\", \"Pythondevlops\")\nt1.tell()\ns1.tell()\nschool.enroll(s1)\nschool.hire(t1)\nprint(school.students)\nprint('---------8888')\n\nprint('999999999')\nschool.staffs[0].tell()\nschool.staffs[0].teach()\n","sub_path":"review_code/day6/jicheng_school.py","file_name":"jicheng_school.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"335283078","text":"# -*- coding: utf-8 -*-\n\nimport re\n\n\nclass PotentialPattern:\n \"\"\"\n Defines a PotentialPattern, which is not yet finished parsing.\n \"\"\"\n\n def __init__(self, current_line_number, pattern_line_number, position, completed):\n \"\"\"\n :param current_line_number: int\n :param pattern_line_number: int\n :param position: int\n :param completed: bool\n \"\"\"\n self.current_line_number = current_line_number\n self.pattern_line_number = pattern_line_number\n self.position = position\n self.completed = completed\n\n\nclass PatternParser:\n \"\"\"\n Parses a pattern and provides method parse_text to find patterns in a list of lines (from file iteration)\n \"\"\"\n\n # TO DO: add Flags support\n def __init__(self, search_pattern, use_regex=False):\n \"\"\"\n Initialises PatternParser with new pattern\n\n :param search_pattern: str either not compiled regex or simple string\n :param use_regex: bool whether to escape the string for use in regex or not\n \"\"\"\n\n self.use_regex = use_regex\n\n self.potential_patterns = dict()\n self.found_patterns = set()\n self.current_text_line = ''\n self.current_text_line_number = 0\n\n self.search_pattern_lines = search_pattern.splitlines()\n self.number_of_search_pattern_lines = len(self.search_pattern_lines) - 1 # indexing\n\n # We will use regex for search anyway, so escape it if it is not meant to be a regex\n if not self.use_regex:\n self.search_pattern_lines = [re.escape(search_pattern_line) for search_pattern_line in\n self.search_pattern_lines]\n self._create_search_objects()\n self.current_text_line_number = 0\n\n def reset(self):\n \"\"\"\n Use, if you start new text\n\n :return:\n \"\"\"\n self.potential_patterns = dict()\n self.found_patterns = set()\n self.current_text_line = ''\n\n def _create_search_objects(self):\n \"\"\"\n Method that creates pattern objects like re.compile and sets self.search_pattern_lines to it\n\n Overwrite in child classes, if you wish different behavior.\n See cls._evaluate_search_objects and cls._parse_first_line before!\n\n :return:\n \"\"\"\n self.search_pattern_lines = [re.compile(search_pattern_line) for search_pattern_line in\n self.search_pattern_lines]\n\n def _evaluate_search_objects(self, text, pattern_line_number, position):\n \"\"\"\n Method that evaluates text + search object, for example re.compile('a').match('a')\n\n You can use this method to override the default search functionality in child classes.\n\n Be aware, that if you do so, you may need to change cls._create_search_objects and cls._parse_first_line as well\n\n :param text: str The string unit aka line to be searched for\n :param pattern_line_number: int The line number of the current PotentialPattern\n :param position: int The position in text where to look\n :return: Bool or None. None: The patterns is not continuing. None: The patterns is not finished\n \"\"\"\n\n search_object = self.search_pattern_lines[pattern_line_number]\n match_object = search_object.match(text, position)\n\n if match_object is None:\n return False # The patterns is not continuing\n if pattern_line_number < self.number_of_search_pattern_lines and match_object:\n return None # The patterns is not finished\n if pattern_line_number is self.number_of_search_pattern_lines and match_object:\n return True # The patterns is completed\n else:\n raise Exception(u\"Error in Logic. Please go debugging\") # No clue what is going on – debug!\n # TO DO: Add more meaningful exception\n\n def _parse_first_lines(self):\n \"\"\"\n Finds occurrences of first line of pattern and populates self.potential_patterns with PotentialPatterns\n\n Works first come first save – so with pattern\n\n x\n y\n x\n\n and text\n\n x\n y\n x\n y\n x\n\n only one (the first) occurrence will be found\n\n x\n y\n x x\n y\n x\n\n will work however\n\n \"\"\"\n\n first_line_pattern = self.search_pattern_lines[0]\n start = 0\n while True:\n match = first_line_pattern.search(self.current_text_line, start)\n if match is None:\n break\n position = match.start()\n if position not in self.potential_patterns: # Assuming First come, first serve\n self.potential_patterns[position] = PotentialPattern(\n current_line_number=self.current_text_line_number,\n pattern_line_number=0,\n position=position,\n completed=None,\n )\n start = match.end()\n\n def _continue_parsing_potential_objects(self):\n \"\"\"\n Takes the outcome of cls._evaluate_search_objects and administers it\n :return: int found completed patterns\n \"\"\"\n\n positions_to_remove = set()\n found = 0\n\n for position, potential_pattern in self.potential_patterns.items():\n\n result = self._evaluate_search_objects(\n text=self.current_text_line,\n pattern_line_number=potential_pattern.pattern_line_number,\n position=potential_pattern.position\n )\n\n if result is False:\n positions_to_remove.add(position) # Pattern did not continue - remove\n continue\n if result is None:\n potential_pattern.pattern_line_number += 1\n continue # Go up one line in pattern\n if result is True:\n potential_pattern.completed = True\n found += 1\n positions_to_remove.add(position) # pattern is finished - count and free slot\n self.found_patterns.add(position) # log\n continue\n\n self.potential_patterns = {position: self.potential_patterns[position] for position in\n self.potential_patterns.keys() if position not in positions_to_remove}\n\n return found\n\n def parse_text(self, text_line):\n \"\"\"\n Use to parse line from the text, where you are searching your patterns in it.\n :param text_line: the unit of text to look in\n :return: int found completed patterns\n \"\"\"\n self.current_text_line = text_line\n self._parse_first_lines()\n found = self._continue_parsing_potential_objects()\n self.current_text_line_number += 1\n return found\n","sub_path":"textpatternrecognition/pattern.py","file_name":"pattern.py","file_ext":"py","file_size_in_byte":6840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"10462493","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/5/31 PM2:37\n# @Author : Qiming Zhang\n# @File : LongestHarmoniousSubsequence\nimport collections\nclass Solution(object):\n def findLHS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dict = collections.Counter(nums)\n result = 0\n for d in dict.keys():\n if d + 1 in dict:\n result = max(result, dict[d] + dict[d + 1])\n return result\n","sub_path":"HashTable/LongestHarmoniousSubsequence.py","file_name":"LongestHarmoniousSubsequence.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"554827369","text":"\n\nfrom xai.brain.wordbase.verbs._procure import _PROCURE\n\n#calss header\nclass _PROCURING(_PROCURE, ):\n\tdef __init__(self,): \n\t\t_PROCURE.__init__(self)\n\t\tself.name = \"PROCURING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"procure\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_procuring.py","file_name":"_procuring.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"47002218","text":"import httplib\nimport functools\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import IntegrityError\n\nfrom framework.auth.decorators import must_be_signed\n\nfrom framework.exceptions import HTTPError\n\nfrom addons.osfstorage.models import OsfStorageFileNode, OsfStorageFolder\nfrom osf.models import OSFUser, AbstractNode\nfrom website.files import exceptions\nfrom website.project.decorators import (\n must_not_be_registration, must_have_addon,\n)\n\ndef handle_django_errors(func):\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except ObjectDoesNotExist:\n raise HTTPError(httplib.NOT_FOUND)\n except IntegrityError:\n raise HTTPError(httplib.CONFLICT)\n except exceptions.VersionNotFoundError:\n raise HTTPError(httplib.NOT_FOUND)\n return wrapped\n\ndef autoload_filenode(must_be=None, default_root=False):\n \"\"\"Implies both must_have_addon osfstorage node and\n handle_odm_errors\n Attempts to load fid as a OsfStorageFileNode with viable constraints\n \"\"\"\n def _autoload_filenode(func):\n @handle_django_errors\n @must_have_addon('osfstorage', 'node')\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n node = kwargs['node']\n\n if 'fid' not in kwargs and default_root:\n file_node = kwargs['node_addon'].get_root()\n else:\n file_node = OsfStorageFileNode.get(kwargs.get('fid'), node)\n\n if must_be and file_node.kind != must_be:\n raise HTTPError(httplib.BAD_REQUEST, data={\n 'message_short': 'incorrect type',\n 'message_long': 'FileNode must be of type {} not {}'.format(must_be, file_node.kind)\n })\n\n kwargs['file_node'] = file_node\n\n return func(*args, **kwargs)\n\n return wrapped\n return _autoload_filenode\n\n\ndef waterbutler_opt_hook(func):\n\n @must_be_signed\n @handle_django_errors\n @must_not_be_registration\n @must_have_addon('osfstorage', 'node')\n @functools.wraps(func)\n def wrapped(payload, *args, **kwargs):\n try:\n user = OSFUser.load(payload['user'])\n dest_node = AbstractNode.load(payload['destination']['node'])\n source = OsfStorageFileNode.get(payload['source'], kwargs['node'])\n dest_parent = OsfStorageFolder.get(payload['destination']['parent'], dest_node)\n\n kwargs.update({\n 'user': user,\n 'source': source,\n 'destination': dest_parent,\n 'name': payload['destination']['name'],\n })\n except KeyError:\n raise HTTPError(httplib.BAD_REQUEST)\n\n return func(*args, **kwargs)\n return wrapped\n","sub_path":"addons/osfstorage/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"42022586","text":"import cv2 as cv\nimport numpy as np\n\ndef do_nothing(x):\n pass\n\n# Create a video capture object\ncapture = cv.VideoCapture(0)\n\n# Create a window and trackbars\nwinname = 'Canny Edge Detection'\ncv.namedWindow(winname)\ncv.createTrackbar('minVal', winname, 2000, 5000, do_nothing)\ncv.createTrackbar('maxVal', winname, 4000, 5000, do_nothing)\n\n# Infinite loop\nwhile True:\n # Read a video frame\n ret, frame = capture.read()\n\n if ret is False:\n print('Error: No image is captured!')\n break\n\n # Convert the frame to gray\n img_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n\n # Get the threshold values\n minVal = cv.getTrackbarPos('minVal', winname)\n maxVal = cv.getTrackbarPos('maxVal', winname)\n\n # Canny edge detection\n img_edge = cv.Canny(img_gray, minVal, maxVal, apertureSize=5)\n\n # Display result\n img_vis = frame.copy()\n img_vis = np.uint8(img_vis/2.)\n img_vis[img_edge != 0] = (0, 255, 0)\n cv.imshow(winname, img_vis)\n ch = cv.waitKey(5)\n if ch == 27:\n break\n\ncv.destroyAllWindows()\n","sub_path":"11_image_gradients/06_canny_edge_detection_video.py","file_name":"06_canny_edge_detection_video.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"328479843","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\n\"\"\"\n给定两个数组,编写一个函数来计算它们的交集。\n\n \n\n示例 1:\n\n输入:nums1 = [1,2,2,1], nums2 = [2,2]\n输出:[2]\n示例 2:\n\n输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]\n输出:[9,4]\n \n\n说明:\n\n输出结果中的每个元素一定是唯一的。\n我们可以不考虑输出结果的顺序。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/intersection-of-two-arrays\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\n\nimport doctest\nfrom typing import List\n\n\nclass Solution:\n \"\"\"\n >>> s = Solution()\n >>> s.intersection([1, 2, 2, 1], [2, 2])\n [2]\n >>> s.intersection([4, 9, 5], [9, 4, 9, 8, 4])\n [9, 4]\n \"\"\"\n\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \"\"\"\n hash升级,直接使用set\n \"\"\"\n result_set = set()\n set1 = set(nums1)\n\n for num in nums2:\n if num in set1:\n result_set.add(num) # set1里出现的nums2元素 存放到结果\n return list(result_set)\n\n def intersection2(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \"\"\"\n 使用hash来做\n \"\"\"\n hash_map, ret = {}, []\n for i in nums1:\n if not i in hash_map:\n hash_map[i] = 0\n\n for i in nums2:\n if i in hash_map:\n ret.append(i)\n del hash_map[i]\n return ret\n\n def intersection3(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \"\"\"\n 使用内置函数\n 先转换为集合,求交集之后再转换为数组\n \"\"\"\n # 或者符号运算: list(set(nums1) & set(nums2))\n return list(set(nums1).intersection(set(nums2)))\n\n\nif __name__ == '__main__':\n doctest.testmod()\n","sub_path":"algorithms/leetcode/easy/0349_两个数组的交集.py","file_name":"0349_两个数组的交集.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"162581422","text":"import scrapy\nfrom scrapy.http.request import Request\nfrom house_price.items import *\n\nclass DmozSpider(scrapy.Spider):\n name = \"dmoz\"\n allowed_domains = [\"http://shanghai.anjuke.com\"]\n max_page = 17\n\n def start_requests(self):\n \tfor i in range(self.max_page):\n yield Request('http://shanghai.anjuke.com/community/props/sale/8461/p%d/#filtersort' % i,\n callback=self.parse)\n \n\n def parse(self, response):\n for sel in response.xpath('//div[@class=\"details\"]'):\n item = HousePriceItem()\n item['title'] = sel.xpath('p[@class=\"title\"]/span/text()').extract()\n item['size'] = sel.xpath('p[@class=\"para\"]/span[1]/text()').extract()\n item['structure'] = sel.xpath('p[@class=\"para\"]/span[2]/text()').extract()\n item['price'] = sel.xpath('p[@class=\"para\"]/span[3]/text()').extract()\n item['position'] = sel.xpath('p[@class=\"para\"]/span[4]/text()').extract()\n yield item\n","sub_path":"house_price/spiders/dmoz_spider.py","file_name":"dmoz_spider.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"653567943","text":"import collections\nimport itertools\nimport types\n\ntry:\n import graphviz\n GRAPHVIZ_INSTALLED = True\nexcept ImportError:\n GRAPHVIZ_INSTALLED = False\n\nfrom sklearn.utils import metaestimators\n\nfrom .. import base\n\nfrom . import func\nfrom . import union\n\n\n__all__ = ['Pipeline']\n\n\nclass Pipeline(collections.OrderedDict):\n \"\"\"Chains a sequence of estimators.\n\n Sequentially apply a list of estimators. Pipelines helps to define machine learning systems in a\n declarative style, which makes a lot of sense when we think in a stream manner. For further\n information and practical examples, take a look at the\n `user guide <../notebooks/the-art-of-using-pipelines.html>`_.\n\n Parameters:\n steps (list): Ideally a list of (name, estimator) tuples. If an estimator is given without\n a name then a name is automatically inferred from the estimator.\n\n Example:\n\n ::\n\n >>> from creme import compose\n >>> from creme import feature_extraction\n >>> from creme import linear_model\n >>> from creme import preprocessing\n\n >>> tfidf = feature_extraction.TFIDFVectorizer('text')\n >>> counts = feature_extraction.CountVectorizer('text')\n >>> text_part = compose.Whitelister('text') | (tfidf + counts)\n\n >>> num_part = compose.Whitelister('a', 'b') | preprocessing.PolynomialExtender()\n\n >>> model = text_part + num_part\n >>> model |= preprocessing.StandardScaler()\n >>> model |= linear_model.LinearRegression()\n\n >>> dot = model.draw()\n\n .. image:: ../_static/pipeline_docstring.svg\n :align: center\n\n \"\"\"\n\n def __init__(self, steps=None):\n if steps is not None:\n for step in steps:\n self |= step\n\n def __or__(self, other):\n \"\"\"Inserts a step at the end of the pipeline.\"\"\"\n self.add_step(other, at_start=False)\n return self\n\n def __ror__(self, other):\n \"\"\"Inserts a step at the start of the pipeline.\"\"\"\n self.add_step(other, at_start=True)\n return self\n\n def __add__(self, other):\n \"\"\"Merges with another Pipeline or TransformerUnion into a TransformerUnion.\"\"\"\n if isinstance(other, union.TransformerUnion):\n return other.__add__(self)\n return union.TransformerUnion([self, other])\n\n def __str__(self):\n \"\"\"Return a human friendly representation of the pipeline.\"\"\"\n return ' | '.join(self.keys())\n\n @property\n def __class__(self):\n \"\"\"Returns the class of the final estimator for type checking purposes.\n\n A Pipeline is semantically equivalent to it's final estimator in terms of usage. This is\n mostly used for deceiving the ``isinstance`` method.\n\n \"\"\"\n return self.final_estimator.__class__\n\n @property\n def transformers(self):\n \"\"\"If a pipeline has $n$ steps, then the first $n-1$ are necessarily transformers.\"\"\"\n if isinstance(self.final_estimator, base.Transformer):\n return self.values()\n return itertools.islice(self.values(), len(self) - 1)\n\n @property\n def is_supervised(self):\n \"\"\"Only works if all the steps of the pipelines are transformers.\"\"\"\n return any(transformer.is_supervised for transformer in self.values())\n\n def add_step(self, step, at_start):\n \"\"\"Adds a step to either end of the pipeline while taking care of the input type.\"\"\"\n\n # Infer a name if none is given\n if not isinstance(step, (list, tuple)):\n step = (str(step), step)\n\n name, estimator = step\n\n # If a function is given then wrap it in a FuncTransformer\n if isinstance(estimator, types.FunctionType):\n name = estimator.__name__\n estimator = func.FuncTransformer(estimator)\n\n # Check if an identical step has already been inserted\n if name in self:\n raise KeyError(f'{name} already exists')\n\n # Instantiate the estimator if it hasn't been done\n if isinstance(estimator, type):\n estimator = estimator()\n\n # Store the step\n self[name] = estimator\n\n # Move the step to the start of the pipeline if so instructed\n if at_start:\n self.move_to_end(step[0], last=False)\n\n @property\n def final_estimator(self):\n \"\"\"The final estimator.\"\"\"\n return self[next(reversed(self))]\n\n def fit_one(self, x, y=None):\n \"\"\"Fits each step with ``x``.\"\"\"\n\n # Loop over the first n - 1 steps, which should all be transformers\n for t in itertools.islice(self.values(), len(self) - 1):\n x_pre = x\n x = t.transform_one(x)\n\n # If a transformer is supervised then it has to be updated\n if t.is_supervised:\n\n if isinstance(t, union.TransformerUnion):\n for sub_t in t.values():\n if sub_t.is_supervised:\n sub_t.fit_one(x_pre, y)\n\n else:\n t.fit_one(x_pre, y)\n\n self.final_estimator.fit_one(x, y)\n return self\n\n def transform_one(self, x):\n \"\"\"Transform an input.\n\n Only works if each estimator has a ``transform_one`` method.\n\n \"\"\"\n for transformer in self.transformers:\n\n if isinstance(transformer, union.TransformerUnion):\n\n # Fit the unsupervised part of the union\n for sub_transformer in transformer.values():\n if not sub_transformer.is_supervised:\n sub_transformer.fit_one(x)\n\n elif not transformer.is_supervised:\n transformer.fit_one(x)\n\n x = transformer.transform_one(x)\n\n return x\n\n @metaestimators.if_delegate_has_method(delegate='final_estimator')\n def predict_one(self, x):\n \"\"\"Predict output.\n\n Only works if each estimator has a ``transform_one`` method and the final estimator has a\n ``predict_one`` method.\n\n \"\"\"\n x = self.transform_one(x)\n return self.final_estimator.predict_one(x)\n\n @metaestimators.if_delegate_has_method(delegate='final_estimator')\n def predict_proba_one(self, x):\n \"\"\"Predicts probabilities.\n\n Only works if each estimator has a ``transform_one`` method and the final estimator has a\n ``predict_proba_one`` method.\n\n \"\"\"\n x = self.transform_one(x)\n return self.final_estimator.predict_proba_one(x)\n\n def debug_one(self, x, show_types=True):\n \"\"\"Displays the state of a set of features as it goes through the pipeline.\n\n Parameters:\n x (dict) A set of features.\n show_types (bool): Whether or not to display the type of feature along with it's value.\n\n \"\"\"\n def print_features(x, indent=False, space_after=True):\n for k, v in x.items():\n type_str = f' ({type(v).__name__})' if show_types else ''\n print(('\\t' if indent else '') + f'{k}: {v}' + type_str)\n if space_after:\n print()\n\n def print_title(title, indent=False):\n print(('\\t' if indent else '') + title)\n print(('\\t' if indent else '') + '-' * len(title))\n\n # Print the initial state of the features\n print_title('0. Input')\n print_features(x)\n\n for i, t in enumerate(self.transformers):\n if isinstance(t, union.TransformerUnion):\n print_title(f'{i+1}. Transformer union')\n for j, (name, sub_t) in enumerate(t.items()):\n print_title(f'{i+1}.{j} {name}', indent=True)\n print_features(sub_t.transform_one(x), indent=True)\n x = t.transform_one(x)\n print_features(x)\n else:\n print_title(f'{i+1}. {t}')\n x = t.transform_one(x)\n print_features(x)\n\n # Print the predicted output from the final estimator\n final = self.final_estimator\n if not isinstance(final, base.Transformer):\n print_title(f'{len(self)}. {final}')\n\n if hasattr(final, 'debug_one'):\n final.debug_one(x)\n print()\n\n if isinstance(final, base.Classifier):\n print_features(final.predict_proba_one(x), space_after=False)\n else:\n print(final.predict_one(x))\n\n def draw(self):\n \"\"\"Draws the pipeline using the ``graphviz`` library.\"\"\"\n\n if not GRAPHVIZ_INSTALLED:\n raise ImportError('graphviz is not installed')\n\n def get_first_estimator(d):\n \"\"\"Gets first estimator key of a Pipeline or TransformerUnion.\"\"\"\n\n for first_key in d.keys():\n first_step = d.get(first_key)\n break\n\n if isinstance(first_step, (Pipeline, union.TransformerUnion)):\n # Recurse\n first_key = get_first_estimator(first_step)\n\n return first_key\n\n def draw_step(node, previous_node):\n \"\"\"Draws a node and its previous edge.\"\"\"\n if node in nodes:\n node = node + '_'\n return draw_step(node, previous_node)\n\n graph.node(node, node.rstrip('_'))\n graph.edge(previous_node, node)\n nodes.append(node)\n edges.append(previous_node)\n\n def draw_steps(d=self, skip_first=False):\n \"\"\"Draws all estimators graph nodes and edges.\"\"\"\n\n union_ending_node_ix = None\n\n for name, step in d.items():\n\n if skip_first:\n skip_first = False\n continue\n\n # If step is a Pipeline recurse on step\n if isinstance(step, Pipeline):\n draw_steps(step)\n\n # If step is a TransformerUnion, dive inside\n elif isinstance(step, union.TransformerUnion):\n\n node_before_union = nodes[-1]\n\n # Draw each TransformerUnion steps\n for sub_name, sub_step in step.items():\n\n # If sub step is another nested step, draw its first estimator and recurse\n if isinstance(sub_step, (Pipeline, union.TransformerUnion)):\n sub_sub_key = get_first_estimator(sub_step)\n draw_step(node=sub_sub_key, previous_node=node_before_union)\n draw_steps(d=sub_step, skip_first=True)\n # Else just draw it\n else:\n draw_step(node=sub_name, previous_node=node_before_union)\n\n union_ending_node_ix = len(nodes)\n\n else:\n draw_step(name, nodes[-1])\n\n # If previous step was a TransformerUnion and following node have been drawn\n if union_ending_node_ix == len(nodes) - 1:\n # Connect TransformerUnion child nodes with the next step\n for node in nodes[1: -1]:\n if node not in edges:\n graph.edge(node, nodes[union_ending_node_ix])\n edges.append(node)\n # Reset TransformerUnion flag\n union_ending_node_ix = None\n\n nodes, edges = ['x'], []\n graph = graphviz.Digraph()\n graph.node('x')\n\n draw_steps()\n\n graph.node('y')\n graph.edge(nodes[-1], 'y')\n\n return graph\n","sub_path":"creme/compose/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":11634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"315080210","text":"import spotipy\r\nfrom spotipy.oauth2 import SpotifyClientCredentials\r\nimport requests\r\n\r\nclient_credentials_manager = SpotifyClientCredentials(client_id='c12ed8a6c3874da7ac31ed2af10a7a85', client_secret='02a365059142471a9ae7411ad0ecda78')\r\nsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\r\n\r\nresults = sp.track('5WHTFyqSii0lmT9R21abT8')\r\nprint(results)\r\n\r\ntoken = client_credentials_manager.get_access_token()\r\n\r\nanalysis = requests.get('https://api.spotify.com/v1/audio-analysis/5WHTFyqSii0lmT9R21abT8', headers={'Authorization': 'Bearer ' + token})\r\nprint(analysis.content)\r\nfeatures = requests.get('https://api.spotify.com/v1/audio-features/5WHTFyqSii0lmT9R21abT8', headers={'Authorization': 'Bearer ' + token})\r\nprint('\\n', features.content)","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"634385637","text":"import socket\nserver = socket.socket()\ninput_name = input(\"Enter the host/ip name =>\")\nif input_name == \"mohsen\" :\n host = \"192.168.1.36\"\nelse :\n host = input_name\nport = 8080\nserver.connect((host,port))\nprint(\"You connected to the server sucssefully\")\nusername = input(\"Enter your username => \")\nusername = username.encode()\nserver.send(username)\n###########################\nfile_name = input(\"enter you file name =>\")\nfile = open(file_name , \"wb\")\nfile_data = server.recv(999999999)\nfile.write(file_data)\nfile.close()\nprint(\"file as recived succesfully\")\n","sub_path":"file transfer/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"620081422","text":"from django.db import models\nfrom django.urls import reverse\n\nfrom account.models import UserManager, Users\nfrom utility.models import PersonalInformation, BaseModel\n\n\nclass CustomerServiceManager(UserManager):\n \"\"\"\n Custom manager to deal with all Customer Service entity\n \"\"\"\n\n def get_queryset(self):\n \"\"\"\n override default queryset\n \"\"\"\n return super(CustomerServiceManager, self).get_queryset().filter(role=3)\n\n def create_user(self, **extra_fields):\n \"\"\"\n set role for this entity\n and make entity staff\n \"\"\"\n extra_fields.setdefault('role', 3)\n extra_fields.setdefault('is_staff', True)\n return super(CustomerServiceManager, self).create_user(**extra_fields)\n\n\nclass CustomerServes(Users):\n \"\"\"\n Customer Serves Proxy class\n \"\"\"\n\n objects = CustomerServiceManager()\n\n class Meta:\n proxy = True\n\n\nclass Profile(PersonalInformation, BaseModel):\n user = models.OneToOneField('customer_service.CustomerServes', on_delete=models.CASCADE, related_name='agent')\n branch = models.ForeignKey('center.Branch', on_delete=models.CASCADE, related_name='agent')\n department = models.ManyToManyField('center.Department', related_name='agent')\n\n def get_absolute_url(self):\n return reverse(\"customer_service:profile_overview\", kwargs={\"pk\": self.pk})\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"587893053","text":"import unittest\nfrom dz import get_html\n\n\nclass MyTestCase(unittest.TestCase):\n def test_html_page(self):\n request = get_html(\"https://panorama.pub\")\n self.assertNotEqual(request, 0)\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_get_html_page.py","file_name":"test_get_html_page.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"598289057","text":"import requests\nfrom requests.auth import HTTPBasicAuth\nimport json\nfrom testrail import *\nfrom unittest import TestCase\nimport unittest\nimport datetime\nfrom base_test_case import BaseTestCase\nfrom base_test_case import TestData\nfrom OrgAPI.precondition_org_api_test_case import AA_OrganizationApiTestCase\n\nclass AD_OrganizationMembersTestCase(BaseTestCase):\n\n def test_01_get_actions_organization_member_by_id(self):\n\n TestData.case_id = \"621349\"\n response = self.get_from_API_org(url=\"/organizationMembers/\"+BaseTestCase.orgMemberId+\"/actions\", token=TestData.analyst_token)\n self.assert_Equal(response.status_code, 200)\n self.saveResponses(response)\n self.assertTrue(response.text)\n# {{base_url}}/organizationMembers?email=blastmotionqa%2Bstudent_1518904013162%40gmail.com\n\n def test_02_get_organization_member_by_email(self):\n\n TestData.case_id = \"655739\"\n response = self.get_from_API_org(url=\"/organizationMembers?email=\"+BaseTestCase.player_username_http, token=TestData.admin_token)\n self.assert_Equal(response.status_code, 200)\n self.saveResponses(response)\n self.assertTrue(response.text)\n\n def test_03_get_organization_member_by_userId(self):\n\n TestData.case_id = \"655740\"\n response = self.get_from_API_org(url=\"/organizationMembers?userId=\"+BaseTestCase.userId, token=TestData.admin_token)\n self.assert_Equal(response.status_code, 200)\n self.saveResponses(response)\n self.assertTrue(response.text)\n\n def test_04_get_organization_member_by_exId(self):\n TestData.case_id = \"655742\"\n response = self.get_from_API_org(url=\"/organizationMembers?externalId=1\", token=TestData.admin_token)\n self.assert_Equal(response.status_code, 200)\n self.saveResponses(response)\n self.assertTrue(response.text)\n\n def test_05_get_organization_member_by_orgId(self):\n TestData.case_id = \"655741\"\n response = self.get_from_API_org(url=\"/organizationMembers?organizationIdentifier=smoothie\", token=TestData.admin_token)\n self.assert_Equal(response.status_code, 200)\n self.saveResponses(response)\n self.assertTrue(response.text)\n","sub_path":"regression_tests/OrgAPI/organization_members_test_case.py","file_name":"organization_members_test_case.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"178077918","text":"import sys\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\ndef soft_update(target, source, tau):\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)\n\ndef hard_update(target, source):\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(param.data)\n\n\"\"\"\nFrom: https://github.com/pytorch/pytorch/issues/1959\nThere's an official LayerNorm implementation in pytorch now, but it hasn't been included in \npip version yet. This is a temporary version\nThis slows down training by a bit\n\"\"\"\nclass LayerNorm(nn.Module):\n def __init__(self, num_features, eps=1e-5, affine=True):\n super(LayerNorm, self).__init__()\n self.num_features = num_features\n self.affine = affine\n self.eps = eps\n\n if self.affine:\n self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())\n self.beta = nn.Parameter(torch.zeros(num_features))\n\n def forward(self, x):\n shape = [-1] + [1] * (x.dim() - 1)\n mean = x.view(x.size(0), -1).mean(1).view(*shape)\n std = x.view(x.size(0), -1).std(1).view(*shape)\n\n y = (x - mean) / (std + self.eps)\n if self.affine:\n shape = [1, -1] + [1] * (x.dim() - 2)\n y = self.gamma.view(*shape) * y + self.beta.view(*shape)\n return y\n\nnn.LayerNorm = LayerNorm\n\n\nclass Actor(nn.Module):\n def __init__(self, kernel_size):\n super(Actor, self).__init__()\n\n self.conv1 = nn.Conv2d(3, 16, kernel_size = kernel_size)\n self.conv2 = nn.Conv2d(16, 4, kernel_size = kernel_size)\n self.pool1 = nn.MaxPool2d(2, 2)\n\n\n self.conv1_ = nn.Conv2d(4, 16, kernel_size = kernel_size, stride = 2)\n self.conv2_ = nn.Conv2d(16, 3, kernel_size = kernel_size, stride = 2)\n\n\n def forward(self, inputs):\n x = inputs\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = self.pool1(x)\n x = F.relu(self.conv1_(x))\n mu = F.tanh(self.conv2_(x))\n return mu\n\nclass Critic_Conv(nn.Module):\n def __init__(self, kernel_size):\n super(Critic, self).__init__()\n\n self.conv1 = nn.Conv2d(3, 16, kernel_size = kernel_size)\n self.conv2 = nn.Conv2d(16, 4, kernel_size = kernel_size)\n self.pool1 = nn.MaxPool2d(2, 2)\n\n self.conv3 = nn.Conv2d(4, 16, kernel_size = kernel_size, stride = 2)\n self.conv4 = nn.Conv2d(16, 3, kernel_size = kernel_size, stride = 2)\n\n\n self.conv1_ = nn.Conv2d(3, 16, kernel_size = kernel_size)\n self.conv2_ = nn.Conv2d(16, 4, kernel_size = kernel_size)\n self.pool1_ = nn.MaxPool2d(2,2)\n self.conv3_ = nn.Conv2d(4, 16, kernel_size = kernel_size, stride = 2)\n self.conv4_ = nn.Conv2d(16, 3, kernel_size = kernel_size, stride = 2)\n\n self.conv = nn.Conv2d(3, 1, kernel_size = kernel_size, stride = 1)\n\n\n\n def forward(self, inputs, actions):\n x = inputs\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = self.pool1(x)\n x = F.relu(self.conv3(x))\n mu = F.tanh(self.conv4(x))\n \n x_ = actions\n x_ = self.conv1_(x_)\n x_ = F.relu(x_)\n x_ = self.conv2d_(x_)\n x_ = F.relu(x_)\n x_ = self.pool1_(x_)\n x_ = F.relu(self.conv3(x_))\n mu_ = F.tanh(self.conv4(x_))\n\n y = torch.sum(self.conv(mu_ + mu), 0) \n\n return y\n\nclass Critic_Mix(nn.Module):\n def __init__(self, input_size, hidden_size):\n super(Critic, self).__init__()\n \n self.conv1 = nn.Conv2d(3, 3, 1)\n self.conv2 = nn.Conv2d(3, 3, 1)\n\n self.linear1 = nn.Linear(3 * input_size[-1] * input_size[-2], hidden_size)\n self.ln1 = nn.LayerNorm(hidden_size)\n\n self.linear2 = nn.Linear(hidden_size + 3 * input_size[-1] * input_size[-2], hidden_size)\n self.ln2 = nn.LayerNorm(hidden_size)\n\n self.V = nn.Linear(hidden_size, 1)\n self.V.weight.data.mul_(0.1)\n self.V.bias.data.mul_(0.1)\n\n def forward(self, inputs, actions):\n x = self.conv1(inputs)\n x = x.view(x.size(0), -1) \n x = self.linear1(x)\n x = self.ln1(x)\n x = F.relu(x)\n\n y = self.conv2(actions)\n y = y.view(y.size(0), -1)\n x = self.linear2(torch.cat((x, y), 1))\n x = self.ln2(x)\n x = F.relu(x)\n V = self.V(x)\n return V\n\n\n\nclass DDPG(object):\n def __init__(self, gamma, tau, kernel_size, hidden_size, input_size, device):\n self.actor = Actor(kernel_size).to(device)\n self.actor_target = Actor(kernel_size).to(device)\n self.actor_optim = Adam(self.actor.parameters(), lr=1e-4)\n\n self.critic = Critic_Conv(kernel_size).to(device)\n self.critic_target = Critic_Conv(kernel_size).to(device)\n #self.critic = Critic(input_size, hidden_size).to(device)\n #self.critic_target = Critic(input_size, hidden_size).to(device)\n self.critic_optim = Adam(self.critic.parameters(), lr=1e-3)\n\n self.gamma = gamma\n self.tau = tau\n\n hard_update(self.actor_target, self.actor) # Make sure target is with the same weight\n hard_update(self.critic_target, self.critic)\n\n self.mask = None\n \n\n def select_action(self, state, action_noise=None):\n self.actor.eval()\n mu = self.actor((Variable(state)))\n\n self.actor.train()\n mu = mu.data\n\n if action_noise is not None:\n mu += torch.Tensor(action_noise.noise())\n action = mu.clamp(-1, 1)\n\n if action.size() != state.size():\n bg = 0.0 * state\n if self.mask is None:\n start = max(0, int((bg.size()[-2] - action.size()[-2])/2))\n end = start + min(action.size()[-2], bg.size()[-2])\n start_ = max(0, int((-action.size()[-1] + bg.size()[-1])/2))\n end_ = start_ + min(action.size()[-1], bg.size()[-1])\n self.mask = [start, end, start_, end_]\n else:\n start, end, start_, end_ = self.mask[:]\n bg[:, :, start: end, start_ : end_] = bg[..., start:end, start_: end_] + action\n action = bg\n return action\n\n\n def update_parameters(self, batch):\n state_batch = Variable(torch.cat(batch.state))\n action_batch = Variable(torch.cat(batch.action))\n reward_batch = Variable(torch.cat(batch.reward))\n mask_batch = Variable(torch.cat(batch.mask))\n next_state_batch = Variable(torch.cat(batch.next_state))\n \n next_action_batch = self.actor_target(next_state_batch)\n next_state_action_values = self.critic_target(next_state_batch, next_action_batch)\n\n reward_batch = reward_batch.unsqueeze(1)\n mask_batch = mask_batch.unsqueeze(1)\n expected_state_action_batch = reward_batch + (self.gamma * mask_batch * next_state_action_values)\n\n self.critic_optim.zero_grad()\n\n state_action_batch = self.critic((state_batch), (action_batch))\n\n value_loss = F.mse_loss(state_action_batch, expected_state_action_batch)\n value_loss.backward()\n self.critic_optim.step()\n\n self.actor_optim.zero_grad()\n\n policy_loss = -self.critic((state_batch),self.actor((state_batch)))\n\n policy_loss = policy_loss.mean()\n policy_loss.backward()\n self.actor_optim.step()\n\n soft_update(self.actor_target, self.actor, self.tau)\n soft_update(self.critic_target, self.critic, self.tau)\n\n return value_loss.item(), policy_loss.item()\n\n def perturb_actor_parameters(self, param_noise):\n \"\"\"Apply parameter noise to actor model, for exploration\"\"\"\n hard_update(self.actor_perturbed, self.actor)\n params = self.actor_perturbed.state_dict()\n for name in params:\n if 'ln' in name: \n pass \n param = params[name]\n param += torch.randn(param.shape) * param_noise.current_stddev\n\n def save_model(self, env_name, suffix=\"\", actor_path=None, critic_path=None):\n if not os.path.exists('models/'):\n os.makedirs('models/')\n\n if actor_path is None:\n actor_path = \"models/ddpg_actor_{}_{}\".format(env_name, suffix) \n if critic_path is None:\n critic_path = \"models/ddpg_critic_{}_{}\".format(env_name, suffix) \n print('Saving models to {} and {}'.format(actor_path, critic_path))\n torch.save(self.actor.state_dict(), actor_path)\n torch.save(self.critic.state_dict(), critic_path)\n\n def load_model(self, actor_path, critic_path):\n print('Loading models from {} and {}'.format(actor_path, critic_path))\n if actor_path is not None:\n self.actor.load_state_dict(torch.load(actor_path))\n if critic_path is not None: \n self.critic.load_state_dict(torch.load(critic_path))\n\n\nclass Value(nn.Module):\n def __init__(self, kernel_size, hidden_size):\n super(Value, self).__init__()\n \n self.conv1 = nn.Conv2d(3, 6, kernel_size)\n #self.conv2 = nn.Conv2d(6, 6, kernel_size)\n self.conv3 = nn.Conv2d(6, 1, kernel_size)\n\n self.V = nn.Linear(hidden_size, 1)\n self.V.weight.data.mul_(0.1)\n self.V.bias.data.mul_(0.1)\n\n def forward(self, inputs):\n x = self.conv1(inputs)\n x = F.relu(x)\n #x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n V = self.V(x.view(x.size(0), -1))\n return V\n\n\n\nclass VALUE(object):\n def __init__(self, gamma, tau, kernel_size, hidden_size, device):\n self.device = device\n self.critic = Value(kernel_size, hidden_size).to(self.device)\n self.critic_target = Value(kernel_size, hidden_size).to(self.device)\n self.critic_optim = Adam(self.critic.parameters(), lr=1e-3)\n hard_update(self.critic_target, self.critic)\n\n self.gamma = gamma\n self.tau = tau\n\n def select_action(self, state):\n self.critic.train()\n state_ = Variable(state).to(self.device)\n state_.requires_grad = True\n v = self.critic(state_)\n self.critic.zero_grad()\n v.backward(retain_graph = True)\n action = state_.grad.sign().detach_()\n return action\n\n\n def update_parameters(self, batch):\n state_batch = Variable(torch.cat(batch.state))\n reward_batch = Variable(torch.cat(batch.reward))\n next_state_batch = Variable(torch.cat(batch.next_state))\n \n next_state_action_values = self.critic_target(next_state_batch, next_action_batch)\n\n reward_batch = reward_batch.unsqueeze(1)\n expected_state_action_batch = reward_batch + (self.gamma * next_state_action_values)\n\n self.critic_optim.zero_grad()\n\n state_action_batch = self.critic((state_batch))\n\n value_loss = F.mse_loss(state_action_batch, expected_state_action_batch)\n value_loss.backward()\n self.critic_optim.step()\n\n soft_update(self.critic_target, self.critic, self.tau)\n\n return value_loss.item()\n\n def save_model(self, env_name, suffix=\"\", critic_path=None):\n if not os.path.exists('models/'):\n os.makedirs('models/')\n\n if critic_path is None:\n critic_path = \"models/value_critic_{}_{}\".format(env_name, suffix) \n print('Saving models to {} and {}'.format(critic_path))\n torch.save(self.critic.state_dict(), critic_path)\n\n def load_model(self, critic_path):\n print('Loading models from {} and {}'.format(critic_path))\n if critic_path is not None: \n self.critic.load_state_dict(torch.load(critic_path))\n","sub_path":"bird_view/models/ddpg.py","file_name":"ddpg.py","file_ext":"py","file_size_in_byte":11833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"606259623","text":"import EngineParts.Engine as Engine\nimport Thermos.Isentropics as Istrop\nimport Thermos.Shocks as Shock\nEngine = Engine.Engine\n\n\nclass Diffuser(Engine):\n \"\"\"\"\n This is the class responsible for modeling a diffuser.\n \"\"\"\n\n def __init__(self):\n self.gamma = 1.4\n self.efficiency = 1\n self.mach = 0\n self.p01 = None\n self.t01 = None\n\n def __init__(self, gamma=1.4, mach=0, efficiency=1):\n self.gamma = gamma\n self.efficiency = efficiency\n self.mach = mach\n self.p01 = None\n self.t01 = None\n\n def outlet_stagnation_pressure(self, pa):\n if self.p01 is None:\n rd = Shock.diffuser_shock_loss(self.mach)\n p0a = Istrop.pressure(None, pa, self.gamma, self.mach)\n self.p01 = rd * pa * ((self.efficiency * ((p0a / pa) ** ((self.gamma - 1) / self.gamma)\n - 1) + 1) ** (self.gamma / (self.gamma - 1)))\n return self.p01\n\n def outlet_stagnation_temperature(self, pa, ta):\n if self.p01 is None:\n self.outlet_stagnation_pressure(pa)\n self.t01 = Istrop.press2temp(None, ta, Istrop.pressure(None, pa, self.gamma, self.mach), pa, self.gamma)\n return self.t01\n\n def compute_outlet(self, pa, ta):\n return [self.outlet_stagnation_pressure(pa), self.outlet_stagnation_temperature(pa, ta)];\n\n","sub_path":"src/EngineParts/Diffuser.py","file_name":"Diffuser.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"617808959","text":"# Copyright 2015 Metaswitch Networks\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport json\n\nfrom nose.plugins.attrib import attr\n\nfrom test_base import TestBase\nfrom tests.st.utils.docker_host import DockerHost\n\n\nclass TestProfileCommands(TestBase):\n @attr('slow')\n def test_profile_commands(self):\n \"\"\"\n Test that the profile rule update command successfully updates.\n \"\"\"\n with DockerHost('host', start_calico=False) as host:\n\n host.calicoctl(\"profile add TEST_PROFILE\")\n\n json_dict = {\"id\": \"TEST_PROFILE\",\n \"inbound_rules\": [\n {\"action\": \"allow\",\n \"src_tag\": \"TEST_PROFILE\"},\n {\"action\": \"deny\"}\n ],\n \"outbound_rules\": [{\"action\": \"deny\",\n \"dst_net\": \"192.168.0.0/16\"},\n {\n \"action\": \"allow\"\n }]}\n\n update = json.dumps(json_dict)\n cmd = \"/code/dist/calicoctl profile TEST_PROFILE rule update\"\n host.execute(\"echo '%s' | %s\" % (update, cmd))\n\n self.assertIn('1 deny',\n host.calicoctl(\"profile TEST_PROFILE rule show\"))\n\n result = host.calicoctl(\"profile TEST_PROFILE rule json\")\n rules = json.loads(result)\n self.assertDictEqual(rules, json_dict)\n\n # Test that adding and removing a tag works.\n self.assertNotIn(\"TEST_TAG\", self.show_tag(host))\n host.calicoctl(\"profile TEST_PROFILE tag add TEST_TAG\")\n self.assertIn(\"TEST_TAG\", self.show_tag(host))\n host.calicoctl(\"profile TEST_PROFILE tag remove TEST_TAG\")\n self.assertNotIn(\"TEST_TAG\", self.show_tag(host))\n\n def show_tag(self, host):\n return host.calicoctl(\"profile TEST_PROFILE tag show\").rstrip()\n","sub_path":"calico_containers/tests/st/test_profile_commands.py","file_name":"test_profile_commands.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"545081645","text":"import random;\n#-------------------------------------------------------------------------------\n# Name: module_lab\n# Purpose:\n#\n# Author: Thog\n#\n# Created: 18/10/2014\n# Copyright: (c) Thog 2014\n# Licence: GNU GPL Version 3\n#-------------------------------------------------------------------------------\n\ndef charge_labyrinthe(nom) :\n \"\"\"\n Charge le labyrinthe a partir du fichier nom.txt\n nom : nom du fichier sans l'extension .txt\n Valeur de retour : liste contenant les donnees du labyrinthe\n \"\"\"\n print(\"Chargement du lab \" + nom + \"...\")\n try:\n file = open(nom + \".txt\", mode=\"r\")\n except IOError:\n print(\"Impossible d'ouvrir le fichier!\")\n exit(1)\n result = file.readlines()\n \n for i in range(len(result)):\n result[i] = result[i].strip()\n \n file.close()\n return result\n\ndef tresor(categorie, data) :\n \"\"\"\n Incremente le nombre de piece d’or en fonction du tresor\n categorie : type de tresor decouvert (1,2 ou 3)\n data : donnees du jeu (nb de pieces d’or, niveau, etc...)\n \"\"\"\n if(categorie == \"1\"):\n data['or'] += random.randint(1, 5);\n elif(categorie == \"2\"):\n data['or'] += random.randint(5, 10);\n elif(categorie == \"3\"):\n data['or'] += random.randint(0, 25);\n\n\ndef combat(data):\n \"\"\"\n Decremente la vie du joueur de manière aléatoire lors du combat\n data: donnees du jeu\n \"\"\"\n \n nb = random.randint(1, 3);\n if(nb == 1):\n data['vie'] -= random.randint(5, 10)\n elif(nb == 2):\n data['vie'] -= random.randint(1, 5)\n\ndef barre_score(data):\n \"\"\"\n Barre de score affichant les donnees du jeu\n data : données du jeu (nb de pièces d’or et niveau)\n Pas de valeur de retour\n \"\"\"\n print(\"Level: \" + str(data['niveau']) + \" Vie : \" + str(data['vie']) + \" Or: \" + str(data['or']))\n \n \ndef affiche_labyrinthe(lab, perso, pos_perso, tresor) :\n \"\"\"\n Affiche le labyrinthe\n lab : liste contenant le labyrinthe\n perso : caractère représentant le personnage\n pos_perso : liste contenant la position du personnage [ligne,colonne]\n tresor : caractère représentant le trésor affiché\n Pas de valeur retournée\n \"\"\"\n # Tant qu'il y a des lignes dans lab\n for index in range(len(lab)) :\n ligne = lab[index].replace(\"1\", tresor).replace(\"2\", tresor).replace(\"3\", tresor);\n \n # Afficher la ligne\n for i in range(len(ligne)) : \n if(i == pos_perso[0] and index == pos_perso[1]):\n print(perso, end=\"\")\n else :\n print(ligne[i], end=\"\")\n print(\"\", end=\"\\n\")\n\ndef verification_deplacement(lab, x, y, tresorChar, data):\n \"\"\"\n Indique si le dépalcement du personnage est valide ou pas\n lab : liste contenant le labyrinthe\n x : Nouvelle position sur les colonnes\n y : Nouvelle position sur les lignes\n data : données du jeu (nb de pièces d’or et niveau)\n Valeurs de retour :\n None : déplacement interdit\n [x, y] : liste contenant la nouvelle position autorisée\n \"\"\"\n\n # Recuperation de la ligne en fonction de y\n ligneY = lab[y]\n \n # Si le caractere corespond a la sortie du niveau\n if(ligneY[x] == \"O\"):\n return [-1, 1] \n # Sinon si tout aucune colision existe, retourne les coordonnees demande.\n elif(ligneY[x] != \"-\" and ligneY[x] != \"|\" and ligneY[x] != \"+\"):\n if(ligneY[x] == \"1\" or ligneY[x] == \"2\" or ligneY[x] == \"3\"):\n tresor(ligneY[x], data);\n # Avoid TypeError: 'str' object does not support item assignment by recreating the line\n lab[y] = ligneY[0:x] + \" \" + ligneY[x + 1:]; \n elif(ligneY[x] == \"$\"):\n combat(data);\n return [x, y]\n \n # Retourne par defaut un resultat null.\n return None\n\ndef choix_joueur(lab , pos, tresor, data):\n \"\"\"\n Incrémente le nombre de pièce d’or en fonction du trésor\n categorie : type de trésor découvert (1,2 ou 3)\n data : données du jeu (nb de pièces d’or et niveau)\n \"\"\"\n \n # Direction du joueur en minuscule\n dir = input(\" Quelle direction ?\").lower();\n \n # Copie des positions precedentes\n posDemand = [pos[0], pos[1]]\n \n # Verification du deplacement demande\n if(dir == \"b\"): \n posDemand[1] += 1\n elif(dir == \"h\"): \n posDemand[1] -= 1\n elif(dir == \"g\"):\n posDemand[0] -= 1\n elif(dir == \"d\"):\n posDemand[0] += 1\n else: print(\"Deplacement inconnu !\")\n \n # Verification des deplacement\n move = verification_deplacement(lab, posDemand[0], posDemand[1], tresor, data)\n \n # Deplacement valide\n if(move != None):\n return move\n \n # Sinon, renvoie les coordonnees d'origine\n else:\n print(\"Deplacement interdit !\") \n return pos\n\ndef jeu(level, data, num_niveau, perso, pos_perso, tresor):\n \"\"\"\n Affiche le labyrinthe et le personnage après chaque déplacement\n level : labyrinthe\n data : données du jeu (nb de pièces d’or et niveau)\n perso : caractère représentant le personnage\n pos_perso : liste contenant la position du personnage [ligne,colonne]\n tresor : caractère représentant le trésor affiché\n Pas de valeur retournée\n \"\"\"\n \n # Boucle infini\n while(1) :\n # Clean Console\n affiche_labyrinthe(level, perso, pos_perso, tresor)\n # Affiche le score\n barre_score(data)\n \n # Attend une entree du joueur et met a jour ses positions \n pos_perso = choix_joueur(level, pos_perso, tresor, data)\n \n # Si les positions sont les positons de fin alors\n if(pos_perso == [-1, 1]):\n print(\"Vous avez reussi le niveau !\")\n # Fin de la boucle\n break\n # Si la vie du joueur est inferieur ou egale a 0\n elif(data['vie'] <= 0):\n print(\"Vous etes mort !\")\n # Quitte le jeu\n exit(0)","sub_path":"TP5_continue/module_lab.py","file_name":"module_lab.py","file_ext":"py","file_size_in_byte":6122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"550390668","text":"import numpy as np\nfrom scipy.special import logsumexp\nfrom math import floor\n\nclass Layer:\n \"\"\"\n A building block. Each layer is capable of performing two things:\n\n - Process input to get output: output = layer.forward(input)\n\n - Propagate gradients through itself: grad_input = layer.backward(input, grad_output)\n\n Some layers also have learnable parameters which they update during layer.backward.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Here you can initialize layer parameters (if any) and auxiliary stuff.\n \"\"\"\n\n def forward(self, input):\n \"\"\"\n Takes input data of shape [batch, ...], returns output data [batch, ...]\n \"\"\"\n def backward(self, input, grad_output):\n \"\"\"\n Performs a backpropagation step through the layer, with respect to the given input. Updates layer parameters and returns gradient for next layer\n Let x be layer weights, output – output of the layer on the given input and grad_output – gradient of layer with respect to output\n\n To compute loss gradients w.r.t parameters, you need to apply chain rule (backprop):\n (d loss / d x) = (d loss / d output) * (d output / d x)\n Luckily, you already receive (d loss / d output) as grad_output, so you only need to multiply it by (d output / d x)\n If your layer has parameters (e.g. dense layer), you need to update them here using d loss / d x. The resulting update is a sum of updates in a batch.\n \n returns (d loss / d input) = (d loss / d output) * (d output / d input)\n \"\"\"\n\nclass ReLU(Layer):\n def __init__(self):\n \"\"\"\n ReLU layer simply applies elementwise rectified linear unit to all inputs\n This layer does not have any parameters.\n \"\"\"\n\n def forward(self, input):\n\n return input * (input > 0)\n\n def backward(self, input, grad_output):\n\n temp = np.zeros_like(input)\n temp[input > 0] = 1\n return grad_output * temp\n\n\nclass Dense(Layer):\n def __init__(self, input_units, output_units, learning_rate=0.1):\n\n self.learning_rate = learning_rate\n\n self.weights = np.random.normal(scale=np.sqrt(2.0 / (output_units + input_units)), \n size=(input_units, output_units))\n self.biases = np.random.normal(scale=np.sqrt(2.0 / output_units), size=output_units)\n\n def forward(self, input):\n\n return np.dot(input, self.weights) + self.biases\n\n def backward(self, input, grad_output):\n\n dx = np.dot(grad_output, self.weights.T)\n dw = input.T.dot(grad_output)\n db = np.sum(grad_output, axis=0)\n self.biases = self.biases - self.learning_rate * db\n self.weights = self.weights - self.learning_rate * dw\n return dx\n\nclass Conv2d(Layer):\n def __init__(self, in_channels, out_channels, kernel_size, learning_rate=0.1):\n\n self.learning_rate = learning_rate\n self.weights = np.random.normal(scale=np.sqrt(2.0 / ((in_channels + out_channels) / np.prod(kernel_size))), \n size=(in_channels, out_channels, kernel_size[0], kernel_size[1]))# array of shape [in_channels, out_channels, kernel_size, kernel_size]\n self.kernel_size = kernel_size\n\n def forward(self, input):\n\n N, C, H, W = input.shape\n _, F, HH, WW = self.weights.shape\n n_H = H - HH + 1\n n_W = W - WW + 1\n\n Z = np.zeros((N, F, n_H, n_W))\n \n for i in range(N):\n for c in range(F):\n for h in range(n_H):\n for w in range(n_W):\n slice = input[i, :, h : h + HH, w : w + WW]\n s = self.weights[:, c, :, :] * slice\n Z[i, c, h, w] = np.sum(s)\n return Z\n\n def backward(self, input, grad_output):\n\n N, C, H, W = input.shape\n _, F, HH, WW = self.weights.shape\n _, _, n_H, n_W = grad_output.shape\n dinp = np.zeros_like(input) \n dW = np.zeros_like(self.weights)\n \n for i in range(N):\n for c in range(F):\n for h in range(n_H):\n for w in range(n_W): \n slice = input[i, :, h : h + HH, w : w + WW]\n dinp[i, :, h : h + HH, w : w + WW] += self.weights[:, c, :, :] * grad_output[i, c, h, w]\n dW[:, c, :, :] += slice * grad_output[i, c, h, w]\n\n self.weights = self.weights - self.learning_rate * dW\n return dinp\n\n\nclass Maxpool2d(Layer):\n def __init__(self, kernel_size):\n\n self.stride = kernel_size\n self.kernel_size = kernel_size\n\n def forward(self, input):\n \n N, C, H, W = input.shape\n n_H = floor((H - self.kernel_size) / self.stride + 1)\n n_W = floor((W - self.kernel_size) / self.stride + 1)\n\n Z = np.zeros((N, C, n_H, n_W))\n \n for i in range(N):\n for c in range(C):\n for h in range(n_H):\n for w in range(n_W):\n slice = input[i, c, h * self.stride : h * self.stride + self.kernel_size,\n w * self.stride : w * self.stride + self.kernel_size]\n Z[i, c, h, w] = np.amax(slice)\n return Z\n\n def backward(self, input, grad_output):\n N, C, H, W = input.shape\n _, F, n_H, n_W = grad_output.shape\n dinp = np.zeros_like(input) \n \n for i in range(N):\n for c in range(F):\n for h in range(n_H):\n for w in range(n_W): \n slice = input[i, c, h * self.stride : h * self.stride + self.kernel_size, \n w * self.stride : w * self.stride + self.kernel_size]\n mask = (slice == np.amax(slice))\n dinp[i, c, h * self.stride : h * self.stride + self.kernel_size, \n w * self.stride : w * self.stride + self.kernel_size] += mask * grad_output[i, c, h, w]\n return dinp\n\n\nclass Flatten(Layer):\n def __init__(self):\n \"\"\"\n \"\"\"\n\n def forward(self, input):\n return input.reshape(input.shape[0], -1)\n\n def backward(self, input, grad_output):\n return grad_output.reshape(input.shape)\n\n\ndef softmax_crossentropy_with_logits(logits, y_true):\n \n max = np.max(logits, axis=1)\n matrix = logits - max[:, np.newaxis]\n log_exp = matrix[np.arange(len(y_true)), y_true]\n log_sum = logsumexp(matrix, axis=1)\n return np.sum(log_sum - log_exp) / len(y_true)\n \n\ndef grad_softmax_crossentropy_with_logits(logits, y_true):\n \n max = np.max(logits, axis=1)\n matrix = logits - max[:, np.newaxis]\n sum = np.exp(logsumexp(matrix, axis=1))\n ind = np.zeros_like(matrix)\n ind[np.arange(len(y_true)), y_true] = 1\n return (np.exp(matrix) / sum[:, np.newaxis] - ind) / len(y_true)","sub_path":"layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":7050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"520534434","text":"#il existe 3 types de variable sous python\n\nvariable1 = 5 #integer > int qui symbolise un nombre entier\nvariable2 = 3.2 # float > float qui symbolise un chiffre a virgule\nvariable3 = \"Coucou\" # string > str qui symbolise du texte \nvariable4 = True #boolean > bool symbolise une variable soit vrai \n #soir faux\nvariable5 = [\"1er\",\"2eme\",\"3eme\"] #list > une variable liste qui \n #comprend 3 string\n\n#première fonction qui permet d 'afficher du texte a l'écran\n\nprint(\"texte\",variable1, variable2, variable3, variable4)\n\n#Fonction permetant de connaitre le type d'une variable\nprint(type(variable1) )\n\ntypeDeVariable = type(variable1)\n\nprint(\"le type de la variable1 =\", typeDeVariable)\n\nvariable1 = str(variable1)\ntypeDeVariable = type(variable1)\ntypeDeVariable = type(variable1)\nprint(\"le type de la variable1 =\", typeDeVariable)\n\n# En python, il existe plusiseurs operateurs\n#addition > +\n# soustraction > -\n# multiplication > *\n# l'exposant > **\n# division > /\n# division entière > //\n# modulo > %","sub_path":"00_algorithmique/01_python/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"226710680","text":"#!/usr/bin/python3\n\n# This is a sample python script for sending notifications over pushover\n# Write your own script to add a new push service, and modify \n# api_push_script in zmeventnotification.ini to invoke that script\n\n# Example taken from https://support.pushover.net/i44-example-code-and-pushover-libraries#python\n\n# Arguments passed\n# ARG1 = event ID\n# ARG2 = monitor ID\n# ARG3 = monitor name\n# ARG4 = Alarm cause \n# ARG5 = type of event (event_start or event_end)\n# ARG6 (Optional) = image path\n\n# ===============================================================\n# MODIFY THESE\n# ===============================================================\n\n# Look at https://pushover.net/api and put anything you want here\n# just don't add image, title and message as it gets automatically\n# populated later\n\nparam_dict = {\n\n 'token': 'YOUR PUSHOVER APP TOKEN',\n 'user': 'YOUR PUSHOVER USER KEY',\n #'sound':'tugboat',\n #'priority': 0,\n # 'device': 'a specific device',\n # 'url': 'http://whateeveryouwant',\n # 'url_title': 'My URL title',\n\n \n}\n\n\n\n\n# ========== Don't change anything below here, unless you know what you are doing \n\nimport sys\nimport datetime\nimport requests\nimport pyzm.ZMLog as zmlog\nimport os\n\n# ES passes the image path, this routine figures out which image\n# to use inside that path\ndef get_image(path, cause):\n if os.path.exists(path+'/objdetect.jpg'):\n return path+'/objdetect.jpg'\n prefix = cause[0:2]\n if prefix == '[a]':\n return path+'/alarm.jpg'\n else:\n return path+'/snapshot.jpg'\n\n\n# -------- main \n\nzmlog.init(name='zmeventnotification_pushapi')\n\nif len(sys.argv) < 6:\n zmlog.Error ('Missing arguments, got {} arguments, was expecting at least 6: {}'.format(len(sys.argv)-1, sys.argv))\n zmlog.close()\n exit(1)\n\neid = sys.argv[1]\nmid = sys.argv[2]\nmname = sys.argv[3]\ncause = sys.argv[4]\nevent_type = sys.argv[5]\nimage_path = None\nfiles = None\n\nif len(sys.argv) == 7:\n image_path = sys.argv[6]\n fname=get_image(image_path, cause)\n zmlog.Debug (1,'Image to be used is: {}'.format(fname))\n files = {\n \"attachment\": (\"image.jpg\", open(fname,\"rb\"), \"image/jpeg\")\n }\n\n\nparam_dict['title'] = '{} Alarm ({})'.format(mname,eid)\nparam_dict['message'] = cause\nif event_type == 'event_end':\n param_dict['title'] = 'Ended:' + param_dict['title']\n\nr = requests.post(\"https://api.pushover.net/1/messages.json\", data = param_dict, files = files)\nprint(r.text)\n\n\nzmlog.close()\n","sub_path":"pushapi_plugins/pushapi_pushover.py","file_name":"pushapi_pushover.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"219227510","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport riff\nimport click\n\n\n@click.command()\n@click.option(\n \"-c\", \"--contract\", default=\"contract.yml\", help=\"Contract File Location\"\n)\n@click.option(\n \"-e\", \"--endpoint\", default=\"\", help=\"Endpoint to run, exclude for all\"\n)\ndef execute_contract(contract: str, endpoint: str) -> int:\n \"\"\"Contractual API Testing\"\"\"\n\n contract = riff.make_contract(contract)\n\n if not endpoint:\n contract.run()\n else:\n contract.endpoints[endpoint].run()\n\n return 0\n\n\nif __name__ == \"__main__\":\n execute_contract(prog_name=\"riff\")\n","sub_path":"riff/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"364710239","text":"#coding:utf-8\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef drawGraph(func):\n # 関数funcを描画\n x = np.linspace(-2.0,2.0)\n y = func(x)\n plt.plot(x, y)\n \ndef drawCobweb(func, initial):\n # クモの巣図法を描画\n vertices = []\n # 初期座標\n x = initial\n y = 0\n vertices.append([x, y])\n for n in range(1, 10):\n # 垂直方向\n y = func(x)\n vertices.append([x, y])\n # 水平方向\n x = y\n vertices.append([x, y])\n vertices = np.array(vertices)\n plt.plot(vertices[:,0], vertices[:,1], '--')\n \nif __name__ == \"__main__\":\n # y = xを描画\n drawGraph(lambda x: x)\n # y = (3*x-x^3)/2を描画\n drawGraph(lambda x: (3*x-x**3)/2)\n # クモの巣図法を描画\n drawCobweb(lambda x: (3*x-x**3)/2, 1.6)\n axis([-1.8, 1.8, -1.2, 1.2])\n grid(True)\n # グラフの描画実行\n plt.show()\n","sub_path":"chapter1/Cobweb_3.py","file_name":"Cobweb_3.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"240670138","text":"# method 2binary search, log(n)\n\n\nclass Solution(object):\n def missingElement(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n if not nums:\n return 1\n if len(nums) == 1:\n return nums[0] + 1\n left, right = 0, len(nums) - 1\n while left + 1 < right:\n mid = left + (right - left) // 2\n missing = (nums[mid] - nums[left]) - (mid - left)\n if missing >= k:\n right = mid\n else:\n left = mid\n k -= missing\n if (nums[right] - nums[left]) - (right - left) >= k:\n return nums[left] + k\n else:\n k -= (nums[right] - nums[left]) - (right - left)\n return nums[right] + k\n\n\n# method 1, naive line scan, O(n)\n\n\n\"\"\"\n\nGiven a sorted array A of unique numbers, find the K-th missing number starting from the leftmost number of the array.\n\n\n\nExample 1:\n\nInput: A = [4,7,9,10], K = 1\nOutput: 5\nExplanation:\nThe first missing number is 5.\nExample 2:\n\nInput: A = [4,7,9,10], K = 3\nOutput: 8\nExplanation:\nThe missing numbers are [5,6,8,...], hence the third missing number is 8.\nExample 3:\n\nInput: A = [1,2,4], K = 3\nOutput: 6\nExplanation:\nThe missing numbers are [3,5,6,7,...], hence the third missing number is 6.\n\n\nNote:\n\n1 <= A.length <= 50000\n1 <= A[i] <= 1e7\n1 <= K <= 1e8\n\"\"\"","sub_path":"1060. Missing Element in Sorted Array.py","file_name":"1060. Missing Element in Sorted Array.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"603755517","text":"import os\nimport sys\nimport time\nimport csv\nimport pandas as pd\nfrom random import randint\nfrom pprint import pprint\nfrom seleniumwire import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom datetime import datetime\n\nlogs = {}\nnow = datetime.now()\ndate = now.strftime(\"%Y-%m-%d %H:%M:%S\")\nlogs['Timestamp'] = date\n\nColumns = ['Timestamp','Headers','Data','Status']\ndf = pd.DataFrame(columns = Columns)\n\ndef formFilling(driver,data):\t\n\tdriver.find_element_by_xpath('//*[@id=\"reg_username_mobile\"]').send_keys(data['Username'])\t\t\n\n\tdriver.find_element_by_xpath('//*[@id=\"reg_password_mobile\"]').send_keys(data['Password'])\n\t\n\tdriver.find_element_by_xpath('//*[@id=\"reg_email_mobile\"]').send_keys(data['Email'])\n\t\n\tif data['checked'] == 'NO':\t\t\t\n\t\tdriver.find_element_by_xpath('//*[@id=\"reg_email_splOffer_mobile\"]').click()\n\n\tdriver.find_element_by_xpath('//*[@id=\"reg_state_mobile\"]/option[' + data['State'] + ']').click()\n\n\tdriver.find_element_by_xpath('//*[@id=\"btn_register_' + data['Gender'] + '_mobile\"]').click()\n\treturn None\t\t\n\ndef automation():\n\ttry:\n\t\theaders = pd.read_excel('Database/header.xlsx')\n\t\tdata = pd.read_csv('Database/data_rummy.csv')\n\t\tstate_dict = {\n\t\t\"Andaman and Nicobar Islands\": \"1\",\n\t\t\"Andhra Pradesh\": \"2\",\n\t\t\"Assam\": \"3\",\n\t\t\"Bihar\": \"4\",\n\t\t\"Chandigarh\": \"5\",\n\t\t\"Chhattisgarh\": \"6\",\n\t\t\"Dadra and Nagar Haveli\": \"7\",\n\t\t\"Daman and Diu\": \"8\",\n\t\t\"Delhi\": \"9\",\n\t\t\"Goa\": \"10\",\n\t\t\"Gujarat\": \"11\",\n\t\t\"Haryana\": \"12\",\n\t\t\"Himachal Pradesh\": \"13\",\n\t\t\"Jammu and Kashmir\": \"14\",\n\t\t\"Jharkhand\": \"15\",\n\t\t\"Karnataka\": \"16\",\n\t\t\"Kerala\": \"17\",\n\t\t\"Lakshadweep\": \"18\",\n\t\t\"Madhya Pradesh\": \"19\",\n\t\t\"Maharashtra\": \"20\",\n\t\t\"Manipur\": \"21\",\n\t\t\"Meghalaya\": \"22\",\n\t\t\"Mizoram\": \"23\",\n\t\t\"Nagaland\": \"24\",\n\t\t\"Odisha\": \"25\",\n\t\t\"Pondicherry\": \"26\",\n\t\t\"Punjab\": \"27\",\n\t\t\"Rajasthan\": \"28\",\n\t\t\"Sikkim\": \"29\",\n\t\t\"Tamil Nadu\": \"30\",\n\t\t\"Telangana\": \"31\",\n\t\t\"Tripura\": \"32\",\n\t\t\"Uttar Pradesh\": \"33\",\n\t\t\"Uttarakhand\": \"34\",\n\t\t\"West Bengal\": \"35\"\n\t\t}\n\t\tdata['State'].replace(state_dict, inplace=True)\t\t\n\texcept:\n\t\tlogs['Status'] = 'Failed Data not Loaded Successfully'\n\t\treturn None\n\n\tfor i in range(0,headers.shape[0]):\n\t\tdict_headers = {}\n\t\theader = headers.loc[i]\n\t\tif header['Referrer'] != 'NONE':\n\t\t\tdict_headers['Referer'] = header['Referrer']\n\t\tdict_headers[header['Option']] = header['IP']\n\t\tdict_headers['User-Agent'] = header['USERAGENT']\n\n\t\tURL = 'https://www.rummycircle.com/#register'\n\t\ttry:\t\t\t\t\t\n\t\t\tpath = os.getcwd()\n\t\t\tpath_chromedriver = path + \"\\\\Drivers\\\\chromedriver.exe\"\t\n\t\t\tuser_agent = \"user-agent=\"+header['USERAGENT']\n\t\t\tchrome_options = webdriver.ChromeOptions()\t\t\t\n\t\t\tchrome_options.add_argument(user_agent) \t\n\t\t\tdriver = webdriver.Chrome(\t\t\t\n\t\t\t\tchrome_options=chrome_options,\n\t\t\t\texecutable_path=path_chromedriver)\n\t\t\t\n\t\t\tdriver._client.set_header_overrides(headers=dict_headers)\t\t\t\n\t\texcept:\n\t\t\tlogs['Status'] = logs['Status'] + ' - Failed due to Chromedriver not loading Properly'\n\t\t\treturn None\n\t\ttry:\n\t\t\tdatum = data.loc[i]\n\t\t\tlogs['Headers'] = str(dict_headers)\n\t\t\tlogs['Data'] = str(datum)\n\t\t\tdriver.get(URL)\n\t\t\tsleep_time = randint(3, 20)\n\t\t\ttime.sleep(sleep_time)\n\t\t\ttry:\t\t\n\t\t\t\tformFilling(driver,datum)\n\t\t\t\tlogs['Status'] = 'Successful'\n\t\t\texcept:\n\t\t\t\tlogs['Status'] = logs['Status'] + ' - Failed while filling Form'\n\t\t\t# print(logs)\t\n\t\t\tglobal df\n\t\t\tdf = df.append([logs])\t\n\t\texcept:\n\t\t\tprint(\"Reached End of data.csv\")\n\t\t\treturn None\n\t\ttime.sleep(5)\t\n\t\tdriver.quit()\n\tprint(\"Closing Script ...\")\n\treturn None \nautomation()\n\nif os.path.isfile('logs_rummy.csv'):\n print(\"File already exists\")\n with open('logs_rummy.csv', 'a') as f:\n df.to_csv(f, header=False,index=False)\nelse:\n print(\"New file created\")\n df.to_csv('logs_rummy.csv',index=False)","sub_path":"Automating a user defined website/auto_rummy_new.py","file_name":"auto_rummy_new.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"283800493","text":"# %load q01_missing_value/build.py\r\n# Default imports\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import Imputer\r\n# Data loading\r\nny_housing = pd.read_csv('data/train.csv')\r\n# Selecting 4 most relevant variables along with target variable from the dataset fot the Cleaning and Preprocessing.\r\nhousing_data = ny_housing[['MasVnrArea', 'GrLivArea', 'LotShape', 'GarageType', 'SalePrice']]\r\n\r\n\r\n# Write your code here:\r\ndef imputation(housing_data):\r\n cat=housing_data[['LotShape','GarageType']]\r\n num=housing_data[['MasVnrArea','GrLivArea']]\r\n #x=['Attchd']\r\n cat[['GarageType']]=cat[['GarageType']].fillna('Attchd')\r\n #housing_data[['GarageType']].isnull().any()\r\n num['MasVnrArea'].isnull().any()\r\n imp_mean = Imputer(missing_values = 'NaN', strategy='mean')\r\n imp_mean.fit(num[['MasVnrArea']])\r\n num[['MasVnrArea']] = imp_mean.transform(housing_data[['MasVnrArea']])\r\n #housing_data[['GarageType']].isnull().any()\r\n return num,cat\r\n","sub_path":"q01_missing_value/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"206466033","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nimport sciconet as scn\n\n\ndef main():\n def ide(x, y, int_mat):\n \"\"\"int_0^x y(t)dt\n \"\"\"\n lhs1 = tf.matmul(int_mat, y)\n lhs2 = tf.gradients(y, x)[0]\n rhs = 2 * np.pi * tf.cos(2 * np.pi * x) + tf.sin(np.pi * x) ** 2 / np.pi\n return lhs1 + (lhs2 - rhs)[: tf.size(lhs1)]\n\n def func(x):\n \"\"\"\n x: array_like, N x D_in\n y: array_like, N x D_out\n \"\"\"\n return np.sin(2 * np.pi * x)\n\n geom = scn.geometry.Interval(0, 1)\n\n nbc = 1\n quad_deg = 16\n data = scn.data.IDE(geom, ide, func, nbc, quad_deg)\n\n x_dim, y_dim = 1, 1\n layer_size = [x_dim] + [20] * 3 + [y_dim]\n activation = \"tanh\"\n initializer = \"Glorot uniform\"\n net = scn.maps.FNN(layer_size, activation, initializer)\n\n model = scn.Model(data, net)\n\n optimizer = \"adam\"\n lr = 0.001\n batch_size = 16\n ntest = 128\n model.compile(optimizer, lr, batch_size, ntest, metrics=[\"l2 relative error\"])\n\n epochs = 10000\n losshistory, train_state = model.train(epochs)\n\n scn.saveplot(losshistory, train_state, issave=True, isplot=True)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/ide.py","file_name":"ide.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"287900857","text":"import imaplib, base64, os, email, shutil, datetime, smtplib, ssl, json\nfrom pdf2image import convert_from_path, convert_from_bytes\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n#Information for PDF to Image Conversion\n\nemail_user = input(\"Input Gmail Email Here: \") #Changed for anonimity\nemail_pass = input(\"Type Password Here: \") #Changed for anonimity\nsubject_to_search_for = '(SUBJECT \"Announcement Slides\")' #can change to subject line you are searching for\n\n#import json file with the keys\n\nwith open(\"filepaths.json\", \"r\") as filepath:\n path = json.load(filepath)\n\ndef logingIn():\n return email_user, email_pass\n\ndef downloadingAttachments():\n credentials = logingIn()\n\n email_user = credentials[0]\n email_pass = credentials[1]\n\n print('Downloading Attachments...')\n\n mail = imaplib.IMAP4_SSL('imap.gmail.com',993)\n mail.login(email_user, email_pass)\n\n mail.select()\n type, data = mail.search(None, subject_to_search_for) #edit subject line to update search\n mail_ids = data[0]\n id_list = mail_ids.split()\n latestEmail = id_list[-1]\n #print(latestEmail)\n\n typ, data = mail.fetch(latestEmail, '(RFC822)' )\n raw_email = data[0][1]\n #print(raw_email)\n # converts byte literal to string removing b''\n raw_email_string = raw_email.decode('utf-8')\n email_message = email.message_from_string(raw_email_string)\n # downloading attachments\n for part in email_message.walk():\n # this part comes from the snipped I don't understand yet... \n if part.get_content_maintype() == 'multipart':\n continue\n if part.get('Content-Disposition') is None:\n continue\n fileName = part.get_filename()\n if bool(fileName):\n sv_path = os.path.join(path['logo_insertion'] , fileName)\n if not os.path.isfile(sv_path): \n fp = open(sv_path, 'wb')\n fp.write(part.get_payload(decode=True))\n fp.close()\n\n for response_part in data:\n if isinstance(response_part, tuple):\n msg = email.message_from_string(response_part[1].decode('utf-8'))\n email_subject = msg['subject']\n email_from = msg['from']\n print ('From : ' + email_from + '\\n')\n print ('Subject : ' + email_subject + '\\n')\n #print(msg.get_payload(decode=True))\n print ('Download Complete. Please check the appropriate directory.')\n\ndef findSunday(): #funtions is used to date output\n today = datetime.date.today()\n nextSunday = ''\n if today.isoweekday != 7:\n difference = (7 - (today.isoweekday()))\n else:\n difference = 0\n nextSunday = today + datetime.timedelta(days=difference)\n return nextSunday\n\ndef pdfconversion():\n print('Starting Conversion')\n pdf = convert_from_path(path['final_pdf'])\n \n os.chdir(path['temp_slides'])\n cwd = os.getcwd()\n #delete old contents from holding directory\n for item in os.listdir(cwd):\n os.remove(item)\n \n i = 1\n for page in pdf: \n name = 'slide' + str(i) + '.jpg'\n print('Converted Slide' + str(i))\n page.save(name, 'JPEG')\n i += 1\n\n #changes working directory and compresses slides into a zip file\n os.chdir(path['compressed_slides'])\n shutil.make_archive('slides ' + str(findSunday()), 'zip', cwd)\n\n#sending zip folder to thepathav@gmail.com\n\ndef sendToDestination():\n port = 0 \n smtp_server = \"smtp.gmail.com\" \n sender_email = email_user\n receiver_email = input('Who would you like to send the email to?') #Changed for anonimity\n subject = \"Converted Annocement Slides - \" + str(findSunday()) #change subject line for email\n body = \"This message is autogenerated using Python. \\n If you have any questions ask Julius J.\" #Message/ body of email sent\n\n # Creates a multipart message and sets headers\n message = MIMEMultipart()\n message[\"From\"] = sender_email\n message[\"To\"] = receiver_email\n message[\"Subject\"] = subject\n message[\"Bcc\"] = ''\n\n # Add body to email\n message.attach(MIMEText(body, \"plain\"))\n\n # ToDo get most recent file\n filename = 'slides ' + str(findSunday()) + '.zip'\n\n #Open file in binary mode\n with open(filename, \"rb\") as attachment:\n #Add file as application/octet-stream\n #Email client can usually download this automatically as attachment\n part = MIMEBase(\"application\", \"octet-stream\")\n part.set_payload(attachment.read())\n \n #Encode file in ASCII characters to send by email\n encoders.encode_base64(part)\n\n #Add headers as key/value pair to attachment part\n part.add_header(\n \"Content-Disposition\",\n f\"attachment; filename= {filename}\",\n )\n\n #Add attachment to message and convert message to string\n message.attach(part)\n text = message.as_string()\n\n #Log in to server using secure context and send email\n context = ssl.create_default_context()\n with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:\n server.login(email_user, email_pass)\n server.sendmail(sender_email, receiver_email, text)\n\ndownloadingAttachments()\npdfconversion()\nsendToDestination()\n\n#create virtual env -- complete\n#convert pdf to images -- Completed\n#put images in folder\n#compressfolder\n#send to thepathav@gmail.com","sub_path":"email_conversion.py","file_name":"email_conversion.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"227323854","text":"import numpy as np\n\ngreyhounds = 500\nlabradors = 500\n\ngrey_height = 28 + (4 * np.random.randn(greyhounds))\nlab_height = 24 + (4 * np.random.randn(labradors))\n\nprint(grey_height)\n\n# Again, couldn't get the visualisation to work due to the tutorial being old code, but that's alright.\n","sub_path":"dogsIdentification.py","file_name":"dogsIdentification.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"130427542","text":"#!/usr/bin/python3\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sys\nimport getopt\nimport re\n\nHARTREE_TO_EV=27.2113839\npd.options.display.float_format = \"{:>10.3f}\".format\nUSAGE='''Usage :: ./scat_input.py [-h] [-rs] -p -c \n-h help\n-r create rmat?.data files\n-s create ci?np1.data files\n-p path to folder which contains citargmod.prop and rmat?.data\n-c frozen, occupied and virtual MO's in order of symmetry (A1,B1,B2,A2)\n e.g., -c 4,0,0,0 6,2,2,0 4,2,2,0\n would correspond to:\n 4 A1, 0 B1, 0 B2, 0 A2 frozen\n 6 A1, 2 B1, 2 B2, 0 A2 occupied\n 4 A1, 2 B1, 2 B2, 0 A2 virtual'''\nOPTIONS=[\"r\",\"s\"]\n\ndef main(argv):\n\n# path,frozen,occupied,virtual=\"\",\"\",\"\",\"\"\n# processed=[]\n# for i, arg in enumerate(argv):\n# if arg == \"-h\":\n# print(USAGE)\n# quit()\n# if arg == \"-p\":\n# path=argv[i+1]\n# if arg == \"-c\":\n# frozen,occupied,virtual=argv[i+1:i+4]\n#\n# argv=[i for i in argv if i not in [\"-p\",\"-c\",path,frozen,occupied,virtual]]\n# argv=\"\".join(argv).replace(\"-\",\"\")\n#\n# for arg in argv:\n# if arg not in OPTIONS:\n# print(\"Error :: Unknown option \\'\"+str(arg)+\"\\'\")\n# print(USAGE)\n# quit()\n\n print(\"arguments are \",argv)\n\n if argv[0] is not None:\n try:\n df=pd.DataFrame()\n rvalues=[]\n print(\"Reading molpro output files...\")\n for i,filename in enumerate(argv):\n r,sym,energy=getMCSCF(filename)\n rvalues.append(r)\n if filename is argv[0]:\n df=pd.DataFrame(columns=sym)\n df.loc[i]=energy\n else:\n df.loc[i]=energy\n\n df=df.rename({i:r for i,r in enumerate(rvalues)}, axis=\"index\")\n df=df.rename({\"1\":\"A1\",\"2\":\"B1\",\"3\":\"B2\",\"4\":\"A2\"}, axis=\"columns\")\n df=df.apply(pd.to_numeric)\n groundEnergy=df.values.min()\n print(\"Min. Ground State Energy (eV) ::\",groundEnergy*HARTREE_TO_EV)\n df=df.applymap(lambda x: (x-groundEnergy)*HARTREE_TO_EV)\n\n print(df)\n\n plot(df)\n\n except (IOError, OSError) as e:\n print(\"ERROR:: one path is invalid\")\n quit()\n else:\n print(\"ERROR:: Please provide at least one path\")\n print(\" e.g. ./plot.py molpro.out\")\n\ndef getMCSCF(filename):\n\n sym,energy=[],[]\n rindex=0\n r=\"\"\n with open(filename) as infile:\n for i,line in enumerate(infile):\n if \"Bond lengths in Bohr\" in line:\n rindex=i+3\n if all(word in line for word in [\"!MCSCF STATE\",\"Energy\"]):\n sym.append(line.split()[2].split(\".\")[-1])\n energy.append(line.split()[-1])\n if rindex > 0 and i==rindex:\n r=line.replace(\"(\",\"\").replace(\")\",\"\").split()[0]\n r=float(r)\n return r,sym,energy\n\ndef plot(df):\n df.drop([\"B2\"],axis=1,inplace=True)\n print(df)\n df.plot()\n plt.legend(loc='best')\n plt.show()\n\nif __name__ == \"__main__\": main(sys.argv[1:])\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"322114899","text":"#!/usr/bin/env python\n# importing nesscessry modules\nimport rospy\nimport math\nfrom math import sin, cos, pi\nimport signal\nimport tf2_ros\nimport numpy as np\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Point, Pose,Twist,Quaternion,Vector3,TransformStamped\n# setting the parametrs for position of G_bot(turtle_bot)\nx = 0.0\ny = 0.0\ntheta = 0.0\nt = TransformStamped()\ndef euler_to_quaternion(yaw, pitch, roll):\n\n qx = np.sin(roll/2) * np.cos(pitch/2) * np.cos(yaw/2) - np.cos(roll/2) * np.sin(pitch/2) * np.sin(yaw/2)\n qy = np.cos(roll/2) * np.sin(pitch/2) * np.cos(yaw/2) + np.sin(roll/2) * np.cos(pitch/2) * np.sin(yaw/2)\n qz = np.cos(roll/2) * np.cos(pitch/2) * np.sin(yaw/2) - np.sin(roll/2) * np.sin(pitch/2) * np.cos(yaw/2)\n qw = np.cos(roll/2) * np.cos(pitch/2) * np.cos(yaw/2) + np.sin(roll/2) * np.sin(pitch/2) * np.sin(yaw/2)\n\n return [qx, qy, qz, qw]\ndef odom_callback(vel):\n odom_pub = rospy.Publisher(\"odom\",Odometry,queue_size=10)\n odom_broadcaster = tf2_ros.TransformBroadcaster()\n global x,y,theta,current_time,past_time\n # setting the current time and time passed\n current_time = rospy.Time.now()\n dt = (current_time-past_time).to_sec()\n # calculating distance using velocities\n v = vel.linear.x\n vtheta = vel.angular.z\n x += (v * cos(theta))* dt\n y += (v * sin(theta)) * dt\n theta += vtheta * dt\n past_time = current_time\n # transforming the eulars into quaternions\n q = euler_to_quaternion(theta, 0, 0)\n # publishing the transform between /odom and base_link\n t.header.stamp = rospy.Time.now()\n t.header.frame_id = \"odom\"\n t.child_frame_id = \"base_link\"\n t.transform.translation.x = x\n t.transform.translation.y = y\n t.transform.translation.z = 0.0\n t.transform.rotation.x = q[0]\n t.transform.rotation.y = q[1]\n t.transform.rotation.z = q[2]\n t.transform.rotation.w = q[3]\n odom_broadcaster.sendTransform(t)\n #defining the odometry message\n odom = Odometry()\n odom.header.stamp = current_time\n odom.header.frame_id = \"odom\"\n # set the position\n odom.pose.pose = Pose(Point(x, y, 0), Quaternion(*q))\n # set the velocity\n odom.child_frame_id = \"base_link\"\n odom.twist.twist = Twist(Vector3(v, 0, 0), Vector3(0, 0, vtheta))\n # publish the message\n odom_pub.publish(odom)\n rospy.loginfo(q)\n\n# initialising the node\nrospy.init_node(\"odometry_publisher\",anonymous=True)\ncurrent_time = rospy.Time.now()\npast_time = rospy.Time.now()\nrospy.Subscriber(\"/g_cmd_vel\", Twist, odom_callback)\nrospy.spin()\n","sub_path":"raspberry_pi/car_control_2/src/odem/odem.py","file_name":"odem.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"532034565","text":"\"\"\"\nProvides an APIView class that is the base of all views in REST framework.\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport six\nfrom django.conf import settings\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import connection, models, transaction\nfrom django.http import Http404\n\nfrom rest_framework import exceptions, status\nfrom rest_framework.exceptions import _get_error_details, _get_codes, _get_full_details, APIException\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\n\ndef set_rollback():\n atomic_requests = connection.settings_dict.get('ATOMIC_REQUESTS', False)\n if atomic_requests and connection.in_atomic_block:\n transaction.set_rollback(True)\n \n \n \ndef exception_handler(exc, context):\n \"\"\"\n Returns the response that should be used for any given exception.\n\n By default we handle the REST framework `APIException`, and also\n Django's built-in `Http404` and `PermissionDenied` exceptions.\n\n Any unhandled exceptions may return `None`, which will cause a 500 error\n to be raised.\n \"\"\"\n print(\"ok\")\n if isinstance(exc,FlexibleError) and exc.flexible_code==-1:\n return Response({\"status\":exc.status,\"msg\":exc.msg})\n if isinstance(exc, Http404):\n exc = exceptions.NotFound()\n elif isinstance(exc, PermissionDenied):\n exc = exceptions.PermissionDenied()\n if isinstance(exc, APIException):\n headers = {}\n if getattr(exc, 'auth_header', None):\n headers['WWW-Authenticate'] = exc.auth_header\n if getattr(exc, 'wait', None):\n headers['Retry-After'] = '%d' % exc.wait\n\n if isinstance(exc.detail, (list, dict)):\n data = exc.detail\n else:\n data = {'detail': exc.detail}\n\n set_rollback()\n return Response(data, status=exc.status_code, headers=headers)\n\n return None\n\n\n\n \n \nclass RestException(APIException):\n status_code = status.HTTP_400_BAD_REQUEST\n def __init__(self, detail=None, code=None):\n if detail is None:\n detail = self.default_detail\n if code is None:\n code = self.default_code\n\n data ={\"msg\":detail,\"code\":code}\n super(RestException,self).__init__(data)\n \n \nclass AuthenticationFailed(RestException):\n # 认证异常\n status_code = status.HTTP_401_UNAUTHORIZED\n default_detail = 'Incorrect authentication credentials.'\n default_code = 'authentication_failed'\n\n\nclass FlexibleError(Exception):\n flexible_code = -1\n status = 0\n \n def __init__(self, data):\n self.status = data.get(\"status\")\n self.msg = data.get(\"msg\")\n self.detail = data\n \n def __str__(self):\n return self.msg","sub_path":"utils/rest_api/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"75864990","text":"from django.shortcuts import render,HttpResponse\nimport json\nfrom .models import Cataloguedataway\nfrom django.http import JsonResponse\nimport time\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'cataloguedataway/index.html')\n\n\n\n#递归函数\ndef getTree(pid = 0,res = []):\n data = Cataloguedataway.objects.filter(typeparentid= pid)\n lens = len(data)\n for num in range(0, lens):\n num = int(num)\n temp = {\n 'id': data[num].typeid,\n 'typeparentid':data[num].typeparentid,\n 'cataloguename':data[num].cataloguename,\n 'typetime': data[num].typetime,\n }\n # print(num)\n res.append(temp)\n if not hasattr(res[num],'children'):\n res[num]['children'] = []\n res[num]['children'] = getTree(data[num].typeid, res[num]['children'])\n return res\n\n#发布的列表树\ndef getData(request):\n lists = getTree(1,[])\n return HttpResponse(json.dumps(lists), content_type=\"application/json\")\n\n\n#存\ndef saveCleaningRules(request):\n result = {'errorCode':'0x0000', 'errorString': ''}\n if request.method == 'POST':\n cataloguename = request.POST.get('cataloguename')\n typeparentid = request.POST.get('typeparentid')\n id = request.POST.get('id')\n # print(cataloguename)\n print(typeparentid)\n print(id)\n if request.POST.get('save_type') == 'edit':\n data = Cataloguedataway.objects.get(typeid = id)\n data.cataloguename = cataloguename\n data.typeparentid = typeparentid\n elif request.POST.get('save_type') == 'add':\n if Cataloguedataway.objects.filter(typeparentid=id):\n numdata = Cataloguedataway.objects.filter(typeparentid=id)\n listid = []\n for num in range(len(numdata)):\n listid.append(numdata[num].typeid)\n numid = max(listid)+1\n data = Cataloguedataway(cataloguename=cataloguename, typeparentid=id,typeid=numid,count=0,\n typetime=time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n elif id==0:\n numid = int(id)\n numid2 = numid+1\n data = Cataloguedataway(cataloguename = cataloguename,count = 0, typeparentid = id, typeid = numid2, typetime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n\n else:\n numid = int(id)*1000\n numid2 = numid+1\n data = Cataloguedataway(cataloguename = cataloguename,count = 0, typeparentid = id, typeid = numid2, typetime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n\n try:\n data.save()\n except:\n result.errorCode = '0x0001'\n result.errorString = '数据库操作失败'\n else:\n result.errorCode = '0x0002'\n result.errorString = '参数错误'\n return JsonResponse(result)\n\n#删\ndef delCleaningRules(request):\n result = {'errorCode': '0x0000', 'errorString': ''}\n if request.method == 'POST':\n ids = request.POST.get('data')\n # print(ids)\n try:\n Cataloguedataway.objects.extra(where=['typeid in ('+ ids + ')']).delete()\n except:\n result.errorCode = '0x0001'\n result.errorString = '数据库操作失败'\n else:\n result.errorCode = '0x0002'\n result.errorString = '参数错误'\n return JsonResponse(result)\n\ndef allData(request):\n print(\"nihao\")\n a = request.POST.get('dataid', 0)\n print(a)\n b = str(a)\n # b = int(a)\n # print(222)\n # print(b)\n if len(b)>2:\n print(9292)\n data = Cataloguedataway.objects.all()\n print(data)\n print(\"hello\")\n lens = len(data)\n list = []\n for num in range(0, lens):\n num = int(num)\n temp = {\n 'id': data[num].typeid,\n 'typeparentid': data[num].typeparentid,\n 'cataloguename': data[num].cataloguename,\n 'typetime': data[num].typetime,\n }\n list.append(temp)\n return HttpResponse(json.dumps(list), content_type=\"application/json\")\n elif len(b)<2:\n print(82910)\n data = Cataloguedataway.objects.filter(typeid=911)\n print(data)\n print(\"hello\")\n lens = len(data)\n list = []\n for num in range(0, lens):\n num = int(num)\n temp = {\n 'id': data[num].typeid,\n 'typeparentid': data[num].typeparentid,\n 'cataloguename': data[num].cataloguename,\n 'typetime': data[num].typetime,\n }\n list.append(temp)\n return HttpResponse(json.dumps(list), content_type=\"application/json\")","sub_path":"cataloguedataway/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"615654502","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef relu(x):\n return np.maximum(0, x)\n\nif __name__ == '__main__':\n x = np.arange(-5.0, 5.0, 0.1)\n y = relu(x)\n \n plt.plot(x, y)\n plt.ylim(-1.0, 5.5)\n plt.title('relu function')\n plt.show()","sub_path":"Cpt.03/relu_function.py","file_name":"relu_function.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"555937600","text":"#!/usr/bin/env python3\n\nfrom hpecp import ContainerPlatformClient\nimport json,sys,subprocess\nimport os\n\n# Disable the SSL warnings - don't do this on productions! \nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\nos.environ[\"LOG_LEVEL\"] = \"INFO\"\n\ntry:\n with open('./generated/output.json') as f:\n j = json.load(f)\nexcept: \n print(80 * \"*\")\n print(\"ERROR: Can't parse: './generated/output.json'\")\n print(80 * \"*\")\n sys.exit(1)\n\ncontroller_public_ip = j[\"controller_public_ip\"][\"value\"]\nad_server_private_ip = j[\"ad_server_private_ip\"][\"value\"]\n\n\nclient = ContainerPlatformClient(username='admin', \n password='admin123', \n api_host=controller_public_ip, \n api_port=8080,\n use_ssl=True,\n verify_ssl=False)\n\nclient.create_session()\n\nprint(\"*\" * 80)\nprint( \"Current License:\\n\" + str(client.license.get_license()) )\nprint(\"*\" * 80)\nprint( \"Platform ID: \" + client.license.get_platform_id() )\nprint(\"*\" * 80)\nlic = input(\"Paste License Text: \")\n\nwith open('./generated/LICENSE', 'w') as out_file:\n out_file.write(lic)\n\nimport subprocess\nsubprocess.run([\"scp\", \"-i\", \"./generated/controller.prv_key\", \"./generated/LICENSE\", \"centos@{}:/srv/bluedata/license/LICENSE\".format(controller_public_ip)])\n\nclient.license.register_license(\"/srv/bluedata/license/LICENSE\")\n\nprint(\"*\" * 80)\nprint( \"Current License:\\n\" + str(client.license.get_license()) )\nprint(\"*\" * 80)","sub_path":"scripts/end_user_scripts/hpe_admin/license_register.py","file_name":"license_register.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"333310249","text":"from http import HTTPStatus\n\nfrom aiohttp.web_exceptions import HTTPNotFound, HTTPConflict, HTTPBadRequest\nfrom aiohttp.web_response import Response\nfrom aiohttp_validate import validate\nfrom asyncpg import UniqueViolationError, ForeignKeyViolationError\nfrom sqlalchemy import select\n\nfrom storefront.handlers.base import BaseView\nfrom storefront.models import Employee, EmployeeProductRelation, Product\n\n\nclass EmployeesView(BaseView):\n URL_PATH = '/employees'\n\n @validate(\n request_schema={\n 'type': 'object',\n 'properties': {\n 'name': {'type': 'string'},\n 'company_id': {'type': 'integer'}\n },\n 'required': ['name', 'company_id'],\n 'additionalProperties': False\n }\n )\n async def post(self, data, request) -> Response:\n query = Employee.__table__.insert().values(\n name=data['name'], company_id=data['company_id']\n ).returning(Employee.__table__)\n data = await self.postgres.fetchrow(query)\n return Response(body={'data': data}, status=HTTPStatus.CREATED)\n\n async def get(self) -> Response:\n query = Employee.__table__.select()\n data = await self.postgres.fetch(query)\n return Response(body={'data': data})\n\n\nclass EmployeeView(BaseView):\n URL_PATH = '/employees/{id}'\n\n @property\n def employee_id(self) -> int:\n return int(self.request.match_info['id'])\n\n async def get(self) -> Response:\n query = Employee.__table__.select().where(\n Employee.__table__.c.employee_id == self.employee_id\n )\n data = await self.postgres.fetchrow(query)\n if data is None:\n raise HTTPNotFound()\n return Response(body={'data': data})\n\n @validate(\n request_schema={\n 'type': 'object',\n 'properties': {\n 'name': {'type': 'string'},\n 'company_id': {'type': 'integer'}\n },\n 'required': ['name', 'company_id'],\n 'additionalProperties': False\n }\n )\n async def put(self, data, request) -> Response:\n query = Employee.__table__.update().values(\n name=data['name'], company_id=data['company_id']\n ).where(\n Employee.__table__.c.employee_id == self.employee_id\n ).returning(Employee.__table__)\n data = await self.postgres.fetchrow(query)\n if data is None:\n raise HTTPNotFound()\n return Response(body={'data': data})\n\n async def delete(self) -> Response:\n try:\n query = Employee.__table__.delete().where(\n Employee.__table__.c.employee_id == self.employee_id\n ).returning(Employee.__table__)\n\n data = await self.postgres.fetchrow(query)\n if data is None:\n raise HTTPNotFound()\n\n except ForeignKeyViolationError:\n raise HTTPBadRequest(text=('Employee has relations with products '\n 'and can not be deleted'))\n\n return Response(status=204)\n\n\nclass EmployeeProductsView(BaseView):\n URL_PATH = '/employees/{employee_id}/products'\n TABLE = EmployeeProductRelation.__table__\n\n @property\n def employee_id(self) -> int:\n return int(self.request.match_info['employee_id'])\n\n @validate(\n request_schema={\n 'type': 'object',\n 'properties': {\n 'product_id': {'type': 'integer'}\n },\n 'required': ['product_id'],\n 'additionalProperties': False\n }\n )\n async def post(self, data, request) -> Response:\n async with self.postgres.transaction() as conn:\n try:\n query = self.TABLE.insert().values(\n employee_id=self.employee_id,\n product_id=data['product_id']\n )\n await conn.fetchrow(query)\n\n query = Product.__table__.select().where(\n Product.__table__.c.product_id == data['product_id']\n )\n product = await conn.fetchrow(query)\n\n except UniqueViolationError:\n raise HTTPConflict()\n\n except ForeignKeyViolationError:\n raise HTTPBadRequest()\n\n return Response(body={'data': product}, status=HTTPStatus.CREATED)\n\n async def get(self) -> Response:\n query = select(Product.__table__.columns).select_from(\n self.TABLE.join(\n Product.__table__,\n self.TABLE.c.product_id == Product.__table__.c.product_id\n )\n ).where(\n self.TABLE.c.employee_id == self.employee_id\n )\n data = await self.postgres.fetch(query)\n return Response(body={'data': data})\n\n\nclass EmployeeProductDeleteView(BaseView):\n URL_PATH = '/employees/{employee_id}/products/{product_id}'\n\n async def delete(self) -> Response:\n employee_id = int(self.request.match_info['employee_id'])\n product_id = int(self.request.match_info['product_id'])\n\n query = EmployeeProductRelation.__table__.delete().where(\n EmployeeProductRelation.__table__.c.employee_id == employee_id\n ).where(\n EmployeeProductRelation.__table__.c.product_id == product_id\n ).returning(EmployeeProductRelation.__table__)\n\n data = await self.postgres.fetchrow(query)\n if data is None:\n raise HTTPNotFound()\n\n return Response(status=HTTPStatus.NO_CONTENT)\n","sub_path":"storefront/handlers/employees.py","file_name":"employees.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"184024742","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom bookmarks.views import CustomRegistrationView, ListBookmarkView\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^api/', include('bookmarks_api.urls')),\n url(r'^accounts/register/$', CustomRegistrationView.as_view(), name='register'),\n url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),\n url(r'^accounts/', include('registration.backends.simple.urls')),\n url(r'^bookmarks/', include('bookmarks.urls')),\n url(r'^$', ListBookmarkView.as_view())\n)\n","sub_path":"shookmark/shookmark/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"30354852","text":"import json\nimport base64\nimport requests\n\n#1、读取图片数据,整合两张图片JSON数据\nwith open('6.png', 'rb') as f:\n pic1 = f.read()\n\nwith open('china.jpg', 'rb') as f:\n pic2 = f.read()\n\nimage_data = json.dumps(\n [\n {'image': str(base64.b64encode(pic1), 'utf-8'), 'image_type': 'BASE64', 'face_type': 'LIVE', 'quality_control': 'LOW'},\n {'image': str(base64.b64encode(pic2), 'utf-8'), 'image_type': 'BASE64', 'face_type': 'IDCARD', 'quality_control': 'LOW'}\n ]\n)\n#2、拼接API接口\nget_token = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=DzDCjiMxSGoc3HtUmxySbtXu&client_secret=dCYoXlz9mcNzsuklqbwdPhxt7SZxGKNo'\nAPI_url = 'https://aip.baidubce.com/rest/2.0/face/v3/match?access_token='\n\ntext = requests.get(get_token).text\naccess_token = json.loads(text)['access_token']\nprint(access_token)\nurl = API_url + access_token\n#3、请求API接口传入数据,返回图片相似度\nresponse = requests.post(url, data= image_data)\nprint(response.text)\n\nscore = json.loads(response.text)['result']['score']\nif score > 80 :\n print('图片相似度为:{} ,同一个人!'.format(score))\nelse:\n print('图片相似度为:{} ,不是同一个人!'.format(score))\n\n","sub_path":"face_read.py","file_name":"face_read.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"583909539","text":"from django import forms\n\nclass NewUtilityForm(forms.Form):\n\tidentifier = forms.CharField(max_length=30)\n\tsector = forms.ModelChoiceField(queryset=None)\n\tlat = forms.DecimalField(required=False, min_value=-90, max_value=90)\n\tlon = forms.DecimalField(required=False, min_value=-180, max_value=180)\n\tfee_auto = forms.ChoiceField(choices=fee_auto_choices, required=False)\n\tfee_auto = forms.TypedChoiceField(choices=fee_auto_choices, widget = forms.HiddenInput(), coerce=bool)\n\tfee_type = forms.ModelChoiceField( widget = forms.HiddenInput(),\n\t\tqueryset=ContentType.objects.filter(pk__in=[ct.pk for ct in get_fee_types()]))\n\tstart_date = forms.DateField(widget=html5_widgets.DateInput)\n\n\tdef __init__(self, *args, **kwargs):\n\t\tauto = district = None\n\t\tif 'auto' in kwargs:\n\t\t\tauto = kwargs.pop('auto')\n\t\tif 'district' in kwargs:\n\t\t\tdistrict = kwargs.pop('district')\n\t\tsuper(NewUtilityForm, self).__init__(*args, **kwargs)\n\n\t\tif not auto:\n\t\t\tself.fields['amount'] = forms.FloatField(label='Fee Amount', min_value=0)\n\n\t\tif district:\n\t\t\tself.fields['sector'].queryset = Sector.objects.filter(district=district).order_by('name')\n\n\nclass CleaningFeeForm(forms.ModelForm, NewUtilityForm):\n\tclass Meta:\n\t\tmodel = CleaningFee\n\t\tfields = ('identifier', 'sector', 'lat', 'lon', 'fee_auto', 'fee_cycle', 'start_date')","sub_path":"crud/forms/utilityforms.py","file_name":"utilityforms.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"47738635","text":"\r\nimport random\r\n\r\nprint(\"Welcome To My DiceRoll Simulator!\")\r\nx = 1\r\nprint(\"Please input how many faces you would like your dice to have: \")\r\ny = input()\r\nwhile x != 0:\r\n d = random.randint(int(x), int(y))\r\n print(\"The dice landed on:\")\r\n print(d)\r\n\r\n x = input(\"To play again press 1,to stop press 0\")\r\n","sub_path":"DiceRoll/DiceRoll.py","file_name":"DiceRoll.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"472100391","text":"# 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?\n# 比如n=3时,2*3的矩形块有3种覆盖方法:\n\n\nclass Solution:\n def rectCover(self, number):\n if number == 1: return 1\n elif number == 2: return 2\n elif number >= 3:\n prev = 1\n next = 2\n for _ in range(number - 2):\n prev, next = next, prev + next\n return next\n else:\n return 0\n","sub_path":"JZ10. 矩形覆盖.py","file_name":"JZ10. 矩形覆盖.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"198313485","text":"# -*- coding: utf-8 -*-\n\n###########################################################\n### CLASE PROGRESS 1.0 ###\n###########################################################\n### ULTIMA MODIFICACION DOCUMENTADA ###\n### 05/10/2019 ###\n### ###\n###########################################################\n\nimport pygame\nfrom winform.base.objetogral import ObjetoGral\n\nclass Progress(ObjetoGral):\n def __init__(self, C_Form):\n super().__init__(C_Form) # instanciamos la clase padre\n self.min = 0\n self.max = 0\n self.ancho_barra = 0 # ancho de la barra de progreso\n self.rec_barra = 0,0,0,0 # rectangulo de la barra\n \n def config(self, min, max, text, x, y, ancho, alto):\n # min, max (Valores minimos y maximos que se adoptan)\n # text (Valor inicial para mostrar)\n self.min = min\n self.max = max\n super().config(x, y, ancho, alto, str(text))\n self.label_int.config(self.text, self.color_text, \n self.rectangulo,\n \"centrada\", \"centrada\", \n self.text_size)\n \n\n def dibujar(self):\n self.__rect_progress()\n pygame.draw.rect(self.superficie, self.color, self.rectangulo, 0) # dibujamos\n pygame.draw.rect(self.superficie, self.color_b3, self.rec_barra, 0) # dibujamos\n self.label_int.dibujar() \n\n ###################################################\n ### Obtener el valor del rectangulo de la barra ###\n ###################################################\n def __rect_progress(self):\n proporcion = (int(self.text)-self.min)/(self.max-self.min)\n self.ancho_barra = self.ancho * proporcion\n self.rec_barra = self.x, self.y, self.ancho_barra, self.alto\n \n\n","sub_path":"winform/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"116553627","text":"# -*- encoding: utf-8 -*-\nimport os\nimport hashlib\nfrom xml.etree.ElementTree import parse\n\n\ndef read_files_md5(path, file_ext, is_md5=True):\n files_md5_list = []\n files_md5_dict = {}\n path = os.listdir(path)\n for file in path:\n if str(file).split('.')[-1] == file_ext:\n pathname = os.path.join('./', file)\n fp = open(pathname, 'rb')\n contents = fp.read()\n fp.close()\n file_md5 = hashlib.md5(contents).hexdigest()\n file_name = file\n files_md5_list.append(file_name)\n files_md5_dict[file_name] = file_md5\n if is_md5:\n return files_md5_dict\n return files_md5_list\n\n\ndef read_xml_files_md5(xml_name, res):\n phone_name = 'Phone_' + str(str(xml_name).split('_')[-1]).split('.')[0] + '.zip'\n dom = parse(xml_name)\n root = dom.getroot()\n xml_md5_dict = {'resources.zip': root.find('LobbyResMD5').text, 'lua.zip': root.find('LobbyLuaMD5').text,\n phone_name: root.find('LobbyPhoneZipMD5').text, }\n if xml_md5_dict['resources.zip'] != res['resources.zip']:\n root.find('LobbyResMD5').text = str(res['resources.zip'])\n root.find('LobbyResVersion').text = str(int(root.find('LobbyResVersion').text) + 1)\n if xml_md5_dict['lua.zip'] != res['lua.zip']:\n root.find('LobbyLuaMD5').text = str(res['lua.zip'])\n root.find('LobbyLuaVersion').text = str(int(root.find('LobbyLuaVersion').text) + 1)\n if xml_md5_dict[phone_name] != res[phone_name]:\n root.find('LobbyPhoneZipMD5').text = str(res[phone_name])\n root.find('LobbyPhoneZipVersion').text = str(int(root.find('LobbyPhoneZipVersion').text) + 1)\n else:\n print('暂无更新内容!')\n dom.write(xml_name, xml_declaration=True, encoding=\"utf-8\", method=\"xml\")\n\n\nif __name__ == '__main__':\n file_dict = {}\n file_zip_dict = read_files_md5('./', 'zip', True)\n for one_zip_file in file_zip_dict:\n file_dict[one_zip_file] = file_zip_dict[one_zip_file]\n\n for one_xml_file in read_files_md5('./', 'xml', False):\n read_xml_files_md5(one_xml_file, file_dict)\n","sub_path":"Up_res/Up_res.py","file_name":"Up_res.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"280124621","text":"from django.shortcuts import render , redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse , HttpResponseRedirect\nfrom .forms import LoginForm , RegisterForm , QuestionForm , AnswerForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate , login , logout\nfrom django.shortcuts import render\nfrom .models import Question , Answer , Vote_q , Vote_a , up_notif_q , down_notif_q , up_notif_a , down_notif_a , answer_notif\nfrom Profile.models import Save , Interests\nimport re\n\ndef index(request):\n\tif request.user.is_authenticated:\n\t\treturn HttpResponseRedirect('/home/dashboard/')\n\tif request.method == 'POST':\n\t\tform = LoginForm(request.POST , prefix = 'form')\n\t\tif form.is_valid():\n\t\t\tprint(form.cleaned_data['Username'] , form.cleaned_data['Password'] )\n\t\t\tuser = authenticate(request , username = form.cleaned_data['Username'] , password = form.cleaned_data['Password'])\n\t\t\tif user is not None :\n\t\t\t\tlogin(request , user)\n\t\t\t\treturn HttpResponseRedirect('/home/dashboard/')\n\t\t\telse:\n\t\t\t\treturn HttpResponse(\"Invalid Credentials\")\n\t\telse:\n\t\t\tprint(form.errors)\n\t\t\treturn HttpResponse(\"1\")\n\telse:\n\t\tform = LoginForm(prefix = 'form')\n\t\treturn render(request , \"home/home.html\" , {'form':form})\n\n\ndef register(request):\n\tif request.user.is_authenticated:\n\t\treturn HttpResponseRedirect('/home/dashboard/')\n\tif request.method == 'POST':\n\t\tform = RegisterForm(request.POST , prefix = 'form')\n\t\tif form.is_valid():\n\t\t\tUser.objects.create_user(username = form.cleaned_data['username'] ,\n\t\t\t \t\t\t\t\t\tpassword = form.cleaned_data['password'] , email = form.cleaned_data['email'] , \n\t\t\t \t\t\t\t\t\tfirst_name = form.cleaned_data['first_name'] , last_name = form.cleaned_data['last_name'])\n\t\t\treturn redirect('index')\n\t\telse:\n\t\t\treturn HttpResponse(\"Try Again\")\n\telse:\n\t\tform = RegisterForm(prefix = 'form')\n\t\treturn render(request , \"home/register.html\", {'form':form})\n\n\n@login_required\ndef dashboard(request ):\n\tuser = User.objects.get(username = request.user)\n\tinterests = Interests.objects.filter(user = user )\n\tlist1 = []\n\tfor interest in interests:\n\t\tlist1.append(interest.interest)\n\t\t#print(list1 , l1)\n\tl1 = set(list1)\n\tquestion_id = set()\n\tquestions = Question.objects.all().exclude(user = user).order_by('-creation_date')\n\tfor question in questions:\n\t\tx = list(question.interests.split(\" \"))\n\t\tprint(x)\n\t\tl2 = set(x)\n\t\tif l1.intersection(l2):\n\t\t\tquestion_id.add(question.id)\n\tif question_id:\n\t\tquestions = Question.objects.filter(id__in = question_id).order_by('-creation_date')\n\telse:\n\t\tfor question in questions:\n\t\t\t question_id.add(question.id)\n\tanswers = Answer.objects.filter(question_id__in = question_id)\n\tups = Vote_q.objects.filter(question_id__in = question_id).filter(upvote = True)\n\tdowns = Vote_q.objects.filter(question_id__in = question_id).filter(downvote = True)\n\tfor question in questions:\n\t\tcount = 0\n\t\tfor up in ups:\n\t\t\tif up.question_id == question.id:\n\t\t\t\tcount += 1\n\t\tquestion.upvote = count\n\t\tquestion.save()\n\n\n\tfor question in questions:\n\t\tcount = 0\n\t\tfor down in downs:\n\t\t\tif down.question_id == question.id:\n\t\t\t\tcount += 1\n\t\tquestion.downvote = count\n\t\tquestion.save()\n\tanswer_id = set()\n\tfor answer in answers:\n\t\tanswer_id.add(answer.id)\n\tups = Vote_a.objects.filter(answer_id__in = answer_id).filter(upvote = True)\n\tdowns = Vote_a.objects.filter(answer_id__in = answer_id).filter(downvote = True)\n\tfor answer in answers:\n\t\tcount = 0\n\t\tfor up in ups:\n\t\t\tif up.answer_id == answer.id:\n\t\t\t\tcount += 1\n\t\tanswer.upvote = count\n\t\tanswer.save()\n\n\n\tfor answer in answers:\n\t\tcount = 0\n\t\tfor down in downs:\n\t\t\tif down.answer_id == answer.id:\n\t\t\t\tcount += 1\n\t\tanswer.downvote = count\n\t\tanswer.save()\n\n\ta = answer_notif.objects.filter(user = user).filter(read = False).count()\n\tb = up_notif_q.objects.filter(user = user).filter(read = False).count()\n\tc = down_notif_q.objects.filter(user = user).filter(read = False).count()\n\td = up_notif_a.objects.filter(user = user).filter(read = False).count()\n\te = down_notif_a.objects.filter(user = user).filter(read = False).count()\n\treturn render(request , \"home/dashboard.html\" , {'user':user , 'questions':questions ,'answers':answers ,'unread':(a+b+c+d+e)})\n\n\n@login_required\ndef logout_user(request):\n\tlogout(request)\n\treturn redirect('index')\n\n@login_required\ndef ask(request):\n\tuser = User.objects.get(username = request.user)\n\tif request.method == 'POST':\n\t\tform = QuestionForm(request.POST , prefix = \"form\")\n\t\tif form.is_valid():\n\t\t\tprint(type(form.cleaned_data['interests']))\n\n\t\t\tx = re.sub(\"[\\[\\]',]\",\"\",str(form.cleaned_data['interests']))\n\t\t\tquestion = Question(text = form.cleaned_data['text'] , explaination = form.cleaned_data['explanation'] \n\t\t\t\t\t\t\t\t, user = user , interests = x)\n\t\t\tprint(question.interests)\n\t\t\tquestion.save()\n\t\t\treturn HttpResponseRedirect('/home/dashboard/')\n\t\t\n\telse:\n\t\ta = answer_notif.objects.filter(user = user).filter(read = False).count()\n\t\tb = up_notif_q.objects.filter(user = user).filter(read = False).count()\n\t\tc = down_notif_q.objects.filter(user = user).filter(read = False).count()\n\t\td = up_notif_a.objects.filter(user = user).filter(read = False).count()\n\t\te = down_notif_a.objects.filter(user = user).filter(read = False).count()\n\t\tform = QuestionForm(prefix = 'form')\n\t\treturn render(request , 'home/ask.html' , {'form':form,'unread':(a+b+c+d+e)})\n\n@login_required\ndef answer(request , question_id):\n\tquestion = Question.objects.get(id = question_id)\n\tuser = User.objects.get(username = request.user)\n\tanswers = Answer.objects.filter(question_id = question.id).order_by('-creation_date')\n\tif request.method == \"POST\":\n\t\tform = AnswerForm(request.POST , prefix = 'form')\n\t\tif form.is_valid():\n\t\t\tanswer = Answer(user = user , text = form.cleaned_data['text'] , question = question)\n\t\t\ttry:\n\t\t\t\tanswer.save()\n\t\t\texcept:\n\t\t\t\treturn HttpResponse(\"you cannot answer twice\")\n\t\t\tnotif = answer_notif (user = question.user , answerer = request.user , qustion = question)\n\t\t\tnotif.save()\n\t\t\tquestion.answer_count += 1\n\t\t\tquestion.save()\n\t\t\treturn redirect(\"dashboard\")\n\n\telse:\n\t\tform = AnswerForm(prefix = 'form')\n\t\ta = answer_notif.objects.filter(user = user).filter(read = False).count()\n\t\tb = up_notif_q.objects.filter(user = user).filter(read = False).count()\n\t\tc = down_notif_q.objects.filter(user = user).filter(read = False).count()\n\t\td = up_notif_a.objects.filter(user = user).filter(read = False).count()\n\t\te = down_notif_a.objects.filter(user = user).filter(read = False).count()\n\t\treturn render(request , \"home/answer.html\" , {'form':form , 'question':question , 'answers':answers,'unread':(a+b+c+d+e)})\n\n@login_required\ndef question_upvote(request , question_id):\n\tquestion = Question.objects.get(id = question_id)\n\tuser = User.objects.get(username = request.user)\n\ttry:\n\t\tup = Vote_q.objects.get(question = question , user = user)\n\texcept:\n\t\tup = Vote_q(question = question , user = user )\n\tif up.upvote :\n\t\tup.upvote = False\n\telse:\n\t\tup.upvote = True\n\t\tup.downvote = False\n\t\tnotif = up_notif_q(user = question.user , voter = request.user , question = question)\n\t\tnotif.save()\n\tup.save()\n\treturn HttpResponseRedirect(\"/home/dashboard/\")\n\n@login_required\ndef question_downvote(request , question_id):\n\tquestion = Question.objects.get(id = question_id)\n\tuser = User.objects.get(username = request.user)\n\ttry:\n\t\tdown = Vote_q.objects.get(question = question , user = user)\n\texcept:\n\t\tdown = Vote_q(question = question , user = user )\n\tif down.downvote:\n\t\tdown.downvote = False\n\telse:\n\t\tdown.upvote = False\t\n\t\tdown.downvote = True\n\t\tnotif = down_notif_q(user = question.user , voter = request.user , question = question)\n\t\tnotif.save()\n\t\n\tdown.save()\n\treturn HttpResponseRedirect(\"/home/dashboard/\")\n\n\n@login_required\ndef answer_upvote(request , answer_id):\n\tanswer = Answer.objects.get(id = answer_id)\n\tuser = User.objects.get(username = request.user)\n\ttry:\n\t\tup = Vote_a.objects.get(answer = answer , user = user)\n\texcept:\n\t\tup = Vote_a(answer = answer , user = user )\n\tif up.upvote :\n\t\tup.upvote = False\n\telse:\n\t\tup.upvote = True\n\t\tup.downvote = False\n\t\tnotif = up_notif_a(user = answer.user , voter = request.user , answer = answer)\n\t\tnotif.save()\n\tup.save()\n\treturn HttpResponseRedirect(\"/home/dashboard/\")\n\n@login_required\ndef answer_downvote(request , answer_id):\n\tanswer = Answer.objects.get(id = answer_id)\n\tuser = User.objects.get(username = request.user)\n\ttry:\n\t\tdown = Vote_a.objects.get(answer = answer , user = user)\n\texcept:\n\t\tdown = Vote_a(answer = answer , user = user )\n\tif down.downvote:\n\t\tdown.downvote = False\n\telse:\n\t\tdown.upvote = False\t\n\t\tdown.downvote = True\n\t\tnotif = down_notif_a(user = answer.user , voter = request.user , answer = answer)\n\t\tnotif.save()\n\t\n\tdown.save()\n\treturn HttpResponseRedirect(\"/home/dashboard/\")\n\n@login_required\ndef save(request , question_id):\n\tquestion = Question.objects.get(id = question_id)\n\tuser = User.objects.get(username = request.user)\n\tc =0 \n\ttry:\n\t\tsave = Save.objects.get(question = question , user = user)\n\t\tc=1\n\texcept:\n\t\tsave = Save(question = question , user = user)\n\t\tc=2\n\t\n\tif c == 1:\n\t\tsave.delete()\n\telif c==2:\n\t\tsave.save()\n\n\treturn HttpResponseRedirect(\"/home/dashboard/\")\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"489294074","text":"from mpl_toolkits.mplot3d import Axes3D\r\nimport numpy as np\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.rcParams['legend.fontsize'] = 10\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\n\r\nprint(\"Programa que grafica una parabola que parte del origen y termina en los puntos (x,y) dados y su altura\")\r\nprint(\"A continuacion ingresa los puntos 'x' y 'y'\")\r\nx1 = int(input(\"x=\"))\r\ny1 = int(input(\"y=\"))\r\nprint(\"Ahora la altura\")\r\nh1 = int(input(\"h=\"))\r\nif x1 != 0 and y1 != 0:\r\n ec1 = np.array([x1 ** 2, x1, 0])\r\n ec2 = np.array([(x1/2) ** 2, x1 / 2, h1])\r\n var = np.array([[ec1[0], ec1[1]], [ec2[0], ec2[1]]])\r\n sols = np.array([ec1[2], ec2[2]])\r\n ab = np.linalg.solve(var, sols)\r\n a = ab[0]\r\n b = ab[1]\r\n t = np.linspace(0, x1, 100)\r\n tx = np.linspace(0, x1, 100)\r\n ty = np.linspace(0, y1, 100)\r\n z = (a * t**2) + b * t\r\n x = tx\r\n y = ty\r\n x2 = t + (y - x)\r\n y2 = t + (y - x)\r\n y3 = y1-x1\r\n ax.plot(x, y2, z, label='Parabola')\r\n print(\"Ecuacion parametrica: (t,t+\", y3, \",\", a, \"t^2+\", b, \"t)\")\r\n ax.legend()\r\n plt.show()\r\nelif x1 == 0 and y1 != 0:\r\n # print(\"x=0\")\r\n ec1 = np.array([y1 ** 2, y1, 0])\r\n ec2 = np.array([(y1 / 2) ** 2, y1 / 2, h1])\r\n var = np.array([[ec1[0], ec1[1]], [ec2[0], ec2[1]]])\r\n sols = np.array([ec1[2], ec2[2]])\r\n ab = np.linalg.solve(var, sols)\r\n a = ab[0]\r\n b = ab[1]\r\n t = np.linspace(0, y1, 100)\r\n z = a * t ** 2 + b * t\r\n y = t\r\n x = np.linspace(0, 0, 100)\r\n ax.plot(x, y, z, label='Parabola')\r\n print(\"Ecuacion parametrica= (0,t,\", a, \"t^2 +\", b, \"t\")\r\n ax.legend()\r\n plt.show()\r\nelif y1 == 0 and x1 != 0:\r\n # print(\"y=0\")\r\n ec1 = np.array([x1 ** 2, x1, 0])\r\n ec2 = np.array([(x1 / 2) ** 2, x1/2, h1])\r\n var = np.array([[ec1[0], ec1[1]], [ec2[0], ec2[1]]])\r\n sols = np.array([ec1[2], ec2[2]])\r\n ab = np.linalg.solve(var, sols)\r\n a = ab[0]\r\n b = ab[1]\r\n t = np.linspace(0, x1, 100)\r\n z = a * t**2 + b * t\r\n x = t\r\n y = np.linspace(0, 0, 100)\r\n ax.plot(x, y, z, label='Parabola')\r\n print(\"Ecuacion parametrica= (t,0,\", a, \"t^2 +\", b, \"t\")\r\n ax.legend()\r\n plt.show()\r\nelif x1 == 0 and y1 == 0:\r\n print(\"No es posible construir la parabola\")\r\n\r\n","sub_path":"parabola2.0.py","file_name":"parabola2.0.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"528709590","text":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.utils.testing import all_estimators\nimport warnings\nfrom sklearn.datasets import load_wine\n\nwarnings.filterwarnings('ignore')\n\ndataset = load_wine()\nx= dataset.data\ny = dataset.target\n\nx_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=32)\n\nallAlgorithms = all_estimators(type_filter='classifier')\n\nfor (name, algorithm) in allAlgorithms:\n try:\n model = algorithm()\n model.fit(x_train,y_train)\n y_pred = model.predict(x_test)\n print(name, '의 정답률 :', accuracy_score(y_test, y_pred))\n except:\n # continue\n print(name,'은 없는 놈!')\n\nimport sklearn\nprint(sklearn.__version__) # 0.23.2","sub_path":"ml/m09_selectModel_3_wine.py","file_name":"m09_selectModel_3_wine.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"62540346","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 3/20/18 2:46 PM \n\n@author: Hantian Liu\n\"\"\"\nimport load_data as ld\nimport numpy as np\nfrom rot_util import roty, rotx\nfrom math import cos\nimport pickle, os, pdb\nfrom mapping import bodyToGlobal\nimport matplotlib\nmatplotlib.use('TkAgg')\n#from matplotlib.path import Path\nimport matplotlib.pyplot as plt\n\ndef fit_plane(pitch, pts, eps):\n\t\"\"\"by setting up a threshold of eps\n\tdetermine whether the points fit the ground plane\n\n\t:param pitch: 1\n\t:param pts: n*3\n\t:param eps: 1, threshold for plane fitting\n\t:return: k, valid index of points on the ground\n\t\"\"\"\n\n\tpts_num=np.shape(pts)[0]\n\n\t# rotated normal vector to the ground plane\n\tnm_v=np.array([[0],[-1],[0]])\n\tnew_nm_v=np.dot(rotx(pitch), nm_v)\n\n\tplane=np.zeros([1,4])\n\tplane[0,0:3]=new_nm_v.flatten()\n\tplane[0,3]=(0.93+0.33+0.07*cos(pitch))\n\t#pts_homo=np.vstack((pts, np.ones([1, np.shape(pts)[1]])))\n\tpts_homo=np.hstack((pts, np.ones([pts_num, 1])))\n\tplane_mat=np.tile(plane, (pts_num, 1))\n\tto_zero=plane_mat*pts_homo #n*4\n\tto_zero=np.sum(to_zero, axis=1)\n\tto_zero=abs(to_zero) #n\n\tind_valid=np.where(to_zero<=eps)[0]\n\treturn ind_valid\n\n\ndef alignCams(R, t):\n\t\"\"\"get transformation from the depth/IR camera\n\tto the RGB camera\n\n\t:param R: from depth/IR cam to RGB cam\n\t:param t:\n\t:return: T 4*4\n\t\"\"\"\n\tT=np.zeros([4,4])\n\tT[0:3, 0:3]=R\n\tT[0:3,3]=t.flatten()/1000 # in meter now\n\tT[-1,-1]=1\n\treturn T\n\ndef img_to_world(fx, fy, px, py, u, v, Z):\n\t\"\"\"given camera intrinsic parameters, depth and 2D coordinates in camera frame,\n\tconvert to 3D coordinates in camera frame\n\n\t:param fx: 1\n\t:param fy: 1\n\t:param px: 1\n\t:param py: 1\n\t:param u: n\n\t:param v: n\n\t:param Z: n\n\t:return: n*3\n\t\"\"\"\n\tu=u.flatten()\n\tv=v.flatten()\n\tZ=Z.flatten()\n\tu2=u-512/2 #px\n\tv2=v-424/2 #py\n\tX=u2*Z/fx\n\tY=v2*Z/fy\n\tind=(Z>0.5) # invalid depth readings if Z>5m or Z<50cm\n\tind=ind*(Z<5)\n\tZ=Z[ind]\n\tX=X[ind]\n\tY=Y[ind]\n\tnum=len(Z)\n\tpts=np.zeros([num,3])\n\tpts[:,0]=X\n\tpts[:,1]=Y\n\tpts[:,2]=Z\n\treturn pts\n\ndef world_to_img(fx, fy, px, py, pts):\n\t\"\"\"given camera intrinsic parameters, 3D coordinates in camera frame,\n\tconvert to 2D coordinates in camera frame\n\n\t:param fx: 1\n\t:param fy: 1\n\t:param pts: n*3\n\t:return: n, n\n\t\"\"\"\n\tu=fx*pts[:,0]/pts[:,2]+1920/2#px\n\tv=fy*pts[:,1]/pts[:,2]+1080/2#py\n\treturn u, v\n\n\n\n\n","sub_path":"rgbd.py","file_name":"rgbd.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"560629331","text":"# mailtofax settings file\n\n# this is where the attachments will be temporarily stored. /tmp is probably\n# a good spot.\nTMP = '/tmp'\n\n# list of mime types to be interpreted as faxes\nFAX_MIME_TYPES = ['application/pdf']\n\n# sendfax command. Add all options here.\nSENDFAX = 'sendfax '\n\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"389062207","text":"\"\"\"\n128. Longest Consecutive Sequence\nMedium\n\nGiven an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.\n\nExample 1:\nInput: nums = [100,4,200,1,3,2]\nOutput: 4\nExplanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.\n\nExample 2:\nInput: nums = [0,3,7,2,5,8,4,6,0,1]\nOutput: 9\n\"\"\"\n\n\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n \"\"\"\n Define a hash set. For each element x, check if x-1 is in the set.\n If not, x is the start of the sequence. Check if x+1, x+2, ... is in the set and \n update the counter.\n \"\"\"\n res, vals = 0, set(nums)\n while vals:\n left = right = vals.pop()\n while left-1 in vals:\n vals.remove(left-1)\n left -= 1\n while right+1 in vals:\n vals.remove(right+1)\n right += 1\n res = max(res, right - left + 1)\n return res\n\n\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n \"\"\"\n Find the leftmost of the subseq then expand the right side\n Time: O(N), Space: O(N)\n \"\"\"\n vals = set(nums)\n res = 0\n for x in vals:\n if x - 1 not in vals:\n left = right = x\n while right + 1 in vals:\n right += 1\n res = max(res, right - left + 1)\n return res\n\n\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n \"\"\"\n First turn the input into a set of numbers. That takes O(n) and then we can ask in O(1) whether we have a certain number.\n Then go through the numbers. If the number x is the start of a streak (i.e., x-1 is not in the set), then test y = x+1, x+2, x+3, ... and stop at the first number y not in the set. The length of the streak is then simply y-x and we update our global best with that. Since we check each streak only once, this is overall O(n). This ran in 44 ms on the OJ, one of the fastest Python submissions.\n \"\"\"\n vals = set(nums)\n res = 0\n for x in vals:\n if x-1 not in vals:\n y = x + 1\n while y in vals:\n y += 1\n res = max(res, y-x)\n return res\n","sub_path":"python/128. Longest Consecutive Sequence.py","file_name":"128. Longest Consecutive Sequence.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"562511910","text":"__author__ = 'DreTaX'\n__version__ = '3.2b'\nimport clr\n\nclr.AddReferenceByPartialName(\"Fougerite\")\nimport Fougerite\nimport re\n\n\"\"\"\n Class\n\"\"\"\n\nclass DeathMSG:\n \"\"\"\n Methods\n \"\"\"\n red = \"[color #FF0000]\"\n green = \"[color #009900]\"\n\n def On_PluginInit(self):\n Util.ConsoleLog(\"DeathMSG by\" + __author__ + \" Version: \" + __version__ + \" loaded.\", False)\n\n def On_Command(self, Player, cmd, args):\n if cmd == \"uautoban\":\n if len(args) == 0:\n Player.Message(\"---DeathMSG 3.1---\")\n Player.Message(\"/uautoban name - Unbans player\")\n else:\n config = self.DeathMSGConfig()\n deathmsgname = config.GetSetting(\"Settings\", \"deathmsgname\")\n if not Player.Admin and not self.isMod(Player.SteamID):\n Player.MessageFrom(deathmsgname, \"You aren't an admin!\")\n return\n ini = self.DMB()\n pl = self.argsToText(args)\n id = self.GetPlayerUnBannedID(pl)\n ip = self.GetPlayerUnBannedIP(pl)\n if id is None:\n Player.Message(\"Target: \" + pl + \" isn't in the database, or you misspelled It!\")\n return\n iprq = ini.GetSetting(\"NameIps\", ip)\n idrq = ini.GetSetting(\"NameIds\", id)\n ini.DeleteSetting(\"Ips\", iprq)\n ini.DeleteSetting(\"Ids\", idrq)\n ini.DeleteSetting(\"NameIps\", ip)\n ini.DeleteSetting(\"NameIds\", id)\n ini.Save()\n Player.MessageFrom(deathmsgname, \"Player \" + pl + \" unbanned!\")\n\n def On_PlayerKilled(self, DeathEvent):\n if DeathEvent.DamageType is not None and DeathEvent.Victim is not None and DeathEvent.Attacker is not None:\n config = self.DeathMSGConfig()\n try:\n killer = str(DeathEvent.Attacker.Name)\n except:\n return\n victim = str(DeathEvent.Victim.Name)\n deathmsgname = config.GetSetting(\"Settings\", \"deathmsgname\")\n id = self.TrytoGrabID(DeathEvent.Attacker)\n vid = self.TrytoGrabID(DeathEvent.Victim)\n if self.IsAnimal(killer) and id is None:\n e = int(config.GetSetting(\"Settings\", \"enableanimalmsg\"))\n if e == 1:\n a = config.GetSetting(\"Settings\", \"animalkill\")\n a = a.replace(\"victim\", victim)\n a = a.replace(\"killer\", killer)\n Server.BroadcastFrom(deathmsgname, a)\n return\n if self.WasSuicide(int(id), int(vid)):\n e = int(config.GetSetting(\"Settings\", \"enablesuicidemsg\"))\n if e == 1:\n n = config.GetSetting(\"Settings\", \"suicide\")\n n = n.replace(\"victim\", victim)\n Server.BroadcastFrom(deathmsgname, n)\n return\n bodyPart = self.BD(DeathEvent.DamageEvent.bodyPart)\n weapon = DeathEvent.WeaponName\n damage = round(DeathEvent.DamageAmount, 2)\n killerloc = DeathEvent.Attacker.Location\n location = DeathEvent.Victim.Location\n distance = round(Util.GetVectorsDistance(killerloc, location), 2)\n bleed = str(DeathEvent.DamageType)\n kl = int(config.GetSetting(\"Settings\", \"killog\"))\n if bleed == \"Bullet\":\n message = config.GetSetting(\"Settings\", \"msg\")\n n = message.replace(\"victim\", victim)\n n = n.replace(\"killer\", killer)\n n = n.replace(\"weapon\", weapon)\n n = n.replace(\"damage\", str(damage))\n n = n.replace(\"number\", str(distance))\n n = n.replace(\"bodyPart\", str(bodyPart))\n Server.BroadcastFrom(deathmsgname, n)\n autoban = int(config.GetSetting(\"Settings\", \"autoban\"))\n if autoban == 1:\n if distance > self.RangeOf(weapon) > 0:\n tpfriendteleport = DataStore.Get(\"tpfriendautoban\", id)\n hometeleport = DataStore.Get(\"homesystemautoban\", id)\n if (tpfriendteleport == \"none\" or tpfriendteleport is None) and (hometeleport == \"none\" or hometeleport is None):\n z = config.GetSetting(\"Settings\", \"banmsg\")\n z = z.replace(\"killer\", killer)\n DeathEvent.Attacker.Kill()\n Server.BroadcastFrom(deathmsgname, self.red + z)\n ini = self.DMB()\n ip = DeathEvent.Attacker.IP\n ini.AddSetting(\"Ips\", ip, \"1\")\n ini.AddSetting(\"Ids\", id, \"1\")\n ini.AddSetting(\"NameIps\", killer, ip)\n ini.AddSetting(\"NameIds\", killer, id)\n ini.AddSetting(\"Logistical\", killer, \"Gun: \" + weapon + \" Dist: \" + str(distance) + \" BodyP: \" + bodyPart + \" DMG: \" + str(damage))\n ini.Save()\n DeathEvent.Attacker.Disconnect()\n DataStore.Add(\"DeathMSGBAN\", vid, str(location))\n else:\n t = config.GetSetting(\"Settings\", \"TpaMsg\")\n t = t.replace(\"killer\", killer)\n Server.BroadcastFrom(deathmsgname, t)\n if kl == 1:\n self.Log(killer, weapon, distance, victim, bodyPart, damage, 1)\n return\n if kl == 1:\n self.Log(killer, weapon, distance, victim, bodyPart, damage, None)\n elif bleed == \"Melee\":\n if damage == 75:\n hn = config.GetSetting(\"Settings\", \"huntingbow\")\n hn = hn.replace(\"victim\", victim)\n hn = hn.replace(\"killer\", killer)\n hn = hn.replace(\"damage\", str(damage))\n hn = hn.replace(\"number\", str(distance))\n hn = hn.replace(\"bodyPart\", str(bodyPart))\n Server.BroadcastFrom(deathmsgname, hn)\n autoban = int(config.GetSetting(\"Settings\", \"autoban\"))\n if autoban == 1:\n if distance > self.RangeOf(weapon) and self.RangeOf(weapon) > 0:\n tpfriendteleport = DataStore.Get(\"tpfriendautoban\", id)\n hometeleport = DataStore.Get(\"homesystemautoban\", id)\n if (tpfriendteleport == \"none\" or tpfriendteleport is None) and (hometeleport == \"none\" or hometeleport is None):\n z = config.GetSetting(\"Settings\", \"banmsg\")\n z = z.replace(\"killer\", killer)\n DeathEvent.Attacker.Kill()\n Server.BroadcastFrom(deathmsgname, self.red + z)\n ini = self.DMB()\n ip = DeathEvent.Attacker.IP\n ini.AddSetting(\"Ips\", ip, \"1\")\n ini.AddSetting(\"Ids\", id, \"1\")\n ini.AddSetting(\"NameIps\", killer, ip)\n ini.AddSetting(\"NameIds\", killer, id)\n ini.AddSetting(\"Logistical\", killer, \"Gun: Hunting Bow Dist: \" + str(distance) + \" BodyP: \" + str(bodyPart) + \" DMG: \" + str(damage))\n ini.Save()\n DeathEvent.Attacker.Disconnect()\n DataStore.Add(\"DeathMSGBAN\", vid, str(location))\n else:\n t = config.GetSetting(\"Settings\", \"TpaMsg\")\n t = t.replace(\"killer\", killer)\n Server.BroadcastFrom(deathmsgname, t)\n if kl == 1:\n self.Log(killer, \"Hunting Bow\", distance, victim, str(bodyPart), damage, 1)\n return\n if kl == 1:\n self.Log(killer, \"Hunting Bow\", distance, victim, str(bodyPart), damage, None)\n elif damage == 10 or damage == 15:\n s = config.GetSetting(\"Settings\", \"spike\")\n s = s.replace(\"victim\", victim)\n s = s.replace(\"killer\", killer)\n s = s.replace(\"weapon\", \"Spike Wall\")\n Server.BroadcastFrom(deathmsgname, s)\n else:\n n = config.GetSetting(\"Settings\", \"msg\")\n n = n.replace(\"victim\", victim)\n n = n.replace(\"killer\", killer)\n n = n.replace(\"weapon\", weapon)\n n = n.replace(\"damage\", str(damage))\n n = n.replace(\"number\", str(distance))\n n = n.replace(\"bodyPart\", str(bodyPart))\n Server.BroadcastFrom(deathmsgname, n)\n elif bleed == \"Explosion\":\n x = config.GetSetting(\"Settings\", \"explosionmsg\")\n x = x.replace(\"killer\", killer)\n x = x.replace(\"victim\", victim)\n x = x.replace(\"weapon\", \"C4/F1 Grenade\")\n Server.BroadcastFrom(deathmsgname, x)\n elif bleed == \"Bleeding\":\n n = config.GetSetting(\"Settings\", \"bmsg\")\n n = n.replace(\"victim\", victim)\n n = n.replace(\"killer\", killer)\n Server.BroadcastFrom(deathmsgname, n)\n\n def On_PlayerSpawned(self, Player, SpawnEvent):\n id = Player.SteamID\n if DataStore.ContainsKey(\"DeathMSGBAN\", id):\n get = DataStore.Get(\"DeathMSGBAN\", id)\n loc = self.Replace(get)\n newloc = Util.CreateVector(float(loc[0]), float(loc[1]), float(loc[2]))\n Player.TeleportTo(newloc)\n config = self.DeathMSGConfig()\n deathmsgname = config.GetSetting(\"Settings\", \"deathmsgname\")\n Player.MessageFrom(deathmsgname, self.green + \"You got teleported back where you died!\")\n DataStore.Remove(\"DeathMSGBAN\", id)\n\n def On_PlayerConnected(self, Player):\n ini = self.DMB()\n id = self.TrytoGrabID(Player)\n if id is None:\n try:\n Player.Disconnect()\n except:\n pass\n return\n config = self.DeathMSGConfig()\n deathmsgname = config.GetSetting(\"Settings\", \"deathmsgname\")\n ip = Player.IP\n if ini.GetSetting(\"Ips\", ip) is not None and int(ini.GetSetting(\"Ips\", ip)) == 1:\n Player.MessageFrom(deathmsgname, \"You are banned from this server\")\n Player.Disconnect()\n elif ini.GetSetting(\"Ids\", id) is not None and int(ini.GetSetting(\"Ids\", id)) == 1:\n Player.MessageFrom(deathmsgname, \"You are banned from this server\")\n Player.Disconnect()\n\n def TrytoGrabID(self, Player):\n try:\n id = Player.SteamID\n return id\n except:\n return None\n\n def argsToText(self, args):\n text = str.join(\" \", args)\n return text\n\n def Log(self, killer, weapon, dist, victim, body, dmg, tp):\n if tp is None:\n Plugin.Log(\"KillLog\", \" Killer: \" + killer + \" Gun: \" + weapon + \" Dist: \" + str(dist) + \" Victim: \" + victim + \" BodyP: \" + str(body) + \" DMG: \" + str(dmg))\n else:\n Plugin.Log(\"KillLog\", \" Killer: \" + killer + \" Gun: \" + weapon + \" Dist: \" + str(dist) + \" Victim: \" + victim + \" BodyP: \" + str(body) + \" DMG: \" + str(dmg) + \" WAS TELEPORTING\")\n\n def IsAnimal(self, killer):\n if killer == 'Wolf' or killer == 'Bear' or killer == 'MutantWolf' or killer == 'MutantBear':\n return True\n return False\n\n def WasSuicide(self, killerid, victimid):\n if killerid == victimid:\n return True\n return False\n\n def isMod(self, id):\n if DataStore.ContainsKey(\"Moderators\", id):\n return True\n return False\n\n def BD(self, bodyp):\n ini = self.Bodies()\n bodyp = str(bodyp)\n name = ini.GetSetting(\"bodyparts\", bodyp)\n return str(name)\n\n def Bodies(self):\n return Plugin.GetIni(\"bodyparts\")\n\n def DeathMSGConfig(self):\n return Plugin.GetIni(\"DeathMSGConfig\")\n\n def DMB(self):\n return Plugin.GetIni(\"BannedPeopleDM\")\n\n def GetPlayerUnBannedIP(self, name):\n ini = self.DMB()\n name = name.lower()\n checkdist = ini.EnumSection(\"NameIps\")\n for pl in checkdist:\n nameid = ini.GetSetting(\"NameIps\", pl)\n if nameid is not None and pl.lower() == name:\n return str(pl)\n return None\n\n def GetPlayerUnBannedID(self, name):\n ini = self.DMB()\n name = name.lower()\n checkdist = ini.EnumSection(\"NameIds\")\n for pl in checkdist:\n nameid = ini.GetSetting(\"NameIds\", pl)\n if nameid is not None and pl.lower() == name:\n return str(pl)\n return None\n\n def RangeOf(self, weapon):\n ini = Plugin.GetIni(\"range\")\n range = ini.GetSetting(\"range\", weapon)\n return int(range)\n\n def Replace(self, s):\n s = re.sub('[(\\)\\]]', '', s)\n s = s.split(\",\")\n return s","sub_path":"DeathMSG/DeathMSG.py","file_name":"DeathMSG.py","file_ext":"py","file_size_in_byte":13541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"526876178","text":"from models import (\n user_model, state_model,\n region_model, instance_model,\n cluster_model, machine_model,\n machine_tags_model\n)\n\n\ndef migrate_base_models(model_list):\n for model in model_list:\n model.migrate()\n\n\ndef migrate_models(model_list):\n for model in model_list:\n model.migrate()\n\n\ndef drop_table(model_list):\n for model in model_list:\n model.drop_table()\n\n\ndef migrate_all():\n ''' base models '''\n user_model_obj = user_model.UserModel()\n state_model_obj = state_model.StateModel()\n region_model_obj = region_model.RegionModel()\n instance_model_obj = instance_model.InstanceModel()\n\n ''' foreign key models '''\n cluster_model_obj = cluster_model.ClusterModel()\n machine_model_obj = machine_model.MachineModel()\n machine_tags_model_obj = machine_tags_model.MachineTagsModel()\n\n migrate_base_models(\n [user_model_obj, state_model_obj,\n region_model_obj, instance_model_obj]\n )\n\n migrate_models(\n [cluster_model_obj, machine_model_obj,\n machine_tags_model_obj]\n )\n","sub_path":"models/migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"15776616","text":"import sys\nfrom PyQt4 import QtCore, QtGui\n\n#===============================================================================\n# MyCheckBox\n#===============================================================================\n#className\nclass MyCheckBox(QtGui.QCheckBox):\n#|-----------------------------------------------------------------------------|\n# class Variables\n#|-----------------------------------------------------------------------------| \n unchecked_signal = QtCore.pyqtSignal()\n checked_signal = QtCore.pyqtSignal()\n \n#|-----------------------------------------------------------------------------|\n# Constructor \n#|-----------------------------------------------------------------------------|\n def __init__(self, *args, **kwargs):\n QtGui.QCheckBox.__init__(self, *args, **kwargs)\n self.setStyleSheet(\"background-color: rgb(0, 0, 0);\\n\" + \n \"color: rgb(255, 255, 255);\\n\")\n #set default check as False \n self.setChecked(False)\n #set default enable as True\n # if it set to false will always remain on/off\n # here it is on as setChecked is True\n self.setEnabled(True)\n self._enable = True\n#|--------------------------End of Constructor---------------------------------| \n#|-----------------------------------------------------------------------------|\n# mousePressEvent\n#|-----------------------------------------------------------------------------|\n #overrite \n def mousePressEvent(self, *args, **kwargs):\n #tick on and off set here\n if self.isChecked():\n self.setChecked(False)\n self.unchecked_signal.emit()\n else:\n self.setChecked(True)\n self.checked_signal.emit()\n #return QtGui.QCheckBox.mousePressEvent(self, *args, **kwargs)\n#|--------------------------End of mousePressEvent-----------------------------| \n\n#|-----------------------------------------------------------------------------| \n# paintEvent\n#|-----------------------------------------------------------------------------|\n def paintEvent(self,event):\n\n #just setting some size aspects\n self.setMinimumHeight(40)\n self.setMinimumWidth(100)\n self.setMaximumHeight(50)\n self.setMaximumWidth(150)\n\n self.resize(self.parent().width(),self.parent().height())\n painter = QtGui.QPainter()\n painter.begin(self)\n\n #for the black background\n brush = QtGui.QBrush(QtGui.QColor(0,0,0),style=QtCore.Qt.SolidPattern)\n painter.fillRect(self.rect(),brush)\n\n\n #smooth curves\n painter.setRenderHint(QtGui.QPainter.Antialiasing)\n\n #for the on off font\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPixelSize(28)\n painter.setFont(font) \n\n #change the look for on/off\n if self.isChecked():\n #blue fill\n brush = QtGui.QBrush(QtGui.QColor(50,50,255),style=QtCore.Qt.SolidPattern)\n painter.setBrush(brush)\n\n #rounded rectangle as a whole\n painter.drawRoundedRect(0,0,self.width()-2,self.height()-2, \\\n self.height()/2,self.height()/2)\n\n #white circle/button instead of the tick mark\n brush = QtGui.QBrush(QtGui.QColor(255,255,255),style=QtCore.Qt.SolidPattern)\n painter.setBrush(brush)\n painter.drawEllipse(self.width()-self.height(),0,self.height(),self.height())\n\n #on text\n painter.drawText(self.width()/4,self.height()/1.5, \"On\")\n\n else:\n #gray fill\n brush = QtGui.QBrush(QtGui.QColor(50,50,50),style=QtCore.Qt.SolidPattern)\n painter.setBrush(brush)\n\n #rounded rectangle as a whole\n painter.drawRoundedRect(0,0,self.width()-2,self.height()-2, \\\n self.height()/2,self.height()/2)\n\n #white circle/button instead of the tick but in different location\n brush = QtGui.QBrush(QtGui.QColor(255,255,255),style=QtCore.Qt.SolidPattern)\n painter.setBrush(brush)\n painter.drawEllipse(0,0,self.height(),self.height())\n\n #off text\n painter.drawText(self.width()/2,self.height()/1.5, \"Off\")\n\n\n\n","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"208767721","text":"#!/usr/bin/python3\nimport os\nimport fnmatch\nimport time\nimport subprocess\nimport datetime\nimport sys\nfrom bs4 import BeautifulSoup\n\nappname = \"ZeroBB\"\napptmpdir = '/tmp/'+appname\nappname = \"ZeroBB\"\nwebappname = \"ZeroBB\"\n# appname = \"ROOT\" # tomcat 根目錄\ndbname = appname.lower()\ngitrepo = \"https://github.com/ztokamak/\" + appname + \".git\"\nfor file in os.listdir('/etc/init.d/'):\n if fnmatch.fnmatch(file, 'tomcat*'):\n tomcatN = file\n\n\ndef printFile(path):\n print('--------------------------------------------------------')\n f = open(path,'r')\n lines = f.read()\n print(lines)\n print('--------------------------------------------------------')\n f.close()\n\ndef os_exec(cmd):\n print('cmd=' + cmd)\n os.system(cmd)\n\n\ndef importSQL(dbname):\n print(\"sqlfile 列表:\")\n sqllist = []\n for sqlfile in os.listdir(apptmpdir):\n if fnmatch.fnmatch(sqlfile, '*.sql'):\n sqllist.append(sqlfile)\n\n for sqlfile in sqllist:\n print(str(sqllist.index(sqlfile,)) + \". \" + sqlfile)\n print(str(len(sqllist)) + \". exit\")\n \n index = input(\"請選擇要匯入的資料庫檔案 *.sql? \")\n if index == str(len(sqllist)):\n return False\n\n # dbname = input(\"準備匯入 \" + sqllist[int(index)] + \", 請輸入資料庫名稱:\")\n # cmd = 'cat ' + apptmpdir + '/' + sqlfile + ' | mysql -u root -p'\n # cmd = 'mysql -u root -p ' + dbname + ' < ' + apptmpdir + '/' + sqlfile\n # print(cmd)\n # os.system(cmd)\n\n cmd = \"mysql -uroot -p \" + dbname + \" < \" + apptmpdir + \"/\" + sqlfile\n print(\"匯入資料表到此資料庫: \" + cmd)\n os.system(cmd)\n \n return True\n\n\n##### MAIN #############\nos.system(\"sudo apt-get install ant\")\n\nos.system('rm -rf ' + apptmpdir)\nos.system('mkdir ' + apptmpdir)\n\n#git clone https://github.com/ztokamak/ZeroBB.git\nos_exec(\"git clone \"+gitrepo+\" \" + apptmpdir)\n# 取得目前版本號:\n\nfor currentVersion in open(apptmpdir + '/WebContent/META-INF/Version.txt', 'r', encoding='UTF-8'):\n print('currentVersion=',currentVersion)\n\n# 列出版本號\ncmd = 'git --git-dir=' + apptmpdir + '/.git --work-tree=' + apptmpdir + ' tag '\nprint(\"cmd=\" + cmd)\ntags = subprocess.check_output(cmd.split()).decode('utf-8').rstrip().split('\\n')\n\ndef compareVersion(ver):\n ver = ver.lower()\n ver.replace('v', '')\n nums = ver.split('.')\n ans = 0\n base = 1\n for num in reversed(nums):\n ans += int(num)*base\n base *= 1000\n return ans\n\nfor index, tag in enumerate(sorted(tags, key=compareVersion)):\n print(str(index) + \". tag=\" + tag)\n\ntagindex = input(\"請問要取出哪一個 tag 版本? \")\nos_exec('git --git-dir=' + apptmpdir + '/.git --work-tree=' + apptmpdir + ' checkout ' + tags[int(tagindex)])\nopen(apptmpdir + '/WebContent/META-INF/Version.txt', mode='w', encoding='utf-8').write(tags[int(tagindex)])\n\ncmd = \"mysqladmin -u root -p create \" + dbname\nprint(\"建立一個備份資料庫: \")\nos_exec(\"mysqladmin -u root -p create \" + dbname)\n\n#importSQL(dbname)\n\nprint(\"匯入完整資料表到資料庫(\"+dbname+\"): \")\n\nschemasql = \"\"\nfor filename in os.listdir(apptmpdir):\n if fnmatch.fnmatch(filename, 'Schema*.sql'):\n schemasql = filename\nif schemasql != \"\":\n os_exec(\"mysql -uroot -p \" + dbname + \" < \" + apptmpdir + \"/\"+schemasql)\n\nschemaupdatesql = \"\"\nfor filename in os.listdir(apptmpdir):\n if fnmatch.fnmatch(filename, 'SchemaUpdate*.sql'):\n schemaupdatesql = filename\nif schemaupdatesql != \"\":\n print(\"資料庫(\"+dbname+\") 進行資料表升級: \")\n os_exec(\"mysql -uroot -p \" + dbname + \" < \" + apptmpdir + \"/\"+schemaupdatesql)\n\nprint(\"開始打包\")\nos_exec('ant -f ' + apptmpdir + '/build.xml -Dappname=' + appname + ' -DTOMCAT_HOME=/usr/share/' + tomcatN + '/')\n\nprint(\"開始發布\")\nos_exec('/etc/init.d/'+tomcatN+' restart')\nos_exec('rm -rf /var/lib/' + tomcatN + '/webapps/' + webappname + '/')\nos_exec('cp ' + apptmpdir + '/' + appname + '.war /var/lib/' + tomcatN + '/webapps/' + webappname + '.war')\n\n#os_exec('python3 /var/lib/' + tomcatN + '/webapps/' + appname + '/Setup.py')\ncontextpath = '/var/lib/' + tomcatN + '/webapps/'+appname+'/META-INF/context.xml'\nprint(\"Waiting\", end=\"\")\nwhile not os.path.isfile(contextpath):\n print(\".\", end=\"\")\n time.sleep(3)\nprint()\n\nprint(\"開始設定資料庫\")\ncontext = open(contextpath, 'r+', encoding='UTF-8')\ncontextsoup = BeautifulSoup(context, 'xml')\nresource = contextsoup.find('Resource')\nusername = input(\"請輸入資料庫帳號(\"+resource['username']+\"):\")\nif username != \"\":\n resource['username'] = username\npassword = input(\"請輸入資料庫密碼(\"+resource['password']+\"):\")\nif password != \"\":\n resource['password'] = password\n\nos_exec('true > '+ contextpath)\ncontext.seek(0, 0)\ncontext.write(str(contextsoup))\ncontext.close()\n\nos_exec('/etc/init.d/'+tomcatN+' restart')\n","sub_path":"checkNew.py","file_name":"checkNew.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"617765950","text":"#\n# @lc app=leetcode.cn id=25 lang=python\n#\n# [25] K 个一组翻转链表\n#\n# https://leetcode-cn.com/problems/reverse-nodes-in-k-group/description/\n#\n# algorithms\n# Hard (54.60%)\n# Likes: 354\n# Dislikes: 0\n# Total Accepted: 34.5K\n# Total Submissions: 61.9K\n# Testcase Example: '[1,2,3,4,5]\\n2'\n#\n# 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。\n# \n# k 是一个正整数,它的值小于或等于链表的长度。\n# \n# 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。\n# \n# 示例 :\n# \n# 给定这个链表:1->2->3->4->5\n# \n# 当 k = 2 时,应当返回: 2->1->4->3->5\n# \n# 当 k = 3 时,应当返回: 3->2->1->4->5\n# \n# 说明 :\n# \n# \n# 你的算法只能使用常数的额外空间。\n# 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。\n# \n# \n#\n\n# @lc code=start\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def reverseKGroup(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n # 竟然是卡在一个逆序上面\n def reverse(head,left_all,N):\n pre = left_all\n\n for i in range(N):\n nexttemp = head.next\n head.next = pre\n pre = head\n head = nexttemp\n return pre \n\n # 先实现一个k=2\n\n # 判断接下来的N个节点是否为空\n def nextNisempty(head,N):\n # Nlist = []\n for i in range(N):\n if head == None:\n return True,None\n # 记录K区间内的所有节点\n # Nlist.append(head)\n head = head.next\n left_all = head\n return False,left_all\n\n\n first = None\n\n isempty,left_all = nextNisempty(head,k)\n if not isempty ==True:\n pt = reverse(head,self.reverseKGroup(left_all,k),k)\n # 最后一次交换比较特殊,首节点指向剩余所有的\n return pt\n else:\n return head\n \n \n# @lc code=end\na1 = ListNode(1)\na1.next = ListNode(2)\na1.next.next = ListNode(3)\na1.next.next.next = ListNode(4)\na1.next.next.next.next = ListNode(5)\n\nk = 3\n\n\nsolu = Solution()\nans = solu.reverseKGroup(a1,k)\nwhile not ans == None:\n print(ans.val)\n ans = ans.next\n\n","sub_path":"25.k-个一组翻转链表.py","file_name":"25.k-个一组翻转链表.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"36577890","text":"\"\"\"\r\nModule takes script name as argument, updates config parameter values\r\nfrom file bamboo_env_file and runs required script\r\n\"\"\"\r\nfrom os import path, system\r\nimport configparser\r\nimport re\r\nimport argparse\r\nfrom libs.files import do\r\nfrom libs.tm_log import get_logger\r\n\r\nlogger = None\r\n\r\n\r\ndef is_config_variable(key: str) -> bool:\r\n \"\"\"\r\n Check if the string matches config option pattern\r\n :param key: string to be checked\r\n :return: bool\r\n \"\"\"\r\n return bool(re.search(r'(GENERAL|NOTFOUND|BDD|EXECUTION|ROCS|JUNIT|JSON|LOGGING)_([a-z]+(?:_[a-z]+)*)', key))\r\n\r\n\r\ndef split_option(file_obj) -> dict:\r\n \"\"\"\r\n Function splits file contents in format key=value into\r\n {key:value} dict\r\n :param file_obj:\r\n :return: dict\r\n \"\"\"\r\n result = list()\r\n for item in file_obj.readlines():\r\n if len(item.split(\"=\")) == 2:\r\n result.append(item.split(\"=\"))\r\n else:\r\n logger.error(f'Cannot split&use string {item} properly: it must have name=value format')\r\n return {r[0]: r[1] for r in result}\r\n\r\n\r\ndef main():\r\n global logger\r\n try:\r\n config = configparser.ConfigParser()\r\n config.optionxform = lambda option: option # overriding to aviod lowercasing the options\r\n do('parseconfig.ini', 'r', config.read_file)\r\n logger = get_logger(__name__, config)\r\n bb_variables = do('bamboo_env_file', 'r', split_option)\r\n for (k, v) in bb_variables.items():\r\n key = k.strip('bamboo_')\r\n if is_config_variable(key):\r\n option = key.split('_')\r\n try:\r\n if config.has_option(option[0], option[1]):\r\n config.set(option[0], option[1], v)\r\n logger.info(f'Updated config parameter: [{option[0]}][{option[1]}] = {v}')\r\n else:\r\n logger.error(f'No [{option[1]}] option found in [{option[0]}] section of parseconfig.ini file')\r\n except configparser.NoSectionError:\r\n logger.error(f'No [{option[0]}] section found in parseconfig.ini file')\r\n do('parseconfig.ini', 'w', config.write)\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-s\", \"--script\", help=\"Script name to run\")\r\n args = parser.parse_known_args()\r\n script_file = path.join(path.abspath(path.dirname(__file__)), f'{args[0].script}.py')\r\n script_args = ' '.join(args[1])\r\n command = f'{script_file} {script_args}'\r\n logger.info(f'Executing script {command}')\r\n system(f'python {command}')\r\n except Exception as e:\r\n logger.exception(e)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"tm4j_adapter/bamboo_runner.py","file_name":"bamboo_runner.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"314895078","text":"from bs4 import BeautifulSoup\nimport os\n\nbs = BeautifulSoup(open('Scripts/ebml_matroska.xml'), \"html.parser\")\nelements = bs.find_all('element')\n\nfor element in elements:\n name = element['name']\n path = element['path']\n id_ = element['id']\n t = element['type']\n type_map = {\n \"integer\": \"i\",\n \"uinteger\": \"u\",\n \"float\": \"d\",\n \"string\": \"s\",\n \"utf-8\": \"8\",\n \"date\": \"D\",\n \"master\": \"m\",\n \"binary\": \"b\"\n }\n t = type_map[t]\n os.system(f\"python Scripts/generate_tag.py {name.lower()} {name} {id_} {path} -t {t}\")\n","sub_path":"Scripts/matroska_generator.py","file_name":"matroska_generator.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"377437887","text":"from pathlib import Path\nimport json\nimport re\n\n\nclass ReservedWords:\n def __init__(self, path: Path):\n with open(path, encoding='UTF8') as json_file:\n json_data = json.load(json_file)\n self.data = json_data\n self.keys = list(self.data.keys())\n self.compile = re.compile(\"(\"+\")|(\".join(self.keys)+\")\")\n\n def translate(self, line: str):\n for group, idx in sorted([(m.group(), m.groups().index(m.group())) for m in self.compile.finditer(line)], key=lambda x: x[0], reverse=True):\n line = re.sub(group, self.data[self.keys[idx]], line)\n return line\n","sub_path":"docs_translate/reserved_word.py","file_name":"reserved_word.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"617334533","text":"#!/usr/bin/python\n\n#\n# Stress test tool for elasticsearch\n# Written by Roi Rav-Hon @ Logz.io (roi@logz.io)\n#\n\n# Using argparse to parse cli arguments\nimport argparse\n\n# Import threading essentials\nfrom threading import Lock, Thread, Condition\n\n# For randomizing\nimport string\nfrom random import randint, choice\n\n# To get the time\nimport time\n\n# For misc\nimport sys\n\n# For json operations\nimport json\n\n# Try and import elasticsearch\ntry:\n from elasticsearch import Elasticsearch\n\nexcept:\n print(\"Could not import elasticsearch..\")\n print(\"Try: pip install elasticsearch\")\n sys.exit(1)\n\n# Set a parser object\nparser = argparse.ArgumentParser()\n\n# Adds all params\nparser.add_argument(\"es_address\", help=\"The address of your cluster (no protocol or port)\")\nparser.add_argument(\"indices\", type=int, help=\"The number of indices to write to\")\nparser.add_argument(\"documents\", type=int, help=\"The number different documents to write\")\nparser.add_argument(\"clients\", type=int, help=\"The number of clients to write from\")\nparser.add_argument(\"seconds\", type=int, help=\"The number of seconds to run\")\nparser.add_argument(\"--number-of-shards\",type=int, default=3, help=\"Number of shards per index (default 3)\")\nparser.add_argument(\"--number-of-replicas\",type=int, default=1, help=\"Number of replicas per index (default 1)\")\nparser.add_argument(\"--bulk-size\",type=int, default=1000, help=\"Number of document per request (default 1000)\")\nparser.add_argument(\"--max-fields-per-document\",type=int, default=100,\n help=\"Max number of fields in each document (default 100)\")\nparser.add_argument(\"--max-size-per-field\",type=int, default=1000, help=\"Max content size per field (default 1000\")\nparser.add_argument(\"--no-cleanup\", default=False, action='store_true', help=\"Don't delete the indices upon finish\")\nparser.add_argument(\"--stats-frequency\",type=int, default=30,\n help=\"Number of seconds to wait between stats prints (default 30)\")\n\n# Parse the arguments\nargs = parser.parse_args()\n\n# Set variables from argparse output (for readability)\nES_ADDRESS = args.es_address\nNUMBER_OF_INDICES = args.indices\nNUMBER_OF_DOCUMENTS = args.documents\nNUMBER_OF_CLIENTS = args.clients\nNUMBER_OF_SECONDS = args.seconds\nNUMBER_OF_SHARDS = args.number_of_shards\nNUMBER_OF_REPLICAS = args.number_of_replicas\nBULK_SIZE = args.bulk_size\nMAX_FIELDS_PER_DOCUMENT = args.max_fields_per_document\nMAX_SIZE_PER_FIELD = args.max_size_per_field\nNO_CLEANUP = args.no_cleanup\nSTATS_FREQUENCY = args.stats_frequency\n\n# timestamp placeholder\nSTARTED_TIMESTAMP = 0\n\n# Placeholders\nsuccess_bulks = 0\nfailed_bulks = 0\ntotal_size = 0\nindices = []\ndocuments = []\ndocuments_templates = []\nes = None # Will hold the elasticsearch session\n\n# Thread safe\nsuccess_lock = Lock()\nfail_lock = Lock()\nsize_lock = Lock()\n\n\n# Helper functions\ndef increment_success():\n\n # First, lock\n success_lock.acquire()\n\n try:\n # Using globals here\n global success_bulks\n\n # Increment counter\n success_bulks += 1\n\n finally: # Just in case\n # Release the lock\n success_lock.release()\n\n\ndef increment_failure():\n\n # First, lock\n fail_lock.acquire()\n\n try:\n # Using globals here\n global failed_bulks\n\n # Increment counter\n failed_bulks += 1\n\n finally: # Just in case\n # Release the lock\n fail_lock.release()\n\n\ndef increment_size(size):\n\n # First, lock\n size_lock.acquire()\n\n try:\n # Using globals here\n global total_size\n\n # Increment counter\n total_size += size\n\n finally: # Just in case\n # Release the lock\n size_lock.release()\n\n\ndef has_timeout():\n\n # Match to the timestamp\n if (STARTED_TIMESTAMP + NUMBER_OF_SECONDS) > int(time.time()):\n return False\n\n return True\n\n\n# Just to control the minimum value globally (though its not configurable)\ndef generate_random_int(max_size):\n\n try:\n return randint(1, max_size)\n except:\n print(\"Not supporting {0} as valid sizes!\".format(max_size))\n sys.exit(1)\n\n\n# Generate a random string with length of 1 to provided param\ndef generate_random_string(max_size):\n\n return ''.join(choice(string.ascii_lowercase) for _ in range(generate_random_int(max_size)))\n\n\n# Create a document template\ndef generate_document():\n\n temp_doc = {}\n\n # Iterate over the max fields\n for _ in range(generate_random_int(MAX_FIELDS_PER_DOCUMENT)):\n\n # Generate a field, with random content\n temp_doc[generate_random_string(10)] = generate_random_string(MAX_SIZE_PER_FIELD)\n\n # Return the created document\n return temp_doc\n\n\ndef fill_documents():\n\n # Generating 10 random subsets\n for _ in range(10):\n\n # Get the global documents\n global documents\n\n # Get a temp document\n temp_doc = choice(documents_templates)\n\n # Populate the fields\n for field in temp_doc:\n temp_doc[field] = generate_random_string(MAX_SIZE_PER_FIELD)\n\n documents.append(temp_doc)\n\n\ndef client_worker():\n\n # Running until timeout\n while not has_timeout():\n\n curr_bulk = \"\"\n\n # Iterate over the bulk size\n for _ in range(BULK_SIZE):\n\n # Generate the bulk operation\n curr_bulk += \"{0}\\n\".format(json.dumps({\"index\": {\"_index\": choice(indices), \"_type\": \"stresstest\"}}))\n curr_bulk += \"{0}\\n\".format(json.dumps(choice(documents)))\n\n try:\n # Perform the bulk operation\n es.bulk(body=curr_bulk)\n\n # Adding to success bulks\n increment_success()\n\n # Adding to size (in bytes)\n increment_size(sys.getsizeof(str(curr_bulk)))\n\n except:\n\n # Failed. incrementing failure\n increment_failure()\n\n\ndef generate_clients():\n # Clients placeholder\n temp_clients = []\n\n # Iterate over the clients count\n for _ in range(NUMBER_OF_CLIENTS):\n\n temp_thread = Thread(target=client_worker)\n temp_thread.daemon = True\n\n # Create a thread and push it to the list\n temp_clients.append(temp_thread)\n\n # Return the clients\n return temp_clients\n\n\ndef generate_documents():\n # Documents placeholder\n temp_documents = []\n\n # Iterate over the clients count\n for _ in range(NUMBER_OF_DOCUMENTS):\n # Create a document and push it to the list\n temp_documents.append(generate_document())\n\n # Return the documents\n return temp_documents\n\n\ndef generate_indices():\n # Placeholder\n temp_indices = []\n\n # Iterate over the indices count\n for _ in range(NUMBER_OF_INDICES):\n # Generate the index name\n temp_index = generate_random_string(16)\n\n # Push it to the list\n temp_indices.append(temp_index)\n\n try:\n # And create it in ES with the shard count and replicas\n es.indices.create(index=temp_index, body={\"settings\": {\"number_of_shards\": NUMBER_OF_SHARDS,\n \"number_of_replicas\": NUMBER_OF_REPLICAS}})\n\n except:\n print(\"Could not create index. Is your cluster ok?\")\n sys.exit(1)\n\n # Return the indices\n return temp_indices\n\n\ndef cleanup_indices():\n\n # Iterate over all indices and delete those\n for curr_index in indices:\n try:\n # Delete the index\n es.indices.delete(index=curr_index, ignore=[400, 404])\n\n except:\n print(\"Could not delete index: {0}. Continue anyway..\".format(curr_index))\n\n\ndef print_stats():\n\n # Calculate elpased time\n elapsed_time = (int(time.time()) - STARTED_TIMESTAMP)\n\n # Calculate size in MB\n size_mb = total_size / 1024 / 1024\n\n # Protect division by zero\n if elapsed_time == 0:\n mbs = 0\n else:\n mbs = size_mb / float(elapsed_time)\n\n # Print stats to the user\n print(\"Elapsed time: {0} seconds\".format(elapsed_time))\n print(\"Successful bulks: {0} ({1} documents)\".format(success_bulks, (success_bulks * BULK_SIZE)))\n print(\"Failed bulks: {0} ({1} documents)\".format(failed_bulks, (failed_bulks * BULK_SIZE)))\n print(\"Indexed approximately {0} MB which is {1:.2f} MB/s\".format(size_mb, mbs))\n print(\"\")\n\n\ndef print_stats_worker():\n\n # Create a conditional lock to be used instead of sleep (prevent dead locks)\n lock = Condition()\n\n # Acquire it\n lock.acquire()\n\n # Print the stats every STATS_FREQUENCY seconds\n while not has_timeout():\n\n # Wait for timeout\n lock.wait(STATS_FREQUENCY)\n\n # To avoid double printing\n if not has_timeout():\n\n # Print stats\n print_stats()\n\n\ndef main():\n # Define the globals\n global documents_templates\n global indices\n global STARTED_TIMESTAMP\n global es\n\n try:\n # Initiate the elasticsearch session\n es = Elasticsearch(ES_ADDRESS)\n\n except:\n print(\"Could not connect to elasticsearch!\")\n sys.exit(1)\n\n print(\"Generating documents and workers.. \"),\n\n # Generate the clients\n clients = generate_clients()\n\n # Generate docs\n documents_templates = generate_documents()\n fill_documents()\n\n print(\"Done!\")\n print(\"Creating indices.. \"),\n\n indices = generate_indices()\n\n print(\"Done!\")\n\n # Set the timestamp\n STARTED_TIMESTAMP = int(time.time())\n\n print(\"Starting the test. Will print stats every {0} seconds.\".format(STATS_FREQUENCY))\n print(\"The test would run for {0} seconds, but it might take a bit more \"\n \"because we are waiting for current bulk operation to complete. \\n\".format(NUMBER_OF_SECONDS))\n\n # Run the clients!\n map(lambda thread: thread.start(), clients)\n\n # Create and start the print stats thread\n stats_thread = Thread(target=print_stats_worker)\n stats_thread.daemon = True\n stats_thread.start()\n\n # And join them all but the stats, that we don't care about\n map(lambda thread: thread.join(), clients)\n\n print(\"\\nTest is done! Final results:\")\n print_stats()\n\n # Cleanup, unless we are told not to\n if not NO_CLEANUP:\n\n print(\"Cleaning up created indices.. \"),\n\n cleanup_indices()\n\n print(\"Done!\")\n\n\n# Main runner\ntry:\n main()\n\nexcept Exception as e:\n print(\"Got unexpected exception. probably a bug, please report it.\")\n print(\"\")\n print(e.message)\n\n sys.exit(1)\n","sub_path":"elasticsearch-stress-test.py","file_name":"elasticsearch-stress-test.py","file_ext":"py","file_size_in_byte":10415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"330613347","text":"import os\nimport uuid\nfrom common.dbinstance import DbInstance\n\ndef insert_report(report, ipv4_addr):\n # prepare result\n result = {\n 'status': 400,\n 'data': None\n }\n\n # check if user has permission to create report\n permitted = False\n with DbInstance().get_instance().cursor() as cursor:\n cursor.execute(\"\"\"\n SELECT\n a.timestamp_created_report < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 15 SECOND) AS permission\n FROM anons AS a\n WHERE a.ipv4_addr = INET_ATON(%s)\n \"\"\", (ipv4_addr,))\n permitted = cursor.fetchone()\n permitted = True if permitted is None else permitted['permission'] == 1\n \n # create report if permitted\n if permitted:\n # insert/update ipv4_addr row\n rows_anon = cursor.execute(\"\"\"\n INSERT INTO anons (ipv4_addr, timestamp_created_report) VALUES (INET_ATON(%s), CURRENT_TIMESTAMP)\n ON DUPLICATE KEY UPDATE timestamp_created_report=CURRENT_TIMESTAMP\n \"\"\", (ipv4_addr,))\n\n # insert report\n rows_thread = cursor.execute(\"\"\"\n INSERT INTO reports (post_id, data_reason, ipv4_addr)\n VALUES (%s, %s, INET_ATON(%s))\n \"\"\", (report['post_id'], report['reason'], ipv4_addr,))\n id_inserted = cursor.lastrowid\n\n # commit if ok\n if rows_anon >= 1 and rows_thread == 1:\n cursor.connection.commit()\n result['status'] = 201\n result['data'] = {\n 'id': id_inserted\n }\n else:\n result['status'] = 429\n result['data'] = {\n 'message': 'too many requests'\n }\n\n return result\n","sub_path":"services/web/api/db_reports.py","file_name":"db_reports.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"53209209","text":"import pymysql\n\ndb = pymysql.connect(\"192.168.80.134\", \"sczhan\", \"Sczhan@1998.\", \"ceshi\", 3306)\ncursor = db.cursor()\n\n# 创建删除语句\nsql = \"delete from ceshibiao where INCOME > '%f'\"%(9999)\ntry:\n cursor.execute(sql)\n db.commit()\n print(\"执行成功\")\nexcept Exception as e:\n db.rollback()\n print(\"执行失败:\" + e)\ndb.close()","sub_path":"xitike(习题课)/xitike(第6章爬虫与实践)/linux/requests/数据存储/mysql_delete.py","file_name":"mysql_delete.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"603105792","text":"import numpy as np\nimport math\nimport json\nfrom math import pow\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom matplotlib.animation import writers\nimport time\n\nclass Grid:\n # the __init__ method is called at the initialization of a class instance\n # it initializes all global parameters of the class\n # grid: a numpy list of the first x initial grids\n # n: the x? dimension of the grid size\n # m: the y? dimension of the grid size\n # max_time: the maximum number of time steps that will be taken\n # aka, the max size of the list\n # dec: indicates the the number of decimals after the point\n def __init__(self, grid=None, n=2, m=2, max_time=1, dec = 4):\n # class structure for Grids, might be helpful\n if grid is not None:\n self.grid = np.around(grid, dec)\n else:\n self.grid = grid\n self.n = n\n self.m = m\n self.max_time = max_time\n self.dec = dec\n # note this function call will force all grids in the list to be identical (initially)\n self.initialize_grid()\n\n def get_grid(self, i):\n return self.grid[i].copy()\n \n def get_max(self):\n return self.max_time\n \n def what_is_max(self):\n return np.amax(self.grid)\n\n def get(self, k, i, j):\n return self.grid[k][i][j].copy()\n \n def set_v(self, k, i, j, v):\n self.grid[k][i][j] = float(np.around(v,self.dec))\n \n def set_grid(self, i, new_grid):\n self.grid[i] = np.around(new_grid,self.dec)\n \n def set_max(self, max_t):\n self.max_time = max_t\n \n # initializes the list of grids. Makes a list of size max_time\n # composed of grids identical to the first grid\n # by default the grids are filled with zeros\n def initialize_grid(self):\n initial = np.array([np.zeros((self.n,self.m))])\n if self.grid is None:\n self.grid = initial.copy()\n else:\n initial = np.array([self.grid[0]]).copy()\n \n self.grid = initial\n for i in range(1, self.max_time):\n self.grid = np.append(self.grid, initial.copy(), axis = 0)\n\n # set a rectangular shaped portion of the grid at some time step to some value\n # grid_num: (integer) the time step which is being modified\n # i_init: the x?-coord of the rectangles top left corner (integer)\n # j_init: the y?-coord of the rectangles top left corner (integer)\n # x_size: the x-size of the rectangle (integer)\n # y_size: the y-size of the rectangle (integer)\n # value: the value being input into the rectangle\n # add: (boolean) whether the rectangle is replacing the current values\n # or being added to them\n def set_rect(self, grid_num, c, value, radius = -1, add = False, ignore = -1):\n rect = Polygon(c,3)\n for i in range(0,self.n):\n for j in range(0,self.m):\n if (rect.contains(i, j)):\n self.grid[grid_num][i][j] = value\n else:\n distance = rect.distance(i, j, ignore)[0]\n if (distance <= radius):\n mult = distance / radius\n self.grid[grid_num][i][j] = float(np.around(mult*self.grid[grid_num][i][j] + (1 - mult)*value, self.dec))\n \n # in a rectangular portion of the grid have a linear (in/de)crease in values\n # from the center outwards uniformly\n # grid_num: (integer) the time step which is being modified\n # i_init: the x?-coord of the rectangles top left corner (integer)\n # j_init: the y?-coord of the rectangles top left corner (integer)\n # x_size: the x-size of the rectangle (integer)\n # y_size: the y-size of the rectangle (integer)\n # value_max: the maximum value being input into the rectangle\n # value_min: the minimum value being input into the rectangle\n # add: (boolean) whether the rectangle is replacing the current values\n # or being added to them\n # inc: (boolean) whether the values should be increasing or decreasing outwards\n def set_unif_rect(self, grid_num, c_1, c_2, c_3, c_4, v_max, v_min, add = True):\n rect = Polygon([c_1,c_2,c_3,c_4],1,v_min,v_max)\n\n for i in range(0,self.n):\n for j in range(0,self.m):\n if (rect.contains(i,j)):\n value = rect.get_value(i,j)\n if add:\n self.grid[grid_num][i][j] += float(np.around(value,self.dec))\n else:\n self.grid[grid_num][i][j] = float(np.around(value,self.dec))\n\n # in a rectangular portion of the grid have a linear (in/de)crease in values\n # from the bottom-up\n # grid_num: (integer) the time step which is being modified\n # i_init: the x?-coord of the rectangles top left corner (integer)\n # j_init: the y?-coord of the rectangles top left corner (integer)\n # x_s: the x-size of the rectangle (integer)\n # y_s: the y-size of the rectangle (integer)\n # v_max: the maximum value being input into the rectangle (float)\n # v_min: the minimum value being input into the rectangle (float)\n # inc: (boolean) whether the values should be increasing or decreasing bottom-up\n # axis: (boolean) whether we increase in the x or the y direction\n # add: (boolean) whether the rectangle is replacing the current values\n # or being added to them\n def set_rect_inc_dec(self, grid_num, c, side = 1,\n v_max= 1, v_min = 0, add = False):\n rect = Polygon(c,2,v_min,v_max, side = side)\n\n for i in range(0,self.n):\n for j in range(0,self.m):\n if (rect.contains(i,j)):\n value = rect.get_value(i,j)\n if add:\n self.grid[grid_num][i][j] += float(np.around(value,self.dec))\n else:\n self.grid[grid_num][i][j] = float(np.around(value,self.dec))\n \n # in a circle portion of the grid have a linear (in/de)crease in values\n # from the center outwards\n # grid_num: (integer) the time step which is being modified\n # c_i: the x?-coord of the center of the circle (integer)\n # c_j: the y?-coord of the center of the circle (integer)\n # radius: the radius of the circle (float)\n # v_max: the maximum value being input into the circle (float)\n # v_min: the minimum value being input into the circle (float)\n # add: (boolean) whether the circle is replacing the current values\n # or being added to them\n # inc: (boolean) whether the values should be increasing or decreasing outward\n def set_circ_unif(self, grid_num, c_i, c_j, radius, v_max, v_min, c_min = 0,\n add = False, inc = True):\n if c_i > self.n or c_j > self.m:\n print(\"error in provided parameters. Rectangle does not fit.\")\n elif grid_num > self.max_time:\n print(\"error in time step. There is no grid at this time.\")\n else:\n diff = v_max - v_min\n \n for i in range(self.n):\n for j in range(self.m):\n dist = math.sqrt(math.pow(i - c_i, 2) + math.pow(j - c_j, 2))\n\n if (dist < radius):\n value = 0\n if dist > c_min and dist <= radius:\n dist_new = (dist-c_min)/(radius - c_min)\n if (inc):\n value = v_min + diff*dist_new\n else:\n value = v_max - diff*dist_new\n elif dist <= c_min:\n if (inc):\n value = v_min\n else:\n value = v_max\n \n if add:\n self.grid[grid_num][i][j] += float(np.around(value, self.dec))\n elif radius <= radius:\n self.grid[grid_num][i][j] = float(np.around(value, self.dec))\n \n # add the shape of a wave into the grid. Maximal values at r_c away\n # from the center and dissipating outward from the boundary to distance\n # r_d\n # grid_num: (integer) the time step which is being modified\n # c_i: the x?-coord of the center of the circle (integer)\n # c_j: the y?-coord of the center of the circle (integer)\n # r_c: the radius of the circle (float)\n # r_d: the radius of the cirlce boundary (float)\n # v_max: the maximum value being input into the wave (float)\n # v_min: the minimum value being input into the wave (float)\n # add: (boolean) whether the wave is replacing the current values\n # or being added to them\n def set_wave(self, grid_num, c_i, c_j, R, h, c=1, w=3, add = False):\n c = float(c)/6.283\n if c_i > self.n or c_j > self.m:\n print(\"error in provided parameters. Rectangle does not fit.\")\n elif grid_num > self.max_time:\n print(\"error in time step. There is no grid at this time.\")\n else:\n for i in range(self.n):\n for j in range(self.m):\n dist = np.linalg.norm(np.subtract([i,j],[c_i,c_j]))#math.sqrt(math.pow(i - c_i, 2) + math.pow(j - c_j, 2))\n if dist/c < R/c + (1/2) + (math.pi/2):\n value = self.wave_function(dist/c, R/c, h, w)\n if not add:\n self.grid[grid_num][i][j] = float(np.around(value, self.dec))\n else:\n self.grid[grid_num][i][j] += float(np.around(value, self.dec))\n \n #def set_triangle(self, grid_num, p_1, p_2, p_3, )\n\n # print the grids with indices in the set {n \\in N : n \\in [i,j)}\n # i: (integer) initial index\n # j: (integer) final index\n def print_grid(self, i = 0, j = None):\n if j is None:\n j = len(self.grid)\n for n in range(i, j):\n print(self.grid[n])\n\n def plot_grid(self, k, name, vmin=0, vmax=5000,center=0):\n ax = sns.heatmap(self.grid[k], vmin = vmin, vmax = vmax, center = center,\n square = True, xticklabels = False, yticklabels = False,\n cbar = False)\n plt.savefig(name+\".png\")\n plt.clf()\n \n def wave_function(self, x, R, h, w):\n if x >= max(R - (w+0.5)*math.pi,0) and x < R:\n a = x - R - (math.cos(x-R)/2)\n return math.cos(a)*(x/R)*h\n elif x >= R and x < R + (1/2):\n a = x - R - (1/2)\n return math.cos(a)*h\n elif x >= R + (1/2) and x < R + (1/2) + math.pi:\n a = 2*(x - R - (1/2))\n return math.cos(a)*(h/2) + (h/2)\n else:\n return 0\n \n def magnitude(self, v):\n summation = 0\n for i in v:\n summation += pow(i,2)\n return math.sqrt(summation)\n\nclass Polygon:\n # corners: corners of a polygon\n # option: 1,2, or 3. Uniform, increasing, or constant colouring\n # side: Applies to option 2. Increasing as you approach which side?\n # side 1 is segment between corners 1 -> 2, analogously for the rest\n def __init__(self, corners=[[0,0],[0,1],[1,0],[1,1]], option=1, v_min=0, v_max=1, side=1):\n self.corners = corners\n self.option = option\n self.side = side\n self.v_min = v_min\n self.v_max = v_max\n self.max_v = np.amax(corners)\n \n # returns whether the point is contained inside the polygon\n def contains(self, x, y, ex=0):\n extreme = [2*self.max_v, y+ex]\n count = 0\n n = len(self.corners)\n\n \n for i in self.corners:\n if i == [x,y]:\n return True\n \n if (self.orientation([x,y],extreme,i) == 0 and\n self.onSegment([x,y], i, extreme)):\n if ex == 0:\n sign = 1\n else:\n sign = ex/abs(ex)\n\n return self.contains(x,y,ex=-sign*(abs(ex)+10))\n\n for i in range(0,n):\n next = (i+1)%n\n if self.check_intersect(self.corners[i], self.corners[next], [x,y], extreme):\n if self.orientation(self.corners[i], [x,y], self.corners[next]) == 0:\n return self.onSegment(self.corners[i], [x,y], self.corners[next])\n \n count += 1\n\n return count % 2 == 1\n \n # gets distance from nearst segment\n def distance(self, x, y, j = -1):\n dist = np.array([])\n n = len(self.corners)\n for i in range(n):\n dist = np.append(dist, [self.distance_to(self.corners[i], self.corners[(i+1)%n], [x,y])])\n a = min(dist)\n b = np.where(dist == a)[0][0]\n if (not j == -1) and (b == j or dist[j-1] == dist[j]):\n return [math.inf, j]\n return [a, b]\n \n # distance to segment c_1 -> c_2\n def distance_to(self, c_1, c_2, pt):\n v = np.subtract(c_1, c_2)\n a = np.dot(v, np.subtract(c_1, pt))\n v = np.subtract(c_2, c_1)\n b = np.dot(v, np.subtract(c_2, pt))\n if (a > 0 and b > 0):\n b = np.linalg.norm(v)\n w = np.subtract(c_1, pt)\n a = abs(v[0]*w[1] - v[1]*w[0])\n return a/b\n else:\n a = np.linalg.norm(np.subtract(c_1, pt))\n b = np.linalg.norm(np.subtract(c_2, pt))\n return min(a,b)\n \n # gets the value of the given point based on the chosen strategy (option)\n def get_value(self, x, y):\n if self.option == 1:\n dist = self.distance(x, y)\n step = self.get_step(dist[1])/2\n if step <= 0:\n print(\"Error, step size too small\")\n exit(1)\n return self.v_min + (dist[0]/step)*(self.v_max - self.v_min)\n elif self.option == 2:\n dist = 0\n if self.side == len(self.corners)-1:\n dist = self.distance_to(self.corners[self.side], self.corners[0], [x,y])\n elif self.side < len(self.corners)-1:\n dist = self.distance_to(self.corners[self.side], self.corners[self.side+1], [x,y])\n else:\n print(\"Invalid side!\")\n exit(1)\n step = self.get_step(self.side)\n if step <= 0:\n print(\"Error, step size too small\")\n exit(1)\n return self.v_min*(1 - (dist/step)) + self.v_max*(dist/step)\n else:\n return self.v_max\n \n def get_step(self, i):\n vec = np.subtract(self.corners[i-1], self.corners[i])\n mag = math.sqrt(pow(vec[0],2) + pow(vec[1],2))\n return mag\n \n def orientation(self, p, q, r):\n a = q[1] - p[1]; b = r[0] - q[0]\n c = q[0] - p[0]; d = r[1] - q[1]\n value = 0\n if (not a == 0) and (not b == 0):\n value = a*b\n if (not c == 0) and (not d == 0):\n if value == c*d:\n value = 0\n else:\n value = value - c*d\n \n if value == 0:\n return 0\n elif value > 0:\n return 1\n return 2\n \n def onSegment(self, p, q, r):\n if (q[0] <= max(p[0], r[0]) and q[0] >= min(p[0], r[0]) and \n q[1] <= max(p[1], r[1]) and q[1] >= min(p[1], r[1])):\n return True\n return False\n \n def check_intersect(self, p1, q1, p2, q2):\n o1 = self.orientation(p1, q1, p2)\n o2 = self.orientation(p1, q1, q2)\n o3 = self.orientation(p2, q2, p1)\n o4 = self.orientation(p2, q2, q1)\n\n if (o1 != o2) and (o3 != o4):\n return True\n \n if o1 == 0 and self.onSegment(p1, p2, q1):\n return True\n \n if o2 == 0 and self.onSegment(p1, q2, q1):\n return True\n \n if o3 == 0 and self.onSegment(p2, p1, q2):\n return True\n \n if o4 == 0 and self.onSegment(p2, q1, q2):\n return True\n \n return False\n\nclass Modelling:\n def __init__(self, grid_eta=Grid(), d=Grid(), poly=Polygon(), h=1, dt=1):#grid_w = Grid(), grid_v = Grid(), alpha = 1):\n self.d = d\n self.h = h\n self.dt = dt\n self.max = grid_eta.get_max()\n self.poly = poly\n self.matrix = self.setup()\n # add grid at time = 0\n self.grid = grid_eta\n #self.grid_w = grid_w\n #self.grid_v = grid_v\n #self.alpha = alpha\n self.wasted = 0\n self.count = 0\n\n def setup(self):\n c_1 = poly.corners[0]\n c_2 = poly.corners[1]\n c_3 = poly.corners[2]\n size_x = int(np.linalg.norm(np.subtract(c_1, c_2))) + 1\n size_y = int(np.linalg.norm(np.subtract(c_2, c_3))) + 1\n return np.zeros((size_y,size_x))\n \n def next_grid(self, k):\n # need to set up boundary conditions here\n if ((k+2)%50 == 0):\n print(\"Starting grid: \", k+2)\n '''\n if np.amax(self.matrix) > 0:\n ax = sns.heatmap(self.matrix)\n plt.savefig(\"matrix_\"+name+\"_\"+str(k+2))\n plt.clf()\n '''\n \n mat = np.zeros(self.matrix.shape)\n for i in range(0, self.grid.n):\n for j in range(0, self.grid.m):\n # use the \"update formula\"\n self.get_open(k,i,j)\n t_init = time.time()\n if (i <= 80*s and j <= 142*s and self.grid.get(k+1,i,j) > 0 and poly.contains(i,j)):\n c_1 = poly.corners[0]\n c_2 = poly.corners[1]\n c_3 = poly.corners[2]\n l = int(poly.distance_to(c_1, c_2, [i,j]))\n m = int(poly.distance_to(c_2, c_3, [i,j]))\n mat[l][m] = self.grid.get(k+1,i,j)\n self.matrix[l][m] = max(self.matrix[l][m], mat[l][m])\n \n self.wasted = self.wasted - t_init + time.time()\n\n if np.amax(mat) > 0:\n self.save_to_json(mat, k, np.unravel_index(np.argmax(mat),mat.shape))\n \n # compute next step in i, j\n def get_open(self, k, i, j):\n c = math.sqrt(9.81*self.d.get(0,i,j))\n term = pow(c * self.dt / self.h, 2)\n t1 = 2*self.grid.get(k,i,j) - self.grid.get(k-1,i,j)\n t2 = self.get_elmt(k,i+1,j) - 2*self.grid.get(k,i,j) + self.get_elmt(k,i-1,j)\n t3 = self.get_elmt(k,i,j+1) - 2*self.grid.get(k,i,j) + self.get_elmt(k,i,j-1)\n \n self.grid.set_v(k+1, i, j, t1 + term*t2 + term*t3)\n \n #'''\n def get_elmt(self, k, i, j):\n if (i > self.grid.n-1):\n return 0#self.grid.get(k,i-1,j)\n elif (j > self.grid.m-1):\n return 0#self.grid.get(k,i,j-1)\n elif (i < 0):\n return 0#self.grid.get(k,i+1,j)\n elif (j < 0):\n return 0#self.grid.get(k,i,j+1)\n return self.grid.get(k,i,j)\n #'''\n\n '''\n def get_elmt(self, k, i, j):\n if j < 0:\n tt = self.get_tt(k,i,j+1)\n xx = self.get_xx(k,i,j+1)\n ht = pow(self.h, 2)\n return tt*ht - xx + 2*self.grid.get(k,i,j+1) - self.grid.get(k,i,j+2)\n elif i < 0:\n tt = self.get_tt(k,i+1,j)\n yy = self.get_yy(k,i+1,j)\n ht = pow(self.h, 2)\n return tt*ht - yy + 2*self.grid.get(k,i+1,j) - self.grid.get(k,i+2,j)\n elif j > self.grid.m-1:\n tt = self.get_tt(k,i,j-1)\n xx = self.get_xx(k,i,j-1)\n ht = pow(self.h, 2)\n return tt*ht - xx + 2*self.grid.get(k,i,j-1) - self.grid.get(k,i,j-2)\n elif i > self.grid.n-1:\n tt = self.get_tt(k,i-1,j)\n yy = self.get_yy(k,i-1,j)\n ht = pow(self.h, 2)\n return tt*ht - yy + 2*self.grid.get(k,i-1,j) - self.grid.get(k,i-2,j)\n \n return self.grid.get(k,i,j)\n \n def get_tt(self, k, i, j):\n return (self.grid.get(k,i,j) - 2*self.grid.get(k-1,i,j) + self.grid.get(k-2,i,j)) / pow(self.dt, 2)\n \n def get_xx(self, k, i, j):\n if 0 < i and i < self.grid.n-1:\n return (self.grid.get(k,i+1,j) - 2*self.grid.get(k,i,j) + self.grid.get(k,i-1,j))\n elif i == 0:\n return (self.grid.get(k,i+2,j) - 2*self.grid.get(k,i+1,j) + self.grid.get(k,i,j))\n else:\n return (self.grid.get(k,i,j) - 2*self.grid.get(k,i-1,j) + self.grid.get(k,i-2,j))\n\n def get_yy(self, k, i, j):\n if 0 < j and j < self.grid.m-1:\n return (self.grid.get(k,i,j+1) - 2*self.grid.get(k,i,j) + self.grid.get(k,i,j-1))\n elif j == 0:\n return (self.grid.get(k,i,j+2) - 2*self.grid.get(k,i,j+1) + self.grid.get(k,i,j))\n else:\n return (self.grid.get(k,i,j) - 2*self.grid.get(k,i,j-1) + self.grid.get(k,i,j-2))\n '''\n\n '''\n def get_shallow(self, k, i, j):\n result = self.get_vec(k,i,j).copy()\n self.grid_eta.set_v(k+1,i,j, result[0])\n self.grid_w.set_v(k+1,i,j, result[1])\n self.grid_v.set_v(k+1,i,j, result[2])\n '''\n\n '''\n def get_vec(self, k, i, j):\n m1 = np.array([[self.alpha*self.grid_w.get(k,i,j), self.alpha*self.grid_eta.get(k,i,j)+self.d.get(0,i,j), 0],\n [9.81, self.alpha*self.grid_w.get(k,i,j), 0],\n [0, 0, self.alpha*self.grid_w.get(k,i,j)]])\n m2 = np.array([[self.alpha*self.grid_v.get(k,i,j), 0, self.alpha*self.grid_eta.get(k,i,j)+self.d.get(0,i,j)],\n [0, self.alpha*self.grid_v.get(k,i,j), 0],\n [9.81, 0, self.alpha*self.grid_v.get(k,i,j)]])\n m3 = np.array([[self.grid_w.get(k,i,j), self.grid_v.get(k,i,j), 0],\n [0, 0, 0],\n [0, 0, 0]])\n \n #if (self.d.n-1 < i+1):\n if (0 < i):\n ai_1 = self.grid_eta.get(k,i-1,j)\n bi_1 = self.grid_w.get(k,i-1,j)\n ci_1 = self.grid_v.get(k,i-1,j)\n di_1 = self.d.get(0,i-1,j)\n else:\n ai_1 = 0\n bi_1 = self.grid_w.get(k,i,j)\n ci_1 = self.grid_v.get(k,i,j)\n di_1 = 5000\n \n #if (self.d.m-1 < j+1):\n if (0 < j):\n aj_1 = self.grid_eta.get(k,i,j-1)\n bj_1 = self.grid_w.get(k,i,j-1)\n cj_1 = self.grid_v.get(k,i,j-1)\n dj_1 = self.d.get(0,i,j-1)\n else:\n aj_1 = 0\n bj_1 = self.grid_w.get(k,i,j)\n cj_1 = self.grid_v.get(k,i,j)\n dj_1 = 5000\n \n if (self.d.n-1 < i+1):\n ai_2 = self.grid_eta.get(k,i+1,j)\n bi_2 = self.grid_w.get(k,i+1,j)\n ci_2 = self.grid_v.get(k,i+1,j)\n di_2 = self.d.get(0,i+1,j)\n else:\n ai_2 = 0\n bi_2 = self.grid_w.get(k,i,j)\n ci_2 = self.grid_v.get(k,i,j)\n di_2 = 5000\n \n if (self.d.m-1 < j+1):\n aj_2 = self.grid_eta.get(k,i,j+1)\n bj_2 = self.grid_w.get(k,i,j+1)\n cj_2 = self.grid_v.get(k,i,j+1)\n dj_2 = self.d.get(0,i,j+1)\n else:\n aj_2 = 0\n bj_2 = self.grid_w.get(k,i,j)\n cj_2 = self.grid_v.get(k,i,j)\n dj_2 = 5000\n \n v1 = np.array([ai_2 - ai_1,#ai - self.grid_eta.get(k,i,j),\n bi_2 - bi_1,#bi - self.grid_w.get(k,i,j),\n ci_2 - ci_1])#ci - self.grid_v.get(k,i,j)])\n v2 = np.array([aj_2 - aj_1,#aj - self.grid_eta.get(k,i,j),\n bj_2 - bj_1,#bj - self.grid_w.get(k,i,j),\n cj_2 - cj_1])#cj - self.grid_v.get(k,i,j)])\n v3 = np.array([di_2 - di_1,#di - self.d.get(0,i,j),\n dj_2 - dj_1,#dj - self.d.get(0,i,j),\n 0])\n v = np.array([self.grid_eta.get(k-1,i,j), self.grid_w.get(k-1,i,j), self.grid_v.get(k-1,i,j)])\n\n return np.subtract(v, (self.dt / self.h) * (np.add(np.add(m1 @ v1, m2 @ v2), m3 @ v3)))\n '''\n\n def save_to_json(self, m, k=0, ind = (0, 0)):\n data = list(m)\n for i in range(len(m)):\n data[i] = list(m[i])\n \n with open(name+\"_data_viz.json\", \"a\") as write_file:\n json.dump(\"k: \"+str(k), write_file)\n write_file.write('\\n')\n json.dump(\"i,j: \"+str(ind[0])+\", \"+str(ind[1]), write_file)\n write_file.write('\\n')\n for i in data:\n json.dump(i, write_file)\n write_file.write('\\n')\n write_file.write('\\n')\n \n if not k == self.max-1:\n with open(name+\"_data_py.json\", \"r\") as read_file:\n a = json.load(read_file)\n a.append(data)\n data = a\n \n with open(name+\"_data_py.json\", \"w\") as write_file:\n json.dump(data, write_file)\n \n with open(name+\"_data_time.json\", \"r\") as read_file:\n data = json.load(read_file)\n data.append(list([k,np.amax(m)]))\n\n with open(name+\"_data_time.json\", \"w\") as write_file:\n json.dump(data, write_file, indent=2)\n \n def init_json(self):\n a = {\n \"s\": s,\n \"t\": t,\n \"h\": h,\n \"delta\": delta,\n \"radius\": radius,\n \"wavelen\": wavelen,\n \"waves\": waves\n }\n with open(name+\"_data_viz.json\", \"w\") as write_file:\n json.dump(a,write_file,indent=2)\n write_file.write('\\n')\n write_file.write('\\n')\n \n data = list(self.matrix)\n for i in range(len(data)):\n data[i] = list(data[i])\n \n with open(name+\"_data_py.json\", \"w\") as write_file:\n json.dump(list([data]), write_file)\n\n with open(name+\"_data_time.json\", \"w\") as write_file:\n json.dump(list([list([0,0])]), write_file)\n\n def solveEq(self):\n # for loop for time steps and updating grid\n # self.grid_eta.initialize_grid()\n\n self.init_json()\n for k in range(1, self.max-1): # some stopping condition\n # use next_grid to compute next step\n self.next_grid(k)\n #print(\"hello123\")\n self.save_to_json(self.matrix, self.max-1)\n\n ax = sns.heatmap(self.matrix)\n plt.savefig(name+\"_matrix\")\n plt.clf()\n\n print(\"Time wasted: \", self.wasted)\n \n # set the initial parameters\n def set_param(self, c = 0, h = 0, dt = 0):\n if not c == 0:\n self.c = c\n if not h == 0:\n self.h = h\n if not dt == 0:\n self.dt = dt\n\ndef min_stability(h, c):\n # find minimal stable parameters, whatever that may mean\n return h / (c*math.sqrt(2))\n\n# creates the Palma islands topography\ndef palmaTopography(size_x, size_y, s):\n init_topo = np.array([np.full((size_x,size_y),5000)])\n topography = Grid(grid = init_topo, n = size_x, m = size_y, max_time = 1, dec = 1)\n\n # decreasing polygons for the narrow channel\n topography.set_rect_inc_dec(0,[[40*s,110*s],[75*s,135*s],[160*s,135*s],[160*s,0],[100*s,0]],3,v_max=1000,v_min=50)\n topography.set_rect_inc_dec(0,[[40*s,110*s],[0,110*s],[0,0],[40*s,0]],2,v_max=1000,v_min=50)\n topography.set_rect(0,[[0,110*s],[75*s,135*s],[40*s,110*s]],1000)\n topography.set_rect_inc_dec(0,[[0,110*s],[75*s,135*s],[80*s,140*s],[80*s,170*s],\n [0,170*s]],0,v_max=5000,v_min=1000)\n \n # Creates a polygon with 8 corners and a 70*s unit long shore (uniform decrease from 0 to 5000 depth)\n # Represents Spain / Portugal\n # First imput should always be 0\n # Second input is the corners of the polygon\n # Third input is the value inside the polygon\n # Fourth is how far the \"shore\" extends around the polygon, aka how far until 5000m depth\n topography.set_rect(0,[[160*s,280*s],[90*s,330*s],[75*s,340*s],[90*s,370*s],\n [115*s,400*s],[130*s,425*s],[145*s,432*s],[160*s,460*s]],0,70*s)\n\n # France done in two Polygons due to different shores\n topography.set_rect(0,[[160*s,190*s],[140*s,160*s],[100*s,140*s],[80*s,140*s],\n [160*s,135*s]],0,40*s,ignore=3)\n topography.set_rect(0,[[160*s,135*s],[80*s,140*s],[75*s,135*s],[80*s,130*s],[110*s,115*s],\n [85*s,110*s],[120*s,80*s],[125*s,45*s],[160*s,20*s]],0,10*s)\n # The UK land mass\n topography.set_rect(0,[[0,20*s],[20*s,30*s],[20*s,50*s],\n [40*s,40*s],[35*s,70*s],[40*s,110*s],\n [70*s,60*s],[110*s,40*s],[120*s,25*s],\n [100*s,30*s],[100*s,0],[0,0]], 0,10*s)\n\n # uniform values in a cirlce for the Palma and other islands, inputs are straightforward\n topography.set_circ_unif(0,160*s,600*s,36*s,5000,0,c_min=4*s)\n topography.set_circ_unif(0,0,580*s,50*s,5000,200,c_min=8*s)\n\n poly = Polygon([[45*s,103*s],[35*s,117*s],[70*s,142*s],[80*s,128*s]])\n \n return poly, topography\n\ndef otherTopography(size_x, size_y, s):\n init_topo = np.array([np.full((size_x, size_y), 5000)])\n topography = Grid(grid = init_topo, n = size_x, m = size_y, max_time = 1, dec = 1)\n \n return topography\n\ndef get_amplitude(size_x, size_y, s, t, h, r, c, w):\n init_grid = np.array([np.full((size_x,size_y),0)])\n grid = Grid(grid = init_grid, n = size_x, m = size_y, max_time = t, dec = 4)\n\n grid.set_wave(grid_num=0,c_i=160*s,c_j=600*s,R=r*s,h=h*1.2,c=c*s,w=w)\n #grid.set_rect(grid_num=0,c=[[160*s-1,0],[160*s-1,600*s],[160*s,600*s],[160*s,0]],value=0)\n #grid.set_rect(grid_num=0,c=[[160*s-1,600*s-1],[0,600*s-1],[0,600*s],[160*s-1,600*s]],value=0)\n\n grid.initialize_grid()\n grid.set_grid(0,init_grid)\n\n grid.set_wave(grid_num=0,c_i=160*s,c_j=600*s,R=r*s*0.99,h=h,c=c*s,w=w)\n #grid.set_rect(grid_num=0,c=[[160*s-1,0],[160*s-1,600*s],[160*s,600*s],[160*s,0]],value=0)\n #grid.set_rect(grid_num=0,c=[[160*s-1,600*s-1],[0,600*s-1],[0,600*s],[160*s-1,600*s]],value=0)\n\n #grid.set_wave(grid_num=0,c_i=160*s,c_j=600*s,R=r*s*0.99,h=h,c=c*s,w=w)\n\n return grid\n\n'''\ndef get_velocity(size_x, size_y, s, topo, amp, v, t):\n init_grid = np.array([np.full((size_x,size_y),0)])\n grid_v = Grid(grid = init_grid, n = size_x, m = size_y, max_time = t, dec = 1)\n grid_w = Grid(grid = init_grid, n = size_x, m = size_y, max_time = t, dec = 1)\n\n for i in range(topo.n):\n for j in range(topo.m):\n #if not topo.get(0,i,j) == 0:\n #grid_w.set_v(0,i,j,200)\n #grid_v.set_v(0,i,j,200)\n \n if not amp.get(1,i,j) == 0 and (not topo.get(0,i,j) == 0):\n w = np.subtract(v, [i,j])\n x, y = get_dir(w)\n grid_v.set_v(0,i,j,amp.get(0,i,j)*x*math.sqrt(9.81/topo.get(0,i,j)))\n grid_w.set_v(0,i,j,amp.get(0,i,j)*y*math.sqrt(9.81/topo.get(0,i,j)))\n\n grid_v.initialize_grid()\n grid_w.initialize_grid()\n\n for i in range(topo.n):\n for j in range(topo.m):\n #if not topo.get(0,i,j) == 0:\n #grid_w.set_v(0,i,j,200)\n #grid_v.set_v(0,i,j,200)\n \n if not amp.get(0,i,j) == 0 and (not topo.get(0,i,j) == 0):\n w = np.subtract(v, [i,j])\n x, y = get_dir(w)\n grid_v.set_v(0,i,j,amp.get(0,i,j)*x*math.sqrt(9.81/topo.get(0,i,j)))\n grid_w.set_v(0,i,j,amp.get(0,i,j)*y*math.sqrt(9.81/topo.get(0,i,j)))\n \n return grid_v, grid_w\n'''\n\n'''\ndef get_dir(v):\n v = v/np.linalg.norm(v)\n return v[0], v[1]\n'''\n\n# create grid\n# parameters\n# grid: grid at time = 0\n# n: x dimension of grid\n# m: y dimension of grid\n# max_time: time up to which we are considering the model\n# dec: number of decimals after the point\ns = float(input(\"Enter the scale you want: \"))\nprint()\nprint(\"s is now given by: \", s)\nprint(\"s is of type: \", type(s))\n\nt = int(input(\"Enter the number of timesteps: \"))\nprint()\nprint(\"t is now given by: \", t)\nprint(\"t is of type: \", type(t))\n\nh = float(input(\"Enter the initial amplitude: \"))\nprint()\nprint(\"h is now given by: \", h)\nprint(\"h is of type: \", type(h))\n\nname = input(\"Enter a name: \")\nprint()\nprint(\"name is now given by: \", name)\nprint(\"name is of type: \", type(name))\n\n# find minimum stability conditions\nprint(\"Given the parameters, the maximum delta t is: \", min_stability(10/(s*2), math.sqrt(9.81 * 5000)))\n\ndelta = float(input(\"Enter the timestep size: \"))\nprint()\nprint(\"delta is now given by: \", delta)\nprint(\"delta is of type: \", type(delta))\n\nradius = int(input(\"Enter the radius: \"))\nprint()\nprint(\"radius is now given by: \", radius)\nprint(\"radius is of type: \", type(radius))\n\nwavelen = int(input(\"Enter the wavelength: \"))\nprint()\nprint(\"wavelen is now given by: \", wavelen)\nprint(\"wavelen is of type: \", type(wavelen))\n\nwaves = int(input(\"Enter the number of waves: \"))\nprint()\nprint(\"waves is now given by: \", waves)\nprint(\"waves is of type: \", type(waves))\n\n'''\nalpha = float(input(\"Enter the value or alpha: \"))\nprint()\nprint(\"alpha is now given by: \", alpha)\nprint(\"alpha is of type: \", type(alpha))\n'''\n\nsize_x = int(160*s)\nsize_y = int(600*s)\nt0 = time.time()\n\npoly, topography = palmaTopography(size_x, size_y, s)\ntopography.plot_grid(0,\"topography\",center=3000,vmax=3000)\nt1 = time.time()\nprint(\"Made topography in: \", (t1 - t0))\n\ngrid_eta = get_amplitude(size_x, size_y, s, t, h*math.sqrt(9.81), radius, wavelen, waves)\ngrid_eta.plot_grid(0,\"initial_wave \"+name,vmin=-h*0.5,vmax=h*0.5,center=0)\ngrid_eta.plot_grid(1,\"second_wave \"+name, vmin=-h*0.5,vmax=h*0.5,center=0)\n#grid_eta.plot_grid(2,\"third_wave \"+name, vmin=-h*0.5,vmax=h*0.5,center=0)\nt2 = time.time()\nprint(\"Time to construct grid: \", (t2 - t1))\n\n'''\ngrid_v, grid_w = get_velocity(size_x, size_y, s, topography, grid_eta, [160*s, 600*s], t)\ngrid_v.plot_grid(0, \"initial x speed \"+name,vmin=-h*0.1,vmax=h*0.1,center=0)\ngrid_w.plot_grid(0, \"initial y speed \"+name,vmin=-h*0.1,vmax=h*0.1,center=0)\nt3 = time.time()\nprint(\"Time to construct velocity: \", (t3 - t2))\n'''\n\n# create instance of modelling class\ninstance = Modelling(grid_eta=grid_eta, d=topography, poly = poly)#grid_w=grid_w, grid_v=grid_v, alpha = alpha) # need to give the grid here like (grid)\n\n# set the parameters\ninstance.set_param(h = 10/(s*2), dt = delta)#54) # can add c = ?, h = ?, dt = ?\n\nt4 = time.time()\nprint(\"Time to set up Modelling class: \", (t4 - t2))\n# solve the wave equations numerically\ninstance.solveEq() # should take as parameter max time\n\nt5 = time.time()\nprint(\"Time for solveEq(): \", (t5 - t4))\n\n#instance.plot_result(\"test_set\", vmax=200, vmin=-200, step = 1, time = 200)\ngrid = instance.grid.grid\ndata = list(grid)\nfor i in range(len(data)):\n data[i] = list(grid[i])\n for j in range(len(data[i])):\n data[i][j] = list(grid[i][j])\n for k in range(len(data[i][j])):\n data[i][j][k] = float(grid[i][j][k])\n\nwith open(name+\"_grid.json\", \"w\") as write_file:\n json.dump(data, write_file)\n\nt6 = time.time()\nprint(\"Time to dump data to JSON: \", (t6 - t5))\n\n'''\ngrid = instance.grid_w.grid\nfig = plt.figure()\nsave_animation(grid, fig, \"w \"+name)\nt7 = time.time()\nprint(\"Time to make x velocity video: \", (t7 - t6))\n\ngrid = instance.grid_v.grid\nfig = plt.figure()\nsave_animation(grid, fig, \"v \"+name)\nt8 = time.time()\nprint(\"Time to make y velocity video: \", (t8 - t7))\n'''\n\n#instance.grid_v.plot_grid(100, \"test_v\")\n#instance.grid_w.plot_grid(100, \"test_w\")\n\nprint(\"Total time is: \", (t6 - t0))\n\n#print(instance.grid.what_is_max())\n\n","sub_path":"modelling_v-JSON.py","file_name":"modelling_v-JSON.py","file_ext":"py","file_size_in_byte":35581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"495312773","text":"#/usr/bin/env python3\nimport json\nimport click\nimport numpy as np\n\n@click.command()\n@click.argument(\"output_fname\", type=click.Path(file_okay=True, dir_okay=False))\ndef main(output_fname):\n steps = 180\n radius = 10\n\n # r**2 = x**2 + y**2 <=> y = +- sqrt(r**2 - x**2)\n x_0 = np.linspace(-radius, radius, num=steps, endpoint=True)\n x_1 = x_0[::-1]\n x = np.concatenate((x_0, x_1[1:]))\n\n y_0 = np.sqrt(radius**2 - x_0**2)\n y_1 = -y_0[::-1]\n y = np.concatenate((y_0, y_1[1:]))\n\n coords = list(zip(x, y))\n result = [\n {\n \"name\": \"circle\",\n \"polygon\": coords,\n \"type\": \"plus\",\n }\n ]\n\n with open(output_fname, \"w\") as f:\n json.dump(result, f, indent=4, sort_keys=True)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"data/scripts/generate_circle.py","file_name":"generate_circle.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"437272711","text":"# -*- coding: utf-8 -*-\nfrom PIL import Image, ImageDraw, ImageFont\nimport colorsys\nfrom os.path import join, dirname\nimport os\nfrom bokeh.plotting import figure, output_file, show\n\n\nclass HotDetect:\n def __init__(self, image, thresh=0.30):\n self.image = image\n self.width, self.height = image.size\n self.pixels = image.load()\n\n self.hot_area = 0\n self.extra_hot_area = 0\n self.percentage = 0\n self.thresh = thresh\n\n self.font = ImageFont.truetype(join(dirname(__file__), '../fonts/sanfranciscotext-light-webfont.ttf'), 15)\n\n # used for demo\n def focus_on_hot(self):\n _image = self.image.copy()\n pixels = _image.load()\n pencil = ImageDraw.Draw(_image)\n\n _hot_area = 0\n _extra_hot_area = 0\n\n # loop over the image\n # convert (r, g, b) -> (h, s, v), using threshold on h to pick out the red(hot) part\n for x in range(0, self.width):\n for y in range(0, self.height):\n r, g, b, a = pixels[x, y]\n _h, _s, _v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)\n h = _h * 360\n\n # if it's cold part then set it to white\n if 60 <= h <= 280:\n pixels[x, y] = (255, 255, 255)\n # if it's hot area\n elif h <= 60 or h >= 280:\n _hot_area += 1\n if 280 <= h <= 340:\n pixels[x, y] = (74, 94, 107)\n _extra_hot_area += 1\n else:\n pixels[x, y] = (100, 124, 134)\n\n text = '%d / %d = %.6f' % (_extra_hot_area, _hot_area, _extra_hot_area / _hot_area)\n pencil.text(\n (0, self.height - 20),\n text,\n font=self.font,\n fill=(0, 0, 0, 128))\n\n return _image\n\n def get_area_pixels(self):\n pixels = self.image.load()\n area = 0\n\n for x in range(0, self.width):\n for y in range(0, self.height):\n r, g, b, a = pixels[x, y]\n _h, _s, _v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)\n h = _h * 360\n\n if 60 <= h <= 280:\n # do nothing\n pass\n else:\n area += 1\n\n return area / (self.height * self.width)\n\n # percentage -> number result -> 0, 1\n def get_area_percentage(self):\n for x in range(0, self.width):\n for y in range(0, self.height):\n r, g, b, a = self.pixels[x, y]\n _h, _s, _v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)\n h = _h * 360\n\n if h <= 60 or h >= 280:\n # when it's hot add 1 -> hot_area\n self.hot_area += 1\n # when it's extra hot add 1 -> extra_hot_area\n if 280 <= h <= 340:\n self.extra_hot_area += 1\n\n self.percentage = self.extra_hot_area / self.hot_area\n\n result = ''\n if self.percentage >= self.thresh:\n result = '过热'\n\n return self.percentage, result\n\n def show(self):\n self.image.show()\n\n\nif __name__ == '__main__':\n test_path = '../imgs/croped/'\n x_arr = []\n arr = []\n counter = 0\n\n for file in os.listdir(test_path):\n if file != '.DS_Store':\n filepath = test_path + file\n img = Image.open(filepath)\n\n h = HotDetect(img)\n\n value = h.get_area_pixels()\n arr.append(value)\n\n counter += 1\n print('finished => %f' % counter)\n\n arr.sort()\n for i in range(len(arr)):\n x_arr.append(i)\n\n output_file('../graph/splash_area_method.html')\n p = figure(plot_width=1000, plot_height=400)\n p.line(x_arr, arr, line_width=2)\n p.circle(x_arr, arr, size=5, color=\"navy\", alpha=0.5)\n\n show(p)\n","sub_path":"scripts/src/hot_detect.py","file_name":"hot_detect.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"137766335","text":"###############################\n##Working with Files in Python\n##############################\n\n## Opens a file named a.txt and returns a file object called f\n## a.txt it's in the same directory with the python script\n## use a correct relative or absolute path\nf = open('a.txt', 'r') # it will be opened in read-only mode\n\ncontent = f.read() # reads the entire file as a string\nprint(content)\n\nf.closed # => False, file is not closed\n\n## Closes the file\nf.close()\n\n## Opens the file in read-only mode and reads its contents in a list\n## the file object will be automatically closed\nwith open('a.txt', 'r') as my_file:\n content = my_file.readlines() # content is a list\n\nmy_file.closed # => True, my_file has been closed automatically\n\n## file object is an iterable object\nwith open('a.txt', 'r') as my_file:\n for line in my_file: # iterating over the lines within the file\n print(line, end='')\n\n## Opens the file in write-mode.\n## Creates the file if it doesn't exist or overwrites the file if it already exists\nwith open('my_file.txt', 'w') as file:\n file.write('This file will be overwritten!')\n\n## Opens the file in append-mode.\n## Creates the file if it doesn't exist or appends to its end if it exists\nwith open('another_file.txt', 'a') as file:\n file.write('Appending to the end!')\n\n## Opens the file for both read and write\n## Doesn't create the file if it doesn't exist\nwith open('my_file.txt', 'r+') as file:\n file.seek(0) # the cursor is positioned at the beginning of the file\n file.write('Writing and the beginning') # writing and the beginning\n\n file.seek(5) # moving the cursor at position 5\n content = file.read(10) # reading 10 characters starting from position 5\n print(content)","sub_path":"working with files.py","file_name":"working with files.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"491387038","text":"import sys\nimport random\nfrom .basic import *\nfrom . import translation\nfrom .all_genes import all_genes, gap_character\nfrom .genetic_code import genetic_code, reverse_genetic_code\nfrom . import logo_tools\n\nall_trbd_nucseq = {}\nfor organism in all_genes:\n d_ids = sorted( ( id for id,g in all_genes[organism].items() if g.region == 'D' and g.chain == 'B' ) )\n all_trbd_nucseq[ organism ] = dict( ( ( d_ids.index(id)+1, all_genes[organism][id].nucseq ) for id in d_ids ) )\n\n########################################################################################################################\ndefault_mismatch_score_for_cdr3_nucseq_probabilities = -4 ## blast is -3\ndefault_mismatch_score_for_junction_analysis = -4 ## blast is -3\n\ndef count_matches( a,b,mismatch_score=-3 ):\n assert a[0].lower() == a[0]\n #assert a[0].upper() == a[0]\n ## from the beginning\n match_score = 1\n best_score=0\n score=0\n num_matches = 0\n for i in range(min(len(a),len(b))):\n if a[i] == b[i] or logo_tools.nuc_match_lower_case.get( (a[i],b[i]), False ):\n score += match_score\n else:\n score += mismatch_score\n if score >= best_score: ## gt OR EQUAL! take longer matched regions\n best_score = score\n num_matches = i+1\n return num_matches\n\n\n\ndef get_v_cdr3_nucseq( organism, v_gene, paranoid = False ):\n vg = all_genes[organism][v_gene]\n ab = vg.chain\n\n v_nucseq = vg.nucseq\n v_nucseq_offset = vg.nucseq_offset\n v_nucseq = v_nucseq[ v_nucseq_offset: ]\n\n v_alseq = vg.alseq\n alseq_cpos = vg.cdr_columns[-1][0] -1\n #print organism, v_gene, old_v_alseq\n #print organism, v_gene, v_alseq\n numgaps = v_alseq[:alseq_cpos].count('.')\n v_cpos = alseq_cpos - numgaps\n v_nucseq = v_nucseq[3*v_cpos:] ## now v_nucseq starts with the 'C' codon\n\n\n # the following hacky adjustment is now incorporated in the dbfile\n # if organism == 'mouse':\n # if v_gene == 'TRAV13D-1*01':\n # #-----------------------------------\n # #../../../tmp.blat:mismatch: V 6 imgt: a genome: t TRAV13D-1*01\n # #tmp.whoah:whoah 6 act: t 98.7 exp: a 1.1 TRAV13D-1*01 TRAV13-1*01 620\n # #tmp.whoah:whoah: expected: caaggtatcgtgt consensus: caaggtttcgtgt TRAV13D-1*01 620\n # #tmp.3.whoah:whoah 6 act: t 97.4 exp: a 1.4 TRAV13D-1*01 TRAV13-1*01 642\n # #tmp.3.whoah:whoah: expected: caaggtatcgtgt consensus: caaggtttcgtgt TRAV13D-1*01 642\n # #tmp.la_mc.whoah:whoah 6 act: t 89.0 exp: a 7.0 TRAV13D-1*01 TRAV13-1*01 100\n # #tmp.la_mc.whoah:whoah: expected: caaggtatcgtgt consensus: caaggtttcgtgt TRAV13D-1*01 100\n # assert v_nucseq == 'tgtgctatggaac' ## CAM ## THIS WILL FAIL SINCE WE ADDED THIS TO THE DB...\n # v_nucseq = 'tgtgctttggaac' ## CAL\n\n\n return v_nucseq\n\n\ndef get_j_cdr3_nucseq( organism, j_gene, paranoid = False ):\n jg = all_genes[organism][j_gene]\n ab = jg.chain\n\n j_nucseq = jg.nucseq\n j_nucseq_offset = jg.nucseq_offset\n\n ## goes up to (but not including) GXG\n num_genome_j_aas_in_loop = len( jg.cdrs[0].replace(gap_character,''))\n\n ## trim j_nucseq so that it extends up to the F/W position\n j_nucseq = j_nucseq[:3*num_genome_j_aas_in_loop + j_nucseq_offset]\n\n\n # the following hacky adjustments are now incorporated in the dbfile\n # if organism == 'mouse':\n # if j_gene == 'TRAJ47*01':\n # # -----------------------------------\n # # ../../../tmp.blat:mismatch: J 2 imgt: c genome: g TRAJ47*01\n # # ../../../tmp.blat:mismatch: J 24 imgt: g genome: t TRAJ47*01\n # # tmp.whoah:whoah 2 act: g 81.9 exp: c 4.7 TRAJ47*01 TRAJ47*01 1412\n # # tmp.whoah:whoah 24 act: t 82.7 exp: g 16.8 TRAJ47*01 TRAJ47*01 1412\n # # tmp.whoah:whoah: expected: tgcactatgcaaacaagatgatctgt consensus: tggactatgcaaacaagatgatcttt TRAJ47*01 1412\n # # tmp.3.whoah:whoah 2 act: g 81.6 exp: c 5.0 TRAJ47*01 TRAJ47*01 1362\n # # tmp.3.whoah:whoah 24 act: t 82.7 exp: g 16.6 TRAJ47*01 TRAJ47*01 1362\n # # tmp.3.whoah:whoah: expected: tgcactatgcaaacaagatgatctgt consensus: tggactatgcaaacaagatgatcttt TRAJ47*01 1362\n # # tmp.la_mc.whoah:whoah 2 act: g 79.6 exp: c 5.3 TRAJ47*01 TRAJ47*01 113\n # # tmp.la_mc.whoah:whoah 24 act: t 99.1 exp: g 0.9 TRAJ47*01 TRAJ47*01 113\n # # tmp.la_mc.whoah:whoah: expected: tgcactatgcaaacaagatgatctgt consensus: tggactatgcaaacaagatgatcttt TRAJ47*01 113\n # assert j_nucseq == 'tgcactatgcaaacaagatgatctgt' ## C at end\n # j_nucseq = 'tggactatgcaaacaagatgatcttt' ## F at end\n # elif j_gene == 'TRAJ24*01':\n # # -----------------------------------\n # # ../../../tmp.blat:unaligned: J 0 TRAJ24*01\n # # ../../../tmp.blat:unaligned: J 1 TRAJ24*01\n # # ../../../tmp.blat:gapped: J 6 TRAJ24*01\n # # tmp.whoah:whoah 2 act: c 60.3 exp: a 15.3 TRAJ24*01 TRAJ24*01 464\n # # tmp.whoah:whoah 4 act: a 88.6 exp: c 2.8 TRAJ24*01 TRAJ24*01 464\n # # tmp.whoah:whoah 5 act: c 93.3 exp: t 1.5 TRAJ24*01 TRAJ24*01 464\n # # tmp.whoah:whoah 6 act: t 97.2 exp: g 1.1 TRAJ24*01 TRAJ24*01 464\n # # tmp.whoah:whoah: expected: tgaactggccagtttggggaaactgcagttt consensus: gacaactgccagtttggggaaactgcagttt TRAJ24*01 464\n # # tmp.3.whoah:whoah 2 act: c 60.8 exp: a 13.9 TRAJ24*01 TRAJ24*01 475\n # # tmp.3.whoah:whoah 4 act: a 86.3 exp: c 4.2 TRAJ24*01 TRAJ24*01 475\n # # tmp.3.whoah:whoah 5 act: c 94.5 exp: t 1.1 TRAJ24*01 TRAJ24*01 475\n # # tmp.3.whoah:whoah 6 act: t 98.1 exp: g 1.1 TRAJ24*01 TRAJ24*01 475\n # # tmp.3.whoah:whoah: expected: tgaactggccagtttggggaaactgcagttt consensus: gacaactgccagtttggggaaactgcagttt TRAJ24*01 475\n # # tmp.la_mc.whoah:whoah 2 act: c 75.3 exp: a 4.3 TRAJ24*01 TRAJ24*01 93\n # # tmp.la_mc.whoah:whoah 4 act: a 89.2 exp: c 2.2 TRAJ24*01 TRAJ24*01 93\n # # tmp.la_mc.whoah:whoah 5 act: c 97.8 exp: t 1.1 TRAJ24*01 TRAJ24*01 93\n # # tmp.la_mc.whoah:whoah 6 act: t 98.9 exp: g 0.0 TRAJ24*01 TRAJ24*01 93\n # # tmp.la_mc.whoah:whoah: expected: tgaactggccagtttggggaaactgcagttt consensus: gacaactgccagtttggggaaactgcagttt TRAJ24*01 93\n # assert j_nucseq == 'tgaactggccagtttggggaaactgcagttt'\n # j_nucseq = 'gacaactgccagtttggggaaactgcagttt'\n # ## take the consensus\n # ## given that there's an indel (and the alignment to the genome starts at j sequence position 3)\n # ## it's hard to tell what to do at the beginning...\n\n\n\n return j_nucseq\n\n\n\n\ndef analyze_junction( organism, v_gene, j_gene, cdr3_protseq, cdr3_nucseq, force_d_id=0, return_cdr3_nucseq_src=False ):\n #print organism, v_gene, j_gene, cdr3_protseq, cdr3_nucseq\n #assert v_gene.startswith('TR') #and v_gene[2] == j_gene[2]\n ab = all_genes[organism][v_gene].chain\n v_nucseq = get_v_cdr3_nucseq( organism, v_gene )\n j_nucseq = get_j_cdr3_nucseq( organism, j_gene )\n ## how far out do we match\n num_matched_v = count_matches( v_nucseq, cdr3_nucseq, default_mismatch_score_for_junction_analysis )\n\n num_matched_j = count_matches( ''.join( reversed( list( j_nucseq ) )),\n ''.join( reversed( list( cdr3_nucseq ))),\n default_mismatch_score_for_junction_analysis )\n\n\n if num_matched_v + num_matched_j > len(cdr3_nucseq):\n ## some overlap!\n extra = num_matched_v + num_matched_j - len(cdr3_nucseq )\n fake_v_trim = extra//2 ## now deterministic\n fake_j_trim = extra - fake_v_trim\n num_matched_v -= fake_v_trim\n num_matched_j -= fake_j_trim\n\n assert num_matched_v + num_matched_j <= len(cdr3_nucseq)\n\n if num_matched_v + num_matched_j == len(cdr3_nucseq):\n nseq = ''\n else:\n nseq = cdr3_nucseq[num_matched_v:len(cdr3_nucseq)-num_matched_j]\n\n ncount = [1] * len(cdr3_nucseq)\n cdr3_nucseq_src = ['N'] * len(cdr3_nucseq)\n for i in range(num_matched_v):\n ncount[i] = 0\n cdr3_nucseq_src[i] = 'V'\n for i in range(num_matched_j):\n ncount[-1-i] = 0\n cdr3_nucseq_src[-1-i] = 'J'\n\n assert num_matched_v + num_matched_j + len(nseq) == len(cdr3_nucseq)\n\n v_trim = len(v_nucseq)-num_matched_v\n j_trim = len(j_nucseq)-num_matched_j\n\n assert len(cdr3_nucseq) == len(v_nucseq) + len(nseq) + len(j_nucseq) - ( v_trim + j_trim )\n\n #d_info = ''\n n_vj_insert = 0\n n_vd_insert = 0\n n_dj_insert = 0\n d0_trim = 0\n d1_trim = 0\n best_d_id = 0\n\n if ab == 'A':\n n_vj_insert = len(nseq)\n\n elif ab == 'B':\n ## look for one of the d-gene segments\n max_overlap = 0\n for d_id, d_nucseq in all_trbd_nucseq[organism].items():\n if force_d_id and d_id != force_d_id: continue\n for start in range(len(d_nucseq)):\n for stop in range(start,len(d_nucseq)):\n overlap_seq = d_nucseq[start:stop+1]\n if overlap_seq in nseq:\n if len(overlap_seq)>max_overlap:\n max_overlap = len(overlap_seq)\n best_d_id = d_id\n best_overlap_seq = overlap_seq\n best_trim = (start,len(d_nucseq)-1-stop)\n\n if max_overlap: ## found a bit of d, although it might be bogus (eg 1 nt)\n pos = nseq.index( best_overlap_seq )\n for i in range(pos+num_matched_v,pos+num_matched_v+max_overlap):\n assert ncount[i] == 1\n ncount[i] = 0\n cdr3_nucseq_src[i] = 'D'\n nseq = nseq[:i-num_matched_v] + '+' + nseq[i+1-num_matched_v:]\n\n n_vd_insert = pos\n n_dj_insert = len(nseq) - pos - len(best_overlap_seq)\n d0_trim = best_trim[0]\n d1_trim = best_trim[1]\n\n expected_cdr3_nucseq_len = ( len(v_nucseq) + n_vd_insert +\n len(all_trbd_nucseq[organism][best_d_id]) + n_dj_insert +\n len(j_nucseq) -\n ( v_trim + d0_trim + d1_trim + j_trim ) )\n assert len(cdr3_nucseq) == expected_cdr3_nucseq_len\n\n\n else:\n best_d_id = 0\n n_vd_insert = 0\n n_dj_insert = 0\n d0_trim = 0\n d1_trim = 0\n\n\n\n\n if cdr3_protseq:\n assert 3*len(cdr3_protseq) == len(ncount)\n\n newseq = ''\n newseq_ncount = ''\n\n for i,a in enumerate(cdr3_protseq):\n nc = sum(ncount[3*i:3*i+3])\n newseq_ncount += repr(nc)\n if nc>1:\n newseq += a\n elif nc==1:\n newseq += a.lower()\n else:\n newseq += '-'\n\n ## output\n cdr3_protseq_masked = newseq[:]\n cdr3_protseq_new_nucleotide_countstring = newseq_ncount[:]\n else:## no protseq given (perhaps its an out of frame?)\n cdr3_protseq_masked = ''\n cdr3_protseq_new_nucleotide_countstring = ''\n\n new_nucseq = nseq[:]\n\n trims = ( v_trim, d0_trim, d1_trim, j_trim )\n inserts = ( best_d_id, n_vd_insert, n_dj_insert, n_vj_insert )\n\n ## new_nucseq spans the inserted nucleotide sequence and has '+' for D-nucleotides\n if return_cdr3_nucseq_src:\n return new_nucseq, cdr3_protseq_masked, cdr3_protseq_new_nucleotide_countstring, trims, inserts, cdr3_nucseq_src\n else:\n return new_nucseq, cdr3_protseq_masked, cdr3_protseq_new_nucleotide_countstring, trims, inserts\n\n\n\n\ndef add_masked_CDR3_sequences_to_tcr_dict( organism, vals ):\n ## this code is mostly taken from compute_probs.py\n va_gene = vals['va_gene']\n ja_gene = vals['ja_gene']\n vb_gene = vals['vb_gene']\n jb_gene = vals['jb_gene']\n cdr3a_protseq = vals['cdr3a']\n cdr3a_nucseq = vals['cdr3a_nucseq']\n cdr3b_protseq = vals['cdr3b']\n cdr3b_nucseq = vals['cdr3b_nucseq']\n\n a_junction_results = analyze_junction( organism, va_gene, ja_gene, cdr3a_protseq, cdr3a_nucseq )\n b_junction_results = analyze_junction( organism, vb_gene, jb_gene, cdr3b_protseq, cdr3b_nucseq )\n\n cdr3a_new_nucseq, cdr3a_protseq_masked, cdr3a_protseq_new_nucleotide_countstring,a_trims,a_inserts \\\n = a_junction_results\n cdr3b_new_nucseq, cdr3b_protseq_masked, cdr3b_protseq_new_nucleotide_countstring,b_trims,b_inserts \\\n = b_junction_results\n\n # from tcr_sampler.py:\n # trims = ( v_trim, d0_trim, d1_trim, j_trim )\n # inserts = ( best_d_id, n_vd_insert, n_dj_insert, n_vj_insert )\n\n assert a_trims[1] + a_trims[2] + a_inserts[0] + a_inserts[1] + a_inserts[2] + b_inserts[3] == 0\n assert a_inserts[3] == len( cdr3a_new_nucseq )\n\n ita = '+%d-%d'%(sum(a_inserts[1:]),sum(a_trims))\n itb = '+%d-%d'%(sum(b_inserts[1:]),sum(b_trims))\n\n vals[ 'cdr3a_protseq_masked'] = cdr3a_protseq_masked\n vals[ 'a_indels'] = ita\n vals[ 'cdr3a_new_nucseq' ] = cdr3a_new_nucseq\n vals[ 'cdr3b_protseq_masked'] = cdr3b_protseq_masked\n vals[ 'b_indels'] = itb\n vals[ 'cdr3b_new_nucseq' ] = cdr3b_new_nucseq\n\n\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n\n","sub_path":"conga/tcrdist/tcr_sampler.py","file_name":"tcr_sampler.py","file_ext":"py","file_size_in_byte":14895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"602669323","text":"#!/usr/bin/python\n\n'''\n Script for building and uploading a STM8 project with dependency auto-detection\n'''\n\n# set general options\nUPLOAD = 'SWIM' # select 'BSL' or 'SWIM'\nTERMINAL = True # set True to open terminal after upload\nRESET = 1 # STM8 reset: 0=skip, 1=manual, 2=DTR line (RS232), 3=send 'Re5eT!' @ 115.2kBaud, 4=Arduino pin 8, 5=Raspi pin 12\nOPTIONS = '' # e.g. device for SPL ('-DSTM8S105', see stm8s.h)\n\n# set path to root of STM8 templates\nROOT_DIR = '../../../'\nLIB_ROOT = ROOT_DIR + 'Library/'\nTOOL_DIR = ROOT_DIR + 'Tools/'\nOBJDIR = 'output'\nTARGET = 'main.ihx'\n\n# set OS specific\nimport platform\nif platform.system() == 'Windows':\n PORT = 'COM10'\n SWIM_PATH = 'C:/Programme/STMicroelectronics/st_toolset/stvp/'\n SWIM_TOOL = 'ST-LINK'\n SWIM_NAME = 'STM8S105x6' # STM8 Discovery\n #SWIM_NAME = 'STM8S208xB' # muBoard\n MAKE_TOOL = 'mingw32-make.exe'\nelse:\n PORT = '/dev/ttyUSB0'\n SWIM_TOOL = 'stlink'\n SWIM_NAME = 'stm8s105c6' # STM8 Discovery\n #SWIM_NAME = 'stm8s208?b' # muBoard\n MAKE_TOOL = 'make'\n \n# import required modules\nimport sys\nimport os\nimport platform\nimport argparse\nsys.path.insert(0,TOOL_DIR) # assert that TOOL_DIR is searched first\nimport misc\nfrom buildProject import createMakefile, buildProject\nfrom uploadHex import stm8gal, stm8flash, STVP\n\n\n##################\n# main program\n##################\n\n# commandline parameters with defaults\nparser = argparse.ArgumentParser(description=\"compile and upload STM8 project\")\nparser.add_argument(\"--skipmakefile\", default=False, action=\"store_true\" , help=\"skip creating Makefile\")\nparser.add_argument(\"--skipbuild\", default=False, action=\"store_true\" , help=\"skip building project\")\nparser.add_argument(\"--skipupload\", default=False, action=\"store_true\" , help=\"skip uploading hexfile\")\nparser.add_argument(\"--skipterminal\", default=False, action=\"store_true\" , help=\"skip opening terminal\")\nparser.add_argument(\"--skippause\", default=False, action=\"store_true\" , help=\"skip pause before exit\")\nargs = parser.parse_args()\n\n\n# create Makefile\nif args.skipmakefile == False:\n createMakefile(workdir='.', libroot=LIB_ROOT, outdir=OBJDIR, target=TARGET, options=OPTIONS)\n\n# build target \nif args.skipbuild == False:\n buildProject(workdir='.', make=MAKE_TOOL)\n\n# upload code via UART bootloader\nif args.skipupload == False:\n if UPLOAD == 'BSL':\n stm8gal(tooldir=TOOL_DIR, port=PORT, outdir=OBJDIR, target=TARGET, reset=RESET)\n \n \n # upload code via SWIM. Use stm8flash on Linux, STVP on Windows (due to libusb issues)\n if UPLOAD == 'SWIM':\n if platform.system() == 'Windows':\n STVP(tooldir=SWIM_PATH, device=SWIM_NAME, hardware=SWIM_TOOL, outdir=OBJDIR, target=TARGET)\n else:\n stm8flash(tooldir=TOOL_DIR, device=SWIM_NAME, hardware=SWIM_TOOL, outdir=OBJDIR, target=TARGET)\n\n\n# if specified open serial console after upload\nif args.skipterminal == False:\n if TERMINAL == True:\n cmd = 'python '+TOOL_DIR+'terminal.py -p '+PORT\n exitcode = os.system(cmd)\n if (exitcode != 0):\n sys.stderr.write('error '+str(exitcode)+'\\n\\n')\n misc.Exit(exitcode)\n \n# wait for return, then close window\nif args.skippause == False:\n if (sys.version_info.major == 3):\n input(\"\\npress return to exit ... \")\n else:\n raw_input(\"\\npress return to exit ... \")\n sys.stdout.write('\\n\\n')\n\n# END OF MODULE\n","sub_path":"Projects/STM8S_Discovery_Examples/echo_UART_with_ISR/build_upload.py","file_name":"build_upload.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"296508199","text":"\"\"\"\nA ImageMagnifier Idevice is one built up from an image and free text.\n\"\"\"\nimport logging\nfrom exe.engine.idevice import Idevice\nfrom exe.engine.field import TextAreaField, MultimediaField\nfrom exe.engine.translate import lateTranslate\nlog = logging.getLogger(__name__)\nclass MultimediaIdevice(Idevice):\n \"\"\"\n A Multimedia Idevice is one built up from an Multimedia file and free text.\n \"\"\"\n persistenceVersion = 1\n def __init__(self, defaultMedia = None):\n Idevice.__init__(self, \n x_(u\"MP3\"), \n x_(u\"Auckland University of Technology\"), \n x_(u\"The MP3 iDevice allows you to attach an MP3 \" \n \"media file to your content along with relevant textual\"\n \"learning instructions.\"),\n u\"\", \n u\"\")\n self.emphasis = Idevice.NoEmphasis\n self.media = MultimediaField(\n x_(u\"Choose an MP3 file\"),\n x_(u\"\"\n \"
      \"\n \"
    1. Click <Select an MP3> and browse to the MP3 \"\n \" file you wish to insert
    2. \"\n \"
    3. Click on the dropdown menu to select the position \"\n \" that you want the file displayed on screen.
    4. \"\n \"
    5. Enter an optional caption for your file.
    6. \"\n \"
    7. Associate any relevant text to the MP3 file.
    8. \"\n \"
    9. Choose the type of style you would like the iDevice to\"\n \" display e.g. 'Some emphasis' \"\n \"applies a border and icon to the iDevice content displayed.
    10. \"\n \"
    \"\n ))\n self.media.idevice = self\n self.text = TextAreaField(x_(u\"Text\"),\n x_(\"\"\"Enter the text you wish to \nassociate with the file.\"\"\"))\n self.text.idevice = self\n self.float = u\"left\"\n self.caption = u\"\"\n self.icon = u\"multimedia\"\n self._captionInstruc = x_(u\"\"\"Provide a caption for the \nMP3 file. This will appear in the players title bar as well.\"\"\")\n self._alignInstruc = x_(u\"\"\"Alignment allows you to \nchoose where on the screen the media player will be positioned.\"\"\")\n captionInstruc = lateTranslate('captionInstruc')\n alignInstruc = lateTranslate('alignInstruc')\ndef register(ideviceStore):\n \"\"\"Register with the ideviceStore\"\"\"\n ideviceStore.extended.append(MultimediaIdevice())\n","sub_path":"eXe/rev2283-2337/right-branch-2337/exe/engine/multimediaidevice.py","file_name":"multimediaidevice.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"327010219","text":"import os\nimport argparse\nimport time\nimport tensorflow as tf\nimport numpy as np\nimport torch\nfrom torch.utils import data\nfrom functools import partial\n\nfrom datahandler.flow import get_dataset\nfrom model import PWCDCNet\nfrom losses import L1loss, L2loss, EPE, multiscale_loss, multirobust_loss\nfrom utils import show_progress\nfrom flow_utils import vis_flow, vis_flow_pyramid\n\n\nclass Trainer(object):\n def __init__(self, args):\n self.args = args\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n self.sess = tf.Session(config = config)\n self._build_dataloader()\n self._build_graph()\n\n def _build_dataloader(self):\n dset = get_dataset(self.args.dataset)\n data_args = {'dataset_dir':self.args.dataset_dir, \"origin_size\":None,\n 'crop_type':self.args.crop_type, 'crop_shape':self.args.crop_shape,\n 'resize_shape':self.args.resize_shape, 'resize_scale':self.args.resize_scale}\n tset = dset(train_or_val = 'train', **data_args)\n vset = dset(train_or_val = 'val', **data_args)\n self.image_size = tset.image_size\n\n load_args = {'batch_size': self.args.batch_size, 'num_workers':self.args.num_workers,\n 'drop_last':True, 'pin_memory':True}\n self.num_batches = int(len(tset.samples)/self.args.batch_size)\n self.tloader = data.DataLoader(tset, shuffle = True, **load_args)\n self.vloader = data.DataLoader(vset, shuffle = False, **load_args)\n \n def _build_graph(self):\n # Input images and ground truth optical flow definition\n with tf.name_scope('Data'):\n self.images = tf.placeholder(tf.float32, shape = (self.args.batch_size, 2, *self.image_size, 3),\n name = 'images')\n self.flows_gt = tf.placeholder(tf.float32, shape = (self.args.batch_size, *self.image_size, 2),\n name = 'flows')\n\n # Model inference via PWCNet\n self.model = PWCDCNet(num_levels = self.args.num_levels,\n search_range = self.args.search_range,\n warp_type = self.args.warp_type,\n use_dc = self.args.use_dc,\n output_level = self.args.output_level,\n name = 'pwcdcnet')\n self.flows_final, self.flows = self.model(self.images[:,0], self.images[:,1])\n\n # Loss calculation\n with tf.name_scope('Loss'):\n if self.args.loss is 'multiscale':\n self.criterion = multiscale_loss\n else:\n self.criterion =\\\n partial(multirobust_loss, epsilon = self.args.epsilon, q = self.args.q)\n \n _loss = self.criterion(self.flows_gt, self.flows, self.args.weights)\n weights_l2 = tf.reduce_sum([tf.nn.l2_loss(var) for var in self.model.vars])\n self.loss = _loss + self.args.gamma*weights_l2\n\n self.epe = EPE(self.flows_gt, self.flows_final)\n\n # Gradient descent optimization\n with tf.name_scope('Optimize'):\n self.global_step = tf.train.get_or_create_global_step()\n self.global_step_update = self.global_step.assign_add(1)\n if self.args.lr_scheduling:\n boundaries = [200000, 400000, 600000, 800000, 1000000]\n values = [self.args.lr/(2**i) for i in range(len(boundaries)+1)]\n lr = tf.train.piecewise_constant(self.global_step, boundaries, values)\n else:\n lr = self.args.lr\n\n self.optimizer = tf.train.AdamOptimizer(learning_rate = lr)\\\n .minimize(self.loss, var_list = self.model.vars)\n\n # Initialization\n self.saver = tf.train.Saver(self.model.vars)\n self.sess.run(tf.global_variables_initializer())\n if self.args.resume is not None:\n print(f'Loading learned model from checkpoint {self.args.resume}')\n self.saver.restore(self.sess, self.args.resume)\n\n tf.summary.FileWriter('./logs', graph = self.sess.graph)\n \n def train(self):\n train_start = time.time()\n for e in range(self.args.num_epochs):\n # Training\n for i, (images, flows_gt) in enumerate(self.tloader):\n images = images.numpy()/255.0\n flows_gt = flows_gt.numpy()\n \n time_s = time.time()\n _, _, loss, epe = \\\n self.sess.run([self.optimizer, self.global_step_update,\n self.loss, self.epe],\n feed_dict = {self.images: images, self.flows_gt: flows_gt})\n\n if i%20 == 0:\n batch_time = time.time() - time_s\n kwargs = {'loss':loss, 'epe':epe, 'batch time':batch_time}\n show_progress(e+1, i+1, self.num_batches, **kwargs)\n\n # Validation\n loss_vals, epe_vals = [], []\n for images_val, flows_gt_val in self.vloader:\n images_val = images_val.numpy()/255.0\n flows_gt_val = flows_gt_val.numpy()\n\n flows_val, loss_val, epe_val \\\n = self.sess.run([self.flows, self.loss, self.epe],\n feed_dict = {self.images: images_val,\n self.flows_gt: flows_gt_val})\n loss_vals.append(loss_val)\n epe_vals.append(epe_val)\n \n g_step = self.sess.run(self.global_step)\n print(f'\\r{e+1} epoch validation, loss: {np.mean(loss_vals)}, epe: {np.mean(epe_vals)}'\\\n +f', global step: {g_step}, elapsed time: {time.time()-train_start} sec.')\n \n # visualize estimated optical flow\n if self.args.visualize:\n if not os.path.exists('./figure'):\n os.mkdir('./figure')\n # Estimated flow values are downscaled, rescale them compatible to the ground truth\n flow_set = []\n for l, flow in enumerate(flows_val):\n upscale = 20/2**(self.args.num_levels-l)\n flow_set.append(flow[0]*upscale)\n flow_gt = flows_gt_val[0]\n images_v = images_val[0]\n vis_flow_pyramid(flow_set, flow_gt, images_v,\n f'./figure/flow_{str(e+1).zfill(4)}.pdf')\n\n if not os.path.exists('./model'):\n os.mkdir('./model')\n self.saver.save(self.sess, f'./model/model_{e+1}.ckpt')\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--dataset', type = str, default = 'SintelClean',\n help = 'Target dataset, [SintelClean]')\n parser.add_argument('-dd', '--dataset_dir', type = str, required = True,\n help = 'Directory containing target dataset')\n parser.add_argument('-e', '--num_epochs', type = int, default = 100,\n help = '# of epochs [100]')\n parser.add_argument('-b', '--batch_size', type = int, default = 4,\n help = 'Batch size [4]')\n parser.add_argument('-nw', '--num_workers', type = int, default = 2,\n help = '# of workers for data loading [2]')\n\n parser.add_argument('--crop_type', type = str, default = 'random',\n help = 'Crop type for raw data [random]')\n parser.add_argument('--crop_shape', nargs = 2, type = int, default = [384, 448],\n help = 'Crop shape for raw data [384, 448]')\n parser.add_argument('--resize_shape', nargs = 2, type = int, default = None,\n help = 'Resize shape for raw data [None]')\n parser.add_argument('--resize_scale', type = float, default = None,\n help = 'Resize scale for raw data [None]')\n\n parser.add_argument('--num_levels', type = int, default = 6,\n help = '# of levels for feature extraction [6]')\n parser.add_argument('--search_range', type = int, default = 4,\n help = 'Search range for cost-volume calculation [4]')\n parser.add_argument('--warp_type', default = 'bilinear', choices = ['bilinear', 'nearest'],\n help = 'Warping protocol, [bilinear] or nearest')\n parser.add_argument('--use-dc', dest = 'use_dc', action = 'store_true',\n help = 'Enable dense connection in optical flow estimator, [diabled] as default')\n parser.add_argument('--no-dc', dest = 'use_dc', action = 'store_false',\n help = 'Disable dense connection in optical flow estimator, [disabled] as default')\n parser.set_defaults(use_dc = False)\n parser.add_argument('--output_level', type = int, default = 4,\n help = 'Final output level for estimated flow [4]')\n\n parser.add_argument('--loss', default = 'multiscale', choices = ['multiscale', 'robust'],\n help = 'Loss function choice in [multiscale/robust]')\n parser.add_argument('--lr', type = float, default = 1e-4,\n help = 'Learning rate [1e-4]')\n parser.add_argument('--lr_scheduling', dest = 'lr_scheduling', action = 'store_true',\n help = 'Enable learning rate scheduling, [enabled] as default')\n parser.add_argument('--no-lr_scheduling', dest = 'lr_scheduling', action = 'store_false',\n help = 'Disable learning rate scheduling, [enabled] as default')\n parser.set_defaults(lr_scheduling = True)\n parser.add_argument('--weights', nargs = '+', type = float,\n default = [0.32, 0.08, 0.02, 0.01, 0.005],\n help = 'Weights for each pyramid loss')\n parser.add_argument('--gamma', type = float, default = 0.0004,\n help = 'Coefficient for weight decay [4e-4]')\n parser.add_argument('--epsilon', type = float, default = 0.02,\n help = 'Small constant for robust loss [0.02]')\n parser.add_argument('--q', type = float, default = 0.4,\n help = 'Tolerance constant for outliear flow [0.4]')\n\n parser.add_argument('-v', '--visualize', dest = 'visualize', action = 'store_true',\n help = 'Enable estimated flow visualization, [enabled] as default')\n parser.add_argument('--no-visualize', dest = 'visualize', action = 'store_false',\n help = 'Disable estimated flow visualization, [enabled] as default')\n parser.set_defaults(visualize = True)\n parser.add_argument('-r', '--resume', type = str, default = None,\n help = 'Learned parameter checkpoint file [None]')\n \n args = parser.parse_args()\n for key, item in vars(args).items():\n print(f'{key} : {item}')\n\n os.environ['CUDA_VISIBLE_DEVICES'] = input('Input utilize gpu-id (-1:cpu) : ')\n\n trainer = Trainer(args)\n trainer.train()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"275554399","text":"from sqlalchemy import Column, String, Integer, Float\nfrom Src.db.base import Base\n\n\nclass TestFeatureSelected(Base):\n __tablename__ = 'training_feature_selected'\n\n id = Column(Integer, primary_key=True)\n Date = Column(String)\n Tweet_Text = Column(String)\n Tweet_Id = Column(String)\n User_Id = Column(String)\n User_Name = Column(String)\n User_Screen_Name = Column(String)\n Retweets = Column(Float)\n Favorites = Column(Float)\n Class = Column(Float)\n Tweet_length = Column(Integer)\n Number_of_URL = Column(Integer)\n No_of_arond_word = Column(Integer)\n No_of_hash_word = Column(Integer)\n Length_of_User_Name = Column(Integer)\n Number_of_Spam_Word = Column(Integer)\n Number_of_Swear_Word = Column(Integer)\n New_Feature = Column(Integer)\n\n def __init__(self,\n Date,\n Tweet_Text,\n Tweet_Id,\n User_Id,\n User_Name,\n User_Screen_Name,\n Retweets,\n Favorites,\n Class,\n Tweet_length,\n Number_of_URL,\n No_of_arond_word,\n No_of_hash_word,\n Length_of_User_Name,\n Number_of_Spam_Word,\n Number_of_Swear_Word,\n New_Feature):\n self.Date = Date\n self.Tweet_Text = Tweet_Text\n self.Tweet_Id = Tweet_Id\n self.User_Id = User_Id\n self.User_Name = User_Name\n self.User_Screen_Name = User_Screen_Name\n self.Retweets = Retweets\n self.Favorites = Favorites\n self.Class = Class\n self.Tweet_length = Tweet_length\n self.Number_of_URL = Number_of_URL\n self.No_of_arond_word = No_of_arond_word\n self.No_of_hash_word = No_of_hash_word\n self.Length_of_User_Name = Length_of_User_Name\n self.Number_of_Spam_Word = Number_of_Spam_Word\n self.Number_of_Swear_Word = Number_of_Swear_Word\n self.New_Feature = New_Feature\n","sub_path":"Src/entities/test_feature_selected.py","file_name":"test_feature_selected.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"201194619","text":"import numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nsys.path.append(\"..\") #since the notebook is stored in object_detection\n\n# [IN 3]\nfrom utils import label_map_util\nfrom utils import visualization_utils as vis_util #model\n\n# [IN 4]\nMODEL_NAME = 'amubulance_12_07_2019'\nMODEL_FILE = MODEL_NAME + '.tar.gz'\nDOWNLOAD_BASE = 'https://storage.googleapis.com/openimages/web/visualizer/index.html?set=train&type=segmentation&r=false&c=%2Fm%2F012n7d'\n\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\nPATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')\n\nNUM_CLASSES = 90\n\n\n# In[ 5 ]:\n\nopener = urllib.request.URLopener()\nopener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\ntar_file = tarfile.open(MODEL_FILE)\nfor file in tar_file.getmembers():\n file_name = os.path.basename(file.name)\n if 'frozen_inference_graph.pb' in file_name:\n tar_file.extract(file, os.getcwd())\n \n# In[ 6] :\n\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n\n\n# In[ 7 ]:\n\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\n\n# In[ 8 ]:\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n# In[9]:\n\n\nPATH_TO_TEST_IMAGES_DIR = 'test_images'\nTEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 501) ] # we will use only 500 images/ datasets:\n\n\nIMAGE_SIZE = (12, 8) #output size\n\n\n# In[ 10 ]:\n\nwith detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n while True:\n ret, image_np = cap.read()\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0') #detection.\n \n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n vis_util.visualize_boxes_and_labels_on_image_array( #visualization of amubulance\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8)\n","sub_path":"main_sislancode3.py","file_name":"main_sislancode3.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"15790711","text":"'''\n做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用**生成激活码**(或者优惠券),\n使用 Python 如何生成 200 个激活码(或者优惠券)?\n将 生成的 200 个激活码(或者优惠券)保存到 **MySQL** 关系型数据库中。 \n将生成的 200 个激活码(或者优惠券)保存到 **Redis** 非关系型数据库中。 \n'''\n\nimport random\nimport pymysql\nimport redis\n\n#生成200个随机字符串,XXXX-XXXX-XXXX-XXXX\n'''\na-z:97-122\nA-Z:65-90\n0-9:48-57\n'''\nclass randomChar(object):\n\t\"\"\"docstring for randomChar\"\"\"\n\tdef randomString(self):\n\t\tlist = []\n\t\tfor i in range(48,58):\n\t\t\tlist.append(i)\n\t\tfor i in range(65,91):\n\t\t\tlist.append(i)\n\t\tfor i in range(97,123):\n\t\t\tlist.append(i)\n\t\tranS = ''\n\t\tfor j in range(4):\n\t\t\tfor i in range(4):\n\t\t\t\tindex = random.choice(list)\n\t\t\t\tranS += chr(index)\n\t\t\tif j != 3:\n\t\t\t\tranS += '-'\n\t\treturn ranS\n\n\n\n#连接MySql数据库\nclass MySqlOperation(object):\n\t#mysqlRedis\n\tdef __init__(self):\n\t\tself.conn = pymysql.connect(host='localhost',\n\t\t\t\t\t\t\t\t\tuser='root',\n\t\t\t\t\t\t\t\t\tpassword='11111111',\n\t\t\t\t\t\t\t\t\tdb='reptile',\n\t\t\t\t\t\t\t\t\tport=3306,\n\t\t\t\t\t\t\t\t\tcharset='utf8',\n\t\t\t\t\t\t\t\t\tcursorclass=pymysql.cursors.DictCursor)\n\t\tself.cur = self.conn.cursor()\n\tdef op_sql(self, params):\n\t\ttry:\n\t\t\tself.cur.execute(params)\n\t\t\tself.conn.commit()\n\t\t\treturn True\n\t\texcept pymysql.Error as e:\n\t\t\tprint('MySQL Error %d:%s' % (e.args[0], e.args[1]))\n\t\treturn False\n\n\tdef insertCode(self, code):\n\t\tsql = \"insert into mysqlRedis(code) values('%s')\" % code\n\t\tif not self.op_sql(sql):\n\t\t\tprint('insert error %s' % code)\n\t\telse:\n\t\t\tprint('success')\n\n\tdef selectCode(self):\n\t\tsql = \"select code from mysqlRedis\"\n\t\ttry:\n\t\t\tself.cur.execute(sql)\n\t\t\tself.cur.scroll(0, mode='absolute') # 光标回到初始位置\n\t\t\tresults = self.cur.fetchall() # 返回游标中所有结果\n\t\texcept pymysql.Error as e:\n\t\t\tresults = 'sql0001' # 数据库执行失败\n\t\t\tprint(\"MySQL Error %d: %s\" % (e.args[0], e.args[1]))\n\t\tfinally:\n\t\t\treturn results\n\n\n#连接redis数据库\nclass RedisOperation(object):\n\tdef __init__(self):\n\t\tpool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)\n\t\tself.r = redis.Redis(connection_pool=pool)\n\t\t\n\n\n\n#向mysql中插入数据\nfor i in range(200):\n\trandC = randomChar()\n\tcode = randC.randomString()\n\toperation = MySqlOperation()\n\toperation.insertCode(code)\n\n#查询mysql数据并存储在redis中\noperation = MySqlOperation()\nro = RedisOperation()\nr = ro.r\nr.delete('codes')\nfor code in operation.selectCode():\n\tr.sadd('codes', code['code'])\nprint(r.smembers('codes'))\n\n\n\n\n\n","sub_path":"Python/py-test/sql_redis.py","file_name":"sql_redis.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"607556888","text":"import subprocess\nimport os\nimport shlex\nimport logging\nfrom monster.models import Photo\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\n\n\nclass RepoManager:\n \"\"\"\n RepoManager handles repo clone/pull\n \"\"\"\n def __init__(self, repo_url, dest_dir, proxy=None):\n self.repo_url = repo_url\n self.dest_dir = dest_dir\n self.proxy = proxy\n if self.proxy is not None:\n os.environ.update({\n 'https_proxy': self.proxy,\n 'http_proxy': self.proxy\n })\n\n def clone_repo(self):\n cmd = 'git clone {} {}'.format(self.repo_url, self.dest_dir)\n logger.info('Running: {} [proxy: {}]'.format(cmd, self.proxy))\n subprocess.run(shlex.split(cmd))\n\n def pull_repo(self):\n cmd = 'git pull'\n logger.info('Running: {} [proxy: {}]'.format(cmd, self.proxy))\n subprocess.run(shlex.split(cmd), cwd=self.dest_dir)\n\n\nclass PhotoManager:\n PHOTO_EXTENSIONS = ['.jpg', '.png']\n\n def __init__(self, repo_root):\n self.repo_root = repo_root\n\n def photo_path_in_repo(self):\n photo_path = []\n for root, dirs, files in os.walk(self.repo_root):\n # Skip hidden directories, e.g. .git, .pytest_cache\n dirs[:] = [each for each in dirs if not each.startswith('.')]\n photo_path.extend([os.path.join(root, f) for f in files\n if os.path.splitext(f)[-1].lower() in PhotoManager.PHOTO_EXTENSIONS])\n return photo_path\n","sub_path":"monster/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458350790","text":"from PySide2.QtCore import Qt\nfrom PySide2.QtWidgets import QVBoxLayout\n\nfrom node_launcher.constants import LNCLI_COMMANDS\nfrom node_launcher.gui.components.console_dialog import ConsoleWidget\nfrom node_launcher.gui.components.tabs_dialog import TabsDialog\nfrom node_launcher.gui.menu.manage_lnd.lnd_configuration_tab import \\\n LndConfigurationTab\nfrom .lnd_output_tab import LndOutputTab\n\n\nclass LndManagerTabsDialog(TabsDialog):\n def __init__(self, lnd, system_tray):\n super().__init__()\n\n self.lnd = lnd\n self.system_tray = system_tray\n\n # lnd console\n self.console_tab = ConsoleWidget(\n title='lncli',\n program=self.lnd.software.lncli,\n args=self.lnd.lncli_arguments(),\n commands=LNCLI_COMMANDS\n )\n self.tab_widget.addTab(self.console_tab, 'lncli')\n\n # lnd output\n self.output_tab = LndOutputTab(\n lnd=self.lnd,\n system_tray=self.system_tray\n )\n self.tab_widget.addTab(self.output_tab, 'Logs')\n\n self.configuration_tab = LndConfigurationTab(self.lnd)\n self.tab_widget.addTab(self.configuration_tab, 'Configuration')\n\n self.main_layout = QVBoxLayout()\n self.main_layout.addWidget(self.tab_widget)\n self.setLayout(self.main_layout)\n\n self.setWindowTitle('Manage LND')\n\n self.has_run_help = False\n\n def show(self):\n if self.lnd.file['alias'] is not None:\n self.configuration_tab.alias_layout.set_alias(self.lnd.file['alias'])\n\n super().showMaximized()\n self.raise_()\n self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive)\n self.activateWindow()\n\n if not self.has_run_help:\n self.console_tab.run_command('help')\n","sub_path":"node_launcher/gui/menu/manage_lnd/lnd_manager_tabs_dialog.py","file_name":"lnd_manager_tabs_dialog.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"140748137","text":"# coding: utf-8\n\n\"\"\"\n CLOUD API\n\n An enterprise-grade Infrastructure is provided as a Service (IaaS) solution that can be managed through a browser-based \\\"Data Center Designer\\\" (DCD) tool or via an easy to use API. The API allows you to perform a variety of management tasks such as spinning up additional servers, adding volumes, adjusting networking, and so forth. It is designed to allow users to leverage the same power and flexibility found within the DCD visual tool. Both tools are consistent with their concepts and lend well to making the experience smooth and intuitive. # noqa: E501\n\n The version of the OpenAPI document: 5.0\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom ionoscloud.configuration import Configuration\n\n\nclass KubernetesNodePoolProperties(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'name': 'str',\n 'datacenter_id': 'str',\n 'node_count': 'int',\n 'cpu_family': 'str',\n 'cores_count': 'int',\n 'ram_size': 'int',\n 'availability_zone': 'str',\n 'storage_type': 'str',\n 'storage_size': 'int',\n 'k8s_version': 'str',\n 'maintenance_window': 'KubernetesMaintenanceWindow',\n 'auto_scaling': 'KubernetesAutoScaling',\n 'lans': 'list[KubernetesNodePoolLan]',\n 'labels': 'dict(str, str)',\n 'annotations': 'dict(str, str)',\n 'public_ips': 'list[str]',\n 'available_upgrade_versions': 'list[str]',\n }\n\n attribute_map = {\n 'name': 'name',\n 'datacenter_id': 'datacenterId',\n 'node_count': 'nodeCount',\n 'cpu_family': 'cpuFamily',\n 'cores_count': 'coresCount',\n 'ram_size': 'ramSize',\n 'availability_zone': 'availabilityZone',\n 'storage_type': 'storageType',\n 'storage_size': 'storageSize',\n 'k8s_version': 'k8sVersion',\n 'maintenance_window': 'maintenanceWindow',\n 'auto_scaling': 'autoScaling',\n 'lans': 'lans',\n 'labels': 'labels',\n 'annotations': 'annotations',\n 'public_ips': 'publicIps',\n 'available_upgrade_versions': 'availableUpgradeVersions',\n }\n\n def __init__(self, name=None, datacenter_id=None, node_count=None, cpu_family=None, cores_count=None, ram_size=None, availability_zone=None, storage_type=None, storage_size=None, k8s_version=None, maintenance_window=None, auto_scaling=None, lans=None, labels=None, annotations=None, public_ips=None, available_upgrade_versions=None, local_vars_configuration=None): # noqa: E501\n \"\"\"KubernetesNodePoolProperties - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._name = None\n self._datacenter_id = None\n self._node_count = None\n self._cpu_family = None\n self._cores_count = None\n self._ram_size = None\n self._availability_zone = None\n self._storage_type = None\n self._storage_size = None\n self._k8s_version = None\n self._maintenance_window = None\n self._auto_scaling = None\n self._lans = None\n self._labels = None\n self._annotations = None\n self._public_ips = None\n self._available_upgrade_versions = None\n self.discriminator = None\n\n self.name = name\n self.datacenter_id = datacenter_id\n self.node_count = node_count\n self.cpu_family = cpu_family\n self.cores_count = cores_count\n self.ram_size = ram_size\n self.availability_zone = availability_zone\n self.storage_type = storage_type\n self.storage_size = storage_size\n if k8s_version is not None:\n self.k8s_version = k8s_version\n if maintenance_window is not None:\n self.maintenance_window = maintenance_window\n if auto_scaling is not None:\n self.auto_scaling = auto_scaling\n if lans is not None:\n self.lans = lans\n if labels is not None:\n self.labels = labels\n if annotations is not None:\n self.annotations = annotations\n if public_ips is not None:\n self.public_ips = public_ips\n if available_upgrade_versions is not None:\n self.available_upgrade_versions = available_upgrade_versions\n\n @property\n def name(self):\n \"\"\"Gets the name of this KubernetesNodePoolProperties. # noqa: E501\n\n A Kubernetes Node Pool Name. Valid Kubernetes Node Pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. # noqa: E501\n\n :return: The name of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this KubernetesNodePoolProperties.\n\n A Kubernetes Node Pool Name. Valid Kubernetes Node Pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. # noqa: E501\n\n :param name: The name of this KubernetesNodePoolProperties. # noqa: E501\n :type name: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501\n raise ValueError(\"Invalid value for `name`, must not be `None`\") # noqa: E501\n\n self._name = name\n\n @property\n def datacenter_id(self):\n \"\"\"Gets the datacenter_id of this KubernetesNodePoolProperties. # noqa: E501\n\n A valid uuid of the datacenter on which user has access # noqa: E501\n\n :return: The datacenter_id of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: str\n \"\"\"\n return self._datacenter_id\n\n @datacenter_id.setter\n def datacenter_id(self, datacenter_id):\n \"\"\"Sets the datacenter_id of this KubernetesNodePoolProperties.\n\n A valid uuid of the datacenter on which user has access # noqa: E501\n\n :param datacenter_id: The datacenter_id of this KubernetesNodePoolProperties. # noqa: E501\n :type datacenter_id: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and datacenter_id is None: # noqa: E501\n raise ValueError(\"Invalid value for `datacenter_id`, must not be `None`\") # noqa: E501\n\n self._datacenter_id = datacenter_id\n\n @property\n def node_count(self):\n \"\"\"Gets the node_count of this KubernetesNodePoolProperties. # noqa: E501\n\n Number of nodes part of the Node Pool # noqa: E501\n\n :return: The node_count of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: int\n \"\"\"\n return self._node_count\n\n @node_count.setter\n def node_count(self, node_count):\n \"\"\"Sets the node_count of this KubernetesNodePoolProperties.\n\n Number of nodes part of the Node Pool # noqa: E501\n\n :param node_count: The node_count of this KubernetesNodePoolProperties. # noqa: E501\n :type node_count: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and node_count is None: # noqa: E501\n raise ValueError(\"Invalid value for `node_count`, must not be `None`\") # noqa: E501\n\n self._node_count = node_count\n\n @property\n def cpu_family(self):\n \"\"\"Gets the cpu_family of this KubernetesNodePoolProperties. # noqa: E501\n\n A valid cpu family name # noqa: E501\n\n :return: The cpu_family of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: str\n \"\"\"\n return self._cpu_family\n\n @cpu_family.setter\n def cpu_family(self, cpu_family):\n \"\"\"Sets the cpu_family of this KubernetesNodePoolProperties.\n\n A valid cpu family name # noqa: E501\n\n :param cpu_family: The cpu_family of this KubernetesNodePoolProperties. # noqa: E501\n :type cpu_family: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and cpu_family is None: # noqa: E501\n raise ValueError(\"Invalid value for `cpu_family`, must not be `None`\") # noqa: E501\n\n self._cpu_family = cpu_family\n\n @property\n def cores_count(self):\n \"\"\"Gets the cores_count of this KubernetesNodePoolProperties. # noqa: E501\n\n Number of cores for node # noqa: E501\n\n :return: The cores_count of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: int\n \"\"\"\n return self._cores_count\n\n @cores_count.setter\n def cores_count(self, cores_count):\n \"\"\"Sets the cores_count of this KubernetesNodePoolProperties.\n\n Number of cores for node # noqa: E501\n\n :param cores_count: The cores_count of this KubernetesNodePoolProperties. # noqa: E501\n :type cores_count: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and cores_count is None: # noqa: E501\n raise ValueError(\"Invalid value for `cores_count`, must not be `None`\") # noqa: E501\n\n self._cores_count = cores_count\n\n @property\n def ram_size(self):\n \"\"\"Gets the ram_size of this KubernetesNodePoolProperties. # noqa: E501\n\n RAM size for node, minimum size 2048MB is recommended. Ram size must be set to multiple of 1024MB. # noqa: E501\n\n :return: The ram_size of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: int\n \"\"\"\n return self._ram_size\n\n @ram_size.setter\n def ram_size(self, ram_size):\n \"\"\"Sets the ram_size of this KubernetesNodePoolProperties.\n\n RAM size for node, minimum size 2048MB is recommended. Ram size must be set to multiple of 1024MB. # noqa: E501\n\n :param ram_size: The ram_size of this KubernetesNodePoolProperties. # noqa: E501\n :type ram_size: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and ram_size is None: # noqa: E501\n raise ValueError(\"Invalid value for `ram_size`, must not be `None`\") # noqa: E501\n\n self._ram_size = ram_size\n\n @property\n def availability_zone(self):\n \"\"\"Gets the availability_zone of this KubernetesNodePoolProperties. # noqa: E501\n\n The availability zone in which the target VM should exist # noqa: E501\n\n :return: The availability_zone of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: str\n \"\"\"\n return self._availability_zone\n\n @availability_zone.setter\n def availability_zone(self, availability_zone):\n \"\"\"Sets the availability_zone of this KubernetesNodePoolProperties.\n\n The availability zone in which the target VM should exist # noqa: E501\n\n :param availability_zone: The availability_zone of this KubernetesNodePoolProperties. # noqa: E501\n :type availability_zone: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and availability_zone is None: # noqa: E501\n raise ValueError(\"Invalid value for `availability_zone`, must not be `None`\") # noqa: E501\n allowed_values = [\"AUTO\", \"ZONE_1\", \"ZONE_2\"] # noqa: E501\n if self.local_vars_configuration.client_side_validation and availability_zone not in allowed_values: # noqa: E501\n raise ValueError(\n \"Invalid value for `availability_zone` ({0}), must be one of {1}\" # noqa: E501\n .format(availability_zone, allowed_values)\n )\n\n self._availability_zone = availability_zone\n\n @property\n def storage_type(self):\n \"\"\"Gets the storage_type of this KubernetesNodePoolProperties. # noqa: E501\n\n Hardware type of the volume # noqa: E501\n\n :return: The storage_type of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: str\n \"\"\"\n return self._storage_type\n\n @storage_type.setter\n def storage_type(self, storage_type):\n \"\"\"Sets the storage_type of this KubernetesNodePoolProperties.\n\n Hardware type of the volume # noqa: E501\n\n :param storage_type: The storage_type of this KubernetesNodePoolProperties. # noqa: E501\n :type storage_type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and storage_type is None: # noqa: E501\n raise ValueError(\"Invalid value for `storage_type`, must not be `None`\") # noqa: E501\n allowed_values = [\"HDD\", \"SSD\"] # noqa: E501\n if self.local_vars_configuration.client_side_validation and storage_type not in allowed_values: # noqa: E501\n raise ValueError(\n \"Invalid value for `storage_type` ({0}), must be one of {1}\" # noqa: E501\n .format(storage_type, allowed_values)\n )\n\n self._storage_type = storage_type\n\n @property\n def storage_size(self):\n \"\"\"Gets the storage_size of this KubernetesNodePoolProperties. # noqa: E501\n\n The size of the volume in GB. The size should be greater than 10GB. # noqa: E501\n\n :return: The storage_size of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: int\n \"\"\"\n return self._storage_size\n\n @storage_size.setter\n def storage_size(self, storage_size):\n \"\"\"Sets the storage_size of this KubernetesNodePoolProperties.\n\n The size of the volume in GB. The size should be greater than 10GB. # noqa: E501\n\n :param storage_size: The storage_size of this KubernetesNodePoolProperties. # noqa: E501\n :type storage_size: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and storage_size is None: # noqa: E501\n raise ValueError(\"Invalid value for `storage_size`, must not be `None`\") # noqa: E501\n\n self._storage_size = storage_size\n\n @property\n def k8s_version(self):\n \"\"\"Gets the k8s_version of this KubernetesNodePoolProperties. # noqa: E501\n\n The kubernetes version in which a nodepool is running. This imposes restrictions on what kubernetes versions can be run in a cluster's nodepools. Additionally, not all kubernetes versions are viable upgrade targets for all prior versions. # noqa: E501\n\n :return: The k8s_version of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: str\n \"\"\"\n return self._k8s_version\n\n @k8s_version.setter\n def k8s_version(self, k8s_version):\n \"\"\"Sets the k8s_version of this KubernetesNodePoolProperties.\n\n The kubernetes version in which a nodepool is running. This imposes restrictions on what kubernetes versions can be run in a cluster's nodepools. Additionally, not all kubernetes versions are viable upgrade targets for all prior versions. # noqa: E501\n\n :param k8s_version: The k8s_version of this KubernetesNodePoolProperties. # noqa: E501\n :type k8s_version: str\n \"\"\"\n\n self._k8s_version = k8s_version\n\n @property\n def maintenance_window(self):\n \"\"\"Gets the maintenance_window of this KubernetesNodePoolProperties. # noqa: E501\n\n\n :return: The maintenance_window of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: KubernetesMaintenanceWindow\n \"\"\"\n return self._maintenance_window\n\n @maintenance_window.setter\n def maintenance_window(self, maintenance_window):\n \"\"\"Sets the maintenance_window of this KubernetesNodePoolProperties.\n\n\n :param maintenance_window: The maintenance_window of this KubernetesNodePoolProperties. # noqa: E501\n :type maintenance_window: KubernetesMaintenanceWindow\n \"\"\"\n\n self._maintenance_window = maintenance_window\n\n @property\n def auto_scaling(self):\n \"\"\"Gets the auto_scaling of this KubernetesNodePoolProperties. # noqa: E501\n\n\n :return: The auto_scaling of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: KubernetesAutoScaling\n \"\"\"\n return self._auto_scaling\n\n @auto_scaling.setter\n def auto_scaling(self, auto_scaling):\n \"\"\"Sets the auto_scaling of this KubernetesNodePoolProperties.\n\n\n :param auto_scaling: The auto_scaling of this KubernetesNodePoolProperties. # noqa: E501\n :type auto_scaling: KubernetesAutoScaling\n \"\"\"\n\n self._auto_scaling = auto_scaling\n\n @property\n def lans(self):\n \"\"\"Gets the lans of this KubernetesNodePoolProperties. # noqa: E501\n\n array of additional LANs attached to worker nodes # noqa: E501\n\n :return: The lans of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: list[KubernetesNodePoolLan]\n \"\"\"\n return self._lans\n\n @lans.setter\n def lans(self, lans):\n \"\"\"Sets the lans of this KubernetesNodePoolProperties.\n\n array of additional LANs attached to worker nodes # noqa: E501\n\n :param lans: The lans of this KubernetesNodePoolProperties. # noqa: E501\n :type lans: list[KubernetesNodePoolLan]\n \"\"\"\n\n self._lans = lans\n\n @property\n def labels(self):\n \"\"\"Gets the labels of this KubernetesNodePoolProperties. # noqa: E501\n\n map of labels attached to node pool # noqa: E501\n\n :return: The labels of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: dict(str, str)\n \"\"\"\n return self._labels\n\n @labels.setter\n def labels(self, labels):\n \"\"\"Sets the labels of this KubernetesNodePoolProperties.\n\n map of labels attached to node pool # noqa: E501\n\n :param labels: The labels of this KubernetesNodePoolProperties. # noqa: E501\n :type labels: dict(str, str)\n \"\"\"\n\n self._labels = labels\n\n @property\n def annotations(self):\n \"\"\"Gets the annotations of this KubernetesNodePoolProperties. # noqa: E501\n\n map of annotations attached to node pool # noqa: E501\n\n :return: The annotations of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: dict(str, str)\n \"\"\"\n return self._annotations\n\n @annotations.setter\n def annotations(self, annotations):\n \"\"\"Sets the annotations of this KubernetesNodePoolProperties.\n\n map of annotations attached to node pool # noqa: E501\n\n :param annotations: The annotations of this KubernetesNodePoolProperties. # noqa: E501\n :type annotations: dict(str, str)\n \"\"\"\n\n self._annotations = annotations\n\n @property\n def public_ips(self):\n \"\"\"Gets the public_ips of this KubernetesNodePoolProperties. # noqa: E501\n\n Optional array of reserved public IP addresses to be used by the nodes. IPs must be from same location as the data center used for the node pool. The array must contain one extra IP than maximum number of nodes could be. (nodeCount+1 if fixed node amount or maxNodeCount+1 if auto scaling is used) The extra provided IP Will be used during rebuilding of nodes. # noqa: E501\n\n :return: The public_ips of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._public_ips\n\n @public_ips.setter\n def public_ips(self, public_ips):\n \"\"\"Sets the public_ips of this KubernetesNodePoolProperties.\n\n Optional array of reserved public IP addresses to be used by the nodes. IPs must be from same location as the data center used for the node pool. The array must contain one extra IP than maximum number of nodes could be. (nodeCount+1 if fixed node amount or maxNodeCount+1 if auto scaling is used) The extra provided IP Will be used during rebuilding of nodes. # noqa: E501\n\n :param public_ips: The public_ips of this KubernetesNodePoolProperties. # noqa: E501\n :type public_ips: list[str]\n \"\"\"\n\n self._public_ips = public_ips\n\n @property\n def available_upgrade_versions(self):\n \"\"\"Gets the available_upgrade_versions of this KubernetesNodePoolProperties. # noqa: E501\n\n List of available versions for upgrading the node pool # noqa: E501\n\n :return: The available_upgrade_versions of this KubernetesNodePoolProperties. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._available_upgrade_versions\n\n @available_upgrade_versions.setter\n def available_upgrade_versions(self, available_upgrade_versions):\n \"\"\"Sets the available_upgrade_versions of this KubernetesNodePoolProperties.\n\n List of available versions for upgrading the node pool # noqa: E501\n\n :param available_upgrade_versions: The available_upgrade_versions of this KubernetesNodePoolProperties. # noqa: E501\n :type available_upgrade_versions: list[str]\n \"\"\"\n\n self._available_upgrade_versions = available_upgrade_versions\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, KubernetesNodePoolProperties):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, KubernetesNodePoolProperties):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"ionoscloud/models/kubernetes_node_pool_properties.py","file_name":"kubernetes_node_pool_properties.py","file_ext":"py","file_size_in_byte":22817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"213664477","text":"\"\"\"\nCreate a program that reads integers from the user until a blank line is entered. Once\nall of the integers have been read your program should display all of the negative\nnumbers, followed by all of the zeros, followed by all of the positive numbers. Within\neach group the numbers should be displayed in the same order that they were entered\nby the user. For example, if the user enters the values 3, -4, 1, 0, -1, 0, and -2 then\nyour program should output the values -4, -1, -2, 0, 0, 3, and 1. Your program\nshould display each value on its own line.\n\"\"\"\n\n# Create three lists to store the negative, zero and positive values\nnegatives = []\nzeros = []\npositives = []\n\n# Read all of the integers from the user, storing each integer in the correct list\nline = input(\"Enter an integer (blank to quit): \")\nwhile line != \"\":\n num = int(line)\n\n if num < 0:\n negatives.append(num)\n elif num > 0:\n positives.append(num)\n else:\n zeros.append(num)\n\n # Read the next line of the input from the user\n line = input(\"Enter an integer (blank to quit): \")\n\n# Display all of the negative values, then all of the zeros, then all of the positive values\nprint(\"The numbers were: \")\nnegatives.sort()\npositives.sort()\nfor n in negatives:\n print(n)\n\nfor n in zeros:\n print(n)\n\nfor n in positives:\n print(n)\n","sub_path":"5 Lists/_108_negative_zeroes_and_positive.py","file_name":"_108_negative_zeroes_and_positive.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"284988263","text":"from fastavro import writer as fastavro_writer\nfrom fastavro.read import SchemaResolutionError\nimport fastavro\n\nimport pytest\n\nfrom io import BytesIO\n\nschema_dict_a = {\n \"namespace\": \"example.avro2\",\n \"type\": \"record\",\n \"name\": \"evtest\",\n \"fields\": [\n {\"name\": \"a\", \"type\": \"int\"}\n ]\n}\n\nrecord_a = {\"a\": 123}\n\nschema_dict_a_b = {\n \"namespace\": \"example.avro2\",\n \"type\": \"record\",\n \"name\": \"evtest\",\n \"fields\": [\n {\"name\": \"a\", \"type\": \"int\"},\n {\"name\": \"b\", \"type\": [\"null\", \"int\"], \"default\": None}\n ]\n}\n\nrecord_a_b = {\"a\": 234, \"b\": 345}\n\nschema_dict_a_c = {\n \"namespace\": \"example.avro2\",\n \"type\": \"record\",\n \"name\": \"evtest\",\n \"fields\": [\n {\"name\": \"a\", \"type\": \"int\"},\n {\"name\": \"c\", \"type\": [\"null\", \"int\"]}\n ]\n}\n\n\ndef avro_to_bytes_with_schema(avro_schema, avro_dict):\n with BytesIO() as bytes_io:\n fastavro_writer(bytes_io, avro_schema, [avro_dict])\n return bytes_io.getvalue()\n\n\ndef bytes_with_schema_to_avro(avro_read_schema, binary):\n with BytesIO(binary) as bytes_io:\n reader = fastavro.reader(bytes_io, avro_read_schema)\n return next(reader)\n\n\ndef test_evolution_drop_field():\n record_bytes_a_b = avro_to_bytes_with_schema(schema_dict_a_b, record_a_b)\n record_a = bytes_with_schema_to_avro(schema_dict_a, record_bytes_a_b)\n assert \"b\" not in record_a\n\n\ndef test_evolution_add_field_with_default():\n record_bytes_a = avro_to_bytes_with_schema(schema_dict_a, record_a)\n record_b = bytes_with_schema_to_avro(schema_dict_a_b, record_bytes_a)\n assert \"b\" in record_b\n assert record_b.get(\"b\") is None\n\n\ndef test_evolution_add_field_without_default():\n with pytest.raises(SchemaResolutionError):\n record_bytes_a = avro_to_bytes_with_schema(schema_dict_a, record_a)\n bytes_with_schema_to_avro(schema_dict_a_c, record_bytes_a)\n\n\ndef test_enum_evolution_no_default_failure():\n original_schema = {\n \"type\": \"enum\",\n \"name\": \"test\",\n \"symbols\": [\"FOO\", \"BAR\"],\n }\n\n new_schema = {\n \"type\": \"enum\",\n \"name\": \"test\",\n \"symbols\": [\"BAZ\", \"BAR\"],\n }\n\n original_records = [\"FOO\"]\n\n bio = BytesIO()\n fastavro.writer(bio, original_schema, original_records)\n bio.seek(0)\n\n with pytest.raises(fastavro.read.SchemaResolutionError):\n list(fastavro.reader(bio, new_schema))\n\n\ndef test_enum_evolution_using_default():\n original_schema = {\n \"type\": \"enum\",\n \"name\": \"test\",\n \"symbols\": [\"A\", \"B\"],\n }\n\n new_schema = {\n \"type\": \"enum\",\n \"name\": \"test\",\n \"symbols\": [\"C\", \"D\"],\n \"default\": \"C\",\n }\n\n original_records = [\"A\"]\n\n bio = BytesIO()\n fastavro.writer(bio, original_schema, original_records)\n bio.seek(0)\n\n new_records = list(fastavro.reader(bio, new_schema))\n assert new_records == [\"C\"]\n","sub_path":"tests/test_schema_evolution.py","file_name":"test_schema_evolution.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"286384811","text":"\"\"\"Item-specific cleanup managers.\"\"\"\n\nimport logging\nimport os\nimport sys\nfrom datetime import datetime, timedelta\nfrom uuid import uuid4\n\nSDMAIN_ROOT = os.path.abspath('/opt/sdmain') # noqa\nsys.path.append(os.path.join(SDMAIN_ROOT, 'src', 'py', 'utils')) # noqa\nfrom ftp_util import FtpUtil # noqa\nsys.path.append(os.path.join(SDMAIN_ROOT, 'src', 'scripts', 'jenkins')) # noqa\nfrom jenkins_base_helpers import RkLabBaseJenkins # noqa\n\nfrom bodega_core import ItemManager\nfrom bodega_core.exceptions import (bodega_type_error,\n bodega_validation_error,\n bodega_value_error)\nfrom django.conf import settings\nfrom pytz import utc\nfrom .filters import RktestYmlFilter\nfrom .models import Item, JenkinsTask, RktestYml\n\nlog = logging.getLogger(__name__)\n\nRECOVERY_TIME_LIMIT = timedelta(hours=4)\n\nDYNAPOD_FTP_SERVER = 'files-master.colo.rubrik-lab.com'\nDYNAPOD_FTP_USER = 'ubuntu'\nDYNAPOD_FTP_PASSWORD = 'qwerty'\n\nBUILD_SEARCH_LIMIT = 250\n\nAHV_RECOVERY_JOB = 'recover-ahv-pod'\nCLOUD_RECOVERY_JOB = 'recover-cloud-pod'\nDYNAMIC_RECOVERY_JOB = 'recover-dynamic-pod'\nPROD_BRIK_RECOVERY_JOB = 'auto-recover-prod-brik-manufacture'\nSTATIC_RECOVERY_JOB = 'auto-recover-testbed'\nHYPERV_RECOVERY_JOB = 'recover-hyperv-pod'\n\nPLATFORM_TO_RECOVERY_JOB_NAME = {\n RktestYml.PLATFORM_AWS: CLOUD_RECOVERY_JOB,\n RktestYml.PLATFORM_AZURE: CLOUD_RECOVERY_JOB,\n RktestYml.PLATFORM_CISCO: PROD_BRIK_RECOVERY_JOB,\n RktestYml.PLATFORM_DELL: PROD_BRIK_RECOVERY_JOB,\n RktestYml.PLATFORM_DYNAPOD: DYNAMIC_RECOVERY_JOB,\n RktestYml.PLATFORM_DYNAPOD_ROBO: DYNAMIC_RECOVERY_JOB,\n RktestYml.PLATFORM_DYNAPOD_ROBO_AHV: AHV_RECOVERY_JOB,\n RktestYml.PLATFORM_DYNAPOD_ROBO_HYPERV: HYPERV_RECOVERY_JOB,\n RktestYml.PLATFORM_HPE: PROD_BRIK_RECOVERY_JOB,\n RktestYml.PLATFORM_LENOVO: PROD_BRIK_RECOVERY_JOB,\n RktestYml.PLATFORM_PROD_BRIK: PROD_BRIK_RECOVERY_JOB,\n RktestYml.PLATFORM_STATIC: STATIC_RECOVERY_JOB,\n RktestYml.PLATFORM_STATIC_ROBO: STATIC_RECOVERY_JOB,\n}\n\n\"\"\"\nSee INFRA-1074 for some introductory numbers.\n\nWe need 1.1 Microcloud hosts per dynapod, so we can come up with a final\n(vanilla) dynapod price.\n\nOPEX = 1.1 * $0.043 = $0.0473 per hour\nCAPEX = 1.1 * $2000 = $2200\nBodega price = OPEX + 0.000022815*CAPEX = $0.0975, let's round up to $0.10.\n\nSince we're doing all this rounding but want to retain the rationale behind\nthem for future updates, we simply return $0.10 as the price.\n\nTheoretically we should also account for dynapods having special\n(more expensive) data sources like MS SQL and Oracle, but it is not\na big deal for now. It might turn the 1.1 ratio into 1.2 or something\nand add $0.01 to the final price.\n\nProd Briks: We fit ~15 of them per rack and they cost ~$20k CAPEX so\n$5.55/15 + 0.000022815*$20k = ~$0.826 per hour. r528s are a big difference\n(maybe about double) on both OPEX and CAPEX.\n\nEdge nodes/pods: ~1/3 of a Microcloud host. So price probably about $0.03.\n\nAWS pod: Comprised of 4 CDM nodes plus 2 data sources. An example conf\nis in conf/awspod1.specs.yml. The 2 data sources are named winsql2012\nand ubfio.\n\nEach CDM node is a m4.xlarge Linux, so $0.2/hour in US West (Oregon).\nBoth winsql2012 and ubfio are t2.large instances, so $0.094/hour each.\nhttps://aws.amazon.com/ec2/pricing/on-demand/\n\nWe round up to come to $1.0 for the AWS pod ((4 * 0.2) + (2 * 0.1)).\n\"\"\"\nPLATFORM_TO_ITEM_PRICE = {\n RktestYml.PLATFORM_AWS: 1.0,\n RktestYml.PLATFORM_DYNAPOD: 0.1,\n RktestYml.PLATFORM_DYNAPOD_ROBO: 0.03,\n RktestYml.PLATFORM_PROD_BRIK: 0.826,\n RktestYml.PLATFORM_STATIC: 0.1,\n RktestYml.PLATFORM_STATIC_ROBO: 0.03\n}\n\nUNKNOWN_PLATFORM_DEFAULT_PRICE = 0.1\n\n\ndef get_item_price_by_platform(item_requirements):\n platform = item_requirements.get('platform', None)\n # If platform is not specified, try getting an object that\n # meets the item's requirements and use the platform of\n # that item to calculate price.\n if platform is None:\n item = RktestYmlFilter(item_requirements).qs.first()\n if item:\n platform = item.platform\n\n price = PLATFORM_TO_ITEM_PRICE.get(platform)\n\n if price:\n return price\n else:\n log.warn('Unknown item price for platform %s' % platform)\n return UNKNOWN_PLATFORM_DEFAULT_PRICE\n\n\nPROD_BRIK_MANUFACTURING_SERVER_FOR_LOCATION = {\n 'COLO': '10.0.122.32',\n 'HQ': '192.168.18.10'\n}\n\nCLOUD_PROVIDER_FOR_PLATFORM = {\n RktestYml.PLATFORM_AWS: 'aws',\n RktestYml.PLATFORM_AZURE: 'azure'\n}\n\n\nclass ReleaseQualBatonManager(ItemManager):\n def __init__(self):\n \"\"\"Override initialization in ItemManager.\"\"\"\n pass\n\n def get_item_recipe(self, requirements):\n return None\n\n def get_item_price(self, requirements):\n return get_item_price_by_platform(requirements)\n\n def get_pending_items_queryset(self,\n item_queryset):\n return item_queryset.none()\n\n def get_shelf_life(self, item):\n \"\"\"Return the shelf life of the item.\n\n The shelf life of an Item represents how long we want to wait for to\n clean up an Item if it is created but never used. The default timedelta\n means the Item never perishes and we should not clean it up until it is\n used.\n \"\"\"\n return timedelta()\n\n def get_status(self, release_qual_baton):\n return ItemManager.STATUS_SUCCESS\n\n def handle_cleanup(self, release_qual_baton):\n release_qual_baton.held_by = None\n release_qual_baton.save()\n\n def taste_test(self, release_qual_baton, requirements):\n return True\n\n def validate_item_requirements(self, item_requirements, user_sid,\n is_maintenance_order):\n \"\"\"Check if the given item requirements are valid for this Item.\"\"\"\n return\n\n\nclass RktestYmlManager(ItemManager):\n def __init__(self):\n \"\"\"Initialize jenkins_handle to None.\n\n This is done to avoid unnecessary connections to Jenkins when it\n isn't necessary. We will set jenkins_handle when we need to use it.\n \"\"\"\n self.jenkins_handle = None\n\n def _set_jenkins_handle(self):\n \"\"\"Connect to a Jenkins instance under self.jenkins_handle.\n\n RkLabBaseJenkins has what we need to connect to Jenkins, and is\n relatively lightweight, so let's use it. RkLabJenkins (which uses\n RkLabBaseJenkins) handles config files, but is a bit too heavy-handed\n and unnecessary since we use the Django settings file.\n \"\"\"\n rklab_jenkins = RkLabBaseJenkins(settings.JENKINS_API['url'],\n settings.JENKINS_API['username'],\n settings.JENKINS_API['token'])\n self.jenkins_handle = rklab_jenkins.jenkins_handle\n\n def _get_time_elapsed(self, rktestyml):\n \"\"\"Return timedelta of time elapsed since latest cleanup started.\"\"\"\n assert(isinstance(rktestyml.held_by, JenkinsTask))\n recovery_task = rktestyml.held_by\n delta = datetime.now(utc) - recovery_task.time_uuid_updated\n return delta\n\n def _get_timedelta_str(self, td):\n \"\"\"Remove microseconds and return a printable string.\"\"\"\n return str(td - timedelta(microseconds=td.microseconds))\n\n def _get_recovery_job_name(self, rktestyml):\n \"\"\"Return the recovery job name for an RktestYml's platform.\"\"\"\n platform = rktestyml.platform\n if platform not in PLATFORM_TO_RECOVERY_JOB_NAME:\n error_msg = 'Platform %s not supported for recovery' % platform\n bodega_value_error(log, error_msg)\n return PLATFORM_TO_RECOVERY_JOB_NAME[platform]\n\n def _process_jenkins_build_status(self, jenkins_build_status):\n \"\"\"Convert a Jenkins build status string to our own format.\"\"\"\n if jenkins_build_status == 'SUCCESS':\n return self.STATUS_SUCCESS\n elif jenkins_build_status == 'FAILURE' or \\\n jenkins_build_status == 'ABORTED':\n return self.STATUS_FAILURE\n return self.STATUS_WAITING # waiting for build to complete\n\n def _get_uuid_param(self, jenkins_build):\n \"\"\"Get the value of the UUID parameter on a Jenkins build.\n\n The implementation of jenkins_build.get_params() relies on a \"_class\"\n field existing in action objects returned by the API. We don't know\n why, but somehow the legacy Jenkins instance that we outsource recovery\n jobs to has stopped including this \"_class\" field so\n jenkins_build.get_params() returns nothing. So, get the UUID value\n ourselves by examining the API response in _data.\n \"\"\"\n uuid_param = None\n build_actions = jenkins_build._data.get('actions')\n for action in build_actions:\n params_action = action.get('parameters', [])\n for param in params_action:\n if param['name'] == 'UUID':\n uuid_param = param['value']\n return uuid_param\n\n def is_managing(self, rktestyml):\n if not isinstance(rktestyml, RktestYml):\n return False\n if not isinstance(rktestyml.held_by, JenkinsTask):\n return False\n return True\n\n def get_item_recipe(self, requirements):\n return None\n\n def get_item_price(self, requirements):\n return get_item_price_by_platform(requirements)\n\n def get_pending_items_queryset(self,\n item_queryset):\n return item_queryset.none()\n\n def get_shelf_life(self, item):\n \"\"\"Return the shelf life of the item.\n\n The shelf life of an Item represents how long we want to wait for to\n clean up an Item if it is created but never used. The default timedelta\n means the Item never perishes and we should not clean it up until it is\n used.\n \"\"\"\n return timedelta()\n\n def get_status(self, rktestyml):\n \"\"\"Return one of the cleanup statuses from above.\n\n This behaves similarly to jenkinsapi.job.get_build_by_params(...),\n which moves back in time through the list of builds. Unlike\n get_build_by_params(), we are matching the UUID and only the UUID,\n instead of all parameters.\n \"\"\"\n if not self.is_managing(rktestyml):\n return self.STATUS_NOT_MANAGING\n\n recovery_task = rktestyml.held_by\n build_uuid = recovery_task.uuid\n cached_buildnum = recovery_task.cached_buildnum\n\n log.debug(\n ('Getting status of %s ' % rktestyml) +\n ('which is being worked on by %s and ' % repr(build_uuid)) +\n ('currently has cached build number %s' % repr(cached_buildnum)))\n\n if not cached_buildnum:\n log.debug(\n ('%s is being ' % rktestyml) +\n ('worked on by %s and has no cached ' % repr(build_uuid)) +\n ('build number, so seems to be waiting to start.'))\n return self.STATUS_WAITING # waiting for build to start\n\n job_name = self._get_recovery_job_name(rktestyml)\n job = self.jenkins_handle.get_job(job_name)\n\n try:\n build = job.get_build(cached_buildnum)\n build_status = build.get_status()\n current_build_uuid = self._get_uuid_param(build)\n if current_build_uuid == str(build_uuid):\n log.debug(\n '%s %s: Found build: cached_buildnum=%s, status=%s' %\n (rktestyml.filename, repr(build_uuid),\n cached_buildnum, repr(build_status)))\n return self._process_jenkins_build_status(build_status)\n else:\n log.debug(\n ('Cached build %s has ' % repr(cached_buildnum)) +\n ('UUID %s instead of ' % repr(current_build_uuid)) +\n ('expected %s, ' % repr(build_uuid)) +\n ('so invalidating cache.'))\n recovery_task.cached_buildnum = None\n recovery_task.save()\n except:\n log.debug(\n ('Exception while finding cached build %s, ' %\n repr(cached_buildnum)) +\n ('will assume it is still waiting to start.'),\n exc_info=True)\n return self.STATUS_WAITING\n\n def identify_jenkins_tasks(self, rktest_ymls):\n \"\"\"Find Jenkins build numbers for the tasks holding these items.\n\n Outsourcing recovery work to Jenkins continues to be ugly, but until\n we have insourced a la carte replacements, we still need to do this.\n Set the cached_buildnum of the JenkinsTask instances holding the\n rktest_ymls while making a single pass over the Jenkins builds, which\n scales better than our prior technique of looking for only one\n JenkinsTask instance when scanning over Jenkins builds.\n \"\"\"\n log.debug(\n 'Identifying Jenkins tasks for %d rktest_ymls in recovery.' %\n len(rktest_ymls))\n\n self._set_jenkins_handle()\n tasks_by_job_and_uuid = {}\n for rktest_yml in rktest_ymls:\n jenkins_task = rktest_yml.held_by\n if not isinstance(jenkins_task, JenkinsTask):\n log.debug(\n ('%s is held by %s instead of a JenkinsTask ' %\n (rktest_yml, repr(jenkins_task))) +\n ('so ignore it.'))\n continue\n\n if jenkins_task.cached_buildnum is not None:\n log.debug(\n ('%s is held by %s ' %\n (rktest_yml, repr(jenkins_task))) +\n ('which has a cached build number of %s ' %\n repr(jenkins_task.cached_buildnum)) +\n ('for job URL %s ' % repr(jenkins_task.cached_job_url)) +\n ('so no need to search for it again.'))\n continue\n\n recovery_job_name = self._get_recovery_job_name(rktest_yml)\n if recovery_job_name not in tasks_by_job_and_uuid:\n tasks_by_job_and_uuid[recovery_job_name] = {}\n tasks_by_uuid = tasks_by_job_and_uuid[recovery_job_name]\n tasks_by_uuid[str(jenkins_task.uuid)] = jenkins_task\n\n # Sort the recovery job names so those with the most tasks to search\n # for come first. Usually this will be recover-dynamic-pod. Since this\n # is all happening in a single thread, it's preferable to process the\n # jobs with more tasks before those with fewer tasks so the latter do\n # not block the former in the worst case of searching until the end\n # of the range. The jobs with more tasks also probably have higher\n # churn, making it more important to identify those tasks quickly to\n # reduce the risk of them rolling off before we can identify them.\n def num_recovery_job_tasks(recovery_job_name):\n return len(tasks_by_job_and_uuid[recovery_job_name])\n recovery_job_names = sorted(\n tasks_by_job_and_uuid.keys(),\n key=num_recovery_job_tasks,\n reverse=True)\n num_tasks_to_find = 0\n num_unidentified_tasks = 0\n log.debug(\n 'Starting search for tasks among Jenkins jobs %s.' %\n (repr(recovery_job_names)))\n for recovery_job_name in recovery_job_names:\n tasks_by_uuid = tasks_by_job_and_uuid[recovery_job_name]\n num_tasks_to_find += len(tasks_by_uuid)\n num_unidentified_tasks += self._identify_jenkins_tasks_for_job(\n recovery_job_name, tasks_by_uuid)\n log.debug(\n ('Finished searching for %d tasks among Jenkins jobs %s. ' %\n (num_tasks_to_find, repr(recovery_job_names))) +\n ('%d tasks remained unidentified.' % num_unidentified_tasks))\n\n def _identify_jenkins_tasks_for_job(self,\n recovery_job_name,\n tasks_by_uuid):\n log.debug(\n ('Identifying %d Jenkins tasks ' % len(tasks_by_uuid)) +\n ('expected to be instances of Jenkins job %s.' %\n repr(recovery_job_name)))\n job = self.jenkins_handle.get_job(recovery_job_name)\n\n # Search backwards through the Jenkins builds. Consider\n # BUILD_SEARCH_LIMIT builds at minimum but scale it according to the\n # number of tasks we know we're searching for.\n last_build = job.get_last_buildnumber()\n build_search_limit = max(BUILD_SEARCH_LIMIT,\n 2 * len(tasks_by_uuid))\n first_build = max(job.get_first_buildnumber(),\n last_build - build_search_limit)\n log.debug('Looking through builds of %s numbers %d through %d...' %\n (repr(recovery_job_name), last_build, first_build))\n for buildnum in range(last_build, first_build - 1, -1):\n if len(tasks_by_uuid) == 0:\n log.debug(\n ('No more tasks left to identify for job %s ' %\n repr(recovery_job_name)) +\n ('so finishing.'))\n break\n\n try:\n build = job.get_build(buildnum)\n build_status = build.get_status()\n current_build_uuid = self._get_uuid_param(build)\n except:\n log.debug(\n 'Could not find build %s of job %s, moving on...' %\n (repr(buildnum), repr(recovery_job_name)),\n exc_info=True)\n continue\n\n log.debug(\n 'Build %s of job %s has UUID=%s and status=%s.' %\n (repr(buildnum), repr(recovery_job_name),\n repr(current_build_uuid), repr(build_status)))\n if current_build_uuid in tasks_by_uuid:\n recovery_task = tasks_by_uuid[current_build_uuid]\n recovery_task.cached_buildnum = buildnum\n recovery_task.save()\n log.debug(\n ('Found build %s of job %s status=%s ' %\n (repr(buildnum), repr(recovery_job_name),\n repr(build_status))) +\n ('matching recovery task %s ' % recovery_task.uuid) +\n ('holding items %s' %\n repr(recovery_task.holding_items.all())))\n tasks_by_uuid.pop(current_build_uuid)\n\n log.debug(\n ('Finished looking through builds of %s. ' %\n repr(recovery_job_name)) +\n ('%d tasks were still unidentified: %s' %\n (len(tasks_by_uuid), repr(sorted(tasks_by_uuid.keys())))))\n return len(tasks_by_uuid)\n\n def _build_recovery_job(self, rktestyml):\n \"\"\"Trigger a Jenkins recovery job build for an RktestYml.\"\"\"\n assert(isinstance(rktestyml.held_by, JenkinsTask))\n recovery_job_name = self._get_recovery_job_name(rktestyml)\n slave_label = ('%s:%s:rkslave' %\n (rktestyml.location.name, rktestyml.network.name))\n build_params = {\n 'ENCRYPTED': str(rktestyml.encrypted),\n 'R6XX': str(rktestyml.model_r6xx),\n 'RESERVED_RESOURCE': rktestyml.filename,\n 'SLAVE_LABEL': slave_label,\n 'UUID': str(rktestyml.held_by.uuid)\n }\n\n if rktestyml.platform == RktestYml.PLATFORM_PROD_BRIK:\n location = rktestyml.location.name\n build_params['MANUFACTURING_SERVER'] = \\\n PROD_BRIK_MANUFACTURING_SERVER_FOR_LOCATION[location]\n\n if rktestyml.platform == RktestYml.PLATFORM_AWS or \\\n rktestyml.platform == RktestYml.PLATFORM_AZURE:\n build_params['CLOUD_PROVIDER'] = \\\n CLOUD_PROVIDER_FOR_PLATFORM[rktestyml.platform]\n\n job = self.jenkins_handle.get_job(recovery_job_name)\n recovery_task = rktestyml.held_by\n recovery_task.cached_job_url = job.url\n recovery_task.save()\n\n self.jenkins_handle.build_job(recovery_job_name, build_params)\n log.debug('Building job=%s with params=%s' %\n (repr(recovery_job_name), repr(build_params)))\n\n def _start_cleanup(self, rktestyml):\n \"\"\"Start the cleanup process.\n\n A new JenkinsTask should be created for recovery, and a new build\n should be triggered.\n \"\"\"\n recovery_task = JenkinsTask.objects.create()\n rktestyml.held_by = recovery_task\n rktestyml.save()\n log.debug('%s %s: Assigned JenkinsTask to held_by' %\n (rktestyml.filename, repr(recovery_task.uuid)))\n self._build_recovery_job(rktestyml)\n\n def _update_cleanup(self, rktestyml):\n \"\"\"Retry the cleanup process.\n\n The existing JenkinsTask should receive a new UUID, and a new build\n should be triggered.\n \"\"\"\n recovery_task = rktestyml.held_by\n assert(isinstance(recovery_task, JenkinsTask))\n old_uuid = recovery_task.uuid\n recovery_task.uuid = uuid4()\n recovery_task.cached_buildnum = None\n recovery_task.cached_job_url = None\n recovery_task.time_uuid_updated = datetime.now(utc)\n recovery_task.save()\n log.debug(\n ('Updated UUID of JenkinsTask %s holding RktestYml %s ' %\n (repr(recovery_task.sid), rktestyml.filename)) +\n ('from %s to %s' %\n (repr(old_uuid), repr(recovery_task.uuid))))\n self._build_recovery_job(rktestyml)\n\n def _end_cleanup(self, rktestyml):\n \"\"\"End the cleanup process.\n\n The RktestYml should be freed by disassociating its JenkinsTask from\n the held_by field.\n \"\"\"\n rktestyml.held_by = None\n rktestyml.save()\n log.debug('%s has been freed' % rktestyml.filename)\n\n def handle_cleanup(self, rktestyml):\n \"\"\"Handle cleanup of an RktestYml.\"\"\"\n if not isinstance(rktestyml, RktestYml):\n error_msg = 'Cannot handle cleanup for non-RktestYml %s' % \\\n repr(rktestyml)\n bodega_type_error(log, error_msg)\n\n self._set_jenkins_handle()\n if not isinstance(rktestyml.held_by, JenkinsTask):\n if not rktestyml.held_by_object_in_final_state:\n log.warning('%s is held by %s which is not currently in a '\n 'final state. Will not attempt recovery on this '\n 'Item.'\n % (rktestyml, rktestyml.held_by))\n return\n\n if rktestyml.state == Item.STATE_MAINTENANCE:\n log.debug('%s has state set to %s so will not attempt '\n 'recovery on this Item.'\n % (rktestyml, Item.STATE_MAINTENANCE))\n self._end_cleanup(rktestyml)\n else:\n log.debug('%s: Starting cleanup' % rktestyml)\n self._start_cleanup(rktestyml)\n else:\n time_elapsed = self._get_time_elapsed(rktestyml)\n uuid = rktestyml.held_by.uuid\n if RECOVERY_TIME_LIMIT < time_elapsed:\n log.debug('%s %s: Updating cleanup after timeout (%s > %s)' %\n (rktestyml, repr(uuid),\n self._get_timedelta_str(time_elapsed),\n self._get_timedelta_str(RECOVERY_TIME_LIMIT)))\n if rktestyml.state == Item.STATE_MAINTENANCE:\n log.info('%s timed out during recovery but freeing '\n 'the resource since its state is set to %s'\n % (rktestyml, Item.STATE_MAINTENANCE))\n self._end_cleanup(rktestyml)\n else:\n self._update_cleanup(rktestyml)\n return\n\n status = self.get_status(rktestyml)\n if status == self.STATUS_SUCCESS:\n log.debug('%s %s: Ending cleanup for build success' %\n (rktestyml, repr(uuid)))\n self._end_cleanup(rktestyml)\n elif status == self.STATUS_FAILURE:\n log.debug('%s %s: Updating cleanup for build failure' %\n (rktestyml, repr(uuid)))\n if rktestyml.state == Item.STATE_MAINTENANCE:\n log.info('%s failed recovery but freeing the resource '\n 'since its state is set to %s'\n % (rktestyml, Item.STATE_MAINTENANCE))\n self._end_cleanup(rktestyml)\n else:\n self._update_cleanup(rktestyml)\n else:\n log.debug('%s %s: ... has been waiting for %s (limit %s)' %\n (rktestyml, repr(uuid),\n self._get_timedelta_str(time_elapsed),\n self._get_timedelta_str(RECOVERY_TIME_LIMIT)))\n\n def taste_test(self, rktestyml, requirements):\n if rktestyml.platform != RktestYml.PLATFORM_DYNAPOD:\n return True\n\n ftp_util = FtpUtil(DYNAPOD_FTP_SERVER,\n DYNAPOD_FTP_USER,\n DYNAPOD_FTP_PASSWORD)\n file_path = 'Dynapod/%s/%s' % (rktestyml.filename.replace('.yml', ''),\n rktestyml.filename)\n if ftp_util.check_file(file_path):\n return True\n else:\n log.debug(\n 'Taste test failed for %s - rejecting.' % repr(rktestyml))\n return False\n\n def get_non_rare_requirements(self):\n \"\"\"Return a dictionary of requirements that filter out rare RktestYmls.\n\n These requirements allow for order fulfillment to serve non-rare\n RktestYmls whenever possible.\n \"\"\"\n return {'acropolis': False,\n 'encrypted': False,\n 'esx_6_0': False,\n 'hyperv_2016': False,\n 'linux_agent_all_versions': False,\n 'model_r6xx': False,\n 'robofm': False,\n 'robossd': False,\n 'tpm': False,\n 'vcenter_5_1': False,\n 'vcenter_6_5': False,\n 'vcloud_8_1': False,\n 'vcloud_8_2': False,\n 'vcloud_9_0': False,\n 'windows_app_test_only': False}\n\n def validate_item_requirements(self, item_requirements, user_sid,\n is_maintenance_order):\n \"\"\"Check if the given item requirements are valid for this Item.\"\"\"\n for field, value in item_requirements.items():\n filters = RktestYmlFilter.get_filters()\n if field not in filters:\n error_msg = ('\"%s\" is not a recognized requirement name for '\n 'the rktest_yml item type.'\n % field)\n bodega_validation_error(log, error_msg)\n\n rktest_ymls = RktestYmlFilter(item_requirements).qs\n if not rktest_ymls.count():\n error_msg = ('No Items in the (static) inventory of rktest_ymls '\n 'were able to fulfill the requirements of %s so the '\n 'order is likely unfulfillable.'\n % str(item_requirements))\n bodega_validation_error(log, error_msg)\n\n if settings.BLOCK_DYNAPODS_FROM_NON_JENKINS_USERS and \\\n user_sid not in getattr(settings, 'ACCEPTED_USERS_SIDS', []) and \\\n not is_maintenance_order:\n # If the BLOCK_DYNAPODS_FROM_NON_JENKINS_USERS toggle is enabled,\n # only Jenkins users will be able to order dynapods. This rejects\n # their Order POST request with an error message so users don't\n # wait endlessly in the queue.\n if 'platform' in item_requirements:\n platform = item_requirements['platform']\n elif 'filename' in item_requirements:\n yml = RktestYml.objects.get(\n filename=item_requirements['filename'])\n platform = yml.platform\n else:\n log.debug('No platform specified in item requirements. '\n 'Blocking this request to avoid giving dynapods.')\n platform = RktestYml.PLATFORM_DYNAPOD\n\n if platform == RktestYml.PLATFORM_DYNAPOD:\n error_msg = ('Ordering dynapods is currently blocked. Please '\n 'place an order for the DYNAPOD_ROBO platform or '\n 'use a CdmCluster.')\n bodega_validation_error(log, error_msg)\n","sub_path":"lab/bodega/bodega_legacy_items/item_managers.py","file_name":"item_managers.py","file_ext":"py","file_size_in_byte":28692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"560508044","text":"def main():\n i = getPositiveInt()\n print (\"{} is a positive integer\".format(i))\n return 0\n\ndef getPositiveInt():\n while True:\n print(\"n is\", end =\": \")\n n = input()\n n = int(n)\n if n >= 1:\n break\n return n\n\nif __name__ == \"__main__\":\n main()","sub_path":"temp/positive.py","file_name":"positive.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"13114598","text":"from heapq import heappop, heappush\nimport time\n\n\nclass Employee:\n def __init__(self, id, rank):\n self.id = id\n self.rank = rank\n self.on_call = False\n self.current_call = None\n\n def take_call(self, Call):\n Call.assign_handler(self)\n self.on_call = True\n self.current_call = Call\n time.sleep(2)\n self.finish_call()\n\n\n def finish_call(self):\n call = self.current_call\n call.resolve()\n print(\"Employee\", self.rank, \"finishing call\", call.id)\n self.on_call = False\n self.current_call = None\n\n\nclass Call:\n def __init__(self, difficulty, id):\n self.id = id\n self.difficulty = difficulty\n self.resolved = False\n self.handler = None\n print(\"Call: d\", self.difficulty, \"id\", self.id, \"made\")\n\n def resolve(self):\n self.resolved = True\n\n def assign_handler(self, Employee):\n self.handler = Employee\n\nclass CallHandler:\n\n def __init__(self, r, m, d):\n self.respondents = [Employee(x, 1) for x in range(r)]\n self.managers = [Employee(x, 2) for x in range(m)]\n self.directors = [Employee(x, 3) for x in range(d)]\n self.call_queue = []\n\n def add_call(self, Call):\n heappush(self.call_queue, (Call.id, Call))\n\n def assign_call(self):\n id, call = heappop(self.call_queue)\n\n while len(self.call_queue) > 0:\n for r in self.respondents:\n if r.on_call == False and r.rank < call.difficulty:\n r.take_call(call)\n break\n\n for m in self.managers:\n if call.handler != None:\n break\n if m.on_call == False and m.rank < call.difficulty:\n m.take_call(call)\n break\n\n for d in self.directors:\n if call.handler != None:\n break\n if d.on_call == False:\n d.take_call(Call)\n break\n if call.handler == None:\n heappush(self.call_queue, (call.id, call))\n\n\ndef main():\n ch = CallHandler(1,1,1)\n calls = [Call(1,0), Call(1,1), Call(1, 6), Call(0,3), Call(0,2)]\n while len(calls) > 0:\n ch.add_call(calls.pop(0))\n\n for id, c in ch.call_queue:\n print(c.difficulty)\n\n ch.assign_call()\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"Chapter 7/7.2.py","file_name":"7.2.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"102598136","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Created by HazzaCheng on 2020-11-08\n\nimport unittest\n\nfrom src.segment_tree.No307_Range_Sum_Query_Mutable import NumArray\n\n\nclass MyTestCase(unittest.TestCase):\n def setUp(self) -> None:\n self.solution = None\n\n def test(self):\n nums = [1, 3, 5]\n\n self.solution = NumArray(nums)\n self.assertEqual(9, self.solution.sumRange(0, 2))\n self.solution.update(1, 2)\n self.assertEqual(8, self.solution.sumRange(0, 2))\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"python/test/segment_tree/test_no307.py","file_name":"test_no307.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"504470420","text":"\"\"\"create table\n\nRevision ID: aa5da22f086f\nRevises: \nCreate Date: 2019-07-17 00:23:30.710853\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'aa5da22f086f'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('log_man',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('level', sa.Integer(), nullable=True, comment='5开头为错误, 1开头为操作日志, 0结尾为默认值'),\n sa.Column('createTime', sa.DateTime(), nullable=True),\n sa.Column('message', sa.Text(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('tenant',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('qq', sa.BigInteger(), nullable=False, comment='普通int长度不够'),\n sa.Column('status', sa.Integer(), nullable=True, comment=\"下标映射:('招室友', '求带走', '中介', '转租', '房东')\"),\n sa.Column('nickname', sa.String(length=120), nullable=True, comment='qq昵称'),\n sa.Column('sex', sa.Integer(), nullable=True, comment=\"下标映射:('男', '女', '保密')\"),\n sa.Column('age', sa.Integer(), nullable=True, comment='0既保密'),\n sa.Column('exp_sex', sa.Integer(), nullable=True, comment=\"期望室友性别 ,下标映射:('招室友', '求带走', '中介', '转租', '房东')\"),\n sa.Column('rent_a', sa.Integer(), nullable=True, comment='价格区间a~b使用view model处理 1千-3千 '),\n sa.Column('rent_b', sa.Integer(), nullable=True, comment='价格区间a~b使用view model处理 或只有b,b=0为不限 '),\n sa.Column('address', sa.String(length=256), nullable=True, comment='地址相关'),\n sa.Column('detailed', sa.Text(length=3000), nullable=True, comment='详情'),\n sa.Column('updateTime', sa.DateTime(), nullable=True),\n sa.Column('is_show', sa.Boolean(), nullable=True, comment='是否在网页上显示'),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('qq')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('tenant')\n op.drop_table('log_man')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/aa5da22f086f_create_table.py","file_name":"aa5da22f086f_create_table.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"64902050","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# \n# 40924\n# Praha\n# Praha\n# 2008-01-01\n# 9999-09-09\n# \n# \n# CZ0100\n# CZ0100\n# 31\n# 3100\n# \n# \n\nimport xml.etree.ElementTree as ET\nimport json\n\ndef czso_kraje_ciselnik():\n\n\ttree = ET.parse('data/CIS0100_CS.xml')\n\troot = tree.getroot()\n\n\tciselnik = {}\n\n\tfor data in root.iter('DATA'):\n\t\tfor polozka in data.iter('POLOZKA'):\n\t\t\tprint(polozka)\n\t\t\tprint(polozka.find('CHODNOTA').text)\n\t\t\tprint(polozka.find('TEXT').text)\n\n\t\t\tatributy = polozka.find('ATRIBUTY')\n\t\t\tfor atr in atributy.iter('ATR'):\n\t\t\t\tif atr.attrib['akronym'] == 'CZNUTS':\n\t\t\t\t\tciselnik[polozka.find('CHODNOTA').text] = {\n\t\t\t\t\t\t'name': polozka.find('TEXT').text,\n\t\t\t\t\t\t'cznuts': atr.text\n\t\t\t\t\t}\n\n\tjson.dump(ciselnik, open('13/czso-kraje-ciselnik.json', 'w'))\n\ndef czso_okresy_ciselnik():\n\ttree = ET.parse('data/CIS0101_CS.xml')\n\troot = tree.getroot()\n\n\tciselnik = {}\n\n\tfor data in root.iter('DATA'):\n\t\tfor polozka in data.iter('POLOZKA'):\n\t\t\tprint(polozka)\n\t\t\tprint(polozka.find('CHODNOTA').text)\n\t\t\tprint(polozka.find('TEXT').text)\n\n\t\t\tatributy = polozka.find('ATRIBUTY')\n\t\t\tfor atr in atributy.iter('ATR'):\n\t\t\t\tif atr.attrib['akronym'] == 'CZNUTS':\n\t\t\t\t\tciselnik[polozka.find('CHODNOTA').text] = {\n\t\t\t\t\t\t'name': polozka.find('TEXT').text,\n\t\t\t\t\t\t'cznuts': atr.text\n\t\t\t\t\t}\n\n\tprint(ciselnik)\n\tjson.dump(ciselnik, open('13/czso-okresy-ciselnik.json', 'w'))\n\n\n\nczso_kraje_ciselnik()\nczso_okresy_ciselnik()\n","sub_path":"scripty/ciselnik.py","file_name":"ciselnik.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"358982280","text":"import nltk\nfrom split_into_blurbs import split_into_blurbs\nfrom bullet_detection import find_bullet_char_from_text_objects, bullet_indices_from_text_objects\n\ndef full_lines_from_text_objects(text_objects):\n bullet_char = find_bullet_char_from_text_objects(text_objects)\n indices = bullet_indices_from_text_objects(bullet_char, text_objects)\n blurbs = split_into_blurbs(text_objects, indices)\n full_lines = make_full_lines(bullet_char, blurbs)\n return full_lines\n\ndef make_full_lines(bullet_char, blurbs):\n english_vocab = set(w.lower() for w in nltk.corpus.words.words())\n final_lines = {}\n # Disqualify first blurb for now:\n for idx, blurb in enumerate(blurbs[1:]):\n final_lines[idx] = {}\n # final_lines[idx]['blurb'] = blurb.get_text()\n\n leader = blurb[0]\n final_lines[idx]['leader'] = leader.get_text()\n final_lines[idx]['leader_bbox'] = leader.bbox\n\n followers = []\n final_lines[idx]['rejects'] = {}\n final_lines[idx]['followers'] = []\n for f_idx, follower in enumerate(blurb[1:]):\n # Throw out blurbs that are misaligned on left margin\n clean_leader = is_bullet_at_start(bullet_char, leader)\n threshold = 1.5 if clean_leader else 2.0\n exceeding_x0 = leader.bbox[0] * threshold\n if follower.bbox[0] > exceeding_x0:\n final_lines[idx]['rejects'][f_idx] = {}\n final_lines[idx]['rejects'][f_idx]['bbox'] = follower.bbox\n final_lines[idx]['rejects'][f_idx]['follower'] = follower.get_text()\n final_lines[idx]['rejects'][f_idx]['reason'] = 'exceeded'\n continue\n\n # Throw out newlines and empty space\n empty = is_newline_or_whitespace(follower)\n if empty:\n final_lines[idx]['rejects'][f_idx] = {}\n final_lines[idx]['rejects'][f_idx]['follower'] = follower.get_text()\n final_lines[idx]['rejects'][f_idx]['reason'] = 'empty'\n continue\n\n # Add it if the blurb is english\n english = is_english(english_vocab, follower)\n final_lines[idx]['followers'].append(follower.get_text())\n followers.append(follower)\n\n trimmed_leader = trim_leader(bullet_char, leader)\n text_followers = complete_followers(followers)\n final_line = trimmed_leader + text_followers\n final_lines[idx]['final_line'] = final_line\n return final_lines\n\ndef complete_followers(followers):\n if len(followers) == 0: return ''\n final_line = ' '\n for line in followers:\n text = line.get_text()\n final_line += text\n return final_line\n\ndef trim_leader(bullet_char, blurb):\n text = blurb.get_text()\n words = text.split()\n index_after_bullet = words.index(bullet_char) + 1\n return ' '.join(words[index_after_bullet:])\n\ndef is_english(vocab, blurb):\n text = blurb.get_text()\n words = text.split()\n for word in words:\n if word in vocab: return True\n\ndef is_newline_or_whitespace(blurb):\n text = blurb.get_text()\n words = text.split()\n if len(words) == 0: return True\n else: return False\n\ndef is_bullet_at_start(bullet_char, blurb):\n text = blurb.get_text()\n words = text.split()\n if words.index(bullet_char) == 0:\n return True\n else:\n return False\n","sub_path":"full_lines_from_text_objects.py","file_name":"full_lines_from_text_objects.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"26621706","text":"'''Exercício Python 033: Faça um programa que leia três números e mostre qual é o maior e qual é o menor'''\n\nfrom time import sleep\nn1 = int(input('Digite o 1º Numero: '))\nn2 = int(input('Digite o 2º Numero: '))\nn3 = int(input('Digite o 3º Numero: '))\nprint('\\033[34m'+'$*$' * 15)\nprint('\\033[35m'+'PROCESSANDO.....Tem BOBO me OLHANDOOOOO.....')\nsleep(3)\nmenor = n1\nmaior = n1\n#Verificando o MENOR\nif n2 < n1 and n2 < n3:\n menor = n2\nif n3 < n1 and n3 < n1:\n menor = n3\n#verificando o MAIOR\nif n2 > n1 and n2 > n3:\n maior = n2\nif n3 > n1 and n3 > n2:\n maior = n3\nprint('Os Numeros Digitados foram 1º Numero: {0} 2º Numero: {1} 3º Numero: {2}'.format(n1, n2, n3))\nprint('$*$' * 15)\nprint('\\033[4;32m'+'O menor numero é: {}'.format(menor))\nprint('\\033[4;33m'+'O maior numero é: {}'.format(maior))\nprint('-*-' * 15)\n\n","sub_path":"curso_em_video/Exercicios_Python/Desafio_33_IF_escolha_maior_ou_menor.py","file_name":"Desafio_33_IF_escolha_maior_ou_menor.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"588323392","text":"from django.template import Context, RequestContext\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth.models import User\nfrom django import forms\nfrom S2.authoring.models import ArticleForm,Article\n\ndef new_article(request):\n if request.method == 'POST' and request.user.is_authenticated:\n form = ArticleForm(request.POST)\n form.save()\n return render_to_response('reading/reading_base.html', {'form': form}, context_instance=RequestContext(request))\n else:\n form = ArticleForm() \n return render_to_response('authoring/authoring_base.html', {'form': form, 'msg': \"You can create a new article here.\"}, context_instance=RequestContext(request))\n\ndef edit_article(request,article_id):\n if request.method == 'POST' and request.user.is_authenticated:\n posts=request.POST.copy()\n updated_art=Article.objects.get(pk=article_id)\n updated_art.title=posts.get('title', None)\n updated_art.body=posts.get('body', None)\n updated_art.synop=posts.get('synop', None)\n updated_art.save()\n return HttpResponseRedirect(reverse('S2.reading.views.read', args=(article_id,)))\n else:\n article = Article.objects.get(pk=article_id)\n form = ArticleForm(instance=article) \n return render_to_response('authoring/authoring_base.html', {'form': form, 'msg': \"You can edit this article.\"}, context_instance=RequestContext(request))\n\n\n","sub_path":"authoring/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"622004480","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 14 15:46:51 2019\n\n@author: roman\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nfrom datetime import datetime\nimport scipy.optimize\n\n#from Plot import fit\nfrom Model import dampedOscillation\n\ndef fit(t0, T0, model, p = [4, 9, 40, 2*np.pi/50, 28]):\n \n #Estimate fit \n try:\n fitparam, _ = scipy.optimize.curve_fit(model, t0, T0, p)\n \n except:\n fitparam = np.array([0, 0, 1, 0, 25.5])\n \n if len(fitparam) == 5:\n #fitparam[0] = 2; fitparam[1] = 2; fitparam[2] = 500; fitparam[3] = 2*np.pi/43; fitparam[4] = 28.5\n fitFunction = lambda t: model(t, fitparam[0], fitparam[1], fitparam[2], fitparam[3], fitparam[4])\n print('Our fit parameters are [A, phi, tau, omega, C] =', fitparam)\n \n if len(fitparam) == 3:\n fitFunction = lambda t: model(t, fitparam[0], fitparam[1], fitparam[2])\n print('Our fit parameters are [A, tau, C] =', fitparam)\n \n if len(fitparam) == 4:\n fitFunction = lambda t: model(t, fitparam[0], fitparam[1], fitparam[2], fitparam[3])\n print('Our fit parameters are [A, B, tau, C] =', fitparam)\n\n #Calculate fit values\n fitT = fitFunction(t0)\n \n return fitT, fitparam\n \n\n\n#Read the data for time in seo\ndef Read(counter = 2000):\n \n storeData = []\n #plt.ion()\n \n while counter > 0:\n data = arduino.readline().decode('utf-8')[:-2] \n if data:\n data = data.split(';')\n print(data)\n storeData.append(data)\n \n data = np.array(data, dtype = float)\n \n #plt.clf()\n #plt.scatter(data[:,0], data[:,1])\n #plt.pause(0.05)\n #plt.draw()\n \n counter -= 1\n \n #Save the data to file\n now = datetime.now().strftime('%H-%M_%d-%m')\n filename = 'Measurement' + now + \".p\"\n pickle.dump(storeData, open(filename, \"wb\"))\n \n return filename\n\n\ndef PlotTemperature(filename, size = 20):\n \n #Get the data back from file\n Data = pickle.load( open(filename, \"rb\" ) )\n \n #Zeit\n time = np.array(Data, dtype = float)[:,0]/1000\n \n #Temperatur\n temperature = np.array(Data, dtype = float)[:,1]\n \n #Plot values\n plt.figure(figsize = (12,8))\n \n #Plot thresholds\n above = np.ones_like(time) * 30\n below = np.ones_like(time) * 27\n plt.plot(time, above, '-', color = \"red\")\n plt.plot(time, below, '-', color = \"blue\")\n \n plt.plot(time, temperature,'.k', label = 'Temperature')\n \n #Damped oscillation fit\n temperature_fit, param = fit(time, temperature, model = dampedOscillation, \n p = [2, 2, 500, 2*np.pi/43, 28.5])\n print(\"The estimated parameters are: \", param)\n plt.plot(time, temperature_fit, '-', label = 'Damped oscillation fit')\n \n \n plt.xlabel('Time [s]', fontsize = size)\n plt.ylabel(r'Temperature [$^\\circ$C]', fontsize = size)\n\n \n #Set tick fontsize\n plt.xticks(fontsize = size)\n plt.yticks(fontsize = size)\n plt.legend(fontsize=\"xx-large\")\n \n \n plt.savefig('Plots/TwoPointPlot.pdf')\n plt.show()\n \n \ndef PlotTemperatureVsRPM(filename):\n #Get the data back from file\n Data = pickle.load( open(filename, \"rb\" ) )\n \n #Fan speed\n speed = np.array(Data, dtype = float)[:,3]\n \n #Temperatur\n temperature = np.array(Data, dtype = float)[:,1]\n #print(temperature)\n \n plt.figure(figsize = (12,8))\n plt.plot(speed, temperature,'x', label = 'Temperature')\n plt.xlabel('Rounds per minute')\n plt.ylabel(r'Temperature [C]')\n plt.savefig(filename.split('.')[0] + 'RPM.PNG')\n plt.show()\n \n \ndef PlotVentilator(filename):\n #Get the data back from file\n Data = pickle.load( open(filename, \"rb\" ) )\n \n #Fan speed\n speed = np.array(Data, dtype = float)[:,3]\n \n #Fan setting in %\n setting = (np.array(Data, dtype = float)[:,2]+4)*5/2.55\n #print(temperature)\n \n plt.figure(figsize = (12,8))\n plt.plot(setting, speed,'x', label = 'Temperature')\n plt.xlabel('Fan setting in %')\n plt.ylabel(r'Rounds per minute')\n plt.savefig(filename.split('.')[0] + 'Setting.PNG')\n plt.show()\n \n\ndef EstimateB(Data):\n\n Data = np.array(Data, dtype = float)\n \n time = np.linspace(0, 1000/60, 1000) #Zeit der Messung\n\n R = Data[:,2] #Resistance\n logR_R0 = np.log(R/1e5) \n \n \n T = Data[:,1] #Temperature\n T_1 = 1/(T + 273.15)\n \n plt.figure(figsize = (12,8))\n plt.plot(time, T, 'x', label = 'Temperatur')\n plt.show()\n \n \n plt.figure(figsize = (12,8))\n plt.plot(time, R, 'x',label = 'Widerstand')\n plt.show()\n \n \n plt.plot(logR_R0, T_1, 'x',label = '12')\n \n param = np.polyfit(logR_R0, T_1, deg = 1)\n \n fit = logR_R0 * param[0] + param[1]\n \n plt.plot(logR_R0, fit, 'x',label = '12')\n \n\n#Plot the temperature \n#PlotTemperature('Measurement_1_FirstHeating.p')\nPlotTemperature('Data/Measurement_2_FirstOscillation.p')\n#PlotTemperature('Measurement_3_SecondHeating.p')\n\n#PlotTemperature('Measurement_5_Stepwise.p')\n#PlotTemperatureVsRPM('Measurement_5_Stepwise.p')\n#PlotTemperature('Measurement_4_FanStepwise.p')\n#PlotTemperatureVsRPM('Measurement_4_FanStepwise.p')\n#PlotVentilator('Measurement_5_Stepwise.p')\n","sub_path":"TwoPoint/Temperature.py","file_name":"Temperature.py","file_ext":"py","file_size_in_byte":5371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"638042493","text":"from .common import *\n\nfrom av.video.frame import VideoFrame\nfrom av.filter import Graph, Filter\n\n\nclass TestFilters(TestCase):\n\n def test_filter_descriptor(self):\n\n f = Filter('testsrc')\n self.assertEqual(f.name, 'testsrc')\n self.assertEqual(f.description, 'Generate test pattern.')\n self.assertFalse(f.dynamic_inputs)\n self.assertEqual(len(f.inputs), 0)\n self.assertFalse(f.dynamic_outputs)\n self.assertEqual(len(f.outputs), 1)\n self.assertEqual(f.outputs[0].name, 'default')\n self.assertEqual(f.outputs[0].type, 'video')\n\n def test_dynamic_filter_descriptor(self):\n\n f = Filter('split')\n self.assertFalse(f.dynamic_inputs)\n self.assertEqual(len(f.inputs), 1)\n self.assertTrue(f.dynamic_outputs)\n self.assertEqual(len(f.outputs), 0)\n\n def test_generator_graph(self):\n\n graph = Graph()\n src = graph.add('testsrc')\n lutrgb = graph.add('lutrgb', \"r=maxval+minval-val:g=maxval+minval-val:b=maxval+minval-val\", name='invert')\n sink = graph.add('buffersink')\n src.link_to(lutrgb)\n lutrgb.link_to(sink)\n\n # pads and links\n self.assertIs(src.outputs[0].link.output, lutrgb.inputs[0])\n self.assertIs(lutrgb.inputs[0].link.input, src.outputs[0])\n\n frame = sink.pull()\n self.assertIsInstance(frame, VideoFrame)\n\n if Image:\n frame.to_image().save(self.sandboxed('mandelbrot2.png'))\n\n def test_auto_find_sink(self):\n\n graph = Graph()\n src = graph.add('testsrc')\n src.link_to(graph.add('buffersink'))\n graph.configure()\n\n frame = graph.pull()\n\n if Image:\n frame.to_image().save(self.sandboxed('mandelbrot3.png'))\n\n def test_delegate_sink(self):\n\n graph = Graph()\n src = graph.add('testsrc')\n src.link_to(graph.add('buffersink'))\n graph.configure()\n\n print(src.outputs)\n\n frame = src.pull()\n\n if Image:\n frame.to_image().save(self.sandboxed('mandelbrot4.png'))\n\n def test_haldclut_graph(self):\n\n raise SkipTest()\n\n graph = Graph()\n\n img = Image.open(fate_suite('png1/lena-rgb24.png'))\n frame = VideoFrame.from_image(img)\n img_source = graph.add_buffer(frame)\n\n hald_img = Image.open('hald_7.png')\n hald_frame = VideoFrame.from_image(hald_img)\n hald_source = graph.add_buffer(hald_frame)\n\n try:\n hald_filter = graph.add('haldclut')\n except ValueError:\n # Not in Libav.\n raise SkipTest()\n\n sink = graph.add('buffersink')\n\n img_source.link(0, hald_filter, 0)\n hald_source.link(0, hald_filter, 1)\n hald_filter.link(0, sink, 0)\n graph.config()\n\n self.assertIs(img_source.outputs[0].linked_to, hald_filter.inputs[0])\n self.assertIs(hald_source.outputs[0].linked_to, hald_filter.inputs[1])\n self.assertIs(hald_filter.outputs[0].linked_to, sink.inputs[0])\n\n hald_source.push(hald_frame)\n\n img_source.push(frame)\n\n frame = sink.pull()\n self.assertIsInstance(frame, VideoFrame)\n frame.to_image().save(self.sandboxed('filtered.png'))\n","sub_path":"tests/test_filters.py","file_name":"test_filters.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"571953152","text":"from Domain.cheltuieli import creeaza_cheltuiala, get_str, get_nr_ap, get_suma, get_data, get_tipul, get_id\nfrom Logic.adunarea_unei_valori import adunare_valoare_for_data\nfrom Logic.sume_lunare import get_sume_lunare\nfrom Logic.cea_mai_mare_cheltuiala import find_out_biggest_cheltuiala_for_tip\nfrom Logic.ordonare_descrescatoare import ordonare\nfrom Logic.sterge_cheltuieli import sterge_pt_nr_ap\nfrom Logic.undo_and_redo import do_undo, do_redo\nfrom Logic.crud import adaugare, read, modif, stergere\n\n\ndef show_menu():\n print('1.CRUD')\n print('2.Stergerea tuturor cheltuielilor pentru un apartament dat')\n print('3.Adunarea unei valori la toate cheltuielile dintr-o dată citită.')\n print('4.Determinarea celei mai mari cheltuieli pentru fiecare tip de cheltuială.')\n print('5.Ordonarea cheltuielilor descrescător după sumă.')\n print('6.Afișarea sumelor lunare pentru fiecare apartament.')\n print('u.Undo')\n print('r.Redo')\n print('x.Oprire')\n\n\ndef handle_add(lst_cheltuieli, undo_list, redo_list):\n try:\n id_ap = int(input('Introduceti id-ul cheltuielii aici: ')) #nu are rost sa faci functie de test, id ul DEJA trebuie introdus de tip int\n nr_ap = int(input('Introduceti numarul apartamentului aici: '))\n suma = int(input('Introduceti suma cheltuielii aici: '))\n data = input('Introduceti data in care s - a emis cheltuiala in format DD.MM.YYYY aici: ')\n tip = input('Introduceti tipul cheltuielii aici: ')\n new_cheltuiala = creeaza_cheltuiala(id_ap, nr_ap, suma, data, tip)\n lst_cheltuieli = adaugare(lst_cheltuieli,id_ap, nr_ap, suma, data, tip, undo_list, redo_list)\n except ValueError as ve:\n print('Eroare:', ve)\n return lst_cheltuieli\n\ndef handle_show_all(lst_cheltuieli):\n for cheltuiala in lst_cheltuieli:\n print(get_str(cheltuiala))\n\n\ndef handle_show_details(lst_cheltuieli):\n try:\n id_ap = int(input('Introduceti aici Numarul cheltuielii despre care vrem sa aflam detalii: '))\n cheltuiala = read(lst_cheltuieli, id_ap)\n if cheltuiala == None:\n print('Nu ati introdus un id existent, deci consideram prima cheltuiala!')\n cheltuiala = lst_cheltuieli[0]\n print(f'Id-ul cheltuielii:{get_id(cheltuiala)}')\n print(f'Nr_apartament:{get_nr_ap(cheltuiala)}')\n print(f'Suma:{get_suma(cheltuiala)}')\n print(f'Data:{get_data(cheltuiala)}')\n print(f'Tip:{get_tipul(cheltuiala)}')\n except ValueError as ve:\n print('Eroare: ', ve)\n\ndef handle_modif(lst_cheltuieli, undo_list, redo_list):\n try:\n id_ap = int(input('Introduceti id-ul cheltuielii care doriti sa se modifice: '))\n nr_ap = int(input('Dati numarul apartamentului al cheltuielii care se actualizeaza: '))\n suma = int(input('Dati aici noua suma a cheltuielii: '))\n data = input('Dati aici noua data a cheltuielii: ')\n tip = input('Dati aici noul tip al cheltuielii: ')\n new_cheltuiala = creeaza_cheltuiala(id_ap, nr_ap, suma, data, tip)\n lst_cheltuieli = modif(lst_cheltuieli, new_cheltuiala, undo_list, redo_list)\n except ValueError as ve:\n print('Eroare:', ve)\n return lst_cheltuieli\n\ndef handle_delete(lst_cheltuieli, undo_list, redo_list):\n try:\n id = int(input('Dati aici id-ul cheltuielii care doriti sa se stearga: '))\n lst_cheltuieli = stergere(lst_cheltuieli, id, undo_list, redo_list)\n except ValueError as ve:\n print('Eroare:', ve)\n else:\n print(\"S-a sters cu succes cheltuiala!\")\n return lst_cheltuieli\n\ndef handle_crud(lst_cheltuieli, undo_list, redo_list):\n while True:\n print('1.Creeaza')\n print('2.Modifica')\n print('3.Sterge')\n print('a.Afiseaza_cheltuieli')\n print('d.Afiseaza_detalii_cheltuiela')\n print('b.Revenire')\n optiune = input('Introduceti optiunea dorita aici: ')\n if optiune == '1':\n lst_cheltuieli = handle_add(lst_cheltuieli, undo_list, redo_list)\n elif optiune == '2':\n lst_cheltuieli = handle_modif(lst_cheltuieli, undo_list, redo_list)\n elif optiune == '3':\n lst_cheltuieli = handle_delete(lst_cheltuieli, undo_list, redo_list)\n elif optiune == 'a':\n handle_show_all(lst_cheltuieli)\n elif optiune == 'd':\n handle_show_details(lst_cheltuieli)\n elif optiune == 'b':\n break\n else:\n print('Optiune invalida')\n return lst_cheltuieli\n\n\ndef handle_delete_for_nr_ap(lst_cheltuieli, undo_list, redo_list):\n try:\n nr_ap = int(input('Introduceti numarul apartamentului aici: '))\n lst_cheltuieli = sterge_pt_nr_ap(lst_cheltuieli, nr_ap, undo_list, redo_list)\n except ValueError as ve:\n print('Eroare:', ve)\n else:\n print(f'S-au sters cu succes cheltuielile ce aveau numarul apartamentului {nr_ap}')\n return lst_cheltuieli\n\n\ndef handle_add_for_data(lst_cheltuieli, undo_list, redo_list):\n try:\n data = input('Introduceti o data aici pentru care cautam cheltuieli aici: ')\n val = int(input('Introduceti valoarea cu care se modifica cheltuielile aici: '))\n lst_cheltuieli = adunare_valoare_for_data(lst_cheltuieli, data, val, undo_list, redo_list)\n except ValueError as ve:\n print('Eroare:', ve)\n else:\n print('Valorile s au adaugat cu succes!')\n return lst_cheltuieli\n\n\ndef handle_show_biggest_sum_for_each_type(lst_cheltuieli):\n result = find_out_biggest_cheltuiala_for_tip(lst_cheltuieli)\n for tip in result:\n print(f'Pentru tipul: {tip} avem cheltuiala: {get_str(result[tip])}')\n\n\ndef handle_sort_reverse(lst_cheltuieli, undo_list, redo_list):\n lst_cheltuieli = ordonare(lst_cheltuieli, undo_list, redo_list)\n print('Ordonarea s a facut cu succes! ')\n return lst_cheltuieli\n\n\ndef handle_show_sums_for_each_month(lst_cheltuieli):\n result = get_sume_lunare(lst_cheltuieli)\n for luna in result:\n print(f'Pentru Luna {luna} avem lista de sume: {result[luna]}')\n\n\ndef handle_undo(lst_cheltuieli, undo_list, redo_list):\n undo_result = do_undo(undo_list, redo_list, lst_cheltuieli)\n if undo_result is not None:\n return undo_result\n return lst_cheltuieli\n\n\ndef handle_redo(lst_cheltuieli, undo_list, redo_list):\n redo_result = do_redo(undo_list, redo_list, lst_cheltuieli)\n if redo_result is not None:\n return redo_result\n return lst_cheltuieli\n\ndef run_ui(lst_cheltuieli, undo_list, redo_list):\n while True:\n show_menu()\n optiune = input('Introduceti optiunea dorita aici: ')\n if optiune == '1':\n lst_cheltuieli = handle_crud(lst_cheltuieli, undo_list, redo_list)\n elif optiune == '2':\n lst_cheltuieli = handle_delete_for_nr_ap(lst_cheltuieli, undo_list, redo_list)\n elif optiune == '3':\n lst_cheltuieli = handle_add_for_data(lst_cheltuieli, undo_list, redo_list)\n elif optiune == '4':\n handle_show_biggest_sum_for_each_type(lst_cheltuieli)\n elif optiune == '5':\n lst_cheltuieli = handle_sort_reverse(lst_cheltuieli, undo_list, redo_list)\n handle_show_all(lst_cheltuieli)\n elif optiune == '6':\n handle_show_sums_for_each_month(lst_cheltuieli)\n elif optiune == 'u':\n lst_cheltuieli = handle_undo(lst_cheltuieli, undo_list, redo_list)\n elif optiune == 'r':\n lst_cheltuieli = handle_redo(lst_cheltuieli, undo_list, redo_list)\n elif optiune == 'x':\n break\n else:\n print('Optiune invalida')\n return lst_cheltuieli","sub_path":"User_interface/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":7634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"363259927","text":"'''\n rauth.test_hook\n ---------------\n\n Test suite for rauth.hook.\n'''\n\nimport unittest\n\nfrom mock import Mock\nfrom requests import Request\n\n\nclass RauthTestCase(unittest.TestCase):\n def setUp(self):\n # mock request object\n request = Request()\n request.method = 'GET'\n request.url = 'http://example.com/'\n request.headers = {}\n request.params = {}\n request.data = {}\n request.params_and_data = {}\n self.request = request\n\n # mock response object\n response = Mock()\n response.content = 'access_token=321'\n response.headers = {'content-type': 'text/html; charset=UTF-8'}\n response.ok = True\n response.status_code = 200\n response.raise_for_status = lambda: None\n self.response = response\n\n # mock raise_for_status with an error\n def raise_for_status():\n raise Exception('Response not OK!')\n\n self.raise_for_status = raise_for_status\n\n # mock consumer object\n consumer = Mock()\n consumer.key = '123'\n consumer.secret = '456'\n self.consumer = consumer\n\n # mock token object\n token = Mock()\n token.key = '321'\n token.secret = '456'\n self.token = token\n","sub_path":"tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"156901200","text":"_start = \"On the {0} day of Christmas my true love gave to me, \"\n_details = [\"a Partridge in a Pear Tree.\\n\",\n \"two Turtle Doves, \",\n \"three French Hens, \",\n \"four Calling Birds, \",\n \"five Gold Rings, \",\n \"six Geese-a-Laying, \",\n \"seven Swans-a-Swimming, \",\n \"eight Maids-a-Milking, \",\n \"nine Ladies Dancing, \",\n \"ten Lords-a-Leaping, \",\n \"eleven Pipers Piping, \",\n \"twelve Drummers Drumming, \"]\n_days = [\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\",\n \"seventh\", \"eighth\", \"ninth\", \"tenth\", \"eleventh\", \"twelfth\"]\n\n\ndef verse(n):\n if not (1 <= n <= 12):\n raise(IndexError)\n n -= 1\n ret = _start.format(_days[n])\n ret += ''.join(_details[x] for x in range(n, 0, -1))\n ret += \"and \" if n else \"\"\n ret += _details[0]\n return ret\n\n\ndef verses(a, b):\n return ''.join(verse(n) + '\\n' for n in range(a, b + 1))\n\n\ndef sing():\n return verses(1, 12)\n","sub_path":"python/twelve-days/twelve_days.py","file_name":"twelve_days.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"413753843","text":"import cv2\n\ncam=cv2.VideoCapture(0)#start video capture\n\nj=0\nwhile True:\n\n x,frame=cam.read()\n fip=cv2.flip(frame,1)\n j+=1\n\n if(j%2==0):\n cv2.imshow('Frame',fip)\n else:\n cv2.imshow('Frame',frame)\n\n if cv2.waitKey(2000) &0xFF==ord('a'):\n break\n","sub_path":"Session-1/Horizontal_flip.py","file_name":"Horizontal_flip.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"264320952","text":"from settings import settings\n\nfrom office365.runtime.auth.authentication_context import AuthenticationContext\nfrom office365.sharepoint.client_context import ClientContext\n\nurl = 'https://mediadev8.sharepoint.com/NewsArchive'\n\nif __name__ == '__main__':\n context_auth = AuthenticationContext(url=url)\n if context_auth.acquire_token_for_app(client_id=settings['client_credentials']['client_id'],\n client_secret=settings['client_credentials']['client_secret']):\n ctx = ClientContext(url, context_auth)\n web = ctx.web\n ctx.load(web)\n ctx.execute_query()\n print(\"Web title: {0}\".format(web.properties['Title']))\n\n else:\n print(context_auth.get_last_error())\n","sub_path":"examples/sharepoint/sharepoint_app_token_auth.py","file_name":"sharepoint_app_token_auth.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"221563128","text":"import time\n\nfrom appium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\n\ndesired_cap = dict()\n\n# 平台名字\ndesired_cap[\"platformName\"] = 'android'\n\n# 平台版本\ndesired_cap[\"platformVersion\"] = '5.1'\n\n# 设备名字\ndesired_cap[\"deviceName\"] = '1'\n\n# 要打开的应用程序\ndesired_cap[\"appPackage\"] = 'com.android.settings'\n\n# 要打开的界面\ndesired_cap[\"appActivity\"] = '.Settings'\n# 创建驱动对象\ndriver = webdriver.Remote(\"http://localhost:4723/wd/hub\", desired_cap)\n\ndriver.implicitly_wait(10)\n\n# # 找到搜索放大镜并点击\n# driver.find_element_by_id(\"com.android.settings:id/search\").click()\n#\n# # 找到输入框并输入文本\n# driver.find_element_by_class_name(\"android.widget.EditText\").send_keys(\"hello\")\n#\n# # 点击后退\n# driver.find_element_by_xpath(\"//*[@content-desc='收起']\").click()\n# WebDriverWait(driver, 30, poll_frequency=3).until(lambda x: x.find_element_by_xpath(\"//*[contains(@text, '设')]\"))\ntexts = driver.find_elements_by_xpath(\"//*[contains(@text,'设')]\")\nprint(len(texts))\nfor text in texts:\n print(text.text)\n\ntime.sleep(5)\n\ndriver.quit()\n","sub_path":"auto_app_test/day2/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"131533720","text":"import media\nimport fresh_tomatoes\n\n\n# Exemplos de filmes\ntoy_story = media.Movie(\"Toy Story\",\n \"1h 17min\",\n \"A cowboy doll is profoundly threatened and jealous\"\n \" when a new spaceman figure supplants him as top\"\n \" toy in a boy's room.\",\n \"https://m.media-amazon.com/images/M/MV5BMDU2ZWJlM\"\n \"jktMTRhMy00ZTA5LWEzNDgtYmNmZTEwZTViZWJkXkEyXkFqc\"\n \"GdeQXVyNDQ2OTk4MzI@._V1_UX182_CR0,0,182,268_AL_.jpg\",\n \"https://www.youtube.com/watch?v=rNk1Wi8SvNc\")\n\navatar = media.Movie(\"Avatar\",\n \"2h 42m\",\n \"A paraplegic marine dispatched to the moon Pandora on\"\n \" a unique mission becomes torn between following his\"\n \" orders and protecting the world he feels is his home.\",\n \"https://m.media-amazon.com/images/M/MV5BMTYwOTEwNjAz\"\n \"Ml5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_UX182_CR0,0,182,\"\n \"268_AL_.jpg\",\n \"https://www.youtube.com/watch?v=5PSNL1qE6VY\")\n\nmagnolia = media.Movie(\"Magnolia\",\n \"3h 9m\",\n \"An epic mosaic of interrelated characters in search\"\n \" of love, forgiveness, and meaning in the San\"\n \" Fernando Valley\",\n \"https://m.media-amazon.com/images/M/MV5BZjk3YThkNDkt\"\n \"NjZjMS00MTBiLTllNTAtYzkzMTU0N2QwYjJjXkEyXkFqcGde\"\n \"QXVyMTMxODk2OTU@._V1_UX182_CR0,0,182,268_AL_.jpg\",\n \"https://www.youtube.com/watch?v=KnamcFv_N9Q\")\n\nschool_of_rock = media.Movie(\"School Of Rock\",\n \"1h 49m\",\n \"After being kicked out of his rock band, Dewey\"\n \" Finn becomes a substitute teacher of an\"\n \" uptight elementary private school, only to\"\n \" try and turn them into a rock band.\",\n \"https://m.media-amazon.com/images/M/MV5BMjEwO\"\n \"TMzNjYzMl5BMl5BanBnXkFtZTcwNjczMTQyMQ@@._V1_\"\n \"UX182_CR0,0,182,268_AL_.jpg\",\n \"https://www.youtube.com/watch?v=XCwy6lW5Ixc\")\n\nratatouille = media.Movie(\"Ratatouille\",\n \"1h 51m\",\n \"A rat who can cook makes an unusual alliance with\"\n \" a young kitchen worker at a famous restaurant.\",\n \"https://m.media-amazon.com/images/M/MV5BMTMzODU0N\"\n \"TkxMF5BMl5BanBnXkFtZTcwMjQ4MzMzMw@@._V1_UX182_CR0\"\n \",0,182,268_AL_.jpg\",\n \"https://www.youtube.com/watch?v=c3sBBRxDAqk\")\n\nmidnight_in_paris = media.Movie(\"Midnight In Paris\",\n \"1h 40m\",\n \"While on a trip to Paris with his fiancee's\"\n \" family, a nostalgic screenwriter finds\"\n \" himself mysteriously going back to the\"\n \" 1920s everyday at midnight.\",\n \"https://m.media-amazon.com/images/M/MV5BMTM\"\n \"4NjY1MDQwMl5BMl5BanBnXkFtZTcwNTI3Njg3NA@@.\"\n \"_V1_UX182_CR0,0,182,268_AL_.jpg\",\n \"https://www.youtube.com/watch?v=FAfR8omt-CY\")\n\nhunger_games = media.Movie(\"Hunger Games\",\n \"2h 22m\",\n \"Katniss Everdeen voluntarily takes her younger\"\n \" sister's place in the Hunger Games: a televised\"\n \" competition in which two teenagers from each of\"\n \" the twelve Districts of Panem are chosen at\"\n \" random to fight to the death.\",\n \"https://m.media-amazon.com/images/M/MV5BMjA4NDg3\"\n \"NzYxMF5BMl5BanBnXkFtZTcwNTgyNzkyNw@@._V1_UX182\"\n \"_CR0,0,182,268_AL_.jpg\",\n \"https://www.youtube.com/watch?v=mfmrPu43DF8\")\n\n# lista contendo os filmes que serao usados para popular a pagina web\nmovies = [toy_story, avatar, magnolia, school_of_rock, ratatouille,\n midnight_in_paris, hunger_games]\n\n# Abre um a pagina web com a lista de filmes\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"470982188","text":"from random import choice\nmap = {\n 'size_x': 4,\n 'size_y': 4,\n}\n\nplayer = {\n 'x': 1,\n 'y': 1,\n}\n\nghosts = [\n {\n 'x': 3,\n 'y': 0,\n },\n {\n 'x': 3,\n 'y': 3,\n }]\n\nfoods = [\n {\n 'x': 0,\n 'y': 0,\n },\n {\n 'x': 1,\n 'y': 0\n },\n {\n 'x': 0,\n 'y': 1,\n }]\n \n\nplaying = True\n\nwhile playing:\n for y in range(map['size_y']):\n for x in range(map['size_x']):\n\n player_is_here = False\n if y == player['y'] and x == player['x']:\n player_is_here = True\n\n ghost_is_here = False\n for ghost in ghosts:\n if y == ghost['y'] and x == ghost['x']:\n ghost_is_here = True\n\n food_is_here = False\n for food in foods:\n if y == food['y'] and x == food['x']:\n food_is_here = True\n\n if player_is_here:\n print('P ',end='')\n elif ghost_is_here:\n print('G ',end='')\n elif food_is_here:\n print('F ',end='')\n else:\n print('- ',end='')\n print()\n\n \n \n # check win\n \n \n if len(foods) == 1 and player == food:\n print('You won!!!')\n break\n else:\n for food in foods:\n if player == food:\n foods.remove(food)\n \n if player == ghosts[1] or player == ghosts[0] :\n print('You lost!!!')\n break\n \n\n # bind button\n move = input('Your next move: ').upper()\n dx = 0\n dy = 0\n if move == 'W':\n dy = -1\n elif move == 'A':\n dx = -1\n elif move == 'S':\n dy = 1\n elif move == 'D':\n dx = 1\n else:\n playing = False\n\n \n\n \n if 0 <= player['x'] + dx < map['size_x'] and \\\n 0 <= player['y'] + dy < map['size_y']:\n player['x'] += dx\n player['y'] += dy\n\n direct = [1, -1]\n fx = 0\n fy = 0\n move_rand = choice(direct)\n if move_rand == 1:\n fx = choice(direct)\n if move_rand == -1:\n fy = choice(direct)\n for food in foods:\n if ghosts[0] != ghosts[1] != food:\n if 0 <= ghosts[0]['x'] + fx < map['size_x'] and 0 <= ghosts[0]['y'] + fy < map['size_y']:\n ghosts[0]['x'] += fx\n ghosts[0]['y'] += fy\n if 0 <= ghosts[1]['x'] + fx < map['size_x'] and 0 <= ghosts[1]['y'] + fy < map['size_y']:\n ghosts[1]['x'] += fx\n ghosts[1]['y'] += fy\n \n \n \n\n \n\n","sub_path":"ProjectC4E/C4E-20/Fundamentals/Session05/pacman.py","file_name":"pacman.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"142038028","text":"from argparse import ArgumentParser\nfrom collections import defaultdict\nimport glob\nimport os\nimport random\nimport shutil\nimport subprocess\nimport tempfile\nimport uuid\n\n\ndef wav_fp_to_num_samples(wav_fp):\n wav_size = os.stat(wav_fp).st_size\n # Subtract header\n data_size = wav_size - 44\n assert data_size % 2 == 0\n nsamps = data_size // 2\n return nsamps\n\n\ndef tx1_fp_ensemble_complete(tx1_fp):\n with open(tx1_fp, 'r') as f:\n tx1 = f.read()\n p1 = 'P1_NOTEON' in tx1\n p2 = 'P2_NOTEON' in tx1\n tr = 'TR_NOTEON' in tx1\n no = 'NO_NOTEON' in tx1\n return p1 and p2 and tr and no\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n\n parser.add_argument('wav_dirs', type=str, nargs='+')\n parser.add_argument('--anon_dir', type=str)\n parser.add_argument('--nclips', type=int)\n parser.add_argument('--slice_len', type=float)\n parser.add_argument('--seed', type=int)\n\n parser.set_defaults(\n wav_dirs=[],\n anon_dir=None,\n nclips=None,\n slice_len=5,\n seed=0)\n\n args = parser.parse_args()\n\n # Randomize (consistently)\n random.seed(args.seed)\n\n # Gather waveforms of at least slice_len\n slice_len_samps = int(round(args.slice_len * 44100.))\n method_tag_to_fns = {}\n method_tag_to_dir = {}\n print('-' * 80)\n for d in args.wav_dirs:\n method_tag = os.path.split(d)[1]\n fps = sorted(glob.glob(os.path.join(d, '*.wav')))\n fps = [fp for fp in fps if wav_fp_to_num_samples(fp) >= slice_len_samps]\n fps = [fp for fp in fps if tx1_fp_ensemble_complete(fp.replace('.tx1.wav', '.tx1.txt'))]\n fns = ['.'.join(os.path.split(fp)[1].split('.')[:-1]) for fp in fps]\n random.shuffle(fns)\n\n print(method_tag, len(fps))\n\n if len(fps) < args.nclips:\n print('Warning: not enough clips from {} ({})'.format(method_tag, len(fps)))\n nsamp = min(args.nclips, len(fps))\n\n method_tag_to_fns[method_tag] = random.sample(fns, nsamp)\n method_tag_to_dir[method_tag] = d\n\n # Create output directory\n if os.path.isdir(args.anon_dir):\n shutil.rmtree(args.anon_dir)\n os.makedirs(args.anon_dir)\n hit_mp3_dir = os.path.join(args.anon_dir, 'mp3s')\n os.makedirs(hit_mp3_dir)\n\n # Strip revealing information (create UUIDs)\n uuids = set()\n uuid_key = []\n method_tag_to_uuids = defaultdict(list)\n for method_tag, fns in method_tag_to_fns.items():\n for fn in fns:\n wav_fp = os.path.join(method_tag_to_dir[method_tag], '{}.wav'.format(fn))\n nsamps = wav_fp_to_num_samples(wav_fp)\n nsecs = nsamps / 44100.\n offset = random.random() * (nsecs - args.slice_len)\n\n wav_uuid = uuid.uuid4().hex\n assert wav_uuid not in uuids\n uuid_key.append('{},{},{}'.format(wav_uuid, method_tag, fn))\n uuids.add(wav_uuid)\n method_tag_to_uuids[method_tag].append(wav_uuid)\n\n out_fp = os.path.join(hit_mp3_dir, '{}.mp3'.format(wav_uuid))\n with tempfile.NamedTemporaryFile() as f:\n shutil.copyfile(wav_fp, f.name)\n cmd = 'ffmpeg -i {} -ss {} -t {} -q:a 2 -loglevel error -hide_banner -y {}'.format(f.name, offset, args.slice_len, out_fp)\n res = subprocess.call(cmd, shell=True)\n if res > 0:\n raise Exception('ffmpeg failed')\n\n # Create key\n with open(os.path.join(args.anon_dir, 'key.csv'), 'w') as f:\n f.write('\\n'.join(sorted(uuid_key)))\n","sub_path":"userstudy/turk_anonymous_clips.py","file_name":"turk_anonymous_clips.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"608276582","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/mozart/__init__.py\n# Compiled at: 2019-05-07 06:15:52\n# Size of source mod 2**32: 333 bytes\nfrom mozart import cli\nfrom .__version__ import __version__\n__title__ = 'MusicAPI'\n__description__ = 'Nice API for developers who like music™'\n__url__ = 'https://github.com/kushao1267/MusicAPI'\n__author__ = 'krusjra'\n__author_email__ = 'jianliu001922@gmail.com'\n__license__ = 'MIT License'\n__copyright__ = 'Copyright 2019 krusjra'","sub_path":"pycfiles/mozart-1.0.3-py3.6/__init__.cpython-36.py","file_name":"__init__.cpython-36.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"132452217","text":"import requests\nimport bs4 \n#from bs4 import BeautifulSoup\n#res = requests.get('http://nostarch.com')\n#res.raise_for_status()\n#print(res.text)\n\nexampleFile = open('example.html')\nreaded = exampleFile.read()\nexampleSoup = bs4.BeautifulSoup(readed)\nelems = exampleSoup.select('#author')\n#print(\"Elems: \", elems)\nprint(elems)\n\n#print(elems[0].getText() )\n#print(str(elems[0]) )\n#print(elems[0].attrs )\n#type(exampleSoup)\n\n#noStarchSoup = bs4.BeautifulSoup(res.text)\n#type(noStarchSoup)\npElems = exampleSoup.select('p')\nprint(str(pElems[0]) )\nprint( pElems[0].getText() )\n\n\n\n","sub_path":"bSoup.py","file_name":"bSoup.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"140239154","text":"from os import listdir, makedirs\nfrom os.path import isfile, isdir, join\nimport cv2, copy, json, os\nimport numpy as np\nfrom PIL import Image,ImageDraw\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os, shutil, PIL \n\n##################################################################\n# directory\n\ndir1 = './background-images/'\nimdirs = os.listdir(dir1)\nimlist = [ plt.imread(dir1 + i) for i in imdirs ]\n\n\n##################################################################\n# open json file\n\n\ndef open_json_file(file_path):\n if isfile(file_path):\n with open(file_path, 'r') as json_file:\n json_data = json.load(json_file)\n return json_data\n else:\n print(\"json file doesn't exist\")\n exit() \n\n#####################################################################################\n# clearning folders \ndef move_dirs(oslist, src, dst):\n for i in oslist:\n shutil.move(os.path.join(src, i), dst)\n\n\ndef clean_and_rename_directory( dirlist ):\n # directory must be './CV_DeepLearning/Acu_Dataset'\n if os.getcwd().split('/')[-1] == 'Image-Preprocess':\n print('cur')\n os.chdir('../CV_DeepLearning')\n \n dir_lists = os.listdir(dirlist)\n print(os.getcwd())\n for dir_name in dir_lists:\n dir_cur = './Acu_Dataset/' + dir_name\n # 폴더가 하나인 경우 상위 폴더로 통합 \n if len(os.listdir(dir_cur) ) == 1:\n dir_cur2 = dir_cur + '/' + dir_name\n folders = os.listdir(dir_cur2)\n for j in folders:\n shutil.move ( dir_cur2 + '/' + str(j) , dir_cur)\n shutil.rmtree(dir_cur2)\n print('cleaning directory ', dir_cur2)\n\n if len(os.listdir(dir_cur) ) == 3:\n os.mkdir(dir_cur + '/org')\n if True in [ 'dorsal' for d in os.listdir(dir_cur)]: \n kw = '_dorsal_'\n else: \n kw = '_palmar_'\n\n left_dir = dir_cur + '/'+ dir_name + kw + 'left'\n right_dir = dir_cur + '/'+ dir_name + kw + 'right'\n left_list = os.listdir(left_dir)\n right_list = os.listdir(right_dir)\n move_dirs(left_list, left_dir, dir_cur + '/org')\n move_dirs(right_list, right_dir, dir_cur + '/org')\n\n shutil.rmtree(left_dir)\n shutil.rmtree(right_dir)\n print('completed cleaning folders: ', dir_cur)\n\n np_lst = np.array(os.listdir(dir_cur))\n old_name = np_lst[np.array([(not 'org' in d) for d in os.listdir(dir_cur)])][0]\n\n old_file = os.path.join( dir_cur, old_name )\n new_file = os.path.join( dir_cur, dir_name + '_info.json' )\n print('oldfile: ', old_file, ' new_file : ', new_file)\n os.rename(old_file, new_file)\n\n\n\n \n#####################################################################################\n# DB & Path Check\n\ndef open_temp_db():\n db = []\n dorsal_acupunctures = {'양계':'yanggye', '양지':'yangji', '외관':'oegwan', '양곡':'yanggok', \n '합곡':'hapgok', '중저':'jungjer', '삼간':'samgan', '이간':'egan',\n '액문':'ekmoon','상양':'sangyang','중층':'jungcheung','소충':'sochung',\n '소택':'sotack','관충':'gwanchung', '휴게': 'hugye'}\n palmar_acupunctures = {'신문':'shinmoon','대릉':'daereung','태연':'taeyeon','어제':'urjae',\n '소부':'sobu','노궁':'nogung','소상':'sosang'}\n\n db.append(dorsal_acupunctures)\n db.append(palmar_acupunctures)\n return db\n\ndef make_path_tuple(acupuncture_info, changed_hands_path):\n path = []\n for _ in changed_hands_path:\n for f in listdir(_):\n hand_pos = (_.split('/')[2]).strip(f'{acupuncture_info}_')\n path.append((join(_,f), hand_pos))\n return path\n\ndef is_acupuncture(ac, db):\n flag = False\n for _ in db:\n if ac in _:\n flag = True\n ac = _.get(ac)\n return ac\n if not flag:\n print(\"Can't find acupuncture info\")\n exit()\n \n#####################################################################################\n# Image processing: crop, clear background, fill background, rotate, translate, scale\ndef create_circle_patch(img, x, y, color, r=1):\n '''\n input : 0~1 float32 ndarray\n output : 0~255 uint8 ndarray with dots\n '''\n # img = (img * 255 / np.max(img)).astype('uint8')\n if type(img) == np.ndarray:\n img = Image.fromarray(img.astype('uint8'), 'RGB')\n draw = ImageDraw.Draw(img)\n x = 2 if x < 0 else x\n y = 2 if y < 0 else y\n\n leftUpPoint = (x-r, y-r)\n rightDownPoint = (x+r, y+r)\n\n twoPointList = [leftUpPoint, rightDownPoint]\n if color == 'blue':\n fill = (0,0,255,0)\n if color == 'red':\n fill = (255,0,0,0)\n draw.ellipse(twoPointList, fill=fill)\n img = np.array(img)\n img = (img / np.max(img))\n return img\n\n\ndef get_img_distn (img, kw='orange'):\n '''\n W x H x C ; C: RGB\n '''\n if kw == 'orange':\n _ = plt.hist(img.ravel(), bins = 256, color = 'orange', )\n \n if kw == 'red':\n _ = plt.hist(img[:, :, 0].ravel(), bins = 256, color = 'red', alpha = 0.5)\n\n if kw == 'green':\n _ = plt.hist(img[:, :, 1].ravel(), bins = 256, color = 'Green', alpha = 0.5)\n \n if kw == 'blue':\n _ = plt.hist(img[:, :, 2].ravel(), bins = 256, color = 'Blue', alpha = 0.5)\n\n plt.show()\n \n\n\ndef rand_crop_img (img, size = 250, change_col = True, *args):\n '''\n gets nd array greater than (256x256) as an input\n returns randomly cropped image (256x256) as an output\n channel values are uint of 0 to 255\n '''\n if img.dtype == 'float32':\n img = (img * 255 / np.max(img)).astype('uint8')\n im_pil = Image.fromarray(img.astype('uint8'), 'RGB')\n\n x_c = np.random.randint(0, im_pil.size[0] - size)\n y_c = np.random.randint(0, im_pil.size[1] - size)\n img_cropped = im_pil.crop((x_c, y_c, x_c + size, y_c + size)) \n img_cropped = np.asarray(img_cropped) / 255.0\n\n if change_col == True:\n # change color distn \n for j in range(3):\n img_cropped[:, :, j] = (img_cropped[:, :, j] + np.random.uniform(0, 0.15) ) / 2.0\n img_cropped = img_cropped / np.max(img_cropped)\n\n return img_cropped\n\n\ndef clear_background(img):\n # img = cv2.imread('test2\\Hand_0000002.png')\n\n # convert to hsv\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n lower_range = (0,0,100)\n upper_range = (358,45,255)\n mask = cv2.inRange(hsv, lower_range, upper_range)\n\n # invert mask\n mask = 255 - mask\n # cv2.imshow('mask', mask)\n # cv2.waitKey(0)\n\n # apply morphology closing and opening to mask\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)\n mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\n\n result = img.copy()\n result[mask==0] = (255,255,255)\n \n return result\n \n\ndef img_from_mask2(img, mask ):\n '''\n mask : 2d array of true/false\n img : 3d array with rgb channels\n '''\n r = img[:,:,0] + 255*mask[:,:,0] \n g = img[:,:,1] + 255*mask[:,:,1] \n b = img[:,:,2] + 255*mask[:,:,2] \n rgb = np.dstack((r,g,b))\n rgb[rgb > 255] = 0\n return rgb\n\n\ndef save_json_file2(json_data, json_file):\n with open(json_file, 'w') as outfile:\n json.dump(json_data, outfile, indent='\\t')\n\ndef rotate_bound(image, theta):\n # grab the dimensions of the image and then determine the\n # centre\n (h, w) = image.shape[:2]\n (cX, cY) = (w // 2, h // 2)\n\n # grab the rotation matrix (applying the negative of the\n # angle to rotate clockwise), then grab the sine and cosine\n # (i.e., the rotation components of the matrix)\n M = cv2.getRotationMatrix2D((cX, cY), theta, 1.0)\n cos = np.abs(M[0, 0])\n sin = np.abs(M[0, 1])\n\n # compute the new bounding dimensions of the image\n nW = int((h * sin) + (w * cos))\n nH = int((h * cos) + (w * sin))\n\n # adjust the rotation matrix to take into account translation\n M[0, 2] += (nW / 2) - cX\n M[1, 2] += (nH / 2) - cY\n\n # perform the actual rotation and return the image\n return cv2.warpAffine(image, M, (nW, nH), borderMode=cv2.BORDER_TRANSPARENT)\n\ndef rotate_box(coord, cx, cy, h, w, theta):\n \n # opencv calculates standard transformation matrix\n M = cv2.getRotationMatrix2D((cx, cy), theta, 1.0)\n \n # Grab the rotation components of the matrix)\n cos = np.abs(M[0, 0])\n sin = np.abs(M[0, 1])\n \n # compute the new bounding dimensions of the image\n nW = int((h * sin) + (w * cos))\n nH = int((h * cos) + (w * sin))\n \n # adjust the rotation matrix to take into account translation\n M[0, 2] += (nW / 2) - cx\n M[1, 2] += (nH / 2) - cy\n \n # Prepare the vector to be transformed\n v = [coord[0], coord[1],1]\n \n # Perform the actual rotation and return the image\n calculated = np.dot(M,v)\n new_bb = (calculated[0], calculated[1])\n \n return new_bb\n \ndef fill_background_image2(org_path, json_data, save_name, save_path, imlist, chg_flag = False):\n '''\n img_info : list of image names (os.listdir) in the original path \n '''\n img_info = os.listdir(org_path)\n # acup info\n acu_info = list(json_data)[0].split('_')[0]\n # directory for saving image\n save_directory = save_path + '/' + save_name\n if not(isdir(save_directory)):\n makedirs(save_directory)\n img_directory = save_directory + '/' + save_name \n if not(isdir(img_directory)):\n makedirs(img_directory)\n # json_file\n json_new = dict()\n # random index\n random_indx = np.random.randint(low = 0,high = len(imlist), size = len(img_info))\n \n for i in range(0, len(img_info)):\n img_path = org_path + '/' + img_info[i]\n #img_id = img_info[i].split('_')[-1].split('.')[0]\n #img_id = name_list[1]\n names = img_info[i].split('_')\n img_id = names[1].split('.')[0]\n \n if chg_flag == True:\n chg_id = names[2].split('.')[0]\n acupuncture_id = f\"{acu_info}_{img_id}_{chg_id}\"\n else: \n acupuncture_id = f\"{acu_info}_{img_id}\"\n \n # json tag\n acupuncture_new_id = acupuncture_id + '_'+save_name\n xy = json_data[acupuncture_id][1]['acup_coord']\n img_hand_pos = json_data[acupuncture_id][0]['hand_pos']\n \n json_new[acupuncture_new_id] = list()\n json_new[acupuncture_new_id].append({\n \"acup_info\": f\"{acu_info}\",\n \"hand_pos\": f\"{img_hand_pos}\"\n })\n json_new[acupuncture_new_id].append({\n \"acup_coord\": xy\n })\n \n # read the image file, then generate image\n img = clear_background(cv2.imread(img_path, cv2.IMREAD_UNCHANGED))\n height, width = img.shape[:2]\n im_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # np format\n\n # get img mask\n im_mask1 = 1* (im_rgb != 255)\n im_mask2 = 1* (im_rgb == 255)\n \n npimg = rand_crop_img( imlist[ random_indx[i]])\n uint_img = (npimg * 255 / np.max(npimg)).astype('uint8')\n b_image = cv2.resize( uint_img , dsize=(height,width)) \n \n new_img = img_from_mask2( b_image, im_mask1 ) + img_from_mask2( im_rgb, im_mask2 )\n # get PIL img\n img_pil = Image.fromarray(new_img.astype('uint8'), 'RGB') \n img_pil.save(img_directory + '/' + acupuncture_new_id + '.png')\n \n if i % 10 == 0:\n print('completed ' + str(i) + ' images to fill')\n save_json_file2(json_new, save_directory + '/' + acu_info + '_' + save_name + '.json')\n\n \ndef rotate_image_trnsfm(org_path, json_data, save_name, save_path, chg_flag = False):\n \n img_info = os.listdir(org_path)\n acu_info = list(json_data)[0].split('_')[0]\n \n save_directory = save_path + '/' + save_name\n if not(isdir(save_directory)):\n makedirs(save_directory)\n\n img_directory = save_directory + '/' + save_name \n if not(isdir(img_directory)):\n makedirs(img_directory)\n # json_file\n json_new = dict()\n \n angle_list = np.random.randint(low = -180, high = 180, size = len(img_info))\n \n for i in range(0, len(img_info)):\n img_path = org_path + '/' + img_info[i]\n names = img_info[i].split('_')\n img_id = names[1].split('.')[0]\n angle = angle_list[i]\n\n if chg_flag == True:\n chg_id = names[2].split('.')[0]\n acupuncture_id = f\"{acu_info}_{img_id}_{chg_id}\"\n else: \n acupuncture_id = f\"{acu_info}_{img_id}\"\n\n # json tag\n acupuncture_new_id = acupuncture_id + f'_rt{angle}'\n\n x, y, xy = json_data[acupuncture_id][1].values()\n img_hand_pos = json_data[acupuncture_id][0]['hand_pos']\n \n # read the image file, then generate rotated image\n img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\n rotated_img = rotate_bound(img, angle)\n\n # height and width for images\n height, width = img.shape[:2]\n (cx, cy) = (width // 2, height // 2)\n (new_height, new_width) = rotated_img.shape[:2]\n (new_cx, new_cy) = (new_width // 2, new_height // 2)\n \n new_x, new_y = rotate_box((x, y), cx, cy, height, width, angle)\n \n # change to 700 x 700 \n new_x, new_y = int(new_x * 700 / new_width ), int(new_y * 700 / new_height )\n new_xy = (new_x, new_y)\n \n\n json_new[acupuncture_new_id] = list()\n json_new[acupuncture_new_id].append({\n \"acup_info\": f\"{acu_info}\",\n \"hand_pos\": f\"{img_hand_pos}\"\n })\n json_new[acupuncture_new_id].append({\n \"acup_coord\": new_xy\n })\n \n im_mask1 = 255 * (rotated_img == 0)\n rotated_img = (im_mask1 + rotated_img).astype('uint8')\n # resize to 700 x 700\n rotated_img = cv2.resize( rotated_img , dsize=(700,700)) \n \n cv2.imwrite(f'./{img_directory}/{acupuncture_new_id}.png', rotated_img)\n if i % 100 == 0:\n print('completed ' + str(i) + ' images to rotate')\n\n save_json_file2(json_new, save_directory + '/' + acu_info + '_' + save_name + '.json')\n\n\n# translation & cropping related\ndef margin_finder(img):\n # input must be rgb immage\n #width, height = img.shape[:2]\n left_margin = int(np.mean( [ (img[:,:,i] -255).max(axis = 0).argmax() for i in range(3)])) \n up_margin = int(np.mean( [ (img[:,:,i] -255).max(axis = 1).argmax() for i in range(3)])) \n \n r = (img[:,:,0]).min(axis = 0)\n g = (img[:,:,1]).min(axis = 0)\n b = (img[:,:,2]).min(axis = 0)\n right_margin =5 + min(np.where( ((r >= 200) & (r<235) & (g>=238) & (g<250) & (b >= 225) & (b < 250)))[0])\n return left_margin, right_margin, up_margin\n\ndef img_crop(img, margin):\n left_margin, right_margin, up_margin = margin\n return (img[ up_margin:, left_margin:right_margin, :])\n\n\n################\n# Accessing Files\ndef scale_and_translate_img (org_path, json_data, save_name, save_path, chg_flag = False):\n img_info = os.listdir(org_path)\n # acup info\n acu_info = list(json_data)[0].split('_')[0]\n # directory for saving image\n save_directory = save_path + '/' + save_name\n if not(isdir(save_directory)):\n makedirs(save_directory)\n \n img_directory = save_directory + '/' + save_name \n if not(isdir(img_directory)):\n makedirs(img_directory)\n # json_file\n json_new = dict()\n \n for i in range(0, len(img_info)):\n img_path = org_path + '/' + img_info[i]\n names = img_info[i].split('_')\n img_id = names[1].split('.')[0]\n\n if chg_flag == True:\n chg_id = names[2].split('.')[0]\n acupuncture_id = f\"{acu_info}_{img_id}_{chg_id}\"\n else: \n acupuncture_id = f\"{acu_info}_{img_id}\"\n\n # json tag\n\n x_org, y_org, xy = json_data[acupuncture_id][1].values()\n img_hand_pos = json_data[acupuncture_id][0]['hand_pos']\n\n pil_im = PIL.Image.open(img_path)\n np_im = np.array(pil_im)\n\n ###############################################\n # processing\n img = cv2.imread(img_path)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n blurred = cv2.GaussianBlur(gray, (5,5), 0)\n edged = cv2.Canny(blurred, 50, 100, 255)\n\n # edge points location \n y_vals = np.where(edged.max(axis=1))[0]\n x_vals = np.where(edged.max(axis=0))[0]\n # cropping boundary\n y_high = np.min(y_vals)\n y_low = np.max(y_vals)\n x_high = np.max(x_vals)\n x_low = np.min(x_vals)\n # coordinate after cropping: \n x_new = x_org - x_low\n y_new = y_org - y_high\n # cropped image\n cropped = np_im[y_high:y_low, x_low:x_high, :]\n cp_height, cp_width = cropped.shape[:2]\n\n # Scaling IMG\n scale_prop = 0.7\n scalar = np.random.uniform(scale_prop,1)\n x_scale = int(scalar * np.random.randint(cp_width/1.15, min(cp_width*1.5, 700)))\n y_scale = int(scalar * np.random.randint(cp_height/1.5, 700))\n # x,y coord after scaling\n x_coord_sc = x_new * x_scale / cp_width\n y_coord_sc = y_new * y_scale / cp_height\n # scaled \n pil = Image.fromarray(cropped.astype('uint8'), 'RGB')\n pil = pil.resize(size = (x_scale, y_scale))\n np_scaled = np.array(pil)\n \n # Translating IMG\n move_x = np.random.randint(x_scale, 700)\n x_left = move_x - x_scale\n x_right = 700 - move_x \n\n move_y = np.random.randint(y_scale, 700)\n y_up = move_y - y_scale\n y_down = 700 - move_y\n\n # add to blank 700x700\n left_margin = (255*np.ones(shape = (y_scale,x_left, 3), dtype = 'uint8'))\n right_margin = (255*np.ones(shape = (y_scale,x_right, 3), dtype = 'uint8'))\n up_margin = (255*np.ones(shape = (y_up, 700, 3), dtype = 'uint8'))\n down_margin = (255*np.ones(shape = ( y_down,700, 3), dtype = 'uint8'))\n stack1 = np.hstack((left_margin, np_scaled, right_margin))\n fin_img = np.vstack((up_margin, stack1, down_margin))\n\n # new coordinate after translation \n x_new_tr = int(x_left + x_coord_sc)\n y_new_tr = int(y_up + y_coord_sc)\n new_xy = x_new_tr, y_new_tr\n\n acupuncture_new_id = acupuncture_id + f'_sctr{x_scale}+{y_scale}+{x_left}+{y_up}'\n\n json_new[acupuncture_new_id] = list()\n json_new[acupuncture_new_id].append({\n \"acup_info\": f\"{acu_info}\",\n \"hand_pos\": f\"{img_hand_pos}\"\n })\n json_new[acupuncture_new_id].append({\n \"acup_coord\": new_xy\n })\n\n # Save new img\n img_pil = Image.fromarray(fin_img.astype('uint8'), 'RGB') \n img_pil.save(img_directory + '/' + acupuncture_new_id + '.png')\n\n if i % 100 == 0:\n print('completed ' + str(i) + ' images to sctr')\n save_json_file2(json_new, save_directory + '/' + acu_info + '_' + save_name + '.json')\n\n##########################################################################################\n\n# Augment\n\n\ndef augment_hands( class_label, save_name= 'rotated', img_folder = 'org', json_name = None, imlist = None, chg_flag = False):\n # 'C:\\\\Users\\\\NormalKim\\\\[0_BigData_Acu]\\\\Acupuncture-Points\\\\CV_DeepLearning'\n if chg_flag == False: \n org_path = f'./Acu_Dataset/{class_label}/{img_folder}' # rotated/rotated\n json_data = open_json_file(f'./Acu_Dataset/{class_label}/{class_label}_info.json')\n save_path = f'./Acu_Dataset/{class_label}/'\n else:\n folder_path = f'./Acu_Dataset/{class_label}/{img_folder}' # img_folder = rotated\n org_path = folder_path + f'/{img_folder}'\n json_data = open_json_file(folder_path + f'/{json_name}.json')\n save_path = f'./Acu_Dataset/{class_label}/'\n \n print('starting: ', class_label , ' ', save_name)\n if 'rotated' in save_name.split('_')[-1]:\n rotate_image_trnsfm(org_path, json_data, save_name, save_path, chg_flag)\n \n elif 'filled' in save_name.split('_')[-1]:\n fill_background_image2( org_path, json_data, save_name, save_path, imlist, chg_flag)\n\n elif 'sctr' in save_name.split('_')[-1]:\n scale_and_translate_img( org_path, json_data, save_name, save_path, chg_flag)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Image-Preprocess/img_aug_refined.py","file_name":"img_aug_refined.py","file_ext":"py","file_size_in_byte":20431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"349897646","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.io import loadmat\nfrom sklearn.svm import SVC\n\n'''\nStep 0: Load the data from './data/lab8data1.mat'\n'''\n\ndataset = loadmat('data/lab8data1.mat')\nprint(dataset.keys())\n\nX = dataset[\"X\"]\ny = dataset[\"y\"]\n\nprint(\"Dimension of X: {}\".format(X.shape))\nprint(\"Dimension of y: {}\".format(y.shape))\n\nnumber_of_row = X.shape[0]\n\npositives = (y == 1).reshape(number_of_row, 1)\nnegatives = (y == 0).reshape(number_of_row, 1)\n\nprint('\\n')\n\n'''\nStep 1: Instantiate a 'linear' SVM classifier with C = 1\n'''\n\nclassifier1 = SVC(kernel=\"linear\") # By default, C = 1\nclassifier1.fit(X, np.ravel(y))\n\n'''\nStep 2: Visualizing the training set result \n'''\n\nplt.figure(1)\nplt.scatter(X[positives[:, 0], 0], X[positives[:, 0], 1], c=\"r\", marker=\"+\", s=50)\nplt.scatter(X[negatives[:, 0], 0], X[negatives[:, 0], 1], c=\"y\", marker=\"o\", s=50)\n\n# plotting the decision boundary\nX1, X2 = np.meshgrid(np.linspace(X[:, 0].min(), X[:, 0].max(), num=300),\n np.linspace(X[:, 1].min(), X[:, 1].max(), num=300))\n\nplt.contour(X1, X2, classifier1.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), colors=\"b\")\n\n'''\nStep 3: Instantiate a 'linear' SVM classifier with C = 100 and\nplot the decision boundary\n'''\n\nclassifier2 = SVC(kernel=\"linear\", C=100) # By default, C = 1\nclassifier2.fit(X, np.ravel(y))\n\nplt.figure(2)\nplt.scatter(X[positives[:, 0], 0], X[positives[:, 0], 1], c=\"r\", marker=\"+\", s=50)\nplt.scatter(X[negatives[:, 0], 0], X[negatives[:, 0], 1], c=\"y\", marker=\"o\", s=50)\n\n# plotting the decision boundary\nX1, X2 = np.meshgrid(np.linspace(X[:, 0].min(), X[:, 0].max(), num=300),\n np.linspace(X[:, 1].min(), X[:, 1].max(), num=300))\n\nplt.contour(X1, X2, classifier2.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), colors=\"b\")\n\nplt.show()","sub_path":"Lab/day10/lab8-problem1-1.py","file_name":"lab8-problem1-1.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"359918165","text":"from os import listdir\r\nfrom pickle import dump\r\nfrom keras.applications.vgg16 import VGG16\r\nfrom keras.preprocessing.image import load_img\r\nfrom keras.preprocessing.image import img_to_array\r\nfrom keras.applications.vgg16 import preprocess_input\r\nfrom keras.models import Model\r\nimport cv2\r\nfrom pickle import load\r\nimport numpy as np\r\nfrom sklearn.cluster import MiniBatchKMeans\r\nfrom Kmeans import KMeans\r\nfrom numpy import reshape,array\r\n\r\ndef extract_features(directory):\r\n # load the model\r\n model = VGG16()\r\n # re-structure the model\r\n model.layers.pop()\r\n model = Model(inputs=model.inputs, outputs=model.layers[-1].output)\r\n # summarize\r\n print(model.summary())\r\n # extract features from each photo\r\n features = dict()\r\n sift_features = dict()\r\n sift_kmeans=[]\r\n for name in listdir(directory):\r\n # load an image from file\r\n filename = directory + '/' + name\r\n image = load_img(filename, target_size=(224, 224))\r\n img = cv2.imread(filename)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\r\n\r\n\r\n # convert the image pixels to a numpy array\r\n image = img_to_array(image)\r\n # reshape data for the model\r\n image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))\r\n # prepare the image for the VGG model\r\n image = preprocess_input(image)\r\n # get features\r\n feature = model.predict(image, verbose=0)\r\n # get image id\r\n image_id = name.split('.')[0]\r\n # store feature\r\n features[image_id] = feature\r\n\r\n # Extracting SIFT features\r\n sift = cv2.xfeatures2d.SIFT_create()\r\n kp, des = sift.detectAndCompute(img, None)\r\n sift_features[image_id] = des\r\n sift_kmeans.append(des)\r\n print('>%s' % name)\r\n return features,sift_features,sift_kmeans\r\n\r\n# extract features from all images\r\ndirectory = '/home/vthotigar/bda_data/image_data'\r\nfeatures,sift_features,sift_kmeans = extract_features(directory)\r\nprint('Extracted Features: %d' % len(features))\r\ncluster_model = MiniBatchKMeans(n_clusters=64)\r\nsift_kmeans, cluster_model = KMeans.cluster_features(sift_kmeans, cluster_model)\r\nsift = dict()\r\nj=0\r\nfor k, i in features.items():\r\n sift[k] = sift_kmeans[j]\r\n j=j+1\r\nprint(j)\r\n# save to file\r\ndump(features, open('features.pkl', 'wb'))\r\ndump(sift, open('sift_features.pkl', 'wb'))\r\ndump(cluster_model, open('clustermodel.pkl','wb'))\r\n# sift=dict()\r\n# all_features = load(open('features.pkl', 'rb'))\r\n# sift_features = load(open('sift_features.pkl', 'rb'))\r\n# for k,i in enumerate(all_features):\r\n# sift[i]=sift_features[k]\r\n# print(array(sift_features[k]).shape)\r\n# dump(sift, open('sift_features.pkl', 'wb'))\r\n","sub_path":"Source/Optimized Model/extractfeatures.py","file_name":"extractfeatures.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"457342298","text":"# -*- coding: utf-8 -*-\n#\n# Load data from NWB file\n#\n\n# Builtin/3rd party package imports\nimport os\nimport sys\nimport h5py\nimport subprocess\nimport numpy as np\nfrom tqdm import tqdm\n\n# Local imports\nfrom syncopy import __nwb__\nfrom syncopy.datatype.continuous_data import AnalogData\nfrom syncopy.datatype.discrete_data import EventData\nfrom syncopy.shared.errors import SPYError, SPYTypeError, SPYValueError, SPYWarning, SPYInfo\nfrom syncopy.shared.parsers import io_parser, scalar_parser, filename_parser\n\n# Conditional imports\nif __nwb__:\n import pynwb\n\n# Global consistent error message if NWB is missing\nnwbErrMsg = \"\\nSyncopy WARNING: Could not import 'pynwb'. \\n\" +\\\n \"{} requires a working pyNWB installation. \\n\" +\\\n \"Please consider installing 'pynwb', e.g., via conda: \\n\" +\\\n \"\\tconda install -c conda-forge pynwb\\n\" +\\\n \"or using pip:\\n\" +\\\n \"\\tpip install pynwb\"\n\n__all__ = [\"load_nwb\"]\n\n\ndef load_nwb(filename, memuse=3000, container=None):\n \"\"\"\n Read contents of NWB files\n\n Parameters\n ----------\n filename : str\n Name of (may include full path to) NWB file (e.g., `\"/path/to/mydata.nwb\"`).\n memuse : scalar\n Approximate in-memory cache size (in MB) for reading data from disk\n container : str\n Name of syncopy container folder to create the syncopy data in\n\n Returns\n -------\n objdict : dict\n Any NWB `TimeSeries`-like data is imported into an :class:`~syncopy.AnalogData`\n object. If the NWB file contains TTL pulse data, an additional\n :class:`~syncopy.EventData` object is instantiated. The syncopy\n objects are returned as a dictionary whose keys are the base-names\n (sans path) of the corresponding files.\n \"\"\"\n\n # Abort if NWB is not installed\n if not __nwb__:\n raise SPYError(nwbErrMsg.format(\"read_nwb\"))\n\n # Check if file exists\n nwbPath, nwbBaseName = io_parser(filename, varname=\"filename\", isfile=True, exists=True)\n nwbFullName = os.path.join(nwbPath, nwbBaseName)\n\n # Ensure `memuse` makes sense`\n try:\n scalar_parser(memuse, varname=\"memuse\", lims=[0, np.inf])\n except Exception as exc:\n raise exc\n\n # First, perform some basal validation w/NWB\n try:\n this_python = os.path.join(os.path.dirname(sys.executable),'python')\n subprocess.run([this_python, \"-m\", \"pynwb.validate\", nwbFullName], check=True)\n except subprocess.CalledProcessError as exc:\n err = \"NWB file validation failed. Original error message: {}\"\n raise SPYError(err.format(str(exc)))\n\n # Load NWB meta data from disk\n nwbio = pynwb.NWBHDF5IO(nwbFullName, \"r\", load_namespaces=True)\n nwbfile = nwbio.read()\n\n # Allocate lists for storing temporary NWB info: IMPORTANT use lists to preserve\n # order of data chunks/channels\n nSamples = 0\n tStarts = []\n sRates = []\n dTypes = []\n angSeries = []\n ttlVals = []\n ttlChanStates = []\n ttlChans = []\n ttlDtypes = []\n\n # If the file contains `epochs`, use it to infer trial information\n hasTrials = \"epochs\" in nwbfile.fields.keys()\n\n # Access all (supported) `acquisition` fields in the file\n for acqName, acqValue in nwbfile.acquisition.items():\n\n # Actual extracellular analog time-series data\n if isinstance(acqValue, pynwb.ecephys.ElectricalSeries):\n\n channels = acqValue.electrodes[:].location\n if channels.unique().size == 1:\n SPYWarning(\"No channel names found for {}\".format(acqName))\n\n dTypes.append(acqValue.data.dtype)\n if acqValue.channel_conversion is not None:\n dTypes.append(acqValue.channel_conversion.dtype)\n\n tStarts.append(acqValue.starting_time)\n sRates.append(acqValue.rate)\n nSamples = max(nSamples, acqValue.data.shape[0])\n angSeries.append(acqValue)\n\n # TTL event pulse data\n elif \".TTLs\" in str(acqValue.__class__):\n\n if acqValue.name == \"TTL_PulseValues\":\n ttlVals.append(acqValue)\n elif acqValue.name == \"TTL_ChannelStates\":\n ttlChanStates.append(acqValue)\n elif acqValue.name == \"TTL_Channels\":\n ttlChans.append(acqValue)\n else:\n lgl = \"TTL data exported via `esi-oephys2nwb`\"\n act = \"unformatted TTL data '{}'\"\n raise SPYValueError(lgl, varname=acqName, actual=act.format(acqValue.description))\n\n ttlDtypes.append(acqValue.data.dtype)\n ttlDtypes.append(acqValue.timestamps.dtype)\n\n # Unsupported\n else:\n lgl = \"supported NWB data class\"\n raise SPYValueError(lgl, varname=acqName, actual=str(acqValue.__class__))\n\n # If the NWB data is split up in \"trials\" (i.e., epochs), ensure things don't\n # get too wild (uniform sampling rates and timing offsets)\n if hasTrials:\n if all(tStarts) is None or all(sRates) is None:\n lgl = \"acquisition timings defined by `starting_time` and `rate`\"\n act = \"`starting_time` or `rate` not set\"\n raise SPYValueError(lgl, varname=\"starting_time/rate\", actual=act)\n if np.unique(tStarts).size > 1 or np.unique(sRates).size > 1:\n lgl = \"acquisitions with unique `starting_time` and `rate`\"\n act = \"`starting_time` or `rate` different across acquisitions\"\n raise SPYValueError(lgl, varname=\"starting_time/rate\", actual=act)\n epochs = nwbfile.epochs[:]\n trl = np.zeros((epochs.shape[0], 3), dtype=np.intp)\n trl[:, :2] = (epochs - tStarts[0]) * sRates[0]\n msg = \"Found {} trials\".format(trl.shape[0])\n else:\n trl = np.array([[0, nSamples, 0]])\n msg = \"No trial information found. Proceeding with single all-encompassing trial\"\n\n # Print status update to inform user\n SPYInfo(msg)\n\n # Check for filename\n if container is not None:\n if not isinstance(container, str):\n raise SPYTypeError(container, varname=\"container\", expected=\"str\")\n if not os.path.splitext(container)[1] == \".spy\":\n container += \".spy\"\n if not os.path.isdir(container):\n os.makedirs(container)\n fileInfo = filename_parser(container)\n filebase = os.path.join(fileInfo[\"folder\"],\n fileInfo[\"container\"],\n fileInfo[\"basename\"])\n\n # If TTL data was found, ensure we have exactly one set of values and associated\n # channel markers\n if max(len(ttlVals), len(ttlChans)) > min(len(ttlVals), len(ttlChans)):\n lgl = \"TTL pulse values and channel markers\"\n act = \"pulses: {}, channels: {}\".format(str(ttlVals), str(ttlChans))\n raise SPYValueError(lgl, varname=ttlVals[0].name, actual=act)\n if len(ttlVals) > 1:\n lgl = \"one set of TTL pulses\"\n act = \"{} TTL data sets\".format(len(ttlVals))\n raise SPYValueError(lgl, varname=ttlVals[0].name, actual=act)\n\n # Use provided TTL data to initialize `EventData` object\n evtData = None\n objectDict = {}\n if len(ttlVals) > 0:\n msg = \"Creating separate EventData object for embedded TTL pulse data...\"\n SPYInfo(msg)\n if container is not None:\n filename = filebase + \".event\"\n else:\n filename = None\n\n evtData = EventData(dimord=[\"sample\",\"eventid\",\"chans\"], filename=filename)\n h5evt = h5py.File(evtData.filename, mode=\"w\")\n evtDset = h5evt.create_dataset(\"data\", dtype=int,\n shape=(ttlVals[0].data.size, 3))\n # Column 1: sample indices\n # Column 2: TTL pulse values\n # Column 3: TTL channel markers\n if 'resolution' in ttlChans[0].__nwbfields__:\n ts_resolution = ttlChans[0].resolution\n else:\n ts_resolution = ttlChans[0].timestamps__resolution\n\n evtDset[:, 0] = ((ttlChans[0].timestamps[()] - tStarts[0]) / ts_resolution).astype(np.intp)\n evtDset[:, 1] = ttlVals[0].data[()].astype(int)\n evtDset[:, 2] = ttlChans[0].data[()].astype(int)\n evtData.data = evtDset\n evtData.samplerate = float(1 / ts_resolution)\n if hasTrials:\n evtData.trialdefinition = trl\n else:\n evtData.trialdefinition = np.array([[np.nanmin(evtDset[:,0]), np.nanmax(evtDset[:,0]), 0]])\n msg = \"No trial information found. Proceeding with single all-encompassing trial\"\n\n # Write logs\n log_msg = \"Read data from NWB file {}\".format(nwbFullName)\n evtData.log = log_msg\n objectDict[os.path.basename(evtData.filename)] = evtData\n\n # Compute actually available memory\n pbarDesc = \"Reading data in blocks of {} GB\".format(round(memuse / 1000, 2))\n memuse *= 1024**2\n\n # Process analog time series data and convert stuff block by block (if necessary)\n pbar = tqdm(angSeries, position=0, disable=None)\n for acqValue in pbar:\n # Show dataset name in progress bar label\n pbar.set_description(\"Loading {} from disk\".format(acqValue.name))\n\n # Allocate `AnalogData` object and use generated HDF5 file-name to manually\n # allocate a target dataset for reading the NWB data\n if container is not None:\n filename = filebase + \"_\" + acqValue.name + \".analog\"\n else:\n filename = None\n\n angData = AnalogData(dimord=AnalogData._defaultDimord, filename=filename)\n angShape = [None, None]\n angShape[angData.dimord.index(\"time\")] = acqValue.data.shape[0]\n angShape[angData.dimord.index(\"channel\")] = acqValue.data.shape[1]\n h5ang = h5py.File(angData.filename, mode=\"w\")\n angDset = h5ang.create_dataset(\"data\", dtype=np.result_type(*dTypes), shape=angShape)\n\n # If channel-specific gains are set, load them now\n if acqValue.channel_conversion is not None:\n gains = acqValue.channel_conversion[()]\n if np.all(gains == gains[0]):\n gains = gains[0]\n\n # Given memory cap, compute how many data blocks can be grabbed per swipe:\n # `nSamp` is the no. of samples that can be loaded into memory without exceeding `memuse`\n # `rem` is the no. of remaining samples, s. t. ``nSamp + rem = angDset.shape[0]`\n # `blockList` is a list of samples to load per swipe, i.e., `[nSamp, nSamp, ..., rem]`\n nSamp = int(memuse / (acqValue.data.shape[1] * angDset.dtype.itemsize))\n rem = int(angDset.shape[0] % nSamp)\n blockList = [nSamp] * int(angDset.shape[0] // nSamp) + [rem] * int(rem > 0)\n\n for m, M in enumerate(tqdm(blockList, desc=pbarDesc, position=1, leave=False, disable=None)):\n st_samp, end_samp = m * nSamp, m * nSamp + M\n angDset[st_samp : end_samp, :] = acqValue.data[st_samp : end_samp, :]\n if acqValue.channel_conversion is not None:\n angDset[st_samp : end_samp, :] *= gains\n\n # Finalize angData\n angData.data = angDset\n channels = acqValue.electrodes[:].location\n if channels.unique().size == 1:\n SPYWarning(\"No channel names found for {}\".format(acqName))\n angData.channel = None\n else:\n angData.channel = channels.to_list()\n angData.samplerate = sRates[0]\n angData.trialdefinition = trl\n angData.info = {'starting_time' : tStarts[0]}\n angData.log = log_msg\n objectDict[os.path.basename(angData.filename)] = angData\n\n return objectDict\n","sub_path":"syncopy/io/load_nwb.py","file_name":"load_nwb.py","file_ext":"py","file_size_in_byte":11592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"173371856","text":"import time\nimport numpy as np\nfrom metrics.edm import euclidean_distance_matrix\n\n\ndef euclidean_numpy(x, y):\n \"\"\"Euclidean square distance matrix.\n\n Inputs:\n x: (N,) numpy array\n y: (N,) numpy array\n\n Ouput:\n (N, N) Euclidean square distance matrix:\n r_ij = (x_ij - y_ij)^2\n \"\"\"\n\n x2 = np.einsum('ij,ij->i', x, x)[:, np.newaxis]\n y2 = np.einsum('ij,ij->i', y, y)[:, np.newaxis].T\n\n xy = x @ y.T\n\n return np.abs(x2 + y2 - 2. * xy)\n\n\nnsamples, nfeat = (12000, 50)\nx = 10. * np.random.random([nsamples, nfeat])\n\nstart = time.time()\nedm_f90 = euclidean_distance_matrix(x.T, x.T)\nprint(\"f90: %.2f seconds\" % (time.time() - start))\n\nstart = time.time()\nedm_np = euclidean_numpy(x, x)\nprint(\"numpy: %.2f seconds\" % (time.time() - start))\n\nprint('\\ndiff : %.2e'% np.abs(edm_f90 - edm_np).max())\n","sub_path":"f2py/distance-f90-pythonized/test_edm.py","file_name":"test_edm.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"643137555","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport csv\n\ndef helper(x, coeffCOS, coeffSIN):\n result = coeffCOS[0] / 2\n for i in range(1, len(coeffCOS)):\n result += (coeffCOS[i]*np.cos(i*x) + coeffSIN[i]*np.sin(i*x))\n return result\n\nstart = 0\nstop = 6\ndensity = 1000\n\ndata = \"results/results_\"\nextension = \".txt\"\npath = \"plots/\"\n\npoints = [5, 10, 20, 50, 100]\ndegrees = [4, 7, 10, 20]\nfileNames = [\"f1\", \"f2\"]\n\nfor kind in fileNames:\n if kind == \"f1\":\n originX = np.linspace(start, stop, num=density)\n originY = np.exp(np.cos(originX))\n if kind == \"f2\":\n originX = np.linspace(start, stop, num=density)\n originY = np.sin(originX) * np.exp(-originX/np.pi)\n for number in points:\n x = []\n y = []\n with open(data + kind + \"_\" + str(number) + extension,'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=' ')\n for row in plots:\n x.append(float(row[0]))\n y.append(float(row[1]))\n\n for degree in degrees:\n approximationX = np.linspace(start, stop, num=density)\n approximationY = []\n with open(data + kind + \"P_\" + str(number) + \"_\" + str(degree) + \"_COS\" + extension,'r') as csvfile:\n coeffsCOS = csvfile.readlines()\n coeffsCOS = [float(str(i[:-1])) for i in coeffsCOS]\n with open(data + kind + \"P_\" + str(number) + \"_\" + str(degree) + \"_SIN\" + extension,'r') as csvfile:\n coeffsSIN = csvfile.readlines()\n coeffsSIN = [float(str(i[:-1])) for i in coeffsSIN]\n for item in approximationX:\n approximationY.append(helper(item, coeffsCOS, coeffsSIN))\n\n print('.', end='', flush=True)\n plt.clf()\n\n plt.plot(originX, originY)\n plt.scatter(x, y)\n plt.plot(approximationX, approximationY)\n\n plt.title(str(kind) + \"| points: \" + str(number) + \" deg: \" + str(degree))\n plt.ylabel('y')\n plt.xlabel('x')\n plt.savefig(path + str(kind) + \"_\" + str(number) + \"_deg\" + str(degree) + \".png\")\n","sub_path":"lab5/trigonometric/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"116645997","text":"'''\nCreated on Nov 8, 2012\n\n@author: Wighton\n'''\n\nfrom pyglet.gl import *\nimport pyglet\nfrom pyglet.window import key\n\nclass Renderer(object):\n '''\n classdocs\n '''\n\n\n def __init__(self, w, h):\n self.width = w\n self.height = h\n self.sceneObjects = []\n \n \n def addSceneObject(self, object):\n self.sceneObjects.append(object)\n \n def setupEventHandlers(self):\n \n #Setup event handler for on draw\n @self.window.event\n def on_draw():\n self.draw() \n \n \n \n def setupOpenGL(self):\n '''\n Perform initial OpenGL setup\n \n This code from pyglet documentation\n '''\n \n try:\n # Try and create a window with multisampling (antialiasing)\n config = Config(sample_buffers = 1, samples = 4, \n depth_size=16, double_buffer = True,)\n \n #Create the window\n self.window = pyglet.window.Window(self.width, self.height, 'Motion Planner', \n resizable = True, config = config)\n \n except pyglet.window.NoSuchConfigException:\n #Multisampling\n self.window = pyglet.window.Window(resizable = True)\n \n \n # One-time GL setup\n glClearColor(217.0/255.0, 230.0/255.0, 237.0/255.0, 1)\n glColor3f(1, 0, 0)\n \n glViewport(0,0,self.width,self.height);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0,self.width,0,self.height,-100,100);\n glMatrixMode(GL_MODELVIEW);\n\n\n def start(self):\n self.setupOpenGL()\n self.setupEventHandlers()\n \n #kick off the pyglet view\n pyglet.app.run()\n \n \n \n def draw(self):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n \n #Setup the viewport\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0,self.width,0,self.height,-100,100);\n\n glMatrixMode(GL_MODELVIEW)\n\n for object in self.sceneObjects:\n object.draw()\n \n ","sub_path":"Renderer.py","file_name":"Renderer.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"248447873","text":"import sys\nimport random\nimport string\nfrom collections import defaultdict\n\ndef postprocessing(corpus_files):\n '''\n Removes the special characters from the parallel corpus \n obtained after reordering it. \n '''\n for corpus_file in corpus_files:\n data = []\n \n # Read from language corpus file \n with open(corpus_file, 'r') as inp:\n for index, line in enumerate(inp):\n if len(line) > 0:\n line = line.strip()\n data.append(line.translate(str.maketrans(\"\", \"\", string.punctuation)))\n data.append(\"\")\n \n # Update language corpus file \n with open(corpus_file, 'w') as f:\n f.write('\\n'.join(data))\n \n return\n\n\nif __name__ == \"__main__\":\n # Parameter checking \n if len(sys.argv) < 2:\n print(\"Usage: python postprocess.py [file_path(s)]\")\n sys.exit(0)\n \n postprocessing(sys.argv[1:])\n","sub_path":"src/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"490024860","text":"import logging\r\nimport os\r\nfrom environment.config import *\r\nfrom timeit import default_timer as timer\r\nfrom environment.pyhard_config import pyhard_config\r\nfrom sklearn.model_selection import train_test_split\r\nimport numpy as np\r\nfrom modAL.models import ActiveLearner\r\nfrom environment.which_classifier import which_classifier\r\nfrom modAL.uncertainty import uncertainty_sampling\r\nfrom environment.compute_f1 import compute_f1\r\nimport pandas as pd\r\nfrom pathlib import Path\r\nfrom math import floor\r\n\r\nfrom pyhard.measures import ClassificationMeasures\r\nfrom modAL.uncertainty import classifier_uncertainty\r\n\r\ndef pyhard_framework(X_raw, y_raw, idx_data, idx_bag, classifier, init_size, cost, strategy):\r\n\r\n sample_size = 0 # contador de amostras utilizadas pela estratégia\r\n accuracy_history = []\r\n f1_history = []\r\n start = timer()\r\n\r\n strategy = pyhard_config(strategy)\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(X_raw[idx_data[idx_bag][TRAIN]],\r\n y_raw[idx_data[idx_bag][TRAIN]],\r\n train_size=floor(len(X_raw[idx_data[idx_bag][TRAIN]]) * 0.10),\r\n stratify=y_raw[idx_data[idx_bag][TRAIN]],\r\n random_state=1)\r\n\r\n sample_size = sample_size + len(X_train)\r\n\r\n learner = ActiveLearner(\r\n estimator=which_classifier(classifier),\r\n query_strategy=uncertainty_sampling,\r\n X_training=X_train, y_training=y_train\r\n )\r\n\r\n accuracy_history.append(learner.score(X_raw[idx_data[idx_bag][TEST]], y_raw[idx_data[idx_bag][TEST]]))\r\n f1_history.append(compute_f1(learner, X_test, y_test, \"weighted\"))\r\n\r\n X_pool = X_raw[idx_data[idx_bag][TRAIN]] # Resolve o problema de reposição do loop\r\n y_pool = y_raw[idx_data[idx_bag][TRAIN]] # Resolve o problema de reposição do loop\r\n len_x_pool = int(floor(len(X_raw[idx_data[idx_bag][TRAIN]])*0.05))\r\n\r\n for i in range(cost):\r\n try:\r\n X_train, X_pool, y_train, y_pool = train_test_split(X_pool, y_pool, train_size=len_x_pool)\r\n\r\n pred = learner.predict(X_train)\r\n\r\n path_to_bag_files = (Path('.') / 'strategies' / 'pyHard' / 'pyhard_files' / strategy['measure'] / str(\r\n 'bag_' + str(idx_bag)))\r\n\r\n X_rawAndY_raw = np.column_stack([X_train, pred])\r\n np.savetxt(str(path_to_bag_files / 'data.csv'), X_rawAndY_raw, fmt='%i', delimiter=\",\")\r\n\r\n os.system('pyhard --no-isa -c ' + str(path_to_bag_files / 'config.yaml'))\r\n except Exception as e:\r\n print(e)\r\n\r\n else:\r\n df = pd.read_csv(path_to_bag_files /'metadata.csv')\r\n\r\n idx = list(df.sort_values(by=strategy['sortby'], ascending=strategy['ascending'])['instances'][:cost]) #pega as `cost` primeiras amostras (talvez precise mudar pra algo relacionado ao init size ou criar alguma funcao nova)\r\n\r\n X_train = X_train[idx] # ORACULO RECEBE\r\n y_train = y_train[idx] # ORACULO ROTULOU\r\n\r\n sample_size = sample_size + len_x_pool\r\n learner.teach(X_train, y_train)\r\n\r\n accuracy_history.append(learner.score(X_raw[idx_data[idx_bag][TEST]], y_raw[idx_data[idx_bag][TEST]]))\r\n f1_history.append(compute_f1(learner, X_test, y_test, \"weighted\"))\r\n\r\n end = timer()\r\n time_elapsed = end - start\r\n\r\n return {\"accuracy_history\": accuracy_history,\r\n \"f1_history\": f1_history,\r\n \"package\": \"Pyhard\",\r\n \"id_bag\": idx_bag,\r\n \"time_elapsed\": time_elapsed,\r\n \"classifier\": classifier,\r\n \"sample_size\": sample_size / len(X_raw[idx_data[idx_bag][TRAIN]]),\r\n \"strategy\": strategy['name']}\r\n","sub_path":"ALIH/strategies/pyHard/pyhard_framework.py","file_name":"pyhard_framework.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569722933","text":"# odometry.py\r\n#\r\n# skeleton code for University of Michigan ROB550 Botlab\r\n#\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n# \r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n# \r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see .\r\n\r\nimport sys, os, time\r\nimport lcm\r\nfrom math import *\r\n\r\nfrom breezyslam.robots import WheeledRobot\r\n\r\nfrom lcmtypes import maebot_motor_feedback_t\r\nfrom lcmtypes import maebot_sensor_data_t\r\nfrom lcmtypes import odo_pose_xyt_t\r\nfrom lcmtypes import odo_dxdtheta_t\r\n\r\nclass Maebot(WheeledRobot):\r\n \r\n def __init__(self):\r\n self.wheelDiameterMillimeters = 32.0 # diameter of wheels [mm]\r\n self.axleLengthMillimeters = 80.0 # separation of wheels [mm] \r\n self.ticksPerRev = 16.0 # encoder tickers per motor revolution\r\n self.gearRatio = 30.0 # 30:1 gear ratio\r\n self.enc2mm = (pi * self.wheelDiameterMillimeters) / (self.gearRatio * self.ticksPerRev) # encoder ticks to distance [mm]\r\n\r\n self.prevEncPos = (0,0,0) # store previous readings for odometry\r\n self.prevOdoPos = (0,0,0) # store previous x [mm], y [mm], theta [rad]\r\n self.currEncPos = (0,0,0) # current reading for odometry\r\n self.currOdoPos = (0,0,0) # store odometry x [mm], y [mm], theta [rad]\r\n self.currOdoVel = (0,0,0) # store current velocity dxy [mm], dtheta [rad], dt [s]\r\n WheeledRobot.__init__(self, self.wheelDiameterMillimeters/2.0, self.axleLengthMillimeters/2.0)\r\n\r\n # LCM Initialization and Subscription\r\n self.lc = lcm.LCM()\r\n lcmMotorSub = self.lc.subscribe(\"MAEBOT_MOTOR_FEEDBACK\", self.motorFeedbackHandler)\r\n lcmSensorSub = self.lc.subscribe(\"MAEBOT_SENSOR_DATA\", self.sensorDataHandler)\r\n \r\n self.lcm_msg_counter = [0, 0]\r\n \r\n def calcVelocities(self):\r\n # IMPLEMENT ME\r\n # TASK: CALCULATE VELOCITIES FOR ODOMETRY\r\n # Update self.currOdoVel and self.prevOdoVel\r\n rclf.currOdoVel = (dxy, dtheta, dt)\r\n\r\n def getVelocities(self):\r\n # IMPLEMENT ME\r\n # TASK: RETURNS VELOCITY TUPLE\r\n # Return a tuple of (dxy [mm], dtheta [rad], dt [s])\r\n return (dxy, dtheta, dt) # [mm], [rad], [s]\r\n\r\n def calcOdoPosition(self):\r\n # IMPLEMENT ME\r\n # TASK: CALCULATE POSITIONS\r\n # Update self.currOdoPos and self.prevOdoPos\r\n self.prevOdoPos = self.currOdoPos\r\n\r\n def getOdoPosition(self):\r\n # IMPLEMENT ME\r\n # TASK: RETURNS POSITION TUPLE\r\n # Return a tuple of (x [mm], y [mm], theta [rad])\r\n return (x, y, theta) # [mm], [rad], [s]\r\n\r\n# def publishOdometry(self):\r\n # IMPLEMENT ME\r\n # TASK: PUBLISHES BOT_ODO_POSE MESSAGE\r\n \r\n# def publishVelocities(self):\r\n # IMPLEMENT ME\r\n # TASK: PUBLISHES BOT_ODO_VEL MESSAGE\r\n\r\n def motorFeedbackHandler(self,channel,data):\r\n msg = maebot_motor_feedback_t.decode(data)\r\n # IMPLEMENT ME\r\n # TASK: PROCESS ENCODER DATA\r\n # get encoder positions and store them in robot,\r\n # update robots position and velocity estimate\r\n self.lcm_msg_counter[0] = self.lcm_msg_counter[0] + 1\r\n\r\n def sensorDataHandler(self,channel,data):\r\n msg = maebot_sensor_data_t.decode(data)\r\n # IMPLEMENT ME\r\n # TASK: PROCESS GYRO DATA\r\n self.lcm_msg_counter[1] = self.lcm_msg_counter[1] + 1\r\n\r\n def MainLoop(self):\r\n oldTime = time.time()\r\n frequency = 20;\r\n while(1):\r\n self.lc.handle()\r\n if(self.lcm_msg_counter[0] * self.lcm_msg_counter[1] > 0):\r\n #self.publishOdometry()\r\n #self.publishVelocities()\r\n oldTime = time.time()\r\n self.lcm_msg_counter[0] = self.lcm_msg_counter[0] - 1\r\n self.lcm_msg_counter[1] = self.lcm_msg_counter[1] - 1\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n robot = Maebot()\r\n robot.MainLoop() \r\n","sub_path":"Project1-Localization-&-Mapping-Using-Autonomous-Mobile-Robotled folder/src/botlab/odometry_counter.py","file_name":"odometry_counter.py","file_ext":"py","file_size_in_byte":4226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"319970948","text":"\"\"\" Keras loss functions will choke on NaN inputs, which we'll often have for\nunspecified inputs. These are just a couple simple loss functions that mask NaN\nvalues in both the test and predicted tensors when computing the cost. \"\"\"\n\nimport keras.backend as K\nimport tensorflow as tf\n\ndef masked_mean_squared_error(y_true, y_pred):\n mask = tf.is_finite(y_true)\n y_true_mask = tf.boolean_mask(y_true, mask)\n y_pred_mask = tf.boolean_mask(y_pred, mask)\n return K.mean(K.square(y_pred_mask - y_true_mask), axis=-1)\n\n\ndef masked_mean_absolute_error(y_true, y_pred):\n mask = tf.is_finite(y_true)\n y_true_mask = tf.boolean_mask(y_true, mask)\n y_pred_mask = tf.boolean_mask(y_pred, mask)\n return K.mean(K.abs(y_pred_mask - y_true_mask), axis=-1)\n","sub_path":"code/predicting_model/nfp/models/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"568966006","text":"import pygame\nimport time\nfrom pygame.locals import *\nfrom Particle import Particle\n\nclass ParticleEmitter():\n \"\"\"Emites a particle on a predefined interval.\"\"\"\n def __init__(self, screen_width, screen_height, x_col, y_pos, particles, emit_time_in_sec = 1):\n \"\"\"Constructor for ParticleEmitter class\n Arguments:\n screen_width: the width of the surface to blit to in pixels\n screen_height: the height of the surface to blit to in pixels\n x_pos: the x position to start in\n y_pos: the initial y position\n particles: the particles group to add the emitted particle to\n emit_time_in_sec: the interval (in seconds) to emit a new particle on. optional.\n \"\"\"\n self.last_emit_time = time.time()\n self.emit_time_in_sec = emit_time_in_sec\n self.screen_width = screen_width\n self.screen_height = screen_height\n self.x_col = x_col\n self.y_pos = y_pos\n self.particles = particles\n self._emit_particle()\n\n\n def _emit_particle(self):\n particle = Particle(self.screen_width, self.screen_height, self.x_col, self.y_pos)\n self.particles.add(particle)\n\n def update(self):\n if time.time() - self.last_emit_time > self.emit_time_in_sec:\n self._emit_particle()\n self.last_emit_time = time.time()\n","sub_path":"particle_emitter.py","file_name":"particle_emitter.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"411762088","text":"import math\ndef quadratic_equation(a, b, c):\n de=b**2-4*a*c\n if de>=0: \n x1=(-b+math.sqrt(de))/(2*a)\n x2=(-b-math.sqrt(de))/(2*a)\n return x1,x2\n else: \n return\nprint (quadratic_equation(2, 3, 0))\nprint (quadratic_equation(1, -6, 5))\n\nimport tensorflow as tf\na = tf.placeholder(tf.int16)\nb = tf.placeholder(tf.int16)\nadd = tf.add(a, b)\nmul = tf.multiply(a, b)\nwith tf.Session() as sess:\n # Run every operation with variable input\n\tprint (\"Addition with variables: %i\" % sess.run(add, feed_dict={a: 2, b: 3}))\n\tprint (\"Multiplication with variables: %i\" % sess.run(mul, feed_dict={a: 2, b: 3}))\n\t\nmatrix1 = tf.constant([[3., 3.]])\nmatrix2 = tf.constant([[2.],[2.]])\nproduct=tf.matmul(matrix1,matrix2)\nwith tf.Session() as sess:\n result = sess.run(product)\n print (result)","sub_path":"testpython.py","file_name":"testpython.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"613532674","text":"\"\"\"Adds voice channels category\n\nRevision ID: e3ab9447b076\nRevises: 311f7bbcdf77\nCreate Date: 2020-10-12 16:06:46.843494\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"e3ab9447b076\"\ndown_revision = \"311f7bbcdf77\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n with op.batch_alter_table(\"servers\") as b:\n b.add_column(sa.Column(\"voice_category_xid\", sa.BigInteger(), nullable=True))\n\n\ndef downgrade():\n with op.batch_alter_table(\"servers\") as b:\n b.drop_column(\"voice_category_xid\")\n","sub_path":"src/spellbot/versions/versions/e3ab9447b076_adds_voice_channels_category.py","file_name":"e3ab9447b076_adds_voice_channels_category.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"470116416","text":"#!/usr/bin/python\nimport json\nfrom util.field import Field\n\nclass Schema:\n schema_name = \"None\"\n parsable_fields = []\n additional_fields = []\n enums = None\n\n def __init__(self, schema_json):\n schema_dict = json.loads(schema_json)\n\n self.schema_name = schema_dict[\"name\"]\n pf = schema_dict[\"parsable_fields\"]\n for key, value in pf.items():\n field = Field(key, value)\n self.parsable_fields.append(field)\n\n af = schema_dict[\"additional_fields\"]\n for key, value in pf.items():\n field = Field(key, value)\n self.additional_fields.append(field)\n\n @staticmethod\n def debug_print(schema):\n print(\"Schema Name: \" + schema.schema_name)\n print(\"Parsable Fields:\\n\")\n for item in schema.parsable_fields:\n Field.debug_print(item)\n\n print(\"Additional Fields:\\n\")\n for item in schema.additional_fields:\n Field.debug_print(item)\n","sub_path":"src/util/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"447592123","text":"\n\ndef traverse_path(world):\n # Bring in length of rooms\n num_rooms = len(world.rooms)\n # print(num_rooms)\n # Create return path for later\n return_path = []\n # Create visited set to store all visited rooms\n visited = set()\n\n # Initiate starting room cases (add to visited and return_path)\n current_room = world.startingRoom\n # print(current_room)\n visited.add(current_room)\n return_path.append(current_room)\n # print(len(visited))\n\n # Loop while we haven't found all rooms\n # Two loops. Outer loop for adding the initial 4 rooms, and the inner loop for traversing the paths of those 4 rooms\n while(len(visited) < num_rooms):\n\n # Check all directions to see if they exist in your current room (if statements)\n connected_rooms = []\n if current_room.n_to:\n connected_rooms.append(current_room.n_to)\n if current_room.s_to:\n connected_rooms.append(current_room.s_to)\n if current_room.e_to:\n connected_rooms.append(current_room.e_to)\n if current_room.w_to:\n connected_rooms.append(current_room.w_to)\n # Set this up for next loop. If all rooms are explored, then that means this is last room\n unexplored_connected_rooms = False\n # print(f'Connected Rooms:{connected_rooms}')\n\n # Loop through all connections and if there is a direction and it isn't in visited, then tag it as unexplored. Otherwise, remove it\n for c in connected_rooms:\n if c not in visited:\n unexplored_connected_rooms = True\n else:\n connected_rooms.remove(c)\n\n # Check all unexplored rooms in the connected_rooms list, add them to visited and return path, then set them to false.\n while unexplored_connected_rooms == True:\n current_room = connected_rooms[0]\n # print(current_room)\n visited.add(current_room)\n return_path.append(current_room)\n # Loop through this room's potential directions like I did above\n connected_rooms = []\n if current_room.n_to:\n connected_rooms.append(current_room.n_to)\n if current_room.s_to:\n connected_rooms.append(current_room.s_to)\n if current_room.e_to:\n connected_rooms.append(current_room.e_to)\n if current_room.w_to:\n connected_rooms.append(current_room.w_to)\n\n unexplored_connected_rooms = False\n\n # Recheck the rooms. This should remove the room we just traversed\n for c in connected_rooms:\n if c not in visited:\n unexplored_connected_rooms = True\n else:\n connected_rooms.remove(c)\n\n # Update path with this loop's iteration of current room\n new_path = bfs(current_room, visited)\n current_room = new_path[-1]\n visited.add(current_room)\n # Append it to path up above\n # print(f'RETURN PATH:{return_path}')\n return_path += new_path\n\n # return path is full of objects. need to loop through and spit out directions based on return_path[i] and return_path[i+1]\n final_path = []\n for i in range(0, len(return_path)-1):\n # print(return_path[i])\n if return_path[i].n_to == return_path[i+1]:\n final_path.append(\"n\")\n if return_path[i].s_to == return_path[i+1]:\n final_path.append(\"s\")\n if return_path[i].e_to == return_path[i+1]:\n final_path.append(\"e\")\n if return_path[i].w_to == return_path[i+1]:\n final_path.append(\"w\")\n\n print(f'FINAL PATH:{final_path}')\n return final_path\n\n\ndef bfs(room, visited_rooms):\n # print(visited_rooms)\n visited = set()\n queue = [[room]]\n\n while queue:\n path = queue.pop()\n vertex = path[-1]\n\n # print(f'VERTEX ID:{vertex.id}')\n\n if vertex.id not in visited:\n if vertex not in visited_rooms:\n # Slice the first element of path off\n return path[1:]\n visited.add(vertex.id)\n\n connected_rooms = []\n # If direction exists AND the id isnt in visited, then add to the list.\n if vertex.n_to and vertex.n_to.id not in visited:\n connected_rooms.append(vertex.n_to)\n if vertex.e_to and vertex.e_to.id not in visited:\n connected_rooms.append(vertex.e_to)\n if vertex.s_to and vertex.s_to.id not in visited:\n connected_rooms.append(vertex.s_to)\n if vertex.w_to and vertex.w_to.id not in visited:\n connected_rooms.append(vertex.w_to)\n for r in connected_rooms:\n new_path = list(path)\n new_path.append(r)\n queue.insert(0, new_path)\n","sub_path":"projects/adventure/traverse_path.py","file_name":"traverse_path.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"585136981","text":"#!/usr/bin/env python\n\"\"\"\nTest runner for those who have no nose.\n\"\"\"\nimport unittest\n\n\nTEST_MODULES = (\n 'tests.benchmark-tests',\n 'tests.doctests',\n 'tests.functional-tests'\n)\n\ndef main():\n from optparse import OptionParser\n\n usage = \"Usage: %prog [options]\"\n parser = OptionParser(usage=usage)\n parser.add_option(\n \"-b\", \"--benchmark\", dest=\"benchmark\",\n help=\"perform benchmarks\", action='store_true',\n default=False\n )\n parser.add_option(\n \"--mysql-engine\", dest='mysql_engine',\n help=\"specify mysql engine to use, can be 'MyISAM' \" \\\n \"(default) or 'InnoDB'\",\n default='MyISAM'\n )\n parser.add_option(\n \"-e\", \"--echo\", dest='echo', action='store_true',\n help=\"enable sqlalchemy debug output to stdout\",\n default=False\n )\n parser.add_option(\n \"-q\", \"--quiet\", dest=\"quiet\", action=\"store_true\",\n help=\"do not print progress information\",\n default=False\n )\n\n (options, args) = parser.parse_args()\n if len(args) != 1:\n parser.error('specify database connection string ' \\\n '(for example, \"sqlite://\")')\n\n [db_uri] = args\n import os\n os.environ['DB_URI'] = db_uri\n if options.echo:\n os.environ['ECHO'] = '1'\n if options.benchmark:\n os.environ['BENCHMARK'] = '1'\n os.environ['MYSQL_ENGINE'] = options.mysql_engine\n\n # checking imports\n import sqlalchemy\n import sqlamp\n import tests._testlib\n\n if options.quiet:\n verbosity = 0\n else:\n verbosity = 2\n unittest.TextTestRunner(verbosity=verbosity).run(get_suite())\n\n\ndef get_suite():\n suite = unittest.TestSuite()\n for test_module_name in TEST_MODULES:\n module = __import__(test_module_name, {}, {}, ['get_suite'])\n suite.addTest(module.get_suite())\n return suite\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"tests/run-all.py","file_name":"run-all.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"368489508","text":"import logging\nfrom optparse import make_option\nfrom django.db import transaction, connections, DEFAULT_DB_ALIAS\nfrom django.core.management.base import BaseCommand\nfrom vdw.variants.models import Transcript, VariantEffect\nfrom vdw.variants.pipeline.utils import EffectStream\nfrom vdw.pipeline.load import pgcopy_batch\n\nlog = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n option_list = BaseCommand.option_list + (\n make_option('--database', action='store', dest='database',\n default=DEFAULT_DB_ALIAS,\n help='Nominates a database to print the SQL for. Defaults '\n 'to the \"default\" database.'),\n\n make_option('--transcripts', action='store_true', default=False,\n help='Causes the transcript table to be truncated prior '\n 'to reloading.'),\n\n make_option('--stdout', action='store_true', default=False,\n help='Writes the stream to stdout rather than to the '\n 'database'),\n )\n\n def handle(self, path, **options):\n database = options.get('database')\n transripts = options.get('transripts')\n stdout = options.get('stdout')\n\n with open(path) as fin:\n stream = EffectStream(fin, skip_existing=False)\n\n if stdout:\n while True:\n line = stream.readline()\n if line == '':\n break\n log.debug(line)\n else:\n cursor = connections[database].cursor()\n\n with transaction.commit_manually(database):\n try:\n cursor.execute('TRUNCATE {0}'.format(\n VariantEffect._meta.db_table))\n if transripts:\n cursor.execute('TRUNCATE {0} CASCADE'.format(\n Transcript._meta.db_table))\n columns = stream.output_columns\n db_table = VariantEffect._meta.db_table\n pgcopy_batch(stream, db_table, columns, cursor,\n database)\n\n transaction.commit(database)\n except Exception as e:\n transaction.rollback(database)\n log.exception(e)\n raise\n","sub_path":"vdw/variants/management/subcommands/reload_snpeff.py","file_name":"reload_snpeff.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"115733111","text":"import sys \r\nfrom PyQt5 import QtGui, uic\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import *\r\n\r\n\r\nui_path = r\"34. 그림판 만들기(PYQT)\\그림판.ui\"\r\nform_class = uic.loadUiType(ui_path)[0] \r\n\r\n\r\nclass WindowClass(QMainWindow, form_class) : \r\n def __init__(self) :\r\n super().__init__()\r\n self.setupUi(self)\r\n\r\n self.brushColor = Qt.black \r\n\r\n self.canvas = QtGui.QPixmap(self.lb_canvas.width(), self.lb_canvas.height()) \r\n self.canvas.fill(QtGui.QColor(\"white\")) \r\n self.lb_canvas.setPixmap(self.canvas)\r\n\r\n self.btn_black.clicked.connect(self.btn_clicked) \r\n self.btn_black.setStyleSheet('background:black')\r\n\r\n self.btn_red.clicked.connect(self.btn_clicked)\r\n self.btn_red.setStyleSheet('background:red')\r\n\r\n self.btn_blue.clicked.connect(self.btn_clicked)\r\n self.btn_blue.setStyleSheet('background:blue')\r\n\r\n self.btn_clear.clicked.connect(self.btn_clear_clicked) \r\n \r\n def btn_clicked(self):\r\n btn_value = self.sender().objectName()\r\n print(btn_value)\r\n if btn_value == 'btn_black':\r\n self.brushColor = Qt.black\r\n elif btn_value == 'btn_red':\r\n self.brushColor = Qt.red\r\n elif btn_value == 'btn_blue':\r\n self.brushColor = Qt.blue\r\n \r\n def btn_clear_clicked(self):\r\n print(\"모두지움\")\r\n self.canvas.fill(QtGui.QColor(\"white\"))\r\n self.lb_canvas.setPixmap(self.canvas)\r\n\r\n def mouseMoveEvent(self, e):\r\n painter = QtGui.QPainter(self.lb_canvas.pixmap())\r\n painter.setPen(QPen(self.brushColor, 5, Qt.SolidLine, Qt.RoundCap)) \r\n painter.drawPoint(e.x(), e.y())\r\n painter.end()\r\n self.update()\r\n\r\nif __name__ == \"__main__\" :\r\n app = QApplication(sys.argv) \r\n myWindow = WindowClass() \r\n myWindow.show() \r\n app.exec_()","sub_path":"파이썬과 40개의 작품들/34. 그림판 만들기(PYQT)/main34-3.py","file_name":"main34-3.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"464195914","text":"import tensorflow as tf\nimport numpy as np\nimport math\nimport sys\nimport glob\nimport os\nimport time\n#np.set_printoptions(threshold = 1e6)\nfrom PhoneClassifer import phone_classifer\nfrom utils.load_data import get_data,default_config,phns,get_data_onebyone\nfrom LOAD_SAVE_PARAMS.LOAD_SAVE_PARAMS import save_weight,load_weight\n\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\n\nconfig = ConfigProto()\n\nconfig.gpu_options.allow_growth = True\nsession = InteractiveSession(config=config)\ntf.compat.v1.keras.backend.set_session(session)\ntf.compat.v1.keras.backend.clear_session()\n\n\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '/gpu:0'\nnp.random.seed(1)\ndef train(model,params,batch_size):\n acc=[]\n wav_files_list = glob.glob(default_config[\"data_path_phcls_test\"])\n #print(wav_files_list)\n iter_data=get_data_onebyone(wav_files_list,batch_size,False)#get_data(wav_files_list,batch_size,data_augment=False)#二分类开这个会无法收敛\n los=[]\n for x,y in iter_data:\n e_start=time.time()\n \n X=tf.concat(x,0)\n \n y=[tf.cast(y1,dtype=tf.float32) for y1 in y]\n\n y_hard=y.copy()\n\n y_hard=tf.one_hot(y_hard,int(len(phns)))\n \n Y_hard=tf.concat(y_hard,0)\n \n X=tf.cast(X,dtype=tf.float32)\n \n Y_hard=tf.cast(Y_hard,dtype=tf.float32)\n\n logits,ppgs,preds=model(X,dropout_rate=0.0)\n loss=model.loss_sigmoid(logits,Y_hard)\n \n print(\"loss:%f\"%loss)\n los.append(loss)\n \n\n ac=return_accuracy(Y_hard,ppgs)\n print(\"训练准确率:%f\"%ac)\n acc.append(ac)\n e_end=time.time()\n print(\"一次耗时%f秒\"%(e_end-e_start))\n \n \n filepath=\"test_acc.txt\"\n flie=open(filepath,\"a+\")\n \n flie.write(str(tf.math.reduce_mean(acc).numpy())+\"\\n\")\n flie.close()\n\n \n\n filepath=\"test_loss.txt\"\n flie=open(filepath,\"a+\")\n \n flie.write(str(tf.math.reduce_mean(los).numpy())+\"\\n\")\n flie.close()\n \n\n \ndef return_accuracy(Y,Y_pre):\n num=Y.shape[0]*Y.shape[1]\n \n rowMaxSoft=np.argmax(Y_pre, axis=-1)+1\n rowMax=np.argmax(Y, axis=-1)+1\n \n rowMaxSoft=rowMaxSoft.reshape([1,-1])\n rowMax=rowMax.reshape([1,-1])\n \n nonO=rowMaxSoft-rowMax\n \n exist = (nonO != 0) * 1.0\n factor = np.ones([nonO.shape[1],1])\n res = np.dot(exist, factor)\n \n accuracy=(float(num)-res[0][0])/float(num)\n \n return accuracy\n \nif __name__ == \"__main__\":\n \n batch_size=1\n\n input_nums=default_config[\"n_mfcc\"]\n\n num_hiddens=512#default_config[\"hidden_units\"]\n\n num_outputs=default_config[\"n_mfcc\"]\n\n layer_nums=12\n\n multi_head=12\n \n max_position_dim=1024\n\n clip_norm=1.0\n #lr=1e-5#5e-6\n model=phone_classifer(lr=1e-5,input_nums=input_nums,hidden_nums=num_hiddens,output_nums=num_outputs,max_position_dim=max_position_dim,layers_encoder=layer_nums,labels_num=len(phns),multi_head=multi_head)\n\n params=model.get_params()+model.get_params_vc()\n \n #params=model.get_params_bert_position()+model.get_params_bert_layer()+model.get_params_vc()\n\n epochs=3000\n\n isContinue=True\n\n if isContinue==True:\n load_weight(\"ckp\",\"params_pc\",params)\n\n\n for i in range(epochs):\n with tf.device('/gpu:0'):\n train(model,params,batch_size)\n","sub_path":"test_phone_classifier.py","file_name":"test_phone_classifier.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"342332287","text":"#!/usr/bin/env /home/psapir/anaconda3/bin/python3.6\n# -*- coding: iso-8859-15 -*-\n\nimport sys\nsys.path.append('/home/psapir/prog/msm/lib')\nfrom simlib import simulate, gaussian, potential\nimport numpy as np\nimport pyemma\n\n\n# CL arguments\nm_val = float(sys.argv[1])\nnum_steps = int(sys.argv[2])\ndt = float(sys.argv[3])\nnum_clusters = int(sys.argv[4])\n\n# Potential parameters\ng1 = gaussian(np.ones(1),\n np.array([-m_val]),\n np.array([3]))\ng2 = gaussian(np.ones(1),\n np.array([+m_val]),\n np.array([3]))\nU = potential([g1, g2])\n\n# Simulation Parameters\nparameters = {\n 'name': 'kramers_test',\n 'num_steps': num_steps,\n 'num_dim': 1,\n 'num_particles': 1,\n 'KBT': 1,\n 'Ddt': 0.001,\n 'x0': -m_val,\n 'potential': U\n}\n\n# Simulation\nprint('Simulating')\nxs = simulate(parameters).flatten()\n\n# Clustering\nprint('Clustering')\ncluster = pyemma.coordinates.cluster_kmeans(xs, k=num_clusters, max_iter=50)\n\n# ITS\nprint('Calculating ITS')\nits = pyemma.msm.its(cluster.dtrajs, lags=np.linspace(1, 10000, 10).astype(int), nits=1, errors='bayes')\n\n# MSM\nLAG = 5000\nprint('Calculating MSM')\nbayesian_msm = pyemma.msm.bayesian_markov_model(cluster.dtrajs, lag=LAG, conf=0.95)\nsample_mean = bayesian_msm.sample_mean('timescales', k=1)\nsample_conf_l, sample_conf_r = bayesian_msm.sample_conf('timescales', k=1)\n\n# Save data\nwith open('data/kr2_{:0.2f}.data'.format(m_val), 'w') as f:\n f.write('{} {} {} {}\\n'.format(m_val, sample_mean[0]*dt, sample_conf_l[0]*dt, sample_conf_r[0]*dt))\nprint('Done.')\n","sub_path":"simulations/validations/kramers/kramers.py","file_name":"kramers.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"221282968","text":"#\n# Functions for interacting with the pcus table in the database\n#\n# Mark Huang \n# Copyright (C) 2006 The Trustees of Princeton University\n#\n\nfrom PLC.Faults import *\nfrom PLC.Parameter import Parameter\nfrom PLC.Filter import Filter\nfrom PLC.Debug import profile\nfrom PLC.Table import Row, Table\nfrom PLC.Interfaces import valid_ip, Interface, Interfaces\nfrom PLC.Nodes import Node, Nodes\n\nclass PCU(Row):\n \"\"\"\n Representation of a row in the pcus table. To use,\n instantiate with a dict of values.\n \"\"\"\n\n table_name = 'pcus'\n primary_key = 'pcu_id'\n join_tables = ['pcu_node']\n fields = {\n 'pcu_id': Parameter(int, \"PCU identifier\"),\n 'site_id': Parameter(int, \"Identifier of site where PCU is located\"),\n 'hostname': Parameter(str, \"PCU hostname\", max = 254),\n 'ip': Parameter(str, \"PCU IP address\", max = 254),\n 'protocol': Parameter(str, \"PCU protocol, e.g. ssh, https, telnet\", max = 16, nullok = True),\n 'username': Parameter(str, \"PCU username\", max = 254, nullok = True),\n 'password': Parameter(str, \"PCU username\", max = 254, nullok = True),\n 'notes': Parameter(str, \"Miscellaneous notes\", max = 254, nullok = True),\n 'model': Parameter(str, \"PCU model string\", max = 32, nullok = True),\n 'node_ids': Parameter([int], \"List of nodes that this PCU controls\"),\n 'ports': Parameter([int], \"List of the port numbers that each node is connected to\"),\n 'last_updated': Parameter(int, \"Date and time when node entry was created\", ro = True),\n }\n\n def validate_ip(self, ip):\n if not valid_ip(ip):\n raise PLCInvalidArgument(\"Invalid IP address \" + ip)\n return ip\n\n validate_last_updated = Row.validate_timestamp\n\n def update_timestamp(self, col_name, commit = True):\n \"\"\"\n Update col_name field with current time\n \"\"\"\n\n assert 'pcu_id' in self\n assert self.table_name\n\n self.api.db.do(\"UPDATE %s SET %s = CURRENT_TIMESTAMP \" % (self.table_name, col_name) + \\\n \" where pcu_id = %d\" % (self['pcu_id']) )\n self.sync(commit)\n\n def update_last_updated(self, commit = True):\n self.update_timestamp('last_updated', commit)\n\n def add_node(self, node, port, commit = True):\n \"\"\"\n Add node to existing PCU.\n \"\"\"\n\n assert 'pcu_id' in self\n assert isinstance(node, Node)\n assert isinstance(port, int)\n assert 'node_id' in node\n\n pcu_id = self['pcu_id']\n node_id = node['node_id']\n\n if node_id not in self['node_ids'] and port not in self['ports']:\n self.api.db.do(\"INSERT INTO pcu_node (pcu_id, node_id, port)\" \\\n \" VALUES(%(pcu_id)d, %(node_id)d, %(port)d)\",\n locals())\n\n if commit:\n self.api.db.commit()\n\n self['node_ids'].append(node_id)\n self['ports'].append(port)\n\n def remove_node(self, node, commit = True):\n \"\"\"\n Remove node from existing PCU.\n \"\"\"\n\n assert 'pcu_id' in self\n assert isinstance(node, Node)\n assert 'node_id' in node\n\n pcu_id = self['pcu_id']\n node_id = node['node_id']\n\n if node_id in self['node_ids']:\n i = self['node_ids'].index(node_id)\n port = self['ports'][i]\n\n self.api.db.do(\"DELETE FROM pcu_node\" \\\n \" WHERE pcu_id = %(pcu_id)d\" \\\n \" AND node_id = %(node_id)d\",\n locals())\n\n if commit:\n self.api.db.commit()\n\n self['node_ids'].remove(node_id)\n self['ports'].remove(port)\n\nclass PCUs(Table):\n \"\"\"\n Representation of row(s) from the pcus table in the\n database.\n \"\"\"\n\n def __init__(self, api, pcu_filter = None, columns = None):\n Table.__init__(self, api, PCU, columns)\n\n sql = \"SELECT %s FROM view_pcus WHERE True\" % \\\n \", \".join(self.columns)\n\n if pcu_filter is not None:\n if isinstance(pcu_filter, (list, tuple, set, int)):\n pcu_filter = Filter(PCU.fields, {'pcu_id': pcu_filter})\n elif isinstance(pcu_filter, dict):\n pcu_filter = Filter(PCU.fields, pcu_filter)\n else:\n raise PLCInvalidArgument(\"Wrong pcu filter %r\"%pcu_filter)\n sql += \" AND (%s) %s\" % pcu_filter.sql(api)\n\n self.selectall(sql)\n","sub_path":"PLC/PCUs.py","file_name":"PCUs.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"61616363","text":"import calendar\nimport json\nimport time\nimport unittest\nimport urllib\nfrom urlparse import urlparse, urlunparse\n\nimport requests\nimport websocket\nfrom django.conf import settings\nfrom cla_common.address_lookup.ordnance_survey import AddressLookup\n\n\ndef unix_timestamp():\n return calendar.timegm(time.gmtime())\n\n\nclass SmokeTests(unittest.TestCase):\n def test_can_access_backend(self):\n \"access the backend\"\n requests.get(settings.BACKEND_BASE_URI + \"/status.json\")\n\n def test_can_lookup_postcode(self):\n \"\"\"Lookup a postcode with OS Places\"\"\"\n postcode_to_lookup = \"SW1A 1AA\"\n key = settings.OS_PLACES_API_KEY\n addresses = AddressLookup(key=key).by_postcode(postcode_to_lookup)\n self.assertGreater(len(addresses), 0)\n result_postcode = addresses[0].get(\"DPA\", {}).get(\"POSTCODE\")\n self.assertEqual(result_postcode, postcode_to_lookup)\n\n def test_can_access_socketserver(self):\n \"connect to socket server\"\n\n parts = urlparse(settings.SOCKETIO_SERVER_URL)\n host, _, port = parts.netloc.partition(\":\")\n host = host or settings.SITE_HOSTNAME\n port = \":%s\" % port if port else \"\"\n path = parts.path + \"/1/\"\n parts = list(parts)\n protocol = \"https\" if settings.SESSION_COOKIE_SECURE else \"http\"\n origin = \"{protocol}://{host}\".format(protocol=protocol, host=host)\n headers = {\"Origin\": origin}\n\n response = requests.get(\n \"{origin}{port}{path}?{params}\".format(\n origin=origin,\n port=port,\n path=path,\n params=urllib.urlencode({\"t\": unix_timestamp(), \"transport\": \"polling\", \"b64\": \"1\"}),\n ),\n timeout=10,\n headers=headers,\n verify=False,\n )\n\n session_id = json.loads(response.text[4:])[\"sid\"]\n\n parts[0] = \"ws\"\n parts[1] = parts[1] or host\n parts[2] = path + \"websocket/\"\n parts[4] = urllib.urlencode({\"sid\": session_id, \"transport\": \"polling\", \"timestamp\": unix_timestamp()})\n ws_url = urlunparse(parts)\n ws = websocket.create_connection(ws_url)\n ws.send(\"0:::\")\n","sub_path":"cla_frontend/apps/status/tests/smoketests.py","file_name":"smoketests.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"496456733","text":"# Copyright 2022 The KerasCV 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# 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\nimport tensorflow as tf\n\nfrom keras_cv.utils import bbox\n\n\nclass BBOXTestCase(tf.test.TestCase):\n def setUp(self):\n super().setUp()\n self.corner_bbox = tf.constant(\n [[10, 10, 110, 110], [20, 20, 120, 120]], dtype=tf.float32\n )\n self.xywh_bbox = tf.constant(\n [[60, 60, 100, 100], [70, 70, 100, 100]], dtype=tf.float32\n )\n\n def test_corner_to_xywh(self):\n self.assertAllClose(bbox.corners_to_xywh(self.corner_bbox), self.xywh_bbox)\n\n # Make sure it also accept higher rank than 2\n corner_bbox_3d = tf.expand_dims(self.corner_bbox, 0)\n xywh_bbox_3d = tf.expand_dims(self.xywh_bbox, 0)\n self.assertAllClose(bbox.corners_to_xywh(corner_bbox_3d), xywh_bbox_3d)\n\n # Make sure it also accept more value after last index.\n padded_corner_bbox = tf.pad(\n self.corner_bbox, [[0, 0], [0, 2]]\n ) # Right pad 2 more value\n padded_xywh_bbox = tf.pad(self.xywh_bbox, [[0, 0], [0, 2]])\n self.assertAllClose(bbox.corners_to_xywh(padded_corner_bbox), padded_xywh_bbox)\n\n # Same for higher rank\n padded_corner_bbox_3d = tf.expand_dims(padded_corner_bbox, 0)\n padded_xywh_bbox_3d = tf.expand_dims(padded_xywh_bbox, 0)\n self.assertAllClose(\n bbox.corners_to_xywh(padded_corner_bbox_3d), padded_xywh_bbox_3d\n )\n\n def test_xywh_to_corner(self):\n self.assertAllClose(bbox.xywh_to_corners(self.xywh_bbox), self.corner_bbox)\n\n # Make sure it also accept higher rank than 2\n corner_bbox_3d = tf.expand_dims(self.corner_bbox, 0)\n xywh_bbox_3d = tf.expand_dims(self.xywh_bbox, 0)\n self.assertAllClose(bbox.xywh_to_corners(xywh_bbox_3d), corner_bbox_3d)\n\n # Make sure it also accept more value after last index.\n padded_corner_bbox = tf.pad(\n self.corner_bbox, [[0, 0], [0, 2]]\n ) # Right pad 2 more value\n padded_xywh_bbox = tf.pad(self.xywh_bbox, [[0, 0], [0, 2]])\n self.assertAllClose(bbox.xywh_to_corners(padded_xywh_bbox), padded_corner_bbox)\n\n # Same for higher rank\n padded_corner_bbox_3d = tf.expand_dims(padded_corner_bbox, 0)\n padded_xywh_bbox_3d = tf.expand_dims(padded_xywh_bbox, 0)\n self.assertAllClose(\n bbox.xywh_to_corners(padded_xywh_bbox_3d), padded_corner_bbox_3d\n )\n\n def test_bbox_padding(self):\n bboxes = [[1, 2, 3, 4], [5, 6, 7, 8]]\n target_shape = [3, 4]\n result = bbox.pad_bbox_batch_to_shape(bboxes, target_shape)\n self.assertAllClose(result, [[1, 2, 3, 4], [5, 6, 7, 8], [-1, -1, -1, -1]])\n\n target_shape = [2, 5]\n result = bbox.pad_bbox_batch_to_shape(bboxes, target_shape)\n self.assertAllClose(result, [[1, 2, 3, 4, -1], [5, 6, 7, 8, -1]])\n\n # Make sure to raise error if the rank is different between bbox and target\n # shape\n with self.assertRaisesRegex(ValueError, \"Target shape should have same rank\"):\n bbox.pad_bbox_batch_to_shape(bboxes, [1, 2, 3])\n\n # Make sure raise error if the target shape is smaller\n target_shape = [3, 2]\n with self.assertRaisesRegex(\n ValueError, \"Target shape should be larger than bounding box shape\"\n ):\n bbox.pad_bbox_batch_to_shape(bboxes, target_shape)\n","sub_path":"keras_cv/utils/bbox_test.py","file_name":"bbox_test.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"268210356","text":"#!/usr/bin/python\n\nimport sys\nimport re\nimport string\nfrom copy import deepcopy \nfrom colorama import Fore, Style, Back\nfrom prettytable import PrettyTable\nfrom simplex import Simplex\n\ndef open_file():\n try:\n return open(\"lab5_variant_11.txt\")\n except FileNotFoundError:\n print(\"Oops! File not exist...\")\n exit()\n\n\ndef get_matrix_table(matrix):\n if len(matrix) < 1: return ''\n\n x = PrettyTable()\n fields = ['']\n for i in range(len(matrix[0])):\n fields.append(\"B\" + str(i + 1))\n\n x.field_names = fields\n for i in range(len(matrix)):\n x.add_row(['A' + str(i + 1)] + matrix[i])\n return x\n\n\ndef check_saddle_point(minA, maxB):\n maxFromMatrixA = minA[max(minA, key = minA.get)]\n minFromMatrixB = maxB[min(maxB, key = maxB.get)]\n return [maxFromMatrixA, minFromMatrixB]\n\n\ndef check_rows(firstRow, secondRow):\n equalElements = 0\n for i in range(len(firstRow)):\n if firstRow[i] < secondRow[i]: return 0\n if firstRow[i] == secondRow[i]: equalElements += equalElements\n\n return 0 if equalElements == len(firstRow) else 1\n\n\ndef check_dominant_rows(matrix):\n matrixAfterExcludingRows = []\n deletedRows = []\n\n for i in range(len(matrix)):\n for j in range(len(matrix)):\n if i == j: continue\n result = check_rows(matrix[i], matrix[j])\n if result != 0 and j not in deletedRows:\n deletedRows.append(j)\n print(\"Стретегія А\" + str(i + 1), \"домінуюча над стратегією А\" + str(j + 1), \"тому забираємо рядок\", j + 1)\n\n for i in range(len(matrix)):\n if i in deletedRows: continue\n matrixAfterExcludingRows.append(matrix[i])\n\n return matrixAfterExcludingRows\n\n\ndef check_dominant_columns(matrix):\n matrixAfterExcludingColumns = []\n deletedColumns = []\n transposedMatrix = [list(x) for x in zip(*matrix)]\n\n for i in range(len(transposedMatrix)):\n for j in range(len(transposedMatrix)):\n if i == j: continue\n result = check_rows(transposedMatrix[j], transposedMatrix[i])\n if result != 0 and j not in deletedColumns:\n deletedColumns.append(j)\n print(\"Стретегія В\" + str(i + 1), \"домінуюча над стратегією В\" + str(j + 1), \"тому забираємо стовпчик\", j + 1)\n \n for i in range(len(matrix)):\n matrixAfterExcludingColumns.append([])\n for j in range(len(matrix[i])):\n if j in deletedColumns: continue\n matrixAfterExcludingColumns[i].append(matrix[i][j])\n\n return matrixAfterExcludingColumns\n\n\nfile = open_file()\n\nmatrix = []\nfor line in file:\n matrix.append([int(d) for d in re.split(';', re.sub('\\n', '', line))])\n\nif len(matrix) < 2: exit()\nprint(Fore.WHITE + \"Вхідні дані\", Style.RESET_ALL)\nprint(get_matrix_table(matrix))\n\nprint(Fore.WHITE + \"Перевірка матриці на наявність сідлової точки\", Style.RESET_ALL)\nx = PrettyTable()\nfields = ['']\nfor i in range(len(matrix)):\n fields.append(\"B\" + str(i + 1))\n\nfields.append('a = min(Ai)')\nx.field_names = fields\n\nminA = {}\nmaxB = {}\n\nfor i in range(len(matrix)):\n minA[i] = min(matrix[i])\n x.add_row(['A' + str(i + 1)] + matrix[i] + [Fore.WHITE + str(minA[i]) + Style.RESET_ALL])\n for j in range(len(matrix[i])):\n if j not in maxB or maxB[j] < matrix[i][j]:\n maxB[j] = matrix[i][j]\n\nx.add_row(['b = max(Bi)' + Fore.WHITE] + [maxB[element] for element in maxB] + ['' + Style.RESET_ALL])\nprint(x)\n\n[maxFromMatrixA, minFromMatrixB] = check_saddle_point(minA, maxB)\nif maxFromMatrixA == minFromMatrixB:\n print(\"Сідлова точка присутня!\")\nelse:\n print(\"a = max(min(Ai)) =\", maxFromMatrixA)\n print(\"b = min(max(Bi)) =\", minFromMatrixB)\n print(\"Сідлова точка відсутня, так як a != b\")\n print(\"Ціна гри знаходиться в межах:\", Fore.RED, maxFromMatrixA, \"<= y <=\", minFromMatrixB, Style.RESET_ALL) \n\n\nprint(Fore.WHITE, \"\\nПеревірка матриці на домінуючі рядки і домінуючі стовпці:\", Style.RESET_ALL)\nprint(Fore.WHITE + \"З позиції виграшу гравця А\", Style.RESET_ALL)\nmatrixAfterExcludingRows = check_dominant_rows(matrix)\nprint(Fore.RED + \"Після перевірки домінуючих рядків наша матриця набула наступного вигляду: \", Style.RESET_ALL)\nprint(get_matrix_table(matrixAfterExcludingRows))\n\n\nprint(Fore.WHITE + \"З позиції програшу гравця В\", Style.RESET_ALL)\nmatrixAfterExcludingColumns = check_dominant_columns(matrixAfterExcludingRows)\nprint(Fore.RED + \"Після перевірки домінуючих стовпчиків наша матриця набула наступного вигляду: \", Style.RESET_ALL)\nprint(get_matrix_table(matrixAfterExcludingColumns))\n\ntransposedMatrix = [list(x) for x in zip(*matrixAfterExcludingColumns)]\nprint(Fore.WHITE + \"\\nЗнаходимо рішення гри в змішаних стратегіях\", Style.RESET_ALL)\nprint(Fore.RED + \"Знайти мінімум функції F(x) при обмеженнях (для гравця ||)\", Style.RESET_ALL)\n\nsecondPlayersConditions = []\nfor i in range(len(transposedMatrix)):\n secondPlayersConditions.append('')\n for j in range(len(transposedMatrix[i])):\n secondPlayersConditions[i] += str(transposedMatrix[i][j]) + 'x_' + str(j + 1) + ' + '\n\nfor i in range(len(secondPlayersConditions)):\n print(secondPlayersConditions[i][:-2] + '>= 1')\n\nmainCondition = 'F(x) = '\nfor i in range(len(matrixAfterExcludingColumns)):\n mainCondition += 'x_' + str(i + 1) + ' + '\n\nprint(mainCondition[:-2] + '--> min')\n\nprint(Fore.RED + \"Знайти мінімум функції Z(y) при обмеженнях (для гравця |)\", Style.RESET_ALL)\nfirstPlayersConditions = []\n\nvars_count = 0\nfor i in range(len(matrixAfterExcludingColumns)):\n firstPlayersConditions.append('')\n columns = len(matrixAfterExcludingColumns[i])\n for j in range(columns):\n firstPlayersConditions[i] += str(matrixAfterExcludingColumns[i][j]) + 'y_' + str(j + 1) + ' + '\n if columns > vars_count:\n vars_count = columns\n\nconditions = ''\nfor i in range(len(firstPlayersConditions)):\n firstPlayersConditions[i] = firstPlayersConditions[i][:-2] + '<= 1'\n\nmainCondition = ''\nfor i in range(len(transposedMatrix)):\n mainCondition += '1y_' + str(i + 1) + ' + '\n\nmainCondition = mainCondition[:-2]\n\nfor line in firstPlayersConditions:print(line)\nprint('Z(y) = ' + mainCondition + '--> max')\n\nprint(Fore.WHITE + \"\\nВирішимо пряму задачу лінійного програмування симплексним методом\", Style.RESET_ALL)\nprint(Fore.WHITE + \"Визначимо максимальне значення цільової функції\", Fore.RED, mainCondition + '--> max', Fore.WHITE + \"при настуних умовах-обмеженнях:\", Style.RESET_ALL)\nprint(conditions)\nprint(Fore.WHITE + \"Після переведення в канонічну форму переходимо до основно алгоритму симплекс-методом\", Style.RESET_ALL)\n\nsimplexResult = Simplex(num_vars=vars_count, constraints=firstPlayersConditions, objective_function=mainCondition)\nprint(Fore.WHITE + \"\\nОтримуємо наступні результати:\", Style.RESET_ALL)\n\nx_result = {}\ny_result = {}\nfor key in simplexResult.solution:\n if 'y_' in key:\n y_result[key] = simplexResult.solution[key]\n elif 'x_' in key:\n x_result[key] = simplexResult.solution[key]\n\nyResultCond = 'F(y) = '\nyResult = 0\nfor i in range(vars_count):\n print('y' + str(i + 1) + ' =', y_result['y_' + str(i + 1)], end=' ')\n yResult += 1 * y_result['y_' + str(i + 1)]\n yResultCond += \"1 * \" + str(y_result['y_' + str(i + 1)]) + ' + '\n\n\nprint(\"\\n\" + Fore.RED + yResultCond[:-2] + '= ' + str(yResult), Style.RESET_ALL, '\\n')\n\nxResultCond = 'F(x) = '\nxResult = 0\nfor i in range(vars_count):\n print('x' + str(i + 1) + ' =', x_result['x_' + str(i + 1)], end=' ')\n xResult += 1 * x_result['x_' + str(i + 1)]\n xResultCond += \"1 * \" + str(x_result['x_' + str(i + 1)]) + ' + '\n\n\nprint(\"\\n\" + Fore.RED + xResultCond[:-2] + '= ' + str(xResult), Style.RESET_ALL)\n\nprint(\"\\nЦіна гри буде рівна g = 1/F(x)\")\nprint(Fore.WHITE + \"g = 1/(\" + str(xResult), \") =\", str(1/xResult), Style.RESET_ALL)\n","sub_path":"Lab5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"77416325","text":"\"\"\"\nNOTES: make sure mongod running. use `sudo mongod` in terminal\n\"\"\"\n\nfrom pymongo import MongoClient\nimport requests\nfrom bs4 import BeautifulSoup\nimport pickle\nimport time\nimport datetime\nimport string\nimport re\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n\nclass AirBnBListing(object):\n \"\"\"\n Initializes an AirBnBListing object\n This allows you to scrape listings or retrieve listings from MongoDB\n\n INPUT:\n - db_name (str): 'airbnb' or 'airbnb_test'\n - coll_name (str): 'listings'\n \"\"\"\n\n def __init__(self, db_name, coll_name):\n self.BASE_ROOM_URL = \"https://www.airbnb.com/rooms/\"\n\n client = MongoClient()\n self.db = client[db_name]\n self.coll = self.db[coll_name]\n\n self.listing_id = \"\"\n self.url = \"\"\n self.r = None\n self.d = {}\n\n def scrape_from_web(self, listing_id):\n '''\n Scrapes a single listing's info from AirBnB\n\n INPUT:\n - listing_id (int or str): the id of the listing you're trying to scrape\n OUTPUT: None\n '''\n\n self.listing_id = str(listing_id) # ensure listing_id is a string\n self.url = self.BASE_ROOM_URL + self.listing_id\n self.r = requests.get(self.url)\n pkl = pickle.dumps(self.r)\n self.d = {'_id': self.listing_id,\n 'url': self.url,\n 'content': self.r.content,\n 'pickle': pkl,\n 'time': time.time(),\n 'dt': datetime.datetime.utcnow(),\n 'requests_meta': {\n 'status_code': self.r.status_code,\n 'is_redirect': self.r.is_redirect,\n 'is_ok': self.r.ok,\n 'raise_for_status': self.r.raise_for_status(),\n 'reason': self.r.reason\n }\n }\n\n def scrape_from_web_for_app(self, listing_id):\n '''\n Scrapes a single listing's info from AirBnB\n note: specific for the production instance of the app\n\n INPUT:\n - listing_id (int or str): the id of the listing you're trying to scrape\n OUTPUT: None\n '''\n\n self.listing_id = str(listing_id) # ensure listing_id is a string\n self.url = self.BASE_ROOM_URL + self.listing_id\n self.r = requests.get(self.url)\n self.d = {'_id': self.listing_id,\n 'url': self.url,\n 'content': self.r.content,\n 'time': time.time(),\n 'dt': datetime.datetime.utcnow(),\n }\n\n def pull_from_db(self, listing_id):\n '''\n Pulls a previously scraped listing's data from the MongoDB collection\n\n INPUT:\n - listing_id (int or str): the id of the listing you're trying to pull\n OUTPUT: None\n '''\n listing = self.coll.find_one({'_id': listing_id})\n\n self.listing_id = listing_id\n self.url = listing['url']\n self.r = pickle.loads(listing['pickle'])\n self.d = listing\n\n def pull_from_db_cached(self, listing_id):\n '''\n Pulls a previously scraped listing's data from the MongoDB collection\n Used for any listing after the production db crashed\n\n INPUT:\n - listing_id (int or str): the id of the listing you're trying to pull\n OUTPUT: None\n '''\n listing_id = str(listing_id)\n listing = self.coll.find_one({'_id': listing_id})\n\n self.listing_id = listing_id\n # self.url = listing['url']\n # self.r = pickle.loads(listing['pickle'])\n self.d = listing\n\n def insert_into_coll(self, overwrite=False):\n '''\n Inserts the current listing's data into the MongoDB collection\n - If the listing does not exist, it gets inserted\n - If the listing exists, the insertion depends on if we wish to overwrite\n\n INPUT:\n - overwrite (bool): whether to overwrite if the listing already exists\n OUTPUT:\n - bool: \n * Returns True if a listing was inserted (new or overwriten)\n * Return False if the listing existed and overwrite=False\n '''\n if not self.is_in_collection():\n self.coll.insert(self.d)\n return True\n elif overwrite:\n self.coll.update({'_id': self.listing_id}, {'$set': self.d})\n return True\n else:\n return False\n\n def scrape_and_insert(self, listing_id, overwrite=False):\n '''\n Runs scrape_from_web() & insert_into_coll() with parameters provided\n NOTE: this method does NOT return what insert_into_coll returns\n\n INPUT:\n - listing_id (int or str): the id of the listing you're trying to pull\n - overwrite (bool): whether to overwrite if the listing already exists\n OUTPUT: None\n '''\n self.scrape_from_web(listing_id=listing_id)\n self.insert_into_coll(overwrite=overwrite)\n\n def is_in_collection(self, listing_id=None):\n '''\n Checks to see if the current listing's data is in the MongoDB collection\n NOTE: this method is only useful in conjunction with scrape_from_web()\n\n INPUT:\n - listing_id (None or int or str):\n * the id of the listing you're trying to pull\n * if None (default), uses self.listing_id\n OUTPUT: None\n '''\n if not listing_id:\n listing_id = self.listing_id\n else:\n listing_id = str(listing_id)\n return bool(self.coll.find_one({'_id': listing_id}))\n\n def is_other_in_collection(self, listing_id):\n '''\n ********** DEPRECIATED ***********\n REASON: more efficient to combine this method wth is_in_collection()\n SOLUTION: use is_in_collection() with explicit listing_id)\n **********************************\n\n Checks to see if an explicit listing's data is in the MongoDB collection\n NOTE: this method is only useful in conjunction with scrape_from_web()\n\n INPUT: None\n OUTPUT: None\n '''\n return bool(self.coll.find_one({'_id': listing_id}))\n\n def _lemmatize(self, s):\n\n lemma = WordNetLemmatizer()\n words = s.split()\n lemmatized_words = [lemma.lemmatize(word) for word in words]\n return ' '.join(lemmatized_words)\n\n def _expand_contractions(self, s):\n '''\n Helper Function to expand contractions:\n\n INPUT:\n - s (str): raw description text\n OUTPUT:\n - str: the text with the contractions expanded\n '''\n # edited from\n # http://stackoverflow.com/questions/19790188/expanding-english-language-contractions-in-python\n\n contractions_dict = {\n \"ain't\": \"am not\",\n \"aren't\": \"are not\",\n \"can't\": \"cannot\",\n \"can't've\": \"cannot have\",\n \"'cause\": \"because\",\n \"could've\": \"could have\",\n \"couldn't\": \"could not\",\n \"couldn't've\": \"could not have\",\n \"didn't\": \"did not\",\n \"doesn't\": \"does not\",\n \"don't\": \"do not\",\n \"hadn't\": \"had not\",\n \"hadn't've\": \"had not have\",\n \"hasn't\": \"has not\",\n \"haven't\": \"have not\",\n \"he'd\": \"he would\",\n \"he'd've\": \"he would have\",\n \"he'll\": \"he will\",\n \"he'll've\": \"he shall have / he will have\",\n \"he's\": \"he is\",\n \"how'd\": \"how did\",\n \"how'd'y\": \"how do you\",\n \"how'll\": \"how will\",\n \"how's\": \"how is\",\n \"i'd\": \"I would\",\n \"i'd've\": \"I would have\",\n \"i'll\": \"I will\",\n \"i'll've\": \"i will have\",\n \"i'm\": \"i am\",\n \"i've\": \"i have\",\n \"isn't\": \"is not\",\n \"it'd\": \"it would\",\n \"it'd've\": \"it would have\",\n \"it'll\": \"it shall / it will\",\n \"it'll've\": \"it shall have / it will have\",\n \"it's\": \"it has / it is\",\n \"let's\": \"let us\",\n \"ma'am\": \"madam\",\n \"mayn't\": \"may not\",\n \"might've\": \"might have\",\n \"mightn't\": \"might not\",\n \"mightn't've\": \"might not have\",\n \"must've\": \"must have\",\n \"mustn't\": \"must not\",\n \"mustn't've\": \"must not have\",\n \"needn't\": \"need not\",\n \"needn't've\": \"need not have\",\n \"o'clock\": \"of the clock\",\n \"oughtn't\": \"ought not\",\n \"oughtn't've\": \"ought not have\",\n \"shan't\": \"shall not\",\n \"sha'n't\": \"shall not\",\n \"shan't've\": \"shall not have\",\n \"she'd\": \"she would\",\n \"she'd've\": \"she would have\",\n \"she'll\": \"she shall / she will\",\n \"she'll've\": \"she shall have / she will have\",\n \"she's\": \"she has / she is\",\n \"should've\": \"should have\",\n \"shouldn't\": \"should not\",\n \"shouldn't've\": \"should not have\",\n \"so've\": \"so have\",\n \"so's\": \"so as / so is\",\n \"that'd\": \"that would\",\n \"that'd've\": \"that would have\",\n \"that's\": \"tthat is\",\n \"there'd\": \"there had / there would\",\n \"there'd've\": \"there would have\",\n \"there's\": \"there is\",\n \"they'd\": \"they would\",\n \"they'd've\": \"they would have\",\n \"they'll\": \"they will\",\n \"they'll've\": \"they shall have / they will have\",\n \"they're\": \"they are\",\n \"they've\": \"they have\",\n \"to've\": \"to have\",\n \"wasn't\": \"was not\",\n \"we'd\": \"we would\",\n \"we'd've\": \"we would have\",\n \"we'll\": \"we will\",\n \"we'll've\": \"we will have\",\n \"we're\": \"we are\",\n \"we've\": \"we have\",\n \"weren't\": \"were not\",\n \"what'll\": \"what shall / what will\",\n \"what'll've\": \"what shall have / what will have\",\n \"what're\": \"what are\",\n \"what's\": \"what has / what is\",\n \"what've\": \"what have\",\n \"when's\": \"when has / when is\",\n \"when've\": \"when have\",\n \"where'd\": \"where did\",\n \"where's\": \"where has / where is\",\n \"where've\": \"where have\",\n \"who'll\": \"who shall / who will\",\n \"who'll've\": \"who shall have / who will have\",\n \"who's\": \"who has / who is\",\n \"who've\": \"who have\",\n \"why's\": \"why is\",\n \"why've\": \"why have\",\n \"will've\": \"will have\",\n \"won't\": \"will not\",\n \"won't've\": \"will not have\",\n \"would've\": \"would have\",\n \"wouldn't\": \"would not\",\n \"wouldn't've\": \"would not have\",\n \"y'all\": \"you all\",\n \"y'all'd\": \"you all would\",\n \"y'all'd've\": \"you all would have\",\n \"y'all're\": \"you all are\",\n \"y'all've\": \"you all have\",\n \"you'd\": \"you would\",\n \"you'd've\": \"you would have\",\n \"you'll\": \"you will\",\n \"you'll've\": \"you shall have / you will have\",\n \"you're\": \"you are\",\n \"you've\": \"you have\"\n }\n\n contractions_re = re.compile('(%s)' % '|'.join(contractions_dict.keys()))\n\n def replace(match):\n return contractions_dict[match.group(0)]\n return contractions_re.sub(replace, s)\n\n def _clean_description(self, d):\n '''\n Cleans up an AirBnB description as defined by:\n soup.find('div', {'class':'row description'}) /\n .find('div', {'class':'expandable-content expandable-content-long'}) /\n .get_text()\n where soup is the BeautifulSoup of the page content\n\n INPUT:\n - d (str): see above for how d is defined\n OUTPUT:\n - str: returns the cleaned up string\n '''\n # remove section Names/headers of the AirBnB description\n d = d.replace('\\nThe Space\\n', \"\", 1)\n d = d.replace('\\nGuest Access\\n', \"\", 1)\n d = d.replace('\\nInteraction with Guests\\n', \"\", 1)\n d = d.replace('\\nThe Neighbourhood\\n', \"\", 1) # CA specific\n d = d.replace('\\nThe Neighborhood\\n', \"\", 1) # US specific\n d = d.replace('\\nGetting Around\\n', \"\", 1)\n d = d.replace('\\nOther Things to Note\\n', \"\", 1)\n\n # convert the string to lowercase\n d = d.lower()\n # expand all contractions\n d = self._expand_contractions(d)\n # remove all non words\n d = re.sub(\"[^a-zA-Z]\",\" \", d)\n # remove punctuation\n # d = re.compile('[%s]' % re.escape(string.punctuation)).sub(' ', d)\n # lemmatize\n d = self._lemmatize(d)\n # remove line breaks\n d = d.replace('\\n', \" \")\n # remove multiple spaces\n d = ' '.join(d.split())\n\n return d\n\n def extract_features(self):\n '''\n Extracts all of the predefined features of the currently loaded listing\n\n INPUT: None\n OUTPUT:\n - dict: the dictionary of the predefined features extracted\n '''\n features = {}\n\n soup = BeautifulSoup(self.r.content)\n\n try:\n listing_name = soup.find('div', {'class': \"rich-toggle wish_list_button\"})['data-name']\n features['listing_name'] = listing_name\n except TypeError:\n pass\n\n try:\n address = soup.find('div', {'class': \"rich-toggle wish_list_button\"})['data-address']\n features['address'] = address\n except TypeError:\n pass\n\n try:\n num_saved = soup.find('div', {'class': \"rich-toggle wish_list_button\"})['title']\n features['num_saved'] = num_saved\n except (TypeError, KeyError):\n pass\n\n try:\n headline = soup.find('meta', {'property': \"og:description\"})['content']\n features['headline'] = headline\n except TypeError:\n pass\n\n try:\n description_raw = soup.find('div', {'class': 'row description'}).find('div', {'class': 'expandable-content expandable-content-long'}).get_text()\n features['description_raw'] = description_raw\n features['description_clean'] = self._clean_description(description_raw)\n except AttributeError:\n pass\n\n try:\n price_currency = soup.find('meta', {'itemprop': 'priceCurrency'})['content']\n features['price_currency'] = price_currency\n except TypeError:\n pass\n\n try:\n price = soup.find('meta', {'itemprop': 'price'})['content']\n features['price'] = price\n except TypeError:\n pass\n\n try:\n hood = soup.find('div', {'id': 'neighborhood-seo-link'}).h3.a.get_text().strip()\n except (AttributeError):\n hood = \"N/A\"\n features['neighborhood'] = hood\n\n return features\n\n def extract_clean_description(self):\n '''\n Extracts and returns the clean_description of the current listing\n\n INPUT: None\n OUTPUT:\n - str:\n * if we're able to clean up the string, returns cleaned description\n * if we error out, we return an empty string\n '''\n\n soup = BeautifulSoup(self.r.content)\n\n try:\n description_raw = soup.find('div', {'class': 'row description'}).find('div', {'class': 'expandable-content expandable-content-long'}).get_text()\n return self._clean_description(description_raw)\n except:\n return \"\"\n\n def extract_clean_description_cached(self):\n '''\n Extracts and returns the clean_description of the current listing\n Used for any listing after the production db crashed\n\n INPUT: None\n OUTPUT:\n - str:\n * if we're able to clean up the string, returns cleaned description\n * if we error out, we return an empty string\n '''\n\n try:\n description_raw = self.d['description_raw']\n return self._clean_description(description_raw)\n except:\n return \"\"\n\n def add_features(self, new_features):\n '''\n Adds new features to the currently loaded listing's data\n Note: The listing must already exist in the MongoDB collection\n\n INPUT:\n - new_features (dict): a dictionary of new features to add the the listing\n OUTPUT: None\n '''\n # self.coll.update({'_id': self.listing_id}, new_features)\n self.coll.update({'_id': self.listing_id}, {'$set:': new_features})\n\n def extract_and_add_features(self):\n '''\n Runs extract_features() on the currently loaded listing's data,\n and tthen runs add_features() to add them\n Note: The listing must already exist in the MongoDB collection\n\n INPUT: None\n OUTPUT: None\n '''\n new_features = self.extract_features()\n if new_features != {}:\n self.add_features(new_features=new_features)\n else:\n error_warning = {'error': 1, 'message': 'NO FEATURES EXTRACTED'}\n self.add_features(new_features=error_warning)\n","sub_path":"libs/airbnb/airbnblisting.py","file_name":"airbnblisting.py","file_ext":"py","file_size_in_byte":17211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"159950481","text":"import ujson as json\n\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import AnonymousUser\n\n\nclass JwtTokenMiddleware:\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n # Code to be executed for each request before\n # the view (and later middleware) are called.\n if 'admin' not in request.path:\n token = request.META.get('HTTP_TOKEN')\n if isinstance(request.user, AnonymousUser):\n auth = authenticate(request, token=token)\n if auth:\n request.user = auth\n\n response = self.get_response(request)\n\n # Code to be executed for each request/response after\n # the view is called.\n\n return response\n\n\nclass JsonRequestMiddleware:\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n request_json = {}\n if request.method != 'GET' and request.content_type == 'application/json' and request.body:\n try:\n request_json = json.loads(request.body)\n except ValueError:\n pass\n\n request.JSON = request_json\n\n response = self.get_response(request)\n\n return response\n","sub_path":"common/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"204203656","text":"import pickle\nfrom scipy.sparse import csr_matrix # for fetching rows\nimport numpy as np\nfrom collections import Counter\nimport os\n\ndef getFilename( splitNumber, isTraining, isLabel,\n dataDirName = 'training_testing_and_results_pickles',\n testCluster = 'twenty_newsgroups',\n extensionName = 'pickle',\n isUsingMatlab = False\n ):\n '''\n returns filename to load from already test-train-split data\n 4 mandatory options:\n - splitNumber: integer\n - isTraining: True if file for training\n - isLabel: True if file for getting label associated to matrix\n - isUsingMAtlabl: True if used to import learnt parameters from matlab\n\n SIDE effect: if directory doesn't exist, directory will be created\n\n returns a string with prefixes attace\n '''\n # recent git update renamed directories for consistent naming scheme\n alternateClusterName = testCluster\n trainingTestingStr = 'training' if isTraining else 'testing'\n matrixLabelStr = '_labels_vector_' if isLabel else '_'\n trainingTestingMatrixStr = 'trained_param' if isUsingMatlab else trainingTestingStr + '_matrix' \n fName = alternateClusterName + '_' + trainingTestingMatrixStr + \\\n matrixLabelStr + 'cv#' + str( splitNumber ) + '.' + extensionName\n prefix = './'+ dataDirName + '/' + testCluster + '/cv' + str( splitNumber ) + '/'\n os.makedirs( prefix, exist_ok=True )\n return prefix + fName\n\ndef partitionDataPerTopic( dataTopics, dataM ):\n '''\n Given a list of topics (asscoiated with each row in dataM) and dataM,\n return a list of unique topics, and a dictionary whose\n key: label, value: submatrix whose rows have value label\n (i.e. dataTopics[i] = label -> dataM.getrow(i) is a row in d[label])\n\n - dataTopics: a list of topics associated with each row\n o has a special structure: [ 0,0,0,.... ,0,1,1,...,1,2...,2.. and so on]\n - dataM: a matrix with efficient slicing and row reading\n \n returns a list of unique topics, and a dictionary described above\n '''\n topicToMatrixD = {}\n topicCounts = Counter( dataTopics )\n startIdx = 0\n # UPDATE variables: startIdx, endIdx\n for topic in topicCounts.keys():\n endIdx = startIdx + topicCounts[ topic ]\n topicToMatrixD[ topic ] = dataM[ startIdx:endIdx ]\n startIdx = endIdx\n return (list( topicCounts.keys() ), topicToMatrixD)\n\nif __name__ == '__main__':\n '''\n Step 1. Read and load training/test data split\n Step 2. partition training/test data per topic\n '''\n # --------------------------------\n # Step 1. Read and load training/test data split\n splitNumber = 0\n trainingMatF = getFilename( splitNumber, isTraining=True, isLabel=False ) \n trainingLabelF = getFilename( splitNumber, isTraining=True, isLabel=True ) \n testingMatF = getFilename( splitNumber, isTraining=False, isLabel=False ) \n testingLabelF = getFilename( splitNumber, isTraining=False, isLabel=True ) \n\n #garboF = getFilename( splitNumber, False, False, dataDirName='foo', alternateClusterName='')\n with open( trainingMatF, 'rb' ) as f:\n trainingMat = csr_matrix( pickle.load( f ) )\n # fast matrix, whose get_row returns ONLY non-zero values\n with open( trainingLabelF, 'rb' ) as f:\n trainingLabel = pickle.load( f )\n # trainingLabel is a list\n # ordered such that 0 appears x_0, 1 appears x_1, and so forth\n with open( testingMatF, 'rb' ) as f:\n testingMat = csr_matrix( pickle.load( f ) )\n with open( testingLabelF, 'rb' ) as f:\n testingLabel = pickle.load( f )\n # --------------------------------\n # Step 2. partition training/test data per topic \n \n (topicList, partitionedTrainingD) = partitionDataPerTopic( trainingLabel, trainingMat )\n (_, partitionedTestingD) = partitionDataPerTopic( testingLabel, testingMat )\n # key: topic, val: matrix whose col dimensions = |lexicon|, row dim = # docs belonging to topic\n\n trainingWordFrequencyD = {}\n # key: topic, value: array of topic wide frequency, len( array ) = | lexicon |\n for topic in topicList:\n # sum frequency row-wise\n topicFrequencyMat = partitionedTrainingD[ topic ].sum( axis = 0 )\n trainingWordFrequencyD[ topic ] = np.array( topicFrequencyMat )[0]\n","sub_path":"splitData.py","file_name":"splitData.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"301155717","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\n#data directory\ndatadir = \"D:/Intern Project/Raw data/CollegeScorecard_Raw_Data\"\n\n\n# In[4]:\n\n\nimport warnings \nwarnings.filterwarnings('ignore')\n\n\n# In[5]:\n\n\n#list of files in directory\n#ls \"D:/Intern Project/Raw data/CollegeScorecard_Raw_Data\"\n\n\n# In[6]:\n\n\n#read in the 2009 data\nCOL = pd.read_csv(datadir + '/MERGED2009_10_PP.csv')\n\n\n# In[7]:\n\n\nCOL.info()\n\n\n# In[8]:\n\n\n# Which columns have no NAs\ncol_dna = COL.dropna(axis=1)\ncol_dna.info()\n\n\n# In[9]:\n\n\ncol_dtypes = dict(col_dna.dtypes.replace(np.dtype('int64'),np.dtype('float64'))) # make the dtypes floats\ncol_dtypes['UNITID'] = np.dtype('int64') # convert the UNITID back to int\nvars_interest = ['ADM_RATE','UGDS','TUITIONFEE_IN','TUITIONFEE_OUT','MN_EARN_WNE_P10'] # Include these vars\ncol_dtypes.update({a: np.dtype('float64') for a in vars_interest}) # make them floats\n\n\n# In[10]:\n\n\ncol_try_again = pd.read_csv(datadir + '/MERGED2009_10_PP.csv',na_values='PrivacySuppressed',\n dtype=col_dtypes,usecols=col_dtypes.keys())\ncol_try_again.info()\n\n\n# In[11]:\n\n\ncol_try_again['Year'] = pd.Period('2010',freq='Y')\n\n\n# In[12]:\n\n\ndef read_cs_data(year,col_dtypes,datadir):\n \"\"\"read a CollegeScorecard dataframe\"\"\"\n nextyr = str(int(year) + 1)[-2:]\n filename = datadir + '/MERGED{}_{}_PP.csv'.format(year,nextyr)\n col = pd.read_csv(filename,na_values='PrivacySuppressed',\n dtype=col_dtypes,usecols=col_dtypes.keys())\n col['Year'] = pd.Period(str(int(year) + 1),freq='Y')\n return col\n\n\n# In[13]:\n\n\ncol = pd.concat((read_cs_data(str(y),col_dtypes,datadir) for y in range(1999,2018)))\ncol = col.set_index(['UNITID','Year'])\n\n\n# In[14]:\n\n\ncol.head()\n\n\n# In[15]:\n\n\ncol.UGDS.sum()\n\n\n# In[16]:\n\n\nx = col.groupby('Year').sum()['UGDS']\nx = pd.DataFrame(x)\nx\n\n\n# In[17]:\n\n\nx = x.drop(x.index[1])\nx\n\n\n# # Undergraduates enrollment from 2000 to 2018\n\n# In[57]:\n\n\nax = x.plot(y='UGDS', linestyle = '-', marker = 'o', figsize=(15,8))\nax.set_title('undergraduate Enrollment')\nax.set_ylabel('UG Enrollment')\nplt.xticks(fontsize=12)\nplt.show()\n\n\n# In[48]:\n\n\nplt.figure(figsize=(20, 20))\nax = x.plot(y='UGDS',linestyle = '-', marker = 'o')\nax.set_title('undergraduate pop.')\nax.set_ylabel('UG Enrollment')\nplt.show()\n\n\n# In[ ]:\n\n\ny = col.groupby('STABBR').sum()['UGDS']\ny = pd.DataFrame(y)\ny = y.rename(columns=lambda x:x.strip())\ny.head()\n\n\n# In[ ]:\n\n\ny['STABBR'] = y.index\ny.head()\n\n\n# In[ ]:\n\n\nplt.figure(figsize=(10,6))\nax = y.plot(y='UGDS')\nax.set_title('undergraduate pop.')\nax.set_ylabel('UG Enrollment')\nplt.legend()\n\n\n# In[ ]:\n\n\nsns.set_style('dark')\nplt.figure(figsize = (16, 16))\nax = sns.barplot(y.STABBR.value_counts().values, list(y.STABBR.value_counts().index), \n palette = sns.color_palette('bright', len(y.STABBR.value_counts())))\nfor p in ax.patches:\n width = p.get_width()\n plt.text(20+p.get_width(), p.get_y()+0.55*p.get_height(),\n '{:1.0f}'.format(width),\n ha='center', va='center', fontsize = 12)\nplt.title('Number of undergraduate enrollments per state', fontsize = 15)\nplt.xlabel('Number of under graduates', fontsize = 13)\nplt.ylabel('State Code', fontsize = 13)\nplt.xticks([], [])\nplt.yticks(fontsize = 12)\n\nplt.tight_layout();\n\n\n# In[ ]:\n\n\nplt.figure(figsize = (7, 4))\nsdvzs = sns.barplot(data = y , x = 'UGDS' , y = 'STABBR', color = sns.color_palette()[0])\nfor p in sdvzs.patches:\n width = p.get_width()\n plt.text(20+p.get_width()/0.9555, p.get_y()+0.55*p.get_height(),\n '{:1.0f}'.format(width),\n ha='center', va='center',fontsize = 12)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"mergedscorecard.py","file_name":"mergedscorecard.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"138183288","text":"\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport random\n\nfrom itertools import islice\nfrom utils import decorate, savefig\n\n\n# TODO: remove this when NetworkX is fixed\nfrom warnings import simplefilter\nimport matplotlib.cbook\nsimplefilter(\"ignore\", matplotlib.cbook.mplDeprecation)\n\n# node colors for drawing networks\ncolors = sns.color_palette('pastel', 5)\nsns.set_palette(colors)\n\ndef undirected_graph():\n\t\"\"\"makes an undirected graph showing five cities and the drive times\n\tbetween them.\"\"\"\n\n\tpositions = dict(\tAlbany=(-74, 43),\n\t\t\t\t\t\tBoston=(-71, 42),\n\t\t\t\t\t\tNYC = (-74, 41),\n\t\t\t\t\t\tPhilly = (-75, 40))\n\n\tG = nx.Graph()\n\tG.add_nodes_from(positions)\n\n\tdrive_times = {('Albany','Boston'): 3,\n\t\t\t\t\t('Albany','NYC'): 4,\n\t\t\t\t\t('Boston', 'NYC'): 4,\n\t\t\t\t\t('NYC', 'Philly'): 2}\n\n\tG.add_edges_from(drive_times)\n\n\tpositions['Pittsburgh'] = (-80, 40)\n\n\tnew_drive_times = {('Pittsburgh', 'Albany'): 7,\n\t\t\t\t\t\t('Pittsburgh', 'NYC'): 6,\n\t\t\t\t\t\t('Pittsburgh', 'Philly'): 5,\n\t\t\t\t\t\t('Pittsburgh', 'Boston'): 9}\n\n\tG.add_node('Pittsburgh')\n\tG.add_edges_from(new_drive_times)\n\n\tdrive_times = {**drive_times, **new_drive_times}\n\n\tnx.draw(G, positions,\n\t\t\tnode_color='C1',\n\t\t\tnode_shape='s',\n\t\t\tnode_size=2500,\n\t\t\twith_labels=True)\n\n\tnx.draw_networkx_edge_labels(G, positions, edge_labels=drive_times)\n\n\tplt.show()\n\ndef directed_graph():\n\t\"\"\"makes a directed graph of a small directed social network (e.g. twitter)\"\"\"\n\tG = nx.DiGraph()\n\n\tG.add_node('Alice')\n\tG.add_node('Bob')\n\tG.add_node('Chuck')\n\tG.add_node('Ben')\n\n\t# syntax for directed graph: ( points to )\n\tG.add_edge('Alice', 'Bob')\n\tG.add_edge('Alice', 'Chuck')\n\tG.add_edge('Bob', 'Alice')\n\tG.add_edge('Bob', 'Chuck')\n\tG.add_edge('Ben', 'Chuck')\n\tG.add_edge('Ben', 'Bob')\n\tG.add_edge('Alice', 'Ben')\n\n\n\tprint(list(G.nodes()))\n\n\tprint(list(G.edges()))\n\n\tnx.draw_circular(G,\n\t\t\t\t\tnode_size = 2000,\n\t\t\t\t\tnode_color = 'C0',\n\t\t\t\t\twith_labels = True)\n\n\tplt.axis('equal')\n\tplt.show()\n\ndef all_pairs(nodes):\n\t\"\"\"generator producing all pairs of tuples in range nodes\n\tnodes: iterable (e.g. range)\"\"\"\n\n\tfor i, u in enumerate(nodes):\n\t\tfor j, v in enumerate(nodes):\n\t\t\tif i>j:\n\t\t\t\tyield u, v\n\ndef m_pairs(nodes, m):\n\t\"\"\"returns a random sample of size m from the set all_pairs\"\"\"\n\ts = set(all_pairs(nodes))\n\treturn random.sample(s, m)\n\ndef make_complete_graph(n):\n\t\"\"\"returns a complete undirected graph with n nodes\"\"\"\n\tG = nx.Graph()\n\tnodes = range(n)\n\tG.add_nodes_from(nodes)\n\tG.add_edges_from(all_pairs(nodes))\n\treturn G\n\ndef reachable_nodes(G, start):\n\t\"\"\"returns the reachable nodes of G from start node.\n\tThis algorithm performs depth-first-search and is inefficient\n\tfor most uses.\n\t\n\tG: networkx.Graph or networkx.DiGraph\n\tstart: node in G\n\treturns: list of nodes seen from start\n\t\"\"\"\n\tseen = set()\n\tstack = [start]\n\twhile stack:\n\t\tnode = stack.pop()\n\t\tif node not in seen:\n\t\t\tseen.add(node)\n\t\t\tstack.extend(G.neighbors(node))\n\treturn seen\n\ndef is_connected(G):\n\t\"\"\"returns True if undirected graph G is fully connected, False otherwise\n\t\"\"\"\n\tstart=next(iter(G))\n\treachable = reachable_nodes_precheck(G, start)\n\treturn len(reachable) == len(G)\n\ndef is_connected_directed(G):\n\t\"\"\"returns True if directed graph G is fully connected, False otherwise\n\t\"\"\"\n\tfor node in G.nodes:\n\t\t# start = next(iter(G))\n\t\tstart = node\n\t\treachable = reachable_nodes(G, start)\n\t\tif len(reachable) != len(G):\n\t\t\treturn False\n\treturn True\n\ndef random_pairs(nodes, p):\n\t\"\"\"generates random edges based on flip of many-sided coin\n\tnodes: iterable of nodes (e.g. range)\n\tp: probability of returning node\n\tyields: edge\n\t\"\"\"\n\tfor edge in all_pairs(nodes):\n\t\tif flip(p):\n\t\t\tyield edge\n\ndef flip(p):\n\t\"\"\"returns True if random float is less than p, false otherwise\n\timitates flip of many-sided coin with p chance of success\"\"\"\n\treturn np.random.random() < p\n\ndef make_random_graph(n, p):\n\t\"\"\"make random undirected graph\n\tn: number of nodes\n\tp: probability that a given edge exists\n\treturns: nx.Graph\n\t\"\"\"\n\tG = nx.Graph()\n\tnodes = range(n)\n\tG.add_nodes_from(nodes)\n\tG.add_edges_from(random_pairs(nodes, p))\n\treturn G\n\ndef make_m_graph(n, m):\n\t\"\"\"makes random undirected graph of n nodes and m edges\n\tn: number of nodes\n\tm: number of edges\n\treturns: nx.Graph\n\t\"\"\"\n\tG = nx.Graph()\n\tnodes = range(n)\n\tG.add_nodes_from(nodes)\n\tG.add_edges_from(m_pairs(nodes, m))\n\treturn G\n\ndef invert_tuple(g):\n\t\"\"\"generator that flips 2-value tuple output of another generator g\n\t\"\"\"\n\twhile True:\n\t\ttry:\n\t\t\ta, b = next(g)\n\t\t\tyield b, a\n\t\texcept:\n\t\t\tbreak\n\ndef make_random_directed_graph(n,p):\n\t\"\"\"makes a random directed graph\n\tn: number of nodes in graph\n\tp: probability of a given node existing\n\treturns: nx.DiGraph\n\t\"\"\"\n\tG = nx.DiGraph()\n\tnodes = range(n)\n\tG.add_nodes_from(nodes)\n\tG.add_edges_from(random_pairs(nodes, p))\n\n\treverse_pairs = invert_tuple( random_pairs(nodes, p) )\n\tG.add_edges_from(reverse_pairs)\n\treturn G\n\ndef prob_connected(n, p=None, m=None, iters=100):\n\t\"\"\"determines the probabiltiy of an undirected Erdos-Renyi graph being connected.\n\tER graph can be specified as ER(n,p) or ER(n,m), but not ER(n,p,m)\n\tn: number of nodes in graph\n\tp: probability of a given node existing\n\tm: number of edges in graph\n\titers: number of iterations\n\t\"\"\"\n\tif (p==None) & (m==None):\n\t\traise ValueError('prob_connected must have either p or m, but not both')\n\t\n\telif (p!=None) & (m!=None):\n\t\traise ValueError('prob_connected must have either p or m, but not both')\n\n\telif p != None:\n\t\ttf = [is_connected(make_random_graph(n, p)) for i in range(iters)]\n\n\telif m != None:\n\t\ttf = [is_connected(make_m_graph(n, m)) for i in range(iters)]\n\n\treturn np.mean(tf)\n\n\nif __name__ == '__main__':\n\n\t# undirected_graph()\n\n\tnp.random.seed(17)\n\n\tnodes = range(10)\n\tprint(m_pairs(nodes, 6))\n\n\n\t##############\n\t## Displays p(connected) vs. p(node) for various graph sizes\n\t# ns = [300, 100, 30, 10]\n\t# ps = np.logspace(-2.5, 0, 11)\n\t# sns.set_palette('Blues_r', 4)\n\n\t# for n in ns:\n\n\t# \tys = [prob_connected(n, p=p) for p in ps]\n\t# \tpstar = np.log(n) / n\n\t# \tprint(n)\n\t# \tplt.axvline(pstar, color='gray')\n\t# \tplt.plot(ps, ys, label='n=%d' %n)\n\n\t# decorate(xlabel='Prob of edge (p)',\n\t# \t\t\tylabel = 'Prob connected',\n\t# \t\t\txscale = 'log')\n\n\t##############\n\t## Displays p(connected) vs. m edges for various graph sizes\n\t# ns = [300, 100, 30, 10]\n\t# sns.set_palette('Blues_r', 4)\n\n\t# for n in ns:\n\t# \tprint('n: ',n)\n\t# \tmax_m = n*(n-1)/2\n\t# \tps = np.logspace(-2.5, 0, 11)\n\n\t# \tys = [prob_connected(n, m = int(p*max_m)) for p in ps]\n\t# \tpstar = np.log(n) / n\n\t# \tplt.axvline(pstar, color='gray')\n\t# \tplt.plot(ps, ys, label='n=%d' %n)\n\n\t# decorate(xlabel='Prob of edge (p)',\n\t# \t\t\tylabel = 'Prob connected',\n\t# \t\t\txscale = 'log')\n\n\n\t# random_graph = make_random_graph(10, 0.3)\n\t# print('is random directed graph connected?', end=' ')\n\t# print(is_connected( random_graph ))\n\n\t# nx.draw_circular(\tG,\n\t# \t\t\t\t\tnode_color='C2',\n\t# \t\t\t\t\tnode_size=1000,\n\t# \t\t\t\t\twith_labels=True)\n\t\n\t# savefig('myfigs/chap02-6')\n\t# plt.show()","sub_path":"mycode/ch02.py","file_name":"ch02.py","file_ext":"py","file_size_in_byte":6959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"110055977","text":"import adv.adv_test\nfrom core.advbase import *\nfrom slot.a import *\nfrom slot.d import *\n\ndef module():\n return Dragonyule_Nefaria\n\nclass Dragonyule_Nefaria(Adv):\n a1 = ('s',0.25)\n conf = {}\n conf['slot.a'] = Mega_Friends()+Primal_Crisis()\n conf['acl'] = \"\"\"\n `dragon\n `s1, fsc\n `s3, fsc\n `fs, seq=4\n \"\"\"\n coab = ['Blade', 'Xander', 'Thaniel']\n conf['slots.d'] = Leviathan()\n\nif __name__ == '__main__':\n conf = {}\n adv.adv_test.test(module(), conf)\n\n","sub_path":"adv/d_nefaria.py","file_name":"d_nefaria.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"265551000","text":"import sublime, sublime_plugin\nimport os\nimport string, random\nimport pickle\n\nglobal BOOKMARKS\nBOOKMARKS = {}\n\ndef id_generator(size=5, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))\n\ndef save_bookmarks():\n global BOOKMARKS\n storage = os.path.expanduser(\"~\") + os.path.sep + 'dogears.bookmarks'\n storage = os.path.expanduser(\"~\") + os.path.sep + 'dogears.bookmarks'\n storage_file = open(storage, 'wb')\n pickle.dump(BOOKMARKS, storage_file)\n storage_file.close()\n\ndef load_bookmarks(view):\n global BOOKMARKS\n storage = os.path.expanduser(\"~\") + os.path.sep + 'dogears.bookmarks'\n if os.path.lexists(storage):\n storage_file = open(storage, 'rb')\n BOOKMARKS = pickle.load(storage_file)\n storage_file.close()\n\n for key, bookmark in BOOKMARKS.items():\n # Create a region to behave like a bookmark\n view.add_regions('dogears_' + key, bookmark['regions'], \"\", \"bookmark\")\n\n\nclass NewBookmarkCommand(sublime_plugin.TextCommand):\n def run(self, edit):\n sel = self.view.sel()\n\n if not len(sel) == 1:\n # Work only on single selections\n return\n\n if not sel[0].begin() == sel[0].end():\n # Only on single caret selections\n return\n\n point = sel[0].begin()\n self.point = point\n\n self.fileName = self.view.file_name()\n\n window = self.view.window()\n\n defaultString = os.path.basename(self.fileName) + \" - \"\n\n window.show_input_panel(\"Enter Bookmark Name: \", defaultString, self.on_bookmark_name_entered, None, None)\n\n def on_bookmark_name_entered(self, bookmarkName):\n # Create a unique ID for the bookmark\n global BOOKMARKS\n key = id_generator()\n\n bookmark = {}\n bookmark['fileName'] = self.fileName\n bookmark['baseName'] = os.path.basename(self.fileName)\n bookmark['name'] = bookmarkName\n bookmark['regions'] = [s for s in self.view.sel()]\n\n BOOKMARKS[key] = bookmark\n\n # Create a region to behave like a bookmark\n self.view.add_regions('dogears_' + key, bookmark['regions'], \"\", \"bookmark\")\n\n print(\"Saving bookmark {0} at key {1}\".format(bookmarkName, key))\n save_bookmarks()\n\n\nclass BrowseBookmarksCommand(sublime_plugin.TextCommand):\n def run(self, edit):\n global BOOKMARKS\n bookmarkOpts = []\n self.panelKeys = []\n\n load_bookmarks(self.view)\n\n for key, val in BOOKMARKS.items():\n bookmarkOpts.append(val['name'])\n self.panelKeys.append(key)\n\n window = self.view.window()\n\n #window.show_quick_panel(bookmarkOpts, # ST2\n # self.on_bookmark_selected) # ST2\n window.show_quick_panel(bookmarkOpts, # ST3\n self.on_bookmark_selected, # on done \n sublime.MONOSPACE_FONT, # flags\n 0, # index\n self.on_bookmark_selected) # on highlight\n\n def on_bookmark_selected(self, idx):\n global BOOKMARKS\n\n if(idx == -1):\n print(\"No bookmark selected. Returning \")\n return\n\n # Get the key for the bookmark\n key = self.panelKeys[idx]\n\n # Set focus on the which the bookmark was set on\n foundInOpen = False\n\n if not foundInOpen:\n for v in self.view.window().views():\n print(v.file_name())\n if v.file_name() == BOOKMARKS[key]['fileName']:\n self.view.window().focus_view(v)\n foundInOpen = True\n break\n\n if not foundInOpen:\n view = self.view.window().open_file(BOOKMARKS[key]['fileName'])\n self.view.focus_view(view)\n for key, bookmark in BOOKMARKS.items():\n # Create a region to behave like a bookmark\n view.add_regions('dogears_' + key, bookmark['regions'], \"\", \"bookmark\")\n\n # Retrieve the region for the bookmark\n bmRegion = self.view.get_regions(\"dogears_\" + key)\n\n if len(bmRegion) == 0:\n return\n\n self.view.run_command(\"select_all_bookmarks\", {'name':\"dogears_\" + key})\n\n\nclass DeleteBookmarkCommand(sublime_plugin.TextCommand):\n def run(self, edit):\n global BOOKMARKS\n bookmarkOpts = []\n self.panelKeys = []\n\n load_bookmarks(self.view)\n\n for key, val in BOOKMARKS.items():\n bookmarkOpts.append(val['name'])\n self.panelKeys.append(key)\n\n window = self.view.window()\n\n window.show_quick_panel(bookmarkOpts, self.on_bookmark_selected)\n\n def on_bookmark_selected(self, idx):\n global BOOKMARKS\n\n if(idx == -1):\n print(\"No bookmark selected. Returning \")\n return\n\n # Get the key for the bookmark\n key = self.panelKeys[idx]\n bookmarkName = BOOKMARKS[key]['name']\n del BOOKMARKS[key]\n\n # Delete the region for the bookmark\n self.view.erase_regions(\"dogears_\" + key)\n\n print(\"Deleting bookmark {0} at key {1}\".format(bookmarkName, key))\n\n save_bookmarks()","sub_path":"DogEars.py","file_name":"DogEars.py","file_ext":"py","file_size_in_byte":5301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238601183","text":"import logging\nimport os\nimport threading\nimport time\n\nlog = logging.getLogger(__name__)\n\n_WORKER_THREAD = None\n_PID = os.getpid()\n\n_collection_targets = []\n\n\ndef _check_threads_started():\n global _WORKER_THREAD, _PID\n ospid = os.getpid()\n\n if _WORKER_THREAD is None or _PID != ospid:\n\n _PID = ospid\n _WORKER_THREAD = threading.Thread(target=_process, args=(2,))\n _WORKER_THREAD.daemon = True\n _WORKER_THREAD.start()\n\n\ndef _process(interval):\n pid = os.getpid()\n log.info(\"Starting process thread in pid %s\", pid)\n\n while True:\n now = time.time()\n for (\n collection_target,\n connection,\n sender,\n last_called,\n ) in _collection_targets:\n if now - last_called[0] > interval:\n last_called[0] = now\n sender.send(connection, collection_target, now, interval, pid)\n\n time.sleep(0.2)\n\n\ndef add_target(connection, collection_target, sender):\n _collection_targets.append((collection_target, connection, sender, [0]))\n _check_threads_started()\n","sub_path":"sqlalchemy_collectd/client/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"527301390","text":"from rest_framework.exceptions import ValidationError\nfrom rest_framework import serializers\n\nfrom .models import AddressBook, Entry\n\n\nclass AddressBookSerializer(serializers.ModelSerializer):\n class Meta:\n model = AddressBook\n fields = ('id',)\n\n def validate(self, data):\n self._ensure_no_addressbook()\n return data\n\n def _ensure_no_addressbook(self):\n user = self.context['request'].user\n addressbook_exists = AddressBook.objects.filter(owner=user).exists()\n if addressbook_exists:\n raise ValidationError('Address book has been alredy created.')\n\n\nclass EntrySerializer(serializers.ModelSerializer):\n id = serializers.ReadOnlyField()\n\n class Meta:\n model = Entry\n fields = ('id', 'first_name', 'last_name', 'mobile_number', 'address',\n 'email')\n\n def validate(self, data):\n self._ensure_addressbook_exists()\n return data\n\n def _ensure_addressbook_exists(self):\n user = self.context['request'].user\n addressbook_exists = AddressBook.objects.filter(owner=user).exists()\n if not addressbook_exists:\n raise ValidationError('No address book found. Create it first.')\n\n def create(self, validated_data):\n address_book = self.context['request'].user.address_book\n validated_data['address_book'] = address_book\n return super().create(validated_data)\n","sub_path":"apps/contacts/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"516777063","text":"import matplotlib.pyplot as plt\n\n\nclass Visualization:\n \"\"\"Easy neural network training progress visualization.\"\"\"\n\n test = ([0], [0])\n train = ([0], [0])\n cross_entropy = ([], [])\n\n def __init__(self, steps=200):\n \"\"\"Initialize the figure with 2 subplots and 4 line plots.\"\"\"\n self.fig = plt.figure('Digit Classification')\n self.ax1 = self.fig.add_subplot(121)\n self.ax2 = self.fig.add_subplot(122)\n\n self.ax1.set_title('Accuracy')\n self.ax1.set_xlim([0, steps])\n self.ax1.set_ylim([0, 1.1])\n self.ax2.set_title('Loss')\n self.ax2.set_xlim([0, steps])\n self.ax2.set_ylim([0, 100])\n\n self.train_plt, = self.ax1.plot([0], [0])\n self.test_plt, = self.ax1.plot([0], [0])\n self.cross_entropy_plt, = self.ax2.plot([0], [0])\n plt.tight_layout()\n plt.show()\n\n def __call__(self, i, test=None, train=None, cross_entropy=None):\n \"\"\"Update the plot by calling the instance. \n Updates are applied selectively to named arguments. \n \"\"\"\n if test is not None:\n self.test[0].append(i)\n self.test[1].append(test)\n self.test_plt.set_data(*self.test)\n if train is not None:\n self.train[0].append(i)\n self.train[1].append(train)\n self.train_plt.set_data(*self.train)\n if cross_entropy is not None:\n self.cross_entropy[0].append(i)\n self.cross_entropy[1].append(cross_entropy)\n self.cross_entropy_plt.set_data(*self.cross_entropy)\n self.ax1.legend(labels=['Train: {:.4f}'.format(self.train[1][-1]),\n 'Test: {:.4f}'.format(self.test[1][-1])])\n self.ax2.legend(\n labels=['Cross Entropy: {:.4f}'.format(self.cross_entropy[1][-1])])\n self.fig.canvas.draw()\n","sub_path":"src/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"179690768","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/3/23 23:39\n# @Author : Winspain\n# @File : wxpy.py\n# @Software: PyCharm\n# 导入模块\nfrom wxpy import *\nimport requests,json\nimport time\ndef weatherApi():\n #调用和风天气的API city可以通过https://cdn.heweather.com/china-city-list.txt城市列表获取\n url = 'https://free-api.heweather.com/v5/weather?city=CN101210410&key=8a439a7e0e034cdcb4122c918f55e5f3'\n #用urllib2创建一个请求并得到返回结果\n req = requests.get(url)\n resp = req.text\n #将JSON转化为Python的数据结构\n json_data = json.loads(resp)\n city_data=json_data['HeWeather5'][0]\n hourly_data= json_data['HeWeather5'][0]['hourly_forecast']\n daily_data = json_data['HeWeather5'][0]['daily_forecast']\n\n t1 = u'当前时间:' + daily_data[0]['date']\n t2 = u'城市:' + city_data['basic']['city']\n t3 = u'PM指数:' + city_data['aqi']['city']['pm25']\n t4 = u'白天天气:' + daily_data[0]['cond']['txt_d']\n t5 = u'夜间天气:' + daily_data[0]['cond']['txt_n']\n t6 = u'今天{0}: 气温:{1}°/{2}°'.format(str(daily_data[0]['date']),daily_data[0]['tmp']['min'],daily_data[0]['tmp']['max'])\n t7 = u'未来小时天气:{0} {1}'.format(str(hourly_data[0]['date']).split()[1],hourly_data[0]['cond']['txt'])\n t8 = u'未来小时天气:{0} {1}'.format(str(hourly_data[1]['date']).split()[1],hourly_data[1]['cond']['txt'])\n t9 = u'未来小时天气:{0} {1}'.format(str(hourly_data[2]['date']).split()[1],hourly_data[2]['cond']['txt'])\n t10 = u'未来{0} 天气:{1}°/{2}°'.format(daily_data[1]['date'],daily_data[1]['tmp']['min'],daily_data[1]['tmp']['max'])\n t11 = u'未来{0} 天气:{1}°/{2}°'.format(daily_data[2]['date'],daily_data[1]['tmp']['min'],daily_data[2]['tmp']['max'])\n t12 = u'穿衣建议:' + json_data['HeWeather5'][0]['suggestion']['drsg']['txt']\n\n weather = t1+'\\n'+t2+'\\n'+t3+'\\n'+t4+'\\n'+t5+'\\n'+t6+'\\n'+t7+'\\n'+t8+'\\n'+t9+'\\n'+t10+'\\n'+t11+'\\n'+t12\n #print(weather)\n return weather\n\ndef persistenceLogin():\n while True:\n bot = Bot(cache_path=True)\n return bot\nif __name__ == '__main__':\n # 初始化机器人,扫码登陆\n bot = persistenceLogin()\n #bot = Bot(cache_path=True,console_qr=False)\n # xiaomilu = bot.friends().search('小麋鹿')[0]\n # for i in range(24):\n # xiaomilu.send(weatherApi())\n # time.sleep((i+1)*1800)\n for i in range(24):\n go = bot.groups().search('测试')[0]\n # go.send(weatherApi())\n t = time.ctime()\n go.send(t)\n time.sleep(1800)\n embed()","sub_path":"weixinMsg.py","file_name":"weixinMsg.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"191888086","text":"#! /usr/bin/env python\n\n###################################\n# make_ppi_csvfiles.py\n###################################\n\nimport os,re,csv, networkx as nx\ndef visit(c1,c2):\n\treturn min(c1,c2)+','+max(c1,c2)\n\t\npath = '/Users/niamhdurfee/MEGA/data_for_Niamh/'\n\n###############################################\n########### ECOLI ##############\n###############################################\n\nspecies = 'ecoli'\ndictFile = path+'/ppi/str2dom_511145.txt'\npickleFile = path+species+'/pickle_files/'+species\n\n# create a dictionary to translate between strings and PDB domain names\ntmp = [re.split('\\t',line[:-1]) for line in open(dictFile,'r')]\nstrdb2dom_511145 = {line[1][7:12]:re.split(',',line[2]) for line in tmp if line[1][:7] == '511145.'}\n\t# what are the unique string-db that we need\nstrdb = [strdb for strdb in strdb2dom_511145]\n\n# what are the relevant ppi we want (i.e., the string-db \n# we want, and the appropriate types of interactions\ntmp = [re.split('\\t',re.sub('511145.','',line[:-1])) for line in open(path+'ppi/511145.protein.actions.v10.txt','r')]\nppi = [line[:2] for line in tmp if line[0] in strdb and line[1] in strdb and line[2] == 'binding']\n\n# create a set so we only get one version of the interaction \nppi_withdomains = set()\nfor interaction in ppi:\n\t\n\t# get the PDB form of the two interactors\n\tc1 = strdb2dom_511145[interaction[0]]\n\tc2 = strdb2dom_511145[interaction[1]]\n\t\n\t# there may be multiple names for a given ID, so we need to \n\t# go through each\n\tfor chain1 in c1:\n\t\tfor chain2 in c2:\n\t\t\t# we don't care about self interactions\n\t\t\tif not chain1 == chain2:\n\t\t\t\tppi_withdomains.add(visit(chain1.lower(),chain2.lower()))\nppi = [re.split(',',line) for line in ppi_withdomains]\n\n# write these interactions to a CSV file\nf = csv.writer(open(path+species+'/pickle_files/ppi.csv','w'))\nf.writerows(ppi)\n\n###############################################\n########### YEAST ##############\n###############################################\n\nspecies = 'yeast'\ndictFile = path+'ppi/biogrid2dom_559292.txt'\nppiFile = path+'ppi/yeast.biogrid.txt'\n\n# create a dictionary to translate between the biogrid IDs\n# and PDB domain names\ntmp = [re.split('\\t',line[:-1]) for line in open(dictFile)]\ntmp2 = [[re.split(';',line[1][:-1]),re.split(',',line[2])] for line in tmp[1:] if line[1] != '']\nbiogrid2dom = {}\nfor line in tmp2:\n\tfor bio in line[0]:\n\t\tbiogrid2dom[bio] = line[1]\n\n#\tand save all the biogrid IDs that we need for our data set.\nbiogrid = []\nfor i in tmp2:\n\tfor ea in i[0]:\n\t\tbiogrid.append(ea)\n\n# and all the protein protein interactions we need from the data\ntmp = [re.split('\\t',line[:-1]) for line in open(ppiFile)]\nppi = [[line[3],line[4]] for line in tmp if line[12] == 'physical' and line[3] in biogrid and line[4] in biogrid]\n\n# create a set so we only get one version of the interaction \nppi_withdomains = set()\nfor interaction in ppi:\n\t\n\t# get the PDB form of the two interactors\n\tc1 = biogrid2dom[interaction[0]]\n\tc2 = biogrid2dom[interaction[1]]\n\t\n\t# there may be multiple names for a given ID, so we need to \n\t# go through each\n\tfor chain1 in c1:\n\t\tfor chain2 in c2:\n\t\t\t# we don't care about self interactions\n\t\t\tif not chain1 == chain2:\n\t\t\t\tppi_withdomains.add(visit(chain1.lower(),chain2.lower()))\nppi = [re.split(',',line) for line in ppi_withdomains]\n\n# write these interactions to a CSV file\nf = csv.writer(open(path+species+'/pickle_files/ppi.csv','w'))\nf.writerows(ppi)","sub_path":"scripts/make_ppi_csvfiles.py","file_name":"make_ppi_csvfiles.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"333936665","text":"from turtle import*\nclass Ball:\n def __init__(self,color,size,speed):\n self.x = 0\n self.y = 0\n self.speed = speed\n self.size = size\n self.color = color\n \n self.turtle = Turtle()\n self.turtle.shape(\"circle\")\n self.turtle.shapesize(self.size)\n self.turtle.color(self.color)\n \n\n def move(self):\n self.x +=self.speed\n self.y +=self.speed\n self.turtle.goto(self.x,self.y)\n \nball = Ball(\"red\",2,1)\nfor i in range(100):\n ball.move()\n\n \n \n","sub_path":"CT_python/HW12/lab02.py","file_name":"lab02.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"221833361","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\n# 伊孑志の雨量\nURL = \"http://www03.city.takarazuka.hyogo.jp/ht/01.html\"\n\n\ndef get_rainfall():\n html = requests.get(URL)\n soup = BeautifulSoup(html.content, \"lxml\")\n titen_hyou = soup.find(\"div\", id=\"titen-hyou\")\n trs = titen_hyou.find_all(\"tr\")\n return (\n __extract_rainfall(trs, 6),\n __extract_rainfall(trs, 10)\n )\n\n\ndef __extract_rainfall(trs, index):\n return float(trs[index].string.replace(\"mm\", \"\"))\n\n\nif __name__ == '__main__':\n one_hour, continuous = get_rainfall()\n print(one_hour, continuous)\n","sub_path":"phrases/lib/get_rainfall.py","file_name":"get_rainfall.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"235523108","text":"# Copyright 2019-present Kensho Technologies, LLC.\n\"\"\"Helpers for rewriting GraphQL AST objects using structural sharing.\"\"\"\nfrom copy import copy\n\nfrom graphql.language.ast import (\n Argument, Field, InlineFragment, ListValue, Name, OperationDefinition, SelectionSet,\n StringValue\n)\n\nfrom ...compiler.helpers import get_parameter_name, is_tagged_parameter\nfrom ...schema import FilterDirective, TagDirective\nfrom ..macro_edge.directives import MacroEdgeTargetDirective\n\n\ndef _replace_tag_names_in_tag_directive(name_change_map, tag_directive):\n \"\"\"Apply tag parameter renaming to the given tag directive.\n\n Args:\n name_change_map: Dict[str, str] mapping tag names to new names\n tag_directive: GraphQL library tag directive whose name is in the name_change_map.\n This ast is not mutated.\n\n Returns:\n GraphQL library directive object, equivalent to the input one, with its name changed\n according to the name_change_map. If no changes were made, this is the same object\n as the input tag directive.\n \"\"\"\n # Schema validation has ensured this exists\n current_name = tag_directive.arguments[0].value.value\n new_name = name_change_map[current_name]\n\n if new_name == current_name:\n # No changes are necessary, return the original input object.\n return tag_directive\n\n renamed_tag_directive = copy(tag_directive)\n renamed_tag_directive.arguments = [Argument(Name('tag_name'), StringValue(new_name))]\n return renamed_tag_directive\n\n\ndef _replace_tag_names_in_filter_directive(name_change_map, filter_directive):\n \"\"\"Apply tag parameter renaming to the given filter directive.\n\n Args:\n name_change_map: Dict[str, str] mapping tag names to new names\n filter_directive: GraphQL library filter directive object that potentially uses\n tagged parameters. All such tagged parameters should be in\n the name_change_map. This directive object is not mutated,\n and if no changes are necessary then it will be returned\n\n Returns:\n GraphQL library directive object, equivalent to the input one, with any tagged parameters it\n uses replaced according to the name_change_map. If no changes were made, this is the\n same object as the input filter directive.\n \"\"\"\n made_changes = False\n\n new_arguments = []\n for argument in filter_directive.arguments:\n if argument.name.value == 'op_name':\n new_arguments.append(argument)\n elif argument.name.value == 'value':\n new_value_list = []\n for value in argument.value.values:\n parameter = value.value\n new_value = value\n\n # Rewrite tagged parameter names if necessary.\n if is_tagged_parameter(parameter):\n current_name = get_parameter_name(parameter)\n new_name = name_change_map[current_name]\n if new_name != current_name:\n made_changes = True\n new_value = StringValue('%' + new_name)\n\n new_value_list.append(new_value)\n\n if made_changes:\n new_argument = Argument(Name('value'), value=ListValue(new_value_list))\n else:\n new_argument = argument\n new_arguments.append(new_argument)\n else:\n raise AssertionError(u'Unknown argument name {} in filter directive {}, this should '\n u'have been caught in an earlier validation step.'\n .format(argument.name.value, filter_directive))\n\n if not made_changes:\n # No changes were made, return the original input object.\n return filter_directive\n\n filter_with_renamed_args = copy(filter_directive)\n filter_with_renamed_args.arguments = new_arguments\n return filter_with_renamed_args\n\n\ndef _replace_tag_names_in_directives(name_change_map, directives):\n \"\"\"Return directives with tag names replaced according to the name_change_map.\n\n Args:\n name_change_map: Dict[str, str] mapping all tag names in the ast to new names\n directives: list of GraphQL library directive objects in which we want to replace tag names.\n\n Returns:\n list of GraphQL library directive objects, equivalent to the input ones, with tag names\n renamed according to the name_change_map. If no changes were made, this is the\n same object as the input directives list.\n \"\"\"\n # Rename tag names in @tag and @filter directives, and record if we made changes\n made_changes = False\n new_directives = []\n for directive in directives:\n if directive.name.value == TagDirective.name:\n renamed_tag_directive = _replace_tag_names_in_tag_directive(name_change_map, directive)\n made_changes_to_tag = directive is not renamed_tag_directive\n\n made_changes = made_changes or made_changes_to_tag\n new_directives.append(renamed_tag_directive)\n elif directive.name.value == FilterDirective.name:\n filter_with_renamed_args = _replace_tag_names_in_filter_directive(\n name_change_map, directive)\n made_changes_to_filter = directive is not filter_with_renamed_args\n\n made_changes = made_changes or made_changes_to_filter\n new_directives.append(filter_with_renamed_args)\n else:\n new_directives.append(directive)\n\n if made_changes:\n return new_directives\n else:\n return directives\n\n\n# ############\n# Public API #\n# ############\n\ndef replace_tag_names(name_change_map, ast):\n \"\"\"Return a new ast with tag names replaced according to the name_change_map.\n\n Args:\n name_change_map: Dict[str, str] mapping all tag names in the ast to new names\n ast: GraphQL library AST object, such as a Field, InlineFragment, or OperationDefinition\n This ast is not mutated.\n\n Returns:\n GraphQL library AST object, equivalent to the input one, with all tag names replaced\n according to the name_change_map. If no changes were made, this is the same object\n as the input.\n \"\"\"\n if not isinstance(ast, (Field, InlineFragment, OperationDefinition)):\n return ast\n\n made_changes = False\n\n # Recurse into selections.\n new_selection_set = None\n if ast.selection_set is not None:\n new_selections = []\n for selection_ast in ast.selection_set.selections:\n new_selection_ast = replace_tag_names(name_change_map, selection_ast)\n\n if selection_ast is not new_selection_ast:\n # Since we did not get the exact same object as the input, changes were made.\n # That means this call will also need to make changes and return a new object.\n made_changes = True\n\n new_selections.append(new_selection_ast)\n new_selection_set = SelectionSet(new_selections)\n\n # Process the current node's directives.\n directives = ast.directives\n new_directives = _replace_tag_names_in_directives(name_change_map, directives)\n made_changes = made_changes or (directives is not new_directives)\n\n if not made_changes:\n # We didn't change anything, return the original input object.\n return ast\n\n new_ast = copy(ast)\n new_ast.selection_set = new_selection_set\n new_ast.directives = new_directives\n return new_ast\n\n\ndef remove_directives_from_ast(ast, directive_names_to_omit):\n \"\"\"Return an equivalent AST to the input, but with instances of the named directives omitted.\n\n Args:\n ast: GraphQL library AST object, such as a Field, InlineFragment, or OperationDefinition\n directive_names_to_omit: set of strings describing the names of the directives to omit\n\n Returns:\n GraphQL library AST object, equivalent to the input one, with all instances of\n the named directives omitted. If the specified directives do not appear in the input AST,\n the returned object is the exact same object as the input.\n \"\"\"\n if not isinstance(ast, (Field, InlineFragment, OperationDefinition)):\n return ast\n\n made_changes = False\n\n new_selection_set = None\n if ast.selection_set is not None:\n new_selections = []\n for selection_ast in ast.selection_set.selections:\n new_selection_ast = remove_directives_from_ast(selection_ast, directive_names_to_omit)\n\n if selection_ast is not new_selection_ast:\n # Since we did not get the exact same object as the input, changes were made.\n # That means this call will also need to make changes and return a new object.\n made_changes = True\n\n new_selections.append(new_selection_ast)\n new_selection_set = SelectionSet(new_selections)\n\n directives_to_keep = [\n directive\n for directive in ast.directives\n if directive.name.value not in directive_names_to_omit\n ]\n if len(directives_to_keep) != len(ast.directives):\n made_changes = True\n\n if not made_changes:\n # We didn't change anything, return the original input object.\n return ast\n\n new_ast = copy(ast)\n new_ast.selection_set = new_selection_set\n new_ast.directives = directives_to_keep\n return new_ast\n\n\ndef omit_ast_from_ast_selections(ast, ast_to_omit):\n \"\"\"Return an equivalent AST to the input, but with the specified AST omitted if it appears.\n\n Args:\n ast: GraphQL library AST object, such as a Field, InlineFragment, or OperationDefinition\n ast_to_omit: GraphQL library AST object, the *exact same* object that should be omitted.\n This function uses reference equality, since deep equality can get expensive.\n\n Returns:\n GraphQL library AST object, equivalent to the input one, with all instances of\n the specified AST omitted. If the specified AST does not appear in the input AST,\n the returned object is the exact same object as the input.\n \"\"\"\n if not isinstance(ast, (Field, InlineFragment, OperationDefinition)):\n return ast\n\n if ast.selection_set is None:\n return ast\n\n made_changes = False\n\n selections_to_keep = []\n for selection_ast in ast.selection_set.selections:\n if selection_ast is ast_to_omit:\n # Drop the current selection.\n made_changes = True\n else:\n new_selection_ast = omit_ast_from_ast_selections(selection_ast, ast_to_omit)\n if new_selection_ast is not selection_ast:\n # The current selection contained the AST to omit, and was altered as a result.\n made_changes = True\n selections_to_keep.append(new_selection_ast)\n\n if not made_changes:\n return ast\n\n new_ast = copy(ast)\n if not selections_to_keep:\n new_ast.selection_set = None\n else:\n new_ast.selection_set = SelectionSet(selections_to_keep)\n\n return new_ast\n\n\ndef find_target_and_copy_path_to_it(ast):\n \"\"\"Copy the AST objects on the path to the target, returning the copied AST and the target AST.\n\n This function makes it easy to make changes to the AST at the macro edge target directive while\n using structural sharing, i.e. without mutating the original object while doing the minimum\n amount of copying necessary:\n - If called with an AST that does not contain a macro edge target directive, it is guaranteed to\n produce the original AST input object as part of the result, instead of making a copy.\n - If called with an AST that does contain that directive, it will return a new AST object that\n has copies for all AST objects on the traversal path toward the AST containing the directive,\n together with a shallow copy of the AST object that contains the directive itself.\n\n Args:\n ast: GraphQL library AST object\n\n Returns:\n tuple containing:\n - GraphQL library AST object equivalent to the input AST. Objects on the path to the\n macro edge target directive are shallow-copied.\n - GraphQL library AST object at the macro edge target directive of the resulting AST,\n or None if there was no such directive in the AST.\n \"\"\"\n # Base case\n for directive in ast.directives:\n if directive.name.value == MacroEdgeTargetDirective.name:\n target_ast = copy(ast)\n return target_ast, target_ast\n\n # Recurse\n new_selections = []\n target_ast = None\n if isinstance(ast, (Field, InlineFragment, OperationDefinition)):\n if ast.selection_set is not None:\n for selection in ast.selection_set.selections:\n new_selection, possible_target_ast = find_target_and_copy_path_to_it(selection)\n new_selections.append(new_selection)\n if possible_target_ast is not None:\n target_ast = possible_target_ast\n else:\n raise AssertionError(u'Unexpected AST type received: {} {}'.format(type(ast), ast))\n\n if target_ast is None:\n return ast, None\n else:\n new_ast = copy(ast)\n new_ast.selection_set = SelectionSet(new_selections)\n return new_ast, target_ast\n","sub_path":"graphql_compiler/macros/macro_edge/ast_rewriting.py","file_name":"ast_rewriting.py","file_ext":"py","file_size_in_byte":13316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"536472535","text":"'''Import Extra Modules'''\nimport os\n\nimport PyQt4.QtCore #@UnresolvedImport\nimport PyQt4.QtGui #@UnresolvedImport\nimport PyQt4.uic #@UnresolvedImport\n\nimport logging\n\n\ndef supression_warnings():\n PyQt4.uic.properties.logger.setLevel( logging.WARNING )\n PyQt4.uic.uiparser.logger.setLevel( logging.WARNING )\n\ndef window_stay_on_top( value, ui_name ):\n flags = ui_name.windowFlags()\n\n if value:\n ui_name.setWindowFlags( flags | PyQt4.QtCore.Qt.WindowStaysOnTopHint )\n\n else:\n ui_name.setWindowFlags( flags & ~PyQt4.QtCore.Qt.WindowStaysOnTopHint )\n\n'''\n========================================================================\n----> Procedure adds and removes index from given QComboBox <----\n========================================================================\n'''\ndef add_remove_combo( combo, add = False, remove = False, data = '' ):\n if add:\n if data != '':\n combo.addItem ( data )\n list_count = combo.count()\n combo.setCurrentIndex( list_count - 1 )\n\n if remove:\n current_index = combo.currentIndex ()\n combo.removeItem ( current_index )\n\n'''\n========================================================================\n----> Procedure returns all items in given QComboBox <----\n========================================================================\n'''\ndef get_combo_items( combo ):\n items = []\n\n count_items = combo.count()\n\n for i in range( count_items ):\n items.append( str( combo.itemText( i ) ) )\n\n return items\n\n'''\n========================================================================\n----> Procedure searches given QComboBox for passed item <----\n========================================================================\n'''\ndef search_combo_items( combo, item ):\n count_items = combo.count()\n\n if count_items != 0:\n for i in range( count_items ):\n if item == str( combo.itemText( i ) ):\n item_value = i\n break\n\n else:\n item_value = None\n\n return item_value\n\n else:\n return None\n\n'''\n========================================================================\n----> Procedure adds items to given QTableWidget <----\n========================================================================\n'''\ndef add_table_item( table, items ):\n row = table.rowCount()\n table.insertRow( row )\n\n column = 0\n\n for item in items:\n item = PyQt4.QtGui.QTableWidgetItem( item )\n table.setItem ( row, column, item )\n column += 1\n\n'''\n========================================================================\n----> Procedure removes selected rows from given QTableWidget <----\n========================================================================\n'''\ndef remove_selected_table_row( table ):\n sel_rows = table.selectionModel().selectedRows()\n\n if sel_rows != []:\n for sel_row in reversed( sel_rows ):\n table.removeRow( sel_row.row() )\n\n'''\n========================================================================\n----> Procedure returns selected items from given QTableWidget <----\n========================================================================\n'''\ndef get_selected_table_items( table ):\n column_count = table.columnCount()\n sel_rows = table.selectionModel().selectedRows()\n\n items = []\n\n if sel_rows != []:\n for row in sel_rows:\n for column in range( column_count ):\n items.append( str( table.item( row.row(), column ).text() ) )\n\n return items\n'''\n========================================================================\n----> Procedure sets passed directory to self.dir_line <----\n========================================================================\n'''\ndef set_line( line, data ):\n line.setText( str( data ) )\n\n'''\n========================================================================\n----> Procedure searches for passed directory if is dosn't exist\ncreate it <----\n========================================================================\n'''\ndef get_directory( file_location ):\n file_directory = os.path.dirname( file_location )\n\n if not os.path.exists( file_directory ):\n os.makedirs( file_directory )\n\n'''\n========================================================================\n----> Procedure create a QMessageBox and will return reply <----\n========================================================================\n'''\ndef yes_no_dialog( self, name, message ):\n reply = PyQt4.QtGui.QMessageBox.question( self, name, message,\n PyQt4.QtGui.QMessageBox.Yes | \n PyQt4.QtGui.QMessageBox.No )\n\n if reply == PyQt4.QtGui.QMessageBox.Yes:\n return True\n\n elif reply == PyQt4.QtGui.QMessageBox.No:\n return False\n","sub_path":"python/packages/oop_python/core/py_pyqt.py","file_name":"py_pyqt.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"5543757","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /root/singa_auto/utils/service.py\n# Compiled at: 2020-04-23 12:22:03\n# Size of source mod 2**32: 2386 bytes\nimport os, signal, traceback, logging\nfrom datetime import datetime\nfrom singa_auto.utils.log import configure_logging\nlogger = logging.getLogger(__name__)\ncurr_time = datetime.now().strftime('%d-%m-%Y_%I-%M-%S_%p')\n\ndef run_worker(meta_store, start_worker, stop_worker):\n service_id = os.environ['SINGA_AUTO_SERVICE_ID']\n service_type = os.environ['SINGA_AUTO_SERVICE_TYPE']\n container_id = os.environ.get('HOSTNAME', 'localhost')\n configure_logging('{}-ServiceID-{}-ContainerID-{}'.format(curr_time, service_id, container_id))\n\n def _sigterm_handler(_signo, _stack_frame):\n logger.warn('Terminal signal received: %s, %s' % (_signo, _stack_frame))\n stop_worker()\n exit(0)\n\n signal.signal(signal.SIGINT, _sigterm_handler)\n signal.signal(signal.SIGTERM, _sigterm_handler)\n with meta_store:\n service = meta_store.get_service(service_id)\n meta_store.mark_service_as_running(service)\n try:\n logger.info('Starting worker \"{}\" for service of ID \"{}\"...'.format(container_id, service_id))\n start_worker(service_id, service_type, container_id)\n logger.info('Stopping worker...')\n stop_worker()\n except Exception as e:\n logger.error('Error while running worker:')\n logger.error(traceback.format_exc())\n with meta_store:\n service = meta_store.get_service(service_id)\n meta_store.mark_service_as_errored(service)\n stop_worker()\n raise e","sub_path":"pycfiles/singa_auto-0.2.1-py2.py3-none-any/service.cpython-36.py","file_name":"service.cpython-36.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"590901884","text":"from rest_framework import serializers\nfrom email_validation.models import EmailValidation\nfrom placed_user.serializers import PlacedUserSerializer\n\n\nclass EmailValidationSerializer(serializers.ModelSerializer):\n used_by = PlacedUserSerializer()\n requested_by = PlacedUserSerializer()\n\n class Meta:\n model = EmailValidation\n depth = 2\n\n\nclass EmailValidationCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = EmailValidation\n fields = ('type', 'email', 'first_name', 'last_name', 'requested_by', 'group')\n","sub_path":"django-apps/placed_backend/email_validation/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"93350618","text":"import torch\n\nfrom torch.utils._pytree import tree_map\nfrom functools import partial\nfrom torch.fx.operator_schemas import normalize_function\nfrom torch.utils._mode_utils import no_dispatch\nfrom torch._subclasses.meta_utils import MetaConverter\nfrom typing import Union\nfrom torch._ops import OpOverload\nfrom torch.utils._python_dispatch import TorchDispatchMode\nimport functools\n\naten = torch.ops.aten\n\n_device_not_kwarg_ops = (\n aten._resize_output_.default,\n aten.nested_tensor.default,\n aten.pin_memory.default,\n aten.is_pinned.default,\n aten.to.device,\n aten.to.prim_Device,\n aten._pin_memory.default,\n aten._resize_output.functional,\n aten._resize_output.out,\n)\n\n# this op is never actually used\n_non_kwarg_device_constructors = (torch.ops.aten._list_to_tensor,)\n\ndef contains_tensor_types(type):\n tensor_type = torch._C.TensorType.get()\n return type.isSubtypeOf(tensor_type) or any(\n contains_tensor_types(e) for e in type.containedTypes()\n )\n\n\n@functools.lru_cache(None)\ndef _is_tensor_constructor(func: OpOverload):\n assert isinstance(func, OpOverload)\n schema = func._schema\n if any(contains_tensor_types(arg.type) for arg in schema.arguments):\n return False\n # TODO: no real reason to restrict multiple outputs\n return (\n len(schema.returns) == 1 and schema.returns[0].type is torch._C.TensorType.get()\n )\n\n\n# Similar to `MetaConverter`, this is a class for converting\n# multiple tensors into fake tensors which share the same view/storage\n# structure. Like `MetaConverter`, it will keep alive all\n# tensors that are converted to FakeTensors.\nclass FakeTensorConverter(MetaConverter):\n def __init__(self):\n self.tensor_memo = {}\n self.meta_converter = MetaConverter()\n\n def from_real_tensor(self, t):\n existing_device = t.device\n self.tensor_memo[t] = FakeTensor(self.meta_converter(t), existing_device)\n return self.tensor_memo[t]\n\n def from_meta_and_device(self, t, device):\n if t in self.tensor_memo:\n return self.tensor_memo[t]\n self.tensor_memo[t] = FakeTensor(t, device)\n return self.tensor_memo[t]\n\n def __call__(self, t, device=None):\n assert t.device.type != 'meta' or device is not None\n if t in self.tensor_memo:\n return self.tensor_memo[t]\n elif t.device.type != 'meta':\n return self.from_real_tensor(t)\n else:\n return self.from_meta_and_device(t, device)\n\n\n\n# Meta tensors give you the ability to run PyTorch code without having to\n# actually do computation through tensors allocated on a `meta` device.\n# Because the device is `meta`, meta tensors do not model device propagation.\n# FakeTensor extends MetaTensors to also carry an additional `fake_device`\n# which tracks devices that would have been used.\n\ndef torch_dispatch_impl(cls_or_mode_instance, func, types, args, kwargs, run_function):\n kwargs = kwargs if kwargs else {}\n in_fake_mode = isinstance(cls_or_mode_instance, FakeTensorMode)\n converter = cls_or_mode_instance.fake_tensor_converter if in_fake_mode else FakeTensorConverter()\n\n # This classes virtualizes .device() calls, need to short-circuit\n # it instead of calling device again or we would keep on recurring\n if func == torch.ops.prim.device.default:\n assert len(args) == 1 and isinstance(args[0], FakeTensor)\n return args[0].fake_device\n\n def wrap(e, device=None):\n if isinstance(e, torch.Tensor) and not isinstance(e, FakeTensor):\n return converter(e, device)\n else:\n return e\n\n # if we are in the dispatch mode, we will enter this function even if the inputs\n # are not FakeTensors. For now, throw if any non-Fake Tensor inputs\n # and just support constructors. TODO: extend more broadly\n if isinstance(cls_or_mode_instance, FakeTensorMode):\n conversion_made = False\n\n def check_non_fake_tensor(x):\n nonlocal conversion_made\n conversion_made = conversion_made or (isinstance(x, torch.Tensor) and not isinstance(x, FakeTensor))\n\n tree_map(check_non_fake_tensor, args)\n tree_map(check_non_fake_tensor, kwargs)\n\n if conversion_made:\n raise Exception(\n \"Invoking operators with non-Fake Tensor inputs in FakeTensorMode is not yet supported. \"\n f\"Please convert all Tensors to FakeTensors first. Found in {func}\"\n )\n\n # _to_copy fails when run with FakeTensors to cuda device\n # TODO: debug\n if func == torch.ops.aten._to_copy.default:\n _, new_kwargs = normalize_function(\n func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True\n )\n out_device = new_kwargs.pop(\"device\", new_kwargs[\"input\"].device)\n with no_dispatch():\n input = new_kwargs.pop(\"input\").to(\"meta\")\n return FakeTensor(\n torch.ops.aten._to_copy(input, **new_kwargs), out_device\n )\n\n if _is_tensor_constructor(func):\n assert func not in _non_kwarg_device_constructors\n _, new_kwargs = normalize_function(\n func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True\n )\n # cpu is default device if none is specified\n out_device = new_kwargs.pop(\"device\", torch.device(\"cpu\"))\n new_kwargs[\"device\"] = torch.device(\"meta\")\n r = run_function(func, types, (), new_kwargs)\n return FakeTensor(r, out_device)\n\n r = run_function(func, types, args, kwargs)\n\n # TODO: handle non-kwarg devices\n assert func not in _device_not_kwarg_ops, f\"NYI: {func}\"\n\n # if device is specified, use that\n if kwargs.get(\"device\", None):\n return tree_map(partial(wrap, device=kwargs[\"device\"]), r)\n\n # operators which copy size from another tensor do not\n # also take device from the size tensor\n # other size_as operators are not builtin operators\n if func == aten.resize_as_.default:\n _, new_kwargs = normalize_function(\n func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True\n )\n # device of the input is returned\n return tree_map(partial(wrap, device=new_kwargs[\"input\"].device), r)\n\n common_device = FakeTensor._find_common_device(func, args, kwargs)\n\n return tree_map(partial(wrap, device=common_device), r)\n\n\nclass FakeTensor(torch.Tensor):\n fake_device: torch.device\n\n @staticmethod\n def __new__(cls, elem, device):\n return torch.Tensor._make_subclass(\n cls, elem, elem.requires_grad, dispatch_device=True\n )\n\n def __init__(self, elem, device: Union[torch.device, str]):\n # elem does not need to be recorded, because FakeTensor *is a* elem\n assert elem.device.type == \"meta\"\n device = device if isinstance(device, torch.device) else torch.device(device)\n self.fake_device = device\n\n @staticmethod\n def from_tensor(t):\n existing_device = t.device\n return FakeTensor(t.to(device=\"meta\"), existing_device)\n\n # TODO: resolve error in default __repr__\n def __repr__(self):\n return f\"FakeTensor({self.fake_device})\"\n\n @classmethod\n def __torch_dispatch__(cls, func, types, args=(), kwargs=None):\n def run_fn(func, types, args, kwargs):\n return torch.Tensor.__torch_dispatch__(func, types, args, kwargs)\n return torch_dispatch_impl(cls, func, types, args, kwargs, run_fn)\n\n @staticmethod\n def _find_common_device(func, args, kwargs):\n # cpu - zero-dim tensors can be called in cuda kernels,\n # so overwrite the common_device if it the only existing\n # device comes from a cpu zero-dim tensor\n common_device = None\n is_cpu_zero_dim = None\n\n def cpu_zero_dim(t):\n return t.device.type == \"cpu\" and t.dim() == 0\n\n def merge_devices(t):\n nonlocal common_device\n nonlocal is_cpu_zero_dim\n if not isinstance(t, FakeTensor):\n return\n\n if common_device is None:\n common_device = t.device\n is_cpu_zero_dim = cpu_zero_dim(t)\n return\n\n t_is_cpu_zero_dim = cpu_zero_dim(t)\n if t.device == common_device:\n if is_cpu_zero_dim:\n is_cpu_zero_dim = t_is_cpu_zero_dim\n return\n\n # mismatching devices !\n # if current tensor is cpu 0 dim, defer to existing device\n if t_is_cpu_zero_dim:\n return\n\n # current device is from cpu 0 dim tensor, overwrite\n if is_cpu_zero_dim:\n common_device = t.device\n is_cpu_zero_dim = t_is_cpu_zero_dim\n return\n\n # mismatching devices of non-zero dim tensors, throw\n # This might be valid behavior and need to be explicitly modeled, e.g. reshape_as\n raise Exception(\n f\"Unhandled FakeTensor Device Propagation for {func}, found two different devices {common_device}, {t.device}\"\n )\n\n tree_map(merge_devices, args)\n tree_map(merge_devices, kwargs)\n\n assert common_device is not None, f\"Could not find common device for {func}\"\n\n return common_device\n\n __torch_function__ = torch._C._disabled_torch_function_impl\n\n\n# We keep one instantiation of `fake_tensor_converter` active\n# for the duration of `with torch_enable_mode(FakeTensorMode)`.\n# This allows accurate storage aliasing across invocation of\n# different operators. While this will keep all freshly allocated\n# tensors alive during `FakeTensorMode`, there will no be no\n# new allocations of Tensors which have non-meta storage so\n# memory should not significantly incraese.\n\nclass FakeTensorMode(TorchDispatchMode):\n def __init__(self):\n self.fake_tensor_converter = FakeTensorConverter()\n\n def __torch_dispatch__(self, func, types, args=(), kwargs=None):\n def run_fn(func, types, args, kwargs):\n return func(*args, **kwargs)\n return torch_dispatch_impl(self, func, types, args, kwargs, run_fn)\n","sub_path":"torch/_subclasses/fake_tensor.py","file_name":"fake_tensor.py","file_ext":"py","file_size_in_byte":10136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"71487685","text":"def main():\n n, v = map(int, input().split())\n a = [int(input()) for _ in range(n)]\n result = -1\n for i in a:\n if i == v and i > result:\n result = i\n print(result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/python/book_programming_solution/chap03/q_1.py","file_name":"q_1.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"216973416","text":"import cv2\nimport numpy as np\n\nfrom core.randaugment.augment import *\n\nimages = np.load('./dataset/cifar10@4000/unlabeled_1.npy', allow_pickle = True)\n\naugment = RandAugment()\n\nfor u, ua in images:\n _ui = cv2.resize(u, (112, 112))\n _uai = cv2.resize(ua, (112, 112))\n \n cv2.imshow('show', _ui)\n cv2.imshow('show with augment', _uai)\n cv2.waitKey(0)\n\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"370311529","text":"import os\r\n\r\ndirectories = {\r\n 'downloadDir': 'Download',\r\n 'libFolder': 'Lib',\r\n 'buildDir': os.path.abspath('Build'),\r\n 'tools_path': os.path.abspath('Tools'),\r\n 'project_dir': os.getcwd()\r\n}\r\n\r\ndependencies = {\r\n 'nginx': {\r\n 'version': '1.5.4',\r\n 'zlib_version': '1.2.8',\r\n 'pcre_version': '8.37',\r\n 'openssl_version': '1.0.2d',\r\n 'rebuild': True\r\n },\r\n # 'nodejs': {\r\n # 'rebuild': True\r\n # }\r\n}\r\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"17910535","text":"#coding:utf-8\r\n'''\r\nCreated on 2018年1月9日\r\n\r\n@author: qiujiahao\r\n\r\n@email:997018209@qq.com\r\n\r\n'''\r\n \r\nfrom flask import jsonify\r\nfrom conf import *\r\nfrom cnn.data import data as cnn_data\r\nfrom flask import Flask\r\nfrom flask import request,render_template\r\nfrom server.app import app\r\nimport tensorflow as tf\r\nimport module\r\nimport json \r\n\r\nargs=get_args()\r\nprint('当前配置参数列表:\\n{}'.format(args))\r\ncnn_data=cnn_data(args)\r\ncnn_module=module.cnn_module(args,cnn_data)\r\n\r\n@app.route('/deep_chat/v2',methods=[\"POST\"])\r\ndef chat():\r\n client_params=request.get_json(force=True)\r\n server_param={}\r\n if client_params['method'] == 'chat':\r\n cnn_module.predict(client_params,server_param)\r\n elif client_params['method'] == 'retrain':\r\n cnn_module.train(client_params,server_param)\r\n elif client_params['method'] == 'lookup':\r\n cnn_module.lookup(client_params,server_param)\r\n elif client_params['method'] == 'live':\r\n params={'success':'true'}\r\n server_param['result']=params\r\n \r\n server_param['id']=client_params['id']\r\n server_param['jsonrpc']=client_params['jsonrpc']\r\n server_param['method']=client_params['method']\r\n print(server_param)\r\n return json.dumps(server_param, ensure_ascii=False).encode(\"utf-8\")\r\n","sub_path":"11.人机对话第二次验收版本/对话_第二版/server/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"602691443","text":"import re\nimport shlex\nimport os\nimport markdown\nfrom django.templatetags.static import static\n\n### Regular Expressions #######################################################\n\n# Tile: anything before at least three equal signs at the start of a line\ntitle_re = re.compile(r'^(?P.*?)\\s*\\n={3}=*\\s*?$',\n re.DOTALL | re.MULTILINE)\n\n# Teaser: block of text between `[[[` and `]]]`\nteaser_re = re.compile(r'\\[\\[\\[\\s*(?P<teaser>.*?)\\s*\\]\\]\\]\\s*?$',\n re.DOTALL | re.MULTILINE)\n\n# Tag: `@tags` set meta-data about the story\ndef tag_re(tagname):\n # start of line\n # optional space\n # \"@tagname\"\n # at least one space (if there are ags)\n # args\n # trailing white space, end of line\n tag_pattern = r'^\\s*?@{}(?:\\s+(?P<args>.*?))?\\s*?$'.format(tagname)\n return re.compile(tag_pattern, re.MULTILINE)\n\n# Key-word Arguments: utility for parsing out arguments in blocks\ndef parse_kwargs(kwarg_str):\n kwarg_p = r'^\\s*(?P<kw>\\S*?)\\s*=\\s*(?P<quote>[\",\\'])(?P<arg>.*?)(?<!\\\\)(?P=quote)\\s*$'\n kwarg_re = re.compile(kwarg_p, re.DOTALL | re.MULTILINE)\n kwargs = {}\n for kv in re.finditer(kwarg_re, kwarg_str):\n kv_dict = kv.groupdict()\n kwargs.update({kv_dict['kw']: kv_dict['arg']})\n return kwargs\n\n# Blocks: inside curly braces with a `@name` and keyword arguments\ndef block_re(blockname):\n bp = r'^\\s*?{{\\s*?@{}\\s*?(?:\\s+(?P<args>.*?))?\\s*}}\\s*?$'.format(blockname)\n return re.compile(bp, re.DOTALL | re.MULTILINE)\n\n###############################################################################\n\n\n\n### Parsers ###################################################################\n\n### Tag Parsers: these determine how a tag's arguments will be interpreted to\n# form the \"value\" of the meta-data specified by the tag\n\n# Parse everything on the line with the tag as the value\ndef parse_tag_wholeline(args):\n return str(args)\n\n# Parse the rest of the line as a comma-separated list of values\ndef parse_tag_csv(args):\n return [a.strip() for a in args.split(',')]\n\n\n### Block Parsers: these determine what HTML will replace the block in the text\n# of the story\n\n# Graph Block\ndef parse_block_graph(img_path, title=None, subtitle=None, footnote=None):\n title_html = ''\n if not title is None:\n title_html = '<div class=\"title\">{}</div>'.format(title)\n\n subtitle_html = ''\n if not subtitle is None:\n subtitle = markdown.markdown(subtitle)\n subtitle_html = '<div class=\"subtitle\">{}</div>'.format(subtitle)\n\n img_url = static(img_path)\n body_html = '<a href={src} class=\"no-change\">'.format(src=img_url)\n body_html += '<img src={src} width=100% />'.format(src=img_url)\n body_html += '</a>'\n\n footnote_html = ''\n if not footnote is None:\n footnote = markdown.markdown(footnote)\n footnote_html = '<div class=\"footnote\">{}</div>'.format(footnote)\n\n html = [\n '<div class=\"graph-shortcode-wrapper\">',\n title_html,\n subtitle_html,\n body_html,\n footnote_html,\n '</div>',\n ]\n return os.linesep.join(html)\n\n# Quote Block\ndef parse_block_quote(quote, name=None, source=None, side = \"left\"):\n blockquote_class = \"blockquote\"\n if side.lower() == \"right\":\n blockquote_class = ' '.join([blockquote_class, \"blockquote-reverse\"])\n\n quote_html = '<p class=\"mb-0\">{}</p>'.format(quote)\n\n source_html = None\n if source is not None:\n source_html = '<cite title=\"{0}\">{0}</cite>'.format(source)\n\n footnote = ' in '.join([h for h in [name, source_html] if h is not None])\n footnote_html = ''\n if footnote:\n footnote_html = '<footer class=\"blockquote-footer\">{}</footer>'.format(footnote)\n\n html = [\n '<blockquote class=\"{}\">'.format(blockquote_class),\n quote_html,\n footnote_html,\n '</blockquote>',\n ]\n return os.linesep.join(html)\n\n# Break Block\ndef parse_block_break():\n return \"<hr>\"\n\n###############################################################################\n\n\nregistered_tags = {\n \"author\": parse_tag_wholeline,\n \"date\": parse_tag_wholeline,\n \"outlet\": parse_tag_wholeline,\n \"djangotags\": parse_tag_csv,\n \"image\": parse_tag_wholeline,\n }\n\nregistered_blocks = {\n \"graph\": parse_block_graph,\n \"quote\": parse_block_quote,\n \"break\": parse_block_break,\n }\n\n\ndef parse_blocks(text):\n for block, block_parser in registered_blocks.iteritems():\n b_re = block_re(block)\n b_match = re.search(b_re, text)\n while b_match:\n kwargs = {}\n if \"args\" in b_match.groupdict():\n kwargs = parse_kwargs(b_match.group('args'))\n block_html = block_parser(**kwargs)\n print(\"BLOCK:\")\n print(block_html)\n text = os.linesep.join([text[:b_match.start()],\n block_html,\n text[b_match.end():]])\n b_match = re.search(b_re, text)\n return text\n\n\ndef parse_project(fname):\n with open(fname) as f:\n ftext = f.read()\n\n # Match, record, and remove the title and teaser\n title = ''\n title_match = re.search(title_re, ftext)\n if title_match:\n title = title_match.group('title')\n ftext = ' '.join([ftext[:title_match.start()],\n ftext[title_match.end():]])\n\n teaser = ''\n teaser_match = re.search(teaser_re, ftext)\n if teaser_match:\n teaser = teaser_match.group('teaser')\n ftext = ' '.join([ftext[:teaser_match.start()],\n ftext[teaser_match.end():]])\n\n attributes = {\n 'title': title,\n 'teaser': teaser,\n }\n\n\n for tag, tag_parser in registered_tags.iteritems():\n t_re = tag_re(tag)\n t_match = re.search(t_re, ftext)\n if t_match:\n args = ''\n if \"args\" in t_match.groupdict():\n val = tag_parser(t_match.group('args'))\n attributes.update({tag: val})\n ftext = ' '.join([ftext[:t_match.start()],\n ftext[t_match.end():]])\n\n attributes.update({ 'text': ftext })\n return attributes\n\n\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"slant/dataviz/project_parser/project_parser.py","file_name":"project_parser.py","file_ext":"py","file_size_in_byte":5777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"604187322","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 8 17:21:36 2020\n\n@author: SheilaCarolina\n\"\"\"\nfrom chatterbot.parsing import datetime_parsing\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ChatterBotCorpusTrainer\nfrom googletrans import Translator\n\nbot = ChatBot(\n 'Math & Time Bot',\n logic_adapters=[\n 'chatterbot.logic.MathematicalEvaluation',\n 'chatterbot.logic.TimeLogicAdapter'\n ],\n filters=[filters.get_recent_repeated_responses]\n)\n\n#trainer = ChatterBotCorpusTrainer(bot)\n#trainer.train(\"chatterbot.corpus.portuguese\")\n\n# Print an example of getting one math based response\nresponse = bot.get_response('Quanto é 4 + 9?')\nprint(response)\n\ntranslator = Translator()\n\n# Print an example of getting one time based response\nresponse = bot.get_response('Que horas são?')\nprint(response)\nresposta = bot.get_response('Que horas são?')\nimp = translator.translate(str(resposta), src=\"en\", dest=\"pt\")\nprint(imp.text)\n\ndata = datetime_parsing(\"Hoje é dia 08/05/2020\")\nprint(data)\nprint(data[0][0])\n","sub_path":"DhoryChatterBot8py.py","file_name":"DhoryChatterBot8py.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"518464592","text":"from .particle import Particle\nfrom scipy import constants as C\n\nclass Neutron(Particle):\n def __init__(self, x=0, y=0, z=0, vx=0, vy=0, vz=0, temperature=298.15,**other_properties):\n Particle.__init__(self, x, y, z, vx, vy, vz, temperature, **other_properties)\n self.type = \"Baryon\"\n self.statistics = \"Fermion\"\n self.compounds = {\"u\", \"d\", \"d\"}\n self.mass_MeV = C.value(\"neutron mass energy equivalent in MeV\") # [MeV/c2]\n self.mass_kg = C.value(\"neutron mass\") # [kg]\n self.charge = 0 # [C]\n self.spin = 1 / 2\n self.radius = 0.8 * 10 ** -15 # [m]\n self.meanLifetime = 879.466 # [s]\n self.magneticDipoleMoment = C.value(\"neutron mag. mom.\") # [J*T**-1]\n self.electricDipoleMoment = 2.9 * 10 ** -26 # [e*cm]\n self.electricPolarizability = 1.1615 * 10 ** -3 # [f*m**3]\n self.magneticPolarizability = 3.720 * 10 ** -4 # [f*m**3]\n\n def get_color(self):\n return '#28d73c' # green","sub_path":"Particles/neutron.py","file_name":"neutron.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"168051601","text":"##\n## Agregue el año como una columna a la tabla tbl0.tsv \n## \n#Importar Pandas y numpy\nimport pandas as pd\nimport numpy as np\n#Leer archivos\ndatos = pd.read_csv('tbl0.tsv',delimiter='\\t',encoding='utf-8')\ndatos['ano']=pd.to_datetime(datos['_c3'],format='%Y-%m-%d', errors='coerce').dt.year\ndatos = datos.fillna(0)\ndatos['ano']=datos['ano'].astype(int)\nprint(datos)\n","sub_path":"q08.py","file_name":"q08.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"218587136","text":"from serial import *\nimport math\nimport keyboard\nimport time\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import pyplot as plt\nimport threading\n\n\n\nSERIALPATH = 'COM18'\nline = ''\nANCHORS_TABFILE = 'C:/Users/pestourb/Documents/GitHub/SecureLoc/anchors.tab'\nDWM1000_TIMEBASE = 15.65E-12\nSPEED_OF_LIGHT = 2.5E8\nexit_flag = False\nSTEP = 0.25 #m\nSTART_POS = (0.9,2.4,0.)\nbuffer = []\n\n\ndef serial_handler(port):\n global exit_flag\n global buffer\n target = START_POS\n \n if not(port.is_open):\n print(\"ERROR: serial port is closed.\")\n return\n while not(exit_flag):\n \n \n # writing to serial port\n while buffer:\n timeshifts = buffer.pop()\n print(timeshifts)\n for anchor in timeshifts:\n port.write( ('0' + anchor + str(timeshifts[anchor]) + '\\r\\n').encode() ) \n \n \n try:\n if port.in_waiting > 0:\n line = port.readline().decode('utf-8').strip()\n print(line)\n \n \n except KeyboardInterrupt:\n print(\"Ctrl + C received, quitting...\")\n exit_flag = True\n continue\n \n except:\n print(\"Looks like the device has been disconnected\")\n exit_flag = True\n continue\n\n\n \n\n\ndef parse_anchors(tabfile = ANCHORS_TABFILE):\n anchors_dic = {}\n with open(tabfile) as f:\n for line in f:\n \n if len(line) > 3 and line[0] != '#':\n parsed_line = line.split()\n anchor_id = parsed_line[3]\n anchors_dic[anchor_id] = (float(parsed_line[0]),float(parsed_line[1]),float(parsed_line[2]))\n return(anchors_dic)\n \n\n\ndef compute_rangings(pos,anchors_dic):\n rangings = {}\n for anchor in anchors_dic:\n coord = anchors_dic[anchor]\n ranging = math.sqrt( sum([ (x - y)**2 for x,y in zip(pos,coord)]) )\n rangings[anchor] = ranging\n return(rangings)\n\n\n \n\ndef compute_timeshifts(rogue_pos,target_pos,anchors_dic):\n rangings_rogue = compute_rangings(rogue_pos,anchors_dic)\n rangings_target = compute_rangings(target_pos,anchors_dic)\n\n timeshifts = {}\n \n for anchor in rangings_rogue:\n r1 = rangings_rogue[anchor]\n r2 = rangings_target[anchor]\n # rounding the timeshift to a integer value\n timeshift = int( 2 * (r2 - r1) / (DWM1000_TIMEBASE * SPEED_OF_LIGHT) )\n timeshifts[anchor] = timeshift\n return(timeshifts)\n \n\ndef check_keyboard(target):\n global exit_flag\n (x,y,z) = target\n if (keyboard.is_pressed('q') ):\n exit_flag = True\n\n elif keyboard.is_pressed('UP'):\n y += STEP\n \n elif keyboard.is_pressed('DOWN'):\n y -= STEP\n \n elif keyboard.is_pressed('LEFT'):\n x -= STEP\n \n elif keyboard.is_pressed('RIGHT'):\n x += STEP\n \n elif keyboard.is_pressed('d'):\n z += STEP\n \n elif keyboard.is_pressed('c'):\n z -= STEP\n else:\n time.sleep(0.1)\n return(False)\n \n print(\"target: \"+ str( (x,y,z) ) )\n time.sleep(0.3)\n \n return(x,y,z)\n \n\ndef update_line(hl, new_data):\n\txdata, ydata, zdata = hl._verts3d\n\thl.set_xdata(list(np.append(xdata, new_data[0])))\n\thl.set_ydata(list(np.append(ydata, new_data[1])))\n\thl.set_3d_properties(list(np.append(zdata, new_data[2])))\n\tplt.draw()\n \n# 3D display \n \n## Testing the timeshifts computation\n\n#anchors_dic = parse_anchors()\n#print(compute_rangings( (2.,2.,0.), anchors_dic))\n#print(compute_timeshifts( (2.,2.,0.), (2.5,2.5,0.), anchors_dic))\ndef run():\n global buffer # quick and dirty coding\n target = START_POS\n anchors_dic = parse_anchors()\n map = plt.figure()\n map_ax = Axes3D(map)\n map_ax.autoscale(enable=True, axis='both', tight=True)\n \n # # # Setting the axes properties\n map_ax.set_xlim3d([0.0, 2.0])\n map_ax.set_ylim3d([0.0, 5.0])\n map_ax.set_zlim3d([0.0, 2.0])\n \n hl, = map_ax.plot3D([0], [0], [0])\n \n update_line(hl, target) \n plt.show(block=False)\n plt.pause(0.01)\n \n while not(exit_flag):\n\n #old_target = tuple(target)\n #keyboard.wait('UP','DOWN')\n \n out = check_keyboard(target)\n \n if out:\n target = out\n \n # calculating the timeshifts\n timeshifts = compute_timeshifts(START_POS,target,anchors_dic)\n \n \n # sending updated timeshifts to teensyduino\n buffer.append(timeshifts)\n \n \n update_line(hl, target)\n plt.show(block=False)\n plt.pause(0.01)\n\n\n\nport = Serial(SERIALPATH)\nt = threading.Thread(target = serial_handler, args = (port,) )\nt.start()\n\n#t2 = threading.Thread(target = run)\n#t2.start()\nrun()\n\n#port = Serial(SERIALPATH)\n#read_serial(port)\n \n \n\n \n \n","sub_path":"DecaWino/Arduino/DelayedACKATK/AttackMonitoring.py","file_name":"AttackMonitoring.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"86405019","text":"# (C) Copyright IBM Corp. 2020.\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 ibm_watson_machine_learning.libs.repo.mlrepository import MetaNames\nfrom ibm_watson_machine_learning.libs.repo.mlrepository import MetaProps\nfrom ibm_watson_machine_learning.libs.repo.mlrepository import ModelArtifact\nfrom ibm_watson_machine_learning.libs.repo.util.library_imports import LibraryChecker\nfrom ibm_watson_machine_learning.libs.repo.base_constants import *\nfrom .python_version import PythonVersion\nimport numpy as np\nimport json\n\nlib_checker = LibraryChecker()\n\nif lib_checker.installed_libs[SCIKIT]:\n from ibm_watson_machine_learning.libs.repo.mlrepositoryartifact.scikit_pipeline_reader import ScikitPipelineReader\n from ibm_watson_machine_learning.libs.repo.mlrepositoryartifact.xgboost_model_reader import XGBoostModelReader\n from sklearn.base import BaseEstimator\n from ibm_watson_machine_learning.libs.repo.mlrepositoryartifact.version_helper import ScikitVersionHelper, XGBoostVersionHelper\n\nif lib_checker.installed_libs[XGBOOST]:\n from xgboost import XGBRegressor, XGBClassifier\n from ibm_watson_machine_learning.libs.repo.mlrepositoryartifact.version_helper import ScikitVersionHelper\n import sys\n import os\n try:\n sys.stderr = open(os.devnull, 'w')\n import xgboost as xgb\n except Exception as ex:\n print ('Failed to import xgboost. Error: ' + str(ex))\n finally:\n sys.stderr.close() # close /dev/null\n sys.stderr = sys.__stderr__\n\n\nclass ScikitPipelineModelArtifact(ModelArtifact):\n \"\"\"\n Class of model artifacts created with MLRepositoryCLient.\n\n :param sklearn.pipeline.Pipeline scikit_pipeline_model: Pipeline Model which will be wrapped\n \"\"\"\n def __init__(self, scikit_pipeline_model, training_features=None, training_target=None, feature_names=None,\n label_column_names=None, uid=None, name=None, meta_props=MetaProps({})):\n lib_checker.check_lib(SCIKIT)\n super(ScikitPipelineModelArtifact, self).__init__(uid, name, meta_props)\n\n is_scikit, is_xgboost = False, False\n\n if issubclass(type(scikit_pipeline_model), BaseEstimator):\n is_scikit = True\n\n if not is_scikit and lib_checker.installed_libs[XGBOOST]:\n if isinstance(scikit_pipeline_model, xgb.Booster):\n is_xgboost = True\n\n if not (is_scikit or is_xgboost):\n raise ValueError('Invalid type for scikit ml_pipeline_model: {}'.\n format(scikit_pipeline_model.__class__.__name__))\n\n self.ml_pipeline_model = scikit_pipeline_model\n self.ml_pipeline = None # no pipeline or parent reference\n\n\n if meta_props.prop(MetaNames.RUNTIMES) is None and meta_props.prop(MetaNames.RUNTIME_UID) is None and meta_props.prop(MetaNames.FRAMEWORK_RUNTIMES) is None:\n ver = PythonVersion.significant()\n runtimes = '[{\"name\":\"python\",\"version\": \"'+ ver + '\"}]'\n self.meta.merge(\n MetaProps({MetaNames.FRAMEWORK_RUNTIMES: runtimes})\n )\n\n if is_xgboost:\n self.meta.merge(\n MetaProps({\n MetaNames.FRAMEWORK_NAME: XGBoostVersionHelper.model_type(scikit_pipeline_model),\n MetaNames.FRAMEWORK_VERSION: XGBoostVersionHelper.model_version(scikit_pipeline_model)\n })\n )\n\n if(training_features is not None):\n if(training_target is None):\n if not (isinstance(training_features, xgb.DMatrix)):\n raise ValueError(\"Training target column has not been provided for the training data set\")\n self.meta.merge(self._get_schema(training_features, training_target, feature_names, label_column_names))\n\n self._reader = XGBoostModelReader(self.ml_pipeline_model)\n else:\n if lib_checker.installed_libs[XGBOOST]:\n if (issubclass(type(scikit_pipeline_model), XGBClassifier) or issubclass(type(scikit_pipeline_model), XGBRegressor)):\n if MetaNames.FRAMEWORK_LIBRARIES not in self.meta.meta:\n framewk_library_entry = {\"name\": \"xgboost\",\n \"version\": xgb.__version__}\n framewk_library_entry_full = json.dumps([framewk_library_entry])\n self.meta.merge(\n MetaProps({\n MetaNames.FRAMEWORK_LIBRARIES: framewk_library_entry_full\n })\n )\n else:\n self._xgboost_in_model(scikit_pipeline_model)\n\n self.meta.merge(\n MetaProps({\n MetaNames.FRAMEWORK_NAME: ScikitVersionHelper.model_type(scikit_pipeline_model),\n MetaNames.FRAMEWORK_VERSION: ScikitVersionHelper.model_version(scikit_pipeline_model)\n })\n )\n\n if(training_features is not None):\n if(training_target is None):\n raise ValueError(\"Training target column has not been provided for the training data set\")\n self.meta.merge(self._get_schema(training_features, training_target, feature_names, label_column_names))\n\n self._reader = ScikitPipelineReader(self.ml_pipeline_model)\n\n\n def _xgboost_in_model(self, model):\n import sklearn\n if '17' in sklearn.__version__:\n from sklearn.grid_search import GridSearchCV, RandomizedSearchCV\n else:\n from sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n from sklearn.multiclass import OneVsRestClassifier\n from sklearn.pipeline import Pipeline\n from sklearn.ensemble import VotingClassifier\n _estimators = [GridSearchCV, RandomizedSearchCV, VotingClassifier, OneVsRestClassifier, Pipeline]\n\n set_libraries = False\n\n for estimator in _estimators:\n if isinstance(model, estimator):\n if isinstance(model, GridSearchCV) or isinstance(model, RandomizedSearchCV):\n estimator = model.best_estimator_\n if isinstance(estimator, XGBRegressor) or isinstance(estimator, XGBClassifier):\n set_libraries = True\n elif isinstance(model, Pipeline):\n estimator = model.steps[-1][1]\n if isinstance(estimator, XGBRegressor) or isinstance(estimator, XGBClassifier):\n set_libraries = True\n else:\n for est in model.estimators_:\n if isinstance(est, XGBRegressor) or isinstance(est, XGBClassifier):\n set_libraries = True\n\n if set_libraries:\n if MetaNames.FRAMEWORK_LIBRARIES not in self.meta.meta:\n framewk_library_entry = {\"name\": \"xgboost\",\n \"version\": xgb.__version__}\n framewk_library_entry_full = json.dumps([framewk_library_entry])\n self.meta.merge(\n MetaProps({\n MetaNames.FRAMEWORK_LIBRARIES: framewk_library_entry_full\n })\n )\n\n def _get_schema(self, training_features, training_target, feature_names, label_column_names):\n is_xgboost_dmatrix = False\n\n if(training_target is None): #training_target is None for Dmatrix\n training_props = {\n # \"features\": {\"type\": type(training_features).__name__, \"fields\": []},\n # \"labels\": {\"type\": type(training_features.get_label()).__name__, \"fields\": []}\n \"type\": type(training_features).__name__,\n \"fields\" : [],\n \"labels\": { \"fields\": []}\n }\n else:\n training_props = {\n \"type\": type(training_features).__name__,\n \"fields\": [],\n \"labels\": {\"fields\": []}\n }\n\n lib_checker.check_lib(PANDAS)\n import pandas as pd\n\n # Check feature types, currently supporting pandas df, numpy.ndarray, python lists and Dmatrix\n if(isinstance(training_features, pd.DataFrame)):\n for feature in training_features.dtypes.iteritems():\n training_props[\"fields\"].append({\"name\": feature[0], \"type\": str(feature[1])})\n elif(isinstance(training_features, np.ndarray)):\n dims = training_features.shape\n if len(dims) == 1:\n if feature_names is None:\n feature_names = 'f1'\n training_props[\"fields\"].append({\"name\": feature_names, \"type\": type(training_features[0]).__name__})\n else:\n if feature_names is None:\n feature_names = ['f' + str(i) for i in range(dims[1])]\n elif isinstance(feature_names, np.ndarray):\n feature_names = feature_names.tolist()\n for i in range(dims[1]):\n training_props[\"fields\"].append({\n \"name\": feature_names[i], \"type\": type(training_features.item(0, i)).__name__\n })\n\n elif(isinstance(training_features, list)):\n if not isinstance(training_features[0], list):\n if feature_names is None:\n feature_names = 'f1'\n training_props[\"fields\"].append({\"name\": feature_names, \"type\": type(training_features[0]).__name__})\n else:\n if feature_names is None:\n feature_names = ['f' + str(i) for i in range(len(training_features[0]))]\n elif isinstance(feature_names, np.ndarray):\n feature_names = feature_names.tolist()\n for i in range(len(training_features[0])):\n training_props[\"fields\"].append({\n \"name\": feature_names[i], \"type\": type(training_features[0][i]).__name__\n })\n elif(isinstance(training_features, xgb.DMatrix)):\n for index, feature in enumerate(training_features.feature_names): #start=0\n training_props[\"fields\"].append({\"name\": feature, \"type\": str(training_features.feature_types[index])})\n is_xgboost_dmatrix = True\n else:\n raise ValueError(\"Unsupported training data type %s provided\" % (type(training_features).__name__))\n\n #Check target or label data types\n if(isinstance(training_target, pd.DataFrame)):\n for feature in training_target.dtypes.iteritems():\n training_props[\"labels\"][\"fields\"].append({\"name\": feature[0], \"type\": str(feature[1])})\n elif(isinstance(training_target, pd.Series)):\n training_props[\"labels\"][\"fields\"].append({\"name\": training_target.name, \"type\": str(training_target.dtype)})\n elif(isinstance(training_target, np.ndarray)):\n dims = training_target.shape\n if len(dims) == 1:\n if label_column_names is None:\n label_column_names = 'l1'\n elif isinstance(label_column_names, list) or isinstance(label_column_names, np.ndarray):\n label_column_names = label_column_names[0]\n training_props[\"labels\"][\"fields\"].append({\"name\": label_column_names, \"type\": type(training_target.item(0)).__name__})\n else:\n if label_column_names is None:\n label_column_names = ['l' + str(i) for i in range(dims[1])]\n elif isinstance(label_column_names, np.ndarray):\n label_column_names = label_column_names.tolist()\n for i in range(dims[1]):\n training_props[\"labels\"][\"fields\"].append({\n \"name\": label_column_names[i], \"type\": type(training_target.item(0, i)).__name__\n })\n elif(isinstance(training_target, list)):\n if not isinstance(training_target[0], list):\n if label_column_names is None:\n label_column_names = 'l1'\n elif isinstance(label_column_names, list) or isinstance(label_column_names, np.ndarray):\n label_column_names = label_column_names[0]\n training_props[\"labels\"][\"fields\"].append({\n \"name\": label_column_names, \"type\": type(training_target[0]).__name__\n })\n else:\n if label_column_names is None:\n label_column_names = ['l' + str(i) for i in range(len(training_target[0]))]\n elif isinstance(label_column_names, np.ndarray):\n label_column_names = label_column_names.tolist()\n for i in range(len(training_target[0])):\n training_props[\"labels\"][\"fields\"].append({\n \"name\": label_column_names[i], \"type\": type(training_target[0][i]).__name__\n })\n elif(isinstance(training_features, xgb.DMatrix)): #For DMatrix labels is part of training_data and not training_target\n training_props[\"labels\"][\"fields\"].append({\"type\": str(type(training_features.get_label()[0]).__name__)})\n else:\n raise ValueError(\"Unsupported label data type %s provided\" % (type(training_target)))\n\n if is_xgboost_dmatrix:\n label = None\n else:\n label = training_props[\"labels\"][\"fields\"][0][\"name\"]\n\n del training_props[\"labels\"]\n return MetaProps({\n MetaNames.TRAINING_DATA_SCHEMA: training_props,\n MetaNames.LABEL_FIELD: label\n })\n\n def pipeline_artifact(self):\n \"\"\"\n Returns None. Pipeline is not implemented for scikit model.\n \"\"\"\n pass\n\n def reader(self):\n \"\"\"\n Returns reader used for getting pipeline model content.\n\n :return: reader for sklearn.pipeline.Pipeline\n :rtype: ScikitPipelineReader\n \"\"\"\n\n return self._reader\n\n def _copy(self, uid=None, meta_props=None):\n if uid is None:\n uid = self.uid\n\n if meta_props is None:\n meta_props = self.meta\n\n return ScikitPipelineModelArtifact(\n self.ml_pipeline_model,\n uid=uid,\n name=self.name,\n meta_props=meta_props\n )","sub_path":"venv/Lib/site-packages/ibm_watson_machine_learning/libs/repo/mlrepositoryartifact/scikit_pipeline_model_artifact.py","file_name":"scikit_pipeline_model_artifact.py","file_ext":"py","file_size_in_byte":14968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"499047480","text":"# -*- coding: utf-8 -*-\nfrom rq import Queue\nfrom redis import Redis\nfrom flask import redirect, render_template, url_for, flash\nfrom coaster.views import load_models\nfrom coaster.utils import getbool\nfrom sqlalchemy.exc import IntegrityError\nfrom .. import app, lastuser\nfrom ..models import (db, Profile, ProposalSpace, ProposalSpaceRedirect, Participant, Event, TicketType, TicketClient, SyncTicket)\nfrom baseframe import forms\nfrom baseframe import _\nfrom baseframe.forms import render_form\nfrom ..forms import EventForm, TicketTypeForm, ParticipantBadgeForm, TicketClientForm\nfrom ..jobs import import_tickets\n\n\nredis_connection = Redis()\nfunnelq = Queue('funnel', connection=redis_connection)\n\n\n@app.route('/<space>/admin', methods=['GET', 'POST'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n permission='admin')\ndef admin(profile, space):\n csrf_form = forms.Form()\n if csrf_form.validate_on_submit():\n for ticket_client in space.ticket_clients:\n if ticket_client and ticket_client.name == u'explara':\n funnelq.enqueue(import_tickets, ticket_client.id)\n flash(_(u\"Importing tickets from vendors...Refresh the page in about 30 seconds...\"), 'info')\n return redirect(space.url_for('admin'), code=303)\n return render_template('admin.html', profile=profile, space=space, events=space.events, csrf_form=csrf_form)\n\n\n@app.route('/<space>/events/new', methods=['GET', 'POST'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n permission='new-event')\ndef new_event(profile, space):\n form = EventForm()\n if form.validate_on_submit():\n event = Event(proposal_space=space)\n form.populate_obj(event)\n event.make_name()\n try:\n db.session.add(event)\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n flash(_(u\"This event already exists.\"), 'info')\n return redirect(space.url_for('admin'), code=303)\n return render_form(form=form, title=_(u\"New Event\"), submit=_(u\"Add Event\"))\n\n\n@app.route('/<space>/event/<name>/edit', methods=['GET', 'POST'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n (Event, {'name': 'name', 'proposal_space': 'space'}, 'event'),\n permission='edit-event')\ndef event_edit(profile, space, event):\n form = EventForm(obj=event, model=Event)\n if form.validate_on_submit():\n form.populate_obj(event)\n db.session.commit()\n flash(_(u\"Your changes have been saved\"), 'info')\n return redirect(space.url_for('admin'), code=303)\n return render_form(form=form, title=_(u\"Edit event\"), submit=_(u\"Save changes\"))\n\n\n@app.route('/<space>/ticket_type/<name>', methods=['GET'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n (TicketType, {'name': 'name', 'proposal_space': 'space'}, 'ticket_type'),\n permission='view-ticket-type')\ndef ticket_type(profile, space, ticket_type):\n participants = Participant.query.join(SyncTicket).filter(SyncTicket.ticket_type == ticket_type).all()\n return render_template('ticket_type.html', profile=profile, space=space, ticket_type=ticket_type, participants=participants)\n\n\n@app.route('/<space>/ticket_type/new', methods=['GET', 'POST'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n permission='new-ticket-type')\ndef new_ticket_type(profile, space):\n form = TicketTypeForm()\n form.events.query = space.events\n if form.validate_on_submit():\n ticket_type = TicketType(proposal_space=space)\n form.populate_obj(ticket_type)\n ticket_type.make_name()\n try:\n db.session.add(ticket_type)\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n flash(_(u\"This ticket type already exists.\"), 'info')\n return redirect(space.url_for('admin'), code=303)\n return render_form(form=form, title=_(u\"New Ticket Type\"), submit=_(u\"Add ticket type\"))\n\n\n@app.route('/<space>/ticket_type/<name>/edit', methods=['GET', 'POST'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n (TicketType, {'name': 'name', 'proposal_space': 'space'}, 'ticket_type'),\n permission='edit-event')\ndef ticket_type_edit(profile, space, ticket_type):\n form = TicketTypeForm(obj=ticket_type, model=TicketType)\n form.events.query = space.events\n if form.validate_on_submit():\n form.populate_obj(ticket_type)\n db.session.commit()\n flash(_(u\"Your changes have been saved\"), 'info')\n return redirect(space.url_for('admin'), code=303)\n return render_form(form=form, title=_(u\"Edit ticket type\"), submit=_(u\"Save changes\"))\n\n\n@app.route('/<space>/ticket_client/new', methods=['GET', 'POST'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n permission='new-ticket-client')\ndef new_ticket_client(profile, space):\n form = TicketClientForm()\n if form.validate_on_submit():\n ticket_client = TicketClient(proposal_space=space)\n form.populate_obj(ticket_client)\n try:\n db.session.add(ticket_client)\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n flash(_(u\"This ticket client already exists.\"), 'info')\n return redirect(space.url_for('admin'), code=303)\n return render_form(form=form, title=_(u\"New Ticket Client\"), submit=_(u\"Add Ticket Client\"))\n\n\n@app.route('/<space>/ticket_client/<id>/edit', methods=['GET', 'POST'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n (TicketClient, {'id': 'id', 'proposal_space': 'space'}, 'ticket_client'),\n permission='edit-ticket-client')\ndef ticket_client_edit(profile, space, ticket_client):\n form = TicketClientForm(obj=ticket_client, model=TicketClient)\n if form.validate_on_submit():\n form.populate_obj(ticket_client)\n db.session.commit()\n flash(_(u\"Your changes have been saved\"), 'info')\n return redirect(space.url_for('admin'), code=303)\n return render_form(form=form, title=_(u\"Edit ticket client\"), submit=_(u\"Save changes\"))\n\n\n@app.route('/<space>/event/<name>', methods=['GET', 'POST'], subdomain='<profile>')\n@lastuser.requires_login\n@load_models(\n (Profile, {'name': 'profile'}, 'g.profile'),\n ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),\n (Event, {'name': 'name', 'proposal_space': 'space'}, 'event'),\n permission='view-event')\ndef event(profile, space, event):\n participants = Participant.checkin_list(event)\n form = ParticipantBadgeForm()\n if form.validate_on_submit():\n badge_printed = True if getbool(form.data.get('badge_printed')) else False\n db.session.query(Participant).filter(Participant.id.in_([participant.id for participant in event.participants])).\\\n update({'badge_printed': badge_printed}, False)\n db.session.commit()\n return redirect(url_for('event', profile=space.profile.name, space=space.name, name=event.name), code=303)\n checked_in_count = len([p for p in participants if p.checked_in])\n return render_template('event.html', profile=profile, space=space, participants=participants, event=event, badge_form=ParticipantBadgeForm(model=Participant), checked_in_count=checked_in_count, checkin_form=forms.Form())\n","sub_path":"funnel/views/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"208752832","text":"# -*- coding: utf-8 -*-\n# Copyright 2015 - 2016 OpenMarket Ltd\n# Copyright 2017 Vector Creations Ltd\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 hmac\nimport logging\nfrom hashlib import sha1\n\nfrom six import string_types\n\nfrom twisted.internet import defer\n\nimport synapse\nimport synapse.types\nfrom synapse.api.constants import LoginType\nfrom synapse.api.errors import (\n Codes,\n LimitExceededError,\n SynapseError,\n UnrecognizedRequestError,\n)\nfrom synapse.config.ratelimiting import FederationRateLimitConfig\nfrom synapse.config.server import is_threepid_reserved\nfrom synapse.http.servlet import (\n RestServlet,\n assert_params_in_dict,\n parse_json_object_from_request,\n parse_string,\n)\nfrom synapse.util.msisdn import phone_number_to_msisdn\nfrom synapse.util.ratelimitutils import FederationRateLimiter\nfrom synapse.util.threepids import check_3pid_allowed\n\nfrom ._base import client_patterns, interactive_auth_handler\n\n# We ought to be using hmac.compare_digest() but on older pythons it doesn't\n# exist. It's a _really minor_ security flaw to use plain string comparison\n# because the timing attack is so obscured by all the other code here it's\n# unlikely to make much difference\nif hasattr(hmac, \"compare_digest\"):\n compare_digest = hmac.compare_digest\nelse:\n\n def compare_digest(a, b):\n return a == b\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass EmailRegisterRequestTokenRestServlet(RestServlet):\n PATTERNS = client_patterns(\"/register/email/requestToken$\")\n\n def __init__(self, hs):\n \"\"\"\n Args:\n hs (synapse.server.HomeServer): server\n \"\"\"\n super(EmailRegisterRequestTokenRestServlet, self).__init__()\n self.hs = hs\n self.identity_handler = hs.get_handlers().identity_handler\n\n @defer.inlineCallbacks\n def on_POST(self, request):\n body = parse_json_object_from_request(request)\n\n assert_params_in_dict(\n body, [\"id_server\", \"client_secret\", \"email\", \"send_attempt\"]\n )\n\n if not check_3pid_allowed(self.hs, \"email\", body[\"email\"]):\n raise SynapseError(\n 403,\n \"Your email domain is not authorized to register on this server\",\n Codes.THREEPID_DENIED,\n )\n\n existingUid = yield self.hs.get_datastore().get_user_id_by_threepid(\n \"email\", body[\"email\"]\n )\n\n if existingUid is not None:\n raise SynapseError(400, \"Email is already in use\", Codes.THREEPID_IN_USE)\n\n ret = yield self.identity_handler.requestEmailToken(**body)\n return (200, ret)\n\n\nclass MsisdnRegisterRequestTokenRestServlet(RestServlet):\n PATTERNS = client_patterns(\"/register/msisdn/requestToken$\")\n\n def __init__(self, hs):\n \"\"\"\n Args:\n hs (synapse.server.HomeServer): server\n \"\"\"\n super(MsisdnRegisterRequestTokenRestServlet, self).__init__()\n self.hs = hs\n self.identity_handler = hs.get_handlers().identity_handler\n\n @defer.inlineCallbacks\n def on_POST(self, request):\n body = parse_json_object_from_request(request)\n\n assert_params_in_dict(\n body,\n [\"id_server\", \"client_secret\", \"country\", \"phone_number\", \"send_attempt\"],\n )\n\n msisdn = phone_number_to_msisdn(body[\"country\"], body[\"phone_number\"])\n\n if not check_3pid_allowed(self.hs, \"msisdn\", msisdn):\n raise SynapseError(\n 403,\n \"Phone numbers are not authorized to register on this server\",\n Codes.THREEPID_DENIED,\n )\n\n existingUid = yield self.hs.get_datastore().get_user_id_by_threepid(\n \"msisdn\", msisdn\n )\n\n if existingUid is not None:\n raise SynapseError(\n 400, \"Phone number is already in use\", Codes.THREEPID_IN_USE\n )\n\n ret = yield self.identity_handler.requestMsisdnToken(**body)\n return (200, ret)\n\n\nclass UsernameAvailabilityRestServlet(RestServlet):\n PATTERNS = client_patterns(\"/register/available\")\n\n def __init__(self, hs):\n \"\"\"\n Args:\n hs (synapse.server.HomeServer): server\n \"\"\"\n super(UsernameAvailabilityRestServlet, self).__init__()\n self.hs = hs\n self.registration_handler = hs.get_registration_handler()\n self.ratelimiter = FederationRateLimiter(\n hs.get_clock(),\n FederationRateLimitConfig(\n # Time window of 2s\n window_size=2000,\n # Artificially delay requests if rate > sleep_limit/window_size\n sleep_limit=1,\n # Amount of artificial delay to apply\n sleep_msec=1000,\n # Error with 429 if more than reject_limit requests are queued\n reject_limit=1,\n # Allow 1 request at a time\n concurrent_requests=1,\n ),\n )\n\n @defer.inlineCallbacks\n def on_GET(self, request):\n ip = self.hs.get_ip_from_request(request)\n with self.ratelimiter.ratelimit(ip) as wait_deferred:\n yield wait_deferred\n\n username = parse_string(request, \"username\", required=True)\n\n yield self.registration_handler.check_username(username)\n\n return (200, {\"available\": True})\n\n\nclass RegisterRestServlet(RestServlet):\n PATTERNS = client_patterns(\"/register$\")\n\n def __init__(self, hs):\n \"\"\"\n Args:\n hs (synapse.server.HomeServer): server\n \"\"\"\n super(RegisterRestServlet, self).__init__()\n\n self.hs = hs\n self.auth = hs.get_auth()\n self.store = hs.get_datastore()\n self.auth_handler = hs.get_auth_handler()\n self.registration_handler = hs.get_registration_handler()\n self.identity_handler = hs.get_handlers().identity_handler\n self.room_member_handler = hs.get_room_member_handler()\n self.macaroon_gen = hs.get_macaroon_generator()\n self.ratelimiter = hs.get_registration_ratelimiter()\n self.clock = hs.get_clock()\n\n @interactive_auth_handler\n @defer.inlineCallbacks\n def on_POST(self, request):\n body = parse_json_object_from_request(request)\n\n client_addr = request.getClientIP()\n\n time_now = self.clock.time()\n\n allowed, time_allowed = self.ratelimiter.can_do_action(\n client_addr,\n time_now_s=time_now,\n rate_hz=self.hs.config.rc_registration.per_second,\n burst_count=self.hs.config.rc_registration.burst_count,\n update=False,\n )\n\n if not allowed:\n raise LimitExceededError(\n retry_after_ms=int(1000 * (time_allowed - time_now))\n )\n\n kind = b\"user\"\n if b\"kind\" in request.args:\n kind = request.args[b\"kind\"][0]\n\n if kind == b\"guest\":\n ret = yield self._do_guest_registration(body, address=client_addr)\n return ret\n return\n elif kind != b\"user\":\n raise UnrecognizedRequestError(\n \"Do not understand membership kind: %s\" % (kind,)\n )\n\n # we do basic sanity checks here because the auth layer will store these\n # in sessions. Pull out the username/password provided to us.\n desired_password = None\n if \"password\" in body:\n if (\n not isinstance(body[\"password\"], string_types)\n or len(body[\"password\"]) > 512\n ):\n raise SynapseError(400, \"Invalid password\")\n desired_password = body[\"password\"]\n\n desired_username = None\n if \"username\" in body:\n if (\n not isinstance(body[\"username\"], string_types)\n or len(body[\"username\"]) > 512\n ):\n raise SynapseError(400, \"Invalid username\")\n desired_username = body[\"username\"]\n\n appservice = None\n if self.auth.has_access_token(request):\n appservice = yield self.auth.get_appservice_by_req(request)\n\n # fork off as soon as possible for ASes and shared secret auth which\n # have completely different registration flows to normal users\n\n # == Application Service Registration ==\n if appservice:\n # Set the desired user according to the AS API (which uses the\n # 'user' key not 'username'). Since this is a new addition, we'll\n # fallback to 'username' if they gave one.\n desired_username = body.get(\"user\", desired_username)\n\n # XXX we should check that desired_username is valid. Currently\n # we give appservices carte blanche for any insanity in mxids,\n # because the IRC bridges rely on being able to register stupid\n # IDs.\n\n access_token = self.auth.get_access_token_from_request(request)\n\n if isinstance(desired_username, string_types):\n result = yield self._do_appservice_registration(\n desired_username, access_token, body\n )\n return (200, result) # we throw for non 200 responses\n return\n\n # for either shared secret or regular registration, downcase the\n # provided username before attempting to register it. This should mean\n # that people who try to register with upper-case in their usernames\n # don't get a nasty surprise. (Note that we treat username\n # case-insenstively in login, so they are free to carry on imagining\n # that their username is CrAzYh4cKeR if that keeps them happy)\n if desired_username is not None:\n desired_username = desired_username.lower()\n\n # == Shared Secret Registration == (e.g. create new user scripts)\n if \"mac\" in body:\n # FIXME: Should we really be determining if this is shared secret\n # auth based purely on the 'mac' key?\n result = yield self._do_shared_secret_registration(\n desired_username, desired_password, body\n )\n return (200, result) # we throw for non 200 responses\n return\n\n # == Normal User Registration == (everyone else)\n if not self.hs.config.enable_registration:\n raise SynapseError(403, \"Registration has been disabled\")\n\n guest_access_token = body.get(\"guest_access_token\", None)\n\n if \"initial_device_display_name\" in body and \"password\" not in body:\n # ignore 'initial_device_display_name' if sent without\n # a password to work around a client bug where it sent\n # the 'initial_device_display_name' param alone, wiping out\n # the original registration params\n logger.warn(\"Ignoring initial_device_display_name without password\")\n del body[\"initial_device_display_name\"]\n\n session_id = self.auth_handler.get_session_id(body)\n registered_user_id = None\n if session_id:\n # if we get a registered user id out of here, it means we previously\n # registered a user for this session, so we could just return the\n # user here. We carry on and go through the auth checks though,\n # for paranoia.\n registered_user_id = self.auth_handler.get_session_data(\n session_id, \"registered_user_id\", None\n )\n\n if desired_username is not None:\n yield self.registration_handler.check_username(\n desired_username,\n guest_access_token=guest_access_token,\n assigned_user_id=registered_user_id,\n )\n\n # FIXME: need a better error than \"no auth flow found\" for scenarios\n # where we required 3PID for registration but the user didn't give one\n require_email = \"email\" in self.hs.config.registrations_require_3pid\n require_msisdn = \"msisdn\" in self.hs.config.registrations_require_3pid\n\n show_msisdn = True\n if self.hs.config.disable_msisdn_registration:\n show_msisdn = False\n require_msisdn = False\n\n flows = []\n if self.hs.config.enable_registration_captcha:\n # only support 3PIDless registration if no 3PIDs are required\n if not require_email and not require_msisdn:\n # Also add a dummy flow here, otherwise if a client completes\n # recaptcha first we'll assume they were going for this flow\n # and complete the request, when they could have been trying to\n # complete one of the flows with email/msisdn auth.\n flows.extend([[LoginType.RECAPTCHA, LoginType.DUMMY]])\n # only support the email-only flow if we don't require MSISDN 3PIDs\n if not require_msisdn:\n flows.extend([[LoginType.RECAPTCHA, LoginType.EMAIL_IDENTITY]])\n\n if show_msisdn:\n # only support the MSISDN-only flow if we don't require email 3PIDs\n if not require_email:\n flows.extend([[LoginType.RECAPTCHA, LoginType.MSISDN]])\n # always let users provide both MSISDN & email\n flows.extend(\n [[LoginType.RECAPTCHA, LoginType.MSISDN, LoginType.EMAIL_IDENTITY]]\n )\n else:\n # only support 3PIDless registration if no 3PIDs are required\n if not require_email and not require_msisdn:\n flows.extend([[LoginType.DUMMY]])\n # only support the email-only flow if we don't require MSISDN 3PIDs\n if not require_msisdn:\n flows.extend([[LoginType.EMAIL_IDENTITY]])\n\n if show_msisdn:\n # only support the MSISDN-only flow if we don't require email 3PIDs\n if not require_email or require_msisdn:\n flows.extend([[LoginType.MSISDN]])\n # always let users provide both MSISDN & email\n flows.extend([[LoginType.MSISDN, LoginType.EMAIL_IDENTITY]])\n\n # Append m.login.terms to all flows if we're requiring consent\n if self.hs.config.user_consent_at_registration:\n new_flows = []\n for flow in flows:\n inserted = False\n # m.login.terms should go near the end but before msisdn or email auth\n for i, stage in enumerate(flow):\n if stage == LoginType.EMAIL_IDENTITY or stage == LoginType.MSISDN:\n flow.insert(i, LoginType.TERMS)\n inserted = True\n break\n if not inserted:\n flow.append(LoginType.TERMS)\n flows.extend(new_flows)\n\n auth_result, params, session_id = yield self.auth_handler.check_auth(\n flows, body, self.hs.get_ip_from_request(request)\n )\n\n # Check that we're not trying to register a denied 3pid.\n #\n # the user-facing checks will probably already have happened in\n # /register/email/requestToken when we requested a 3pid, but that's not\n # guaranteed.\n\n if auth_result:\n for login_type in [LoginType.EMAIL_IDENTITY, LoginType.MSISDN]:\n if login_type in auth_result:\n medium = auth_result[login_type][\"medium\"]\n address = auth_result[login_type][\"address\"]\n\n if not check_3pid_allowed(self.hs, medium, address):\n raise SynapseError(\n 403,\n \"Third party identifiers (email/phone numbers)\"\n + \" are not authorized on this server\",\n Codes.THREEPID_DENIED,\n )\n\n if registered_user_id is not None:\n logger.info(\n \"Already registered user ID %r for this session\", registered_user_id\n )\n # don't re-register the threepids\n registered = False\n else:\n # NB: This may be from the auth handler and NOT from the POST\n assert_params_in_dict(params, [\"password\"])\n\n desired_username = params.get(\"username\", None)\n guest_access_token = params.get(\"guest_access_token\", None)\n new_password = params.get(\"password\", None)\n\n if desired_username is not None:\n desired_username = desired_username.lower()\n\n threepid = None\n if auth_result:\n threepid = auth_result.get(LoginType.EMAIL_IDENTITY)\n\n # Also check that we're not trying to register a 3pid that's already\n # been registered.\n #\n # This has probably happened in /register/email/requestToken as well,\n # but if a user hits this endpoint twice then clicks on each link from\n # the two activation emails, they would register the same 3pid twice.\n for login_type in [LoginType.EMAIL_IDENTITY, LoginType.MSISDN]:\n if login_type in auth_result:\n medium = auth_result[login_type][\"medium\"]\n address = auth_result[login_type][\"address\"]\n\n existingUid = yield self.store.get_user_id_by_threepid(\n medium, address\n )\n\n if existingUid is not None:\n raise SynapseError(\n 400,\n \"%s is already in use\" % medium,\n Codes.THREEPID_IN_USE,\n )\n\n registered_user_id = yield self.registration_handler.register_user(\n localpart=desired_username,\n password=new_password,\n guest_access_token=guest_access_token,\n threepid=threepid,\n address=client_addr,\n )\n # Necessary due to auth checks prior to the threepid being\n # written to the db\n if threepid:\n if is_threepid_reserved(\n self.hs.config.mau_limits_reserved_threepids, threepid\n ):\n yield self.store.upsert_monthly_active_user(registered_user_id)\n\n # remember that we've now registered that user account, and with\n # what user ID (since the user may not have specified)\n self.auth_handler.set_session_data(\n session_id, \"registered_user_id\", registered_user_id\n )\n\n registered = True\n\n return_dict = yield self._create_registration_details(\n registered_user_id, params\n )\n\n if registered:\n yield self.registration_handler.post_registration_actions(\n user_id=registered_user_id,\n auth_result=auth_result,\n access_token=return_dict.get(\"access_token\"),\n bind_email=params.get(\"bind_email\"),\n bind_msisdn=params.get(\"bind_msisdn\"),\n )\n\n return (200, return_dict)\n\n def on_OPTIONS(self, _):\n return 200, {}\n\n @defer.inlineCallbacks\n def _do_appservice_registration(self, username, as_token, body):\n user_id = yield self.registration_handler.appservice_register(\n username, as_token\n )\n return (yield self._create_registration_details(user_id, body))\n\n @defer.inlineCallbacks\n def _do_shared_secret_registration(self, username, password, body):\n if not self.hs.config.registration_shared_secret:\n raise SynapseError(400, \"Shared secret registration is not enabled\")\n if not username:\n raise SynapseError(\n 400, \"username must be specified\", errcode=Codes.BAD_JSON\n )\n\n # use the username from the original request rather than the\n # downcased one in `username` for the mac calculation\n user = body[\"username\"].encode(\"utf-8\")\n\n # str() because otherwise hmac complains that 'unicode' does not\n # have the buffer interface\n got_mac = str(body[\"mac\"])\n\n # FIXME this is different to the /v1/register endpoint, which\n # includes the password and admin flag in the hashed text. Why are\n # these different?\n want_mac = hmac.new(\n key=self.hs.config.registration_shared_secret.encode(),\n msg=user,\n digestmod=sha1,\n ).hexdigest()\n\n if not compare_digest(want_mac, got_mac):\n raise SynapseError(403, \"HMAC incorrect\")\n\n user_id = yield self.registration_handler.register_user(\n localpart=username, password=password\n )\n\n result = yield self._create_registration_details(user_id, body)\n return result\n\n @defer.inlineCallbacks\n def _create_registration_details(self, user_id, params):\n \"\"\"Complete registration of newly-registered user\n\n Allocates device_id if one was not given; also creates access_token.\n\n Args:\n (str) user_id: full canonical @user:id\n (object) params: registration parameters, from which we pull\n device_id, initial_device_name and inhibit_login\n Returns:\n defer.Deferred: (object) dictionary for response from /register\n \"\"\"\n result = {\"user_id\": user_id, \"home_server\": self.hs.hostname}\n if not params.get(\"inhibit_login\", False):\n device_id = params.get(\"device_id\")\n initial_display_name = params.get(\"initial_device_display_name\")\n device_id, access_token = yield self.registration_handler.register_device(\n user_id, device_id, initial_display_name, is_guest=False\n )\n\n result.update({\"access_token\": access_token, \"device_id\": device_id})\n return result\n\n @defer.inlineCallbacks\n def _do_guest_registration(self, params, address=None):\n if not self.hs.config.allow_guest_access:\n raise SynapseError(403, \"Guest access is disabled\")\n user_id = yield self.registration_handler.register_user(\n make_guest=True, address=address\n )\n\n # we don't allow guests to specify their own device_id, because\n # we have nowhere to store it.\n device_id = synapse.api.auth.GUEST_DEVICE_ID\n initial_display_name = params.get(\"initial_device_display_name\")\n device_id, access_token = yield self.registration_handler.register_device(\n user_id, device_id, initial_display_name, is_guest=True\n )\n\n return (\n 200,\n {\n \"user_id\": user_id,\n \"device_id\": device_id,\n \"access_token\": access_token,\n \"home_server\": self.hs.hostname,\n },\n )\n\n\ndef register_servlets(hs, http_server):\n EmailRegisterRequestTokenRestServlet(hs).register(http_server)\n MsisdnRegisterRequestTokenRestServlet(hs).register(http_server)\n UsernameAvailabilityRestServlet(hs).register(http_server)\n RegisterRestServlet(hs).register(http_server)\n","sub_path":"synapse/rest/client/v2_alpha/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":23737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404091490","text":"import json\nimport unittest\nfrom collections import namedtuple\n\nfrom birdseye.utils import PY3, PY2\nfrom birdseye import eye\nfrom birdseye.db import Call, Session\nfrom bs4 import BeautifulSoup\n\nsession = Session()\n\n\n@eye\ndef bar():\n pass\n\n\n@eye\ndef foo():\n x = 1\n y = 2\n if x + y > 5:\n 1 / 0\n else:\n x * y\n try:\n bar(x + x, 2 / 0, y + y)\n foo\n except ZeroDivisionError:\n x - y\n for i in [1, 2]:\n for j in [3, 4]:\n i + j\n for k in [5]:\n k\n bar()\n {'list': [n for n in [1, 2]]}\n\n\nclass NormalClass(object):\n def __init__(self):\n self.x = 1\n\n def __repr__(self):\n return '<A>'\n\n\nclass SlotClass(object):\n __slots__ = ('slot1',)\n\n def __init__(self):\n self.slot1 = 3\n\n def __repr__(self):\n return '<B>'\n\n\ncall_id = 0\n\n\ndef call_id_mock(*_):\n global call_id\n call_id += 1\n return 'test_id_%s' % call_id\n\n\neye._call_id = call_id_mock\n\n\ndef get_call_ids(func):\n start_id = call_id + 1\n func()\n end_id = call_id + 1\n return ['test_id_%s' % i for i in range(start_id, end_id)]\n\n\nCallStuff = namedtuple('CallStuff', 'call, soup, call_data, func_data, types')\n\n\ndef get_call_stuff(c_id):\n call = session.query(Call).filter_by(id=c_id).one()\n\n # <pre> makes it preserve whitespace\n soup = BeautifulSoup('<pre>' + call.function.html_body + '</pre>', 'html.parser')\n\n call_data = json.loads(call.data)\n func_data = json.loads(call.function.data)\n types = dict((name, i) for i, name in enumerate(call_data['type_names']))\n return CallStuff(call, soup, call_data, func_data, types)\n\n\ndef byteify(x):\n if isinstance(x, dict):\n return dict((byteify(key), byteify(value)) for key, value in x.items())\n elif isinstance(x, list):\n return [byteify(element) for element in x]\n elif isinstance(x, unicode):\n return x.encode('utf-8')\n else:\n return x\n\n\nclass TestBirdsEye(unittest.TestCase):\n maxDiff = None\n\n def test_stuff(self):\n call_ids = get_call_ids(foo)\n call, soup, call_data, func_data, t = get_call_stuff(call_ids[0])\n\n node_values = call_data['node_values']\n actual_values = {'expr': {}, 'stmt': {}, 'loop': {}}\n loops = {}\n actual_node_loops = {}\n for span in soup('span'):\n index = span['data-index']\n if index not in node_values:\n continue\n data_type = span['data-type']\n text = span.text.strip()\n actual_values[data_type][text] = node_values[index]\n if data_type == 'loop':\n loops[text.split()[1]] = index\n this_node_loops = func_data['node_loops'].get(index)\n if this_node_loops:\n actual_node_loops[text] = [str(x) for x in this_node_loops]\n\n bar_value = [repr(bar), t['function']]\n if PY3:\n bar_value.append(['__wrapped__', [repr(bar.__wrapped__), t['function']]])\n\n expected_values = {\n 'expr': {\n 'x': ['1', t['int']],\n 'y': ['2', t['int']],\n 'x + y': ['3', t['int']],\n 'x + y > 5': ['False', t['bool']],\n 'x * y': ['2', t['int']],\n '2 / 0': ['ZeroDivisionError: division by zero\\n', -1],\n 'bar': bar_value,\n 'bar()': ['None', t['NoneType'], {'inner_call': call_ids[1]}],\n 'x + x': ['2', t['int']],\n 'x - y': ['-1', t['int']],\n 'i': {'0': {'0': ['1', t['int']],\n '1': ['1', t['int']]},\n '1': {'0': ['2', t['int']],\n '1': ['2', t['int']]}},\n 'i + j': {'0': {'0': ['4', t['int']],\n '1': ['5', t['int']]},\n '1': {'0': ['5', t['int']],\n '1': ['6', t['int']]}},\n 'j': {'0': {'0': ['3', t['int']],\n '1': ['4', t['int']]},\n '1': {'0': ['3', t['int']],\n '1': ['4', t['int']]}},\n 'k': {'0': {'0': ['5', t['int']]},\n '1': {'0': ['5', t['int']]}},\n '[n for n in [1, 2]]': ['[1, 2]', t['list'],\n 'len() = 2',\n ['0', ['1', t['int']]],\n ['1', ['2', t['int']]]],\n 'n': {'0': ['1', t['int']],\n '1': ['2', t['int']]},\n \"{'list': [n for n in [1, 2]]}\":\n [\"{'list': [1, 2]}\", t['dict'],\n 'len() = 1',\n [\"'list'\",\n ['[1, 2]', t['list'],\n 'len() = 2',\n ['0', ['1', t['int']]],\n ['1', ['2', t['int']]]]]],\n },\n 'stmt': {\n 'x = 1': True,\n 'y = 2': True,\n '''\n if x + y > 5:\n 1 / 0\n else:\n x * y\n '''.strip(): True,\n 'x * y': True,\n '''\n try:\n bar(x + x, 2 / 0, y + y)\n foo\n except ZeroDivisionError:\n x - y\n '''.strip(): True,\n 'bar(x + x, 2 / 0, y + y)': True,\n 'x - y': True,\n 'i + j': {'0': {'0': True, '1': True}, '1': {'0': True, '1': True}},\n 'k': {'0': {'0': True}, '1': {'0': True}},\n 'bar()': True,\n \"{'list': [n for n in [1, 2]]}\": True,\n },\n 'loop': {\n '''\n for i in [1, 2]:\n for j in [3, 4]:\n i + j\n for k in [5]:\n k \n '''.strip(): True,\n '''\n for j in [3, 4]:\n i + j\n '''.strip(): {'0': True, '1': True},\n '''\n for k in [5]:\n k \n '''.strip(): {'0': True, '1': True},\n 'for n in [1, 2]': True,\n }\n }\n if PY2:\n actual_values = byteify(actual_values)\n self.assertEqual(actual_values, expected_values)\n\n expected_node_loops = {\n 'i + j': [loops['i'], loops['j']],\n 'i': [loops['i'], loops['j']],\n 'j': [loops['i'], loops['j']],\n 'k': [loops['i'], loops['k']],\n '''\n for j in [3, 4]:\n i + j\n '''.strip(): [loops['i']],\n '''\n for k in [5]:\n k \n '''.strip(): [loops['i']],\n 'n': [loops['n']]\n }\n self.assertEqual(actual_node_loops, expected_node_loops)\n\n def test_comprehension_loops(self):\n # noinspection PyUnusedLocal\n @eye\n def f():\n # @formatter:off\n len(([([x for x in [] for y in []], [x for x in [] for y in []]) for x in [x for x in [] for y in []] for y in [x for x in [] for y in []]], [([x for x in [] for y in []], [x for x in [] for y in []]) for x in [x for x in [] for y in []] for y in [x for x in [] for y in []]]))\n # @formatter:on\n\n soup = get_call_stuff(get_call_ids(f)[0]).soup\n for line in str(soup).splitlines():\n self.assertTrue(line.count('for') in (0, 1))\n\n def test_expansion(self):\n @eye\n def f():\n x = {'t': [(7, 8, [9, 10]), NormalClass(), SlotClass(), \"Hello World!\" * 50]}\n len(x)\n\n stuff = get_call_stuff(get_call_ids(f)[0])\n value = [x for x in stuff.call_data['node_values'].values()\n if isinstance(x, list) and\n \"'t': \" in x[0]\n ][0]\n t = stuff.types\n self.assertEqual(\n value,\n [\"{'t': [(7, 8, [...]), <A>, <B>, 'Hello World!H...d!Hello World!']}\",\n t['dict'], 'len() = 1',\n [\"'t'\", [\"[(7, 8, [9, 10]), <A>, <B>, 'Hello World!H...d!Hello World!']\",\n t['list'], 'len() = 4',\n ['0', ['(7, 8, [9, 10])',\n t['tuple'], 'len() = 3',\n ['0', ['7', t['int']]],\n ['1', ['8', t['int']]],\n ['2', ['[9, 10]', t['list']]]]],\n ['1', ['<A>', t['NormalClass'],\n ['x', ['1', t['int']]]]],\n ['2', ['<B>', t['SlotClass'],\n ['slot1', ['3', t['int']]]]],\n ['3', [\"'Hello World!H...d!Hello World!'\",\n t['str'], 'len() = 600']]]]])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_birdseye.py","file_name":"test_birdseye.py","file_ext":"py","file_size_in_byte":8769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"190427512","text":"import os\nimport re\nfrom string import letters\n\nimport webapp2\nimport jinja2\n\nfrom google.appengine.ext import ndb\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nclass BlogHandler(webapp2.RequestHandler):\n def write(self, *a, **kw):\n self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = JINJA_ENVIRONMENT.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n self.write(self.render_str(template, **kw))\n\n\nclass MainPage(BlogHandler):\n def get(self):\n self.write('yo yo test test')\n\n###### blog implementation \n\ndef blog_key(name = 'default'):\n return ndb.Key.from_path('blogs',name)\n\nclass Post(ndb.Model):\n subject = ndb.StringProperty(required = True)\n content = ndb.TextProperty(required = True)\n created = ndb.DateTimeProperty(auto_now_add = True)\n last_modified = ndb.DateTimeProperty(auto_now = True)\n\n def render(self):\n self._render_text = self.content.replace('\\n' '<br>')\n return render_str(\"post.html\", p = self)\n\nclass BlogFront(BlogHandler):\n def get(self):\n posts = ndb.gql(\"SELECT * from Post order by created desc limit 10\") # look up all the post ordered by creation time. store them in post object. Only show the last 10 entries\n self.render('index.html', posts = posts) # renders the html page with the result of the query and var post anpersjournalblog\n\nclass PostPage(BlogHandler):\n def get(self, post_id):\n key = ndb.Key.from_path('Post', int(post_id), parent=blog_key())\n post = ndb.get(key)\n\n if not post:\n self.error(404)\n return\n\n self.render(\"permalink.html\", post = post)\n\n\nclass NewPost(BlogHandler):\n def get(self):\n self.render(\"newpost.html\")\n\n def post(self):\n subject = self.request.get('subject') #verifying the form\n content = self.request.get('content') \n\n if subject and content:\n p = Post(parent = blog_key(), subject=subject, content=content) #if valid content add post\n p.put() #stores the element in the database \n self.redirect('/blog/%s' % str(p.key().id())) #redirect\n else:\n error = \"A paragraph or subject is missing! \" \n self.render(\"newpost.html\", subject=subject, content=content, error=error)\n\n\napp = webapp2.WSGIApplication([\n ('/', MainPage),\n ('/blog/?', BlogFront),\n ('/blog/([0-9]+)', PostPage),\n ('/blog/newpost', NewPost), #syntax for GAE pull up last 10 posts\n], debug=True)\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"635474637","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n#Code challenge: determinant of shifted matrices\n# (as shift the matrix further and further towards the identity matrix,\n# the abs of determinant is larger and larger)\n\n#Generate a 6x6 matrix;\n# shift amount (l=lambda)\nlamdas = np.linspace(0, 0.1, 30)\ndets = []\nfor deti in range (0, len(lamdas)):\n for i in range(0, 999):\n M = np.round(np.random.rand(20,20) * 10)\n\n #impose a linear dependence\n M[:,0] = M[:,1]\n\n #shift the matrix (0->0.1 times the identity matrix) (lambda)\n M = M + lamdas[deti]*np.eye(20,20)\n\n #comput the abs(determinant) of the shifted matrix\n det = []\n det.append(np.abs(np.linalg.det(M)))\n dets.append(np.mean(det))\n#repeat 1000 times, take the averge abs(det)\n#plot of det as a function of lambda\nplt.plot(lamdas, dets, 's')\nplt.show()\n\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"377208555","text":"#!/usr/bin/env python\nimport json\nfrom argparse import ArgumentParser\nfrom tqdm import tqdm\nfrom wikisql.lib.dbengine import DBEngine\nfrom wikisql.lib.query import Query\nfrom wikisql.lib.common import count_lines\n\nimport os\nimport random\n\nrandom.seed(1)\n\n# Jan1 2019. Wonseok. Path info has added to original wikisql/evaluation.py\n# Only need to add \"query\" (essentially \"sql\" in original data) and \"table_id\" while constructing file.\n\nif __name__ == '__main__':\n\n # Hyper parameters\n mode = 'dev'\n ordered = False\n\n dset_name = 'wikisql_tok'\n saved_epoch = 'best' # 30-162\n\n # Set path\n #path_h = '/home/wonseok' # change to your home folder\n path_h = '.' # change to your home folder\n #path_wikisql_tok = os.path.join(path_h, 'data', 'wikisql_tok')\n path_wikisql_tok = os.path.join(path_h, 'bert_and_wikisql', 'wikisql_tok')\n path_save_analysis = '.'\n\n # Path for evaluation results.\n #path_wikisql0 = os.path.join(path_h,'data/WikiSQL-1.1/data')\n path_wikisql0 = os.path.join(path_h, 'bert_and_wikisql', 'wikisql')\n path_source = os.path.join(path_wikisql0, f'{mode}.jsonl')\n path_db = os.path.join(path_wikisql0, f'{mode}.db')\n wikisql_sql = os.path.join(path_wikisql0, f'{mode}.in')\n #path_pred = os.path.join(path_save_analysis, f'results_{mode}.jsonl')\n\n gold_sqls = []\n for l in open(wikisql_sql, 'r'):\n gold_sqls.append(l.strip())\n\n\n # For the case when use \"argument\"\n parser = ArgumentParser()\n parser.add_argument('--source_file', help='source file for the prediction', default=path_source)\n parser.add_argument('--db_file', help='source database for the prediction', default=path_db)\n parser.add_argument('--pred_file', help='predictions by the model')\n parser.add_argument('--ordered', action='store_true', help='whether the exact match should consider the order of conditions')\n args = parser.parse_args()\n args.ordered=ordered\n\n i = 0\n right = []\n wrong = []\n\n engine = DBEngine(args.db_file)\n exact_match = []\n with open(args.source_file) as fs, open(args.pred_file) as fp:\n grades = []\n for ls, lp in tqdm(zip(fs, fp), total=count_lines(args.pred_file)):\n eg = json.loads(ls)\n ep = json.loads(lp)\n qg = Query.from_dict(eg['sql'], ordered=args.ordered)\n gold = engine.execute_query(eg['table_id'], qg, lower=True)\n pred = ep.get('error', None)\n qp = None\n if not ep.get('error', None):\n try:\n qp = Query.from_dict(ep['query'], ordered=args.ordered)\n pred = engine.execute_query(eg['table_id'], qp, lower=True)\n except Exception as e:\n pred = repr(e)\n correct = pred == gold\n match = qp == qg\n if match:\n right.append((ep['nlu'], ep['sql'], gold_sqls[i], i))\n else:\n wrong.append((ep['nlu'], ep['sql'], gold_sqls[i], i))\n i += 1\n grades.append(correct)\n exact_match.append(match)\n\n print(json.dumps({\n 'ex_accuracy': sum(grades) / len(grades),\n 'lf_accuracy': sum(exact_match) / len(exact_match),\n }, indent=2))\n\n\n random.shuffle(right)\n target_dir = os.path.dirname(os.path.realpath(args.pred_file))\n right_file = open(os.path.join(target_dir, 'right.txt'), 'w')\n for r in right:\n right_file.write(str(r[3]) + '\\n')\n right_file.write(r[0] + '\\n')\n right_file.write(r[1] + '\\n')\n right_file.write('*'*20 + '\\n')\n\n random.shuffle(wrong)\n wrong_file = open(os.path.join(target_dir, 'wrong.txt'), 'w')\n for w in wrong:\n wrong_file.write(str(w[3]) + '\\n')\n wrong_file.write(w[0] + '\\n')\n wrong_file.write(w[1] + '\\n')\n wrong_file.write(w[2] + '\\n')\n wrong_file.write('*'*20 + '\\n')\n\n\n","sub_path":"get_right_wrong.py","file_name":"get_right_wrong.py","file_ext":"py","file_size_in_byte":3911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"20118409","text":"import json\nimport random\nimport sys\n\n\ndef gera_lista(limite_inferior, limite_superior, quantidade_numeros):\n lista_de_valores = []\n for i in range(limite_inferior, limite_superior, (limite_superior - limite_inferior)//quantidade_numeros):\n lista_de_valores.append(\n '\"{:011d}\", \"{}\", \"{}\", \"{}\"\\n'.format(\n i,\n names[random.randint(0,quantidade_names-1)],\n middle_names[random.randint(0,quantidade_middle_names-1)],\n surnames[random.randint(0,quantidade_surnames-1)]\n )\n )\n return lista_de_valores\n\ndef gera_arquivo(limite_inferior, limite_superior, quantidade_numeros, arquivo):\n lista_de_valores = []\n with open(arquivo, \"w+\") as file:\n for i in range(limite_inferior, limite_superior, (limite_superior - limite_inferior)//quantidade_numeros):\n file.write(\n '\"{:011d}\", \"{}\", \"{}\", \"{}\"\\n'.format(\n i,\n names[random.randint(0,quantidade_names-1)],\n middle_names[random.randint(0,quantidade_middle_names-1)],\n surnames[random.randint(0,quantidade_surnames-1)]\n )\n )\n\ndef load_names(filename):\n names = []\n with open(filename) as json_file: \n data = json.load(json_file)\n names = [p for p in data]\n return names\n\nif __name__ == '__main__':\n\n if len(sys.argv) == 4:\n filename = sys.argv[1]\n quantidade_arquivos = sys.argv[2]\n quantidade_numeros = sys.argv[3]\n else:\n filename = \"registered{}.csv\"\n quantidade_arquivos = 1\n quantidade_numeros = 50000\n\n # parametros do algoritmo\n names = load_names('names.json')\n quantidade_names = len(names)\n middle_names = load_names('middle-names.json')\n quantidade_middle_names = len(middle_names)\n surnames = load_names('surnames.json')\n quantidade_surnames = len(surnames)\n\n # ALTERAR os arquivos gerados são definidos aqui\n for i in range(quantidade_arquivos):\n limite_inferior = 0 + i*quantidade_numeros\n limite_superior = quantidade_numeros + i*quantidade_numeros\n gera_arquivo(limite_inferior, limite_superior, quantidade_numeros, filename.format(i))\n","sub_path":"generate_names.py","file_name":"generate_names.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"479162545","text":"#!/usr/bin/env python3\n\"\"\"Keras module\"\"\"\nimport tensorflow.keras as K\n\n\ndef train_model(network, data, labels, batch_size, epochs,\n validation_data=None, early_stopping=False,\n patience=0, verbose=True, shuffle=False):\n \"\"\"Trains a model using the mini-batch gradient descent and analyze\n validation data.\n\n Args:\n network (keras.model): Is the model to train.\n data (numpy.ndarray): Is containing the input data of shapr (m, nx)\n where m is the number of input data and nx is the number of\n features.\n labesl (numpy.ndarray): Is containing the one-hot labels of data.\n batch_size (int): Is the size of batch used for mini-batch gradient\n descent.\n epochs (int): Is the number of passes through the data for MBGD.\n validation_data (numpy.ndarray): Is the data to validate the model with\n early_stoppint (boolean): determines whether early stopping should be\n used or not.\n patience (int): Is the patience used for early stopping.\n verbose (boolean): Is determines if output should be printed during\n training.\n shuffle (boolean): Is determines whether to shuffle the batches every\n epoch, It is set to False for reproducibility.\n\n Returns:\n Objects: History objects generated after training.\n\n \"\"\"\n if early_stopping:\n callback = K.callbacks.EarlyStopping(patience=patience)\n else:\n callback = None\n history = network.fit(\n x=data,\n y=labels,\n epochs=epochs,\n batch_size=batch_size,\n verbose=verbose,\n validation_data=validation_data,\n shuffle=shuffle,\n callbacks=[callback]\n )\n return history\n","sub_path":"supervised_learning/0x06-keras/6-train.py","file_name":"6-train.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"224339655","text":"from random import randint\nword = \"champion\"\na = list(word)\nfor i in range(len(a)):\n b = randint(0, len(a) - 1) # lay ngau nhien so tu 0 - (len(a))\n a.append(a[b]) # them gia tri o tri random \"b\" vao cuoi list\n a.pop(b) # moi khi them moi gia tri o vtri \"b\" thi xoa di phan tu o vi tri \"b\" truoc do\nprint(*a)\nloop = True\nuser = input(\"Your answer: \")\nwhile loop:\n if user == word:\n print(\"Hura\")\n loop = False\n else:\n print(\":(\")\n loop = True\n user = input(\"Your answer: \")\n \n\n#print(list(a[random.randint(0, 2)]))\n# print(a)\n# print(b)\n# print(len(a))\n","sub_path":"Fundamentals/Session3/Homework/word_jumble.py","file_name":"word_jumble.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"358450947","text":"'''-------------------------------------------------------------------------------------\nAUTHORS\t\t\t:\tBrian Chung & Michael Cingari & Owen Salcido\nLAST MODIFIED\t:\t11/18/2019\nFILE : 'syntax_analysis_helper.py'\n-------------------------------------------------------------------------------------'''\n\n#Given errorID and token, return an error code\ndef syntaxError(errorID, token):\n if(errorID == \"S\"):\n if(token == \"end\"):\n return(\"Only use ; if there is a next statement\")\n else:\n return(\"Not a valid statement.\")\n elif(errorID == \"A\"):\n return(\"Not a valid assignment.\")\n elif(errorID == \"E\"):\n return(\"Not a valid expression.\")\n elif(errorID == \"E'\"):\n return(\"Not a valid expression.\")\n elif(errorID == \"T\"):\n return(\"Not a valid term.\")\n elif(errorID == \"T'\"):\n return(\"Not a valid term.\")\n elif(errorID == \"F\"):\n return(\"Not a valid factor.\")\n elif(errorID == \"D\"):\n return(\"Not a valid declarative.\")\n elif(errorID == \"P\"):\n return(\"Not a valid type.\")\n elif(errorID == \"Mi\"):\n return(\"Not a valid ID\")\n elif(errorID == \"I\"):\n return(\"Not a valid if statement\")\n elif(errorID == \"L\"):\n return(\"Not a valid else statement\")\n elif(errorID == \"W\"):\n return(\"Not a valid while statement\")\n elif(errorID == \"B\"):\n return(\"Not a valid begin statement\")\n elif(errorID == \"Ms\"):\n return(\"Not a valid statement\")\n elif(errorID == \"C\"):\n return(\"Not a valid conditional\")\n elif(errorID == \"C'\"):\n return(\"Not a valid conditional\")\n elif(errorID == \"R\"):\n return(\"Not a valid relational operator\")\n else:\n return(\"Unknown error\")\n\n#Convert shortened rule into readable format\ndef convertRule(ruleID):\n if(ruleID == \"S\"):\n return(\"<Statement>\")\n elif(ruleID == \"A\"):\n return(\"<Assignment>\")\n elif(ruleID == \"E\"):\n return(\"<Expression>\")\n elif(ruleID == \"E'\"):\n return(\"<Expression Prime>\")\n elif(ruleID == \"T\"):\n return(\"<Term>\")\n elif(ruleID == \"T'\"):\n return(\"<Term Prime>\")\n elif(ruleID == \"F\"):\n return(\"<Factor>\")\n elif(ruleID == \"D\"):\n return(\"<Declarative>\")\n elif(ruleID == \"P\"):\n return(\"<Type>\")\n elif(ruleID == \"Mi\"):\n return(\"<More IDs>\")\n elif(ruleID == \"I\"):\n return(\"<If Statement>\")\n elif(ruleID == \"L\"):\n return(\"<Else Statement>\")\n elif(ruleID == \"W\"):\n return(\"<While Statement>\")\n elif(ruleID == \"B\"):\n return(\"<Block Statement>\")\n elif(ruleID == \"Ms\"):\n return(\"<More Statements>\")\n elif(ruleID == \"C\"):\n return(\"<Conditional>\")\n elif(ruleID == \"C'\"):\n return(\"<Conditional Prime>\")\n elif(ruleID == \"R\"):\n return(\"<Relational Operator>\")\n elif(ruleID == \"ID\"):\n return(\"<Identifier>\")\n else:\n return(ruleID)\n\n#Output a printable format of the full production rule given pop and push values during stack parsing\ndef printProductionRules(poppedValue, pushValues):\n outputString = \" \"\n outputString += convertRule(poppedValue) + \" -> \"\n for values in pushValues:\n outputString += convertRule(values) + \" \"\n return(outputString)","sub_path":"code/syntax_analysis_helper.py","file_name":"syntax_analysis_helper.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"472289754","text":"import numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nfrom base.base_train import BaseTrain\n\n\nclass ExampleTrainer(BaseTrain):\n def __init__(self, sess, model, data, config, logger):\n super(ExampleTrainer, self).__init__(sess, model, data, config, logger)\n\n def train_epoch(self):\n loop = tqdm(range(self.config.num_iter_per_epoch))\n losses = []\n accs = []\n test_losses = []\n test_accs = []\n for _ in loop:\n loss, acc, test_loss, test_acc = self.train_step()\n losses.append(loss)\n accs.append(acc)\n test_losses.append(test_loss)\n test_accs.append(test_acc)\n loss = np.mean(losses)\n acc = np.mean(accs)\n\n cur_it = self.model.global_step_tensor.eval(self.sess)\n summaries_dict = {'loss': loss, 'acc': acc}\n self.logger.summarize(cur_it, summaries_dict=summaries_dict)\n\n test_loss = np.mean(test_losses)\n test_acc = np.mean(test_accs)\n summaries_dict = {'loss': test_loss, 'acc': test_acc}\n self.logger.summarize(cur_it, summarizer=\"test\", summaries_dict=summaries_dict)\n\n self.model.save(self.sess)\n\n def train_step(self):\n test_batch_x, test_batch_y = next(self.data.next_test_batch(self.config.batch_size))\n feed_dict = {self.model.x: test_batch_x, self.model.y: test_batch_y,\n self.model.mode: tf.estimator.ModeKeys.EVAL}\n test_loss, test_acc = self.sess.run([self.model.loss, self.model.accuracy], feed_dict=feed_dict)\n\n batch_x, batch_y = next(self.data.next_batch(self.config.batch_size))\n feed_dict = {self.model.x: batch_x, self.model.y: batch_y, self.model.mode: tf.estimator.ModeKeys.TRAIN}\n # print(\"\\n\")\n # print(\"y: \"+str(batch_y))\n # print(\"\\n\")\n _, loss, acc, predictions, label_indices = self.sess.run(\n [self.model.train_op, self.model.loss, self.model.accuracy, self.model.predictions, self.model.label_indices],\n feed_dict=feed_dict)\n # print(\"\\n\")\n # print(\"label_indices: \"+str(label_indices))\n # print(\"\\n\")\n # print(predictions)\n return loss, acc, test_loss, test_acc\n","sub_path":"trainers/digit_recognizer_trainer.py","file_name":"digit_recognizer_trainer.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"336081001","text":"#!/usr/bin/env python2.7\n# script by Alex Eames http://RasPi.tv\n# http://RasPi.tv/\n# http://RasPi.tv/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi\n#-gpio-part-3\nimport RPi.GPIO as GPIO\nimport ADC0832 as ADC\nimport subprocess\nimport Adafruit_CharLCD as LCD\nimport time\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nlcd = LCD.Adafruit_CharLCDPlate()\nselectADC = False\nwhile True:\n IPaddr = subprocess.check_output(['hostname ', ' -I'])\n if len(IPaddr) > 8:\n break\n else:\n time.sleep(2)\nName = subprocess.check_output(['hostname']).strip()\ndisplayText = IPaddr + Name\n\n\ndef getvoltage():\n stepspervolt = 3.3 / 255\n ADCvalue = ADC.getResult()\n ADCvoltage = ADCvalue * stepspervolt\n Displaystring = \"ADC voltage:\\n %3.3f\" % ADCvoltage\n return Displaystring\n\n\ndef subtractvoltage(getvoltage):\n return Displaystring\n\n\ndef getIP():\n return displayText\n\n\ndef my_callbackADC(channel):\n global selectADC\n selectADC = True\n\n\ndef my_callbackIP(channel):\n global selectADC\n selectADC = False\n\n\n# when a falling edge is detected on port 17, regardless of whatever\n# else is happening in the program, the function my_callback will be run\nGPIO.add_event_detect(17, GPIO.FALLING, callback=my_callbackADC, bouncetime=300)\n\n# when a falling edge is detected on port 23, regardless of whatever\n# else is happening in the program, the function my_callback2 will be run\n# 'bouncetime=300' includes the bounce control written into interrupts2a.py\nGPIO.add_event_detect(23, GPIO.FALLING, callback=my_callbackIP, bouncetime=300)\n\nolddisplay = None\n\ntry:\n while True:\n if selectADC:\n display = getvoltage()\n else:\n display = getIP()\n if display == olddisplay:\n pass\n else:\n lcd.clear()\n lcd.message(display)\n olddisplay = display\n time.sleep(0.4)\n\n\nexcept KeyboardInterrupt:\n GPIO.cleanup() # clean up GPIO on CTRL+C exit\nGPIO.cleanup() # clean up GPIO on normal exit","sub_path":"Python/Lab4.py","file_name":"Lab4.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"390208809","text":"#2014-10-13 Yifeng Ding\n#\n#Write a script using this function to make\n#a pcolormesh map of the topo/bathy\n#\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport urllib\n\nurl = \"http://www.nio.org/userfiles/file/datainfo/global_merged5.txt\"\n\nf=urllib.urlopen(url)\n\nlon=[]\nlat=[]\ntop=[]\n\nfor line in f.readlines():\n\tif len(line)==4 :\n\t\tilon,ilat,itop,dum = line.split()\n\t\tlon.append(ilon)\n\t\tlat.append(ilat)\n\t\ttop.append(itop)\n\nmlon=np.reshape(np.array(lon),[2161,4321])\nmlat=np.reshape(np.array(lat),[2161,4321])\nmtop=np.reshape(np.array(top),[2161,4321])\n\nplt.pcolormesh(mlon,mlat,mtop,cmap=plt.cm.RdBu_r)\n\nCS = plt.contour(mlon, mlat, mtop,(-1000.,1000),colors='k',linewidths=1)\nCS.collections[1].set_linestyle('solid')\n\nCS2 = plt.contour(mlon, mlat, mtop,(0.,),colors='k',linewidths=2)\nCS2.collections[0].set_linestyle('solid')\n\nplt.show()\n","sub_path":"HW2/plot_map.py","file_name":"plot_map.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"129151398","text":"import numpy as np\nimport tflite_runtime.interpreter as tflite\nimport time\n\nepoch = 200\n\ndef tflite_inference(model,batch_size):\n # Load the TFLite model and allocate tensors.\n interpreter = tflite.Interpreter(model_path=\"/home/mendel/block_iteration/{}.tflite\".format(model),\n experimental_delegates=[tflite.load_delegate('libedgetpu.so.1')])\n #interpreter = tflite.Interpreter(model_path=\"{}.tflite\".format(model))\n interpreter.allocate_tensors()\n\n # Get input and output tensors.\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n # Test the model on random input data.\n input_shape = input_details[0]['shape']\n input_shape = [batch_size,224,224,3]\n input_data = np.array(np.random.random_sample(input_shape), dtype=np.uint8)\n interpreter.resize_tensor_input(input_details[0]['index'], (batch_size,224,224,3))\n interpreter.allocate_tensors()\n interpreter.set_tensor(input_details[0]['index'], input_data)\n\n #allocate data\n start1 = time.time()\n interpreter.invoke()\n end1 = time.time()\n \n start2 = time.time()\n for i in range(epoch):\n interpreter.invoke()\n end2 = time.time()\n \n # The function `get_tensor()` returns a copy of the tensor data.\n # Use `tensor()` in order to get a pointer to the tensor.\n \n output_data = interpreter.get_tensor(output_details[0]['index'])\n del(output_data)\n print(\"batch_size :\", '%d' % (batch_size),\n \"first_time :\", '%.3f' % ((end1 - start1)*1000), \"ms\",\n \"infrence :\", '%.3f' % ((end2 - start2)*1000/epoch), \"ms\",\n \" time/batch :\", '%.3f' % ((end2 - start2)*1000/(batch_size*epoch)), \"ms\"\n ) \n\nprint(\"mobilenet_v1_1.0_224_quant_edgetpu, epoch: \", epoch)\n\nbatch_list = [31,32,33,63,64,65,127,128,129] \n\nfor i in range(len(batch_list)) :\n tflite_inference(\"mobilenet_v1_1.0_224_quant_edgetpu\", batch_size=batch_list[i])\n\n\n","sub_path":"edgetpu/mobilenetv1/batch_inference.py","file_name":"batch_inference.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"178852022","text":"#!/usr/bin/env python\n# -*- encoding:utf-8 -*-\n\n# Author: lixingtie\n# Email: lixingtie@barfoo.com.cn\n# Create Date: 2012-12-13\n\nimport os\nimport glob\nimport shutil\nimport tempfile\nimport zipfile, rarfile\nimport json\nimport tornado\nfrom bson import ObjectId, DBRef\nfrom core.web import HandlerBase\nfrom framework.mvc.web import url\nfrom framework.data.mongo import db, Document\nfrom framework.web import paging, JSONEncoder\n\ntry:\n from cStringIO import StringIO\nexcept:\n from StringIO import StringIO\n\n\n@url(\"/resources/list.html\")\nclass List(HandlerBase):\n def get(self):\n categoryID = self.get_argument('categoryID', '');\n cond = {}\n if categoryID:\n cond = {\"category.$id\":ObjectId(categoryID)}\n cursor = db.resources.find(cond)\n self.context.paging = paging.parse(self)\n self.context.paging.count = cursor.count()\n self.context.categorys = list(db.resourcescategory.find())\n self.context.resources = cursor.skip(paging.skip(self.context.paging)).limit(self.context.paging.size)\n\n return self.template()\n\n@url(\"/resources/edit.html\")\nclass Edit(HandlerBase):\n def get(self):\n id = self.get_argument(\"id\")\n resource = db.resources.find_one({ \"_id\" : ObjectId(id) })\n return self.json(resource, cls=JSONEncoder)\n\n def head(self):\n id = self.get_argument(\"id\", \"\") or None\n name = self.get_argument(\"name\", \"\")\n\n dul_doc = False # 判断name是否重复\n has_doc = db.resources.find({'name': name})\n if id:\n if has_doc.count() > 1:\n dul_doc = True\n elif has_doc.count() == 1:\n if str(has_doc[0]._id) != id:\n dul_doc = True\n else:\n if has_doc.count() >= 1:\n dul_doc = True\n\n if not dul_doc:\n self.set_status(404)\n\n def post(self):\n id = self.get_argument(\"_id\", \"\") or None\n\n new = not id\n if new:\n doc = Document()\n doc._id = id = ObjectId()\n resource_paths = {'css': {}, 'js': {}}\n else:\n doc = db.resources.find_one({'_id': ObjectId(id)})\n resource_paths = json.loads(doc.resource_paths)\n id = doc.pop('_id')\n\n doc.name = self.get_argument(\"name\", \"\")\n doc.alias = self.get_argument(\"alias\", \"\")\n doc.category = DBRef(\"resourcescategory\", ObjectId(self.get_argument(\"category\")))\n doc.tag = self.get_argument(\"tag\", \"\")\n doc.description = self.get_argument(\"description\", \"\")\n\n resource = self.request.files.get('resource')\n if resource:\n if not new: # 上传了新的文件,删除旧的文件\n remove_files( db.resources.find_one({ \"_id\" : ObjectId(id) }) )\n\n resource = resource[0]\n ext = os.path.splitext(resource['filename'])[1].lower()\n extract_folder = os.path.join('static', 'custom', doc.name.encode('utf8'))\n\n if not os.path.exists(extract_folder):\n os.makedirs(extract_folder)\n\n css_container = resource_paths['css'] # dict obj\n js_container = resource_paths['js'] # dict obj\n\n if ext == '.zip':\n css_paths, js_paths = process_compress(resource, extract_folder, 'zip')\n doc.resource_parent = extract_folder\n\n elif ext == '.rar':\n css_paths, js_paths = process_compress(resource, extract_folder, 'rar')\n doc.resource_parent = extract_folder\n\n elif ext in ['js', 'css']:\n file_name = os.path.join(extract_folder, resource['filename'])\n with open(file_name, 'wb') as fp:\n fp.write( resource['body'] )\n\n css_paths = {}\n js_paths = {}\n\n if ext == 'js':\n js_paths[file_name] = 0\n else:\n css_paths[file_name] = 0\n\n for path in css_container:\n if path in css_paths:\n css_paths[path] = css_container[path]\n resource_paths['css'] = css_paths\n\n for path in js_container:\n if path in js_paths:\n js_paths[path] = js_container[path]\n resource_paths['js'] = js_paths\n\n doc.resource_paths = json.dumps(resource_paths)\n if new:\n db.resources.save(doc)\n else:\n db.resources.update({ \"_id\" : ObjectId(id) }, { \"$set\" : doc })\n\n return self.redirect(\"list.html\")\n\n@url(\"/resources/remove.html\")\nclass Remove(HandlerBase):\n def get(self):\n return self.post()\n\n def post(self):\n id = self.get_argument(\"id\")\n resource = db.resources.find_one({ \"_id\" : ObjectId(id) })\n remove_files(resource)\n\n db.resources.remove({ \"_id\" : ObjectId(id) })\n self.redirect(\"list.html\")\n\n@url(\"/resources/download/(?:([a-z0-9]{24}))?\")\nclass Download(HandlerBase):\n \"\"\" 下载资源文件 \"\"\"\n\n @tornado.web.asynchronous\n def get(self, uid):\n \"\"\" \"\"\"\n resource = db.resources.find_one({ \"_id\" : ObjectId(uid) })\n\n zip_root = tempfile.mkdtemp()\n zip_path = os.path.join(zip_root, 'download.zip')\n\n try:\n with zipfile.ZipFile(zip_path, 'w') as myzip:\n self.add_folder_to_zip(myzip, resource.resource_parent, resource.resource_parent)\n\n self.set_header('Content-Type', 'application/zip')\n self.set_header('Content-Length', str(os.path.getsize(zip_path)))\n self.set_header('Cache-Control', 'private, max-age=0, no-cache')\n self.set_header('Content-Disposition', 'attachment; filename=%s.zip' % resource.alias.encode('utf8'))\n\n with file(zip_path) as fp:\n while True:\n data = fp.read(1024*100)\n if not data:\n break\n self.write(data)\n\n finally:\n self.finish()\n shutil.rmtree(zip_root)\n\n def add_folder_to_zip(self, myzip, top, folder):\n \"\"\" 压缩文件夹 \"\"\"\n #folder = folder.encode('ascii')\n #folder = folder.decode('utf8').encode('utf8')\n folder = folder.encode('utf-8').strip()\n for file_path in glob.glob(folder+\"/*\"):\n if os.path.isfile(file_path):\n file_name = file_path.replace(top, '')\n myzip.write(file_path, file_name)\n elif os.path.isdir(file_path):\n self.add_folder_to_zip(myzip, top, file_path)\n\n@url(\"/resources/sort.html\")\nclass Sort(HandlerBase):\n \"\"\"资源排序\"\"\"\n def get(self):\n id=self.get_argument(\"id\")\n resource=db.resources.find_one({\"_id\":ObjectId(id)})\n res={\"js\":None,\"css\":None}\n\n resource_paths = json.loads(resource.resource_paths)\n for v in res:\n l1=[]\n data=resource_paths[v]\n\n if isinstance(data, dict):\n for path, sort in data.items():\n l1.append((path, sort, path[7:]))\n\n l1.sort(lambda x,y:-cmp(x[1],y[1]))\n res[v]=l1\n\n self.context.data=res\n self.context.Id=id\n return self.template()\n\n def post(self):\n\n id=self.get_argument(\"id\")\n doc=db.resources.find_one({\"_id\":ObjectId(id)})\n parms=[(\"csspath\",\"csssort\",\"css\"),(\"jspath\",\"jssort\",\"js\")]\n resource_paths = json.loads(doc.resource_paths)\n\n for v in parms:\n name=self.get_argument(v[0])\n sort=self.get_argument(v[1])\n names=str(name).split(\",\")\n sorts=str(sort).split(\",\")\n l2 = {}\n for i,a in enumerate(names):\n if not a:\n continue\n l2[a] = int(sorts[i])\n\n resource_paths[v[2]] = l2\n\n doc.pop(\"_id\")\n doc.resource_paths = json.dumps(resource_paths)\n db.resources.update({ \"_id\" : ObjectId(id) }, { \"$set\" : doc })\n self.redirect(\"list.html\")\n\ndef process_compress(obj, extract_folder, type):\n \"\"\" \"\"\"\n output = StringIO()\n output.write(obj['body'])\n\n if type == 'zip':\n compress = zipfile.ZipFile(output)\n else:\n compress = rarfile.RarFile(output)\n\n scripts = {}\n styles = {}\n for info in compress.infolist():\n if info.filename.count(os.path.sep) > 2:\n continue\n\n ext = os.path.splitext(info.filename)[1].lower()\n # 只有js和css才需要记录\n if ext == '.js':\n scripts[os.path.join(extract_folder, info.filename) ] = 0\n elif ext == '.css':\n styles[os.path.join(extract_folder, info.filename)] = 0\n\n compress.extractall(extract_folder)\n compress.close()\n output.close()\n\n return styles, scripts\n\ndef remove_files(resource):\n \"\"\" 删除资源文件 \"\"\"\n\n resource_paths = json.loads(resource.resource_paths)\n\n if 'resource_parent' in resource and resource.resource_parent:\n os.system('rm -rf ' + resource.resource_parent)\n\n elif 'resource_paths' in resource and resource_paths:\n for path in resource_paths['css']:\n os.remove( path )\n for path in resource_paths['js']:\n os.remove( path )\n","sub_path":"handlers/resources/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":9291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"215934826","text":"from influxdb import DataFrameClient\nimport os\nimport json\nimport pandas as pd\n\n\npath1 = \"/home/suchita/PycharmProjects/StreamingTDA/tryjson\"\njsonfile = path1\n\n# dict2 = {} # create an empty list\n\ndef create_dict(dict1, timestamp):\n cols = [\"timestamp\", \"key\", \"BID_PRICE\", \"ASK_PRICE\", \"BID_SIZE\", \"ASK_SIZE\", \"ASK_ID\", \"BID_ID\", \"TOTAL_VOLUME\",\n \"LAST_SIZE\", \"TRADE_TIME\", \"QUOTE_TIME\", \"HIGH_PRICE\", \"LOW_PRICE\", \"BID_TICK\", \"CLOSE_PRICE\",\n \"EXCHANGE_ID\",\n \"MARGINABLE\", \"SHORTABLE\", \"ISLAND_BID_DEPRECATED\", \"ISLAND_ASK_DEPRECATED\", \"ISLAND_VOLUME_DEPRECATED\",\n \"QUOTE_DAY\", \"TRADE_DAY\", \"VOLATILITY\", \"DESCRIPTION\", \"LAST_ID\", \"DIGITS\", \"OPEN_PRICE\",\n \"NET_CHANGE\", \"HIGH_52_WEEK\", \"LOW_52_WEEK\", \"PE_RATIO\", \"DIVIDEND_AMOUNT\", \"DIVIDEND_YIELD\",\n \"ISLAND_BID_SIZE_DEPRECATED\", \"ISLAND_ASK_SIZE_DEPRECATED\", \"NAV\", \"FUND_PRICE\",\n \"EXCHANGE_NAME\", \"DIVIDEND_DATE\", \"IS_REGULAR_MARKET_QUOTE\", \"IS_REGULAR_MARKET_TRADE\",\n \"REGULAR_MARKET_LAST_PRICE\", \"REGULAR_MARKET_LAST_SIZE\", \"REGULAR_MARKET_TRADE_TIME\",\n \"REGULAR_MARKET_TRADE_DAY\", \"REGULAR_MARKET_NET_CHANGE\", \"SECURITY_STATUS\", \"MARK\", \"QUOTE_TIME_IN_LONG\",\n \"TRADE_TIME_IN_LONG\",\"REGULAR_MARKET_TRADE_TIME_IN_LONG\"]\n newdict = {}\n newdict = newdict.fromkeys(cols)\n newdict['timestamp'] = timestamp\n for k, v in dict1.items():\n if k in cols:\n newdict[k] = v\n return newdict\n\ndef get_list_of_json_files():\n list_of_files = os.listdir('/home/suchita/PycharmProjects/StreamingTDA/tryjson/') # creates list of all the files in the folder\n return list_of_files\n\ndef write_db():\n\n cols1 = [\"timestamp\", \"key\", \"BID_PRICE\", \"ASK_PRICE\", \"BID_SIZE\", \"ASK_SIZE\", \"ASK_ID\", \"BID_ID\", \"TOTAL_VOLUME\",\n \"LAST_SIZE\", \"TRADE_TIME\", \"QUOTE_TIME\", \"HIGH_PRICE\", \"LOW_PRICE\", \"BID_TICK\", \"CLOSE_PRICE\", \"EXCHANGE_ID\",\n \"MARGINABLE\", \"SHORTABLE\", \"ISLAND_BID_DEPRECATED\", \"ISLAND_ASK_DEPRECATED\", \"ISLAND_VOLUME_DEPRECATED\",\n \"QUOTE_DAY\", \"TRADE_DAY\", \"VOLATILITY\", \"DESCRIPTION\", \"LAST_ID\", \"DIGITS\", \"OPEN_PRICE\",\n \"NET_CHANGE\", \"HIGH_52_WEEK\", \"LOW_52_WEEK\", \"PE_RATIO\", \"DIVIDEND_AMOUNT\", \"DIVIDEND_YIELD\",\n \"ISLAND_BID_SIZE_DEPRECATED\", \"ISLAND_ASK_SIZE_DEPRECATED\", \"NAV\", \"FUND_PRICE\",\n \"EXCHANGE_NAME\", \"DIVIDEND_DATE\", \"IS_REGULAR_MARKET_QUOTE\", \"IS_REGULAR_MARKET_TRADE\",\n \"REGULAR_MARKET_LAST_PRICE\", \"REGULAR_MARKET_LAST_SIZE\", \"REGULAR_MARKET_TRADE_TIME\",\n \"REGULAR_MARKET_TRADE_DAY\", \"REGULAR_MARKET_NET_CHANGE\", \"SECURITY_STATUS\", \"MARK\", \"QUOTE_TIME_IN_LONG\",\n \"TRADE_TIME_IN_LONG\",\"REGULAR_MARKET_TRADE_TIME_IN_LONG\"]\n # with open('//home/suchita/PycharmProjects/StreamingTDA/output.csv', 'a', newline='') as c:\n # writer = csv.DictWriter(c, fieldnames=cols1)\n # writer.writeheader()\n dbClient = DataFrameClient('localhost', 8086, 'stockdata')\n dbClient.create_database('stockdata')\n # tagdic = {'key'}\n list_of_files = get_list_of_json_files()\n for file in list_of_files:\n print(file)\n with open(path1 + \"/\" + file) as f:\n data = json.loads(f)\n count = len(data['content'])\n\n for i in range(count):\n dict2 = {**data['content'][i]}\n dict3 = create_dict(dict2, data['timestamp'])\n df = pd.DataFrame(dict3)\n print(dict3)\n dbClient.write_points(pd, measurement = 'StockData', database= 'stockdata')\n\n\nif __name__ == \"__main__\":\n write_db()","sub_path":"datastorage.py","file_name":"datastorage.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"12584128","text":"#!/usr/bin/env python\n\nimport argparse\nimport os\nimport struct\nimport sys\n\ndef auto_int(x):\n return int(x, 0)\n\ndef decompress_mio0(raw_bytes):\n magic = raw_bytes[:4]\n assert magic == b'MIO0'\n\n uncompressed_size, lengths_offs, data_offs = struct.unpack('>LLL', raw_bytes[4:16])\n flags_offs = 0x10\n\n output = b\"\"\n while True:\n command_byte = raw_bytes[flags_offs]\n flags_offs += 1\n\n for i in reversed(range(8)):\n if command_byte & (1 << i):\n # Literal\n uncompressed_size -= 1\n output += bytes([raw_bytes[data_offs]])\n data_offs += 1\n else:\n # LZSS\n tmp, = struct.unpack('>H', raw_bytes[lengths_offs:lengths_offs+2])\n lengths_offs += 2\n\n window_offset = (tmp & 0x0FFF) + 1\n window_length = (tmp >> 12) + 3\n uncompressed_size -= window_length\n for j in range(window_length):\n output += bytes([output[-window_offset]])\n\n if uncompressed_size <= 0:\n return output\n\ndef print_hex_dump(raw_bytes):\n count = 0\n for b in raw_bytes:\n if count % 16 == 0:\n sys.stdout.write(' ' * 4)\n sys.stdout.write('{:02x} '.format(b))\n count += 1\n if count % 16 == 0:\n sys.stdout.write('\\n')\n if count % 16:\n sys.stdout.write('\\n')\n\ndef pw64_dump_filesys(fname, startOffset, hexSize, outputDir):\n currentDumpFilename = None\n\n if outputDir:\n os.makedirs(outputDir, exist_ok=True)\n\n def dump_binary(raw_bytes):\n if outputDir and currentDumpFilename is not None:\n with open(f'{outputDir}/{currentDumpFilename}', 'wb') as f:\n f.write(raw_bytes)\n\n if hexSize > 0:\n if len(raw_bytes) > hexSize:\n raw_bytes = raw_bytes[:hexSize]\n print_hex_dump(raw_bytes)\n\n def chunk_iter():\n while (fin.tell() < formEnd):\n chunkType = fin.read(4)\n chunkTypeStr = chunkType.decode('utf-8')\n\n # Special handling: GZIP chunks are decompressed before they're interpreted\n if chunkType == b'GZIP':\n gzipLength = int.from_bytes(fin.read(4), byteorder='big')\n absOffset = fin.tell() + gzipLength\n magic = fin.read(4)\n magicStr = magic.decode('utf-8')\n decompLength = int.from_bytes(fin.read(4), byteorder='big')\n\n compBytes = fin.read(gzipLength - 8)\n\n length = decompLength\n rawBytes = decompress_mio0(compBytes)\n else:\n length = int.from_bytes(fin.read(4), byteorder='big')\n rawBytes = fin.read(length)\n magicStr = chunkTypeStr\n\n yield magicStr, rawBytes\n\n def print_chunk_header(magicStr, rawBytes, extra=''):\n fileOffset = fin.tell()\n print('0x%06X|%06X: %s: 0x%06X: %s' % (fileOffset, fileOffset - startOffset, magicStr, len(rawBytes), extra))\n\n with open(fname, 'rb') as fin:\n fin.seek(startOffset)\n while True:\n fileOffset = fin.tell()\n sys.stdout.write('0x%06X|%06X: ' % (fileOffset, fileOffset - startOffset))\n magic = fin.read(4)\n\n if len(magic) == 0 or magic == b'\\0\\0\\0\\0': # End of file\n break\n\n # All entries should be FORMs\n assert magic == b'FORM'\n formLength = int.from_bytes(fin.read(4), byteorder='big')\n formEnd = fin.tell() + formLength\n formType = fin.read(4)\n formTypeStr = formType.decode('utf-8')\n print('%s: 0x%06X (end: 0x%06X)' % (formTypeStr, formLength, formEnd))\n chunkIndex = 0\n\n currentDumpPrefix = f'{formTypeStr}_0x{fileOffset:X}'\n currentDumpFilename = None\n\n if formTypeStr == 'UVSQ':\n # UVSQ has a single COMM block\n for magicStr, rawBytes in chunk_iter():\n print_chunk_header(magicStr, rawBytes)\n if magicStr == 'COMM':\n count = int(rawBytes[0])\n uvsq = '>Hf'\n # +1 becuase last u16/float might be special\n for i in range(count + 1):\n (idx, val) = struct.unpack(uvsq, rawBytes[1+6*i:7+6*i])\n print(' 0x%04X: %f' % (idx, val))\n elif formTypeStr == 'PDAT':\n for magicStr, rawBytes in chunk_iter():\n if magicStr == 'PPOS':\n floats = struct.unpack('>ffffff', rawBytes)\n print_chunk_header(magicStr, rawBytes, '%g %g %g %g %g %g' % floats)\n else:\n print_chunk_header(magicStr, rawBytes)\n dump_binary(rawBytes)\n else:\n # Generic handler\n for magicStr, rawBytes in chunk_iter():\n length = len(rawBytes)\n currentDumpFilename = f'{currentDumpPrefix}_{chunkIndex}_{magicStr}.bin'\n\n if magicStr == 'PAD ': # PAD always seems to be 4 bytes of 0 - ignore it\n print_chunk_header(magicStr, rawBytes)\n elif magicStr == 'NAME': # ASCII name identifier\n nameStr = rawBytes.decode('utf-8').rstrip('\\0')\n print_chunk_header(magicStr, rawBytes, nameStr)\n elif magicStr == 'INFO': # usually mission objective\n infoStr = rawBytes.decode('utf-8').rstrip('\\0')\n print_chunk_header(magicStr, rawBytes, infoStr)\n elif magicStr == 'JPTX': # some ASCII identifier\n infoStr = rawBytes.decode('utf-8').rstrip('\\0')\n print_chunk_header(magicStr, rawBytes, infoStr)\n elif magicStr in ['PART', 'STRG', 'BITM', 'FRMT', 'IMAG',\n 'ESND', 'TPAD', 'CNTG', 'HOPD', 'LWIN',\n 'LSTP', 'TARG', 'FALC', 'BALS', 'HPAD',\n 'BTGT', 'THER', 'PHTS', 'SIZE', 'DATA',\n 'QUAT', 'XLAT', 'PHDR', 'RHDR', 'PPOS',\n 'RPKT', 'COMM',\n '.CTL', '.TBL',\n 'SCPP', 'SCPH', 'SCPX', 'SCPY', 'SCPR', 'SCPZ', 'SCP#',\n 'LEVL', 'RNGS', 'BNUS', 'WOBJ', 'LPAD', 'TOYS', 'TPTS', 'APTS']:\n print_chunk_header(magicStr, rawBytes)\n dump_binary(rawBytes)\n else:\n # Should not happen.\n assert False\n\n chunkIndex += 1\n else:\n # Should not happen.\n assert False\n\nif __name__ == '__main__':\n ap = argparse.ArgumentParser(description='Pilotwings 64 File System Dumper')\n ap.add_argument('file', help='File path of input')\n ap.add_argument('-s', '--start', dest='startOffset', type=auto_int, default=0x0DF5B0, help='Start offset of file system')\n ap.add_argument('-x', '--hex', dest='hexSize', type=auto_int, default=0x60, help='Size of hexdump for unparsed sections')\n ap.add_argument('-o', '--output-dir', dest='outputDir', help=\"Automatically dump and decompress individual files\")\n args = ap.parse_args()\n pw64_dump_filesys(args.file, args.startOffset, args.hexSize, args.outputDir)\n","sub_path":"pw64_filesys_dump.py","file_name":"pw64_filesys_dump.py","file_ext":"py","file_size_in_byte":7656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"281239224","text":"import sys #For getting command line arguments\nimport subprocess # For running bash commands\nimport requests # For posting requests to telegram\nimport datetime # For measuring performance\n\n#GLOBAL\nTOKEN = \"1372388727:AAFHvMlZcpY4_9FsrXcjtc-aA9YXdCPXdgY\" #Bot Token\nMASTER_ID = \"1375865756\" # Juan Rey's Telegram personal ID\n# MASTER_ID= \"881381200\"\n\ndef get_usr_info()->str:\n url=f\"https://api.telegram.org/bot{TOKEN}/getUpdates\"\n dict_=requests.post(url).json()\n # print(dict_)\n #Get the latest result from user input\n chat_id=dict_['result'][len(dict_['result'])-1]['message']['from']['id']\n print(chat_id)\n return chat_id\n\ndef send_message(msg:str=\"Pizza Time!\", chat_id:str=MASTER_ID):\n #https://api.telegram.org/bot$token/sendMessage?chat_id=$chat&text=Pizza+Time\n send_url=f\"https://api.telegram.org/bot{TOKEN}/sendMessage\"\n data={'chat_id':chat_id,'text':msg}\n dict_=requests.post(send_url,data).json()\n # print(dict_)\n\ndef send_image(img_path:str,chat_id:str=MASTER_ID):\n send_url=f\"https://api.telegram.org/bot{TOKEN}/sendPhoto\"\n data={'chat_id':chat_id}\n files={'photo':open(img_path,'rb')}\n requests.post(send_url,files=files,data=data)\n\ndef run(command:str):\n p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)\n stdout = []\n while True:\n line = p.stdout.readline()\n stdout.append(line)\n print(line)\n if line == '' and p.poll() != None:\n break\n return ''.join(stdout)\n\n\nif __name__ == \"__main__\":\n #chat_id=get_usr_info();\n try:\n if len(sys.argv)>1:\n command=sys.argv[1]\n start=datetime.datetime.now()\n start_string=start.strftime(\"%d\")+'-'+start.strftime(\"%m\")+'-'+start.strftime(\"%Y\")+' '+start.strftime(\"%I\")+':'+start.strftime(\"%M\")+':'+start.strftime(\"%S\")\n print(f\"Starting process {command} at {start_string}\")\n send_message(msg=f\"Starting process {command} at {start_string}\")\n # result_text=run(command)\n # send_message(msg=result_text)\n result=subprocess.run(command, shell=True, capture_output=True, text=True)\n finish=datetime.datetime.now()\n finish_string=finish.strftime(\"%d\")+'-'+finish.strftime(\"%m\")+'-'+finish.strftime(\"%Y\")+' '+finish.strftime(\"%I\")+':'+finish.strftime(\"%M\")+':'+finish.strftime(\"%S\")\n delta=finish-start\n if result.stdout !='':\n text=f\"Pizza Time! Running {command} finished at {finish_string} (that's delta={delta.total_seconds()}s)!\\n\"\n text2=f\"You know I'm something of a scientist myself\\n\"\n print(text+result.stdout+text2)\n send_message(msg=text+result.stdout+text2)\n send_image(sys.path[0]+\"/images/toby_scientist.png\")\n if result.stderr != '':\n text=f\"Uh oh, error generated running {command}, exited at {finish_string} (that's delta={delta.total_seconds()}s)\\n\"\n text2=f\"You'll get your rent when you fix this damn code\\n\"\n print(text+result.stderr)\n send_message(msg=text+result.stderr+text2)\n send_image(sys.path[0]+\"/images/toby_cry.jpg\")\n except Exception as e:\n send_message(msg=\"Uh oh, that's a bad pizza. Error running my python script.\")\n send_image(sys.path[0]+\"/images/toby_scream.jpg\")\n pass\n","sub_path":"PizzaTime.py","file_name":"PizzaTime.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"78267034","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files.\n\"\"\"\nimport csv\n\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\n\"\"\"\nTASK 3:\n(080) is the area code for fixed line telephones in Bangalore.\nFixed line numbers include parentheses, so Bangalore numbers\nhave the form (080)xxxxxxx.)\n\nPart A: Find all of the area codes and mobile prefixes called by people\nin Bangalore.\n - Fixed lines start with an area code enclosed in brackets. The area\n codes vary in length but always begin with 0.\n - Mobile numbers have no parentheses, but have a space in the middle\n of the number to help readability. The prefix of a mobile number\n is its first four digits, and they always start with 7, 8 or 9.\n - Telemarketers' numbers have no parentheses or space, but they start\n with the area code 140.\n\nPrint the answer as part of a message:\n\"The numbers called by people in Bangalore have codes:\"\n <list of codes>\nThe list of codes should be print out one per line in lexicographic order with no duplicates.\n\nPart B: What percentage of calls from fixed lines in Bangalore are made\nto fixed lines also in Bangalore? In other words, of all the calls made\nfrom a number starting with \"(080)\", what percentage of these calls\nwere made to a number also starting with \"(080)\"?\n\nPrint the answer as a part of a message::\n\"<percentage> percent of calls from fixed lines in Bangalore are calls\nto other fixed lines in Bangalore.\"\nThe percentage should have 2 decimal digits\n\"\"\"\n\nmyList = []\nindex = 2\nrec_num = '(0'\nnum_blore = 0\nnum_other = 0\n\ndef calc_percentage(first_five_letters, first_two_letters, num_blore, num_other):\n if first_five_letters == '(080)':\n num_blore += 1\n elif first_two_letters == '(0':\n num_other += 1\n return num_blore, num_other\n\nfor element in calls:\n if element[0][0:5] == '(080)':\n while element[1][0:2] == '(0' and element[1][index] != ')':\n rec_num += element[1][index]\n index += 1\n if element[1][index] == ')':\n rec_num += element[1][index]\n if rec_num not in myList:\n myList.append(rec_num)\n if (element[1][0] == '7' or element[1][0] == '8' or element[1][0] == '9') and (element[1][0:5] not in myList):\n myList.append(element[1][0:5])\n\n num_blore, num_other = calc_percentage(element[1][0:5], element[1][0:2], num_blore, num_other)\n\n index = 2\n rec_num = '(0'\n\nprint(\"The numbers called by people in Bangalore have codes:\\n{0}\".format(sorted(myList, key=str)))\n\nprint(\"\\n{:.2f} percent of calls from fixed lines in Bangalore are calls to other fixed lines \"\n \"in Bangalore.\".format(float(num_blore)/float(num_blore+num_other)*100))","sub_path":"Task3.py","file_name":"Task3.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"595250649","text":"from PIL import Image, ImageFont, ImageDraw\n\ndesc_font_main = ImageFont.truetype('./assets/fonts/Play-Regular.ttf', 48)\n\ntemplate = {\n 'create':\n 'Игрок\\n'\n '%s\\n'\n 'Создал гильдию\\n'\n '%s',\n 'delete':\n 'Игрок\\n'\n '%s\\n'\n 'Удалил гильдию\\n'\n '%s',\n 'transfer':\n '%s\\n'\n 'Теперь новый Глава\\n'\n 'Гильдии\\n'\n '%s',\n 'rename':\n 'Гильдия\\n'\n '%s\\n'\n 'Теперь известна как\\n'\n '%s',\n 'embargo':\n '%s\\n'\n 'Объявила эмбарго\\n'\n 'Гильдие\\n'\n '%s',\n 'unembargo':\n '%s\\n'\n 'Отменила эмбарго\\n'\n 'Гильдие\\n'\n '%s',\n}\n\n\ndef construct_guild_grand(atype: str, data1: str, data2: str):\n assetfile = Image.open('./assets/announcers/guild_grand.png')\n img = ImageDraw.Draw(assetfile)\n # 593 x 435\n text = template[atype] % (data1, data2)\n img.multiline_text(((593 / 2), (435 / 2 + 65)), text, font=desc_font_main, anchor=\"mm\", align=\"center\")\n fPath = './tmp/' + atype + '_' + data1 + '_' + data2 + '.png'\n assetfile.save(fPath)\n return fPath\n","sub_path":"libs/img/grandConstruct.py","file_name":"grandConstruct.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"215218889","text":"from PyPDF2 import PdfFileReader, PdfFileWriter\nfrom PyPDF2.pdf import ContentStream\nfrom PyPDF2.generic import TextStringObject, NameObject\nfrom PyPDF2.utils import b_\n\n# watermark to remove\nwm_text = \"DOI\"\n# replacing the watermark with nothing\nreplace_with = \"\"\n\n# Load PDF into pyPDF\nsource = PdfFileReader(\"sample.pdf\")\noutput = PdfFileWriter()\n\n# Iterating through each page\nfor page in range(source.getNumPages()):\n # Current Page\n page = source.getPage(page)\n content_object = page[\"/Contents\"].getObject()\n content = ContentStream(content_object, source)\n\n # Iterating over all pdf elements\n for operands, operator in content.operations:\n if operator == b_(\"TJ\"):\n text = operands[0][0]\n if isinstance(text, TextStringObject) and text.startswith(wm_text):\n operands[0] = TextStringObject(replace_with)\n\n page.__setitem__(NameObject(\"/Contents\"), content)\n\n output.addPage(page)\n\noutputStream = open(\"output.pdf\", \"wb\")\noutput.write(outputStream)","sub_path":"unwatermark.py","file_name":"unwatermark.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"595834027","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 26 18:42:40 2017\n\n@author: JIN\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ntraining_set = pd.read_csv('Google_Stock_Price_Train.csv')\ntraining_set = training_set.iloc[:, 1:2].values\n\n#Feature Scaling\nfrom sklearn.preprocessing import MinMaxScaler\nsc = MinMaxScaler()\ntraining_set = sc.fit_transform(training_set)\n\n#Getting th inputs and the outputs\nX_train = training_set[0:1257]\nY_train = training_set[1:1258]\n\n# Reshaping\n# (the # of obserbation, timestemp, # of features)\nX_train = np.reshape(X_train, (1257, 1, 1)) \n\n# Part 2 - Building the RNN\n\n# Importing the Keras libraries and packages\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\n\n# Initialising the RNN\nregressor = Sequential()\n\n# Adding the input layer and the LSTM layer command+i to see info\nregressor.add(LSTM(units = 4, activation = 'sigmoid', input_shape = (None, 1)))\n\n# Adding the output layer\nregressor.add(Dense(units = 1))\n\n# Compiling the RNN\nregressor.compile(optimizer = 'adam', loss = 'mean_squared_error') \n\n# Fitting the RNN to the traing set \n\nregressor.fit(X_train, Y_train, batch_size = 32, epochs = 200 )\n\n# Part 3 - Making the predictions and visualising the results \n\n# Getting the real stock price of 2017\n\ntest_set = pd.read_csv('GOOG.csv')\nreal_stock_price = test_set.iloc[:, 1:2].values\n\n# Getting the predictd stock price of 2017\ninputs = real_stock_price\ninputs = sc.transform(inputs)\ninputs = np.reshape(inputs, (252, 1, 1))\npredicted_stock_price = regressor.predict(inputs)\npredicted_stock_price = sc.inverse_transform(predicted_stock_price)\n\n# Visualising the results\n\nplt.plot(real_stock_price, color = 'red', label = 'Real Google Stock Price')\nplt.plot(predicted_stock_price, color = 'blue', label = 'Predicted Google Stock Price')\nplt.title('Google Stock Price Prediction')\nplt.xlabel('Time')\nplt.ylabel('Price')\nplt.legend()\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"rnn2.py","file_name":"rnn2.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"576401943","text":"#!/usr/bin/env python3\n\n\"\"\"Khronos stream extension for EGL.\n\nThis extension defines new EGL resource types for referencing\ndisplay control hardware associated with an EGL device.\n\nhttp://www.khronos.org/registry/egl/extensions/KHR/EGL_EXT_output_base.txt\n\n\"\"\"\n# Copyright (c) 2012-14 Tim Pederick.\n#\n# This file is part of Pegl.\n#\n# Pegl is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Pegl is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n# License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Pegl. If not, see <http://www.gnu.org/licenses/>.\n\n# Standard library imports.\nfrom ctypes import POINTER, c_char_p\n\n# Local imports.\nfrom . import load_ext\nfrom ..attribs import Attribs, Details\nfrom .. import EGLError, error_codes\nfrom .khr_stream import NO_STREAM\nfrom ..types import *\n\n# EGL_EXT_output_drm\nEGL_DRM_CRTC_EXT = 0x3234\nEGL_DRM_PLANE_EXT = 0x3235\nEGL_DRM_CONNECTOR_EXT = 0x3236\n\n\nclass LayerAttribs(Attribs):\n '''The set of EGL attributes relevant to layer objects.'''\n # For setting and querying swap intervals.\n SWAP_INTERVAL_EXT = 0x322F\n # Min and Max values for swapping intervals\n MIN_SWAP_INTERVAL = 0x303B\n MAX_SWAP_INTERVAL = 0x303C\n details = {SWAP_INTERVAL_EXT: Details('Functions which set'\n 'or query the swap '\n 'interval use this attribute',\n c_int, 0),\n MIN_SWAP_INTERVAL: Details('The maximum value of swap'\n 'intervals that will elapse'\n 'before a buffer swap completes',\n c_int, 0),\n MAX_SWAP_INTERVAL: Details('The minimum value of swap'\n 'intervals that will elapse'\n 'before a buffer swap completes',\n c_int, 0)\n }\n\n\n# New errors.\nclass BadOutputLayerEXT(EGLError):\n \"\"\"Given EGLOutputLayerEXT argument is invalid\"\"\"\n default_msg = 'Given EGLOutputLayerEXT argument is invalid'\n\n\nclass BadOutputPortEXT(EGLError):\n \"\"\"Given EGLOutputPortEXT argument is invalid\"\"\"\n default_msg = 'Given EGLOutputPortEXT argument is invalid'\n\n\nerror_codes[0x322D] = BadOutputLayerEXT\nerror_codes[0x322E] = BadOutputPortEXT\n\n# Get handles of extension functions.\neglGetOutputLayersEXT = load_ext(b'eglGetOutputLayersEXT', EGLBoolean,\n (EGLDisplay, EGLAttrib,\n POINTER(EGLOutputLayerEXT),\n EGLint, POINTER(EGLint)),\n fail_on=BadOutputLayerEXT)\n\neglGetOutputPortsEXT = load_ext(b'eglGetOutputPortsEXT', EGLBoolean,\n (EGLDisplay, EGLAttrib,\n POINTER(EGLOutputPortEXT),\n EGLint, POINTER(EGLint)),\n fail_on=BadOutputPortEXT)\n\neglOutputLayerAttribEXT = load_ext(b'eglOutputLayerAttribEXT', EGLBoolean,\n (EGLDisplay, EGLOutputLayerEXT,\n EGLint, EGLAttrib),\n fail_on=BadOutputLayerEXT)\n\neglQueryOutputLayerAttribEXT = load_ext(b'eglQueryOutputLayerAttribEXT', EGLBoolean,\n (EGLDisplay, EGLOutputLayerEXT, EGLint,\n POINTER(EGLAttrib)),\n fail_on=BadOutputLayerEXT)\n\neglQueryOutputLayerStringEXT = load_ext(b'eglQueryOutputLayerStringEXT', c_char_p,\n (EGLDisplay, EGLOutputLayerEXT, EGLint),\n fail_on=BadOutputLayerEXT)\n\neglOutputPortAttribEXT = load_ext(b'eglOutputPortAttribEXT', EGLBoolean,\n (EGLDisplay, EGLOutputPortEXT,\n EGLint, EGLAttrib),\n fail_on=BadOutputPortEXT)\n\neglQueryOutputPortAttribEXT = load_ext(b'eglQueryOutputPortAttribEXT', EGLBoolean,\n (EGLDisplay, EGLOutputPortEXT, EGLint,\n POINTER(EGLAttrib)),\n fail_on=BadOutputLayerEXT)\n\neglQueryOutputPortStringEXT = load_ext(b'eglQueryOutputPortStringEXT', c_char_p,\n (EGLDisplay, EGLOutputPortEXT, EGLint),\n fail_on=BadOutputPortEXT)\n# EGL_EXT_stream_consumer_egloutput\neglStreamConsumerOutputEXT = load_ext(b'eglStreamConsumerOutputEXT', c_ibool,\n (EGLDisplay, EGLStreamKHR, EGLOutputLayerEXT),\n fail_on=NO_STREAM)\n","sub_path":"pegl/ext/ext_output_base.py","file_name":"ext_output_base.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"245837984","text":"from collections import deque\r\n\r\nclass Graph(object):\r\n\tdef __init__(self):\r\n\t\tself.nodes = [] # stores all reference to all nodes\r\n\r\nclass Node(object):\r\n\tdef __init__(self, data):\r\n\t\tself.data = data\r\n\t\tself.neighbors = [] # stores Neighboring nodes\r\n\r\n\r\ndef bfs(node):\r\n\t# start queue and visited set, initiate node in both\r\n\t# while queue is not empty we can process bfs\r\n\t\t# pop a node off queue\r\n\t\t# process popped node\r\n\t\t# add all unvisited neighbors onto queue and visited\r\n\tpass\r\n\r\ndef bfs_print(node):\r\n\tif node == None: return\r\n\tbfsvisited = set([node])\r\n\tqueue = deque([node]) # start queue, initiate root in it\r\n\twhile queue: # while queue is not empty\r\n\t\tcurrent = queue.popleft() # pop queue\r\n\t\tbfsvisited.add(current) # mark visited\r\n\t\tprint(current.data) # process\r\n\t\tfor neighbor in current.neighbors: # add popped node's neighbors into queue\r\n\t\t\tif neighbor not in bfsvisited:\r\n\t\t\t\tbfsvisited.add(neighbor)\r\n\t\t\t\tqueue.append(neighbor)\r\n\treturn\r\n\r\nbfs_print(n1)\r\n","sub_path":"bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"240946634","text":"from PIL import Image\nimport pytesseract\nimport logging\nimport cv2\nimport os\nimport pathlib\n\nclass Picture_to_text():\n\n def Get_text_from_picture(self, image):\n logging.basicConfig(filename=\"Text_Graber.log\", level=logging.INFO)\n logging.debug(\"initializing...\")\n\n try:\n logging.info(\"Opening image: {}\".format(image))\n image = cv2.imread(image)\n\n logging.info(\"Cleare image from junk\")\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray = cv2.medianBlur(gray, 3)\n\n filename = \"{}.png\".format(os.getpid())\n print(filename)\n # print(str(pathlib.Path(__file__).parent.absolute()))\n\n cv2.imwrite(filename, gray)\n \n custom_config = r'-l rus --psm 6'\n logging.info(\"Try to read russian text from picture\")\n text_from_file = pytesseract.image_to_string(Image.open(filename), config=custom_config)\n\n except Exception as e:\n print(e)\n logging.info(\"Error! Check input file, it should be here: {}\".format(image))\n text_from_file = \"Кажеться ты обосрался\"\n\n text_file_name = \"Output.txt\"\n logging.info(\"Create output file with text\")\n text_file = open(text_file_name, \"w\")\n text_file.write(text_from_file)\n text_file.close()\n\n return text_file_name","sub_path":"NeuroPlusPoop/Picture/OCR.py","file_name":"OCR.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"167299741","text":"#!/usr/bin/python\n'''\nDDFacet, a facet-based radio imaging package\nCopyright (C) 2013-2017 Cyril Tasse, l'Observatoire de Paris,\nSKA South Africa, Rhodes University\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n'''\n\nimport subprocess\nimport os\nimport warnings\nfrom setuptools import setup\nfrom setuptools.command.install import install\nfrom setuptools.command.sdist import sdist\nfrom distutils.command.build import build\nfrom os.path import join as pjoin\nimport sys\n\npkg='DDFacet'\nskymodel_pkg='SkyModel'\n__version__ = \"0.5.3.0\"\nbuild_root=os.path.dirname(__file__)\n\ntry:\n import six\nexcept ImportError as e:\n raise ImportError(\"Six not installed. Please install Python 2.x compatibility package six before running DDFacet install. \"\n \"You should not see this message unless you are not running pip install (19.x) -- run pip install!\")\ntry:\n import pybind11\nexcept ImportError as e:\n raise ImportError(\"Pybind11 not installed. Please install C++ binding package pybind11 before running DDFacet install. \"\n \"You should not see this message unless you are not running pip install (19.x) -- run pip install!\")\n\ndef backend(compile_options):\n if compile_options is not None:\n print(\"Compiling extension libraries with user defined options: '%s'\"%compile_options)\n else:\n compile_options = \"\"\n if six.PY3:\n compile_options += \" -DENABLE_PYTHON_2=OFF \"\n compile_options += \" -DENABLE_PYTHON_3=ON \"\n elif six.PY2:\n compile_options += \" -DENABLE_PYTHON_2=ON \"\n compile_options += \" -DENABLE_PYTHON_3=OFF \"\n\n path = pjoin(build_root, pkg, 'cbuild')\n try:\n subprocess.check_call([\"mkdir\", path])\n except:\n warnings.warn(\"%s already exists in your source folder. We will not create a fresh build folder, but you \"\n \"may want to remove this folder if the configuration has changed significantly since the \"\n \"last time you run setup.py\" % path)\n subprocess.check_call([\"cd %s && cmake %s .. && make\" %\n (path, compile_options if compile_options is not None else \"\"), \"\"], shell=True)\n\nclass custom_install(install):\n install.user_options = install.user_options + [\n ('compopts=', None, 'Any additional compile options passed to CMake')\n ]\n def initialize_options(self):\n install.initialize_options(self)\n self.compopts = None\n\n def run(self):\n backend(self.compopts)\n install.run(self)\n\nclass custom_build(build):\n build.user_options = build.user_options + [\n ('compopts=', None, 'Any additional compile options passed to CMake')\n ]\n def initialize_options(self):\n build.initialize_options(self)\n self.compopts = None\n\n def run(self):\n backend(self.compopts)\n build.run(self)\n\nclass custom_sdist(sdist):\n def run(self):\n bpath = pjoin(build_root, pkg, 'cbuild')\n if os.path.isdir(bpath):\n subprocess.check_call([\"rm\", \"-rf\", bpath])\n sdist.run(self)\n\ndef define_scripts():\n #these must be relative to setup.py according to setuputils\n DDF_scripts = [os.path.join(pkg, script_name) for script_name in ['DDF.py', 'CleanSHM.py', 'MemMonitor.py', 'Restore.py', 'SelfCal.py']]\n SkyModel_scripts = [os.path.join(skymodel_pkg, script_name) for script_name in ['ClusterCat.py', 'dsm.py', 'dsreg.py', 'ExtractPSources.py', \n 'Gaussify.py', 'MakeCatalog.py', 'MakeMask.py', 'MakeModel.py', 'MaskDicoModel.py', 'MyCasapy2bbs.py', 'MaskDicoModel.py']]\n return DDF_scripts + SkyModel_scripts\n\ndef readme():\n \"\"\" Return README.rst contents \"\"\"\n with open('README.rst') as f:\n return f.read()\n\ndef requirements():\n\n requirements = [(\"nose >= 1.3.7\", \"nose >= 1.3.7\"),\n (\"Cython >= 0.25.2\", \"Cython >= 0.25.2\"),\n (\"numpy >= 1.15.1\", \"numpy >= 1.15.1\"), #Ubuntu 18.04\n (\"sharedarray >= 3.2.0\", \"sharedarray >= 3.2.0\"),\n (\"Polygon3 >= 3.0.8\", \"Polygon2 >= 2.0.8\"),\n (\"pyFFTW >= 0.10.4\", \"pyFFTW >= 0.10.4\"),\n (\"astropy >= 3.0\", \"astropy <= 2.0.11\"),\n (\"deap >= 1.0.1\", \"deap >= 1.0.1\"),\n (\"ptyprocess>=0.5\", \"ptyprocess<=0.5\"), #workaround for ipdb on py2\n (\"ipdb >= 0.10.3\", \"ipdb <= 0.10.3\"),\n (\"python-casacore >= 3.0.0\", \"python-casacore >= 3.0.0\"),\n (\"pyephem >= 3.7.6.0\", \"pyephem >= 3.7.6.0\"),\n (\"numexpr >= 2.6.2\", \"numexpr >= 2.6.2\"),\n (\"matplotlib >= 2.0.0\", \"matplotlib >= 2.0.0\"),\n (\"scipy >= 1.3.3\", \"scipy >= 0.16.0\"),\n (\"astLib >= 0.8.0\", \"astLib >= 0.8.0\"),\n (\"psutil >= 5.2.2\", \"psutil >= 5.2.2\"),\n (\"py-cpuinfo >= 3.2.0\", \"py-cpuinfo >= 3.2.0\"),\n (\"tables >= 3.6.0\", \"tables < 3.6.0\"),\n (\"prettytable >= 0.7.2\", \"prettytable >= 0.7.2\"),\n (\"pybind11 >= 2.2.2\", \"pybind11 >= 2.2.2\"),\n (\"pyfits >= 3.5\", \"pyfits >= 3.5\"), #kittens dependency, do not remove\n (\"configparser >= 3.7.1\", \"configparser >= 3.7.1\"),\n (\"pandas >=0.23.3\", \"pandas >=0.23.3\"),\n (\"ruamel.yaml >= 0.15.92\", \"ruamel.yaml >= 0.15.92\"),\n (\"pylru >= 1.1.0\", \"pylru >= 1.1.0\"),\n (\"six >= 1.12.0\", \"six >= 1.12.0\"),\n (\"pybind11 >= 2.2.2\", \"pybind11 >= 2.2.2\"),\n (\"codex-africanus[dask] <= 0.1.8\", \"codex-africanus[dask] <= 0.1.8\"),\n (\"bdsf > 1.8.15\", \"bdsf<=1.8.15\") # SkyModel / kms dependency\n ] \n\n py3_requirements, py2_requirements = zip(*requirements)\n install_requirements = py2_requirements if six.PY2 else py3_requirements\n\n return install_requirements\n\nsetup(name=pkg,\n version=__version__,\n description='Facet-based radio astronomy continuum imager',\n long_description = readme(),\n url='http://github.com/saopicc/DDFacet',\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Environment :: Console\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: GNU General Public License v2 (GPLv2)\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python\",\n \"Topic :: Scientific/Engineering :: Astronomy\"],\n author='Cyril Tasse',\n author_email='cyril.tasse@obspm.fr',\n license='GNU GPL v2',\n cmdclass={'install': custom_install,\n 'sdist': custom_sdist,\n 'build': custom_build\n },\n #python_requires='<3.0',\n packages=[pkg, skymodel_pkg],\n install_requires=requirements(),\n include_package_data=True,\n zip_safe=False,\n long_description_content_type='text/markdown',\n scripts=define_scripts(),\n extras_require={\n 'dft-support': ['montblanc >= 0.6.1'],\n 'moresane-support': ['pymoresane >= 0.3.0'],\n 'testing-requirements': ['nose >= 1.3.7'],\n 'fits-beam-support': ['meqtrees-cattery'],\n }\n)\n","sub_path":"pypi_install_script/DDFacet-0.5.3.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":7883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"235874913","text":"from django.shortcuts import render, HttpResponse\nimport psycopg2\n\n# Create your views here.\ndef init(request):\n try:\n conn = psycopg2.connect(\n database='formationdjango',\n host='localhost',\n user='djangouser',\n password='secret'\n ) \n\n curr = conn.cursor()\n\n curr.execute(\"\"\" \n CREATE TABLE IF NOT EXISTS ex02_movies (\n title varchar(64) NOT NULL UNIQUE,\n episode_nb integer PRIMARY KEY,\n opening_crawl text,\n director varchar(32) NOT NULL,\n producer varchar(128) NOT NULL,\n release_date date NOT NULL\n )\n \"\"\")\n conn.commit()\n conn.close()\n return HttpResponse('OK')\n except psycopg2.Error as e:\n return HttpResponse(e)\n return HttpResponse('you should not be here!')\n\ndef populate_insert(curr, query, title):\n try:\n curr.execute(query)\n curr.commit()\n return (\"OK<br>\")\n except psycopg2.Error as e:\n print(\"{} : {}\\n\".format(title, e))\n return(\"\")\n\ndef populate(request):\n try:\n conn = psycopg2.connect(\n database='formationdjango',\n host='localhost',\n user='djangouser',\n password='secret'\n ) \n\n curr = conn.cursor()\n\n out = \"\"\n movie = \"The Phantom Menace\"\n curr.execute(\"\"\" \n INSERT INTO ex02_movies\n (episode_nb, title, director, producer, release_date)\n VALUES ('1',\n 'The Phantom Menace',\n 'Georges Lucas',\n 'Rick McCallum',\n '1999-05-19')\n \"\"\")\n out += \"OK<br>\"\n\n movie = \"Attack of the Clones\"\n curr.execute(\"\"\" \n INSERT INTO ex02_movies\n (episode_nb, title, director, producer, release_date)\n VALUES ('2',\n 'Attack of the Clones',\n 'Georges Lucas',\n 'Rick McCallum',\n '2002-05-16')\n \"\"\")\n out += \"OK<br>\"\n\n movie = \"Revenge of the Sith\"\n curr.execute(\"\"\" \n INSERT INTO ex02_movies\n (episode_nb, title, director, producer, release_date)\n VALUES ('3',\n 'Revenge of the Sith',\n 'Georges Lucas',\n 'Rick McCallum',\n '2005-05-19')\n \"\"\")\n out += \"OK<br>\"\n\n movie = \"A New Hope\"\n curr.execute(\"\"\" \n INSERT INTO ex02_movies\n (episode_nb, title, director, producer, release_date)\n VALUES ('4',\n 'A New Hope',\n 'Georges Lucas',\n 'Gary Kurtz, Rick McCallum',\n '1977-05-25')\n \"\"\")\n out += \"OK<br>\"\n\n movie = \"The Empire Strikes Back\"\n curr.execute(\"\"\" \n INSERT INTO ex02_movies\n (episode_nb, title, director, producer, release_date)\n VALUES ('5',\n 'The Empire Strikes Back',\n 'Irvin Kershner',\n 'Gary Kutz, Rick McCallum',\n '1980-05-17')\n \"\"\")\n out += \"OK<br>\"\n\n movie = \"Return of the Jedi\"\n curr.execute(\"\"\" \n INSERT INTO ex02_movies\n (episode_nb, title, director, producer, release_date)\n VALUES ('6',\n 'Return of the Jedi',\n 'Richard Marquand',\n 'Howard G. Kazanjian, George Lucas, Rick McCallum',\n '1983-05-25')\n \"\"\")\n out += \"OK<br>\"\n\n movie = \"The Force Awakens\"\n curr.execute(\"\"\" \n INSERT INTO ex02_movies\n (episode_nb, title, director, producer, release_date)\n VALUES ('7',\n 'The Force Awakens',\n 'J. J. Abrams',\n 'Kathleen Kennedy, J. J. Abrams, Bryan Burk',\n '2015-12-11')\n \"\"\")\n out += \"OK<br>\"\n\n conn.commit()\n conn.close()\n return HttpResponse(out)\n except psycopg2.Error as e:\n return HttpResponse(\"{} ::: {}\".format(movie, e))\n return HttpResponse('you should not be here!')\n\ndef display(request):\n try:\n conn = psycopg2.connect(\n database='formationdjango',\n host='localhost',\n user='djangouser',\n password='secret'\n ) \n\n curr = conn.cursor()\n\n curr.execute(\"SELECT * FROM ex02_movies\")\n response = curr.fetchall()\n\t\t\n if not response:\n return HttpResponse('No data available')\n res = \"<table style='border: 1px solid black; border-collapse: collapse;'>\"\n for r in response:\n res += '<tr style=\"border: 1px solid black;\">'\n for e in r:\n res += \"<td style='border: 1px solid black;'>\" + str(e) + \"</td>\"\n res += \"</table>\"\n conn.commit()\n conn.close()\n return HttpResponse(res)\n except psycopg2.Error as e:\n return HttpResponse(e)\n return HttpResponse('you should not be here!')\n\n\ndef delete(request):\n try:\n conn = psycopg2.connect(\n database = 'formationdjango',\n host = 'localhost',\n user = 'djangouser',\n password = 'secret'\n )\n curr = conn.cursor()\n curr.execute(\"DELETE FROM ex02_movies\")\n conn.commit()\n conn.close()\n return HttpResponse('OK')\n except psycopg2.Error as e:\n return HttpResponse(e)\n return HttpResponse('you should not be here!')","sub_path":"d05/ex02/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"178711944","text":"\"\"\"\nCLI for a user-defined software stack script\n\"\"\"\n\nimport sys\nimport argparse\nimport os\nimport tempfile\n\nfrom ..hdist_logging import Logger, DEBUG, INFO\n\nfrom ..core import InifileConfiguration, BuildStore, SourceCache, DEFAULT_CONFIG_FILENAME\nfrom .recipes import build_recipes\n\n__all__ = ['stack_script_cli']\n\ndef stack_script_cli(root_recipe):\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('--config',\n default=os.path.expanduser(DEFAULT_CONFIG_FILENAME),\n help='location of Hashdist config-file (default: %s))' % DEFAULT_CONFIG_FILENAME)\n parser.add_argument('-k', '--keep-always', action='store_true',\n help='keep build directory even if there is no error')\n parser.add_argument('-K', '--keep-never', action='store_true',\n help='never keep build directory, even if there is an error')\n parser.add_argument('-v', '--verbose', action='store_true',\n help='verbose mode')\n parser.add_argument('-s', '--status', action='store_true',\n help='do not run build, only show status')\n parser.add_argument('target', nargs='?',\n help='name of symlink that should be created to results')\n args = parser.parse_args()\n\n if args.keep_always and args.keep_never:\n parser.error('-k and -K are incompatible')\n elif args.keep_always:\n args.keep = 'always'\n elif args.keep_never:\n args.keep = 'never'\n else:\n args.keep = 'error'\n\n if args.target and os.path.exists(args.target) and not os.path.islink(args.target):\n parser.error('\"%s\" exists and is not a symlink')\n logger = Logger(DEBUG if args.verbose else INFO)\n \n config = InifileConfiguration.create(args.config)\n build_store = BuildStore.create_from_config(config, logger)\n source_cache = SourceCache.create_from_config(config, logger)\n \n sys.stderr.write('Status:\\n\\n%s\\n\\n' % root_recipe.format_tree(build_store))\n if build_store.is_present(root_recipe.get_build_spec()):\n sys.stderr.write('Everything up to date!\\n')\n else:\n sys.stderr.write('Build needed\\n')\n\n if not args.status:\n build_recipes(build_store, source_cache, [root_recipe], keep_build=args.keep)\n\n artifact_dir = build_store.resolve(root_recipe.get_artifact_id())\n if not artifact_dir:\n if args.target:\n logger.warning('Not updating symlink \"%s\" since build is not up to date' % args.target)\n return\n\n if args.target:\n # create-&-rename in order to force-create symlink\n templink = args.target + '-temp-%d' % os.getpid()\n os.symlink(artifact_dir, templink)\n try:\n os.rename(templink, args.target)\n except:\n os.unlink(templink)\n raise\n logger.info('Created \"%s\" -> \"%s\"' % (args.target, artifact_dir))\n else:\n logger.info('Results in \"%s\"' % artifact_dir)\n \n\n \n","sub_path":"hashdist/recipes/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"79755733","text":"# pylint: disable=C0103\r\n\"\"\"\r\nThis module includes the solver functions as well as the models for PWM\r\ncarrier comparison and computational delay.\r\n\r\n\"\"\"\r\nimport numpy as np\r\nfrom scipy.integrate import solve_ivp\r\nfrom helpers import abc2complex\r\n\r\n\r\n# %%\r\ndef solve(mdl, d_abc, t_span, max_step=np.inf):\r\n \"\"\"\r\n Solve the continuous-time model over t_span.\r\n\r\n Parameters\r\n ----------\r\n mdl : object\r\n Model to be simulated.\r\n d_abc : array_like of floats, shape (3,)\r\n Duty ratio references in the interval [0, 1].\r\n t_span : 2-tuple of floats\r\n Interval of integration (t0, tf). The solver starts with t=t0 and\r\n integrates until it reaches t=tf.\r\n max_step : float, optional\r\n Max step size of the solver. The default is inf.\r\n\r\n \"\"\"\r\n # Common code\r\n def run_solver(t_span):\r\n # Skip possible zero time spans\r\n if t_span[-1] > t_span[0]:\r\n # Get initial values\r\n x0 = mdl.get_initial_values()\r\n # Integrate\r\n sol = solve_ivp(mdl.f, t_span, x0, max_step=max_step)\r\n # Set the new initial values (last points of the solution)\r\n t0_new, x0_new = t_span[-1], sol.y[:, -1]\r\n mdl.set_initial_values(t0_new, x0_new)\r\n # Data logger\r\n if mdl.datalog:\r\n mdl.datalog.save(mdl, sol)\r\n\r\n if not mdl.pwm:\r\n # Update the duty ratio space vector (constant over the time span)\r\n mdl.q = abc2complex(d_abc)\r\n # Run the solver\r\n run_solver(t_span)\r\n else:\r\n # Sampling period\r\n T_s = t_span[-1] - t_span[0]\r\n # Compute the normalized switching spans and the corresponding states\r\n tn_sw, q_sw = mdl.pwm(d_abc)\r\n # Convert the normalized switching spans to seconds\r\n t_sw = t_span[0] + T_s*tn_sw\r\n # Loop over the switching time spans\r\n for i, t_sw_span in enumerate(t_sw):\r\n # Update the switching state vector (constant over the time span)\r\n mdl.q = q_sw[i]\r\n # Run the solver\r\n run_solver(t_sw_span)\r\n\r\n\r\n# %%\r\nclass PWM:\r\n \"\"\"\r\n This class implements carrier comparison of three-phase PWM. The switching\r\n instants and the switching states are explicitly and exactly computed from\r\n the duty ratios. The switching instants can be used in the ODE solver.\r\n\r\n \"\"\"\r\n\r\n # pylint: disable=R0903\r\n def __init__(self, N=2**12):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n N : int, optional\r\n Amount of PWM quantization levels. The default is 2**12.\r\n\r\n \"\"\"\r\n self.N = N\r\n self.falling_edge = False\r\n\r\n def __call__(self, d_abc):\r\n \"\"\"\r\n Compute the normalized switching instants and the switching states.\r\n\r\n Parameters\r\n ----------\r\n d_abc : array_like of floats, shape (3,)\r\n Duty ratios in the range [0, 1].\r\n\r\n Returns\r\n -------\r\n tn_sw : ndarray, shape (4,2)\r\n Normalized switching instants,\r\n tn_sw = [0, t1, t2, t3, 1].\r\n q : complex ndarray, shape (4,)\r\n Switching state space vectors corresponding to the switching\r\n instants. For example, the switching state q[1] is applied\r\n at the interval tn_sw[1].\r\n\r\n Notes\r\n -----\r\n Switching instants t_sw split the sampling period T_s into\r\n four spans. No switching (e.g. da = 0 or da = 1) or simultaneous\r\n switching instants (e.g da == db) lead to zero spans, i.e.,\r\n t_sw[i] == t_sw[i].\r\n\r\n \"\"\"\r\n # Quantize the duty ratios to N levels\r\n d_abc = np.round(self.N*np.asarray(d_abc))/self.N\r\n # Initialize the normalized switching instant array\r\n tn_sw = np.zeros((4, 2))\r\n tn_sw[3, 1] = 1\r\n # Could be understood as a carrier comparison\r\n if self.falling_edge:\r\n # Normalized switching instants (zero crossing instants)\r\n tn_sw[1:4, 0] = np.sort(d_abc)\r\n tn_sw[0:3, 1] = tn_sw[1:4, 0]\r\n # Compute the switching state array\r\n q_abc = (tn_sw[:, 0] < d_abc[:, np.newaxis]).astype(int)\r\n else:\r\n # Rising edge\r\n tn_sw[1:4, 0] = np.sort(1 - d_abc)\r\n tn_sw[0:3, 1] = tn_sw[1:4, 0]\r\n q_abc = (tn_sw[:, 0] >= 1 - d_abc[:, np.newaxis]).astype(int)\r\n # Change the carrier direction for the next call\r\n self.falling_edge = not self.falling_edge\r\n # Switching state space vector\r\n q = abc2complex(q_abc)\r\n return tn_sw, q\r\n\r\n def __str__(self):\r\n desc = ('PWM model:\\n'\r\n ' {} quantization levels')\r\n return desc.format(self.N)\r\n\r\n\r\n# %%\r\nclass Delay:\r\n \"\"\"\r\n This class implements a delay as a ring buffer.\r\n\r\n \"\"\"\r\n\r\n # pylint: disable=R0903\r\n def __init__(self, length=1, elem=3):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n length : int, optional\r\n Length of the buffer in samples. The default is 1.\r\n\r\n \"\"\"\r\n # Creates a zero list\r\n self.data = length*[elem*[0]]\r\n self._length = length # Needed for __str__ only\r\n\r\n def __call__(self, u):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n u : array_like, shape (elem,)\r\n Input array.\r\n\r\n Returns\r\n -------\r\n array_like, shape (elem,)\r\n Output array.\r\n\r\n \"\"\"\r\n # Add the latest value to the end of the list\r\n self.data.append(u)\r\n # Pop the first element and return it\r\n return self.data.pop(0)\r\n\r\n def __str__(self):\r\n desc = ('Computational delay:\\n {} sampling periods')\r\n return desc.format(self._length)\r\n","sub_path":"model/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"52926638","text":"\n\n\"\"\"getInput() is a function the gets the users input (language choice) and returns a greeting in the selected language\"\"\"\n\ndef getInput():\n userInput = input(\"Hello! Please choose a greeting from one of the following languages: Japenese, Bahamian or Spanish.\")\n\n \"\"\" I am using \"or\" incase the user capitalizes the language\"\"\"\n \n if userInput == \"japanese\" or userInput == \"Japanese\":\n print(\"こんにちは、元気ですか?\")\n elif userInput == \"bahamian\" or userInput == \"Bahamian\":\n print(\"Had go bui?\")\n elif userInput == \"spanish\" or userInput == \"Spanish\":\n print(\"Hola como estas?\")\n else:\n print(\"Please choose one of the three languages\")\n getInput()\n \n \n \ngetInput();\n\n","sub_path":"A_Euteneuer_Week2.py","file_name":"A_Euteneuer_Week2.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"288378925","text":"import json\nfrom tqdm import tqdm\n\n\nimport numpy as np\nimport pandas as pd\n\nfrom textblob import TextBlob, Word\nimport time\n\n\n\n\nf = open('../../gen/data-preparation/temp/whitehouse_briefing_27_04.json','r', encoding='utf-8')\n\ncon=[]\n\nfor i, line in enumerate(f):\n if i % 2: # counting starts at 0, and `i % 2` is true for odd numbers\n continue\n con.append(line)\n\n# con = f.readlines()\n\noutfile = open('../../gen/data-preparation/temp/parsed-data.csv', 'w', encoding = 'utf-8')\n\n# outfile.write('id\\tcreated_at\\ttext\\n')\nprint('Extracting location and text...')\n\n#extract data about location, date and hashtags\nlocation=[]\n# date=[]\nhashtags=[]\ntext=[]\n\nfor line in con:\n # print(line)\n tweet = json.loads(line)\n\n \n \n try:\n location_obj = tweet.get('user').get('location')\n except:\n location_obj = 'NA'\n \n try: \n hashtags_obj = tweet.get('entities').get('hashtags')\n except: \n hashtags_obj = 'NA'\n\n try: \n text_obj = tweet.get('text')\n except: \n text_obj = 'NA'\n\n # date.append(date_obj)\n location.append(location_obj)\n hashtags.append(hashtags_obj)\n text.append(text_obj)\n\n## create df\ndf=pd.DataFrame({'location':location,\n 'text':text,\n })\n\nprint('Location and text are extracted')\nprint('Dataset size is',df.shape[0])\n #prettify location, creat dictionary of locations where key is location and value is a number of time the hashtag was used\nloc_dic={key: 0 for key in set(location)}\n\nfor loc in location:\n loc_dic[loc]+=1\n\na=sorted( ((v,k) for k,v in loc_dic.items()), reverse=True)[:150]\n\n#classify location for inside, outside\nprint('Classifying tweets...')\nloc150= [i[1] for i in a]\nus_word2 = ['USA','CA','NY','DC','TX','GA','MA','WA','NV','PA','FL','AZ','D.C.','LA']\nus_word1 = ['United States','USA','USA ','Los Angeles','US','New York','Texas','California','Florida','NYC','Washington DC','America','Ohio','New York City']\nworld_drop=['Global','Worldwide','Planet Earth','Everywhere','North America','WORLDWIDE','Earth','Houston, Poole, & Budapest']\n\ninside=[]\noutside=[]\nfor loc in loc150[1:]:\n \n c = loc.split(',')\n if (len(c)>1) and (c[1].strip() in us_word2):\n inside.append(loc)\n elif (len(c)==1) and (c[0].strip() in us_word1):\n inside.append(loc)\n elif loc not in world_drop:\n outside.append(loc)\n\n#add column 'in US' to df\nin_US = []\nfor loc in df['location']:\n # print(loc)\n if loc in inside:\n in_US.append(1)\n elif loc in outside:\n in_US.append(0)\n else:\n in_US.append('NA')\n\ndf['in_US']=in_US\ndf=df[df['in_US']!='NA']\n\nprint('Tweets are classified')\n\n#drop duplicates\ndf=df.drop_duplicates('text')\nprint('Dataset size is ', df.shape[0])\n\n\n#translate into English\n#If it's in English\nprint('Detecting tweets\\' languages...')\neng=[]\nfor text in df['text']:\n if len(text)>5:\n try:\n \n if detect(text)=='en':\n eng.append(1)\n else:\n eng.append(0)\n except:\n eng.append(3)\n continue\n else:\n eng.append(2)\n \ndf['is_in_eng']=eng\n\nprint('Languages of tweets are detected ')\n#Translate\nprint('Translating tweets...')\ntext_en=[]\n\ni=0\nfor text in tqdm(df['text']):\n \n # ind=df[df['text']==text].index\n # k=int(df['is_in_eng'].iloc[ind])\n # print(k)\n k=df['is_in_eng'].iloc[i]\n \n if k!=1:\n try:\n text_blob = TextBlob(text)\n text_blob = text_blob.translate(to='en')\n # print(text_blob)\n time.sleep(5)\n text_en.append(text_blob)\n except:\n text_en.append(text)\n continue\n \n else:\n text_en.append(text)\n \n i+=1\n\ndf['text_eng']=text_en\nprint('Saving tweets...')\n\n#Save\ndf.to_csv(outfile, index=False)\n\n\n\n# cnt = 0\n# for line in con:\n# if (len(line)<=5): continue\n\n# cnt+=1\n# obj = json.loads(line.replace('\\n',''))\n\n# text = obj.get('text')\n# text = text.replace('\\t', '').replace('\\n', '')\n\n# outfile.write(obj.get('id_str')+'\\t'+obj.get('created_at')+'\\t'+text+'\\n')\n# if (cnt>1000): break\n\nprint('done.')\n","sub_path":"src/data-preparation/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"519319772","text":"import socket\nimport sys\n\n#create an INET, STREAMing socket\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n#bind the socket to the local host,\n# and a well known port\nserversocket.bind(('localhost', 8888))\n\nserversocket.listen(1)\n\n# Set the timeout of the socket to 250 miliseconds.\nserversocket.settimeout(0.250)\n\nclient = 0\n\ntry: # try to accept a connection.\n print (\"Waiting for someone to connect..\")\n (client, address) = serversocket.accept()\n if client == 0: # if it was not possible to connect to a client\n print(\"No one to connect to..\")\n serversocket.close()\n sys.exit(1)\n else: # else do the business\n print (\"New connection from\", address)\n msg = client.recv(14).decode()\n if msg != 0:\n print (\"Received message..\")\n print (msg)\n msg = \"Hello client!\"\n client.sendall(msg.encode())\n client.close()\n serversocket.close()\nexcept OSError as msg: # handle when there is no one to connect to.\n serversocket.close()\n","sub_path":"python_server/server_test.py","file_name":"server_test.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"114898811","text":"class OrderedStream:\n\n def __init__(self, n: int):\n self.n=n\n self.data=[None]*n\n self.ptr=0\n\n def insert(self, id: int, value: str) -> List[str]:\n id-=1\n self.data[id]=value\n if self.ptr!=id:\n return[]\n else:\n while self.ptr<self.n and self.data[self.ptr]!=None: self.ptr+=1 \n return self.data[id:self.ptr]\n\n# Your OrderedStream object will be instantiated and called as such:\n# obj = OrderedStream(n)\n# param_1 = obj.insert(id,value)\n\n","sub_path":"python/design-an-ordered-stream.py","file_name":"design-an-ordered-stream.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"361504986","text":"import os\nimport numpy as np\n\ntry:\n import flopy\nexcept:\n msg = 'Error. FloPy package is not available.\\n'\n msg += 'Try installing using the following command:\\n'\n msg += ' pip install flopy'\n raise Exception(msg)\n\ntry:\n import pymake\nexcept:\n msg = 'Error. Pymake package is not available.\\n'\n msg += 'Try installing using the following command:\\n'\n msg += ' pip install https://github.com/modflowpy/pymake/zipball/master'\n raise Exception(msg)\n\nfrom framework import testing_framework, running_on_CI\nfrom simulation import Simulation\n\nex = ['csub_zdisp01']\nexdirs = []\nfor s in ex:\n exdirs.append(os.path.join('temp', s))\n\ncmppth = 'mfnwt'\n\nddir = 'data'\n\n## run all examples on Travis\ncontinuous_integration = [True for idx in range(len(exdirs))]\n\n# set replace_exe to None to use default executable\nreplace_exe = None\n\nhtol = [None for idx in range(len(exdirs))]\ndtol = 1e-3\nbudtol = 1e-2\n\nbud_lst = ['STO-SS_IN', 'STO-SS_OUT',\n 'STO-SY_IN', 'STO-SY_OUT',\n 'CSUB-CGELASTIC_IN', 'CSUB-CGELASTIC_OUT',\n 'CSUB-ELASTIC_IN', 'CSUB-ELASTIC_OUT',\n 'CSUB-INELASTIC_IN', 'CSUB-INELASTIC_OUT',\n 'CSUB-WATERCOMP_IN', 'CSUB-WATERCOMP_OUT']\n\n# static model data\n# temporal discretization\nnper = 31\nperlen = [1.] + [365.2500000 for i in range(nper - 1)]\nnstp = [1] + [6 for i in range(nper - 1)]\ntsmult = [1.0] + [1.3 for i in range(nper - 1)]\n# tsmult = [1.0] + [1.0 for i in range(nper - 1)]\nsteady = [True] + [False for i in range(nper - 1)]\ntdis_rc = []\nfor idx in range(nper):\n tdis_rc.append((perlen[idx], nstp[idx], tsmult[idx]))\n\n# spatial discretization data\nnlay, nrow, ncol = 3, 20, 20\nshape3d = (nlay, nrow, ncol)\nsize3d = nlay * nrow * ncol\ndelr, delc = 1000., 2000.\ntop = 0.\nbotm = [-100, -150., -350.]\nzthick = [top - botm[0],\n botm[0] - botm[1],\n botm[1] - botm[2]]\nstrt = 0.\nhnoflo = 1e30\nhdry = -1e30\n\n# create idomain and ibound\nidomain = np.ones((nlay, nrow, ncol), dtype=np.int32)\nidomain[0, 10:, :] = 0\nidomain[1, 0:5, :] = 0\nidomain[1, 15:, :] = 0\nidomain[2, 0:10, :] = 0\niex = np.zeros((nlay, nrow, ncol), dtype=np.int32)\niex[idomain == 0] = 1\n\n# calculate hk\nhk1fact = 1. / 50.\nhk1 = 0.5 * hk1fact\n# hk1[0, :] = 1000. * hk1fact\n# hk1[-1, :] = 1000. * hk1fact\n# hk1[:, 0] = 1000. * hk1fact\n# hk1[:, -1] = 1000. * hk1fact\nhk = [20., hk1, 5.]\n\n# calculate vka\nvka = [1e6, 7.5e-5, 1e6]\n\n# layer 1 is convertible\nlaytyp = [1, 0, 0]\n\n# solver options\nnouter, ninner = 500, 300\nhclose, rclose, relax = 1e-9, 1e-6, 1.\nnewtonoptions = ''\nimsla = 'BICGSTAB'\n\n# chd data\nc = []\nc6 = []\nccol = [j for j in range(ncol)]\nfor j in ccol:\n c.append([0, 0, j, strt, strt])\n c6.append([(0, 0, j), strt])\ncd = {0: c}\ncd6 = {0: c6}\nmaxchd = len(cd[0])\n\n# drain data\ndr = []\ndr6 = []\ndrh = strt - 1.\ndrc = 10.\nfor j in ccol:\n dr.append([2, nrow - 1, j, drh, drc])\n dr6.append([(2, nrow - 1, j), drh, drc])\ndrd = {0: dr}\ndrd6 = {0: dr6}\nmaxdrd = len(drd[0])\n\n# pumping well data\nwrp = [12, 12, 13, 13]\nwcp = [9, 10, 9, 10]\nwq = [-14000., -8000., -5000., -3000.]\nd = []\nd6 = []\nfor r, c, q in zip(wrp, wcp, wq):\n d.append([2, r, c, q])\n d6.append([(2, r, c), q])\nwd = {1: d}\nwd6 = {1: d6}\nmaxwel = len(wd[1])\nmaxwel = len(wd[1])\n\n# storage and compaction data\n# ske = [6e-4, 3e-4, 6e-4]\n# ss = [3e-6, 0., 3e-6]\nss = [0., 0., 0.]\nvoid = 0.82\ntheta = void / (1. + void)\n\n# static ibc and sub data\nsgm = 0.\nsgs = 0.\nomega = 1.0\n\n# no delay bed data\nnndb = 3\nlnd = [0, 1, 2]\nhc = -7.\nthicknd0 = [15., 50., 30.]\nccnd0 = [6e-4, 3e-4, 6e-4]\ncrnd0 = [6e-6, 3e-6, 6e-6]\nsfv = []\nsfe = []\nfor k in range(nlay):\n sfv.append(ccnd0[k] * thicknd0[k])\n sfe.append(crnd0[k] * thicknd0[k])\n\n# ibc packagedata container counter\nsub6 = []\nibcno = 0\n\n# create no delay bed packagedata entries\nif nndb > 0:\n cdelays = 'nodelay'\n for kdx, k in enumerate(lnd):\n for i in range(nrow):\n for j in range(ncol):\n # skip constant head cells\n if idomain[k, i, j] == 0:\n continue\n tag = '{:02d}_{:02d}_{:02d}'.format(k + 1, i + 1, j + 1)\n # create nodelay entry\n # no delay beds\n b = thicknd0[kdx]\n d = [ibcno, (k, i, j), cdelays, hc,\n b, 1., ccnd0[kdx], crnd0[kdx], theta,\n 999., -999., tag]\n sub6.append(d)\n ibcno += 1\n\n# create delay bed packagedata entries and coarse-grained materia storage\nske_scaled = []\n# create S for aquifer and no-delay beds\nfor k in range(nlay):\n sst = (zthick[k] - thicknd0[k]) * ss[k] / zthick[k]\n ske_scaled.append(sst)\n\nmaxcsub = len(sub6)\n\n# sub output data\nds15 = [0, 0, 0, 2052, 0, 0, 0, 2053, 0, 0, 0, 0]\nds16 = [0, nper - 1, 0, nstp[-1] - 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]\n\n\n# variant SUB package problem 3\ndef get_model(idx, dir):\n name = ex[idx]\n\n # build MODFLOW 6 files\n ws = dir\n sim = flopy.mf6.MFSimulation(sim_name=name, version='mf6',\n exe_name='mf6',\n sim_ws=ws)\n # create tdis package\n tdis = flopy.mf6.ModflowTdis(sim, time_units='DAYS',\n nper=nper, perioddata=tdis_rc)\n\n # create gwf model\n zthick = [top - botm[0],\n botm[0] - botm[1],\n botm[1] - botm[2]]\n elevs = [top] + botm\n\n gwf = flopy.mf6.ModflowGwf(sim, modelname=name,\n newtonoptions=newtonoptions,\n save_flows=True)\n\n # create iterative model solution and register the gwf model with it\n ims = flopy.mf6.ModflowIms(sim, print_option='SUMMARY',\n outer_dvclose=hclose,\n outer_maximum=nouter,\n under_relaxation='NONE',\n inner_maximum=ninner,\n inner_dvclose=hclose, rcloserecord=rclose,\n linear_acceleration=imsla,\n scaling_method='NONE',\n reordering_method='NONE',\n relaxation_factor=relax)\n sim.register_ims_package(ims, [gwf.name])\n\n dis = flopy.mf6.ModflowGwfdis(gwf, nlay=nlay, nrow=nrow, ncol=ncol,\n delr=delr, delc=delc,\n top=top, botm=botm,\n idomain=idomain,\n filename='{}.dis'.format(name))\n\n # initial conditions\n ic = flopy.mf6.ModflowGwfic(gwf, strt=strt,\n filename='{}.ic'.format(name))\n\n # node property flow\n npf = flopy.mf6.ModflowGwfnpf(gwf, save_flows=False,\n icelltype=laytyp,\n k=hk,\n k33=vka)\n # storage\n sto = flopy.mf6.ModflowGwfsto(gwf, save_flows=False, iconvert=laytyp,\n ss=0, sy=0,\n storagecoefficient=None,\n steady_state={0: True},\n transient={1: True})\n\n # csub files\n opth = '{}.csub.obs'.format(name)\n ibcsv = '{}.ib.strain.csv'.format(name)\n skcsv = '{}.sk.strain.csv'.format(name)\n copth = '{}.compaction.bin'.format(name)\n zopth = '{}.zdisplacement.bin'.format(name)\n csub = flopy.mf6.ModflowGwfcsub(gwf,\n boundnames=True,\n head_based=True,\n specified_initial_interbed_state=True,\n effective_stress_lag=True,\n save_flows=True,\n strainib_filerecord=ibcsv,\n straincg_filerecord=skcsv,\n compaction_filerecord=copth,\n zdisplacement_filerecord=zopth,\n ninterbeds=maxcsub,\n beta=0., cg_ske_cr=ss,\n packagedata=sub6)\n orecarray = {}\n tag = '{:02d}_{:02d}_{:02d}'.format(3, wrp[0] + 1, wcp[0] + 1)\n oloc = (2, wrp[0], wcp[0])\n orecarray['csub_obs.csv'] = [('tcomp3', 'interbed-compaction', tag),\n ('sk-tcomp3', 'coarse-compaction', oloc),\n ('ibi-tcomp3', 'inelastic-compaction', tag),\n ('ibe-tcomp3', 'elastic-compaction', tag)]\n csub_obs_package = csub.obs.initialize(filename=opth, digits=10,\n print_input=True,\n continuous=orecarray)\n\n # drain\n drn = flopy.mf6.ModflowGwfdrn(gwf, maxbound=maxdrd,\n stress_period_data=drd6)\n\n # wel file\n wel = flopy.mf6.ModflowGwfwel(gwf, print_input=True, print_flows=True,\n maxbound=maxwel,\n stress_period_data=wd6)\n\n # chd files\n chd = flopy.mf6.modflow.mfgwfchd.ModflowGwfchd(gwf,\n maxbound=maxchd,\n stress_period_data=cd6,\n save_flows=False)\n\n # output control\n oc = flopy.mf6.ModflowGwfoc(gwf,\n budget_filerecord='{}.cbc'.format(name),\n head_filerecord='{}.hds'.format(name),\n headprintrecord=[\n ('COLUMNS', 10, 'WIDTH', 15,\n 'DIGITS', 6, 'GENERAL')],\n saverecord=[('HEAD', 'ALL'),\n ('BUDGET', 'ALL')],\n printrecord=[('HEAD', 'LAST'),\n ('BUDGET', 'ALL')])\n\n # build MODFLOW-NWT files\n cpth = cmppth\n ws = os.path.join(dir, cpth)\n mc = flopy.modflow.Modflow(name, model_ws=ws, version=cpth)\n dis = flopy.modflow.ModflowDis(mc, nlay=nlay, nrow=nrow, ncol=ncol,\n nper=nper, perlen=perlen, nstp=nstp,\n tsmult=tsmult, steady=steady, delr=delr,\n delc=delc, top=top, botm=botm)\n bas = flopy.modflow.ModflowBas(mc, ibound=idomain, strt=strt,\n hnoflo=hnoflo,\n stoper=0.01)\n upw = flopy.modflow.ModflowUpw(mc, laytyp=laytyp, ipakcb=1001,\n hk=hk, vka=vka,\n ss=ske_scaled, sy=0.,\n hdry=hdry)\n sub = flopy.modflow.ModflowSub(mc, ndb=0, nndb=nndb,\n isuboc=1, ln=lnd,\n hc=hc, sfe=sfe, sfv=sfv,\n ids15=ds15, ids16=ds16)\n chd = flopy.modflow.ModflowChd(mc, stress_period_data=cd)\n drn = flopy.modflow.ModflowDrn(mc, stress_period_data=drd)\n wel = flopy.modflow.ModflowWel(mc, stress_period_data=wd)\n oc = flopy.modflow.ModflowOc(mc, stress_period_data=None,\n save_every=1,\n save_types=['print head', 'save head',\n 'save budget'])\n fluxtol = (float(nlay * nrow * ncol) - 4.) * rclose\n nwt = flopy.modflow.ModflowNwt(mc,\n headtol=hclose, fluxtol=fluxtol,\n maxiterout=nouter, linmeth=2,\n maxitinner=ninner,\n unitnumber=132,\n options='SPECIFIED',\n backflag=0, idroptol=0)\n return sim, mc\n\n\ndef build_models():\n for idx, dir in enumerate(exdirs):\n sim, mc = get_model(idx, dir)\n sim.write_simulation()\n mc.write_input()\n return\n\n\ndef eval_zdisplacement(sim):\n print('evaluating z-displacement...')\n\n # MODFLOW 6 total compaction results\n fpth = os.path.join(sim.simpath, 'csub_obs.csv')\n try:\n tc = np.genfromtxt(fpth, names=True, delimiter=',')\n except:\n assert False, 'could not load data from \"{}\"'.format(fpth)\n\n # MODFLOW-2005 total compaction results\n fn = '{}.total_comp.hds'.format(os.path.basename(sim.name))\n fpth = os.path.join(sim.simpath, 'mfnwt', fn)\n try:\n sobj = flopy.utils.HeadFile(fpth, text='LAYER COMPACTION')\n tc0 = sobj.get_ts((2, wrp[0], wcp[0]))\n except:\n assert False, 'could not load data from \"{}\"'.format(fpth)\n\n # calculate maximum absolute error\n diff = tc['TCOMP3'] - tc0[:, 1]\n diffmax = np.abs(diff).max()\n msg = 'maximum absolute total-compaction difference ({}) '.format(diffmax)\n\n if diffmax > dtol:\n sim.success = False\n msg += 'exceeds {}'.format(dtol)\n assert diffmax < dtol, msg\n else:\n sim.success = True\n print(' ' + msg)\n\n # get results from listing file\n fpth = os.path.join(sim.simpath,\n '{}.lst'.format(os.path.basename(sim.name)))\n budl = flopy.utils.Mf6ListBudget(fpth)\n names = list(bud_lst)\n d0 = budl.get_budget(names=names)[0]\n dtype = d0.dtype\n nbud = d0.shape[0]\n\n # get results from cbc file\n cbc_bud = ['STO-SS', 'STO-SY',\n 'CSUB-CGELASTIC', 'CSUB-ELASTIC',\n 'CSUB-INELASTIC', 'CSUB-WATERCOMP']\n d = np.recarray(nbud, dtype=dtype)\n for key in bud_lst:\n d[key] = 0.\n fpth = os.path.join(sim.simpath,\n '{}.cbc'.format(os.path.basename(sim.name)))\n cobj = flopy.utils.CellBudgetFile(fpth, precision='double')\n kk = cobj.get_kstpkper()\n times = cobj.get_times()\n for idx, (k, t) in enumerate(zip(kk, times)):\n for text in cbc_bud:\n qin = 0.\n qout = 0.\n v = cobj.get_data(kstpkper=k, text=text)[0]\n if isinstance(v, np.recarray):\n vt = np.zeros(size3d, dtype=np.float)\n for jdx, node in enumerate(v['node']):\n vt[node - 1] += v['q'][jdx]\n v = vt.reshape(shape3d)\n for kk in range(v.shape[0]):\n for ii in range(v.shape[1]):\n for jj in range(v.shape[2]):\n vv = v[kk, ii, jj]\n if vv < 0.:\n qout -= vv\n else:\n qin += vv\n d['totim'][idx] = t\n d['time_step'][idx] = k[0]\n d['stress_period'] = k[1]\n key = '{}_IN'.format(text)\n d[key][idx] = qin\n key = '{}_OUT'.format(text)\n d[key][idx] = qout\n\n diff = np.zeros((nbud, len(bud_lst)), dtype=np.float)\n for idx, key in enumerate(bud_lst):\n diff[:, idx] = d0[key] - d[key]\n diffmax = np.abs(diff).max()\n msg = 'maximum absolute total-budget difference ({}) '.format(diffmax)\n\n # write summary\n fpth = os.path.join(sim.simpath,\n '{}.bud.cmp.out'.format(os.path.basename(sim.name)))\n f = open(fpth, 'w')\n for i in range(diff.shape[0]):\n if i == 0:\n line = '{:>10s}'.format('TIME')\n for idx, key in enumerate(bud_lst):\n line += '{:>25s}'.format(key + '_LST')\n line += '{:>25s}'.format(key + '_CBC')\n line += '{:>25s}'.format(key + '_DIF')\n f.write(line + '\\n')\n line = '{:10g}'.format(d['totim'][i])\n for idx, key in enumerate(bud_lst):\n line += '{:25g}'.format(d0[key][i])\n line += '{:25g}'.format(d[key][i])\n line += '{:25g}'.format(diff[i, idx])\n f.write(line + '\\n')\n f.close()\n\n if diffmax > budtol:\n sim.success = False\n msg += 'exceeds {}'.format(dtol)\n assert diffmax < dtol, msg\n else:\n sim.success = True\n print(' ' + msg)\n\n # compare z-displacement data\n fpth1 = os.path.join(sim.simpath,\n '{}.zdisplacement.bin'.format(\n os.path.basename(sim.name)))\n fpth2 = os.path.join(sim.simpath, cmppth, 'csub_zdisp01.vert_disp.hds')\n text1 = 'CSUB-ZDISPLACE'\n text2 = 'Z DISPLACEMENT'\n fout = os.path.join(sim.simpath,\n '{}.z-displacement.bin.out'.format(\n os.path.basename(sim.name)))\n success_tst = pymake.compare_heads(None, None,\n text=text1, text2=text2,\n outfile=fout,\n files1=fpth1,\n files2=fpth2,\n difftol=True,\n verbose=True,\n exarr=iex)\n msg = 'z-displacement comparison success = {}'.format(success_tst)\n if success_tst:\n sim.success = True\n print(msg)\n else:\n sim.success = False\n assert success_tst, msg\n\n return\n\n\n# - No need to change any code below\ndef test_mf6model():\n # determine if running on Travis or GitHub actions\n is_CI = running_on_CI()\n r_exe = None\n if not is_CI:\n if replace_exe is not None:\n r_exe = replace_exe\n\n # initialize testing framework\n test = testing_framework()\n\n # build the models\n build_models()\n\n # run the test models\n for idx, dir in enumerate(exdirs):\n if is_CI and not continuous_integration[idx]:\n continue\n yield test.run_mf6, Simulation(dir, exfunc=eval_zdisplacement,\n exe_dict=r_exe,\n htol=htol[idx],\n idxsim=idx)\n\n return\n\n\ndef main():\n # initialize testing framework\n test = testing_framework()\n\n # build the models\n build_models()\n\n # run the test models\n for idx, dir in enumerate(exdirs):\n sim = Simulation(dir, exfunc=eval_zdisplacement,\n exe_dict=replace_exe, htol=htol[idx], idxsim=idx)\n test.run_mf6(sim)\n\n return\n\n\nif __name__ == \"__main__\":\n # print message\n print('standalone run of {}'.format(os.path.basename(__file__)))\n\n # run main routine\n main()\n","sub_path":"Groundwater/mf6/autotest/test_gwf_csub_zdisp01.py","file_name":"test_gwf_csub_zdisp01.py","file_ext":"py","file_size_in_byte":18608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"402270960","text":"import discord\nimport os\nimport botcommands\nimport config\nimport time\n\n\nclass DankBot(discord.Client):\n def __init__(self, **options):\n super().__init__(**options)\n self.conversations = {}\n self.start_time = time.time()\n self.active = True\n self.limited_users = set()\n\n async def on_message(self, message):\n author_id = message.author.id\n admin = author_id in config.admins\n\n if author_id == self.user.id or (not admin and not self.active) or author_id in self.limited_users:\n return\n\n if message.content.startswith(config.prefix):\n await botcommands.command(message, admin)\n elif author_id in self.conversations and self.conversations[author_id].channel == message.channel:\n if self.conversations[author_id].last_message_time + config.convo_time_out < time.time():\n # Timed out\n self.conversations.pop(author_id)\n else:\n # Not timed out\n self.conversations[author_id].last_message_time = time.time()\n await self.send_message(message.channel, self.conversations[author_id].session.think(message.content))\n\n\nif __name__ == '__main__':\n # Run:\n bot = DankBot()\n botcommands.bot = bot\n bot.run(os.environ['DISCORD_BOT_USER'], os.environ['DISCORD_BOT_PASS'])\n","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"84343555","text":"import falcon\nimport json\nimport os\nimport re\nimport glob\nimport cssutils\nfrom bs4 import BeautifulSoup\n\n\ndef req_to_dict(req):\n try:\n raw_json = req.stream.read()\n except Exception as ex:\n raise falcon.HTTPError(falcon.HTTP_400, 'Error', ex.message)\n\n try:\n result_dict = json.loads(raw_json, encoding='utf-8')\n except ValueError:\n raise falcon.HTTPError(\n falcon.HTTP_400,\n 'Malformed JSON',\n 'Could not decode the request body. The '\n 'JSON was incorrect.'\n )\n\n return result_dict\n\n\ndef extract_html(path_html_file):\n with open(path_html_file, 'r') as html_file:\n dom = html_file.read()\n\n return dom\n\n\ndef extract_name_directory_lo(html):\n soup = BeautifulSoup(html, 'html.parser')\n\n return soup.a['href']\n\n\ndef get_all_files(folder, ext):\n os.chdir(folder)\n files = []\n for file in glob.glob(ext):\n files.append(file)\n\n return files\n\n\ndef change_html(DOM):\n soup = BeautifulSoup(DOM, \"html.parser\")\n google_translate_html = \"\"\"\n <style>.goog-te-banner-frame{display:none;}</style>\n <div id=\"google_translate_element\" style=\"display:none\"></div><script type=\"text/javascript\">function googleTranslateElementInit(){new google.translate.TranslateElement({pageLanguage: 'es', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false}, 'google_translate_element');}</script><script src=\"//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit\" type=\"text/javascript\"></script><script type=\"text/javascript\">function translate(lang){var $frame=$('.goog-te-menu-frame:first'); if (!$frame.length){alert(\"Error: Could not find Google translate frame.\"); return false;}$frame.contents().find('.goog-te-menu2-item span.text:contains('+lang+')').get(0).click(); return false;}</script>\n \"\"\"\n print(soup)\n soup.body.append(BeautifulSoup(google_translate_html, \"html.parser\"))\n for tag in soup.find_all():\n try:\n style = tag['style']\n css_parse = cssutils.parseStyle(style)\n css_parse['font-family'] = ''\n tag['style'] = css_parse.cssText\n except:\n pass\n\n return str(soup)\n\n\ndef all_rem_or_em_to_px(css_styles):\n base = 16\n for rule in css_styles:\n try:\n if rule.style['font-size']:\n if rule.selectorText == 'html':\n base = rule.style['font-size']\n if is_percentage(base):\n number = [float(s) for s in re.findall(\n r'-?\\d+\\.?\\d*', base)][0]\n base = 16 * (number/100)\n rule.style['font-size'] = '{0}px;'.format(base)\n else:\n old_font_size = rule.style['font-size']\n if not is_px(old_font_size):\n number = [float(s) for s in re.findall(\n r'-?\\d+\\.?\\d*', old_font_size)][0]\n rem = number\n px = base * rem\n rule.style['font-size'] = '{0}px;'.format(px)\n except:\n pass\n\n try:\n if rule.style['font']:\n rule.style['font'] = ''\n\n except:\n pass\n\n return css_styles\n\n\ndef is_percentage(units):\n return units[-1] == '%'\n\n\ndef is_px(units):\n return units[-1] == 'x'\n\n\ndef is_rem_or_em(units):\n return units[-1] == 'm'\n\n\ndef to_rem(units, base=12):\n number = [float(s) for s in re.findall(r'-?\\d+\\.?\\d*', units)][0]\n if is_px(units):\n px = number\n rem = px/base\n rem = '{0}rem;'.format(rem)\n return rem\n\n\ndef change_css(css_styles):\n css_styles = all_rem_or_em_to_px(css_styles)\n font_size_html = False\n for rule in css_styles:\n try:\n if rule.style['font-size']:\n if rule.selectorText == 'html':\n rule.style['font-size'] = '12px;'\n font_size_html = True\n else:\n old_font_size = rule.style['font-size']\n rule.style['font-size'] = to_rem(old_font_size)\n except:\n pass\n\n if not font_size_html:\n css_styles.insertRule('html {font-size: 12px;}')\n\n return css_styles\n\n\ndef unwrap_p(dom):\n soup = BeautifulSoup(dom, 'html.parser')\n\n for p_tag in soup.findAll('p'):\n for span_tag in p_tag.findAll('span'):\n span_tag.unwrap()\n try:\n if(not p_tag.get('style').isspace()):\n p_tag['style'] = '{0};{1}'.format(\n p_tag.get('style'), span_tag.get('style'))\n else:\n p_tag['style'] = span_tag.get('style')\n except:\n pass\n\n return str(soup)\n\n\ndef process_html(path_html_file):\n html = unwrap_p(change_html(extract_html(path_html_file)))\n with open(path_html_file, 'w') as html_file:\n html_file.write(html)\n\n\ndef process_css(path_css_file):\n css = change_css(extract_css_rules(path_css_file)).cssText\n with open(path_css_file, 'wb') as css_file:\n css_file.write(css)\n\n\ndef extract_css_rules(path_css_file):\n sheet = cssutils.parseFile(path_css_file)\n return sheet\n","sub_path":"api/v1/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"429982868","text":"import matplotlib.pyplot as pl\nimport numpy as np\n\nx = np.arange(0,10,0.1)\na = np.cos(x)\nb = np.sin(x)\n\npl.plot(x,a,'r')\npl.plot(x,b,'b')\npl.show()","sub_path":"Hackerrank/hsh.py","file_name":"hsh.py","file_ext":"py","file_size_in_byte":147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"199146943","text":"\"\"\" snomRoomCapacity uses M9B Gateways to count all devices (beacons) within the proximity.\n In case a Gateway sees more than MAX_ALLOWED_DEVICES=2 devices an alarm is send to Mxx handsets\n and KNX actions (Light flashing, open window) is fired.\n\"\"\"\nimport time\nimport logging\nimport schedule\nimport requests\n\nfrom DB.DECTMessagingDb import DECTMessagingDb\nfrom DECTKNXGatewayConnector import DECT_KNX_gateway_connector\n\nclass snomRoomCapacityClient():\n \"\"\" snomRoomCapacityClient uses M9B Gateways to count all devices (beacons) within the proximity.\n In case a Gateway sees more than MAX_ALLOWED_DEVICES=2 devices an alarm is send to Mxx handsets\n and KNX actions (Light flashing, open window) is fired.\n \"\"\"\n def __init__(self, enable=True):\n self.enable = enable\n\n def check_rooms_capacity(self):\n \"\"\"Reads m9b_device_status_2 and counts all devices within the proximity of\n an M9B Gateway.\n In case there are more than MAX_ALLOWED_DEVICES seen by a M9B Gateway,\n an alarm is send to handsets seen by the M9B Gateway and KNX Actions are fired.\n\n KNX Actions need to be defined before running this function, e.g.\n ACTIONS = [\n {'m9b_IPEI': '0328D3C918', 'device_bt_mac': '000413B50038', 'url': '/1/1/10-aus' , 'proximity': '0'},\n {'m9b_IPEI': '0328D3C918', 'device_bt_mac': '000413B50038', 'url': '/1/1/10-an' , 'proximity': '1'},\n {'m9b_IPEI': '0328D3C918', 'device_bt_mac': '000413B50038', 'url': '/1/1/10-an' , 'proximity': '2'},\n {'m9b_IPEI': '0328D3C918', 'device_bt_mac': '000413B50038', 'url': '/1/1/10-an' , 'proximity': '3'}\n ]\n KNX_gateway.update_actions(ACTIONS)\n \"\"\"\n if msgDb:\n\n result = msgDb.read_m9b_device_status_2_db()\n max_room_counts = msgDb.read_gateway_db(beacon_gateway_IPEI='', max_allowed_devices='')\n print(result)\n #[{'account': '000413B50038', 'bt_mac': '000413B50038',\n #'rssi': '-53', 'uuid': 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF90FF',\n #'beacon_type': 'a', 'proximity': '3',\n #'beacon_gateway_IPEI': '0328D3C918', 'beacon_gateway_name': 'Schreibtisch',\n #'time_stamp': '2020-10-29 10:44:22.489801', 'server_time_stamp': '2020-10-29 09:44:22', 'timeout': 96945}]\n\n # not unique\n m9bs = list({v['beacon_gateway_IPEI']:v['beacon_gateway_IPEI'] for v in result}.values())\n #print(m9bs)\n\n for m9b in m9bs:\n # get btmac data for m9b\n selected_items = [{k:d[k] for k in d if k!=\"a\"} for d in result if d.get(\"beacon_gateway_IPEI\") == m9b]\n logger.debug(\"%s devices seen by M9B=%s (%s)\", len(selected_items), m9b, selected_items[0][\"beacon_gateway_name\"])\n \n if len(selected_items) > selected_items[0]['max_allowed_devices']:\n logger.info(\"check_rooms_capacity: capacity of %s exceeded.\", selected_items[0][\"beacon_gateway_IPEI\"])\n\n for elem in selected_items:\n # send alarm to all handsets - base_connection is needed from the Devives Tabel\n logger.info(f'send alarm to {elem[\"account\"]} on base connection {elem[\"base_connection\"]}' )\n # fire knx action(s)\n logger.info(f'fire knx action for {elem[\"account\"]},{elem[\"bt_mac\"]} seen by M9B:{elem[\"beacon_gateway_IPEI\"]}' )\n KNX_gateway.fire_KNX_action(elem[\"bt_mac\"], elem[\"beacon_gateway_IPEI\"], \"1\")\n\n # send alarm to handset\n message = [\n {\"name\": elem[\"account\"], \"account\": elem[\"account\"]},\n {\"name\": \"FormControlTextarea1\", \"account\": \"Corona Alert - %s additional person(s) in room %s!\" % (len(selected_items)-2, elem[\"beacon_gateway_name\"])},\n {\"name\": \"FormControlStatus1\", \"account\": \"0\"},\n {\"name\": \"submitbutton\", \"account\": \"\"}\n ]\n\n # notify the user with alarm.\n try:\n # send btmacs updated data back to viewer.\n _r = requests.post('http://127.0.0.1:8081/en_US/alarm', json=message)\n except requests.exceptions.Timeout as errt:\n print (\"Timeout Error location:\",errt)\n\n\n\nif __name__ == \"__main__\":\n\n # prepare logger\n logger = logging.getLogger('SnomM9BCapacity')\n logger.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s')\n\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n # get access to the DB\n # DB reuse and type\n ODBC=False\n INITDB=False\n msgDb = DECTMessagingDb(odbc=ODBC, initdb=INITDB)\n\n # get access to KXN\n KNX_gateway = DECT_KNX_gateway_connector(knx_url='http://10.110.16.63:1234', maxsize=5, loglevel=logging.WARNING)\n\n # get a mqtt instance sending data in hass.io form\n rc = snomRoomCapacityClient()\n # add all the capacity overflow actions\n ACTIONS = [\n {'m9b_IPEI': '0328D3C918', 'device_bt_mac': '000413B50038', 'url': '/1/1/10-aus' , 'proximity': '0'},\n {'m9b_IPEI': '0328D3C918', 'device_bt_mac': '000413B50038', 'url': '/1/1/10-an' , 'proximity': '1'},\n {'m9b_IPEI': '0328D3C918', 'device_bt_mac': '000413B50038', 'url': '/1/1/10-an' , 'proximity': '2'},\n {'m9b_IPEI': '0328D3C918', 'device_bt_mac': '000413B50038', 'url': '/1/1/10-an' , 'proximity': '3'}\n ]\n KNX_gateway.update_actions(ACTIONS)\n\n # fire data with scheduler\n logger.debug(\"main: schedule.every(2).seconds.do(rc.check_rooms_capacity)\")\n schedule.every(10).seconds.do(rc.check_rooms_capacity)\n\n while True:\n # check and execute scheduled task\n schedule.run_pending()\n","sub_path":"app/snomRoomCapacity.py","file_name":"snomRoomCapacity.py","file_ext":"py","file_size_in_byte":6019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"479690371","text":"# https://list.tmall.com/search_product.htm?cat=50512020&s=(i-1)*60 #第i页\nimport re\nfrom urllib import request\nimport pprint\nheader=('user-agent',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36')\nopener=request.build_opener()\nopener.addheaders=[header]\nrequest.install_opener(opener)\n\nfor i in range(1,3):\n url='https://list.tmall.com/search_product.htm?cat=50512020&s='+'(i-1)*60'\n res=request.urlopen(url,timeout=2).read().decode('utf-8','ignore')\n pattern='//(.+?.jpg)'\n imagelist=re.compile(pattern).findall(res)\n # print(len(imageurl))\n # pprint.pprint(imageurl)\n for j in range(len(imagelist)):\n thisImgUrl='http://'+imagelist[j]\n file='C:/Users/Meng/Desktop/面试通过/项目/爬虫防屏蔽和代理服务器/淘宝爬糖图/第'+str(i)+'页-第'+str(j+1)+'张图.jpg'\n request.urlretrieve(thisImgUrl,filename=file)\n","sub_path":"爬虫防屏蔽和代理服务器/图片爬虫实战.py","file_name":"图片爬虫实战.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"70075297","text":"# Test mockupcryptd.\n\nimport pymongo\nimport mockupcryptd\nimport os\nimport sys\nimport signal\n\nexample_schema = {\n \"bsonType\": \"object\",\n \"properties\": {\n \"ssn\": {\n \"encrypt\": {\n \"type\": \"string\",\n \"algorithm\": \"Randomized\",\n \"keyId\": {\n \"$binary\": {\n \"base64\": \"1+niXaxyRL6AB6xRzUp/Ew==\",\n \"subType\": \"04\"\n }\n },\n \"keyVaultAlias\": \"default\"\n }\n }\n }\n}\n\n\ndef test_schema_parsing():\n encrypt_map = {}\n mockupcryptd.build_encrypt_map(encrypt_map, example_schema)\n assert \"ssn\" in encrypt_map\n assert encrypt_map[\"ssn\"] == example_schema[\"properties\"][\"ssn\"][\"encrypt\"]\n\n\ndef test_marking():\n mockupcryptd.version = \"spec\"\n marking = mockupcryptd.make_marking(\n {\"algorithm\": \"det\", \"keyVaultAlias\": \"kva\", \"iv\": \"an iv\", \"keyId\": \"my key id\"}, \"test\")\n parsed = mockupcryptd.parse_marking(marking)\n assert parsed == {'v': 'test', 'a': 'det',\n 'va': 'kva', 'iv': 'an iv', 'ki': 'my key id'}\n\ndef live_test (test_fn):\n started_mockupcryptd = False\n if not os.path.exists(\"/tmp/mongocryptd.sock\"):\n print(\"mockupcryptd not detected to be running, starting for test\")\n newpid = os.fork()\n if newpid == 0:\n print(\"Child starting mockupcryptd\")\n mockupcryptd.main()\n sys.exit(0)\n started_mockupcryptd = True\n client = pymongo.MongoClient(\"mongodb://%2Ftmp%2Fmongocryptd.sock\")\n test_fn(client)\n if started_mockupcryptd:\n os.kill(newpid, signal.SIGINT)\n os.wait()\n\ndef test_find_cmd(client):\n db = client[\"admin\"]\n resp = db.command({\n \"find\": \"collection\",\n \"filter\": {\n \"ssn\": \"123-45-6789\",\n },\n \"jsonSchema\": example_schema\n })\n print(resp)\n\ndef main():\n test_schema_parsing()\n test_marking()\n live_test(test_find_cmd)\n print(\"All tests pass\")\n","sub_path":"test/test_mockupcryptd.py","file_name":"test_mockupcryptd.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"424808112","text":"\"\"\"\nBar chart demo with pairs of bars grouped for easy comparison.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef show1(ax, x, y_1, labelS, c):\n bar_width = 0.35\n\n opacity = 1\n\n rects1 = ax.bar(x, y_1, bar_width,\n alpha=opacity,\n color=c,\n label=labelS)\n return rects1\n \ndef show1_special(ax, x, y_1, minimal, labelS, c):\n x_new = x[0:minimal]\n y_new = y_1[0:minimal]\n x_new_right = x[minimal:]\n y_new_right = y_1[minimal:]\n allRight = 0\n \n for i in y_new_right:\n allRight += i\n\n\n if len(x) < minimal:\n x_final = x\n y_final = y_1\n else:\n x_final = x_new\n y_final = y_new\n\n## if len(x_new_right) > 0:\n## x_final = np.append(x_new, x_new_right[0])\n## y_final = np.append(y_new, allRight)\n## else :\n## x_final = x_new\n## y_final = y_new\n \n bar_width = 0.35\n \n opacity = 1\n\n rects1 = ax.bar(x_final, y_final, bar_width,\n alpha=opacity,\n color=c,\n label=labelS)\n return rects1\n #ax.annotate('pixels', xy=(20, 20), xycoords='figure pixels')\n\ndef show2(ax, x, y_1, labelS, c, mark, dot):\n line_2, = ax.plot(x, y_1, ls=dot, marker=mark, label=labelS, color=c)\n return line_2\n \ndef show2_special(ax, x, y_1, minimal, labelS, c, mark, dot):\n x_new = x[0:minimal]\n y_new = y_1[0:minimal]\n x_new_right = x[minimal:]\n y_new_right = y_1[minimal:]\n allRight = 0\n \n for i in y_new_right:\n allRight += i\n\n\n if len(x) < minimal:\n x_final = x\n y_final = y_1\n else:\n x_final = x_new\n y_final = y_new\n\n line_2, = ax.plot(x_final, y_final, ls=dot, marker=mark, label=labelS, color=c)\n return line_2\n\ndef show(x, y_1, y_2):\n n_groups = 5\n \n fig, ax = plt.subplots()\n\n bar_width = 0.35\n\n opacity = 0.4\n\n rects1 = plt.bar(x, y_1, bar_width,\n alpha=opacity,\n color='b',\n label='ICT')\n\n rects2 = plt.bar(x + bar_width, y_2, bar_width,\n alpha=opacity,\n color='r',\n label='SCT')\n\n plt.xlabel('covered times')\n plt.ylabel('number of schemas')\n plt.title('Scores by group and gender')\n plt.xticks(x + bar_width, x)\n plt.legend()\n\n plt.tight_layout()\n plt.show()\nif __name__ == \"__main__\":\n x = np.array([0, 1, 2, 3, 4])\n y_1 = (20, 35, 30, 35, 27)\n y_2 = (25, 32, 34, 20, 25)\n show(x, y_1, y_2)\n","sub_path":"ex/specific_post_deal with average values/cover_num/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"152820535","text":"from helpers.constants import MaxUint256\nfrom tests.sett.fixtures.SettMiniDeployBase import SettMiniDeployBase\nfrom config.badger_config import sett_config\nfrom helpers.token_utils import distribute_from_whales\nfrom brownie import *\nfrom helpers.proxy_utils import deploy_proxy\nfrom scripts.systems.constants import SettType\n\n\nclass HelperCvxMiniDeploy(SettMiniDeployBase):\n def fetch_params(self):\n params = sett_config.helper.cvx.params\n want = sett_config.helper.cvx.params.want\n\n return (params, want)\n\n def post_vault_deploy_setup(self, deploy=True):\n if deploy:\n distribute_from_whales(self.deployer, 1)\n\n def post_deploy_setup(self, deploy):\n if deploy:\n return\n\n # Vault uses testMultisig\n self.testMultisig = accounts.at(self.vault.governance(), force=True)\n\n # NB: Not all vaults are pauseable.\n try:\n if self.vault.paused():\n self.vault.unpause({\"from\": self.testMultisig})\n except exceptions.VirtualMachineError:\n pass\n\n # Check that vault's and Strat's controller is the same\n assert self.vault.controller() == self.strategy.controller()\n\n # Check that want is the same for vault and strategy\n assert self.vault.token() == self.strategy.want()\n\n self.controller = interface.IController(self.vault.controller())\n\n # Add strategy to controller for want\n self.controller.approveStrategy(\n self.strategy.want(), self.strategy.address, {\"from\": self.governance}\n )\n self.controller.setStrategy(\n self.strategy.want(), self.strategy.address, {\"from\": self.governance}\n )\n\n assert self.controller.strategies(self.vault.token()) == self.strategy.address\n assert self.controller.vaults(self.strategy.want()) == self.vault.address\n\n # Add actors to guestlist\n guestlist = VipCappedGuestListBbtcUpgradeable.at(self.vault.guestList())\n\n addresses = []\n for account in accounts:\n addresses.append(account.address)\n\n # Add actors addresses\n addresses.append(guestlist.owner())\n addresses.append(self.governance.address)\n addresses.append(self.strategist.address)\n addresses.append(self.keeper.address)\n addresses.append(self.guardian.address)\n addresses.append(self.deployer.address)\n\n invited = [True] * len(addresses)\n\n owner = accounts.at(guestlist.owner(), force=True)\n\n guestlist.setGuests(addresses, invited, {\"from\": owner})\n guestlist.setUserDepositCap(MaxUint256, {\"from\": owner})\n guestlist.setTotalDepositCap(MaxUint256, {\"from\": owner})\n","sub_path":"tests/sett/fixtures/HelperCvxMiniDeploy.py","file_name":"HelperCvxMiniDeploy.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"467014971","text":"######################################################################\n## Tyler Gardner\n##\n## Pipeline to fit binary orbits\n## and search for additional companions\n##\n## For binary orbits from MIRCX/GRAVITY\n##\n######################################################################\n\nfrom lmfit import minimize, Minimizer, Parameters, Parameter, report_fit\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nfrom tqdm import tqdm\nimport matplotlib.cm as cm\nfrom read_data import read_data,read_wds,read_orb6\nfrom astrometry_model import astrometry_model,triple_model,lnlike,lnprior,lnpost,create_init\nfrom orbit_plotting import orbit_model,triple_orbit_model\nfrom astroquery.simbad import Simbad\nfrom astropy.coordinates import SkyCoord\n\n###########################################\n## SETUP PATHS\n###########################################\n\nif os.getcwd()[7:14] == 'tgardne':\n ## setup paths for user\n path = '/Users/tgardne/ARMADA_orbits'\n path_etalon = '/Users/tgardne/etalon_epochs/etalon_fits/etalon_factors_fit.txt'\n path_wds = '/Users/tgardne/wds_targets'\n path_orb6 = '/Users/tgardne/catalogs/orb6orbits.sql.txt'\n \nelif os.getcwd()[7:19] == 'adam.scovera':\n ## Adam's path\n path = '/Users/adam.scovera/Documents/UofM/BEPResearch_Data/ARMADA_orbits'\n path_etalon = '/Users/adam.scovera/Documents/UofM/BEPResearch_Data/etalon_factors_fit.txt'\n path_wds = '/Users/adam.scovera/Documents/UofM/BEPResearch_Data/wds_targets'\n path_orb6 = '/Users/adam.scovera/Documents/UofM/BEPResearch_Data/orb6orbits.sql.txt'\n\n###########################################\n## Specify Target\n###########################################\ntarget_hd = input('Target HD #: ')\nquery = Simbad.query_objectids('HD %s'%target_hd)\nfor item in query:\n if 'HIP' in item[0]:\n target = item[0].split()[1]\n print('HIP %s'%target)\n if 'WDS' in item[0]:\n target_wds = item[0][5:15]\n print('WDS %s'%target_wds)\n\n\n###########################################\n## Read in ARMADA data\n###########################################\nweight=1\nfilepath = input('Path to file: ')\nfile = open(filepath)\nt,p,theta,error_maj,error_min,error_pa,error_deg = read_data(file,weight)\nfile.close()\n\n### correct PAs based on precession\ncoord = SkyCoord.from_name(\"HD %s\"%target_hd,parse=True)\nra = coord.ra.value*np.pi/180\ndec = coord.dec.value*np.pi/180\n\n###########################################\n## Apply etalon correction\n###########################################\nfile=open(path_etalon)\nmjd_etalon=[]\nf_etalon=[]\nfor line in file.readlines():\n if line.startswith('#'):\n continue\n mjd_etalon.append(float(line.split()[0]))\n f_etalon.append(float(line.split()[1]))\nfile.close()\nmjd_etalon=np.array(mjd_etalon)\nf_etalon=np.array(f_etalon)\n\netalon_factor=[]\nfor i in t:\n idx = np.where(abs(i-mjd_etalon)==min(abs(i-mjd_etalon)))\n if min(abs(i-mjd_etalon))>0.5:\n print('Closest factor for %s is %s days away'%(i,min(abs(i-mjd_etalon))))\n f = f_etalon[idx][0]\n etalon_factor.append(f)\netalon_factor=np.array(etalon_factor)\n\nprint(' date etalon factor')\nfor i,j in zip(t,etalon_factor):\n print(i,j)\n\n## apply etalon correction\netalon = input('Apply etalon correction? (y/n) ')\nvlti = input('Add indices for vlti (y/n)? ')\nif vlti=='y':\n vlti_idx = input('enter indices (e.g. 1 2 3): ').split(' ')\n vlti_idx = np.array([int(i) for i in vlti_idx])\nelse:\n vlti_idx = np.array([])\n\nif etalon=='y':\n print('Applying etalon correction')\n if len(vlti_idx)>0:\n etalon_factor[vlti_idx] = 1.0\n p = p/etalon_factor\nelse:\n print('No etalon correction applied')\nxpos=p*np.sin(theta)\nypos=p*np.cos(theta)\n\n\n###########################################\n## Read in WDS data - and plot to check\n###########################################\nfile=open(os.path.expanduser(\"%s/wds%s.txt\"%(path_wds,target_wds)))\nweight = 10\ndtype = 'S'\n\nt_wds,p_wds,theta_wds,error_maj_wds,error_min_wds,error_pa_wds,error_deg_wds = read_wds(file,weight,dtype)\nprint('Number of WDS data points = %s'%len(p_wds))\n\n## correct WDS for PA\ntheta_wds -= (0.00557*np.sin(ra)/np.cos(dec)*((t_wds-51544.5)/365.25))/180*np.pi\n\nxpos_wds=p_wds*np.sin(theta_wds)\nypos_wds=p_wds*np.cos(theta_wds)\nidx = np.argmin(t)\n\nplt.plot(xpos_wds,ypos_wds,'o',label='WDS')\nplt.plot(xpos_wds[0],ypos_wds[0],'*')\nplt.plot(xpos[idx],ypos[idx],'*')\nplt.plot(xpos,ypos,'+',label='ARMADA')\nplt.plot(0,0,'*')\nplt.gca().invert_xaxis()\nplt.title('All Data')\nplt.xlabel('dra (mas)')\nplt.ylabel('ddec (mas)')\nplt.legend()\nplt.show()\n\nflip = input('Flip WDS data? (y/n): ')\nif flip=='y':\n xpos_wds=-p_wds*np.sin(theta_wds)\n ypos_wds=-p_wds*np.cos(theta_wds)\n plt.plot(xpos_wds,ypos_wds,'o',label='WDS')\n plt.plot(xpos_wds[0],ypos_wds[0],'*')\n plt.plot(xpos[idx],ypos[idx],'*')\n plt.plot(xpos,ypos,'+',label='ARMADA')\n plt.plot(0,0,'*')\n plt.gca().invert_xaxis()\n plt.title('All Data')\n plt.xlabel('dra (mas)')\n plt.ylabel('ddec (mas)')\n plt.legend()\n plt.show()\n\n better = input('Flip data back to original? (y/n): ')\n if better=='y':\n xpos_wds=p_wds*np.sin(theta_wds)\n ypos_wds=p_wds*np.cos(theta_wds)\n\n###########################################\n## Get an estimate of the orbital parameters\n###########################################\ntry:\n a,P,e,inc,omega,bigomega,T = read_orb6(target,path_orb6)\nexcept:\n print('No elements found in ORB6')\n \nself_params = input('Input own params?')\nif self_params=='y':\n a = float(input('a (mas): '))\n P = float(input('P (year): '))*365.25\n e = float(input('ecc : '))\n inc = float(input('inc (deg): '))*np.pi/180\n omega = float(input('omega (deg): '))*np.pi/180\n bigomega = float(input('bigomega (deg): '))*np.pi/180\n T = float(input('T (mjd): '))\n\n###########################################\n## Combined WDS+ARMADA for fitting\n###########################################\nxpos_all = np.concatenate([xpos,xpos_wds])\nypos_all = np.concatenate([ypos,ypos_wds])\nt_all = np.concatenate([t,t_wds])\nerror_maj_all = np.concatenate([error_maj,error_maj_wds])\nerror_min_all = np.concatenate([error_min,error_min_wds])\nerror_pa_all = np.concatenate([error_pa,error_pa_wds])\nerror_deg_all = np.concatenate([error_deg,error_deg_wds])\n\n##########################################\n## Function for fitting/plotting data\n#########################################\ndef ls_fit(params,xp,yp,tp,emaj,emin,epa):\n #do fit, minimizer uses LM for least square fitting of model to data\n minner = Minimizer(astrometry_model, params, fcn_args=(xp,yp,tp,\n emaj,emin,epa),\n nan_policy='omit')\n result = minner.minimize()\n # write error report\n print(report_fit(result))\n\n ## plot fit\n a_start = result.params['a']\n P_start = result.params['P']\n e_start = result.params['e']\n inc_start = result.params['inc']\n w_start = result.params['w']\n bigw_start = result.params['bigw']\n T_start = result.params['T']\n\n ra,dec,rapoints,decpoints = orbit_model(a_start,e_start,inc_start,\n w_start,bigw_start,P_start,\n T_start,t_all)\n fig,ax=plt.subplots()\n ax.plot(xpos_all[len(xpos):], ypos_all[len(xpos):], 'o', label='WDS')\n ax.plot(xpos,ypos,'o', label='ARMADA')\n ax.plot(0,0,'*')\n ax.plot(ra, dec, '--',color='g')\n #plot lines from data to best fit orbit\n i=0\n while i<len(decpoints):\n x=[xpos_all[i],rapoints[i]]\n y=[ypos_all[i],decpoints[i]]\n ax.plot(x,y,color=\"black\")\n i+=1\n ax.set_xlabel('milli-arcsec')\n ax.set_ylabel('milli-arcsec')\n ax.invert_xaxis()\n ax.axis('equal')\n ax.set_title('HD%s Outer Orbit'%target_hd)\n plt.legend()\n plt.show()\n\n return result\n\n###########################################\n## Do a least-squares fit\n###########################################\nparams = Parameters()\nparams.add('w', value= omega, min=0, max=2*np.pi)\nparams.add('bigw', value= bigomega, min=0, max=2*np.pi)\nparams.add('inc', value= inc, min=0, max=2*np.pi)\nparams.add('e', value= e, min=0, max=0.99)\nparams.add('a', value= a, min=0)\nparams.add('P', value= P, min=0)\nparams.add('T', value= T, min=0)\n\nresult = ls_fit(params,xpos_all,ypos_all,t_all,error_maj_all,error_min_all,error_pa_all)\n\n#############################################\n## Filter through bad WDS points\n#############################################\ndef on_click_remove(event):\n bad_x = event.xdata\n bad_y = event.ydata\n diff = np.sqrt((xpos_all-bad_x)**2+(ypos_all-bad_y)**2)\n idx = np.nanargmin(diff)\n xpos_all[idx] = np.nan\n ypos_all[idx] = np.nan\n\n ax.cla()\n ax.plot(xpos_all[len(xpos):], ypos_all[len(xpos):], 'o', label='WDS')\n ax.plot(xpos,ypos,'o', label='ARMADA')\n ax.plot(0,0,'*')\n ax.plot(ra, dec, '--',color='g')\n #plot lines from data to best fit orbit\n i=0\n while i<len(decpoints):\n x=[xpos_all[i],rapoints[i]]\n y=[ypos_all[i],decpoints[i]]\n ax.plot(x,y,color=\"black\")\n i+=1\n ax.set_xlabel('milli-arcsec')\n ax.set_ylabel('milli-arcsec')\n ax.invert_xaxis()\n ax.axis('equal')\n ax.set_title('Click to REMOVE points')\n plt.legend()\n plt.draw()\n\ndef on_click_flip(event):\n bad_x = event.xdata\n bad_y = event.ydata\n diff = np.sqrt((xpos_all-bad_x)**2+(ypos_all-bad_y)**2)\n idx = np.nanargmin(diff)\n xpos_all[idx] = -xpos_all[idx]\n ypos_all[idx] = -ypos_all[idx]\n\n ax.cla()\n ax.plot(xpos_all[len(xpos):], ypos_all[len(xpos):], 'o', label='WDS')\n ax.plot(xpos,ypos,'o', label='ARMADA')\n ax.plot(0,0,'*')\n ax.plot(ra, dec, '--',color='g')\n #plot lines from data to best fit orbit\n i=0\n while i<len(decpoints):\n x=[xpos_all[i],rapoints[i]]\n y=[ypos_all[i],decpoints[i]]\n ax.plot(x,y,color=\"black\")\n i+=1\n ax.set_xlabel('milli-arcsec')\n ax.set_ylabel('milli-arcsec')\n ax.invert_xaxis()\n ax.axis('equal')\n ax.set_title('Click to FLIP points')\n plt.legend()\n plt.draw()\n\nfilter_wds = input('Remove/flip any WDS data? (y/n)')\nwhile filter_wds == 'y':\n a_start = result.params['a']\n P_start = result.params['P']\n e_start = result.params['e']\n inc_start = result.params['inc']\n w_start = result.params['w']\n bigw_start = result.params['bigw']\n T_start = result.params['T']\n ra,dec,rapoints,decpoints = orbit_model(a_start,e_start,inc_start,\n w_start,bigw_start,P_start,\n T_start,t_all)\n fig,ax=plt.subplots()\n ax.plot(xpos_all[len(xpos):], ypos_all[len(xpos):], 'o', label='WDS')\n ax.plot(xpos,ypos,'o', label='ARMADA')\n ax.plot(0,0,'*')\n ax.plot(ra, dec, '--',color='g')\n #plot lines from data to best fit orbit\n i=0\n while i<len(decpoints):\n x=[xpos_all[i],rapoints[i]]\n y=[ypos_all[i],decpoints[i]]\n ax.plot(x,y,color=\"black\")\n i+=1\n ax.set_xlabel('milli-arcsec')\n ax.set_ylabel('milli-arcsec')\n ax.invert_xaxis()\n ax.axis('equal')\n ax.set_title('Click to FLIP points')\n plt.legend()\n cid = fig.canvas.mpl_connect('button_press_event', on_click_flip)\n plt.show()\n fig.canvas.mpl_disconnect(cid)\n plt.close()\n\n fig,ax=plt.subplots()\n ax.plot(xpos_all[len(xpos):], ypos_all[len(xpos):], 'o', label='WDS')\n ax.plot(xpos,ypos,'o', label='ARMADA')\n ax.plot(0,0,'*')\n ax.plot(ra, dec, '--',color='g')\n #plot lines from data to best fit orbit\n i=0\n while i<len(decpoints):\n x=[xpos_all[i],rapoints[i]]\n y=[ypos_all[i],decpoints[i]]\n ax.plot(x,y,color=\"black\")\n i+=1\n ax.set_xlabel('milli-arcsec')\n ax.set_ylabel('milli-arcsec')\n ax.invert_xaxis()\n ax.axis('equal')\n ax.set_title('Click to REMOVE points')\n plt.legend()\n cid = fig.canvas.mpl_connect('button_press_event', on_click_remove)\n plt.show()\n fig.canvas.mpl_disconnect(cid)\n plt.close()\n\n\n params = Parameters()\n params.add('w', value= omega, min=0, max=2*np.pi)\n params.add('bigw', value= bigomega, min=0, max=2*np.pi)\n params.add('inc', value= inc, min=0, max=2*np.pi)\n params.add('e', value= e, min=0, max=0.99)\n params.add('a', value= a, min=0)\n params.add('P', value= P, min=0)\n params.add('T', value= T, min=0)\n\n result = ls_fit(params,xpos_all,ypos_all,t_all,error_maj_all,error_min_all,error_pa_all)\n filter_wds = input('Remove more data? (y/n)')\n\n##########################################\n## Save Plots\n##########################################\nresids_armada = astrometry_model(result.params,xpos,ypos,t,error_maj,\n error_min,error_pa)\nndata_armada = 2*sum(~np.isnan(xpos))\nchi2_armada = np.nansum(resids_armada**2)/(ndata_armada-len(result.params))\nprint('-'*10)\nprint('chi2 armada = %s'%chi2_armada)\nprint('-'*10)\n\ndirectory='%s/HD%s_scale/'%(path,target_hd)\nif not os.path.exists(directory):\n os.makedirs(directory)\n\nscale=1\nif chi2_armada<1.0:\n scale=1/np.sqrt(chi2_armada)\na_start = result.params['a']\nP_start = result.params['P']\ne_start = result.params['e']\ninc_start = result.params['inc']\nw_start = result.params['w']\nbigw_start = result.params['bigw']\nT_start = result.params['T']\nra,dec,rapoints,decpoints = orbit_model(a_start,e_start,inc_start,\n w_start,bigw_start,P_start,\n T_start,t_all)\nfig,ax=plt.subplots()\nax.plot(xpos_all[len(xpos):], ypos_all[len(xpos):], 'o', label='WDS')\nax.plot(xpos,ypos,'o', label='ARMADA')\nax.plot(0,0,'*')\nax.plot(ra, dec, '--',color='g')\n#plot lines from data to best fit orbit\ni=0\nwhile i<len(decpoints):\n x=[xpos_all[i],rapoints[i]]\n y=[ypos_all[i],decpoints[i]]\n ax.plot(x,y,color=\"black\")\n i+=1\nax.set_xlabel('milli-arcsec')\nax.set_ylabel('milli-arcsec')\nax.invert_xaxis()\nax.axis('equal')\nax.set_title('HD%s Outer Orbit'%target_hd)\nplt.legend()\nplt.savefig('%s/HD%s_outer_leastsquares.pdf'%(directory,target_hd))\nplt.close()\n\n## plot resids for ARMADA\nfig,ax=plt.subplots()\nxresid = xpos - rapoints[:len(xpos)]\nyresid = ypos - decpoints[:len(ypos)]\n\n#need to measure error ellipse angle east of north\nfor ras, decs, w, h, angle in zip(xresid,yresid,error_maj/scale,error_min/scale,error_deg):\n ellipse = Ellipse(xy=(ras, decs), width=2*w, height=2*h, \n angle=90-angle, facecolor='none', edgecolor='black')\n ax.add_patch(ellipse)\n\nax.plot(xresid, yresid, 'o')\nax.plot(0,0,'*')\nax.set_xlabel('milli-arcsec')\nax.set_ylabel('milli-arcsec')\nax.invert_xaxis()\nax.axis('equal')\nax.set_title('HD%s Resids'%target_hd)\nplt.savefig('%s/HD%s_resid_leastsquares.pdf'%(directory,target_hd))\nplt.close()\n\n## residuals\nresids = np.sqrt(xresid**2 + yresid**2)\nresids_median = np.around(np.median(resids)*1000,2)\nprint('-'*10)\nprint('Mean residual = %s micro-as'%resids_median)\nprint('-'*10)\n\n## Save txt file with best orbit\nf = open(\"%s/%s_orbit_ls.txt\"%(directory,target_hd),\"w+\")\nf.write(\"# P(d) a(mas) e i(deg) w(deg) W(deg) T(mjd) mean_resid(mu-as)\\r\\n\")\nf.write(\"%s %s %s %s %s %s %s %s\"%(P_start.value,a_start.value,e_start.value,\n inc_start.value*180/np.pi,w_start.value*180/np.pi,\n bigw_start.value*180/np.pi,T_start.value,\n resids_median))\nf.close()\n\n##########################################\n## Grid Search for Scale factor\n##########################################\nscale = np.linspace(0.99,1.01,1000)\n\nprint('Grid Searching over scale factor')\nparams_outer=[]\nchi2 = []\nfor f in tqdm(scale):\n params = Parameters()\n params.add('w', value= w_start, min=0, max=2*np.pi)\n params.add('bigw', value= bigw_start, min=0, max=2*np.pi)\n params.add('inc', value= inc_start, min=0, max=2*np.pi)\n params.add('e', value= e_start, min=0, max=0.99)\n params.add('a', value= a_start, min=0)\n params.add('P', value= P_start, min=0)\n params.add('T', value= T_start, min=0)\n #params.add('pscale', value=1)\n\n lst = np.array([1.0]*len(xpos_all))\n lst[vlti_idx] = f\n\n #do fit, minimizer uses LM for least square fitting of model to data\n minner = Minimizer(astrometry_model, params, fcn_args=(xpos_all*lst,ypos_all*lst,t_all,\n error_maj_all,error_min_all,\n error_pa_all),\n nan_policy='omit')\n result = minner.minimize()\n params_outer.append([result.params['P'],result.params['a'],result.params['e'],result.params['w']\n ,result.params['bigw'],result.params['inc'],result.params['T']])\n chi2.append(result.redchi)\nparams_outer=np.array(params_outer)\nchi2 = np.array(chi2)\n\nidx = np.where(chi2==min(chi2))\nscale_best = scale[idx]\n\nplt.plot(scale,1/chi2,'o-')\nplt.xlabel('Scale factor')\nplt.ylabel('1/chi2')\nplt.title('Best Factor = %s'%scale_best)\nplt.savefig('%s/HD%s_chi2_scale.pdf'%(directory,target_hd))\nplt.close()\n\nprint('Best factor = %s'%scale_best)","sub_path":"compute_scale.py","file_name":"compute_scale.py","file_ext":"py","file_size_in_byte":17164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"417052073","text":"#!/usr/bin/env python3\r\n\r\n# Authors: M269 Module Team\r\n# Date: 20/11/12\r\n\r\n\r\ndef nameSearch(names, target):\r\n for name in names:\r\n if name == target:\r\n return True\r\n return False\r\n\r\n\r\ndef findHighest(intList):\r\n highest = intList[0]\r\n for item in intList:\r\n if item > highest:\r\n highest = item\r\n return highest\r\n\r\n\r\ndef gradeStudents(names, marks):\r\n results = []\r\n for i in range(len(names)):\r\n results.append(names[i])\r\n if marks[i] >= 70:\r\n results.append('A')\r\n elif marks[i] < 70 and marks[i] >= 50:\r\n results.append('B')\r\n elif marks[i] < 50 and marks[i] >= 30:\r\n results.append('C')\r\n else:\r\n results.append('F')\r\n return results\r\n\r\n\r\nnumList = [5, 2, 21, 8, 20, 36, 1, 11, 13, 4, 17]\r\nnameList = ['Smith', 'Jones', 'Turing', 'Bloggs', 'Meyer', 'Hampden']\r\nmarkList = [30, 40, 50, 60, 70, 18]\r\nprint()\r\nprint('Testing nameSearch()')\r\nprint(nameSearch(nameList, 'Turing'))\r\nprint(nameSearch(nameList, 'Fred'))\r\nprint('______________________________')\r\n\r\nprint()\r\nprint('Testing findHighest()')\r\nprint(findHighest(numList))\r\nprint('______________________________')\r\n\r\nprint()\r\nprint('Testing gradeStudents()')\r\nprint(gradeStudents(nameList, markList))\r\n","sub_path":"examples/M269_Unit_2/Python_activity_2.4/Python_activity_2.4.py","file_name":"Python_activity_2.4.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"448343791","text":"\"\"\" Scene detection on video sequence using different algorithms\n\n\n\"\"\"\nimport sys\nimport cv2\nfrom pprint import pprint\n\nimport detectionalgo as algo\nimport util\n\n\nclass Video:\n def __init__(self, filename):\n self.cap = cv2.VideoCapture()\n self.cap.open(filename)\n if not self.cap.isOpened():\n raise ValueError(filename)\n self.detection_algo = getattr(algo, 'naive')\n # print(self.get_dimensions())\n self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n\n def __del__(self):\n self.cap.release()\n\n def set_algo(self, algo_name):\n try:\n self.detection_algo = getattr(algo, algo_name)\n except:\n sys.exit('algorithm not found')\n\n def get_cuts(self, **kwargs) -> []:\n \"\"\"Compute the time of the cuts in the video,\n :return a list of the frame numbers where cut occurs\n \"\"\"\n cuts = self.detection_algo(self.cap, **kwargs)\n return cuts\n\n\ndef run_algo(video, algo, threshold) -> None:\n video.set_algo(algo)\n cuts = video.get_cuts(threshold=threshold)\n report(algo, cuts)\n\n\ndef report(algo, cuts) -> None:\n print(\"*\" * 40)\n print(\"Using algo: '{}'\".format(algo))\n # print(cuts)\n print(\"Cross checking with ground truth:\")\n util.verify_result(cuts, 10)\n false_pos = util.count_false_positives(cuts)\n print(\"false positives : {} \".format(len(false_pos)) + str(false_pos))\n\n\ndef main():\n if len(sys.argv) < 2:\n print(\"Error - file name must be specified as first argument.\")\n return\n\n filename = sys.argv[1]\n try:\n video = Video(filename)\n except ValueError:\n print(\"Could not open {}\", filename)\n return\n\n # run_algo(video, 'naive', None)\n # run_algo(video, 'fade_cuts', 100)\n # run_algo(video, 'edge_detection_cached', None)\n run_algo(video, 'edge_detection', None)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/scenedetection.py","file_name":"scenedetection.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"325875778","text":"from StoredObject import *\n\nclass Photo(StoredObject):\n def __init__ (self, id, pic, small_pic):\n self.id = id\n self.pic = pic\n self.small_pic = small_pic\n\n\nclass PhotosUploadInfo:\n def __init__(self, aid, upload_url = None, upload_hash = None, upload_rhash = None):\n self.upload_url = upload_url\n self.upload_hash = upload_hash\n self.upload_rhash = upload_rhash\n self.aid = aid\n\nclass Photos:\n def __init__(self, total, photos, ts = None, upload_info = None):\n self.total = total\n self.photos = photos\n self.ts = ts\n self.upload = upload_info\n","sub_path":"userapi/Photo.py","file_name":"Photo.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"42456040","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 26 09:20:51 2018\n稀疏滤波器\n@author: John Kwok\n\"\"\"\n#%%\nimport numpy as np\nimport tensorflow as tf\nclass SparseFilter:\n '稀疏滤波器类'\n\n '''\n 构造函数:初始化各个参数,以及相关tf运算\n X-输入的数据,每个列向量为一个样本,行数为样本原始特征数,列数为样本数\n D-目标特征数\n '''\n def __init__(self,X,D):\n self.X = X\n # print(X.shape[0])\n\n self.W = tf.Variable(tf.truncated_normal(shape=(X.shape[0],D),\n stddev=0.1,\n dtype=tf.float64),\n name=\"SF_W\")\n print(self.W.shape)\n F = tf.matmul(self.W,self.X,transpose_a = True)\n Fs = tf.sqrt(tf.square(F) + 1e-8)\n #Fs = tf.log(tf.square(F) + 1)\n L2Row = tf.norm(Fs,\n ord=2,\n axis = 1,\n keep_dims=True)\n Fs = tf.div(Fs,L2Row)\n L2Col = tf.norm(Fs,\n ord = 2,\n axis = 0,\n keep_dims=True)\n Fs = tf.div(Fs,L2Col)\n self.cost = tf.norm(Fs,\n ord=1,\n keep_dims=True)\n self.opt = tf.train.AdamOptimizer(learning_rate=100,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-08,\n use_locking=False,\n name='Adam').minimize(self.cost)\n\n '''训练函数:用于训练'''\n def train(self,numIter):\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(numIter):\n sess.run(self.opt)\n print(sess.run(self.cost))\n return sess.run(self.W) \n \n \n#%%\n \n#%%\n'''\n载入文件插值、对齐好的数据文件,并返回训练集、测试集\n参数:\n dataPath 数据文件地址\n test_size 测试集占比\n输出:\n X_train,X_test, y_train, y_test\n shape = (6,300)\n'''\nfrom sklearn.model_selection import train_test_split\ndef getTrainTestSet(dataPath = \"JustifiedData.npy\",test_size = 0.1):\n X = []\n Y = []\n dataSet = np.load(dataPath)\n for data in dataSet:\n S = data[\"Acc\"]\n S = np.concatenate((S,data[\"Gyr\"]),axis = 0)\n #S = S.reshape((6,300))\n X.append(S)\n Y.append(data[\"Label\"])\n# print(np.array(X).shape)\n# print(np.array(Y).shape)\n X = np.array(X)\n Y = np.array(Y)\n# X_train, X_test, y_train, y_test\n return train_test_split(X,Y,test_size = test_size,random_state = 0)\n'''\n数据预处理函数\n1.特征构造\n2.标准化\n'''\ndef dataProcess(data,logPrint = True):\n if(logPrint):\n print(\"processing...\")\n '''\n # 特征构造\n x_2 = np.power(data, 2)\n x_3 = np.power(data, 3)\n sin = np.sin(data)\n cos = np.cos(data)\n data = np.concatenate((data,x_2,x_3,sin,cos),axis = 1)\n if(logPrint):\n print(\"特征构造完毕!\")\n '''\n # 标准化\n #print(data.shape)\n mean = np.mean(data,axis = (1,2))\n #std = np.std(data,axis = (1,2))\n mean = mean[:,np.newaxis,np.newaxis]\n #std = std[:,np.newaxis,np.newaxis]\n #data = (data-mean)/std\n data = data-mean\n if(logPrint):\n #print(\"数据标准化完毕!(未去标准差)\")\n #print(\"数据形状:\")\n print(data.shape)\n return data\n\n\nX_train, X_test, y_train, y_test = getTrainTestSet()\nX_train = dataProcess(X_train)\nX_test = dataProcess(X_test)\n#print(\"数据初始化完毕!\")\n\n#%%\n\nX = X_train.reshape(-1,1800).T\nsf = SparseFilter(X,32*32)\nW = sf.train(100)\na = np.transpose(W).dot(X)\nnp.save(\"SFW.npy\",W)\n#%%\nprint(\"finished\")\nprint(W.shape)\n \n \n\n\n\n \n#%%\n'''\n# 测试\n#X = np.random.randn(20,10)\nsf = SparseFilter(X,32*32)\nW = sf.train(100)\n\na = np.transpose(W).dot(X)\nprint(a.shape)\n#%%\nprint(np.transpose(W).dtype)\n \n\n#%%\n'''\n'''\ntf.matmul() 为矩阵乘法\n\ntf.multiply() 为矩阵点乘\n\nnp.dot() 为矩阵乘法\n\nnp.multiply() 为矩阵点乘\n'''\n'''\na = np.array([[1,2,3],[4,5,6]])\nb = np.array([[1,2,3],[4,5,6]])\nc = np.array([[1,2],[3,4],[3,4]])\nprint(np.dot(a,c))\nprint(np.multiply(a,b))\n'''","sub_path":"src/SparseFilter.py","file_name":"SparseFilter.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"306467806","text":"\"\"\"\nCopyright (C) 2016 Skylark Drones\nAllSystemsGo Checklist Page\n\"\"\"\n\nfrom PyQt5.QtWidgets import (QHBoxLayout, QWidget, QVBoxLayout, QScrollArea, QCheckBox, QFrame, QMessageBox)\nfrom PyQt5.QtSql import QSqlQuery\nfrom . import CommonWidgets as CM\n\n\nclass AllSystemsGo(QWidget):\n\n def __init__(self, MDLA, stack, statusBar, sessionDatabase):\n super().__init__()\n\n self.dirty = False\n\n contentPad = 20\n checkBoxWidth = self.width() - 35\n\n MDLA.sessionDatabaseChanged.connect(lambda: self.clearSessionData(staticUIElements))\n\n self.fuselageCheck = QCheckBox(\"Fuselage\")\n self.wingCheck = QCheckBox(\"Wing\")\n self.wingExtnCheck = QCheckBox(\"Wing Extn\")\n self.tailCheck = QCheckBox(\"Tail\")\n self.tailPinCheck = QCheckBox(\"Tail Pin\")\n self.servoCheck = QCheckBox(\"Servo\")\n self.motorCheck = QCheckBox(\"Motor\")\n self.propellerCheck = QCheckBox(\"Propeller\")\n self.airspeedCheck = QCheckBox(\"Airspeed Sensor\")\n self.pixhawkCheck = QCheckBox(\"Pixhawk Connection\")\n self.domeCheck = QCheckBox(\"Dome\")\n self.carbonRodCheck = QCheckBox(\"Carbon Rods\")\n self.landingGearCheck = QCheckBox(\"Landing Gear\")\n\n airframePhysicalGroup = CM.createChecklistGroup(\n [self.fuselageCheck, self.wingCheck, self.wingExtnCheck, self.tailCheck, self.tailPinCheck, self.servoCheck,\n self.motorCheck, self.propellerCheck, self.airspeedCheck, self.pixhawkCheck, self.domeCheck,\n self.carbonRodCheck, self.landingGearCheck],\n \"Airframe Physical Check\",\n checkBoxWidth\n )\n\n self.physicalCheck = QCheckBox(\"Physical Check\")\n self.settingsCheck = QCheckBox(\"Settings (ISO, Aperture, Exposure)\")\n self.zoomCheck = QCheckBox(\"Zoom Constraint\")\n self.sdCheck = QCheckBox(\"SD Card\")\n self.batteryCheck = QCheckBox(\"Battery and cables\")\n\n cameraGroup = CM.createChecklistGroup(\n [self.physicalCheck, self.settingsCheck, self.zoomCheck, self.sdCheck, self.batteryCheck],\n \"Camera Check\",\n checkBoxWidth\n )\n\n self.assembleCheck = QCheckBox(\"Assemble\")\n self.rfdCheck = QCheckBox(\"RFD Connectivity\")\n self.modeCheck = QCheckBox(\"Mode Switch\")\n self.motorThrottleCheck = QCheckBox(\"Motor Throttle\")\n self.powerCheck = QCheckBox(\"Power Module\")\n self.triggerCheck = QCheckBox(\"Trigger Check\")\n self.cgCheck = QCheckBox(\"CG\")\n self.servoTempCheck = QCheckBox(\"Servo Temperature\")\n self.controlSurfaceCheck = QCheckBox(\"Control Surface\")\n self.stabilizeCheck = QCheckBox(\"Stabilize\")\n self.airspeedCalibrateCheck = QCheckBox(\"Airspeed Calibration\")\n\n controlsGroup = CM.createChecklistGroup(\n [self.assembleCheck, self.rfdCheck, self.modeCheck, self.motorThrottleCheck, self.powerCheck,\n self.triggerCheck, self.cgCheck, self.servoTempCheck, self.controlSurfaceCheck, self.stabilizeCheck,\n self.airspeedCalibrateCheck],\n \"Controls Check\",\n checkBoxWidth\n )\n\n staticUIElements = [\n {'Checkbox': self.fuselageCheck, 'Row': 'fuselageCheck'},\n {'Checkbox': self.wingCheck, 'Row': 'wingCheck'},\n {'Checkbox': self.wingExtnCheck, 'Row': 'wingExtnCheck'},\n {'Checkbox': self.tailCheck, 'Row': 'tailCheck'},\n {'Checkbox': self.tailPinCheck, 'Row': 'tailPinCheck'},\n {'Checkbox': self.servoCheck, 'Row': 'servoCheck'},\n {'Checkbox': self.motorCheck, 'Row': 'motorCheck'},\n {'Checkbox': self.propellerCheck, 'Row': 'propellerCheck'},\n {'Checkbox': self.airspeedCheck, 'Row': 'airspeedCheck'},\n {'Checkbox': self.pixhawkCheck, 'Row': 'pixhawkCheck'},\n {'Checkbox': self.domeCheck, 'Row': 'domeCheck'},\n {'Checkbox': self.carbonRodCheck, 'Row': 'carbonRodCheck'},\n {'Checkbox': self.landingGearCheck, 'Row': 'landingGearCheck'},\n {'Checkbox': self.physicalCheck, 'Row': 'physicalCheck'},\n {'Checkbox': self.settingsCheck, 'Row': 'settingsCheck'},\n {'Checkbox': self.zoomCheck, 'Row': 'zoomCheck'},\n {'Checkbox': self.sdCheck, 'Row': 'sdCheck'},\n {'Checkbox': self.batteryCheck, 'Row': 'batteryCheck'},\n {'Checkbox': self.assembleCheck, 'Row': 'assembleCheck'},\n {'Checkbox': self.rfdCheck, 'Row': 'rfdCheck'},\n {'Checkbox': self.modeCheck, 'Row': 'modeCheck'},\n {'Checkbox': self.motorThrottleCheck, 'Row': 'motorThrottleCheck'},\n {'Checkbox': self.powerCheck, 'Row': 'powerCheck'},\n {'Checkbox': self.triggerCheck, 'Row': 'triggerCheck'},\n {'Checkbox': self.cgCheck, 'Row': 'cgCheck'},\n {'Checkbox': self.servoTempCheck, 'Row': 'servoTempCheck'},\n {'Checkbox': self.controlSurfaceCheck, 'Row': 'controlSurfaceCheck'},\n {'Checkbox': self.stabilizeCheck, 'Row': 'stabilizeCheck'},\n {'Checkbox': self.airspeedCalibrateCheck,'Row': 'airspeedCalibrateCheck'}\n ]\n\n for element in staticUIElements:\n element['Checkbox'].stateChanged.connect(self.updateDirty)\n\n allSystemsGoChecklists = QVBoxLayout()\n allSystemsGoChecklists.setSpacing(20)\n allSystemsGoChecklists.addWidget(airframePhysicalGroup[0])\n allSystemsGoChecklists.addWidget(cameraGroup[0])\n allSystemsGoChecklists.addWidget(controlsGroup[0])\n\n contentArea = QWidget()\n contentArea.setLayout(allSystemsGoChecklists)\n\n mainScrollView = QScrollArea()\n mainScrollView.setFrameStyle(QFrame.NoFrame)\n mainScrollView.setWidget(contentArea)\n\n # Back button (to go back to home page)\n self.backButton = CM.createButton(\"Back\", tool_tip=\"Go back to main page\", min_height=40)\n self.backButton.clicked.connect(lambda: self.goHome(stack, MDLA, statusBar, sessionDatabase, staticUIElements))\n\n # Save button\n self.saveButton = CM.createButton(\"Save\", min_height=40)\n self.saveButton.clicked.connect(lambda: self.saveSessionData(MDLA, statusBar, sessionDatabase, staticUIElements))\n\n self.mainButtonsHBox = QHBoxLayout()\n self.mainButtonsHBox.setSpacing(10)\n self.mainButtonsHBox.addWidget(self.saveButton)\n self.mainButtonsHBox.addWidget(self.backButton)\n\n layout = QVBoxLayout()\n layout.setSpacing(20)\n layout.setContentsMargins(contentPad, contentPad, contentPad, contentPad)\n layout.addWidget(mainScrollView)\n layout.addItem(self.mainButtonsHBox)\n\n self.loadSessionData(MDLA, sessionDatabase, staticUIElements)\n self.setLayout(layout)\n\n def goHome(self, stack, MDLA, statusBar, sessionDatabase, staticUIElements):\n if self.dirty:\n buttonPressed = QMessageBox.question(self, \"Save changes?\",\n \"\"\"\n <p>Do you want to save the changes before leaving this page?\n \"\"\", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)\n if buttonPressed == QMessageBox.No:\n self.clearSessionData(staticUIElements)\n self.loadSessionData(MDLA, sessionDatabase, staticUIElements)\n else:\n self.saveSessionData(MDLA, statusBar, sessionDatabase, staticUIElements)\n\n stack.setCurrentIndex(0)\n\n def updateDirty(self):\n self.dirty = True\n\n def clearSessionData(self, staticUIElements):\n \"\"\"\n Clear All systems go page UI\n\n Args:\n :param staticUIElements: Static UI elements properties (Array Dict)\n \"\"\"\n for element in staticUIElements:\n element['Checkbox'].setChecked(False)\n\n def loadSessionData(self, MDLA, sessionDatabase, staticUIElements):\n \"\"\"\n Read states of static UI elements from local session database\n\n Args:\n :param MDLA: Mock Drone Log Analyser object (QObject)\n :param sessionDatabase: Local session database object (QSqlDatabase)\n :param staticUIElements: Static UI elements properties (Array Dict)\n \"\"\"\n sessionQuery = QSqlQuery(sessionDatabase)\n sessionQuery.setForwardOnly(True)\n\n for element in staticUIElements:\n sessionQuery.exec_(\"\"\"SELECT {} FROM All_Systems_Go WHERE id=1\"\"\".format(element['Row']))\n sessionQuery.seek(0)\n\n if sessionQuery.lastError().text().strip():\n QMessageBox.critical(None, \"Database Error!\",\n \"\"\"\n <p>{} is unable to read some of the data on the All Systems Go page due to a database error. Please\n <a href=\"https://github.com/krnekhelesh/Drone-Log-Formatter/issues/new\">report a bug</a>\n on the Github project page to inform the developers.\n\n <p>{} will still open afterwards.\n\n <p>Error Message: {}\n \"\"\".format(MDLA.applicationName, MDLA.applicationName, sessionQuery.lastError().text()))\n\n if sessionQuery.value(0) is not None:\n element['Checkbox'].setChecked(sessionQuery.value(0))\n\n self.dirty = False\n\n def saveSessionData(self, MDLA, statusBar, sessionDatabase, staticUIElements):\n \"\"\"\n Save states of static UI elements into local session database\n\n Args:\n :param MDLA: Mock Drone Log Analyser object (QObject)\n :param statusBar: Application status bar (QStatusBar)\n :param sessionDatabase: Local session database object (QSqlDatabase)\n :param staticUIElements: Static UI elements properties (Array Dict)\n \"\"\"\n sessionQuery = QSqlQuery(sessionDatabase)\n commandString = \"\"\n\n for element in staticUIElements:\n commandString += element['Row'] + \"=\" + str(element['Checkbox'].checkState()) + \",\"\n\n commandString = commandString[:-1]\n sessionQuery.exec_(\"\"\"UPDATE All_Systems_Go SET {} WHERE id=1\"\"\".format(commandString))\n\n if sessionQuery.lastError().text().strip():\n QMessageBox.critical(self, \"Database Error!\",\n \"\"\"\n <p>{} is unable to save some of the data due to a database error. Please\n <a href=\"https://github.com/krnekhelesh/Drone-Log-Formatter/issues/new\">report a bug</a>\n on the Github project page to inform the developers.\n\n <p>Error Message: {}\n \"\"\".format(MDLA.applicationName, sessionQuery.lastError().text()))\n statusBar.showMessage(\"All Systems Go session not saved!\", 3000)\n else:\n self.dirty = False\n statusBar.showMessage(\"All Systems Go session saved\", 3000)","sub_path":"ui/AllSystemsGo.py","file_name":"AllSystemsGo.py","file_ext":"py","file_size_in_byte":11334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"572719826","text":"\"\"\"Escribir un programa que solicite al usuario el ingreso del nombre de un equipo local con la cantidad de goles\nque metió en un partido, y del nombre de un equipo visitante con la cantidad de goles que metió en el mismo partido.\nLuego, imprimir por pantalla el nombre del ganador o un mensaje indicando que hubo un empate.\n\n Ingrese equipo local: Boca\n Ingrese goles equipo local: 3\n Ingrese equipo local: River\n Ingrese goles equipo visitante: 1\n Boca\n\n Ingrese equipo local: Boca\n Ingrese goles equipo local: 0\n Ingrese equipo local: River\n Ingrese goles equipo visitante: 2\n River\n\n Ingrese equipo local: Boca\n Ingrese goles equipo local:2\n Ingrese equipo local: River\n Ingrese goles equipo visitante: 2\n Empate\"\"\"\n\nequipo_local = input(\"Ingrese equipo local: \")\ngoles_local = int(input(\"Ingrese goles equipo local: \"))\nequipo_visitante = input(\"Ingrese equipo visitante: \")\ngoles_visitante = int(input(\"Ingrese goles equipo visitante: \"))\n\nif goles_local > goles_visitante:\n print(equipo_local)\nelif goles_local < goles_visitante:\n print(equipo_visitante)\nelse:\n print(\"Empate\")","sub_path":"RomanD/ejercicios_rpl/estructuras_basicas/ej_6_quien_gano.py","file_name":"ej_6_quien_gano.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"471337996","text":"def iter_a(number):\n mask = (1 << 16) - 1\n while True:\n number = (number * 16807) % 2_147_483_647\n yield number & mask\n\n\ndef iter_b(number):\n mask = (1 << 16) - 1\n while True:\n number = (number * 48271) % 2_147_483_647\n yield number & mask\n\n\ndef solve(init_a, init_b):\n counter = 0\n for n, (val_a, val_b) in enumerate(zip(iter_a(init_a), iter_b(init_b))):\n if val_a == val_b:\n counter += 1\n if n > 40e6:\n break\n return counter\n\n\nif __name__ == \"__main__\":\n import fileinput\n\n init_a, init_b = (int(line.strip().split()[-1]) for line in fileinput.input())\n print(\n f\"The number of times the generators were equal with starting \"\n f\"values {init_a} and {init_b} where {solve(init_a, init_b)}\"\n )\n","sub_path":"aoc_2017/solutions2017/day15/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"574628259","text":"fruits = [\"apple\", \"cardboard\", \"cheese\", \"grapes\", \"sand\"]\n# if fruits[0] == \"apple\":\n# print(\"Yum!\")\n# elif fruits [0] == \"cardboard\" or fruits[0] == \"sand\":\n# print (\"Yuck!\")\n# else:\n# print(\"Not bad.\")\n# if \"apple\" not in fruits[0]:\n# print(\"Yuck!\")\n\nage= 5\nif age > 0 and age <= 2:\n print(\"baby\")\nif age > 2 and age <= 18:\n print(\"child\")\n\nelse:\n print(\"adult\")\n","sub_path":"python/fruitsfun.py","file_name":"fruitsfun.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"320746867","text":"from collections import defaultdict\nimport symengine as sy\nimport numpy as np\n\n\nclass Variable:\n\n __slots__ = (\n \"data\",\n \"parents\",\n \"local_gradients\",\n \"grad\",\n )\n\n def __init__(self, data, parents=(), local_gradients=()):\n self.data = data\n self.parents = frozenset(parents)\n self.local_gradients = local_gradients\n self.grad = 0.0\n\n def __add__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n data = self.data + other.data\n local_gradients = {self: 1.0, other: 1.0}\n return Variable(\n data=data, parents=(self, other), local_gradients=local_gradients\n )\n\n def __radd__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n return other.__add__(self)\n\n def __mul__(self, other):\n if other is self:\n return self.__pow__(2)\n other = Variable(other) if not isinstance(other, Variable) else other\n data = self.data * other.data\n local_gradients = {self: other.data, other: self.data}\n return Variable(\n data=data, parents=(self, other), local_gradients=local_gradients\n )\n\n def __rmul__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n return other.__mul__(self)\n\n def __neg__(self):\n data = -self.data\n local_gradients = {self: -1.0}\n return Variable(data=data, parents=(self,), local_gradients=local_gradients)\n\n def __sub__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n return self.__add__(-other)\n\n def __rsub__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n return other.__add__(-self)\n\n def __pow__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n data = self.data ** other.data\n local_gradients = {\n self: other.data * (self.data ** (other.data - 1.0)),\n other: sy.log(self.data) * (self.data ** other.data),\n }\n return Variable(\n data=data, parents=(self, other), local_gradients=local_gradients,\n )\n\n def __rpow__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n return other.__pow__(self)\n\n def __truediv__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n return self.__mul__(other.__pow__(-1.0))\n\n def __rtruediv__(self, other):\n other = Variable(other) if not isinstance(other, Variable) else other\n return other.__mul__(self.__pow__(-1.0))\n\n def exp(self):\n data = sy.exp(self.data)\n local_gradients = {self: sy.exp(self.data)}\n return Variable(data=data, parents=(self,), local_gradients=local_gradients)\n\n def log(self):\n data = sy.log(self.data)\n local_gradients = {self: self.data ** (-1.0)}\n return Variable(data=data, parents=(self,), local_gradients=local_gradients)\n\n def sqrt(self):\n return self.__pow__(0.5)\n\n def backward(self):\n self.grad = 1\n for node in self._toposort():\n for parent in node.parents:\n local_grad = node.local_gradients[parent]\n parent.grad += local_grad * node.grad\n\n def _toposort(self):\n postorder = []\n visited = set()\n\n def dfs(node):\n if node.parents and node not in visited:\n visited.add(node)\n for parent in node.parents:\n dfs(parent)\n postorder.append(node)\n\n dfs(self)\n return reversed(postorder)\n\n def __repr__(self):\n return str(self.data)\n\n\ndef _relu(var):\n var = Variable(var) if not isinstance(var, Variable) else var\n data = sy.Piecewise((0, var.data <= 0), (var.data, var.data > 0))\n local_gradients = {var: sy.Piecewise((0, var.data <= 0), (1, var.data > 0))}\n return Variable(data=data, parents=(var,), local_gradients=local_gradients)\n\n\nrelu = np.vectorize(lambda x: _relu(x))\n\n\ndef get_gradients(variable, wrt=None):\n \"\"\"Calculate gradients of `variable` with respect to `wrt`.\n This method should generally not be used as it is slow and\n inefficient.\n \"\"\"\n gradients = defaultdict(lambda: 0.0)\n\n def compute_gradients(variable, path_value):\n if variable.local_gradients:\n for parent, grad in variable.local_gradients.items():\n to_par = path_value * grad\n if wrt is None or str(parent) in wrt:\n gradients[str(parent)] += to_par\n compute_gradients(parent, to_par)\n\n compute_gradients(variable, path_value=1)\n return dict(gradients)\n","sub_path":"deuterium/autograd.py","file_name":"autograd.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247825033","text":"import datetime\nimport io\nimport logging\nimport uuid\nfrom confluent_kafka import Consumer, KafkaError\n\nlogger = logging.getLogger(__name__)\n\n\nclass AVROConsumer:\n hour = 22\n\n def __init__(self, config, idx):\n\n self.config = config\n self.idx = idx\n self.topic = config[\"input_topic\"] if \"input_topic\" in config else self._get_topic()\n self.fix_topic = True if \"input_topic\" in config else False \n\n def _get_topic(self):\n global hour\n date = datetime.datetime.today()\n if date.hour >= hour:\n date += datetime.timedelta(days=1)\n topic = 'ztf_{}_programid1'.format(date.strftime('%Y%m%d'))\n return topic\n\n def start(self):\n consumer_group = self.config[\"consumer.group\"] if \"consumer.group\" in self.config else \"Dummy{}\".format(uuid.uuid1());\n self.consumer = Consumer({\n 'bootstrap.servers': self.config[\"broker\"],\n 'group.id': consumer_group,\n 'auto.offset.reset': 'earliest'\n })\n logger.debug(\"subscribing to {}\".format(self.topic))\n self.consumer.subscribe([self.topic])\n\n def consume(self):\n global hour\n while True:\n date = datetime.datetime.today()\n logger.debug(date)\n if not self.fix_topic and date.hour >= hour:\n self.topic = self._get_topic()\n self.consumer.subscribe([self.topic])\n\n #Read kafka stream\n msg = self.consumer.poll(1.0)\n if msg is None:\n continue\n elif msg.error():\n logger.warning(\"Consumer error: {}\".format(msg.error()))\n continue\n else:\n avro = msg.value()\n return avro\n","sub_path":"consumer-with-config/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"530015910","text":"\"\"\"\nA deliberately bad implementation of [Boids](http://dl.acm.org/citation.cfm?doid=37401.37406)\nfor use as an exercise on refactoring.\n\"\"\"\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\nimport random\n\n# Deliberately terrible code for teaching purposes\n\nrange_val=50\nlimit_1=100\nlimit_2=10000\nmiddle_const=0.01\nspeed_const=0.125\n\n#boids_x=[random.uniform(-450,50.0) for x in range(range_val)]\n#boids_y=[random.uniform(300.0,600.0) for x in range(range_val)]\n#boid_x_velocities=[random.uniform(0,10.0) for x in range(range_val)]\n#boid_y_velocities=[random.uniform(-20.0,20.0) for x in range(range_val)]\n#boids=(boids_x,boids_y,boid_x_velocities,boid_y_velocities)\n\nclass Boids(object):\n def __init__(self, input_list=None, flag=0 ):\n if flag==0:\n self.random_init()\n if flag==1:\n self.from_file(input_list)\n \n def random_init(self):\n self.x=[random.uniform(-450,50.0) for x in range(range_val)]\n self.y=[random.uniform(300.0,600.0) for x in range(range_val)]\n self.x_velocity=[random.uniform(0,10.0) for x in range(range_val)]\n self.y_velocity=[random.uniform(-20.0,20.0) for x in range(range_val)]\n \n def from_file(self, input_list):\n self.x=input_list[0]\n self.y=input_list[1]\n self.x_velocity=input_list[2]\n self.y_velocity=input_list[3]\n\nboids=Boids()\n#print boids.y\n#print type(boids)\n\ndef update_boids(boids):\n\txs,ys,xvs,yvs=boids.x, boids.y, boids.x_velocity, boids.y_velocity\n\t# Fly towards the middle\n\tfor i in range(len(xs)):\n\t\tfor j in range(len(xs)):\n\t\t\txvs[i]=xvs[i]+(xs[j]-xs[i])*middle_const/len(xs)\n\tfor i in range(len(xs)):\n\t\tfor j in range(len(xs)):\n\t\t\tyvs[i]=yvs[i]+(ys[j]-ys[i])*middle_const/len(xs)\n\t# Fly away from nearby boids\n\tfor i in range(len(xs)):\n\t\tfor j in range(len(xs)):\n\t\t\tif (xs[j]-xs[i])**2 + (ys[j]-ys[i])**2 < limit_1:\n\t\t\t\txvs[i]=xvs[i]+(xs[i]-xs[j])\n\t\t\t\tyvs[i]=yvs[i]+(ys[i]-ys[j])\n\t# Try to match speed with nearby boids\n\tfor i in range(len(xs)):\n\t\tfor j in range(len(xs)):\n\t\t\tif (xs[j]-xs[i])**2 + (ys[j]-ys[i])**2 < limit_2:\n\t\t\t\txvs[i]=xvs[i]+(xvs[j]-xvs[i])*speed_const/len(xs)\n\t\t\t\tyvs[i]=yvs[i]+(yvs[j]-yvs[i])*speed_const/len(xs)\n\t# Move according to velocities\n\tfor i in range(len(xs)):\n\t\txs[i]=xs[i]+xvs[i]\n\t\tys[i]=ys[i]+yvs[i]\n\n\nfigure=plt.figure()\naxes=plt.axes(xlim=(-500,1500), ylim=(-500,1500))\nscatter=axes.scatter(boids.x,boids.y)\n\ndef animate(frame):\n update_boids(boids)\n scatter.set_offsets(zip(boids.x,boids.y))\n\n\nanim = animation.FuncAnimation(figure, animate,\n frames=50, interval=50)\n\nif __name__ == \"__main__\":\n plt.show()\n","sub_path":"boids.py","file_name":"boids.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"218369863","text":"n=int(input())\np=0\nfor i in range(0,n):\n c=n%10\n p=p+c\n n=n//10\ns1=str(p)\nc=s1[::-1]\nif c==s1:\n print(\"YES\")\nelse:\n print(\"NO\")\n","sub_path":"hunter_set4_40.py","file_name":"hunter_set4_40.py","file_ext":"py","file_size_in_byte":143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"340883333","text":"#!/usr/bin/env python\nimport profile\nfrom neuron import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import *\nimport math\nimport itertools\nimport os\nimport json\nimport io\n\n\nclass LTS(Neuron):\n def __init__(self, vm=0, c=1, params={}, sa=0, **kwargs):\n super(LTS, self).__init__(vm, c, sa, **kwargs)\n # Initial guesses for equilibrium potentials: -60 mV = Ekrev, \n # 75 = ENarev, -35 = ar rev, 140 = Ecarev\n ekrev = -90 # original: -60\n enarev = 50 # original: 75\n ecacat = 125 # original: 125 for cat, 140 for ca\n ecarev = 125\n leakrev = -65 # original: -74\n arrev = -35 # original: -35\n etraub = -57.5 # from Kawaguchi 1995\n\n self.add_channel(NaTraub, enarev, params['gna'], etraub)\n self.add_channel(KTraub, ekrev, params['gkv'], etraub)\n self.add_channel(leak, leakrev, params['gleak']) # 0.07\n # self.add_channel(ca, ecarev, params['gca']) # 3.0\n # self.add_channel(KCaTraub, ekrev, params['gkca']) # 0.5\n # self.add_channel(ar, arrev, params['gar']) # 0.001\n self.add_channel(CaT, ecacat, params['gcat']) # 0.2\n self.add_channel(KmYamada, ekrev, params['gkm'])\n\nclass FS(Neuron):\n def __init__(self, vm=0, c=1, params={}, sa=0, **kwargs):\n super(FS, self).__init__(vm, c, sa, **kwargs)\n ek = -90\n ena = 50\n eleak = -70.4\n etraub = -57.9\n self.add_channel(NaTraub, ena, params['gna'], etraub)\n self.add_channel(KTraub, ek, params['gkv'], etraub)\n self.add_channel(leak, eleak, params['gleak'])\n self.add_channel(KmYamada, ek, params['gkm'])","sub_path":"lts.py","file_name":"lts.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"200434061","text":"# Amin Aliari - 9431066\r\n# Project: Signal bouns project\r\n# Title: 2. Noise reduction\r\n\r\n# ----------------- imports -----------------\r\nfrom os import walk\r\n\r\nimport numpy as np\r\nfrom numpy.random import seed\r\nfrom numpy.random import rand\r\n\r\nfrom librosa import stft, istft\r\n\r\nfrom scipy.io import wavfile\r\n\r\nimport matplotlib.colors\r\nimport matplotlib.pyplot as plt\r\n# -------------------------------------------\r\n\r\n# ----------------- constants -----------------\r\nNOISE_VALUE = 1\r\n# ---------------------------------------------\r\n\r\n\r\ndef plot_graph(filename):\r\n freq, cdata = wavfile.read(filename)\r\n data = cdata.astype(np.float32) # discrete data\r\n length = data.shape[0] / freq\r\n\r\n time = np.linspace(0, length, data.shape[0])\r\n\r\n plt.plot(time, data, label=\"wave\")\r\n plt.xlabel(\"time\")\r\n plt.ylabel(\"amplitude\")\r\n plt.show()\r\n\r\n\r\ndef add_noise(filename) -> np.ndarray:\r\n freq, cdata = wavfile.read(filename)\r\n data = cdata.astype(np.float32) # discrete data\r\n\r\n sample_count = len(data)\r\n\r\n seed(1)\r\n max_value = np.amax(data) * NOISE_VALUE\r\n noise = rand(sample_count) * 2 - max_value\r\n noise = noise.astype(np.float32)\r\n\r\n data = np.add(data, noise)\r\n\r\n wavfile.write('noisy.wav', freq, data.astype(np.int16))\r\n\r\n return freq, data, noise\r\n\r\n\r\n# main\r\n# wav_data: noisy file, noise_data = only the noise part\r\nfreq, wav_data, noise_data = add_noise(\"test.wav\")\r\n\r\ns = stft(wav_data)\r\nss = np.abs(s)\r\nangle = np.angle(s)\r\nb = np.exp(1.0j * angle)\r\nns = stft(noise_data)\r\nnss = np.abs(ns)\r\n\r\nmns = np.mean(nss, axis=1)\r\nsa = ss - mns.reshape((mns.shape[0], 1))\r\n\r\nsa0 = sa * b\r\ny = istft(sa0)\r\nwavfile.write('fixed.wav', freq, y.astype(np.int16))\r\nplot_graph('fixed.wav')\r\n","sub_path":"project/NoiseEater.py","file_name":"NoiseEater.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"442461560","text":"import numpy as np\n\n\nclass Graph(object):\n def __init__(self, matrix):\n self.n = len(matrix[0])\n # self.vertex = []\n self.adj = matrix\n\n def dijkstra(self, start, end):\n d = [np.inf for i in range(self.n)]\n prev = [None for i in range(self.n)]\n d[start] = 0\n S = set([])\n Q = set([i for i in range(self.n)])\n while len(Q) != 0:\n tmp_min = None\n for v in Q:\n if tmp_min is None or np.less(d[v], d[tmp_min]):\n tmp_min = v\n v = tmp_min\n S.add(v)\n Q.remove(v)\n for u in range(len(self.adj[v])):\n if self.adj[v][u] is not None:\n if np.less(d[v] + self.adj[v][u], d[u]):\n d[u] = d[v] + self.adj[v][u]\n prev[u] = v\n path = []\n v = end\n while v is not None:\n path = [v] + path\n v = prev[v]\n\n return path\n","sub_path":"Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"433337894","text":"#\n# This file is part of LiteX.\n#\n# This file is Copyright (c) 2022 Florent Kermarrec <florent@enjoy-digital.fr>\n# SPDX-License-Identifier: BSD-2-Clause\n\nfrom migen import *\nfrom migen.fhdl.module import _ModuleProxy\nfrom migen.fhdl.specials import Special\n\nfrom litex.soc.interconnect.csr import AutoCSR\nfrom litex.soc.integration.doc import AutoDoc\n\n# LiteX Module -------------------------------------------------------------------------------------\n\nclass LiteXModule(Module, AutoCSR, AutoDoc):\n def __setattr__(m, name, value):\n # Migen:\n if name in [\"comb\", \"sync\", \"specials\", \"submodules\", \"clock_domains\"]:\n if not isinstance(value, _ModuleProxy):\n raise AttributeError(\"Attempted to assign special Module property - use += instead\")\n # LiteX fix-up: Automatically collect specials/submodules/clock_domains:\n # - m.module_x = .. equivalent of Migen's m.submodules.module_x = ..\n elif isinstance(value, Module) and ((name, value) not in m._submodules):\n setattr(m.submodules, name, value)\n # - m.special_x = .. equivalent of Migen's m.specials.special_x = ..\n elif isinstance(value, Special) and (value not in m._fragment.specials):\n setattr(m.specials, name, value)\n # - m.cd_x = .. equivalent of Migen's m.clock_domains.cd_x = ..\n elif isinstance(value, ClockDomain) and (value not in m._fragment.clock_domains):\n setattr(m.clock_domains, name, value)\n # Else use default __setattr__.\n else:\n object.__setattr__(m, name, value)\n\n # LiteX fix-up: Automatically collect specials/submodules/clock_domains:\n def __iadd__(m, other):\n # - m += module_x equivalent of Migen's m.submodules += module_x.\n if isinstance(other, Module):\n print(other)\n m.submodules += other\n # - m += special_x equivalent of Migen's m.specials += special_x.\n elif isinstance(other, Special):\n m.specials += other\n # - m += cd_x equivalent of Migen's m.clock_domains += cd_x.\n elif isinstance(other, ClockDomain):\n m.clock_domains += other\n # Else use default __iadd__.\n else:\n object.__iadd__(m, other)\n return m\n\n def add_module(self, name, module):\n assert isinstance(module, Module)\n assert not hasattr(self, name)\n setattr(self, name, module)\n\n def get_module(self, name):\n module = getattr(self, name, None)\n if module is not None:\n assert isinstance(module, Module)\n return module\n","sub_path":"litex/gen/fhdl/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"647967726","text":"def update_param(name, param):\n if name == 'distribution':\n param['values'].remove('custom')\n return param\n return None # param untouched\n\n\ndef class_extensions():\n @property\n def Lambda(self):\n \"\"\"DEPRECATED. Use ``self.lambda_`` instead\"\"\"\n return self._parms[\"lambda\"] if \"lambda\" in self._parms else None\n\n @Lambda.setter\n def Lambda(self, value):\n self._parms[\"lambda\"] = value\n\n @staticmethod\n def getGLMRegularizationPath(model):\n \"\"\"\n Extract full regularization path explored during lambda search from glm model.\n\n :param model: source lambda search model\n \"\"\"\n x = h2o.api(\"GET /3/GetGLMRegPath\", data={\"model\": model._model_json[\"model_id\"][\"name\"]})\n ns = x.pop(\"coefficient_names\")\n res = {\n \"lambdas\": x[\"lambdas\"],\n \"explained_deviance_train\": x[\"explained_deviance_train\"],\n \"explained_deviance_valid\": x[\"explained_deviance_valid\"],\n \"coefficients\": [dict(zip(ns, y)) for y in x[\"coefficients\"]],\n }\n if \"coefficients_std\" in x:\n res[\"coefficients_std\"] = [dict(zip(ns, y)) for y in x[\"coefficients_std\"]]\n return res\n\n @staticmethod\n def makeGLMModel(model, coefs, threshold=.5):\n \"\"\"\n Create a custom GLM model using the given coefficients.\n\n Needs to be passed source model trained on the dataset to extract the dataset information from.\n\n :param model: source model, used for extracting dataset information\n :param coefs: dictionary containing model coefficients\n :param threshold: (optional, only for binomial) decision threshold used for classification\n \"\"\"\n model_json = h2o.api(\n \"POST /3/MakeGLMModel\",\n data={\"model\": model._model_json[\"model_id\"][\"name\"],\n \"names\": list(coefs.keys()),\n \"beta\": list(coefs.values()),\n \"threshold\": threshold}\n )\n m = H2OGeneralizedLinearEstimator()\n m._resolve_model(model_json[\"model_id\"][\"name\"], model_json)\n return m\n\n\nextensions = dict(\n __imports__=\"\"\"import h2o\"\"\",\n __class__=class_extensions,\n __init__validation=\"\"\"\nif \"Lambda\" in kwargs: kwargs[\"lambda_\"] = kwargs.pop(\"Lambda\")\n\"\"\"\n)\n\noverrides = dict(\n alpha=dict(\n setter=\"\"\"\n# For `alpha` and `lambda` the server reports type float[], while in practice simple floats are also ok\nassert_is_type({pname}, None, numeric, [numeric])\nself._parms[\"{sname}\"] = {pname}\n\"\"\"\n ),\n lambda_=dict(\n setter=\"\"\"\nassert_is_type({pname}, None, numeric, [numeric])\nself._parms[\"{sname}\"] = {pname}\n\"\"\"\n ),\n)\n\ndoc = dict(\n __class__=\"\"\"\nFits a generalized linear model, specified by a response variable, a set of predictors, and a\ndescription of the error distribution.\n\nA subclass of :class:`ModelBase` is returned. The specific subclass depends on the machine learning task\nat hand (if it's binomial classification, then an H2OBinomialModel is returned, if it's regression then a\nH2ORegressionModel is returned). The default print-out of the models is shown, but further GLM-specific\ninformation can be queried out of the object. Upon completion of the GLM, the resulting object has\ncoefficients, normalized coefficients, residual/null deviance, aic, and a host of model metrics including\nMSE, AUC (for logistic regression), degrees of freedom, and confusion matrices.\n\"\"\"\n)\n","sub_path":"h2o-bindings/bin/custom/python/gen_glm.py","file_name":"gen_glm.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"257342181","text":"import tensorflow as tf\nimport sys, os\nsys.path.append(os.pardir)\nimport numpy as np\nimport codecs\nimport collections\nfrom operator import itemgetter\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\"\"\"\n1.使用tf.while_loop\n\n\"\"\"\ndir_name = os.path.dirname(__file__)\ncheckpoint_path = dir_name+'/seq2seq_ckpt-0'\nhidden_size = 1024\nnum_layers = 2\nsrc_vocab_size = 10000\ntrg_vocab_size = 4000\nshare_emb_and_softmax = True\n\nsos_id = 1\neos_id = 2\n\nclass NMTModel(object):\n def __init__(self):\n self.enc_cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.LSTMCell(hidden_size) for _ in range(num_layers)])\n self.dec_cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.LSTMCell(hidden_size) for _ in range(num_layers)])\n\n self.src_embedding = tf.get_variable('src_emb',[src_vocab_size,hidden_size]) # 定义词向量\n self.trg_embedding = tf.get_variable('trg_emb',[trg_vocab_size,hidden_size])\n\n if share_emb_and_softmax:\n self.softmax_weight = tf.transpose(self.trg_embedding)\n\n else:\n self.softmax_weight = tf.get_variable('weight',[hidden_size,trg_vocab_size])\n self.softmax_bias = tf.get_variable('softmax_bias',[trg_vocab_size])\n def inference(self,src_input):\n src_size = tf.convert_to_tensor([len(src_input)],dtype=tf.int32)\n src_input = tf.convert_to_tensor([src_input],dtype=tf.int32)\n src_emb = tf.nn.embedding_lookup(self.src_embedding,src_input)\n\n with tf.variable_scope('encoder'):\n enc_outputs,enc_state = tf.nn.dynamic_rnn(self.enc_cell,src_emb,src_size,dtype=tf.float32)\n\n max_dec_len = 100 # 设置解码的最大步数\n with tf.variable_scope('decoder/rnn/multi_rnn_cell'):\n # 使用一个变长的TensorArray来存储生成的句子\n # 含有init_array.read() init.write() 传入--init.unstack(array或者tensor)\n # init.write(index, value, name=None) 指定index位置写入Tensor\n # ta.unstack(value, name=None) 可以看做是stack的反操作,输入Tensor,输出一个新的TensorArray对象\n # init.stack(name=None) 将TensorArray中元素叠起来当做一个Tensor输出\n init_array = tf.TensorArray(dtype=tf.int32,size=0,dynamic_size=True,clear_after_read=False)\n init_array = init_array.write(0,sos_id)\n # 构建初始的循环状态--rnn的隐藏状态,保存生成句子的tensorarray,记录解码步数的整数step\n init_loop_var = (enc_state,init_array,0)\n\n def continue_loop_condition(state,trg_ids,step):\n # 循环直到解码器输出<eox>,或者达到最大步数\n # 计算一个张量在维度上元素的“逻辑和”,如果有axis设定轴,则在设定的维度上计算逻辑和,否则在所有维度上计算逻辑和--对应numpy的all\n # 输出不等于<eos> 和 step < max_dec_len-1 ,有一个为False则退出\n return tf.reduce_all(tf.logical_and(tf.not_equal(trg_ids.read(step),eos_id),tf.less(step,max_dec_len-1)))\n\n def loop_body(state,trg_ids,step):\n trg_input = [trg_ids.read(step)] # 读取第step个值\n trg_emb = tf.nn.embedding_lookup(self.trg_embedding,trg_input) # 用词向量方式表示\n # 这里不使用dynamic_rnn,而是直接调用dec_cell向前计算一步,因为测试时每一步的输出需要作为下一步的输入\n dec_outputs,next_state = self.dec_cell.call(state=state,inputs=trg_emb)\n output = tf.reshape(dec_outputs,[-1,hidden_size]) # 这里只有一个batch_size为1 num_step也只有一个\n\n logits = (tf.matmul(output,self.softmax_weight)+self.softmax_bias)\n # 选取logit最大的值作为输出\n next_id = tf.argmax(logits,axis=1,output_type=tf.int32)\n trg_ids = trg_ids.write(step+1,next_id[0])\n return next_state,trg_ids,step+1\n\n state,trg_ids,step = tf.while_loop(continue_loop_condition,loop_body,init_loop_var)\n return trg_ids.stack()\n\ndef main():\n with tf.variable_scope('nmt_model',reuse=None):\n model = NMTModel()\n test_sentence = [90,13,0,689,4,2]\n\n output_op = model.inference(test_sentence)\n sess = tf.Session()\n saver = tf.train.Saver()\n saver.restore(sess,checkpoint_path)\n\n output = sess.run(output_op)\n print(output)\n sess.close()\n\nif __name__=='__main__':\n main()\n","sub_path":"tensorflow_note/ch09/machine_trg_test.py","file_name":"machine_trg_test.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"303394932","text":"\"\"\"\nPackage for interacting on the network at a high level.\n\"\"\"\nimport random\nimport pickle\nimport asyncio\nimport logging\n\nfrom kademlia.file_data import FileData\nfrom kademlia.gossip_protocol import GossipProtocol\nfrom kademlia.storage import Storage\nfrom kademlia.utils import digest\nfrom kademlia.node import Node\n\nlog = logging.getLogger(__name__) # pylint: disable=invalid-name\n\n\n# pylint: disable=too-many-instance-attributes\nclass Server:\n \"\"\"\n High level view of a node instance. This is the object that should be\n created to start listening as an active node on the network.\n \"\"\"\n\n protocol_class = GossipProtocol\n\n def __init__(self, ksize=20, alpha=3, node_id=None, storage=None):\n \"\"\"\n Create a server instance. This will start listening on the given port.\n Args:\n ksize (int): The k parameter from the paper\n alpha (int): The alpha parameter from the paper\n node_id: The id for this node on the network.\n storage: An instance that implements the interface\n :class:`~kademlia.storage.IStorage`\n \"\"\"\n self.ksize = ksize\n self.alpha = alpha\n self.storage = Storage()\n self.node = Node(node_id or digest(random.getrandbits(255)))\n self.transport = None\n self.protocol = None\n self.refresh_loop = None\n self.save_state_loop = None\n\n def stop(self):\n if self.transport is not None:\n self.transport.close()\n\n if self.refresh_loop:\n self.refresh_loop.cancel()\n\n if self.save_state_loop:\n self.save_state_loop.cancel()\n\n def _create_protocol(self):\n return self.protocol_class(self.node, self.ksize)\n\n async def listen(self, port, interface='0.0.0.0'):\n \"\"\"\n Start listening on the given port.\n Provide interface=\"::\" to accept ipv6 address\n \"\"\"\n loop = asyncio.get_event_loop()\n self.transport, self.protocol = await loop.create_datagram_endpoint(self._create_protocol,\n local_addr=(interface,\n port))\n log.info(\"Node %i listening on %s:%i\",\n self.node.long_id, interface, port)\n\n def bootstrappable_neighbors(self):\n \"\"\"\n Get a :class:`list` of (ip, port) :class:`tuple` pairs suitable for\n use as an argument to the bootstrap method.\n The server should have been bootstrapped\n already - this is just a utility for getting some neighbors and then\n storing them if this server is going down for a while. When it comes\n back up, the list of nodes can be used to bootstrap.\n \"\"\"\n neighbors = self.protocol.find_neighbors(self.node)\n return [tuple(n)[-2:] for n in neighbors]\n\n def build_unique_code(self):\n return digest(random.getrandbits(255))\n\n async def bootstrap(self, address):\n \"\"\"\n Bootstrap the server by connecting to other known nodes in the network.\n Args:\n addrs: (ip, port) `tuple` pair. Note that only IP\n addresses are acceptable - hostnames will cause an error.\n \"\"\"\n log.debug(\"Attempting to bootstrap node with %i initial contact\",\n len(address))\n gathered = await self.bootstrap_node(address)\n request_id = self.build_unique_code()\n if gathered is not None:\n await self.protocol.call_connect(address, request_id)\n\n async def bootstrap_node(self, addr):\n result = await self.protocol.ping(addr, self.node.id)\n return Node(result[1], addr[0], addr[1]) if result[0] else None\n\n async def get(self, name):\n \"\"\"\n Get a key if the network has it.\n Returns:\n :class:`None` if not found, the value otherwise.\n \"\"\"\n log.info(\"Looking up key %s\", name)\n request_id = str(Node(self.build_unique_code()).long_id)\n dkey = digest(name)\n # if this node has it, return it\n if self.storage.find_file(dkey):\n self.protocol.history_of_find_file_request_ids_from_this_node[request_id] = \\\n FileData(request_id, name, self.storage.get_path(name))\n else:\n node = Node(dkey)\n closer = self.protocol.find_neighbours_closer_then_me(node)\n\n if not closer:\n log.warning(\"There are no known neighbors to get key %s\", name)\n return None\n\n self.protocol.call_find(closer, dkey, request_id)\n return request_id\n\n def get_results_by_search_ids(self, ids):\n return self.protocol.get_results_by_ids(ids)\n\n def get_all_files(self):\n return self.storage.get_all()\n\n def get_all_neighbours(self):\n return self.protocol.neighbours\n\n async def set(self, name, path):\n \"\"\"\n Set the given string key to the given value in the network.\n \"\"\"\n\n log.info(\"Saving '%s' on network\", name)\n dkey = digest(name)\n value = self.storage.upload(path)\n return await self.set_digest(name, dkey, value)\n\n async def set_digest(self, name, dkey, value):\n \"\"\"\n Set the given SHA1 digest key (bytes) to the given value in the\n network.\n \"\"\"\n node = Node(dkey)\n\n nearest = self.protocol.find_neighbors(node)\n if not nearest:\n log.warning(\"There are no known neighbors to set key %s\", dkey.hex())\n return False\n neighbors = []\n for n in nearest:\n if n.distance_to(node) <= self.node.distance_to(node):\n neighbors.append(n)\n\n if len(neighbors) == 0:\n self.storage.download(name, value)\n for n in neighbors:\n await self.protocol.call_store(n, name, dkey, value)\n\n # return true only if at least one store call succeeded\n # return any(await asyncio.gather(*results))\n\n def save_state(self, fname):\n \"\"\"\n Save the state of this node (the alpha/ksize/id/immediate neighbors)\n to a cache file with the given fname.\n \"\"\"\n log.info(\"Saving state to %s\", fname)\n data = {\n 'ksize': self.ksize,\n 'alpha': self.alpha,\n 'id': self.node.id,\n 'neighbors': self.bootstrappable_neighbors()\n }\n if not data['neighbors']:\n log.warning(\"No known neighbors, so not writing to cache.\")\n return\n with open(fname, 'wb') as file:\n pickle.dump(data, file)\n\n @classmethod\n async def load_state(cls, fname, port, interface='0.0.0.0'):\n \"\"\"\n Load the state of this node (the alpha/ksize/id/immediate neighbors)\n from a cache file with the given fname and then bootstrap the node\n (using the given port/interface to start listening/bootstrapping).\n \"\"\"\n log.info(\"Loading state from %s\", fname)\n with open(fname, 'rb') as file:\n data = pickle.load(file)\n svr = Server(data['ksize'], data['alpha'], data['id'])\n await svr.listen(port, interface)\n if data['neighbors']:\n await svr.bootstrap(data['neighbors'])\n return svr\n\n def save_state_regularly(self, fname, frequency=600):\n \"\"\"\n Save the state of node with a given regularity to the given\n filename.\n Args:\n fname: File name to save retularly to\n frequency: Frequency in seconds that the state should be saved.\n By default, 10 minutes.\n \"\"\"\n self.save_state(fname)\n loop = asyncio.get_event_loop()\n self.save_state_loop = loop.call_later(frequency,\n self.save_state_regularly,\n fname,\n frequency)\n\n\ndef check_dht_value_type(value):\n \"\"\"\n Checks to see if the type of the value is a valid type for\n placing in the dht.\n \"\"\"\n typeset = [\n int,\n float,\n bool,\n str,\n bytes\n ]\n return type(value) in typeset # pylint: disable=unidiomatic-typecheck\n","sub_path":"kademlia/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":8296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"327061612","text":"# Task 2 GeekBrains Python Fast Start\n\n\ndef choose_work_task():\n # Choose work task\n\n print('Выберите задачу:')\n print('Стричь газон (1)')\n print('Копать картофан (2)')\n print('Вынести мусор (3)')\n\n choosed_task = input('?')\n\n print('Вы выборали задачу {}'.format(choosed_task))\n\n\ndef task_first():\n # Task 1\n name = input('Ваше имя: ')\n print('{}, добро пожаловать в мир Пайтон!'.format(name))\n\n we_work = input('Давайте поработаем (Y/N)?')\n\n if we_work == 'Y':\n choose_work_task()\n elif we_work == 'N':\n print('До свидания!')\n else:\n pass\n\n\ndef main():\n # Initial function\n task_first()\n\n\nmain()\n","sub_path":"GeePyFastStart_2.py","file_name":"GeePyFastStart_2.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"62222048","text":"from sqlalchemy import Column, String, Integer, Float, Boolean, text\nfrom sqlalchemy import inspect\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.ext.declarative import declarative_base\nimport yaml\n\n_base = declarative_base()\n\n\nclass TrainingFlags(_base):\n # Training hyperparameters model default inception_v2\n __tablename__ = 'training_params'\n __table_args__ = {\"schema\": \"train_config\"}\n\n id = Column(UUID(as_uuid=False), default=text(\"uuid_generate_v1()\"), primary_key=True)\n name = Column(String, primary_key=True, nullable=False)\n dataset_name = Column(String, default='cifar10')\n purpose = Column(String, default=\"cifar\")\n training_log_dir = Column(String, default=None)\n optimizer = Column(String, default='sgd')\n batch_size = Column(Integer, default=8)\n train_image_size = Column(Integer, default=224)\n max_number_of_steps = Column(Integer, default=10000000)\n log_every_n_steps = Column(Integer, default=10)\n save_interval_secs = Column(Integer, default=300)\n save_summaries_secs = Column(Integer, default=600)\n weight_decay = Column(Float, default=0.00004)\n adadelta_rho = Column(Float, default=0.95)\n adagrad_initial_accumulator_value = Column(Float, default=0.1)\n adam_beta1 = Column(Float, default=0.9)\n adam_beta2 = Column(Float, default=0.999)\n opt_epsilon = Column(Float, default=1.0)\n ftrl_learning_rate_power = Column(Float, default=-0.5)\n ftrl_initial_accumulator_value = Column(Float, default=0.1)\n ftrl_l1 = Column(Float, default=0.0)\n ftrl_l2 = Column(Float, default=0.0)\n momentum = Column(Float, default=0.9)\n rmsprop_momentum = Column(Float, default=0.9)\n rmsprop_decay = Column(Float, default=0.9)\n learning_rate_decay_type = Column(String, default='exponential')\n learning_rate = Column(Float, default=0.01)\n end_learning_rate = Column(Float, default=0.0001)\n label_smoothing = Column(Float, default=0.0)\n learning_rate_decay_factor = Column(Float, default=0.94)\n num_epochs_per_decay = Column(Float, default=2.0)\n sync_replicas = Column(Boolean, default=False)\n replicas_to_aggregate = Column(Integer, default=1)\n moving_average_decay = Column(Integer, default=None)\n tf_master = Column(String, default=None)\n num_clones = Column(Integer, default=1)\n clone_on_cpu = Column(Boolean, default=False)\n worker_replicas = Column(Integer, default=1)\n num_ps_tasks = Column(Integer, default=0)\n num_readers = Column(Integer, default=8)\n num_preprocessing_threads = Column(Integer, default=4)\n task = Column(Integer, default=1)\n labels_offset = Column(Integer, default=0)\n model_name = Column(String, default='inception_v2')\n preprocessing_name = Column(String, default=None)\n checkpoint_path = Column(String, default=None)\n checkpoint_exclude_scopes = Column(String, default=None)\n ignore_missing_vars = Column(Boolean, default=False)\n trainable_scopes = Column(String, default=None)\n dataset_split_name = Column(String, default=None)\n dataset_dir = Column(String, default=None)\n measure = Column(String, default=None)\n ordering = Column(Integer, default=0)\n patch_size = Column(Integer, default=8)\n curriculum = Column(Boolean, default=False)\n master = Column(String, default=None)\n backup_measure = Column(String, default=None)\n measure_list = Column(String, default=None)\n\n def to_dict(self):\n return {c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs}\n\n @staticmethod\n def serialize(config):\n # dict to Hyperparams object\n assert config, \"Supplied config is None\"\n assert isinstance(config, dict), \"Supplied config is not a dict instance\\n\"\n obj = TrainingFlags()\n for key, value in config.items():\n setattr(obj, key, value)\n\n return obj\n\n def dump(self, filename):\n try:\n with open(filename, 'w+') as outfile:\n yaml.dump(self.to_dict(), outfile, default_flow_style=False)\n outfile.close()\n except BaseException as e:\n print(e.args)\n\n\nclass EvalFlags:\n __tablename__ = 'eval_config'\n\n model = Column(String, default=None)\n checkpoint_path = Column(String, default=None)\n\n pass\n","sub_path":"clo/config/configurations.py","file_name":"configurations.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"528013066","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 3 13:32:03 2017\n\n@author: Marten\n\"\"\"\n\n\nimport time \nimport cv2\nfrom pyardrone import ARDrone \nimport logging \n\nlogging.basicConfig(level=logging.DEBUG)\n\nclient = ARDrone()\nprint(client)\nclient.video_ready.wait()\ntry: \n while True: \n print(\"dislplay\")\n cv2.imshow(\"im\",client.frame)\n \n if cv2.waitKey(10) == ord(' '): \n break\n \nfinally: \n client.close()\n ","sub_path":"Test/VideoCapturetest.py","file_name":"VideoCapturetest.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"471684198","text":"#No Name Corp.\r\n#Sam Ni, Jeffery Wong, Eldon Wu\r\n#Rigged:Election Day\r\n#Hillary Clinton must go on a mission to stop Donald Trump from winning the\r\n#election because she found out about Trump’s evil plans for America, you must\r\n#rig the election!Use the spacebar, the right, and left arrow keys to play.\r\nfrom gamelib import*\r\ngame = Game(1500,600,\"Rigged:Election Day\")\r\nbk = Image(\"eldon.png\",game)\r\nbk.resizeTo(1600,600)\r\nbk.draw()\r\nhillary = Image(\"Hillaryclinton.png\",game)\r\nhillary.resizeBy(-50)\r\nhillary.moveTo(500,360)\r\ntrump = Image(\"trump.png\",game)\r\ntrump.moveTo(1100,360)\r\nbooth = Image(\"FotingBooth.png\",game)\r\nbooth.moveTo(1300,370)\r\nsteve = Image(\"bodyguard.png\",game)\r\nsteve.resizeBy(-75)\r\nsteve.moveTo(999,400)\r\nvote = Image(\"Bullet.png\",game)\r\nvote.resizeBy(-96)\r\nvote.setSpeed(5,90)\r\nvote.visible = True\r\nrealvote = Image(\"realvote.png\",game)\r\nrealvote.resizeTo(vote.width,vote.height)\r\nrealvote.setSpeed(4,randint(-10,180))\r\nplatform = Image(\"god.png\",game)\r\nplatform.resizeTo(booth.width,100)\r\nboomboom = Animation(\"explosjon3.png\",16,game,512/16,512/16)\r\nboomboom.visible = False\r\nvoter = Image(\"Voter.png\",game)\r\nvoter.resizeBy(-75)\r\nvoter.moveTo(50,360)\r\ntitlebk2 = Image(\"trumhead.png\",game)\r\ntitlebk2.moveTo(300,600)\r\ntitlebk1 = Image(\"hillhead.png\",game)\r\ntitlebk1.moveTo(250,450)\r\ntitlebk1.resizeBy(-20)\r\nmugshot = Image(\"headofgod.png\",game)\r\nmugshot.resizeTo(450,450)\r\nmugshot.moveTo(1300,400)\r\nshotmug = Image(\"headofdog.png\",game)\r\nshotmug.resizeTo(500,500)\r\nshotmug.moveTo(900,350)\r\njeffrey = Image(\"Jeffrey.png\",game)\r\njeffrey.resizeTo(game.width,game.height)\r\nplay = Image(\"experiment.png\",game)\r\nplay.moveTo(190,418)\r\nfont = Image(\"helpme.png\",game)\r\nfont.resizeBy(-50)\r\nfont.moveTo(977,70)\r\notherfont = Image(\"damnit.png\",game)\r\notherfont.resizeTo(font.width,font.height)\r\notherfont.moveTo(977,118)\r\nintroductions = Image(\"dance.png\",game)\r\nintroductions.resizeBy(-60)\r\nintroductions.moveTo(270,530)\r\nspacebar = Image(\"otherdance.png\",game)\r\nspacebar.resizeBy(-65)\r\nspacebar.moveTo(100,530)\r\nwin = Image(\"goodending.png\",game)\r\nwin.resizeTo(font.width,font.height)\r\nwin.moveTo(977,70)\r\nlose = Image(\"trueending.png\",game)\r\nlose.resizeTo(font.width,font.height)\r\nlose.moveTo(977,70)\r\nlevelfont = Image(\"level2.png\",game)\r\nlevelfont.moveTo(levelfont.x,50)\r\n#Image Test\r\n'''while not game.over:\r\n game.processInput()\r\n #hillary.draw()\r\n #trump.draw()\r\n #booth.draw()\r\n #steve.draw()\r\n #vote.draw()\r\n #platform.draw()\r\n #boomboom.draw()\r\n #voter.draw()\r\n \r\n game.update(30)'''\r\nuranus = [] \r\nfor index in range(100):\r\n uranus.append(Image(\"Bullet.png\",game)) \r\nfor index in range(100):\r\n uranus[index].resizeBy(-96)\r\n x = randint(100,1500)\r\n y = randint(100,600)\r\n uranus[index].moveTo(x, -y)\r\n uranus[index].setSpeed(2,180)\r\n\r\nsaturn = []\r\nfor index in range(50):\r\n saturn.append(Image(\"Bullet.png\",game))\r\nfor index in range(50):\r\n saturn[index].resizeBy(-96)\r\n saturn[index].setSpeed(5,180)\r\n\r\njupiter = []\r\nfor index in range(50):\r\n jupiter.append(Image(\"realvote.png\",game))\r\nfor index in range(50):\r\n jupiter[index].resizeBy(-96)\r\n jupiter[index].setSpeed(5,180)\r\n\r\nmars = []\r\nfor index in range(100):\r\n mars.append( Image( \"god.png\",game))\r\n mars[index].resizeTo(booth.width,100)\r\nfor index in range(100):\r\n x = randint(100,700)\r\n y = randint(100,4000)\r\n mars[index].moveTo(x, -y)\r\n mars[index].setSpeed(2,180)\r\n\r\nvenus = []\r\nfor index in range(50):\r\n venus.append(Image(\"Bullet.png\",game))\r\nfor index in range(50):\r\n venus[index].resizeBy(-96)\r\n venus[index].setSpeed(2,90)\r\n\r\n#Title Screen\r\ngame.over = False\r\nwhile not game.over:\r\n game.processInput()\r\n\r\n jeffrey.draw()\r\n play.draw()\r\n font.draw()\r\n otherfont.draw()\r\n shotmug.draw()\r\n mugshot.draw()\r\n introductions.draw()\r\n spacebar.draw()\r\n if play.collidedWith(mouse) and mouse.LeftClick:\r\n game.over = True\r\n\r\n game.update(30)\r\n\r\n#Level 1\r\ngame.over = False\r\nTvotes = 20\r\nCvotes = 0\r\nvotecount = 1\r\ntimecount = 100\r\nwhile not game.over:\r\n game.processInput()\r\n bk.draw()\r\n booth.draw()\r\n hillary.draw()\r\n vote.move(False)\r\n steve.move(True)\r\n realvote.move(True)\r\n 'steve.visible = False'\r\n #Venus\r\n for index in range(50):\r\n if vote.collidedWith(steve,\"rectangle\"):\r\n venus[index].move(True)\r\n #Saturn\r\n for index in range(50):\r\n saturn[index].moveTo(hillary.x,hillary.y)\r\n saturn[index].visible = False\r\n saturn[index].move(True)\r\n if saturn[index].isOffScreen(\"top\") and saturn[index].visible:\r\n saturn[index].visible = False\r\n if keys.Pressed[K_DOWN] and vote.move(False):\r\n vote.moveTo(hillary.x,hillary.y)\r\n vote.visible = True\r\n vote.setSpeed(1,-90)\r\n #Don't use Jupiter\r\n\r\n #mars and uranus having a blast!\r\n for index in range(100):\r\n #mars[index].move()\r\n uranus[index].move()\r\n '''if mars[index].isOffScreen(\"bottom\") and mars[index].visible:\r\n #mars[index].visible = False'''\r\n if uranus[index].isOffScreen(\"bottom\") and uranus[index].visible:\r\n uranus[index].visible = False\r\n '''if mars[index].collidedWith(vote):\r\n vote.visible = False\r\n boomboom.moveTo(mars[index].x,mars[index].y)\r\n boomboom.visible = True'''\r\n if uranus[index].collidedWith(hillary,\"rectangle\"):\r\n votecount += randint(1,2)\r\n uranus[index].visible = False\r\n if uranus[index].collidedWith(steve,\"rectangle\"):\r\n uranus[index].visible = False\r\n if vote.collidedWith(realvote):\r\n vote.visible = False\r\n if vote.collidedWith(steve,\"rectangle\"):\r\n vote.setSpeed(4,randint(-10,180))\r\n steve.health -= randint(10,30)\r\n if vote.collidedWith(hillary,\"rectangle\"):\r\n vote.visible = False\r\n hillary.health -= randint(0,40)\r\n if realvote.collidedWith(hillary,\"rectangle\"):\r\n realvote.visible = False\r\n hillary.health -= randint(0,40)\r\n if steve.health <=1:\r\n steve.moveTo(999999,999999)\r\n steve.visible = False\r\n if vote.collidedWith(booth):\r\n vote.visible = False\r\n Cvotes +=1\r\n Tvotes -=1\r\n realvote.visible = True\r\n realvote.moveTo(booth.x,booth.y)\r\n realvote.setSpeed(5,randint(10,180))\r\n realvote.visible = True\r\n if hillary.collidedWith(steve,\"rectangle\"):\r\n hillary.moveTo(500,360)\r\n hillary.health -= randint(10,40)\r\n if hillary.isOffScreen():\r\n hillary.moveTo(400,360)\r\n if Cvotes <= Tvotes-1:\r\n steve.visible = True\r\n steve.draw()\r\n if votecount <=0:\r\n game.over = True\r\n if Cvotes >= Tvotes+1:\r\n game.drawText(\"You Win!\",100,5)\r\n game.over = True\r\n if hillary.health <=1:\r\n game.over = True\r\n '''if keys.Pressed[K_UP] and vote.isOffScreen():\r\n vote.moveTo(hillary.x,hillary.y+10)\r\n vote.visible = True\r\n vote.setSpeed(4,0)\r\n votecount -=1\r\n if keys.Pressed[K_DOWN] and vote.isOffScreen():\r\n vote.moveTo(hillary.x+10,hillary.y)\r\n vote.visible = True\r\n vote.setSpeed(4,-90)\r\n votecount -=1#votecount goes down by more than one'''\r\n if keys.Pressed[K_SPACE] and vote.isOffScreen():\r\n vote.moveTo(hillary.x+65,hillary.y)\r\n vote.visible = True\r\n vote.setSpeed(4,-90)\r\n votecount -=1\r\n if keys.Pressed[K_RIGHT]:\r\n hillary.y += 7\r\n hillary.x += 3\r\n hillary.y -= 7\r\n if keys.Pressed[K_LEFT]:\r\n hillary.y += 7\r\n hillary.x -= 3\r\n hillary.y -= 7\r\n\r\n game.drawText(\"Health: \" + str(hillary.health),hillary.x - 40 ,hillary.y - 110)\r\n game.drawText(\"Health: \" + str(steve.health),steve.x - 40 ,steve.y - 110)\r\n game.drawText(\"Ammo: \" + str(votecount),50,550)\r\n game.drawText(\"Votes For Clinton: \" + str(Cvotes),150,550)\r\n game.drawText(\"Votes For Trump: \" + str(Tvotes),320,550)\r\n #game.displayTime(50,525)\r\n game.update(60)\r\n\r\n#Level 2\r\ngame.over = False\r\nhillary.health = 100\r\nTvotes = 25\r\nwhile not game.over and hillary.health > 1:\r\n game.processInput()\r\n bk.draw()\r\n booth.draw()\r\n hillary.draw()\r\n vote.move(False)\r\n trump.move(True)\r\n realvote.move(True)\r\n levelfont.draw()\r\n 'steve.visible = False'\r\n #Venus\r\n for index in range(50):\r\n if vote.collidedWith(steve,\"rectangle\"):\r\n venus[index].move(True)\r\n #Saturn\r\n for index in range(50):\r\n saturn[index].moveTo(hillary.x,hillary.y)\r\n saturn[index].visible = False\r\n saturn[index].move(True)\r\n if saturn[index].isOffScreen(\"top\") and saturn[index].visible:\r\n saturn[index].visible = False\r\n if keys.Pressed[K_DOWN] and vote.move(False):\r\n vote.moveTo(hillary.x,hillary.y)\r\n vote.visible = True\r\n vote.setSpeed(1,-90)\r\n #Don't use Jupiter\r\n\r\n #mars and uranus having a blast!\r\n for index in range(50):\r\n #mars[index].move()\r\n uranus[index].move()\r\n if uranus[index].isOffScreen(\"bottom\") and uranus[index].visible:\r\n uranus[index].visible = False\r\n if uranus[index].collidedWith(hillary,\"rectangle\"):\r\n votecount += randint(1,2)\r\n uranus[index].visible = False\r\n if uranus[index].collidedWith(steve,\"rectangle\"):\r\n uranus[index].visible = False\r\n if vote.collidedWith(realvote):\r\n vote.visible = False\r\n if vote.collidedWith(trump,\"rectangle\"):\r\n vote.setSpeed(4,randint(-10,180))\r\n trump.health -= randint(10,30)\r\n if vote.collidedWith(hillary,\"rectangle\"):\r\n vote.visible = False\r\n hillary.health -= randint(0,40)\r\n if realvote.collidedWith(hillary,\"rectangle\"):\r\n realvote.visible = False\r\n hillary.health -= randint(0,40)\r\n if trump.health <=1:\r\n trump.moveTo(999999,999999)\r\n trump.visible = False\r\n if vote.collidedWith(booth):\r\n vote.visible = False\r\n Cvotes +=1\r\n Tvotes -=1\r\n realvote.visible = True\r\n realvote.moveTo(booth.x,booth.y)\r\n realvote.setSpeed(5,randint(10,180))\r\n realvote.visible = True\r\n if hillary.collidedWith(steve,\"rectangle\"):\r\n hillary.moveTo(500,360)\r\n hillary.health -= randint(10,40)\r\n if hillary.isOffScreen():\r\n hillary.moveTo(400,360)\r\n if Cvotes <= Tvotes-1:\r\n steve.visible = True\r\n steve.draw()\r\n if votecount <=0:\r\n game.over = True\r\n if Cvotes >= Tvotes+1:\r\n game.drawText(\"You Win!\",100,5)\r\n game.over = True\r\n if hillary.health <=1:\r\n game.over = True\r\n if keys.Pressed[K_SPACE] and vote.isOffScreen():\r\n vote.moveTo(hillary.x+65,hillary.y)\r\n vote.visible = True\r\n vote.setSpeed(4,-90)\r\n votecount -=1\r\n if keys.Pressed[K_RIGHT]:\r\n hillary.y += 7\r\n hillary.x += 3\r\n hillary.y -= 7\r\n if keys.Pressed[K_LEFT]:\r\n hillary.y += 7\r\n hillary.x -= 3\r\n hillary.y -= 7\r\n\r\n game.drawText(\"Health: \" + str(hillary.health),hillary.x - 40 ,hillary.y - 110)\r\n game.drawText(\"Health: \" + str(trump.health),trump.x - 40 ,trump.y - 110)\r\n game.drawText(\"Ammo: \" + str(votecount),50,550)\r\n game.drawText(\"Votes For Clinton: \" + str(Cvotes),150,550)\r\n game.drawText(\"Votes For Trump: \" + str(Tvotes),320,550)\r\n #game.displayTime(50,525)\r\n game.update(60)\r\n\r\n#End Screen\r\ngame.over = False\r\nwhile not game.over:\r\n game.processInput()\r\n jeffrey.draw()\r\n if Cvotes >= Tvotes:\r\n titlebk1.draw()\r\n win.draw()\r\n if Cvotes <= Tvotes:\r\n titlebk2.draw()\r\n lose.draw()\r\n if keys.Pressed[K_SPACE]:\r\n game.over = True\r\n \r\n game.update(60)\r\ngame.quit()\r\n","sub_path":"REALmainRiggedelectionday.py","file_name":"REALmainRiggedelectionday.py","file_ext":"py","file_size_in_byte":11872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"483443489","text":"# @Author : jkl\n# @Email : 189156395@qq.com\n# @Time : 2020/9/6 11:07 下午\n# @File : 02-从尾到头打印链表.py\n\n\nclass Solution:\n def printListFromTailToHead(self, listNode):\n ret = []\n p = listNode\n while p:\n ret.insert(0, p)\n p = p.next\n return ret\n","sub_path":"链表/02-从尾到头打印链表.py","file_name":"02-从尾到头打印链表.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"286273027","text":"from django.conf.urls import url\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns=[\n url(r'^$', views.linhvuc.as_view(),name='linhvuc'),\n url(r'^dangki/$',views.dangki,name='dangki'),\n url(r'^dangnhap/$',auth_views.login,{'template_name':'Trangchu/Dangnhap.html'},name='dangnhap'),\n url(r'^dangxuat/$',auth_views.logout,{'next_page':'/'},name='dangxuat'),\n url(r'^(?P<asdddd>\\w+)/$',views.cacsanpham.as_view(),name='cacsanpham'),\n]\n","sub_path":"Trangchu/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":"83"} +{"seq_id":"176934459","text":"from django.contrib.auth import authenticate, logout\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib import messages\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db import IntegrityError, transaction\nfrom django.contrib.auth.models import Group, Permission\n\n# forms\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import TemplateView\n\nfrom .forms import UserForm,UserUpdateForm,CategoryForm, ProductImageForm, ProductForm, ProductMetaForm,UserGroupForm\nfrom .forms import ProductAttributeForm,ProductAttributeEditForm,ProductAttributeValueForm, ProductAttributeAssociationForm , BannerForm\nfrom .models import User, Categories,Product,ProductAttributeValue, ProductAttributeAssociation, ProductImage, ProductMeta,ProductAttribute\nfrom .models import Banner, UserWishlist\n\n\nfrom django.forms import inlineformset_factory\n\nfrom .decorators import unauthenticated_user, allowed_users\n\n# Create your views here.\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef index(request):\n return render(request, 'myapp/starter.html')\n\n\n# @unauthenticated_user\ndef login(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n valuenext = request.POST.get('next')\n user = authenticate(request, username=username, password=password)\n groups = request.user.groups.values_list('name', flat = True)\n if user is not None and valuenext == '':\n if 'admin' in groups or user.is_superuser:\n auth_login(request, user)\n messages.success(request, 'you are logged in')\n return redirect('myapp:index')\n else:\n messages.warning(request, 'you are not authorized for it')\n elif user is not None and valuenext != '':\n if 'admin' in groups or user.is_superuser:\n auth_login(request, user)\n return redirect(valuenext)\n else:\n messages.warning(request, 'you are not authorized for it')\n else:\n messages.info(request, 'please enter right credentials')\n return render(request, 'myapp/login.html')\n\n\ndef logoutUser(request):\n logout(request)\n return redirect('myapp:login')\n\n# ----------------------------------------- users -------------------------------------------------\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef UserList(request):\n users = User.objects.get_queryset().order_by('id')\n #wishlist=UserWishlist.objects.filter(user_wishlist__)\n\n page=request.GET.get('page',1)\n paginator=Paginator(users,10)\n try:\n users=paginator.page(page)\n except PageNotAnInteger:\n users=paginator.page(1)\n except EmptyPage:\n users=paginator.page(paginator.num_pages)\n\n if request.method=='POST':\n page_n=request.POST.get('page_n',None) # getting page number\n\n users=paginator.page(page_n).object_list\n\n\n return render(request, 'myapp/user_list.html', {'users': users})\n\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef UserChange(request):\n instance = request.user\n if request.method == 'POST':\n form = ChangeDetailForm(request.POST, instance=instance)\n if form.is_valid():\n form.save()\n return redirect('myapp:index')\n else:\n form = ChangeDetailForm(instance=instance)\n return render(request, 'myapp/change_detail.html', {'form': form})\n\n\n@login_required(login_url='myapp:login')\n# def UserChangePsw(request,id):\ndef UserChangePsw(request):\n # instance=get_object_or_404(User, id=id)\n instance = request.user\n if request.method == 'POST':\n form = OldPassForm(request.POST, instance=instance)\n if form.is_valid():\n # instance = form.save(commit=False)\n old_password = form.cleaned_data['old_password']\n new_password = form.cleaned_data['new_password']\n confirm_password = form.cleaned_data['confirm_password']\n if new_password == confirm_password:\n user = request.user\n print(user.password)\n if user.check_password(old_password):\n user.set_password(new_password)\n user.save() # add data to database\n messages.success(request, 'password change succesfully')\n return redirect('myapp:UserUpdate')\n else:\n messages.warning(request, 'your current password password is not matched ')\n else:\n messages.error(request, 'new password and current password is not matched ')\n\n form = OldPassForm()\n\n return render(request, 'myapp/user_psd_change.html', {'form': form})\n\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef UserAdd(request):\n if request.method == 'POST':\n\n form = UserForm(request.POST)\n if form.is_valid():\n form.save() # add data to database\n messages.success(request, \"user added succesfully\")\n return redirect('myapp:UserList')\n else:\n form = UserForm()\n return render(request, 'myapp/user_add.html', {'form': form, })\n\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef UserUpdate(request, id):\n instance = get_object_or_404(User, id=id)\n if request.method == 'POST':\n form = UserUpdateForm(request.POST, instance=instance)\n if form.is_valid():\n form.save() # add data to database\n messages.success(request, \"user updated successfuly\")\n return redirect('myapp:UserList')\n else:\n form = UserUpdateForm(instance=instance)\n\n return render(request, 'myapp/user_update.html', {'form': form, 'id': id})\n\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef UserDelete(request, id):\n data = get_object_or_404(User, id=id)\n try:\n data.delete()\n messages.success(request, \"user deleted succesfully\")\n except IntegrityError:\n messages.warning(request, \"user cant deleted because of integrity\")\n\n return redirect('myapp:UserList')\n\n#------------------------------------group-----------------------------------------\ndef group_list(request):\n groups=Group.objects.all()\n group_ids=Group.objects.all().values_list('id', flat=True)\n #permissions=group_ids.permissions_set.all()\n permissions=Permission.objects.filter(group__id__in=group_ids)\n return render(request,'myapp/group_list.html',{'groups_ids':group_ids,'permsissions':permissions})\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef group_select(request):\n if request.method=='POST':\n form=UserGroupForm(request.POST)\n if form.is_valid():\n form=form.save(commit=False)\n form.save()\n messages.success(request,\"group added successfully\")\n else:\n form=UserGroupForm()\n return render(request,'myapp/group.html',{'form':form})\n\n\n\n#------------------------------------category--------------------------------------\n@login_required(login_url='myapp:login')\ndef category_list(request):\n # categories=Categories.objects.all()\n #gave this error UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list:\n # <class 'myapp.models.Categories'> QuerySet.\n\n categories = Categories.objects.get_queryset().order_by('id') #retrive all categories\n page=request.GET.get('page',1) # if page doesn't exist it will fallback to default value 1 which is what get intends to do\n\n paginator=Paginator(categories,3) # telling how many category objects on each page\n try:\n categories=paginator.page(page)\n except PageNotAnInteger:\n categories=paginator.page(1)\n except EmptyPage:\n categories=paginator.page(paginator.num_pages)\n\n if request.method=='POST':\n page_n=request.POST.get('page_n',None) # getting page number\n\n categories=paginator.page(page_n).object_list\n\n # categories=serializers.serialize('json',categories1)\n # categories=list(paginator.page(page_n)).object_list.values('id','name','parent','Description',\n # 'created_by','created_date','modify_by',\n # 'modified_date','status')\n # return JsonResponse(categories,content_type='application/json',safe=False)\n\n context = {'categories': categories}\n return render(request, 'myapp/categories_list.html', context)\n\n\n# def detail_category(request, pk):\n# category = get_object_or_404(Categories, pk=pk) #retrive single category\n# return render(request, 'myapp/categories_detail.html', {'category': category})\n\n#create\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef new_category(request):\n if request.method == \"POST\":\n form = CategoryForm(request.POST)\n #to see if the data is valid or not ..like form validation\n if form.is_valid():\n instance = form.save(commit=False) # add data to database\n instance.created_by = request.user\n instance.modify_by = request.user\n instance.save()\n messages.success(request, \"category added succesfully\")\n return redirect('myapp:category_list')\n else:\n form = CategoryForm()\n return render(request, 'myapp/categories_add.html', {'form': form})\n\n#update\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef edit_category(request, pk):\n instance = get_object_or_404(Categories, pk=pk)\n if request.method == \"POST\":\n form = CategoryForm(request.POST, instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.modify_by = request.user\n instance.save() # add data to database\n messages.success(request, \"category updated successfuly\")\n return redirect('myapp:category_list')\n else:\n form = CategoryForm(instance=instance)\n return render(request, 'myapp/categories_edit.html', {'form': form,'pk':pk})\n\n#delete\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef delete_category(request, pk):\n category = get_object_or_404(Categories, pk=pk)\n try:\n category.delete()\n messages.success(request, \"Category deleted succesfully\")\n except IntegrityError:\n messages.warning(request, \"category cannot be deleted because of integrity\")\n\n return redirect('myapp:category_list')\n\n#---------------------------product attribute----------------------------#\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef Product_Attribute(request):\n product_attributes = ProductAttribute.objects.order_by('id')\n page = request.GET.get('page', 1)\n paginator = Paginator(product_attributes, 4)\n try:\n product_attributes = paginator.page(page)\n except PageNotAnInteger:\n product_attributes = paginator.page(1)\n except EmptyPage:\n product_attributes = paginator.page(paginator.num_pages)\n\n if request.method == 'POST':\n page_n = request.POST.get('page_n', None) # getting page number\n\n product_attributes = paginator.page(page_n).object_list\n\n return render(request, 'attribute/product_attribute.html', {'product_attributes': product_attributes})\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef Product_Attribute_Add(request):\n\n if request.method == 'POST':\n form=ProductAttributeForm(request.POST)\n if form.is_valid():\n instance=form.save(commit=False)\n instance.created_by = request.user\n instance.modified_by = request.user\n instance.save()\n messages.success(request, \"Attribute added succesfully\")\n return redirect('myapp:ProductAttribute')\n else:\n form=ProductAttributeForm()\n return render(request, 'attribute/product_attribute_add.html', {'form': form})\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef Product_Attribute_Edit(request,id):\n instance=get_object_or_404(ProductAttribute,id=id)\n if request.method == 'POST':\n form = ProductAttributeEditForm(request.POST, instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.modified_by = request.user\n instance.save()\n messages.success(request, \"Attribute edited succesfully\")\n return redirect('myapp:ProductAttribute')\n else:\n form = ProductAttributeEditForm(instance=instance)\n return render(request, 'attribute/product_attribute_edit.html', {'form': form,'id':id})\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef Product_Attribute_Delete(request,id):\n data = get_object_or_404(ProductAttribute, id=id)\n try:\n data.delete()\n messages.success(request, \"product attribute deleted succesfully\")\n except IntegrityError:\n messages.warning(request, \"product attribute have products so cant delete\")\n\n return redirect('myapp:ProductAttribute')\n\n#---------------------------product attribute----------------------------#\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef Product_Attribute_Value(request):\n product_attribute_values = ProductAttributeValue.objects.order_by('id')\n page = request.GET.get('page', 1)\n paginator = Paginator(product_attribute_values, 4)\n try:\n product_attribute_values = paginator.page(page)\n except PageNotAnInteger:\n product_attribute_values = paginator.page(1)\n except EmptyPage:\n product_attribute_values = paginator.page(paginator.num_pages)\n\n if request.method == 'POST':\n page_n = request.POST.get('page_n', None) # getting page number\n\n product_attribute_values = paginator.page(page_n).object_list\n return render(request, 'attribute/product_att_value.html', {'product_attribute_values': product_attribute_values})\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef Product_Attribute_Value_Add(request):\n if request.method == 'POST':\n form = ProductAttributeValueForm(request.POST)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.created_by = request.user\n instance.modified_by = request.user\n instance.save()\n messages.success(request, \"Attribute value added succesfully\")\n return redirect('myapp:ProductAttributeValue')\n else:\n form = ProductAttributeValueForm()\n return render(request, 'attribute/product_att_value_add.html', {'form': form})\n\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef Product_Attribute_Value_Edit(request,id):\n instance=get_object_or_404(ProductAttributeValue,id=id) # we want form with data of a speciifc id\n if request.method==\"POST\":\n form = ProductAttributeValueForm(request.POST, instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.modify_by = request.user\n instance.save()\n # form.save_m2m()\n messages.success(request, \"product attribute value updated successfuly\")\n return redirect('myapp:ProductAttributeValue')\n else:\n form = ProductAttributeValueForm(instance=instance)\n return render(request, 'attribute/product_att_value_edit.html', {'form': form, 'id': id})\n\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef Product_Attribute_Value_Delete(request,id):\n data = get_object_or_404(ProductAttribute, id=id) # or ProductAttribute.objects.get(id=id)\n try:\n data.delete()\n messages.success(request, \"attribute value deleted succesfully\")\n except IntegrityError:\n messages.warning(request, \"product attribute have products so cant delete\")\n return redirect('myapp:ProductAttributeValue')\n\n\n#---------------------------products----------------------------#\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef product_list(request):\n products = Product.objects.order_by('id') # retrive all products\n page = request.GET.get('page', 1)\n paginator = Paginator(products, 5)\n try:\n products = paginator.page(page)\n except PageNotAnInteger:\n products = paginator.page(1)\n except EmptyPage:\n products = paginator.page(paginator.num_pages)\n\n if request.method == 'POST':\n page_n = request.POST.get('page_n', None) # getting page number\n\n products = paginator.page(page_n).object_list\n context = {'products': products}\n return render(request, 'myapp/products_list.html', context)\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef add_new_product(request):\n ProductImageFormSet=inlineformset_factory(Product, ProductImage,form=ProductImageForm,extra=1)\n ProductAttributeFormset=inlineformset_factory(Product, ProductAttributeAssociation,form=ProductAttributeAssociationForm,extra=2)\n ProductMetaFormset=inlineformset_factory(Product, ProductMeta,form=ProductMetaForm,extra=1)\n\n if request.method == \"POST\":\n form1 = ProductForm(request.POST)\n formset1 = ProductImageFormSet(request.POST, request.FILES)\n formset2 = ProductMetaFormset(request.POST)\n formset3 = ProductAttributeFormset(request.POST)\n\n if form1.is_valid() and formset1.is_valid() and formset2.is_valid() and formset3.is_valid():\n #Each query is immediately committed to the db\n with transaction.atomic():\n instance = form1.save(commit=False)\n instance.created_by=request.user\n instance.modified_by=request.user\n instance.save()\n form1.save_m2m()\n\n for image in formset1:\n if image.is_valid():\n image=image.save(commit=False)\n image.product=instance\n image.save()\n\n for data in formset2:\n if data.is_valid():\n data=data.save(commit=False)\n data.product=instance\n data.save()\n\n for attribute in formset3:\n if attribute.is_valid() and attribute.has_changed():\n attribute=attribute.save(commit=False)\n attribute.product_id=instance\n attribute.save()\n\n messages.success(request,\"Product added successfully\")\n return redirect(\"myapp:ProductList\")\n else:\n form1 = ProductForm()\n formset1 = ProductImageFormSet()\n formset2 = ProductMetaFormset()\n formset3 = ProductAttributeFormset()\n return render(request,\"myapp/product_add.html\",{'form1':form1,\n 'formset1':formset1,\n 'formset2':formset2,\n 'formset3':formset3})\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef edit_product(request, id):\n product = get_object_or_404(Product, id=id)\n ProductImageFormSet = inlineformset_factory(Product, ProductImage, form=ProductImageForm, extra=1)\n ProductAttributeFormset = inlineformset_factory(Product, ProductAttributeAssociation,\n form=ProductAttributeAssociationForm, extra=1)\n ProductMetaFormset = inlineformset_factory(Product, ProductMeta, form=ProductMetaForm, extra=1)\n\n if request.method == 'POST':\n form1 = ProductForm(request.POST, instance=product)\n formset1 = ProductImageFormSet(request.POST, request.FILES, instance=product)\n formset2 = ProductMetaFormset(request.POST, instance=product)\n formset3 = ProductAttributeFormset(request.POST, instance=product)\n\n if form1.is_valid() and formset1.is_valid() and formset2.is_valid() and formset3.is_valid():\n with transaction.atomic():\n # import pdb\n # pdb.set_trace()\n instance = form1.save(commit=False)\n instance.modify_by = request.user\n instance.save()\n form1.save_m2m()\n formset3.save()\n\n for image in formset1:\n if image.is_valid() and image.has_changed():\n image = image.save(commit=False)\n image.product = instance\n image.save()\n\n instance2 = formset1.save(commit=False)\n for obj in formset1.deleted_objects:\n obj.delete()\n\n instance3 = formset2.save(commit=False)\n for obj in formset2.deleted_objects:\n obj.delete()\n\n instance4 = formset3.save(commit=False)\n for obj in formset3.deleted_objects:\n obj.delete()\n\n messages.success(request, \"product edited succesfully\")\n return redirect('myapp:ProductList')\n\n else:\n form1 = ProductForm(request.GET or None, instance=product)\n formset1 = ProductImageFormSet(instance=product)\n formset2 = ProductMetaFormset(instance=product)\n formset3 = ProductAttributeFormset(instance=product)\n\n return render(request, 'myapp/product_edit.html',\n {'form1': form1, 'formset1': formset1, 'formset2': formset2,'formset3':formset3, 'id': id})\n\n# def load_product_attribute_value(request):\n# product_attribute_id = request.GET.get('product_attribute_id')\n# print(product_attribute_id)\n# product_attribute_value_ids = ProductAttributeValue.objects.filter(attribute_name=product_attribute_id)\n# return render(request, 'attribute/product_attribute_list_options.html',\n# {'product_attribute_value_ids': product_attribute_value_ids})\n\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef delete_product(request, id):\n product = get_object_or_404(Product, id=id)\n try:\n product.delete()\n messages.success(request, \"Product deleted succesfully\")\n except IntegrityError:\n messages.warning(request, \"Product cannot be deleted because of integrity\")\n return redirect('myapp:ProductList')\n\n\n#________________________________________Banner__________________________________________#\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef banner_list(request):\n banner=Banner.objects.order_by('id')\n page = request.GET.get('page', 1)\n paginator = Paginator(banner, 3)\n try:\n banner = paginator.page(page)\n except PageNotAnInteger:\n banner = paginator.page(1)\n except EmptyPage:\n banner = paginator.page(paginator.num_pages)\n\n if request.method == 'POST':\n page_n = request.POST.get('page_n', None) # getting page number\n\n banner = paginator.page(page_n).object_list\n return render(request,'myapp/banner.html',{'banners':banner})\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef new_banner(request):\n if request.method=='POST':\n form=BannerForm(request.POST)\n if form.is_valid():\n instance=form.save(commit=False)\n instance.save()\n messages.success(request,\"Banner added successfully.\")\n return redirect('myapp:BannerList')\n else:\n form=BannerForm()\n return render(request,'myapp/banner_add.html',{'form':form})\n\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef edit_banner(request, id):\n banner = get_object_or_404(Banner, id=id)\n if request.method == \"POST\":\n form =BannerForm(request.POST, instance=banner)\n if form.is_valid():\n banner = form.save(commit=False)\n #instance.modify_by = request.user\n banner.save() # add data to database\n messages.success(request, \"banner updated successfuly\")\n return redirect('myapp:BannerList')\n else:\n form = BannerForm(instance=banner)\n return render(request, 'myapp/banner_edit.html', {'form': form,'id':id})\n\n#delete\n@login_required(login_url='myapp:login')\n@allowed_users(allowed_roles=['admin'])\ndef delete_banner(request, id):\n instance = get_object_or_404(Banner, id=id)\n try:\n instance.delete()\n messages.success(request, \"banner deleted succesfully\")\n except IntegrityError:\n messages.warning(request, \"banner cannot be deleted because of integrity\")\n\n return redirect('myapp:BannerList')\n","sub_path":"new_admin_django/ecommerce/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":25325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"298798393","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2017年3月7日\n@author: guanglin\n'''\nimport sys,os,shutil,chardet,time\nprint('Current DIR: '+os.getcwd())\nparent_path=r'C:\\Users\\guanglin\\git\\shrimp_py\\src\\os\\\\'\ncnt_file=parent_path+r'read2.txt'\nif not os.path.exists(cnt_file):\n print(cnt_file+'不存在。')\n os._exit(1)\nprint('文件大小:%d字节' %os.path.getsize(cnt_file))\nfp=open(cnt_file,'r')\nmyline=fp.read()\nfcode=chardet.detect(myline)['encoding']\nprint('File encoding:'+fcode)\nif fcode != 'utf-8':\n fcode='gbk'\nprint('sys.stdin.encoding==>'+sys.stdin.encoding)\nfp.close()\n########read()\n# fp=open(cnt_file,'r')\n# myline=fp.read()\n# fcode=chardet.detect(myline)['encoding']\n# print 'File coding:'+fcode\n# fp.seek(0)\n# print '====='+cnt_file+'=====\\n'+myline+'\\n=========='\n# for line in myline:\n# print line\n# fp.close()\n############迭代\nfp=open(cnt_file,'r')\nfor i in fp:\n print(i.strip('\\n\\r').decode(fcode).encode(sys.stdin.encoding))\nfp.close()\n#########readline()\n# fp=open(cnt_file,'r')\n# # fp.seek(15,0)\n# myline=fp.readline()\n# while myline:\n# # print fp.tell()\n# print myline.strip('\\r\\n')\n# myline=fp.readline()\n# fp.close()\n##########readlines()\n# fp=open(cnt_file,'r')\n# \n# lines=fp.readlines()\n# for myline in lines:\n# print myline.strip('\\r\\n')\n# fp.close()\ntime.sleep(3)","sub_path":"src/OS/file-r.py","file_name":"file-r.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"311877462","text":"import sys\nsys.path.append('../Grupo1/Librerias/storageManager')\nsys.path.append('../Grupo1/Librerias/')\nsys.path.append('../Grupo1/Instrucciones/')\nsys.path.append('../Grupo1/Utils')\nsys.path.append('../Grupo1')\n\nimport gramatica as g\nfrom enum import Enum\nimport math\nimport random\nimport hashlib \nfrom jsonMode import *\nimport Utils.Lista as l\n\nfrom tkinter import * #importando tkinter\nimport tkinter as TK\nimport Utils.TablaSimbolos as table\nimport Utils.Lista as l\nimport Librerias.storageManager.jsonMode as storage\nimport Librerias.storageManager.c3dGen as c3dgen\nfrom tkinter.filedialog import askopenfilename as files\nimport os\nimport webbrowser\nfrom Utils.fila import fila\nfrom Error import *\nimport Instrucciones.DML.select as select\nimport json\n\n\n\n\n#from storageManager import jsonMode as manager\nstorage.dropAll() \ndatos = l.Lista({}, '')\ndef createDB(database: str) :\n \n instruccion = g.parse(\"CREATE DATABASE IF NOT EXISTS test OWNER = 'root' MODE = 1;\")\n erroresSemanticos = []\n for instr in instruccion['ast'] :\n \n if instr != None:\n result = instr.executec3d(datos)\n #print(result+'--MF')\n if isinstance(result, Error):\n #print(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")\n \n print(str(result.desc))\n erroresSemanticos.append(result)\n elif isinstance(instr, select.Select) or isinstance(instr, select.QuerysSelect):\n print(str(instr.ImprimirTabla(result)))\n else:\n print(str(result))\n\n\n #*********************** CREATE DB ****************************\n resultado = 10 #createDatabase(database)\n \n if resultado==0:\n print('Base de datos ' + database + ' creada correctamente')\n elif resultado==2:\n print('Error al crear la base de datos ' + database + '. El nombre ya existe')\n elif resultado==1:\n print('Ha ocurrido un error al crear la base de datos ' + database + '.')\n elif resultado==0:\n print('Error desconocido')\n\n\n# READ and show databases by constructing a list\ndef showDB() :\n \n resultado = showDatabases()\n print(resultado)\n\n# READ and show databases by constructing a list\ndef useDatabase(database: str) : \n\n instruccion = g.parse(\"USE TEST;\")\n erroresSemanticos = []\n for instr in instruccion['ast'] :\n \n if instr != None:\n result = instr.executec3d(datos)\n #print(result+'--MF')\n if isinstance(result, Error):\n print(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")\n \n print(str(result.desc))\n erroresSemanticos.append(result)\n elif isinstance(instr, select.Select) or isinstance(instr, select.QuerysSelect):\n print(str(instr.ImprimirTabla(result)))\n else:\n print(str(result))\n\n \n print('Use ' + database)\n\n# CREATE a table checking their existence\ndef createTbl(database: str, table: str, listColumns: any):\n \n cadenaE = 'CREATE TABLE ' + table.upper() + \" (\"\n contaCol=0\n for colIns in listColumns:\n if contaCol==0:\n cadenaE = cadenaE + colIns\n else:\n cadenaE = cadenaE + \", \" + colIns\n contaCol +=1\n \n cadenaE = cadenaE + \");\"\n\n # instruccion = g.parse('CREATE TABLE tbProducto (idproducto integer primary key, \\\n \t# \t\t\t\t\t producto varchar(150), \\\n \t# \t\t\t\t\t fechacreacion date, \\\n\t# \t\t\t\t\t estado integer);')\n\n instruccion = g.parse(cadenaE)\n\n erroresSemanticos = []\n for instr in instruccion['ast'] :\n \n if instr != None:\n result = instr.executec3d(datos)\n #print(result+'--MF')\n if isinstance(result, Error):\n #print(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")\n \n print(str(result.desc))\n erroresSemanticos.append(result)\n elif isinstance(instr, select.Select) or isinstance(instr, select.QuerysSelect):\n print(str(instr.ImprimirTabla(result)))\n else:\n print(str(result))\n\n\n\n resultado = 10 #createTable(database, table, numberColumns)\n\n if resultado == 1:\n print('Error(42P16): invalid_table_definition.')\n elif resultado == 2:\n print('Error(???): No existe la base de datos.')\n elif resultado == 3:\n print('Error(42P07): duplicate_table.')\n elif resultado == 0:\n print('Tabla ' + table + ' creada correctamente')\n\n\n# a table checking their existence\ndef insertC3D(database: str, table: str, register: list):\n #print('************ registro') \n #print(register)\n\n cadenaIns = 'INSERT INTO ' + table + ' VALUES('\n contadorCampos=0\n for campoIns in register:\n if contadorCampos==0:\n if es_numero(campoIns):\n cadenaIns = cadenaIns + str(campoIns)\n else:\n fTipo = campoIns.find(\"NOW\") \n if fTipo >=0 :\n cadenaIns = cadenaIns + str(campoIns) \n else:\n cadenaIns = cadenaIns + \"'\" + str(campoIns) + \"'\"\n else:\n if es_numero(campoIns):\n cadenaIns = cadenaIns + \",\" + str(campoIns)\n else:\n fTipo = campoIns.find(\"NOW\") \n if fTipo >=0 :\n cadenaIns = cadenaIns + \",\" + str(campoIns) \n else:\n cadenaIns = cadenaIns + \",'\" + str(campoIns) + \"'\"\n\n contadorCampos+=1; \n cadenaIns = cadenaIns + \");\"\n\n\n instruccion = g.parse(cadenaIns)\n erroresSemanticos = []\n for instr in instruccion['ast'] :\n \n if instr != None:\n result = instr.executec3d(datos)\n #print(result+'--MF')\n if isinstance(result, Error):\n print(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")\n \n print(str(result.desc))\n erroresSemanticos.append(result)\n elif isinstance(instr, select.Select) or isinstance(instr, select.QuerysSelect):\n print(str(instr.ImprimirTabla(result)))\n else:\n print(str(result))\n\n resultado = 100 #insert(database, table, register)\n if resultado == 1:\n print('Error(42P16): invalid_table_definition.')\n elif resultado == 2:\n print('Error(???): No existe la base de datos.')\n elif resultado == 3:\n print('Error(???): No existe la tabla.')\n elif resultado == 4:\n print('Error(???): Llave primaria duplicada.')\n elif resultado == 5:\n print('Error(???): No coincide el numero de campos.')\n elif resultado == 0:\n print('Dato insertado correctamente')\n\ndef updateC3D(database: str, table: str, register: dict, columns: list):\n #print('************ registro') \n #print(register)\n resultado = update(database, table, register, columns)\n if resultado == 1:\n print('Error(42P16): invalid_table_definition.')\n elif resultado == 2:\n print('Error(???): No existe la base de datos.')\n elif resultado == 3:\n print('Error(???): No existe la tabla.')\n elif resultado == 4:\n print('Error(???): Llave primaria no existe.')\n elif resultado == 5:\n print('Error(???): No coincide el numero de campos.')\n elif resultado == 0:\n print('Update realizado correctamente')\n\ndef selectC3D(database: str, columns: any, tablas: any, cwhere: str):\n #print('************ registro') \n #print(register)\n\n cadenaE = 'SELECT '\n contCampos=0\n for i in columns:\n if contCampos==0:\n cadenaE = cadenaE + str(i)\n else:\n cadenaE = cadenaE + ', ' + str(i)\n contCampos+=1\n \n if len(tablas)>0:\n cadenaE = cadenaE + ' FROM ' \n contCampos=0\n for j in tablas:\n if contCampos==0:\n cadenaE = cadenaE + str(j)\n else:\n cadenaE = cadenaE + ', ' + str(j)\n contCampos+=1\n\n if len(cwhere)>0:\n cadenaE = cadenaE + ' WHERE ' + cwhere \n cadenaE = cadenaE + ';'\n instruccion = g.parse(cadenaE)\n erroresSemanticos = []\n for instr in instruccion['ast'] :\n varValor=0\n if instr != None:\n result = instr.executec3d(datos)\n #print(result+'--MF')\n if isinstance(result, Error): \n print(str(result.desc))\n erroresSemanticos.append(result)\n elif isinstance(instr, select.Select) or isinstance(instr, select.QuerysSelect):\n if 'count' in result:\n varValor = result['count']['columnas'][0] \n else:\n contResult=0\n varColName=''\n for colRes in result.keys():\n varColName = colRes\n contResult+=1\n if contResult==1:\n varValor = result[varColName]['columnas'][0][0]\n else:\n print(str(instr.ImprimirTabla(result)))\n\n else: \n print(str(result))\n \n\n\n resultado = 100 #update(database, table, register, columns)\n if resultado == 1:\n print('Error(42P16): invalid_table_definition.')\n elif resultado == 2:\n print('Error(???): No existe la base de datos.')\n elif resultado == 3:\n print('Error(???): No existe la tabla.')\n elif resultado == 4:\n print('Error(???): Llave primaria no existe.')\n elif resultado == 5:\n print('Error(???): No coincide el numero de campos.')\n elif resultado == 0:\n print('Update realizado correctamente')\n\n return varValor\n\n\ndef existTableC3D(database: str, table: str) -> bool: \n resultado = existTable(database,table)\n if resultado is False:\n print('La tabla no existe')\n return resultado\n\ndef es_numero(variable : any):\n try:\n float(variable)\n return True\n except :\n return False\n\n# show databases by constructing a list\ndef showTables(database: str) -> list:\n resultado = showTables(database)\n print(resultado)","sub_path":"parser/fase2/team01/Grupo1/c3d/sentencias.py","file_name":"sentencias.py","file_ext":"py","file_size_in_byte":10534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"95321249","text":"from vogue.commands.load.application_tag import application_tags\nfrom vogue.server import create_app\nfrom vogue.commands.base import cli\nfrom vogue.adapter.plugin import VougeAdapter\n\napp = create_app(test=True)\n\n\ndef test_application_tag(database):\n app.db = database\n app.adapter = VougeAdapter(database.client, db_name=database.name)\n\n # GIVEN a correct foramted input string\n app_tags = '[{\"tag\":\"MELPCFR030\", \"prep_category\":\"wgs\"}, {\"tag\":\"MELPCFR090\", \"prep_category\":\"hej\"}]'\n\n # WHEN adding a application tags\n runner = app.test_cli_runner()\n result = runner.invoke(cli, ['load', 'apptag', app_tags])\n\n # THEN assert the new apptags should be added to the colleciton\n assert app.adapter.app_tag_collection.estimated_document_count() == 2\n assert app.adapter.app_tag('MELPCFR030')['category'] == 'wgs'\n assert app.adapter.app_tag('MELPCFR090')['category'] == 'hej'\n\n\ndef test_application_tag_missing_tag(database):\n app.db = database\n app.adapter = VougeAdapter(database.client, db_name=database.name)\n\n # GIVEN a a input where the tag key is missing for one of the application tag dicts\n app_tags = '[{\"category\":\"wgs\"}, {\"tag\":\"MELPCFR030\", \"category\":\"wgs\"}]'\n\n # WHEN adding a application tags\n runner = app.test_cli_runner()\n result = runner.invoke(cli, ['load', 'apptag', app_tags])\n\n # THEN assert the new apptag should be added to the colleciton\n assert app.adapter.app_tag_collection.estimated_document_count() == 1\n\n\ndef test_application_tag_wrong_input(database):\n app.db = database\n\n # GIVEN a badly foramted input string\n app_tags = \"[{'tag':'MELPCFR030', 'category':'wgs'}]}\"\n\n # WHEN adding a application tags\n runner = app.test_cli_runner()\n result = runner.invoke(cli, ['load', 'apptag', app_tags])\n\n # THEN assert Badly formated json! Can not load json. Exiting.\n assert result.exit_code == 1\n","sub_path":"tests/cli/load/test_load_application_tag.py","file_name":"test_load_application_tag.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"476768137","text":"# a generator returns an object (iterator) which we can iterate over.\n# every generator object is one-time use\n# to store result of generation, it's best to assign generator object to variable\n\n# generator functions are usually made as a loop with a suitable end condition\n# they accept an iterable\n# generator function goes like this:\n# yield returns a value and pauses the function saving local state\ndef countdown(num):\n while num > 0:\n yield num\n num -= 1\n\n# Calling the function does not execute it\n# It creates generator object\nval = countdown(5)\nval1 = countdown(6)\n\n# Each next() call executes function until yield\n# Every subsequent call continues from after yield until next yeild\nprint(next(val), \"-> Expected 5\")\nprint(next(val1), \"-> Expected 6\")\nprint(next(val), \"-> Expected 4\")\nprint(next(val1), \"-> Expected 5\")\nprint(next(val), \"-> Expected 3\")\nprint(next(val1), \"-> Expected 4\")\nprint(next(val), \"-> Expected 2\")\nprint(next(val1), \"-> Expected 3\")\nprint(next(val), \"-> Expected 1\")\nprint(next(val1), \"-> Expected 2\")\n\n# If the iteration is impossible, the error is raised\ntry:\n print(next(val))\nexcept StopIteration:\n print(\"The countdown is over\")\n\n# You may loop through iterator (created by gen. expression or gen. function)\nval2 = countdown(7)\nprint(\"Looping with generator function\")\nfor x in val2:\n print(x)\n\n# Generator expression does the same as list comprehension but lazily\ngenerator_range = (x for x in range(10)) # this is generator expression\nlist_range = [x for x in range(10)] # this is list comprehension\n\n# Generator is in fact an anonymous generator function\nval3 = (x for x in range(7))\nprint(\"Looping with generator expression\")\nfor x in val3:\n print(x)\n\n# The best way to \"reverse\" an iterator would be to reversed(list(iter)) which returns an iterator\nval3_reversed = reversed(list(val3))\n\n# They are faster for large data size compared to available memory\nmy_generator = (x for x in range(1111))\nprint(sum(my_generator))\n\n# Why to use them:\n# 1. Easy to implement compared to iterators\n# 2. Represent an infinite stream\n# This one can generate all even numbers, in theory.\ndef all_even():\n n = 0\n while True:\n yield n\n n += 2\n\n# 3. Pipeline operations\ndef even_filter(nums):\n for num in nums:\n if num % 2 == 0:\n yield num\ndef multiply_by_three(nums):\n for num in nums:\n yield num * 3\ndef convert_to_string(nums):\n for num in nums:\n yield f'The Number: {num}'\n\nnums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\npipeline = convert_to_string(multiply_by_three(even_filter(nums)))\nfor num in pipeline:\n print (num)\n\n# Use .send() method which sends values to yield\ndef coroutine():\n result = yield\n yield result\n\ngenerator = coroutine()\nnext(generator)\na = generator.send(5)\nprint(a)\n\n# 'next(generator)' is exactly equivalent to 'generator.send(None)'\n\n# generators are great for parsing large amounts of data without handling everything at once\n# generator functions get one item at a time, and generators get the entire data for such functions\n# Simple examples are here: https://realpython.com/introduction-to-python-generators/#generator-expressions (Use Cases)\n","sub_path":"Main_practice/generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"181725252","text":"from scanner import Symbol\nfrom scanner import Scanner\nfrom names import Names\nfrom error import Error\nimport sys\nimport os\n\n\ndef open_file(path):\n try:\n \"\"\"Open and return the file specified by path for reading\"\"\"\n return open(path, \"r\", encoding=\"utf-8\")\n except IOError:\n print(\"error, can't find or open file\")\n sys.exit()\n\n\n\ndef main():\n \"\"\"Preliminary exercises for Part IIA Project GF2.\"\"\"\n\n # Check command line arguments\n arguments = sys.argv[1:]\n if len(arguments) != 1:\n print(\"Error! One command line argument is required.\")\n sys.exit()\n\n else:\n print(\"\\nNow opening file...\")\n # Print the path provided and try to open the file for reading\n path = os.getcwd()+ \"/\" + arguments[0]\n print(path) #print path\n scan = Scanner(path, Names())\n print(\"scanning from: \" + path)\n print(\"\")\n print(\"type\\tid\\tline#\\tstart_char#\\tend_char#\\tstring\")\n i = 0\n while True:\n #initial symbol listing\n symbol = scan.get_symbol()\n print(symbol.type, end=\"\\t\")\n print(symbol.id, end=\"\\t\")\n print(symbol.line_number, end=\"\\t\")\n print(symbol.start_char_number, end=\"\\t\\t\")\n print(symbol.end_char_number, end=\"\\t\\t\")\n print(symbol.string)\n if(symbol.type == scan.EOF):\n break\n i += 1\n #calling an error for each symbol\n Error(i%20,symbol)\n\n print(\"printing error message\\n\\n\\n\")\n #printing error\n Error.print_error(scan)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"final/practice_test_error.py","file_name":"practice_test_error.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"413598110","text":"import contextlib\n\nimport babel\nimport langcodes\nfrom langcodes.tag_parser import LanguageTagError\nfrom redbot.core import commands, i18n\nfrom redbot.core.utils.chat_formatting import humanize_number\n\ntick = \"\\N{WHITE HEAVY CHECK MARK} \"\ncross = \"\\N{CROSS MARK} \"\nvalid = lambda t, b: tick + t if b else cross + t\n\n##########################################################################\n# This cog is hidden from the Red index, whilst its still being developed.\n##########################################################################\n\nclass Locales(commands.Cog):\n \"\"\"\n Get information about locales and language codes.\n \"\"\"\n\n __author__ = [\"Kreusada\"]\n __version__ = \"1.0.3\"\n\n def __init__(self, bot):\n self.bot = bot\n\n def format_help_for_context(self, ctx: commands.Context) -> str:\n context = super().format_help_for_context(ctx)\n authors = \", \".join(self.__author__)\n return f\"{context}\\n\\nAuthor: {authors}\\nVersion: {self.__version__}\"\n\n async def get_country_from_locale(self, ctx, lang):\n bot_locale = await i18n.get_locale_from_guild(self.bot, ctx.guild)\n x = langcodes.Language.get(lang).describe(bot_locale.split('-')[0])[\"language\"].capitalize()\n if x.startswith(\"Unknown\"):\n return False\n return x\n\n def cog_unload(self):\n with contextlib.suppress(Exception):\n self.bot.remove_dev_env_value(\"locales\")\n\n async def initialize(self) -> None:\n if 719988449867989142 in self.bot.owner_ids:\n with contextlib.suppress(Exception):\n self.bot.add_dev_env_value(\"locales\", lambda x: self)\n\n async def red_delete_data_for_user(self, **kwargs):\n \"\"\"Nothing to delete.\"\"\"\n return\n\n @commands.group()\n async def locale(self, ctx):\n \"\"\"Get information about locales and language codes.\"\"\"\n pass\n\n @locale.command()\n async def isvalid(self, ctx, language_code: str):\n \"\"\"See if a language code is valid.\"\"\"\n with contextlib.suppress(LanguageTagError):\n code = langcodes.Language.get(language_code).is_valid()\n if code:\n return await ctx.send(valid(\"That is a valid language code.\", True))\n await ctx.send(valid(\"That is not a valid language code.\", False))\n\n @locale.command()\n async def get(self, ctx, language_code: str):\n \"\"\"Get the language from a language code.\"\"\"\n bot_locale = await i18n.get_locale_from_guild(self.bot, ctx.guild)\n with contextlib.suppress(LanguageTagError):\n lang = langcodes.Language.get(language_code).display_name(bot_locale)\n if not lang.startswith(\"Unknown language\"):\n return await ctx.send(lang.capitalize())\n await ctx.send(\"Unknown language code.\")\n\n @locale.command()\n async def bot(self, ctx):\n \"\"\"Get your bot's locale.\"\"\"\n bot_locale = await i18n.get_locale_from_guild(self.bot, ctx.guild)\n is_owner = await self.bot.is_owner(ctx.author)\n msg = f\"{ctx.me.name}'s locale is {bot_locale}.\"\n if is_owner:\n msg += f\"\\nYou can change it through `{ctx.clean_prefix}set locale`.\"\n await ctx.send(msg)\n\n @locale.command(usage=\"<language_code> [writing_or_speaking]\")\n async def populous(self, ctx, language_code: str, writing_or_speaking: str = \"speaking\"):\n \"\"\"Get the number of speakers/writers for a language.\"\"\"\n language_code = language_code.split('-')[0]\n with contextlib.suppress(LanguageTagError):\n if not writing_or_speaking.lower()[0] in [\"s\", \"w\"]:\n return await ctx.send(f\"Please specify 'writing' or 'speaking', not '{writing_or_speaking}''.\")\n country_name = await self.get_country_from_locale(ctx, language_code)\n if not country_name:\n return await ctx.send(valid(\"That is not a valid language code.\", False))\n speaking = langcodes.Language.get(language_code).speaking_population()\n writing = langcodes.Language.get(language_code).writing_population()\n text = \"Over {} people {} {}.\"\n if writing_or_speaking.startswith(\"s\"):\n data = humanize_number(speaking)\n grammar = \"speak\"\n else:\n data = humanize_number(writing)\n grammar = \"write in\"\n return await ctx.send(text.format(data, grammar, country_name))\n await ctx.send(f\"Unrecognized language code: '{language_code}'.\")\n","sub_path":"locales/locales.py","file_name":"locales.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"492068830","text":"# shortest_path\n\nimport numpy as np\nfrom scipy.sparse import csgraph\nfrom scipy.sparse import csr_matrix\n\n\ndef main():\n # Arr : 隣接行列\n # sample\n Arr = np.array([[0, 1, 2, 0],\n [0, 0, 0, 1],\n [3, 0, 0, 3],\n [0, 0, 0, 0]])\n\n # 全点対最短経路\n d = csgraph.shortest_path(Arr)\n print(d)\n # 単一始点最短経路\n start = 0\n d = csgraph.shortest_path(Arr, indices=start)\n start2 = 1\n d = csgraph.shortest_path(Arr, indices=[start, start2])\n\n # 最短経路獲得\n d, p = csgraph.shortest_path(Arr, return_predecessors=True)\n start = 0\n end = 3\n root = get_path(start, end, p)\n\n # その他引数について\n '''\n directed: bool: デフォルトはTrue\n unweighted: bool: デフォルトはFalse, Trueだとすべての重みを1にする\n '''\n\n # optional\n '''\n method選択によって高速化が可能\n dijkstraを使いたいときは, 引数limitが必要になる\n numpy arrayじゃなくてcsr_matrixの方が高速らしい\n '''\n N = 5\n cost = [1, 2, 1, 3, 3]\n starts = [0, 0, 1, 2, 2]\n nexts = [1, 2, 3, 0, 3]\n csr = csr_matrix((cost, (starts, nexts)), shape=(N, N))\n print(csr)\n\n\ndef get_path(start, goal, pred):\n return get_path_row(start, goal, pred[start])\n\n\ndef get_path_row(start, goal, pred_row):\n path = []\n i = goal\n while i != start and i >= 0:\n path.append(i)\n i = pred_row[i]\n if i < 0:\n return []\n path.append(i)\n return path[::-1]\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"components/search/shortest_path.py","file_name":"shortest_path.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"607640778","text":"from openpyxl import load_workbook\nfrom get_data_excel import get_excel_data\nimport csv\n\n\ndef get_identifier(row):\n return row['StrId']\n\n\ndef create_skipper(get_identifier):\n unique_item_identifiers = set([])\n def skipper(enumerable):\n for item in enumerable:\n if get_identifier(item) in unique_item_identifiers:\n continue # skip this one\n unique_item_identifiers.add(get_identifier(item))\n yield item\n return skipper\n\n\n\nif __name__ == '__main__':\n \n #sheet1 = workbook['SeldomAnnot']\n #sheet2 = workbook['SeldomAll']\n\n workbook_input = raw_input('enter spreadsheet name (should be xlsx): ') # open files\n workbook = load_workbook('./' + workbook_input + '.xlsx')\n #workbook column names: headers = [\"StrId\", \"ProjId\", \"TweetText\", \"Label\"]\n\n sheet_input1 = raw_input('enter first spreadsheet name (as it appears on the tab name): ') \n sheet_input2 = raw_input('enter second spreadsheet name (as it appears on the tab name): ') \n sheet1 = workbook[sheet_input1]\n sheet2 = workbook[sheet_input2]\n \n excel_data1 = get_excel_data(sheet1)\n \n excel_data2 = get_excel_data(sheet2) \n\n skipper = create_skipper(get_identifier)\n \n new_workbook_input = raw_input('enter the name of your new csv file: ')\n \n writer = csv.writer(open('./' + new_workbook_input + '.csv', 'w'))\n \n for row in skipper(excel_data1):\n str_id=row['StrId']\n projid=row['ProjId']\n tweet_text = row['TweetText'].encode('utf-8')\n writer.writerow([str_id,projid, tweet_text])\n for row in skipper(excel_data2):\n str_id=row['StrId']\n projid=row['ProjId']\n tweet_text = row['TweetText'].encode('utf-8')\n writer.writerow([str_id,projid, tweet_text])\n","sub_path":"duplicates/without_dupes_importing_excel_data2.py","file_name":"without_dupes_importing_excel_data2.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"561361261","text":"length = input(\"How tall are you?\")\nlength = float(length)\n\nweight = input(\"Whats your weight?\")\nweight = float(weight)\n\nif length > 100:\n\tlength = (length/100)\n\ndef bmi(length, weight):\n\tbmi = (float(weight)/(float(length)+float(length)))\n\tbmi = round(bmi,1)\n\tprint(\"If your weight is %s kg and your length is %s m, your BMI will be %s\" % (weight, length, bmi))\n\nbmi(length, weight)","sub_path":"bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"119234961","text":"__author__ = 'grburgess'\n\nimport collections\nimport warnings\n\nimport astropy.io.fits as fits\nimport numpy as np\nimport pandas as pd\n\nfrom threeML.plugins.EventListLike import EventListLike\nfrom threeML.utils.fermi_relative_mission_time import compute_fermi_relative_mission_times\nfrom threeML.utils.time_series.event_list import EventListWithLiveTime\nfrom threeML.exceptions.custom_exceptions import deprecated\n\n__instrument_name = \"Fermi LAT LLE\"\n\n\nclass BinningMethodError(RuntimeError):\n pass\n\n\nclass FermiLATLLELike(EventListLike):\n @deprecated('Please use the TimeSeriesBuilder for LAT LLE data. This plugin will soon disappear')\n def __init__(self, name, lle_file, ft2_file, rsp_file, source_intervals, background_selections=None, restore_background=None,\n trigger_time=None, poly_order=-1, unbinned=False, verbose=True):\n \"\"\"\n A plugin to natively bin, view, and handle Fermi LAT LLE data.\n An LLE event file and FT2 (1 sec) are required as well as the associated response\n\n\n\n Background selections are specified as\n a comma separated string e.g. \"-10-0,10-20\"\n\n Initial source selection is input as a string e.g. \"0-5\"\n\n One can choose a background polynomial order by hand (up to 4th order)\n or leave it as the default polyorder=-1 to decide by LRT test\n\n :param name: name of the plugin\n :param lle_file: lle event file\n :param ft2_file: fermi FT2 file\n :param background_selections: comma sep. background intervals as string\n :param source_intervals: comma sep. source intervals as string\n :param rsp_file: lle response file\n :param trigger_time: trigger time if needed\n :param poly_order: 0-4 or -1 for auto\n :param unbinned: unbinned likelihood fit (bool)\n :param verbose: verbose (bool)\n\n\n \"\"\"\n\n\n self._default_unbinned = unbinned\n\n self._lat_lle_file = LLEFile(lle_file, ft2_file, rsp_file)\n\n if trigger_time is not None:\n self._lat_lle_file.trigger_time = trigger_time\n\n # Mark channels less than 50 MeV as bad\n\n channel_50MeV = np.searchsorted(self._lat_lle_file.energy_edges[0],50000) - 1\n\n native_quality = np.zeros(self._lat_lle_file.n_channels,dtype=int)\n\n idx = np.arange(self._lat_lle_file.n_channels) < channel_50MeV\n\n native_quality[idx] = 5\n\n event_list = EventListWithLiveTime(\n arrival_times=self._lat_lle_file.arrival_times - self._lat_lle_file.trigger_time,\n energies=self._lat_lle_file.energies,\n n_channels=self._lat_lle_file.n_channels,\n live_time=self._lat_lle_file.livetime,\n live_time_starts=self._lat_lle_file.livetime_start - self._lat_lle_file.trigger_time,\n live_time_stops=self._lat_lle_file.livetime_stop - self._lat_lle_file.trigger_time,\n start_time=self._lat_lle_file.tstart - self._lat_lle_file.trigger_time,\n stop_time=self._lat_lle_file.tstop - self._lat_lle_file.trigger_time,\n quality=native_quality,\n first_channel=1,\n #rsp_file=rsp_file,\n instrument=self._lat_lle_file.instrument,\n mission=self._lat_lle_file.mission,\n verbose=verbose)\n\n super(FermiLATLLELike,self).__init__(name,\n event_list,\n rsp_file=rsp_file,\n source_intervals=source_intervals,\n background_selections=background_selections,\n poly_order=poly_order,\n unbinned=unbinned,\n verbose=verbose,\n restore_poly_fit=restore_background\n )\n\n def view_lightcurve(self, start=-10, stop=20., dt=1., use_binner=False, energy_selection=None,\n significance_level=None):\n \"\"\"\n\n :param use_binner: use the bins created via a binner\n :param start: start time to view\n :param stop: stop time to view\n :param dt: dt of the light curve\n :param energy_selection: string containing energy interval\n :return: None\n \"\"\"\n super(FermiLATLLELike, self).view_lightcurve(start=start,\n stop=stop,\n dt=dt,\n use_binner=use_binner,\n energy_selection=energy_selection,\n significance_level=significance_level)\n\n def _output(self):\n super_out = super(FermiLATLLELike, self)._output()\n return super_out.append(self._lat_lle_file._output())\n\n\nclass LLEFile(object):\n def __init__(self, lle_file, ft2_file, rsp_file):\n \"\"\"\n Class to read the LLE and FT2 files\n\n Inspired heavily by G. Vianello\n\n\n\n :param lle_file:\n :param ft2_file:\n \"\"\"\n\n with fits.open(rsp_file) as rsp_:\n\n data = rsp_['EBOUNDS'].data\n\n self._emin = data.E_MIN\n self._emax = data.E_MAX\n self._channels = data.CHANNEL\n\n with fits.open(lle_file) as ft1_:\n\n data = ft1_['EVENTS'].data\n\n self._events = data.TIME # - trigger_time\n self._energy = data.ENERGY * 1E3 # keV\n\n self._tstart = ft1_['PRIMARY'].header['TSTART']\n self._tstop = ft1_['PRIMARY'].header['TSTOP']\n self._utc_start = ft1_['PRIMARY'].header['DATE-OBS']\n self._utc_stop = ft1_['PRIMARY'].header['DATE-END']\n self._instrument = ft1_['PRIMARY'].header['INSTRUME']\n self._telescope = ft1_['PRIMARY'].header['TELESCOP'] + \"_LLE\"\n self._gti_start = ft1_['GTI'].data['START']\n self._gti_stop = ft1_['GTI'].data['STOP']\n\n try:\n self._trigger_time = ft1_['EVENTS'].header['TRIGTIME']\n\n\n except:\n\n # For whatever reason\n warnings.warn(\n \"There is no trigger time in the LLE file. Must be set manually or using MET relative times.\")\n\n self._trigger_time = 0\n\n # bin the energies into PHA channels\n # and filter out over/underflow\n self._bin_energies_into_pha()\n\n # filter events outside of GTIs\n\n self._apply_gti_to_events()\n\n with fits.open(ft2_file) as ft2_:\n\n ft2_tstart = ft2_['SC_DATA'].data.field(\"START\") # - trigger_time\n ft2_tstop = ft2_['SC_DATA'].data.field(\"STOP\") # - trigger_time\n ft2_livetime = ft2_['SC_DATA'].data.field(\"LIVETIME\")\n\n ft2_bin_size = 1.0 # seconds\n\n if not np.all(ft2_livetime <= 1.0):\n\n warnings.warn(\"You are using a 30s FT2 file. You should use a 1s Ft2 file otherwise the livetime \"\n \"correction will not be accurate!\")\n\n ft2_bin_size = 30.0 # s\n\n # Keep only the needed entries (plus a padding)\n idx = (ft2_tstart >= self._tstart - 10 * ft2_bin_size) & (\n ft2_tstop <= self._tstop + 10 * ft2_bin_size)\n\n self._ft2_tstart = ft2_tstart[idx]\n self._ft2_tstop = ft2_tstop[idx]\n self._livetime = ft2_livetime[idx]\n\n # now filter the livetime by GTI\n\n self._apply_gti_to_live_time()\n\n\n\n\n\n # Now sort all vectors\n idx = np.argsort(self._ft2_tstart)\n\n self._ft2_tstart = self._ft2_tstart[idx]\n self._ft2_tstop = self._ft2_tstop[idx]\n self._livetime = self._livetime[idx]\n\n def _apply_gti_to_live_time(self):\n \"\"\"\n This function applies the GTIs to the live time intervals\n\n It will remove any livetime interval not falling within the\n boundaries of a GTI. The FT2 bins are assumed to have the same\n boundaries as the GTI.\n\n Events falling outside the GTI boundaries are already removed.\n\n :return: none\n \"\"\"\n\n # First negate all FT2 entries\n\n filter_idx = np.zeros_like(self._livetime, dtype=bool)\n\n # now loop through each GTI interval\n\n for start, stop in zip(self._gti_start, self._gti_stop):\n\n # create an index of all the FT2 bins falling within this interval\n\n tmp_idx = np.logical_and(start <= self._ft2_tstart, self._ft2_tstop <= stop)\n\n # add them to the already selected idx\n filter_idx = np.logical_or(filter_idx, tmp_idx)\n\n # Now filter the whole list\n self._ft2_tstart = self._ft2_tstart[filter_idx]\n self._ft2_tstop = self._ft2_tstop[filter_idx]\n self._livetime = self._livetime[filter_idx]\n\n def _apply_gti_to_events(self):\n \"\"\"\n\n This created a filter index for events falling outside of the\n GTI. It must be run after the events are binned in energy because\n a filter is set up in that function for events that have energies\n outside the EBOUNDS of the DRM\n\n :return: none\n \"\"\"\n\n # initial filter\n filter_idx = np.zeros_like(self._events, dtype=bool)\n\n # loop throught the GTI intervals\n for start, stop in zip(self._gti_start, self._gti_stop):\n\n # capture all the events within that interval\n tmp_idx = np.logical_and(start <= self._events, self._events <= stop)\n\n # combine with the already selected events\n filter_idx = np.logical_or(filter_idx, tmp_idx)\n\n # filter from the energy selection\n self._filter_idx = np.logical_and(self._filter_idx, filter_idx)\n\n def is_in_gti(self, time):\n \"\"\"\n\n Checks if a time falls within\n a GTI\n\n :param time: time in MET\n :return: bool\n \"\"\"\n\n in_gti = False\n\n for start, stop in zip(self._gti_start, self._gti_stop):\n\n if (start <= time) and (time <= stop):\n\n in_gti = True\n\n return in_gti\n\n\n\n\n def _bin_energies_into_pha(self):\n \"\"\"\n\n bins the LLE data into PHA channels\n\n :return:\n \"\"\"\n\n edges = np.append(self._emin, self._emax[-1])\n\n self._pha = np.digitize(self._energy, edges)\n\n\n # There are some events outside of the energy bounds. We will dump those\n\n\n self._filter_idx = self._pha > 0\n\n self._n_channels = len(self._channels)\n\n @property\n def trigger_time(self):\n \"\"\"\n Gets the trigger time in MET\n :return: trigger time in MET\n \"\"\"\n return self._trigger_time\n\n @trigger_time.setter\n def trigger_time(self, val):\n\n assert self._tstart <= val <= self._tstop, \"Trigger time must be within the interval (%f,%f)\" % (\n self._tstart, self._tstop)\n\n self._trigger_time = val\n\n @property\n def tstart(self):\n return self._tstart\n\n @property\n def tstop(self):\n return self._tstop\n\n @property\n def arrival_times(self):\n \"\"\"\n The GTI/energy filtered arrival times in MET\n :return:\n \"\"\"\n return self._events[self._filter_idx]\n\n @property\n def energies(self):\n \"\"\"\n The GTI/energy filtered pha energies\n :return:\n \"\"\"\n return self._pha[self._filter_idx]\n\n @property\n def n_channels(self):\n return self._n_channels\n\n @property\n def mission(self):\n \"\"\"\n Return the name of the mission\n :return:\n \"\"\"\n return self._instrument\n\n @property\n def energy_edges(self):\n\n return np.vstack((self._emin,self._emax))\n\n @property\n def instrument(self):\n \"\"\"\n Return the name of the instrument and detector\n\n :return:\n \"\"\"\n\n return self._telescope\n\n @property\n def livetime(self):\n return self._livetime\n\n @property\n def livetime_start(self):\n return self._ft2_tstart\n\n @property\n def livetime_stop(self):\n return self._ft2_tstop\n\n\n\n def __repr__(self):\n\n return self._output().to_string()\n\n\n def _output(self):\n\n \"\"\"\n Examine the currently selected interval\n If connected to the internet, will also look up info for other instruments to compare with\n Fermi.\n\n :return: none\n \"\"\"\n\n mission_dict = compute_fermi_relative_mission_times(self._trigger_time)\n\n fermi_dict = collections.OrderedDict()\n\n fermi_dict['Fermi Trigger Time'] = \"%.3f\" % self._trigger_time\n fermi_dict['Fermi MET OBS Start'] = \"%.3f\" % self._tstart\n fermi_dict['Fermi MET OBS Stop'] = \"%.3f\" % self._tstop\n fermi_dict['Fermi UTC OBS Start'] = self._utc_start\n fermi_dict['Fermi UTC OBS Stop'] = self._utc_stop\n\n fermi_df = pd.Series(fermi_dict, index=list(fermi_dict.keys()))\n\n\n if mission_dict is not None:\n mission_df = pd.Series(mission_dict, index=list(mission_dict.keys()))\n\n fermi_df = fermi_df.append(mission_df)\n\n\n\n return fermi_df\n\n\n\n\n\n\n","sub_path":"threeML/plugins/FermiLATLLELike.py","file_name":"FermiLATLLELike.py","file_ext":"py","file_size_in_byte":13332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"164087404","text":"\"\"\"\nTDD\n@Author: WSWSCSJ\n\"\"\"\nfrom compose.video import Video\nfrom compose.audio import Audio\nfrom compose.picture import Picture\nfrom common.constants import *\n\nfrom loguru import logger\n\nclass ProcessTest:\n failures = []\n\n def __init__(self, request):\n self.request = request\n\n @property\n def run(self):\n video_attributes = (\n \"fps\", \"frames\", \"step\", \"length\",\n \"size\", \"video_format\", \"render\"\n )\n audio_attributes = (\n \"start\", \"end\", \"audio_format\"\n )\n\n pictures_stream = []\n with open(\"/Users/chenxuejun/Downloads/test1.JPG\", \"rb\") as _:\n pictures_stream.append(_.read())\n with open(\"/Users/chenxuejun/Downloads/test2.JPG\", \"rb\") as _:\n pictures_stream.append(_.read())\n with open(\"/Users/chenxuejun/Downloads/test3.JPG\", \"rb\") as _:\n pictures_stream.append(_.read())\n with open(\"/Users/chenxuejun/Downloads/starboy.mp3\", \"rb\") as _:\n audio = _.read()\n size = Size.size\n color = Color.WHITE\n\n pictures = []\n for _ in pictures_stream:\n _ = Picture(_, color, size).picture\n if _ is not None:\n pictures.append(_)\n else:\n self.failures.extend(_.failures)\n return False\n for p in pictures:\n logger.debug(p.shape)\n audio = Audio(audio_stream=audio)\n video = Video(picture_set=pictures)\n succeed = video.produce and video.set_audio(audio.audio_file_clip)\n if not succeed:\n self.failures.extend(video.failures)\n else:\n succeed = video.video_stream\n logger.debug(\"file {}\".format(video.composite_file_name))\n # del video\n # del audio\n if self.failures:\n logger.error(self.failure)\n return succeed\n\n @property\n def failure(self):\n return \"\\n\".join(self.failures)\n\nif __name__ == \"__main__\":\n logger.debug(type(ProcessTest(\"\").run))","sub_path":"ByDjango/compose/test/process_test.py","file_name":"process_test.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"128947363","text":"import sys\n\n\ndef set_row(i, x, matrix):\n matrix[i] = [x for _ in range(len(matrix[i]))]\n\n\ndef set_col(j, x, matrix):\n for i in matrix:\n i[j] = x\n\n\ndef query_row(i, matrix):\n print(sum(matrix[i]))\n\n\ndef query_col(j, matrix):\n print(sum(matrix[x][j] for x in range(len(matrix))))\n\n\nif __name__ == '__main__':\n filename = \"input.txt\"\n if len(sys.argv) == 2:\n filename = sys.argv[1]\n\n my_matrix = [[0 for _ in range(256)] for x in range(256)]\n functions = {'SetCol': set_col, 'SetRow': set_row, 'QueryCol': query_col, 'QueryRow': query_row}\n\n f = open(filename, 'r')\n for line in f:\n line_list = list(line.strip().split())\n arguments = list(map(int, line_list[1:]))\n func_s = functions[line_list[0]]\n func_s(*arguments, my_matrix)\n f.close()\n","sub_path":"easy/087-query-board/query_board.py","file_name":"query_board.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"337089821","text":"import os\r\nfrom unittest import IsolatedAsyncioTestCase\r\n\r\nfrom backend.domain.model.course import Course\r\nfrom backend.infra.database.connection import DatabaseConnection\r\nfrom backend.infra.repository.courses_repository_db import CoursesRepositoryDB\r\n\r\n\r\nclass TestCoursesRepository(IsolatedAsyncioTestCase):\r\n @classmethod\r\n def setUpClass(cls) -> None:\r\n os.environ[\"ENV\"] = \"TEST\"\r\n\r\n cls.connection = DatabaseConnection()\r\n cls.courses_repository = CoursesRepositoryDB(connection=cls.connection)\r\n\r\n def tearDown(self) -> None:\r\n self.connection.db.execute(\"DELETE FROM courses;\")\r\n\r\n @staticmethod\r\n def build_course():\r\n return Course.parse_obj(\r\n {\"name\": \"Test course\", \"image\": \"http://images.com/image.jpg\"}\r\n )\r\n\r\n async def test_save(self):\r\n course = self.build_course()\r\n\r\n await self.courses_repository.save(course)\r\n\r\n self.assertIsNotNone(course.id)\r\n self.assertIsNotNone(course.created_at)\r\n\r\n async def test_exists_by_id(self):\r\n course = self.build_course()\r\n await self.courses_repository.save(course)\r\n\r\n exists = await self.courses_repository.exists_by_id(course.id)\r\n\r\n self.assertTrue(exists)\r\n\r\n async def test_exists_by_name(self):\r\n course = self.build_course()\r\n await self.courses_repository.save(course)\r\n\r\n exists = await self.courses_repository.exists_by_name(name=course.name)\r\n\r\n self.assertTrue(exists)\r\n\r\n async def test_find_all(self):\r\n courses = Course.parse_list(\r\n [\r\n {\"name\": f\"Test course {i}\", \"image\": \"http://images.com/image.jpg\"}\r\n for i in range(5)\r\n ]\r\n )\r\n\r\n for course in courses:\r\n await self.courses_repository.save(course)\r\n\r\n fetched_courses = await self.courses_repository.find_all()\r\n\r\n created_courses_names = {course.name for course in courses}\r\n fetched_courses_names = {course.name for course in fetched_courses}\r\n\r\n self.assertEqual(len(fetched_courses_names), len(courses))\r\n self.assertTrue(created_courses_names.issubset(fetched_courses_names))\r\n\r\n async def test_find_many_by_id(self):\r\n courses = [\r\n Course.parse_obj(\r\n {\"name\": f\"Test course {i}\", \"image\": \"http://images.com/image.jpg\"}\r\n )\r\n for i in range(5)\r\n ]\r\n\r\n for course in courses:\r\n await self.courses_repository.save(course)\r\n\r\n fetched_courses = await self.courses_repository.find_many_by_ids(\r\n [\r\n course.id\r\n for course in courses\r\n if course.name in {\"Test course 2\", \"Test course 4\"}\r\n ]\r\n )\r\n\r\n fetched_courses_names = {course.name for course in fetched_courses}\r\n\r\n self.assertEqual(len(fetched_courses_names), 2)\r\n self.assertEqual(fetched_courses_names, {\"Test course 2\", \"Test course 4\"})\r\n\r\n async def test_find_many_with_name_like(self):\r\n courses = [\r\n Course.parse_obj(\r\n {\"name\": f\"Test course {i}\", \"image\": \"http://images.com/image.jpg\"}\r\n )\r\n for i in range(5)\r\n ]\r\n\r\n for course in courses:\r\n await self.courses_repository.save(course)\r\n\r\n fetched_courses = await self.courses_repository.find_many_with_name_like(\r\n \"test course\"\r\n )\r\n\r\n for course in fetched_courses:\r\n self.assertIn(\"Test course\", course.name)\r\n","sub_path":"backend/backend/infra/repository/__tests__/test_courses_repository.py","file_name":"test_courses_repository.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"485337288","text":"# A programme to count the number of time a definite word\n# is used as a noun or as a verb in a corpus\n\nimport nltk\nfrom nltk.corpus import nps_chat as nps\nimport matplotlib.pyplot as plt\n\nuser_input = input(\"Please enter a word:\" ).strip().lower()\ntext = nps.tagged_words(tagset='universal')\n\ncount_verb = 0\nfor pair in text:\n if pair[0].lower() == user_input.lower():\n if \"v\" in pair[1].lower():\n count_verb+=1\n\ncount_noun = 0\nfor pair in text:\n if pair[0].lower() == user_input.lower():\n if \"n\" in pair[1].lower():\n count_noun+=1\nif count_noun == 0 and count_verb == 0:\n print(\"There are no instances of this word neither as a noun, nor as a verb in this corpus\")\nelse:\n print(\"There are\", count_noun, \"number of\", user_input, \" as a noun in the text\")\n print(\"There are\", count_verb, \"number of\", user_input, \" as a verb in the text\")\n\n figure = plt.figure()\n plt.title('Word Frequency')\n plt.grid(True)\n plt.bar(['Noun', 'Verb'], [count_noun, count_verb], color=['c', 'm'])\n figure.set_figwidth(4)\n figure.set_figheight(5)","sub_path":"nltk_05_count_word_as_verb_noun.py","file_name":"nltk_05_count_word_as_verb_noun.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"440932373","text":"#*******************************************************************\r\n#Program Name: extraCredit.py\r\n#Programmer: Gabriela Tolosa Ramirez\r\n#CSC - 119: Fall 2018 - 002\r\n#Date: Nov 12,2018\r\n#Purpose: Page 444 - P7.2\r\n#Modules used: N/A\r\n#Input Variable(s): fileIn(stg), fileOut(stg)\r\n#Output(s): fileOut(txt), filePrint(stg)\r\n#*******************************************************************\r\n\r\ndef main():\r\n #ask user for the name of the in/out files\r\n fileIn = input(\"Input file name: \")#littleLamb.txt\r\n fileOut = input(\"Output file name: \")#littleLamb2.txt\r\n\r\n #open files\r\n inFile = open(fileIn,'r')\r\n outFile = open(fileOut,'w')\r\n\r\n #copy file with modifications\r\n count = 1\r\n line = inFile.readline()\r\n while line != \"\":\r\n outFile.write(\"/*\")\r\n outFile.write(str(count))\r\n outFile.write(\"*/\")\r\n outFile.write(line)\r\n count += 1\r\n line = inFile.readline()\r\n inFile.close()\r\n outFile.close()\r\n\r\n #print text of second file\r\n filePrint = open(fileOut,'r')\r\n line = filePrint.readline()\r\n while line != \"\":\r\n print(line)\r\n line = filePrint.readline()\r\n filePrint.close()\r\n\r\nmain()\r\n","sub_path":"Homework/Day 12/Extra Credit/extraCredit.py","file_name":"extraCredit.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"469463091","text":"\"\"\"\n####################\nensembl_data.py\n####################\nCode supporting automated retrieval/mirroring/processing of ensembl data files and directories.\n\nWARNING:\n To some extent the functionality of this code is dependant on the\n current formating of Ensembl's internal directory structure and how\n it responts to ``urllib2.urlopen(url)``.\n\"\"\"\nimport urllib2\nimport sys\nimport os\nfrom collections import defaultdict\n\n\nfrom gfunc import externals\nfrom gfunc.fileIO import walk_dirs_for_fileName\nfrom gfunc.data_classes import Bunch\n\n\ndef to_stdout(txt):\n sys.stdout.write(txt)\n sys.stdout.flush()\n \ndef to_stderr(txt):\n sys.stderr.write(txt)\n sys.stderr.flush()\n\n\n\n\ndef validate_downloads(base_dir):\n \"\"\"\n *GIVEN:*\n * ``base_dir`` = top-level directory containing files to be validated.\n *DOES:*\n * Decends into ``base_dir`` and records paths to all lower-level files.\n * Uses the CHECKSUMS files it finds to set up external system calls to ``sum``\n for each file listed in the direcory's CHECKSUMS file.\n * A file named VALIDATIONS is created in each directory listing each file in the directory and one of the following outcomes: \n * PASS = passed checksum match\n * FAIL = failed checksum match\n * NOT_IN_CHECKSUMS = file found in directory but NOT listed in the CHECKSUMS file\n * NOT_IN_DIR = file listed in CHECKSUMS file, but not found in the directory.\n *RETURNS:*\n * ``results`` = a summary of all VALIDATIONS files (list of strings)\n \"\"\"\n \n results = []\n \n file_paths = walk_dirs_for_fileName(dir_path=base_dir,pattern=\"*\")\n \n checksum_paths = [x for x in file_paths if x.endswith('CHECKSUMS')]\n \n for cksum in checksum_paths:\n cksum_data = [line.strip('\\n').split() for line in open(cksum)]\n \n current_dir_path = cksum.replace('/CHECKSUMS','')\n \n scores = check_files(dir_path=current_dir_path , cksum_data=cksum_data)\n results.extend(scores)\n \n vFile = open('%s/VALIDATIONS' % (current_dir_path), 'w')\n for line in scores:\n vFile.write('%s\\n' % (line))\n vFile.close()\n \n return results\n \n \n \n \ndef check_files(dir_path,cksum_data):\n \"\"\"\n *GIVEN:*\n * ``dir_path`` = path to a directory containing files to be validated\n * ``cksum_data`` = parsed contents of the CHECKSUMS file for this directory\n *DOES:*\n * Compares files in the directory with checksums in the CHECKSUMS file and scores them as PASS/FAIL\n * Documents and classifies discrepancies between files listed in CHECKSUMS file vs files actually\n in the directory: classifies them as NOT_IN_CHECKSUMS or NOT_IN_DIR.\n *RETURNS:*\n * ``results`` = list of strings\n \"\"\"\n results = []\n \n cksums = {}\n for cksm,blocks,name in cksum_data:\n cksums[name] = (cksm,blocks)\n \n # get the sets of file names from CHECKSUMS file as well as from the actual directory.\n in_cksums = set([x[-1] for x in cksum_data])\n in_cur_dir = walk_dirs_for_fileName(dir_path=dir_path,pattern='*')\n in_cur_dir = set([x.split('/')[-1] for x in in_cur_dir if x.split('/')[-1]])\n \n in_cur_dir.discard('CHECKSUMS')\n in_cur_dir.discard('VALIDATIONS')\n \n not_in_cksums = list(in_cur_dir - in_cksums) # files in current directory but not listed in CHECKSUMS file\n not_in_dir = list(in_cksums - in_cur_dir) # files in CHECKSUMS file but not current directory\n in_both = list(in_cksums & in_cur_dir) # files in both\n \n for f in in_both:\n stdout,stderr = externals.runExternalApp(progName='sum',argStr='%s/%s' % (dir_path,f))\n if tuple(stdout.split()) == cksums[f]:\n results.append('PASS\\t%s' % (f))\n else:\n results.append('FAIL\\t%s' % (f))\n \n for f in not_in_cksums:\n results.append('NOT_IN_CHECKSUMS\\t%s' % (f))\n \n for f in not_in_dir:\n results.append('NOT_IN_DIR\\t%s' % (f))\n \n results.sort(key=lambda x: x.split()[-1]) # sort results by file name\n \n return results\n \n\n\ndef web_ls(url):\n \"\"\"\n *GIVEN:*\n * ``url`` = the url of an ensembl-based ftp:// target\n *DOES:*\n * reads the url data and extracts file/directory names\n * stores info in a dict named ``contents``; keyed by 'dirs' or 'files' and pointing to lists of respective urls.\n *RETURNS:*\n * ``contents`` dictionary.\n \"\"\"\n \n for attempt in range(5):\n try:\n page = urllib2.urlopen(url)\n results = [(x.split()[0] , x.split()[-1]) for x in page]\n break\n except:\n if attempt > 5:\n raise\n else:\n to_stderr(\"Connection failed: trying again...\\n\")\n \n \n contents = defaultdict(list)\n for permissions_str,name in results:\n if permissions_str.startswith('d'):\n contents['dirs'].append(url.rstrip('/') + '/' + name)\n else:\n contents['files'].append(url.rstrip('/') + '/' + name)\n \n return contents\n\ndef web_walk(base_url):\n \"\"\"\n *GIVEN:*\n * ``base_url`` = the url of an ensembl-based ftp:// target directory\n *DOES:*\n * recursively stores directories and file urls (uses ``web_ls``),\n continues to follow directories until all file urls have been\n collected below ``base_url``.\n *RETURNS:*\n * ``file_urls`` = list of file url strings under ``base_url``.\n \"\"\"\n \n file_urls = []\n \n contents = web_ls(base_url)\n file_urls.extend(contents['files'])\n \n for dir_url in contents['dirs']:\n file_urls.extend(web_walk(dir_url))\n \n return file_urls\n\nclass DataGrabber(object):\n \"\"\"\n Class to manage conecting to ensembl-based ftp data dumps and retrieving them.\n \"\"\" \n\n def __init__(self,base_url,species,data_types,base_local_path,verbose=False):\n \"\"\"\n Initiate DataGrabber object for conecting to ensembl-based ftp data dumps.\n \"\"\"\n\n self._verbose = verbose\n self._supported_programs = ('aria2c','rsync','curl','wget')\n self._init_map = {'rsync':self._init_rsync,\n 'aria2c':self._init_aria2c,\n 'curl':self._init_curl,\n 'wget':self._init_wget}\n \n self._settings = Bunch()\n self._settings.base_url = base_url.rstrip('/')\n self._settings.species = species\n self._settings.data_types = data_types\n self._settings.base_local_path = base_local_path\n self._get_avail_data_types() # will be tuple\n \n \n def _get_avail_data_types(self):\n \"\"\"\n *GIVEN:*\n * self\n *DOES:*\n * [x] queries base_url for the availible directories (data types)\n * [x] stores a tuple to self._avail_data_types\n *RETURNS:*\n * None\n \"\"\"\n if self._verbose:\n to_stdout('Checking server for current data types...')\n contents = web_ls(self._settings.base_url)\n \n self._avail_data_types = tuple([x.split('/')[-1] for x in contents['dirs']])\n if self._verbose:\n to_stdout('\\tAvailible types set to: %s\\n' % (str(self._avail_data_types)))\n \n def _get_url_list(self):\n \"\"\"\n *GIVEN:*\n * sufficently initiated ``self`` instance\n *DOES:*\n * [x] uses:\n \n # ``self._settings.base_url``\n # ``self._settings.species``\n # ``self._settings.data_types``\n \n to construct full urls for every file to be downloaded\n and saves them to self._target_urls.\n *RETURNS:*\n * ``None`` \n \"\"\"\n \n target_directories = []\n target_urls = []\n \n base_url = self._settings.base_url\n for species in self._settings.species:\n for data_type in self._settings.data_types:\n target_directories.append('%s/%s/%s' % (base_url,data_type,species))\n if self._verbose:\n to_stdout('Collecting file urls for download...')\n for target_dir in target_directories:\n target_urls.extend(web_walk(target_dir))\n \n self._target_urls = tuple(target_urls)\n if self._verbose:\n to_stdout('\\tDONE!\\n')\n \n def _init_curl(self):\n \"\"\"\n *GIVEN:*\n * self\n *DOES:*\n * [] format the command line string for cURL based on self._settings\n *RETURNS:*\n * command line string\n \"\"\"\n raise NotImplementedError()\n \n def _init_wget(self):\n \"\"\"\n *GIVEN:*\n * self\n *DOES:*\n * [] format the command line string for wget based on self._settings\n *RETURNS:*\n * command line string\n \"\"\"\n raise NotImplementedError\n \n def _init_aria2c(self):\n \"\"\"\n *GIVEN:*\n * self\n *DOES:*\n * format the command line string for aria2c based on self._settings\n * writes a file that encodes the target_urls and their new local paths for aria2c to read.\n *RETURNS:*\n * command line string\n \"\"\"\n \n # write out a log file containing the targeted urls and their new local paths for aria2c to read \n file_path = '%s/target_urls_aria2c_input.txt' % (self._settings.base_local_path)\n aria2c_input_file = open(file_path, 'w')\n if self._verbose:\n to_stdout('Writing options file for aria2c...')\n for target_url in self._target_urls:\n aria2c_input_file.write(\"%s\\n dir=%s\\n out=%s\\n\" % (target_url,\n self._settings.base_local_path,\n target_url.split('://')[1]))\n aria2c_input_file.close()\n if self._verbose:\n to_stdout('\\tDONE!\\n') \n \n cmd_string = '-l %s/aria2c.log -c -i %s -j5' % (self._settings.base_local_path,file_path)\n \n \n return cmd_string\n \n def _init_rsync(self):\n \"\"\"\n *GIVEN:*\n * self\n *DOES:*\n * [] format the command line string for rsync based on self._settings\n *RETURNS:*\n * command line string\n \"\"\"\n raise NotImplementedError \n \n \n def _execute(self,program):\n \"\"\"\n *GIVEN:*\n * self\n * supported program\n *DOES:*\n * [x] initiates command line string based on which program is included\n * [x] runs externals.runExternalApp(program,args)\n *RETURNS:*\n * return externals.runExternalApp(program,args)\n \"\"\"\n if self._verbose:\n to_stdout('Initializing command string for: %s\\n' % (program))\n command_string = self._init_map[program.split('/')[-1]]()\n \n if self._verbose:\n to_stdout('Executing command: %s %s\\n' % (program,command_string))\n return externals.runExternalApp(progName=program,argStr=command_string)\n \n\n \n def _which_transfer_method(self):\n \"\"\"\n *GIVEN:*\n * self\n *DOES:*\n * [x] queries system for certain external file transfer programs\n (NOTE: for now in order of preference (see ``self._supported_programs``). \n Eventually, I may add more and/or include a pure urllib2 solution for\n systems w/o supported external apps.)\n * [x] chooses one that will work on the system\n *RETURNS:*\n * choice of program\n \"\"\"\n \n accepted_program_path = False\n for prog in self._supported_programs:\n accepted_program_path = externals.whereis(prog)\n if accepted_program_path:\n break\n \n if not bool(accepted_program_path):\n raise Exception(\"Your system does not seem to have any of the supported download methods availible: %s. Please install one and try again.\") % (self._supported_programs)\n else:\n return accepted_program_path\n \n def settings(self):\n \"\"\"\n \n *RETURNS:*\n * dict of current settings for ensembl access.\n \n \"\"\"\n return self._settings.copy()\n \n def transfer_data(self,unzip=False):\n \"\"\"\n *GIVEN:*\n * sufficently initiated ``self`` instance\n *DOES:*\n * [x] decides which method to use to get the data\n * [x] creates local directory if needed based on base_local_path\n * [x] initiates data transfer\n * [?] complains if it detects incomplete transfer\n * [?] if unzip evaluates to True, recursively unzip any files\n with extentions suggesting they are compressed.\n *RETURNS:*\n * None\n \"\"\"\n # choose first program to try \n if self._verbose:\n to_stdout('Choosing download program from your system...')\n prog = self._which_transfer_method()\n if self._verbose:\n to_stdout('\\t SELECTED: %s\\n' % (prog))\n \n # create local home for the data\n externals.mkdirp(self._settings.base_local_path)\n \n # write out a log file containing the targeted urls for reference.\n self._get_url_list()\n url_list_file = open('%s/target_urls.txt' % (self._settings.base_local_path), 'w')\n for target_url in self._target_urls:\n url_list_file.write(\"%s\\n\" % (target_url))\n url_list_file.close()\n self._target_url_file_path = os.path.abspath(url_list_file.name)\n \n # begin execution of transfer\n execution_result = self._execute(prog)\n\nif __name__ == '__main__':\n pass","sub_path":"src/gfunc/ensembl_data.py","file_name":"ensembl_data.py","file_ext":"py","file_size_in_byte":14036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"642484455","text":"import os\nimport logging\nimport coloredlogs\nfrom datetime import timedelta, date\nfrom gettext import gettext\nfrom telegram import Bot, TelegramError\nfrom telegram.ext import Updater, MessageHandler, Filters, CommandHandler\nfrom botmanlib.menus.helpers import add_to_db, generate_underscore, unknown_command, to_state, get_settings_file, write_settings_file\n\nfrom src.models import User, DBSession\nfrom src.settings import TOKEN, SETTINGS_FILE, PERIOD\nfrom src.menus.start import StartMenu\nfrom src.menus.admin import AdminMenu\nfrom src.helpers import restricted_users, kicked_users, users_from_chat, timedelta_from_str\n\nlogger = logging.getLogger(__name__)\n\ndef stop(bot, update, user_data):\n _ = user_data['_'] if '_' in user_data else gettext\n user = DBSession.query(User).filter(\n User.chat_id == user_data['user'].chat_id).first()\n user.active = False\n DBSession.add(user)\n DBSession.commit()\n bot.send_message(chat_id=user.chat_id,\n text='Вы удалены из бота.')\n\ndef welcome(bot, update):\n data = get_settings_file(SETTINGS_FILE)\n message = update.message\n group_id = data['autopublish']['group_id']\n new_users = message.new_chat_members\n previous_add_msg_id = data['previous_add_message']\n previous_msg_id = data['previous_welcome_message']\n if previous_msg_id is not None and previous_add_msg_id is not None :\n try:\n bot.delete_message(chat_id=group_id, message_id=previous_msg_id)\n bot.delete_message(chat_id=group_id, message_id=previous_add_msg_id)\n logger.debug(f'Delete {previous_msg_id}')\n except TelegramError as e:\n logger.error(f'{e} - wrong previous message id')\n\n for new_user in new_users:\n text = f\"{data['hello_message']}, {new_user.first_name}\" \n logger.info(f'{new_user.first_name} joined to chat {group_id}({message.chat.title})')\n bot.send_message(chat_id=group_id, text=text, reply_to_message_id=message.message_id)\n data['previous_add_message'] = message.message_id\n data['previous_welcome_message'] = message.message_id + 1\n\n try:\n write_settings_file(data, SETTINGS_FILE)\n logger.debug('Попереднє повідомлення записано')\n except (TypeError, IOError) as e:\n logger.error(e)\n \n user = DBSession.query(User).filter(User.chat_id == new_user.id).first()\n if user is None:\n user = User()\n user.chat_id = new_user.id\n user.name = new_user.first_name\n user.username = new_user.username\n user.active = True\n user.join_date = date.today()\n user.expiration_date = (date.today()\n + timedelta_from_str(data['grace_mode'])\n + timedelta_from_str(data['silence_mode']))\n add_to_db(user, session=DBSession)\n else:\n user.active = True \n\ndef goodbye(bot, update):\n data = get_settings_file(SETTINGS_FILE)\n message = update.message\n group_id = data['autopublish']['group_id']\n left_user = message.left_chat_member\n user = DBSession.query(User).filter(User.chat_id == left_user.id).first()\n user.active = False\n add_to_db(user, session=DBSession)\n bot.delete_message(chat_id=group_id, message_id=message.message_id)\n\n\ndef error(bot, update, error):\n logger.error(f'Update \"{str(update)}\" caused error \"{error}\"')\n\n\ndef main():\n bot = Bot(token=TOKEN)\n updater = Updater(token=TOKEN)\n job_queue = updater.job_queue\n dispatcher = updater.dispatcher\n coloredlogs.install()\n\n # Handlers\n start_menu = StartMenu(bot=bot, dispatcher=dispatcher)\n admin_menu = AdminMenu(bot=bot, dispatcher=dispatcher)\n stop_handler = CommandHandler('stop', stop, pass_user_data=True)\n \n # adding menus\n dispatcher.add_handler(stop_handler)\n dispatcher.add_handler(start_menu.handler)\n dispatcher.add_handler(admin_menu.handler)\n dispatcher.add_handler(MessageHandler(Filters.status_update.left_chat_member, goodbye))\n dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, welcome))\n dispatcher.add_error_handler(error)\n\n if not os.path.exists(SETTINGS_FILE):\n with open(SETTINGS_FILE + \".BAK\", 'r') as settings:\n out = open(SETTINGS_FILE, 'w')\n out.write(settings.read())\n out.close()\n logger.info(\"Settings file created\")\n \n logger.info(\"Bot started\")\n update_queue = updater.start_polling()\n \n # запуск процесса для мута людей, которые не оплатили\n job_queue.run_repeating(restricted_users, PERIOD, first=1, name=\"restricted_users\")\n \n # запуск процесса для кика людей\n job_queue.run_repeating(kicked_users, PERIOD, first=1, name=\"kicked_users\")\n\n # запуск процесса для добавления людей состоящих в чате\n users_from_chat()\n\n updater.idle()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"35009548","text":"from django.urls import path\nfrom . import views\n\napp_name = 'post'\n\n# 메뉴 등록 !!\n\nurlpatterns = [\n path(\"\", views.main, name=\"main1\"),\n path(\"post_list/\", views.post_list, name=\"post_l\"),\n #post_list라는 메뉴를 추가한 것\n path(\"post_list/<int:pk>/\", views.post_detail, name=\"post_d\"),\n path(\"post_create/\", views.post_create, name=\"post_c\"),\n # path(\"post_update/<int:pk>/\", views.post_update, name=\"post_u\"),\n # path(\"post_delete/<int:pk>/\", views.post_delete, name=\"post_del\"),\n\n]","sub_path":"post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"312872752","text":"# -*- coding:utf-8 -*-\n\nimport pprint\nimport random\nimport json\n\nfrom topologylistener import message_utils\n\n\nsend_idx = 0\n\n\ndef mock_send(payload, correlation_id):\n global send_idx\n\n print('Send request #{}'.format(send_idx))\n print('Send correlation id: {}'.format(correlation_id))\n\n send_idx += 1\n encoded = json.dumps(payload, indent=4)\n print(encoded)\n print('\\n')\n\n\nmessage_utils.send_cache_message = mock_send\n\n\ndef main():\n switch_set = []\n isl_set = []\n flow_set = []\n\n payload_dummy = []\n for dummy_size in (20, 32, 64, 128, 512, 1024):\n desc = ' {} '.format(dummy_size)\n dummy = '*' * dummy_size\n dummy = dummy[:2] + desc + dummy[2 + len(desc):]\n dummy = dummy[:dummy_size]\n payload_dummy.append(dummy)\n\n for kind, dest in (\n ('switch', switch_set),\n ('isl', isl_set),\n ('flow', flow_set)):\n\n available_chunks = payload_dummy[:]\n random.shuffle(available_chunks)\n for payload in available_chunks:\n dest.append({'kind': kind, 'payload': payload})\n\n message_utils.send_network_dump(\n 'correlation', switch_set, isl_set, flow_set, size_limit=10000)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"services/topology-engine/queue-engine/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"215429","text":"import click\n\nfrom demoflask.app import app, db\nfrom demoflask.models import TestMethod\n\n\n@app.cli.command()\n@click.option('--drop', is_flag=True, help='Create after drop.')\ndef initdb(drop):\n if drop:\n \"\"\"Initialize the database.\"\"\"\n if drop:\n click.confirm('This operation will delete the database, do you want to continue?', abort=True)\n db.drop_all()\n click.echo('Drop tables.')\n db.create_all()\n click.echo('Initialized database.')\n\n\n@app.cli.command()\n@click.option('--count', default=20, help='Quantity of messages, default is 20.')\ndef forge(count):\n \"\"\"Generate fake messages.\"\"\"\n from faker import Faker\n\n db.drop_all()\n db.create_all()\n\n fake = Faker()\n click.echo('Working...')\n\n for i in range(count):\n message = TestMethod(\n methodName=fake.name(),\n methodDesc=fake.name(),\n className=fake.name(),\n classDesc=fake.name(),\n fileName=fake.name(),\n fileDesc=fake.name(),\n moduleName=fake.name(),\n moduleDesc=fake.name(),\n author=fake.name()\n )\n db.session.add(message)\n\n db.session.commit()\n click.echo('Created %d fake messages.' % count)","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"217343170","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[134]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\n\n# In[135]:\n\n\nds = pd.read_csv('http://iali.in/datasets/Social_Network_Ads.csv')\nds = ds[['Gender','Age','EstimatedSalary','Purchased']]\n\n\n# In[136]:\n\n\ngender = {'Male': 1,'Female': 0}\nds.Gender = [gender[item] for item in ds.Gender] \n\n\n# In[137]:\n\n\nX = ds.iloc[:,0:3].values\nY = ds.iloc[:,-1].values\nds.head()\n\n\n# In[138]:\n\n\nplt.plot(X_train,'o')\n\n\n# In[139]:\n\n\nX_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size = 0.2,random_state = 1)\n\n\n# In[140]:\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier()\nknn.fit(X_train, Y_train)\nknnpredictions = knn.predict(X_test)\n\n\n# In[141]:\n\n\naccuracy_score(knnpredictions,Y_test)\n\n\n# In[142]:\n\n\nfrom sklearn.tree import DecisionTreeClassifier\ndt = DecisionTreeClassifier()\ndt.fit(X_train, Y_train)\ndtpredictions = dt.predict(X_test)\n\n\n# In[143]:\n\n\naccuracy_score(dtpredictions,Y_test)\n\n\n# In[144]:\n\n\nfrom sklearn.svm import SVC\nsvm = SVC(gamma = 'auto')\nsvm.fit(X_train, Y_train)\nsvmpredictions = svm.predict(X_test)\n\n\n# In[145]:\n\n\naccuracy_score(svmpredictions,Y_test)\n\n","sub_path":"Day 2/Coderweek day 2 Classify.py","file_name":"Coderweek day 2 Classify.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"452633344","text":"# -*- coding: utf-8 -*-\n\"\"\"\nA module providing multhop method for solving lifting line problem\n\"\"\"\nimport numpy as np\nfrom numba import jit\nfrom collections import namedtuple\n\n\nπ = np.pi\n\n\n_multhopp_result = namedtuple('multhopp_result', ('ys','c_ls','C_L'))\n_ext_multhopp_result = namedtuple('ext_multhopp_result', ('ys', 'c_ls', 'C_L', 'αᵢs','C_Wi'))\n\n\n#@jit\ndef _solve_multhopp(αs, θs, chords, b, dcls, return_B = False):\n \"\"\"Calculates lift distribution with multhopp method.\n \n :param αs: angle of attack in radians at grid points\n :param θs: gridpoints in transformed spanwise coordinates y=b/2 cos(θ)\n :param chords: chord lenghtes at grid points\n :param dcls: lift slope of wing sections at grid points\n :rtype: dict\n \"\"\"\n M = len(θs)\n\n # create empyt matrix (N_MxN_M) for multhoppcoefficients\n Bb = np.zeros((M, M))\n Bd = np.zeros(M)\n\n # calculation of multhopp coefficients\n for v, (θv, c, dcl_v) in enumerate(zip(θs, chords, dcls)):\n for n, θn in enumerate(θs):\n\n # diagonal elements\n if v == n:\n Bb[v, v] = (M+1)/(4*np.sin(θv))\n Bd[v] = 2*b/(dcl_v*c)\n # non diagonal elements\n else:\n Bb[v, n] = - ((1-(-1.)**(v-n))/2*(np.sin(θn)/ \\\n ((M+1)*(np.cos(θn)-np.cos(θv))**2)))\n\n B = Bb + np.diag(Bd)\n\n #print(B)\n\n #print(B.shape, αs.shape)\n # calculation of local circulation\n γs = np.dot(np.linalg.inv(B), αs)\n\n #print(γs)\n if return_B:\n return γs, Bb, Bd\n else:\n return γs\n\ndef _calculate_liftcoefficients(Θs, γs, chords, Λ, b, M):\n \"\"\"calculates lift coefficients from circulation\n \n Args:\n ...\n chords (ndarray): chord lenghtes\n b (float): span width\n M (int): number of grid points\n \n Returns:\n c_l (ndarray), C_L (float): lift distribution and wing lift coefficients\n \"\"\"\n\n\n # calculate lift coefficient distritbution\n c_l = 2*b/(np.array(chords)) * np.array(γs)\n\n # calculate overall lift coefficient (whole wing)\n C_L = π*Λ / (M+1) * np.sum(γs * np.sin(Θs))\n\n return c_l, C_L\n\ndef calcgridpoints(ys: np.array, b:float, Λ:float, M:int = None):\n # calculate number of gridpoints\n if M is None:\n M = int(round(Λ)*4-1) # has to be uneven, not more than 4*aspect ratio\n elif M%2 == 0:\n M += 1 # has to be uneven\n\n # grid points as angle\n θs = np.linspace(np.pi/(M+1), M/(M+1)*np.pi, M)\n\n # calculate grid points\n calc_ys = -b/2 * np.cos(θs)\n\n return θs, calc_ys\n\ndef multhopp(αs: np.array, chords: np.array, ys: np.array, dcls: np.array=np.nan, M:int=None,\n mode = 'c_l', interp = True, data=None ):\n\n \n if np.isnan(dcls).all():\n dcls = np.array([2*π]*len(ys))\n\n # interpolate\n if interp: \n # calculate wingspan\n b = 2*max(ys)\n\n # calculate wing area\n S = 2 * np.trapz(y=chords, x=ys)\n \n # calculate aspect ratio\n Λ = b**2 / S\n θs, calc_ys = calcgridpoints(ys, b, Λ, M)\n \n calc_αs = np.interp(np.abs(calc_ys), ys, αs)\n calc_chords = np.interp(np.abs(calc_ys), ys, chords)\n calc_dcls = np.interp(np.abs(calc_ys), ys, dcls)\n else:\n b = data['b']\n S = data['S']\n Λ = b**2/S\n\n calc_ys = ys\n calc_chords = chords\n calc_αs = αs\n calc_dcls = dcls\n\n θs = np.arccos(-2*calc_ys/b)\n\n #print(θs)\n\n # calculate circulation distribution\n γs, Bb, Bd = _solve_multhopp(calc_αs, θs, calc_chords, b, calc_dcls, return_B=True)\n\n B = Bb+np.diag(Bd)\n\n # return only ys and gamma\n if mode in ('gamma', 'γ'):\n return calc_ys, γs\n \n # calculate coefficients\n c_ls, C_L = _calculate_liftcoefficients(θs, γs, calc_chords, Λ, b, M)\n\n if mode == 'c_l':\n # return lift coefficients\n return _multhopp_result(calc_ys, c_ls, C_L)\n elif mode == 'combined':\n # return lift coefficients, induced angle and induced drag\n\n αᵢs = Bb@γs\n C_Di = π*Λ/(M+1) * np.sum( γs * αᵢs * np.sin(θs))\n \n return _ext_multhopp_result(calc_ys, c_ls, C_L, αᵢs, C_Di)\n","sub_path":"wingstructure/liftingline.py","file_name":"liftingline.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"34151910","text":"# coding: utf-8\nimport time\nimport signal\nimport logging\nfrom tornado.ioloop import IOLoop\n\n\ndef graceful_shutdown(http_server, max_time_out=3):\n loop = IOLoop.instance()\n\n def sig_handler(s, frame):\n logging.warning('Caught signal: %s, %s', s, frame)\n loop.add_callback_from_signal(shutdown)\n\n def shutdown():\n logging.info('Stopping http server')\n http_server.stop()\n\n logging.info('IOLoop will shutdown in %s seconds ...', max_time_out)\n deadline = time.time() + max_time_out\n\n def stop_loop():\n now = time.time()\n timeouts = [timeout for timeout in loop._timeouts if timeout.deadline < deadline]\n if now < deadline and (loop._callbacks or timeouts):\n return loop.add_timeout(now + 1, stop_loop)\n loop.stop()\n logging.info('Shutdown completed')\n\n stop_loop()\n\n for sig in (signal.SIGQUIT, signal.SIGINT, signal.SIGTERM):\n signal.signal(sig, sig_handler)\n","sub_path":"util/grace.py","file_name":"grace.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"307439264","text":"import requests\r\n#import csv\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nfrom functools import partial \r\nfrom operator import is_not\r\nfrom dateutil import parser\r\nimport pandas as pd\r\nfrom datetime import timedelta, date\r\n\r\n\r\nlinks = []\r\nnews_data = []\r\nfilter_null = partial(filter, partial(is_not, None))\r\nproxies = {\r\n \"http\": \"your http proxy\",\r\n \"https\": \"your https proxy\"\r\n}\r\n\r\ndef daterange(date1, date2):\r\n for n in range(int ((date2 - date1).days)+1):\r\n yield date1 + timedelta(n)\r\n\r\nstart_dt = date(2019, 9, 12) \r\nend_dt = date(2019,9,13)\r\nfor dt in daterange(start_dt, end_dt):\r\n #print(dt.strftime(\"%Y-%m-%d\"))\r\n url = \"https://www.thehindubusinessline.com/archive/web\" # no trailing /\r\n myurl = \".html\"\r\n Daystr = str(dt.year) + \"/\" + str(dt.month) + \"/\" + str(dt.day)\r\n final_url = '/'.join([url, Daystr]) + myurl\r\n# print(final_url)\r\n try:\r\n page = requests.get(final_url, proxies=proxies)\r\n \r\n soup = BeautifulSoup(page.text, 'html.parser')\r\n\r\n last_links = soup.find(class_='left-column')\r\n\r\n artist_name_list_items = last_links.find_all('a')\r\n for artist_name in artist_name_list_items:\r\n \r\n links.append(artist_name.get('href'))\r\n L =list(filter_null(links))\r\n \r\n regex = re.compile(r'https')\r\n \r\n selected_files = list(filter(regex.match, L))\r\n# print(selected_files) \r\n# print(list(page))\r\n except Exception as e:\r\n print(e)\r\n print(\"continuing....\")\r\n continue\r\n\r\nfor url in selected_files:\r\n news_category = url.split('/')[-3]\r\n try:\r\n data = requests.get(url, proxies=proxies)\r\n soup = BeautifulSoup(data.content, 'html.parser')\r\n \r\n last_links2 = soup.find(id='ControlPara') \r\n last_links3 = last_links2.find_all('p')\r\n metadate = soup.find('meta', attrs={'name': 'publish-date'})['content']\r\n #print(metadate)\r\n metadate = parser.parse(metadate).strftime('%m-%d-%Y')\r\n metaauthor = soup.find('meta', attrs={'name': 'twitter:creator'})['content']\r\n news_articles = [{'news_headline': soup.find('div', \r\n attrs={\"class\": \"title-bor-bottom\"}).string,\r\n 'news_article': last_links3,\r\n 'news_author': metaauthor,\r\n 'news_date': metadate,\r\n 'news_category': news_category}\r\n ]\r\n \r\n news_data.extend(news_articles) \r\n# print(list(page))\r\n except Exception as e:\r\n print(e)\r\n print(\"continuing....\")\r\n continue\r\n \r\ndf = pd.DataFrame(news_data)\r\n# print(news_data)\r\ndf = df[['news_headline', 'news_article', 'news_category','news_author', 'news_date']]\r\n# return df\r\nprint(df)\r\ndf.to_csv(\"hblmar2018.csv\",encoding = 'utf-8', index = False)","sub_path":"Using Request_BeautifulSoup/hblscraper.py","file_name":"hblscraper.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"513564657","text":"# Given a palette, gets largest object in picture composed of that palette\r\n\r\nimport glob, os\r\nfrom PIL import Image\r\nimport palette_index\r\n\r\nCOLORKEY = (128, 160, 128)\r\n# COLORKEY = (0, 0, 0)\r\nFIND_COLORKEY = False\r\nYLIMIT = 70\r\nXLIMIT = 0\r\npalette_set = palette_index.hero_shield\r\n\r\nfolder = 'hero_shield/'\r\nname = 'Shield'\r\n\r\nif os.path.exists(folder + 'Background.png'):\r\n background = Image.open(folder + 'Background.png').convert('RGB')\r\nelse:\r\n background = None\r\nprint(background)\r\n\r\nimages = [fp for fp in glob.glob(folder + '*.png') if not fp.endswith('Background.png')]\r\nfor idx, fp in enumerate(sorted(images)):\r\n print(fp)\r\n image = Image.open(fp).convert('RGB')\r\n width, height = image.size\r\n # Remove palette info\r\n if width == 248:\r\n image = image.crop((0, 0, 240, 160))\r\n width, height = image.size\r\n\r\n if not background and palette_set:\r\n grid = [False for _ in xrange(width*height)]\r\n for x in xrange(width):\r\n for y in xrange(height):\r\n color = image.getpixel((x, y))\r\n if color in palette_set and y <= YLIMIT and x <= 144:\r\n grid[y*width + x] = True\r\n else:\r\n image.putpixel((x, y), (128, 160, 128))\r\n\r\n print('Determining largest image...')\r\n count = 0\r\n set_grid = [0 for _ in xrange(width*height)]\r\n discrete_images = {}\r\n for num, present in enumerate(grid):\r\n if present and not set_grid[num]:\r\n count += 1\r\n discrete_images[count] = set()\r\n x, y = num%width, num/width\r\n discrete_images[count].add((x, y))\r\n explored = []\r\n explored.append(num)\r\n while explored:\r\n visit = explored.pop()\r\n if set_grid[visit]:\r\n continue # already visited\r\n x, y = visit%width, visit/width \r\n set_grid[visit] = count\r\n # get adjacent\r\n adjacents = []\r\n if x > 0: # Left\r\n adjacents.append(visit - 1)\r\n if x < width - 1: # Right\r\n adjacents.append(visit + 1)\r\n if y > 0: # Top\r\n adjacents.append(visit - width)\r\n if y < len(grid)/width - 1: # Bottom\r\n adjacents.append(visit + width)\r\n for adj in adjacents:\r\n if grid[adj]:\r\n discrete_images[count].add((adj%width, adj/width))\r\n explored.append(adj)\r\n\r\n which_count = 0\r\n current_max = 0\r\n for count in discrete_images:\r\n this_length = len(discrete_images[count])\r\n if this_length > current_max:\r\n current_max = this_length\r\n which_count = count\r\n\r\n print('Cropping...')\r\n for x in xrange(width):\r\n for y in xrange(height):\r\n if (x, y) not in discrete_images[which_count]:\r\n image.putpixel((x, y), COLORKEY)\r\n elif background:\r\n for x in xrange(width):\r\n for y in xrange(height):\r\n my_color = image.getpixel((x, y))\r\n bg_color = background.getpixel((x, y))\r\n if my_color == bg_color or (YLIMIT and y > YLIMIT) or (XLIMIT and x > XLIMIT) or (palette_set and my_color not in palette_set):\r\n image.putpixel((x, y), COLORKEY)\r\n elif FIND_COLORKEY:\r\n COLORKEY = image.getpixel((0, 0))\r\n print(COLORKEY)\r\n for x in xrange(width):\r\n for y in xrange(height):\r\n my_color = image.getpixel((x, y))\r\n if my_color == COLORKEY or (YLIMIT and y > YLIMIT) or (XLIMIT and x > XLIMIT):\r\n image.putpixel((x, y), FIND_COLORKEY)\r\n\r\n image.save(name + str(idx) + '.png')\r\n","sub_path":"Utilities/Animations/animation_grabber.py","file_name":"animation_grabber.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"2757381","text":"# Let mistletoe parse TeX tokens for us.\r\n\r\nimport re\r\nimport html\r\nfrom mistletoe.span_token import SpanToken, RawText\r\nfrom mistletoe.html_renderer import HTMLRenderer\r\nimport tex\r\nfrom mako.template import Template\r\n\r\nclass InlineMath(SpanToken):\r\n pattern = re.compile(r\"[$](([^$]|\\\\[$])+)[$](?![$])\")\r\n parse_inner = False\r\n parse_group = 1 \r\n\r\nclass HTMLRendererWithTex(HTMLRenderer):\r\n\r\n def __init__(self, renderer, preamble = None):\r\n super().__init__(InlineMath)\r\n self.tex = tex.Tex(preamble = preamble, renderer = renderer)\r\n self.renderer = renderer\r\n self.template = Template(filename = renderer.template_filename(\"embed\"))\r\n\r\n def render_inline_math(self, token):\r\n hash = self.tex.render(token.content)\r\n # alt text. heuristic: if it's only one line, it can go in\r\n if '\\n' in token.content:\r\n alt = \"tex formula\"\r\n else:\r\n alt = html.escape(token.content, quote = True)\r\n resdata = self.renderer.render_resource(hash)\r\n return self.template.render(resdata = resdata, alt = alt)\r\n\r\nclass HTMLRendererWithTexForHTML(HTMLRenderer):\r\n \"\"\"\r\n This one is for creating the HTML output.\r\n \"\"\"\r\n\r\n def __init__(self, renderer, preamble = None):\r\n super().__init__(InlineMath)\r\n self.tex = tex.Tex(preamble = preamble, renderer = renderer)\r\n self.renderer = renderer\r\n self.template = Template(filename = renderer.template_filename(\"html_embed\"))\r\n\r\n def render_inline_math(self, token):\r\n hash = self.tex.render(token.content)\r\n if '\\n' in token.content:\r\n alt = \"tex formula\"\r\n else:\r\n alt = html.escape(token.content, quote = True)\r\n resdata = self.renderer.render_resource(hash)\r\n localfolder = self.renderer.package.name + \"_files\"\r\n return self.template.render(resdata = resdata, alt = alt, localfolder = localfolder)\r\n","sub_path":"src/mistletoe_latex.py","file_name":"mistletoe_latex.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"420917209","text":"from django.shortcuts import render\n\nfrom app.settings import FILE_INFLATION_CSV\n\nimport csv\n\n\n\n\ndef inflation_view(request):\n template_name = 'inflation.html'\n\n # чтение csv-файла и заполнение контекста\n with open(FILE_INFLATION_CSV, newline='') as csv_file:\n reader = csv.reader(csv_file, delimiter=';')\n read_inflation = [\n '-' if i is None else i for i in reader\n ]\n\n context = {\n 'table_header': read_inflation[0],\n 'table_rows': read_inflation[1:]\n }\n\n return render(request, template_name,\n context)\n","sub_path":"netology_django_tasks/dynamic-templates/task1/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"457926343","text":"# NOTE: 0) run this script from within (i)python with\r\n# >>> run demo_ssp4arts.py\r\n# or from terminal with\r\n# >>> python demo_ssp4arts.py\r\n# 1) Requires the typhon package to be installed (and its location to be known).\r\n# 2) To allow the script to locate your ARTS-SSDB Python interface, at least\r\n# one of the following needs to be fulfiled (used in this order of priority):\r\n# - You run this script from inside the Python interface folder.\r\n# - You run this script from inside the DataInterfaces folder.\r\n# - DataInterfaces folder (or, in general, the superfolder to the\r\n# interface Python folder) is in your PYTHONPATH.\r\n# - the DataInterfaces folder (in turn assumed to hold the Python interface\r\n# subfolder) is a subfolder to the specified SSDBpath.\r\n# 3) Currently produces one scat and meta data file per scattering\r\n# element. In ARTS, you can use ScatSpeciesScatAndMetaRead to import\r\n# these data.\r\n\r\n\r\n####################\r\n# Input. Modify according to your needs.\r\n####################\r\n\r\n# location of SSDB in your system\r\nSSDBpath = '/your/database/location/SSD'\r\n\r\n# location (and name) of ARTS scat_data and scat_meta output\r\n# the filename is constructed as:\r\n# > outpath/sdBase_sdSize_size[.meta].sdExt\r\n# with\r\n# sdSize in ['dmax','dveq','mass']\r\n# size being the respective size of the particle in [um] or [kg]\r\n# sdExt in ['xml','xml.gz','xml.bin'] determining the file format\r\noutpath = '.'\r\nsdBase = 'EvansSnow_TotRand'\r\nsdExt = 'xml.bin'\r\nsdSize = 'dmax'\r\n\r\n# properties of particles to extract SSP for\r\n# use utils.ssdb_display to see what data (habits, orientations, sizes,\r\n# frequencies, temperatures) are available.\r\n# see assp.assp_import_ssdb for further details on the parameters.\r\n\r\nhabID = 1 # habit ID\r\norient = 'totally_random' # orientation\r\n\r\nminD = 0. # minimum size to extract\r\nmaxD = float(\"inf\") # maximum size to extract\r\nsizeparam = 'dmax' # size parameter to apply extraction limits on.\r\n # available (param [unit]): 'dmax' [m], 'dveq' [m], 'mass' [kg]\r\n\r\nfmin = 0. # minimum frequency to extract [Hz]\r\nfmax = float(\"inf\") # maximum frequency to extract\r\n\r\ntmin = 0. # minimum temperature to extract [K]\r\ntmax = float(\"inf\") # maximum temperature to extract\r\n\r\n\r\n\r\n####################\r\n# Importing required modules. Do not modify (unless you know what you are doing).\r\n####################\r\n#try import from current location\r\n#(ie see, whether we are inside the Python interface folder)\r\ntry:\r\n import utils\r\n import assp\r\nexcept ImportError:\r\n #try import of Python interface package from current location (by inserting\r\n # current location at start of sys.path)\r\n # (ie see, whether we are inside a DataInterfaces folder)\r\n #implicitly also imports (with lower priority) if Python interface package is\r\n # a subfolder to any of the other PYTHONPATH entries.\r\n try:\r\n import os.path\r\n os.path.sys.path.insert(0,'')\r\n from Python import utils\r\n from Python import assp\r\n except ImportError:\r\n #finally, try DataInterfaces folder in SSDBpath\r\n db_interface_path = os.path.join(os.path.dirname(SSDBpath),'DataInterfaces')\r\n #if os.path.isdir(db_interface_path):\r\n os.path.sys.path.append(db_interface_path)\r\n try:\r\n from Python import utils\r\n from Python import assp\r\n except ImportError:\r\n raise Exception(\\\r\n 'Script requires utils and assp from the SSDB python interface,\\n' + \\\r\n 'but import failed.\\n' + \\\r\n 'Maybe you are neither in the SSDB DataInterfaces folder\\n' + \\\r\n 'nor in its Python subfolder nor have added the folder to your PYTHONPATH?' )\r\nexcept Exception as e:\r\n print('Script requires utils and assp from the SSDB python interface,\\n' + \\\r\n 'but import failed with following error message:\\n' + \\\r\n ' %s%\\n' %str(e))\r\n\r\ntry:\r\n import typhon.arts.xml as tax\r\nexcept ImportError:\r\n raise Exception(\\\r\n 'This script requires the typhon package. Retry after installing.')\r\n\r\n\r\n####################\r\n# Data extraction. (Likely) no need to modify.\r\n####################\r\n\r\n# Init database\r\nutils.ssdb_init( SSDBpath )\r\n\r\n# Import data, with some cropping in size and freq\r\n# S and M are the single scatttering data and metadata\r\nS,M = assp.assp_import_ssdb( habID, orient, allow_nodata=False,\r\n size_range=[minD, maxD], size_type=sizeparam,\r\n freq_range=[fmin, fmax],\r\n temp_range=[tmin, tmax] )\r\n\r\n# Don't think, the following is needed. Hence, skip here.\r\n# Some processing could be necessary. For example, to ensure that data are\r\n# ordered in Dmax: \r\n#\r\n#[dmax,ind] = unique( [ M.diameter_max ] )\r\n#\r\n#S = S(ind)\r\n#M = M(ind)\r\n\r\n# Convert S and M to ARTS internal format (assuming this is scat species 1)\r\n#for i = 1 : length(S)\r\n# scat_data{1}{i} = S(i)\r\n# scat_meta{1}{i} = M(i)\r\n#end\r\n\r\n# Create files\r\nassert(sdExt=='xml' or sdExt=='xml.gz' or sdExt=='xml.bin'), \\\r\n 'File extension needs to be either \"xml\", \"xml.bin\", or \"xml.gz\".'\r\nextpart = sdExt.rpartition('.')\r\nif extpart[-1]=='bin':\r\n sdExt = extpart[0]\r\n fmt = 'binary'\r\nelse:\r\n fmt = 'ascii'\r\n\r\nfilename = '%s/%s_%s' %(outpath,sdBase,sdSize)\r\nif (sdSize=='dmax'):\r\n for i in range(len(S)):\r\n psize = M[i].diameter_max*1e6\r\n tax.save(S[i],'%s%04.0fum.%s' %(filename,psize,sdExt),format=fmt)\r\n tax.save(M[i],'%s%04.0fum.meta.%s' %(filename,psize,sdExt), format=fmt)\r\nelif (sdSize=='dveq'):\r\n for i in range(len(S)):\r\n psize = M[i].diameter_volume_equ*1e6\r\n tax.save(S[i],'%s%04.0fum.%s' %(filename,psize,sdExt),format=fmt)\r\n tax.save(M[i],'%s%04.0fum.meta.%s' %(filename,psize,sdExt), format=fmt)\r\nelif (sdSize=='mass'):\r\n for i in range(len(S)):\r\n psize = M[i].mass\r\n tax.save(S[i],'%s%.2ekg.%s' %(filename,psize,sdExt),format=fmt)\r\n tax.save(M[i],'%s%.2ekg.meta.%s' %(filename,psize,sdExt), format=fmt)\r\nelse:\r\n raise Exception(\\\r\n \"Size description parameter '%s' is unknown. Only 'dmax','dveq','mass' allowed.\" %sdSize)\r\n\r\n","sub_path":"demo_ssp4arts.py","file_name":"demo_ssp4arts.py","file_ext":"py","file_size_in_byte":6166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"102364325","text":"import sys\nsys.path.append(\"..\")\n\nfrom threadsTest import *\n\nimport events\nfrom events.eventTypes import *\nfrom events.arbiter import *\n\nfrom proxiesSim import *\n\nglobal proxies\n\t\t\naudioModule = EventPrintThread(\"audio thread\", False)\nfaceModule = EventPrintThread(\"face thread\", True)\nmoveModule = EventPrintThread(\"move thread\", False)\nmanager = Arbiter(\"event manager\", False, audioModule, faceModule, moveModule)\naudioModule.set_manager(manager)\nfaceModule.set_manager(manager)\nmoveModule.set_manager(manager)\ninputControl = EventInputThread(\"input thread \", True)\ninputControl.set_manager(manager)\ninputControl.start()\nmanager.begin()\nmanager.start()\n\n","sub_path":"src/tests/testArbiter.py","file_name":"testArbiter.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"343930661","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 30 11:35:11 2019\r\n\r\n@author: FartherSkies\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.parallel\r\nimport torch.optim as optim\r\nimport torch.utils.data\r\nfrom torch.autograd import Variable\r\n\r\n# data is similar to RBM model\r\n\r\nmovies = pd.read_csv('ml-1m/movies.dat', sep = '::', header = None, engine = 'python', encoding = 'latin-1')\r\nusers = pd.read_csv('ml-1m/users.dat', sep = '::', header = None, engine = 'python', encoding = 'latin-1')\r\nratings = pd.read_csv('ml-1m/ratings.dat', sep = '::', header = None, engine = 'python', encoding = 'latin-1')\r\n\r\n# Preparing the training set and the test set\r\ntraining_set = pd.read_csv('ml-100k/u1.base', delimiter = '\\t')\r\ntraining_set = np.array(training_set, dtype = 'int')\r\ntest_set = pd.read_csv('ml-100k/u1.test', delimiter = '\\t')\r\ntest_set = np.array(test_set, dtype = 'int')\r\n\r\n# Convert to arrays\r\nnb_users = int(max(max(training_set[:,0]), max(test_set[:,0])))\r\nnb_movies = int(max(max(training_set[:,1]), max(test_set[:,1])))\r\n # based on user/movie index from two different RANDOM splits\r\n\r\nprint (nb_movies, nb_users)\r\n\r\n# observations = row, features = columns\r\n\r\ndef convert (data):\r\n # list of list for pytorch\r\n new_data = []\r\n for id_users in range (1, nb_users+1):\r\n id_movies = data[:,1][data[:,0] == id_users]\r\n id_ratings = data[:,2][data[:,0] == id_users]\r\n # indices of the RATED movies\r\n ratings = np.zeros (nb_movies)\r\n ratings[id_movies-1]=id_ratings\r\n new_data.append (list(ratings))\r\n return new_data\r\n\r\ntorch_train = convert (training_set)\r\ntorch_test = convert (test_set)\r\n\r\n# to torch tensor\r\ntorch_train = torch.FloatTensor (torch_train)\r\ntorch_test = torch.FloatTensor (torch_test)\r\n\r\n# autoencoder class : {f(x)}->object\r\n# nn(parent) > ae_class(child) >> inheritance\r\n\r\nclass Stacked_AE (nn.Module):\r\n def __init__(self,):\r\n super(Stacked_AE, self).__init__()\r\n # all functions and inherited\r\n \r\n # encoding\r\n self.fc1 = nn.Linear(nb_movies, 30)\r\n self.fc2 = nn.Linear(30, 10)\r\n # decoding\r\n self.fc3 = nn.Linear(10, 30)\r\n self.fc4 = nn.Linear(30, nb_movies)\r\n \r\n self.activation = nn.Sigmoid()\r\n # self.activation = nn.LeakyReLU()\r\n # self.activation = nn.Tanh ()\r\n self.dropout = nn.Dropout(0.5)\r\n def forward (self, x):\r\n x = self.activation(self.fc1(x))\r\n x = self.dropout (x)\r\n x = self.activation(self.fc2(x))\r\n # x = self.dropout (x)\r\n x = self.activation(self.fc3(x))\r\n x = self.fc4(x)\r\n return x\r\n\r\nsae = Stacked_AE()\r\ncriterion = nn.MSELoss()\r\noptimizer = optim.RMSprop(sae.parameters(), lr=0.02, weight_decay=0.5)\r\n\r\n# training\r\n\r\nnb_epochs = 200\r\nfor epoch in range (1, nb_epochs+1):\r\n train_loss = 0\r\n s = 0. # how many users acutally rated\r\n for id_user in range (nb_users):\r\n input = Variable (torch_train [id_user]).unsqueeze(0)\r\n # will create a batch\r\n target = input.clone()\r\n if torch.sum (target.data>0) > 0:\r\n output = sae (input)\r\n target.require_grad = False\r\n output[target == 0] = 0\r\n loss = criterion (output, target)\r\n mean_corrector = nb_movies/float(torch.sum(target.data>0) + 1e-10)\r\n # stability\r\n \r\n # optimizer.zero_grad() - causes no change, mapping?\r\n loss.backward()\r\n train_loss += np.sqrt(loss.data * mean_corrector)\r\n # index of error\r\n s += 1.\r\n optimizer.step()\r\n # update weights\r\n # backward = direction of udpate\r\n # optimizer = intensity of update\r\n print ('epoch: '+str(epoch)+'; '+'loss: '+str(train_loss/s))\r\n \r\n # given that target = 0, we're not using loss.zero_grad\r\n # https://stackoverflow.com/questions/44732217/why-do-we-need-to-explicitly-call-zero-grad\r\n \r\n# test set\r\n \r\ntest_loss = 0\r\ns = 0. # how many users acutally rated\r\nfor id_user in range (nb_users):\r\n input = Variable (torch_train [id_user]).unsqueeze(0)\r\n # will create a batch\r\n target = Variable (torch_test [id_user]).unsqueeze(0)\r\n if torch.sum (target.data>0) > 0:\r\n output = sae (input)\r\n target.require_grad = False\r\n output[target == 0] = 0\r\n loss = criterion (output, target)\r\n mean_corrector = nb_movies/float(torch.sum(target.data>0) + 1e-10)\r\n test_loss += np.sqrt(loss.data * mean_corrector)\r\n s += 1.\r\nprint ('test loss: '+str(test_loss/s))\r\n\r\n# single item prediction\r\n\r\ntarget_user_id = 3\r\ntarget_movie_id = 345\r\ninput = Variable(torch_train[target_user_id-1]).unsqueeze(0)\r\noutput = sae(input)\r\noutput_numpy = output.data.numpy()\r\nprint (''+ str(output_numpy[0,target_movie_id-1]))\r\n ","sub_path":"Udemy/Deep Learning A-Z/Building my AutoEncoder/my_ae.py","file_name":"my_ae.py","file_ext":"py","file_size_in_byte":4955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"549737157","text":"from __future__ import unicode_literals\n\n# ANSI_COLOR = \"\\x1b[{0}m\"\nANSI_BOLD = 1\nANSI_RED = 31\nANSI_GREEN = 32\nANSI_YELLOW = 33\nANSI_RESET = 0\nFORCE_TTY_COLOR = False\n\n\ndef tty_color(stream, *codes):\n if codes and FORCE_TTY_COLOR or hasattr(stream, \"isatty\") and stream.isatty():\n stream.write(\"\\x1b[{}m\".format(\";\".join([str(i) for i in codes])))\n","sub_path":"ksconf/util/terminal.py","file_name":"terminal.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"79593842","text":"#!/usr/bin/env python3\n\nimport sys\nfrom parse import *\nimport pickle\nimport pandas as pd\n\nsecondsBeforeTrigger = 0.1\nsecondsAfterTrigger = 0.01\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"usage: extract_data.py <directory|file.raw> <extract_dir>\")\n sys.exit(1)\n\n (path, fileBasenames) = getInputFiles(sys.argv[1])\n extractDir = sys.argv[2]\n if not os.path.exists(extractDir):\n os.makedirs(extractDir)\n\n captures = []\n extractIdx = 0\n invalidTriggers = 0\n audioPeaks = []\n for file in fileBasenames:\n usedPeaks = set()\n try:\n print(\"reading {}\".format(file))\n cap = Capture.fromFile(path, file)\n\n for t,state in cap.triggers:\n # find wav peak for this trigger\n searchBefore = .03\n searchAfter = .06\n b = max(cap.firstValid, t - searchBefore)\n e = min(cap.lastValid, t + searchAfter)\n if e - b < searchAfter:\n continue\n\n try:\n (trFrom, trTo) = findFromTo(b, e, cap.wavHullTtrigg)\n except Exception:\n continue\n\n smallestDistance = max(searchBefore, searchAfter)\n peak = -1\n for i in range(trFrom, trTo):\n distance = t - cap.wavHullTtrigg[i]\n absd = np.abs(distance)\n if absd < smallestDistance and i not in usedPeaks:\n smallestDistance = absd\n peak = i\n\n usedPeaks.add(peak)\n if peak == -1:\n try:\n (wavFrom, wavTo) = findFromTo(b, e, cap.wavT)\n except Exception:\n continue\n if np.sum(cap.wavHullYd[wavFrom:wavTo]) > 0.01:\n invalidTriggers += 1\n audioPeak = 0.0\n else:\n audioPeak = cap.wavHullYtrigg[peak]\n\n b = max(cap.firstValid, t - secondsBeforeTrigger)\n e = min(cap.lastValid, t + secondsAfterTrigger)\n if e - b < secondsBeforeTrigger:\n continue\n try:\n (rawFrom, rawTo) = findFromTo(b, e, cap.t)\n except Exception:\n continue\n\n t0 = cap.t[rawFrom]\n time = [int((x - t0) * 1000000) for x in cap.t[rawFrom:rawTo]]\n pos = cap.rawPos[rawFrom:rawTo]\n vel = cap.rawVel[rawFrom:rawTo]\n audioPeaks += [audioPeak]\n data = {\n 't': time,\n 'pos': pos,\n 'vel': vel,\n 'triggerTime': t - t0,\n 'audioPeak': audioPeak,\n 'logicState': state,\n }\n\n # Store data (serialize)\n with open(os.path.join(extractDir, '{}.pickle'.format(extractIdx)), 'wb') as handle:\n pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)\n extractIdx += 1\n\n #fig = go.Figure()\n #fig.add_trace(go.Scattergl(\n # name='raw pos',\n # x=cap.t[rawFrom:rawTo],\n # y=pos,\n # yaxis=plotAxisPosRaw,\n #))\n #fig.add_trace(go.Scattergl(\n # name='raw vel',\n # x=cap.t[rawFrom:rawTo],\n # y=vel,\n # yaxis=plotAxisVelRaw,\n #))\n #fig.add_trace(go.Scattergl(\n # name='desired',\n # x=[cap.t[rawFrom], cap.t[rawTo]],\n # y=[desiredVel, desiredVel],\n # yaxis=plotAxisWav,\n #))\n\n ##(wavFrom, wavTo) = findFromTo(b, e, cap.wavHullT)\n ##wavHullYh = cap.wavHullYh[wavFrom:wavTo]\n ##wavHullYl = cap.wavHullYl[wavFrom:wavTo]\n ##wavHullYd = np.abs(np.array(wavHullYh) - np.array(wavHullYl))\n ##fig.add_trace(go.Scattergl(\n ## name='hull h',\n ## x=cap.wavHullT[wavFrom:wavTo],\n ## y=wavHullYh,\n ## yaxis=plotAxisWav,\n ##))\n ##fig.add_trace(go.Scattergl(\n ## name='hull l',\n ## x=cap.wavHullT[wavFrom:wavTo],\n ## y=wavHullYl,\n ## yaxis=plotAxisWav,\n ##))\n ##fig.add_trace(go.Scattergl(\n ## name='hull d',\n ## x=cap.wavHullT[wavFrom:wavTo],\n ## y=wavHullYd,\n ## yaxis=plotAxisWav,\n ##))\n #setFigureLayout(fig)\n #plotly.offline.plot(fig, filename='/tmp/efafrrga.html', auto_open=True)\n #wavHullYh = cap.wavHullYh[b:e]\n #wavHullYl = cap.wavHullYl[b:e]\n except IOError as e:\n print(\"Error while loading Capture:\")\n print(e)\n continue\n\n # save meta info\n meta = {\n 'audioPeaks': audioPeaks,\n }\n pd.DataFrame(meta).to_csv(os.path.join(extractDir, '.meta'), index=None)\n print(\"extracted {} samples, and skipped {} invalid triggers\".format(extractIdx, invalidTriggers))\n","sub_path":"contrib/continuous/extract_data.py","file_name":"extract_data.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"369925118","text":"import os\nimport argparse\nimport sys\nimport shutil\n\ncurrentdir = os.getcwd()\nrootdir = \"D:\\\\Programming\\\\Workspace\\\\CommandLine\\\\AppContextICSE\\\\InstrumentedAppAPKOnly\\\\InstrumentedApp1\"\nfor path, subdirs, files in os.walk(rootdir):\n for name in files:\n if name.endswith(\".apk\"):\n filepath = os.path.join(path, name)\n p, filename = os.path.split(filepath)\n a, dir = os.path.split(p)\n manifest_dir = os.path.join(currentdir, \"Decomplied\", dir)\n filepath1 = os.path.join(manifest_dir, filename)\n manifest_file = os.path.join(filepath1, \"AndroidManifest.xml\")\n destPath = os.path.join(\"D:\\\\Programming\\\\Workspace\\\\CommandLine\\\\AppContextICSE\", \"GenomeManifest\",dir,filename)\n if not os.path.exists(destPath):\n os.makedirs(destPath)\n destManifest = os.path.join(destPath, \"AndroidManifest.xml\")\n destapk = os.path.join(destPath, name)\n shutil.copyfile(filepath, destapk);\n shutil.copyfile(manifest_file, destManifest);\n\n","sub_path":"Manifest/extractManifestForInstrument.py","file_name":"extractManifestForInstrument.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"23621553","text":"#!/usr/bin/env python\nimport rospy\nimport numpy as np\nimport math\nimport tf\nfrom enum import Enum\nfrom std_msgs.msg import UInt8, Float64\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Twist\nfrom nav_msgs.msg import Odometry\n\ndef callback(x): \n pass\n\nclass ControlParking():\n def __init__(self):\n\n self.sub_odom = rospy.Subscriber('/odom', Odometry, self.cbOdom, queue_size=1)\n self.parking_start = rospy.Subscriber('/pak_or', UInt8, self.cbParkingStart, queue_size=1)\n self.pub_cmd_vel = rospy.Publisher('/cmd_vel', Twist, queue_size = 1)\n self.paking_order_st = rospy.Publisher('/pak_or_st', UInt8, queue_size = 1)\n self.sub_scan_obstacle = rospy.Subscriber('/scan', LaserScan, self.cbScanObstacle, queue_size=1)\n self.theta = 0.0\n self.current_theta = 0.0\n self.last_current_theta = 0.0\n self.is_step_start = False\n self.current_step_of_parking = 1\n self.lastError = 0.0\n self.is_step_parking = True\n self.side = 0\n self.realside = 0\n loop_rate = rospy.Rate(10) # 10hz\n while not rospy.is_shutdown():\n if self.is_step_parking == True:\n self.fnParking()\n \n loop_rate.sleep()\n\n rospy.on_shutdown(self.fnShutDown)\n def cbScanObstacle(self, scan):\n self.side = 0\n for i in range(80,100):\n if scan.ranges[i] < 0.5 and scan.ranges[i] > 0.01:\n self.side = 2\n for i in range(260,280):\n if scan.ranges[i] < 0.5 and scan.ranges[i] > 0.01:\n self.side = 1\n def cbParkingStart(self, parking_start_msg):\n self.is_step_parking = True\n self.lastError = 0.0\n\n def fnParking(self):\n print(self.current_step_of_parking)\n if self.current_step_of_parking == 1:\n rospy.loginfo(\"find anortor car\")\n if self.side == 1:\n self.current_step_of_parking = 2\n self.realside = 1\n elif self.side == 2:\n self.current_step_of_parking = 3\n self.realside = 2\n\n\n elif self.current_step_of_parking == 2:\n rospy.loginfo(\"Left\")\n if self.is_step_start == False:\n self.lastError = 0.0\n self.desired_theta = self.current_theta + 1.57\n self.is_step_start = True\n\n error = self.fnTurn()\n\n if math.fabs(error) < 0.05:\n rospy.loginfo(\"Left finished\")\n self.current_step_of_parking = 4\n self.is_step_start = False \n\n\n elif self.current_step_of_parking == 3:\n rospy.loginfo(\"Right\")\n if self.is_step_start == False:\n self.lastError = 0.0\n self.desired_theta = self.current_theta - 1.57\n self.is_step_start = True\n\n error = self.fnTurn()\n\n if math.fabs(error) < 0.05:\n rospy.loginfo(\"Right finished\")\n self.current_step_of_parking = 4\n self.is_step_start = False\n\n\n elif self.current_step_of_parking == 4:\n rospy.loginfo(\"in_parking\")\n if self.is_step_start == False:\n self.lastError = 0.0\n self.start_pos_x = self.current_pos_x\n self.start_pos_y = self.current_pos_y\n self.is_step_start = True\n\n error = self.fnStraight(0.25)\n\n if math.fabs(error) < 0.005:\n rospy.loginfo(\"parking_lot_in finished\")\n self.current_step_of_parking = 5\n self.is_step_start = False \n\n\n elif self.current_step_of_parking == 5:\n rospy.loginfo(\"parking_lot_stop\")\n self.fnStop()\n\n rospy.sleep(2)\n\n rospy.loginfo(\"parking_lot_stop finished\")\n self.current_step_of_parking = 6\n\n\n elif self.current_step_of_parking == 6:\n rospy.loginfo(\"Turn around\")\n if self.is_step_start == False:\n self.lastError = 0.0\n self.desired_theta = self.current_theta + 3.14\n self.is_step_start = True\n\n error = self.fnTurn()\n\n if math.fabs(error) < 0.05:\n rospy.loginfo(\"Turn finished\")\n self.current_step_of_parking = 7\n self.is_step_start = False\n\n\n elif self.current_step_of_parking == 7:\n rospy.loginfo(\"out_parking\")\n if self.is_step_start == False:\n self.lastError = 0.0\n self.start_pos_x = self.current_pos_x\n self.start_pos_y = self.current_pos_y\n self.is_step_start = True\n\n error = self.fnStraight(0.25)\n\n if math.fabs(error) < 0.005:\n rospy.loginfo(\"parking_lot_in finished\")\n if self.realside==1:\n self.current_step_of_parking = 9\n if self.realside==2:\n self.current_step_of_parking = 8\n self.is_step_start = False \n \n\n elif self.current_step_of_parking == 8:\n rospy.loginfo(\"Right\")\n if self.is_step_start == False:\n self.lastError = 0.0\n self.desired_theta = self.current_theta - 1.57\n self.is_step_start = True\n\n error = self.fnTurn()\n\n if math.fabs(error) < 0.05:\n rospy.loginfo(\"Right finished\")\n self.current_step_of_parking = 10\n self.is_step_start = False\n\n elif self.current_step_of_parking == 9:\n rospy.loginfo(\"Left\")\n if self.is_step_start == False:\n self.lastError = 0.0\n self.desired_theta = self.current_theta + 1.57\n self.is_step_start = True\n\n error = self.fnTurn()\n\n if math.fabs(error) < 0.05:\n rospy.loginfo(\"Left finished\")\n self.current_step_of_parking = 10\n self.is_step_start = False\n\n\n elif self.current_step_of_parking == 10:\n rospy.loginfo(\"in_parking\")\n if self.is_step_start == False:\n self.lastError = 0.0\n self.start_pos_x = self.current_pos_x\n self.start_pos_y = self.current_pos_y\n self.is_step_start = True\n\n error = self.fnStraight(0.25)\n\n if math.fabs(error) < 0.005:\n rospy.loginfo(\"parking_lot_in finished\")\n self.current_step_of_parking = 0\n self.is_step_start = False \n\n else:\n rospy.loginfo(\"idle (if finished to go out from parking lot)\")\n msg_parking_finished = UInt8()\n msg_parking_finished.data = 1\n self.paking_order_st.publish(msg_parking_finished)\n self.fnStop()\n self.is_step_parking = False\n\n\n def cbOdom(self, odom_msg):\n quaternion = (odom_msg.pose.pose.orientation.x, odom_msg.pose.pose.orientation.y, odom_msg.pose.pose.orientation.z, odom_msg.pose.pose.orientation.w)\n self.current_theta = self.euler_from_quaternion(quaternion)\n\n if (self.current_theta - self.last_current_theta) < -math.pi:\n self.current_theta = 2. * math.pi + self.current_theta\n self.last_current_theta = math.pi\n elif (self.current_theta - self.last_current_theta) > math.pi:\n self.current_theta = -2. * math.pi + self.current_theta\n self.last_current_theta = -math.pi\n else:\n self.last_current_theta = self.current_theta\n\n self.current_pos_x = odom_msg.pose.pose.position.x\n self.current_pos_y = odom_msg.pose.pose.position.y\n \n def euler_from_quaternion(self, quaternion):\n theta = tf.transformations.euler_from_quaternion(quaternion)[2]\n return theta\n def fnTurn(self):\n err_theta = self.current_theta - self.desired_theta\n \n rospy.loginfo(\"Parking_Turn\")\n rospy.loginfo(\"err_theta desired_theta current_theta : %f %f %f\", err_theta, self.desired_theta, self.current_theta)\n Kp = 0.8\n\n Kd = 0.03\n\n angular_z = Kp * err_theta + Kd * (err_theta - self.lastError)\n self.lastError = err_theta\n\n twist = Twist()\n twist.linear.x = 0\n twist.linear.y = 0\n twist.linear.z = 0\n twist.angular.x = 0\n twist.angular.y = 0\n twist.angular.z = -angular_z\n self.pub_cmd_vel.publish(twist)\n\n rospy.loginfo(\"angular_z : %f\", angular_z)\n\n return err_theta\n\n def fnStraight(self, desired_dist):\n err_pos = math.sqrt((self.current_pos_x - self.start_pos_x) ** 2 + (self.current_pos_y - self.start_pos_y) ** 2) - desired_dist\n \n rospy.loginfo(\"Parking_Straight\")\n\n Kp = 0.4\n Kd = 0.05\n\n angular_z = Kp * err_pos + Kd * (err_pos - self.lastError)\n self.lastError = err_pos\n\n twist = Twist()\n twist.linear.x = 0.07\n twist.linear.y = 0\n twist.linear.z = 0\n twist.angular.x = 0\n twist.angular.y = 0\n twist.angular.z = 0\n self.pub_cmd_vel.publish(twist)\n\n return err_pos\n\n def fnStop(self):\n twist = Twist()\n twist.linear.x = 0\n twist.linear.y = 0\n twist.linear.z = 0\n twist.angular.x = 0\n twist.angular.y = 0\n twist.angular.z = 0\n self.pub_cmd_vel.publish(twist)\n\n\n def fnShutDown(self):\n rospy.loginfo(\"Shutting down. cmd_vel will be 0\")\n\n twist = Twist()\n twist.linear.x = 0\n twist.linear.y = 0\n twist.linear.z = 0\n twist.angular.x = 0\n twist.angular.y = 0\n twist.angular.z = 0\n self.pub_cmd_vel.publish(twist) \n\n def main(self):\n rospy.spin()\n\nif __name__ == '__main__':\n rospy.init_node('control_parking')\n node = ControlParking()\n node.main()\n","sub_path":"catkin_ws/src/steamcup/src/oioi.py","file_name":"oioi.py","file_ext":"py","file_size_in_byte":9981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247011700","text":"# Create your views here.\nimport logging\n\nfrom django.utils.translation import gettext as _\nfrom rest_framework.response import Response\nfrom rest_framework.status import HTTP_400_BAD_REQUEST\nfrom rest_framework.views import APIView\n\nfrom config.const import *\nfrom config.utils import *\nfrom config.utils import now_ms, req_log_message, res_log_message\nfrom core.post.models import Favorite, Post, Tag\n\nlogger = logging.getLogger(__name__)\n\nclass AddToFavorites(APIView):\n def post(self, request):\n req_time = now_ms()\n logger.info(req_log_message(request, req_time))\n post_id = request.data.get(\"post_id\")\n favorite_name = request.data.get(\"favorite\")\n if not (validate_charfield_input(favorite_name, favorite_title_max_length)):\n return Response({'error': _('favorite name is too long.')},\n status=HTTP_400_BAD_REQUEST)\n user = request.user\n favorites = Favorite.objects.get_or_create(title=favorite_name, profile=user.profile)\n if (Post.objects.filter(id=post_id).exists()):\n favorites[0].posts.add(Post.objects.get(id=post_id))\n log_result = 'Post(id={0}) added to favorite (id={1}.'.format(post_id, favorites[0].id)\n log_message = res_log_message(request, log_result, req_time)\n logger.info(log_message)\n return Response({'status': _('succeeded')})\n else:\n return Response({'error': _('no such post')},\n status=HTTP_400_BAD_REQUEST)\nclass RemoveFromFavorites(APIView):\n def post(self, request):\n req_time = now_ms()\n logger.info(req_log_message(request, req_time))\n favorite_id = request.data.get(\"favorite_id\")\n if (Favorite.objects.filter(id=favorite_id).exists()):\n Favorite.objects.get(id=favorite_id).delete()\n log_result = 'favorite (id={0}) removed from favorite list'.format(favorite_id)\n log_message = res_log_message(request, log_result, req_time)\n logger.info(log_message)\n return Response({'status': _('succeeded')})\n else:\n return Response({'error': _('no such favorite')},\n status=HTTP_400_BAD_REQUEST)\n\nclass AddToTags(APIView):\n def post(self, request):\n req_time = now_ms()\n logger.info(req_log_message(request, req_time))\n post_id = request.data.get(\"post_id\")\n tag_text = request.data.get(\"tag\")\n post = Post.objects.get(id=post_id)\n\n # post=Post.objects.get(post_id=post_id)\n # if post.profile.user != request.user\n # return({({'error': _('you cant add tag to others post)},\n # status=HTTP_400_BAD_REQUEST)})\n tags = Tag.objects.get_or_create(text=tag_text)\n tags[0].posts.add(post)\n post.tags.add(tags[0])\n log_result = 'tag (text={0}) added to Post (id={1}).'.format(tag_text, post_id)\n log_message = res_log_message(request, log_result, req_time)\n logger.info(log_message)\n return Response({'status': _('succeeded')})\n","sub_path":"core/post/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"444395264","text":"\"\"\"\n2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\nWhat is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\n\"\"\"\n\ndef DivideAll(number):\n for i in range(2,21):\n if number % i != 0:\n return False\n return True\n\nnum = 20\nflag = True\nwhile flag:\n if DivideAll(num):\n flag = False\n else:\n num = num +1\nprint(num)\n","sub_path":"Problem5.py","file_name":"Problem5.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"73015296","text":"import tensorflow as tf \nfrom tools.data_pool import DataPool\n\nFROZEN_GRAPH_FILE = \"./frozen_graph/graph.pb\"\nDATA_DIR = './data/aclImdb/test'\n\ndef _main():\n # 加载计算图\n # parse the graph_def file\n\n with tf.gfile.GFile(FROZEN_GRAPH_FILE, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n # load the graph_def in the default graph\n\n graph = tf.Graph()\n with graph.as_default():\n tf.import_graph_def(\n graph_def,\n input_map = None,\n return_elements = None,\n name = \"trained\",\n op_dict = None,\n producer_op_list = None\n )\n inputs = graph.get_tensor_by_name('trained/input_data:0')\n loss = graph.get_tensor_by_name('trained/loss:0')\n out_softmax = graph.get_tensor_by_name('trained/softmax_prediction:0')\n\n # 数据构造\n data_generator = data_pool.DataPool(data_top_dir=DATA_DIR, is_use_embedding=False, batch_size=1)\n with tf.Session() as sess:\n for sentence, label in next(data_generator):\n feed_dict = {\n inputs: sentence,\n }\n predict = sess.run([softmax_prediction], feed_dict=feed_dict)\n print(label)\n print(predict)\n break\n\nif __name__ == \"__main__\":\n _main()","sub_path":"cha6_rnn/2_movie_review_classification/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"379423848","text":"# -*- coding: utf-8 *-*\n\"\"\"Hook to run after template is created\"\"\"\nimport os\nimport shutil\nimport subprocess\nfrom subprocess import CalledProcessError\n\nPROJECT_DIRECTORY = os.path.realpath(os.path.curdir)\n\ndef remove_dir(dirpath):\n \"\"\"Recursively delete a directory\"\"\"\n shutil.rmtree(os.path.join(PROJECT_DIRECTORY, dirpath))\n\ndef remove_file(filepath):\n \"\"\"Remove a file from the generated template\"\"\"\n os.remove(os.path.join(PROJECT_DIRECTORY, filepath))\n\nif __name__ == '__main__':\n if 'Not open source' == '{{ cookiecutter.open_source_license }}':\n remove_file('LICENSE')\n\n if 'n' == '{{ cookiecutter.windows_support }}':\n remove_file('appveyor.yml')\n remove_file(os.path.sep.join(['docs', 'make.bat']))\n remove_file('make.bat')\n\n if 'n' == '{{ cookiecutter.docs }}':\n remove_dir('docs')\n\n try:\n subprocess.run(\n ['which',\n 'pipenv'],\n stdout=subprocess.DEVNULL).check_returncode()\n subprocess.run(['pipenv', 'lock', '--dev'])\n subprocess.run(['pipenv', 'sync', '--dev'])\n except CalledProcessError:\n print('pipenv not installed, or not available on PATH')\n","sub_path":"hooks/post_gen_project.py","file_name":"post_gen_project.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"349748416","text":"from django.db import models\n\n\nclass ClientInfo(models.Model):\n \"\"\"\n Модель инфо человека, записывающегося на вебинар\n \"\"\"\n first_name = models.CharField(\"Имя\", max_length=15)\n last_name = models.CharField(\"Фамилия\", max_length=15)\n # company = models.CharField(\"Компания\", max_length=50)\n email = models.EmailField(\"Email\")\n # phone = models.IntegerField(verbose_name=\"Телефон\")\n \n class Meta:\n verbose_name = \"Клиент\"\n verbose_name_plural = \"Клиенты\"\n \n def __str__(self):\n return self.first_name\n","sub_path":"webinar/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"441547301","text":"\"\"\"TC ETDMS Validator\nValidates etdms for usage at Library and Archives Canada\n(mandatory fields, non-repeatable fields, desired fields)\n\"\"\"\nimport sys\n\nimport requests\nimport bs4\n\n\ndef check_url(base_url: str) -> bool:\n \"\"\"Verify that url exist and gives us a status code 200\"\"\"\n try:\n res = requests.get(base_url)\n res.raise_for_status()\n except requests.exceptions.HTTPError as err:\n print(err)\n return False\n except requests.exceptions.Timeout as err:\n print(\"Request timeout for \" + base_url)\n return False\n except requests.exceptions.TooManyRedirects as err:\n print(\"Too many redirects for \" + base_url)\n return False\n except requests.exceptions.RequestException as err:\n print(err)\n return False\n print(\"INFO: url is valid\")\n return True\n\ndef check_metadata_formats(base_url: str, metadata_format: str = '') -> bool:\n \"\"\"Check which metadata formats are supported by the server\"\"\"\n formats_url = base_url + '?verb=ListMetadataFormats'\n available_formats = []\n supports_ore = False\n found_valid_format = False\n # Namespaces we recognise\n usable_formats = ( \\\n '(http://www.ndltd.org/standards/metadata/etdms/1.1/)' \\\n '(http://www.ndltd.org/standards/metadata/etdms/1.0/)'\n )\n res = requests.get(formats_url)\n soup = bs4.BeautifulSoup(res.text, \"xml\")\n formats = soup.find_all('metadataFormat')\n print(\"Available metadata formats (*=harvestable)\")\n print(\"-----------------\")\n for frmt in formats:\n if frmt.metadataNamespace.text in usable_formats:\n star = \"*\"\n found_valid_format = True\n else:\n star = \" \"\n if frmt.metadataNamespace.text.lower() == 'http://www.w3.org/2005/Atom'.lower():\n supports_ore = True\n print(star + frmt.metadataPrefix.text + ' (' + frmt.metadataNamespace.text + ')')\n available_formats.append(frmt.metadataPrefix.text)\n print(\"-----------------\")\n if supports_ore:\n print('INFO: Server supports ORE')\n else:\n print('ERROR: Server does NOT support ORE')\n if metadata_format != '' and metadata_format in available_formats:\n print('INFO: using format [' + metadata_format + ']')\n elif metadata_format != '' and metadata_format not in available_formats:\n print('INFO: requested format <' + metadata_format + '> is not available')\n return False\n elif metadata_format == '' and not found_valid_format:\n print('ERROR: no metadata correponds to a recognized namespace. Impossible to harvest')\n return False \n elif metadata_format == '' and found_valid_format:\n print('WARNING: no metadata format selected. Please specify a format to complete the validation.')\n return False\n\n return True\n\n\ndef check_identify(base_url: str) -> bool:\n \"\"\"Check that the server is OAI-PMH version 2.0\"\"\"\n identify_url = base_url + '?verb=Identify'\n try:\n res = requests.get(identify_url)\n res.raise_for_status()\n except requests.exceptions.RequestException as err:\n print(err)\n return False\n\n soup = bs4.BeautifulSoup(res.text, \"xml\")\n if soup.protocolVersion is None:\n print(\"Invalid OAI-PMH\")\n return False\n if soup.protocolVersion.text != \"2.0\":\n print(\"Unknown OAI-PMH version : \" + soup.protocolVersion)\n return False\n print('INFO: Server is OAI-PMH 2.0')\n return True\n\n\ndef check_these(base_url: str, metadata_format: str, dataset: str = \"\") -> bool:\n \"\"\"Check the first these for mandatory fields and validity\"\"\"\n records_url = base_url \\\n + \"?verb=ListRecords\" \\\n + \"&metadataPrefix=\" + metadata_format\n if dataset != \"\":\n records_url += \"&set=\" + dataset\n print('INFO: using set [' + dataset + ']')\n\n print(\"INFO: requested url [\" + records_url + ']')\n\n try:\n res = requests.get(records_url)\n res.raise_for_status()\n except requests.exceptions.RequestException as err:\n print(err)\n return False\n\n soup = bs4.BeautifulSoup(res.text, \"xml\")\n if soup.error is not None:\n print('ERROR: ' + soup.error.text)\n return False\n is_valid = True\n\n if soup.resumptionToken and 'completeListSize' in soup.resumptionToken:\n print(\"INFO: completeListSize = \" + soup.resumptionToken['completeListSize'])\n\n # Mandatory fields\n if soup.thesis is None:\n print(\"ERROR: Missing <thesis> root element, this repository can't be harvested\")\n return False\n if soup.thesis.title is None or soup.thesis.title.text == '':\n print(\"ERROR: Missing mandatory <title> field\")\n is_valid = False\n if soup.thesis.creator is None or soup.thesis.creator.text == '':\n print(\"ERROR: Missing mandatory <creator> field\")\n is_valid = False\n if soup.thesis.publisher is None or soup.thesis.publisher.text == '':\n print(\"ERROR: Missing mandatory <publisher> field\")\n is_valid = False\n if soup.thesis.date is None or soup.thesis.date.text == '':\n print(\"ERROR: Missing mandatory <date> field\")\n is_valid = False\n if soup.thesis.identifier is None or soup.thesis.identifier.text == '':\n print(\"ERROR: Missing mandatory <identifier> field\")\n is_valid = False\n if soup.thesis.language is None or soup.thesis.language.text == '':\n print(\"ERROR: Missing mandatory <language> field\")\n is_valid = False\n\n #Non repeatable fields\n if soup.thesis.date is not None and len(soup.thesis.date) > 1:\n print(\"ERROR: <date> is a non-repeatable field and currently appears \" + len(soup.thesis.date) + ' times.')\n is_valid = False\n\n # Desired field\n if soup.thesis.subject is None or soup.thesis.subject.text == '':\n print(\"WARNING: <subject> is a desired field that is not present\")\n if soup.thesis.description is None or soup.thesis.description.text == '':\n print(\"WARNING: <description> is a desired field that is not present\")\n if soup.thesis.contributor is None or soup.thesis.contributor.text == '':\n print(\"WARNING: <contributor> is a desired field that is not present\")\n if (soup.thesis.degree is None \n or soup.thesis.degree.name is None\n or soup.thesis.degree.name == ''):\n print(\"WARNING: <degree><name> is a desired field that is not present\")\n\n if not is_valid:\n print(\"ERROR: data is not formatted properly, this feed can't be harvested\")\n\n return is_valid\n\n\ndef main():\n \"\"\"main function that check cli arguments all start everything\"\"\"\n if len(sys.argv) == 1:\n print(\"Enter an URL as the first argument\")\n sys.exit(2)\n\n #demo_url = \"https://etheses-test01.canadaeast.cloudapp.azure.com/oai/request\"\n url = sys.argv[1]\n\n if len(sys.argv) >= 3 and sys.argv[2]:\n metadata_format = sys.argv[2]\n else:\n metadata_format = ''\n\n if len(sys.argv) >= 4 and sys.argv[3]:\n dataset = sys.argv[3]\n else:\n dataset = ''\n\n if (check_url(url)\n and check_identify(url)\n and check_metadata_formats(url, metadata_format)\n and check_these(url, metadata_format, dataset)):\n print(\"Validation completed successfuly, metadata can be harvested\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":7363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"78459719","text":"import numpy as np\nfrom tqdm import trange\n\ndef read_input():\n wires = []\n try:\n f = open(\"input.txt\")\n except FileNotFoundError:\n print(\"Could not find an input file\")\n f.close()\n quit(-1)\n for line in f:\n wire = [(x[0], int(x[1::])) for x in line.split(',')]\n wires.append(wire)\n return wires\n\ndef size_of_grid(wires):\n minx = 10000000\n miny = 10000000\n maxx = -10000000\n maxy = -10000000\n x = 0\n y = 0\n for wire in wires:\n for step in wire:\n if x < minx:\n minx = x\n if x > maxx:\n maxx = x\n if y < miny:\n miny = y\n if y > maxy:\n maxy = y\n if step[0] == \"U\":\n y += step[1]\n elif step[0] == \"D\":\n y -= step[1]\n elif step[0] == \"R\":\n x += step[1]\n elif step[0] == \"L\":\n x -= step[1]\n else:\n print('INVALID DIRECTION')\n quit(-1)\n print(minx, miny, maxx, maxy)\n\ndef fill_board(board, wires):\n wire_num = 0\n for wire in wires:\n wire_num += 1\n pos = [15874, 7695]\n board[15874, 7695] = -1\n for step in wire:\n if step[0] == \"U\":\n for i in range(step[1]):\n pos[1] += 1\n if board[pos[0],pos[1]] == wire_num or board[pos[0],pos[1]] == 0:\n board[pos[0],pos[1]] = wire_num\n else:\n board[pos[0],pos[1]] = -2\n elif step[0] == \"D\":\n for i in range(step[1]):\n pos[1] -= 1\n if board[pos[0],pos[1]] == wire_num or board[pos[0],pos[1]] == 0:\n board[pos[0],pos[1]] = wire_num\n else:\n board[pos[0],pos[1]] = -2\n elif step[0] == \"R\":\n for i in range(step[1]):\n pos[0] += 1\n if board[pos[0],pos[1]] == wire_num or board[pos[0],pos[1]] == 0:\n board[pos[0],pos[1]] = wire_num\n else:\n board[pos[0],pos[1]] = -2\n elif step[0] == \"L\":\n for i in range(step[1]):\n pos[0] -= 1\n if board[pos[0],pos[1]] == wire_num or board[pos[0],pos[1]] == 0:\n board[pos[0],pos[1]] = wire_num\n else:\n board[pos[0],pos[1]] = -2\n\n\ndef search_for_X(board):\n min_dist = 10000000000\n min_pos = []\n for i in trange(len(board)):\n for j in range(len(board[0])):\n if board[i,j] == -2:\n dist = abs(15874 - i) + abs(7695 - j)\n if dist < min_dist:\n min_dist = dist\n min_pos = (i,j)\n #print(min_pos, board[i,j], min_dist)\n print(min_pos)\n return min_dist\n\ndef printboard(board, size):\n for j in range(size):\n print()\n for i in range(size):\n val = int(board[15874-(size//2) + i, 7695-(size//2) + j])\n if val == -1:\n print('O', end='')\n elif val == 0:\n print('.', end='')\n elif val == 1:\n print('|', end='')\n elif val == -2:\n print('X', end='')\n else:\n print(val, end='')\n\n\ndef main():\n wires = read_input()\n #size_of_grid(wires) I need a 22583x14404 start is at 15\n print(\"Initializing the board\")\n board = np.zeros((22583,14404))\n print(\"Adding wires to the board\")\n fill_board(board, wires)\n #printboard(board, 130)\n print(\"Performing Bruteforce search\")\n min_dist = search_for_X(board)\n print(f'Minimum Manhattan Distance: {min_dist}')\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"day3/wires.py","file_name":"wires.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"134875284","text":"\"\"\"\nCartesian Genetic Programming\n=============================\nGenetic Programming is concerned with the automatic evolution (as in \nDarwinian evolution) of computational structures (such as mathematical \nequations, computer programs, digital circuits, etc.). CGP is a highly \nefficient and flexible form of Genetic Programming that encodes a graph \nrepresentation of a computer program. It was developed by Julian Miller\nin 1999. For more information see: http://cartesiangp.co.uk/\n\nThis script written by Petr Dvoracek in 2017. http://flea.name/\n\"\"\"\n\nimport random \nfrom copy import deepcopy\n\n# The main pillar of this algorithm lies in the directed oriented graph in\n# which each node represents a specific operation. \n# The nodes are commonly arranged in square lattice.\nDEFAULT_MATRIX_SIZE = (2, 5) # ROWS, COLS\n\n# The interconnection between columns. \nDEFAULT_LEVEL_BACK = 5 # If the value is equal to number of columns then \n # the interconnection is maximal.\n\n# The operation set. \n# List of tuples(`str` name, `int` arity (inputs), `function` operation). \nDEFAULT_OPERATION_SET = set([(\"BUF\", 1, lambda *arg: arg[0]),\n (\"NOT\", 1, lambda *arg: ~arg[0]), \n (\"AND\", 2, lambda *arg: ~(arg[0] & arg[1])), \n (\"OR\", 2, lambda *arg: ~(arg[0] | arg[1])), \n (\"XOR\", 2, lambda *arg: arg[0] & arg[1]), \n (\"NAND\", 2, lambda *arg: arg[0] | arg[1]),\n (\"NOR\", 2, lambda *arg: arg[0] ^ arg[1]), \n (\"XNOR\", 2, lambda *arg: ~(arg[0] ^ arg[1])),\n ])\n\n# Lets find full adder by default.\n# For all input combinations define:\nDEFAULT_INPUT_DATA = [0b00001111, # A\n 0b00110011, # B\n 0b01010101] # Carry in\n# Define output combinations\nDEFAULT_TRAINING_DATA = [0b01101001, # SUM\n 0b00010111] # Carry out\n\n# The CGP is a genetic algorithm. Therefore, we need to define evolutionary parameters.\n# The number of candidate solutions.\nDEFAULT_POP_SIZE = 5 \n# Maximal generations (how long the algorithm will run)\nDEFAULT_MAX_GENERATIONS = 10000 \n\n# This function returns the list of objects with poistion `index` in the `nested_list` (list of arrays).\n# Example: get_sublist(1, [(\"A\", 3, 5), (\"C\", 1), (\"D\", \"C\")]) --> [3, 1, \"C\"]\nget_sublist = lambda index, nested_list : list(map(lambda sublist: sublist[index], nested_list))\n\n# How many genes will be mutated.\n# 10% of the chromosome length can be mutated. Chromosome length = each_node * len(node) + len(last_node); The length of node is maximal arity + the operation.\nDEFAULT_MUTATIONS = int((DEFAULT_MATRIX_SIZE[0] * DEFAULT_MATRIX_SIZE[1] * (max(get_sublist(1, DEFAULT_OPERATION_SET)) + 1) + len(DEFAULT_TRAINING_DATA)) * 0.10)\n#DEFAULT_MUTATIONS = 4\n\n\n\nclass CGP(object):\n # Printing if we find better fitness during the evolution.\n PRINT_INFO = False\n\n def __set_connections(self):\n \"\"\" Calculates the set of valid connections \"\"\"\n # For each column create valid connection interval from previous `l-back` connections.\n self._valid_connection = [(self.rows * (column - self.level_back), self.rows * column) for column in range(self.columns)] \n # Filter invalid indexes which are negative -> make them 0\n self._valid_connection = list(map(lambda sublist: list(map(lambda x: x if (x >= 0) else 0, sublist)), self._valid_connection))\n\n def __test_operation_set(self, operation_set):\n \"\"\" Check the validity of operation set.\n \n Parameters\n operation_set : list of operations\n Each opeartaion is a tuple(`str` name, `int` arity, `function` operation). \n Raises\n CGPError\n If the operation set contains inconsistent operations.\n \"\"\"\n \n # Test for empty set.\n if not operation_set:\n raise CGPError(\"EMPTY_SET\")\n # Test if each operation has a triplet of (str, int, function) and tests the arity.\n for operation in operation_set:\n if len(operation) != 3 or type(operation[0]) is not str \\\n or type(operation[1]) is not int \\\n or not callable(operation[2]):\n raise CGPError(\"INCONSISTENT_SET\", value=operation)\n # Negative arity of function is stupid. Unless, you are doing some deep shit math. \n if operation[1] < 0: \n raise CGPError(\"INCONSISTENT_ARITY\", value=operation)\n\n def set_data(self, input_data, training_data):\n \"\"\" Set Input and output data\n \n Parameters\n input_data : list\n The list of input data. In the case of digital circuit design, \n this contains all the input combinations. \n training_data : list\n The target circuit.\n \"\"\"\n self.input_data_range = list(range(-len(input_data), 0))\n self.input_data = input_data\n self.training_data = training_data\n\n def set_matrix(self, matrix, level_back=0):\n \"\"\" Initate the matrix. \n\n Parameters\n matrix : tuple (int, int)\n This tuple represents the size of matrix (rows, columns)\n\n Other Parameters\n level_back : int\n The interconnection between columns.\n \"\"\"\n self.matrix = matrix # Though, it is not used.\n self.rows = matrix[0]\n self.columns = matrix[1]\n\n self.level_back = level_back if level_back > 0 else matrix[1] # If `level_back` has invalid value (0 or less), then the interconnection is maximal. \n self.__set_connections()\n \n def set_operation_set(self, operation_set):\n \"\"\" Set the operation set.\n Parameters\n operation_set : list of operations\n Each opeartaion is a tuple(`str` name, `int` arity, `function` operation). \n Raises\n CGPError\n If the operation set contains inconsistent operations.\n \"\"\"\n self.__test_operation_set(operation_set)\n self.operation_set = operation_set\n # Transpose the operation set data.\n self.operations = get_sublist(2, operation_set)\n self.operations_arity = get_sublist(1, operation_set)\n self.operations_names = get_sublist(0, operation_set)\n # Get maximal arity\n self.maximal_arity = max(self.operations_arity)\n \n def __init__(self, matrix, operation_set, input_data, training_data, level_back=0):\n \"\"\" Initate the matrix, node arrangement, operation set and i/o data. \n\n Parameters\n matrix : tuple (int, int)\n This tuple represents the size of matrix (rows, columns)\n operation set : list of tuples (`str` name, `int` arity, `function` operation). \n The operation set.\n input_data : list\n The list of input data. In the case of digital circuit design, \n this contains all the input combinations. \n training_data : list\n The target circuit.\n\n Other Parameters\n level_back : int\n The interconnection between columns.\n\n Raises\n CGPError\n If the operation set contains inconsistent operations.\n \"\"\"\n super(CGP, self).__init__()\n \n self.set_matrix(matrix, level_back=level_back)\n self.set_operation_set(operation_set)\n self.set_data(input_data, training_data)\n\n def __create_chromosome(self):\n \"\"\" Initate the chromosome. \n The chromsome encodes the interconnection of the CGP graph. See: http://www.oranchak.com/cgp/doc/fig2.jpg\n \"\"\"\n # Init array for chromosome\n chromosome = []\n # This function selects random value from input data or previous node in the graph.\n connect = lambda connection: random.choice(self.input_data_range + list(range(connection[0], connection[1])))\n \n # Nodes may differ by their connection between columns. The interconnection is depended on the value of level back. \n for column_index in range(self.columns):\n # Get valid connection range for nodes in the column\n valid_con = self._valid_connection[column_index]\n # Function for the creation of the node. Firstly creates the connections, then adds the node operation. \n create_node = lambda: [connect(valid_con) for _ in range(self.maximal_arity)] + [random.choice(self.operations)]\n chromosome += [create_node() for _ in range(self.rows)]\n # Add last `node` which binds the primary outputs of the graph to nodes.\n valid_con = (0, len(chromosome))\n chromosome += [[connect(valid_con) for _ in self.training_data]]\n return chromosome\n\n def __init_pop(self, pop_size):\n \"\"\" Initiate the population of `pop_size` size \"\"\"\n self.pop = [self.__create_chromosome() for _ in range(pop_size)]\n # The best individual is saved in `self.best_chrom` with the best fitness `self.fitness`.\n self.best_chrom = deepcopy(self.pop[0])\n self.best_fitness = self.max_fitness\n\n def __mutate_gene(self, chromosome):\n \"\"\" Mutate random value in a `chromsome`. \n \n Parameters\n chromosome : chromsome strucutre\n The representation of candidate solution which is subject to a mutation. \n \"\"\"\n # This function selects random value from input data or previous node in the graph.\n connect = lambda connection: random.choice(self.input_data_range + list(range(connection[0], connection[1])))\n # Select some node\n random_node_idx = random.randint(0, len(chromosome) - 1)\n random_node = chromosome[random_node_idx]\n \n # And select an index from the node\n random_idx = random.randint(0, len(random_node) - 1) # Note: A <= rnd <= B\n previous_value = random_node[random_idx]\n if random_node is chromosome[-1]:\n # We mutate the last node\n while previous_value == random_node[random_idx]:\n random_node[random_idx] = connect((0, len(chromosome)))\n elif random_idx == self.maximal_arity:\n # We mutate the operation (indexing from 0)\n while previous_value == random_node[random_idx]:\n random_node[random_idx] = random.choice(self.operations)\n else:\n # We mutate the connection\n while previous_value == random_node[random_idx]:\n random_node[random_idx] = connect(self._valid_connection[ random_node_idx // self.rows ])\n\n def mutate(self):\n \"\"\" Creates a copy of the best solution and mutates it random-times.\n\n Return\n chromsome : chromosome structure\n The representation of the other candidate solution, which is similar to the best found solution.\n \"\"\"\n # Copy the best chromsome\n chromosome = deepcopy(self.best_chrom)\n # And mutate it as much as possible\n for _ in range(random.randint(1, self.mutation_rate+1)): # Mutate it at least once. Else the chromsome wouldn't change.\n self.__mutate_gene(chromosome)\n return chromosome\n\n def init_eval(self):\n \"\"\" This function is started before the run of evolution. \"\"\"\n # Buffer for the evaluation.\n buffer_data = deepcopy(self.input_data) + list(range(self.rows * self.columns + len(self.training_data)))\n buffer_indexes = list(range(-len(self.input_data), len(buffer_data) - len(self.input_data)))\n self.buffer = dict(zip(buffer_indexes, buffer_data))\n \n # Maximal fitness\n self.max_fitness = len(self.training_data) * (2 ** len(self.input_data))\n\n # Fitness mask.\n # V mask V The number of bites V # We are doing parallel evaluation. \n self.bitmask = 2 ** (2 ** len(self.input_data)) - 1\n # Set generations.\n self.generation = 0\n\n def chrom_to_str(self, chromosome):\n \"\"\" Creates a string representation of chromosome, in which the nodes are aligned into a lattice. \n Each node has syntax `index` : [`previous index`, ... , `previous index`, `Function name`] \n If the node was primary output, then the node is ended with a string `<- `. \n The primary outputs are also printed in the last line for the sake of their permutation. \n\n Parameters\n chromsome : chromosome structure\n The representation of chromosome.\n Returns\n str\n The string representation of chromosome.\n \"\"\"\n # Some math stuff\n max_input_strlen = len(str(self.columns * self.rows))\n max_length_of_operation_string = max(list(map(len, self.operations_names)))\n chrom_str = \"\"\n for i in range(self.rows):\n line = \"\"\n for j in range(self.columns):\n # Grab the node index \n node_idx = j * self.rows + i\n node = chromosome[node_idx]\n # Find the inputs, and align them.\n inputs = node[:-1] # The last node is operation; the rest are the inputs.\n aligned_inputs = list(map(lambda x: str(x).rjust(max_input_strlen), inputs))\n # Find out the operation name and align it.\n operation = node[-1]\n operation_index = self.operations.index(operation)\n operation_name = self.operations_names[operation_index]\n aligned_operation_name = operation_name.rjust(max_length_of_operation_string)\n # save it\n if node_idx in chromosome[-1]:\n flag = \"<- \"\n else:\n flag = \" \"\n line += str(node_idx).rjust(max_input_strlen) + \": [\" + \", \".join(aligned_inputs) + \", \" + aligned_operation_name + \"]\" + flag\n chrom_str += line + \"\\n\"\n return chrom_str + str(chromosome[-1])\n\n \n def eval(self, chromosome):\n \"\"\" Evaluates the `chromosome` and returns the fitness value. Also checks if we found a better solution.\n Parameters\n chromsome : chromosome structure\n The representation of a candidate solution.\n Returns\n int : fitness value\n The quality of the candidate solution.\n TODO\n Optimise it. Skip neutral mutations. Skip unused nodes. (Maybe use C/C++ function?)\n Move the fitness check \n \"\"\"\n fitness = 0 \n # Evaluate each node.\n for idx, node in enumerate(chromosome[:-1]):\n # TODO SKIP unused nodes\n # Save the value of the operation `node[-1]`. The arguments are given in `node[:-1]` and they are the indexes into the `buffer`.\n self.buffer[idx] = node[-1](*[self.buffer[i] for i in node[:-1]])\n # Grab the value \n for idx, target in zip(chromosome[-1], self.training_data):\n #print idx, target, self.bitmask\n fitness += bin((self.buffer[idx] ^ target) & self.bitmask).count(\"1\")\n # Checks if we found a better solution.\n # Shouldnt be here.\n if fitness <= self.best_fitness:\n if CGP.PRINT_INFO and fitness < self.best_fitness:\n print(\"Generation: \" + str(self.generation).rjust(10) + \"\\tFitness: \" + str(fitness))\n self.best_fitness = fitness\n self.best_chrom = deepcopy(chromosome)\n return fitness\n\n def run(self, pop_size, mutations, generations):\n \"\"\" Runs the evolution.\n Parameters\n chromsome : chromosome structure\n The representation of chromosome.\n \"\"\"\n # Init evaluation\n self.init_eval()\n # Init mutation\n self.mutation_rate = mutations\n # Creates first population `self.pop` and evaluates it `self.eval`.\n self.__init_pop(pop_size)\n # Run evolution\n for self.generation in range(generations):\n # Evaluate pop\n list(map(self.eval, self.pop))\n # Mutate pop; fix the peroformance \n new_pop = [self.mutate() for _ in self.pop]\n self.pop = new_pop\n #break\n \n def __str__(self):\n return self.chrom_to_str(self.best_chrom)\n \n\nclass CGPError(Exception):\n def __init__(self, error_code, value=\"\"):\n \"\"\" Inits the exception. \"\"\"\n self.error_code = error_code\n self.value = value\n\n def __str__(self):\n \"\"\" Print error message, depending on the given error code. \"\"\"\n error_msg = {\n \"EMPTY_SET\" : \"The operation set is empty.\",\n \"INCONSISTENT_SET\" : \"The operation set contains inconsistent operation: \" + repr(self.value) + \"\\n\"\\\n + \"Please use triplet (`str` name, `int` arity, `function` operation)\",\n \"INCONSISTENT_ARITY\" : \"The arity of operation \" + repr(self.value) +\" can not be negative.\", # Note: if you are doing some high math sh.t, then write your own CGP with blackjack and h..kers.\n }.get(self.error_code, \"Unknown error - \" + repr(self.error_code))\n return error_msg\n\n\nif __name__ == '__main__':\n CGP.PRINT_INFO = True\n cgp = CGP(DEFAULT_MATRIX_SIZE, DEFAULT_OPERATION_SET, DEFAULT_INPUT_DATA, DEFAULT_TRAINING_DATA)\n cgp.run(DEFAULT_POP_SIZE, DEFAULT_MUTATIONS, DEFAULT_MAX_GENERATIONS)\n print(cgp)\n","sub_path":"cgp_py3.py","file_name":"cgp_py3.py","file_ext":"py","file_size_in_byte":17659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"319811404","text":"total = 0\ncount = 0\naverage = None\n\nwhile True:\n line = input('Enter a number: ')\n if line == 'done':\n break\n try:\n total = total + int(line);\n count = count + 1;\n average = float(total) / float(count)\n except:\n print('Invalid input')\nprint('Done!')\nprint('Total: ', total)\nprint('Count: ', count)\nprint('Average: ', average)\n","sub_path":"py4e/Chapter5.Ex.1.py","file_name":"Chapter5.Ex.1.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"152711689","text":"import PAsearchSites\nimport PAutils\n\n\ndef search(results, lang, siteNum, searchData):\n url = PAsearchSites.getSearchSearchURL(siteNum).replace('www', 'content')\n req = PAutils.HTTPRequest(url + searchData.encoded)\n searchResults = req.json()['data']\n for searchResult in searchResults['videos']:\n title = searchResult['title']\n curID = PAutils.Encode(searchResult['slug'])\n\n score = 100 - Util.LevenshteinDistance(searchData.title.lower(), title.lower())\n\n if len(title) > 29:\n title = title[:32] + '...'\n\n results.Append(MetadataSearchResult(id='%s|%d' % (curID, siteNum), name='%s [%s]' % (title, PAsearchSites.getSearchSiteName(siteNum)), score=score, lang=lang))\n\n return results\n\n\ndef update(metadata, lang, siteNum, movieGenres, movieActors, art):\n metadata_id = str(metadata.id).split('|')\n sceneId = PAutils.Decode(metadata_id[0])\n basePath = PAsearchSites.getSearchBaseURL(siteNum).replace('www', 'content')\n sceneURL = basePath + '/api/content/v1/videos/' + sceneId\n req = PAutils.HTTPRequest(sceneURL)\n detailsPageElements = req.json()['data']['item']\n\n # Title\n metadata.title = detailsPageElements['title']\n\n # Summary\n try:\n raw = detailsPageElements['description']\n summary = HTML.ElementFromString(raw).xpath('//p')[0].text_content().strip()\n metadata.summary = summary\n except:\n pass\n\n # Studio\n metadata.studio = 'VR Bangers'\n\n # Tagline and Collection\n metadata.collections.clear()\n tagline = PAsearchSites.getSearchSiteName(siteNum)\n metadata.tagline = tagline\n metadata.collections.add(tagline)\n\n # Release Date\n date = detailsPageElements['publishedAt']\n date_object = datetime.fromtimestamp(date)\n metadata.originally_available_at = date_object\n metadata.year = metadata.originally_available_at.year\n\n # Genres\n movieGenres.clearGenres()\n for genreLink in detailsPageElements['categories']:\n genreName = genreLink['name']\n movieGenres.addGenre(genreName)\n\n # Actors\n movieActors.clearActors()\n for actorLink in detailsPageElements['models']:\n actorName = actorLink['title']\n actorPhotoURL = ''\n if 'featuredImage' in actorLink and 'permalink' in actorLink['featuredImage']:\n actorPhotoURL = basePath + actorLink['featuredImage']['permalink']\n movieActors.addActor(actorName, actorPhotoURL)\n\n # Posters\n maybeSlider = detailsPageElements['sliderImage']\n if maybeSlider:\n imgUrl = basePath + maybeSlider['permalink']\n art.append(imgUrl)\n\n maybePoster = detailsPageElements['poster']\n if maybePoster:\n imgUrl = basePath + maybePoster['permalink']\n art.append(imgUrl)\n\n for imgObj in detailsPageElements['galleryImages']:\n imgUrl = basePath + imgObj['permalink']\n art.append(imgUrl)\n\n Log('Artwork found: %d' % len(art))\n for idx, posterUrl in enumerate(art, 1):\n if not PAsearchSites.posterAlreadyExists(posterUrl, metadata):\n # Download image file for analysis\n try:\n image = PAutils.HTTPRequest(posterUrl)\n im = StringIO(image.content)\n resized_image = Image.open(im)\n width, height = resized_image.size\n # Add the image proxy items to the collection\n if width > 1 or height > width:\n # Item is a poster\n metadata.posters[posterUrl] = Proxy.Media(image.content, sort_order=idx)\n if width > 100 and width > height:\n # Item is an art item\n metadata.art[posterUrl] = Proxy.Media(image.content, sort_order=idx)\n except:\n pass\n\n return metadata\n","sub_path":"Contents/Code/siteVRBangers.py","file_name":"siteVRBangers.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"308235036","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\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.win32\\egg\\rbtools\\testing\\testcase.py\n# Compiled at: 2017-04-19 05:14:04\nfrom __future__ import unicode_literals\nimport re, unittest\n\nclass TestCase(unittest.TestCase):\n \"\"\"The base class for RBTools test cases.\n\n Unlike the standard unittest.TestCase, this allows the test case\n description (generally the first line of the docstring) to wrap multiple\n lines.\n \"\"\"\n ws_re = re.compile(b'\\\\s+')\n\n def shortDescription(self):\n \"\"\"Returns the description of the current test.\n\n This changes the default behavior to replace all newlines with spaces,\n allowing a test description to span lines. It should still be kept\n short, though.\n \"\"\"\n doc = self._testMethodDoc\n if doc is not None:\n doc = doc.split(b'\\n\\n', 1)[0]\n doc = self.ws_re.sub(b' ', doc).strip()\n return doc","sub_path":"pycfiles/RBTHSC-0.7.9.2.dev0-py2.7/testcase.py","file_name":"testcase.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"300994112","text":"from flask import Flask, render_template, request, redirect, session, flash\r\n\r\napp = Flask(__name__)\r\napp.secret_key = 'carniceria'\r\n\r\nclass NotaMateria:\r\n\tdef __init__(self, nome, media1, media2, mediafinal):\r\n\t\tself.nome = nome\r\n\t\tself.media1 = media1\r\n\t\tself.media2 = media2\r\n\t\tself.mediafinal = mediafinal\r\n\t\t\r\n\r\n#abortar essa classe\r\nclass Usuario:\r\n\tdef __init__(self, idd, nome, senha):\r\n\t\tself.idd = idd\r\n\t\tself.nome = nome\r\n\t\tself.senha = senha\r\n\r\nclass NovoUsuarioCadastrado:\r\n\tdef __init__(self, novonome, sobrenome, nomeusuario, novasenha, email, curso, anoformacao,\r\n\t\tmateria1, materia2, materia3, materia4, materia5, materia6, materia7, materia8):\r\n\t\tself.nomeNovoUsu = novonome\r\n\t\tself.sobrenomeNovoUsu = sobrenome\r\n\t\tself.nomeusuarioNovoUsu = nomeusuario\r\n\t\tself.senhaNovoUsu = novasenha\r\n\t\tself.emailNovoUsu = email\r\n\t\tself.cursoNovoUsu = curso\r\n\t\tself.anoformacaoNovoUsu = anoformacao\r\n\t\tself.materia1 = materia1\r\n\t\tself.materia2 = materia2\r\n\t\tself.materia3 = materia3\r\n\t\tself.materia4 = materia4\r\n\t\tself.materia5 = materia5\r\n\t\tself.materia6 = materia6\r\n\t\tself.materia7 = materia7\r\n\t\tself.materia8 = materia8\r\n\r\n\r\nNovoUsu1 = NovoUsuarioCadastrado('Lívia', 'Pimentel', 'livinha100canela', 'pacocandeaveia', 'liviafragoso.pi@gmail.com', 'AER', '2020',\r\n\t'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx')\r\nNovoUsu2 = NovoUsuarioCadastrado('Talita', 'Castro', 'talitamejeira', 'soudomej', 'talitacastro126@gmail.com', 'MEC', '2020', \r\n\t'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx')\r\nNovoUsu3 = NovoUsuarioCadastrado('Rafaella', 'Bambokian', 'bambokian', 'carniceria', 'rafaellabambokian@gmail.com', 'COMP', '2020',\r\n\t'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx')\r\n\r\nlistaUsuariosCadastrados = [NovoUsu1, NovoUsu2, NovoUsu3]\r\nlistaGambi = [NovoUsu1]\r\nlistamateriasUsuario = []\r\n \t\t\t\r\n# substituir por banco de dados\r\nusuarios = {NovoUsu1.nomeusuarioNovoUsu: NovoUsu1, NovoUsu2.nomeusuarioNovoUsu: NovoUsu2, NovoUsu3.nomeusuarioNovoUsu: NovoUsu3}\r\n\r\n# Renderização de páginas\r\n@app.route('/login')\r\ndef login():\r\n\treturn render_template('login.html')\r\n\r\n@app.route('/autenticar', methods=['POST',])\r\ndef autenticar():\r\n\tif request.form['usuario'] in usuarios:\r\n\t\tusuarioLogando = usuarios[request.form['usuario']]\r\n\t\tif usuarioLogando.senhaNovoUsu == request.form['senha']:\r\n\t\t\tsession['usuario_logado'] = usuarioLogando.nomeusuarioNovoUsu\r\n\t\t\t# gambiarra\r\n\t\t\tlistaGambi.append(usuarioLogando)\r\n\r\n\t\t\treturn redirect('/principal')\r\n\t\t\tflash(usuarioLogando.nomeNovoUsu + ' logado com sucesso.') #ta bugandoooo\r\n\t\telse:\r\n\t\t\tflash('Senha incorreta. Tente novamente!')\r\n\t\t\treturn redirect('/login')\r\n\telse:\r\n\t\tflash(request.form['usuario'] + ' não logado. Tente novamente!')\r\n\t\treturn redirect('/login')\r\n\r\n@app.route('/principal')\r\ndef principal():\r\n\tultimoEle = len(listaGambi)-1 #AAAA\r\n\treturn render_template('principal.html', nomeLogin = listaGambi[ultimoEle].nomeNovoUsu + ' ' + listaGambi[ultimoEle].sobrenomeNovoUsu,\r\n\t\tcursoLogin = listaGambi[ultimoEle].cursoNovoUsu, semestreLogin ='Turma ' + listaGambi[ultimoEle].anoformacaoNovoUsu)\r\n\r\n@app.route('/logout')\r\ndef logout():\r\n\tsession['usuario_logado'] = None\r\n\tflash('Nenhum usuário logado.')\r\n\treturn redirect('/login')\r\n\r\n@app.route('/cadastrousuario')\r\ndef cadastropessoais():\r\n\treturn render_template('cadastrousuario.html')\r\n\r\n@app.route('/cadastrandousuario', methods=['POST',])\r\ndef salvardadospessoais():\r\n\tprimeiroNome = request.form['first_name']\r\n\tultimoNome = request.form['last_name']\r\n\tnovoUsuario = request.form['usuario_valido']\r\n\tnovaSenha = request.form['password']\r\n\tnovoEmail = request.form['email_inline']\r\n\tcursoUsu = request.form['curso-select']\r\n\tanoformacaoUsu = request.form['anoformacao-select']\r\n\tmateria1 = request.form['nome-materia1']\r\n\tmateria2 = request.form['nome-materia2']\r\n\tmateria3 = request.form['nome-materia3']\r\n\tmateria4 = request.form['nome-materia4']\r\n\tmateria5 = request.form['nome-materia5']\r\n\tmateria6 = request.form['nome-materia6']\r\n\tmateria7 = request.form['nome-materia7']\r\n\tmateria8 = request.form['nome-materia8']\r\n\r\n\tNovoUsuInserido = NovoUsuarioCadastrado(primeiroNome, ultimoNome, novoUsuario, novaSenha, novoEmail, cursoUsu, anoformacaoUsu,\r\n\t\tmateria1, materia2, materia3, materia4, materia5, materia6, materia7, materia8)\r\n\tlistaUsuariosCadastrados.append(NovoUsuInserido)\r\n\tultimoEle = len(listaUsuariosCadastrados)-1\r\n\treturn render_template('principal.html', \r\n\t\tnomeLogin = listaUsuariosCadastrados[ultimoEle].nomeNovoUsu + ' ' + listaUsuariosCadastrados[ultimoEle].sobrenomeNovoUsu,\r\n\t\tcursoLogin = listaUsuariosCadastrados[ultimoEle].cursoNovoUsu, semestreLogin ='Turma ' + listaUsuariosCadastrados[ultimoEle].anoformacaoNovoUsu)\r\n\r\n\r\n@app.route('/notas')\r\ndef Notas():\r\n\tultimoElem = len(listaUsuariosCadastrados)-1 #AAAA\r\n\tlistam1 = NotaMateria(listaUsuariosCadastrados[ultimoElem].materia1, '0', '0', '0')\r\n\tlistamateriasUsuario.append(listam1)\r\n\tlistam2 = NotaMateria(listaUsuariosCadastrados[ultimoElem].materia2, '0', '0', '0')\r\n\tlistamateriasUsuario.append(listam2)\r\n\tlistam3 = NotaMateria(listaUsuariosCadastrados[ultimoElem].materia3, '0', '0', '0')\r\n\tlistamateriasUsuario.append(listam3)\r\n\tlistam4 = NotaMateria(listaUsuariosCadastrados[ultimoElem].materia4, '0', '0', '0')\r\n\tlistamateriasUsuario.append(listam4)\r\n\tlistam5 = NotaMateria(listaUsuariosCadastrados[ultimoElem].materia5, '0', '0', '0')\r\n\tlistamateriasUsuario.append(listam5)\r\n\tlistam6 = NotaMateria(listaUsuariosCadastrados[ultimoElem].materia6, '0', '0', '0')\r\n\tlistamateriasUsuario.append(listam6)\r\n\tlistam7 = NotaMateria(listaUsuariosCadastrados[ultimoElem].materia7, '0', '0', '0')\r\n\tlistamateriasUsuario.append(listam7)\r\n\tlistam8 = NotaMateria(listaUsuariosCadastrados[ultimoElem].materia8, '0', '0', '0')\r\n\tlistamateriasUsuario.append(listam8)\r\n\t#listamateriasUsuario = [listam1, listam2, listam3, listam4, listam5, listam6, listam7, listam8] #antiga listam\r\n\treturn render_template('notas.html', materias=listamateriasUsuario)\r\n\r\n@app.route('/formularionota')\r\ndef formularionota():\r\n\tif 'usuario_logado' not in session or session['usuario_logado'] == None:\r\n\t\treturn redirect('/login')\r\n\treturn render_template('formularionota.html', materias=listamateriasUsuario)\r\n\r\n@app.route('/adicionarnota', methods=['POST',])\r\ndef salvarnotas():\r\n# def salvar():\r\n\tmateriaNota = request.form['materia']\r\n\t# atividadeNota = request.form['atividade']\r\n\tvalorNota = request.form['valor']\r\n\tporcentagemNota = request.form['porcentagem']\r\n\t# listamx = NotaMateria(materiaNota, valorNota, valorNota, valorNota)\r\n\t# listam.append(listamx)\r\n\r\n\treturn redirect('/notas')\r\n\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n@app.route('/agenda')\r\ndef agenda():\r\n\treturn render_template('agenda.html')\r\n\r\n@app.route('/lembretes')\r\ndef lembretes():\r\n\treturn render_template('lembretes.html')\r\n\r\n\r\n\r\n# @app.route('/principal')\r\n# def principal():\r\n# \treturn render_template('principal.html', nomeLogin=usuarios[request.form['usuario']], \r\n# \t\tcursoLogin=usuarios[request.form['usuario']], semestreLogin=usuarios[request.form['usuario']])\r\n\r\napp.run(debug=True)","sub_path":"AlunITA v1/flask/alunita.py","file_name":"alunita.py","file_ext":"py","file_size_in_byte":7036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238840824","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on %(date)s\n\n@author: %(username)s\n\"\"\"\n\nimport datetime\nfrom pylab import *\nimport pandas as pd\nimport numpy as np\nimport sqlite3\n#import seaborn as sns\n#\n#\n#sns.palplot(sns.color_palette(\"Set1\", 4))\n#sns.set_style(\"white\")\n#sns.set_style(\"ticks\")\n\nwith sqlite3.connect('guam_groundwater.db') as conn:\n AnionResults = pd.read_sql_query('SELECT * FROM \"AnionResults\";', conn)\n CationResults = pd.read_sql_query('SELECT * FROM \"CationResults\";', conn)\n SampleNameMasterList = pd.read_sql_query('SELECT * FROM \"SampleNameMasterList\";', conn)\n GroundwaterSampleDetails = pd.read_sql_query('SELECT * FROM \"GroundwaterSampleDetails\";', conn)\n FieldTrip = pd.read_sql_query('SELECT * FROM \"FieldTrip\";', conn)\nconn.commit()\nconn.close()\n\n#GroundwaterSampleDetails = pd.read_pickle('GroundwaterSampleDetails')\n\nFieldTrip['EndFieldTrip'] = pd.to_datetime(FieldTrip['EndFieldTrip'])\nAnionResults = pd.merge(AnionResults, GroundwaterSampleDetails, how = 'left', on = 'SampleName')\nAnionResults = pd.merge(AnionResults, FieldTrip, how = 'left', on = 'idFieldTrip')\n\nCationResults = pd.merge(CationResults, GroundwaterSampleDetails, how = 'left', on = 'SampleName')\n\nDrip_Names = list(set(AnionResults.Site))\nDrip_Names.remove(nan)\n\ndef plot_all(series, x_val, y_val):\n for i in range(0,len(Drip_Names)):\n# sns.despine()\n fig2 = plt.figure(num=2, figsize = (11,8.5), facecolor='w', edgecolor='k')\n ax1 = fig2.add_subplot(111)\n plotname = Drip_Names[i]\n set_to_plot = series[series.Site == plotname]\n set_to_plot = set_to_plot.sort(x_val)\n ax1.plot(set_to_plot[x_val], set_to_plot[y_val],label = plotname, marker = 'o')\n xlabel(x_val)\n ylabel(y_val)\n legend(loc = 'best', numpoints = 1)\n \nplot_all(AnionResults, 'EndFieldTrip','Cl')","sub_path":"anions_plot.py","file_name":"anions_plot.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"123670904","text":"########################\n# Za oceno 6\n\ndef sosedov(x, y, mine):\n \"\"\"\n Vrni število sosedov polja s koordinatami `(x, y)` na katerih je mina.\n Polje samo ne šteje.\n\n Args:\n x (int): koordinata x\n y (int): koordinata y\n mine (set of tuple of int): koordinate min\n\n Returns:\n int: število sosedov\n \"\"\"\n vsi_sosedi = [(x + 1,y),(x - 1,y),(x,y+1),(x,y-1),(x-1,y+1),(x+1,y-1),(x+1,y+1),(x-1,y-1)]\n st_sosedov = 0\n for mina in mine:\n if mina in vsi_sosedi:\n st_sosedov += 1\n return st_sosedov\n\ndef najvec_sosedov(mine, s, v):\n \"\"\"\n Vrni koordinati polja z največ sosednjih min\n\n Args:\n mine (set of (int, int)): koordinate min\n s (int): širina polja\n v (int): višina polja\n\n Returns:\n tuple of int: koordinati polja\n\n \"\"\"\n najvec = 0\n koordinate = (0,0)\n for j in range(v):\n for i in range(s):\n if sosedov(i,j,mine) > najvec:\n najvec = sosedov(i,j,mine)\n koordinate = (i,j)\n return koordinate\n\ndef brez_sosedov(mine, s, v):\n \"\"\"\n Vrni množico koordinat polj brez min na sosednjih poljih. Polje samo lahko\n vsebuje mino.\n\n Args:\n mine (set of tuple of int): koordinate min\n s (int): širina polja\n v (int): višina polja\n\n Returns:\n set of tuple: polja brez min na sosednjih poljih\n \"\"\"\n mno = set()\n for j in range(v):\n for i in range(s):\n if sosedov(i,j,mine) == 0:\n mno.add((i,j))\n return mno\n\ndef koliko_min(mine,s,v,k):\n mno = set()\n for j in range(v):\n for i in range(s):\n if sosedov(i, j, mine) == k:\n mno.add((i, j))\n return mno\n\ndef po_sosedih(mine, s, v):\n \"\"\"\n Vrni slovar, katerega ključi so možna števila sosednjih polj z minami\n (torej števila od 0 do 8), vrednosti pa množice koordinat polj s toliko\n sosedami.\n\n Args:\n mine (set of tuple of int): koordinate min\n s (int): širina polja\n v (int): višina polja\n\n Returns:\n dict: (glej zgoraj)\n \"\"\"\n km = {i: set() for i in range(9)}\n for key in km.keys():\n km[key] = koliko_min(mine,s,v,key)\n return km\n\n########################\n# Za oceno 7\n\ndef dolzina_poti(pot):\n \"\"\"\n Vrni dolžino podane poti, vključno z vmesnimi polji.\n\n Args:\n pot (list of tuple): seznam koordinat polj\n\n Returns:\n int: dolžina poti\n \"\"\"\n c = 0\n for i in range(len(pot)-1):\n if pot[i][0] != pot[i+1][0]:\n c += abs(pot[i][0] - pot[i+1][0])\n elif pot[i][1] != pot[i+1][1]:\n c += abs(pot[i][1] - pot[i+1][1])\n return c\n\ndef varen_premik(x0, y0, x1, y1, mine):\n \"\"\"\n Vrni `True`, če je pomik z (x0, y0) and (x1, y1) varen, `False`, če ni.\n\n Args:\n x0 (int): koordinata x začetnega polja\n y0 (int): koordinata y začetnega polja\n x1 (int): koordinata x končnega polja\n y1 (int): koordinata y končnega polja\n mine (set of tuple of int): koordinate min\n\n Returns:\n bool: `True`, če je premik varen, `False`, če ni.\n \"\"\"\n dol = dolzina_poti([(x0,y0),(x1,y1)])\n vmesne_koordinate = []\n naj_enak = 0\n enak = 0\n c = 2\n if x0 != x1:\n naj_enak = min(x0,x1)\n elif y0 != y1:\n naj_enak = min(y0,y1)\n if x0 == x1:\n enak = x0\n c = 0\n elif y0 == y1:\n enak = y0\n c = 1\n for i in range(naj_enak,naj_enak+(dol-1)):\n if c == 0:\n vmesne_koordinate.append((enak,i+1))\n elif c == 1:\n vmesne_koordinate.append((i+1,enak))\n vmesne_koordinate.insert(0,(x0,y0))\n vmesne_koordinate.append((x1,y1))\n for koord in vmesne_koordinate:\n if koord in mine:\n return False\n return True\n\ndef varna_pot(pot, mine):\n \"\"\"\n Vrni `True`, če je podana pot varna, `False`, če ni.\n\n Args:\n pot (list of tuple of int): koordinate točk na poti (brez vmesnih točk)\n mine (set of tuple of int): koordinate min\n\n Returns:\n bool: `True`, če je pot varna, `False`, če ni.\n \"\"\"\n if len(pot) > 1:\n for i in range(len(pot)-1):\n if not varen_premik(pot[i][0], pot[i][1], pot[i + 1][0], pot[i + 1][1], mine):\n return False\n return True\n else:\n if len(pot) == 0:\n return True\n elif pot[0] in mine:\n return False\n return True\n\n########################\n# Za oceno 8\n\ndef polje_v_mine(polje):\n \"\"\"\n Vrni koordinate min v podanem polju.\n\n Niz polje opisuje polje tako, da so vodoravne \"vrstice\" polja ločene s\n presledki. Prosta polja so označena z znako `.`, mine z `X`.\n\n Args:\n polje (str): polje\n\n Returns:\n mine (set of tuple of int): koordinate min\n s (int): širina polja\n v (int): višina polja.\n \"\"\"\n se = []\n sezn = polje.split(\" \")\n sezn = ' '.join(sezn).split()\n s = len(sezn[0])\n v = len(sezn)\n i = -1\n j = -1\n for vrs in sezn:\n i+=1\n for znak in vrs:\n j+=1\n if znak == \"X\":\n se.append((j,i))\n j = -1\n return (set(se),s,v)\n\n\n","sub_path":"code/batch-1/dn7/M-71.py","file_name":"M-71.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"211916552","text":"\"\"\"\nCreates and compiles regexs and message + meaning dictionaries that can be used to search the log for problem\nmessages.\n\nCreated by Harvey Breaux for use with Cradlepoint Logs\n\"\"\"\n\nimport pandas as pd\nimport re\nimport os\nimport sys\nimport json\n\n\nclass ScanLog(object):\n \"\"\"\n The scan log object works with Cradlepoint log files and a xlsx or json database of log messages and their meanings.\n It uses regex to scan through logs to find problem messages from the database, and then it writes the messages and\n their meanings to an output file.\n \"\"\"\n\n # initialized allowed search categories\n ALLOWED_CATEGORIES = {'Connectivity+Modem', 'IPSec', 'Routing Protocols', 'NCP', 'NCM'}\n\n def __init__(self, input_file, output_file, log_database='log_messages.xlsx'):\n self.input_file = input_file\n self.output_file = output_file # unused in this implementation, scanning returns a list instead of a file\n self.log_database = log_database\n self.search_categories = self.ALLOWED_CATEGORIES.copy()\n\n def convert_xlsx(self):\n \"\"\"\n Converts an XLSX file to a python dictionary with keys and values that equate to messages and their meanings.\n For each \"message\" line a regex group trailer and header get applied. This is considered part of conversion. :)\n This function assumes that any unique identifiers in the log messages have been replaced with \".*\"\n \"\"\"\n\n # assemble path to xlsx\n dirname = os.path.dirname(__file__)\n xlsx = os.path.join(dirname, self.log_database)\n\n # make our search dictionary\n search_dictionary = {}\n\n # Loop through our search categories to open the correct sheets and load any messages in them into our df\n for category in self.search_categories:\n\n # Load a DataFrame from the specified categories sheet and only look at the message + meaning columns\n try:\n cols = [2, 3]\n df = pd.read_excel(xlsx, sheet_name=category, usecols=cols, encoding='UTF-8')\n\n # loop through rows and append them to the search_dictionary\n for index, row in df.iterrows():\n # write row to our search dictionary and appened a greedy match to end of line\n search_dictionary['(' + str(row['Message']).rstrip() + '.*$)'] = row['Meaning']\n\n except Exception as e:\n print(\"Exception occured while loading %s: %s\" % (category, e))\n continue\n\n return search_dictionary\n\n def convert_json(self):\n \"\"\"\n Converts an json file to a python dictionary with keys and values that equate to messages and their meanings.\n For each \"message\" line a regex group trailer and header get applied.\n This function assumes that any unique identifiers in the log messages have been replaced with \".*\"\n \"\"\"\n # assemble path to json\n dirname = os.path.dirname(__file__)\n json_file = os.path.join(dirname, self.log_database)\n\n with open(json_file, 'r') as j:\n json_dictionary = json.load(j)\n\n # make our search dictionary\n search_dictionary = {}\n\n # Loop through our search categories to load any messages in them into our search_dictionary\n for category in self.search_categories:\n category_messages = json_dictionary[category]\n for messages in category_messages:\n search_dictionary[messages.get(\"Message\")] = messages.get(\"Meaning\")\n\n return search_dictionary\n\n def search_log(self):\n \"\"\"\n search_log a log file for search terms and then write matches + their meanings to an output file\n dictionary: dictionary from convert_xlsx() or convert_json()\n \"\"\"\n # create search dictionary from our database\n dictionary = self._convert_db()\n\n problem_messages = []\n\n # open input and output files\n with open(self.input_file, 'r', encoding='UTF-8') as input_file:\n\n # search every line for a match\n for i, line in enumerate(input_file, 1):\n for key in dictionary.keys():\n # search line for a match\n match = re.search(key, line)\n\n # if there's a match, write the line, match, and the meaning to our output file\n if match:\n # 1/2/20 - removing print of whole log message because some messages are humongous\n problem_messages.append(\"Problem found on line %s: \" % i)\n problem_messages.append(\" %s\" % key)\n problem_messages.append(\"Common meaning of error: %s\" % dictionary[key] + '\\n')\n\n return problem_messages\n\n def _convert_db(self):\n \"\"\"Check log db type and return the correctly dictionary\"\"\"\n if self.log_database.endswith('.xlsx'):\n return self.convert_xlsx()\n\n elif self.log_database.endswith('.json'):\n return self.convert_json()\n\n def add_category(self, category):\n \"\"\"Add log categories to be searched for\"\"\"\n if category in self.ALLOWED_CATEGORIES:\n self.search_categories.add(category)\n else:\n raise Exception('The category %s does not exist. Allowed categories: %s' % (category, self.ALLOWED_CATEGORIES))\n\n def remove_category(self, category):\n \"\"\"Remove a log category to be searched for\"\"\"\n # Data validation, remove category if hasn't been already\n if category in self.search_categories:\n self.search_categories.remove(category)\n elif category not in self.search_categories:\n pass\n\n\nif __name__ == \"__main__\":\n ScanLog(sys.argv[1], sys.argv[2], 'log_messages.json').search_log()\n","sub_path":"scan_log.py","file_name":"scan_log.py","file_ext":"py","file_size_in_byte":5835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"271510840","text":"import copy\r\ndef is_inStraight(action, straight_member):\r\n\r\n flag = 0\r\n print(straight_member)\r\n if len(straight_member) != 0:\r\n for card in action[2]:\r\n if card in straight_member:\r\n flag = 1\r\n break\r\n return flag\r\n\r\ndef combine_handcards(handcards, rank, card_val):\r\n cards = {}\r\n cards[\"Single\"] = []\r\n cards[\"Pair\"] = []\r\n cards[\"Trips\"] = []\r\n cards[\"Bomb\"] = []\r\n bomb_info = {}\r\n\r\n handcards = sorted(handcards, key=lambda item: card_val[item[1]])\r\n start = 0\r\n for i in range(1, len(handcards) + 1):\r\n if i == len(handcards) or handcards[i][-1] != handcards[i - 1][-1]:\r\n if (i - start == 1):\r\n cards[\"Single\"].append(handcards[i - 1])\r\n elif (i - start == 2):\r\n cards[\"Pair\"].append(handcards[start:i])\r\n elif (i - start) == 3:\r\n cards[\"Trips\"].append(handcards[start:i])\r\n else:\r\n cards[\"Bomb\"].append(handcards[start:i])\r\n bomb_info[handcards[start][-1]] = i - start\r\n start = i\r\n\r\n rank = rank\r\n temp = []\r\n for i in handcards:\r\n if i[-1] != rank and i[-1] != 'B' and i[-1] != 'R':\r\n temp.append(i)\r\n for i in cards['Bomb']:\r\n if i[0][-1] != rank and i[0][-1] != 'B' and i[0][-1] != 'R':\r\n for j in i:\r\n temp.remove(j)\r\n cardre = [0] * 14\r\n for i in temp:\r\n if i[-1] == 'A':\r\n cardre[1] += 1\r\n if i[-1] == '2':\r\n cardre[2] += 1\r\n if i[-1] == '3':\r\n cardre[3] += 1\r\n if i[-1] == '4':\r\n cardre[4] += 1\r\n if i[-1] == '5':\r\n cardre[5] += 1\r\n if i[-1] == '6':\r\n cardre[6] += 1\r\n if i[-1] == '7':\r\n cardre[7] += 1\r\n if i[-1] == '8':\r\n cardre[8] += 1\r\n if i[-1] == '9':\r\n cardre[9] += 1\r\n if i[-1] == 'T':\r\n cardre[10] += 1\r\n if i[-1] == 'J':\r\n cardre[11] += 1\r\n if i[-1] == 'Q':\r\n cardre[12] += 1\r\n if i[-1] == 'K':\r\n cardre[13] += 1\r\n\r\n st = []\r\n minnum = 10\r\n mintwonum = 10\r\n\r\n for i in range(1, len(cardre) - 4):\r\n if 0 not in cardre[i:i + 5]:\r\n onenum = 0\r\n zeronum = 0\r\n twonum = 0\r\n for j in cardre[i:i + 5]:\r\n if j - 1 == 0:\r\n zeronum += 1\r\n if j - 1 == 1:\r\n onenum += 1\r\n if j - 1 == 2:\r\n twonum += 1\r\n\r\n if zeronum > onenum and minnum >= onenum:\r\n if len(st) == 0:\r\n if zeronum >= onenum + twonum:\r\n st.append(i)\r\n minnum = onenum\r\n mintwonum = twonum\r\n else:\r\n if minnum == onenum:\r\n if i == 1:\r\n if mintwonum > twonum:\r\n if zeronum >= onenum + twonum:\r\n st = []\r\n st.append(i)\r\n minnum = onenum\r\n mintwonum = twonum\r\n else:\r\n if mintwonum >= twonum:\r\n if zeronum >= onenum + twonum:\r\n st = []\r\n st.append(i)\r\n minnum = onenum\r\n mintwonum = twonum\r\n else:\r\n if zeronum >= onenum + twonum:\r\n st = []\r\n st.append(i)\r\n minnum = onenum\r\n mintwonum = twonum\r\n\r\n if 0 not in cardre[10:] and cardre[1] != 0:\r\n onenum = 0\r\n zeronum = 0\r\n twonum = 0\r\n for j in cardre[10:]:\r\n if j - 1 == 0:\r\n zeronum += 1\r\n if j - 1 == 1:\r\n onenum += 1\r\n if j - 1 == 2:\r\n twonum += 1\r\n if cardre[1] - 1 == 0:\r\n zeronum += 1\r\n if cardre[1] - 1 == 1:\r\n onenum += 1\r\n if cardre[1] - 1 == 2:\r\n twonum += 1\r\n\r\n if zeronum > onenum and minnum >= onenum:\r\n if len(st) == 0:\r\n\r\n if zeronum >= onenum + twonum:\r\n st.append(10)\r\n minnum = onenum\r\n mintwonum = twonum\r\n else:\r\n\r\n if minnum == onenum:\r\n if mintwonum >= twonum:\r\n if zeronum >= onenum + twonum:\r\n st = []\r\n st.append(10)\r\n minnum = onenum\r\n mintwonum = twonum\r\n else:\r\n if zeronum >= onenum + twonum:\r\n st = []\r\n st.append(10)\r\n minnum = onenum\r\n mintwonum = twonum\r\n\r\n tmp = []\r\n Flushtmp = []\r\n nowhandcards = []\r\n Straight = []\r\n if len(st) > 0:\r\n for i in range(st[0], st[0] + 5):\r\n if 1 < i < 10:\r\n Straight.append(str(i))\r\n if i % 13 == 1:\r\n Straight.append('A')\r\n if i == 10:\r\n Straight.append('T')\r\n if i == 11:\r\n Straight.append('J')\r\n if i == 12:\r\n Straight.append('Q')\r\n if i == 13:\r\n Straight.append('K')\r\n sttemp = []\r\n for i in range(4):\r\n sttemp.append([0] * 5)\r\n counttemp = 0\r\n\r\n colortemp = {\"S\": 0, \"H\": 1, \"C\": 2, \"D\": 3}\r\n rev_colortemp = {0: 'S', 1: 'H', 2: 'C', 3: 'D'}\r\n for i in range(0, len(handcards) - 1):\r\n if handcards[i][-1] in Straight:\r\n sttemp[colortemp[handcards[i][0]]][counttemp] += 1\r\n if handcards[i][-1] != handcards[i + 1][-1]:\r\n counttemp += 1\r\n\r\n StraightFlushflag = -1\r\n\r\n for i in range(4):\r\n if sttemp[i][0] > 0 and sttemp[i][1] > 0 and sttemp[i][2] > 0 and sttemp[i][3] > 0 and sttemp[i][4] > 0:\r\n StraightFlushflag = i\r\n if StraightFlushflag >= 0:\r\n for i in Straight:\r\n Flushtmp.append(rev_colortemp[StraightFlushflag] + i)\r\n for i in range(0, len(handcards)):\r\n if handcards[i] not in Flushtmp:\r\n nowhandcards.append(handcards[i])\r\n\r\n else:\r\n for i in range(0, len(handcards)):\r\n if handcards[i][-1] in Straight:\r\n tmp.append(handcards[i])\r\n Straight.remove(handcards[i][-1])\r\n else:\r\n nowhandcards.append(handcards[i])\r\n\r\n newcards = {}\r\n newcards[\"Single\"] = []\r\n newcards[\"Pair\"] = []\r\n newcards[\"Trips\"] = []\r\n newcards[\"Bomb\"] = []\r\n newcards['Straight'] = []\r\n newcards['StraightFlush'] = []\r\n\r\n if len(tmp) == 5:\r\n if tmp[-1][-1] == 'A' and tmp[-2][-1] == '5':\r\n tmpptmp = [tmp[-1]]\r\n for kkk in tmp[:-1]:\r\n tmpptmp.append(kkk)\r\n newcards['Straight'].append(tmpptmp)\r\n else:\r\n newcards['Straight'].append(tmp)\r\n if len(Flushtmp) == 5:\r\n newcards['StraightFlush'].append(Flushtmp)\r\n start = 0\r\n for i in range(1, len(nowhandcards) + 1):\r\n if i == len(nowhandcards) or nowhandcards[i][-1] != nowhandcards[i - 1][-1]:\r\n if (i - start == 1):\r\n newcards[\"Single\"].append(nowhandcards[i - 1])\r\n elif (i - start == 2):\r\n newcards[\"Pair\"].append(nowhandcards[start:i])\r\n elif (i - start) == 3:\r\n newcards[\"Trips\"].append(nowhandcards[start:i])\r\n else:\r\n newcards[\"Bomb\"].append(nowhandcards[start:i])\r\n start = i\r\n\r\n return newcards, bomb_info\r\n\r\ndef rest_cards(handcards,remaincards,rank):\r\n\r\n card_value_v2s = {0: \"A\", 1: \"2\", 2: \"3\", 3: \"4\", 4: \"5\", 5: \"6\", 6: \"7\", 7: \"8\", 8: \"9\", 9: \"T\", 10: \"J\",\r\n 11: \"Q\", 12: \"K\"}\r\n card_value_s2v = {\"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 11,\r\n \"Q\": 12, \"K\": 13, \"A\": 14, \"B\": 16, \"R\": 17}\r\n\r\n card_index = {\"A\": 0, \"2\": 1, \"3\": 2, \"4\": 3, \"5\": 4, \"6\": 5, \"7\": 6, \"8\": 7, \"9\": 8, \"T\": 9, \"J\": 10,\r\n \"Q\": 11, \"K\": 12, \"R\": 13, \"B\": 13}\r\n new_remaincards = {}\r\n for key,val in remaincards.items():\r\n new_remaincards[key] = copy.deepcopy(val)\r\n for card in handcards:\r\n card_type = str(card[0])\r\n x = card_index[card[1]]\r\n new_remaincards[card_type][x] = remaincards[card_type][x]-1\r\n\r\n rest_cards = []\r\n\r\n for key,value in new_remaincards.items():\r\n for i in range(0,len(value)):\r\n if value[i] ==0 :\r\n continue\r\n if i == 13 and key == 'S':\r\n val = 'B'\r\n elif i == 13 and key == 'H':\r\n val = 'R'\r\n else:\r\n val = card_value_v2s[i]\r\n if value[i]==1:\r\n rest_cards.append(key+val)\r\n elif value[i] == 2:\r\n rest_cards.append(key + val)\r\n rest_cards.append(key + val)\r\n if len(rest_cards)==0:\r\n print(rest_cards)\r\n card_value_s2v[str(rank)] = 15\r\n rest_cards = sorted(rest_cards,key = lambda item:card_value_s2v[item[1]])\r\n new_rest_cards = []\r\n tmp = []\r\n pre = rest_cards[0]\r\n tmp = [pre]\r\n for cards in rest_cards[1:]:\r\n if cards[1]!=pre[1]:\r\n new_rest_cards.append(tmp)\r\n tmp = [cards]\r\n pre = cards\r\n else:\r\n tmp.append(cards)\r\n new_rest_cards.append(tmp)\r\n return new_rest_cards\r\n\r\ndef choose_bomb( bomb_actionList, handcards, sorted_cards, bomb_info, rank_card, card_val):\r\n new_card_val = copy.deepcopy(card_val)\r\n new_card_val['A'] = 14\r\n new_card_val[rank_card[1]] = 15\r\n bomb_res = []\r\n\r\n new_card_val[\"JOKER\"] = 10000\r\n straight_member = []\r\n if len(sorted_cards[\"Straight\"]) != 0:\r\n straight_member += sorted_cards[\"Straight\"][0]\r\n if len(sorted_cards[\"StraightFlush\"]) != 0:\r\n straight_member += sorted_cards[\"StraightFlush\"][0]\r\n\r\n for action in bomb_actionList:\r\n\r\n index = action[0]\r\n action = action[1]\r\n if action[0] == \"Bomb\":\r\n if action[1]==rank_card[1]:\r\n prior = 0\r\n rank_card_num = 0\r\n for card in action[2]:\r\n if card == rank_card:\r\n rank_card_num += 1\r\n if rank_card_num == 1:\r\n prior = 3\r\n elif rank_card_num == 2:\r\n prior = 16\r\n l = len(action[2])\r\n bomb_res.append((index, new_card_val[action[1]] + (l - 4) * 16+prior))\r\n else:\r\n if action[1] in bomb_info:\r\n if bomb_info[action[1]] == len(action[2]) and rank_card not in action[2]:\r\n l = len(action[2])\r\n bomb_res.append((index, new_card_val[action[1]] + (l - 4) * 16))\r\n elif len(sorted_cards[\"Trips\"])==0:\r\n if len(action[2])>bomb_info[action[1]] and rank_card in action[2]:\r\n l = len(action[2])\r\n rank_card_num = len(action[2]) - bomb_info[action[1]]\r\n prior = 0\r\n if rank_card_num == 1:\r\n prior = 3\r\n elif rank_card_num == 2:\r\n prior = 16\r\n bomb_res.append((index, new_card_val[action[1]] + (l - 4) * 16+prior))\r\n\r\n elif action[1] not in bomb_info and rank_card in action[2]:\r\n if is_inStraight(action, straight_member):\r\n continue\r\n prior = 0\r\n rank_card_num = 0\r\n for card in action[2]:\r\n if card == rank_card:\r\n rank_card_num += 1\r\n if rank_card_num == 1:\r\n prior = 3\r\n elif rank_card_num == 2:\r\n prior = 16\r\n l = len(action[2])\r\n bomb_res.append((index, new_card_val[action[1]] + (l - 4) * 16 + prior))\r\n elif action[0] == \"StraightFlush\":\r\n if len(sorted_cards[\"StraightFlush\"]) > 0:\r\n curStraight = sorted_cards[\"StraightFlush\"][0][0][1]\r\n if curStraight == action[1] and rank_card not in action[2]:\r\n bomb_res.append((index, new_card_val[action[1]] + 32))\r\n\r\n if len(bomb_res) == 0:\r\n return -1\r\n else:\r\n bomb_res = sorted(bomb_res, key=lambda item: item[1])\r\n return bomb_res[0][0]\r\n\r\ndef one_hand(numofmy,numofnext,actionList,myPos,greaterPos,cards_num,restcards,card_val,rank_card):\r\n\r\n max_bomb = 0\r\n rank_card_num = 0\r\n for cards in restcards:\r\n if rank_card in cards:\r\n rank_card_num+=1\r\n for cards in restcards:\r\n if cards[0][1]==rank_card[1] and len(cards)>=4:\r\n l = len(cards)\r\n max_bomb = max(max_bomb,card_val[cards[0][1]]+(l-4)*14)\r\n elif cards[0][1]!=rank_card[1] and len(cards)>=4:\r\n l = len(cards)\r\n max_bomb = max(max_bomb, card_val[cards[0][1]] +(l+rank_card_num-4)*14)\r\n elif cards[0][1]!=rank_card[1] and len(cards)==3 and rank_card_num>=1:\r\n max_bomb = max(max_bomb, card_val[cards[0][1]] + (rank_card_num-1)*14)\r\n elif cards[0][1] != rank_card[1] and len(cards) == 2 and rank_card_num == 2:\r\n max_bomb = max(max_bomb, card_val[cards[0][1]])\r\n\r\n tag = 0\r\n if (myPos+2)%4 != greaterPos:\r\n for action in actionList[1:]:\r\n tag +=1\r\n if numofmy == len(action[2]):\r\n return tag\r\n else:\r\n for action in actionList[1:]:\r\n tag += 1\r\n if action[0]!=\"Bomb\" and action[0]!=\"StraightFlush\" and numofmy == len(action[2]):\r\n return tag\r\n if (action[0]==\"Bomb\" or action[0]==\"StraightFlush\") and numofmy == len(action[2]):\r\n\r\n if action[0]==\"Bomb\":\r\n l = len(action[2])\r\n cur_level = card_val[action[1]]+(l-4)*14\r\n else:\r\n cur_level = card_val[action[1]] + 14\r\n if numofnext>cards_num and cur_level>max_bomb:\r\n return 0\r\n else:\r\n return tag\r\n\r\n return -1\r\n\r\ndef get_remain_card_type(remaincards,remaincards_classbynum):\r\n card_re = {}\r\n Single_type = []\r\n Pair_type = []\r\n Trips_type = []\r\n Bomb_type = []\r\n ThreePair_type = []\r\n TwoTrips_type= []\r\n Straight_type= []\r\n StraightFlush_type =[]\r\n for i in range(len(remaincards_classbynum)):\r\n if remaincards_classbynum[i]>= 4:\r\n Single_type.append(1)\r\n Bomb_type.append(1)\r\n Pair_type.append(1)\r\n continue\r\n else:\r\n Bomb_type.append(0)\r\n if remaincards_classbynum[i]>= 3:\r\n Single_type.append(1)\r\n Trips_type.append(1)\r\n Pair_type.append(1)\r\n continue\r\n else:\r\n Trips_type.append(0)\r\n if remaincards_classbynum[i]>= 2:\r\n Single_type.append(1)\r\n Pair_type.append(1)\r\n continue\r\n else:\r\n Pair_type.append(0)\r\n if remaincards_classbynum[i]>= 1:\r\n Single_type.append(1)\r\n else:\r\n Single_type.append(0)\r\n #check Bomb\r\n Bomb_type =Bomb_type[:-2]\r\n if remaincards['H'][-1]==2 and remaincards['S'][-1]==2:\r\n Bomb_type.append(1)\r\n else:\r\n Bomb_type.append(0)\r\n card_re['Bomb'] =Bomb_type\r\n card_re['Pair'] = Pair_type\r\n card_re['Trips'] = Trips_type[:-2]\r\n card_re['Single'] = Single_type\r\n if len(Pair_type)>0:\r\n card_re['ThreeWithTwo'] = Trips_type[:-2]\r\n else:\r\n card_re['ThreeWithTwo'] = [0]*13\r\n for i in range(len(Pair_type)-3):\r\n if Pair_type[i]==1 and Pair_type[i+1]==1 and Pair_type[(i+2)%13] ==1:\r\n ThreePair_type.append(1)\r\n else:\r\n ThreePair_type.append(0)\r\n card_re['ThreePair'] =ThreePair_type\r\n for i in range(len(Trips_type)-2):\r\n if Trips_type[i]==1 and Trips_type[(i+1)%13]==1:\r\n TwoTrips_type.append(1)\r\n else:\r\n TwoTrips_type.append(0)\r\n card_re['TwoTrips'] =TwoTrips_type\r\n #check Straight\r\n for i in range(len(remaincards_classbynum) - 5):\r\n if remaincards_classbynum[i]>0 and remaincards_classbynum[i+1]>0 and remaincards_classbynum[i+2]>0 and remaincards_classbynum[i+3]>0 and remaincards_classbynum[(i+4)%13]>0 :\r\n Straight_type.append(0)\r\n else:\r\n Straight_type.append(1)\r\n card_re['Straight'] = Straight_type\r\n card_color = ['S','H','C','D']\r\n for i in range(len(Straight_type)):\r\n if Straight_type[i]==1:\r\n Straight_typeflag =0\r\n for j in card_color:\r\n if remaincards[j][i]>0 and remaincards[j][i+1]>0 and remaincards[j][i+2]>0 and remaincards[j][i+3]>0 and remaincards[j][(i+4)%13]>0:\r\n StraightFlush_type.append(1)\r\n Straight_typeflag =1\r\n break\r\n if Straight_typeflag ==0:\r\n StraightFlush_type.append(0)\r\n else:\r\n StraightFlush_type.append(0)\r\n return card_re\r\n\r\ndef cal_bomb_num(sorted_cards,handcards,rank_card):\r\n cur_Bomb_num = len(sorted_cards[\"Bomb\"]) + len(sorted_cards[\"StraightFlush\"])\r\n rank_card_num = 0\r\n for card in handcards:\r\n if card == rank_card:\r\n rank_card_num += 1\r\n\r\n if rank_card_num == 1:\r\n for trip in sorted_cards[\"Trips\"]:\r\n if rank_card not in trip:\r\n cur_Bomb_num += 1\r\n break\r\n if rank_card_num == 2:\r\n if len(sorted_cards[\"Trips\"])==1 and rank_card not in sorted_cards[\"Trips\"][0]:\r\n cur_Bomb_num += 1\r\n elif len(sorted_cards[\"Trips\"])==2 and rank_card in sorted_cards[\"Trips\"][1]:\r\n cur_Bomb_num += 1\r\n elif len(sorted_cards[\"Trips\"])==2 and rank_card not in sorted_cards[\"Trips\"][1]:\r\n cur_Bomb_num += 2\r\n elif len(sorted_cards[\"Trips\"])>=2:\r\n cur_Bomb_num += 2\r\n\r\n for bomb in sorted_cards[\"Bomb\"]:\r\n if rank_card in bomb:\r\n cur_Bomb_num -= 1\r\n\r\n return cur_Bomb_num\r\n\r\ndef combine_ThreePair(handcards,rank_card,sorted_cards,card_val):\r\n card_origin = {\"A\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 11,\r\n \"Q\": 12, \"K\": 13}\r\n card_val['A'] = 1\r\n card_val[rank_card[1]] = card_origin[rank_card[1]]\r\n Pairs = {}\r\n Trips = {}\r\n for pair in sorted_cards[\"Pair\"]:\r\n Pairs[card_val[pair[0][1]]] = pair\r\n for trips in sorted_cards[\"Trips\"]:\r\n Trips[card_val[trips[0][1]]] = trips\r\n\r\n for key,val in card_origin.items():\r\n if val >12 or val == 1:\r\n continue\r\n\r\n\r\ndef caldistance2(trips_actionlist,pair_actionlist,rank):\r\n rank_card = 'H' + str(rank)\r\n card_value_s2v = {\"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 11,\r\n \"Q\": 12, \"K\": 13, \"A\": 14, \"B\": 16, \"R\": 17}\r\n card_value_s2v[rank_card[-1]] = 15\r\n return card_value_s2v[trips_actionlist[0][0]],card_value_s2v[trips_actionlist[0][0]] - card_value_s2v[pair_actionlist[1][0]],card_value_s2v[pair_actionlist[1][0]],card_value_s2v[pair_actionlist[0][0]]\r\n\r\ndef caldistance3(trips_actionlist,pair_actionlist,rank):\r\n rank_card = 'H' + str(rank)\r\n card_value_s2v = {\"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 11,\r\n \"Q\": 12, \"K\": 13, \"A\": 14, \"B\": 16, \"R\": 17}\r\n card_value_s2v[rank_card[-1]] = 15\r\n return card_value_s2v[pair_actionlist[0][0]],card_value_s2v[trips_actionlist[0][0]] - card_value_s2v[pair_actionlist[0][0]],card_value_s2v[trips_actionlist[1][0]],card_value_s2v[trips_actionlist[0][0]]\r\n\r\ndef getindex(tag, actList, actionList):\r\n myaction = tag\r\n mynumber = actList[0][0]\r\n mycard = \"None\"\r\n if myaction == \"Single\":\r\n mycard = [actList[0][1]]\r\n else:\r\n mycard = actList[0][1]\r\n my_act = []\r\n my_act.append(myaction)\r\n my_act.append(mynumber)\r\n my_act.append(mycard)\r\n print(my_act)\r\n if my_act in actionList:\r\n return actionList.index(my_act)\r\n else:\r\n return 0\r\n\r\ndef getindex1(tag, actList, actionList):\r\n myaction = tag\r\n mynumber = actList[1][0]\r\n mycard = \"None\"\r\n if myaction == \"Single\":\r\n mycard = [actList[1][1]]\r\n else:\r\n mycard = actList[1][1]\r\n my_act = []\r\n my_act.append(myaction)\r\n my_act.append(mynumber)\r\n my_act.append(mycard)\r\n print(my_act)\r\n if my_act in actionList:\r\n return actionList.index(my_act)\r\n else:\r\n return 0\r\n\r\ndef rankfour(twotrips_actionlist,threepair_actionlist,actionList,cur2,cur3):#cur2是连对,cur3是连三\r\n\r\n card_value_s2v2 = {\"A\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 11,\r\n \"Q\": 12, \"K\": 13, \"B\": 16, \"R\": 17}\r\n minvalue = [100,100]\r\n\r\n if len(threepair_actionlist):\r\n minvalue[0] = card_value_s2v2[threepair_actionlist[0][0]]\r\n\r\n if len(twotrips_actionlist):\r\n minvalue[1] = card_value_s2v2[twotrips_actionlist[0][0]]\r\n\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0 and minvalue[0]<=cur2:\r\n return getindex(\"ThreePair\",threepair_actionlist,actionList)\r\n\r\n if minpos == 1 and minvalue[1]<=cur3:\r\n return getindex(\"TwoTrips\",twotrips_actionlist,actionList)\r\n\r\ndef rankthree(single_actionlist,pair_actionlist,trips_actionlist,threetwo_actionlist,actionList,numofnext,rank,cur1,cur4,cur5,cur6,curp2):\r\n card_value_s2v = {\"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 11,\r\n \"Q\": 12, \"K\": 13, \"A\": 14, \"B\": 16, \"R\": 17}\r\n card_value_s2v[rank] = 15\r\n if len(pair_actionlist) == len(trips_actionlist) or (\r\n len(pair_actionlist) >= 2 and len(trips_actionlist) >= 2):\r\n if card_value_s2v[threetwo_actionlist[0][0]] < cur4 or numofnext==1:\r\n return getindex(\"ThreeWithTwo\",threetwo_actionlist,actionList)\r\n elif len(single_actionlist) and card_value_s2v[single_actionlist[0][0]] < cur1 and numofnext==5:\r\n return getindex(\"Single\",single_actionlist,actionList)\r\n else:\r\n minvalue = [100, 100]\r\n if len(threetwo_actionlist):\r\n minvalue[0] = card_value_s2v[threetwo_actionlist[0][0]]\r\n\r\n if len(single_actionlist):\r\n minvalue[1] = card_value_s2v[single_actionlist[0][0]]\r\n\r\n if len(threetwo_actionlist)>1 and len(single_actionlist) == 1:#三带二有压\r\n minvalue[0] = minvalue[0] + 1\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0 :\r\n return getindex(\"ThreeWithTwo\", threetwo_actionlist, actionList)\r\n if minpos == 1 :\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n elif len(threetwo_actionlist) == 1 and len(single_actionlist)>1:#单张有压\r\n minvalue[1] = minvalue[1] + 1\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0 :\r\n return getindex(\"ThreeWithTwo\", threetwo_actionlist, actionList)\r\n if minpos == 1 :\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n else:\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0:\r\n return getindex(\"ThreeWithTwo\", threetwo_actionlist, actionList)\r\n if minpos == 1:\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n\r\n else:\r\n len3 = len(pair_actionlist)\r\n len4 = len(trips_actionlist)\r\n\r\n if numofnext == 3 and len(pair_actionlist) and card_value_s2v[pair_actionlist[0][0]] < cur4:\r\n return getindex(\"Pair\",pair_actionlist,actionList)\r\n if numofnext == 2 and len(trips_actionlist) and card_value_s2v[trips_actionlist[0][0]] < cur5:\r\n return getindex(\"ThreeWithTwo\",threetwo_actionlist,actionList)\r\n\r\n if len3 > len4:\r\n mint,_,minp2,minp1= caldistance2(trips_actionlist,pair_actionlist,rank)\r\n if minp2 <= cur5 and mint <= cur6:\r\n if minp1 > mint:\r\n return getindex(\"ThreeWithTwo\",threetwo_actionlist,actionList)\r\n else:return getindex1(\"Pair\",pair_actionlist,actionList)\r\n elif minp2 > cur5 and mint <= cur6:\r\n if minp2 > cur5 + curp2:\r\n if minp1 < cur5:\r\n return getindex(\"Pair\",pair_actionlist,actionList)\r\n else:\r\n return getindex(\"ThreeWithTwo\",threetwo_actionlist,actionList)\r\n else:\r\n return getindex(\"ThreeWithTwo\",threetwo_actionlist,actionList)\r\n elif minp2 <= cur5 and mint > cur6:\r\n return getindex(\"Pair\",pair_actionlist,actionList)\r\n else:\r\n return getindex(\"ThreeWithTwo\",threetwo_actionlist,actionList)\r\n\r\n else:\r\n minp, _, mint2, mint1 = caldistance3(trips_actionlist, pair_actionlist, rank)\r\n if minp <= cur5:\r\n return getindex(\"ThreeWithTwo\",threetwo_actionlist,actionList)\r\n elif mint1 < cur6 and minp > cur5:\r\n return getindex(\"Trips\",trips_actionlist,actionList)\r\n else:\r\n if minp >= cur5 + curp2:\r\n return getindex(\"Trips\",trips_actionlist,actionList)\r\n else:\r\n return getindex(\"ThreeWithTwo\",threetwo_actionlist,actionList)\r\n\r\n\r\ndef ranktwo(hand_cards,single_actionlist,pair_actionlist,trips_actionlist,actionList,numofnext,rank,max_val):\r\n card_value_s2v = {\"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 11,\r\n \"Q\": 12, \"K\": 13, \"A\": 14, \"B\": 16, \"R\": 17}\r\n card_value_s2v[rank] = 15\r\n rank_card = 'H'+rank\r\n if len(single_actionlist):\r\n if numofnext == 1:\r\n return getindex(\"Pair\", pair_actionlist, actionList)\r\n if numofnext == 2:\r\n return getindex(\"Single\",single_actionlist,actionList)\r\n else:\r\n minvalue = [100, 100]\r\n if len(pair_actionlist):\r\n minvalue[0] = card_value_s2v[pair_actionlist[0][0]]\r\n\r\n if len(single_actionlist):\r\n minvalue[1] = card_value_s2v[single_actionlist[0][0]]\r\n\r\n if len(pair_actionlist) > 1 and len(single_actionlist) == 1:\r\n minvalue[0] = minvalue[0] + 1\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0:\r\n return getindex(\"Pair\", pair_actionlist, actionList)\r\n if minpos == 1:\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n elif len(pair_actionlist) == 1 and len(single_actionlist) > 1:\r\n minvalue[1] = minvalue[1] + 1\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0:\r\n return getindex(\"Pair\", pair_actionlist, actionList)\r\n if minpos == 1:\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n else:\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0:\r\n return getindex(\"Pair\", pair_actionlist, actionList)\r\n if minpos == 1:\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n else:\r\n return getindex(\"Pair\", pair_actionlist, actionList)\r\n\r\n\r\ndef rankone(single_actionlist,trips_actionlist,actionList,numofnext,rank):\r\n card_value_s2v = {\"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 11,\r\n \"Q\": 12, \"K\": 13, \"A\": 14, \"B\": 16, \"R\": 17}\r\n card_value_s2v[rank] = 15\r\n if len(single_actionlist):\r\n if numofnext == 1:\r\n return getindex(\"Trips\", trips_actionlist, actionList)\r\n if numofnext == 3:\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n else:\r\n minvalue = [100, 100]\r\n if len(trips_actionlist):\r\n minvalue[0] = card_value_s2v[trips_actionlist[0][0]]\r\n\r\n if len(single_actionlist):\r\n minvalue[1] = card_value_s2v[single_actionlist[0][0]]\r\n\r\n if len(trips_actionlist) > 1 and len(single_actionlist) == 1: # 三带二有压\r\n minvalue[0] = minvalue[0] + 1\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0:\r\n return getindex(\"Trips\", trips_actionlist, actionList)\r\n if minpos == 1:\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n elif len(trips_actionlist) == 1 and len(single_actionlist) > 1: # 单张有压\r\n minvalue[1] = minvalue[1] + 1\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0:\r\n return getindex(\"Trips\", trips_actionlist, actionList)\r\n if minpos == 1:\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n else:\r\n minpos = minvalue.index(min(minvalue))\r\n if minpos == 0:\r\n return getindex(\"Trips\", trips_actionlist, actionList)\r\n if minpos == 1:\r\n return getindex(\"Single\", single_actionlist, actionList)\r\n else:\r\n return getindex(\"Trips\", trips_actionlist, actionList)","sub_path":"第一届掼蛋程序/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":30447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"269415150","text":"# ----------------------------------------------------------------------------#\n# Imports\n# ----------------------------------------------------------------------------#\n\nimport dateutil.parser\nimport babel\nfrom flask import Flask, render_template, request, flash, redirect, url_for\nfrom flask_moment import Moment\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nimport logging\nfrom logging import Formatter, FileHandler\nfrom forms import *\nfrom common import GENRES\nimport psycopg2\nimport re\n# ----------------------------------------------------------------------------#\n# App Config.\n# ----------------------------------------------------------------------------#\n\napp = Flask(__name__)\nmoment = Moment(app)\napp.config.from_object('config')\ndb = SQLAlchemy(app)\n\nmigrate = Migrate(app, db)\n\n\n# ----------------------------------------------------------------------------#\n# Models.\n# ----------------------------------------------------------------------------#\n\n\nclass Venue(db.Model):\n __tablename__ = 'Venue'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n city = db.Column(db.String(120))\n state = db.Column(db.String(120))\n address = db.Column(db.String(120))\n phone = db.Column(db.String(120))\n image_link = db.Column(db.String(500))\n facebook_link = db.Column(db.String(120))\n genres = db.relationship('VGenres', backref=\"venue\")\n website = db.Column(db.String(500))\n seeking_talent = db.Column(db.BOOLEAN)\n seeking_description = db.Column(db.String(500))\n shows = db.relationship(\"Show\", backref=\"venue\")\n\n\nclass VGenres(db.Model):\n __tablename__ = 'VGenres'\n\n genre = db.Column(db.Enum(GENRES), primary_key=True)\n vid = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False, primary_key=True)\n\nclass AGenres(db.Model):\n __tablename__ = 'AGenres'\n\n agenre = db.Column(db.Enum(GENRES), primary_key=True)\n aid = db.Column(db.Integer, db.ForeignKey('Artist.id'), nullable=False, primary_key=True)\nclass Show(db.Model):\n __tablename__ = 'Show'\n\n id = db.Column(db.Integer, primary_key=True)\n vid = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False)\n aid = db.Column(db.Integer, db.ForeignKey('Artist.id'), nullable=False)\n start_time = db.Column(db.TIMESTAMP, nullable=False)\n\nclass Artist(db.Model):\n __tablename__ = 'Artist'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n city = db.Column(db.String(120))\n state = db.Column(db.String(120))\n phone = db.Column(db.String(120))\n image_link = db.Column(db.String(500))\n facebook_link = db.Column(db.String(120))\n website = db.Column(db.String(500))\n seeking_venue = db.Column(db.BOOLEAN)\n seeking_description = db.Column(db.String(500))\n shows = db.relationship(\"Show\", backref=\"artist\")\n genres = db.relationship(\"AGenres\", backref=\"artist\")\n\n# ----------------------------------------------------------------------------#\n# Filters.\n# ----------------------------------------------------------------------------#\n\ndef format_datetime(value, format_type='medium'):\n date = dateutil.parser.parse(value)\n if format_type == 'full':\n format_type = \"EEEE MMMM, d, y 'at' h:mma\"\n elif format_type == 'medium':\n format_type = \"EE MM, dd, y h:mma\"\n return babel.dates.format_datetime(date, format_type)\n\n\napp.jinja_env.filters['datetime'] = format_datetime\n\n\n# ----------------------------------------------------------------------------#\n# Controllers.\n# ----------------------------------------------------------------------------#\n\n@app.route('/')\ndef index():\n return render_template('pages/home.html')\n\n\n# Venues\n# ----------------------------------------------------------------\ndef get_idx(data, city, _state):\n for i in range(0, len(data)):\n if data[i].get('city') == city and data[i].get('state') == _state:\n return i\n\n return -1\n\n@app.route('/venues')\ndef venues():\n v = Venue.query.all()\n data = []\n for i in range(0, len(v)):\n idx = get_idx(data, v[i].city, v[i].state)\n v_dict = {\n \"id\": v[i].id,\n \"name\": v[i].name,\n \"num_upcoming_shows\": len(v[i].shows)\n }\n if idx != -1:\n data[idx].get('venues').append(v_dict)\n else:\n data.append({\n \"city\": v[i].city,\n \"state\": v[i].state,\n \"venues\": [v_dict]\n })\n return render_template('pages/venues.html', areas=data)\n\n\n@app.route('/venues/search', methods=['POST'])\ndef search_venues():\n # seach for Hop should return \"The Musical Hop\".\n # search for \"Music\" should return \"The Musical Hop\" and \"Park Square Live Music & Coffee\"\n term = request.form.get('search_term')\n raw = Venue.query.filter(Venue.name.ilike(\"%\" + term + \"%\")).all()\n data = list(map(lambda v: {\n \"id\": v.id,\n \"name\": v.name,\n \"num_upcoming_shows\": len(list(filter(filter_upcoming_shows, v.shows)))\n }, raw))\n response = {\n \"count\": len(data),\n \"data\": data\n }\n return render_template('pages/search_venues.html', results=response,\n search_term=request.form.get('search_term', ''))\n\n\ndef filter_past_shows(show):\n if(show.start_time > datetime.today()):\n return False\n else:\n return True\ndef filter_upcoming_shows(show):\n if(show.start_time < datetime.today()):\n return False\n else:\n return True\ndef map_show(show):\n return {\n \"artist_id\": show.aid,\n \"artist_name\": show.artist.name,\n \"artist_image_link\": show.artist.image_link,\n \"start_time\": str(show.start_time)\n }\ndef map_show_artist(show):\n return {\n \"venue_id\": show.vid,\n \"venue_name\": show.venue.name,\n \"venue_image_link\": show.venue.image_link,\n \"start_time\": str(show.start_time)\n }\n@app.route('/venues/<int:venue_id>')\ndef show_venue(venue_id):\n v = Venue.query.get(venue_id)\n if v is None:\n flash(\"Can't find such venue!\")\n return redirect(\"/\")\n else:\n past_shows = list(filter(filter_past_shows, v.shows))\n upcoming_shows = list(filter(filter_upcoming_shows, v.shows))\n data = {\n \"id\": v.id,\n \"past_shows\": list(map(map_show, past_shows)),\n \"upcoming_shows\": list(map(map_show, upcoming_shows)),\n \"past_shows_count\": len(past_shows),\n \"upcoming_shows_count\": len(upcoming_shows),\n \"name\": v.name,\n \"city\": v.city,\n \"state\": v.state,\n \"address\": v.address,\n \"phone\": v.phone,\n \"image_link\": v.image_link,\n \"facebook_link\": v.facebook_link,\n \"genres\": map(lambda x: x.genre.value, VGenres.query.filter_by(vid=venue_id).all()),\n \"website\": v.website,\n \"seeking_talent\": v.seeking_talent,\n \"seeking_description\": v.seeking_description\n }\n return render_template('pages/show_venue.html', venue=data)\n\n\n# Create Venue\n# ----------------------------------------------------------------\n\n@app.route('/venues/create', methods=['GET'])\ndef create_venue_form():\n form = VenueForm()\n return render_template('forms/new_venue.html', form=form)\n\n\n@app.route('/venues/create', methods=['POST'])\ndef create_venue_submission():\n form = VenueForm(request.form)\n get = request.form.get\n\n if not form.validate():\n flash(form.errors)\n return render_template('forms/new_venue.html', form=form)\n venue = Venue(\n address=get(\"address\"),\n name=get(\"name\"),\n city=get(\"city\"),\n state=get(\"state\"),\n phone=get(\"phone\"),\n facebook_link=get(\"facebook_link\"),\n image_link=get(\"image_link\"),\n website=get(\"website\"),\n seeking_description=get(\"seeking_description\"),\n seeking_talent=get(\"seeking_talent\") == 'YES'\n )\n db.session.add(venue)\n db.session.commit()\n _genres = request.form.getlist(\"genres\")\n for i in range(0, len(_genres)):\n _genre = VGenres(genre=_genres[i], vid=venue.id)\n db.session.add(_genre)\n db.session.commit()\n # on successful db insert, flash success\n flash('Venue ' + request.form['name'] + ' was successfully listed!')\n return redirect(\"/venues/\" + str(venue.id))\n\n\n@app.route('/venues/<venue_id>', methods=['DELETE'])\ndef delete_venue(venue_id):\n # SQLAlchemy ORM to delete a record. Handle cases where the session commit could fail.\n try:\n v = Venue.query.get(int(venue_id))\n name = v.name\n _genres = VGenres.query.filter_by(vid=venue_id).all()\n for i in range(0, len(_genres)):\n db.session.delete(_genres[i])\n db.session.delete(v)\n db.session.commit()\n flash(\"Deleted \" + name + \" Successfully\")\n except Exception as e:\n flash(str(e))\n finally:\n return redirect('/')\n # BONUS CHALLENGE: Implement a button to delete a Venue on a Venue Page, have it so that\n # clicking that button delete it from the db then redirect the user to the homepage\n\n\n# Artists\n# ----------------------------------------------------------------\n@app.route('/artists')\ndef artists():\n _artists = Artist.query.all()\n data = list(map(lambda artist: {\n \"id\": artist.id,\n \"name\": artist.name\n }, _artists))\n\n return render_template('pages/artists.html', artists=data)\n\n\n@app.route('/artists/search', methods=['POST'])\ndef search_artists():\n term = request.form.get('search_term')\n raw = Artist.query.filter(Artist.name.ilike(\"%\" + term + \"%\")).all()\n data = list(map(lambda a: {\n \"id\": a.id,\n \"name\": a.name,\n \"num_upcoming_shows\": len(list(filter(filter_upcoming_shows, a.shows)))\n }, raw))\n response = {\n \"count\": len(data),\n \"data\": data\n }\n return render_template('pages/search_artists.html', results=response,\n search_term=request.form.get('search_term', ''))\n\n\n@app.route('/artists/<int:artist_id>')\ndef show_artist(artist_id):\n # shows the venue page with the given venue_id\n a = Artist.query.get(artist_id)\n if a is None:\n flash(\"Can't find such Artist!\")\n return redirect(\"/\")\n else:\n past = list(filter(filter_past_shows, a.shows))\n upcoming = list(filter(filter_upcoming_shows, a.shows))\n data = {\n \"id\": a.id,\n \"past_shows\": list(map(map_show_artist, past)),\n \"upcoming_shows\": list(map(map_show_artist, upcoming)),\n \"past_shows_count\": len(past),\n \"upcoming_shows_count\": len(upcoming),\n \"name\": a.name,\n \"city\": a.city,\n \"state\": a.state,\n \"phone\": a.phone,\n \"image_link\": a.image_link,\n \"facebook_link\": a.facebook_link,\n \"genres\": map(lambda x: x.agenre.value, AGenres.query.filter_by(aid=artist_id).all()),\n \"website\": a.website,\n \"seeking_venue\": a.seeking_venue,\n \"seeking_description\": a.seeking_description,\n }\n return render_template('pages/show_artist.html', artist=data)\n\n\n# Update\n# ----------------------------------------------------------------\n@app.route('/artists/<int:artist_id>/edit', methods=['GET'])\ndef edit_artist(artist_id):\n form = EditArtistForm()\n a = Artist.query.get(artist_id)\n artist = {\n \"id\": a.id,\n \"name\": a.name,\n \"genres\": list(map(lambda x: x.agenre.value, AGenres.query.filter_by(aid=artist_id).all())),\n \"city\": a.city,\n \"state\": a.state,\n \"phone\": a.phone,\n \"website\": a.website,\n \"facebook_link\": a.facebook_link,\n \"seeking_venue\": a.seeking_venue,\n \"seeking_description\": a.seeking_description,\n \"image_link\": a.image_link\n }\n return render_template('forms/edit_artist.html', form=form, artist=artist)\n\n\n@app.route('/artists/<int:artist_id>/edit', methods=['POST'])\ndef edit_artist_submission(artist_id):\n # called upon submitting the new artist listing form\n form = EditArtistForm(request.form)\n get = request.form.get\n\n if not form.validate():\n flash(form.errors)\n return redirect('/artists/' + str(artist_id) + '/edit')\n\n is_seeking = get(\"seeking_venue\") == 'YES'\n artist = Artist.query.get(artist_id)\n artist.city = get('city')\n artist.state = get('state')\n artist.phone = get('phone')\n artist.facebook_link = get('facebook_link')\n artist.image_link = get('image_link')\n artist.website = get('website')\n artist.seeking_venue = is_seeking\n artist.seeking_description = get('seeking_description')\n # db.session.commit()\n _old_genres = list(map(lambda x: x.agenre.name, artist.genres))\n # delete all _old_genres...\n for i in range(0, len(artist.genres)):\n db.session.delete(artist.genres[i])\n\n db.session.commit()\n # add new genre..\n _genres = request.form.getlist(\"genres\")\n for i in range(0, len(_genres)):\n _genre = AGenres(agenre=_genres[i], aid=artist_id)\n db.session.add(_genre)\n db.session.commit()\n\n\n # on successful db insert, flash success\n flash('Artist ' + artist.name + ' was successfully Updated!')\n return redirect(url_for('show_artist', artist_id=artist_id))\n\n\n@app.route('/venues/<int:venue_id>/edit', methods=['GET'])\ndef edit_venue(venue_id):\n form = VenueForm()\n v = Venue.query.get(venue_id)\n venue = {\n \"id\": venue_id,\n \"name\": v.name,\n \"genres\": list(map(lambda x: x.genre.value, VGenres.query.filter_by(vid=venue_id).all())),\n \"address\": v.address,\n \"city\": v.city,\n \"state\": v.state,\n \"phone\": v.phone,\n \"website\": v.website,\n \"facebook_link\": v.facebook_link,\n \"seeking_talent\": v.seeking_talent,\n \"seeking_description\": v.seeking_description,\n \"image_link\": v.image_link\n }\n return render_template('forms/edit_venue.html', form=form, venue=venue)\n\n\n@app.route('/venues/<int:venue_id>/edit', methods=['POST'])\ndef edit_venue_submission(venue_id):\n form = EditVenueForm(request.form)\n get = request.form.get\n\n if not form.validate():\n flash(form.errors)\n return redirect('/venues/' + str(venue_id) + '/edit')\n\n try:\n is_seeking = get(\"seeking_talent\") == 'YES'\n venue = Venue.query.get(venue_id)\n venue.city = get('city')\n venue.state = get('state')\n venue.phone = get('phone')\n venue.facebook_link = get('facebook_link')\n venue.image_link = get('image_link')\n venue.website = get('website')\n venue.seeking_talent = is_seeking\n venue.seeking_description = get('seeking_description')\n _old_genres = list(map(lambda x: x.genre.name, venue.genres))\n # delete all _old_genres...\n for i in range(0, len(venue.genres)):\n db.session.delete(venue.genres[i])\n db.session.commit()\n\n # add new genre..\n _genres = request.form.getlist(\"genres\")\n for i in range(0, len(_genres)):\n _genre = VGenres(genre=_genres[i], vid=venue_id)\n db.session.add(_genre)\n db.session.commit()\n except Exception as e:\n flash(str(e))\n return redirect('/venues/' + str(venue_id) + '/edit')\n # on successful db insert, flash success\n flash('Venue ' + venue.name + ' was successfully Updated!')\n return redirect(url_for('show_venue', venue_id=venue_id))\n\n\n# Create Artist\n# ----------------------------------------------------------------\n\n@app.route('/artists/create', methods=['GET'])\ndef create_artist_form():\n form = ArtistForm()\n return render_template('forms/new_artist.html', form=form)\n\n\n@app.route('/artists/create', methods=['POST'])\ndef create_artist_submission():\n # called upon submitting the new artist listing form\n form = ArtistForm(request.form)\n get = request.form.get\n\n if not form.validate():\n flash(form.errors)\n return render_template('forms/new_artist.html', form=form)\n\n is_seeking = get(\"seeking_venue\") == 'YES'\n artist = Artist(\n name=get(\"name\"),\n city=get(\"city\"),\n state=get(\"state\"),\n phone=get(\"phone\"),\n facebook_link=get(\"facebook_link\"),\n image_link=get(\"image_link\"),\n website=get(\"website\"),\n seeking_venue=is_seeking,\n seeking_description=get(\"seeking_description\") if is_seeking else \"\"\n )\n db.session.add(artist)\n db.session.commit()\n _genres = request.form.getlist(\"genres\")\n for i in range(0, len(_genres)):\n _genre = AGenres(agenre=_genres[i], aid=artist.id)\n db.session.add(_genre)\n db.session.commit()\n # on successful db insert, flash success\n flash('Artist ' + request.form['name'] + ' was successfully listed!')\n return redirect(\"/artists/\" + str(artist.id))\n\n# Shows\n# ----------------------------------------------------------------\n\n@app.route('/shows')\ndef shows():\n _shows = Show.query.all()\n data = list(map(lambda show: {\n \"venue_id\": show.vid,\n \"venue_name\": show.venue.name,\n \"artist_id\": show.aid,\n \"artist_name\": show.artist.name,\n \"artist_image_link\": show.artist.image_link,\n \"start_time\": str(show.start_time)\n }, _shows))\n # displays list of shows at /shows\n return render_template('pages/shows.html', shows=data)\n\n\n@app.route('/shows/create')\ndef create_shows():\n # renders form. do not touch.\n form = ShowForm()\n return render_template('forms/new_show.html', form=form)\n\n\n@app.route('/shows/create', methods=['POST'])\ndef create_show_submission():\n # called to create new shows in the db, upon submitting new show listing form\n form = ShowForm(request.form)\n get = request.form.get\n\n if not form.validate():\n flash(form.errors)\n return render_template('forms/new_show.html', form=form)\n try:\n show = Show(\n aid=get(\"artist_id\"),\n vid=get(\"venue_id\"),\n start_time=get(\"start_time\")\n )\n db.session.add(show)\n db.session.commit()\n except psycopg2.errors.ForeignKeyViolation:\n flash(\"Didn't find either an artist or venue with such id...\")\n return render_template('forms/new_show.html', form=form)\n except Exception as e:\n flash(e)\n return render_template('forms/new_show.html', form=form)\n # on successful db insert, flash success\n flash('Show was successfully listed!')\n return redirect(\"/shows\")\n\n\n@app.route('/shows/search', methods=['POST'])\ndef search_shows():\n term = request.form.get('search_term')\n raw = Show.query.all()\n data = list(map(lambda show: {\n \"artist_name\": show.artist.name,\n \"venue_name\": show.venue.name,\n \"start_time\": str(show.start_time),\n \"artist_id\": show.aid,\n \"venue_id\": show.vid\n }, list(filter(\n lambda show: re.search(term, show.artist.name + \" \" + show.venue.name, re.IGNORECASE)\n , raw))))\n response = {\n \"count\": len(data),\n \"data\": data\n }\n return render_template('pages/search_shows.html', results=response,\n search_term=request.form.get('search_term', ''))\n\n\n@app.errorhandler(404)\ndef not_found_error(error):\n return render_template('errors/404.html'), 404\n\n\n@app.errorhandler(500)\ndef server_error(error):\n return render_template('errors/500.html'), 500\n\n\nif not app.debug:\n file_handler = FileHandler('error.log')\n file_handler.setFormatter(\n Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')\n )\n app.logger.setLevel(logging.INFO)\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n app.logger.info('errors')\n\n# ----------------------------------------------------------------------------#\n# Launch.\n# ----------------------------------------------------------------------------#\n\n# Default port:\nif __name__ == '__main__':\n app.run()\n\n# Or specify port manually:\n'''\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n'''\n","sub_path":"projects/01_fyyur/starter_code/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":20235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"319938166","text":"import scrapy\nfrom bs4 import BeautifulSoup\n\n\nclass GimageSpider(scrapy.Spider):\n name = 'gimage'\n allowed_domains = ['www.google.com.tw/imghp']\n start_urls = ['https://www.google.com.tw/imghp?hl=zh-TW&ogbl']\n\n def parse(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n \n # print(ele)","sub_path":"my_scrapy/spiders/gimage.py","file_name":"gimage.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"74755979","text":"import time\nimport traceback\nimport json\nimport requests\nimport argparse\n\n\nclass HttpUtil(object):\n def __init__(self):\n self._req = requests.session()\n\n @property\n def requests(self):\n return self._req\n\n\ndef login(requests, base_url):\n try:\n if str(base_url).endswith('/') is False:\n base_url += '/'\n account = config_json.get('user')\n if account and account.get('username') and account.get('password'):\n post_data = {'username': account.get('username'), 'password': account.get('password')}\n return requests.post(base_url + 'api/auth/', json=post_data)\n return None\n except OSError:\n traceback.print_exc()\n return None\n\n\ndef post_code(requests, base_url, json_str):\n if str(base_url).endswith('/') is False:\n base_url += '/'\n try:\n res = requests.post(base_url + 'api/submission/', json=json_str)\n print(res.text)\n return 'SUCCESS'\n except OSError:\n traceback.print_exc()\n return None\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='提交或更新爬虫账号到VJ')\n parser.add_argument('--config', type=str, default='config.json', help='json config file path')\n args = parser.parse_args()\n with open(args.config, 'r') as f:\n config_json = json.loads(f.read())\n base_url = config_json.get('base_url')\n\n client = HttpUtil()\n res = login(client.requests, base_url)\n client.requests.headers.update({'X-CSRFToken': client.requests.cookies.get('csrftoken')})\n json_str = {\n 'code': \"\"\"\n #include <iostream>\n using namespace std;\n int main(){\n int a, b;\n while(cin >> a >> b){\n cout << a + b << endl;\n }\n }\n \"\"\",\n 'language': '1',\n 'remote_id': 1000,\n 'remote_oj': 'WUST'\n }\n for i in range(5):\n pos = post_code(client.requests, base_url, json_str)\n time.sleep(5)\n exit(0)\n exit(1)\n","sub_path":"tools/submit_code.py","file_name":"submit_code.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"499573265","text":"\"\"\"\"Hacs base setup task.\"\"\"\nfrom .base import HacsTask\n\n\nasync def async_setup() -> None:\n \"\"\"Set up this task.\"\"\"\n return Task()\n\n\nclass Task(HacsTask):\n \"\"\" \"Hacs task base.\"\"\"\n\n def execute(self) -> None:\n self.log.debug(\"Hello World!\")\n","sub_path":"custom_components/hacs/tasks/hello_world.py","file_name":"hello_world.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"499864920","text":"import sys\nimport json\n\nnom_fichier = sys.argv[1]\n\nwith open(nom_fichier) as f:\n data = json.load(f)\n\n# créer une liste\nliste = [c['SOLIFE']['url'] for c in data if 'SOLIFE' in c]\n\n# parcours avec un générateur (pas de création de liste)\nfor x in (c['SOLIFE']['url'] for c in data if 'SOLIFE' in c):\n print(x)\n\n# parcours avec un filtre (pas de création de liste)\nfor x in filter(lambda c : \"SOLIFE\" in c, data):\n print(x['SOLIFE']['url'])\n\n# parcours old school\nfor c in data:\n if 'SOLIFE' in c:\n print(c['SOLIFE']['url'])","sub_path":"json_couloir.py","file_name":"json_couloir.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"650721322","text":"from __future__ import division\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom numpy import mean, std\nfrom math import sqrt\nfrom scipy.stats import ttest_ind, sem, f\nimport scipy.stats as st\nimport xpressplot as xp\nimport gzip\n\n__path__ = os.getcwd()\n\ndef mean_confidence_interval(data, confidence=0.95):\n _interval = st.t.interval(\n alpha=confidence,\n df=len(data)-1,\n loc=np.mean(data),\n scale=st.sem(data)\n )\n _interval = [\"{:e}\".format(e) for e in _interval]\n\n return np.mean(data), _interval\n\ndef mean_confidence_interval_norm(data, confidence=0.95):\n _interval = st.norm.interval(\n alpha=confidence,\n loc=np.mean(data),\n scale=st.sem(data)\n )\n _interval = [\"{:e}\".format(e) for e in _interval]\n return np.mean(data), _interval\n\ndef cohen_d(x,y):\n return (\n mean(x) - mean(y)) / sqrt((std(x, ddof=1) ** 2 + std(y, ddof=1) ** 2) / 2.0\n )\n\ndef confidence_overlap(set1, set2, id, confidence=0.95):\n\n conf1 = mean_confidence_interval(\n set1.loc[id].values.tolist(),\n confidence=confidence)\n conf2 = mean_confidence_interval(\n set2.loc[id].values.tolist(),\n confidence=confidence)\n\n conf1 = [float(x) for x in conf1[1]]\n conf2 = [float(x) for x in conf2[1]]\n\n def getOverlap(a, b):\n return max(0, min(a[1], b[1]) - max(a[0], b[0]))\n\n _overlap = getOverlap(conf1, conf2)\n _diff = max(conf1 + conf2) - min(conf1 + conf2)\n\n if _overlap > 0:\n print('Confidence intervals (' + str(confidence) + ') OVERLAP')\n print(\n 'Overlap: ' + str(_overlap)\n + ' (' + str(round((_overlap / _diff) * 100, 2)) + '%)')\n print(' Interval 1: ' + str(conf1))\n print(' Interval 2: ' + str(conf2))\n else:\n print('Confidence intervals (' + str(confidence) + ') DO NOT overlap')\n\ndef g_decompress(\n path,\n file,\n output):\n\n g_open = open(os.path.join(path, output), \"wb\")\n with gzip.open(os.path.join(path, file), \"rb\") as f:\n g_data = f.read()\n g_open.write(g_data)\n g_open.close()\n\ndef read_table(\n url,\n sep='\\t',\n index_col=0,\n header='infer',\n low_memory=False,\n compression='infer',\n comment='#'):\n \"\"\"Read tab-delimited table\n \"\"\"\n\n data = pd.read_csv(\n url,\n sep=sep,\n index_col=index_col,\n header=header,\n low_memory=low_memory,\n compression=compression,\n comment=comment)\n\n return data\n\n\n# RNA d values\nrna_url = os.path.abspath(os.path.join(\".\", \"data\", \"sce_mct1_omics\", \"sce_mct1_03hr_counts_diffx.tsv\"))\nrna_de = pd.read_csv(\n rna_url,\n sep='\\t',\n index_col=0)\n\nmct1_rnaseq_tpm = read_table(\n url=os.path.join(\n __path__,\n \"mct1_analysis\",\n \"data\",\n \"mct1_rnaseq_data\",\n \"sce_mct1_deduped_tpm_threshold25.tsv\")\n)\n\ngtf = pd.read_csv(\n os.path.join(\n __path__,\n \"mct1_analysis\",\n \"data\",\n \"analysis_lists\",\n \"Saccharomyces_cerevisiae.R64-1-1.103.gtf.gz\"),\n sep='\\t',\n comment='#',\n low_memory=False,\n header=None)\norig_name_label='gene_id \"'\norig_name_location=0\nnew_name_label='gene_name \"'\nnew_name_location=1\ngtf_genes = gtf.loc[gtf[2] == 'gene']\ngtf_genes['original'] = gtf[8].str.split(';').str[orig_name_location]\ngtf_genes['new'] = gtf[8].str.split(';').str[new_name_location]\ngtf_genes['original'] = gtf_genes['original'].map(lambda x: x.lstrip(str(orig_name_label)).rstrip('\"').lstrip('\"').rstrip(' '))\ngtf_genes['new'] = gtf_genes['new'].map(lambda x: x.lstrip(str(new_name_label)).rstrip('\"').rstrip(' '))\ngtf_genes = gtf_genes[['original','new']].copy()\n\ngene_dict = {}\nfor index, row in gtf_genes.iterrows():\n if row[1] == 'source \"sgd':\n gene_dict[row[0]] = row[0]\n else:\n gene_dict[row[0]] = row[1]\n\nrna_de_renamed = rna_de.copy()\nrna_de_renamed['new'] = rna_de_renamed.index.to_series().map(gene_dict).fillna(\n rna_de_renamed.index.to_series())\nrna_de_renamed = rna_de_renamed.set_index('new')\nrna_de_renamed.index.name = None\n\nmct1_rnaseq_tpm_renamed = mct1_rnaseq_tpm.copy()\nmct1_rnaseq_tpm_renamed['new'] = mct1_rnaseq_tpm_renamed.index.to_series().map(\n gene_dict\n ).fillna(\n mct1_rnaseq_tpm_renamed.index.to_series())\nmct1_rnaseq_tpm_renamed = mct1_rnaseq_tpm_renamed.set_index('new')\nmct1_rnaseq_tpm_renamed.index.name = None\n\n\"\"\"\n14251X4\t WT\n14251X6\t mct1del\n14251X10\tWT\n14251X12\tmct1del\n14251X16\tWT\n14251X18\tmct1del\n14251X22\tWT\n14251X24\tmct1del\n\"\"\"\nrna_mct1 = mct1_rnaseq_tpm_renamed[[\n '14251X6',\n '14251X12',\n '14251X18',\n '14251X24']]\nrna_wt = mct1_rnaseq_tpm_renamed[[\n '14251X4',\n '14251X10',\n '14251X16',\n '14251X22']]\n\n\nrna_list = [\n 'GLK1',\n 'PGI1',\n 'PFK1', 'PFK2',\n 'FBP1',\n 'FBA1', 'TPI1',\n 'TDH1', 'TDH2', 'TDH3',\n 'PGK1',\n 'GPM1',\n 'ENO1', 'ENO2',\n 'PYK2', 'CDC19',\n 'PYC1', 'PYC2',\n 'CIT1', 'CIT2', 'CIT3',\n 'ACO1', 'ACO2',\n 'IDH1', 'IDH2',\n 'LPD1', 'KGD1', 'KGD2',\n 'LSC1', 'LSC2',\n 'SDH1', 'SDH2', 'SDH3', 'SDH4',\n 'FUM1',\n 'MDH1',\n 'GDH1', 'GDH2', 'GLN1',\n 'ALT1', 'ALT2',\n 'DLD1', 'DLD2', 'DLD3',\n 'MAE1',\n 'AAT1',\n 'CTP1', 'DIC1'\n]\n\nfor x in rna_list:\n try:\n print(x)\n print('fold change: '+ str(np.log2(\n (sum(rna_mct1.loc[x].values))\n / (sum(rna_wt.loc[x].values))))\n\n )\n print('Cohen\\'s d: '+ str(\n cohen_d(\n rna_mct1.loc[x].values,\n rna_wt.loc[x].values)\n )\n )\n confidence_overlap(rna_mct1, rna_wt, x, confidence=0.95)\n print(\n rna_de_renamed.loc[x]\n )\n print()\n print()\n except:\n print('Skipping ' + x + '...')\n print()\n print()\n\nfor x in rna_list:\n try:\n fc = str(round(np.log2(\n (sum(rna_mct1.loc[x].values))\n / (sum(rna_wt.loc[x].values)))\n , 2))\n p = str(\"{:.2e}\".format(rna_de_renamed.loc[x]['FDR']))\n d = str(round(\n cohen_d(\n rna_mct1.loc[x].values,\n rna_wt.loc[x].values)\n , 2))\n\n print(x, ' & 3 hr & ', fc, ' & ', p, ' & ', d, '\\\\\\\\ \\hline')\n except:\n pass\n\n\n\n\n\n\n\n\n\n# Proteomics d values\nraw_proteomics_url = os.path.abspath(os.path.join(\".\", \"mct1_analysis\", \"data\", \"mct1_proteomics_data\", \"proteomics_values.txt\"))\n\nproteomics = pd.read_csv(\n raw_proteomics_url,\n sep='\\t',\n index_col=0)\nproteomics_mct1 = proteomics[[\n 'mct1_1',\n 'mct1_2',\n 'mct1_3']]\nproteomics_wt = proteomics[[\n 'WT_1',\n 'WT_2',\n 'WT_3']]\n\nprotein_list = [\n 'GLK1',\n 'PGI1',\n 'PFK1', 'PFK2',\n 'FBP1',\n 'FBA1', 'TPI1',\n 'TDH1', 'TDH2', 'TDH3',\n 'PGK1',\n 'GPM1',\n 'ENO1', 'ENO2',\n 'PYK2', 'CDC19',\n 'PYC1', 'PYC2',\n 'CIT1', 'CIT2', 'CIT3',\n 'ACO1', 'ACO2',\n 'IDH1', 'IDH2',\n 'LPD1', 'KGD1', 'KGD2',\n 'LSC1', 'LSC2',\n 'SDH1', 'SDH2', 'SDH3', 'SDH4',\n 'FUM1',\n 'MDH1',\n 'GDH1', 'GDH2', 'GLN1',\n 'ALT1', 'ALT2',\n 'DLD1', 'DLD2', 'DLD3',\n 'MAE1',\n 'AAT1',\n 'CTP1', 'DIC1'\n]\n\nfor x in protein_list:\n print(x)\n print('fold change: '+ str(np.log2(\n (sum(proteomics_mct1.loc[x].values))\n / (sum(proteomics_wt.loc[x].values))))\n\n )\n print('Cohen\\'s d: '+ str(\n cohen_d(\n proteomics_mct1.loc[x].values,\n proteomics_wt.loc[x].values)\n )\n )\n confidence_overlap(proteomics_mct1, proteomics_wt, x, confidence=0.95)\n print(\n ttest_ind(\n proteomics_mct1.loc[x].values,\n proteomics_wt.loc[x].values)\n )\n print()\n print()\n\nfor x in protein_list:\n try:\n fc = str(round(np.log2(\n (sum(proteomics_mct1.loc[x].values))\n / (sum(proteomics_wt.loc[x].values)))\n , 2))\n p = str(\"{:.2e}\".format(\n ttest_ind(\n proteomics_mct1.loc[x].values,\n proteomics_wt.loc[x].values)[1]\n ))\n d = str(round(\n cohen_d(\n proteomics_mct1.loc[x].values,\n proteomics_wt.loc[x].values)\n , 2))\n\n print(x.capitalize(), '(' + x + ') & 12 hr & ', fc, ' & ', p, ' & ', d, '\\\\\\\\ \\hline')\n except:\n pass\n\n\n\n\n\n\n\n\n\n\nraw_metabolomics_url = os.path.abspath(\"./mct1_analysis/data/mct1_metabolomics_data/mct1_metabolomics_allValues.txt\")\nraw_metabolomics_url = os.path.abspath(\"./mct1_analysis/data/mct1_metabolomics_data/mct1_metabolomics_allValues.txt\")\nmetabolomics_180min = pd.read_csv(\n raw_metabolomics_url,\n sep='\\t',\n index_col=0)\n\nmetabolomics_mct1_180min = metabolomics_180min[[\n 'mct1KO at 3hr minR+Leu 1',\n 'mct1KO at 3hr minR+Leu 2',\n 'mct1KO at 3hr minR+Leu 3',\n 'mct1KO at 3hr minR+Leu 4',\n 'mct1KO at 3hr minR+Leu 5',\n 'mct1KO at 3hr minR+Leu 6'\n]]\nmetabolomics_wt_180min = metabolomics_180min[[\n 'WT at 3hr minR+Leu 1',\n 'WT at 3hr minR+Leu 2',\n 'WT at 3hr minR+Leu 3',\n 'WT at 3hr minR+Leu 4',\n 'WT at 3hr minR+Leu 5'\n]]\n\nmetabolomics_wt_180min.index.tolist()\n\ngc_metabolomics = [\n ' Glucose 6-phosphate',\n ' Fructose-6-phosphate ',\n ' fructose-1,6-diphosphate',\n ' 3-Phosphoglyceric acid ',\n ' Phosphoenolpyruvate ',\n ' Pyruvic acid ',\n ' Glyoxylic acid ',\n ' Citric acid ',\n ' Isocitric acid ',\n ' Succinic acid ',\n ' Fumaric acid ',\n ' D-Malic acid ',\n ' L-Alanine',\n ' L-Lactic acid ',\n ' L-Aspartic acid',\n ' L-Glutamic acid',\n ' 2-Hydroxyglutaric acid',\n]\n\nfor x in gc_metabolomics:\n print(x)\n print('fold change: '+ str(np.log2(\n (sum(metabolomics_mct1_180min.loc[x].values))\n / (sum(metabolomics_wt_180min.loc[x].values))))\n\n )\n print('Cohen\\'s d: '+ str(\n cohen_d(\n metabolomics_mct1_180min.loc[x].values,\n metabolomics_wt_180min.loc[x].values)\n )\n )\n confidence_overlap(\n metabolomics_mct1_180min,\n metabolomics_wt_180min,\n x,\n confidence=0.95)\n print(\n ttest_ind(\n metabolomics_mct1_180min.loc[x].values,\n metabolomics_wt_180min.loc[x].values)\n )\n print()\n print()\n\n\n\n\nfor x in gc_metabolomics:\n try:\n fc = str(round(np.log2(\n (sum(metabolomics_mct1_180min.loc[x].values))\n / (sum(metabolomics_wt_180min.loc[x].values)))\n , 2))\n p = str(\"{:.2e}\".format(\n ttest_ind(\n metabolomics_mct1_180min.loc[x].values,\n metabolomics_wt_180min.loc[x].values)[1]\n ))\n d = str(round(\n cohen_d(\n metabolomics_mct1_180min.loc[x].values,\n metabolomics_wt_180min.loc[x].values)\n , 2))\n\n print(x[1:-1].capitalize(), '() & 3 hr & ', fc, ' & ', p, ' & ', d, '\\\\\\\\ \\hline')\n except:\n pass\n\n\n\n\n\n\n\n# CTP1 Metabolomics\nraw_metabolomics_ctp1 = os.path.abspath(os.path.join(\".\", \"mct1_analysis\", \"data\", \"ctp1_metabolomics_data\", \"ctp1_metabolomics_allValues.txt\"))\n\nmetabolomics = pd.read_csv(\n raw_metabolomics_ctp1,\n sep='\\t',\n index_col=0)\n\nctp1_sr_wt_ev = metabolomics[[\n 'WT_SR_EV1',\n 'WT_SR_EV2',\n 'WT_SR_EV3']]\n\nctp1_sr_wt_a1 = metabolomics[[\n 'WT_SR_A1',\n 'WT_SR_A2',\n 'WT_SR_A3']]\n\nctp1_sr_mct_ev = metabolomics[[\n 'MCT_SR_EV1',\n 'MCT_SR_EV2',\n 'MCT_SR_EV3']]\n\nctp1_sr_mct_a1 = metabolomics[[\n 'MCT_SR_A1',\n 'MCT_SR_A2',\n 'MCT_SR_A3']]\n\n\nlc_metabolomics = [\n 'Glucose',\n 'F6P',\n 'F16BP',\n 'Pyruvate',\n 'CoA',\n 'Citrate',\n 'a-KG',\n 'Succinate',\n 'Fumarate',\n 'Malate',\n 'Glutamate',\n 'Glutamine',\n 'Aspartate',\n 'Alanine'\n]\n\nprint('mct1-del vs WT')\nfor x in lc_metabolomics:\n print(x)\n print('fold change: '+ str(np.log2(\n (sum(ctp1_sr_mct_ev.loc[x].values))\n / (sum(ctp1_sr_wt_ev.loc[x].values))))\n\n )\n print('Cohen\\'s d: '+ str(\n cohen_d(\n ctp1_sr_mct_ev.loc[x].values,\n ctp1_sr_wt_ev.loc[x].values)\n )\n )\n confidence_overlap(\n ctp1_sr_mct_ev,\n ctp1_sr_wt_ev,\n x,\n confidence=0.95)\n print(\n ttest_ind(\n ctp1_sr_mct_ev.loc[x].values,\n ctp1_sr_wt_ev.loc[x].values)\n )\n print()\n print()\n\nfor x in lc_metabolomics:\n try:\n fc = str(round(np.log2(\n (sum(ctp1_sr_mct_ev.loc[x].values))\n / (sum(ctp1_sr_wt_ev.loc[x].values)))\n , 2))\n p = str(\"{:.2e}\".format(\n ttest_ind(\n ctp1_sr_mct_ev.loc[x].values,\n ctp1_sr_wt_ev.loc[x].values)[1]\n ))\n d = str(round(\n cohen_d(\n ctp1_sr_mct_ev.loc[x].values,\n ctp1_sr_wt_ev.loc[x].values)\n , 2))\n\n print(x.capitalize(), '() & 12 hr & ', fc, ' & ', p, ' & ', d, '\\\\\\\\ \\hline')\n except:\n pass\n\n\n\n\n\n\nprint('mct1-del+CTP1 vs mct1-del')\nfor x in lc_metabolomics:\n print(x)\n print('fold change: '+ str(np.log2(\n (sum(ctp1_sr_mct_a1.loc[x].values))\n / (sum(ctp1_sr_mct_ev.loc[x].values))))\n\n )\n print('Cohen\\'s d: '+ str(\n cohen_d(\n ctp1_sr_mct_a1.loc[x].values,\n ctp1_sr_mct_ev.loc[x].values)\n )\n )\n confidence_overlap(\n ctp1_sr_mct_a1,\n ctp1_sr_mct_ev,\n x,\n confidence=0.95)\n print(\n ttest_ind(\n ctp1_sr_mct_a1.loc[x].values,\n ctp1_sr_mct_ev.loc[x].values)\n )\n print()\n print()\n\n\nfor x in lc_metabolomics:\n try:\n fc = str(round(np.log2(\n (sum(ctp1_sr_mct_a1.loc[x].values))\n / (sum(ctp1_sr_mct_ev.loc[x].values)))\n , 2))\n p = str(\"{:.2e}\".format(\n ttest_ind(\n ctp1_sr_mct_a1.loc[x].values,\n ctp1_sr_mct_ev.loc[x].values)[1]\n ))\n d = str(round(\n cohen_d(\n ctp1_sr_mct_a1.loc[x].values,\n ctp1_sr_mct_ev.loc[x].values)\n , 2))\n\n print(x.capitalize(), '() & 12 hr & ', fc, ' & ', p, ' & ', d, '\\\\\\\\ \\hline')\n except:\n pass\n","sub_path":"fig_4_source/notebooks/mct1_statistics.py","file_name":"mct1_statistics.py","file_ext":"py","file_size_in_byte":14265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"392863279","text":"# Module: url\r\n# Description: Launch websites\r\n# Usage: !url website\r\n# Dependencies: os, asyncio, configs\r\n\r\nimport time\r\nfrom modules.video_module import video_duration\r\nimport os, asyncio, configs\r\n\r\nfrom lib import helpers\r\n\r\nasync def url(ctx, txt):\r\n await ctx.send(\"Launching the Website\")\r\n print(txt)\r\n list = txt.split(\" \")\r\n\r\n for i in range(len(list)):\r\n if list[0].__contains__('https'):\r\n if list[i].__contains__('youtube'):\r\n txt = list[i]\r\n print(txt)\r\n current = time.time()\r\n videoDuration = video_duration(list[0])\r\n\r\n if configs.operating_sys == \"Windows\":\r\n media_control = helpers.MediaControlAdapter(configs.operating_sys)\r\n media_control.media_key_close() # close the currently open tab\r\n await asyncio.sleep(3) # add some time to let the window close before doing anything else\r\n os.system(\"start {0}\".format(txt))\r\n await asyncio.sleep(3) # put time between commands and return focus to main thread\r\n media_control.media_key_fullscreen()\r\n await asyncio.sleep(2) # put time between commands and return focus to main thread\r\n else:\r\n await ctx.send(\"The URL you entered is not available.\")\r\n await ctx.send(\"Please enter the following:\")\r\n await ctx.send('\"https://youtube.com/ (rest of the video link)\"')\r\n await ctx.send(list)\r\n await asyncio.sleep(3)\r\n else:\r\n await ctx.send(\"URL feature is not available in this platform.\")\r\n await asyncio.sleep(3)\r\n","sub_path":"modules/urlLauncher_module.py","file_name":"urlLauncher_module.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"647809108","text":"from js9 import j\n\nfrom .parser import CapacityParser\n\nJSBASE = j.application.jsbase_get_class()\n\n\nclass Factory(JSBASE):\n\n def __init__(self):\n self.__jslocation__ = \"j.tools.capacity\"\n JSBASE.__init__(self)\n self.parser = CapacityParser()\n","sub_path":"JumpScale9Lib/tools/capacity/Factory.py","file_name":"Factory.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"148256761","text":"import xlrd\nfrom xlutils3.copy import copy\n\n\nclass ExcelParse(object):\n \"\"\"\n path:excel路径\n sheet:excel中的sheet下表\n head_index:excel标题头所在的行数\n callback:遍历每一行的回掉\n offset:内容体遍历的起始位置\n limit:遍历的总记录数\n descName:最终生成的excel\n \"\"\"\n def __init__(self, path, sheet=0, head_index=0, callback=None, offset=0, limit=None, desc_name=\"aaa.xls\"):\n data = xlrd.open_workbook(path)\n self.table = data.sheet_by_index(sheet)\n self.nrows = self.table.nrows\n self.callback = callback\n self.headIndex = head_index\n self.ncols = self.table.ncols\n self.headers = []\n self.bodys = []\n self.limit = limit\n self.descTable = copy(data)\n self.desc_name = desc_name\n self.offset = offset\n self.parse_header()\n\n def parse(self):\n for i in range(self.nrows):\n row = self.table.row_values(i)\n # data = self.callback and self.callback(self.table, row)\n self.callback and self.callback(self.table, row)\n\n def prase_body(self):\n start = self.offset or (self.headIndex + 1)\n end = (self.limit + start) if None is not self.limit else self.nrows\n for bodyIndex in range(start, end):\n self.callback and self.callback(self, self.table.row_values(bodyIndex), bodyIndex)\n\n def parse_header(self):\n head = self.table.row_values(self.headIndex)\n for i in range(self.ncols):\n self.headers.append(head[i])\n\n \"\"\"\n 获取单元格的值\n \"\"\"\n def get_cell_value(self, row_index, header):\n row = self.table.row_values(row_index)\n index = self.headers.index(header)\n return row[index]\n\n \"\"\"\n 设置excel的单元格的值\n \"\"\"\n def set_cell_value(self, row_index, header, value, sheet=0):\n index = self.headers.index(header)\n table = self.descTable.get_sheet(sheet)\n table.write(row_index, index, value)\n\n \"\"\"\n 保存\n \"\"\"\n def save(self):\n self.descTable.save(self.desc_name)\n\n# http://browser.ihtsdotools.org/api/v1/snomed/en-edition/v20170731/descriptions?query=Headaches&limit=50&searchMode=partialMatching&lang=english&statusFilter=activeOnly&skipTo=0&returnLimit=100&normalize=true\n# table, nRows = read_excel(\"../sym_about.xlsx\")\n# print nRows\n","sub_path":"utils/excel_utils.py","file_name":"excel_utils.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"650192979","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*\nfrom re import match\nimport sys\n\nCOLCOUNT = 10\nID,FORM,LEMMA,UPOS,XPOS,FEATS,HEAD,DEPREL,DEPS,MISC = range(COLCOUNT)\nCOLNAMES = 'ID,FORM,LEMMA,UPOS,XPOS,FEATS,HEAD,DEPREL,DEPS,MISC'.split(',')\n\nPOS = ['ADJ', 'ADP', 'ADV', 'AUX', 'CCONJ', 'DET', 'INTJ', 'NOUN', 'NUM', 'PART', 'PRON', 'PROPN', 'PUNCT', 'SCONJ', 'SYM', 'VERB', 'X', 'PREP', 'POSTP', 'UNKN']\n\n\ndef validate(filename_in, filename_out):\n\n is_new_sentence = True\n common_result = True\n line_number = 0\n errors = []\n\n def new_error(line_number, col_name, field_value, message):\n global common_result\n common_result = False\n errors.append('{}; invalid field: {}: {}: {}'.format(line_number, col_name, field_value, message))\n\n with open(filename_in, 'r', encoding='utf-8') as f:\n for line in f:\n line_number += 1\n if line[0] == '#':\n continue\n elif line == '\\n':\n is_new_sentence = True\n continue\n else:\n fields = line.split('\\t')\n if not len(fields) == 10:\n errors.append(str(line_number) + '; wrong number of fields')\n common_result = False\n else:\n if not match(r'((\\d+)|((\\d+)-\\d+)|((\\d+).\\d+))', fields[ID]):\n new_error(line_number, 'ID', fields[ID], 'wrong format')\n if (is_new_sentence == True and int(fields[ID].split('-')[0]) != 1) or (is_new_sentence == False and int(fields[ID].split('-')[0]) != prev_id + 1 and int(fields[ID].split('-')[0]) != prev_id) or (len(fields[ID].split('-')) > 1 and int(fields[ID].split('-')[1]) <= int(fields[ID].split('-')[0])):\n new_error(line_number, 'ID', fields[ID], 'incorrect value')\n if fields[FORM] == '':\n new_error(line_number, 'FORM', fields[FORM], 'empty')\n if fields[LEMMA] == '':\n new_error(line_number, 'LEMMA', fields[LEMMA], 'empty')\n if fields[UPOS] != '_' and fields[UPOS] not in POS:\n new_error(line_number, 'UPOS', fields[UPOS], 'wrong format')\n if fields[XPOS] == '':\n new_error(line_number, 'XPOS', fields[XPOS], 'empty')\n if fields[FEATS] != '_' and not match(r'(([A-Z0-9][A-Z0-9a-z]*=[A-Z0-9][a-zA-Z0-9]*)(\\u007c([A-Z0-9][A-Z0-9a-z]*=[A-Z0-9][a-zA-Z0-9]*))*(#(([A-Z0-9][A-Z0-9a-z]*=[A-Z0-9][a-zA-Z0-9]*)(\\u007c([A-Z0-9][A-Z0-9a-z]*=[A-Z0-9][a-zA-Z0-9]*))*)))*', fields[FEATS]):\n #or (match(r'\\w+=\\w+\\u007c\\w+=\\w+#\\w+=\\w+\\u007c\\w+=\\w+', fields[FEATS]) and (fields[FEATS].split('#')[0].split('|')[0].split('=')[0] != fields[FEATS].split('#')[1].split('|')[0].split('=')[0] or fields[FEATS].split('#')[0].split('|')[1].split('=')[0] != fields[FEATS].split('#')[1].split('|')[1].split('=')[0]))):\n new_error(line_number, 'FEATS', fields[FEATS], 'wrong format')\n if fields[HEAD] == '':\n new_error(line_number, 'HEAD', fields[HEAD], 'empty')\n if fields[DEPREL] == '':\n new_error(line_number, 'DEPREL', fields[DEPREL], 'empty')\n if fields[DEPS] == '':\n new_error(line_number, 'DEPS', fields[DEPS], 'empty')\n if fields[MISC] in ('', '\\n'):\n new_error(line_number, 'MISC', fields[MISC], 'empty')\n\n prev_id = int(fields[ID].split('-')[0])\n is_new_sentence = False\n\n with open(filename_out, 'w', encoding='utf-8') as f:\n f.write('\\n'.join(errors))\n\n\ndef main():\n if len(sys.argv) < 2:\n print(\"usage: corpora_validation.py filename\")\n return\n filename = sys.argv[1]\n filename_out = filename + '_errors.txt'\n validate(filename, filename_out)\n\nif __name__ == '__main__':\n main()","sub_path":"evaluation/corpora_validation.py","file_name":"corpora_validation.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"218445399","text":"# coding: utf-8\nfrom base import Manager\nfrom riotpy.resources.match import MatchListResource\n\n\nclass MatchListManager(Manager):\n\n def get_summoner_match_list(self, summoner_id,\n champion_ids=None, ranked_queues=None, seasons=None,\n begin_time=None, end_time=None,\n begin_index=None, end_index=None):\n \"\"\"\n Get a match list for the summoner_id\n\n :param summoner_id: the summoner id\n :param champion_ids: list of champion_ids to look or all the ids separated by `,`.\n :param ranked_queues: list of ranked_queues to look or all the ids separated by `,`.\n :param seasons: list of seasons to look or all the ids separated by `,`.\n :param begin_time: The begin time to use for fetching games specified as epoch milliseconds.\n :param end_time: The end time to use for fetching games specified as epoch milliseconds.\n :param begin_index: The begin index to use for fetching games.\n :param end_index: The begin index to use for fetching games.\n\n\n :return: A resources.team.TeamResource list\n \"\"\"\n extra = {}\n\n if champion_ids:\n if isinstance(champion_ids, list):\n champion_ids = ','.join(champion_ids)\n extra['championIds'] = champion_ids\n\n if ranked_queues:\n if isinstance(ranked_queues, list):\n ranked_queues = ','.join(ranked_queues)\n extra['rankedQueues'] = ranked_queues\n\n if seasons:\n if isinstance(seasons, list):\n seasons = ','.join(seasons)\n extra['seasons'] = seasons\n\n if begin_time:\n extra['beginTime'] = begin_time\n if end_time:\n extra['endTime'] = begin_time\n\n if begin_index:\n extra['beginIndex'] = begin_index\n if end_index:\n extra['endIndex'] = end_index\n\n content = self._get('/api/lol/{}/{}/matchlist/by-summoner/{}'.format(\n self.api.region,\n self.version,\n summoner_id), extra=extra\n )\n\n # data = {\n # 'start_index': content.start_index,\n # 'end_index': content.end_index,\n # 'total_games': content.total_games,\n # 'matches': []\n # }\n\n return self._dict_to_resource(content, resource_class=MatchListResource)\n","sub_path":"riotpy/managers/match_list.py","file_name":"match_list.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"275264815","text":"jogador = {\n \"count\": 20,\n \"count_total\": 20542,\n \"page\": 5,\n \"page_total\": 1028,\n \"items_per_page\": 20,\n \"items\": [\n {\n \"id\": 93971,\n \"resource_id\": 246529,\n \"name\": \"Bergkamp\",\n \"age\": None,\n \"resource_base_id\": 246529,\n \"fut_bin_id\": 28708,\n \"fut_wiz_id\": 19816,\n \"first_name\": \"Dennis\",\n \"last_name\": \"Bergkamp\",\n \"common_name\": \"Bergkamp\",\n \"height\": 183,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 34,\n \"club\": 112658,\n \"rarity\": 84,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CF\",\n \"skill_moves\": 4,\n \"weak_foot\": 4,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"MED\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 79,\n \"pace\": 85,\n \"shooting\": 93,\n \"passing\": 89,\n \"dribbling\": 94,\n \"defending\": 39,\n \"physicality\": 79,\n \"pace_attributes\": {\n \"acceleration\": 86,\n \"sprint_speed\": 84\n },\n \"shooting_attributes\": {\n \"positioning\": 96,\n \"finishing\": 95,\n \"shot_power\": 93,\n \"long_shots\": 86,\n \"volleys\": 98,\n \"penalties\": 94\n },\n \"passing_attributes\": {\n \"vision\": 96,\n \"crossing\": 85,\n \"free_kick_accuracy\": 85,\n \"short_passing\": 91,\n \"long_passing\": 81,\n \"curve\": 87\n },\n \"dribbling_attributes\": {\n \"agility\": 88,\n \"balance\": 83,\n \"reactions\": 96,\n \"ball_control\": 99,\n \"dribbling\": 92,\n \"composure\": 98\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 73,\n \"standing_tackle\": 42,\n \"sliding_tackle\": 37\n },\n \"physicality_attributes\": {\n \"jumping\": 79,\n \"stamina\": 83,\n \"strength\": 78,\n \"aggression\": 75\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93972,\n \"resource_id\": 246503,\n \"name\": \"Madeira Caeiro Figo\",\n \"age\": None,\n \"resource_base_id\": 246503,\n \"fut_bin_id\": 28707,\n \"fut_wiz_id\": 19818,\n \"first_name\": \"Luís Filipe\",\n \"last_name\": \"Madeira Caeiro Figo\",\n \"common_name\": \"Luís Figo\",\n \"height\": 180,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 38,\n \"club\": 112658,\n \"rarity\": 84,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"RM\",\n \"skill_moves\": 4,\n \"weak_foot\": 4,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"LOW\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 82,\n \"pace\": 93,\n \"shooting\": 90,\n \"passing\": 92,\n \"dribbling\": 94,\n \"defending\": 42,\n \"physicality\": 82,\n \"pace_attributes\": {\n \"acceleration\": 95,\n \"sprint_speed\": 92\n },\n \"shooting_attributes\": {\n \"positioning\": 93,\n \"finishing\": 91,\n \"shot_power\": 88,\n \"long_shots\": 91,\n \"volleys\": 82,\n \"penalties\": 86\n },\n \"passing_attributes\": {\n \"vision\": 91,\n \"crossing\": 93,\n \"free_kick_accuracy\": 96,\n \"short_passing\": 93,\n \"long_passing\": 88,\n \"curve\": 89\n },\n \"dribbling_attributes\": {\n \"agility\": 93,\n \"balance\": 82,\n \"reactions\": 90,\n \"ball_control\": 95,\n \"dribbling\": 97,\n \"composure\": 86\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 65,\n \"standing_tackle\": 42,\n \"sliding_tackle\": 39\n },\n \"physicality_attributes\": {\n \"jumping\": 75,\n \"stamina\": 91,\n \"strength\": 80,\n \"aggression\": 78\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93973,\n \"resource_id\": 246528,\n \"name\": \"Puyol Saforcada\",\n \"age\": None,\n \"resource_base_id\": 246528,\n \"fut_bin_id\": 28706,\n \"fut_wiz_id\": 19819,\n \"first_name\": \"Carles\",\n \"last_name\": \"Puyol Saforcada\",\n \"common_name\": \"Carles Puyol\",\n \"height\": 178,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 45,\n \"club\": 112658,\n \"rarity\": 84,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CB\",\n \"skill_moves\": 2,\n \"weak_foot\": 3,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"MED\",\n \"defense_work_rate\": \"HIGH\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 73,\n \"pace\": 75,\n \"shooting\": 46,\n \"passing\": 70,\n \"dribbling\": 62,\n \"defending\": 96,\n \"physicality\": 92,\n \"pace_attributes\": {\n \"acceleration\": 74,\n \"sprint_speed\": 75\n },\n \"shooting_attributes\": {\n \"positioning\": 45,\n \"finishing\": 36,\n \"shot_power\": 72,\n \"long_shots\": 43,\n \"volleys\": 38,\n \"penalties\": 56\n },\n \"passing_attributes\": {\n \"vision\": 60,\n \"crossing\": 71,\n \"free_kick_accuracy\": 49,\n \"short_passing\": 78,\n \"long_passing\": 75,\n \"curve\": 52\n },\n \"dribbling_attributes\": {\n \"agility\": 56,\n \"balance\": 57,\n \"reactions\": 92,\n \"ball_control\": 67,\n \"dribbling\": 55,\n \"composure\": 87\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 94,\n \"standing_tackle\": 96,\n \"sliding_tackle\": 95\n },\n \"physicality_attributes\": {\n \"jumping\": 88,\n \"stamina\": 88,\n \"strength\": 94,\n \"aggression\": 94\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93974,\n \"resource_id\": 258862,\n \"name\": \"Beckham\",\n \"age\": None,\n \"resource_base_id\": 258862,\n \"fut_bin_id\": 28705,\n \"fut_wiz_id\": 19821,\n \"first_name\": \"David\",\n \"last_name\": \"Beckham\",\n \"common_name\": \"Beckham\",\n \"height\": 182,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 14,\n \"club\": 112658,\n \"rarity\": 84,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"RM\",\n \"skill_moves\": 3,\n \"weak_foot\": 3,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"HIGH\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 86,\n \"pace\": 84,\n \"shooting\": 91,\n \"passing\": 97,\n \"dribbling\": 90,\n \"defending\": 70,\n \"physicality\": 84,\n \"pace_attributes\": {\n \"acceleration\": 81,\n \"sprint_speed\": 86\n },\n \"shooting_attributes\": {\n \"positioning\": 93,\n \"finishing\": 85,\n \"shot_power\": 97,\n \"long_shots\": 99,\n \"volleys\": 85,\n \"penalties\": 92\n },\n \"passing_attributes\": {\n \"vision\": 96,\n \"crossing\": 99,\n \"free_kick_accuracy\": 99,\n \"short_passing\": 94,\n \"long_passing\": 98,\n \"curve\": 99\n },\n \"dribbling_attributes\": {\n \"agility\": 80,\n \"balance\": 86,\n \"reactions\": 96,\n \"ball_control\": 94,\n \"dribbling\": 88,\n \"composure\": 97\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 74,\n \"standing_tackle\": 70,\n \"sliding_tackle\": 64\n },\n \"physicality_attributes\": {\n \"jumping\": 75,\n \"stamina\": 95,\n \"strength\": 79,\n \"aggression\": 84\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93975,\n \"resource_id\": 246499,\n \"name\": \"Nesta\",\n \"age\": None,\n \"resource_base_id\": 246499,\n \"fut_bin_id\": 28704,\n \"fut_wiz_id\": 19817,\n \"first_name\": \"Alessandro\",\n \"last_name\": \"Nesta\",\n \"common_name\": \"Nesta\",\n \"height\": 187,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 27,\n \"club\": 112658,\n \"rarity\": 84,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CB\",\n \"skill_moves\": 2,\n \"weak_foot\": 3,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"MED\",\n \"defense_work_rate\": \"HIGH\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 73,\n \"pace\": 74,\n \"shooting\": 43,\n \"passing\": 67,\n \"dribbling\": 70,\n \"defending\": 96,\n \"physicality\": 89,\n \"pace_attributes\": {\n \"acceleration\": 75,\n \"sprint_speed\": 73\n },\n \"shooting_attributes\": {\n \"positioning\": 38,\n \"finishing\": 40,\n \"shot_power\": 51,\n \"long_shots\": 40,\n \"volleys\": 44,\n \"penalties\": 48\n },\n \"passing_attributes\": {\n \"vision\": 59,\n \"crossing\": 57,\n \"free_kick_accuracy\": 34,\n \"short_passing\": 83,\n \"long_passing\": 73,\n \"curve\": 47\n },\n \"dribbling_attributes\": {\n \"agility\": 42,\n \"balance\": 53,\n \"reactions\": 90,\n \"ball_control\": 80,\n \"dribbling\": 68,\n \"composure\": 79\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 89,\n \"standing_tackle\": 97,\n \"sliding_tackle\": 98\n },\n \"physicality_attributes\": {\n \"jumping\": 85,\n \"stamina\": 84,\n \"strength\": 93,\n \"aggression\": 88\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93976,\n \"resource_id\": 246509,\n \"name\": \"Stoichkov\",\n \"age\": None,\n \"resource_base_id\": 246509,\n \"fut_bin_id\": 28703,\n \"fut_wiz_id\": 19820,\n \"first_name\": \"Hristo\",\n \"last_name\": \"Stoichkov\",\n \"common_name\": \"Stoichkov\",\n \"height\": 178,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 9,\n \"club\": 112658,\n \"rarity\": 84,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"ST\",\n \"skill_moves\": 4,\n \"weak_foot\": 3,\n \"foot\": \"Left\",\n \"attack_work_rate\": \"MED\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 85,\n \"pace\": 94,\n \"shooting\": 95,\n \"passing\": 89,\n \"dribbling\": 94,\n \"defending\": 52,\n \"physicality\": 88,\n \"pace_attributes\": {\n \"acceleration\": 95,\n \"sprint_speed\": 93\n },\n \"shooting_attributes\": {\n \"positioning\": 95,\n \"finishing\": 96,\n \"shot_power\": 95,\n \"long_shots\": 95,\n \"volleys\": 93,\n \"penalties\": 92\n },\n \"passing_attributes\": {\n \"vision\": 90,\n \"crossing\": 87,\n \"free_kick_accuracy\": 97,\n \"short_passing\": 89,\n \"long_passing\": 84,\n \"curve\": 95\n },\n \"dribbling_attributes\": {\n \"agility\": 93,\n \"balance\": 85,\n \"reactions\": 91,\n \"ball_control\": 95,\n \"dribbling\": 95,\n \"composure\": 92\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 85,\n \"standing_tackle\": 54,\n \"sliding_tackle\": 49\n },\n \"physicality_attributes\": {\n \"jumping\": 81,\n \"stamina\": 89,\n \"strength\": 85,\n \"aggression\": 94\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93977,\n \"resource_id\": 246527,\n \"name\": \"Del Piero\",\n \"age\": None,\n \"resource_base_id\": 246527,\n \"fut_bin_id\": 28702,\n \"fut_wiz_id\": 19822,\n \"first_name\": \"Alessandro\",\n \"last_name\": \"Del Piero\",\n \"common_name\": \"Del Piero\",\n \"height\": 174,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 27,\n \"club\": 112658,\n \"rarity\": 84,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CF\",\n \"skill_moves\": 4,\n \"weak_foot\": 5,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 79,\n \"pace\": 85,\n \"shooting\": 94,\n \"passing\": 92,\n \"dribbling\": 94,\n \"defending\": 44,\n \"physicality\": 69,\n \"pace_attributes\": {\n \"acceleration\": 86,\n \"sprint_speed\": 84\n },\n \"shooting_attributes\": {\n \"positioning\": 96,\n \"finishing\": 97,\n \"shot_power\": 90,\n \"long_shots\": 93,\n \"volleys\": 88,\n \"penalties\": 99\n },\n \"passing_attributes\": {\n \"vision\": 96,\n \"crossing\": 91,\n \"free_kick_accuracy\": 99,\n \"short_passing\": 92,\n \"long_passing\": 83,\n \"curve\": 96\n },\n \"dribbling_attributes\": {\n \"agility\": 86,\n \"balance\": 67,\n \"reactions\": 91,\n \"ball_control\": 97,\n \"dribbling\": 97,\n \"composure\": 95\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 77,\n \"standing_tackle\": 43,\n \"sliding_tackle\": 37\n },\n \"physicality_attributes\": {\n \"jumping\": 59,\n \"stamina\": 84,\n \"strength\": 67,\n \"aggression\": 60\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93998,\n \"resource_id\": 100845817,\n \"name\": \"Toni Kroos\",\n \"age\": None,\n \"resource_base_id\": 182521,\n \"fut_bin_id\": 28751,\n \"fut_wiz_id\": 19844,\n \"first_name\": \"Toni\",\n \"last_name\": \"Kroos\",\n \"common_name\": \"Kroos\",\n \"height\": 183,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 53,\n \"nation\": 21,\n \"club\": 243,\n \"rarity\": 51,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CM\",\n \"skill_moves\": 3,\n \"weak_foot\": 5,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"MED\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 83,\n \"pace\": 78,\n \"shooting\": 89,\n \"passing\": 95,\n \"dribbling\": 88,\n \"defending\": 76,\n \"physicality\": 76,\n \"pace_attributes\": {\n \"acceleration\": 82,\n \"sprint_speed\": 75\n },\n \"shooting_attributes\": {\n \"positioning\": 84,\n \"finishing\": 84,\n \"shot_power\": 98,\n \"long_shots\": 94,\n \"volleys\": 90,\n \"penalties\": 80\n },\n \"passing_attributes\": {\n \"vision\": 94,\n \"crossing\": 92,\n \"free_kick_accuracy\": 88,\n \"short_passing\": 97,\n \"long_passing\": 97,\n \"curve\": 90\n },\n \"dribbling_attributes\": {\n \"agility\": 80,\n \"balance\": 87,\n \"reactions\": 94,\n \"ball_control\": 94,\n \"dribbling\": 85,\n \"composure\": 93\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 61,\n \"standing_tackle\": 78,\n \"sliding_tackle\": 63\n },\n \"physicality_attributes\": {\n \"jumping\": 34,\n \"stamina\": 87,\n \"strength\": 80,\n \"aggression\": 64\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93243,\n \"resource_id\": 134426450,\n \"name\": \"Sadio Mané\",\n \"age\": None,\n \"resource_base_id\": 208722,\n \"fut_bin_id\": 27987,\n \"fut_wiz_id\": 18897,\n \"first_name\": \"Sadio\",\n \"last_name\": \"Mané\",\n \"common_name\": \"Mané\",\n \"height\": 175,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 13,\n \"nation\": 136,\n \"club\": 9,\n \"rarity\": 64,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"LW\",\n \"skill_moves\": 4,\n \"weak_foot\": 4,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 82,\n \"pace\": 97,\n \"shooting\": 90,\n \"passing\": 85,\n \"dribbling\": 93,\n \"defending\": 47,\n \"physicality\": 81,\n \"pace_attributes\": {\n \"acceleration\": 98,\n \"sprint_speed\": 96\n },\n \"shooting_attributes\": {\n \"positioning\": 97,\n \"finishing\": 95,\n \"shot_power\": 89,\n \"long_shots\": 83,\n \"volleys\": 79,\n \"penalties\": 75\n },\n \"passing_attributes\": {\n \"vision\": 90,\n \"crossing\": 82,\n \"free_kick_accuracy\": 69,\n \"short_passing\": 90,\n \"long_passing\": 75,\n \"curve\": 81\n },\n \"dribbling_attributes\": {\n \"agility\": 96,\n \"balance\": 89,\n \"reactions\": 96,\n \"ball_control\": 92,\n \"dribbling\": 94,\n \"composure\": 87\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 89,\n \"standing_tackle\": 45,\n \"sliding_tackle\": 41\n },\n \"physicality_attributes\": {\n \"jumping\": 91,\n \"stamina\": 94,\n \"strength\": 75,\n \"aggression\": 79\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 92228,\n \"resource_id\": 10535,\n \"name\": \"Hernández Creus\",\n \"age\": None,\n \"resource_base_id\": 10535,\n \"fut_bin_id\": 26870,\n \"fut_wiz_id\": None,\n \"first_name\": None,\n \"last_name\": None,\n \"common_name\": \"Xavi\",\n \"height\": None,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 45,\n \"club\": 112658,\n \"rarity\": 12,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CM\",\n \"skill_moves\": None,\n \"weak_foot\": None,\n \"foot\": None,\n \"attack_work_rate\": None,\n \"defense_work_rate\": None,\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 82,\n \"pace\": 81,\n \"shooting\": 80,\n \"passing\": 95,\n \"dribbling\": 93,\n \"defending\": 72,\n \"physicality\": 72,\n \"pace_attributes\": {\n \"acceleration\": None,\n \"sprint_speed\": None\n },\n \"shooting_attributes\": {\n \"positioning\": None,\n \"finishing\": None,\n \"shot_power\": None,\n \"long_shots\": None,\n \"volleys\": None,\n \"penalties\": None\n },\n \"passing_attributes\": {\n \"vision\": None,\n \"crossing\": None,\n \"free_kick_accuracy\": None,\n \"short_passing\": None,\n \"long_passing\": None,\n \"curve\": None\n },\n \"dribbling_attributes\": {\n \"agility\": None,\n \"balance\": None,\n \"reactions\": None,\n \"ball_control\": None,\n \"dribbling\": None,\n \"composure\": None\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": None,\n \"standing_tackle\": None,\n \"sliding_tackle\": None\n },\n \"physicality_attributes\": {\n \"jumping\": None,\n \"stamina\": None,\n \"strength\": None,\n \"aggression\": None\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93265,\n \"resource_id\": 50385698,\n \"name\": \"Wayne Rooney\",\n \"age\": None,\n \"resource_base_id\": 54050,\n \"fut_bin_id\": 28002,\n \"fut_wiz_id\": 18914,\n \"first_name\": \"Wayne\",\n \"last_name\": \"Rooney\",\n \"common_name\": \"Rooney\",\n \"height\": 176,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 14,\n \"nation\": 14,\n \"club\": 91,\n \"rarity\": 25,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"ST\",\n \"skill_moves\": 4,\n \"weak_foot\": 4,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 87,\n \"pace\": 87,\n \"shooting\": 95,\n \"passing\": 88,\n \"dribbling\": 91,\n \"defending\": 71,\n \"physicality\": 90,\n \"pace_attributes\": {\n \"acceleration\": 89,\n \"sprint_speed\": 86\n },\n \"shooting_attributes\": {\n \"positioning\": 91,\n \"finishing\": 94,\n \"shot_power\": 99,\n \"long_shots\": 94,\n \"volleys\": 97,\n \"penalties\": 95\n },\n \"passing_attributes\": {\n \"vision\": 91,\n \"crossing\": 90,\n \"free_kick_accuracy\": 93,\n \"short_passing\": 84,\n \"long_passing\": 90,\n \"curve\": 87\n },\n \"dribbling_attributes\": {\n \"agility\": 86,\n \"balance\": 80,\n \"reactions\": 95,\n \"ball_control\": 94,\n \"dribbling\": 91,\n \"composure\": 99\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 95,\n \"standing_tackle\": 70,\n \"sliding_tackle\": 51\n },\n \"physicality_attributes\": {\n \"jumping\": 82,\n \"stamina\": 90,\n \"strength\": 90,\n \"aggression\": 91\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 92264,\n \"resource_id\": 167198,\n \"name\": \"Éric Cantona\",\n \"age\": None,\n \"resource_base_id\": 167198,\n \"fut_bin_id\": 985,\n \"fut_wiz_id\": None,\n \"first_name\": None,\n \"last_name\": None,\n \"common_name\": \"Cantona\",\n \"height\": None,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 18,\n \"club\": 112658,\n \"rarity\": 12,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CF\",\n \"skill_moves\": None,\n \"weak_foot\": None,\n \"foot\": None,\n \"attack_work_rate\": None,\n \"defense_work_rate\": None,\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 85,\n \"pace\": 89,\n \"shooting\": 93,\n \"passing\": 90,\n \"dribbling\": 93,\n \"defending\": 53,\n \"physicality\": 92,\n \"pace_attributes\": {\n \"acceleration\": None,\n \"sprint_speed\": None\n },\n \"shooting_attributes\": {\n \"positioning\": None,\n \"finishing\": None,\n \"shot_power\": None,\n \"long_shots\": None,\n \"volleys\": None,\n \"penalties\": None\n },\n \"passing_attributes\": {\n \"vision\": None,\n \"crossing\": None,\n \"free_kick_accuracy\": None,\n \"short_passing\": None,\n \"long_passing\": None,\n \"curve\": None\n },\n \"dribbling_attributes\": {\n \"agility\": None,\n \"balance\": None,\n \"reactions\": None,\n \"ball_control\": None,\n \"dribbling\": None,\n \"composure\": None\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": None,\n \"standing_tackle\": None,\n \"sliding_tackle\": None\n },\n \"physicality_attributes\": {\n \"jumping\": None,\n \"stamina\": None,\n \"strength\": None,\n \"aggression\": None\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 93039,\n \"resource_id\": 84120476,\n \"name\": \"Alphonso Davies\",\n \"age\": None,\n \"resource_base_id\": 234396,\n \"fut_bin_id\": 27949,\n \"fut_wiz_id\": 18847,\n \"first_name\": \"Alphonso\",\n \"last_name\": \"Davies\",\n \"common_name\": \"Davies\",\n \"height\": 181,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 19,\n \"nation\": 70,\n \"club\": 21,\n \"rarity\": 5,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"LB\",\n \"skill_moves\": 4,\n \"weak_foot\": 4,\n \"foot\": \"Left\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 91,\n \"pace\": 99,\n \"shooting\": 83,\n \"passing\": 89,\n \"dribbling\": 96,\n \"defending\": 91,\n \"physicality\": 90,\n \"pace_attributes\": {\n \"acceleration\": 99,\n \"sprint_speed\": 99\n },\n \"shooting_attributes\": {\n \"positioning\": 93,\n \"finishing\": 83,\n \"shot_power\": 88,\n \"long_shots\": 78,\n \"volleys\": 73,\n \"penalties\": 74\n },\n \"passing_attributes\": {\n \"vision\": 88,\n \"crossing\": 94,\n \"free_kick_accuracy\": 57,\n \"short_passing\": 99,\n \"long_passing\": 75,\n \"curve\": 86\n },\n \"dribbling_attributes\": {\n \"agility\": 99,\n \"balance\": 96,\n \"reactions\": 92,\n \"ball_control\": 92,\n \"dribbling\": 99,\n \"composure\": 87\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 77,\n \"standing_tackle\": 92,\n \"sliding_tackle\": 95\n },\n \"physicality_attributes\": {\n \"jumping\": 91,\n \"stamina\": 94,\n \"strength\": 88,\n \"aggression\": 91\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 92018,\n \"resource_id\": 84074625,\n \"name\": \"Robert Lewandowski\",\n \"age\": None,\n \"resource_base_id\": 188545,\n \"fut_bin_id\": 26634,\n \"fut_wiz_id\": 17853,\n \"first_name\": \"Robert\",\n \"last_name\": \"Lewandowski\",\n \"common_name\": \"Lewandowski\",\n \"height\": 184,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 19,\n \"nation\": 37,\n \"club\": 21,\n \"rarity\": 42,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"ST\",\n \"skill_moves\": 4,\n \"weak_foot\": 4,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 79,\n \"pace\": 80,\n \"shooting\": 93,\n \"passing\": 82,\n \"dribbling\": 89,\n \"defending\": 45,\n \"physicality\": 85,\n \"pace_attributes\": {\n \"acceleration\": 79,\n \"sprint_speed\": 80\n },\n \"shooting_attributes\": {\n \"positioning\": 96,\n \"finishing\": 96,\n \"shot_power\": 91,\n \"long_shots\": 87,\n \"volleys\": 91,\n \"penalties\": 90\n },\n \"passing_attributes\": {\n \"vision\": 83,\n \"crossing\": 75,\n \"free_kick_accuracy\": 89,\n \"short_passing\": 88,\n \"long_passing\": 74,\n \"curve\": 83\n },\n \"dribbling_attributes\": {\n \"agility\": 80,\n \"balance\": 85,\n \"reactions\": 96,\n \"ball_control\": 91,\n \"dribbling\": 88,\n \"composure\": 91\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 89,\n \"standing_tackle\": 44,\n \"sliding_tackle\": 20\n },\n \"physicality_attributes\": {\n \"jumping\": 87,\n \"stamina\": 79,\n \"strength\": 89,\n \"aggression\": 84\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 90778,\n \"resource_id\": 996,\n \"name\": \"Éric Cantona\",\n \"age\": None,\n \"resource_base_id\": 996,\n \"fut_bin_id\": 985,\n \"fut_wiz_id\": 734,\n \"first_name\": \"Eric\",\n \"last_name\": \"Cantona\",\n \"common_name\": \"Cantona\",\n \"height\": 188,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 18,\n \"club\": 112658,\n \"rarity\": 12,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CF\",\n \"skill_moves\": 0,\n \"weak_foot\": 0,\n \"foot\": \"\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 85,\n \"pace\": 89,\n \"shooting\": 93,\n \"passing\": 90,\n \"dribbling\": 93,\n \"defending\": 53,\n \"physicality\": 92,\n \"pace_attributes\": {\n \"acceleration\": 0,\n \"sprint_speed\": 0\n },\n \"shooting_attributes\": {\n \"positioning\": 0,\n \"finishing\": 0,\n \"shot_power\": 0,\n \"long_shots\": 0,\n \"volleys\": 0,\n \"penalties\": 0\n },\n \"passing_attributes\": {\n \"vision\": 0,\n \"crossing\": 0,\n \"free_kick_accuracy\": 0,\n \"short_passing\": 0,\n \"long_passing\": 0,\n \"curve\": 0\n },\n \"dribbling_attributes\": {\n \"agility\": 0,\n \"balance\": 0,\n \"reactions\": 0,\n \"ball_control\": 0,\n \"dribbling\": 0,\n \"composure\": 0\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 0,\n \"standing_tackle\": 0,\n \"sliding_tackle\": 0\n },\n \"physicality_attributes\": {\n \"jumping\": 0,\n \"stamina\": 0,\n \"strength\": 0,\n \"aggression\": 0\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 90779,\n \"resource_id\": 166906,\n \"name\": \"Franco Baresi\",\n \"age\": None,\n \"resource_base_id\": 166906,\n \"fut_bin_id\": 63,\n \"fut_wiz_id\": 90,\n \"first_name\": \"Franco\",\n \"last_name\": \"Baresi\",\n \"common_name\": \"Baresi\",\n \"height\": 176,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 27,\n \"club\": 112658,\n \"rarity\": 12,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CB\",\n \"skill_moves\": 0,\n \"weak_foot\": 0,\n \"foot\": \"\",\n \"attack_work_rate\": \"MED\",\n \"defense_work_rate\": \"HIGH\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 74,\n \"pace\": 70,\n \"shooting\": 49,\n \"passing\": 76,\n \"dribbling\": 72,\n \"defending\": 95,\n \"physicality\": 82,\n \"pace_attributes\": {\n \"acceleration\": 0,\n \"sprint_speed\": 0\n },\n \"shooting_attributes\": {\n \"positioning\": 0,\n \"finishing\": 0,\n \"shot_power\": 0,\n \"long_shots\": 0,\n \"volleys\": 0,\n \"penalties\": 0\n },\n \"passing_attributes\": {\n \"vision\": 0,\n \"crossing\": 0,\n \"free_kick_accuracy\": 0,\n \"short_passing\": 0,\n \"long_passing\": 0,\n \"curve\": 0\n },\n \"dribbling_attributes\": {\n \"agility\": 0,\n \"balance\": 0,\n \"reactions\": 0,\n \"ball_control\": 0,\n \"dribbling\": 0,\n \"composure\": 0\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 0,\n \"standing_tackle\": 0,\n \"sliding_tackle\": 0\n },\n \"physicality_attributes\": {\n \"jumping\": 0,\n \"stamina\": 0,\n \"strength\": 0,\n \"aggression\": 0\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 90780,\n \"resource_id\": 238435,\n \"name\": \"Lothar Matthäus\",\n \"age\": None,\n \"resource_base_id\": 238435,\n \"fut_bin_id\": 121,\n \"fut_wiz_id\": 167,\n \"first_name\": \"Lothar\",\n \"last_name\": \"Matthaus\",\n \"common_name\": \"Matthäus\",\n \"height\": 174,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 2118,\n \"nation\": 21,\n \"club\": 112658,\n \"rarity\": 12,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"CM\",\n \"skill_moves\": 0,\n \"weak_foot\": 0,\n \"foot\": \"\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"HIGH\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 87,\n \"pace\": 89,\n \"shooting\": 89,\n \"passing\": 90,\n \"dribbling\": 82,\n \"defending\": 90,\n \"physicality\": 85,\n \"pace_attributes\": {\n \"acceleration\": 0,\n \"sprint_speed\": 0\n },\n \"shooting_attributes\": {\n \"positioning\": 0,\n \"finishing\": 0,\n \"shot_power\": 0,\n \"long_shots\": 0,\n \"volleys\": 0,\n \"penalties\": 0\n },\n \"passing_attributes\": {\n \"vision\": 0,\n \"crossing\": 0,\n \"free_kick_accuracy\": 0,\n \"short_passing\": 0,\n \"long_passing\": 0,\n \"curve\": 0\n },\n \"dribbling_attributes\": {\n \"agility\": 0,\n \"balance\": 0,\n \"reactions\": 0,\n \"ball_control\": 0,\n \"dribbling\": 0,\n \"composure\": 0\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 0,\n \"standing_tackle\": 0,\n \"sliding_tackle\": 0\n },\n \"physicality_attributes\": {\n \"jumping\": 0,\n \"stamina\": 0,\n \"strength\": 0,\n \"aggression\": 0\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 92076,\n \"resource_id\": 67129665,\n \"name\": \"Cristiano Ronaldo\",\n \"age\": None,\n \"resource_base_id\": 20801,\n \"fut_bin_id\": 26692,\n \"fut_wiz_id\": None,\n \"first_name\": None,\n \"last_name\": None,\n \"common_name\": \"Ronaldo\",\n \"height\": None,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 31,\n \"nation\": 38,\n \"club\": 114153,\n \"rarity\": 3,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"ST\",\n \"skill_moves\": None,\n \"weak_foot\": None,\n \"foot\": None,\n \"attack_work_rate\": None,\n \"defense_work_rate\": None,\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 78,\n \"pace\": 90,\n \"shooting\": 94,\n \"passing\": 83,\n \"dribbling\": 91,\n \"defending\": 36,\n \"physicality\": 78,\n \"pace_attributes\": {\n \"acceleration\": None,\n \"sprint_speed\": None\n },\n \"shooting_attributes\": {\n \"positioning\": None,\n \"finishing\": None,\n \"shot_power\": None,\n \"long_shots\": None,\n \"volleys\": None,\n \"penalties\": None\n },\n \"passing_attributes\": {\n \"vision\": None,\n \"crossing\": None,\n \"free_kick_accuracy\": None,\n \"short_passing\": None,\n \"long_passing\": None,\n \"curve\": None\n },\n \"dribbling_attributes\": {\n \"agility\": None,\n \"balance\": None,\n \"reactions\": None,\n \"ball_control\": None,\n \"dribbling\": None,\n \"composure\": None\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": None,\n \"standing_tackle\": None,\n \"sliding_tackle\": None\n },\n \"physicality_attributes\": {\n \"jumping\": None,\n \"stamina\": None,\n \"strength\": None,\n \"aggression\": None\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 91622,\n \"resource_id\": 50489671,\n \"name\": \"Lionel Messi\",\n \"age\": None,\n \"resource_base_id\": 158023,\n \"fut_bin_id\": 25795,\n \"fut_wiz_id\": 16943,\n \"first_name\": \"Lionel\",\n \"last_name\": \"Messi\",\n \"common_name\": \"Messi\",\n \"height\": 170,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 53,\n \"nation\": 52,\n \"club\": 241,\n \"rarity\": 48,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"RW\",\n \"skill_moves\": 4,\n \"weak_foot\": 4,\n \"foot\": \"Left\",\n \"attack_work_rate\": \"MED\",\n \"defense_work_rate\": \"LOW\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 77,\n \"pace\": 85,\n \"shooting\": 92,\n \"passing\": 91,\n \"dribbling\": 95,\n \"defending\": 38,\n \"physicality\": 65,\n \"pace_attributes\": {\n \"acceleration\": 91,\n \"sprint_speed\": 80\n },\n \"shooting_attributes\": {\n \"positioning\": 93,\n \"finishing\": 95,\n \"shot_power\": 86,\n \"long_shots\": 94,\n \"volleys\": 88,\n \"penalties\": 75\n },\n \"passing_attributes\": {\n \"vision\": 95,\n \"crossing\": 85,\n \"free_kick_accuracy\": 94,\n \"short_passing\": 91,\n \"long_passing\": 91,\n \"curve\": 93\n },\n \"dribbling_attributes\": {\n \"agility\": 91,\n \"balance\": 95,\n \"reactions\": 94,\n \"ball_control\": 96,\n \"dribbling\": 96,\n \"composure\": 96\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 70,\n \"standing_tackle\": 35,\n \"sliding_tackle\": 24\n },\n \"physicality_attributes\": {\n \"jumping\": 68,\n \"stamina\": 72,\n \"strength\": 69,\n \"aggression\": 44\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n },\n {\n \"id\": 92402,\n \"resource_id\": 100851841,\n \"name\": \"Robert Lewandowski\",\n \"age\": None,\n \"resource_base_id\": 188545,\n \"fut_bin_id\": 27095,\n \"fut_wiz_id\": 18173,\n \"first_name\": \"Robert\",\n \"last_name\": \"Lewandowski\",\n \"common_name\": \"Lewandowski\",\n \"height\": 184,\n \"weight\": None,\n \"birth_date\": None,\n \"league\": 19,\n \"nation\": 37,\n \"club\": 21,\n \"rarity\": 3,\n \"traits\": [],\n \"specialities\": [],\n \"tradeable\": True,\n \"position\": \"ST\",\n \"skill_moves\": 4,\n \"weak_foot\": 4,\n \"foot\": \"Right\",\n \"attack_work_rate\": \"HIGH\",\n \"defense_work_rate\": \"MED\",\n \"total_stats\": None,\n \"total_stats_in_game\": None,\n \"rating\": 93,\n \"rating_average\": 79,\n \"pace\": 81,\n \"shooting\": 93,\n \"passing\": 82,\n \"dribbling\": 88,\n \"defending\": 45,\n \"physicality\": 85,\n \"pace_attributes\": {\n \"acceleration\": 80,\n \"sprint_speed\": 81\n },\n \"shooting_attributes\": {\n \"positioning\": 96,\n \"finishing\": 96,\n \"shot_power\": 91,\n \"long_shots\": 87,\n \"volleys\": 91,\n \"penalties\": 90\n },\n \"passing_attributes\": {\n \"vision\": 83,\n \"crossing\": 75,\n \"free_kick_accuracy\": 89,\n \"short_passing\": 88,\n \"long_passing\": 74,\n \"curve\": 83\n },\n \"dribbling_attributes\": {\n \"agility\": 79,\n \"balance\": 84,\n \"reactions\": 95,\n \"ball_control\": 90,\n \"dribbling\": 87,\n \"composure\": 90\n },\n \"defending_attributes\": {\n \"interceptions\": None,\n \"heading_accuracy\": 89,\n \"standing_tackle\": 44,\n \"sliding_tackle\": 20\n },\n \"physicality_attributes\": {\n \"jumping\": 87,\n \"stamina\": 79,\n \"strength\": 89,\n \"aggression\": 84\n },\n \"goalkeeper_attributes\": {\n \"diving\": None,\n \"handling\": None,\n \"kicking\": None,\n \"positioning\": None,\n \"reflexes\": None\n }\n }\n ]\n}\n\nfor value in jogador[\"items\"]:\n print(value[\"first_name\"])\n print(value[\"common_name\"])\n print(value[\"last_name\"])\n print(value[\"foot\"])\n print(value[\"name\"])\n print(value[\"shooting\"])\n print(value[\"passing\"])\n print(value[\"shooting_attributes\"][\"shot_power\"])\n print()\n","sub_path":"Python/objto_json_players.py","file_name":"objto_json_players.py","file_ext":"py","file_size_in_byte":41566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"296480179","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'virtual'\n\nfrom ...schema import *\n\n\nclass ApiGroups(Base):\n\n __tablename__ = 'api_groups'\n\n __table_args__ = {'extend_existing': True, }\n\n gid = Column(Integer, primary_key=True)\n gidup = Column(Integer, ForeignKey(\"api_groups.gid\"))\n g_name = Column(String(4000))\n domainid = Column(Integer)\n\n def __repr__(self):\n return ('[%d]%s' % (self.id, self.g_name, )).encode('utf-8')\n","sub_path":"addons/onyma/schema/onyma/apigroups.py","file_name":"apigroups.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"139586884","text":"# -*- coding: utf-8 -*-\n\nimport pytest\nfrom hamcrest import assert_that, equal_to_ignoring_whitespace, is_\n\nfrom hermes.comments import CommentsApi\nfrom hermes.helpers.random_data_generator import TextHelper\n\n\nclass TestNegativeCommentParams(object):\n\n @pytest.mark.parametrize('sentiment', [0.5, -0.5, 100500, ''])\n def test_negative_set_sentiment(self, logged_client, sentiment, config):\n code, result = CommentsApi.set_sentiment(config['comment4']['id'],\n sentiment)\n assert_that(code, is_(422),\n 'Expected that code is \"%s\", but was \"%s\".' % (422, code))\n if sentiment == 100500:\n sentiment = float(sentiment)\n err_msg = 'not a valid value for sentiment: %s' % sentiment\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that error is \"%s\", but was \"%s\".' % (\n err_msg, result\n ))\n\n @pytest.mark.parametrize('workflow', ['super', 123, '$%#@!'])\n def test_negative_set_workflow_state(self, logged_client, workflow,\n config):\n code, result = CommentsApi.set_workflow(config['comment4']['id'],\n workflow)\n assert_that(code, is_(422),\n 'Expected that code is \"%s\", but was \"%s\".' % (422, code))\n err_msg = 'not a valid value for workflow_state: %s' % workflow\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that error is \"%s\", but was \"%s\".' % (\n err_msg, result['error']\n ))\n\n @pytest.mark.parametrize('user_id', [100500, 'abc', None, ''])\n def test_negative_set_assign(self, logged_client, user_id, config):\n comment_id = config['comment2']['id']\n code, result = CommentsApi.set_assign(comment_id, user_id)\n assert_that(code, is_(400),\n 'Expected that code is \"%s\", but was \"%s\".' % (400, code))\n if user_id is None:\n user_id = ''\n msg = 'User #%s not found' % user_id\n assert_that(result['error'], equal_to_ignoring_whitespace(msg),\n 'Expected that message is \"%s\", but was \"%s\".' % (\n msg, result['error']\n ))\n\n @pytest.mark.parametrize('comment_id', ['abc', '!a2'])\n def test_negative_set_comment(self, logged_client, comment_id):\n code, result = CommentsApi.set_comment(comment_id,\n TextHelper.get_random_text(10))\n assert_that(code, is_(404),\n 'Expected that code is \"%s\", but was \"%s\".' % (404, code))\n err_msg = 'TextResponse with the id: %s was not found' % comment_id\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that err msg is \"%s\", but was \"%s\".' % (\n err_msg, result['error']\n ))\n\n @pytest.mark.parametrize('comment_id', ['abc', '!a2'])\n def test_negative_sentiment_set_by_not_valid_comment_id(self, comment_id,\n logged_client,\n config):\n code, result = CommentsApi.set_sentiment(\n comment_id=comment_id, sentiment=1)\n assert_that(code, is_(422),\n 'Expected that code is \"%s\", but was \"%s\".' % (422, code))\n err_msg = 'not a valid value for patient_comment_id: %s' % comment_id\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that err msg is \"%s\", but was \"%s\".' % (\n err_msg, result['error']\n ))\n\n @pytest.mark.parametrize('comment_id', ['abc', '!a2'])\n def test_negative_work_flow_by_not_valid_comment_id(self, logged_client,\n config, comment_id):\n code, result = CommentsApi.set_workflow(\n comment_id=comment_id, workflow_state='resolved')\n assert_that(code, is_(422),\n 'Expected that code is \"%s\", but was \"%s\".' % (422, code))\n err_msg = 'not a valid value for patient_comment_id: %s' % comment_id\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that err msg is \"%s\", but was \"%s\".' % (\n err_msg, result['error']\n ))\n","sub_path":"hermes_api_tests/tests/comments/test_negative_crud_comment_params.py","file_name":"test_negative_crud_comment_params.py","file_ext":"py","file_size_in_byte":4602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"337188051","text":"import salt.exceptions\n\ndef set_value(name, key, value):\n '''\n Change a value of a key in a YAML document\n\n name\n The YAML file to modify\n key\n The key to modify. Can specify the whole path, with tokens delimited by '/'\n value\n The new value \n '''\n\n ret = {\n 'name': name,\n 'changes': {},\n 'result': True,\n 'comment': '',\n 'pchanges': {},\n }\n\n current_yaml = __salt__['yaml.load_yaml'](name)\n current_value = __salt__['yaml.get_value'](current_yaml, key)\n\n if current_value == value:\n ret['result'] = True\n ret['comment'] = 'The key \\'' + key + '\\' already has the value \\'' + value + '\\''\n return ret\n\n if __opts__['test'] == True:\n ret['comment'] = 'The value of \\'' + key + '\\' will be changed'\n ret['pchanges'] = {\n 'old': current_value,\n 'new': value,\n }\n \n ret['result'] = None\n\n return ret\n \n new_state = __salt__['yaml.modify_yaml'](current_yaml, key, value)\n\n __salt__['yaml.save_yaml'](current_yaml, name)\n\n ret['comment'] = 'The state of \"{0}\" was changed!'.format(name)\n\n ret['changes'] = {\n 'old': current_value,\n 'new': value,\n }\n\n ret['result'] = True \n\n return ret","sub_path":"patroni/vagrant/salt/roots/_states/yaml_config.py","file_name":"yaml_config.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"246145340","text":"#!/usr/bin/python3.3\nfrom tkinter import *\nfrom tkinter.messagebox import *\nimport math\n\n#Initialise le mobile et l'affiche\ndef startMobile(mobile):\n if type(mobile) is not Poid:\n mobile.setDistance()\n afficher(canvas, mobile)\n\n#Lit un fichier et reconnais le format, renvoi le mobile contruit\ndef lireFichier():\n global mobile\n nom = nomFichier.get()\n fichier = open(nom, \"r\")\n if fichier == None:\n showwarning(\"Echec\", \"Aucun fichier de ce nom est présent\")\n return\n lignes = fichier.readlines()\n fichier.close()\n if len(lignes) == 0:\n showwarning(\"Echec\", \"Le fichier est vide\")\n return\n if len(lignes) == 1:\n l = eval(lignes[0])\n mobile = constrMobile(l)\n else:\n l = list()\n for i in lignes:\n k = i[:-1]\n if len(k) > 0:\n l.append(int(k))\n mobile = constrParDiffEquilibre(l)\n \n startMobile(mobile)\n\n#Sauvegarde le mobile dans le fichier\ndef saveMobile():\n global mobile\n nom = nomFichierSave.get()\n fichier = open(nom, \"w\")\n fichier.write(str(mobile))\n print(\"TEST : {}\".format(mobile))\n fichier.close()\n\n#Sauvegarde de la liste des poids d'un mobile dans un fichier\ndef saveList():\n global mobile\n nom = nomFichierSave.get()\n fichier = open(nom, \"w\")\n l = list()\n mobile.toList(l)\n for i in l:\n fichier.write(str(i)+\"\\n\")\n fichier.write(\"\\n\")\n fichier.close()\n\n#Construit le mobile selon une liste d'un mobile déjà formé\ndef constrMobile(l):\n\tn = Noeud()\n\tif type(l[0]) is int:\n\t n.gauche = Poid(l[0])\n\telif type(l[0]) is list:\n\t n.gauche = constrMobile(l[0])\n\tif len(l) < 2:\n\t return n.gauche\n\t\n\tif type(l[1]) is int:\n\t n.droit = Poid(l[1])\n\telif type(l[1]) is list:\n\t n.droit = constrMobile(l[1])\n\treturn n\n\n#Construit le mobile selon un algorithme d'arbre équilibré d'une profondeur minimale\ndef constrParDiffEquilibre(l):\n n = Noeud()\n if len(l) < 2:\n n = Poid(l[0])\n return n\n n.gauche = Poid(l[0])\n n.droit = Poid(l[1])\n \n for i in range(2, len(l)):\n n = n.constrParDiffEquilibre(l[i])\n \n return n\n\n#Affiche le mobile n dans la zone de dessin\ndef afficher(canvas, n):\n width = canvas.winfo_width()\n height = canvas.winfo_height()\n canvas.delete(\"all\")\n echelle = 0.5\n echellePoid = (min(width, height)*0.8//len(n))//n.maximum()\n echelleH = height*0.8//n.profondeur()\n \n if type(n) is Poid:\n canvas.create_line(width//2, 0, width//2, height*0.2)\n longueur = echellePoid*n.valeur\n canvas.create_oval(width//2 - longueur//2, height*0.2, width//2 + longueur//2, height*0.2+longueur)\n else:\n \tcanvas.create_line(width*n.valeur, 0, width*n.valeur, height*0.1)\n \tdessineNoeud(canvas, n, width//2, height*0.1, echelle, echellePoid, echelleH)\n \n canvas.update()\n \n#Dessine un noeud de l'arbre représentant le mobile n dans la zone de dessin\ndef dessineNoeud(canvas, n, x, y, echelle, echellePoid, echelleH):\n width = canvas.winfo_width()\n height = canvas.winfo_height()\n xG = x - width*echelle*n.valeur\n xD = xG+echelle*width\n canvas.create_line(xG, y, xD, y)\n canvas.create_line(xG, y, xG, y+echelleH)\n canvas.create_line(xD, y, xD, y+echelleH)\n \n if type(n.droit) is Poid:\n longueur = echellePoid*n.droit.valeur\n canvas.create_oval(xD-longueur//2, y+echelleH, xD+longueur//2, y+echelleH+longueur)\n canvas.create_text(xD, y+echelleH+longueur//2, text=str(n.droit))\n else:\n dessineNoeud(canvas, n.droit, xD, y+echelleH, echelle*echelle, echellePoid, echelleH)\n if type(n.gauche) is Poid:\n longueur = echellePoid*n.gauche.valeur\n canvas.create_oval(xG-longueur//2, y+echelleH, xG+longueur//2, y+echelleH+longueur)\n canvas.create_text(xG, y+echelleH+longueur//2, text=str(n.gauche))\n else:\n dessineNoeud(canvas, n.gauche, xG, y+echelleH, echelle*echelle, echellePoid, echelleH)\n \n\n#### NOEUD ####\nclass Noeud:\n \n def __init__(self):\n self.valeur = 0\n self.gauche = None\n self.droit = None\n \n def __str__(self):\n return \"[\"+str(self.gauche)+\",\"+str(self.droit)+\"]\"\n \n def __getattr__(self, nom):\n print(\"Pas d'attribut \",nom,\" dans un objet Poid\")\n \n def peser(self):\n return self.gauche.peser() + self.droit.peser()\n \n def setDistance(self):\n if type(self.gauche) is Noeud:\n self.gauche.setDistance()\n if type(self.droit) is Noeud:\n self.droit.setDistance()\n self.valeur = self.droit.peser() / (self.gauche.peser()+self.droit.peser())\n print(\"VALEUR = {}\".format(+self.valeur))\n \n def maximum(self):\n g = self.gauche.maximum()\n d = self.droit.maximum()\n if g > d:\n return g\n else:\n return d\n \n def __len__(self):\n return len(self.gauche) + len(self.droit)\n \n def profondeur(self):\n g = self.gauche.profondeur()\n d = self.droit.profondeur()\n if g > d:\n return g+1\n else:\n return d+1\n \n def constrParDiffEquilibre(self, v):\n poidG = self.gauche.peser()\n poidD = self.droit.peser()\n if v >= (poidG+poidD):\n n = Noeud()\n n.gauche = self\n n.droit = Poid(v)\n return n\n if poidG == poidD:\n if self.gauche.profondeur() > self.droit.profondeur():\n self.droit = self.droit.constrParDiffEquilibre(v)\n else:\n self.gauche = self.gauche.constrParDiffEquilibre(v)\n elif poidG > poidD :\n self.droit = self.droit.constrParDiffEquilibre(v)\n else:\n self.gauche = self.gauche.constrParDiffEquilibre(v)\n return self\n \n def toList(self, l):\n self.gauche.toList(l)\n self.droit.toList(l)\n\n\n#### POID ####\nclass Poid(Noeud):\n \n def __init__(self, v):\n self.valeur = v\n \n def __str__(self):\n return str(self.valeur)\n \n def __getattr__(self, nom):\n print(\"Pas d'attribut \",nom,\" dans un objet Poid\")\n \n def peser(self):\n return self.valeur\n \n def maximum(self):\n return self.valeur\n \n def __len__(self):\n return 1\n \n def profondeur(self):\n return 1\n \n def constrParDiffEquilibre(self, v):\n p = Noeud()\n p.gauche = self\n p.droit = Poid(v)\n return p\n \n def toList(self, l):\n l.append(self.valeur)\n \n\n#### MAIN ####\n\nif __name__ == \"__main__\":\n #mobile\n mobile = Noeud()\n\n #création de la fenêtre\n fenetre = Tk()\n\n #création de la zone de paramétrage\n param = Frame(fenetre, borderwidth=2)\n param.pack(pady=10)\n paramLecture = LabelFrame(param, borderwidth=2, text=\"Charger un fichier\")\n paramLecture.pack(side=LEFT, padx=10)\n paramSave = LabelFrame(param, borderwidth=2, text=\"Sauvegarder un mobile\")\n paramSave.pack(side=LEFT, padx=10)\n \n #Zone de lecture d'un fichier\n labelFichier = Label(paramLecture, text=\"Nom du fichier\")\n labelFichier.pack(side=LEFT, padx=10, pady=10)\n nomFichier = StringVar()\n entreeFichier = Entry(paramLecture, textvariable=nomFichier)\n entreeFichier.pack(side=LEFT, padx=10, pady=10)\n boutonFichier = Button(paramLecture, text=\"Charger\", command=lireFichier)\n boutonFichier.pack(side=LEFT, padx=10, pady=10)\n \n #Zone de sauvegarde d'un mobile\n labelFichierSave = Label(paramSave, text=\"Nom du fichier\")\n labelFichierSave.pack(side=LEFT, padx=10, pady=10)\n nomFichierSave = StringVar()\n entreeFichierSave = Entry(paramSave, textvariable=nomFichierSave)\n entreeFichierSave.pack(side=LEFT, padx=10, pady=10)\n boutonFichierSave = Button(paramSave, text=\"Sauvegarder\", command=saveMobile)\n boutonFichierSave.pack(side=LEFT, padx=10, pady=10)\n\n #création du canvas\n canvas = Canvas(fenetre,width=800, height=600, background=\"white\")\n canvas.pack()\n canvas.update()\n\n fenetre.mainloop()\n","sub_path":"mobile.py","file_name":"mobile.py","file_ext":"py","file_size_in_byte":8100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"57655045","text":"from collections import OrderedDict\nimport glob\n\nfrom ...Operation import Operation\nfrom ... import Operation as opmod \nfrom ... import optools\n\nclass BatchPostProcess(Operation):\n \"\"\"\n Take the batch output (list of dicts) from a previously completed Batch,\n and use each dict to form inputs for the execution of a post-processing workflow.\n For each item to be taken from the previous batch, two keys are needed:\n one key indicates a previous batch workflow output, \n and another indicates the corresponding current workflow input.\n \"\"\"\n\n def __init__(self):\n input_names = ['batch_output','output_keys','workflow','input_keys']\n output_names = ['batch_inputs','batch_outputs']\n super(BatchPostProcess,self).__init__(input_names,output_names)\n self.input_doc['batch_output'] = 'list of dicts produced as batch output from another batch execution operation'\n self.input_doc['output_keys'] = 'list of keys for harvesting batch outputs (must be outputs of the previous batch workflow)'\n self.input_doc['workflow'] = 'a reference to the workflow to be executed in this batch'\n self.input_doc['input_keys'] = 'list of keys for setting workflow inputs, in corresponding order to output_keys'\n self.output_doc['batch_inputs'] = 'list of dicts of input_key:input_value for each of the input_keys'\n self.output_doc['batch_outputs'] = 'list of dicts of workflow outputs'\n self.input_type['workflow'] = opmod.entire_workflow\n self.input_type['batch_output'] = opmod.workflow_item\n \n def run(self):\n \"\"\"\n Build a list of [uri:value] dicts to be used in the workflow.\n \"\"\"\n batch_output = self.inputs['batch_output']\n out_keys = self.inputs['output_keys']\n inp_keys = self.inputs['input_keys']\n wf = self.inputs['workflow']\n if (wf is None or batch_output is None or out_keys is None or inp_keys is None):\n return\n self.outputs['batch_inputs'] = []\n self.outputs['batch_outputs'] = []\n n_batch = len(batch_output)\n for d_out in batch_output:\n inp_dict = OrderedDict() \n for kout,kin in zip(out_keys,inp_keys):\n inp_dict[kin] = d_out[kout]\n wf.set_wf_input(kin,d_out[kout])\n wf.execute()\n self.outputs['batch_inputs'].append(inp_dict)\n self.outputs['batch_outputs'].append(wf.wf_outputs_dict())\n\n","sub_path":"paws/core/operations/EXECUTION/BATCH/BatchPostProcess.py","file_name":"BatchPostProcess.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"34338403","text":"import sys\nimport re\nimport os\n\ndef mix_points(in_original, in_mixin):\n for mix_point in in_mixin:\n for orig_point in in_original:\n if points_equal(mix_point[1:], orig_point[1:]):\n orig_point[0] = mix_point[0]\n\ndef relabel_points(in_original, in_new_labels):\n for point, label in zip(in_original, in_new_labels):\n point[0] = label\n\ndef points_equal(in_a, in_b):\n return abs(max([float(a) - float(b) for a, b in zip(in_a, in_b)])) < 1e-6\n\ndef process_original_data(in_stream):\n processed_result = []\n for line in in_stream:\n # making line format proper for visualizing, not calculations\n line = re.sub(',', '\\.', line)\n line_split = [term.split(':')[-1] for term in line.strip().split()]\n processed_result.append(line_split)\n return processed_result\n\ndef process_model_data(in_stream):\n processed_result = []\n for line in in_stream:\n line = re.sub(',', '\\.', line)\n line_split = line.strip().split()\n if len(line_split) > 2:\n line_split_filtered = [term.split(':')[-1] for term in line_split]\n line_split_filtered[0] = '4'\n processed_result.append(line_split_filtered)\n return processed_result\n\ndef process_prediction_data(in_stream):\n return ['1' if line.strip() == '1' else '2' for line in in_stream]\n\ndef write_original_data_file(in_original_data, out_stream):\n for line in in_original_data:\n print >>out_stream, '\\t'.join(line[:-1]) + '\\t' + line[-1]\n\ndef write_sv_data_file(in_original_data, in_model_data, out_stream):\n new_original_data = in_original_data[:]\n mix_points(new_original_data, in_model_data)\n for line in new_original_data:\n print >>out_stream, '\\t'.join(line[:-1]) + '\\t' + line[-1]\n\ndef write_prediction_data_file(in_original_data, in_prediction_data, out_stream):\n new_original_data = in_original_data[:]\n relabel_points(new_original_data, in_prediction_data)\n\n for line in new_original_data:\n print >>out_stream, '\\t'.join(line[:-1]) + '\\t' + line[-1]\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 4:\n exit('Usage: collect_data.py <original data file> <model file> <prediction file>')\n original_data = process_original_data(open(sys.argv[1]))\n model_data = process_model_data(open(sys.argv[2]))\n prediction_data = process_prediction_data(open(sys.argv[3]))\n \n write_original_data_file(original_data, open(os.path.basename(sys.argv[1]) + '.original', 'w'))\n write_sv_data_file(original_data, model_data, open(os.path.basename(sys.argv[1]) + '.sv', 'w'))\n write_prediction_data_file(original_data, prediction_data, open(os.path.basename(sys.argv[1]) + '.prediction', 'w'))\n\n","sub_path":"collect_data.py","file_name":"collect_data.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"122125466","text":"# -*- coding: utf-8 -*-\n\n#\n# MIT License\n#\n# Copyright (c) 2018 Milan Cermak <cermak@ics.muni.cz>, Institute of Computer Science, Masaryk University\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\nimport math # Mathematical functions\n\n\ndef get_distance(vector, configuration):\n \"\"\"\n Compute Quadratic form distance of given vector and patterns specified in the configuration.\n\n :param vector: vector that is compared with patterns specified in configuration\n :param configuration: loaded application configuration\n :return: Dictionary of pattern names and its distances from given vector\n \"\"\"\n distances = {}\n for pattern in configuration['distance']['patterns']:\n request_distance = sum([((v - p) / p) ** 2 for v, p in zip(vector['vector']['request'], pattern['request'])])\n response_distance = sum([((v - p) / p) ** 2 for v, p in zip(vector['vector']['response'], pattern['response'])])\n distance = math.sqrt(request_distance + response_distance)\n distances[pattern['name']] = distance\n return {'distances': distances}\n","sub_path":"applications/detection/pattern_finder/spark/modules/distance_functions/biflow_quadratic_form.py","file_name":"biflow_quadratic_form.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"637788917","text":"import keyboard\nimport json\nimport time\n\nfrom random import randint\n\nDEBUG = True\nbanner = \"\"\" __ ___ __ \n __ /\\\\ \\\\ __ /\\\\_ \\\\ /\\\\ \\\\__ \n/\\\\_\\\\ __ __\\\\ \\\\ \\\\____ /\\\\_\\\\\\\\//\\\\ \\\\ __ ___ \\\\ \\\\ ,_\\\\ \n\\\\/\\\\ \\\\ /\\\\ \\\\/\\\\ \\\\\\\\ \\\\ '__`\\\\\\\\/\\\\ \\\\ \\\\ \\\\ \\\\ /'__`\\\\ /' _ `\\\\\\\\ \\\\ \\\\/ \n \\\\ \\\\ \\\\\\\\ \\\\ \\\\_\\\\ \\\\\\\\ \\\\ \\\\L\\\\ \\\\\\\\ \\\\ \\\\ \\\\_\\\\ \\\\_ /\\\\ \\\\L\\\\.\\\\_ /\\\\ \\\\/\\\\ \\\\\\\\ \\\\ \\\\_ \n _\\\\ \\\\ \\\\\\\\ \\\\____/ \\\\ \\\\_,__/ \\\\ \\\\_\\\\/\\\\____\\\\\\\\ \\\\__/.\\\\_\\\\\\\\ \\\\_\\\\ \\\\_\\\\\\\\ \\\\__\\\\\n/\\\\ \\\\_\\\\ \\\\\\\\/___/ \\\\/___/ \\\\/_/\\\\/____/ \\\\/__/\\\\/_/ \\\\/_/\\\\/_/ \\\\/__/\n\\\\ \\\\____/ \n \\\\/___/ \n\n __ \n /\\\\ \\\\ __ \n ___ \\\\ \\\\ \\\\___ __ /\\\\_\\\\ ___ ____ __ __ __ __ \n /'___\\\\\\\\ \\\\ _ `\\\\ /'__`\\\\ \\\\/\\\\ \\\\ /' _ `\\\\ /',__\\\\ /'__`\\\\ /\\\\ \\\\/\\\\ \\\\/\\\\ \\\\ \n/\\\\ \\\\__/ \\\\ \\\\ \\\\ \\\\ \\\\ /\\\\ \\\\L\\\\.\\\\_\\\\ \\\\ \\\\ /\\\\ \\\\/\\\\ \\\\ /\\\\__, `\\\\/\\\\ \\\\L\\\\.\\\\_\\\\ \\\\ \\\\_/ \\\\_/ \\\\\n\\\\ \\\\____\\\\ \\\\ \\\\_\\\\ \\\\_\\\\\\\\ \\\\__/.\\\\_\\\\\\\\ \\\\_\\\\\\\\ \\\\_\\\\ \\\\_\\\\\\\\/\\\\____/\\\\ \\\\__/.\\\\_\\\\\\\\ \\\\___x___/'\n \\\\/____/ \\\\/_/\\\\/_/ \\\\/__/\\\\/_/ \\\\/_/ \\\\/_/\\\\/_/ \\\\/___/ \\\\/__/\\\\/_/ \\\\/__//__/ \n\"\"\"\nsquad = []\n\n\n# Load config\nwith open('config.json') as configFile:\n config = json.load(configFile)\n\n\n# Define core functions\ndef selectMerc():\n while True:\n search = input(\"Type in the name of a Merc: \")\n if search.lower() in (merc.lower() for merc in config['mercs'].keys()):\n return search.lower().capitalize()\n else:\n print(\"I couldn't find that merc, please check your spelling or check your config\")\n\n\ndef setupSquad():\n if DEBUG == True:\n return [\"Aura\", \"Skyhammer\", \"Proxy\"]\n squad = []\n \n print(\"First slot:\")\n squad.append(selectMerc())\n \n print(\"Second slot:\")\n squad.append(selectMerc())\n\n print(\"Third slot:\")\n squad.append(selectMerc())\n \n return squad\n\n\ndef callVote():\n print(\"Calling a vote!\")\n\n expireTime = time.time() + float(config['general']['voteTimeout'])\n votes = {\n squad[0]: 0,\n squad[1]: 0,\n squad[2]: 0,\n }\n while time.time() < expireTime:\n votes[list(votes.keys())[randint(0, 2)]] += 1\n\n numberToBeat = 0\n winners = []\n for k,v in votes.items():\n if v > numberToBeat:\n numberToBeat = v\n winners = [k]\n elif v == numberToBeat:\n winners.append(k)\n \n\n if len(winners) > 1:\n print(\"There was a tie\")\n winner = winners[randint(0,len(winners)-1)]\n else:\n winner = winners[0]\n\n\n print(winner, \"Wins with\", numberToBeat,\"votes!\")\n selected = squad.index(winner)\n if selected == 0:\n print(\"Pressing\", config[\"game\"][\"selectFirstMercKeybind\"])\n keyboard.press_and_release(config[\"game\"][\"selectFirstMercKeybind\"])\n elif selected == 1:\n print(\"Pressing\", config[\"game\"][\"selectSecondMercKeybind\"])\n keyboard.press_and_release(config[\"game\"][\"selectSecondMercKeybind\"])\n elif selected == 2:\n print(\"Pressing\", config[\"game\"][\"selectThirdMercKeybind\"])\n keyboard.press_and_release(config[\"game\"][\"selectThirdMercKeybind\"])\n \n\n# Add keyboard listeners\nkeyboard.add_hotkey('ctrl+shift+v', callVote)\n\n\n# Run the program\nif __name__ == '__main__':\n print(banner)\n squad = setupSquad()\n keyboard.wait()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"395020635","text":"# # #coding=utf-8\n# #\n# # class Myclass():\n# # name=\"sum\"\n# #\n# # def Sayhi(self):\n# # print('hello')\n# #\n# #\n# # #实例化类\n# # a=Myclass()\n# # #调用类里面的方法\n# # a.Sayhi()\n# # coding: utf8\n#\n# # @Author: 郭 璞\n# # @File: DLUTLibraryLogin.py\n# # @Time: 2017/4/7\n# # @Contact: 1064319632@qq.com\n# # @blog: http://blog.csdn.net/marksinoberg\n# # @Description: 大连理工大学图书馆模拟登陆,添加了验证码识别脚本\n#\n# import BeautifulSoup\n# import pytesseract\n# import requests.sessions\n# from PIL import Image\n#\n# loginurl = 'http://opac.lib.dlut.edu.cn/reader/redr_verify.php'\n# captchaurl = 'http://opac.lib.dlut.edu.cn/reader/captcha.php'\n#\n# headers = {\n# 'Referer': 'http://opac.lib.dlut.edu.cn/reader/login.php',\n# \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36\",\n# }\n#\n# s= requests.Session()\n# ##### 获取到验证码并保存\n# checkcodecontent = s.get(captchaurl, headers=headers)\n#\n# with open('checkcode.jpg', 'wb') as f:\n# f.write(checkcodecontent.content)\n# f.close()\n# print('验证码已写入到本地!', '下面开始调用tesseract-OCR引擎识别验证码!')\n#\n# img = Image.open('checkcode.jpg', mode='r')\n# result = pytesseract.image_to_string(image=img)\n# checkcode = result\n# print('验证码为:', checkcode)\n#\n# # os.startfile('checkcode.jpg')\n# # checkcode = input('请输入验证码:')\n# ##### 准备登陆图书馆系统\n# payload = {\n# 'number':'学号',\n# 'passwd':'密码',\n# 'captcha': checkcode,\n# 'select':'cert_no'\n# }\n#\n# response = s.post(loginurl, headers=headers, data=payload)\n# print('服务器端返回码: ', response.status_code)\n# soup = BeautifulSoup(response.text, 'html.parser')\n# ## 打印当前用户\n# username = soup.find('font', {'color': 'blue'})\n# print(username.get_text())\n# ## 打印积分信息\n# jifen = soup.find_all('span', {'class': 'bigger-170'})[3]\n# jifen = str(jifen.get_text())\n# print('当前登录用户总积分:', jifen)\n#coding:utf-8\nfrom selenium import webdriver\n# a=dict['Chrome','Firefox']\nbrowser = webdriver.Firefox()\nbase_url = \"http://www.senbaba.cn\"\nbrowser.get(base_url)\nbrowser.maximize_window()\ntry:\n browser.save_screenshot(\"F:\\\\BugP\\\\chrome.png\")\nexcept:\n print(\"error\")\nbrowser.close()\n","sub_path":"接口测试/Interface/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"368164602","text":"import math, random\n\nimport gym\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.autograd as autograd\nimport torch.nn.functional as F\n\nfrom collections import deque\n\nfrom IPython.display import clear_output\n# import matplotlib.pyplot as plt\n# plt.ion()\n\nclass ReplayBuffer(object):\n def __init__(self, capacity):\n self.buffer = deque(maxlen=capacity)\n\n def push(self, state, action, reward, next_state, done):\n state = np.expand_dims(state, 0)\n next_state = np.expand_dims(next_state, 0)\n\n self.buffer.append((state, action, reward, next_state, done))\n\n def sample(self, batch_size):\n state, action, reward, next_state, done = zip(*random.sample(self.buffer, batch_size))\n return np.concatenate(state), action, reward, np.concatenate(next_state), done\n\n def __len__(self):\n return len(self.buffer)\n\nclass DQN(nn.Module):\n def __init__(self, num_inputs, num_actions):\n super(DQN, self).__init__()\n self.num_inputs = num_inputs\n self.num_actions = num_actions\n self.layers = nn.Sequential(\n nn.Linear(num_inputs, 128),\n nn.ReLU(),\n nn.Linear(128, 128),\n nn.ReLU(),\n nn.Linear(128, num_actions)\n )\n\n def forward(self, x):\n return self.layers(x)\n\n def act(self, state, epsilon):\n with torch.no_grad():\n if random.random() > epsilon:\n state = torch.FloatTensor(state).unsqueeze(0).to('cuda')\n q_value = self.forward(state)\n action = q_value.max(1)[1].data[0].item()\n else:\n action = random.randrange(self.num_actions)\n return action\n\nclass StateSimulator(nn.Module):\n def __init__(self, num_inputs, num_actions):\n super(StateSimulator, self).__init__()\n # predict num_actions * ([state, reward, done])\n self.num_inputs = num_inputs\n self.num_actions = num_actions\n self.layers = nn.Sequential(\n nn.Linear(num_inputs, 128),\n nn.ReLU(),\n nn.Linear(128, 128),\n nn.ReLU(),\n nn.Linear(128, num_actions * (num_inputs + 2))\n )\n\n def forward(self, x):\n batch_size = x.size(0)\n y = self.layers(x)\n y = y.view(batch_size, self.num_actions, -1)\n pred_next_states = y[..., :self.num_inputs]\n pred_rewards = y[..., self.num_inputs]\n pred_dones = F.sigmoid(y[..., self.num_inputs + 1])\n return pred_next_states, pred_rewards, pred_dones\n\n def step(self, state, action):\n # state is a numpy array\n with torch.no_grad():\n state = torch.FloatTensor(state).unsqueeze(0).to('cuda')\n batch_size = state.size(0)\n y = self.layers(state)\n y = y.view(batch_size, self.num_actions, -1)\n pred_next_states = y[..., :self.num_inputs]\n pred_rewards = y[..., self.num_inputs]\n pred_dones = F.sigmoid(y[..., self.num_inputs + 1])\n\n pred_next_state = pred_next_states[0, action, :].cpu().numpy()\n pred_reward = pred_rewards[0, action].cpu().item()\n pred_done = (pred_dones[0, action] > 0.5).cpu().item()\n pred_done = bool(pred_done)\n\n return pred_next_state, pred_reward, pred_done\n\n\ndef compute_td_loss(batch_size, replay_buffer, optimizer, model, gamma):\n state, action, reward, next_state, done = replay_buffer.sample(batch_size)\n\n state = autograd.Variable(torch.FloatTensor(np.float32(state))).cuda()\n next_state = autograd.Variable(torch.FloatTensor(np.float32(next_state)), volatile=True).cuda()\n action = autograd.Variable(torch.LongTensor(action)).cuda()\n reward = autograd.Variable(torch.FloatTensor(reward)).cuda()\n done = autograd.Variable(torch.FloatTensor(done)).cuda()\n\n q_values = model(state)\n next_q_values = model(next_state)\n\n q_value = q_values.gather(1, action.unsqueeze(1)).squeeze(1)\n next_q_value = next_q_values.max(1)[0]\n expected_q_value = reward + gamma * next_q_value * (1 - done)\n\n loss = (q_value - autograd.Variable(expected_q_value.data)).pow(2).mean()\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n return loss\n\ndef compute_simulator_loss(batch_size, replay_buffer, optimizer, model, gamma):\n state, action, reward, next_state, done = replay_buffer.sample(batch_size)\n\n state = autograd.Variable(torch.FloatTensor(np.float32(state))).cuda()\n next_state = autograd.Variable(torch.FloatTensor(np.float32(next_state)), volatile=True).cuda()\n action = autograd.Variable(torch.LongTensor(action)).cuda()\n reward = autograd.Variable(torch.FloatTensor(reward)).cuda()\n done = autograd.Variable(torch.FloatTensor(done)).cuda()\n\n pred_next_states, pred_rewards, pred_dones = model(state)\n indexes = torch.arange(0, batch_size).long()\n pred_next_state = pred_next_states[indexes, action, :]\n pred_reward = pred_rewards[indexes, action]\n pred_done = pred_dones[indexes, action]\n\n\n loss_state = (pred_next_state - next_state).pow(2).mean()\n loss_reward = (pred_reward - reward).pow(2).mean()\n loss_done = nn.BCELoss()(pred_done, done)\n\n loss = loss_state + loss_reward + loss_done\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n return loss\n\ndef plot(frame_idx, rewards, losses):\n # clear_output(True)\n plt.clf()\n # plt.figure(figsize=(20,5))\n # plt.subplot(131)\n plt.title('frame %s. reward: %s' % (frame_idx, np.mean(rewards[-10:])))\n plt.plot(rewards)\n # plt.subplot(132)\n # plt.title('loss')\n # plt.plot(losses)\n plt.pause(0.001)\n\ndef main():\n env_id = \"CartPole-v0\"\n env = gym.make(env_id)\n\n epsilon_start = 1.0\n epsilon_final = 0.01\n epsilon_decay = 500\n\n epsilon_by_frame = lambda frame_idx: epsilon_final + (epsilon_start - epsilon_final) * math.exp(\n -1. * frame_idx / epsilon_decay)\n\n q_net = DQN(env.observation_space.shape[0], env.action_space.n)\n simulator = StateSimulator(env.observation_space.shape[0], env.action_space.n)\n\n optimizer_q_net = optim.Adam(q_net.parameters(), lr=1e-03)\n optimizer_simulator = optim.Adam(simulator.parameters(), lr=1e-03)\n\n replay_buffer_q_net = ReplayBuffer(1000)\n replay_buffer_simulator = ReplayBuffer(1000)\n\n num_frames = 100000\n batch_size = 32\n gamma = 0.99\n\n # fig = plt.figure(figsize=(20, 5))\n\n losses_q_learning = []\n losses_simulator = []\n all_rewards = []\n episode_reward = 0\n\n state = env.reset()\n state_simulator = env.reset()\n\n q_net = q_net.cuda()\n simulator = simulator.cuda()\n for frame_idx in range(1, num_frames + 1):\n epsilon = epsilon_by_frame(frame_idx)\n action = q_net.act(state, epsilon)\n\n next_state, reward, done, _ = env.step(action)\n replay_buffer_simulator.push(state, action, reward, next_state, done)\n\n next_state_simu, reward_simu, done_simu = simulator.step(state_simulator, action)\n replay_buffer_q_net.push(state_simulator, action, reward_simu, next_state_simu, done)\n\n state = next_state\n state_simulator = next_state_simu\n episode_reward += reward\n\n if done:\n state = env.reset()\n state_simulator = env.reset()\n all_rewards.append(episode_reward)\n episode_reward = 0\n\n if len(replay_buffer_q_net) > batch_size:\n loss = compute_td_loss(batch_size, replay_buffer_q_net, optimizer_q_net, q_net, gamma)\n losses_q_learning.append(loss.data[0])\n\n if len(replay_buffer_simulator) > batch_size:\n loss_simu = compute_simulator_loss(batch_size, replay_buffer_simulator, optimizer_simulator, simulator, gamma)\n losses_simulator.append(loss_simu.data[0])\n\n # if frame_idx % 200 == 0:\n # plot(frame_idx, all_rewards, losses_q_learning)\n\n\nif __name__ == '__main__':\n main()","sub_path":"dqn_simulator.py","file_name":"dqn_simulator.py","file_ext":"py","file_size_in_byte":7980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"332888847","text":"class Solution:\n def shortestDistance(self, grid):\n if not grid or not grid[0]:\n return -1\n\n DIRECTIONS = [(1, 0), (-1, 0), (0, -1), (0, 1)]\n M, N = len(grid), len(grid[0])\n n_buildings = sum(val for row in grid for val in row if val == 1)\n hit = [[0] * N for _ in range(M)]\n dist_sum = [[0] * N for _ in range(M)]\n\n def bfs(x, y):\n visited = [[False] * N for _ in range(M)]\n visited[x][y] = True\n cnt = 1\n dq = collections.deque([(x, y, 0)])\n while dq:\n i, j, dist = dq.popleft()\n for di, dj in DIRECTIONS:\n new_i, new_j, new_dist = i + di, j + dj, dist + 1\n if 0 <= new_i < M and 0 <= new_j < N and not visited[new_i][new_j]:\n visited[new_i][new_j] = True\n if grid[new_i][new_j] == 0:\n dq.append((new_i, new_j, new_dist))\n dist_sum[new_i][new_j] += new_dist\n hit[new_i][new_j] += 1\n if grid[new_i][new_j] == 1:\n cnt += 1\n return cnt == n_buildings\n\n if not all(bfs(x, y) for x in range(M) for y in range(N) if grid[x][y] == 1):\n return -1\n\n return min([dist_sum[x][y] for x in range(M) for y in range(N) if grid[x][y] == 0 and hit[x][y] == n_buildings] or [-1])\n","sub_path":"leetcode/py/317.py","file_name":"317.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"437551362","text":"#SUPPORT VECTOR MACHINE\nimport math\nimport random\nimport pickle\nfrom os import path\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.feature_selection import SelectKBest, f_regression, mutual_info_classif\nfrom sklearn import svm\n\nimport matplotlib.pyplot as plt\n\nx_ticks=[]\nk_accuracies=[]\nk_recalls=[]\n\nproba_threshold = 0.5\n\naccuracies= []\nrecalls = []\ncredit_data_df = pd.read_csv(\"data/dev_data.csv\")\n\n# create a dataframe of zeros | example rslt_df = dataframe[dataframe['Percentage'] > 80]\ncredit_data_df_legit = credit_data_df[credit_data_df['Class'] == 0]\n# create a dataframe of 1s only |\ncredit_data_df_fraud = credit_data_df[credit_data_df['Class'] == 1]\n\nfeature_headers = ['Time', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21', 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28', 'Amount']\n\nrandom_seeds = [23]#, 34]#, 1, 56]#, 67, 45, 6]\n\nlb_range=range(1, 21)\nfor load_balancing_ratio in lb_range:\n accuracies = []\n recalls = []\n numberOfOnes = credit_data_df_fraud.shape[0]\n # **load-balancing**\n numberOfZeros = math.floor(load_balancing_ratio * numberOfOnes)\n for rs in random_seeds:\n print(rs)\n # choose a random sample of zeros\n credit_data_df_legit_random = credit_data_df_legit.sample(numberOfZeros, random_state=rs)\n\n # merge the above with the ones and do the rest of the pipeline with it\n result = credit_data_df_legit_random.append(credit_data_df_fraud)\n\n # **load-balancing**\n\n # create dataframe X, which includes variables time, amount, V1, V2, V3, V4 (dtataframe subsetin)\n X = result[feature_headers]\n\n # create array y, which includes the classification only\n y = result['Class']\n\n select_kbest = SelectKBest(mutual_info_classif, k=5)\n X_new = select_kbest.fit_transform(X, y)\n mask = select_kbest.get_support()\n\n # use sklearn to split the X and y, into X_train, X_test, y_train y_test with 80/20 split\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=rs, stratify=y)\n\n clf = svm.SVC(C=1, kernel='linear', cache_size=7000, probability=True, random_state=rs, class_weight='balanced')\n clf.fit(X_train, y_train)\n ml_object = [clf, mask]\n\n # use the model\n #pickle.dump(model_and_features, open(path.join('models', 'svm.pkl'), 'wb'))\n probs = clf.predict_proba(X_test)\n preds = probs[:, 1]\n #if probability is above the threshold classify as a 1\n y_pred = [1 if x >= proba_threshold else 0 for x in preds]\n\n # use sklearn metrics to judge accuracy of model using test data\n acc = accuracy_score(y_test, y_pred)\n accuracies.append(acc)\n # output score\n print(acc)\n\n # precision / recall\n # confusion matrix |\n # https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html\n target_names = ['class 0', 'class 1']\n print(confusion_matrix(y_test, y_pred))\n tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()\n print((tn, fp, fn, tp))\n\n recall = tp / (tp + fn)\n recalls.append(recall)\n print(classification_report(y_test, y_pred, target_names=target_names))\n\n fpr, tpr, threshold = metrics.roc_curve(y_test, preds)\n roc_auc = metrics.auc(fpr, tpr)\n\n observations_df = pd.DataFrame(columns = ['y_true', 'prediction', 'proba'])\n observations_df['y_true'] = y_test\n observations_df['prediction'] = y_pred\n observations_df['proba'] = preds\n # method I: plt\n #plot_roc()\n\n #Threshold\n #ROC prob\n mean_accuracy = np.mean(np.array(accuracies))\n mean_recall = np.mean(np.array(recalls))\n print('accuracy mean = ' + str(mean_accuracy))\n print('recall mean = ' + str(mean_recall))\n k_accuracies.append(mean_accuracy)\n k_recalls.append(mean_recall)\n\n\n\nplt.plot(lb_range, k_accuracies)\nplt.ylabel('Accuracies')\nplt.xlabel('Load-Balancing Ratio')\nplt.title('SVM Load-Balancing Test on Accuracies')\nplt.xticks(lb_range)\nplt.show()\n\nplt.plot(lb_range, k_recalls)\nplt.ylabel('Recalls')\nplt.title('SVM Load-Balancing Test on Recalls')\nplt.xticks(lb_range)\nplt.xlabel('Load-Balancing Ratio')\nplt.show()\n\n","sub_path":"LBR_Tests/OLD/SVM_LB_OLD2.py","file_name":"SVM_LB_OLD2.py","file_ext":"py","file_size_in_byte":4581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"188838895","text":"#coding:utf-8\nimport requests\n\n\nclass HTMLDownloader(object):\n\n # Download the html of certain word on Youdao Website\n def download(self, url):\n try:\n # Parse the header\n user_agent = \"Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)\"\n headers = {'User-Agent': user_agent}\n r = requests.get(url, headers=headers)\n if r.status_code == 200:\n r.encoding = 'utf-8'\n return r\n except:\n raise Exception(\"could not open the website!\")","sub_path":"HTMLDownloader.py","file_name":"HTMLDownloader.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"284911226","text":"from haystack import Finder\nfrom haystack.database.elasticsearch import ElasticsearchDocumentStore\n\nfrom haystack.retriever.elasticsearch import EmbeddingRetriever\nfrom haystack.reader.transformers import TransformersReader\nfrom haystack.utils import print_answers\nfrom haystack.indexing.cleaning import clean_wiki_text\nfrom haystack.indexing.utils import convert_files_to_dicts\nimport pandas as pd\nimport requests\nimport logging\nimport subprocess\nimport time\nimport os\n\n\nif __name__ == '__main__':\n # Start new server or connect to a running one. true and false respectively\n LAUNCH_ELASTICSEARCH = False\n # Determines whether the Elasticsearch Server has to be populated with data or not\n POPULATE_DOCUMENT_STORE = False\n\n if LAUNCH_ELASTICSEARCH:\n logging.info(\"Starting Elasticsearch ...\")\n status = subprocess.run(\n ['docker run -d -p 9200:9200 -e \"disScovery.type=single-node\" elasticsearch:7.6.2'], shell=True\n )\n if status.returncode:\n raise Exception(\"Failed to launch Elasticsearch. If you want to connect to an existing Elasticsearch instance\"\n \"then set LAUNCH_ELASTICSEARCH in the script to False.\")\n time.sleep(15)\n\n # Init the DocumentStore\n #\n # * specify the name of our `text_field` in Elasticsearch that we want to return as an answer\n # * specify the name of our `embedding_field` in Elasticsearch where we'll store the embedding of our question and that is used later for calculating our similarity to the incoming user question\n # * set `excluded_meta_data=[\"question_emb\"]` so that we don't return the huge embedding vectors in our search results\n\n document_store = ElasticsearchDocumentStore(host=\"localhost\", username=\"\", password=\"\",\n index=\"document\",\n text_field=\"text\",\n embedding_field=\"question_emb\",\n embedding_dim=768,\n excluded_meta_data=[\"question_emb\"])\n\n # Create a Retriever using embeddings\n # Instead of retrieving via Elasticsearch's plain BM25, we want to use vector similarity of the questions (user question vs. FAQ ones).\n # We can use the `EmbeddingRetriever` for this purpose and specify a model that we use for the embeddings.\n #\n retriever = EmbeddingRetriever(\n document_store=document_store, embedding_model=\"deepset/sentence_bert\", gpu=True)\n\n if POPULATE_DOCUMENT_STORE:\n # set path to directory conating the text files\n doc_dir = os.getcwd() + \"\\\\kbQA\\\\data\\\\article_txt_got\"\n # convert files to dicts containing documents that can be indexed to our datastore\n dicts = convert_files_to_dicts(\n dir_path=doc_dir, clean_func=clean_wiki_text, split_paragraphs=True)\n\n df = pd.DataFrame.from_dict(dicts)\n # Get embeddings for our questions from the FAQs\n questions = list(df[\"text\"].values)\n df[\"question_emb\"] = retriever.create_embedding(texts=questions)\n\n # Convert Dataframe to list of dicts and index them in our DocumentStore\n docs_to_index = df.to_dict(orient=\"records\")\n # You can optionally supply a cleaning function that is applied to each doc (e.g. to remove footers)\n # It must take a str as input, and return a str.\n\n # Now, let's write the docs to our DB.\n document_store.write_documents(docs_to_index)\n\n reader = TransformersReader(\n model=\"distilbert-base-uncased-distilled-squad\", tokenizer=\"distilbert-base-uncased\", use_gpu=-1)\n\n # Init reader & and use Finder to get answer (same as in Tutorial 1)\n finder = Finder(reader=reader, retriever=retriever)\n\n prediction = finder.get_answers(\n question=\"Who is the father of Arya?\", top_k_reader=3, top_k_retriever=5)\n\n print_answers(prediction, details=\"all\")\n","sub_path":"kbQA/kbQA_embeddings.py","file_name":"kbQA_embeddings.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"620781991","text":"\"\"\"\nPyInvoke developer task file\nhttps://www.pyinvoke.org/\n\nThese tasks can be run using `invoke <NAME>` or `inv <NAME>` from the project root.\n\nTo show all available tasks `invoke --list`\n\nTo show task help page `invoke <NAME> --help`\n\"\"\"\nimport json\nimport os\nimport pathlib\nimport shutil\n\nimport invoke\n\nfrom scripts import check_type_hint_coverage\n\ntry:\n from tests.integration.usage_statistics import usage_stats_utils\n\n is_ge_installed: bool = True\nexcept ModuleNotFoundError:\n is_ge_installed = False\n\n_CHECK_HELP_DESC = \"Only checks for needed changes without writing back. Exit with error code if changes needed.\"\n_EXCLUDE_HELP_DESC = \"Exclude files or directories\"\n_PATH_HELP_DESC = \"Target path. (Default: .)\"\n\n\n@invoke.task(\n help={\n \"check\": _CHECK_HELP_DESC,\n \"exclude\": _EXCLUDE_HELP_DESC,\n \"path\": _PATH_HELP_DESC,\n }\n)\ndef sort(ctx, path=\".\", check=False, exclude=None):\n \"\"\"Sort module imports.\"\"\"\n cmds = [\"isort\", path]\n if check:\n cmds.append(\"--check-only\")\n if exclude:\n cmds.extend([\"--skip\", exclude])\n ctx.run(\" \".join(cmds), echo=True)\n\n\n@invoke.task(\n help={\n \"check\": _CHECK_HELP_DESC,\n \"exclude\": _EXCLUDE_HELP_DESC,\n \"path\": _PATH_HELP_DESC,\n \"sort\": \"Disable import sorting. Runs by default.\",\n }\n)\ndef fmt(ctx, path=\".\", sort_=True, check=False, exclude=None):\n \"\"\"\n Run code formatter.\n \"\"\"\n if sort_:\n sort(ctx, path, check=check, exclude=exclude)\n\n cmds = [\"black\", path]\n if check:\n cmds.append(\"--check\")\n if exclude:\n cmds.extend([\"--exclude\", exclude])\n ctx.run(\" \".join(cmds), echo=True)\n\n\n@invoke.task(help={\"path\": _PATH_HELP_DESC})\ndef lint(ctx, path=\".\"):\n \"\"\"Run code linter\"\"\"\n cmds = [\"flake8\", path, \"--statistics\"]\n ctx.run(\" \".join(cmds), echo=True)\n\n\n@invoke.task(help={\"path\": _PATH_HELP_DESC})\ndef upgrade(ctx, path=\".\"):\n \"\"\"Run code syntax upgrades.\"\"\"\n cmds = [\"pyupgrade\", path, \"--py3-plus\"]\n ctx.run(\" \".join(cmds))\n\n\n@invoke.task(\n help={\n \"all_files\": \"Run hooks against all files, not just the current changes.\",\n \"diff\": \"Show the diff of changes on hook failure.\",\n \"sync\": \"Re-install the latest git hooks.\",\n }\n)\ndef hooks(ctx, all_files=False, diff=False, sync=False):\n \"\"\"Run and manage pre-commit hooks.\"\"\"\n cmds = [\"pre-commit\", \"run\"]\n if diff:\n cmds.append(\"--show-diff-on-failure\")\n if all_files:\n cmds.extend([\"--all-files\"])\n else:\n # used in CI - runs faster and only checks files that have changed\n cmds.extend([\"--from-ref\", \"origin/HEAD\", \"--to-ref\", \"HEAD\"])\n\n ctx.run(\" \".join(cmds))\n\n if sync:\n print(\" Re-installing hooks ...\")\n ctx.run(\" \".join([\"pre-commit\", \"uninstall\"]), echo=True)\n ctx.run(\" \".join([\"pre-commit\", \"install\"]), echo=True)\n\n\n@invoke.task(aliases=[\"type-cov\"]) # type: ignore\ndef type_coverage(ctx):\n \"\"\"\n Check total type-hint coverage compared to `develop`.\n \"\"\"\n try:\n check_type_hint_coverage.main()\n except AssertionError as err:\n raise invoke.Exit(\n message=f\"{err}\\n\\n See {check_type_hint_coverage.__file__}\", code=1\n )\n\n\n@invoke.task(\n aliases=[\"types\"],\n iterable=[\"packages\"],\n help={\n \"packages\": \"One or more `great_expectatations` sub-packages to type-check with mypy.\",\n \"install-types\": \"Automatically install any needed types from `typeshed`.\",\n \"daemon\": \"Run mypy in daemon mode with faster analysis.\"\n \" The daemon will be started and re-used for subsequent calls.\"\n \" For detailed usage see `dmypy --help`.\",\n \"clear-cache\": \"Clear the local mypy cache directory.\",\n },\n)\ndef type_check(\n ctx,\n packages,\n install_types=False,\n pretty=False,\n warn_unused_ignores=False,\n daemon=False,\n clear_cache=False,\n report=False,\n):\n \"\"\"Run mypy static type-checking on select packages.\"\"\"\n if clear_cache:\n mypy_cache = pathlib.Path(\".mypy_cache\")\n print(f\" Clearing {mypy_cache} ... \", end=\"\")\n try:\n shutil.rmtree(mypy_cache)\n print(\"✅\"),\n except FileNotFoundError as exc:\n print(f\"❌\\n {exc}\")\n\n if daemon:\n bin = \"dmypy run --\"\n else:\n bin = \"mypy\"\n\n ge_pkgs = [f\"great_expectations.{p}\" for p in packages]\n cmds = [\n bin,\n *ge_pkgs,\n ]\n if install_types:\n cmds.extend([\"--install-types\", \"--non-interactive\"])\n if daemon:\n # see related issue https://github.com/python/mypy/issues/9475\n cmds.extend([\"--follow-imports=normal\"])\n if report:\n cmds.extend([\"--txt-report\", \"type_cov\", \"--html-report\", \"type_cov\"])\n if pretty:\n cmds.extend([\"--pretty\"])\n if warn_unused_ignores:\n cmds.extend([\"--warn-unused-ignores\"])\n # use pseudo-terminal for colorized output\n ctx.run(\" \".join(cmds), echo=True, pty=True)\n\n\n@invoke.task(aliases=[\"get-stats\"])\ndef get_usage_stats_json(ctx):\n \"\"\"\n Dump usage stats event examples to json file\n \"\"\"\n if not is_ge_installed:\n raise invoke.Exit(\n message=\"This invoke task requires Great Expecations to be installed in the environment. Please try again.\",\n code=1,\n )\n\n events = usage_stats_utils.get_usage_stats_example_events()\n version = usage_stats_utils.get_gx_version()\n\n outfile = f\"v{version}_example_events.json\"\n with open(outfile, \"w\") as f:\n json.dump(events, f)\n\n print(f\"File written to '{outfile}'.\")\n\n\n@invoke.task(pre=[get_usage_stats_json], aliases=[\"move-stats\"])\ndef mv_usage_stats_json(ctx):\n \"\"\"\n Use databricks-cli lib to move usage stats event examples to dbfs:/\n \"\"\"\n version = usage_stats_utils.get_gx_version()\n outfile = f\"v{version}_example_events.json\"\n cmd = \"databricks fs cp --overwrite {0} dbfs:/schemas/{0}\"\n cmd = cmd.format(outfile)\n ctx.run(cmd)\n print(f\"'{outfile}' copied to dbfs.\")\n\n\nUNIT_TEST_DEFAULT_TIMEOUT: float = 2.0\n\n\n@invoke.task(\n aliases=[\"test\"],\n help={\n \"unit\": \"Runs tests marked with the 'unit' marker. Default behavior.\",\n \"integration\": \"Runs integration tests and exclude unit-tests. By default only unit tests are run.\",\n \"ignore-markers\": \"Don't exclude any test by not passing any markers to pytest.\",\n \"slowest\": \"Report on the slowest n number of tests\",\n \"ci\": \"execute tests assuming a CI environment. Publish XML reports for coverage reporting etc.\",\n \"timeout\": f\"Fails unit-tests if calls take longer than this value. Default {UNIT_TEST_DEFAULT_TIMEOUT} seconds\",\n \"html\": \"Create html coverage report\",\n \"package\": \"Run tests on a specific package. Assumes there is a `tests/<PACKAGE>` directory of the same name.\",\n \"full-cov\": \"Show coverage report on the entire `great_expectations` package regardless of `--package` param.\",\n },\n)\ndef tests(\n ctx,\n unit=True,\n integration=False,\n ignore_markers=False,\n ci=False,\n html=False,\n cloud=True,\n slowest=5,\n timeout=UNIT_TEST_DEFAULT_TIMEOUT,\n package=None,\n full_cov=False,\n):\n \"\"\"\n Run tests. Runs unit tests by default.\n\n Use `invoke tests -p=<TARGET_PACKAGE>` to run tests on a particular package and measure coverage (or lack thereof).\n \"\"\"\n markers = []\n if integration:\n markers += [\"integration\"]\n unit = False\n markers += [\"unit\" if unit else \"not unit\"]\n\n marker_text = \" and \".join(markers)\n\n cov_param = \"--cov=great_expectations\"\n if package and not full_cov:\n cov_param += f\"/{package.replace('.', '/')}\"\n\n cmds = [\n \"pytest\",\n f\"--durations={slowest}\",\n cov_param,\n \"--cov-report term\",\n \"-vv\",\n ]\n if not ignore_markers:\n cmds += [\"-m\", f\"'{marker_text}'\"]\n if unit and not ignore_markers:\n try:\n import pytest_timeout # noqa: F401\n\n cmds += [f\"--timeout={timeout}\"]\n except ImportError:\n print(\"`pytest-timeout` is not installed, cannot use --timeout\")\n\n if cloud:\n cmds += [\"--cloud\"]\n if ci:\n cmds += [\"--cov-report\", \"xml\"]\n if html:\n cmds += [\"--cov-report\", \"html\"]\n if package:\n cmds += [f\"tests/{package.replace('.', '/')}\"] # allow `foo.bar`` format\n ctx.run(\" \".join(cmds), echo=True, pty=True)\n\n\nPYTHON_VERSION_DEFAULT: float = 3.8\n\n\n@invoke.task(\n help={\n \"name\": \"Docker image name.\",\n \"tag\": \"Docker image tag.\",\n \"build\": \"If True build the image, otherwise run it. Defaults to False.\",\n \"detach\": \"Run container in background and print container ID. Defaults to False.\",\n \"py\": f\"version of python to use. Default is {PYTHON_VERSION_DEFAULT}\",\n \"cmd\": \"Command for docker image. Default is bash.\",\n }\n)\ndef docker(\n ctx,\n name=\"gx38local\",\n tag=\"latest\",\n build=False,\n detach=False,\n cmd=\"bash\",\n py=PYTHON_VERSION_DEFAULT,\n):\n \"\"\"\n Build or run gx docker image.\n \"\"\"\n filedir = os.path.realpath(os.path.dirname(os.path.realpath(__file__)))\n curdir = os.path.realpath(os.getcwd())\n if filedir != curdir:\n raise invoke.Exit(\n \"The docker task must be invoked from the same directory as the task.py file at the top of the repo.\",\n code=1,\n )\n\n cmds = [\"docker\"]\n\n if build:\n cmds.extend(\n [\n \"buildx\",\n \"build\",\n \"-f\",\n \"docker/Dockerfile.tests\",\n f\"--tag {name}:{tag}\",\n *[\n f\"--build-arg {arg}\"\n for arg in [\"SOURCE=local\", f\"PYTHON_VERSION={py}\"]\n ],\n \".\",\n ]\n )\n\n else:\n cmds.append(\"run\")\n if detach:\n cmds.append(\"--detach\")\n cmds.extend(\n [\n \"-it\",\n \"--rm\",\n \"--mount\",\n f\"type=bind,source={filedir},target=/great_expectations\",\n \"-w\",\n \"/great_expectations\",\n f\"{name}:{tag}\",\n f\"{cmd}\",\n ]\n )\n\n ctx.run(\" \".join(cmds), echo=True, pty=True)\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":10324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"13285878","text":"#!usr/bin/env python\nimport numpy as np\nfrom lxml import etree\nimport sys\n\n# some constant\nC2B = 2.\npft_array=[2,3,4]\nagf_bs = 0.7\n\n# get filename\nprint(sys.argv)\nsim_type = str(sys.argv[1])\n\n# separate the string to get site name and setup\nsite_name = sim_type.split('_')[0]\nsetup = sim_type.split('_')[1]\n\nxml_fn = \"{:s}_config.xml\".format(sim_type)\n\n\n# write the header for xml files\ns = '''<?xml version=\"1.0\"?>\n<config />'''\ntree = etree.fromstring(s)\n# create three pfts in xml\nxml_pfts=[]\nfor ipft, pft in enumerate(pft_array):\n xml_pfts.append(etree.SubElement(tree,\"pft\"))\n etree.SubElement(xml_pfts[ipft], \"num\").text = \"{:d}\".format(pft)\n etree.SubElement(xml_pfts[ipft], \"root_beta\").text = \"{:f}\".format(0.0025)\n\n## always need to set mortality parameters\n#mort1=7.5\n#mort2=14.0\n\n#for ipft, pft in enumerate(pft_array):\n# etree.SubElement(xml_pfts[ipft], \"mort1\").text = \"{:f}\".format(mort1)\n# etree.SubElement(xml_pfts[ipft], \"mort2\").text = \"{:f}\".format(mort2)\n\n\n# always modify fuse_dbh_max\nxml_ff = etree.SubElement(tree,\"fusefiss\")\netree.SubElement(xml_ff, \"fuse_dbh_max\").text = \"{:f}\".format(20.)\n\nif (setup[0] == '0'):\n # no hydraulics, use fsw as water stress, no trait plasticity\n # do nothing\n\n # initiate rho_array for later use\n rho_array=[0.53,0.71,0.90]\nelif (setup[0] in ['1','2']):\n # with hydraulics, use TLP hydro parameters, TLP water stress\n wood_psi50 = -2.2 * 102.\n wood_Kmax = 3. / 102.\n rho_array=[0.53,0.71,0.90]\n for ipft, pft in enumerate(pft_array):\n etree.SubElement(xml_pfts[ipft], \"wood_psi50\").text = \"{:f}\".format(wood_psi50)\n etree.SubElement(xml_pfts[ipft], \"wood_Kmax\").text = \"{:f}\".format(wood_Kmax)\nelif (setup[0] in ['3','4']):\n # with hydraulics, use XXT hydro parameters, XXT water stress\n retained_carbon_fraction = 0.25\n elongf_min = 0.02\n\n xml_phen = etree.SubElement(tree,\"phenology\")\n etree.SubElement(xml_phen, \"retained_carbon_fraction\").text = \"{:f}\".format(0.25)\n etree.SubElement(xml_phen, \"elongf_min\").text = \"{:f}\".format(elongf_min)\n\n vm0_array = np.array([45.,35.,25]) * 0.44\n rho_array = [0.52,0.74,0.84]\n sla_array = [20.5,18.7,15.7]\n q_array = [1.0,1.,1.]\n b1Ht_array = [-0.0682,0.98,0.3444]\n b2Ht_array = [0.8368,0.4756,0.6571]\n b1Bl_array = np.array([0.012,0.008,0.023]) * 2.\n b2Bl_array = np.array([1.75,2.12,1.93])\n b1Bs_array = np.exp(np.array([-3.38,-2.84,-2.82])) / agf_bs\n b2Bs_array = [2.32,2.28,2.33]\n root_beta_array = np.array([0.96,0.97,0.98]) ** 200.\n b1Rd_array = np.array([1.2,1.6,2.0]) * -0.2185333 * 0.5\n b2Rd_array = np.array([1.,1.,1.]) * .5436442\n stoma_lambda = [6.,9.,12.]\n stoma_beta = np.array([-0.7,-0.4,-0.1]) / 102.\n dark_respiration_factor = [0.015,0.015,0.015]\n\n leaf_turnover_rate = 0.5 * (1. - retained_carbon_fraction)\n root_turnover_rate = 0.5 * (1. - retained_carbon_fraction)\n growth_resp_factor = 0.28\n storage_turnover_rate = 0\n qsw = 0.\n hgt_min = 0.5\n hgt_max = 35.\n wat_dry_ratio_grn = 2.5\n wat_dry_ratio_ngrn = 0.7\n for ipft, pft in enumerate(pft_array):\n xml_pft = xml_pfts[ipft]\n etree.SubElement(xml_pft, \"Vm0\").text = \"{:f}\".format(vm0_array[ipft])\n etree.SubElement(xml_pft, \"rho\").text = \"{:f}\".format(rho_array[ipft])\n etree.SubElement(xml_pft, \"SLA\").text = \"{:f}\".format(sla_array[ipft])\n etree.SubElement(xml_pft, \"q\").text = \"{:f}\".format(q_array[ipft])\n #etree.SubElement(xml_pft, \"b1Ht\").text = \"{:f}\".format(b1Ht_array[ipft])\n #etree.SubElement(xml_pft, \"b2Ht\").text = \"{:f}\".format(b2Ht_array[ipft])\n #etree.SubElement(xml_pft, \"b1Bl\").text = \"{:f}\".format(b1Bl_array[ipft])\n #etree.SubElement(xml_pft, \"b2Bl\").text = \"{:f}\".format(b2Bl_array[ipft])\n #etree.SubElement(xml_pft, \"b1Bs_small\").text = \"{:f}\".format(b1Bs_array[ipft])\n #etree.SubElement(xml_pft, \"b1Bs_big\").text = \"{:f}\".format(b1Bs_array[ipft])\n #etree.SubElement(xml_pft, \"b2Bs_small\").text = \"{:f}\".format(b2Bs_array[ipft])\n #etree.SubElement(xml_pft, \"b2Bs_big\").text = \"{:f}\".format(b2Bs_array[ipft])\n etree.SubElement(xml_pft, \"root_beta\").text = \"{:f}\".format(root_beta_array[ipft])\n etree.SubElement(xml_pft, \"b1Rd\").text = \"{:f}\".format(b1Rd_array[ipft])\n etree.SubElement(xml_pft, \"b2Rd\").text = \"{:f}\".format(b2Rd_array[ipft])\n etree.SubElement(xml_pft, \"stoma_lambda\").text = \"{:f}\".format(stoma_lambda[ipft])\n etree.SubElement(xml_pft, \"stoma_beta\").text = \"{:f}\".format(stoma_beta[ipft])\n etree.SubElement(xml_pft, \"dark_respiration_factor\").text = \\\n \"{:f}\".format(dark_respiration_factor[ipft])\n etree.SubElement(xml_pft, \"leaf_turnover_rate\").text =\\\n \"{:f}\".format(leaf_turnover_rate)\n etree.SubElement(xml_pft, \"root_turnover_rate\").text =\\\n \"{:f}\".format(root_turnover_rate)\n etree.SubElement(xml_pft, \"storage_turnover_rate\").text = \"{:f}\".format(0.)\n etree.SubElement(xml_pft, \"growth_resp_factor\").text =\\\n \"{:f}\".format(growth_resp_factor)\n etree.SubElement(xml_pft, \"qsw\").text = \"{:f}\".format(qsw)\n #etree.SubElement(xml_pft, \"hgt_min\").text = \"{:f}\".format(hgt_min)\n #etree.SubElement(xml_pft, \"hgt_max\").text = \"{:f}\".format(hgt_max)\n etree.SubElement(xml_pft, \"wat_dry_ratio_grn\").text =\\\n \"{:f}\".format(wat_dry_ratio_grn)\n etree.SubElement(xml_pft, \"wat_dry_ratio_ngrn\").text =\\\n \"{:f}\".format(wat_dry_ratio_ngrn)\n\n #min_dbh = np.exp((np.log(hgt_min) - b1Ht_array[ipft]) /\n # (b2Ht_array[ipft]))\n #dbh_crit = np.exp((np.log(hgt_max) - b1Ht_array[ipft]) /\n # (b2Ht_array[ipft]))\n #min_bdead = b1Bs_array[ipft] / C2B * min_dbh ** b2Bs_array[ipft]\n #etree.SubElement(xml_pft, \"min_dbh\").text = \"{:f}\".format(min_dbh)\n #etree.SubElement(xml_pft, \"dbh_crit\").text = \"{:f}\".format(dbh_crit)\n #etree.SubElement(xml_pft, \"min_bdead\").text = \"{:f}\".format(min_bdead)\n\n # now write the hydraulic parameters\n # BC\n lma = 1.e3 * C2B / sla_array[ipft]\n leaf_psi_osmotic = (-0.04 - 1.51 * rho_array[ipft] - 0.0067 * lma) * 102.\n leaf_elastic_mod = 2.5 + 37.5 / (1. + np.exp(-8. * rho_array[ipft]\n + 5.7))\n leaf_rwc_min = 0.01 * leaf_elastic_mod + 0.17\n leaf_psi_tlp = leaf_elastic_mod * (leaf_psi_osmotic / 102.) / \\\n (leaf_elastic_mod + leaf_psi_osmotic / 102.) * 102.\n leaf_density = np.maximum(0.1*1.e3,\n (leaf_elastic_mod-2.03)/25.4*1.e3)\n leaf_water_sat = (-2.32e4 / lma + 782.)\\\n * (1. / (-0.21 * np.log(1.e4 / lma)+ 1.43) - 1.)\\\n / leaf_density\n wood_psi_osmotic = (0.52 - 4.16 * rho_array[ipft]) * 102.\n wood_elastic_mod = (1.02 * np.exp(8.5 * rho_array[ipft] - 2.89)) ** 0.5\n rwc_tlp_wood = 1. - (1. - 0.75 * rho_array[ipft])\\\n / (2.74 + 2.01 * rho_array[ipft])\n wood_rwc_min = wood_elastic_mod * (1. - 0.07 - rwc_tlp_wood) \\\n / (wood_psi_osmotic / 102. * (1. - 0.07)) + 1. \\\n - wood_elastic_mod * 0.07\n wood_water_sat = (1. - rho_array[ipft] / 1.53) / rho_array[ipft]\n wood_psi_tlp = wood_elastic_mod * (wood_psi_osmotic / 102.)\\\n / (wood_elastic_mod + wood_psi_osmotic / 102.)\\\n * 102.\n leaf_water_cap = (1. - leaf_psi_osmotic / (4. * leaf_psi_tlp))\\\n * leaf_water_sat / (4. * abs(leaf_psi_tlp))\n wood_water_cap = (1. - wood_psi_osmotic / (4. * wood_psi_tlp))\\\n * wood_water_sat / (4. * abs(wood_psi_tlp))\n wood_psi50 = (-1.09-(3.57*rho_array[ipft]) ** 1.73) * 102.\n Amax_25 = vm0_array[ipft] * 2.4 / 4.1\n wood_Kmax = np.exp(2.11 - 20.05 * rho_array[ipft] / Amax_25) / 102.\n wood_Kexp = 0.544 * 4. * (-wood_psi50 / 102.) ** -0.17\n leaf_psi_min = (leaf_rwc_min - 1.) * leaf_water_sat / leaf_water_cap\n wood_psi_min = (wood_rwc_min - 1.) * wood_water_sat / wood_water_cap\n\n\n # rewrite from Xu et al. NPH 2016\n leaf_water_cap = 3.e-3 * sla_array[ipft] / C2B / 102. / 2.\n wood_water_cap = np.minimum(400.,np.maximum(50.,\n -700. * (rho_array[ipft] - 0.3) + 400.)) \\\n / (rho_array[ipft] * 1.e3) /102. / 3.\n\n leaf_water_sat = 1.85\n wood_water_sat = 0.7\n\n #leaf_rwc_min = 0.5\n #wood_rwc_min = 0.05\n\n leaf_rwc_min = max(0.,1. + leaf_psi_min * leaf_water_cap /\n leaf_water_sat)\n wood_rwc_min = max(0.,1. + wood_psi_min * wood_water_cap /\n wood_water_sat)\n\n leaf_psi_tlp = (-4.59 + 0.62 * np.log(sla_array[ipft]) \n - 1.15 * np.log(rho_array[ipft])) * 102.\n wood_psi50 = (-3. * rho_array[ipft] - 0.599) * 102.\n wood_Kmax = np.exp(-2.455 * rho_array[ipft] + 2.348 + 0.5 *\n 0.6186) / 102.\n wood_Kexp = 4.\n\n\n etree.SubElement(xml_pft, \"leaf_water_cap\").text = \"{:f}\".format(leaf_water_cap)\n etree.SubElement(xml_pft, \"wood_water_cap\").text = \"{:f}\".format(wood_water_cap)\n etree.SubElement(xml_pft, \"leaf_psi_min\").text = \"{:f}\".format(leaf_psi_min)\n etree.SubElement(xml_pft, \"wood_psi_min\").text = \"{:f}\".format(wood_psi_min)\n etree.SubElement(xml_pft, \"leaf_water_sat\").text = \"{:f}\".format(leaf_water_sat)\n etree.SubElement(xml_pft, \"wood_water_sat\").text = \"{:f}\".format(wood_water_sat)\n etree.SubElement(xml_pft, \"leaf_rwc_min\").text = \"{:f}\".format(leaf_rwc_min)\n etree.SubElement(xml_pft, \"wood_rwc_min\").text = \"{:f}\".format(wood_rwc_min)\n etree.SubElement(xml_pft, \"leaf_psi_tlp\").text = \"{:f}\".format(leaf_psi_tlp)\n etree.SubElement(xml_pft, \"wood_psi_tlp\").text = \"{:f}\".format(wood_psi_tlp)\n etree.SubElement(xml_pft, \"wood_Kmax\").text = \"{:f}\".format(wood_Kmax)\n etree.SubElement(xml_pft, \"wood_Kexp\").text = \"{:f}\".format(wood_Kexp)\n etree.SubElement(xml_pft, \"wood_psi50\").text = \"{:f}\".format(wood_psi50)\n\n\noutput_str = etree.tostring(tree, encoding=\"UTF-8\",\n xml_declaration=True,\n pretty_print=True,\n doctype='<!DOCTYPE config SYSTEM \"ed.dtd\">')\n\n# write into file\nwith open(xml_fn,'wb') as f:\n f.write(output_str)\n","sub_path":"ED2-treering/run_HKK/create_xml_201803.py","file_name":"create_xml_201803.py","file_ext":"py","file_size_in_byte":10668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"61753","text":"''' This module holds most of the items related to github oauth login\n and the related sqlite user database '''\n\nfrom sqlalchemy import create_engine, Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\n\nauthBase = declarative_base()\n\n\nclass User(authBase):\n \"\"\" this class is used when dealing with Oauth user data stored\n in an sqlite database for sqlalchemy and github-flask\"\"\"\n __tablename__ = 'users'\n\n id = Column(Integer, primary_key=True)\n username = Column(String(200))\n github_access_token = Column(String(200))\n\n def __init__(self, github_access_token):\n self.github_access_token = github_access_token\n\nauth_engine = create_engine('sqlite:///auth.db')\n\ndb_session = scoped_session(sessionmaker(auth_engine))\n\nauthBase.query = db_session.query_property()\n\n\ndef get_user_by_id(id_num):\n \"\"\" returns the Oauth user associated with this id \"\"\"\n target_user = db_session.query(User).filter_by(id=id_num).one()\n return target_user\n\n\ndef add_user_name(id_num, user_name):\n \"\"\" adds a user to the Oauth user database \"\"\"\n target_user = get_user_by_id(id_num)\n if target_user != []:\n target_user.username = user_name\n db_session.commit()\n\n\ndef empty_users():\n \"\"\" removes all Oauth users. This should have additional checks added\n before using it in the production environment \"\"\"\n db_session.query(User).delete()\n db_session.commit()\n\nauthBase.metadata.create_all(bind=auth_engine)\n","sub_path":"Vagrant/item_catalog/auth_db.py","file_name":"auth_db.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"539479972","text":"# -*- coding: utf-8 -*-\nimport os.path\nimport scrapy\nfrom HTMLParser import HTMLParser\n\n\nclass ObservadorSpider(scrapy.Spider):\n name = \"jornal_negocios\"\n allowed_domains = [\"jornaldenegocios.pt\"]\n start_urls = [\n \"http://www.jornaldenegocios.pt\",\n ]\n\n visit = []\n\n def parse(self, response):\n\n # self.parse_content(response)\n for href in response.css(\"a::attr('href')\"):\n url = response.urljoin(href.extract())\n yield scrapy.Request(url, callback=self.parse_content)\n\n def parse_content(self, response):\n\n if hasattr(response, 'xpath'):\n\n title = response.xpath('//title')\n head = response.xpath('//*[contains(concat(\" \",@class,\" \"), \" lead \")]')\n article = response.xpath('//*[contains(concat(\" \",@class,\" \"), \" txt_artigo \")]')\n\n content = \"\"\n\n if title:\n content += title.extract()[0] + \"\\n\"\n\n if head:\n content += head.extract()[0] + \"\\n\"\n\n for line in article:\n content += HTMLParser().unescape(line.extract()) + \"\\n\"\n\n filename = self.name + \"/\" + '-'.join(response.url.split(\"/\")[3:]) + '.raw'\n\n if not os.path.isfile(filename):\n open(filename, \"wb\").write(content.encode('utf-8', 'ignore'))\n\n if hasattr(response, 'css'):\n for href in response.css(\"a::attr('href')\"):\n url = response.urljoin(href.extract())\n\n if url not in self.visit:\n self.visit.append(url)\n yield scrapy.Request(url, callback=self.parse_content)\n","sub_path":"resources/spiders/jornal_negocios.py","file_name":"jornal_negocios.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"410652692","text":"#! /d/python366/python\n \n# 定义一个使用不定长参数的函数,并在函数中打印出参数及其类型,统计传入参数的个数\n\ndef test(*args,**kwargs):\n print(\"args : 参数-{};类型-{};个数-{}\".format(args,type(args),len(args)))\n print(\"kwargs : 参数-{};类型-{};个数-{}\".format(kwargs,type(kwargs),len(kwargs)))\n\ntest(*[1,2,3])\ntest([1,2,3])\ntest(\"abc123\",1,2)\ntest(1,2,a = 1,**{'b' : 2})\ntest(**{'a' : 1,'b' : 2})\n\n\n\n\n\n# 使用递归函数求n的阶乘\n\ndef factorial(num):\n if num == 1:\n return num*num\n tamp = num * factorial(num-1)\n return tamp\n\nresult = factorial(4)\nprint(result)","sub_path":"9月-Python核心编程/python核心编程阶段-python基础/11-函数参数和返回值/9-21 课后习题.py","file_name":"9-21 课后习题.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"348009837","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThe entrance for ipfs module.\n\"\"\"\nimport shutil\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom src import hive_setting\nfrom src.utils_v1.constants import VAULT_ACCESS_WR, VAULT_ACCESS_R, DID_INFO_DB_NAME\nfrom src.utils_v1.payment.vault_service_manage import inc_vault_file_use_storage_byte\nfrom src.utils.consts import COL_IPFS_FILES, DID, APP_DID, COL_IPFS_FILES_PATH, COL_IPFS_FILES_SHA256, \\\n COL_IPFS_FILES_IS_FILE, SIZE, COL_IPFS_FILES_IPFS_CID, COL_IPFS_CID_REF, CID, COUNT, CREATE_TIME, MODIFY_TIME\nfrom src.utils.db_client import cli\nfrom src.utils.did_auth import check_auth_and_vault\nfrom src.utils.file_manager import fm\nfrom src.utils.http_exception import InvalidParameterException, FileNotFoundException, AlreadyExistsException\nfrom src.utils.http_response import hive_restful_response, hive_stream_response\n\n\nclass IpfsFiles:\n def __init__(self):\n \"\"\"\n Use IPFS node as the file storage.\n 1. Every did has a local files cache.\n 2. Every did/app_did has its own files collection.\n 3. When uploading the file, cache it locally. Then upload to the IPFS node with the timed script.\n 4. The files with same content is relating to the same CID of the IPFS node. So it can not be unpined in IPFS.\n \"\"\"\n pass\n\n @hive_restful_response\n def upload_file(self, path):\n if not path:\n raise InvalidParameterException()\n\n did, app_did = check_auth_and_vault(VAULT_ACCESS_WR)\n self.upload_file_by_did(did, app_did, path)\n return {\n 'name': path\n }\n\n @hive_stream_response\n def download_file(self, path):\n if not path:\n raise InvalidParameterException()\n\n did, app_did = check_auth_and_vault(VAULT_ACCESS_R)\n return self.download_file_by_did(did, app_did, path)\n\n @hive_restful_response\n def delete_file(self, path):\n \"\"\"\n Delete the file.\n 1. remove the file in files cache.\n 2. unpin the file in IPFS node.\n :param path:\n :return:\n \"\"\"\n if not path:\n raise InvalidParameterException()\n\n did, app_did = check_auth_and_vault(VAULT_ACCESS_WR)\n col_filter = {DID: did,\n APP_DID: app_did,\n COL_IPFS_FILES_PATH: path}\n doc = cli.find_one(did, app_did, COL_IPFS_FILES, col_filter, is_raise=False)\n if not doc:\n return\n\n file_path = fm.ipfs_get_file_path(did, app_did, path)\n if file_path.exists():\n file_path.unlink()\n\n self.delete_file_metadata(did, app_did, doc, col_filter=col_filter)\n inc_vault_file_use_storage_byte(did, 0 - doc[SIZE])\n\n @hive_restful_response\n def move_file(self, src_path, dst_path):\n if not src_path or not dst_path:\n raise InvalidParameterException()\n elif src_path == dst_path:\n raise InvalidParameterException(msg='The source file and the destination file can not be the same.')\n\n return self.move_file_really(src_path, dst_path)\n\n @hive_restful_response\n def copy_file(self, src_path, dst_path):\n if not src_path or not dst_path:\n raise InvalidParameterException()\n elif src_path == dst_path:\n raise InvalidParameterException(msg='The source file and the destination file can not be the same.')\n\n return self.move_file_really(src_path, dst_path, True)\n\n @hive_restful_response\n def list_folder(self, path):\n \"\"\"\n List the files recursively.\n :param path: Empty means root folder.\n :return: File list.\n \"\"\"\n did, app_did = check_auth_and_vault(VAULT_ACCESS_WR)\n col_filter = {DID: did, APP_DID: app_did}\n if path:\n folder_path = path if path[len(path) - 1] == '/' else f'{path}/'\n col_filter[COL_IPFS_FILES_PATH] = {\n '$regex': f'^{folder_path}'\n }\n docs = cli.find_many(did, app_did, COL_IPFS_FILES, col_filter)\n if not docs and path:\n raise InvalidParameterException(f'Can not find the folder {path}')\n return {\n 'value': list(map(lambda d: self._get_list_file_info_by_doc(d), docs))\n }\n\n @hive_restful_response\n def get_properties(self, path):\n if not path:\n raise InvalidParameterException()\n\n did, app_did = check_auth_and_vault(VAULT_ACCESS_R)\n doc = self.check_file_exists(did, app_did, path)\n\n return {\n 'name': doc[COL_IPFS_FILES_PATH],\n 'is_file': doc[COL_IPFS_FILES_IS_FILE],\n 'size': doc[SIZE],\n 'created': doc['created'],\n 'updated': doc['modified'],\n }\n\n @hive_restful_response\n def get_hash(self, path):\n if not path:\n raise InvalidParameterException()\n\n did, app_did = check_auth_and_vault(VAULT_ACCESS_R)\n doc = self.check_file_exists(did, app_did, path)\n\n return {\n 'name': doc[COL_IPFS_FILES_PATH],\n 'algorithm': 'SHA256',\n 'hash': doc[COL_IPFS_FILES_SHA256]\n }\n\n def upload_file_by_did(self, did, app_did, path: str):\n \"\"\"\n Upload file really.\n 1. generate the local file name and save the content to local.\n 2. add file document to the vault_files collection or update doc by remove cid.\n 3. return None.\n 4. run a timely script to upload file to IPFS node and update the relating file documents.\n :param did: the user did\n :param app_did: the application did\n :param path: the file relative path, not None\n :return: None\n \"\"\"\n file_path = fm.ipfs_get_file_path(did, app_did, path)\n fm.write_file_by_request_stream(file_path)\n col_filter = {DID: did,\n APP_DID: app_did,\n COL_IPFS_FILES_PATH: path}\n doc = cli.find_one(did, app_did, COL_IPFS_FILES, col_filter, is_create=True, is_raise=False)\n if not doc:\n # not exists, add new one.\n file_doc = {\n DID: did,\n APP_DID: app_did,\n COL_IPFS_FILES_PATH: path,\n COL_IPFS_FILES_SHA256: fm.get_file_content_sha256(file_path),\n COL_IPFS_FILES_IS_FILE: True,\n SIZE: file_path.stat().st_size,\n COL_IPFS_FILES_IPFS_CID: None,\n }\n result = cli.insert_one(did, app_did, COL_IPFS_FILES, file_doc, is_create=True)\n inc_vault_file_use_storage_byte(did, file_doc[SIZE])\n else:\n # exists, just remove cid for uploading the file to IPFS node later.\n old_cid = doc[COL_IPFS_FILES_IPFS_CID]\n self.update_file_metadata(did, app_did, path, file_path, col_filter=col_filter)\n inc_vault_file_use_storage_byte(did, file_path.stat().st_size - doc[SIZE])\n if old_cid:\n self.decrease_cid_ref(old_cid)\n\n def add_file_to_metadata(self, did, app_did, rel_path, file_path):\n file_doc = {\n DID: did,\n APP_DID: app_did,\n COL_IPFS_FILES_PATH: rel_path,\n COL_IPFS_FILES_SHA256: fm.get_file_content_sha256(file_path),\n COL_IPFS_FILES_IS_FILE: True,\n SIZE: file_path.stat().st_size,\n COL_IPFS_FILES_IPFS_CID: None,\n }\n result = cli.insert_one(did, app_did, COL_IPFS_FILES, file_doc, is_create=True)\n\n def update_file_metadata(self, did, app_did, rel_path: str, full_path: Path, col_filter=None, sha256=None):\n if not col_filter:\n col_filter = {DID: did,\n APP_DID: app_did,\n COL_IPFS_FILES_PATH: rel_path}\n update = {'$set': {COL_IPFS_FILES_IPFS_CID: None,\n COL_IPFS_FILES_SHA256: fm.get_file_content_sha256(full_path) if not sha256 else sha256,\n SIZE: full_path.stat().st_size}}\n result = cli.update_one(did, app_did, COL_IPFS_FILES, col_filter, update, is_extra=True)\n\n def delete_file_metadata(self, did, app_did, doc, col_filter=None):\n old_cid = None\n if doc[COL_IPFS_FILES_IPFS_CID]:\n old_cid = doc[COL_IPFS_FILES_IPFS_CID]\n\n if not col_filter:\n col_filter = {DID: did,\n APP_DID: app_did,\n COL_IPFS_FILES_PATH: doc[COL_IPFS_FILES_PATH]}\n\n cli.delete_one(did, app_did, COL_IPFS_FILES, col_filter, is_check_exist=False)\n if old_cid:\n self.decrease_cid_ref(old_cid)\n\n def download_file_by_did(self, did, app_did, path: str):\n \"\"\"\n Download file by did.\n 1. check file caches.\n 2. download file from IPFS to files cache if no cache.\n 3. return the file content as the response.\n :param did: The user did.\n :param app_did:\n :param path:\n :return:\n \"\"\"\n doc = self.check_file_exists(did, app_did, path)\n file_path = fm.ipfs_get_file_path(did, app_did, path)\n if not file_path.exists():\n fm.ipfs_download_file_to_path(doc[COL_IPFS_FILES_IPFS_CID], file_path)\n return fm.get_response_by_file_path(file_path)\n\n def move_file_really(self, src_path, dst_path, is_copy=False):\n \"\"\"\n Move or copy file, not support directory.\n 1. check the existence of the source file.\n 2. move or copy file.\n 3. update the source file document or insert a new one.\n :param src_path: The path of the source file.\n :param dst_path: The path of the destination file.\n :param is_copy: True means copy file, else move.\n :return: Json data of the response.\n \"\"\"\n did, app_did = check_auth_and_vault(VAULT_ACCESS_WR)\n\n src_filter = {DID: did, APP_DID: app_did, COL_IPFS_FILES_PATH: src_path}\n dst_filter = {DID: did, APP_DID: app_did, COL_IPFS_FILES_PATH: dst_path}\n src_doc = cli.find_one(did, app_did, COL_IPFS_FILES, src_filter)\n dst_doc = cli.find_one(did, app_did, COL_IPFS_FILES, dst_filter)\n if not src_doc:\n raise FileNotFoundException(msg=f'Source file {src_path} does not exist.')\n if dst_doc:\n raise AlreadyExistsException(msg=f'Destination file {dst_path} exists.')\n\n full_src_path = fm.ipfs_get_file_path(did, app_did, src_path)\n full_dst_path = fm.ipfs_get_file_path(did, app_did, dst_path)\n if full_dst_path.exists():\n full_dst_path.unlink()\n if full_src_path.exists():\n if is_copy:\n shutil.copy2(full_src_path.as_posix(), full_dst_path.as_posix())\n else:\n shutil.move(full_src_path.as_posix(), full_dst_path.as_posix())\n\n if is_copy:\n file_doc = {\n DID: did,\n APP_DID: app_did,\n COL_IPFS_FILES_PATH: dst_path,\n COL_IPFS_FILES_SHA256: src_doc[COL_IPFS_FILES_SHA256],\n COL_IPFS_FILES_IS_FILE: True,\n SIZE: src_doc[SIZE],\n COL_IPFS_FILES_IPFS_CID: src_doc[COL_IPFS_FILES_IPFS_CID],\n }\n cli.insert_one(did, app_did, COL_IPFS_FILES, file_doc)\n inc_vault_file_use_storage_byte(did, src_doc[SIZE])\n else:\n cli.update_one(did, app_did, COL_IPFS_FILES, src_filter,\n {'$set': {COL_IPFS_FILES_PATH: dst_path}}, is_extra=True)\n return {\n 'name': dst_path\n }\n\n def _get_list_file_info_by_doc(self, file_doc):\n return {\n 'name': file_doc[COL_IPFS_FILES_PATH],\n 'is_file': file_doc[COL_IPFS_FILES_IS_FILE],\n 'size': file_doc[SIZE],\n }\n\n def check_file_exists(self, did, app_did, path: str):\n col_filter = {DID: did,\n APP_DID: app_did,\n COL_IPFS_FILES_PATH: path}\n doc = cli.find_one(did, app_did, COL_IPFS_FILES, col_filter)\n if not doc:\n raise FileNotFoundException(msg=f'Can not find the file metadata with path: {path}')\n return doc\n\n def get_ipfs_file_access_url(self, metadata):\n return f'{hive_setting.IPFS_PROXY_URL}/ipfs/{metadata[COL_IPFS_FILES_IPFS_CID]}'\n\n def increase_cid_ref(self, cid):\n now = datetime.utcnow().timestamp()\n doc = cli.find_one_origin(DID_INFO_DB_NAME, COL_IPFS_CID_REF, {CID: cid}, is_raise=False)\n if not doc:\n doc = {\n CID: cid,\n COUNT: 1,\n CREATE_TIME: now,\n MODIFY_TIME: now\n }\n cli.insert_one_origin(DID_INFO_DB_NAME, COL_IPFS_CID_REF, doc, is_create=True, is_extra=False)\n else:\n self._update_ipfs_cid_ref_count(cid, doc[COUNT] + 1)\n\n def decrease_cid_ref(self, cid):\n now = datetime.utcnow().timestamp()\n doc = cli.find_one_origin(DID_INFO_DB_NAME, COL_IPFS_CID_REF, {CID: cid}, is_raise=False)\n if not doc:\n fm.ipfs_unpin_cid(cid)\n return\n if doc[COUNT] <= 1:\n cli.delete_one_origin(DID_INFO_DB_NAME, COL_IPFS_CID_REF, {CID: cid}, is_check_exist=False)\n fm.ipfs_unpin_cid(cid)\n else:\n self._update_ipfs_cid_ref_count(cid, doc[COUNT] - 1)\n\n def _update_ipfs_cid_ref_count(self, cid, count):\n now = datetime.utcnow().timestamp()\n col_filter = {CID: cid}\n update = {'$set': {\n COUNT: count,\n MODIFY_TIME: now\n }}\n cli.update_one_origin(DID_INFO_DB_NAME, COL_IPFS_CID_REF, col_filter, update)\n","sub_path":"src/modules/ipfs/ipfs.py","file_name":"ipfs.py","file_ext":"py","file_size_in_byte":13673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"342264284","text":"\r\nimport jwt,json\r\nfrom datetime import datetime, timedelta\r\nfrom sqlalchemy.sql import select\r\nfrom app.config.models import Keystore,Garage,Customer,ActivationCode\r\nfrom sqlalchemy import desc, text\r\nfrom app.util.encrypt_helper import EncryptHelper\r\nfrom app.services.exceptions import UserNotExistError,AuthenticationError\r\nfrom keystore.keystore_manager import KeystoreManager,KeystoreStatusEnum\r\nfrom keystore.keystore_validation_enum import KeystoreValidationEnum\r\nfrom keystore.exceptions import KeystoreExpiredError, KeystoreInvalidError\r\nfrom app.services.systemlog_service import SystemlogService\r\nfrom app.config.system_event_type import SystemEventType\r\nfrom app.util.custom_json_encoder import custom_json_handler\r\nimport uuid\r\nimport string\r\n\r\nclass KeystoreService:\r\n \"\"\" every thing about key \"\"\"\r\n _db =None\r\n _log_service = None\r\n _syslog = None\r\n def __init__(self, db):\r\n self._db = db\r\n self._log_service = SystemlogService(db)\r\n self._syslog = {}\r\n\r\n async def generate_and_save_keystore(self,key:Keystore):\r\n keystore = await self.generate_encrypted_keystore(key)\r\n return await self.add_keystore(key)\r\n\r\n async def generate_and_udpate_keystore(self,key:Keystore):\r\n keystore = await self.generate_encrypted_keystore(key)\r\n return await self.update_keystore(key,key['keystore_id'])\r\n \r\n async def generate_encrypted_keystore(self,key:Keystore)->str:\r\n keystoreManager = KeystoreManager(\r\n key['start_date']\r\n , key['end_date']\r\n , key['fixed_account_total']\r\n , key['dynamic_account_total']\r\n , key['key_manager_email']\r\n , key['service_type']\r\n , key['note']\r\n , key['customer_id']\r\n , key['key_type']\r\n , key['key_status'])\r\n\r\n encrypted= keystoreManager.encrypt()\r\n\r\n check_key_status_result = keystoreManager.verify(encrypted)\r\n key['key_validation_status'] = KeystoreValidationEnum.VALID\r\n if KeystoreValidationEnum.EXPIRED == check_key_status_result:\r\n raise KeystoreExpiredError('expired')\r\n elif KeystoreValidationEnum.INVALID == check_key_status_result:\r\n raise KeystoreInValidError('invalid')\r\n \r\n # key['start_date'] = datetime.strptime(key['start_date'], '%Y-%m-%dT%H:%M:%S.%fZ')\r\n # key['end_date'] = datetime.strptime(key['end_date'], '%Y-%m-%dT%H:%M:%S.%fZ')\r\n key['start_date'] = datetime.strptime(key['start_date'][:10], '%Y-%m-%d')\r\n key['end_date'] = datetime.strptime(key['end_date'][:10], '%Y-%m-%d')\r\n key['key_value'] = encrypted.decode(\"utf8\")\r\n \r\n return key\r\n\r\n async def update_keystore_status(self,status:KeystoreStatusEnum, keystore_id:int):\r\n async with self._db.acquire() as conn:\r\n result = await conn.execute(Key.update({key_status:Enum(status)}).where(Keystore.c.keystore_id == keystore_id))\r\n return result.rowcount\r\n \r\n async def get_keystores(self):\r\n \"\"\" get keys list \"\"\"\r\n async with self._db.acquire() as conn:\r\n keys = [dict(row.items()) async for row in await conn.execute('select t1.*,t2.company_name from keystore t1 join customer t2 on t1.customer_id = t2.customer_id')]\r\n return keys\r\n\r\n async def add_keystore(self,key:Keystore):\r\n self._syslog['create_account_id']=key['create_account_id']\r\n self._syslog['event_id']=SystemEventType.Add.value\r\n self._syslog['event_message']=json.dumps(key,default=custom_json_handler)\r\n #result = await self._log_service.addlog(self._syslog)\r\n async with self._db.acquire() as conn:\r\n result = await conn.execute(Keystore.insert(key))\r\n return result.lastrowid\r\n\r\n async def delete_keystore_by_id(self,keystore_id:int,customer_id:int) -> int:\r\n self._syslog['create_account_id']=customer_id\r\n self._syslog['event_id']=SystemEventType.DELETE_INFO.value\r\n self._syslog['event_message']=json.dumps(keystore_id,default=custom_json_handler)\r\n #result = await self._log_service.addlog(self._syslog)\r\n async with self._db.acquire() as conn:\r\n result = await conn.execute(Keystore.delete().where(Keystore.c.keystore_id == keystore_id))\r\n return result.rowcount\r\n\r\n async def get_keystores_by_customer_id(self,id:str):\r\n param = {'id':id}\r\n sql = \"\"\"select t1.*,t2.company_name from keystore t1 join customer t2 on t1.customer_id = t2.customer_id where t1.customer_id = :id\"\"\"\r\n async with self._db.acquire() as conn:\r\n keys = [dict(row.items()) async for row in await conn.execute(text(sql),param)]\r\n return keys\r\n \r\n async def get_keystores_by_id(self,id:int) -> Keystore:\r\n async with self._db.acquire() as conn:\r\n data= await conn.execute(Keystore.select().where((Keystore.c.keystore_id == id)))\r\n return await data.fetchone()\r\n \r\n async def update_keystore(self,key,keystore_id:Keystore) -> int:\r\n self._syslog['create_account_id']=key['create_account_id']\r\n self._syslog['event_id']=SystemEventType.UPDATE_INFO.value\r\n self._syslog['event_message']='update_keystore: '+json.dumps(keystore_id,default=custom_json_handler)+json.dumps(key,default=custom_json_handler)\r\n #result = await self._log_service.addlog(self._syslog)\r\n async with self._db.acquire() as conn:\r\n result = await conn.execute(Keystore.update().values(key).where(Keystore.c.keystore_id == keystore_id))\r\n return result.rowcount\r\n\r\n async def get_pad_config_by_key(self,inital_key) :\r\n try:\r\n config = {}\r\n garage_id = int(inital_key.split('-')[1])\r\n async with self._db.acquire() as conn :\r\n customer_id = await conn.execute(select([Garage.c.customer_id]).where(Garage.c.garage_id == garage_id))\r\n customer_id = await customer_id.scalar()\r\n r = [dict(row.items()) async for row in await conn.execute(ActivationCode.select().where(ActivationCode.c.garage_id==garage_id).where(ActivationCode.c.activation_code==inital_key))]\r\n device_key = r[0]['device_key']\r\n # get device table name\r\n device_table_sql = \"\"\"select * from (\tselect CASE device_type WHEN '3' THEN 'device_pad_args' WHEN '1' THEN 'device_pv3_args' WHEN '4' \r\n THEN 'device_ibox_args' WHEN '2' THEN 'lane' END as device_table\r\n from device_view where garage_id =:garage_id and device_key =:device_key) a \"\"\"\r\n if len(r) > 0: \r\n garage = [dict(row.items()) async for row in await conn.execute(Garage.select().where(Garage.c.garage_id==garage_id))]\r\n customer = [dict(row.items()) async for row in await conn.execute(Customer.select().where(Customer.c.customer_id==customer_id))]\r\n device_type = [dict(row.items()) async for row in await conn.execute(text(device_table_sql),{\"garage_id\" :garage_id ,\"device_key\" :device_key})]\r\n config['garage'] = garage\r\n config['customer'] = customer\r\n print(device_type)\r\n if len(device_type) > 0 and 'device_table' in device_type[0]:\r\n device_sql = f\"\"\"select * from {device_type[0]['device_table']} where {device_type[0]['device_table']}_id = (select device_id from device_view where garage_id =:garage_id and device_key =:device_key) \"\"\"\r\n device = [dict(row.items()) async for row in await conn.execute(text(device_sql),{\"garage_id\" :garage_id ,\"device_key\" :device_key})]\r\n config['device'] = device\r\n else :\r\n config['device'] = ''\r\n except Exception as e:\r\n print(e)\r\n config['error'] = 'Server Error'\r\n return config\r\n\r\n async def encrypt_key_for_pad_config(self,garage_id,device_key,account):\r\n is_new = await self.check_if_code_created_before(garage_id,device_key)\r\n async with self._db.acquire() as conn :\r\n if is_new :\r\n device_key_after_clear= device_key.replace(\".\",\"\")\r\n activation_code = {\r\n 'activation_code':f\"{str(uuid.uuid4())[:4]}-{garage_id}-{device_key_after_clear}\",\r\n 'garage_id':garage_id,\r\n 'create_account_id':account,\r\n 'device_key':device_key\r\n }\r\n r = await conn.execute (ActivationCode.insert(activation_code))\r\n return activation_code['activation_code']\r\n else :\r\n code = await conn.execute(select([ActivationCode.c.activation_code]).where(ActivationCode.c.garage_id == garage_id).where(ActivationCode.c.device_key == device_key))\r\n code = await code.scalar()\r\n return code\r\n \r\n async def check_if_code_created_before(self,garage_id,device_key):\r\n async with self._db.acquire() as conn :\r\n rs = [dict(row.items()) async for row in await conn.execute(ActivationCode.select()\r\n .where(ActivationCode.c.garage_id==garage_id)\r\n .where(ActivationCode.c.device_key==device_key))]\r\n if len(rs)>0:\r\n return False\r\n else:\r\n return True\r\n \r\n","sub_path":"app/services/keystore_service.py","file_name":"keystore_service.py","file_ext":"py","file_size_in_byte":9502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"235317793","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\n\nclass ListBox(Gtk.ScrolledWindow):\n\n def __init__(self, on_row_remove, on_row_select):\n Gtk.ScrolledWindow.__init__(self)\n\n self.on_row_remove = on_row_remove\n\n self.list_box = Gtk.ListBox()\n self.list_box.connect('row-activated', lambda lb, row: on_row_select(self, row.object))\n self.add_with_viewport(self.list_box)\n self.rows = []\n\n def add_item(self, object, display_name):\n row = Gtk.ListBoxRow()\n row_hbox = Gtk.HBox()\n\n label = Gtk.Label(display_name)\n label.set_alignment(0, 0.5)\n row_hbox.pack_start(label, True, True, 5)\n\n if self.on_row_remove is not None:\n remove_button = Gtk.Button(None, image=Gtk.Image(stock=Gtk.STOCK_DELETE))\n remove_button.row = row\n remove_button.connect('clicked', self.remove_item)\n row_hbox.pack_start(remove_button, True, True, 0)\n\n row.add(row_hbox)\n row.object = object\n\n self.list_box.add(row)\n self.rows.append(row)\n self.list_box.show_all()\n\n def remove_item(self, button):\n self.list_box.remove(button.row)\n self.list_box.show_all()\n self.on_row_remove(self, button.row.object)\n\n def clear_selection(self):\n self.list_box.unselect_all()\n\n def clear_items(self):\n for row in self.rows:\n self.list_box.remove(row)\n self.rows.clear()\n","sub_path":"editor/widgets/itemspanel/listbox.py","file_name":"listbox.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"609183839","text":"# kado/__init__.py\n# ================\n#\n# Copying\n# -------\n#\n# Copyright (c) 2018 kado authors and contributors.\n#\n# This file is part of the *kado* project.\n#\n# kado is a free software project. You can redistribute it and/or\n# modify if under the terms of the MIT License.\n#\n# This software project is distributed *as is*, WITHOUT WARRANTY OF ANY\n# KIND; including but not limited to the WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE and NONINFRINGEMENT.\n#\n# You should have received a copy of the MIT License along with\n# kado. If not, see <http://opensource.org/licenses/MIT>.\n#\nimport semver\n\n\n#: Semantic version information of kado.\nVERSION_INFO = semver.VersionInfo(\n major=0,\n minor=0,\n patch=0,\n prerelease='alpha0',\n build=None\n)\n\n#: Project version string.\n__version__ = str(VERSION_INFO)\n","sub_path":"kado/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"330390660","text":"#!/usr/bin/env python\n#\n# Copyright 2010 Per Olofsson\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 json\nimport urllib2\n\nfrom Processor import Processor, ProcessorError\n\n\n__all__ = [\"AdobeReaderURLProvider\"]\n\n\nAR_BASE_URL = (\"http://get.adobe.com/reader/webservices/json/standalone/\"\n \"?platform_type=Macintosh&platform_dist=OSX&platform_arch=x86-32\"\n \"&platform_misc=10.8.0&language=%s&eventname=readerotherversions\")\n\nLANGUAGE_DEFAULT = \"English\"\nMAJOR_VERSION_DEFAULT = \"11\"\n\nMAJOR_VERSION_MATCH_STR = \"adobe/reader/mac/%s\"\n\nclass AdobeReaderURLProvider(Processor):\n description = \"Provides URL to the latest Adobe Reader release.\"\n input_variables = {\n \"language\": {\n \"required\": False,\n \"description\": (\"Which language to download. Examples: 'English', \"\n \"'German', 'Japanese', 'Swedish'. Default is %s.\"\n % LANGUAGE_DEFAULT),\n },\n \"major_version\": {\n \"required\": False,\n \"description\": (\"Major version. Examples: '10', '11'. Defaults to \"\n \"%s\" % MAJOR_VERSION_DEFAULT)\n },\n \"base_url\": {\n \"required\": False,\n \"description\": \"Default is %s\" % AR_BASE_URL,\n },\n }\n output_variables = {\n \"url\": {\n \"description\": \"URL to the latest Adobe Reader release.\",\n },\n }\n \n __doc__ = description\n \n def get_reader_dmg_url(self, base_url, language, major_version):\n request = urllib2.Request(base_url % language)\n request.add_header(\"x-requested-with\", \"XMLHttpRequest\")\n try:\n url_handle = urllib2.urlopen(request)\n json_response = url_handle.read()\n url_handle.close()\n except BaseException as e:\n raise ProcessorError(\"Can't open %s: %s\" % (base_url, e))\n \n reader_info = json.loads(json_response)\n major_version_string = MAJOR_VERSION_MATCH_STR % major_version\n matches = [item[\"download_url\"] for item in reader_info \n if major_version_string in item[\"download_url\"]]\n try:\n return matches[0]\n except IndexError:\n raise ProcessorError(\n \"Can't find Adobe Reader download URL for %s, version %s\" \n % (language, major_version))\n \n def main(self):\n # Determine base_url, language and major_version.\n base_url = self.env.get(\"base_url\", AR_BASE_URL)\n language = self.env.get(\"language\", LANGUAGE_DEFAULT)\n major_version = self.env.get(\"major_version\", MAJOR_VERSION_DEFAULT)\n \n self.env[\"url\"] = self.get_reader_dmg_url(\n base_url, language, major_version)\n \n\nif __name__ == \"__main__\":\n processor = AdobeReaderURLProvider()\n processor.execute_shell()\n \n","sub_path":"Code/autopkglib/processors/AdobeReaderURLProvider.py","file_name":"AdobeReaderURLProvider.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"104396681","text":"#TRABAJO PRACTICO Nº 2\r\n\r\n#Ejercicio 2: Escribir un programa que permita ingresar tres numeros enteros, calcular y mostrar su promedio.\r\n\r\n#Paso 1: Introducir tres variables de enteros\r\nnro1=int(input(\"Ingrese un primer número entero: \"))\r\nnro2=int(input(\"Ingrese un segundo número entero: \"))\r\nnro3=int(input(\"Ingrese un tercer número entero: \"))\r\n \r\n#Paso 2: Devolver su promedio\r\nprint(\"El promedio entre los tres números es: \", ((nro1+nro2+nro3)/3))\r\n\r\nprint(\"Es decir,\",nro1+nro2+nro3,\"dividido 3 es igual a \",(nro1+nro2+nro3)/3)\r\n\r\n# Se usa la variable \"int\" para numeros enteros. Si ingresamos un número decimal, salta error.\r\n# Se usa la variable \"float\" para ingresar números decimales, y \"str\" para cadena de caracteres.\r\n# No se puede imprimir usando \"int\" porque las variables decimales no pueden interpretarse como enteras.\r\n# El promedio de un conjunto de números es la suma de ellos y su división por la cantidad de términos.\r\n","sub_path":"Trabajo Práctico 2/tp2_2.py","file_name":"tp2_2.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"508922925","text":"# Author: @ MuLun_Zhu\n# @Time : 2020/2/15 10:03 上午\n# 提交text\n\nimport pymysql\n\n# 工作目录\ndb = pymysql.connect(host=\"124.71.184.35\", user=\"root\", password=\"Czr8686478//\", database=\"plant\", port=3306)\ncur = db.cursor()\n\n\n# 注册sql验证\ndef registersql(id, pwd):\n register_sql = \"insert into user(iduser,password) values(%d,'%s');\" % (int(id), pwd)\n print(register_sql)\n cur.execute(register_sql)\n db.commit()\n num1 = cur.rowcount\n print(num1)\n if num1 != 1:\n print(\"注册 失败失败失败\")\n return False\n else:\n print(\"注册 成功成功成功\")\n return True\n\n\n# 登录sql验证\ndef signsql(iduser, pwd):\n sign_sql = \"select user.iduser,user.password from user where iduser=%d and password='%s';\" % (int(iduser), pwd)\n print(sign_sql)\n cur.execute(sign_sql)\n longth = cur.fetchall()\n print(longth)\n if len(longth) != 1:\n print(\"登录 sql注入\")\n return \"warn\"\n else:\n print(\"登录 成功成功成功\")\n return \"ok\"\n\n\n# 判断账号是否存在 登录界面\ndef sign_sql_account_exist(iduser):\n sign_sql = \"select user.iduser,user.password from user where iduser=%d ;\" % (int(iduser))\n print(sign_sql)\n cur.execute(sign_sql)\n longth = cur.fetchall()\n print(longth)\n print(len(longth))\n if len(longth) == 0:\n print(\"登录失败 账号不存在\")\n return \"no\"\n elif len(longth) == 1:\n print(\"登录 存在此账号\")\n return \"yes\"\n else:\n print(\"sql注入\")\n return \"no\"\n\n\n# 登陆后自动显示昵称\ndef nicknamesql(name):\n # try:\n sign_sql = \"select user.nickname from user where iduser=%s;\"\n print(sign_sql)\n cur.execute(sign_sql, (name))\n # except Exception as result:\n # print(result)\n # else:\n longth = cur.fetchall()\n print(longth)\n nickname_str = longth[0][0]\n print(nickname_str)\n if isinstance(nickname_str, str):\n print(\"昵称获取成功\")\n return nickname_str\n else:\n print(\"昵称获取失败\")\n return False\n\n\n# 密码更新\ndef pwdsql(id, pwd):\n register_sql = \"update user set password='%s' where iduser=%d;\" % (pwd, int(id))\n print(register_sql)\n cur.execute(register_sql)\n db.commit()\n num2 = cur.rowcount\n if num2 != 1:\n print(\"更新密码 失败失败失败\")\n return 0\n else:\n print(\"更新密码 成功成功成功\")\n return 1\n\n\n# 更改昵称\ndef nickname_change_sql(name, nickname):\n register_sql = \"update user set nickname=%s where iduser=%s;\"\n print(register_sql)\n cur.execute(register_sql, (nickname, name))\n db.commit()\n num3 = cur.rowcount\n if cur.rowcount != 1:\n print(\"更改昵称 失败失败失败\")\n return 0\n else:\n print(\"更改昵称 成功成功成功\")\n return 1\n\n\n# 输入植物名,搜索环境\ndef search_for_environment(name):\n register_sql = \"select info.name,info.type,info.ph,info.light,info.temp,info.rh,info.sm,info.n,info.p,info.k from info where name like '%{name}%';\".format(\n name=name)\n print(register_sql)\n cur.execute(register_sql)\n tuple_info = cur.fetchall()\n print(\"serach_tuple_info = \", end=\"\")\n print(tuple_info)\n num4 = len(tuple_info)\n print(num4)\n # tuple处理成列表\n list_info = []\n for tuple in tuple_info:\n midden = []\n for item in tuple:\n midden.append(item)\n list_info.append(midden)\n\n if num4 == 0:\n print(\"无相关数据 \")\n return 0\n elif num4 >= 2:\n print(\"多条数据,默认使用第一条\")\n return list_info\n else:\n print(\"一条数据 成功成功成功\")\n return list_info\n\n\n# 筛选正向检索结果\ndef filtrate(name, type):\n filtrate_sql = \"select info.name,info.type,info.ph,info.light,info.temp,info.rh,info.sm,info.n,info.p,info.k from info where name like '%{name}%' and type like '%{type}%';\".format(\n name=name, type=type)\n print(filtrate_sql)\n cur.execute(filtrate_sql)\n tuple_info = cur.fetchall()\n print(\"filtrate_tuple_info = \", end=\"\")\n print(tuple_info)\n num4 = len(tuple_info)\n print(num4)\n # tuple处理成列表\n list_info = []\n for tuple in tuple_info:\n midden = []\n for item in tuple:\n midden.append(item)\n list_info.append(midden)\n\n if num4 == 0:\n print(\"无相关数据 \")\n return 0\n else:\n return list_info\n\n\n# 根据环境,搜索植物\ndef search_for_plant_sql(info_list):\n if info_list[0] == \"4-5\":\n info_list[0] = \"4%\"\n elif info_list[0] == \"5-6\":\n info_list[0] = \"5%\"\n elif info_list[0] == \"6-7\":\n info_list[0] = \"6%\"\n elif info_list[0] == \"7-8\":\n info_list[0] = \"7%\"\n elif info_list[0] == \"8-9\":\n info_list[0] = \"8%\"\n elif info_list[0] == \"9-10\":\n info_list[0] = \"9%\"\n\n change_list = [5, 5, 5, 5, 5, 5]\n for index, item in enumerate(info_list[2:]):\n if item == 5000:\n change_list[index] = 5000\n print(change_list)\n\n filtrate_sql = \"select info.name,info.type,info.ph,info.light,info.temp,info.rh,info.sm,info.n,info.p,info.k\" \\\n \" from info where\" \\\n \" info.ph like '%s' and\" \\\n \" info.light like '%s' and\" \\\n \" info.temp between %d and %d and\" \\\n \" info.rh between %d and %d and\" \\\n \" info.sm between %d and %d and\" \\\n \" info.n between %d and %d and\" \\\n \" info.p between %d and %d and\" \\\n \" info.k between %d and %d;\" % (info_list[0], info_list[1],\n info_list[2] - change_list[0], info_list[2] + change_list[0],\n info_list[3] - change_list[1], info_list[3] + change_list[1],\n info_list[4] - change_list[2], info_list[4] + change_list[2],\n info_list[5] - change_list[3], info_list[5] + change_list[3],\n info_list[6] - change_list[4], info_list[6] + change_list[4],\n info_list[7] - change_list[5], info_list[7] + change_list[5])\n print(filtrate_sql)\n cur.execute(filtrate_sql)\n info_tuple = cur.fetchall()\n print(\"for_plant_tuple_info = \", end=\"\")\n print(info_tuple)\n num5 = len(info_tuple)\n print(num5)\n # tuple处理成列表\n list_info = []\n for tuple in info_tuple:\n midden = []\n for item in tuple:\n midden.append(item)\n list_info.append(midden)\n\n if num5 == 0:\n print(\"无相关数据 \")\n return 0\n else:\n return list_info\n\n\n# 筛选反向检索结果\ndef filtrate_for_plant_sql(info_list, type):\n if info_list[0] == \"4-5\":\n info_list[0] = \"4%\"\n elif info_list[0] == \"5-6\":\n info_list[0] = \"5%\"\n elif info_list[0] == \"6-7\":\n info_list[0] = \"6%\"\n elif info_list[0] == \"7-8\":\n info_list[0] = \"7%\"\n elif info_list[0] == \"8-9\":\n info_list[0] = \"8%\"\n elif info_list[0] == \"9-10\":\n info_list[0] = \"9%\"\n\n change_list = [5, 5, 5, 5, 5, 5]\n for index, item in enumerate(info_list[2:]):\n if item == 5000:\n change_list[index] = 5000\n print(change_list)\n print(type)\n filtrate_sql = \"select info.name,info.type,info.ph,info.light,info.temp,info.rh,info.sm,info.n,info.p,info.k\" \\\n \" from info where\" \\\n \" info.ph like '%s' and\" \\\n \" info.light like '%s' and \" \\\n \" info.type='%s'and \" \\\n \" info.temp between %d and %d and\" \\\n \" info.rh between %d and %d and\" \\\n \" info.sm between %d and %d and\" \\\n \" info.n between %d and %d and\" \\\n \" info.p between %d and %d and\" \\\n \" info.k between %d and %d;\" % (info_list[0], info_list[1], type,\n info_list[2] - change_list[0], info_list[2] + change_list[0],\n info_list[3] - change_list[1], info_list[3] + change_list[1],\n info_list[4] - change_list[2], info_list[4] + change_list[2],\n info_list[5] - change_list[3], info_list[5] + change_list[3],\n info_list[6] - change_list[4], info_list[6] + change_list[4],\n info_list[7] - change_list[5], info_list[7] + change_list[5],)\n print(filtrate_sql)\n cur.execute(filtrate_sql)\n info_tuple = cur.fetchall()\n print(\"for_plant_tuple_info = \", end=\"\")\n print(info_tuple)\n num5 = len(info_tuple)\n print(num5)\n # tuple处理成列表\n list_info = []\n for tuple in info_tuple:\n midden = []\n for item in tuple:\n midden.append(item)\n list_info.append(midden)\n\n if num5 == 0:\n print(\"��相关数据 \")\n return 0\n else:\n return list_info\n\n\n# 提交数据\ndef submit_info(infolist):\n sub_sql = \"insert into info (info.name,info.type,info.ph,info.light,info.temp,info.rh,info.sm,info.n,info.p,info.k)\" \\\n \"values('{name}','{type}','{ph}','{light}',{temp},{rh},{sm},{n},{p},{k});\".format(\n name=infolist[0], type=infolist[1], ph=infolist[3], light=infolist[2], temp=infolist[4], rh=infolist[5],\n sm=infolist[6], n=infolist[7], p=infolist[8], k=infolist[9])\n print(sub_sql)\n cur.execute(sub_sql)\n num6 = cur.rowcount\n db.commit()\n if num6 == 1:\n print(\"插入数据成功 \")\n return 1\n else:\n print(\"插入数据失败 \")\n return 0\n\n\n# 关闭db和游标\ndef close_db_and_cur():\n cur.close()\n db.close()\n print(\"合法退出程序\")\n","sub_path":"pro_sql.py","file_name":"pro_sql.py","file_ext":"py","file_size_in_byte":10088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"587339849","text":"from django.db import models\nfrom django.conf import settings\nfrom easy_thumbnails.files import get_thumbnailer\n\n\ndef product_item_file_path_upload_to(instance, filename):\n return 'product_images/{}/{}'.format(instance.product.tenant.pk, filename)\n\n\nclass ProductImage(models.Model):\n product = models.ForeignKey('Product', related_name='product_images')\n file_path = models.FileField(upload_to=product_item_file_path_upload_to)\n sort_order = models.IntegerField(\"Sort Order\", null=False, default=0)\n\n def __str__(self):\n return self.file_path.url\n\n def convert_to_dict(self):\n return {\n \"id\": self.pk,\n \"productId\": self.product.pk,\n \"filePath\": self.file_path.url,\n \"sortOrder\": self.sort_order\n }\n\n def thumbnail(self):\n return_value = '<img src=\"{}{}\" alt=\"\"/>'.format(settings.STATIC_URL, \"main/images/unknown-thumbnail.png\")\n if self.file_path:\n try:\n thumbnailer = get_thumbnailer(self.file_path)\n thumbnail = thumbnailer.get_thumbnail({'size': (120, 90), 'crop': True})\n return_value = '<img src=\"{}{}\" alt=\"{}\"/>'.format(settings.MEDIA_URL, thumbnail, self.file_path.url)\n except Exception as e:\n # Log here...\n pass\n\n return return_value\n\n class Meta:\n app_label = \"db\"\n verbose_name = \"Product Image\"\n verbose_name_plural = \"Product Images\"\n ordering = [\"file_path\"]\n","sub_path":"db/models/product_image.py","file_name":"product_image.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"1010193","text":"import logging\nfrom logging.handlers import RotatingFileHandler\nimport os\nfrom datetime import datetime\n\nimport coloredlogs\n\nimport settings as default_settings\n\n\nlogging.getLogger('urllib3.connectionpool').setLevel(logging.ERROR)\n\n\n\ndef main_logger(settings=default_settings):\n log_dir = os.path.dirname(settings.LOG_FILE_PATH)\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n root_logger = logging.getLogger()\n level = getattr(logging, settings.LOG_LEVEL)\n log_formatter = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')\n filename = datetime.now().strftime('%Y_%m_%d.log')\n filepath = os.path.join(log_dir, filename)\n\n file_handler = RotatingFileHandler(\n filename=filepath,\n mode='a',\n maxBytes=settings.LOG_MAX_FILE_BYTES,\n backupCount=settings.LOG_BACKUP_COUNT\n )\n\n file_handler.setFormatter(log_formatter)\n root_logger.addHandler(file_handler)\n\n root_logger.setLevel(level)\n coloredlogs.install(level=level)\n return root_logger\n\n\nlogger = main_logger()\n","sub_path":"scrapyard/common/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"607311211","text":"# -*- coding: utf-8 -*-\ndef primo(a):\n b=0\n for i in range(1,a+1,1):\n if x%i==0:\n b=b+1\n if b==2:\n return True\n else:\n return False\nc=int(input('digite c:'))\nd=int(input('digite d:'))\nif primo(c) and primo(d):\n if d==c+2:\n print('S')\nif primo(c)==False or primo(d)==False:\n print('N')\n \n\n \n \n ","sub_path":"moodledata/vpl_data/107/usersdata/217/52184/submittedfiles/questao3.py","file_name":"questao3.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"552328336","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 precDown(self, lists, i=0):\n lchild = i*2 + 1\n rchild = lchild + 1\n while rchild < len(lists) or lchild < len(lists):\n if lists[lchild] != lists[-1] and lists[rchild].val < lists[lchild].val:\n child = rchild\n else:\n child = lchild\n if lists[i].val > lists[child].val:\n lists[i], lists[child] = lists[child], lists[i]\n i = child\n lchild = i*2 + 1\n rchild = lchild + 1\n else:\n break\n \n def buildHeap(self, lists):\n lists = filter(None, lists)\n start = len(lists)/2 -1\n for i in range(start, -1, -1):\n self.precDown(lists, i)\n return lists\n \n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n if not filter(None, lists):\n return []\n lists = self.buildHeap(lists)\n head = lists[0]\n cur = head\n curLen = len(lists)\n lists[0] = lists[0].next\n while True:\n if lists[0] is None:\n lists = self.buildHeap(lists)\n else:\n lists = self.precDown(lists, 0)\n if not lists:\n break\n cur.next = lists[0]\n lists[0] = lists[0].next\n cur = cur.next\n return head\n","sub_path":"algorithms/merge_k_sorted_lists_[heap_timeout].py","file_name":"merge_k_sorted_lists_[heap_timeout].py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"393729394","text":"\n\nimport pandas as pd\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n\n#Read Data File from syatem....\ndata = pd.read_excel(\"C:/Users/inparp00/Desktop/dataFile.xlsx\")\nprint(type(data))\n\n#print(data.get(\"email\"))\n\nlistOfEmails = list(data.get(\"email\"))\nlistOFNames = list(data.get(\"name\"))\n#print(listOfEmails)\n\n\n#To Send Emails\ntry:\n \n #Setting Up the Server\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login('EmailID', 'PASSWORD')\n\n #Setting Sender and Receiver\n from_ = 'EmailID'\n to_ = listOfEmails\n\n #Setting message (This can also contain Image)\n message = MIMEMultipart(\"alternative\")\n\n #Defining subject\n message[\"Subject\"] = \"Proposal for scrap and non ferrous metals.\"\n message[\"from\"] = 'EmailID'\n\n\n#Writing message in HTML Format\n html = '''\n <html>\n <head></head>\n\n <body>\n \n\n<p>Dear Sir/Madam,</p>\n<p>I would like to inform you....</p>\n<p>I will be pleased...</p>\n<p>We hope to have.........</p>\n<p>Looking forward to ........</p>\n\n </body>\n\n </html>\n \n '''\n\n#Converting html to Text\n messagePart2 = MIMEText(html, \"html\")\n\n#Attaching HTML part to message which was defined earlier\n message.attach(messagePart2)\n\n\n#Sending message\n server.sendmail(from_,to_,message.as_string())\n\n print(\"Message Sent\")\n\n\n server.quit()\n\nexcept Exception as e:\n print(e)","sub_path":"EmailAutomation/emailBotGmail.py","file_name":"emailBotGmail.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"39445781","text":"import queue\ndef diff(word1,word2):\n ran=len(word1)\n cnt=0\n for i in range(ran):\n if word1[i]!=word2[i]:\n cnt+=1\n if cnt==1:\n return 1\n else:\n return 0\n \ndef solution(begin, target, words):\n if target not in words:\n return 0\n if begin==target:\n return 0\n word_num=len(words)\n check=[0]*word_num\n q=queue.Queue()\n q.put(begin)\n answer=1\n while q:\n comp=q.get()\n for i in range(word_num):\n if comp==words[i]:\n answer=check[i]+1\n for i in range(word_num):\n if diff(comp,words[i])==1 and check[i]==0:\n if words[i]==target:\n return answer\n q.put(words[i])\n check[i]=answer\n","sub_path":"Programmers/단어 변환.py","file_name":"단어 변환.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"505237561","text":"\nimport os\nimport pickle\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy.stats import norm\nfrom sklearn import mixture\n\nfrom keras.layers import Input, Dense, Lambda, Conv2D, MaxPooling2D,UpSampling2D, Flatten, Reshape\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras import objectives , utils,optimizers\nfrom keras.datasets import mnist\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom keras.callbacks import Callback\nimport tensorflow as tf\n\nimport sys\nsys.path.append('../../utils')\n\nfrom importDatasets import importMnist\nfrom importDatasets import importMnistFashion\nfrom importDatasets import importOlivetti\nfrom importDatasets import importSquareAndCross\n\n\nfrom datetime import datetime\n# -----------------------------------------------------------------------------\n# Fetch Data\n# -----------------------------------------------------------------------------\n\n# fh_import_dataset = lambda : importMnist()\nfh_import_dataset = lambda : importMnistFashion()\n\n(dataset_name,\n x_train,\n x_test,\n y_train,\n y_test,\n sample_dim,\n sample_channels,\n original_dim,\n num_classes) = fh_import_dataset()\n\ntraining_size = 55000\nx_val = x_train[training_size:,:]\ny_val = y_train[training_size:,:]\nx_train =x_train[:training_size,:] #np.reshape(x_train, (len(x_train), 28, 28, 1)) # adapt this if using `channels_first` image data format\nx_test = x_test[:training_size,:] #np.reshape(x_test, (len(x_test), 28, 28, 1))\ny_train = y_train[:training_size,:]\ny_test = y_test[:training_size,:]\n\n\n\nbatch_size = 100\nlatent_dim = 15\nepochs = 300\nintermediate_dim = 500\nepsilon_std = 1.0\nlearning_rate = 0.00001\n\n\n# -----------------------------------------------------------------------------\n# Build Model\n# -----------------------------------------------------------------------------\n\nexperiment_name = dataset_name + \\\n '_____z_dim_' + str(latent_dim)\n\n # if ~ os.path.isdir('../experiments'):\n # os.makedirs('../experiments')\nexperiment_dir_path = '../experiments/exp' + \\\n '_____' + \\\n str(datetime.now().strftime('%Y-%m-%d_____%H-%M-%S')) + \\\n '_____' + \\\n experiment_name\nos.makedirs(experiment_dir_path)\n\n\n########## Network Layers ########################################################\nx = Input(batch_shape=(batch_size, original_dim))\nx_reshaped = Reshape((28,28,1))\nh_e_1 = Conv2D(16, (3, 3), activation='relu', padding='same')\nh_e_2 = MaxPooling2D((2, 2), padding='same')\nh_e_3 = Conv2D(16, (3, 3), activation='relu', padding='same')\nh_e_4 = MaxPooling2D((2, 2), padding='same')\nh_e_5 = Conv2D(8, (3, 3), activation='relu', padding='same')\nh_e_6 = MaxPooling2D((2, 2), padding='same')\nh_e_7 = Flatten()\n\nz_mean = Dense(latent_dim)\nz_log_var = Dense(latent_dim)\n\ndef sampling(args):\n z_mean, z_log_var = args\n epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.,\n stddev=epsilon_std)\n return z_mean + K.exp(z_log_var / 2) * epsilon\n\n# h_d_x_1 = Dense(4*4*8, activation = 'relu')\n# h_d_x_2 = Reshape((4,4,8))\n# h_d_x_3 = Conv2D(8, (3, 3), activation='relu', padding='same')\n# h_d_x_4 = UpSampling2D((2, 2))\n# h_d_x_5 = Conv2D(16, (3, 3), activation='relu', padding='same')\n# h_d_x_6 = UpSampling2D((2, 2))\n# h_d_x_7 = Conv2D(16, (3, 3), activation='relu')\n# h_d_x_8 = UpSampling2D((2, 2))\n# x_decoded_reshaped = Conv2D(1, (3, 3), activation='sigmoid', padding='same')\n# x_decoded = Flatten()\n\nh_d_y_1 = Dense(intermediate_dim, activation='relu')\nh_d_y_2 = Dense(intermediate_dim, activation='relu')\ny_decoded = Dense(10, activation='sigmoid')\n\nyy = Input(batch_shape = (batch_size,10))\n##### Build model #########################################################################################\n_x_reshaped = x_reshaped(x)\n_h_e_1 = h_e_1(_x_reshaped)\n_h_e_2 = h_e_2(_h_e_1)\n_h_e_3 = h_e_3(_h_e_2)\n_h_e_4 = h_e_4(_h_e_3)\n_h_e_5 = h_e_5(_h_e_4)\n_h_e_6 = h_e_6(_h_e_5)\n_h_e_7 = h_e_7(_h_e_6)\n\n\n_z_mean = z_mean(_h_e_7)\n_z_log_var = z_log_var(_h_e_7)\nz = Lambda(sampling, output_shape=(latent_dim,))([_z_mean, _z_log_var])\n\n# _h_d_x_1 = h_d_x_1(z)\n# _h_d_x_2 = h_d_x_2(_h_d_x_1)\n# _h_d_x_3 = h_d_x_3(_h_d_x_2)\n# _h_d_x_4 = h_d_x_4(_h_d_x_3)\n# _h_d_x_5 = h_d_x_5(_h_d_x_4)\n# _h_d_x_6 = h_d_x_6(_h_d_x_5)\n# _h_d_x_7 = h_d_x_7(_h_d_x_6)\n# _h_d_x_8 = h_d_x_8(_h_d_x_7)\n# _x_decoded_reshaped = x_decoded_reshaped(_h_d_x_8)\n# _x_decoded = x_decoded(_x_decoded_reshaped)\n\n\n_h_d_y_1 = h_d_y_1(z)\n_h_d_y_2 = h_d_y_2(_h_d_y_1)\n_y_decoded = y_decoded(_h_d_y_2)\n\n###### Define Loss ################################################################################\n\n# def vae_loss(x, _x_decoded):\ndef vae_loss(y, _y_decoded):\n\n # xent_loss = original_dim * objectives.binary_crossentropy(x, _x_decoded)\n kl_loss = - 0.5 * K.sum(1 + _z_log_var - K.square(_z_mean) - K.exp(_z_log_var), axis=-1)\n y_loss= 10 * objectives.categorical_crossentropy(yy, _y_decoded)\n # return xent_loss + kl_loss + y_loss\n return kl_loss + y_loss\n\nmy_adam = optimizers.Adam(lr=learning_rate, beta_1=0.1)\n\n# vae = Model(inputs = [x,yy], outputs =[_x_decoded,_y_decoded]) #(x,_x_decoded)\nvae = Model(inputs = [x,yy], outputs =[_y_decoded]) #(x,_x_decoded)\nvae.compile(optimizer=my_adam, loss=vae_loss)\n\n\n# -----------------------------------------------------------------------------\n# Train Model\n# -----------------------------------------------------------------------------\n#### Build another model####################################################\n_x_reshaped_ = x_reshaped(x)\n_h_e_1_ = h_e_1(_x_reshaped_)\n_h_e_2_ = h_e_2(_h_e_1_)\n_h_e_3_ = h_e_3(_h_e_2_)\n_h_e_4_ = h_e_4(_h_e_3_)\n_h_e_5_ = h_e_5(_h_e_4_)\n_h_e_6_ = h_e_6(_h_e_5_)\n_h_e_7_ = h_e_7(_h_e_6_)\n\n\n_z_mean_ = z_mean(_h_e_7_)\n\n\n# _h_d_x_1_ = h_d_x_1(_z_mean_)\n# _h_d_x_2_ = h_d_x_2(_h_d_x_1_)\n# _h_d_x_3_ = h_d_x_3(_h_d_x_2_)\n# _h_d_x_4_ = h_d_x_4(_h_d_x_3_)\n# _h_d_x_5_ = h_d_x_5(_h_d_x_4_)\n# _h_d_x_6_ = h_d_x_6(_h_d_x_5_)\n# _h_d_x_7_ = h_d_x_7(_h_d_x_6_)\n# _h_d_x_8_ = h_d_x_8(_h_d_x_7_)\n# _x_decoded_reshaped_ = x_decoded_reshaped(_h_d_x_8_)\n# _x_decoded_ = x_decoded(_x_decoded_reshaped_)\n\n_h_d_y_1_ = h_d_y_1(_z_mean_)\n_h_d_y_2_ = h_d_y_2(_h_d_y_1_)\n_y_decoded_ = y_decoded(_h_d_y_2_)\n\n\n# vaeencoder = Model(x,[_x_decoded_,_y_decoded_])\nvaeencoder = Model(x,[_y_decoded_])\n#####################################################################################\n\n# _, b = vaeencoder.predict(x_test, batch_size = batch_size)\nb = vaeencoder.predict(x_test, batch_size = batch_size)\n\ny_test_label = np.argmax(y_test,axis =1)\n\nAccuracy = np.zeros((epochs,1))\nii=0\npickle.dump((ii),open('counter','wb'))\ntext_file_name = experiment_dir_path + '/accuracy_log.txt'\nclass ACCURACY(Callback):\n\n def on_epoch_end(self,batch,logs = {}):\n ii= pickle.load(open('counter', 'rb'))\n # _, b = vaeencoder.predict(x_test, batch_size = batch_size)\n b = vaeencoder.predict(x_test, batch_size = batch_size)\n Accuracy[ii, 0]\n\n lll = np.argmax(b, axis =1)\n n_error = np.count_nonzero(lll - y_test_label)\n ACC = 1 - n_error / 10000\n Accuracy[ii,0] = ACC\n print('\\n accuracy = ', ACC)\n ii= ii + 1\n pickle.dump((ii),open('counter', 'wb'))\n with open(text_file_name, 'a') as text_file:\n print('Epoch #{} Accuracy:{} \\n'.format(ii, ACC), file=text_file)\n\naccuracy = ACCURACY()\n\n# model_weights = pickle.load(open('weights_vaesdr_' + str(latent_dim) + 'd_trained_on_' + dataset_name, 'rb'))\n# vae.set_weights(model_weights)\n\n# vae.fit([x_train, y_train],[x_train, y_train],\nvae.fit([x_train, y_train],[y_train],\n shuffle=True,\n epochs=epochs,\n batch_size=batch_size,\n # validation_data =([x_val,y_val],[x_val,y_val]),\n validation_data =([x_val,y_val],[y_val]),\n callbacks = [accuracy])\n\nmodel_weights = vae.get_weights()\npickle.dump((model_weights), open('weights_vaesdr_' + str(latent_dim) + 'd_trained_on_' + dataset_name, 'wb'))\n############################################################################################################\n\n# -----------------------------------------------------------------------------\n# Analysis\n# -----------------------------------------------------------------------------\n\n###### Builder Encoder ######################################################################\nencoder = Model(x, _z_mean)\n\nx_test_encoded = encoder.predict(x_test, batch_size=batch_size)\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], linewidth = 0, c=y_test_label)\n\n# #### build generator #########################################################################\n# generator_input = Input(shape=(latent_dim,))\n\n# _h_g_x_1_ = h_d_x_1(generator_input)\n# _h_g_x_2_ = h_d_x_2(_h_g_x_1_)\n# _h_g_x_3_ = h_d_x_3(_h_g_x_2_)\n# _h_g_x_4_ = h_d_x_4(_h_g_x_3_)\n# _h_g_x_5_ = h_d_x_5(_h_g_x_4_)\n# _h_g_x_6_ = h_d_x_6(_h_g_x_5_)\n# _h_g_x_7_ = h_d_x_7(_h_g_x_6_)\n# _h_g_x_8_ = h_d_x_8(_h_g_x_7_)\n# _x_generated_reshaped = x_decoded_reshaped(_h_g_x_8_)\n# _x_generated_ = x_decoded(_x_generated_reshaped)\n\n# generator = Model(generator_input,_x_generated_)\n# # -------------------------------------\n# # Fit GMM\n# # -------------------------------------\n\n# # display a 2D plot of the digit classes in the latent space\n# x_train_encoded = encoder.predict(x_train, batch_size=batch_size)\n\n# n_components = num_classes\n# cv_type = 'full'\n# gmm = mixture.GaussianMixture(n_components=n_components, covariance_type=cv_type)\n# gmm.fit(x_train_encoded)\n\n# x_decoded, b = vaeencoder.predict(x_test,batch_size = batch_size)\n\n\n# # -------------------------------------\n# # Plots\n# # -------------------------------------\n\n\n\n# def getFigureOfSamplesForInput(x_samples, sample_dim, number_of_sample_images, grid_x, grid_y):\n# figure = np.zeros((sample_dim * number_of_sample_images, sample_dim * number_of_sample_images))\n# for i, yi in enumerate(grid_x):\n# for j, xi in enumerate(grid_y):\n# digit = x_samples[i * number_of_sample_images + j, :].reshape(sample_dim, sample_dim)\n# figure[i * sample_dim: (i + 1) * sample_dim,\n# j * sample_dim: (j + 1) * sample_dim] = digit\n# return figure\n\n\n# number_of_sample_images = 15\n# grid_x = norm.ppf(np.linspace(0.05, 0.95, number_of_sample_images))\n# grid_y = norm.ppf(np.linspace(0.05, 0.95, number_of_sample_images))\n\n# plt.figure()\n\n# ax = plt.subplot(1,3,1)\n# x_samples_a = x_test\n# canvas = getFigureOfSamplesForInput(x_samples_a, sample_dim, number_of_sample_images, grid_x, grid_y)\n# plt.imshow(canvas, cmap='Greys_r')\n# ax.set_title('Original Test Images', fontsize=8)\n# ax.get_xaxis().set_visible(False)\n# ax.get_yaxis().set_visible(False)\n\n# ax = plt.subplot(1,3,2)\n# x_samples_b = x_decoded\n# canvas = getFigureOfSamplesForInput(x_samples_b, sample_dim, number_of_sample_images, grid_x, grid_y)\n# plt.imshow(canvas, cmap='Greys_r')\n# ax.set_title('Reconstructed Test Images', fontsize=8)\n# ax.get_xaxis().set_visible(False)\n# ax.get_yaxis().set_visible(False)\n\n# ax = plt.subplot(1,3,3)\n# x_samples_c = gmm.sample(10000)\n# x_samples_c = np.random.permutation(x_samples_c[0]) # need to randomly permute because gmm.sample samples 1000 from class 1, then 1000 from class 2, etc.\n# x_samples_c = generator.predict(x_samples_c)\n# canvas = getFigureOfSamplesForInput(x_samples_c, sample_dim, number_of_sample_images, grid_x, grid_y)\n# plt.imshow(canvas, cmap='Greys_r')\n# ax.set_title('Generated Images', fontsize=8)\n# ax.get_xaxis().set_visible(False)\n# ax.get_yaxis().set_visible(False)\n\n# plt.show()\n# # plt.savefig('images/'+ dataset_name + '_samples.png')\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"amir/supervised_conv_bw/main_without_x.py","file_name":"main_without_x.py","file_ext":"py","file_size_in_byte":12150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"372889727","text":"import PyQt5.QtWidgets as qt_widgets\nimport PyQt5.QtCore as qt_core\nimport handlers.userhandler as user_handling\nimport handlers.accounthandler as account_handling\nimport pyqt5_global.variables as stack\n\n#Signup window class and functionality\nclass Window_Overview(qt_widgets.QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Using Overview')\n self.setProperty('Main_Window', True)\n self.setGeometry(50, 50, 1000, 500)\n\n def user_interface(self, userData):\n #Begin Column: Checking information\n self.labelChecking = qt_widgets.QLabel(self)\n self.labelChecking.setText('Checking')\n self.labelChecking.move(160, 30)\n\n self.labelAccountChecking = qt_widgets.QLabel(self)\n self.buttonChecking = qt_widgets.QPushButton('Details', self)\n if(user_handling.findChecking(userData)):\n self.labelAccountChecking.setText('Checking account found')\n self.labelAccountChecking.move(160, 80)\n self.buttonChecking.setText('Details')\n self.buttonChecking.move(160, 120)\n else:\n self.labelAccountChecking.setText('Checking account NOT found')\n self.labelAccountChecking.move(160, 80)\n self.buttonChecking.setText('Add Account')\n self.buttonChecking.move(160, 120)\n\n #Begin Column: Savings information\n self.labelSavings = qt_widgets.QLabel(self)\n self.labelSavings.setText('Savings')\n self.labelSavings.move(360, 30)\n\n self.labelAccountSavings = qt_widgets.QLabel(self)\n self.buttonSavings = qt_widgets.QPushButton('Details', self)\n if(user_handling.findSavings(userData)):\n self.labelAccountSavings.setText('Savings account found')\n self.labelAccountSavings.move(360, 80)\n self.buttonSavings.setText('Details')\n self.buttonSavings.move(360, 120)\n else:\n self.labelAccountSavings.setText('Savings account NOT found')\n self.labelAccountSavings.move(360, 80)\n self.buttonSavings.setText('Add Account')\n self.buttonSavings.move(360, 120)\n\n #Begin Column: Credit information\n self.labelCredit = qt_widgets.QLabel(self)\n self.labelCredit.setText('Credit')\n self.labelCredit.move(560, 30)\n self.show()\n","sub_path":"pybank/pybank/account_overview.py","file_name":"account_overview.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"96889123","text":"#!/usr/bin/env python3\n\nimport iterm2\nimport random\n\nasync def SetPresetInSession(connection, session, preset_name):\n preset = await iterm2.ColorPreset.async_get(connection, preset_name)\n if not preset:\n return\n profile = await session.async_get_profile()\n if not profile:\n return\n await profile.async_set_color_preset(preset)\n print(\"activating {}\".format(preset_name))\n\nasync def main(connection):\n app = await iterm2.async_get_app(connection)\n color_preset_names = await iterm2.ColorPreset.async_get_list(connection)\n session = app.current_terminal_window.current_tab.current_session\n await SetPresetInSession(connection, session, random.choice(color_preset_names))\n\niterm2.run_until_complete(main)\n","sub_path":"change-theme.py","file_name":"change-theme.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"295450120","text":"\"\"\" DaCe Python parsing functionality and entry point to Python frontend. \"\"\"\nfrom __future__ import print_function\nimport inspect\nimport copy\nimport os\n\nfrom dace import symbolic, dtypes\nfrom dace.config import Config\nfrom dace.frontend.python import newast\nfrom dace.sdfg import SDFG\nfrom dace.data import create_datadescriptor\n\n\ndef _get_type_annotations(f, f_argnames, decorator_args):\n \"\"\" Obtains types from decorator or from type annotations in a function. \n \"\"\"\n type_annotations = {}\n if hasattr(f, '__annotations__'):\n type_annotations.update(f.__annotations__)\n\n # Type annotation conditions\n has_args = len(decorator_args) > 0\n has_annotations = len(type_annotations) > 0\n if 'return' in type_annotations:\n raise TypeError('DaCe programs do not have a return type')\n if has_args and has_annotations:\n raise SyntaxError('DaCe programs can only have decorator arguments ' +\n '(\\'@dace.program(...)\\') or type annotations ' +\n '(\\'def program(arr: type, ...)\\'), but not both')\n\n # Alert if there are any discrepancies between annotations and arguments\n if has_args:\n # Make sure all arguments are annotated\n if len(decorator_args) != len(f_argnames):\n raise SyntaxError(\n 'Decorator arguments must match number of DaCe ' +\n 'program parameters (expecting ' + str(len(f_argnames)) + ')')\n # Return arguments and their matched decorator annotation\n return {\n k: create_datadescriptor(v)\n for k, v in zip(f_argnames, decorator_args)\n }\n elif has_annotations:\n # Make sure all arguments are annotated\n if len(type_annotations) != len(f_argnames):\n raise SyntaxError(\n 'Either none or all DaCe program parameters must ' +\n 'have type annotations')\n return {k: create_datadescriptor(v) for k, v in type_annotations.items()}\n\n\ndef _get_argnames(f):\n \"\"\" Returns a Python function's argument names. \"\"\"\n try:\n return inspect.getfullargspec(f).args\n except AttributeError:\n return inspect.getargspec(f).args\n\n\ndef _compile_module(s, name='<string>'):\n \"\"\" Compiles a string representing a python module (file or code) and\n returns the resulting global objects as a dictionary mapping name->val.\n :param name: Optional name for better error message handling.\n \"\"\"\n\n gen_module = {}\n code = compile(s, name, 'exec')\n exec(code, gen_module)\n return gen_module\n\n\ndef parse_from_file(filename, *compilation_args):\n \"\"\" Try to parse all DaCe programs in `filename` and return a list of\n obtained SDFGs. Raises exceptions in case of compilation errors.\n Also accepts optional compilation arguments containing types and symbol\n values.\n \"\"\"\n\n with open(filename, 'r') as f:\n code = f.read()\n\n mod = _compile_module(code, filename)\n\n programs = [\n program for program in mod.values()\n if isinstance(program, DaceProgram)\n ]\n\n return [parse_function(p, *compilation_args) for p in programs]\n\n\ndef parse_from_function(function, *compilation_args, strict=None):\n \"\"\" Try to parse a DaceProgram object and return the `dace.SDFG` object\n that corresponds to it.\n :param function: DaceProgram object (obtained from the `@dace.program`\n decorator).\n :param compilation_args: Various compilation arguments e.g. dtypes.\n :param strict: Whether to apply strict transformations or not (None\n uses configuration-defined value). \n :return: The generated SDFG object.\n \"\"\"\n if not isinstance(function, DaceProgram):\n raise TypeError(\n 'Function must be of type dace.frontend.python.DaceProgram')\n\n # Obtain DaCe program as SDFG\n sdfg = function.generate_pdp(*compilation_args)\n\n # No need at this point\n # Fill in scope entry/exit connectors\n #sdfg.fill_scope_connectors()\n # Memlet propagation\n #if sdfg.propagate:\n # labeling.propagate_labels_sdfg(sdfg)\n ########################\n\n # Apply strict transformations automatically\n if (strict == True or (strict is None and Config.get_bool(\n 'optimizer', 'automatic_strict_transformations'))):\n sdfg.apply_strict_transformations()\n\n # Drawing the SDFG (again) to a .dot file\n sdfg.draw_to_file(recursive=True)\n sdfg.save(os.path.join('_dotgraphs', 'program.sdfg'))\n\n # Validate SDFG\n sdfg.validate()\n\n return sdfg\n\n\ndef _get_locals_and_globals():\n \"\"\" Retrieves a list of local and global variables four steps up in the\n stack. This is used to retrieve variables around and defined before\n @dace.programs for adding symbols. \"\"\"\n frame = inspect.currentframe()\n outer_frame = frame.f_back.f_back.f_back.f_back\n result = {}\n # Update globals, then locals\n result.update(outer_frame.f_globals)\n result.update(outer_frame.f_locals)\n\n return result\n\n\nclass DaceProgram:\n \"\"\" A data-centric program object, obtained by decorating a function with\n `@dace.program`. \"\"\"\n\n def __init__(self, f, args, kwargs):\n self.f = f\n self.args = args\n self.kwargs = kwargs\n self._name = f.__name__\n self.argnames = _get_argnames(f)\n\n # NOTE: Important to call this outside list/dict comprehensions\n global_vars = _get_locals_and_globals()\n\n self.global_vars = {\n k: v\n for k, v in global_vars.items() if dtypes.isallowed(v)\n }\n if self.argnames is None:\n self.argnames = []\n\n @property\n def name(self):\n return self._name\n\n def to_sdfg(self, *args, strict=None):\n \"\"\" Parses the DaCe function into an SDFG. \"\"\"\n return parse_from_function(self, *args, strict=strict)\n\n def compile(self, *args, strict=None, specialize=None):\n \"\"\" Convenience function that parses and compiles a DaCe program. \"\"\"\n sdfg = parse_from_function(self, *args, strict=strict)\n return sdfg.compile(specialize=specialize)\n\n def __call__(self, *args, **kwargs):\n \"\"\" Convenience function that parses, compiles, and runs a DaCe \n program. \"\"\"\n binaryobj = self.compile(*args)\n # Add named arguments to the call\n kwargs.update({aname: arg for aname, arg in zip(self.argnames, args)})\n # Update arguments with symbols in data shapes\n kwargs.update({\n sym: symbolic.symbol(sym).get()\n for arg in args\n for sym in (symbolic.symlist(arg.descriptor.shape) if hasattr(\n arg, 'descriptor') else [])\n })\n # Update arguments with symbol values\n for aname in self.argnames:\n if aname in binaryobj.sdfg.arrays:\n sym_shape = binaryobj.sdfg.arrays[aname].shape\n for sym in (sym_shape):\n if symbolic.issymbolic(sym):\n try:\n kwargs[str(sym)] = sym.get()\n except:\n pass\n\n return binaryobj(**kwargs)\n\n def generate_pdp(self, *compilation_args):\n \"\"\" Generates the parsed AST representation of a DaCe program.\n :param compilation_args: Various compilation arguments e.g., dtypes.\n :return: A 2-tuple of (program, modules), where `program` is a\n `dace.astnodes._ProgramNode` representing the parsed DaCe \n program, and `modules` is a dictionary mapping imported \n module names to their actual module names (for maintaining\n import aliases).\n \"\"\"\n dace_func = self.f\n args = self.args\n\n # If exist, obtain type annotations (for compilation)\n argtypes = _get_type_annotations(dace_func, self.argnames, args)\n\n # Parse argument types from call\n if len(inspect.getfullargspec(dace_func).args) > 0:\n if not argtypes:\n if not compilation_args:\n raise SyntaxError(\n 'DaCe program compilation requires either type annotations '\n 'or arrays')\n\n # Parse compilation arguments\n if len(compilation_args) != len(self.argnames):\n raise SyntaxError(\n 'Arguments must match DaCe program parameters (expecting '\n '%d)' % len(self.argnames))\n argtypes = {\n k: create_datadescriptor(v)\n for k, v in zip(self.argnames, compilation_args)\n }\n for k, v in argtypes.items():\n if v.transient: # Arguments to (nested) SDFGs cannot be transient\n v_cpy = copy.deepcopy(v)\n v_cpy.transient = False\n argtypes[k] = v_cpy\n #############################################\n\n # Parse allowed global variables\n # (for inferring types and values in the DaCe program)\n global_vars = copy.copy(self.global_vars)\n\n modules = {\n k: v.__name__\n for k, v in global_vars.items() if dtypes.ismodule(v)\n }\n modules['builtins'] = ''\n\n # Add symbols as globals with their actual names (sym_0 etc.)\n global_vars.update({\n v.name: v\n for k, v in global_vars.items() if isinstance(v, symbolic.symbol)\n })\n\n # Allow SDFGs and DaceProgram objects\n # NOTE: These are the globals AT THE TIME OF INVOCATION, NOT DEFINITION\n other_sdfgs = {\n k: v\n for k, v in dace_func.__globals__.items()\n if isinstance(v, (SDFG, DaceProgram))\n }\n\n # Parse AST to create the SDFG\n return newast.parse_dace_program(dace_func, argtypes, global_vars,\n modules, other_sdfgs, self.kwargs)\n","sub_path":"dace/frontend/python/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":10038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"570065756","text":"from .n_bits_swap_env import NBitsSwapEnv\nfrom .n_bits_swap_mnist_env import NBitsSwapMNISTEnv\n\nfrom gym.envs.registration import register\n\nfor n in range(40):\n register(\n id=f'{n}BitsSwap-v0',\n entry_point='regym.environments.envs.gym_envs.n_bits_swap_env:NBitsSwapEnv',\n kwargs={'n' : n, 'fixed_goal' : False},\n )\n register(\n id=f'{n}BitsSwap-FixedGoal-v0',\n entry_point='regym.environments.envs.gym_envs.n_bits_swap_env:NBitsSwapEnv',\n kwargs={'n' : n, 'fixed_goal' : True},\n )\n register(\n id=f'{n}BitsSwap-SimpleMNIST-v0',\n entry_point='regym.environments.envs.gym_envs.n_bits_swap_mnist_env:NBitsSwapMNISTEnv',\n kwargs={'n' : n, 'simple': True, 'fixed_goal' : False, 'train': True},\n )\n register(\n id=f'{n}BitsSwap-HardMNIST-v0',\n entry_point='regym.environments.envs.gym_envs.n_bits_swap_mnist_env:NBitsSwapMNISTEnv',\n kwargs={'n' : n, 'simple':False, 'fixed_goal' : False, 'train': True},\n )\n","sub_path":"regym/environments/envs/gym_envs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"544369298","text":"import numpy as np\r\nimport os\r\nimport sys\r\nimport gc\r\nfrom pathlib import Path\r\nimport rasterio as rst\r\nimport matplotlib.pyplot as plt\r\nimport cv2 as cv\r\nfrom scipy.ndimage import gaussian_filter\r\nfrom GetImages import GetImages\r\n# from skimage import measure\r\n# from scipy.stats import itemfreq\r\n# import matplotlib.animation as animation\r\n# from MP4Maker import MP4Maker\r\nimport cc3d\r\n\r\nclass ConnectedComp:\r\n image_retrieval = GetImages()\r\n ###################################################\r\n ## Function: image_locations ##\r\n ## Retrieves file paths from the designated ##\r\n ## directory, and returns a numpy array of file ##\r\n ## names. ##\r\n ###################################################\r\n def image_locations(self, path=\"Original_Images\"):\r\n dir = Path(path)\r\n image_names = []\r\n for file in dir.glob('*.tif*'):\r\n file_name = os.path.dirname(file) + \"/\" + os.path.basename(file)\r\n image_names.append(file_name) \r\n image_names.sort() \r\n return np.asarray(image_names)\r\n\r\n ###################################################\r\n ## Function: get_file_name ##\r\n ## Parses the file name from a path string. ##\r\n ###################################################\r\n def get_file_name(self, image_path):\r\n index_slash = image_path.rfind('/')\r\n return image_path[index_slash+1:len(image_path)]\r\n\r\n ###################################################\r\n ## Function: apply_connected_comp ##\r\n ## Applies connected components to the images ##\r\n ## in order to track parts of the fire over time.##\r\n ###################################################\r\n def apply_connected_comp(self, apply_directory, save_directory, num_components=100, num_images = 960):\r\n index_slash = save_directory.rfind('/')\r\n directory = save_directory[0:index_slash]\r\n print(\"Applying Connected Components...\")\r\n if not os.path.exists(directory):\r\n os.makedirs(directory) \r\n file_names = []\r\n images = []\r\n meta = []\r\n meta.append(['driver', 'dtype', 'nodata', 'width', 'height', 'count', 'crs', 'pixel width', 'row rotation', 'upperleftx_coord', 'column rotation', 'pixel height','upperlefty_coord', 'blockxsize', 'blockysize', 'tiled', 'compress', 'interleave'])\r\n index = 0\r\n save_iter = 1\r\n prev_iter = 0\r\n num_iter = num_images\r\n image_array = self.image_retrieval.image_locations(apply_directory)\r\n for image_path in image_array:\r\n if index == num_iter: \r\n print(\"prev_iter=\", prev_iter)\r\n print('save_iter=', save_iter)\r\n print('num_iter=', num_iter)\r\n file_names = np.asarray(file_names)\r\n images = np.asarray(images)\r\n meta = np.asarray(meta)\r\n connectivity = 6 \r\n print(\"Connecting Components...\")\r\n labeled_data = cc3d.connected_components(images, connectivity=connectivity)\r\n labeled_data[labeled_data > int(num_components)] = 0\r\n\r\n print(\"Saving Images\",prev_iter,\"-\",(num_iter - 1),\"...\")\r\n np.save(save_directory + str(prev_iter) + \"_\" + str(num_iter - 1) + \".npy\", labeled_data)\r\n print(\"Saving Names\",prev_iter,\"-\",(num_iter - 1),\"...\")\r\n np.save(save_directory + str(prev_iter) + \"_\" + str(num_iter - 1) + \"_names.npy\", file_names)\r\n print(\"Saving Meta\",prev_iter,\"-\",(num_iter - 1),\"...\")\r\n np.save(save_directory + str(prev_iter) + \"_\" + str(num_iter - 1) + \"_meta.npy\", meta)\r\n\r\n prev_iter = num_iter\r\n save_iter += 1\r\n num_iter *= save_iter\r\n print(\"prev_iter=\", prev_iter)\r\n print('save_iter=', save_iter)\r\n print('num_iter=', num_iter)\r\n file_names = []\r\n meta = []\r\n images = []\r\n labeled_data = []\r\n gc.collect()\r\n\r\n name = self.image_retrieval.get_file_name(image_path)\r\n raster = rst.open(image_path)\r\n profile = raster.profile\r\n image = raster.read(1)\r\n image[image == 255] = 1\r\n file_names.append(name)\r\n images.append(image)\r\n pixel_transform = profile['transform']\r\n meta.append(['GTiff', 'uint8', 0.0, 2462, 3500, 1, 'epsg:4326', pixel_transform[0], pixel_transform[1], pixel_transform[2], pixel_transform[3], pixel_transform[4], pixel_transform[5], 256, 256, True, 'deflate', 'band'])\r\n index += 1\r\n raster.close()\r\n\r\ndef main():\r\n print(\"Notice: Please note that this script is intended to run after KMeansConverter.py. If it is executed after a different script it will not work.\")\r\n cc = ConnectedComp()\r\n if len(sys.argv) < 2:\r\n print(\"Please enter the directory of the images you would like to compress and the new directory for the compressed images.\")\r\n elif sys.argv[1].lower() == \"cc\" and len(sys.argv) == 5:\r\n cc.apply_connected_comp(sys.argv[2], sys.argv[3], sys.argv[4])\r\n elif sys.argv[1].lower() == \"cc\" and len(sys.argv) != 5:\r\n print(\"To apply connected components to images please enter: cc image_directory_to_apply save_directory number_components\")\r\n else:\r\n print(\"To apply connected components to images please enter: cc image_directory_to_apply save_directory number_components\")\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"ConnectedComp.py","file_name":"ConnectedComp.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"305675137","text":"from django import template\nfrom django.template import NodeList\nfrom django.template import Variable\nfrom django.contrib.auth.models import Group\n\nregister = template.Library()\n\nclass GroupCheckNode(template.Node):\n def __init__(self, groups, nodelist_true, nodelist_false):\n self.groups = groups\n self.nodelist_true = nodelist_true\n self.nodelist_false = nodelist_false\n\n def render(self, context):\n user = Variable('user').resolve(context)\n\n if not user.is_authenticated:\n return self.nodelist_false.render(context)\n\n allowed = False\n for checkgroup in self.groups:\n\n if checkgroup.startswith('\"') and checkgroup.endswith('\"'):\n checkgroup = checkgroup[1:-1]\n\n if checkgroup.startswith(\"'\") and checkgroup.endswith(\"'\"):\n checkgroup = checkgroup[1:-1]\n\n try:\n group = Group.objects.get(name=checkgroup)\n except Group.DoesNotExist:\n try:\n group = Group.objects.get(\n name=Variable(checkgroup).resolve(context)\n )\n except Group.DoesNotExist:\n group = None\n break\n\n if group in user.groups.all():\n allowed = True\n break\n\n if allowed:\n return self.nodelist_true.render(context)\n else:\n return self.nodelist_false.render(context)\n\n@register.tag()\ndef ifusergroup(parser, token):\n \"\"\"\n Check to see if the currently logged in user belongs to one or more groups\n Requires the Django authentication contrib app and middleware. Mod of\n http://djangosnippets.org/snippets/2736/\n to support multi-word group names\n (with single/double quotes, e.g. {% ifusergroup 'Store Keeper' %}).\n\n Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or\n {% ifusergroup Admins Clients Programmers Managers %} ... {% else %} ... {% endifusergroup %}\n\n \"\"\"\n try:\n tokensp = token.split_contents()\n groups = []\n groups += tokensp[1:]\n except ValueError:\n raise template.TemplateSyntaxError(\"Tag 'ifusergroup' requires at least 1 argument.\")\n\n nodelist_true = parser.parse(('else', 'endifusergroup'))\n token = parser.next_token()\n\n if token.contents == 'else':\n nodelist_false = parser.parse(('endifusergroup',))\n parser.delete_first_token()\n else:\n nodelist_false = NodeList()\n\n return GroupCheckNode(groups, nodelist_true, nodelist_false)\n","sub_path":"djtools/templatetags/ifusergroup.py","file_name":"ifusergroup.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"216479988","text":"import datetime\nfrom django.db import models\n\nfrom opinion.group.report.models import ReportEnter\n\n\nclass StockFundamental(models.Model):\n \"\"\"\n Simple fundamental analysis, micro valuation for stock, weekly update\n \"\"\"\n report = models.OneToOneField(ReportEnter, null=True, blank=True)\n\n # Strong-Form Hypothesis\n # rank\n mean_rank = models.FloatField(default=3, help_text='Fundamental Mean Rank')\n accuracy = models.IntegerField(default=50, help_text='Upgrade/downgrade accuracy')\n rank_change = models.CharField(\n max_length=20, help_text='Latest rank change', default='upgrade',\n choices=(('upgrade', 'Upgrade'), ('hold', 'Hold'), ('downgrade', 'Downgrade')),\n )\n change_date = models.DateField(null=True, help_text='Latest rank change date')\n risk = models.CharField(\n max_length=20, help_text='From S&P report', default='middle',\n choices=(('low', 'Low'), ('middle', 'Middle'), ('high', 'High'))\n )\n\n # target price\n tp_max = models.DecimalField(\n max_digits=10, decimal_places=2, default=0, help_text='Max Target Price'\n )\n tp_mean = models.DecimalField(\n max_digits=10, decimal_places=2, default=0, help_text='Mean Target Price'\n )\n tp_min = models.DecimalField(\n max_digits=10, decimal_places=2, default=0, help_text='Min Target Price'\n )\n\n # ownership change\n ownership_activity = models.CharField(\n max_length=20,\n choices=(('selling', 'Selling'), ('holding', 'Holding'), ('buying', 'Buying')),\n help_text='Ownership net activity - 45 days'\n )\n ownership_date = models.DateField(null=True, help_text='Latest short interest date')\n insider_trade = models.CharField(\n max_length=20, help_text='Insider trades - 30 days', default='holding',\n choices=(('selling', 'Selling'), ('holding', 'Holding'), ('buying', 'Buying')),\n )\n insider_date = models.DateField(null=True, help_text='Latest short interest date')\n short_interest = models.CharField(\n max_length=20, help_text='Short interest - 0.5 month', default='range',\n choices=(('decrease', 'Decrease'), ('range', 'Range'), ('increase', 'Increase')),\n )\n short_date = models.DateField(null=True, help_text='Latest short interest date')\n guru = models.TextField(blank=True, null=True, help_text='Latest guru trade')\n\n\nclass StockIndustry(models.Model):\n \"\"\"\n Industry analysis, update season after earning or enter position\n \"\"\"\n report = models.OneToOneField(ReportEnter, null=True, blank=True)\n\n # industry overall\n direction = models.CharField(\n max_length=20, default=None, blank=True, null=True,\n help_text='Zack industry chart direction 3 months',\n choices=(('bull', 'Bull'), ('neutral', 'Neutral'), ('bear', 'Bear')),\n )\n isolate = models.BooleanField(default=False, help_text='Stock price with index?')\n industry_rank = models.CharField(\n max_length=20, default='middle', help_text='Zack industry rank',\n choices=(('top', 'Top'), ('middle', 'Middle'), ('bottom', 'Bottom')),\n )\n sector_rank = models.CharField(\n max_length=20, default='middle', help_text='Zack industry rank',\n choices=(('top', 'Top'), ('middle', 'Middle'), ('bottom', 'Bottom')),\n )\n\n # stock vs peer\n stock_rank = models.CharField(\n max_length=20, default='middle', help_text='Zack stock rank vs peer',\n choices=(('better', 'Better'), ('same', 'Same'), ('lower', 'Lower')),\n )\n stock_growth = models.CharField(\n max_length=20, default='middle', help_text='Zack stock rank vs peer',\n choices=(('better', 'Better'), ('same', 'Same'), ('lower', 'Lower')),\n )\n stock_financial = models.CharField(\n max_length=20, default='middle', help_text='Zack stock rank vs peer',\n choices=(('better', 'Better'), ('same', 'Same'), ('lower', 'Lower')),\n )\n\n\nclass UnderlyingArticle(models.Model):\n \"\"\"\n Primary use for tracking story telling or irrational move\n \"\"\"\n report = models.OneToOneField(ReportEnter, null=True, blank=True)\n\n # Semi-Strong Form\n category = models.CharField(\n max_length=20, help_text='Type of this market story', default='title',\n choices=(('title', 'Big title'), ('story', 'Story telling'), ('news', 'Simple News'))\n )\n article_name = models.CharField(\n default='', max_length=200, help_text='Name of the story, news, title'\n )\n article_story = models.CharField(\n max_length=20, help_text='Current state of article telling', default='good30',\n choices=(\n ('good90', 'Good story 90% chance, 88% follow'),\n ('good30', 'Good story 30% chance, 78% follow'),\n ('bad90', 'Bad story 90% chance, 38% follow'),\n ('bad30', 'Bad story 30% chance, 7% follow')\n )\n )\n period_state = models.CharField(\n max_length=20, help_text='Current state of story telling', default='latest',\n choices=(\n ('latest', 'Latest 1 or 2 days'),\n ('recent', 'Recent 1 week'),\n ('forget', 'Pass 2 weeks')\n )\n )\n\n # news summary\n news_rank = models.CharField(\n max_length=20, default=None, blank=True, null=True,\n help_text='Benzinga pro news rank 14 days',\n choices=(('good', 'Good'), ('neutral', 'Neutral'), ('bad', 'Bad')),\n )\n news_effect = models.CharField(\n max_length=20, default='neutral', help_text='14 days price move with news',\n choices=(('bull', 'Bull'), ('neutral', 'Neutral'), ('bear', 'Bear')),\n )\n\n # behavior opinion\n fundamental_effect = models.BooleanField(\n default=True, help_text='This article have fundamental effect?'\n )\n rational = models.BooleanField(\n default=True, help_text='This story is rational? yes or no, you only follow'\n )\n blind_follow = models.BooleanField(\n default=True, help_text='Follow story? Short term follow? Long term reverse?'\n )\n reverse_effect = models.BooleanField(\n default=True, help_text='Is this bad news as good news? good news as bad news?'\n )\n\n # news effect price probability\n bull_chance = models.FloatField(default=33, help_text='Chance of bull move by this news')\n range_chance = models.FloatField(default=34, help_text='Chance of range move by this news')\n bear_chance = models.FloatField(default=33, help_text='Chance of bear move by this news')\n","sub_path":"opinion/group/fundamental/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"134329863","text":"import datetime\nimport sublime\nimport sublime_plugin\nimport os\n\n\nclass AddTagCommand(sublime_plugin.TextCommand):\n\n def run(self, edit):\n self.DefineComment()\n\n def DefineComment(self):\n print(\"AddTag\")\n settings = sublime.load_settings('delphi-ide.sublime-settings')\n datetimeformat = settings.get(\"datetimeformat\", \"%d/%m/%Y\")\n\n line = os.environ['USERNAME'].title() + ' - ' + \\\n datetime.datetime.now().strftime(datetimeformat)\n self.view.run_command(\n \"insert_snippet\", {\"contents\": \"%s\" % '// ' + line})\n","sub_path":"addtag.py","file_name":"addtag.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"362170766","text":"import time, subprocess, re\n\n\nclass CC2:\n def __init__(self):\n self.fhLog = open(\"logs/CC2Log\", \"a+\")\n self.fhLog.write(\"====================\\n\")\n self.fhLog.write(str(time.time()) + \" CC2 is running\\n\")\n self.zombieList = [None, None, None]\n self.running()\n\n def running(self):\n time.sleep(3)\n while True:\n self.checkZombies()\n time.sleep(1)\n\n def checkZombies(self):\n\n fhCCC = open(\"channel/CCChannel\", \"r\")\n lines = fhCCC.readlines()\n if len(lines) is 0:\n return\n pids = lines[0].split(' ')\n\n down = 0\n for i in range(len(pids)):\n pid = pids[i]\n proc = self.is_running(pid)\n if proc is False:\n down += 1\n\n if down > 0:\n fhCC = open(\"channel/CommunicationChannel\", \"w\")\n fhCC.write('down ' + str(down))\n fhCC.close()\n fhCCC = open(\"channel/CCChannel\", \"w\")\n fhCCC.write('')\n fhCCC.close()\n self.fhLog.write(\n str(time.time()) + \" CC2 cleared CC communication channel, send message to master, we have \" + str(\n down) + \" zombies down\\n\")\n\n def is_running(self, process):\n\n s = subprocess.Popen([\"ps\", \"axw\"], stdout=subprocess.PIPE)\n for x in s.stdout:\n\n if re.search(process, x):\n return True\n\n return False\n\n\nCC2()\n","sub_path":"CC2.py","file_name":"CC2.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"186748134","text":"#!/usr/bin/env python3\nimport sys, os, re\nimport numpy as np\nimport random as rd\nimport matplotlib.pyplot as plt\n\n#--------------------------------------------------------------------------#\ndef main(output_folder):\n # only one monolayer mosaic is considered here\n nb_cells = 400 # 200 per nb_types\n space = 500\n nb_types = 2\n #TODO: test optimal death rate\n death_rate = 0.65\n\n density = nb_cells/nb_types * 1e6 / (space * space)\n\n cells = createCells(nb_cells, space, nb_types, dif=True)\n initial_ri = getRi(cells, nb_types)\n\n # plotMosaic(cells, nb_types)\n\n print(\"initial density (per cell type):\", int(density), \"- initial ri:\", initial_ri)\n\n# fate_mosaic = fate(cells)\n# death_mosaic = death(fate_mosaic, death_rate)\n death_mosaic = death(cells, death_rate)\n migration_mosaic = migration(cells, repetition=25, exclusion=30)\n\n# fate_ri = getRi(fate_mosaic, nb_types)\n death_ri = getRi(death_mosaic, nb_types)\n migration_ri = getRi(migration_mosaic, nb_types)\n\n print()\n# print(\"non AB fate:\", fate_ri)\n print(\"non AB death:\", death_ri)\n print(\"non AB migration:\", migration_ri)\n\n# plotMosaic(fate_mosaic, nb_types, \"Mosaic created with non AB fate mechanism\")\n plotMosaic(death_mosaic, nb_types, \"Mosaic created with non AB death mechanism\")\n plotMosaic(migration_mosaic, nb_types, \"Mosaic created with non AB migration mechanism\")\n\n plt.show()\n\n return 1\n#--------------------------------------------------------------------------#\ndef plotMosaic(cells, nb_types, title):\n plt.figure()\n for i in range(0, len(cells)):\n plt.plot(cells[i][0], cells[i][1], 'o', color=rgb(0, nb_types, cells[i][2]))\n plt.title(title)\n\n#--------------------------------------------------------------------------#\ndef rgb(minimum, maximum, value):\n minimum, maximum = float(minimum), float(maximum)\n ratio = 2 * (value-minimum) / (maximum - minimum)\n b = int(max(0, 255*(1 - ratio)))\n r = int(max(0, 255*(ratio - 1)))\n g = 255 - b - r\n\n return r/255, g/255, b/255\n\n#--------------------------------------------------------------------------#\ndef createCells(nb_cells, space, nb_types, dif=True):\n cells = []\n for i in range(0, nb_cells):\n new_cell = [round(rd.uniform(0, space), 2), round(rd.uniform(0, space), 2), int(rd.uniform(0, nb_types))] if dif else [round(rd.uniform(0, space), 2), round(rd.uniform(0, space), 2), -1]\n while positionConflict(cells, new_cell):\n new_cell = [round(rd.uniform(0, space), 2), round(rd.uniform(0, space), 2), int(rd.uniform(0, nb_types))] if dif else [round(rd.uniform(0, space), 2), round(rd.uniform(0, space), 2), -1]\n cells.append(new_cell)\n\n return cells\n\n#--------------------------------------------------------------------------#\ndef positionConflict(cells, new_cell):\n for cell in cells:\n if twodDistance(cell, new_cell) < 7:\n return True\n return False\n\n#--------------------------------------------------------------------------#\ndef writeRi(positions_list, nb_types):\n #TODO\n getRi(positions_list, nb_types)\n\n#--------------------------------------------------------------------------#\ndef getRi(positions_list, nb_types):\n ri = []\n for type in range(0, nb_types):\n shortest_dist_list = getDistLists(positions_list, type)\n ri.append(round((np.average(shortest_dist_list)/np.std(shortest_dist_list)), 2))\n\n return round(np.average(ri), 2), round(np.std(ri), 2)\n\n#--------------------------------------------------------------------------#\ndef getDistLists(coord_list, type):\n shortest_dist_list = []\n for i in range(0, len(coord_list)):\n distance_list = []\n cell_coord = coord_list[i]\n cell_type = coord_list[i][2]\n if cell_type != type:\n continue\n for j in range(0, len(coord_list)):\n other_cell_coord = coord_list[j]\n other_cell_type = coord_list[j][2]\n if other_cell_type != type:\n continue\n tempsDistance = twodDistance(cell_coord, other_cell_coord)\n # if cell is not itself\n if tempsDistance != 0:\n distance_list.append(tempsDistance)\n # add shortest distance\n shortest_dist_list.append(min(distance_list))\n\n return shortest_dist_list\n\n#--------------------------------------------------------------------------#\ndef twodDistance(a, b):\n return np.sqrt(np.square(a[0] - b[0]) + np.square(a[1] - b[1]))\n\n#--------------------------------------------------------------------------#\ndef newCoord(cell_ref, cell_to_move, dist, factor=4):\n x = cell_to_move[0] + (factor*(cell_to_move[0]-cell_ref[0])/dist)\n y = cell_to_move[1] + (factor*(cell_to_move[1]-cell_ref[1])/dist)\n return round(x, 2), round(y, 2), cell_to_move[2]\n\n#--------------------------------------------------------------------------#\ndef fate(cells, write=False):\n for i in range(0, len(cells)):\n cell_a = cells[i]\n if cell_a[2] == -1:\n closest_cell = 1e6; closest_cell_type = -1\n for j in range(0, len(cells)):\n cell_b = cells[j]\n if cell_b[2] != -1:\n distance = twodDistance(cell_a, cell_b)\n if distance < closest_cell:\n closest_cell = distance\n closest_cell_type = cell_b[2]\n # if no differentiated cells yet\n if closest_cell_type == -1:\n new_type = int(rd.uniform(0, 2))\n elif closest_cell_type == 1:\n new_type = 0\n elif closest_cell_type == 0:\n new_type =1\n cells[i] = [cell_a[0], cell_a[1], new_type]\n if write:\n writeRi(cells, 2)\n\n return cells\n\n#--------------------------------------------------------------------------#\ndef death(cells, death_rate):\n repetition = int(len(cells)*death_rate)\n for iteration in range(0, repetition):\n print(\"death mechanism iteration\", iteration, \"out of\", repetition, end=\"\\r\", flush=True)\n # find closest cells couple\n closest_cells = 1e6; closest_couple = []\n for i in range(0, len(cells)):\n cell_a = cells[i]\n for j in range(0, len(cells)):\n cell_b = cells[j]\n # if homotypic cells\n if cell_b[2] == cell_a[2]:\n distance = twodDistance(cell_a, cell_b)\n if distance > 0 and distance < closest_cells:\n closest_cells = distance\n closest_couple = [cell_a, cell_b]\n # decide if cell_a or cell_b has to be removed\n second_closest_a = 1e6\n cell_a = closest_couple[0]\n for i in range(0, len(cells)):\n cell_c = cells[i]\n distance = twodDistance(cell_a, cell_c)\n if distance < second_closest_a and distance > closest_cells:\n second_closest_a = distance\n\n second_closest_b = 1e6\n cell_b = closest_couple[1]\n for i in range(0, len(cells)):\n cell_c = cells[i]\n distance = twodDistance(cell_b, cell_c)\n if distance < second_closest_b and distance > closest_cells:\n second_closest_b = distance\n # select cell to remove between a and b\n cell_to_remove = cell_a if second_closest_a < second_closest_b else cell_b\n # remove selected cell\n cells.remove(cell_to_remove)\n\n return cells\n\n#--------------------------------------------------------------------------#\ndef migration(cells, repetition=25, exclusion=25):\n for iteration in range(0, repetition):\n print(\"migration mechanism iteration\", iteration, \"out of\", repetition, end=\"\\r\", flush=True)\n # for each cell, repulse all cells that are too close\n for i in range(0, len(cells)):\n cell_a = cells[i]\n for j in range(0, len(cells)):\n cell_b = cells[j]\n # if homotypic cells\n if cell_b[2] == cell_a[2]:\n distance = twodDistance(cell_a, cell_b)\n if distance > 0 and distance < exclusion:\n cells[j] = newCoord(cell_a, cell_b, distance)\n\n return cells\n\n#--------------------------------------------------------------------------#\n# check number of arguments\nif len(sys.argv)==2:\n if main(sys.argv[1]):\n print(\"done\")\n else:\n print(\"error during execution\")\nelse:\n raise SystemExit('Error: need 1 arg: [output folder]')\n","sub_path":"non_AB_mechanisms.py","file_name":"non_AB_mechanisms.py","file_ext":"py","file_size_in_byte":8596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"91140856","text":"import cv2\nimport numpy as np\nimport RPi.GPIO as GPIO\nimport time\n\nservoPIN = 17\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(servoPIN, GPIO.OUT)\n\npwm = GPIO.PWM(servoPIN, 50)\npwm.start(5)\n\ndef setServoAngle(srvo, angle):\n dutyCycle = angle / 18. + 1\n print(dutyCycle)\n srvo.ChangeDutyCycle(dutyCycle)\n\ncap = cv2.VideoCapture(0)\nprint(cap)\n\n#cap.set(3, rows)\n#cap.set(4, cols)\n\nwidth = 640\nheight = 480\n\nx_medium = int(width / 2)\ncenter = int(height / 2)\n\ndef nothing(x):\n pass\n\ncv2.namedWindow(\"Frame\")\ncv2.createTrackbar(\"L-H\", \"Frame\",0,180,nothing)\ncv2.createTrackbar(\"L-S\", \"Frame\",131,255,nothing)\ncv2.createTrackbar(\"L-V\", \"Frame\",152,255,nothing)\ncv2.createTrackbar(\"U-H\", \"Frame\",180,180,nothing)\ncv2.createTrackbar(\"U-S\", \"Frame\",255,255,nothing)\ncv2.createTrackbar(\"U-V\", \"Frame\",255,255,nothing)\n\n\nfont = cv2.FONT_HERSHEY_COMPLEX\nwhile True:\n _,frame = cap.read()\n \n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n \n l_h = cv2.getTrackbarPos(\"L-H\", \"Frame\")\n l_s = cv2.getTrackbarPos(\"L-S\", \"Frame\")\n l_v = cv2.getTrackbarPos(\"L-V\", \"Frame\")\n u_h = cv2.getTrackbarPos(\"U-H\", \"Frame\")\n u_s = cv2.getTrackbarPos(\"U-S\", \"Frame\")\n u_v = cv2.getTrackbarPos(\"U-V\", \"Frame\")\n \n lower_red = np.array([l_h, l_s, l_v])\n upper_red = np.array([u_h, u_s, u_v])\n \n mask = cv2.inRange(hsv, lower_red, upper_red)\n kernel = np.ones((5, 5), np.uint8)\n mask = cv2.erode(mask, kernel)\n color_mask = cv2.bitwise_and(frame, frame, mask=mask)\n \n # Contours detection\n _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n \n for cnt in contours:\n area = cv2.contourArea(cnt)\n approx = cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt, True), True)\n x = approx.ravel()[0]\n y = approx.ravel()[1]\n \n if area > 400:\n \n \n #if len(approx) == 3:\n # cv2.putText(frame, \"Triangle\", (x, y), font, 1, (0, 0, 0))\n #elif len(approx) == 4:\n # cv2.putText(frame, \"Rectangle\", (x, y), font, 1, (0, 0, 0))\n # cv2.drawContours(frame, [approx], 0, (0, 0, 0), 5)\n if len(approx) > 5:\n print(width)\n print(height)\n \n #cv2.putText(frame, \"Circle\", (x, y), font, 1, (0, 0, 0))\n #cv2.putText(frame, format(dist), (x, y), font, 1, (0, 0, 0))\n cv2.putText(frame, \"Circle\", (x, y), font, 1, (0, 0, 0))\n \n looptim = looptim = 1\n if((looptim % 10) == 0):\n looptime = 0\n \n cv2.imshow('Frame', frame)\n cv2.imshow('color_mask', color_mask)\n c = cv2.waitKey(1)\n if c == 27:\n break\n \ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"303908734","text":"import ast\n\nimport numpy as np\n\nimport numba\nfrom numba import decorators\nfrom numba.ufunc_builder import UFuncBuilder\nfrom numba.minivect import minitypes\n\nimport blaze\nimport blaze.idx\nfrom blaze.expr import visitor\nfrom blaze.expr import ops\nfrom blaze.expr import paterm\nfrom blaze.datashape import coretypes\nfrom blaze.engine import pipeline\nfrom blaze.engine import executors\nfrom blaze.sources import canonical\n\nfrom blaze.datashape import datashape\nfrom blaze import Table, NDTable, Array, NDArray\n\nfrom numbapro.vectorize import Vectorize\n\nclass GraphToAst(visitor.BasicGraphVisitor):\n \"\"\"\n Convert a blaze graph to a Python AST.\n \"\"\"\n\n binop_to_astop = {\n ops.Add: ast.Add,\n ops.Mul: ast.Mult,\n }\n\n def __init__(self):\n super(GraphToAst, self).__init__()\n self.ufunc_builder = UFuncBuilder()\n\n def App(self, app):\n if app.operator.arity == 2:\n op = binop_to_astop.get(type(app.operator), None)\n if op is not None:\n left, right = self.visit(app.operator.children)\n return ast.BinOp(left=left, op=op(), right=right)\n\n return self.Unknown(app)\n\n def Unknown(self, tree):\n return self.ufunc_builder.register_operand(tree)\n\n\ndef get_datashape(dshape_aterm):\n \"Assemble datashape from aterm dshape\"\n args = []\n for arg in dshape_aterm.args:\n if isinstance(arg, paterm.AInt):\n args.append(arg.n)\n elif isinstance(arg, paterm.AString):\n args.append(arg.s)\n else:\n raise NotImplementedError\n\n return datashape(*args)\n\nclass ATermToAstTranslator(visitor.GraphTranslator):\n \"\"\"\n Convert an aterm graph to a Python AST.\n \"\"\"\n\n opname_to_astop = {\n 'add': ast.Add,\n 'mul': ast.Mult,\n }\n\n nesting_level = 0\n\n def __init__(self, executors):\n super(ATermToAstTranslator, self).__init__()\n self.ufunc_builder = UFuncBuilder()\n self.executors = executors\n\n def register(self, graph, result, lhs=None):\n if lhs is not None:\n assert self.nesting_level == 0\n\n if self.nesting_level == 0:\n # Bottom of graph that we can handle\n operands = self.ufunc_builder.operands\n pyast_function = self.ufunc_builder.build_ufunc_ast(result)\n # print getsource(pyast_function)\n py_ufunc = self.ufunc_builder.compile_to_pyfunc(pyast_function)\n\n executor = build_executor(py_ufunc, operands, graph)\n self.executors[id(executor)] = executor\n\n if lhs is not None:\n operands.append(lhs)\n\n annotation = paterm.AAnnotation(\n ty=None,\n annotations=['numba', id(executor), bool(lhs)]\n )\n appl = paterm.AAppl(paterm.ATerm('Executor'), operands,\n annotation=annotation)\n return appl\n\n self.result = result\n\n # Delete this node\n return None\n\n def match_assignment(self, app):\n assert self.nesting_level == 0\n\n lhs, rhs = app.args\n\n #\n ### Visit rhs\n #\n self.nesting_level += 1\n self.visit(rhs)\n rhs_result = self.result\n self.nesting_level -= 1\n\n #\n ### Visit lhs\n #\n # TODO: extend paterm.matches\n is_simple = (lhs.spine.label == 'Slice' and\n lhs.args[0].spine.label == 'Array' and\n all(v.label == \"None\" for v in lhs.args[1:]))\n if is_simple:\n self.nesting_level += 1\n lhs = self.visit(lhs)\n self.nesting_level -= 1\n self.ufunc_builder.operands.pop() # pop LHS from operands\n else:\n # LHS is complicated, let someone else (or ourselves!) execute\n # it independently\n # self.nesting_level is 0 at this point, so it will be registered\n # independently\n state = self.ufunc_builder.save()\n lhs = self.visit(lhs)\n lhs_result = self.result\n self.ufunc_builder.restore(state)\n\n #\n ### Build and return kernel if the rhs was an expression we could handle\n #\n if rhs_result:\n return self.register(app, rhs_result, lhs=lhs)\n else:\n app.args = [lhs, rhs]\n return app\n\n def handle_arithmetic(self, app, op):\n self.nesting_level += 1\n self.visit(app.args[1:])\n self.nesting_level -= 1\n\n left, right = self.result\n result = ast.BinOp(left=left, op=op(), right=right)\n return self.register(app, result)\n\n def AAppl(self, app):\n \"Look for unops, binops and reductions and anything else we can handle\"\n if paterm.matches('Arithmetic;*', app.spine):\n opname = app.args[0].label.lower()\n op = self.opname_to_astop.get(opname, None)\n type = get_datashape(app.annotation.ty)\n is_array = type.shape or self.nesting_level\n if op is not None and is_array and len(app.args) == 3: # args = [op, lhs, rhs]\n return self.handle_arithmetic(app, op)\n\n elif paterm.matches('Slice;*', app.spine):\n array, start, stop, step = app.args\n if all(paterm.matches(\"None;*\", op) for op in (start, stop, step)):\n return self.visit(array)\n\n elif paterm.matches(\"Assign;*\", app.spine):\n return self.match_assignment(app)\n\n elif paterm.matches(\"Array;*\", app.spine) and self.nesting_level:\n self.maybe_operand(app)\n return None\n\n return self.unhandled(app)\n\n def AInt(self, constant):\n self.result = ast.Num(n=constant.n)\n return constant\n\n AFloat = AInt\n\n def maybe_operand(self, aterm):\n if self.nesting_level:\n self.result = self.ufunc_builder.register_operand(aterm)\n\n def unhandled(self, aterm):\n \"An term we can't handle, scan for sub-trees\"\n nesting_level = self.nesting_level\n state = self.ufunc_builder.save()\n\n self.nesting_level = 0\n self.visitchildren(aterm)\n self.nesting_level = nesting_level\n self.ufunc_builder.restore(state)\n\n self.maybe_operand(aterm)\n return aterm\n\n\ndef build_executor(py_ufunc, operands, aterm_subgraph_root):\n \"\"\" Build a ufunc and an wrapping executor from a Python AST \"\"\"\n result_dtype = unannotate_dtype(aterm_subgraph_root)\n operand_dtypes = map(unannotate_dtype, operands)\n\n vectorizer = Vectorize(py_ufunc)\n vectorizer.add(restype=minitype(result_dtype),\n argtypes=map(minitype, operand_dtypes))\n ufunc = vectorizer.build_ufunc()\n\n # TODO: build an executor tree and substitute where we can evaluate\n executor = executors.ElementwiseLLVMExecutor(\n ufunc,\n operand_dtypes,\n result_dtype,\n )\n\n return executor\n\ndef getsource(ast):\n from meta import asttools\n return asttools.dump_python_source(ast).strip()\n\ndef unannotate_dtype(aterm):\n \"\"\" Takes a term with a datashape annotation and returns the NumPy\n dtype associate with it\n\n >>> term\n x{dshape(\"2, 2, int32\")}\n >>> unannotate_dtype(term)\n int32\n \"\"\"\n # unpack the annotation {'s': 'int32'}\n unpack = paterm.matches('dshape(s);*', aterm.annotation['type'])\n ds_str = unpack['s']\n dshape = datashape(ds_str.s)\n\n dtype = coretypes.to_dtype(dshape)\n return dtype\n\ndef minitype(dtype):\n return minitypes.map_dtype(dtype)\n\ndef substitute_llvm_executors(aterm_graph, executors):\n translator = ATermToAstTranslator(executors)\n return translator.visit(aterm_graph)\n","sub_path":"blaze/engine/llvm_execution.py","file_name":"llvm_execution.py","file_ext":"py","file_size_in_byte":7694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"455582063","text":"\"\"\"Models state and remote services of one vehicle.\"\"\"\nfrom enum import Enum\nimport logging\nfrom typing import List\n\nfrom bimmer_connected.state import VehicleState\nfrom bimmer_connected.remote_services import RemoteServices\nfrom bimmer_connected.const import VEHICLE_IMAGE_URL\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass DriveTrainType(Enum):\n \"\"\"Different types of drive trains.\"\"\"\n CONVENTIONAL = 'CONV'\n PHEV = 'PHEV'\n BEV = 'BEV'\n BEV_REX = 'BEV_REX'\n\n\n#: Set of drive trains that have a combustion engine\nCOMBUSTION_ENGINE_DRIVE_TRAINS = {DriveTrainType.CONVENTIONAL, DriveTrainType.PHEV, DriveTrainType.BEV_REX}\n\n#: set of drive trains that have a high voltage battery\nHV_BATTERY_DRIVE_TRAINS = {DriveTrainType.PHEV, DriveTrainType.BEV, DriveTrainType.BEV_REX}\n\n\nclass VehicleViewDirection(Enum):\n \"\"\"Viewing angles for the vehicle.\n\n This is used to get a rendered image of the vehicle.\n \"\"\"\n FRONTSIDE = 'FRONTSIDE'\n FRONT = 'FRONT'\n REARSIDE = 'REARSIDE'\n REAR = 'REAR'\n SIDE = 'SIDE'\n DASHBOARD = 'DASHBOARD'\n DRIVERDOOR = 'DRIVERDOOR'\n REARBIRDSEYE = 'REARBIRDSEYE'\n\n\nclass ConnectedDriveVehicle(object):\n \"\"\"Models state and remote services of one vehicle.\n\n :param account: ConnectedDrive account this vehicle belongs to\n :param attributes: attributes of the vehicle as provided by the server\n \"\"\"\n\n def __init__(self, account, attributes: dict) -> None:\n self._account = account\n self.attributes = attributes\n self.state = VehicleState(account, self)\n self.remote_services = RemoteServices(account, self)\n\n def update_state(self) -> None:\n \"\"\"Update the state of a vehicle.\"\"\"\n self.state.update_data()\n\n @property\n def drive_train(self) -> DriveTrainType:\n \"\"\"Get the type of drive train of the vehicle.\"\"\"\n return DriveTrainType(self.attributes['driveTrain'])\n\n @property\n def name(self) -> str:\n \"\"\"Get the name of the vehicle.\"\"\"\n return self.attributes['model']\n\n @property\n def has_hv_battery(self) -> bool:\n \"\"\"Return True if vehicle is equipped with a high voltage battery.\n\n In this case we can get the state of the battery in the state attributes.\n \"\"\"\n return self.drive_train in HV_BATTERY_DRIVE_TRAINS\n\n @property\n def has_internal_combustion_engine(self) -> bool:\n \"\"\"Return True if vehicle is equipped with an internal combustion engine.\n\n In this case we can get the state of the gas tank.\"\"\"\n return self.drive_train in COMBUSTION_ENGINE_DRIVE_TRAINS\n\n @property\n def drive_train_attributes(self) -> List[str]:\n \"\"\"Get list of attributes available for the drive train of the vehicle.\n\n The list of available attributes depends if on the type of drive train.\n Some attributes only exist for electric/hybrid vehicles, others only if you\n have a combustion engine. Depending on the state of the vehicle, some of\n the attributes might still be None.\n \"\"\"\n result = ['remaining_range_total']\n if self.has_hv_battery:\n result += ['charging_time_remaining', 'charging_status', 'max_range_electric', 'charging_level_hv']\n if self.has_internal_combustion_engine:\n result += ['remaining_fuel']\n if self.has_hv_battery and self.has_internal_combustion_engine:\n result += ['remaining_range_electric', 'remaining_range_fuel']\n return result\n\n def get_vehicle_image(self, width: int, height: int, direction: VehicleViewDirection) -> bytes:\n \"\"\"Get a rendered image of the vehicle.\n\n :returns bytes containing the image in PNG format.\n \"\"\"\n url = VEHICLE_IMAGE_URL.format(\n vin=self.vin,\n server=self._account.server_url,\n width=width,\n height=height,\n view=direction.value,\n )\n header = self._account.request_header\n # the accept field of the header needs to be updated as we want a png not the usual JSON\n header['accept'] = 'image/png'\n response = self._account.send_request(url, headers=header)\n return response.content\n\n def __getattr__(self, item):\n \"\"\"In the first version: just get the attributes from the dict.\n\n In a later version we might parse the attributes to provide a more advanced API.\n :param item: item to get, as defined in VEHICLE_ATTRIBUTES\n \"\"\"\n return self.attributes.get(item)\n\n def __str__(self) -> str:\n \"\"\"Use the name as identifier for the vehicle.\"\"\"\n return '{}: {}'.format(self.__class__, self.name)\n","sub_path":"bimmer_connected/vehicle.py","file_name":"vehicle.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"367105227","text":"#!/usr/bin/env python3\n\n\"\"\"\nTest blk-mq scalability with the null-blk kernel module.\n\"\"\"\n\nimport argparse\nimport datetime\nimport glob\nimport json\nimport multiprocessing\nimport os\nimport os.path\nimport re\nimport statistics\nimport subprocess\nimport sys\n\n\ndef run_fio(args, num_jobs):\n subprocess.check_call(['modprobe', '-r', 'null_blk'])\n subprocess.check_call(['modprobe', 'null_blk', 'queue_mode=2',\n 'hw_queue_depth={}'.format(args.queue_depth),\n 'submit_queues={}'.format(args.hw_queues)])\n if args.disable_iostats:\n with open('/sys/block/nullb0/queue/iostats', 'w') as f:\n f.write('0\\n')\n name = 'fio{}'.format(num_jobs)\n output = name + '.json'\n fio_cmd = [\n 'fio',\n '--output={}'.format(output),\n '--output-format=json',\n '--name={}'.format(name),\n '--filename=/dev/nullb0',\n '--direct=1',\n '--numjobs={}'.format(num_jobs),\n '--cpus_allowed_policy=split',\n '--runtime=10',\n '--time_based',\n '--ioengine={}'.format(args.ioengine),\n '--iodepth={}'.format(args.iodepth),\n '--rw={}'.format(args.rw),\n ]\n subprocess.check_call(fio_cmd, stdout=subprocess.DEVNULL)\n\n with open(output, 'r') as f:\n fio_output = json.load(f)\n return aggregate_iops(fio_output)\n\n\ndef aggregate_iops(fio_output):\n read_iops = [job['read']['iops'] for job in fio_output['jobs']]\n read_merges = sum(disk_util['read_merges'] for disk_util in fio_output['disk_util'])\n return {\n 'num_jobs': len(fio_output['jobs']),\n 'total_iops': sum(read_iops),\n 'min_iops': min(read_iops),\n 'max_iops': max(read_iops),\n 'mean_iops': statistics.mean(read_iops),\n 'iops_stdev': statistics.stdev(read_iops) if len(read_iops) > 1 else 0.0,\n 'merges': read_merges,\n }\n\n\ndef print_header():\n print('JOBS\\tTOTAL IOPS\\tMIN IOPS\\tMAX IOPS\\tMEAN IOPS\\tIOPS STDEV\\tMERGES', file=sys.stderr)\n sys.stderr.flush()\n\n\ndef print_results(iops):\n print('{num_jobs}\\t{total_iops}\\t{min_iops}\\t{max_iops}\\t{mean_iops}\\t{iops_stdev}\\t{merges}'.format(**iops))\n sys.stdout.flush()\n\n\ndef main():\n def positive_int(value):\n n = int(value)\n if n <= 0:\n raise ValueError\n return n\n parser = argparse.ArgumentParser(\n description='test blk-mq scalability with null-blk',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n '--parse', metavar='PATH', type=str, default=argparse.SUPPRESS,\n help='parse saved result directory instead of running; all other options will be ignored')\n\n script_group = parser.add_argument_group('script options')\n script_group.add_argument(\n '-m', '--min-jobs', type=int, default=1,\n help='minimum number of jobs to run in parallel')\n script_group.add_argument(\n '-M', '--max-jobs', type=int, default=multiprocessing.cpu_count(),\n help='maximum number of jobs to run in parallel')\n\n null_blk_group = parser.add_argument_group('null-blk parameters')\n null_blk_group.add_argument(\n '-q', '--hw-queues', type=positive_int, default=multiprocessing.cpu_count(),\n help='number of null-blk hardware queues to use')\n null_blk_group.add_argument(\n '-d', '--queue-depth', type=positive_int, default=64,\n help='depth of null-blk hardware queues')\n null_blk_group.add_argument(\n '--disable-iostats', action='store_true', help='disable iostats')\n\n fio_group = parser.add_argument_group('fio parameters')\n fio_group.add_argument(\n '--ioengine', type=str, default='libaio', help='I/O engine')\n fio_group.add_argument(\n '--iodepth', type=positive_int, default=64, help='I/O depth')\n fio_group.add_argument(\n '--rw', type=str, default='randread', help='I/O pattern')\n\n args = parser.parse_args()\n\n if hasattr(args, 'parse'):\n os.chdir(args.parse)\n print_header()\n paths = glob.glob('fio*.json')\n paths.sort(key=lambda path: int(re.search(r'\\d+', path).group()))\n for path in paths:\n with open(path, 'r') as f:\n fio_output = json.load(f)\n iops = aggregate_iops(fio_output)\n print_results(iops)\n return\n\n now = datetime.datetime.now()\n dir = 'null_blk_scale_' + now.replace(microsecond=0).isoformat()\n os.mkdir(dir)\n print(os.path.abspath(dir), file=sys.stderr)\n os.chdir(dir)\n\n info = {\n 'args': vars(args),\n 'date': now.isoformat(),\n 'kernel_version': os.uname().release,\n }\n with open('info.json', 'w') as f:\n json.dump(info, f, sort_keys=True, indent=4)\n\n print_header()\n for num_jobs in range(args.min_jobs, args.max_jobs + 1):\n iops = run_fio(args, num_jobs)\n print_results(iops)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/null_blk_scale.py","file_name":"null_blk_scale.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"303704740","text":"from django import forms\nimport floppyforms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import User\nfrom app.generics.exceptions import ShouldNotExist\nfrom app.generics.choices import LIST_OF_ADDRESS_TYPES, GENDERS\nfrom customer.models import UserProfile, ExtendedInformation\n\n\nclass NewUserForm(floppyforms.Form):\n\n first_name = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'First Name'}))\n last_name = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Last Name'}))\n email = forms.EmailField(\n widget=floppyforms.EmailInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Email'}))\n phone_mobile = floppyforms.CharField(\n required=False,\n widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Mobile number', 'autocomplete': 'false'}))\n gender = floppyforms.ChoiceField(choices=GENDERS, widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Gender', 'autocomplete': 'true'}))\n address = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Address'}))\n\n def save(self):\n email = self.cleaned_data['email']\n username = get_user_model().objects.filter(username=email)\n useremail = get_user_model().objects.filter(email=email)\n profile = UserProfile.objects.filter(email=email)\n\n if len(username) != 0 or len(profile) != 0 or len(useremail) != 0:\n raise ShouldNotExist\n\n new_user = get_user_model().objects.create_user(\n self.data.get('email', None),\n email=self.data.get('email', None),\n first_name=self.data.get('first_name', None),\n last_name=self.data.get('last_name', None)\n )\n\n # http://stackoverflow.com/questions/6034763/django-attributeerror-user-object-has-no-attribute-backend-but-it-does\n new_user.backend = 'django.contrib.auth.backends.ModelBackend'\n new_user.profile, created = UserProfile.objects.get_or_create(user=new_user)\n new_user.profile.first_name = new_user.first_name\n new_user.profile.last_name = new_user.last_name\n new_user.profile.email = new_user.email\n # new_user.profile.phone_mobile = self.data.get('mobile', None)\n # new_user.profile.gender = self.data.get('gender', None)\n new_user.profile.save()\n\n new_user.extended_information, created = ExtendedInformation.objects.get_or_create(user=new_user)\n new_user.extended_information.phone_mobile = self.phone_mobile\n new_user.extended_information.address = self.address\n new_user.extended_information.gender = self.gender\n new_user.extended_information.save()\n\n # new_user.account_verification = AccountVerification.objects.get_or_create(user=new_user)\n\n # context_data = {\n # 'first_name': new_user.profile.first_name,\n # 'last_name': new_user.profile.last_name,\n # 'key': str(new_user.account_verification.key),\n # }\n\n # send_password_reset_email.delay(email=self.cleaned, context_data=context_data)\n return new_user\n\n\nclass ProfileForm(floppyforms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n class Meta:\n model = UserProfile\n exclude = ('date', 'email', 'client',)\n widgets = {\n 'first_name': floppyforms.TextInput(),\n 'last_name': floppyforms.TextInput(),\n }\n\n\nclass ExtendedInformationForm(forms.ModelForm):\n class Meta:\n model = ExtendedInformation\n exclude = ('user',)\n fields = (\n 'phone_mobile',\n 'gender',\n )\n widgets = {\n 'phone_mobile': floppyforms.TextInput(attrs={'length': \"10\"}),\n 'address': floppyforms.TextInput(attrs={'placeholder': 'Your Address'}),\n 'gender': floppyforms.Select(choices=GENDERS),\n }","sub_path":"customer/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"4050308","text":"\nfrom django import forms\nfrom .models import Context\n\nclass ContextForm(forms.ModelForm):\n class Meta:\n model = Context\n fields = (\n 'context_id',\n 'area_easting',\n 'area_northing',\n 'context_number',\n 'context_type',\n 'description',\n 'deposition_interpretation',\n 'subtable',\n 'chronology',\n 'chronology_source',\n 'stratigraphic_narrative',\n )\n","sub_path":"excavation/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"429587142","text":"from flask_app import app\nfrom flask import Flask,render_template, redirect, request\nfrom flask_app.models.post import Post\nfrom flask_app.models.type import Type\nfrom flask_bcrypt import Bcrypt\nfrom flask import flash\n\n@app.route('/managetypes') \ndef types():\n types = Type.get_all()\n\n return render_template(\"types.html\", types = types)\n\n\n@app.route('/deletetype/<int:id>') \ndef deletetype(id):\n data = {\n 'id': id\n }\n posts = Post.get_all()\n numPostsOfType = 0\n\n for p in posts:\n if p.type_id == id:\n numPostsOfType += 1\n \n if numPostsOfType > 0:\n type = Type.get_by_id(data)\n flash(f\"Cannot delete {type.name}. {numPostsOfType} post(s) exist of that type.\")\n return redirect(\"/managetypes\")\n\n Type.delete(data)\n return redirect(\"/managetypes\")\n\n@app.route('/addtype', methods=['POST']) \ndef addtype():\n data = {\n 'name': request.form['name'],\n 'img_url': request.form['img_url'],\n 'description': request.form['description']\n }\n Type.save(data)\n return redirect(\"/managetypes\")","sub_path":"flask_app/controllers/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"408158069","text":"import numpy as np\n\n# from custom_code.settings import NUM_FOLDS\n\n\nclass timefold(object):\n \"\"\"\n Cross-validation methods for timeseries data.\n\n Available methods\n * nested\n Generates train-test pair indices with a growing training window.\n\n Example (folds=3):\n TRAIN: [0 1 2] TEST: [3 4 5]\n TRAIN: [0 1 2 3 4 5] TEST: [6 7 8]\n TRAIN: [0 1 2s 3 4 5 6 7] TEST: [8 9]\n\n * window\n Generates train-test pair indices with a moving window.\n\n Example (folds=3):\n TRAIN: [0 1 2] TEST: [3 4 5]\n TRAIN: [3 4 5] TEST: [6 7 8]\n TRAIN: [6 7] TEST: [8 9]\n\n * step\n Generates one step ahead train-test pair indices with specified testing size.\n\n Fold argument is ignored. The maximum possible number of folds is generated based on\n the number of samples and specified testing window size.\n\n Example (test_size=1):\n TRAIN: [0] TEST: [1]\n TRAIN: [0 1] TEST: [2]\n TRAIN: [0 1 2] TEST: [3]\n TRAIN: [0 1 2 3] TEST: [4]\n TRAIN: [0 1 2 3 4] TEST: [5]\n TRAIN: [0 1 2 3 4 5] TEST: [6]\n TRAIN: [0 1 2 3 4 5 6] TEST: [7]\n TRAIN: [0 1 2 3 4 5 6 7] TEST: [8]\n TRAIN: [0 1 2 3 4 5 6 7 8] TEST: [9]\n\n * shrink\n Generates train-test pair indices with a shrinking training window and constant testing window.\n\n Example (folds=3):\n TRAIN: [0 1 2 3 4 5 6 7] TEST: [8 9]\n TRAIN: [3 4 5 6 7] TEST: [8 9]\n TRAIN: [6 7] TEST: [8 9]\n\n * stratified\n Generates stratified train-test pair indices where a ratio is preserved per fold.\n\n To be implemented\n \"\"\"\n\n def __init__(self, folds=10, method='nested', min_train_size=1, min_test_size=1, step_size=1):\n self.folds = folds\n self.method = method\n self.min_train_size = min_train_size\n self.min_test_size = min_test_size\n self.step_size = step_size\n\n def split(self, X):\n \"\"\"\n Split data into train-test pairs based on specified cross-validation method.\n \"\"\"\n folds = self.folds\n method = self.method\n min_train_size = self.min_train_size\n min_test_size = self.min_test_size\n step_size = self.step_size\n\n X_obs = X.shape[0]\n indices = np.arange(X_obs)\n\n if folds >= X_obs:\n raise ValueError(\n (\"The number of folds {0} must be smaller than the number of observations {1}\".format(folds, X_obs)))\n\n folds += 1\n fold_indices = np.array_split(indices, folds, axis=0)\n fold_sizes = [len(fold) for fold in fold_indices][:-1]\n train_starts = [fold[0] for fold in fold_indices][:-1]\n train_ends = [fold[0] for fold in fold_indices][1:]\n\n if method == 'nested':\n for end, size in zip(train_ends, fold_sizes):\n yield(indices[:end], indices[end:end + size])\n\n elif method == 'window':\n for start, end, size in zip(train_starts, train_ends, fold_sizes):\n yield(indices[start:end], indices[end:end + size])\n\n elif method == 'step':\n steps = np.arange(min_train_size, indices[-1], step_size)\n for step in steps:\n yield(indices[:step], indices[step:step + min_test_size])\n\n elif method == 'shrink':\n for start, size in zip(train_starts, fold_sizes):\n yield(indices[start:train_ends[-1]], indices[-fold_sizes[-1]:])\n\n elif method == 'stratified':\n pass\n\n else:\n raise ValueError(\"Unknown method supplied '{0}'. Method must be one of: 'nested', 'window', 'step', \"\n \"'stratified'\".format(method))\n","sub_path":"custom_code/timefold.py","file_name":"timefold.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"408908","text":"import argparse\nimport os\nimport sys\nimport csv\nimport numpy as np\nfrom keras_retinanet import models\nfrom keras_retinanet.utils.keras_version import check_keras_version\nfrom keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\nfrom keras_retinanet.utils.visualization import draw_box, draw_caption\nfrom keras_retinanet.utils.colors import label_color\nfrom keras_retinanet.preprocessing.csv_generator import _open_for_csv, _read_annotations, _open_for_csv, _read_classes\nimport keras\nimport tensorflow as tf\n\ndef get_session():\n\tconfig = tf.ConfigProto()\n\tconfig.gpu_options.allow_growth = True\n\treturn tf.Session(config=config)\ndef parse_args(args):\n\t\"\"\" Parse the arguments.\n\t\"\"\"\n\tparser = argparse.ArgumentParser(description='Evaluation script for a RetinaNet network.')\n\tsubparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type')\n\tsubparsers.required = True\n\n\tcoco_parser = subparsers.add_parser('coco')\n\tcoco_parser.add_argument('coco_path', help='Path to dataset directory (ie. /tmp/COCO).')\n\n\tpascal_parser = subparsers.add_parser('pascal')\n\tpascal_parser.add_argument('pascal_path', help='Path to dataset directory (ie. /tmp/VOCdevkit).')\n\n\tcsv_parser = subparsers.add_parser('csv')\n\tcsv_parser.add_argument('annotations', help='Path to CSV file containing annotations for evaluation.')\n\tcsv_parser.add_argument('classes', help='Path to a CSV file containing class label mapping.')\n\n\tparser.add_argument('model', help='Path to RetinaNet model.')\n\tparser.add_argument('--convert-model', help='Convert the model to an inference model (ie. the input is a training model).', action='store_true')\n\tparser.add_argument('--backbone', help='The backbone of the model.', default='resnet50')\n\tparser.add_argument('--gpu', help='Id of the GPU to use (as reported by nvidia-smi).')\n\tparser.add_argument('--score-threshold', help='Threshold on score to filter detections with (defaults to 0.05).', default=0.05, type=float)\n\tparser.add_argument('--iou-threshold', help='IoU Threshold to count for a positive detection (defaults to 0.5).', default=0.5, type=float)\n\tparser.add_argument('--max-detections', help='Max Detections per image (defaults to 100).', default=100, type=int)\n\tparser.add_argument('--save-path', help='Path for saving images with detections (doesn\\'t work for COCO).')\n\tparser.add_argument('--image-min-side', help='Rescale the image so the smallest side is min_side.', type=int, default=800)\n\tparser.add_argument('--image-max-side', help='Rescale the image if the largest side is larger than max_side.', type=int, default=1333)\n\tparser.add_argument('--config', help='Path to a configuration parameters .ini file (only used with --convert-model).')\n\n\n\treturn parser.parse_args(args)\n\n# use this environment flag to change which GPU to use\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n# set the modified tf session as backend in keras\nkeras.backend.tensorflow_backend.set_session(get_session())\n\n\ndef main(args=None):\n\t# parse arguments\n\tif args is None:\n\t\targs = sys.argv[1:]\n\targs = parse_args(args)\n\n\t# make sure keras is the minimum required version\n\tcheck_keras_version()\n\n\t# optionally choose specific GPU\n\tif args.gpu:\n\t\tos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\tkeras.backend.tensorflow_backend.set_session(get_session())\n\n\t# make save path if it doesn't exist\n\tif args.save_path is not None and not os.path.exists(args.save_path):\n\t\tos.makedirs(args.save_path)\n\n\t# optionally load config parameters\n\tif args.config:\n\t\targs.config = read_config_file(args.config)\n\n\t# create the generator\n\t#generator = create_generator(args)\n\n\t# optionally load anchor parameters\n\tanchor_params = None\n\tif args.config and 'anchor_parameters' in args.config:\n\t\tanchor_params = parse_anchor_parameters(args.config)\n\n\t# load the model\n\tprint('Loading model, this may take a second...')\n\tmodel = models.load_model(args.model, backbone_name=args.backbone)\n\n\t# optionally convert the model\n\tif args.convert_model:\n\t\tmodel = models.convert_model(model, anchor_params=anchor_params)\n\n\t# print model summary\n\tprint(model.summary())\n\n\tprint(\"annotations\",args.annotations)\n\tprint(\"classes\",args.classes)\n\tprint(\"min\",args.image_min_side)\n\tprint(\"max\",args.image_max_side)\n\tprint(\"configs\",args.config)\n\tiou_threshold=args.iou_threshold\n\tscore_threshold=args.score_threshold\n\tmax_detections=args.max_detections\n\n\n\timage_names = []\n\timage_data = {}\n\t\n\n\t# Take base_dir from annotations file if not explicitly specified.\n \n\n\t# parse the provided class file\n\ttry:\n\t\twith _open_for_csv(args.classes) as file:\n\t\t\tclasses = _read_classes(csv.reader(file, delimiter=','))\n\texcept ValueError as e:\n\t\traise_from(ValueError('invalid CSV class file: {}: {}'.format(args.classes, e)), None)\n\n\tlabels = {}\n\tfor key, value in classes.items():\n\t\tlabels[value] = key\n\n\t# csv with img_path, x1, y1, x2, y2, class_name\n\ttry:\n\t\twith _open_for_csv(args.annotations) as file:\n\t\t\tfile_annotations = _read_annotations(csv.reader(file, delimiter=','), classes)\n\texcept ValueError as e:\n\t\traise_from(ValueError('invalid CSV annotations file: {}: {}'.format(args.annotations, e)), None)\n\timage_names = list(file_annotations.keys())\n\t\n\tnum_classes = len(labels)\n\n\tall_detections = [[None for i in range(num_classes) if i in labels] for j in range(len(image_names))]\n\tfor image_index in range(len(image_names)):\n\t\t\"\"\" Load annotations for an image_index.\n\t\t\"\"\"\n\t\tpath = file_annotations[image_names[image_index]]\n\t\tannotations = {'labels': np.empty((0,)), 'bboxes': np.empty((0, 4))}\n\n\t\tfor idx, annot in enumerate(file_annotations[image_names[image_index]]):\n\t\t\tfor key, value in classes.items():\n\t\t\t\tif annot['class'] == key:\n\t\t\t\t\tbreak;\n\n\n\t\t\tannotations['labels'] = np.concatenate((annotations['labels'], [value]))\n\t\t\tannotations['bboxes'] = np.concatenate((annotations['bboxes'], [[\n\t\t\t\tfloat(annot['x1']),\n\t\t\t\tfloat(annot['y1']),\n\t\t\t\tfloat(annot['x2']),\n\t\t\t\tfloat(annot['y2']),\n\t\t\t]]))\n\n\tf = []\n\tfor label in range(num_classes):\n\t\tfor cls in classes:\n\t\t\t\tif classes[cls] == label:\n\t\t\t\t\tprint('class',cls)\n\t\t\t\t\tbreak\n\t\tf.append(open(\"results/comp4_det_\"+args.annotations.split(\"/\")[-1].split(\".\")[0]+\"_\"+cls+\".txt\",'w'))\n\n\n\tfor i in range(0, len(image_names)):\n\t\tprint('image num',i)\n\t\tfile_name = image_names[i]\n\n\n\t\t# load image\n\t\timage = read_image_bgr(file_name)\n\t\timage = preprocess_image(image)\n\t\timage, scale = resize_image(image)\n\t\tboxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0))\n\t\tboxes /= scale\n\n\t\t# select indices which have a score above the threshold\n\t\tindices = np.where(scores[0, :] > score_threshold)[0]\n\n\t\t# select those scores\n\t\tscores = scores[0][indices]\n\n\t\t# find the order with which to sort the scores\n\t\tscores_sort = np.argsort(-scores)[:max_detections]\n\n\t\t# select detections\n\t\timage_boxes = boxes[0, indices[scores_sort], :]\n\t\timage_scores = scores[scores_sort]\n\t\timage_labels = labels[0, indices[scores_sort]]\n\t\timage_detections = np.concatenate([image_boxes, np.expand_dims(image_scores, axis=1), np.expand_dims(image_labels, axis=1)], axis=1)\n\t\t# copy detections to all_detections\n\t\tfor label in range(num_classes):\n\t\t\tif not label in labels:\n\t\t\t\tcontinue\n\t\t\tdets = image_detections[image_detections[:, -1] == label, :-1]\n\t\t\tfor cls in classes:\n\t\t\t\tif classes[cls] == label:\n\t\t\t\t\tprint('class',cls)\n\t\t\t\t\tbreak\n\t\t\tfor scr in dets:\n\t\t\t\tf[label].write(file_name.split(\"/\")[-1].split(\".\")[0]+\" \"+str(scr[4])+\" \"+str(scr[0])+\" \"+str(scr[1])+\" \"+str(scr[2])+\" \"+str(scr[3])+\"\\n\")\n\t\t\t\t\n\tfor label in range(num_classes):\n\t\tf[label].close()\n\t\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"custom_eval.py","file_name":"custom_eval.py","file_ext":"py","file_size_in_byte":7668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"201837597","text":"# -*- coding: utf-8 -*-\nimport paddle\nfrom paddle import fluid\nimport math\nfrom paddle.fluid.layers.learning_rate_scheduler import _decay_step_counter\nfrom paddle.fluid.initializer import init_on_cpu\nimport paddle.fluid.layers.ops as ops\nfrom paddle.fluid.layers import control_flow\n\ndef cosine_decay_v2(learning_rate, totalsteps):\n \"\"\"Applies cosine decay to the learning rate.\n lr = 0.05 * (math.cos(global_step * (math.pi / totalsteps)) + 1)\n decrease lr for every mini-batch.\n \"\"\"\n global_step = _decay_step_counter()\n\n with init_on_cpu():\n decayed_lr = learning_rate * \\\n (ops.cos(global_step * (math.pi / float(totalsteps))) + 1)/2\n return decayed_lr\n\n\ndef cosine_decay_v2_with_warmup(learning_rate, warmupsteps, totalsteps):\n \"\"\"Applies cosine decay to the learning rate.\n lr = 0.05 * (math.cos(epoch * (math.pi / 120)) + 1)\n decrease lr for every mini-batch and start with warmup.\n \"\"\"\n global_step = _decay_step_counter()\n lr = fluid.layers.tensor.create_global_var(\n shape=[1],\n value=0.0,\n dtype='float32',\n persistable=True,\n name=\"learning_rate\")\n\n with init_on_cpu():\n with control_flow.Switch() as switch:\n with switch.case(global_step < warmupsteps):\n decayed_lr = learning_rate * (global_step / float(warmupsteps))\n fluid.layers.tensor.assign(input=decayed_lr, output=lr)\n with switch.default():\n decayed_lr = learning_rate * \\\n (ops.cos((global_step - warmupsteps) * (math.pi / (totalsteps))) + 1)/2\n fluid.layers.tensor.assign(input=decayed_lr, output=lr)\n return lr\n","sub_path":"image_feature/metric_learning/learning_rate.py","file_name":"learning_rate.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"514799477","text":"# In this lecture we'll cover the fundamentals of loops.\n# A loop is basically a way to execute a statement multiple times.\n# Loops allow to save a lot of code, and avoid some replications.\n# In Python there are two different loops: for and while\n\nemails = [\"foo@email.com\", \"me@gmail.com\", \"you@hotmail.com\"]\n\n# If we want to print each item inside the list, we can do by using one print\n# function for each item of the list, but this implies some kind of replication of code.\n# The for loop is very useful in a case like this:\n\nfor email in emails:\n print (email)\n\n# The previous two lines print the item of the list, for each item\n\n# Suppose that we want to print only the gmail addresses:\n\nfor email in emails:\n if email.endswith(\"@gmail.com\"):\n print (email)\n\n# We can do the same using the operator in:\n\nfor email in emails:\n if \"gmail\" in email:\n print (email)\n\n# Now we are going to cover the usage of for loop with more lists simultaneously\n\nnames = [\"John\", \"Jack\", \"Amber\"]\nemail_domains = [\"gmail.com\", \"hotmail.com\", \"yahoo.com\"]\n\nfor i,j in zip (names, email_domains):\n print(i,j)\n\n# zip function is used to access two or more lists contemporary\n","sub_path":"12_For_Loop/12_For_Loop.py","file_name":"12_For_Loop.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"536249906","text":"from testing import *\nfrom testing.tests import *\nfrom testing.assertions import *\nimport random\n\n\nwith scale(3), all_or_nothing(skip_after_fail=True):\n with tested_function_name(\"find_keys\"):\n random.seed(15676)\n\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\n def check(map, v, expected):\n @test(\"find_keys({}, {}) should return {}\", repr(map), repr(v), repr(expected))\n def _():\n must_be_equal(expected, tested_function(map, v))\n\n def generated_test():\n map = dict()\n expected = []\n\n val = random.randrange(1000)\n n = random.randrange(2, 5)\n\n while len(map) < n:\n k = random.randrange(1000)\n expected.append(k)\n map[k] = val\n\n expected = sorted(list(set(expected)))\n\n n = random.randrange(2, 5)\n while n > 0:\n k = random.randrange(1000)\n v = random.randrange(1000)\n\n if k not in map and v != val:\n map[k] = v\n n -= 1\n\n check(map, val, expected)\n\n\n check( {'a': 1}, 1, [ 'a' ] )\n check( {'a': 1, 'b': 2}, 1, [ 'a' ] )\n check( {'a': 1, 'b': 2}, 2, [ 'b' ] )\n check( {'a': 1, 'b': 1}, 1, [ 'a', 'b' ] )\n check( {'a': 1, 'b': 1}, 2, [] )\n check( {1: 'a', 2: 'a', 3: 'b'}, 'a', [1, 2] )\n\n for _ in range(1000):\n generated_test()\n","sub_path":"1ejaar(2018-2019)/2e semester/scriptalen/ExamJanuary 2019/exercises/find-keys/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"11790587","text":"#code for basic geocoding search\nimport requests\nimport sys\nimport json\n\nurl = \"https://us1.locationiq.com/v1/search.php\"\n#change this to the input\nquery = sys.argv[1]\n\ndata = {\n 'key': '8d6879e1df3d64',\n 'q': query,\n 'format': 'json'\n}\n\nresponse = requests.get(url, params=data)\n\nrjson = response.json()\n#latitude\nlat = rjson[0]['lat']\n#longitude\nlon = rjson[0]['lon']\n#display name\ndisplay = rjson[0]['display_name']\n\n#print(lat, lon, display)","sub_path":"pre_processing_scripts/apisearch.py","file_name":"apisearch.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"306771404","text":"#-*- coding:utf8 -*-\n\nimport wikipydia\n\nimport mediawiki\n# import re\n\nLANG = 'ru'\nSEE_ALSO = {'ru': u\"См. также\",\n 'en': u\"See also\"}\n\nclass WikiPage(object):\n def __init__(self, query, lang=LANG):\n self.title, self.text = self.get_wiki(query, lang)\n self.lang = lang\n\n def __repr__(self):\n return self.title\n\n def get_wiki(self, query, lang):\n try:\n title = wikipydia.opensearch(query, language=lang)[1][0].encode('utf8')\n text = wikipydia.query_text_raw(title, language=lang)\n return title, text['text'].encode('utf8')\n except IndexError:\n pass\n\n def get_see_also(self):\n try:\n sections = wikipydia.get_sections(self.text)\n section = [h.strip().decode('utf8') for h in sections['headers']].index(SEE_ALSO[self.lang])\n return wikipydia.get_links( sections['contents'][section] ).values()\n except ValueError:\n return []\n\n def gen_html(self):\n return mediawiki.wiki2html(self.text, True)\n # result = []\n # headers = wikipydia.get_sections(self.text)['headers']\n # contents = wikipydia.get_sections(self.text)['contents']\n # for section in zip(headers, contents):\n # power = (len(re.findall(\"=*\", section[0])[0])+1)\n # head_name = ' '.join(section[0].split(' ')[1:])\n # head = \"<h%d>%s</h%d>\" % (power, head_name, power)\n # result.append(head)\n # result.append(section[1])\n # return ''.join(result)\n","sub_path":"wsgi/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"468349622","text":"# This server serves the webpages. It does not interact with the websockets.\n\nimport string, cgi, time\nimport json\nfrom os import curdir, sep\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\n# This is a simple http server and is not very safe in its current form.\n# No encryption is offered and a clever user could access any file on your system with this setup.\nclass MyHandler(BaseHTTPRequestHandler):\n\n # Handles GET requests\n # PATH is the request path including the leading /\n # By default will just act as a base server and return files\n def do_GET(self):\n try:\n out = None\n if self.path == '/':\n self.path = \"/index.html\"\n if self.path == '/host':\n self.path == '/host.html'\n if self.path[0:4] == \"/lib\":\n self.path = \"/vendor\" + self.path[4:]\n\n qInd = self.path.find(\"?\")\n if (qInd >= 0):\n request = self.path[qInd:]\n self.path = self.path[:qInd]\n if self.path == '/userFunc':\n out = userFunc()\n contentType = \"json\"\n if out is None:\n ext = self.path.split('.')\n ext = ext[len(ext)-1]\n read = 'rb'\n with open(curdir + sep + self.path, read) as f:\n out = f.read()\n contentType = ext\n self.gen_headers(contentType)\n self.wfile.write(out)\n return\n except IOError:\n self.send_error(404, 'File Not Found: %s' % self.path)\n\n # Generates headers for the given content type\n # Possible values are html, css, js, and json\n # Invalid values default to html\n def gen_headers(self, contentType):\n self.send_response(200)\n contentType = 'text/html'\n if (ext == \"css\"):\n contentType = 'text/css'\n elif (ext == \"js\"):\n contentType = 'application/javascript'\n elif (ext == \"json\"):\n contentType = 'application/json'\n self.send_header('Content-type', contentType)\n self.end_headers()\n\n # Handles POST requests\n # PATH is the request path including the leading /\n # body is a dictionary of the JSON body of the POST\n def do_POST(self):\n path = self.path[4:]\n length = int(self.headers['Content-Length'])\n body = json.loads(self.rfile.read(length).decode(\"utf-8\")) \n self.send_response(200)\n return\n\n# User defined function. Returns json.\ndef userFunc():\n return '{\"name\": \"PyWebPlug\"}'\n\n# A manual header parser\ndef parseHeaders(headers):\n headers = headers.split('\\n')\n out = {}\n for header in headers:\n parts = header.split(\":\")\n if len(parts) > 1:\n out[parts[0]] = parts[1]\n return out\n\ndef main():\n try:\n # Server on the standard webserver port of 80.\n server = HTTPServer(('', 8001), MyHandler)\n print(\"Starting webpage server...\")\n server.serve_forever()\n except KeyboardInterrupt:\n print(' received, closing server.')\n server.socket.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"611961943","text":"from django.urls import path\nfrom rest_framework import routers\n\nfrom main.views import ProjectListAPIView, \\\n ProjectDetailAPIView, BlockListView, BlockDetailView, TaskViewSet, \\\n MemberProjectViewSet, TaskDocumentViewSet, \\\n task_comment_lists, task_comment_detail\n\nurlpatterns = [\n path('projects/', ProjectListAPIView.as_view()),\n path('projects/<int:pk>/', ProjectDetailAPIView.as_view()),\n path('blocks/', BlockListView.as_view()),\n path('blocks/<int:pk>/', BlockDetailView.as_view()),\n path('tasks/<int:pk>/comments/', task_comment_lists),\n path('comments/<int:pk>/', task_comment_detail)\n]\n\nrouter = routers.DefaultRouter()\nrouter.register('tasks', TaskViewSet, base_name='api')\nrouter.register('task_documents', TaskDocumentViewSet, base_name='api')\nrouter.register('project_members', MemberProjectViewSet, base_name='api')\n\nurlpatterns += router.urls\n","sub_path":"JIRA/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"16752792","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport subprocess\nimport src.context_manager\nimport src.prerequisites\nimport src.path\nimport src.manage_config\nimport src.error\nimport decode_and_score\n\n\n# decode_and_score for multiple WAV file\ndef multiple_decode_and_score(wav=None, stm=None):\n\n values = init(wav, stm)\n wav = {}\n for roots, dirs, files in os.walk(values['wav_folder']):\n for file in files:\n if file.endswith('.wav'):\n key = os.path.join(values['wav_folder'], file)\n value = os.path.join(\n values['stm_folder'],\n os.path.splitext(file)[0] + '.stm'\n )\n wav[key] = value\n\n # Check for STM files that are not encoded in utf-8\n stm = [wav[k] for k, v in wav.items()]\n encode_to_utf8_list(stm)\n\n # launch decode/score process\n ctm = {}\n for wav, stm in wav.items():\n decode_and_score.decode_and_score(wav, stm)\n wav_name = os.path.splitext(os.path.basename(wav))[0]\n path = os.path.join(values['output_dir'], wav_name, wav_name + '.ctm')\n ctm[stm] = path\n concatenate_ctm = values['output_dir'] + '/full_ctm'\n concatenate_stm = values['output_dir'] + '/full_stm'\n\n # Check for CTM/SRm files that are not encoded in utf-8\n encode_to_utf8(ctm)\n\n # Concating CTM and STM files\n with open(concatenate_ctm, 'w', encoding='utf-8') as full_ctm:\n with open(concatenate_stm, 'w', encoding='utf-8') as full_stm:\n for stm, ctm in ctm.items():\n with open(stm, 'r', encoding='utf-8') as sf:\n print('--- Opening stm file : {}'.format(stm))\n full_stm.write(sf.read())\n with open(ctm, 'r', encoding='utf-8') as cf:\n print('--- Opening ctm file : {}'.format(ctm))\n full_ctm.write(cf.read())\n\n # Sort CTM and STM files\n subprocess.call('sort -k1,1 -k4,4n {}'.format(concatenate_stm), shell=True)\n subprocess.call('sort -k1,1 -k3,3n {}'.format(concatenate_ctm), shell=True)\n\n # Add SCLITE path to $PATH\n kaldi_path = decode_and_score.get_kaldi_path(values)\n sclite_path = src.path.get_folder_path(kaldi_path, \"sctk\")\n if sclite_path.startswith('__'):\n src.error.print_error(sclite_path)\n os.environ['PATH'] = os.environ['PATH'] + ':' + sclite_path + '/bin'\n\n # Score the big STM/CTM file\n subprocess.call(\n 'sclite -h {} ctm -r {} stm -o sum pra prf snt dtl'.\n format(concatenate_ctm, concatenate_stm),\n shell=True)\n\n\ndef init(wav_folder=None, stm_folder=None):\n \"\"\"\n Check configuration file and wav/stm folders,\n in order to extract all usable values.\n This function also check for available path pass to the script\n \"\"\"\n values = src.manage_config.check_conf_file(\n None,\n None,\n wav_folder,\n stm_folder\n )\n result = src.prerequisites.check_folder(\n values['wav_folder'],\n values['stm_folder']\n )\n if result is not 0:\n src.error.print_error(result)\n return values\n\n\ndef encode_to_utf8(dictionary):\n \"\"\"\n Function that check for stm and ctm files that are not utf-8 encoded,\n copy non-utf8 version into 'filename.no_utf8' version,\n and convert this version to 'filename' with utf8 encoding\n \"\"\"\n for stm, ctm in dictionary.items():\n encoding = subprocess.getoutput(\n 'file -bi {} | cut -d \"=\" -f2'.\n format(stm)\n )\n if encoding is not \"utf-8\":\n os.rename(stm, stm + '.no_utf8')\n subprocess.call(\n 'iconv -f {} -t utf-8 {}.no_utf8 > {}'.\n format(encoding, stm, stm),\n shell=True\n )\n encoding = subprocess.getoutput(\n 'file -bi {} | cut -d \"=\" -f2'.\n format(ctm)\n )\n if encoding is not \"utf-8\":\n os.rename(ctm, ctm + '.no_utf8')\n subprocess.call(\n 'iconv -f {} -t utf-8 {}.no_utf8 > {}'.\n format(encoding, ctm, ctm),\n shell=True\n )\n\n\ndef encode_to_utf8_list(list_var):\n for element in list_var:\n encoding = subprocess.getoutput(\n 'file -bi {} | cut -d \"=\" -f2'.\n format(element)\n )\n if encoding is not \"utf-8\":\n os.rename(element, element + '.no_utf8')\n subprocess.call(\n 'iconv -f {} -t utf-8 {}.no_utf8 > {}'.\n format(encoding, element, element),\n shell=True\n )\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--wav',\n help='The wav FOLDER that you want to decode',\n type=str\n )\n parser.add_argument(\n '--stm',\n help='The stm FOLDER that correspond to the wav file',\n type=str\n )\n args = parser.parse_args()\n\n multiple_decode_and_score(\n args.wav,\n args.stm\n )\n","sub_path":"wrapper_for_kaldi/multiple_decode_and_score.py","file_name":"multiple_decode_and_score.py","file_ext":"py","file_size_in_byte":6017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"30741037","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom collections import Counter\n\n\ndef part1(values: list) -> int:\n twos = threes = 0\n for v in values:\n c = Counter(v)\n found_two = found_three = False\n for l, n in c.items():\n if found_two and found_three:\n break\n elif not found_two and n == 2:\n twos += 1\n found_two = True\n elif not found_three and n == 3:\n threes += 1\n found_three = True\n return twos * threes\n\n\ndef part2(values: list) -> str:\n for i in range(0, len(values)):\n current_id = values[i]\n for j in range(i + 1, len(values)):\n diff_count = 0\n diff_char_num = None\n tested_id = values[j]\n for k in range(0, len(current_id)):\n if current_id[k] != tested_id[k]:\n diff_count += 1\n diff_char_num = k\n if diff_count > 1:\n break\n if diff_count == 1:\n return current_id[:diff_char_num] + current_id[(diff_char_num + 1):]\n\n\nif __name__ == '__main__':\n with open('input.txt') as f:\n values = list(f.read().splitlines())\n print(part1(values)) # 6200\n print(part2(values)) # xpysnnkqrbuhefmcajodplyzw\n","sub_path":"2018/day_02/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"374067854","text":"from lingvodoc.views.v2.utils import (\n get_user_by_client_id,\n view_field_from_object\n)\nfrom sqlalchemy.exc import IntegrityError\n\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\nfrom lingvodoc.models import (\n DBSession,\n Locale,\n TranslationAtom,\n TranslationGist,\n BaseGroup,\n User,\n DictionaryPerspective,\n DictionaryPerspectiveToField,\n Field,\n Client,\n Group,\n UserBlobs,\n Language,\n ObjectTOC,\n LexicalEntry,\n Dictionary,\n Entity\n)\n\nfrom sqlalchemy import (\n func,\n or_,\n and_,\n tuple_\n)\nfrom pyramid.httpexceptions import (\n HTTPBadRequest,\n HTTPConflict,\n HTTPFound,\n HTTPInternalServerError,\n HTTPNotFound,\n HTTPOk\n)\nfrom pyramid.security import authenticated_userid\n# from pyramid.chameleon_zpt import render_template_to_response\nfrom pyramid.renderers import render_to_response\nfrom lingvodoc.exceptions import CommonException\n\nimport sys\nimport multiprocessing\n\nif sys.platform == 'darwin':\n multiprocessing.set_start_method('spawn')\n\nimport logging\nlog = logging.getLogger(__name__)\nimport json\nimport requests\nfrom pyramid.request import Request\nfrom time import time\n\n\n@view_config(route_name='testing', renderer='json')\ndef testing(request):\n with_group = 0\n without_group = 0\n for group in DBSession.query(Group).filter_by(base_group_id=26).all():\n DBSession.delete(group)\n for persp in DBSession.query(DictionaryPerspective):\n group = DBSession.query(Group).filter_by(base_group_id=22, subject_client_id=persp.client_id,\n subject_object_id=persp.object_id).first()\n if not group:\n without_group +=1\n new_group = Group(base_group_id=26, subject_client_id=persp.client_id,\n subject_object_id=persp.object_id)\n for user in group.users:\n new_group.users.append(user)\n DBSession.add(new_group)\n return {\"good\": with_group, \"bad\": without_group}\n\n@view_config(route_name='main', renderer='templates/main.pt', request_method='GET')\ndef main_get(request):\n client_id = authenticated_userid(request)\n user = get_user_by_client_id(client_id)\n variables = {'client_id': client_id, 'user': user}\n return render_to_response('templates/main.pt', variables, request=request)\n\n\n@view_config(route_name='all_statuses', renderer='json', request_method='GET')\ndef all_statuses(request):\n from pyramid.request import Request\n import json\n\n response = list()\n for status in ['WiP', 'Published', 'Limited access', 'Hidden']:\n\n subreq = Request.blank('/translation_service_search')\n subreq.method = 'POST'\n subreq.headers = request.headers\n subreq.json = {'searchstring': status}\n headers = {'Cookie': request.headers['Cookie']}\n subreq.headers = headers\n resp = request.invoke_subrequest(subreq)\n response.append(resp.json)\n request.response.status = HTTPOk.code\n return response\n\n\n@view_config(route_name='all_locales', renderer='json', request_method='GET')\ndef all_locales(request):\n response = list()\n locales = DBSession.query(Locale).all()\n for locale in locales:\n locale_json = dict()\n locale_json['shortcut'] = locale.shortcut\n locale_json['intl_name'] = locale.intl_name\n locale_json['created_at'] = locale.created_at\n locale_json['id'] = locale.id\n response.append(locale_json)\n request.response.status = HTTPOk.code\n return response\n\n\n@view_config(route_name='all_locales_desktop', renderer='json', request_method='GET')\ndef all_locales_desktop(request):\n settings = request.registry.settings\n path = settings['desktop']['central_server'] + 'all_locales'\n session = requests.Session()\n session.headers.update({'Connection': 'Keep-Alive'})\n adapter = requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=1, max_retries=10)\n session.mount('http://', adapter)\n status = session.get(path)\n if status.status_code == 200:\n request.response.status = HTTPOk.code\n return status.json()\n else:\n print(status.status_code)\n request.response.status = HTTPInternalServerError.code\n return {'error': 'no connection'}\n\n\n@view_config(route_name='published_dictionaries_desktop', renderer='json', request_method='POST')\ndef published_dictionaries_desktop(request):\n req = request.json_body\n settings = request.registry.settings\n path = settings['desktop']['central_server'] + 'published_dictionaries'\n session = requests.Session()\n session.headers.update({'Connection': 'Keep-Alive'})\n adapter = requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=1, max_retries=10)\n session.mount('http://', adapter)\n\n with open('authentication_data.json', 'r') as f:\n cookies = json.loads(f.read())\n status = session.post(path, json=req, cookies=cookies)\n if status.status_code == 200:\n request.response.status = HTTPOk.code\n return status.json()\n else:\n print(status.status_code)\n request.response.status = HTTPInternalServerError.code\n return {'error':'no connection'}\n\n\n@view_config(route_name='all_perspectives_desktop', renderer='json', request_method='GET')\ndef all_perspectives_desktop(request):\n settings = request.registry.settings\n path = settings['desktop']['central_server'] + 'perspectives'\n published = request.params.get('published', None)\n path += '?visible=true'\n if published:\n path += '&published=true'\n session = requests.Session()\n session.headers.update({'Connection': 'Keep-Alive'})\n adapter = requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=1, max_retries=10)\n session.mount('http://', adapter)\n with open('authentication_data.json', 'r') as f:\n cookies = json.loads(f.read())\n status = session.get(path, cookies=cookies)\n if status.status_code == 200:\n request.response.status = HTTPOk.code\n return status.json()\n else:\n print(status.status_code)\n request.response.status = HTTPInternalServerError.code\n return {'error':'no connection'}\n\n\n@view_config(route_name='permissions_on_perspectives_desktop', renderer='json', request_method='GET')\ndef permissions_on_perspectives_desktop(request):\n\n settings = request.registry.settings\n path = settings['desktop']['central_server'] + 'permissions/perspectives'\n session = requests.Session()\n session.headers.update({'Connection': 'Keep-Alive'})\n adapter = requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=1, max_retries=10)\n session.mount('http://', adapter)\n with open('authentication_data.json', 'r') as f:\n cookies = json.loads(f.read())\n status = session.get(path, cookies=cookies)\n server_perms = status.json()\n path = request.route_url('permissions_on_perspectives')\n subreq = Request.blank(path)\n subreq.method = 'GET'\n subreq.headers = request.headers\n resp = request.invoke_subrequest(subreq)\n desktop_perms = resp.json\n\n def remove_keys(obj, rubbish):\n if isinstance(obj, dict):\n obj = {\n key: remove_keys(value, rubbish)\n for key, value in obj.items()\n if key not in rubbish and value is not None}\n elif isinstance(obj, list):\n obj = [remove_keys(item, rubbish)\n for item in obj\n if item not in rubbish]\n return obj\n\n server_perms.update(desktop_perms)\n return remove_keys(server_perms, ['publish'])\n\n\n\ndef dict_ids(obj):\n return {\"client_id\": obj.client_id,\n \"object_id\": obj.object_id}\n\n\n@view_config(route_name='corpora_fields', renderer='json', request_method='GET')\ndef corpora_fields(request):\n response = list()\n data_type_query = DBSession.query(Field) \\\n .join(TranslationGist,\n and_(Field.translation_gist_object_id == TranslationGist.object_id,\n Field.translation_gist_client_id == TranslationGist.client_id))\\\n .join(TranslationGist.translationatom)\n sound_field = data_type_query.filter(TranslationAtom.locale_id == 2,\n TranslationAtom.content == 'Sound').one() # todo: a way to find this fields if wwe cannot use one\n markup_field = data_type_query.filter(TranslationAtom.locale_id == 2,\n TranslationAtom.content == 'Markup').one()\n\n response.append(view_field_from_object(request=request, field = sound_field))\n response[0]['contains'] = [view_field_from_object(request=request, field = markup_field)]\n response.append(view_field_from_object(request=request, field = markup_field))\n request.response.status = HTTPOk.code\n return response\n\n\n@view_config(route_name='all_data_types', renderer='json', request_method='GET')\ndef all_data_types(request):\n from pyramid.request import Request\n import json\n\n response = list()\n for data_type in ['Text', 'Image', 'Sound', 'Markup', 'Link', 'Grouping Tag']:\n\n subreq = Request.blank('/translation_service_search')\n subreq.method = 'POST'\n subreq.headers = request.headers\n subreq.json = {'searchstring': data_type}\n # headers = {'Cookie': request.headers['Cookie']}\n # subreq.headers = headers\n resp = request.invoke_subrequest(subreq)\n response.append(resp.json)\n request.response.status = HTTPOk.code\n return response\n\n\n@view_config(route_name='create_group', renderer='json', request_method='POST', permission='logged_in') # todo: other permission?\ndef create_group(request):\n try:\n variables = {'auth': request.authenticated_userid}\n\n req = request.json_body\n client = DBSession.query(Client).filter_by(id=variables['auth']).first()\n if not client:\n raise KeyError(\"Invalid client id (not registered on server). Try to logout and then login.\",\n variables['auth'])\n user = DBSession.query(User).filter_by(id=client.user_id).first()\n if not user:\n raise CommonException(\"This client id is orphaned. Try to logout and then login once more.\")\n if not DBSession.query(Group).filter_by(id=req['id']).first():\n group = Group(id=req['id'],\n base_group_id=req['base_group_id'],\n subject_client_id=req['subject_client_id'],\n subject_object_id=req['subject_object_id'])\n DBSession.add(group)\n for user_id in req['users']:\n curr_user = DBSession.query(User).filter_by(id=user_id).first()\n if curr_user not in group.users:\n group.users.append(curr_user)\n\n return {}\n except KeyError as e:\n request.response.status = HTTPBadRequest.code\n return {'error': str(e)}\n\n except IntegrityError as e:\n request.response.status = HTTPInternalServerError.code\n return {'error': str(e)}\n\n@view_config(route_name='create_persp_to_field', renderer='json', request_method='POST', permission='edit') # todo: other permission?\ndef create_persp_to_field(request):\n try:\n variables = {'auth': request.authenticated_userid}\n\n req = request.json_body\n client = DBSession.query(Client).filter_by(id=variables['auth']).first()\n if not client:\n raise KeyError(\"Invalid client id (not registered on server). Try to logout and then login.\",\n variables['auth'])\n user = DBSession.query(User).filter_by(id=client.user_id).first()\n if not user:\n raise CommonException(\"This client id is orphaned. Try to logout and then login once more.\")\n if not DBSession.query(DictionaryPerspectiveToField).filter_by(client_id=req['client_id'], object_id=req['object_id']).first():\n field_object = DictionaryPerspectiveToField(client_id=req['client_id'],\n object_id=req['object_id'],\n parent_client_id=req['parent_client_id'],\n parent_object_id=req['parent_object_id'],\n field_client_id=req['field_client_id'],\n field_object_id=req['field_object_id'],\n self_client_id=req['self_client_id'],\n self_object_id=req['self_object_id'],\n position=req['position'])\n DBSession.add(field_object)\n\n return {}\n except KeyError as e:\n request.response.status = HTTPBadRequest.code\n return {'error': str(e)}\n\n except IntegrityError as e:\n request.response.status = HTTPInternalServerError.code\n return {'error': str(e)}\n\n except CommonException as e:\n request.response.status = HTTPConflict.code\n return {'error': str(e)}\n\n\nconn_err_msg = \"\"\"\\\nPyramid is having a problem using your SQL database. The problem\nmight be caused by one of the following things:\n\n1. You may need to run the \"initialize_lingvodoc_db\" script\n to initialize your database tables. Check your virtual\n environment's \"bin\" directory for this script and try to run it.\n\n2. Your database server may not be running. Check that the\n database server referred to by the \"sqlalchemy.url\" setting in\n your \"development.ini\" file is running.\n\nAfter you fix the problem, please restart the Pyramid application to\ntry it again.\n\"\"\"","sub_path":"lingvodoc/views/v2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"38347050","text":"import asyncio,json,logging\nimport aiohttp, sys, pytz, os\nfrom aiohttp import web\nfrom aiohttp_wsgi import WSGIHandler\nfrom aiohttp_session import get_session\nfrom flask import Flask, render_template, jsonify\nimport pydash \nfrom types import SimpleNamespace\nfrom ip2geotools.databases.noncommercial import DbIpCity\nfrom collections import OrderedDict\nfrom itertools import islice\nfrom pathlib import Path\n\nclass SlicableOrderedDict(OrderedDict):\n\tdef __getitem__(self, k):\n\t\tif not isinstance(k, slice):\n\t\t\treturn OrderedDict.__getitem__(self, k)\n\t\tx = SlicableOrderedDict()\n\t\tfor idx, key in enumerate(self.keys()):\n\t\t\tif k.start <= idx < k.stop:\n\t\t\t\tx[key] = self[key]\n\t\treturn x\n\nPATH = Path(__file__).resolve().parent\nASSET_PATH = os.path.join(PATH,'assets')\n\n\nSECRET = 'trowel-moral-freedom-able-chest-success-climate'\nINFO = {}\nLATENCY = {}\nSTATS = {}\nPENDING = {}\nIP_ADDR = {}\nBLOCKS=SlicableOrderedDict()\n\nMAX_BLOCKS_HISTORY = 10\nMAX_TRANSACTION_HISTORY = 100\nMAX_HISTORY_UPDATE = 50\nMAX_CONNECTION_ATTEMPTS = 50\nCONNECTION_ATTEMPTS_TIMEOUT = 1000\nQUORUM_COUNT=150\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.jinja_loader.searchpath.insert(0, '.')\n\nlog = logging.getLogger(__name__)\n\n@app.route('/')\ndef index():\n\treturn render_template('index.html')\n\nclass ClientSocket(web.View):\n\tasync def get(self):\n\t\tws = web.WebSocketResponse()\n\t\tawait ws.prepare(self.request)\n\t\tif (not 'websockets' in self.request.app.keys()):\n\t\t\tself.request.app['websockets']=[]\n\t\t\n\t\tself.request.app['websockets'].append(ws)\n\t\tawait send_history(ws)\n\t\tasync for msg in ws:\n\t\t\tif msg.tp == MsgType.text:\n\t\t\t\tif msg.data == 'close':\n\t\t\t\t\tawait ws.close()\n\t\t\t\telse:\n\t\t\t\t\tlog.debug(result)\n\t\t\telif msg.tp == MsgType.error:\n\t\t\t\tlog.debug('ws connection closed with exception %s' % ws.exception())\n\n\t\tself.request.app['websockets'].remove(ws)\n\t\tlog.debug('websocket connection closed')\n\n\t\treturn ws\n\nasync def send_history (ws):\n\t# this is the socket for the UI\n\tdata = {\n\t\t'emit':[ 'history', {\t\t\n\t\t\t'nodes':INFO,\n\t\t\t'latency': LATENCY,\n\t\t\t'stats': STATS,\n\t\t\t'pending': PENDING,\n\t\t\t'blocks': BLOCKS,\n\t\t\t'ip2geo':IP_ADDR\n\t\t}]\n\t} \n\tawait ws.send_str(json.dumps(data))\n\nasync def emit(_ws,topic,payload=None):\n\tif payload is None:\n\t\tmsg={ 'emit':[ topic ] }\n\telse:\n\t\tmsg={ 'emit':[ topic, payload] }\n\tif _ws is not None:\n\t\tif _ws._req is not None:\n\t\t\tif _ws._req.transport is not None:\n\t\t\t\tif not _ws._req.transport.is_closing():\n\t\t\t\t\tawait _ws.send_str(json.dumps(msg))\n\n\nasync def handle_hello(socket, payload):\n\tglobal INFO\n\tglobal IP_ADDR\n\tif payload['secret'] == SECRET:\n\t\tINFO[payload['id']]=payload['info']\n\t\tif payload['ip'][0:7] == '192.168':\n\t\t\tlat=0.0\n\t\t\tlongi=0.0\n\t\telse:\n\t\t\tlat=0.0\n\t\t\tlongi=0.0\n\t\tIP_ADDR[payload['id']]={\n\t\t\t'ip':payload['ip'],\n\t\t\t'geo': '{0},{1}'.format(lat,longi) \n\t\t}\n\t\tawait emit(socket,'ready')\n\telse:\n\t\tawait socket.close()\n\nasync def handle_node_ping(socket,payload):\n\tawait emit(socket,'node-pong',{\n\t\t'clientTime':payload['clientTime'],\n\t\t'serverTime':pydash.utilities.now()\n\t})\n\nasync def handle_latency(socket, payload):\n\tglobal LATENCY\n\tLATENCY[payload['id']]=payload['latency']\n\nasync def handle_history(socket, payload):\n\tprint(payload)\n\nasync def handle_stats(socket, payload):\n\tglobal STATS\n\tSTATS[payload['id']]=payload['stats']\n\nasync def handle_pending(socket, payload):\n\tglobal PENDING\n\tPENDING[payload['id']]=payload['stats']['pending']\n\nasync def handle_block(socket, payload):\n\tglobal BLOCKS\n\tBLOCKS.update({ payload['block']['hash'] : payload['block'] })\n\tBLOCKS.move_to_end(payload['block']['hash'],last=False)\n\tkeeper = 0\n\tif len(BLOCKS) > MAX_BLOCKS_HISTORY:\n\t\tBLOCKS=BLOCKS[0:MAX_BLOCKS_HISTORY-1]\n\nasync def handle_update(socket, payload):\n\tprint(payload)\n\nclass NodeSocket(web.View):\n\t\"\"\"\n\thello\n\t{'id': 'Testing', 'info': {'name': 'Testing', 'node': 'tao/Testing/v2.2.1-stable/linux-amd64/go1.12.17', 'port': 20202, 'net': '558', 'protocol': 'eth/63', 'api': 'No', 'os': 'linux', 'os_v': 'amd64', 'client': '0.1.1', 'canUpdateHistory': True}, 'secret': 'trowel-moral-freedom-able-chest-success-climate'}\n\tnode-ping\n\t{'clientTime': '2021-02-04 14:24:53.044383714 +0000 UTC m=+18476.440831755', 'id': 'Testing'}\n\tlatency\n\t{'id': 'Testing', 'latency': '1'}\n\tblock\n\t{'block': {'number': 3721676, 'hash': '0x1083cf440419f5a082d0e59530441f61a8715675e3adf5e43e910aee1fda6b13', 'parentHash': '0xeeea3669e9138f052d8763fcb612dca68597da502f5ff2db6fbfb8c9003cab94', 'timestamp': 1612448693, 'miner': '0x053b283836c9bc6f4bb1eec207337089cba8bdd6', 'gasUsed': 0, 'gasLimit': 84000000, 'difficulty': '19', 'totalDifficulty': '19672013', 'transactions': [{'hash': '0x89398aa948b8f8b18e767ed9bea957507973d31d4dffd82796a1bfe595b586f2'}], 'transactionsRoot': '0x43d84d2e02f5ade429f15ab140e4806a22b5863366d70858c1c0367209f8049a', 'stateRoot': '0x1e4e904ec924e359adb16dfedf37d8a7a071b660ba9965d6d187eb9a6c7df186', 'uncles': []}, 'id': 'Testing'}\n\tpending\n\t{'id': 'Testing', 'stats': {'pending': 0}}\n\tstats\n\t{'id': 'Testing', 'stats': {'active': True, 'syncing': True, 'mining': False, 'hashrate': 0, 'peers': 6, 'gasPrice': 250000000, 'uptime': 100}}\n\t\"\"\"\n\tasync def get(self):\n\t\tws = web.WebSocketResponse()\n\t\tawait ws.prepare(self.request)\n\t\t_id=''\n\n\t\ttry:\n\t\t\tif (not 'websockets' in self.request.app.keys()):\n\t\t\t\tself.request.app['websockets']=[]\n\t\t\tasync for msg in ws:\n\t\t\t\tif msg.type == aiohttp.WSMsgType.TEXT:\n\t\t\t\t\tser = json.loads(msg.data)\n\t\t\t\t\ttopic = ser['emit'][0]\n\t\t\t\t\tser['emit'][1]['ip'] = self.request.headers.get('X-Real-IP')\n\t\t\t\t\tpayload = ser['emit'][1]\n\t\t\t\t\t_id = payload['id']\n\t\t\t\t\tfor _ws in self.request.app['websockets']:\n\t\t\t\t\t\tif _ws is not None:\n\t\t\t\t\t\t\tif _ws._req is not None:\n\t\t\t\t\t\t\t\tif _ws._req.transport is not None:\n\t\t\t\t\t\t\t\t\tif not _ws._req.transport.is_closing():\n\t\t\t\t\t\t\t\t\t\tawait _ws.send_str(json.dumps(ser))\n\t\t\t\t\tfunction=getattr(sys.modules[__name__], 'handle_{0}'.format(topic.replace('-','_')))\n\t\t\t\t\tif topic == 'end':\n\t\t\t\t\t\tdel INFO[_id]\n\t\t\t\t\t\tdel LATENCY[_id]\n\t\t\t\t\t\tdel STATS[_id]\n\t\t\t\t\t\tdel PENDING[_id]\n\t\t\t\t\t\tdel IP_ADDR[_id]\n\t\t\t\t\t\tawait ws.close()\n\t\t\t\t\telse:\n\t\t\t\t\t\tawait function(ws,payload)\n\t\t\t\telif msg.type == aiohttp.WSMsgType.ERROR:\n\t\t\t\t\t# delete node \n\t\t\t\t\tprint('ws connection closed with exception %s' %\n\t\t\t\t\t\t ws.exception())\n\t\texcept ConnectionResetError:\n\t\t\tpass\n\t\tdel INFO[_id]\n\t\tdel LATENCY[_id]\n\t\tdel STATS[_id]\n\t\tdel PENDING[_id]\n\t\tdel IP_ADDR[_id]\n\t\tprint('connection closed')\n\n\t\treturn ws\n\nif __name__ == \"__main__\":\n\tloop = asyncio.get_event_loop()\n\taio_app = web.Application()\n\twsgi = WSGIHandler(app)\n\taio_app.router.add_route('*', '/{path_info: *}', wsgi.handle_request)\n\taio_app.router.add_routes([web.static('/assets', ASSET_PATH)])\n\taio_app.router.add_route('GET', '/socket',ClientSocket)\n\taio_app.router.add_route('GET', '/api', NodeSocket)\ntry:\n\tweb.run_app(aio_app, port=3000)\nexcept KeyboardInterrupt:\n\tlog.debug(' Stop server begin')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"447213265","text":"from bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport requests,threading\nfrom project.api import Api\nfrom project.db import Database\n\nclass Scrap():\n\n\tdef google_query(cls,query):\n\t\turl='https://www.google.com/en'\n\t\tdriver=webdriver.Firefox(executable_path=r'project/firefox_driver/geckodriver.exe')\n\t\ttry:\n\t\t\tdriver.get(url)\n\t\t\tinput_=driver.find_element_by_class_name('gLFyf')\n\t\t\tinput_.send_keys(query)\n\t\t\tbtn=driver.find_element_by_xpath('/html/body/div/div[3]/form/div[2]/div/div[3]/center/input[1]')\n\t\t\tbtn.click()\n\t\texcept Exception as err:\n\t\t\tprint(err)\n\n\n\n\tdef boi_rate(cls):\n\n\t\turl=['https://www.boi.org.il/en/Markets/ExchangeRates/Pages/Default.aspx']\n\t\tdriver=webdriver.Firefox(executable_path=r'project/firefox_driver/geckodriver.exe')\n\t\tfor x in url:\n\t\t\ttry:\n\t\t\t\tdriver.get(x)\n\t\t\t\tsoup=BeautifulSoup(driver.page_source,'lxml')\n\t\t\t\ttd=soup.find_all('td')\n\t\t\t\tlist_rate=[]\n\t\t\t\tfor z in td:\n\t\t\t\t\t#rate=z.find('td',{'data-wcag-dynamic-font':'true'}).text\n\t\t\t\t\tlist_rate.append(z.text)\n\t\t\t\tif len(list_rate)>1:\n\t\t\t\t\tDatabase().delete_from('rate')\n\t\t\t\t\td_rate=list_rate[8]\n\t\t\t\t\td_xrate=list_rate[9]\n\t\t\t\t\tp_rate=list_rate[14]\n\t\t\t\t\tp_xrate=list_rate[15]\n\t\t\t\t\ty_rate=list_rate[20]\n\t\t\t\t\ty_xrate=list_rate[21]\n\t\t\t\t\te_rate=list_rate[26]\n\t\t\t\t\te_xrate=list_rate[27]\n\t\t\t\t\tDatabase().insert_into('rate',d_rate,d_xrate,p_rate,p_xrate,y_rate,y_xrate,e_rate,e_xrate)\n\t\t\t\t\n\t\t\texcept Exception as err:\n\t\t\t\tprint(err)\n\t\t\tfinally:\n\t\t\t\tdriver.close()\n\n\tdef imdb_scrap(cls):\n\t\turl='https://www.imdb.com/?ref_=nv_home'\n\t\t#try:\n\t\tr=requests.get(url)\n\t\tif r.status_code==200:\n\t\t\tDatabase().delete_from('imdb_movie',None,None)\n\t\t\tsoup=BeautifulSoup(r.text,'lxml')\n\t\t\tlink=soup.find_all('div',class_='title')\n\t\t\tx=0\n\t\t\twhile x<3:\n\t\t\t\tfilm=(link[x].text)\n\t\t\t\tApi().imdb_api(film)\n\t\t\t\tx+=1\n\n\tdef youtube_scrap(cls):\n\t\t\n\t\turl=[\n\t\t\t\t'https://www.youtube.com/user/schafer5/videos',\n\t\t\t\t'https://www.youtube.com/user/TechGuyWeb/videos',\n\t\t\t\t'https://www.youtube.com/channel/UCnxGkOGNMqQEUMvroOWps6Q/videos'\n\t\t\t]\n\t\tDatabase().delete_from('yt_channels')\n\t\tfor z in url:\n\t\t\ttry:\n\t\t\t\tdriver=webdriver.Firefox(executable_path=r'project/firefox_driver/geckodriver.exe')\n\t\t\t\tdriver.get(z)\n\t\t\t\tsoup=BeautifulSoup(driver.page_source,'lxml')\n\t\t\t\tlink=soup.find_all('a',id='video-title')\n\t\t\t\n\t\t\t\tx=0\n\t\t\t\tyt_dict={'title':[],'views':[],'href':[]}\n\t\t\t\twhile x<len(link):\n\t\t\t\t\ttemp=link[x].get('aria-label')\n\t\t\t\t\tif temp!=None and temp!='':\n\t\t\t\t\t\tyt_dict['title'].append(temp.split('by')[0])\n\t\t\t\t\t\tyt_dict['views'].append(temp.split('by')[1])\n\t\t\t\t\thref=link[x].get('href')\n\t\t\t\t\tif href!=None and href!='':\n\t\t\t\t\t\thref=href.split('=')[1]\n\t\t\t\t\t\tyt_dict['href'].append(href)\n\t\t\t\t\tx+=1\n\t\t\t\n\t\t\t\tif yt_dict!=None:\n\t\t\t\t\ti=0\n\t\t\t\t\twhile i<5:\n\t\t\t\t\t\tDatabase().insert_into('yt_channels',None,yt_dict['title'][i],yt_dict['views'][i],yt_dict['href'][i],)\n\t\t\t\t\t\ti+=1\n\t\t\texcept Exception as err:\n\t\t\t\tprint(err)\n\t\t\tfinally:\n\t\t\t\tdriver.close()\n\n\tdef science_scrap(cls):\n\n\t\turl=['https://www.scientificamerican.com/']\n\t\tdriver=webdriver.Firefox(executable_path=r'project/firefox_driver/geckodriver.exe')\n\t\ttry:\n\t\t\tfor z in url:\n\t\t\t\tdriver.get(z)\n\t\t\t\tsoup=BeautifulSoup(driver.page_source,'lxml')\n\t\t\t\t#grid=soup.find('div',class_='listing-wide__thumb')\n\t\t\t\tgrid=soup.find_all('div',class_='grid__col large-up-1 medium-1-2')\n\t\t\t\th3=soup.find_all('div',class_='listing-wide__inner')\n\t\t\t\tp=soup.find_all('p',class_='t_body listing-wide__inner__desc')\n\t\t\t\tmeta=soup.find_all('div',class_='t_meta')\n\t\t\t\tscience_dict={'source':[],'img':[],'link':[],'title':[],'text':[],'meta':[]}\n\t\t\t\t\n\t\t\t\tfor x in grid:\n\t\t\t\t\tsource=x.find('source')['srcset']\n\t\t\t\t\timg=x.find('img')['src']\n\t\t\t\t\tscience_dict['source'].append(source)\n\t\t\t\t\tscience_dict['img'].append(img)\n\t\t\t\t\t\n\t\t\t\tfor x in h3:\n\t\t\t\t\tlink=x.find('a')['href']\n\t\t\t\t\ttitle=x.find('a').string\n\t\t\t\t\tscience_dict['link'].append(link)\n\t\t\t\t\tscience_dict['title'].append(title)\n\t\t\t\t\n\t\t\t\tfor x in p:\n\t\t\t\t\ttext=x.string\n\t\t\t\t\tscience_dict['text'].append(text)\n\t\t\t\t\n\n\t\t\t\tfor x in meta:\n\t\t\t\t\tmeta=x.string\n\t\t\t\t\tscience_dict['meta'].append(meta)\n\n\t\t\t\tif science_dict['source']!=None:\n\t\t\t\t\tDatabase().delete_from('science_news')\n\t\t\t\t\tx=0\n\t\t\t\t\twhile x<5:\n\t\t\t\t\t\tDatabase().insert_into('science_news',str(science_dict['source'][x]),str(science_dict['img'][x]),str(science_dict['link'][x]),str(science_dict['title'][x]),str(science_dict['text'][x]),str(science_dict['meta'][x]))\n\t\t\t\t\t\tx+=1\n\t\t\t\t\n\t\texcept Exception as err:\n\t\t\tprint(err)\n\t\tfinally:\n\t\t\tdriver.close()\n\n\tdef populer_machine(cls):\n\n\t\turl=['https://www.popularmechanics.com/']\n\t\tdriver=webdriver.Firefox(executable_path=r'project/firefox_driver/geckodriver.exe')\n\t\tfor z in url:\n\t\t\ttry:\n\t\t\t\tdriver.get(z)\n\t\t\t\tsoup=BeautifulSoup(driver.page_source,'lxml')\n\t\t\t\tlink_item=soup.find_all('div',class_='full-item')\n\t\t\t\tdict_items={'link':[],'img':[],'title':[],'content':[],'author':[]}\n\t\t\t\t\n\t\t\t\tfor x in link_item:\n\t\t\t\t\tlink=x.find('a',class_='full-item-image item-image')['href']\n\t\t\t\t\timg=x.find('span')['data-lqip']\n\t\t\t\t\timg=img.split('?')[0]\n\t\t\t\t\ttitle=x.find('a',class_='full-item-title item-title').string\n\t\t\t\t\tcontent=x.find('div',class_='full-item-dek item-dek').text\n\t\t\t\t\tauthor=x.find('span',class_='byline-name').string\n\t\t\t\t\t\n\t\t\t\t\tdict_items['link'].append(link)\n\t\t\t\t\tdict_items['img'].append(img)\n\t\t\t\t\tdict_items['title'].append(title)\n\t\t\t\t\tdict_items['content'].append(content)\n\t\t\t\t\tdict_items['author'].append(author)\n\n\t\t\t\tif dict_items['link']!=None:\n\t\t\t\t\tDatabase().delete_from('popluer_machine')\n\t\t\t\tz=0\n\t\t\t\twhile z<len(dict_items['link']):\n\t\t\t\t\tif z>1 and z<7:\n\t\t\t\t\t\tDatabase().insert_into('popluer_machine',str(dict_items['link'][z]),str(dict_items['img'][z]),str(dict_items['title'][z]),str(dict_items['content'][z]),str(dict_items['author'][z]))\n\t\t\t\t\tz+=1\n\t\t\t\t\n\t\t\texcept Exception as err:\n\t\t\t\tprint(err)\n\t\t\tfinally:\n\t\t\t\tdriver.close()\n\n","sub_path":"site_1/project/scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":5840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"112242151","text":"n,m,k = map(int, input().split())\nsl = []\nfor _ in range(n):\n s = list(map(int,input()))\n sl.append(s)\n\ncnts09 = []\nfor num in range(10):\n csums = [ [0]*(m+1) for _ in range(n+1)]\n for i in range(n):\n for j in range(m):\n v = 1 if sl[i][j] == num else 0\n csums[i+1][j+1] = csums[i+1][j] + csums[i][j+1] - csums[i][j] + v\n cnts09.append(csums)\n\nminnm = min(n,m)\nfor l in range(minnm,0,-1):\n for ys in range(n):\n for xs in range(m):\n yb = ys+l-1\n xb = xs+l-1\n if yb >= n: continue\n if xb >= m: continue\n max_cnt = 0\n for num in range(10):\n # print(num,yb,xb)\n cnt = cnts09[num][yb+1][xb+1] - cnts09[num][yb+1][xs] - cnts09[num][ys][xb+1] + cnts09[num][ys][xs]\n max_cnt = max(max_cnt,cnt)\n need = l*l-max_cnt\n if need <= k:\n print(l)\n exit()\n","sub_path":"2_kakomon/past/past4/past202010_h.py","file_name":"past202010_h.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"646802304","text":"from flask import render_template, request\nfrom flask import Flask\nfrom flask import jsonify\nimport read_audio\nimport os\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/query', methods=['POST', 'GET'])\ndef get():\n user_name = request.form.get('userName')\n return render_template('base.html', username=user_name)\n\n\n@app.route('/response', methods=['POST'])\ndef process_response():\n request.get_data()\n data = request.data\n print(data.decode('utf-8'))\n res = read_audio.text_to_speech(data.decode('utf-8'))\n return jsonify({\"data\": res})\n\n\nif __name__ == \"__main__\":\n os.environ['FLASK_ENV'] = 'development'\n os.environ['FLASK_DEBUG'] = \"1\"\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"88145270","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.Index.as_view(), name=\"index\"),\n url(r'^algos/$', views.AlgoList.as_view(), name=\"algo-list\"),\n\n url(r'^algo/(?P<pk>\\d+)/(?P<revision>\\d+)', views.AlgoDetail.as_view(), name=\"algo-detail\"), # pk: Algo, revision: AlgoVersion\n url(r'^algo/(?P<pk>\\d+)', views.AlgoDetail.as_view(), name=\"algo-detail\"), # pk: Algo\n url(r'^algo/add/', views.AlgoCreate.as_view(), name=\"algo-create\"),\n url(r'^algo/edit/(?P<pk>\\d+)', views.AlgoEdit.as_view(), name=\"algo-edit\"), # pk: AlgoVersion\n url(r'^algo/history/(?P<pk>\\d+)', views.AlgoHistory.as_view(), name=\"algo-history\"), # pk: Algo\n\n url(r'^category/(?P<pk>\\d+)', views.CategoryDetail.as_view(), name=\"category-detail\"),\n url(r'^categories/', views.CategoryList.as_view(), name=\"category-list\"),\n\n url(r'^implementation/(?P<pk>\\d+)', views.ImplementationDetail.as_view(), name=\"implementation-detail\"),\n url(r'^implementation/add/(?P<algo>\\d+)', views.ImplementationCreate.as_view(), name=\"implementation-create\"),\n url(r'^implementation/diff/(?P<pk1>\\d+)/(?P<pk2>\\d+)', views.ImplementationDiff.as_view(), name=\"implementation-diff\"),\n url(r'^implementation/edit/(?P<pk>\\d+)', views.ImplementationEdit.as_view(), name='implementation-edit'),\n\n url(r'^user/profile/', views.UserProfile.as_view(), name='user-profile'),\n url(r'^user/notebook/$', views.NotebookParams.as_view(), name='user-notebook'),\n url(r'^user/notebook/(?P<format>pdf|tex)/', views.NotebookGen.as_view(), name='user-notebook-gen'),\n\n url(r'^ajax/implementation/(?P<pk>\\d+)', views.ImplementationDetailAjax.as_view()),\n url(r'^ajax/star/(?P<action>add|remove)/(?P<pk>\\d+)', views.StarAjax.as_view()),\n url(r'^star/(?P<action>add|remove)/(?P<pk>\\d+)', views.StarRedirect.as_view(), name='star-redirect'),\n]\n","sub_path":"web/algopedia/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"646844817","text":"import sys\n\nfrom emoji import emojize as em\nfrom telegram.ext import Updater, CallbackQueryHandler\n\nfrom Utils import Provider\nfrom Utils import kbf, mkbf, emoji_number\n\n\nclass KeyboardTests:\n def __init__(self, token):\n self.kb = None\n self.token = token\n self.updater = Updater(self.token)\n self.t_id = 193019697\n\n def callback_test(self, bot, update):\n Provider.process(bot, update, (self,))\n return True\n\n def to_page_callback(self, bot, update, page):\n update.effective_message.edit_text(text=update.effective_message.text + \"+1\",\n reply_markup=self.kb.to_markup(int(page)))\n\n def multi_page_test(self):\n self.updater.dispatcher.add_handler(CallbackQueryHandler(self.callback_test))\n self.kb = kbf.double_button(\"Button1\", \"Button\", \"Button1\", \"Button\") + \\\n kbf.button(text=\"Button2\", callback_data=\"Button\") + \\\n kbf.double_button(\"Button3\", \"Button\", \"Button3\", \"Button\") + \\\n kbf.button(text=\"Button4\", callback_data=\"Button\") + \\\n kbf.double_button(\"Button5\", \"Button\", \"Button5\", \"Button\") + \\\n kbf.button(text=\"Button6\", callback_data=\"Button\")\n\n self.kb = mkbf(self.kb, 2, kbf.button(\"Закончить\", \"end\"))\n\n self.updater.bot.send_message(chat_id=self.t_id, text=\"Test\", reply_markup=self.kb.to_markup(0))\n\n def callback_player(self, bot, update, id):\n pass\n\n def callback_action(self, bot, update, id):\n return True\n\n def game_view_test(self):\n kb = kbf.empty()\n self.updater.bot.send_message(chat_id=self.t_id, text=f\"🗡 Убивали игрока 1️⃣\\n\"\n f\"Будет ли использована \"\n f\"{em(':flower_playing_cards:')} карта лечение?\",\n reply_markup=kbf.confirmation(self.callback_action, self.callback_action))\n self.updater.bot.send_message(chat_id=self.t_id, text=f\"Игрок 1️⃣ есть ли у вас\"\n f\"{em(':flower_playing_cards:')}карта Бронижилет?\",\n reply_markup=kbf.confirmation(self.callback_action, self.callback_action))\n warning_button = (\":warning:\", self.callback_action)\n warning_button2 = (\":warning: 2\", self.callback_action)\n warning_button3 = (\"👺\", self.callback_action)\n voting_button = (\":white_circle:\", self.callback_action)\n no_voting_button = (\":red_circle:\", self.callback_action)\n card_button = (':flower_playing_cards:', self.callback_player)\n no_card_button = ('🚬', self.callback_player)\n clock_button = (\":sound:\", self.callback_action)\n no_clock_button = (\":mute:\", self.callback_action)\n\n for i in range(2, 11):\n role = '🕵🏼' if i in [2, 5, 8] else '👨🏼‍💼'\n role = role if i != 4 else '👮🏼'\n kb += kbf.action_line((str(emoji_number(i)) + role, self.callback_player, 123),\n warning_button if i not in [4, 9] else (\n warning_button2 if i != 4 else warning_button3),\n voting_button if i not in [3, 7] else no_voting_button,\n card_button if i not in [8, 2, 1] else no_card_button,\n clock_button if i >= 6 else no_clock_button)\n\n self.updater.bot.send_message(chat_id=self.t_id,\n text=f\"День №1\\n\"\n f\"🗡 Убили игрока 1️⃣\\n\"\n f\"{em(':cop:')} Коммисар попал\\n\"\n f\"{em(':flower_playing_cards:')} Прослушки не было\\n\"\n f\"{'🔪'*4} Меню Игры {'🔪'*4}\"\n f\"Выставлены игроки под номерами 3️⃣, 7️⃣\",\n reply_markup=kb)\n\n kb = kbf.action_line((\"⏸\", self.callback_action, 1),\n (em(\":arrow_forward:\"), self.callback_action),\n (\"⏹\", self.callback_action))\n self.updater.bot.send_message(chat_id=self.t_id,\n text=f\"Минута игрока номер 6️⃣\\nОсталось 40 секунд {em(':alarm_clock:')}\",\n reply_markup=kb)\n kb = kbf.empty()\n man_with_hand = \"🙋🏻‍♂️\"\n man_without_hand = \"🙅🏽‍♂️\"\n for i in range(0, 10):\n kb += kbf.button(f\"{emoji_number(i)} {man_with_hand*2} {man_without_hand*2} {emoji_number(i)}\", self.callback_action, 2)\n\n self.updater.bot.send_message(chat_id=self.t_id,\n text=f\"На голосование выставлены игроки под номерами 3️⃣, 7️⃣\")\n self.updater.bot.send_message(chat_id=self.t_id,\n text=\"Кто голосует за игрока номер 3️⃣\",\n reply_markup=kb)\n self.updater.start_polling()\n self.updater.idle()\n\n\nif __name__ == \"__main__\":\n test = KeyboardTests(sys.argv[1])\n test.multi_page_test()\n test.game_view_test()\n","sub_path":"Tests/KeyboardTests.py","file_name":"KeyboardTests.py","file_ext":"py","file_size_in_byte":5742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"251089033","text":"import turtle\n\nturtle.ht()\nturtle.speed(0)\nturtle.shape(\"square\")\nturtle.penup()\nturtle.setposition(turtle.window_width() *-.5, turtle.window_height() * .5)\nturtle.pendown()\n\ndef drawSquare(size, color):\n turtle.color(color)\n turtle.fillcolor(color)\n turtle.pen(fillcolor=color, pencolor=color, pensize=0)\n turtle.begin_fill()\n turtle.forward(size)\n turtle.left(90)\n turtle.forward(size)\n turtle.left(90)\n turtle.forward(size)\n turtle.left(90)\n turtle.forward(size)\n turtle.left(90)\n turtle.end_fill()\n\nj = 0\nwhile (j < 9):\n turtle.pendown()\n i = 0\n while (i < 4):\n if j % 2 == 0:\n color1 = \"red\"\n color2 = \"black\"\n if j % 2 == 1:\n color1 = \"black\"\n color2 = \"red\"\n drawSquare(turtle.window_height()/8, color1)\n turtle.forward(turtle.window_height()/8)\n drawSquare(turtle.window_height()/8, color2)\n turtle.forward(turtle.window_height()/8)\n i += 1\n turtle.penup()\n turtle.setposition(turtle.window_width() *-.5, turtle.window_height() * .5)\n turtle.right(90)\n turtle.forward(turtle.window_height()/8 * (j + 1))\n turtle.left(90)\n j += 1\n","sub_path":"lab4p4.py","file_name":"lab4p4.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"374538125","text":"import xlwt\nfrom xlwt import Workbook\nimport xlrd\n\nwb = Workbook()\nloc = \"C:/Users/SHANMUKHI/Dropbox/Shanmukhi Ayush 2020/Data/Demand, Capacity, Distances/Distances between stores/Bihar/SVS-RVS.xlsx\"\nworkbook = xlrd.open_workbook(loc) \nsheet = workbook.sheet_by_index(0)\n\nsheet1 = wb.add_sheet('Distances')\nsheet1.write(0,0,'s')\nsheet1.write(0,1,'r')\nsheet1.write(0,2,'Distance')\n\ns = 1\nr = 9\n\nrow = 1\nfor S in range(1,s+1):\n\tfor R in range(1,r+1):\n\t\tsheet1.write(row,0,S)\n\t\tsheet1.write(row,1,R)\n\t\tsheet1.write(row,2,sheet.cell_value(1,R))\n\t\trow = row + 1\n\nwb.save(\"C:/Users/SHANMUKHI/Dropbox/Shanmukhi Ayush 2020/Data/Demand, Capacity, Distances/Distances between stores/Bihar/distances_sr.xls\")\n#wb.save(\"C:/Users/Shanmukhi/Desktop/test3.xlsx\")","sub_path":"Others/distances_sr.py","file_name":"distances_sr.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"203784202","text":"try:\r\n\tfrom PyQt5.QtGui import *\r\n\tfrom PyQt5.QtWidgets import *\r\n\tfrom PyQt5.QtPrintSupport import *\r\n\tfrom PyQt5.QtCore import *\r\n\tfrom PyQt5.QtSql import *\r\nexcept:\r\n\tfrom PyQt4.QtGui import *\r\n\tfrom PyQt4.QtCore import *\r\n\tfrom PyQt4.QtSql import *\r\n\r\nfrom newLoanItemDialog import *\r\n\r\nimport sys\r\n\r\nclass ManageLoansWidget(QWidget):\r\n\t\"\"\"Docstring for ManageLoans\"\"\"\r\n\tdef __init__(self, parent):\r\n\t\tsuper().__init__()\r\n\r\n\t\tself.parent = parent\r\n\r\n\t\tself.connection = None\r\n\r\n\t\tself.LoansTableModel = QSqlQueryModel()\r\n\t\tself.LoanItemsTableModel = QSqlQueryModel()\r\n\t\tself.ItemModel = QSqlQueryModel()\r\n\r\n\t\tself.printer = QPrinter()\r\n\t\tself.printer.setPageSize(QPrinter.Letter)\r\n\r\n\t\tself.mainLayout = QHBoxLayout()\r\n\r\n\t\tself.leftWidget = QWidget()\r\n\t\t\r\n\t\tself.leftTopWidget = QWidget()\r\n\t\tself.leftBottomWidget = QWidget()\r\n\r\n\t\tself.leftLayout = QVBoxLayout()\r\n\t\tself.leftLayout.addWidget(self.leftTopWidget)\r\n\t\tself.leftLayout.addWidget(self.leftBottomWidget)\r\n\r\n\t\tself.leftWidget.setLayout(self.leftLayout)\r\n\r\n\t\tself.leftTopWidgetLayout = self.displayLoansLayout()\r\n\t\tself.leftTopWidget.setLayout(self.leftTopWidgetLayout)\r\n\r\n\t\tself.rightWidget = QWidget()\r\n\r\n\t\tself.rightLayout = self.searchItem()\r\n\t\tself.rightWidget.setLayout(self.rightLayout)\r\n\r\n\t\tself.mainLayout.addWidget(self.leftWidget)\r\n\t\tself.mainLayout.addWidget(self.rightWidget)\r\n\r\n\t\tself.setLayout(self.mainLayout)\r\n\r\n\tdef displayLoansLayout(self):\r\n\t\tself.manageLoansHeading = QLabel(\"Manage Loans\")\r\n\t\tself.manageLoansHeading.setAlignment(Qt.AlignCenter)\r\n\t\tself.manageLoansHeading.setStyleSheet(\"font-size:20px\")\r\n\r\n\t\tself.backButton = QPushButton(\"<- Back\")\r\n\t\tself.newLoanButton = QPushButton(\"New Loan\")\r\n\r\n\t\tself.topButtonsLayout = QHBoxLayout()\r\n\t\tself.topButtonsLayout.addWidget(self.backButton)\r\n\t\tself.topButtonsLayout.addWidget(self.manageLoansHeading)\r\n\t\tself.topButtonsLayout.addWidget(self.newLoanButton)\r\n\t\tself.topButtonsLayout.setAlignment(self.backButton, Qt.AlignLeft)\r\n\t\tself.topButtonsLayout.setAlignment(self.manageLoansHeading, Qt.AlignCenter)\r\n\t\tself.topButtonsLayout.setAlignment(self.newLoanButton, Qt.AlignRight)\r\n\r\n\t\tself.topButtonsWidget = QWidget()\r\n\t\tself.topButtonsWidget.setLayout(self.topButtonsLayout)\r\n\r\n\t\tself.searchEdit = QLineEdit()\r\n\t\tself.searchButton = QPushButton(\"Search\")\r\n\r\n\t\tself.searchLayout = QHBoxLayout()\r\n\t\tself.searchLayout.addWidget(self.searchEdit)\r\n\t\tself.searchLayout.addWidget(self.searchButton)\r\n\r\n\t\tself.searchGroup = QGroupBox(\"Search Loans\")\r\n\t\tself.searchGroup.setLayout(self.searchLayout)\r\n\r\n\r\n\r\n\t\tself.LoansTable = QTableView()\r\n\t\tself.LoansTable.setSelectionBehavior(QAbstractItemView.SelectRows)\r\n\r\n\t\tself.showAllLoansButton = QPushButton(\"Show All Loans\")\r\n\r\n\t\tself.exportButton = QPushButton(\"Export\")\r\n\t\tself.exportButton.setShortcut('Ctrl+E')\r\n\t\tself.exportButton.setAutoDefault(False)\r\n\t\tself.exportButton.setDefault(False)\r\n\t\tself.exportButton.setEnabled(False)\r\n\t\tself.parent.Print.setEnabled(False)\r\n\r\n\t\tself.deleteButton = QPushButton(\"Delete\")\r\n\t\tself.deleteButton.setAutoDefault(False)\r\n\t\tself.deleteButton.setDefault(False)\r\n\t\tself.deleteButton.setEnabled(False)\r\n\r\n\t\tself.buttonsLayout = QHBoxLayout()\r\n\t\tself.buttonsLayout.addWidget(self.showAllLoansButton)\r\n\t\tself.buttonsLayout.addWidget(self.exportButton)\r\n\t\tself.buttonsLayout.addWidget(self.deleteButton)\r\n\r\n\t\tself.buttonsWidget = QWidget()\r\n\t\tself.buttonsWidget.setLayout(self.buttonsLayout)\r\n\r\n\t\tself.loansLayout = QVBoxLayout()\r\n\t\tself.loansLayout.addWidget(self.LoansTable)\r\n\t\tself.loansLayout.addWidget(self.buttonsWidget)\r\n\r\n\t\tself.manageLoansGroup = QGroupBox(\"Loans\")\r\n\t\tself.manageLoansGroup.setLayout(self.loansLayout)\r\n\r\n\r\n\r\n\t\tself.LoanItemsTable = QTableView()\r\n\t\tself.LoanItemsTable.setSelectionBehavior(QAbstractItemView.SelectRows)\r\n\r\n\t\tself.addLoanItemButton = QPushButton(\"Add Item\")\r\n\t\tself.addLoanItemButton.setEnabled(False)\r\n\t\tself.addLoanItemButton.setDefault(False)\r\n\t\tself.addLoanItemButton.setAutoDefault(False)\r\n\r\n\t\tself.deleteLoanItemButton = QPushButton(\"Delete Item\")\r\n\t\tself.deleteLoanItemButton.setEnabled(False)\r\n\t\tself.deleteLoanItemButton.setDefault(False)\r\n\t\tself.deleteLoanItemButton.setAutoDefault(False)\r\n\r\n\t\tself.loanItemsLayout = QVBoxLayout()\r\n\t\tself.loanItemsLayout.addWidget(self.addLoanItemButton)\r\n\t\tself.loanItemsLayout.setAlignment(self.addLoanItemButton, Qt.AlignLeft)\r\n\r\n\t\tself.loanItemsLayout.addWidget(self.LoanItemsTable)\r\n\r\n\t\tself.loanItemsLayout.addWidget(self.deleteLoanItemButton)\r\n\t\tself.loanItemsLayout.setAlignment(self.deleteLoanItemButton, Qt.AlignRight)\r\n\r\n\t\tself.manageLoanItemsGroup = QGroupBox(\"Loan Items\")\r\n\t\tself.manageLoanItemsGroup.setLayout(self.loanItemsLayout)\r\n\r\n\t\tself.layout = QVBoxLayout()\r\n\t\tself.layout.addWidget(self.topButtonsWidget)\r\n\t\tself.layout.addWidget(self.searchGroup)\r\n\t\tself.layout.addWidget(self.manageLoansGroup)\r\n\t\tself.layout.addWidget(self.manageLoanItemsGroup)\r\n\r\n\t\treturn self.layout\r\n\r\n\tdef searchItem(self):\r\n\t\tif hasattr(self, 'rightWidget'):\r\n\t\t\tself.rightWidget.close()\r\n\t\t\tself.rightWidget = QWidget()\r\n\t\t\tself.rightWidget.setFixedWidth(400)\r\n\t\t\t\r\n\t\tself.searchItemsGroup = QGroupBox(\"Search Items:\")\r\n\t\tself.searchField = QLineEdit()\r\n\t\tself.searchButton = QPushButton(\"Search\")\r\n\t\tself.searchButton.setAutoDefault(True)\r\n\t\tself.searchButton.setDefault(True)\r\n\r\n\t\tself.searchLayout = QHBoxLayout()\r\n\t\tself.searchLayout.addWidget(self.searchField)\r\n\t\tself.searchLayout.addWidget(self.searchButton)\r\n\r\n\t\tself.searchItemsGroup.setLayout(self.searchLayout)\r\n\r\n\t\tself.manageItemsLayout = QVBoxLayout()\r\n\t\tself.manageItemsLayout.addWidget(self.searchItemsGroup)\r\n\r\n\t\tself.searchWidget = QWidget()\r\n\t\tself.searchWidget.setLayout(self.manageItemsLayout)\r\n\r\n\t\tself.tableGroup = QGroupBox(\"Items\")\r\n\r\n\t\tself.tableView = QTableView()\r\n\t\tself.tableView.setMaximumWidth(430)\r\n\r\n\t\theader = QHeaderView(Qt.Horizontal, self.tableView)\r\n\t\theader.setStretchLastSection(True)\r\n\r\n\t\tself.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)\r\n\r\n\t\tself.showAllItemsButton = QPushButton(\"Show All Items\")\r\n\t\tself.showAllItemsButton.setMaximumWidth(130)\r\n\r\n\t\tself.addItemButton = QPushButton(\"+\")\r\n\t\tself.addItemButton.setFixedWidth(30)\r\n\t\tself.addItemButton.setFixedHeight(30)\r\n\r\n\t\tself.addItemButton.setEnabled(False)\r\n\r\n\t\tself.buttonsLayout = QHBoxLayout()\r\n\t\tself.buttonsLayout.addWidget(self.showAllItemsButton)\r\n\t\tself.buttonsLayout.addWidget(self.addItemButton)\r\n\t\tself.buttonsLayout.setAlignment(self.addItemButton, Qt.AlignRight)\r\n\r\n\t\tself.buttonsWidget = QWidget()\r\n\t\tself.buttonsWidget.setLayout(self.buttonsLayout)\r\n\r\n\t\tself.viewItemsLayout = QVBoxLayout()\r\n\t\tself.viewItemsLayout.addWidget(self.buttonsWidget)\r\n\t\tself.viewItemsLayout.addWidget(self.tableView)\r\n\t\t\r\n\t\tself.tableGroup.setLayout(self.viewItemsLayout)\r\n\r\n\t\tself.groupLayout = QVBoxLayout()\r\n\t\tself.groupLayout.addWidget(self.tableGroup)\r\n\r\n\t\tself.groupWidget = QWidget()\r\n\t\tself.groupWidget.setLayout(self.groupLayout)\r\n\r\n\r\n\t\tself.cancelAddItemButton = QPushButton(\"Cancel\")\r\n\t\tself.cancelAddItemButton.setShortcut('Esc')\r\n\t\tself.cancelAddItemButton.setAutoDefault(True)\r\n\t\tself.cancelAddItemButton.setDefault(True)\r\n\t\tself.cancelAddItemButton.setEnabled(True)\r\n\r\n\t\tself.buttonsLayout = QHBoxLayout()\r\n\t\tself.buttonsLayout.addWidget(self.cancelAddItemButton)\r\n\t\tself.buttonsLayout.setAlignment(self.cancelAddItemButton, Qt.AlignLeft)\r\n\r\n\t\tself.buttonsWidget = QWidget()\r\n\t\tself.buttonsWidget.setLayout(self.buttonsLayout)\r\n\r\n\t\tself.loanItemLayout = QVBoxLayout()\r\n\t\tself.loanItemLayout.addWidget(self.searchWidget)\r\n\t\tself.loanItemLayout.addWidget(self.groupWidget)\r\n\t\tself.loanItemLayout.addWidget(self.buttonsWidget)\r\n\r\n\t\treturn self.loanItemLayout\r\n\r\n\tdef switchToAddItem(self):\r\n\t\tself.leftWidget.setEnabled(False)\r\n\t\tself.rightWidget.setEnabled(True)\r\n\r\n\t\tself.showAllItemsInTable()\r\n\r\n\tdef addLoanItem(self):\r\n\t\tselectedRow = self.tableView.selectionModel().selectedRows()\r\n\t\tItemID = int(selectedRow[0].data())\r\n\r\n\t\titemData = self.connection.getItemDataForLoan(ItemID)\r\n\r\n\t\titemID = int(itemData[0])\r\n\r\n\t\tself.itemName = str(itemData[1])\r\n\r\n\t\tloanItemData = {\"LoanID\": self.LoanID,\r\n\t\t\t\t\t\t\"ItemID\": itemID}\r\n\r\n\t\tself.addItemToTable(loanItemData)\r\n\t\tself.tableView.selectionModel().clearSelection()\r\n\r\n\tdef searchDatabase(self):\r\n\t\tqueryText = self.searchField.text()\r\n\r\n\t\tquery = self.connection.getItemSearchQuery(queryText)\r\n\r\n\t\tself.showResults(query)\r\n\r\n\tdef showAllItemsInTable(self):\r\n\t\tself.searchField.clear()\r\n\r\n\t\titems = self.connection.getAllItemsForLoan()\r\n\r\n\t\tself.showResults(items)\r\n\r\n\tdef searchingItems(self):\r\n\t\tself.tableView.selectionModel().clearSelection()\r\n\t\t\r\n\t\tself.searchItemsGroup.setEnabled(True)\r\n\t\tself.tableGroup.setEnabled(True)\r\n\r\n\tdef showResults(self, query):\r\n\t\tself.ItemModel.setQuery(query)\r\n\t\t\r\n\t\tself.tableView.setModel(self.ItemModel)\r\n\t\tself.tableView.setSortingEnabled(True)\r\n\t\tself.tableView.show()\r\n\t\tself.tableView.selectionModel().selectionChanged.connect(self.enableAddItemButton)\r\n\r\n\tdef enableAddItemButton(self):\r\n\t\tself.addItemButton.setEnabled(True)\r\n\r\n\tdef cancelAddItem(self):\r\n\t\tself.leftWidget.setEnabled(True)\r\n\t\tself.rightWidget.setEnabled(False)\r\n\r\n\t\tself.ItemModel.clear()\r\n\r\n\t\tself.tableView.setModel(self.ItemModel)\r\n\t\tself.tableView.show()\r\n\r\n\r\n\r\n\r\n\tdef addItemToTable(self, data):\r\n\t\tloanItem = self.connection.addLoanItem(data)\r\n\r\n\t\tif loanItem:\r\n\t\t\tself.parent.toolBar.setEnabled(False)\r\n\t\t\tself.parent.menubar.setEnabled(False)\r\n\t\t\ttext = \"The Item {0} was successfully added!\".format(self.itemName)\r\n\t\t\tQMessageBox.information(self, \"Item Added\", text)\r\n\t\t\tself.exportButton.setEnabled(True)\r\n\t\t\tself.parent.Print.setEnabled(True)\r\n\t\t\tself.confirmButton.setEnabled(True)\r\n\t\t\tself.addItemButton.setEnabled(False)\r\n\t\t\tself.updateLoanItemTable()\r\n\t\telse:\r\n\t\t\tQMessageBox.information(self, \"Item Not Added\", self.connection.error)\r\n\r\n\tdef addConnection(self, connection):\r\n\t\tself.connection = connection\r\n\t\tself.connections()\r\n\t\treturn True\r\n\r\n\r\n\tdef showAllLoansInTable(self):\r\n\t\tloans = self.connection.getAllLoans()\r\n\r\n\t\tself.showLoanResults(loans)\r\n\r\n\tdef showLoanResults(self, loans):\r\n\t\tself.LoansTableModel.setQuery(loans)\r\n\t\t\r\n\t\tself.LoansTable.setModel(self.LoansTableModel)\r\n\t\tself.LoansTable.setSortingEnabled(True)\r\n\t\tself.LoansTable.show()\r\n\r\n\t\tself.LoansTable.selectionModel().selectionChanged.connect(self.selectLoan)\r\n\r\n\tdef selectLoan(self):\r\n\t\tselectedRow = self.LoansTable.selectionModel().selectedRows()\r\n\t\tLoanID = int(selectedRow[0].data())\r\n\r\n\t\tself.LoanID = LoanID\r\n\r\n\t\tself.addLoanItemButton.setEnabled(True)\r\n\t\tself.deleteButton.setEnabled(True)\r\n\t\tself.exportButton.setEnabled(True)\r\n\t\tself.parent.Print.setEnabled(True)\r\n\r\n\r\n\t\tself.showLoanItemsForLoan(LoanID)\r\n\r\n\r\n\tdef getCustomer(self, customerID):\r\n\t\tcustomer = self.connection.getCustomerDataForInvoice(customerID)\r\n\r\n\t\treturn customer\r\n\r\n\tdef getLoan(self, LoanID):\r\n\t\tloan = self.connection.getLoanforExport(LoanID)\r\n\r\n\t\treturn loan\r\n\r\n\tdef getLoanItems(self, LoanID):\r\n\t\tloanItemsList = self.connection.getLoanItemsForInvoice(LoanID)\r\n\r\n\t\treturn loanItemsList\r\n\r\n\tdef exportLoan(self):\r\n\t\tselectedRow = self.LoansTable.selectionModel().selectedRows()\r\n\t\tLoanID = int(selectedRow[0].data())\r\n\r\n\t\tloan = self.getLoan(LoanID)\r\n\r\n\t\tcustomerID = loan[0]\r\n\r\n\t\tStartDate = str(loan[1])\r\n\r\n\t\tloanLength = loan[2]\r\n\r\n\t\tcustomer = self.getCustomer(customerID)\r\n\r\n\t\tloanItems = self.getLoanItems(LoanID)\r\n\r\n\t\thtml = self.createHtml(customer, StartDate, LoanID, loanItems, loanLength)\r\n\r\n\t\tdialog = QPrintDialog(self.printer, self)\r\n\t\tif dialog.exec_():\r\n\t\t\tdocument = QTextDocument()\r\n\t\t\tdocument.setMetaInformation(0,\"Invoice\")\r\n\t\t\tdocument.setHtml(html)\r\n\t\t\tdocument.print_(self.printer)\r\n\t\telse:\r\n\t\t\ttext = \"The print process has failed!\"\r\n\t\t\tQMessageBox.information(self, \"Printing Failed\", text)\r\n\r\n\tdef warningDialog(self):\r\n\t\tself.ErrorDialog = QMessageBox()\r\n\t\tself.ErrorDialog.setFixedHeight(400)\r\n\t\tself.ErrorDialog.setMaximumWidth(200)\r\n\t\tself.ErrorDialog.setWindowTitle(\"Database Warning\")\r\n\t\tself.ErrorDialog.setText(\"WARNING! You are about to delete a record from the database. \\n \\n\"\r\n\t\t\t\t\t\t\t\t\t\t\t\"This action CANNOT be undone!\")\r\n\t\tself.ErrorDialog.setIcon(QMessageBox.Warning)\r\n\t\tself.cancelButton = self.ErrorDialog.addButton(self.tr(\"Cancel\"), QMessageBox.RejectRole)\r\n\t\tself.okayButton = self.ErrorDialog.addButton(self.tr(\"Okay\"), QMessageBox.AcceptRole)\r\n\t\tself.ErrorDialog.setEscapeButton(self.cancelButton)\r\n\t\tself.ErrorDialog.setDefaultButton(self.cancelButton)\r\n\t\tself.okayButton.clicked.connect(self.deleteLoan)\r\n\t\tself.ErrorDialog.exec_()\r\n\r\n\tdef deleteLoan(self):\r\n\t\tselectedRow = self.LoansTable.selectionModel().selectedRows()\r\n\t\tindex = int(selectedRow[0].data())\r\n\r\n\t\tloanDeleted = self.connection.deleteLoan(index)\r\n\r\n\t\tif loanDeleted:\r\n\t\t\ttext = \"The Loan was successfully deleted!\".format()\r\n\t\t\tQMessageBox.information(self, \"Loan Deleted\", text)\r\n\r\n\t\t\tself.LoansTable.selectionModel().clearSelection()\r\n\t\t\tself.deleteButton.setEnabled(False)\r\n\r\n\t\t\tself.showAllLoansInTable()\r\n\t\t\tself.clearLoanItemsTable()\r\n\t\telse:\r\n\t\t\ttext = \"{0}\".format(self.connection.error)\r\n\t\t\tQMessageBox.information(self, \"Database Error!\", text)\r\n\r\n\tdef showLoanItemsForLoan(self, ID):\r\n\t\tLoanItems = self.connection.getLoanItems(ID)\r\n\r\n\t\tself.LoanItemsTableModel.setQuery(LoanItems)\r\n\r\n\t\tself.LoanItemsTable.setModel(self.LoanItemsTableModel)\r\n\t\tself.LoanItemsTable.setSortingEnabled(True)\r\n\t\tself.LoanItemsTable.show()\r\n\r\n\t\tself.LoanItemsTable.selectionModel().selectionChanged.connect(self.enableDeleteLoanItem)\r\n\t\t\r\n\r\n\tdef clearLoanItemsTable(self):\r\n\t\tself.LoanItemsTableModel.clear()\r\n\r\n\t\tself.LoanItemsTable.setModel(self.LoanItemsTableModel)\r\n\t\tself.LoanItemsTable.setSortingEnabled(True)\r\n\t\tself.LoanItemsTable.show()\r\n\r\n\t\tself.deleteLoanItemButton.setEnabled(False)\r\n\r\n\r\n\tdef enableDeleteLoanItem(self):\r\n\t\tself.deleteLoanItemButton.setEnabled(True)\r\n\r\n\tdef loanItemWarningDialog(self):\r\n\t\tself.ErrorDialog = QMessageBox()\r\n\t\tself.ErrorDialog.setFixedHeight(400)\r\n\t\tself.ErrorDialog.setMaximumWidth(200)\r\n\t\tself.ErrorDialog.setWindowTitle(\"Database Warning\")\r\n\t\tself.ErrorDialog.setText(\"WARNING! You are about to delete a record from the database. \\n \\n\"\r\n\t\t\t\t\t\t\t\t\t\t\t\"This action CANNOT be undone!\")\r\n\t\tself.ErrorDialog.setIcon(QMessageBox.Warning)\r\n\t\tself.cancelButton = self.ErrorDialog.addButton(self.tr(\"Cancel\"), QMessageBox.RejectRole)\r\n\t\tself.okayButton = self.ErrorDialog.addButton(self.tr(\"Okay\"), QMessageBox.AcceptRole)\r\n\t\tself.ErrorDialog.setEscapeButton(self.cancelButton)\r\n\t\tself.ErrorDialog.setDefaultButton(self.cancelButton)\r\n\t\tself.okayButton.clicked.connect(self.deleteItem)\r\n\t\tself.ErrorDialog.exec_()\r\n\r\n\tdef deleteItem(self):\r\n\r\n\t\tselectedRow = self.LoanItemsTable.selectionModel().selectedRows()\r\n\t\tLoanItemID = int(selectedRow[0].data())\r\n\r\n\t\tdeleteItem = self.connection.deleteLoanItem(LoanItemID)\r\n\r\n\t\tif deleteItem:\r\n\t\t\ttext = \"Item deleted from the loan\".format()\r\n\t\t\tQMessageBox.information(self, \"Item Removed\", text)\r\n\t\t\tself.updateLoanItemTable()\r\n\t\t\tself.deleteButton.setEnabled(False)\r\n\t\telse:\r\n\t\t\terror = self.connection.error\r\n\t\t\tQMessageBox.information(self, \"Item Not Removed\", error)\r\n\r\n\r\n\tdef updateLoanItemTable(self):\r\n\t\tselectedRow = self.LoansTable.selectionModel().selectedRows()\r\n\t\tloanID = int(selectedRow[0].data())\r\n\r\n\t\tquery = self.connection.getLoanItems(loanID)\r\n\r\n\t\tif query:\r\n\t\t\tself.LoanItemsTableModel.setQuery(query)\r\n\t\t\tself.LoanItemsTable.setModel(self.LoanItemsTableModel)\r\n\t\t\tself.LoanItemsTable.setSortingEnabled(True)\r\n\t\t\tself.LoanItemsTable.show()\r\n\r\n\r\n\tdef connections(self):\r\n\t\tself.showAllLoansButton.clicked.connect(self.showAllLoansInTable)\r\n\t\tself.deleteButton.clicked.connect(self.warningDialog)\r\n\t\tself.deleteButton.setShortcut(\"Delete\")\r\n\r\n\t\tself.addLoanItemButton.setShortcut('Ctrl+Shift+N')\r\n\t\tself.addLoanItemButton.clicked.connect(self.switchToAddItem)\r\n\r\n\t\tself.deleteLoanItemButton.setShortcut(\"Ctrl+BackSpace\")\r\n\t\tself.deleteLoanItemButton.clicked.connect(self.loanItemWarningDialog)\r\n\r\n\r\n\t\tself.backButton.clicked.connect(self.parent.switchToMainMenu)\r\n\t\tself.backButton.setShortcut(\"Escape\")\r\n\r\n\t\tself.newLoanButton.clicked.connect(self.parent.switchToNewLoan)\r\n\r\n\t\tself.exportButton.clicked.connect(self.exportLoan)\r\n\t\tself.parent.Print.triggered.connect(self.exportLoan)\r\n\r\n\t\tself.addItemButton.clicked.connect(self.addLoanItem)\r\n\r\n\t\tself.cancelAddItemButton.clicked.connect(self.cancelAddItem)\r\n\r\n\r\n\tdef createHtml(self,customer, date, loanID, loanItems, loanLength):\r\n\r\n\t\tcustomerName = \"{0} {1} {2}\".format(customer[0], customer[1], customer [2])\r\n\t\tcustomerStreet = \"{0}\".format(customer[3])\r\n\t\tcustomerTown = \"{0}\".format(customer[4])\r\n\t\tcustomerCounty = \"{0}\".format(customer[5])\r\n\t\tcustomerPostCode = \"{0}\".format(customer[6])\r\n\r\n\t\tamountDue = 0\r\n\t\tfor each in loanItems:\r\n\t\t\tloanRate = each[2]\r\n\t\t\tamountDue += loanRate\r\n\r\n\t\tamountDue = amountDue * loanLength\r\n\r\n\t\tamountDue = round(amountDue, 2)\r\n\r\n\t\tamountIncVAT = amountDue * 1.2\r\n\r\n\t\tamountIncVAT = round(amountIncVAT, 2)\r\n\r\n\r\n\t\thtml = u\"\"\r\n\r\n\t\thtml += (\"\"\"<head>\r\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\t\t\ttable, th, td {border: 0px solid white; border-collapse: collapse}\r\n\t\t\t\t\t\t\tth, td {padding: 0px; text-align: left}\r\n\t\t\t\t\t\t\tth {background-color: black; color: white}\r\n\t\t\t\t\t\t\tbody{font-family:'Helvetica Neue'}\r\n\t\t\t\t\t\t\tbody {padding-bottom: 20px;} \r\n\t\t\t\t\t\t</style>\r\n\t\t\t\t\t</head>\"\"\")\r\n\r\n\t\thtml += (\"\"\"<body>\r\n\t\t\t\t\t<div align=\"left\"><img src=\"./Images/Logo.png\" width=\"50\" height=\"38.95\" alt=\"\"/></div>\r\n\t\t\t\t\t<div align=\"center\"><h1>C3 Media Department</h1></div>\r\n\t\t\t\t\t<div align=\"left\">\r\n\t\t\t\t\t\t<p>\r\n\t\t\t\t\t\t\t{0} <br>\r\n\t\t\t\t\t\t\t{1} <br>\r\n\t\t\t\t\t\t\t{2} <br>\r\n\t\t\t\t\t\t\t{3} <br>\r\n\t\t\t\t\t\t\t{4} <br>\r\n\t\t\t\t\t\t</p>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t\t<div align=\"right\">\r\n\t\t\t\t\t\t<table>\r\n\t\t\t\t\t\t\t<tbody>\r\n\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t<th align=\"right\">Invoice No.</th>\r\n\t\t\t\t\t\t\t\t\t<td>{5}</td>\r\n\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t<th align=\"right\">Date</th>\r\n\t\t\t\t\t\t\t\t\t<td>{6}</td>\r\n\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t<th align=\"right\">Amount Due</th>\r\n\t\t\t\t\t\t\t\t\t<td>£{7}</td>\r\n\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t</tbody>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t\t<br> <hr align=\"center\">\"\"\").format(customerName, customerStreet, customerTown, customerCounty, customerPostCode, loanID, date, amountDue)\r\n\r\n\r\n\t\thtml += (\"\"\"<div align=\"center\">\r\n\t\t\t\t\t<table width=\"400\">\r\n\t\t\t\t\t\t<tbody>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<th width=\"auto\"><strong>ID</strong></th>\r\n\t\t\t\t\t\t\t\t<th width=\"auto\"><strong>Item</strong></th>\r\n\t\t\t\t\t\t\t\t<th width=\"auto\"><strong>Loan Rate</strong></th>\r\n\t\t\t\t\t\t\t</tr>\"\"\")\r\n\r\n\t\tfor each in loanItems:\r\n\t\t\tID = each[0]\r\n\t\t\tName = each[1]\r\n\t\t\tCost = each[2]\r\n\t\t\tCost = round(Cost,2)\r\n\r\n\t\t\thtml += (\"\"\"<tr>\r\n\t\t\t\t\t\t\t<td align=\"center\">{0}</td>\r\n\t\t\t\t\t\t\t<td align=\"right\">{1}</td>\r\n\t\t\t\t\t\t\t<td align=\"right\">£{2}</td>\r\n\t\t\t\t\t\t</tr>\"\"\").format(ID, Name, Cost)\r\n\r\n\r\n\t\thtml += (\"\"\"<tr>\r\n\t\t\t\t\t\t<td colspan=\"3\"></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td></td>\r\n\t\t\t\t\t\t<td align=\"right\"><strong>Loan Length</strong></td>\r\n\t\t\t\t\t\t<td align=\"right\">{0} Days</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td></td>\r\n\t\t\t\t\t\t<td align=\"right\"><strong>Amount Due Exc. VAT:</strong></td>\r\n\t\t\t\t\t\t<td align=\"right\">£{1}</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td></td>\r\n\t\t\t\t\t\t<td align=\"right\"><strong>Amount Due at 20% VAT:</strong></td>\r\n\t\t\t\t\t\t<td align=\"right\">£{2}</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</tbody>\r\n\t\t\t</table>\r\n\t\t</div>\"\"\").format(loanLength, amountDue, amountIncVAT)\r\n\r\n\r\n\t\thtml += (\"\"\"<div align=\"center\">\r\n\t\t\t\t\t\t<br> <hr>\r\n\t\t\t\t\t\t<p>\r\n\t\t\t\t\t\t\tC3 Media Department <br>\r\n\t\t\t\t\t\t\t14 Alpha Terrace <br>\r\n\t\t\t\t\t\t\tTrumpington <br>\r\n\t\t\t\t\t\t\tCambridgeshire<br>\r\n\t\t\t\t\t\t\tCB2 9HT<br>\r\n\t\t\t\t\t\t</p>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t\t</body>\"\"\")\r\n\r\n\r\n\t\treturn html\r\n","sub_path":"Implementation/GUI/manageLoans.py","file_name":"manageLoans.py","file_ext":"py","file_size_in_byte":19513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"562655855","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAgente que gestiona las peticiones de los usuarios\n\"\"\"\nfrom flask import Flask, render_template, request\nimport socket\nimport argparse\nfrom rdflib import Namespace, Graph, RDF, URIRef, Literal, XSD\nfrom AgentUtil.Agent import Agent\nfrom AgentUtil.Logging import config_logger\nfrom AgentUtil.OntoNamespaces import ECSDIAmazon, ACL\nfrom AgentUtil.ACLMessages import get_agent_info, send_message, build_message, get_message_properties, register_agent\nfrom multiprocessing import Process\nfrom AgentUtil.FlaskServer import shutdown_server\nfrom multiprocessing import Queue\nfrom math import floor\n\n__author__ = 'ECSDI_AMAZON'\n\n\n#definimos los parametros de entrada (linea de comandos)\nparser = argparse.ArgumentParser()\nparser.add_argument('--open', help=\"Define si el servidor esta abierto al exterior o no\", action='store_true', default=False)\nparser.add_argument('--port', type=int, help=\"Puerto de comunicacion del agente\")\nparser.add_argument('--dhost', default=socket.gethostname(), help=\"Host del agente de directorio\")\nparser.add_argument('--dport', type=int, help=\"Puerto de comunicacion del agente de directorio\")\n\n# configuramos logger para imprimir\nlogger = config_logger(level=1) #1 para registrar todo (error i info)\n\n\n# parsear los parametros de entrada\nargs = parser.parse_args()\nif args.port is None:\n port = 9090\nelse:\n port = args.port\nif args.open is None:\n hostname = '0.0.0.0'\nelse:\n hostname = '127.0.0.1'\nif args.dport is None:\n dport = 9000\nelse:\n dport = args.dport\nif args.dhost is None:\n dhostname = '127.0.0.1'\nelse:\n dhostname = args.dhost\n\n#definimos un espacio de nombre\nagn = Namespace(\"http://www.agentes.org#\")\n\nqueue = Queue()\n# Contador de mensajes, por si queremos hacer un seguimiento\nmss_cnt = 0\n\n#crear agente\nAgenteUsuario = Agent('AgenteUsuario', agn.AgenteUsuario,\n 'http://%s:%d/comm' % (hostname, port),'http://%s:%d/Stop' % (hostname, port))\n\n\n# direccion del agente directorio\nDirectoryAgent = Agent('DirectoryAgent',\n agn.Directory,\n 'http://%s:%d/Register' % (dhostname, dport),\n 'http://%s:%d/Stop' % (dhostname, dport))\n\n\n\n#crear aplicacion servidor, en el segundo params se puede especificar el lugar de templates\napp = Flask(__name__, template_folder=\"./templates\")\n\n# global dsgraph triplestore\ndsgraph = Graph()\nlista_de_productos = []\nultimo_informe_recibido = Graph()\n\ndef get_message_count():\n global mss_cnt\n if mss_cnt is None:\n mss_cnt = 0\n mss_cnt += 1\n return mss_cnt\n\n#ruta definida para mostrar la pagina principal con diferente opciones\n@app.route(\"/\")\ndef main():\n return render_template(\"pg_usuario.html\")\n\n\n#funcion que se encarga de pedir la busqueda de productos al agente GestorDeProductos\ndef peticion_buscar(request):\n global lista_de_productos\n logger.info(\"Preparando la peticion de busqueda\")\n \n #accion: Buscar_productos\n contenido = ECSDIAmazon[\"Buscar_productos\"+str(get_message_count())]\n grafo = Graph()\n grafo.add((contenido, RDF.type, ECSDIAmazon.Buscar_productos))\n \n nombre_producto = request.form[\"nombre\"]\n #agregamos el nombre del producto\n if nombre_producto:\n nombre_sujeto = ECSDIAmazon[\"Restriccion_nombre\" + str(get_message_count)]\n grafo.add((nombre_sujeto, RDF.type, ECSDIAmazon.Restriccion_nombre))\n grafo.add((nombre_sujeto, ECSDIAmazon.Nombre, Literal(nombre_producto, datatype=XSD.string)))\n grafo.add((contenido, ECSDIAmazon.Restringe, URIRef(nombre_sujeto)))\n precio_min = request.form['precio_min']\n precio_max = request.form['precio_max']\n # agregamos el rango de precios\n ## Recordar: El precio se recibe en euros pero se ha de cambiar a centimos de euro\n if precio_min != \"\" or precio_max != \"\":\n precio_sujeto = ECSDIAmazon['Restriccion_precio' + str(get_message_count())]\n grafo.add((precio_sujeto, RDF.type, ECSDIAmazon.Restriccion_precio))\n if precio_min != \"\":\n if precio_min == \"0\":\n precio_min = 0\n else:\n precio_min = int((float(request.form['precio_min'])*100)//1)\n\n grafo.add((precio_sujeto, ECSDIAmazon.Precio_minimo, Literal(precio_min)))\n if precio_max != \"\":\n if precio_max == \"0\":\n precio_max = 0\n else:\n precio_max = int((float(request.form['precio_max'])*100)//1)\n grafo.add((precio_sujeto, ECSDIAmazon.Precio_maximo, Literal(precio_max)))\n grafo.add((contenido, ECSDIAmazon.Restringe, URIRef(precio_sujeto)))\n\n # pedimos informacion del agente GestorDeProductos\n logger.info(\"Cogiendo informacion del AgenteGestorDeProductos\")\n agente = get_agent_info(agn.AgenteGestorDeProductos, DirectoryAgent, AgenteUsuario, get_message_count())\n logger.info(\"Enviando peticion de busqueda al AgenteGestorDeProductos\")\n # en el mensaje digo en que ruta y puerto tiene que conectarse para enviar el mensaje\n respuesta_msg = send_message(build_message(\n grafo, perf=ACL.request, sender=AgenteUsuario.uri, receiver=agente.uri, msgcnt=get_message_count(), \n content=contenido), agente.address)\n\n # analizo la respuesta que me habra enviado el agente GestorDeProductos\n lista_de_productos = []\n for item in respuesta_msg.subjects(RDF.type, ECSDIAmazon.Producto):\n product = dict(\n id_producto=str(respuesta_msg.value(subject=item, predicate=ECSDIAmazon.Id_producto)),\n nombre_producto=str(respuesta_msg.value(subject=item, predicate=ECSDIAmazon.Nombre_producto)),\n precio_producto=int(respuesta_msg.value(subject=item, predicate=ECSDIAmazon.Precio_producto))/100,\n descripcion_producto=str(respuesta_msg.value(subject=item, predicate=ECSDIAmazon.Descripcion_producto)),\n categoria=str(respuesta_msg.value(subject=item, predicate=ECSDIAmazon.Categoria)),\n marca=str(respuesta_msg.value(subject=item, predicate=ECSDIAmazon.Marca)),\n peso=str(respuesta_msg.value(subject=item, predicate=ECSDIAmazon.Peso_producto))\n )\n lista_de_productos.append(product)\n lista_de_productos = sorted(lista_de_productos, key=lambda p_list: p_list[\"precio_producto\"])\n logger.info(\"Mostramos resultado de la busqueda\")\n return render_template('buscar.html', productos=lista_de_productos, b=True,only_search=True)\n\n\n\ndef iniciar_venta(request):\n global lista_de_productos\n logger.info(\"Analizando la peticion de compra\")\n mi_compra = []\n #coge los indices marcados\n for p in request.form.getlist(\"product_checkbox\"):\n mi_compra.append(lista_de_productos[int(p)])\n \n\n #cogo info de la compra\n tarjeta = str(request.form['tarjeta'])\n direccion = str(request.form['direccion'])\n ciudad = str(request.form['ciudad'])\n codigo_postal = int(request.form['codigo_postal'])\n prioridad = int(request.form['prioridad']) #va entre 1 y 10, de mayor a menor prioridad \n\n #preparo el grafo para comunicarme con el AgenteGestorDeVenta\n #accion: Iniciar_venta\n contenido = ECSDIAmazon[\"Iniciar_venta\" + str(get_message_count())]\n grafo_venta = Graph()\n grafo_venta.add((contenido, RDF.type, ECSDIAmazon.Iniciar_venta))\n grafo_venta.add((contenido, ECSDIAmazon.Tarjeta, Literal(tarjeta, datatype=XSD.int)))\n grafo_venta.add((contenido, ECSDIAmazon.Prioridad, Literal(prioridad, datatype=XSD.int)))\n \n direccion_cliente = ECSDIAmazon[\"Direccion\"+ str(get_message_count())]\n grafo_venta.add((direccion_cliente, RDF.type, ECSDIAmazon.Direccion))\n grafo_venta.add((direccion_cliente, ECSDIAmazon.Direccion, Literal(direccion, datatype=XSD.string)))\n grafo_venta.add((direccion_cliente, ECSDIAmazon.Ciudad, Literal(ciudad, datatype=XSD.string)))\n grafo_venta.add((direccion_cliente, ECSDIAmazon.Codigo_postal, Literal(codigo_postal, datatype=XSD.int)))\n\n venta = ECSDIAmazon[\"Venta\"+str(get_message_count())]\n grafo_venta.add((venta, RDF.type, ECSDIAmazon.Venta))\n grafo_venta.add((venta, ECSDIAmazon.Destino, URIRef(direccion_cliente)))\n logger.info(\"Mi lista de productos\")\n logger.info(\"Mi compra\")\n if not mi_compra:\n return render_template('buscar.html', productos=lista_de_productos, b=True,only_search=False,buy_empty=True)\n\n for producto in mi_compra:\n s = producto[\"id_producto\"]\n url = ECSDIAmazon\n sujeto = url.term(producto[\"id_producto\"])\n grafo_venta.add((sujeto, RDF.type, ECSDIAmazon.Producto))\n grafo_venta.add((sujeto, ECSDIAmazon.Id_producto, Literal(producto['id_producto'], datatype=XSD.string)))\n grafo_venta.add((sujeto, ECSDIAmazon.Nombre_producto, Literal(producto['nombre_producto'], datatype=XSD.string)))\n grafo_venta.add((sujeto, ECSDIAmazon.Precio_producto, Literal(producto['precio_producto'], datatype=XSD.float)))\n grafo_venta.add((sujeto, ECSDIAmazon.Descripcion_producto, Literal(producto['descripcion_producto'], datatype=XSD.string)))\n grafo_venta.add((sujeto, ECSDIAmazon.Categoria, Literal(producto['categoria'], datatype=XSD.string)))\n grafo_venta.add((sujeto, ECSDIAmazon.Marca, Literal(producto['marca'], datatype=XSD.string)))\n grafo_venta.add((sujeto, ECSDIAmazon.Peso_producto, Literal(producto['peso'], datatype=XSD.int)))\n grafo_venta.add((venta, ECSDIAmazon.Contiene, URIRef(sujeto)))\n \n grafo_venta.add((contenido, ECSDIAmazon.De, URIRef(venta)))\n agente = get_agent_info(agn.AgenteGestorDeVentas, DirectoryAgent, AgenteUsuario, get_message_count())\n logger.info(\"Enviando peticion de iniciar venta al AgenteGestorDeVentas\")\n respuesta_msg = send_message(build_message(\n grafo_venta, perf=ACL.request, sender=AgenteUsuario.uri, receiver=agente.uri, msgcnt=get_message_count(), \n content=contenido), agente.address)\n \n logger.info(\"Respuesta recibida\")\n \n #obtenemos valores factura, productos y tarjeta asocida a dicha factura de la compra para mostrar al usuario\n venta_factura = respuesta_msg.value(predicate=RDF.type, object=ECSDIAmazon.Factura)\n venta_tarjeta = str(respuesta_msg.value(subject=venta_factura, predicate=ECSDIAmazon.Tarjeta))\n venta_fecha_aproximada = respuesta_msg.value(subject=venta_factura, predicate=ECSDIAmazon.Fecha_aproximada)\n venta_precio_total = float(respuesta_msg.value(subject=venta_factura, predicate=ECSDIAmazon.Precio_total))\n venta_id=str(respuesta_msg.value(subject=venta_factura, predicate=ECSDIAmazon.Id_venta))\n \n venta_productos = respuesta_msg.subjects(object=ECSDIAmazon.Producto)\n productos_factura = []\n for prod in venta_productos:\n product = dict(\n nombre_producto=str(respuesta_msg.value(subject=prod, predicate=ECSDIAmazon.Nombre_producto)),\n precio_producto=float(respuesta_msg.value(subject=prod, predicate=ECSDIAmazon.Precio_producto)),\n )\n productos_factura.append(product)\n productos_factura = sorted(productos_factura, key=lambda p_list: p_list[\"precio_producto\"])\n logger.info(\"Mostramos la factura recibida\")\n #render de factura\n return render_template('factura.html', productos=productos_factura,id_compra=venta_id, tarjeta=venta_tarjeta, precio_total=venta_precio_total,fecha_aproximada = venta_fecha_aproximada)\n\n\n#busqueda: get para mostrar los filtros de productos y post para atender la peticion de filtros\n@app.route(\"/buscar\", methods=[\"GET\",\"POST\"])\ndef buscar_productos():\n if request.method == \"GET\":\n return render_template(\"buscar.html\", productos=None)\n elif request.method == \"POST\":\n if request.form[\"submit\"] == \"Buscar\":\n return peticion_buscar(request)\n elif request.form[\"submit\"] == \"Comprar\":\n return iniciar_venta(request)\n\n@app.route(\"/ultimo_informe\", methods=[\"GET\"])\ndef obtener_ultimo_informe():\n if request.method == \"GET\":\n return mostrar_ultimo_informe(request)\n\ndef mostrar_ultimo_informe(request):\n global ultimo_informe_recibido\n venta_info = ultimo_informe_recibido.value(predicate=RDF.type, object=ECSDIAmazon.Informar)\n id_venta = ultimo_informe_recibido.value(subject=venta_info, predicate=ECSDIAmazon.Id_venta)\n transportista = ultimo_informe_recibido.value(subject=venta_info, predicate=ECSDIAmazon.Transportista_asignado)\n fecha_final = ultimo_informe_recibido.value(subject=venta_info, predicate=ECSDIAmazon.Fecha_final)\n precio_venta = ultimo_informe_recibido.value(subject=venta_info, predicate=ECSDIAmazon.Precio_venta)\n precio_envio = ultimo_informe_recibido.value(subject=venta_info, predicate=ECSDIAmazon.Precio_envio)\n precio_total = ultimo_informe_recibido.value(subject=venta_info, predicate=ECSDIAmazon.Precio_total)\n tarjeta = ultimo_informe_recibido.value(subject=venta_info,predicate=ECSDIAmazon.Tarjeta)\n return render_template('informe.html',id_venta=id_venta,tarjeta= tarjeta,transportista=transportista,fecha_final=fecha_final,precio_venta=precio_venta ,precio_envio=precio_envio,precio_total=precio_total)\n\n\n@app.route(\"/devolucion\", methods=[\"GET\", \"POST\"])\ndef devolver_productos():\n return True\n\n\n\n@app.route(\"/Stop\")\ndef stop():\n \"\"\"\n Entrypoint que para el agente\n\n :return:\n \"\"\"\n tidyup()\n shutdown_server()\n return \"Parando Servidor\"\n\n\n@app.route(\"/comm\")\ndef comunicacion():\n global ultimo_informe_recibido\n message = request.args['content'] #cogo el contenido enviado\n grafo = Graph()\n logger.info('--Envian una comunicacion')\n grafo.parse(data=message)\n logger.info('--Envian una comunicacion')\n message_properties = get_message_properties(grafo)\n\n resultado_comunicacion = None\n\n if message_properties is None:\n #respondemos que no hemos entendido el mensaje\n resultado_comunicacion = build_message(Graph(), ACL['not-understood'],\n sender=AgenteUsuario.uri, msgcnt=get_message_count())\n else:\n #obtenemos la performativa\n if message_properties['performative'] != ACL.request:\n #Si no es un request, respondemos que no hemos entendido el mensaje\n resultado_comunicacion = build_message(Graph(), ACL['not-understood'],\n sender=AgenteUsuario.uri, msgcnt=get_message_count())\n else:\n #Extraemos el contenido que ha de ser una accion de la ontologia\n contenido = message_properties['content']\n accion = grafo.value(subject=contenido, predicate=RDF.type)\n logger.info(\"La accion es: \" + accion)\n #si la acción es de tipo tranferencia empezamos\n if accion == ECSDIAmazon.Informar:\n logger.info(\"Ya apunto de finalizar\")\n # thread = Thread(target=enviarVenta, args=(contenido,grafo))\n # thread.start()\n ultimo_informe_recibido = grafo\n graf = Graph()\n mensaje = ECSDIAmazon[\"Respuesta\"+ str(get_message_count())]\n graf.add((mensaje,RDF.type, ECSDIAmazon.Respuesta))\n graf.add((mensaje,ECSDIAmazon.Mensaje,Literal(\"OK\",datatype=XSD.string)))\n resultado_comunicacion = graf\n \n logger.info(\"Antes de serializar la respuesta\")\n serialize = resultado_comunicacion.serialize(format=\"xml\")\n return serialize, 200\n\n\ndef tidyup():\n \"\"\"\n Acciones previas a parar el agente\n\n \"\"\"\n global queue\n queue.put(0)\n pass\n\ndef register_message():\n \"\"\"\n Envia un mensaje de registro al servicio de registro\n usando una performativa Request y una accion Register del\n servicio de directorio\n\n :param gmess:\n :return:\n \"\"\"\n\n logger.info('Nos registramos')\n\n gr = register_agent(AgenteUsuario, DirectoryAgent, agn.AgenteUsuario, get_message_count())\n return gr\n\n\ndef agentbehavior1():\n \"\"\"\n Un comportamiento del agente\n\n :return:\n \"\"\"\n graf = register_message()\n \n\nif __name__ == '__main__':\n # Ponemos en marcha los behaviors\n ab1 = Process(target=agentbehavior1)\n ab1.start()\n # Run server\n app.run(host=hostname, port=port, debug=True)\n # Esperamos a que acaben los behaviors\n ab1.join()\n logger.info('Final')","sub_path":"AMAZON/2_AgenteUsuario.py","file_name":"2_AgenteUsuario.py","file_ext":"py","file_size_in_byte":16309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"424728662","text":"\"\"\"Top-level model classes.\n\nAuthor:\n Chris Chute (chute@stanford.edu)\n\"\"\"\n\nimport layers\nimport torch\nimport torch.nn as nn\nimport pdb\n\nclass BiDAF_RNet(nn.Module):\n def __init__(self, word_vectors, char_vectors, hidden_size, drop_prob=0.):\n super(BiDAF_RNet, self).__init__()\n self.emb = layers.WordCharEmbedding(word_vectors=word_vectors,\n char_vectors=char_vectors,\n cnn_size=16,\n hidden_size=hidden_size,\n drop_prob=drop_prob)\n\n self.att = layers.BiDAFAttention(hidden_size=2 * hidden_size,\n drop_prob=drop_prob)\n\n self.selfatt = layers.SelfMatchingAttention(input_size=8 * hidden_size,\n hidden_size=4 * hidden_size,\n num_layers=3,\n drop_prob=drop_prob)\n\n self.mod = layers.RNNEncoder(input_size=8 * hidden_size,\n hidden_size=hidden_size,\n num_layers=2,\n drop_prob=drop_prob)\n\n self.out = layers.BiDAFOutput(hidden_size=hidden_size,\n drop_prob=drop_prob)\n\n def forward(self, cw_idxs, qw_idxs, cc_idxs, qc_idxs):\n c_mask = torch.zeros_like(cw_idxs) != cw_idxs\n q_mask = torch.zeros_like(qw_idxs) != qw_idxs\n \n c_enc = self.emb(cw_idxs, cc_idxs, c_mask) \n q_enc = self.emb(qw_idxs, qc_idxs, q_mask)\n\n att = self.att(c_enc, q_enc, c_mask, q_mask)\n\n h_p = self.selfatt(att)\n\n mod = self.mod(h_p, c_mask.sum(-1))\n\n out = self.out(att, mod, c_mask)\n\n torch.cuda.empty_cache()\n\n return out\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"260592308","text":"#!/usr/bin/env python3\n\n\"\"\"Code generation methods for all low-level nodes in the IR.\nCodegen functions return a string, consisting of the assembly code they\ncorrespond to. Alternatively, they can return a list where:\n - the first element is the assembly code\n - the second element is extra assembly code to be appended at the end of\n the code of the function they are contained in\nThis feature can be used only by IR nodes that are contained in a Block, and\nis used for adding constant literals.\"\"\"\n\nfrom datalayout import *\nfrom ir import *\n\nlocalconsti = 0\n\n\ndef new_local_const_label():\n global localconsti\n lab = '.const' + repr(localconsti)\n localconsti += 1\n return lab\n\n\ndef new_local_const(val):\n lab = new_local_const_label()\n trail = lab + ':\\n\\t.word ' + val + '\\n'\n return lab, trail\n\n\ndef symbol_codegen(self, regalloc):\n if self.allocinfo is None:\n return \"\"\n if not isinstance(self.allocinfo, LocalSymbolLayout):\n return '\\t.comm ' + self.allocinfo.symname + ', ' + repr(self.allocinfo.bsize) + \"\\n\"\n else:\n return '\\t.equ ' + self.allocinfo.symname + ', ' + repr(self.allocinfo.fpreloff) + \"\\n\"\n\n\nSymbol.codegen = symbol_codegen\n\n\ndef irnode_codegen(self, regalloc):\n res = ['\\t' + comment(\"irnode \" + repr(id(self)) + ' type ' + repr(type(self))), '']\n if 'children' in dir(self) and len(self.children):\n for node in self.children:\n try:\n try:\n labl = node.get_label()\n res[0] += labl.name + ':\\n'\n except Exception:\n pass\n res = codegen_append(res, node.codegen(regalloc))\n except Exception as e:\n res[0] += \"\\t\" + comment(\"node \" + repr(id(node)) + \" did not generate any code\")\n res[0] += \"\\t\" + comment(\"exc: \" + repr(e))\n return res\n\n\nIRNode.codegen = irnode_codegen\n\n\ndef block_codegen(self, regalloc):\n res = [comment('block'), '']\n for sym in self.symtab:\n res = codegen_append(res, sym.codegen(regalloc))\n\n if self.parent is None:\n res[0] += '\\t.global __pl0_start\\n'\n res[0] += \"__pl0_start:\\n\"\n\n res[0] += save_regs(REGS_CALLEESAVE + [REG_FP, REG_LR])\n res[0] += '\\tmov ' + get_register_string(REG_FP) + ', ' + get_register_string(REG_SP) + '\\n'\n stacksp = self.stackroom + regalloc.spill_room()\n res[0] += '\\tsub ' + get_register_string(REG_SP) + ', ' + get_register_string(REG_SP) + ', #' + repr(stacksp) + '\\n'\n\n regalloc.enter_function_body(self)\n try:\n res = codegen_append(res, self.body.codegen(regalloc))\n except Exception:\n pass\n\n res[0] += '\\tmov ' + get_register_string(REG_SP) + ', ' + get_register_string(REG_FP) + '\\n'\n res[0] += restore_regs(REGS_CALLEESAVE + [REG_FP, REG_LR])\n res[0] += '\\tbx lr\\n'\n\n res[0] = res[0] + res[1]\n res[1] = ''\n\n try:\n res = codegen_append(res, self.defs.codegen(regalloc))\n except Exception:\n pass\n\n return res[0] + res[1]\n\n\nBlock.codegen = block_codegen\n\n\ndef deflist_codegen(self, regalloc):\n return ''.join([child.codegen(regalloc) for child in self.children])\n\n\nDefinitionList.codegen = deflist_codegen\n\n\ndef fun_codegen(self, regalloc):\n res = '\\n' + self.symbol.name + ':\\n'\n res += self.body.codegen(regalloc)\n return res\n\n\nFunctionDef.codegen = fun_codegen\n\n\ndef binstat_codegen(self, regalloc):\n res = regalloc.gen_spill_load_if_necessary(self.srca)\n res += regalloc.gen_spill_load_if_necessary(self.srcb)\n ra = regalloc.get_register_for_variable(self.srca)\n rb = regalloc.get_register_for_variable(self.srcb)\n rd = regalloc.get_register_for_variable(self.dest)\n param = ra + ', ' + rb\n if self.op == \"plus\":\n res += '\\tadd ' + rd + ', ' + param + '\\n'\n elif self.op == \"minus\":\n res += '\\tsub ' + rd + ', ' + param + '\\n'\n elif self.op == \"times\":\n res += '\\tmul ' + rd + ', ' + param + '\\n'\n elif self.op == \"slash\":\n res += '\\tdiv ' + rd + ', ' + param + '\\n'\n elif self.op == \"eql\":\n res += '\\tcmp ' + param + '\\n'\n res += '\\tmoveq ' + rd + ', #1\\n'\n res += '\\tmovne ' + rd + ', #0\\n'\n elif self.op == \"neq\":\n res += '\\tcmp ' + param + '\\n'\n res += '\\tmoveq ' + rd + ', #0\\n'\n res += '\\tmovne ' + rd + ', #1\\n'\n elif self.op == \"lss\":\n res += '\\tcmp ' + param + '\\n'\n res += '\\tmovlt ' + rd + ', #1\\n'\n res += '\\tmovge ' + rd + ', #0\\n'\n elif self.op == \"leq\":\n res += '\\tcmp ' + param + '\\n'\n res += '\\tmovle ' + rd + ', #1\\n'\n res += '\\tmovgt ' + rd + ', #0\\n'\n elif self.op == \"gtr\":\n res += '\\tcmp ' + param + '\\n'\n res += '\\tmovgt ' + rd + ', #1\\n'\n res += '\\tmovle ' + rd + ', #0\\n'\n elif self.op == \"geq\":\n res += '\\tcmp ' + param + '\\n'\n res += '\\tmovge ' + rd + ', #1\\n'\n res += '\\tmovlt ' + rd + ', #0\\n'\n else:\n raise Exception(\"operation \" + repr(self.op) + \" unexpected\")\n return res + regalloc.gen_spill_store_if_necessary(self.dest)\n\n\nBinStat.codegen = binstat_codegen\n\n\ndef print_codegen(self, regalloc):\n res = regalloc.gen_spill_load_if_necessary(self.src)\n rp = regalloc.get_register_for_variable(self.src)\n res += save_regs(REGS_CALLERSAVE)\n res += '\\tmov ' + get_register_string(0) + ', ' + rp + '\\n'\n res += '\\tbl __pl0_print\\n'\n res += restore_regs(REGS_CALLERSAVE)\n return res\n\n\nPrintCommand.codegen = print_codegen\n\n\ndef read_codegen(self, regalloc):\n rd = regalloc.get_register_for_variable(self.dest)\n\n # punch a hole in the saved registers if one of them is the destination\n # of this \"instruction\"\n savedregs = list(REGS_CALLERSAVE)\n if regalloc.vartoreg[self.dest] in savedregs:\n savedregs.remove(regalloc.vartoreg[self.dest])\n\n res = save_regs(savedregs)\n res += '\\tbl __pl0_read\\n'\n res += '\\tmov ' + rd + ', ' + get_register_string(0) + '\\n'\n res += restore_regs(savedregs)\n res += regalloc.gen_spill_store_if_necessary(self.dest)\n return res\n\n\nReadCommand.codegen = read_codegen\n\n\ndef branch_codegen(self, regalloc):\n targetl = self.target.name\n if not self.returns:\n if self.cond is None:\n return '\\tb ' + targetl + '\\n'\n else:\n res = regalloc.gen_spill_load_if_necessary(self.cond)\n rcond = regalloc.get_register_for_variable(self.cond)\n res += '\\ttst ' + rcond + ', ' + rcond + '\\n'\n return res + '\\t' + ('beq' if self.negcond else 'bne') + ' ' + targetl + '\\n'\n else:\n if self.cond is None:\n res = save_regs(REGS_CALLERSAVE)\n res += '\\tbl ' + targetl + '\\n'\n res += restore_regs(REGS_CALLERSAVE)\n return res\n else:\n res = regalloc.gen_spill_load_if_necessary(self.cond)\n rcond = regalloc.get_register_for_variable(self.cond)\n res += '\\ttst ' + rcond + ', ' + rcond + '\\n'\n res += '\\t' + ('bne' if self.negcond else 'beq') + ' ' + rcond + ', 1f\\n'\n res += save_regs(REGS_CALLERSAVE)\n res += '\\tbl ' + targetl + '\\n'\n res += restore_regs(REGS_CALLERSAVE)\n res += '1:'\n return res\n return comment('impossible!')\n\n\nBranchStat.codegen = branch_codegen\n\n\ndef emptystat_codegen(self, regalloc):\n return '\\t' + comment('emptystat')\n\n\nEmptyStat.codegen = emptystat_codegen\n\n\ndef ldptrto_codegen(self, regalloc):\n rd = regalloc.get_register_for_variable(self.dest)\n res = ''\n trail = ''\n ai = self.symbol.allocinfo\n if type(ai) is LocalSymbolLayout:\n off = ai.fpreloff\n if off > 0:\n res = '\\tadd ' + rd + ', ' + get_register_string(REG_FP) + ', #' + repr(off) + '\\n'\n else:\n res = '\\tsub ' + rd + ', ' + get_register_string(REG_FP) + ', #' + repr(-off) + '\\n'\n else:\n lab, tmp = new_local_const(ai.symname)\n trail += tmp\n res = '\\tldr ' + rd + ', ' + lab + '\\n'\n return [res + regalloc.gen_spill_store_if_necessary(self.dest), trail]\n\n\nLoadPtrToSym.codegen = ldptrto_codegen\n\n\ndef storestat_codegen(self, regalloc):\n res = ''\n trail = ''\n if self.dest.alloct == 'reg':\n res += regalloc.gen_spill_load_if_necessary(self.dest)\n dest = '[' + regalloc.get_register_for_variable(self.dest) + ']'\n else:\n ai = self.dest.allocinfo\n if type(ai) is LocalSymbolLayout:\n dest = '[' + get_register_string(REG_FP) + ', #' + ai.symname + ']'\n else:\n lab, tmp = new_local_const(ai.symname)\n trail += tmp\n res += '\\tldr ' + get_register_string(REG_SCRATCH) + ', ' + lab + '\\n'\n dest = '[' + get_register_string(REG_SCRATCH) + ']'\n\n if type(self.dest.stype) is PointerType:\n desttype = self.dest.stype.pointstotype\n else:\n desttype = self.dest.stype\n typeid = ['b', 'h', None, ''][desttype.size // 8 - 1]\n if typeid != '' and 'unsigned' in desttype.qual_list:\n typeid = 's' + type\n\n res += regalloc.gen_spill_load_if_necessary(self.symbol)\n rsrc = regalloc.get_register_for_variable(self.symbol)\n return [res + '\\tstr' + typeid + ' ' + rsrc + ', ' + dest + '\\n', trail]\n\n\nStoreStat.codegen = storestat_codegen\n\n\ndef loadstat_codegen(self, regalloc):\n res = ''\n trail = ''\n if self.symbol.alloct == 'reg':\n res += regalloc.gen_spill_load_if_necessary(self.symbol)\n src = '[' + regalloc.get_register_for_variable(self.symbol) + ']'\n else:\n ai = self.symbol.allocinfo\n if type(ai) is LocalSymbolLayout:\n src = '[' + get_register_string(REG_FP) + ', #' + ai.symname + ']'\n else:\n lab, tmp = new_local_const(ai.symname)\n trail += tmp\n res += '\\tldr ' + get_register_string(REG_SCRATCH) + ', ' + lab + '\\n'\n src = '[' + get_register_string(REG_SCRATCH) + ']'\n\n if type(self.symbol.stype) is PointerType:\n desttype = self.symbol.stype.pointstotype\n else:\n desttype = self.symbol.stype\n typeid = ['b', 'h', None, ''][desttype.size // 8 - 1]\n if typeid != '' and 'unsigned' in desttype.qual_list:\n typeid = 's' + type\n\n rdst = regalloc.get_register_for_variable(self.dest)\n res += '\\tldr' + typeid + ' ' + rdst + ', ' + src + '\\n'\n res += regalloc.gen_spill_store_if_necessary(self.dest)\n return [res, trail]\n\n\nLoadStat.codegen = loadstat_codegen\n\n\ndef loadimm_codegen(self, regalloc):\n rd = regalloc.get_register_for_variable(self.dest)\n val = self.val\n if val >= -256 and val < 256:\n if val < 0:\n rv = -val - 1\n op = 'mvn '\n else:\n rv = val\n op = 'mov '\n res = '\\t' + op + rd + ', #' + repr(rv) + '\\n'\n trail = ''\n else:\n lab, trail = new_local_const(repr(val))\n res = '\\tldr ' + rd + ', ' + lab + '\\n'\n return [res + regalloc.gen_spill_store_if_necessary(self.dest), trail]\n\n\nLoadImmStat.codegen = loadimm_codegen\n\n\ndef unarystat_codegen(self, regalloc):\n res = regalloc.gen_spill_load_if_necessary(self.src)\n rs = regalloc.get_register_for_variable(self.src)\n rd = regalloc.get_register_for_variable(self.dest)\n if self.op == 'plus':\n if rs != rd:\n res += '\\tmov ' + rd + ', ' + rs + '\\n'\n elif self.op == 'minus':\n res += '\\tmvn ' + rd + ', ' + rs + '\\n'\n res += '\\tadd ' + rd + ', ' + rd + ', #1\\n'\n elif self.op == 'odd':\n res += '\\tand ' + rd + ', ' + rs + ', #1\\n'\n else:\n raise Exception(\"operation \" + repr(self.op) + \" unexpected\")\n res += regalloc.gen_spill_store_if_necessary(self.dest)\n return res\n\n\nUnaryStat.codegen = unarystat_codegen\n\n\ndef generate_code(program, regalloc):\n res = '\\t.text\\n'\n res += '\\t.arch armv6\\n'\n res += '\\t.syntax unified\\n'\n return res + program.codegen(regalloc)\n","sub_path":"codegen.py","file_name":"codegen.py","file_ext":"py","file_size_in_byte":11915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"279320586","text":"from typing import List\n\n\ndef binalysearch(numbers: List[int], target: int):\n \"\"\"Search `target` from `numbers`\n\n Arguments:\n numbers {List[int]} -- **sorted** numbers\n target {int} -- a number to find\n\n Returns:\n number -- the indef of number if it's found. If not, -1.\n \"\"\"\n low = 0\n high = len(numbers) - 1\n\n while low <= high:\n mid = (high + low) // 2\n guess = numbers[mid]\n\n if guess == target:\n return mid\n if guess < target:\n low = mid + 1\n else:\n high = mid - 1\n\n return -1\n","sub_path":"python/grokking-algorithms/01/binarysearch.py","file_name":"binarysearch.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"102782030","text":"__author__ = 'etienne'\n\n\n\n\nliste = [2,4,6,2,6,3,2,5,11,3,6,2,8,9,24,3,45,6,3]\n\n\ndef bubble_sort(liste):\n\n liste_boucle = range(len(liste))\n\n variable_boucle = True # use this to close the cycle\n\n while variable_boucle == True :\n\n for element in liste_boucle:\n bre = 0\n while element < (len(liste)-1):\n if liste[element] > liste[element+1]:\n liste[element],liste[element+1] = liste[element+1],liste[element]\n\n else:\n True\n bre += 1 #if everything is in order, this will transform the variable_boucle to false\n element += 1 #advance in the list\n\n if bre == len(liste)-1:\n print(liste)\n variable_boucle = False\n\n\n\n\nbubble_sort(liste)\n\n\n\n\n","sub_path":"bubble_sort_sorting_algorithm.py","file_name":"bubble_sort_sorting_algorithm.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"95214367","text":"from django.conf.urls import url\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.utils.safestring import mark_safe\nfrom django.shortcuts import reverse\nfrom stark.static.page import Page\nfrom django import forms\nfrom django.db.models import Q\nimport copy\n\n\nclass ListView:\n\n def __init__(self, config_obj, request, data_list):\n self.config_obj = config_obj\n self.request = request\n self.data_list = data_list\n\n def create_head(self):\n # 表头的建立\n heads_list = []\n for field_or_func in self.config_obj.new_list_display():\n if callable(field_or_func):\n head = field_or_func(self.config_obj, is_head=True)\n else:\n if field_or_func != \"__str__\":\n field_obj = self.config_obj.model._meta.get_field(field_or_func)\n head = field_obj.verbose_name\n else:\n head = self.config_obj.model._meta.model_name\n heads_list.append(head)\n return heads_list\n\n def create_body(self):\n # 表内容content_list=[[数据1],[数据2],[数据3]....]\n obj_list = []\n for data_obj in self.data_list:\n content_list = []\n for field_or_func in self.config_obj.new_list_display():\n if callable(field_or_func):\n content = field_or_func(self.config_obj, data_obj)\n else:\n try:\n from django.db.models.fields.related import ManyToManyField\n field_obj = data_obj._meta.get_field(field_or_func)\n if isinstance(field_obj, ManyToManyField):\n contents_list = getattr(data_obj, field_or_func).all()\n content = '||'.join([str(item) for item in contents_list])\n else:\n content = getattr(data_obj, field_or_func)\n if field_or_func in self.config_obj.list_display_links:\n url = self.config_obj.get_change_url(data_obj)\n content = mark_safe(f'<a href=\"{url}\">{content}</a>')\n except:\n content = getattr(data_obj, field_or_func)\n content_list.append(content)\n\n obj_list.append(content_list)\n return obj_list\n\n def actions_list(self):\n actions_list = []\n action_info = []\n if self.config_obj.actions:\n actions_list.extend(self.config_obj.actions)\n actions_list.append(self.config_obj.batch_delete)\n for action in actions_list:\n action_info.append({\n \"desc\": action.short_description,\n \"action\": action.__name__\n })\n return action_info\n\n # filter相关方法\n def filter_field_links(self):\n filter_links = {}\n\n for field in self.config_obj.list_filter:\n # 从get请求中得到需要的filter参数\n params = copy.deepcopy(self.request.GET)\n choice_field_pk = self.request.GET.get(field, 0)\n # 通过多对多或者一对多的字段得到对应的模型表\n field_obj = self.config_obj.model._meta.get_field(field)\n rel_model = field_obj.rel.to\n\n # 得到模型表中的所有数据\n ret_model_queryset = rel_model.objects.all()\n tem = []\n for obj in ret_model_queryset:\n # 将对应的对象pk值添加到字典中,以当前model表的字段为键\n params[field] = obj.pk\n if obj.pk == int(choice_field_pk):\n link = f\"<a style='color:red' href='?{params.urlencode()}'>{obj}</a>\"\n else:\n link = f\"<a href='?{params.urlencode()}'>{obj}</a>\"\n tem.append(link)\n filter_links[field] = tem\n return filter_links\n\n\nclass ModelStark(object):\n \"\"\"\n 默认配置类\n \"\"\"\n # print(self)#<app01.stark.PublishConfig object at 0x000001531BBC6DD8>\n # print(self.model)#<class 'app01.models.Publish'>\n list_display = ['__str__']\n list_display_links = []\n search_fields = []\n actions = []\n list_filter = []\n\n def __init__(self, model):\n self.model = model # 当前模型表\n self.model_name = self.model._meta.model_name # 当前模型表名\n self.app_label = self.model._meta.app_label # 当前模型表所属app名\n\n # 反向解析当前查看表的增删改查的url\n def get_check_url(self):\n url_name = \"%s_%s_check\" % (self.app_label, self.model_name)\n _url = reverse(url_name)\n return _url\n\n def get_add_url(self):\n url_name = \"%s_%s_add\" % (self.app_label, self.model_name)\n _url = reverse(url_name)\n return _url\n\n def get_change_url(self, obj):\n url_name = \"%s_%s_change\" % (self.app_label, self.model_name)\n _url = reverse(url_name, args=(obj.pk,))\n return _url\n\n def get_del_url(self, obj):\n url_name = \"%s_%s_delete\" % (self.app_label, self.model_name)\n _url = reverse(url_name, args=(obj.pk,))\n return _url\n\n def edit(self, data_obj=None, is_head=False):\n if is_head:\n return \"编辑\"\n else:\n return mark_safe(f'<a href={self.get_change_url(data_obj)}><button type=\"button\" class=\"btn btn-info\">编辑</button></a>')\n\n def delete(self, data_obj=None, is_head=False):\n if is_head:\n return \"操作\"\n else:\n return mark_safe(f'<a class=\"delete-link\" href=\"javascript:void(0)\" url=\"{self.get_del_url(data_obj)}\">'\n f'<button type=\"button\" data-toggle=\"modal\" data-target=\"#myModal\"class=\"btn btn-warning btn-delete\">'\n f'删除</button></a>')\n\n def checkbox(self, data_obj=None, is_head=False):\n if is_head:\n return \"选择\"\n else:\n return mark_safe(f\"<input type='checkbox' name='checkbox_pk' value={data_obj.pk}>\")\n\n def batch_delete(self, queryset):\n queryset.delete()\n\n batch_delete.short_description = \"快捷删除选中项\"\n\n def new_list_display(self):\n new_list = []\n new_list.extend(self.list_display)\n if not self.list_display_links:\n new_list.append(ModelStark.edit)\n new_list.append(ModelStark.delete)\n new_list.insert(0, ModelStark.checkbox)\n return new_list\n\n def get_search_condition(self, request):\n condition = request.GET.get('tj')\n search_condition = Q()\n if condition:\n search_condition.connector = \"or\"\n for field in self.search_fields:\n search_condition.children.append((f\"{field}__icontains\", condition))\n return search_condition\n\n def get_filter_condition(self, request):\n condition_dict = request.GET\n filter_condition = Q()\n for condition, val in condition_dict.items():\n if condition in ['page', 'tj']:\n pass\n else:\n filter_condition.children.append((condition, val))\n return filter_condition\n\n def listview(self, request):\n\n # 批量操作\n if request.method == \"POST\":\n print(666)\n pk_list = request.POST.getlist('checkbox_pk')\n queryset = self.model.objects.filter(pk__in=pk_list)\n action_name = request.POST.get(\"action\")\n try:\n action = getattr(self, action_name)\n action(queryset)\n except:\n code = 1\n\n # 添加数据的url,给前端添加button的\n add_url = self.get_add_url()\n # 数据库查询出当数据前表的所有数据\n data_list = self.model.objects.all()\n\n # 调用get_search_condition方法获取search查询条件\n search_conditions = self.get_search_condition(request)\n # 调用get_filter_condition方法获取filter的查询条件\n filter_conditions = self.get_filter_condition(request)\n # 过滤,找出符合要求的数据\n new_data_list = data_list.filter(search_conditions).filter(filter_conditions)\n\n # 调用视图展示类实例化来生成类对象\n listview_obj = ListView(self, request, new_data_list)\n\n # 调用试图类对象生成数据体的方法生成数据\n obj_list = listview_obj.create_body()\n\n # 分页组件实例化传参\n page_obj = Page(total_num=len(obj_list), page_num=request.GET.get(\"page\", 1), request=request,\n every_page_num=10)\n # 根据分页拿到的start和end切片得到所要的数据\n obj_list = obj_list[page_obj.start:page_obj.end]\n # 调用html方法得到分页的html代码片段\n page_html = page_obj.html\n\n return render(request, 'stark/list_view.html', locals())\n\n def get_model_form_class(self):\n class ModelForm(forms.ModelForm):\n class Meta:\n model = self.model\n fields = \"__all__\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field in iter(self.fields):\n self.fields[field].widget.attrs.update({\n 'class': 'form-control'\n })\n\n return ModelForm\n\n def get_new_form(self, form):\n from django.forms.models import ModelChoiceField\n for form_field in form:\n # print('-------------------->',form_field)\n # form_field.field用来从form表单中获得每个字段的类型\n if isinstance(form_field.field, ModelChoiceField):\n print(type(form_field.field))\n form_field.is_pop = True\n # form_field.name用来从form表单中获得字段的名称\n rel_model = self.model._meta.get_field(form_field.name).rel.to\n model_name = rel_model._meta.model_name\n app_label = rel_model._meta.app_label\n _url = reverse(\"%s_%s_add\" % (app_label, model_name))\n form_field.url = _url\n\n form_field.pop_back_id = \"id_\" + form_field.name\n\n return form\n\n def addview(self, request):\n ModelFormClass = self.get_model_form_class()\n if request.method == 'POST':\n form_obj = ModelFormClass(request.POST)\n form_obj = self.get_new_form(form_obj)\n if form_obj.is_valid():\n obj = form_obj.save()\n is_pop = request.GET.get('pop')\n if is_pop:\n text = str(obj)\n pk = obj.pk\n return render(request, \"stark/pop.html\", locals())\n else:\n return redirect(self.get_check_url())\n return render(request, 'stark/addview.html', locals())\n\n form = ModelFormClass()\n form_obj = self.get_new_form(form)\n return render(request, 'stark/addview.html', locals())\n\n def changeview(self, request, id):\n ModelFormClass = self.get_model_form_class()\n # 获取当前要编辑的对象\n edit_obj = self.model.objects.get(pk=id)\n if request.method == \"POST\":\n form = ModelFormClass(data=request.POST, instance=edit_obj)\n if form.is_valid():\n form.save() # update\n return redirect(self.get_check_url())\n return render(request, 'stark/changeview.html', locals())\n\n form_obj = ModelFormClass(instance=edit_obj)\n form_obj = self.get_new_form(form_obj)\n return render(request, 'stark/changeview.html', locals())\n\n def delview(self, request, id):\n check_url = self.get_check_url()\n self.model.objects.get(pk=id).delete()\n return redirect(check_url)\n\n def get_urls(self):\n model_name = self.model._meta.model_name\n app_label = self.model._meta.app_label\n temp = [\n url(r\"^$\", self.listview, name=f'{app_label}_{model_name}_check'),\n url(r\"add/$\", self.addview, name=f'{app_label}_{model_name}_add'),\n url(r\"(\\d+)/change/$\", self.changeview, name=f'{app_label}_{model_name}_change'),\n url(r\"(\\d+)/delete/$\", self.delview, name=f'{app_label}_{model_name}_delete'),\n\n ]\n return temp\n\n @property\n def urls(self):\n return self.get_urls(), None, None\n\n\nclass StarkSite(object):\n def __init__(self):\n # 定义一个字典用于存储接下来需要注册的model和对应congfig配置类\n self._registry = {}\n\n def register(self, model, admin_class=None):\n # 设置配置类,有自定义的就用自定义的,没有就用默认的ModelStark\n if not admin_class:\n admin_class = ModelStark\n # 以model为键,配置类实例化对象为值进行注册\n self._registry[model] = admin_class(model)\n\n def get_urls(self):\n temp = []\n\n # self._registry是以model为键,config_obj配置类实例化对象为值进行注册后的字典容器\n for model, config_obj in self._registry.items():\n # 通过模型表model的._meta方法得到动态的、注册的、model的名字和model所属的app名\n model_name = model._meta.model_name\n app_label = model._meta.app_label\n # \"%s/%s/\" % (app_label, model_name)字符串拼接先得到所需路径的前边部分'app/model/'\n # config_obj.urls为通过配置类对象调用配置类下的urls方法来得到相应model表的增删改查url\n temp.append(url(r\"%s/%s/\" % (app_label, model_name), config_obj.urls))\n\n return temp\n\n @property\n def urls(self):\n return self.get_urls(), None, None\n\n\nsite = StarkSite()\n","sub_path":"servers/site.py","file_name":"site.py","file_ext":"py","file_size_in_byte":13926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"481440603","text":"\n\nimport cv2\nimport numpy as np\n#import matplotlib.pyplot as plt\n#import matplotlib.image as zpimg\n\nimg = cv2.imread('sign.jpeg')\nimgee = img\n\nhsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\nlowerRange= np.array([0,100,100]) \nupperRange= np.array([10,255,255]) \nlowerBound= np.array([160,100,100])\nupperBound= np.array([179,255,255])\n \ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nret, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)\n#create mask\nheight,width = imgee.shape\nmask=np.zeros((height,width),np.uint8)\n\n#to change size of the image\nimage = cv2.resize(img,(360,240))\n\n#object=cv2.inRange(hsv,lowerRange,upperRange)\nobject=cv2.inRange(hsv,lowerBound,upperBound)\n#it allows pixels within range and black out other\ncv2.imshow('first',thresh)\nedged=cv2.Canny(object,30,150)\n\ncontours, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\nfor c in contours:\n\tprint (c)\n\tbreak;\n\nfinal=cv2.drawContours(img,contours,0,(255,0,0),0)\ncv2.imshow('wrw',final)\nobject1=cv2.inRange(img,(255,0,0),(255,0,0))\ncv2.imshow('object1',object1)\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nret, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)\nedged1=cv2.Canny(thresh,100,200)\ncv2.imshow('Edge',edged1)\n\ncircles=cv2.HoughCircles(edged1,cv2.HOUGH_GRADIENT,1,50,param1=50,param2=20,minRadius=50,maxRadius=750)\nfor i in circles[0,:]:\n\ti[2]=i[2]+4\n\t\t#draw on mask\n\tcv2.circle(mask,(i[0],i[1]),i[2],(255,255,255),-1)\n#copy that image using that mask\nmasked_data=cv2.bitwise_and(img,img,mask=mask)\n\n#apply threshold\n_,thresh = cv2.threshold(mask,1,255,cv2.THRESH_BINARY)\n\n#Find Contour\ncnts,_=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\nx,y,w,h =cv2.boundingRect(contours[0])\n\n#crop masked data\ncrop=masked_data[y:y+h,x:x+w]\n\n\n#cv2.rectangle(img,(83,64),(150,170),(0,255,0),3)\ncv2.imshow('orginal',img)\ncv2.imshow('HSV',hsv)\ncv2.imshow('CROP',crop)\ncv2.imshow('mask', object)\ncv2.imshow('edged',edged)\ncv2.imshow('thresh',thresh)\ncv2.imshow('object2',object1)\n\ncv2.waitKey(0)\n\n\n","sub_path":"circle_crop (copy).py","file_name":"circle_crop (copy).py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"105721306","text":"class Solution:\n def spiralOrder(self, matrix: [[int]]) -> [int]:\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n m = len(matrix)\n if m == 0:\n return []\n n = len(matrix[0])\n ret = []\n row_start = 0\n row_end = m - 1\n col_start = 0\n col_end = n - 1\n while row_start <= row_end and col_start <= col_end:\n for j in range(col_start, col_end + 1):\n ret += [matrix[row_start][j]]\n row_start += 1\n for j in range(row_start, row_end + 1):\n ret += [matrix[j][col_end]]\n col_end -= 1\n if row_start <= row_end:\n for j in range(col_end, col_start - 1, -1):\n ret += [matrix[row_end][j]]\n row_end -= 1\n if col_start <= col_end:\n for j in range(row_end, row_start - 1, -1):\n ret += [matrix[j][col_start]]\n col_start += 1\n return ret\n\nprint(Solution().spiralOrder([[2,3]]))","sub_path":"Solutions/54SpiralMatrix.py","file_name":"54SpiralMatrix.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"103162985","text":"from __future__ import print_function\nimport argparse\nimport os\nimport shutil\nimport time\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nfrom pprint import pprint\nfrom torch.autograd import Variable\nimport pandas as pd\nimport numpy as np\nimport random\nfrom warnings import warn\n\nfrom wideresnet import WideResNet\nfrom datetime import datetime\ntoday_datetime = datetime.now().isoformat()[:10]\ntoday = '2017-09-12'\nif today != today_datetime:\n warn('Is today set correctly?')\n\n\n# used for logging to TensorBoard\nif False:\n from tensorboard_logger import configure, log_value\n\nuse_cuda = torch.cuda.is_available()\nparser = argparse.ArgumentParser(description='PyTorch WideResNet Training')\nparser.add_argument('--dataset', default='cifar10', type=str,\n help='dataset (cifar10 [default] or cifar100)')\nparser.add_argument('--epochs', default=200, type=int,\n help='number of total epochs to run')\nparser.add_argument('--start-epoch', default=0, type=int,\n help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch-size', default=512, type=int,\n help='mini-batch size (default: 512)')\nparser.add_argument('--lr', '--learning-rate', default=0.1, type=float,\n help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, help='momentum')\nparser.add_argument('--nesterov', default=True, type=bool, help='nesterov momentum')\nparser.add_argument('--weight-decay', '--wd', default=5e-4, type=float,\n help='weight decay (default: 5e-4)')\nparser.add_argument('--print-freq', '-p', default=10, type=int,\n help='print frequency (default: 10)')\nparser.add_argument('--layers', default=28, type=int,\n help='total number of layers (default: 28)')\nparser.add_argument('--widen-factor', default=10, type=int,\n help='widen factor (default: 10)')\nparser.add_argument('--droprate', default=0, type=float,\n help='dropout probability (default: 0.0)')\nparser.add_argument('--no-augment', dest='augment', action='store_false',\n help='whether to use standard augmentation (default: True)')\nparser.add_argument('--resume', default='', type=str,\n help='path to latest checkpoint (default: none)')\nparser.add_argument('--name', default='WideResNet-28-10', type=str,\n help='name of experiment')\nparser.add_argument('--tensorboard', default=False,\n help='Log progress to TensorBoard', action='store_true')\nparser.add_argument('--num_workers', default=1, help='Number of workers', type=int)\nparser.add_argument('--seed', default=42, help='Random seed', type=int)\n\nparser.set_defaults(augment=True)\nargs = parser.parse_args()\nargs.use_cuda = use_cuda\n\ndef _set_visible_gpus(num_gpus, verbose=True):\n gpus = list(range(torch.cuda.device_count()))\n devices = gpus[:num_gpus]\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = ','.join([str(g) for g in devices])\n if verbose:\n print(\"CUDA_VISIBLE_DEVICES={}\".format(os.environ[\"CUDA_VISIBLE_DEVICES\"]))\n return devices\n\n\ndevice_ids = _set_visible_gpus(args.num_workers)\ncuda_kwargs = {'async': True}\n\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\nrandom.seed(args.seed)\n\nbest_prec1 = 0\n\n\ndef _mkdir(dir):\n if not os.path.isdir(dir):\n os.mkdir(dir)\n return True\n \ndef _write_csv(df, id=''):\n filename = f'output/{today}/{id}.csv'\n _mkdir('output')\n _mkdir(f'output/{today}')\n df.to_csv(filename)\n return True\ndef main():\n global args, best_prec1, data\n if args.tensorboard: configure(\"runs/%s\"%(args.name))\n\n # Data loading code\n normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],\n std=[x/255.0 for x in [63.0, 62.1, 66.7]])\n\n if args.augment:\n transform_train = transforms.Compose([\n \ttransforms.ToTensor(),\n \ttransforms.Lambda(lambda x: F.pad(\n \t\t\t\t\t\tVariable(x.unsqueeze(0), requires_grad=False, volatile=True),\n \t\t\t\t\t\t(4,4,4,4),mode='reflect').data.squeeze()),\n transforms.ToPILImage(),\n transforms.RandomCrop(32),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])\n else:\n transform_train = transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ])\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n\n kwargs = {'num_workers': args.num_workers, 'pin_memory': use_cuda}\n assert(args.dataset == 'cifar10' or args.dataset == 'cifar100')\n print(\"Creating the DataLoader...\")\n train_loader = torch.utils.data.DataLoader(\n datasets.__dict__[args.dataset.upper()]('../data', train=True, download=True,\n transform=transform_train),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n val_loader = torch.utils.data.DataLoader(\n datasets.__dict__[args.dataset.upper()]('../data', train=False, transform=transform_test),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n\n # create model\n print(\"Creating the model...\")\n model = WideResNet(args.layers, args.dataset == 'cifar10' and 10 or 100,\n args.widen_factor, dropRate=args.droprate)\n\n # get the number of model parameters\n print('Number of model parameters: {}'.format(\n sum([p.data.nelement() for p in model.parameters()])))\n\n # for training on multiple GPUs.\n # Use CUDA_VISIBLE_DEVICES=0,1 to specify which GPUs to use\n if use_cuda:\n print(\"Moving the model to the GPU\")\n model = torch.nn.DataParallel(model, device_ids=device_ids)\n model = model.cuda()\n #model = model.cuda()\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_prec1 = checkpoint['best_prec1']\n model.load_state_dict(checkpoint['state_dict'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n cudnn.benchmark = True\n\n # define loss function (criterion) and optimizer\n\n criterion = nn.CrossEntropyLoss()\n if use_cuda:\n criterion = criterion.cuda()\n #optimizer = torch.optim.SGD(model.parameters(), args.lr,\n # momentum=args.momentum, nesterov=args.nesterov,\n # weight_decay=args.weight_decay)\n optimizer = torch.optim.ASGD(model.parameters(), args.lr)\n\n data = []\n train_time = 0\n for epoch in range(args.start_epoch, args.epochs):\n adjust_learning_rate(optimizer, epoch+1)\n\n # train for one epoch\n start = time.time()\n train(train_loader, model, criterion, optimizer, epoch)\n train_time += time.time() - start\n\n # evaluate on validation set\n datum = validate(val_loader, model, criterion, epoch)\n data += [{'train_time': train_time,\n 'epoch': epoch + 1, **vars(args), **datum}]\n df = pd.DataFrame(data)\n _write_csv(df, id=f'{args.num_workers}_{args.seed}')\n pprint({k: v for k, v in data[-1].items() if k in ['train_time', 'num_workers',\n 'test_loss', 'test_acc', 'epoch']})\n prec1 = datum['test_acc']\n\n # remember best prec@1 and save checkpoint\n is_best = prec1 > best_prec1\n best_prec1 = max(prec1, best_prec1)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'best_prec1': best_prec1,\n }, is_best)\n print('Best accuracy: ', best_prec1)\n\ndef train(train_loader, model, criterion, optimizer, epoch):\n \"\"\"Train for one epoch on the training set\"\"\"\n batch_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n\n # switch to train mode\n model.train()\n\n end = time.time()\n pbar = tqdm(enumerate(train_loader))\n start = time.time()\n for i, (input, target) in pbar:\n if use_cuda:\n target = target.cuda(**cuda_kwargs)\n input = input.cuda(**cuda_kwargs)\n input_var = torch.autograd.Variable(input)\n target_var = torch.autograd.Variable(target)\n\n # compute output\n output = model(input_var)\n loss = criterion(output, target_var)\n\n # measure accuracy and record loss\n prec1 = accuracy(output.data, target, topk=(1,))[0]\n losses.update(loss.data[0], input.size(0))\n top1.update(prec1[0], input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n p = 100 * i / len(train_loader)\n pbar.set_description(f'loss={losses.avg:.3f}, acc={top1.avg:.3f} {p:.1f}%')\n # log to TensorBoard\n if args.tensorboard:\n log_value('train_loss', losses.avg, epoch)\n log_value('train_acc', top1.avg, epoch)\n\ndef validate(val_loader, model, criterion, epoch):\n \"\"\"Perform validation on the validation set\"\"\"\n batch_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n pbar = tqdm(enumerate(val_loader))\n for i, (input, target) in pbar:\n target = target.cuda(**cuda_kwargs)\n input = input.cuda(**cuda_kwargs)\n input_var = torch.autograd.Variable(input, volatile=True)\n target_var = torch.autograd.Variable(target, volatile=True)\n\n # compute output\n output = model(input_var)\n loss = criterion(output, target_var)\n\n # measure accuracy and record loss\n prec1 = accuracy(output.data, target, topk=(1,))[0]\n losses.update(loss.data[0], input.size(0))\n top1.update(prec1[0], input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n p = 100 * i / len(val_loader)\n pbar.set_description(f'loss={losses.avg:.3f}, acc={top1.avg:.3f} {p:.1f}%')\n\n #print(' * Prec@1 {top1.avg:.3f}'.format(top1=top1))\n # log to TensorBoard\n if args.tensorboard:\n log_value('val_loss', losses.avg, epoch)\n log_value('val_acc', top1.avg, epoch)\n return {'test_loss': losses.avg,\n 'test_acc': top1.avg}\n\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n \"\"\"Saves checkpoint to disk\"\"\"\n directory = \"runs/%s/\"%(args.name)\n if not os.path.exists(directory):\n os.makedirs(directory)\n filename = directory + filename\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'runs/%s/'%(args.name) + 'model_best.pth.tar')\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef adjust_learning_rate(optimizer, epoch):\n \"\"\"Sets the learning rate to the initial LR divided by 5 at 60th, 120th and 160th epochs\"\"\"\n lr = args.lr * ((0.2 ** int(epoch >= 60)) * (0.2 ** int(epoch >= 120))* (0.2 ** int(epoch >= 160)))\n # log to TensorBoard\n if args.tensorboard:\n log_value('learning_rate', lr, epoch)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(1 / batch_size))\n return res\n\nif __name__ == '__main__':\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":12713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"19447607","text":"from numpy import cos, arccos, sin, arctan, tan, tanh, pi, sqrt; from numpy import array as ary; import numpy as np; tau = 2*pi\nfrom particlerelax import Point, F_LIMIT, REF_STEP_SIZE, quadrature\nfrom SimpleMapping import circle_to_sextant, tessellate_circle_properly, rotate_list_of_points\nfrom scipy.stats import describe\nimport logging\nlogger = logging.getLogger(__name__) #created logger with NOSET level of logging, i.e. all messages are recorded.\nlogger.setLevel(logging.DEBUG)\nlogHandler = logging.FileHandler('interframe_relax.log')\nhandler = logger.addHandler(logHandler)\n\nREF_STEP_SIZE = 0.5\nSTART_FROM_PRISTINE = False\nRESOLUTION = 10\n\ndef str2array(l):\n p=0\n text = ['',]*l.count(']') \n for i in l: \n if i==']': \n p += 1 \n elif i =='[': \n pass \n else: \n text[p] += i \n return ary([np.fromstring(entry.lstrip(', '), sep=',') for entry in text])\n\ndef attract_kernel(x):\n return -tanh(x*2/pi)\n\nclass Slice:\n def __init__(self, list_of_points, ak=attract_kernel):\n self.points = []\n self.ak_raw = ak\n\n for p in list_of_points:\n #each one should be a Point object\n self.points.append(p)\n self.num_points = len(self.points)\n \n def attract_kernel(self, disp):\n return self.ak_raw(disp) # no scaling needed\n \n def walk(self, final_force_array):\n for i in range(self.num_points):\n self.points[i].walk(final_force_array[i])\n '''\n def get_full_internal_forces(self):\n return [ p.get_force_raw(self.points) for p in self.points]\n \n def get_total_force_raw(self, slice_above, slice_below):\n force_list = self.get_full_internal_forces()\n for i in range(self.num_points):\n disp_above = slice_above.points[i].pos - self.points[i].pos\n disp_below = slice_below.points[i].pos - self.points[i].pos\n force_list[i] = np.append(force_list[i], [self.ak_raw(disp_above), self.ak_raw(disp_below)], axis=0)\n return force_list\n '''\n def get_internal_force(self):\n return [ ary(p.get_force(self.points)) for p in self.points ]\n \n def get_total_force(self, slice_above, slice_below):\n force_list = self.get_internal_force()\n total_force = []\n for i in range(self.num_points):\n disp_above = slice_above.points[i].pos - self.points[i].pos\n disp_below = slice_below.points[i].pos - self.points[i].pos\n force_above = self.attract_kernel(disp_above)\n force_below = self.attract_kernel(disp_below)\n averaged_forces = (force_list[i] + force_above + force_below)/3\n total_force.append(averaged_forces)\n return total_force\n\nif __name__=='__main__':\n if START_FROM_PRISTINE:\n circle = tessellate_circle_properly(417)\n data = []\n for theta in np.linspace(0, tau, RESOLUTION):\n rotated_circle = rotate_list_of_points(circle, theta)\n transformed_list = circle_to_sextant(rotated_circle)\n data.append(rotated_circle)\n else:\n with open('single_cable_data.txt', 'r') as f:\n data = ('').join(f.readlines()).replace('\\n','').replace(']],',']]\\n').split('\\n')\n data = [i for i in data if len(i)>3] #at least 3 characters long string is needed\n step_size = len(data)//RESOLUTION\n data_trimmed = ary([ str2array(dat_line[1:-1]) for dat_line in data])[::step_size]\n\n #create a column containing {RESOLUTION} number of slices\n column = []\n for cross_section in data_trimmed:\n column.append( Slice([ Point(pos) for pos in cross_section ]))\n\n step = 0\n des = describe([1,1]) #create dummy des object to start the loop\n while des.minmax[1] > F_LIMIT and des.mean > F_LIMIT/2.5:\n column_force = []\n for i in range(len(column)):\n below = i-1\n above = (i+1)%len(column)\n column_force.append( column[i].get_total_force(column[below], column[above]) )\n des = describe( [quadrature(xy) for xy in np.concatenate(column_force)] )\n logger.debug(\"Step {0} has a mean force of {1} with bounds of {2} and skewness={3}\".format( step, des.mean, des.minmax, des.skewness) )\n\n for i in range(len(data_trimmed)):\n column[i].walk( ary(column_force)[i]*REF_STEP_SIZE )\n logger.info(\"finished step \"+str(step))\n np.save('simple_attract_result.npy', column)\n step += 1 ","sub_path":"interframeattract_simple.py","file_name":"interframeattract_simple.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"244154443","text":"# !/usr/bin/env python\r\n# -- coding: utf-8 --\r\n# @Time : 2023/3/8 17:10\r\n# @Author : liumin\r\n# @File : ptq_demo.py\r\n\r\nimport torch\r\nimport torch.nn as nn\r\n\r\n\r\nclass PTQ_Torch():\r\n def __init__(self):\r\n self.data_dir = '/home/lmin/data/hymenoptera/val'\r\n self.model_dir = 'ckpt/mobilenet_v2_train.pt'\r\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n # weight quantization parameters\r\n self.w_scheme = 'minmax' # org: 0.9216, 'mse': 0.9085 --> 0.9150 'minmax': 0.9020 --> 0.9085 'kl_divergence':\r\n self.w_bit = 8\r\n self.b_bit = 8\r\n\r\n # activation quantization parameters\r\n self.a_scheme = 'minmax'\r\n self.a_bit = 8\r\n\r\n def load_data(self):\r\n data_transform = transforms.Compose([\r\n transforms.Resize(224),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ])\r\n image_dataset = datasets.ImageFolder(self.data_dir, data_transform)\r\n dataload = torch.utils.data.DataLoader(image_dataset, batch_size=1, shuffle=False, num_workers=4)\r\n return dataload\r\n\r\n\r\n def load_model(self):\r\n model = MobileNetV2('mobilenet_v2', classifier=True)\r\n num_ftrs = model.fc[1].in_features\r\n model.fc[1] = nn.Linear(num_ftrs, 2)\r\n model.load_state_dict(torch.load(self.model_dir, map_location='cpu'))\r\n return model\r\n\r\n\r\n def model_accuracy(self, model, dataload):\r\n print('-' * 10)\r\n # Each epoch has a training and validation phase\r\n model.eval() # Set model to evaluate mode\r\n\r\n running_corrects = 0\r\n # Iterate over data.\r\n for inputs, labels in dataload:\r\n inputs = inputs.to(self.device)\r\n labels = labels.to(self.device)\r\n\r\n # forward\r\n # track history if only in train\r\n with torch.set_grad_enabled(False):\r\n outputs = model(inputs)\r\n _, preds = torch.max(outputs, 1)\r\n\r\n running_corrects += torch.sum(preds == labels.data)\r\n\r\n acc = running_corrects.double() / len(dataload.dataset)\r\n return acc\r\n\r\n\r\n def fuse(self, model):\r\n # print('step 1: model fuse and optimize.')\r\n layer_fuse_pairs = get_input_sequences(model)\r\n register_fuse_params_to_prev_layers(model, layer_fuse_pairs)\r\n # print(layer_fuse_pairs)\r\n\r\n replace_quant_ops(model, self.w_bit, self.w_scheme, self.b_bit, self.a_bit, self.a_scheme)\r\n\r\n model.apply(fuse_model)\r\n return model\r\n\r\n\r\n def weight_quantize(self):\r\n pass\r\n\r\n\r\n def activation_quantize(self):\r\n pass\r\n\r\n\r\n def run(self):\r\n dataload = self.load_data()\r\n model = self.load_model()\r\n model.to(self.device)\r\n model.eval()\r\n\r\n acc = self.model_accuracy(model, dataload)\r\n print('float model Acc: {:.4f}'.format(acc))\r\n\r\n model = self.fuse(model)\r\n acc = self.model_accuracy(model, dataload)\r\n print('fuse model Acc: {:.4f}'.format(acc))\r\n\r\n # model.apply(run_calibration(calibration=True))\r\n # 3 replace_quant_to_brecq_quant(model)\r\n # model.apply(set_quant_mode(quantized=True))\r\n\r\n acc = self.model_accuracy(model, dataload)\r\n print('quant model Acc: {:.4f}'.format(acc))\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n ptq_torch = PTQ_Torch()\r\n ptq_torch.run()\r\n print('done!')","sub_path":"quantization/ptq/ptq_demo.py","file_name":"ptq_demo.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"194775653","text":"import random\r\nanswer = input(\"Press enter to roll the dice \")\r\nagain = 1\r\n\r\nwhile again == 1:\r\n if answer == \"\":\r\n print(\"What is the largest number you'd like your dice to be able to roll?\")\r\n number = input()\r\n print(\"You rolled a \" + str(random.randint(1, int(number))))\r\n choice = input(\"Would you like to try again? Y/N: \")\r\n if choice == \"Y\":\r\n again = 1\r\n elif choice == \"y\":\r\n again = 1\r\n else:\r\n again = 2","sub_path":"dice2.py","file_name":"dice2.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"352938828","text":"import json\nimport os\nfrom tencentcloud.common import credential\nfrom tencentcloud.common.profile.client_profile import ClientProfile\nfrom tencentcloud.common.profile.http_profile import HttpProfile\nfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException\nfrom tencentcloud.scf.v20180416 import scf_client, models\n\ndef main_handler(event, context):\n try: \n provision_params = json.loads(event['Message'])\n if len(provision_params) < 4:\n return (\"Missing parameters\")\n cred = credential.Credential(os.environ.get('TENCENTCLOUD_SECRETID'), os.environ.get('TENCENTCLOUD_SECRETKEY'), os.environ.get('TENCENTCLOUD_SESSIONTOKEN')) \n httpProfile = HttpProfile()\n httpProfile.endpoint = \"scf.tencentcloudapi.com\"\n\n clientProfile = ClientProfile()\n clientProfile.httpProfile = httpProfile\n client = scf_client.ScfClient(cred, provision_params[\"Region\"], clientProfile) \n\n req = models.PutProvisionedConcurrencyConfigRequest()\n params = {\n \"FunctionName\": provision_params.get(\"FunctionName\"),\n \"Namespace\": provision_params.get(\"Namespace\"),\n \"Qualifier\": provision_params.get(\"Qualifier\"),\n \"VersionProvisionedConcurrencyNum\": provision_params.get(\"VersionProvisionedConcurrencyNum\")\n }\n req.from_json_string(json.dumps(params))\n\n resp = client.PutProvisionedConcurrencyConfig(req) \n print(resp.to_json_string()) \n\n except TencentCloudSDKException as err: \n print(err) \n return(\"Hello Serverless\")","sub_path":"Python3.6-TimingProvisioned/src/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458729240","text":"import numpy as n\r\n\r\n\r\n# Multideminsional Array\r\n# without Numpy Mutli Array is not supported.\r\n\r\nmyMarks = n.array([\r\n [1,2,3],\r\n [3,2,1],\r\n [3,6,9]\r\n ])\r\n\r\n\r\nprint(myMarks)\r\nflatMarks = myMarks.flatten() # Combine all arrays in one big array\r\nprint(flatMarks)\r\n\r\n# reMarks = flatMarks.reshape(2,2,3) # Combine all arrays in one big array\r\n# print(reMarks)\r\n\r\nmyMatrix = n.matrix('1 2 3 ; 4 5 6 ; 7 8 9')\r\nmyMatrix2 = n.matrix('1 2 3 ; 4 5 6 ; 7 8 9')\r\nprint(myMatrix)\r\n\r\nprint(myMatrix + myMatrix2)\r\n\r\n\r\n","sub_path":"Python/20MultiArrayWithNumpy.py","file_name":"20MultiArrayWithNumpy.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"190324337","text":"# driver.page_source 当前标签页浏览器渲染之后的网页源代码\r\n# driver.current_url 当前标签页的url\r\n# driver.close() 关闭当前标签页,如果只有一个标签页则关闭整个浏览器\r\n# driver.quit() 关闭浏览器\r\n# driver.forward() 页面前进\r\n# driver.back() 页面后退\r\n# driver. save_screenshot() 页面截图\r\n\r\nimport time\r\nfrom selenium import webdriver\r\n\r\nurl = 'http://www.baidu.com'\r\n\r\n# 创建一个浏览器对象\r\ndriver = webdriver.Chrome()\r\n\r\n# 访问指定的url地址\r\ndriver.get(url)\r\n\r\n# 显示源码\r\nprint(driver.page_source)\r\n# 显示响应对应的url\r\nprint(driver.current_url)\r\nprint(driver.title)\r\n\r\ntime.sleep(2)\r\n\r\ndriver.get('https://www.douban.com')\r\ntime.sleep(2)\r\n# 后退\r\ndriver.back()\r\ntime.sleep(2)\r\n# 前进\r\ndriver.forward()\r\n\r\ntime.sleep(2)\r\n# 保存网页快照,常用于验证是否运行或者验证码截图\r\ndriver.save_screenshot('douban.png')\r\n# 关闭当前标签\r\ndriver.close()\r\n# 关闭浏览器\r\ndriver.quit()\r\n","sub_path":"Project/爬虫/3.selenium框架/2.driver属性和方法.py","file_name":"2.driver属性和方法.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"377334969","text":"def tens(number):\r\n\tif number == 2:\r\n\t\treturn len(\"twenty\")\r\n\telif number == 3:\r\n\t\treturn len(\"thirty\")\r\n\telif number == 4:\r\n\t\treturn len(\"forty\")\r\n\telif number == 5:\r\n\t\treturn len(\"fifty\")\r\n\telif number == 6:\r\n\t\treturn len(\"sixty\")\r\n\telif number == 7:\r\n\t\treturn len(\"seventy\")\r\n\telif number == 8:\r\n\t\treturn len(\"eighty\")\r\n\telif number == 9:\r\n\t\treturn len(\"ninety\")\r\n\r\ndef teens(number):\r\n\tif number == 10:\r\n\t\treturn len(\"ten\")\r\n\telif number == 1:\r\n\t\treturn len(\"eleven\")\r\n\telif number == 2:\r\n\t\treturn len(\"twelve\")\r\n\telif number == 3:\r\n\t\treturn len(\"thirteen\")\r\n\telif number == 4:\r\n\t\treturn len(\"fourteen\")\r\n\telif number == 5:\r\n\t\treturn len(\"fifteen\")\r\n\telif number == 6:\r\n\t\treturn len(\"sixteen\")\r\n\telif number == 7:\r\n\t\treturn len(\"seventeen\")\r\n\telif number == 8:\r\n\t\treturn len(\"eighteen\")\r\n\telif number == 9:\r\n\t\treturn len(\"nineteen\")\r\n\r\ndef ones(number):\r\n\tif number == 1:\r\n\t\treturn len(\"one\")\r\n\telif number == 2:\r\n\t\treturn len(\"two\")\r\n\telif number == 3:\r\n\t\treturn len(\"three\")\r\n\telif number == 4:\r\n\t\treturn len(\"four\")\r\n\telif number == 5:\r\n\t\treturn len(\"five\")\r\n\telif number == 6:\r\n\t\treturn len(\"six\")\r\n\telif number == 7:\r\n\t\treturn len(\"seven\")\r\n\telif number == 8:\r\n\t\treturn len(\"eight\")\r\n\telif number == 9:\r\n\t\treturn len(\"nine\")\r\n\t\r\nletterCount = 0\t\r\nremainder = 0\r\nnum = 0\r\n\t\r\nfor i in range(1, 1001, 1):\r\n\tif i == 1000:\r\n\t\tletterCount += len(\"one\") + len(\"thousand\")\r\n\telif (i / 100) >= 1:\r\n\t\tnum = (i / 100)\r\n\t\tremainder = i % 100\r\n\t\tletterCount += len(\"hundred\")\r\n\t\tletterCount += ones(int(num))\r\n\t\tif (remainder / 10) >= 2:\r\n\t\t\tnum = (remainder / 10)\r\n\t\t\tremainder = (remainder % 10)\r\n\t\t\tletterCount += tens(int(num))\r\n\t\t\tletterCount += len(\"and\")\r\n\t\t\tif (remainder > 0):\r\n\t\t\t\tletterCount += ones(remainder)\r\n\t\telif (remainder / 10) == 1:\r\n\t\t\tletterCount += teens(remainder)\r\n\t\t\tletterCount += len(\"and\")\r\n\t\telif (remainder / 10) > 1:\r\n\t\t\tnum = remainder % 10\r\n\t\t\tletterCount += teens(num)\r\n\t\t\tletterCount += len(\"and\")\r\n\t\telif remainder > 0:\r\n\t\t\tletterCount += ones(remainder)\r\n\t\t\tletterCount += len(\"and\")\r\n\telif (i / 10) >= 2:\r\n\t\tnum = (i / 10)\r\n\t\tremainder = i % 10\r\n\t\tletterCount += tens(int(num))\r\n\t\tif (remainder > 0):\r\n\t\t\tletterCount += ones(remainder)\r\n\telif (i / 10) == 1:\r\n\t\tletterCount += teens(i)\r\n\telif (i / 10) > 1:\r\n\t\tremainder = i % 10\r\n\t\tletterCount += teens(remainder)\r\n\telif (i / 1) >= 1:\r\n\t\tletterCount += ones(i)\r\n\t\t\r\nprint(letterCount)","sub_path":"NumberLetterCounts.py","file_name":"NumberLetterCounts.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"72503964","text":"#!/usr/bin/env python3\nimport sys\n\nSHELLCODE = input(\"Shellcode: \")\nXOR_BY = 0xaa\n\nresult_c = \"\"\nresult_nasm = \"\"\n\nfor i in range(0, len(SHELLCODE), 4):\n byte = int(SHELLCODE[i+2:i+4], 16)\n byte = ~byte & 255\n result_c += \"\\\\x\" + hex(byte)[2:]\n result_nasm += hex(byte) + \",\"\n\nresult_nasm = result_nasm[:-1]\n\nprint()\nprint(result_c)\nprint()\nprint(result_nasm)\nprint()\nprint(\"Length:\", len(SHELLCODE) // 4)\n","sub_path":"not_encode.py","file_name":"not_encode.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"145582944","text":"from django.db import models\nfrom users.models import GroovyUser as User\n\n# Create your models here.\n\nclass Playlist(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n name = models.CharField(max_length=100)\n rating_sum = models.IntegerField()\n rating_number = models.IntegerField()\n # extra elements needed in Playlist\n spotify_id = models.CharField(max_length=100)\n description = models.CharField(max_length=100)\n\n def __str__(self):\n return self.name\n\nclass Comment(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE)\n comment_text = models.CharField(max_length=500)\n creation_date = models.DateTimeField(auto_now_add=True, blank=True)\n\nclass Rated(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE)\n rating = models.IntegerField()\n","sub_path":"backend/groovytunes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"79595830","text":"from django.conf import settings\nfrom django.http import HttpResponse\nfrom django.views import View\nfrom django.views.generic import TemplateView\n\nimport os\nimport json\n\nfile_path = os.path.join(settings.PROJECT_ROOT, 'dashboard_script/dataset_details.json')\ndiff_path = os.path.join(settings.PROJECT_ROOT, 'dashboard_script/diffs/')\n\n\nclass DashboardView(TemplateView):\n template_name = \"dashboard.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data()\n try:\n json_detail = json.load(open(file_path, 'r'))\n except IOError:\n json_detail = dict({'dataset_details': None, 'last_checked_on': None})\n context.update({\n 'datasets': json_detail['dataset_details'],\n 'last_checked_on': json_detail['last_checked_on']\n })\n return context\n\n\nclass DiffView(View):\n\n def get(self, request, filename):\n return HttpResponse(open(os.path.join(diff_path, filename)))\n\n\nclass DataSetView(TemplateView):\n template_name = \"diff.html\"\n\n def get_context_data(self, dataset_name, **kwargs):\n context = super().get_context_data(**kwargs)\n\n try:\n json_detail = json.load(open(file_path, 'r'))['dataset_details'][dataset_name]\n except IOError:\n json_detail = dict({\"diff\": None})\n context.update({\n 'dataset': str(dataset_name).strip(),\n 'dataset_details': json_detail\n })\n\n return context\n","sub_path":"retrieverdash/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"192068739","text":"## ircv3_2.py\n# IRCv3.2 support (in progress).\nfrom . import ircv3_1\nfrom . import tags\nfrom . import monitor\nfrom . import metadata\n\n__all__ = ['IRCv3_2Support']\n\n\nclass IRCv3_2Support(metadata.MetadataSupport, monitor.MonitoringSupport, tags.TaggedMessageSupport, ircv3_1.IRCv3_1Support):\n \"\"\" Support for some of IRCv3.2's extensions. \"\"\"\n\n ## IRC callbacks.\n\n async def on_capability_account_tag_available(self, value):\n \"\"\" Add an account message tag to user messages. \"\"\"\n return True\n\n async def on_capability_cap_notify_available(self, value):\n \"\"\" Take note of new or removed capabilities. \"\"\"\n return True\n\n async def on_capability_chghost_available(self, value):\n \"\"\" Server reply to indicate a user we are in a common channel with changed user and/or host. \"\"\"\n return True\n\n async def on_capability_echo_message_available(self, value):\n \"\"\" Echo PRIVMSG and NOTICEs back to client. \"\"\"\n return True\n\n async def on_capability_invite_notify_available(self, value):\n \"\"\" Broadcast invite messages to certain other clients. \"\"\"\n return True\n\n async def on_capability_userhost_in_names_available(self, value):\n \"\"\" Show full user!nick@host in NAMES list. We already parse it like that. \"\"\"\n return True\n\n async def on_capability_uhnames_available(self, value):\n \"\"\" Possibly outdated alias for userhost-in-names. \"\"\"\n return await self.on_capability_userhost_in_names_available(value)\n\n async def on_isupport_uhnames(self, value):\n \"\"\" Let the server know that we support UHNAMES using the old ISUPPORT method, for legacy support. \"\"\"\n await self.rawmsg('PROTOCTL', 'UHNAMES')\n\n ## API overrides.\n\n async def message(self, target, message):\n await super().message(target, message)\n if not self._capabilities.get('echo-message'):\n await self.on_message(target, self.nickname, message)\n if self.is_channel(target):\n await self.on_channel_message(target, self.nickname, message)\n else:\n await self.on_private_message(target, self.nickname, message)\n\n async def notice(self, target, message):\n await super().notice(target, message)\n if not self._capabilities.get('echo-message'):\n await self.on_notice(target, self.nickname, message)\n if self.is_channel(target):\n await self.on_channel_notice(target, self.nickname, message)\n else:\n await self.on_private_notice(target, self.nickname, message)\n\n ## Message handlers.\n\n async def on_raw(self, message):\n if 'account' in message.tags:\n nick, _ = self._parse_user(message.source)\n if nick in self.users:\n metadata = {\n 'identified': True,\n 'account': message.tags['account']\n }\n await self._sync_user(nick, metadata)\n await super().on_raw(message)\n\n async def on_raw_chghost(self, message):\n \"\"\" Change user and/or host of user. \"\"\"\n if 'chghost' not in self._capabilities or not self._capabilities['chghost']:\n return\n\n nick, _ = self._parse_user(message.source)\n if nick not in self.users:\n return\n\n # Update user and host.\n metadata = {\n 'username': message.params[0],\n 'hostname': message.params[1]\n }\n await self._sync_user(nick, metadata)\n","sub_path":"pydle/features/ircv3/ircv3_2.py","file_name":"ircv3_2.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"638988729","text":"from socket import *\n\nsockobj = socket(AF_INET, SOCK_STREAM)\nsockobj.connect(('47.92.27.90',8889))\nsockobj.send(b'20|0|1234|20170425142109|0|000||20170425|\\r\\n')\ndata = sockobj.recv(4096)\nprint(data)\nsockobj.close()\n\n# https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4ce4808f953a1b69&redirect_uri=http://smzr.emsoft.com.cn/api/gcode/&response_type=code&scope=snsapi_base&state=gquery#wechat_redirect","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"603872934","text":"from time import time\nimport math\nimport random\n\ndef maximum(num1, num2):\n \"\"\" Función para hallar el máximo entre dos números \"\"\"\n if(num1 >= num2):\n return num1\n else:\n return num2\n\n\ndef minimum(num1, num2):\n \"\"\" Función para hallar el mínimo entre dos números \"\"\"\n if(num1 < num2):\n return num1\n else:\n return num2\n\n\ndef exhaustive(num_1, num_2):\n \"\"\"Returns m.c.m by using exhaustive method\"\"\"\n initial_time = time()\n a = maximum(num_1, num_2)\n b = minimum(num_1, num_2)\n result = 0\n for i in range(a, (a*b)+1, a):\n if(i%b == 0):\n result = i\n break\n final_time = time()\n execution_time = final_time - initial_time\n return result, execution_time\n\n\ndef simple_factoring(num):\n \"\"\"Returns array with simple factors\"\"\"\n prime_vector = []\n if num <= 1:\n return prime_vector\n prime = 2\n dividend = num\n while dividend != 1:\n if dividend%prime == 0:\n dividend = dividend/prime\n prime_vector.append(prime)\n else:\n prime+=1\n return prime_vector\n\n\ndef complex_factoring(num):\n \"\"\"Returns json with factors and ocurrency\"\"\"\n prime_json = {}\n if num <= 1:\n return prime_json\n prime = 2\n dividend = num\n ocurrency = 0\n while dividend != 1:\n if dividend%prime == 0:\n dividend = dividend/prime\n ocurrency+=1\n prime_json[prime] = ocurrency\n else:\n ocurrency = 0\n prime+=1\n return prime_json\n\n\ndef factorization(num_1, num_2):\n \"\"\"Returns m.c.m by using prime factorization\"\"\"\n initial_time = time()\n num_1_complex_factoring = complex_factoring(num_1)\n num_2_complex_factoring = complex_factoring(num_2)\n sum_list = list(num_1_complex_factoring.items()) + list(num_2_complex_factoring.items())\n sorted_sum_list = sorted(sum_list, key=lambda x: (x[0], x[1]))\n vector_result = dict(sorted_sum_list)\n result = 1\n for k, v in vector_result.items():\n result = result*(math.pow(k, v))\n final_time = time()\n execution_time = final_time - initial_time\n return result, execution_time\n\n\ndef mcd(num_1, num_2):\n \"\"\" Función para hallar el mcd entre dos números \"\"\"\n a = maximum(num_1, num_2)\n b = minimum(num_1, num_2)\n while b!=0:\n res = b\n b = a%b\n a = res\n return res\n\n\ndef euclides(num1, num2):\n \"\"\" Función para hallar el mcm entre dos números por el Algoritmo de Euclides y el tiempo de ejecución\"\"\"\n initial_time = time()\n a = maximum(num1, num2)\n b = minimum(num1, num2)\n mcm = (a / mcd(a, b)) * b\n final_time = time()\n execution_time = final_time - initial_time\n return mcm, execution_time\n\n\ndef multiply_vector(vector): \n total = 1\n for x in vector:\n total *= x \n return total \n\n\ndef multi_exhaustive(vector):\n \"\"\"Returns m.c.m for n numbers by using exhaustive method\"\"\"\n initial_time = time()\n a = max(vector)\n result = 0\n zero_remainder = 0\n for i in range(a, multiply_vector(vector)+1, a):\n for j in range(0, len(vector)):\n if (i%vector[j] == 0):\n zero_remainder+=1\n else:\n zero_remainder = 0\n break\n if (zero_remainder == len(vector)):\n result = i\n break\n final_time = time()\n execution_time = final_time - initial_time\n return result, execution_time\n\n\ndef multi_factorization(vector):\n \"\"\"Returns m.c.m para n números by using prime factorization\"\"\"\n initial_time = time()\n sum_list = []\n for i in vector:\n sum_list = sum_list + list(complex_factoring(i).items())\n sorted_sum_list = sorted(sum_list, key=lambda x: (x[0], x[1]))\n vector_result = dict(sorted_sum_list)\n result = 1\n for k, v in vector_result.items():\n result = result*(math.pow(k, v))\n final_time = time()\n execution_time = final_time - initial_time\n return result, execution_time\n\n\ndef multi_euclides(vector):\n \"\"\" Función para hallar el mcm para n números por el Algoritmo de Euclides\"\"\"\n initial_time = time()\n mcm = vector[0]\n for i in vector[1:]:\n mcm = (mcm*i)/mcd(mcm, i)\n final_time = time()\n execution_time = final_time - initial_time\n return mcm, execution_time\n \n\ndef big_multi_factorization(vector):\n \"\"\"Returns m.c.m para n números en vectores grandes by using prime factorization\"\"\"\n initial_time = time()\n sum_list = []\n for i in vector:\n sum_list = sum_list + list(complex_factoring(i).items())\n sorted_sum_list = sorted(sum_list, key=lambda x: (x[0], x[1]))\n vector_result = dict(sorted_sum_list)\n result = 1\n for k, v in vector_result.items():\n result = result*int((math.pow(k, v)))\n final_time = time()\n execution_time = final_time - initial_time\n result = int(result)\n return result, execution_time\n\n\ndef big_multi_euclides(vector):\n \"\"\" Función para hallar el mcm para n números en vectores grandes usando el Algoritmo de Euclides\"\"\"\n initial_time = time()\n mcm = vector[0]\n for i in vector[1:]:\n mcm = (mcm*i)//mcd(mcm, i)\n final_time = time()\n execution_time = final_time - initial_time\n return mcm, execution_time","sub_path":"algorithms/mcm.py","file_name":"mcm.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404819043","text":"\n\"\"\" A plugin to incorporate work-item creation in VSTS\neasily out of issues detected from Sentry.io \"\"\"\n\nfrom __future__ import absolute_import\n\nfrom django.utils.html import format_html\nfrom mistune import markdown\nfrom rest_framework.response import Response\n\nfrom sentry.api.serializers.models.plugin import PluginSerializer\nfrom sentry.models import Activity, Event, GroupMeta\nfrom sentry.signals import issue_tracker_used\nfrom sentry.utils.http import absolute_uri\n\nfrom sentry.plugins.bases.issue2 import IssueTrackingPlugin2\n\nfrom .mixins import VisualStudioMixin\nfrom .repository_provider import VisualStudioRepositoryProvider\n\n\nclass VstsPlugin(VisualStudioMixin, IssueTrackingPlugin2):\n description = 'Integrate Visual Studio Team Services work items by linking a project.'\n slug = 'vsts'\n conf_key = slug\n auth_provider = 'visualstudio'\n\n issue_fields = frozenset(['id', 'title', 'url'])\n\n def get_configure_plugin_fields(self, request, project, **kwargs):\n # TODO(dcramer): Both Account and Project can query the API an access\n # token, and could likely be moved to the 'Create Issue' form\n return [\n {\n 'name': 'instance',\n 'label': 'Instance',\n 'type': 'text',\n 'placeholder': 'example.visualstudio.com',\n 'required': True,\n 'help': 'VS Team Services account ({account}.visualstudio.com) or TFS server ({server:port}).',\n },\n {\n 'name': 'default_project',\n 'label': 'Default Project Name',\n 'type': 'text',\n 'placeholder': 'MyProject',\n 'required': False,\n 'help': (\n 'Enter the Visual Studio Team Services project name that you wish '\n 'to use as a default for new work items'\n ),\n },\n ]\n\n def is_configured(self, request, project, **kwargs):\n for o in ('instance',):\n if not bool(self.get_option(o, project)):\n return False\n return True\n\n def get_issue_label(self, group, issue, **kwargs):\n return 'Bug {}'.format(issue['id'])\n\n def get_issue_url(self, group, issue, **kwargs):\n \"\"\"\n Given an issue_id (string) return an absolute URL to the issue's\n details page.\n \"\"\"\n return issue['url']\n\n def get_new_issue_fields(self, request, group, event, **kwargs):\n fields = super(VstsPlugin, self).get_new_issue_fields(\n request, group, event, **kwargs)\n client = self.get_client(request.user)\n instance = self.get_option('instance', group.project)\n\n try:\n projects = client.get_projects(instance)\n except Exception as e:\n self.raise_error(e, identity=client.auth)\n\n return [\n {\n 'name': 'project',\n 'label': 'Project',\n 'default': self.get_option('default_project', group.project),\n 'type': 'text',\n 'choices': [i['name'] for i in projects['value']],\n 'required': True,\n }\n ] + fields\n\n def get_link_existing_issue_fields(self, request, group, event, **kwargs):\n return [\n {\n 'name': 'item_id',\n 'label': 'Work Item ID',\n 'default': '',\n 'type': 'text',\n },\n {\n 'name': 'comment',\n 'label': 'Comment',\n 'default': 'I\\'ve identified this issue in Sentry: {}'.format(\n absolute_uri(group.get_absolute_url()),\n ),\n 'type': 'textarea',\n 'help': ('Markdown is supported. Leave blank if you don\\'t want to add a comment.'),\n 'required': False\n }\n ]\n\n def create_issue(self, request, group, form_data, **kwargs):\n \"\"\"\n Creates the issue on the remote service and returns an issue ID.\n \"\"\"\n instance = self.get_option('instance', group.project)\n project = (\n form_data.get('project') or\n self.get_option('default_project', group.project)\n )\n\n client = self.get_client(request.user)\n\n title = form_data['title']\n description = form_data['description']\n link = absolute_uri(group.get_absolute_url())\n try:\n created_item = client.create_work_item(\n instance=instance,\n project=project,\n title=title,\n comment=markdown(description),\n link=link,\n )\n except Exception as e:\n self.raise_error(e, identity=client.auth)\n\n return {\n 'id': created_item['id'],\n 'url': created_item['_links']['html']['href'],\n 'title': title,\n }\n\n def link_issue(self, request, group, form_data, **kwargs):\n client = self.get_client(request.user)\n instance = self.get_option('instance', group.project)\n if form_data.get('comment'):\n try:\n work_item = client.update_work_item(\n instance=instance,\n id=form_data['item_id'],\n link=absolute_uri(group.get_absolute_url()),\n comment=markdown(form_data['comment']) if form_data.get(\n 'comment') else None,\n )\n except Exception as e:\n self.raise_error(e, identity=client.auth)\n else:\n try:\n work_item = client.get_work_item(\n instance=instance,\n id=form_data['item_id'],\n )\n except Exception as e:\n self.raise_error(e, identity=client.auth)\n\n return {\n 'id': work_item['id'],\n 'url': work_item['_links']['html']['href'],\n 'title': work_item['fields']['System.Title'],\n }\n\n def build_issue(self, group):\n conf_key = self.get_conf_key()\n issue = {}\n for key in self.issue_fields:\n issue[key] = GroupMeta.objects.get_value(group, '{}:issue_{}'.format(\n conf_key,\n key,\n ), None)\n if not any(issue.values()):\n return None\n return issue\n\n def has_linked_issue(self, group):\n return bool(self.build_issue(group))\n\n def unlink_issue(self, request, group, issue, **kwargs):\n conf_key = self.get_conf_key()\n # TODO(dcramer): these shouldn't be hardcoded here\n for key in self.issue_fields:\n GroupMeta.objects.unset_value(\n group, '{}:issue_{}'.format(conf_key, key))\n return self.redirect(group.get_absolute_url())\n\n def view_create(self, request, group, **kwargs):\n auth_errors = self.check_config_and_auth(request, group)\n if auth_errors:\n return Response(auth_errors, status=400)\n\n event = group.get_latest_event()\n Event.objects.bind_nodes([event], 'data')\n try:\n fields = self.get_new_issue_fields(request, group, event, **kwargs)\n except Exception as e:\n return self.handle_api_error(e)\n if request.method == 'GET':\n return Response(fields)\n\n errors = self.validate_form(fields, request.DATA)\n if errors:\n return Response({'error_type': 'validation', 'errors': errors}, status=400)\n\n try:\n issue = self.create_issue(\n group=group,\n form_data=request.DATA,\n request=request,\n )\n except Exception as e:\n return self.handle_api_error(e)\n\n conf_key = self.get_conf_key()\n for key in self.issue_fields:\n meta_name = '{}:issue_{}'.format(conf_key, key)\n if key in issue:\n GroupMeta.objects.set_value(group, meta_name, issue[key])\n else:\n GroupMeta.objects.unset_value(group, meta_name)\n\n issue_information = {\n 'title': request.DATA['title'],\n 'provider': self.get_title(),\n 'location': self.get_issue_url(group, issue),\n 'label': self.get_issue_label(group=group, issue=issue),\n }\n Activity.objects.create(\n project=group.project,\n group=group,\n type=Activity.CREATE_ISSUE,\n user=request.user,\n data=issue_information,\n )\n\n issue_tracker_used.send(\n plugin=self, project=group.project, user=request.user,\n sender=type(self)\n )\n return Response({'issue_url': self.get_issue_url(group=group, issue=issue)})\n\n def view_link(self, request, group, **kwargs):\n auth_errors = self.check_config_and_auth(request, group)\n if auth_errors:\n return Response(auth_errors, status=400)\n event = group.get_latest_event()\n Event.objects.bind_nodes([event], 'data')\n\n try:\n fields = self.get_link_existing_issue_fields(\n request, group, event, **kwargs)\n except Exception as e:\n return self.handle_api_error(e)\n if request.method == 'GET':\n return Response(fields)\n errors = self.validate_form(fields, request.DATA)\n if errors:\n return Response({'error_type': 'validation', 'errors': errors}, status=400)\n\n try:\n issue = self.link_issue(\n group=group,\n form_data=request.DATA,\n request=request,\n )\n except Exception as e:\n return self.handle_api_error(e)\n\n conf_key = self.get_conf_key()\n for key in self.issue_fields:\n meta_name = '{}:issue_{}'.format(conf_key, key)\n if key in issue:\n GroupMeta.objects.set_value(group, meta_name, issue[key])\n else:\n GroupMeta.objects.unset_value(group, meta_name)\n\n issue_information = {\n 'title': issue['title'],\n 'provider': self.get_title(),\n 'location': self.get_issue_url(group, issue),\n 'label': self.get_issue_label(group=group, issue=issue),\n }\n Activity.objects.create(\n project=group.project,\n group=group,\n type=Activity.CREATE_ISSUE,\n user=request.user,\n data=issue_information,\n )\n return Response({'message': 'Successfully linked issue.'})\n\n def view_unlink(self, request, group, **kwargs):\n auth_errors = self.check_config_and_auth(request, group)\n if auth_errors:\n return Response(auth_errors, status=400)\n issue = self.build_issue(group)\n if issue and 'unlink' in self.allowed_actions:\n self.unlink_issue(request, group, issue)\n return Response({'message': 'Successfully unlinked issue.'})\n return Response({'message': 'No issues to unlink.'}, status=400)\n\n def plugin_issues(self, request, group, plugin_issues, **kwargs):\n if not self.is_configured(request=request, project=group.project):\n return plugin_issues\n\n item = {\n 'slug': self.slug,\n 'allowed_actions': self.allowed_actions,\n 'title': self.get_title()\n }\n issue = self.build_issue(group)\n if issue:\n item['issue'] = {\n 'issue_id': issue.get('id'),\n 'url': self.get_issue_url(group=group, issue=issue),\n 'label': self.get_issue_label(group=group, issue=issue),\n }\n\n item.update(PluginSerializer(group.project).serialize(\n self, None, request.user))\n plugin_issues.append(item)\n return plugin_issues\n\n # TODO: should we get rid of this (move it to react?)\n def tags(self, request, group, tag_list, **kwargs):\n if not self.is_configured(request=request, project=group.project):\n return tag_list\n\n issue = self.build_issue(group)\n if not issue:\n return tag_list\n\n tag_list.append(\n format_html(\n '<a href=\"{}\">{}</a>',\n self.get_issue_url(group=group, issue=issue),\n self.get_issue_label(group=group, issue=issue),\n )\n )\n\n return tag_list\n\n def setup(self, bindings):\n bindings.add('repository.provider',\n VisualStudioRepositoryProvider, id='visualstudio')\n","sub_path":"src/sentry_plugins/vsts/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":12614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"201417146","text":"import unittest\n\ntestmodules = [\n 'test_lists',\n 'test_strings'\n]\n\nsuite = unittest.TestSuite()\n\nfor module in testmodules:\n try:\n # If the module defines a suite() function, call it to get the suite.\n mod = __import__(module, globals(), locals(), ['suite'])\n suitefn = getattr(mod, 'suite')\n suite.addTest(suitefn())\n except (ImportError, AttributeError):\n # else, just load all the test cases from the module.\n suite.addTest(unittest.defaultTestLoader.loadTestsFromName(module))\n\nunittest.TextTestRunner().run(suite)\n","sub_path":"alltests.py","file_name":"alltests.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"611417183","text":"import asyncio\nimport socketio\nimport aioconsole\n\nsio = socketio.AsyncClient(logger=True, engineio_logger=True) # (logger=True, engineio_logger=True)\n\n@sio.event\nasync def connect():\n print('connection established')\n\n@sio.event\nasync def my_message(data):\n print('message received with ', data)\n await sio.emit('my response', {'response': 'my response'})\n\n@sio.event\nasync def srv_message(data):\n print('message received from server with ', data)\n print('send response')\n await sio.emit('client_response', {'cl2 response': 'my response'})\n return \"OK\", 123\n\n@sio.event\nasync def disconnect():\n print('disconnected from server')\n\nasync def my_background_task(my_argument):\n # do some background work here!\n for i in range(my_argument):\n await sio.sleep(5) # (rather than asyncio.sleep(5) ...?)\n await sio.emit('client_response', {'background emits': 'stam'})\n\n\nasync def kb_echo_to_server(num):\n # ref: https://stackoverflow.com/questions/35223896/listen-to-keypress-with-asyncio\n for i in range(num):\n kb_input = await aioconsole.ainput('enter something: ')\n print(f'kb_input: {kb_input}')\n await sio.emit('client_response', {'from keyborad': kb_input})\n\n\nasync def main():\n await sio.connect('http://localhost:5003')\n\n task = sio.start_background_task(my_background_task, 2)\n await task\n\n task2 = sio.start_background_task(kb_echo_to_server, 5)\n await task2\n\n await sio.wait()\n\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n","sub_path":"flask-socketio-sample/asio-client.py","file_name":"asio-client.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"61650572","text":"\"\"\"Register, NDimensionalRegister and ResolutionSet\nabstract classes to contain area, interval and unit metadata.\n\nImplemented by :class:`smif.convert.interval.TimeIntervalRegister`,\n:class:`smif.convert.area.RegionRegister` and\n:class:`smif.convert.unit.UnitRegister`.\n\"\"\"\nimport logging\nfrom abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict, defaultdict\n\nimport numpy as np\n\n\nclass LogMixin(object):\n\n @property\n def logger(self):\n name = '.'.join([__name__, self.__class__.__name__])\n return logging.getLogger(name)\n\n\nclass Register(LogMixin, metaclass=ABCMeta):\n \"\"\"Abstract class which holds the ResolutionSets\n\n Arguments\n ---------\n axis : int, default=None\n The axis over which operations on the data array are performed\n\n \"\"\"\n data_interface = None\n\n def __init__(self, axis=None):\n self.axis = axis\n\n @property\n @abstractmethod\n def names(self):\n raise NotImplementedError\n\n @abstractmethod\n def register(self, resolution_set):\n raise NotImplementedError\n\n @abstractmethod\n def get_coefficients(self, source, destination):\n raise NotImplementedError\n\n def convert(self, data, from_set_name, to_set_name):\n \"\"\"Convert a list of data points for a given set to another set\n\n Parameters\n ----------\n data: numpy.ndarray\n from_set_name: str\n to_set_name: str\n\n Returns\n -------\n numpy.ndarray\n\n \"\"\"\n coefficients = self.get_coefficients(from_set_name, to_set_name)\n\n if self.axis is not None:\n data_count = data.shape[self.axis]\n if coefficients.shape[0] != data_count:\n msg = \"Size of coefficient array does not match source \" \\\n \"resolution set from data matrix: %s != %s\"\n raise ValueError(msg, coefficients.shape[self.axis],\n data_count)\n\n if self.axis == 0:\n converted = np.dot(coefficients.T, data)\n elif self.axis == 1:\n converted = np.dot(data, coefficients)\n else:\n converted = np.dot(data, coefficients)\n\n return converted\n\n\nclass NDimensionalRegister(Register):\n \"\"\"Abstract class which holds N-Dimensional ResolutionSets\n\n Arguments\n ---------\n axis : int, default=None\n The axis over which operations on the data array are performed\n\n \"\"\"\n def __init__(self, axis=None):\n super().__init__(axis)\n self._register = OrderedDict()\n self._conversions = defaultdict(dict)\n\n def register(self, resolution_set):\n \"\"\"Add a ResolutionSet to the register\n\n Parameters\n ----------\n resolution_set : :class:`smif.convert.ResolutionSet`\n\n Raises\n ------\n ValueError\n If a ResolutionSet of the same name already exists in the register\n \"\"\"\n if resolution_set.name in self._register:\n msg = \"A ResolutionSet named {} has already been loaded\"\n raise ValueError(msg.format(resolution_set.name))\n\n self.logger.info(\"Registering '%s' with %i items\",\n resolution_set.name,\n len(resolution_set))\n\n self._register[resolution_set.name] = resolution_set\n\n @property\n def names(self):\n \"\"\"Names of registered region sets\n\n Returns\n -------\n sets: list of str\n \"\"\"\n return list(self._register.keys())\n\n def get_entry(self, name):\n \"\"\"Returns the ResolutionSet of `name`\n\n Arguments\n ---------\n name : str\n The unique identifier of a ResolutionSet in the register\n\n Returns\n -------\n smif.convert.ResolutionSet\n\n \"\"\"\n if name not in self._register:\n msg = \"ResolutionSet '{}' not registered\"\n raise ValueError(msg.format(name))\n return self._register[name]\n\n def _write_coefficients(self, source, destination, data):\n if self.data_interface:\n self.data_interface.write_coefficients(source,\n destination,\n data)\n else:\n msg = \"Data interface not available to write coefficients\"\n self.logger.warning(msg)\n\n def get_coefficients(self, source, destination):\n \"\"\"Get coefficients representing intersection of sets\n\n Arguments\n ---------\n source : string\n The name of the source set\n destination : string\n The name of the destination set\n\n Returns\n -------\n numpy.ndarray\n \"\"\"\n from_set = self.get_entry(source)\n to_set = self.get_entry(destination)\n\n if from_set.coverage != to_set.coverage:\n log_msg = \"Coverage for '%s' is %d and does not match coverage \" \\\n \"for '%s' which is %d\"\n self.logger.warning(log_msg, from_set.name, from_set.coverage,\n to_set.name, to_set.coverage)\n\n if self.data_interface:\n\n self.logger.info(\"Using data interface to load coefficients\")\n coefficients = self.data_interface.read_coefficients(source,\n destination)\n\n if coefficients is None:\n msg = \"Coefficients not found, generating coefficients for %s to %s\"\n self.logger.info(msg, source, destination)\n\n coefficients = self._obtain_coefficients(from_set, to_set)\n self._write_coefficients(source, destination, coefficients)\n\n else:\n\n msg = \"No data interface specified, generating coefficients for %s to %s\"\n self.logger.info(msg, source, destination)\n coefficients = self._obtain_coefficients(from_set, to_set)\n\n return coefficients\n\n def _obtain_coefficients(self, from_set, to_set):\n \"\"\"\n \"\"\"\n coefficients = np.zeros((len(from_set), len(to_set)), dtype=np.float)\n self.logger.debug(\"Coefficients array is of shape %s for %s to %s\",\n coefficients.shape, from_set.name, to_set.name)\n\n from_names = from_set.get_entry_names()\n for to_idx, to_entry in enumerate(to_set):\n for from_idx in from_set.intersection(to_entry):\n\n proportion = from_set.get_proportion(from_idx, to_entry)\n\n self.logger.debug(\"%i percent of %s is in %s\",\n proportion * 100,\n to_entry.name, from_set.data[from_idx].name)\n from_idx = from_names.index(from_set.data[from_idx].name)\n\n coefficients[from_idx, to_idx] = proportion\n return coefficients\n\n\nclass ResolutionSet(metaclass=ABCMeta):\n \"\"\"Abstract class which holds the Resolution definitions\n \"\"\"\n def __init__(self):\n\n self.name = ''\n self.description = ''\n self.data = []\n self.logger = logging.getLogger(__name__)\n\n def as_dict(self):\n \"\"\"Get a serialisable representation of the object\n \"\"\"\n return {'name': self.name,\n 'description': self.description}\n\n def __iter__(self):\n return iter(self.data)\n\n @abstractmethod\n def get_entry_names(self):\n \"\"\"Get the names of the entries in the ResolutionSet\n\n Returns\n -------\n set\n The set of names which identify each entry in the ResolutionSet\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def intersection(self, bounds):\n \"\"\"Return the subset of entries intersecting with the bounds\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get_proportion(self, entry_a, entry_b):\n \"\"\"Calculate the proportion of `entry_a` and `entry_b`\n\n Arguments\n ---------\n entry_a : string\n Name of an entry in `ResolutionSet`\n entry_b : string\n Name of an entry in `ResolutionSet`\n\n Returns\n -------\n float\n The proportion of `entry_a` and `entry_b`\n \"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def coverage(self):\n raise NotImplementedError\n\n @staticmethod\n @abstractmethod\n def get_bounds(entry):\n \"\"\"Implement this helper method to return bounds from an entry in the register\n\n Arguments\n ---------\n entry\n An entry from a ResolutionSet\n\n Returns\n -------\n bounds\n The bounds of the entry\n \"\"\"\n raise NotImplementedError\n","sub_path":"src/smif/convert/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":8759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"626503489","text":"import sys, traceback, warnings, json\nimport boto3, botocore\nimport archie_shared.archie_exception\nfrom archie_shared.archie_config import read_config, get_all_sqs_queue_option_names\nfrom archie_shared import debugging\n\n\nclass SQSQueueMessage:\n '''\n Creates a message suitable for storing in SQS\n '''\n def __init__(self, message_data, message_id='Undefined', message_type=\"UNIMPLEMENTED\", is_error_msg=False):\n self.message_type = message_type\n self.message_data = message_data\n self.is_error = is_error_msg\n self.message_id = message_id\n\n def __repr__(self):\n return json.dumps({'MessageType': self.message_type, 'Message': self.message_data, 'IsErrorMessage': self.is_error, 'MessageID': self.message_id})\n\n\nclass SQSClient:\n '''\n SQSClient is used to interact with the Amazon AWS SQS Message Queueing service. You can put messages on a pre-defined queue or retrieve messages.\n '''\n def __init__(self, config=read_config()):\n '''\n During initialization any pre-configured queues that doesn't already exist will be created.\n :param config: configparser.ConfigParser class containing the application configuration. DEFAULT=archie_shared.archie_config.read_config()\n '''\n self.config = config\n self.client = boto3.client(\n 'sqs',\n aws_access_key_id=config.get(\"aws\", \"access_key\"),\n aws_secret_access_key=config.get(\"aws\", \"secret_key\"),\n )\n debugging.debug_dump(\"archie_shared.sqs.SQSClient.__init__(): type of self.client: %s\" % type(self.client))\n self.configured_queue_names = self._get_all_configured_queue_names()\n self._check_queues()\n self.queue_urls = self._get_queue_urls()\n debugging.debug_dump(\"archie_shared.sqs.SQSClient.__init__(): SQSClient initialized\")\n\n def send_message(self, queue_name, msg=SQSQueueMessage('No Data')):\n '''\n Send a message to an SQS Queue using the standardised SQSQueueMessage message\n :param queue_name: String if the queue name.\n :param msg: SQSQueueMessage to send to the queue\n :return: String containing the SQS MessageID or None\n '''\n if queue_name in self.queue_urls:\n attr = {\n 'MessageClass': {\n 'StringValue': 'archie_shared.sqs.SQSQueueMessage',\n 'DataType': 'String.archie_shared.sqs.SQSQueueMessage'\n },\n 'MessageID': {\n 'StringValue': msg.message_id,\n 'DataType': 'String'\n },\n 'MessageDataFormat': {\n 'StringValue': 'JSON',\n 'DataType': 'String.json'\n }\n }\n response = self.client.send_message(QueueUrl=self.queue_urls[queue_name], MessageBody=repr(msg), MessageAttributes=attr)\n if 'MessageId' in response:\n debugging.debug_dump(\"archie_shared.sqs.SQSClient.send_message(): Message submitted: MessageId='%s', MD5OfMessageBody='%s', MD5OfMessageAttributes='%s'\" % (response['MessageId'], response['MD5OfMessageBody'], response['MD5OfMessageAttributes']))\n return response['MessageId']\n else:\n warnings.warn(\"Not pushing messages as the queue name is not managed by this application\")\n return None\n\n def poll_messages(self, queue_name='archie_commander', type_filter=None, type_filter_value=None, date_order='DESC', limit=1, delete_messages=True):\n '''\n NOTE: DESC (descending) order means newest on the top and the oldest at the bottom.\n\n :param queue_name: String with the queue name. DEFAULT='archie_commander'\n :param type_filter: String indicating to filter messages either by 'MessageType' or by 'MessageID'. If set to None, no filtering will be done. DEFAULT=None\n :param type_filter_value: String with the value to filter by\n :param date_order: String of either DESC (descending) or ASC (ascending). DEFAULT='DESC'\n :param limit: How many messages to return (in the list). DEFAULT=1 (newest one)\n :param delete_messages: Boolean indicating if retrieved messages must be deleted. DEFAULT=True\n :return: List of SQSQueueMessage\n '''\n sqs_messages = []\n messages = self._get_messages(queue_name)\n if type_filter is not None and type_filter_value is not None:\n new_messages = {}\n for key in list(messages.keys()):\n message = messages[key]\n if type_filter == 'MessageID':\n if message['MessageID'] == type_filter_value:\n new_messages[key] = message\n if type_filter == 'MessageType':\n if message['MessageType'] == type_filter:\n new_messages[key] = message\n messages = new_messages\n message_keys = list(messages.keys())\n if date_order == 'DESC':\n message_keys_sorted = sorted(message_keys, reverse=True)\n else:\n message_keys_sorted = sorted(message_keys)\n if len(message_keys_sorted) > limit:\n message_keys_sorted = message_keys_sorted[:limit]\n for message_timestamp in message_keys_sorted:\n message = messages[message_timestamp]\n sqs_messages.append(SQSQueueMessage(message['MessageData'], message['MessageID'], message['MessageType'], message['IsErrorMessage']))\n if delete_messages:\n if 'ReceiptHandle' in message:\n self.client.delete_message(QueueUrl=self.queue_urls[queue_name], ReceiptHandle=message['ReceiptHandle'])\n debugging.debug_dump(\"archie_shared.sqs.SQSClient.poll_messages(): Deletion request for ReceiptHandle '%s' sent to queue URL '%s\" % (message['ReceiptHandle'], self.queue_urls[queue_name]))\n else:\n warnings.warn(\"archie_shared.sqs.SQSClient.poll_messages(): Message deletion not done as ReceiptHandle is not defined.\")\n return sqs_messages\n\n def _get_messages(self, queue_name):\n messages = {}\n if queue_name in self.queue_urls:\n response = self.client.receive_message(QueueUrl=self.queue_urls[queue_name], WaitTimeSeconds=20, MessageAttributeNames=['All'], AttributeNames=['All'])\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): response=%s\" % response)\n if 'Messages' in response:\n for message in response['Messages']:\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): Inspecting message with SQS MessageID '%s'\" % message['MessageId'])\n attr = message['MessageAttributes']\n body = message['Body']\n msg_sent_timestamp = message['Attributes']['SentTimestamp']\n r_handle = message['ReceiptHandle']\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): attr=%s\" % attr)\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): body=%s\" % body)\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): r_handle=%s\" % r_handle)\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): msg_sent_timestamp=%s\" % msg_sent_timestamp)\n if 'MessageClass' in attr:\n msg_class = attr['MessageClass']\n msg_id = attr['MessageID']\n msg_data_format = attr['MessageDataFormat']\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): msg_class=%s\" % msg_class)\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): msg_id=%s\" % msg_id)\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_messages(): msg_data_format=%s\" % msg_data_format)\n if msg_class['StringValue'] == 'archie_shared.sqs.SQSQueueMessage' and msg_data_format['StringValue'] == 'JSON':\n data = json.loads(body)\n if 'MessageType' in data:\n msg_type = data['MessageType']\n is_err = data['IsErrorMessage']\n messages[msg_sent_timestamp] = {'MessageData': data['Message'], 'MessageType': msg_type, 'ReceiptHandle': r_handle, 'MessageID': msg_id['StringValue'], 'IsErrorMessage': is_err}\n else:\n warnings.warn(\"Not retrieving message as the queue name is not managed by this application\")\n return messages\n\n def _get_queue_urls(self):\n queue_urls = {}\n for queue_name in self.configured_queue_names:\n response = self.client.get_queue_url(QueueName=queue_name)\n if 'QueueUrl' in response:\n queue_urls[queue_name] = response['QueueUrl']\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._get_queue_urls(): Queue '%s' has URL '%s'\" % (queue_name, queue_urls[queue_name]))\n return queue_urls\n\n def _get_all_configured_queue_names(self):\n sqs_queue_names = []\n option_names = get_all_sqs_queue_option_names()\n for on in option_names:\n sqs_queue_names.append(self.config.get('sqs', on))\n return sqs_queue_names\n\n def _check_queues(self):\n for queue_name in self.configured_queue_names:\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._check_queues(): queue_name=%s\" % queue_name)\n try:\n response1 = self.client.get_queue_url(QueueName=queue_name)\n debugging.debug_dump(\"archie_shared.sqs.SQSClient._check_queues(): response1: %s\" % response1)\n except botocore.exceptions.ClientError as e:\n if e.response['Error'].get('Code', 'Unknown') == \"AWS.SimpleQueueService.NonExistentQueue\":\n warnings.warn(\"Queue %s does not exist - attempting to create it.\" % queue_name)\n self._create_queue(queue_name)\n else:\n print(\"An unexpected error occured. Meditation to follow...\")\n print(\"\\tMessage : %s\" % e.response['Error'].get('Message', 'Unknown'))\n print(\"\\tCode : %s\" % e.response['Error'].get('Code', 'Unknown'))\n raise archie_shared.archie_exception.SQSError(\"SQS_Error_Code=%s SQS_Error_Message=%s\" % (e.response['Error'].get('Code', 'Unknown'), e.response['Error'].get('Message', 'Unknown')))\n except:\n traceback.print_exc(file=sys.stdout)\n\n def _create_queue(self, queue_name):\n try:\n queue = self.client.create_queue(\n QueueName=queue_name,\n Attributes={\n 'DelaySeconds': '0',\n }\n )\n print(\"Queue %s created. Queue URL: %s\" % (queue_name, queue['QueueUrl']))\n except:\n raise archie_shared.archie_exception.SQSError(\"Failed to create queue\")\n\n\n\n\n\n# ./end","sub_path":"archie_shared/sqs.py","file_name":"sqs.py","file_ext":"py","file_size_in_byte":11150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"511423431","text":"import requests\r\n\r\nhyperlink = 'https://jsonplaceholder.typicode.com/todos'\r\ntitle_in = input()\r\ncompleted_in = bool(input())\r\n\r\n\r\ndef find_dict(hyperlink, title, completed):\r\n res = requests.get(hyperlink)\r\n lst = res.json()\r\n lstout = []\r\n for one in lst:\r\n if title in one['title'] and completed == one[\"completed\"]:\r\n i = one[\"id\"]\r\n lstout.append(lst[i - 1])\r\n return lstout\r\n\r\n\r\nfor i in find_dict(hyperlink, title_in, completed_in):\r\n print(i)\r\n\r\n","sub_path":"ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"515363309","text":"import os\nimport sys\nimport numpy as np\nimport nibabel as nb\nimport nighresjava\nfrom ..io import load_volume, save_volume, load_mesh_geometry, save_mesh_geometry\nfrom ..utils import _output_dir_4saving, _fname_4saving,_check_available_memory\n\n\ndef levelset_to_mesh(levelset_image, connectivity=\"18/6\", level=0.0,\n inclusive=True, save_data=False, overwrite=False,\n output_dir=None, file_name=None):\n\n \"\"\"Levelset to mesh\n\n Creates a triangulated mesh from the distance to a levelset surface\n representation using a connectivity-consistent marching cube algorithm.\n\n Parameters\n ----------\n levelset_image: niimg\n Levelset image to be turned into a mesh\n connectivity: {\"6/18\",\"6/26\",\"18/6\",\"26/6\"}, optional\n Choice of digital connectivity to build the mesh (default is 18/6)\n level: float, optional\n Value of the levelset function to use as isosurface (default is 0)\n inclusive: bool, optional\n Whether voxels at the exact 'level' value are inside the isosurface\n (default is True)\n save_data: bool, optional\n Save output data to file (default is False)\n overwrite: bool, optional\n Overwrite existing results (default is False)\n output_dir: str, optional\n Path to desired output directory, will be created if it doesn't exist\n file_name: str, optional\n Desired base name for output files with file extension\n (suffixes will be added)\n\n Returns\n ----------\n dict\n Dictionary collecting outputs under the following keys\n (suffix of output files in brackets)\n\n * result (mesh): Surface mesh dictionary of \"points\" and \"faces\"\n (_l2m-mesh)\n\n Notes\n ----------\n Ported from original Java module by Pierre-Louis Bazin. Original algorithm\n from [1]_ and adapted from [2]_.\n\n References\n ----------\n .. [1] Han et al (2003). A Topology Preserving Level Set Method for\n Geometric Deformable Models\n doi:\n .. [2] Lucas et al (2010). The Java Image Science Toolkit (JIST) for\n Rapid Prototyping and Publishing of Neuroimaging Software\n doi:\n \"\"\"\n\n print(\"\\nLevelset to Mesh\")\n\n # make sure that saving related parameters are correct\n if save_data:\n output_dir = _output_dir_4saving(output_dir, levelset_image)\n\n mesh_file = os.path.join(output_dir,\n _fname_4saving(module=__name__,file_name=file_name,\n rootfile=levelset_image,\n suffix='l2m-mesh',ext=\"vtk\"))\n\n if overwrite is False \\\n and os.path.isfile(mesh_file) :\n\n print(\"skip computation (use existing results)\")\n output = {'result': mesh_file}\n return output\n\n # start virtual machine if not running\n try:\n mem = _check_available_memory()\n nighresjava.initVM(initialheap=mem['init'], maxheap=mem['max'])\n except ValueError:\n pass\n\n # initiate class\n algorithm = nighresjava.SurfaceLevelsetToMesh()\n\n # load the data\n lvl_img = load_volume(levelset_image)\n lvl_data = lvl_img.get_fdata()\n hdr = lvl_img.header\n aff = lvl_img.affine\n resolution = [x.item() for x in hdr.get_zooms()]\n dimensions = lvl_data.shape\n\n algorithm.setResolutions(resolution[0], resolution[1], resolution[2])\n algorithm.setDimensions(dimensions[0], dimensions[1], dimensions[2])\n\n algorithm.setLevelsetImage(nighresjava.JArray('float')(\n (lvl_data.flatten('F')).astype(float)))\n\n algorithm.setConnectivity(connectivity)\n algorithm.setZeroLevel(level)\n algorithm.setInclusive(inclusive)\n\n # execute class\n try:\n algorithm.execute()\n\n except:\n # if the Java module fails, reraise the error it throws\n print(\"\\n The underlying Java code did not execute cleanly: \")\n print(sys.exc_info()[0])\n raise\n return\n\n # collect outputs\n npt = int(np.array(algorithm.getPointList(), dtype=np.float32).shape[0]/3)\n mesh_points = np.reshape(np.array(algorithm.getPointList(),\n dtype=np.float32), (npt,3), 'C')\n\n nfc = int(np.array(algorithm.getTriangleList(), dtype=np.int32).shape[0]/3)\n mesh_faces = np.reshape(np.array(algorithm.getTriangleList(),\n dtype=np.int32), (nfc,3), 'C')\n\n # create the mesh dictionary\n mesh = {\"points\": mesh_points, \"faces\": mesh_faces}\n\n if save_data:\n save_mesh_geometry(mesh_file, mesh)\n return {'result': mesh_file}\n else:\n return {'result': mesh}\n","sub_path":"nighres/surface/probability_to_mesh.py","file_name":"probability_to_mesh.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"16687860","text":"import numpy as np\n\n# @brief negative log likelihood (cross entropy metric)\n# @param[in] y Predictions. Shape :: MBx(Shape)xNC with positive values\n# @param[in] t Labels. Shape :: MBx(Shape)xNC with binary values\n# @return The NLL result for each channel. SHape :: MBx(Shape)\ndef nll(y, t):\n\tt = t.max(axis=-1, keepdims=True) == t\n\tt = t.astype(np.int32)\n\tL = (y * t).max(axis=-1)\n\tL = -np.log(L)\n\tL[~np.isfinite(L)] = 100\n\treturn L\n","sub_path":"neural_wrappers/metrics/nll.py","file_name":"nll.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"507830418","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 14 11:32:07 2019\n\n@author: admin\n\"\"\"\n\n# pip install beautifulsoup4\n# pip install requests\n# pip install selenium\n\nfrom bs4 import BeautifulSoup\n#import requests \nfrom selenium import webdriver\nimport pandas as pd \nfrom datetime import datetime\nimport time\nimport numpy as np\nimport re\nimport sys\n\n\ndef a_to_d(odd):\n if 'even' in odd.lower():\n clean_odd = 2 \n elif '-' in odd:\n clean_odd = odd.replace('-','')\n clean_odd = (int(clean_odd)+100) / int(clean_odd)\n elif '+' in odd:\n clean_odd = odd.replace('\\+','')\n clean_odd = 1 + int(clean_odd) / 100 \n else:\n return np.nan\n \n clean_odd = round(1/ clean_odd,2)\n #clean_odd = round(clean_odd,2)\n return clean_odd\n\n\n\ndef open_url(url):\n driver = webdriver.Chrome()\n driver.get(url)\n time.sleep(5) \n return driver \n\n\ndef read_site(driver):\n \n odds_table = pd.DataFrame() \n\n now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n \n soup = BeautifulSoup(driver.page_source, 'html.parser')\n\n # Bets \n container1 = soup.find(\"div\", {\"class\": \"ui-widget-content-body shown market-board-group-content target\"})\n # Score\n container2 = soup.find(\"div\", {\"class\": \"gameTemplate\"})\n\n players = container2.find_all(\"span\", {\"class\": \"participantName name\"})\n player = container2.find(\"span\", {\"class\": \"participantName name\"})\n names = []\n for player in players:\n names.append( player.text.strip() )\n\n set_serve = container2.find('div', {'class': \"setGameCol rightAlign\"}).find_all('span', attrs={'class': re.compile('^serve') }) \n serve = []\n for order in set_serve:\n serve.append (order['class']) \n \n score1_game = container2.find('span', {'ng-bind': \"vm.event.scoreboard.client.score.points.player1\"}).text.strip()\n score2_game = container2.find('span', {'ng-bind': \"vm.event.scoreboard.client.score.points.player2\"}).text.strip() \n \n \n the_sets = container2.find_all('div', {'ng-repeat': 'set in vm.event.scoreboard.client.score.sets track by set.title'})\n\n score_sets = []\n for each_set in the_sets:\n player1 = each_set.find('span', {'ng-bind': 'set.player1'}).text.strip()\n player2 = each_set.find('span', {'ng-bind': 'set.player2'}).text.strip()\n score_sets.append( [player1,player2] )\n\n bet_options = {}\n \n bets = container1.find_all('div', {'class' : 'markets'})\n\n for bet in bets:\n X = bet.find('div', {'class' : 'title'}).text.strip()\n bet_options[X] = []\n temp_odds = []\n for odds in bet.find_all('span', {'class' : 'value'}):\n temp_odds.append( odds.text.strip() )\n bet_options[X] = temp_odds\n \n \n # ALL TOGETHER\n odds_table.loc[0,'log'] = now\n \n odds_table.loc[0,'player1'] = names[0]\n odds_table.loc[0,'player2'] = names[1]\n \n try: \n if serve[0][1] == 'on':\n odds_table.loc[0,'service'] = 'player1'\n except: \n try:\n if serve[1][1] == 'on':\n odds_table.loc[0,'service'] = 'player2'\n except:\n odds_table.loc[0,'service'] = 'N/D'\n\n odds_table.loc[0,'game1'] = score1_game\n odds_table.loc[0,'game2'] = score2_game \n \n str_score = ''\n for set_score in score_sets:\n str_score += str(set_score)\n \n odds_table.loc[0,'score'] = str_score.replace('\\'','')\n \n odds_table.loc[0,'odds1'] = a_to_d(bet_options['Match Winner'][0])\n odds_table.loc[0,'odds2'] = a_to_d(bet_options['Match Winner'][1])\n\n return(odds_table)\n\n\ndef combine_df(df_base,df_new):\n df_base = df_base.append(df_new)\n cols = list(df_base.columns)\n cols.remove('log')\n df_base = df_base.drop_duplicates(subset=cols, keep='first', inplace=False)\n return df_base\n\nTennis_live = pd.DataFrame()\n\nurl = 'https://livebetting.bwin.com/en/live#/9026313'\n\nfile_name = 'Tennis_live4.csv'\n\ndriver = open_url(url)\n\nwhile True:\n count = 0\n try:\n odds_table = read_site(driver)\n Tennis_live = combine_df(Tennis_live,odds_table) \n Tennis_live.to_csv( file_name ,sep=',',na_rep='N/D',index=False)\n count = 0\n time.sleep(5)\n print('ok')\n except:\n print (\"Unexpected error:\", sys.exc_info()[0] )\n count += 1\n if count > 360:\n driver.close()\n driver = open_url(url) \n else:\n time.sleep(5)\n\n\n\n\n\n\n \n ","sub_path":"Tennis_live2.py","file_name":"Tennis_live2.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"440857675","text":"import dash\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nfrom dash.exceptions import PreventUpdate\nimport dash_html_components as html\nimport dash_core_components as dcc\nimport plotly.graph_objs as go\nimport plotly.express as px\nimport pandas as pd\nimport numpy as np\nimport os.path as osp\n\nfrom app import app\n\npd.set_option('display.float_format', lambda x: '%.0f' % x)\n\nDATA_DIR = '/Users/eun-yunhye/Developer/scrap/plotly-dash/data'\ndf_lcrcy_induty = pd.read_csv(osp.join(DATA_DIR, 'TP_LCRCY_USE_ND_INDUTY_DISTRB.csv'))\ndf_mwmn = pd.read_csv(osp.join(DATA_DIR, 'TP_MWMN_ACCTO_CNSMP_PTTRN.csv'))\ndf_postnum = pd.read_table(osp.join(DATA_DIR, '경기도.txt'), sep='|')\n\n# df_postnum = df_postnum.loc[:, ['우편번호', '시도', '시도영문','시군구', '시군구영문', '읍면', '읍면영문', '리명', '행정동명']]\ndf_postnum = df_postnum.drop(['산여부', '지번본번', '지하여부', '건물번호본번', '건물번호부번', '건물관리번호', '다량배달처명', '시군구용건물명', '읍면동일련번호', '지번부번', '법정동명', '구우편번호', '우편번호일련번호', '도로명코드', '도로명', '도로명영문'], axis=1)\ndf_postnum = df_postnum.drop_duplicates(['우편번호'], keep='first')\ndf_1 = df_lcrcy_induty.groupby('가맹점우편번호').sum().reset_index().drop('분석인덱스', axis=1)\ndf_1_merged = pd.merge(df_1, df_postnum.loc[:, ['우편번호', '시군구', '행정동명']], left_on='가맹점우편번호', right_on='우편번호', how='left').drop('우편번호', axis=1).drop_duplicates(['가맹점우편번호'], keep='first')\ndataset = []\ndataset.append(df_1_merged.groupby(['시군구', '행정동명']).sum().reset_index())\n\nhovertemplate = []\nhovertemplate.append([])\nfor row in range(len(dataset[0])):\n city = dataset[0].iloc[row, 0]\n dong = dataset[0].iloc[row, 1]\n charge = dataset[0].iloc[row, 3]\n market = dataset[0].iloc[row, 4]\n hovertemplate[0].append(f'{city} {dong}<br>가맹점 수: {market}<br>사용량: {charge}')\n\ndf_lcrcy_induty['연령대코드'] = df_lcrcy_induty['연령대코드'].apply(lambda x: str(x))\ndf_2 = df_lcrcy_induty.groupby(['가맹점우편번호', '연령대코드']).sum().reset_index().drop('분석인덱스', axis=1).reset_index()\ndf_2_merged = pd.merge(df_2, df_postnum.loc[:, ['우편번호', '시군구', '행정동명']], left_on='가맹점우편번호', right_on='우편번호', how='left').drop('우편번호', axis=1)\ndf_2_merged = df_2_merged.groupby(['시군구', '행정동명', '연령대코드']).sum().reset_index()\ndf_2_merged = df_2_merged.drop(df_2_merged[df_2_merged['연령대코드'] == '70'].index)\ndf_2_merged = df_2_merged.drop(df_2_merged[df_2_merged['연령대코드'] == '80'].index)\ndf_2_merged = df_2_merged.drop(df_2_merged[df_2_merged['연령대코드'] == '90'].index)\ndf_2_merged = df_2_merged.drop(df_2_merged[df_2_merged['연령대코드'] == '90+'].index)\ndataset.append(df_2_merged)\n\ndf_3 = df_mwmn.groupby(['시군구명', '가맹점업종명']).sum().reset_index()\ndf_3_mean = df_mwmn.groupby('가맹점업종명').mean().reset_index()\ndf_3_mean = df_3_mean.rename(columns={'가맹점업종명': '가맹점업종명', '총결제금액': '평균결제금액'})\ndf_3_merged = pd.merge(df_3, df_3_mean, on='가맹점업종명', how='left')\ndataset.append(df_3_merged)\n\nlayout = html.Div([\n html.Div([\n html.H1('LOCAL CURRENCY USAGE', style={'marginBottom': '0'}),\n html.P('행정동별 가맹점수에 따른 지역화폐 사용량', style={'marginTop': '0'}),\n html.Div([\n html.Label([\n '시군구',\n dcc.Dropdown(\n id='page0-city-dropdown',\n options= [{'label': x, 'value': x} for x in sorted(list(set(dataset[0]['시군구'].values)))],\n )\n ], style={'width': '50%'}),\n html.Label([\n '행정동',\n dcc.Dropdown(\n id='page0-dong-dropdown',\n ),\n ], style={'width': '50%'})\n ], style={'width': '100%', 'display': 'inline-block'}),\n html.H3(id='page0-output1', style={'marginBottom': '0'}),\n html.Div([\n dcc.Graph(id='page0-graph1')\n ], style={'width': '100%', 'display': 'inline-block'})\n ], style={'margin': '1%', 'padding': '1% 2%', 'border': '1px solid gray', 'borderRadius': '5px'}),\n html.Div([\n html.H1('ANALYSIS', style={'marginBottom': '0'}),\n html.P('지역화폐 결제 분석', style={'marginTop': '0'}),\n html.H3(id='page0-output2', style={'marginBottom': '0'}),\n html.Div([\n html.Div([\n dcc.Graph(id='page0-graph2')\n ], style={'width': '33%', }),\n html.Div([\n dcc.Graph(id='page0-graph3')\n ], style={'width': '33%', }),\n html.Div([\n dcc.Graph(id='page0-graph4')\n ], style={'width': '33%', }),\n ], style={'width': '100%', 'display': 'flex'})\n ], style={'margin': '1%', 'padding': '1% 2%', 'border': '1px solid gray', 'borderRadius': '5px'}),\n], style={'padding': '1%'})\n \n\n@app.callback(\n Output(component_id='page0-dong-dropdown', component_property='options'),\n [Input(component_id='page0-city-dropdown', component_property='value')],\n)\n\ndef update_options(value):\n if not value:\n raise PreventUpdate\n option_list = sorted(list(set(dataset[0].loc[dataset[0]['시군구'] == value, :]['행정동명'].values)))\n result = [{'label': e, 'value': e} for e in option_list]\n return result\n\n@app.callback(\n [\n Output(component_id='page0-output1', component_property='children'),\n Output(component_id='page0-output2', component_property='children')\n ],\n [\n Input(component_id='page0-city-dropdown', component_property='value'),\n Input(component_id='page0-dong-dropdown', component_property='value')\n ]\n)\n\ndef show_output(city, dong):\n if not city or not dong:\n raise PreventUpdate\n result1 = \"{} {} 가맹점 수: {} 사용량: {}\".format(city, dong,\n dataset[0].loc[(dataset[0]['시군구']==city) & (dataset[0]['행정동명']==dong), :]['상가수'].values[0],\n dataset[0].loc[(dataset[0]['시군구']==city) & (dataset[0]['행정동명']==dong), :]['결제수'].values[0])\n return result1, \"현재 설정 지역: {} {}\".format(city, dong)\n\n@app.callback(\n Output(component_id='page0-graph1', component_property='figure'),\n [\n Input(component_id='page0-city-dropdown', component_property='value'),\n Input(component_id='page0-dong-dropdown', component_property='value')\n ]\n)\n\ndef show_graph1(city, dong):\n if not city or not dong:\n raise PreventUpdate\n\n single = dataset[0].loc[(dataset[0]['시군구']==city) & (dataset[0]['행정동명']==dong), :]\n city = single.iloc[0, 0]\n dong = single.iloc[0, 1]\n charge = single.iloc[0, 3]\n market = single.iloc[0, 4]\n tmp = f'{city} {dong}<br>가맹점 수: {market}<br>사용량: {charge}'\n fig = {\n 'data': [\n go.Scatter(\n name='전체',\n x=dataset[0]['상가수'],\n y=dataset[0]['결제수'],\n mode='markers',\n marker={'size': 10,},\n hovertemplate=hovertemplate[0]\n ),\n go.Scatter(\n name='선택',\n x=single['상가수'],\n y=single['결제수'],\n mode='markers',\n marker={'size':15,},\n hovertemplate=tmp\n )\n ],\n 'layout':\n go.Layout(\n xaxis={\n 'title': '가맹점 수'\n },\n yaxis={\n 'title': '사용량'\n }\n )\n }\n return fig\n\n@app.callback(\n Output(component_id='page0-graph2', component_property='figure'),\n [\n Input(component_id='page0-city-dropdown', component_property='value'),\n Input(component_id='page0-dong-dropdown', component_property='value')\n ]\n)\n\ndef show_graph2(city, dong):\n if not city or not dong:\n raise PreventUpdate\n\n single = dataset[1].loc[(dataset[1]['시군구']==city) & (dataset[1]['행정동명']==dong), :]\n tmp = []\n for i in range(len(single)):\n city = single.iloc[i, 0]\n dong = single.iloc[i, 1]\n age = single.iloc[i, 2]\n cnt = single.iloc[i, 5]\n tmp.append(f'연령대: {age}<br>사용량: {cnt}')\n fig = {\n 'data': [\n go.Bar(\n name=f'{city} {dong}',\n x=single['연령대코드'],\n y=single['결제수'],\n hovertemplate=tmp,\n marker={\n 'color': single['연령대코드'].apply(lambda x: int(x)),\n 'colorscale': 'Viridis'\n }\n ),\n ],\n 'layout':\n go.Layout(\n title={\n 'text': '< 연령별 지역화폐 사용량 >',\n 'font': {\n 'size': 18\n }\n },\n xaxis={\n 'title': '연령대'\n },\n yaxis={\n 'title': '사용량'\n }\n )\n }\n return fig\n\n@app.callback(\n [\n Output(component_id='page0-graph3', component_property='figure'),\n Output(component_id='page0-graph4', component_property='figure'),\n ],\n [\n Input(component_id='page0-city-dropdown', component_property='value'),\n ]\n)\n\ndef show_graph3(city):\n if not city or not dong:\n raise PreventUpdate\n\n single = dataset[2].loc[dataset[2]['시군구명'] == city, :].sort_values(by='총결제금액', ascending=False)\n fig1 = {\n 'data': [\n go.Bar(\n name=f'{city}',\n x=single.head(5)['가맹점업종명'],\n y=single.head(5)['총결제금액'],\n marker_color='indianred'\n\n ),\n go.Bar(\n name=f'경기도 평균',\n x=single.head(5)['가맹점업종명'],\n y=single.head(5)['평균결제금액'],\n marker_color='lightsalmon'\n ),\n ],\n 'layout':\n go.Layout(\n title={\n 'text': '< 타지역 대비 결제금액이 많은 업종 >',\n 'font': {\n 'size': 18\n }\n },\n yaxis={\n 'title': '결제금액'\n },\n legend={\n 'orientation': 'h',\n 'x': 0.2,\n 'y': 1.1\n }\n )\n }\n fig2 = {\n 'data': [\n go.Bar(\n name=f'{city}',\n x=single.tail(5)['가맹점업종명'],\n y=single.tail(5)['총결제금액'],\n marker_color='steelblue'\n\n ),\n go.Bar(\n name=f'경기도 평균',\n x=single.tail(5)['가맹점업종명'],\n y=single.tail(5)['평균결제금액'],\n marker_color='lightskyblue'\n ),\n ],\n 'layout':\n go.Layout(\n title={\n 'text': '< 타지역 대비 결제금액이 적은 업종 >',\n 'font': {\n 'size': 18\n }\n },\n yaxis={\n 'title': '결제금액'\n },\n legend={\n 'orientation': 'h',\n 'x': 0.2,\n 'y': 1.1\n }\n )\n }\n return fig1, fig2","sub_path":"plotly-dash/pages/page0.py","file_name":"page0.py","file_ext":"py","file_size_in_byte":11920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"380142080","text":"from core.TaxonFunc import TaxonFunc\nfrom core.TaxonClass import TaxonClass\n\ndef checkMemberAccess(source, target):\n\t\"\"\"\n\tПроверка возможности доступа к члену класса\n\tsource представлен таксоном типа WppNamed\n\ttarget - член класса\n\t\"\"\"\n\t# Нужно найти метод, в котором находится source\n\tsourceMethod = source.owner\n\twhile not (sourceMethod.owner.isClass() and isinstance(sourceMethod, TaxonFunc)):\n\t\tif sourceMethod.isModule():\n\t\t\tsourceMethod = None\n\t\t\tbreak\n\t\tsourceMethod = sourceMethod.owner\n\n\t# Если target не является статическим, а source принадлежит статическому члену, это ошибка\n\tif not target.isStatic() and sourceMethod and sourceMethod.isStatic():\n\t\tsource.throwError('Non-static %s \"%s\" cannot be referenced from the static \"%s\"' % (target.type, target.getName(), sourceMethod.getName()))\n\n\tTaxonClass.checkAccess(source, target)\n","sub_path":"src3/Wpp/WppClassHelper.py","file_name":"WppClassHelper.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"418131282","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/chuan/GitHub/OrthNet/orthnet/utils/multi_dim.py\n# Compiled at: 2018-03-08 02:47:33\n# Size of source mod 2**32: 1305 bytes\n\n\ndef enumerate_dim(n, dim):\n \"\"\"\n enumerate dims:\n find DIM nonnegative numbers, the sum of which is n, return result in lexicographical order.\n\n input:\n n: total order\n dim: dimension (number of variables)\n\n output:\n a 2D-list, each element a combination (a list)\n\n >>> enumerate_dim(3, 2)\n >>> [[3, 0], [2, 1], [1, 2], [0, 3]]\n \"\"\"\n\n def dfs(res, cur, n, dim):\n if dim == 1:\n res.append(cur + [n])\n return\n for i in reversed(range(n + 1)):\n dfs(res, cur + [i], n - i, dim - 1)\n\n res = []\n dfs(res, [], n, dim)\n return res\n\n\ndef enum_dim(n, dim):\n \"\"\"\n enumerate dims:\n find DIM nonnegative numbers, the sum of which <= n, return result in lexicographical order.\n\n input:\n n: total order\n dim: dimension (number of variables)\n\n output:\n a 2D-list, each element a combination (a list)\n\n >>> enum_dim(3, 2)\n >>> [[0, 0], [1, 0], [0, 1], [2, 0], [1, 1], [0, 2], [3, 0], [2, 1], [1, 2], [0, 3]]\n \"\"\"\n res = [\n [\n [0 for i in range(dim)]]]\n for i in range(n):\n cur = []\n for comb in res[(-1)]:\n for j in range(len(comb)):\n tmp = comb[:]\n tmp[j] += 1\n flag = 1\n for k in cur:\n if tmp == k:\n flag = 0\n break\n\n if flag:\n cur.append(tmp)\n\n res.append(cur)\n\n return res\n\n\ndef dim(n, d):\n res = []\n for i in range(n + 1):\n res.append(enum_dim(i, d))\n\n return res","sub_path":"pycfiles/orthnet-0.4.0.tar/multi_dim.cpython-36.py","file_name":"multi_dim.cpython-36.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"222392630","text":"import math\n\n\nf = open('PSMs_and_ESMs.csv')\n\ntestSize = 4500\nvalSize = 3000\n\nruntime_cutoff = 373.244\n\nf_out = open('selection_data.csv','w',1)\nf_out.write('#Possible data for use in selecting which configuration to use.\\n')\nf_out.write('#Parameters, ESA best fit model type, model param 1, model param 2, RMSE (support), RMSE (challenge), predicted median running time, PAR10 on intermediate problems, median running time on 3500 cities, median running time on 4000 cities, median running time on 4500 cities, approx. Q-90 on 3500 cities, approx. Q-90 on 4000 cities, approx. Q-90 on 4500 cities, PAR10 on 3500 citiices, PAR10 on 4000 cities, PAR10 on 4500 cities\\n')\n\n\nfor ind in range(1,26):\n with open('config-' + str(ind) + '-medians.csv') as f_temp:\n line = f_temp.readline()\n #Note that I made a mistake when spelling parameters in all of the files...\n while('#Parmeters' not in line):\n line = f_temp.readline()\n \n #Extract the parameter string\n params = line.split(\",\")[0].strip().split(\":\")[1].strip()\n #f_out.write(params.replace(\" \",\"_\") + ', ')\n #print(params)\n #Find the line that corresponds to this configuration in the file\n line = f.readline()\n while('#' in line[0] or params not in line):\n line = f.readline()\n f.seek(0)\n\n model = line.split(',')\n a = float(model[2].strip())\n b = float(model[3].strip())\n RMSE = float(model[5].strip())\n \n type = model[1].strip()\n if('poly' in type):\n f_out.write(params.replace(\" \",\"_\") + ', ')\n f_out.write('2, ')\n elif('rootexp' in type):\n f_out.write(params.replace(\" \",\"_\") + ', ')\n f_out.write('1, ')\n elif('exp' in type):\n f_out.write(params.replace(\" \",\"_\") + ', ')\n f_out.write('0, ')\n #f_out.write(model[1].strip() + ', ')\n f_out.write(str(a) + ', ')\n f_out.write(str(b) + ', ')\n f_out.write(model[4].strip() + ', ')\n f_out.write(str(RMSE) + ', ')\n\n if('poly' in model[1]):\n predMed = a*(testSize**b)\n \n elif('rootexp' in model[1]):\n predMed = a*b**(math.sqrt(testSize))\n \n elif('exp' in model[1]):\n predMed = a*b**testSize\n\n f_out.write(str(predMed) + ', ')\n\n #Find the file the corresponds to this configuration\n for i in range(1,26):\n f_times = open('selection_phase/config-' + str(i) + '-medians.csv')\n if(params not in f_times.read()):\n f_times.close()\n else:\n f_times.seek(0)\n break\n totalTime = 0\n count = 0\n for ln in f_times:\n result = ln.split(',')\n if('#' in result[0] or str(valSize) not in result[1]):\n continue\n count = count + 1\n time = float(result[2])\n if(time == float('inf')):\n totalTime = totalTime + runtime_cutoff*10\n else:\n totalTime = totalTime + time\n f_times.close()\n mean = totalTime/count\n\n f_out.write(str(mean) + ', ')\n\n #Find the file the corresponds to this configuration\n for i in range(1,26):\n f_times = open('config-' + str(i) + '-medians.csv')\n if(params not in f_times.read()):\n f_times.close()\n else:\n f_times.seek(0)\n break\n times = {}\n index = {}\n cutoff = {}\n #Keep track of an index for each size\n index['3500'] = 0\n index['4000'] = 0\n index['4500'] = 0\n #Preallocate arrays\n times['3500'] = [0.0]*100\n times['4000'] = [0.0]*100\n times['4500'] = [0.0]*100\n\n if(ind <= 4):\n cutoff['3500'] = 10000\n cutoff['4000'] = 10000\n cutoff['4500'] = 10000\n else:\n cutoff['3500'] = 800\n cutoff['4000'] = 2000\n cutoff['4500'] = 4000\n\n PAR10 = {}\n PAR10['3500'] = 0\n PAR10['4000'] = 0\n PAR10['4500'] = 0\n\n for line in f_times:\n if('#' in line[0]):\n continue\n vals = line.split(',')\n size = vals[1].strip()\n runtime = vals[2].strip()\n #print(float(runtime.replace('inf',cutoff[size])))\n times[size][index[size]] = float(runtime.replace('inf',str(cutoff[size]*10)))\n index[size] += 1\n if('inf' not in runtime):\n PAR10[size] += float(runtime)\n else:\n PAR10[size] += cutoff[size]*10\n\n f_times.close()\n\n for key in PAR10:\n PAR10[key] = PAR10[key]/100\n\n for key in times:\n times[key] = sorted(times[key])\n \n for key in times:\n f_out.write(str((times[key][49] + times[key][50])/2) + ', ')\n \n for key in times:\n f_out.write(str(times[key][89]) + ', ')\n\n j = 1\n for key in PAR10:\n if(j < 3):\n f_out.write(str(PAR10[key]) + ', ')\n else:\n f_out.write(str(PAR10[key]) + '\\n')\n j += 1\n\nf_out.close()\n","sub_path":"EAX/get_selection_data.py","file_name":"get_selection_data.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"609033479","text":"# this program is used to know the location and service provider of the mobile number\n\n\n# firstly, we need to install below in terminal\nimport phonenumbers\n\n#import test file which we have created in the same folder\nfrom test import number1 \nfrom test import number2\nfrom test import number3\nfrom test import number4\n\n\n# to check the country\nfrom phonenumbers import geocoder\n\nch_number1 =phonenumbers.parse(number1, \"CH\")\ncon1= geocoder.description_for_number(ch_number1,\"en\")\n\nch_number2 =phonenumbers.parse(number2, \"CH\")\ncon2=geocoder.description_for_number(ch_number2,\"en\")\n\nch_number3 =phonenumbers.parse(number3, \"CH\")\ncon3= geocoder.description_for_number(ch_number3,\"en\")\n\nch_number4 =phonenumbers.parse(number4, \"CH\")\ncon4= geocoder.description_for_number(ch_number4,\"en\")\n\n\n\n# to check the service provider\nfrom phonenumbers import carrier\n\nser_number1 =phonenumbers.parse(number1, \"RO\")\nser1 =carrier.name_for_number(ser_number1,\"en\")\n\nser_number2 =phonenumbers.parse(number2, \"RO\")\nser2 =carrier.name_for_number(ser_number2,\"en\")\n\nser_number3 =phonenumbers.parse(number3, \"RO\")\nser3 =carrier.name_for_number(ser_number3,\"en\")\n\nser_number4 =phonenumbers.parse(number4, \"RO\")\nser4 =carrier.name_for_number(ser_number4,\"en\")\n\nprint(\" Country for num1: \", con1)\nprint(\"service provider of num1: \", ser1)\nprint()\nprint(\" Country for num2: \", con2)\nprint(\"service provider of num2: \", ser2)\nprint()\nprint(\" Country for num3: \", con3)\nprint(\"service provider of num3: \", ser3)\nprint()\nprint(\" Country for num4: \", con4)\nprint(\"service provider of num4: \", ser4)","sub_path":"phone number/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"228444586","text":"\"\"\"\nBounding box methods usefull for Amsterdam.\n\"\"\"\n\n# Default amstermdam bbox lon, lat, lon, lat\n# square around Amsterdam.\nBBOX = [52.03560, 4.58565,\n 52.48769, 5.31360]\n\n\ndef determine_bbox(request):\n \"\"\"\n Create a bounding box if it is given with the request.\n \"\"\"\n\n err = \"invalid bbox given\"\n\n if 'bbox' not in request.query_params:\n # set default value\n return BBOX, None\n\n bboxp = request.query_params['bbox']\n bbox, err = valid_bbox(bboxp)\n\n if err:\n return None, err\n\n return bbox, err\n\n\ndef valid_bbox(bboxp):\n \"\"\"\n Check if bbox is a valid bounding box\n \"\"\"\n bbox = bboxp.split(',')\n err = None\n\n # check if we got 4 parametes\n if not len(bbox) == 4:\n return [], \"wrong numer of arguments (lon, lat, lon, lat)\"\n\n # check if we got floats\n try:\n bbox = [float(f) for f in bbox]\n except ValueError:\n return [], \"Did not recieve floats\"\n\n # max bbox sizes from mapserver\n # RD EXTENT 100000 450000 150000 500000\n # WGS 52.03560, 4.58565 52.48769, 5.31360\n lat_min = 52.03560\n lat_max = 52.48769\n lon_min = 4.58565\n lon_max = 5.31360\n\n # check if coorinates are withing amsterdam\n # lat1, lon1, lat2, lon2 = bbox\n\n # bbox given by leaflet\n lon1, lat1, lon2, lat2 = bbox\n\n if not lat_max >= lat1 >= lat_min:\n err = f\"lat not within max bbox {lat_max} > {lat1} > {lat_min}\"\n\n if not lat_max >= lat2 >= lat_min:\n err = f\"lat not within max bbox {lat_max} > {lat2} > {lat_min}\"\n\n if not lon_max >= lon2 >= lon_min:\n err = f\"lon not within max bbox {lon_max} > {lon2} > {lon_min}\"\n\n if not lon_max >= lon1 >= lon_min:\n err = f\"lon not within max bbox {lon_max} > {lon1} > {lon_min}\"\n\n # this is how the code expects the bbox\n bbox = [lat1, lon1, lat2, lon2]\n\n return bbox, err\n","sub_path":"api/datapunt_api/bbox.py","file_name":"bbox.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"491546948","text":"from Stack import Stack\n\npilha = Stack()\nmenu = '''\n+--------MENU--------+\n| 1 - Adicionar |\n| 2 - Remover |\n| 3 - Imprimir |\n| 0 - Sair |\n+--------------------+\nEscolha: '''\n\nwhile True:\n opcao = (input(menu))\n if opcao == '0':\n break\n elif opcao == '1':\n pilha.stack_push(input('Informe o valor: '))\n elif opcao == '2':\n pilha.stack_pop() \n elif opcao == '3':\n pilha.stack_print() \n else:\n print('=== Opção inválida ===')","sub_path":"Aula05/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"236793598","text":"\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow.contrib.slim as slim\nimport os\nimport scipy.misc\nimport scipy\nimport gzip\nimport pickle\nimport time\nfrom helpers import *\nfrom sklearn.model_selection import train_test_split\nfrom scipy import stats\nfrom tensorflow.examples.tutorials.mnist import input_data\n\ndef MaxScaleCenterData(data):\n data = data - data.min()\n data = data / data.max()\n data = (data - 0.5)*2\n return data\n\nbatch_size = 128 \niterations = 2001\ndim_show_example = 8\nimg_dim = 64\nimg_chan = 1\nz_size = 2\nlcat_size = 6\nnumber_continuous = 2\nflag_WGAN =0 \nflag_code_dist = 0\nflag_trunc_normal = 0\nflag_normal=0\nflag_uniform=1\nset_code_mu = 0\nset_code_sigma = 1\nset_code_lower = -1\nset_code_upper = 1\nsample_directory = './figs' \nmodel_directory = './models'\ncollecting_directory = './Uniform_bsz_'+str(batch_size)+'_z_'+str(z_size)+'_zk_'+str(lcat_size)+'_zc_'+str(number_continuous)+'_Its_'+str(iterations)+'_64S'\nos.system('mkdir ' + collecting_directory)\nseed = 77\n\nflag_code_dist = 0\nflag_trunc_normal = 1\nflag_normal = 0\nflag_uniform = 0\nconstant_zbatch = np.random.uniform(-1.0,1.0,size=[ lcat_size * dim_show_example , z_size]).astype(np.float32) \n\n\nnp_rng = np.random.RandomState(seed)\n\n\nload_dir = '/home/charles/Documents/code/Tensorflow/Data/ChannelizedMedia' \nfilename = '/OptSnapshots.pkl.gz'\nfilename = '/reduced_45000_83_snesim_realizations_0_5000.pkl.gz'\n\n\nwith gzip.open(load_dir + filename,'rb') as fp:\n images = pickle.load(fp)\nimages = images[:,:2025]\nh=64; dh=2\n\nX = images[:,:,:,None]\nx_train, x_test = train_test_split(X, test_size=0.3)\nx_val, x_test = train_test_split(x_test, test_size=0.10)\n# scale and shift\nx_train = PreprocessImages(x_train[: , : h+dh, : h+dh, 0], dw=h, dh=h, ht=h, wt=h, doreshape=0)\n# apply same scaling to test and validation sets\nx_test = MaxScaleCenterData(x_test[:,:h,:h])\nx_val = MaxScaleCenterData(x_val[:,:h,:h])\n\n#shuffle\nx_train = shuffles(x_train,nshuffles=20)\n\n#use PCA\nif flag_code_dist==1:\n data_z = np.copy(x_train)\n data_z = np.reshape(data_z,[x_train.shape[0], x_train.shape[1] * x_train.shape[2]])\n pca_z = PCA(n_components=2)\n zy = pca_z.fit_transform(data_z)\n\n\ndef generator(z):\n# go1 = 512\n# go2 = 256\n# go3 = 128\n with tf.variable_scope(\"generator\"):\n nhchan = 256 #depends on number of deconvolutions / convolutions with d2s\n nz_dim = int(img_dim/8.) \n nout1 = nhchan * nz_dim**2 * img_chan #4*img_dim**2 #2*2*4*4*256\n go1 = 128 * img_chan\n go2 = 64 * img_chan\n go3 = 32 * img_chan\n go4 = 1 * img_chan #1\n print(img_chan)\n\n zP = slim.fully_connected(z, nout1 ,normalizer_fn=slim.batch_norm, \n activation_fn=tf.nn.relu,scope='g_project',\n weights_initializer=initializer)\n print(\"zP\", zP.get_shape())\n zCon = tf.reshape(zP,[-1, nz_dim, nz_dim, nhchan])\n print(zCon.get_shape())\n\n\n gen1 = slim.convolution2d(zCon, \n num_outputs=go1,\n kernel_size=[3,3],\n padding=\"SAME\",\n normalizer_fn=slim.batch_norm,\n activation_fn=tf.nn.relu,scope='g_conv1',\n weights_initializer=initializer)\n gen1 = tf.depth_to_space(gen1,2)\n print(gen1.get_shape())\n\n gen2 = slim.convolution2d(gen1,\n num_outputs=go2,\n kernel_size=[3,3],\\\n padding=\"SAME\",\\\n normalizer_fn=slim.batch_norm,\\\n activation_fn=tf.nn.relu,\n scope='g_conv2', \\\n weights_initializer=initializer)\n gen2 = tf.depth_to_space(gen2,2)\n print(gen2.get_shape())\n\n gen3 = slim.convolution2d(gen2,\n num_outputs=go3,\n kernel_size=[3,3],\\\n padding=\"SAME\",\n normalizer_fn=slim.batch_norm,\\\n activation_fn=tf.nn.relu,\n scope='g_conv3', \n weights_initializer=initializer)\n gen3 = tf.depth_to_space(gen3,2)\n print(\"gen3: \", gen3.get_shape())\n\n g_out = slim.convolution2d(gen3,\n num_outputs=go4,\n kernel_size=[32,32],\n padding=\"SAME\",\\\n biases_initializer=None,\n activation_fn=tf.nn.tanh,\\\n scope='g_out', \n weights_initializer=initializer)\n\n print(\"g_out: \",g_out.get_shape())\n print(\"End Generator\")\n return g_out\n\ndef discriminator(bottom, cat_list,conts, reuse=False):\n\n with tf.variable_scope(\"discriminator\"):\n do1 = 32 * img_chan\n do2 = 64 * img_chan\n do3 = 128 * img_chan\n do4 = 1024 * img_chan\n do5 = 1 * img_chan\n f = 3\n print(bottom.get_shape())\n dis1 = slim.convolution2d(bottom,\n do1,\n f,\n padding=\"SAME\",\\\n biases_initializer=None,activation_fn=lrelu,\\\n reuse=reuse,scope='d_conv1',weights_initializer=initializer)\n dis1 = tf.space_to_depth(dis1,2)\n print(dis1.get_shape())\n\n dis2 = slim.convolution2d(dis1,\n do2,\n f,\n padding=\"SAME\",\\\n normalizer_fn=slim.batch_norm,activation_fn=lrelu,\\\n reuse=reuse,scope='d_conv2', weights_initializer=initializer)\n dis2 = tf.space_to_depth(dis2,2)\n print(dis2.get_shape())\n\n dis3 = slim.convolution2d(dis2,\n do3,\n f,\n padding=\"SAME\",\\\n normalizer_fn=slim.batch_norm,activation_fn=lrelu,\\\n reuse=reuse,scope='d_conv3',weights_initializer=initializer)\n dis3 = tf.space_to_depth(dis3,2)\n print(dis3.get_shape())\n\n dis4 = slim.fully_connected(slim.flatten(dis3),\n do4,\n activation_fn=lrelu,\\\n reuse=reuse,scope='d_fc1', weights_initializer=initializer)\n print(\"dis4: \", dis4.get_shape())\n\n if img_chan > 1:\n dis4 = tf.reshape(dis4,[-1, img_dim, img_dim, img_chan])\n\n# #Remove/Replace in order to use WGAN\n if flag_WGAN==0:\n d_out = slim.fully_connected(dis4,\n do5,\n activation_fn=None,\\\n reuse=reuse,scope='d_out', \n weights_initializer=initializer)\n else:\n d_out = dis4\n print(\"d_out: \", d_out.get_shape())\n \n print(\"End Discriminator\")\n q_a = slim.fully_connected(dis4,128 * img_chan,normalizer_fn=slim.batch_norm,reuse=reuse,scope='q_fc1', weights_initializer=initializer)\n print(\"q_a\",q_a.get_shape())\n\n ## AUXILIARY NETWORK, mislabeled.\n with tf.variable_scope(\"variational_dist\"):\n q_cat_outs = []\n for idx,var in enumerate(cat_list):\n q_outA = slim.fully_connected(q_a,var,activation_fn=tf.nn.softmax,reuse=reuse,scope='q_out_cat_'+str(idx), weights_initializer=initializer)\n print(\"q_outA\",q_outA.get_shape())\n q_cat_outs.append(q_outA)\n print(\"q_cat_outs\", len(q_cat_outs))\n print(\"q_cat_outs[0]\", q_cat_outs[0].get_shape())\n\n q_cont_outs = None\n if conts > 0:\n q_cont_outs = slim.fully_connected(q_a,conts,activation_fn=tf.nn.tanh,reuse=reuse,scope='q_out_cont_'+str(conts), weights_initializer=initializer)\n print(\"q_cont_outs\",q_cont_outs.get_shape())\n\n print(\"End Variational\")\n\n return d_out,q_cat_outs,q_cont_outs\n\n\ntf.reset_default_graph()\ninitializer = tf.truncated_normal_initializer(stddev=0.02)\n\nz_in = tf.placeholder(shape=[None,z_size],dtype=tf.float32) \nreal_in = tf.placeholder(shape=[None, img_dim, img_dim, img_chan],dtype=tf.float32) \n\n#define all categorical and continuous latent variables\ncategorical_list = [lcat_size]\nlatent_cat_in = tf.placeholder(shape=[None,len(categorical_list)],dtype=tf.int32)\nlatent_cat_list = tf.split(latent_cat_in,len(categorical_list),1)\nlatent_cont_in = tf.placeholder(shape=[None,number_continuous],dtype=tf.float32)\noh_list = []\nfor idx,var in enumerate(categorical_list):\n latent_oh = tf.one_hot(tf.reshape(latent_cat_list[idx],[-1]),var)\n oh_list.append(latent_oh)\nz_lats = oh_list[:]\nz_lats.append(z_in)\nz_lats.append(latent_cont_in)\nz_lat = tf.concat(z_lats,1)\n\n\nGz = generator(z_lat) \nDx,_,_ = discriminator(real_in,categorical_list,number_continuous)\nDg,QgCat,QgCont = discriminator(Gz,categorical_list,number_continuous,reuse=True) \nprint(\"Gz: \", Gz.get_shape())\nprint(\"Dx: \", Dx.get_shape())\nprint(\"Dg: \", Dg.get_shape())\n\n\n#modify discriminator: replace logs by identity for GAN\n# d_loss = -tf.reduce_mean(tf.log(Dx) + tf.log(1.-Dg))\nd_loss = -tf.reduce_mean( Dx) + tf.reduce_mean( Dg )\n\n#modify g_loss = KL Divergence optimizer + reconstruction error\n# g_loss = -tf.reduce_mean(tf.log((Dg/(1-Dg)))) \n#modify also for WGAN\n# g_loss = -tf.reduce_mean(tf.log((Dg/(1-Dg)))) #+ tf.reduce_mean( tf.square( tf.subtract(Gz , real_in ) ) )\ng_loss = -tf.reduce_mean(Dg) \n\n#WGAN: clip the gradients of the discriminator (does this include variational component?)\nclip_d = [p.assign(tf.clip_by_value(p, -0.01, 0.01)) for p in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='discriminator')]\n\n\n#Combine losses for each of the categorical variables.\ncat_losses = []\nfor idx,latent_var in enumerate(oh_list):\n cat_loss = -tf.reduce_sum(latent_var*tf.log(QgCat[idx]),axis=1)\n cat_losses.append(cat_loss)\n \n#Combine losses for each of the continous variables.\nif number_continuous > 0:\n q_cont_loss = tf.reduce_sum(0.5 * tf.square(latent_cont_in - QgCont), axis=1)\nelse:\n q_cont_loss = tf.constant(0.0)\n\nq_cont_loss = tf.reduce_mean(q_cont_loss)\nq_cat_loss = tf.reduce_mean(cat_losses)\nq_loss = tf.add(q_cat_loss,q_cont_loss)\nprint(\"q_cont_loss: \", q_cont_loss)\nprint(\"q_cat_loss: \", q_cat_loss)\nprint(\"q_loss: \", q_loss.get_shape())\ntvars = tf.trainable_variables()\n\ntrainerD = tf.train.AdamOptimizer(learning_rate=0.0002,beta1=0.5)\ntrainerG = tf.train.AdamOptimizer(learning_rate=0.002,beta1=0.5)\ntrainerQ = tf.train.AdamOptimizer(learning_rate=0.0002,beta1=0.5)\n\nd_grads = trainerD.compute_gradients(d_loss,tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='discriminator')) \ng_grads = trainerG.compute_gradients(g_loss,tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='generator'))\nq_grads = trainerQ.compute_gradients(q_loss,tvars) \n\nupdate_D = trainerD.apply_gradients(d_grads)\nupdate_G = trainerG.apply_gradients(g_grads)\nupdate_Q = trainerQ.apply_gradients(q_grads)\n\n\nsummary_loss = []\n\nt0 = time.time()\ninit = tf.global_variables_initializer()\nsaver = tf.train.Saver()\nwith tf.Session() as sess: \n sess.run(init)\n for i in range(iterations):\n idx_batch = np.arange(i*batch_size,(i+1)*batch_size) % x_train.shape[0]\n \n #sample random variable values from PC distribution\n if flag_code_dist ==1:\n zs = zy[idx_batch , :z_size]\n #sample according to pre-define distribution\n else:\n if flag_trunc_normal==1:\n stats.truncnorm((set_code_lower - set_code_mu) / set_code_sigma, (set_code_upper - set_code_mu) / set_code_sigma, loc=set_code_mu, scale=set_code_sigma)\n elif flag_normal==1:\n zs = np_rng.normal(set_code_mu , set_code_sigma,size=[batch_size,z_size]).astype(np.float32) #Generate a random z batch\n elif flag_uniform==1:\n zs = np_rng.uniform(set_code_lower , set_code_lower , size=[batch_size,z_size]).astype(np.float32) #Generate a random z batch\n #sample cat/conts variable values from distribution\n lcat = np.random.randint(0,lcat_size,[batch_size,len(categorical_list)]) #Generate random c batch\n lcont = np.random.uniform(-1,1,[batch_size,number_continuous]) #\n \n# for mnist\n# xs,_ = mnist.train.next_batch(batch_size) #Draw a sample batch from MNIST dataset.\n# xs = (np.reshape(xs,[batch_size,28,28,1]) - 0.5) * 2.0 #Transform it to be between -1 and 1\n# xs = np.lib.pad(xs, ((0,0),(2,2),(2,2),(0,0)),'constant', constant_values=(-1, -1)) #Pad the images so the are 32x32\n# xs = (np.reshape(xs,[batch_size,h,w,1]) - 0.5) * 2.0 #Transform it to be between -1 and 1\n xs = x_train[idx_batch, :, :]\n \n #change dLoss for WGAN\n# _,dLoss = sess.run([update_D,d_loss],feed_dict={z_in:zs,real_in:xs,latent_cat_in:lcat,latent_cont_in:lcont}) #Update the discriminator\n _,dLoss,_ = sess.run([update_D,d_loss,clip_d],feed_dict={z_in:zs,real_in:xs,latent_cat_in:lcat,latent_cont_in:lcont}) #Update the discriminator\n _,gLoss = sess.run([update_G,g_loss],feed_dict={z_in:zs,real_in:xs, latent_cat_in:lcat,latent_cont_in:lcont}) #Update the generator, twice for good measure.\n _,qLoss,qK,qC = sess.run([update_Q,q_loss,q_cont_loss,q_cat_loss],feed_dict={z_in:zs,latent_cat_in:lcat,latent_cont_in:lcont}) #Update to optimize mutual information.\n\n #save summary\n summary_loss.append([gLoss, dLoss, qK, qC, qLoss])\n \n if i % 10 == 0:\n tfinal = time.time()\n# print(\"i: \",i,\"t: %.1f\"%(tfinal-t0),\"G: %.2f \"%str(gLoss) + \" D: \" + str(dLoss) + \" Q: \" + str([qK,qC]))\n \n print(\"i: %d t: %.1f G: %.2f D: %.2f Qi%.2f Qc%.2f\" % (i, tfinal-t0, gLoss, dLoss, qK, qC) )\n \n \n z_sample = np.random.uniform(-1.0,1.0,size=[lcat_size * dim_show_example , z_size]).astype(np.float32) #Generate another z batch\n lcat_sample = np.reshape(np.array([e for e in range(lcat_size) for _ in range(dim_show_example)]),[lcat_size * dim_show_example,1])\n a = np.reshape(np.array([[(e/4.5 - 1.)] for e in range(lcat_size) for _ in range(dim_show_example)]),[lcat_size , dim_show_example]).T\n b = np.reshape(a,[lcat_size * dim_show_example,1])\n c = np.zeros_like(b)\n lcont_sample = np.hstack([b,c])\n\n samples = sess.run(Gz,feed_dict={z_in:constant_zbatch,latent_cat_in:lcat_sample,latent_cont_in:lcont_sample}) #Use new z to get sample images from generator.\n if not os.path.exists(sample_directory):\n os.makedirs(sample_directory)\n #Save sample generator images for viewing training progress.\n save_images(np.reshape(samples[0:lcat_size*dim_show_example],[lcat_size*dim_show_example, img_dim, img_dim]),[lcat_size,dim_show_example],sample_directory+'/fig'+str(i)+'.png')\n \n \n if i % 500 == 0 and i != 0:\n if not os.path.exists(model_directory):\n os.makedirs(model_directory)\n saver.save(sess,model_directory+'/model-'+str(i)+'.cptk')\n print( \"Saved Model\")\n\n\n# In[301]:\n\ndef PlotQQData2Axes(plot_data,set_ylims=[0,1],set_ms=0.9,set_alpha=0.5):\n fig, ax = plt.subplots()\n axes = [ax]\n axes[0].plot( plot_data[:,2] ,'.', c='black', alpha=set_alpha, ms=set_ms,label='Q-Categorical')\n axes[0].plot( plot_data[:,3] ,'.', c='blue', alpha=set_alpha, ms=set_ms,label='Q-Continuous')\n axes[0].set_xlabel('Iteration')\n axes[0].set_ylabel('Loss (Q-cat, Q-con)')\n axes[0].grid()\n axes[0].set_ylim(set_ylims)\n lgnd1 = axes[0].legend(loc=\"upper right\", numpoints=1, fontsize=10)\n lgnd1.legendHandles[0]._legmarker.set_markersize(6)\n lgnd1.legendHandles[1]._legmarker.set_markersize(6)\n\n\ndef PlotGDQQData2Axes(plot_data,set_ms=0.9,set_alpha=0.5):\n fig, ax = plt.subplots()\n ax2 = ax.twinx()\n axes = [ax, ax2]\n axes[0].plot( plot_data[:,0] ,'.',c='green', alpha=set_alpha, ms=set_ms, label='Generator')\n axes[0].plot( plot_data[:,1] ,'.', c='red', alpha=set_alpha, ms=set_ms,label='Discriminator')\n axes[1].plot( plot_data[:,2] ,'.', c='black', alpha=set_alpha, ms=set_ms,label='Q-Categorical')\n axes[1].plot( plot_data[:,3] ,'.', c='blue', alpha=set_alpha, ms=set_ms,label='Q-Continuous')\n axes[0].set_xlabel('Iteration')\n axes[0].set_ylabel('Loss (D, G)')\n lgnd0 = axes[0].legend(loc=\"upper right\", numpoints=1, fontsize=10)\n lgnd0.legendHandles[0]._legmarker.set_markersize(6)\n lgnd0.legendHandles[1]._legmarker.set_markersize(6)\n axes[1].set_xlabel('Iteration')\n axes[1].set_ylabel('Loss (Q-cat, Q-con)')\n axes[1].grid()\n lgnd1 = axes[1].legend(loc=\"upper left\", numpoints=1, fontsize=10)\n lgnd1.legendHandles[0]._legmarker.set_markersize(6)\n lgnd1.legendHandles[1]._legmarker.set_markersize(6)\n# plt.show()\n\n\ndef PlotGDRatioQQData2Axes(plot_data,set_ylims=[-50,100],set_ms=0.9,set_alpha=0.5):\n fig, ax = plt.subplots()\n ax2 = ax.twinx()\n axes = [ax, ax2]\n axes[0].plot( plot_data[:,0]/(plot_data[:,1]+1e-2) ,'.',c='green', alpha=set_alpha, ms=set_ms, label='G/D')\n axes[1].plot( plot_data[:,2] ,'.', c='black', alpha=set_alpha, ms=set_ms,label='Q-Categorical')\n axes[1].plot( plot_data[:,3] ,'.', c='blue', alpha=set_alpha, ms=set_ms,label='Q-Continuous')\n axes[0].set_ylim(set_ylims)\n axes[0].set_xlabel('Iteration')\n axes[0].set_ylabel('Loss Ratio G/D')\n axes[0].grid()\n lgnd0 = axes[0].legend(loc=\"upper right\", numpoints=1, fontsize=10, markerscale = 10)\n# lgnd0.legendHandles._legmarker.set_markersize(6)\n #lgnd0.legendHandles[1]._legmarker.set_markersize(6)\n axes[1].set_xlabel('Iteration')\n axes[1].set_ylabel('Loss (Q-cat, Q-con)')\n axes[1].grid()\n lgnd1 = axes[1].legend(loc=\"upper left\", numpoints=1, fontsize=10, markerscale=10)\n# lgnd1.legendHandles[0]._legmarker.set_markersize(6)\n# lgnd1.legendHandles[1]._legmarker.set_markersize(6)\n# plt.show()\n\n\ndef PlotDGRatioQQData2Axes(plot_data,set_ylims=[-50,100],set_ms=0.9,set_alpha=0.5):\n fig, ax = plt.subplots()\n ax2 = ax.twinx()\n axes = [ax, ax2]\n axes[0].plot( plot_data[:,1]/(plot_data[:,0]+1e-2) ,'.',c='green', alpha=set_alpha, ms=set_ms, label='D/G')\n axes[1].plot( plot_data[:,2] ,'.', c='black', alpha=set_alpha, ms=set_ms,label='Q-Categorical')\n axes[1].plot( plot_data[:,3] ,'.', c='blue', alpha=set_alpha, ms=set_ms,label='Q-Continuous')\n axes[0].set_ylim(set_ylims)\n axes[0].set_xlabel('Iteration')\n axes[0].set_ylabel('Loss Ratio D/G')\n axes[0].grid()\n lgnd0 = axes[0].legend(loc=\"upper right\", numpoints=1, fontsize=10, markerscale = 10)\n\n axes[1].set_xlabel('Iteration')\n axes[1].set_ylabel('Loss (Q-cat, Q-con)')\n axes[1].grid()\n lgnd1 = axes[1].legend(loc=\"upper left\", numpoints=1, fontsize=10, markerscale=10)\n\n#gLoss, dLoss, qK, qC, QLoss\nlosses = np.array(summary_loss)\n\nplot_data = np.abs(losses)\nPlotGDQQData2Axes(plot_data)\nplt.savefig(sample_directory+'/lPlotGDQQData2Axes.png')\nplt.show()\n\nplot_data = losses\nPlotGDQQData2Axes(plot_data)\nplt.savefig(sample_directory+'/PlotGDQQData2Axes.png')\nplt.show()\n\nplot_data = losses\nPlotGDRatioQQData2Axes(plot_data)\nplt.savefig(sample_directory+'/PlotGDRatioQQData2Axes.png')\nplt.show()\n\nplot_data = losses\nPlotGDRatioQQData2Axes(plot_data,set_ylims=[0,10])\nplt.savefig(sample_directory+'/PlotGDRatioQQData2Axes_ylim.png')\nplt.show()\n\nplot_data = losses\nPlotDGRatioQQData2Axes(plot_data,set_ylims=[0,1])\nplt.savefig(sample_directory+'/PlotDGRatioQQData2Axes_ylim.png')\nplt.show()\n\nplot_data = losses\nPlotQQData2Axes(plot_data)\nplt.savefig(sample_directory+'/PlotQQData2Axes.png')\nplt.show()\n\nplot_data = losses\nPlotQQData2Axes(plot_data,set_ylims=[0,1])\nplt.savefig(sample_directory+'/PlotQQData2Axes_ylim.png')\nplt.show()\n\nnp.savetxt(sample_directory+'/losses',losses)\n\n\n\n#Load Saved Session and plot continuous changes in realizations for a sequence of categories \n\nimport tensorflow as tf\nx_train = MaxScaleCenterData( np.reshape( mnist.train._images, [55000,28,28]) )\n\nsample_directory = './figs' #Directory to save sample images from generator in.\nmodel_directory = './models' #Directory to load trained model from.\ndim_show_example = 10\ndim_show_example2 = dim_show_example**2\nsess = tf.Session()\n\ninit = tf.global_variables_initializer()\nsaver = tf.train.Saver()\nwith tf.Session() as sess: \n sess.run(init)\n ckpt = tf.train.get_checkpoint_state(model_directory)\n saver.restore(sess,ckpt.model_checkpoint_path)\n\n i=0\n idx_batch = np.arange(i*batch_size,(i+1)*batch_size) % x_train.shape[0]\n if flag_code_dist==1:\n zs = zy[idx_batch , :z_size]\n constant_zbatch = zs[: dim_show_example, :]\n xs = x_train[idx_batch, :, :]\n \n\n '''\n Generate Plot of fixed code, for sequence of fixed categories and varying 2 continuous variables\n '''\n# z_sample = np.random.uniform(-1.0,1.0, [lcat_size * dim_show_example**2 , z_size]).astype(np.float32) \n zr = np.random.uniform(-1.0,1.0, [1 , z_size]).astype(np.float32) \n zr = np.repeat(zr, lcat_size * dim_show_example**2, axis=0)\n\n zk = np.array([[e] for _ in range(dim_show_example) for _ in range(dim_show_example)for e in range(lcat_size)])\n\n zc1=zc2 = np.linspace(-1,1,dim_show_example) \n zc = np.array( [[zc1[i], zc2[j]] for i in range(dim_show_example) for j in range(dim_show_example)] )\n zc = np.repeat( zc, lcat_size,axis=0)\n print(\"zr: \", zr.shape)\n print(\"zk: \", zk.shape)\n print(\"zc: \", zc.shape)\n samples = sess.run(Gz,feed_dict={z_in: zr,\n latent_cat_in:zk,\n latent_cont_in:zc}) \n\ndcz = dim_show_example\ndcz2 = dcz**2\nif not os.path.exists(sample_directory):\n os.makedirs(sample_directory)\n \n\n \nfor zkval in range(lcat_size):\n im_array = samples[zkval::lcat_size ,:,:,0]\n print(im_array.shape)\n Block = np.bmat([ [im_array[i+dim_show_example*j] for i in range(dim_show_example)] for j in range(dim_show_example)])\n Block.shape\n img = plt.imshow(Block)\n img.set_cmap('hot')\n plt.axis('off')\n plt.savefig(sample_directory+'/samples_zk_'+str(zkval)+'.png',dpi=1000, bbox_inches='tight')\n plt.show()\n \n with gzip.open(sample_directory+'/samples_zk_'+str(zkval)+'.pkl.gz','w') as fp:\n pickle.dump( samples, fp)\n\n \n# data_y_pca_recon = pca_y.inverse_transform(constant_zbatch)\n# data_y_pca_recon = np.reshape(data_y_pca_recon, [data_y_pca_recon.shape[0], img_dim, img_dim, 1])\n# samples_pca_recon = data_y_pca_recon\n# save_images(np.reshape(samples_pca_recon[0:lcat_size*dim_show_example],[lcat_size*dim_show_example, img_dim, img_dim]),[lcat_size,dim_show_example],sample_directory+'/fig_test_pca_recon'+'.png')\n# save_images(np.reshape(xs[0:lcat_size*dim_show_example],[lcat_size*dim_show_example, img_dim, img_dim]),[lcat_size,dim_show_example],sample_directory+'/fig_test_data'+'.png')\n# x1 = np.reshape(samples[0:lcat_size*dim_show_example],[lcat_size*dim_show_example, img_dim, img_dim])\n# x2 = np.reshape(xs[0:lcat_size*dim_show_example],[lcat_size*dim_show_example, img_dim, img_dim])\n# data_samples = np.concatenate((x1,x2))\n# save_images(data_samples,[2*lcat_size,dim_show_example],sample_directory+'/fig_test_data_samples'+'.png')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom sklearn.metrics import pairwise_distances\ngen_data = []\n\nfor zk in range(lcat_size):\n gen_data.append(samples[zk::lcat_size,:,:].tolist())\n\nn=2500\nd=64\ndata = (np.reshape(samples[zk::lcat_size],[n,d*d])/2.0 + 0.5)\nnmodes=100\npca = PCA(n_components = nmodes, copy=True, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', random_state=None)\ndata_pca = pca.fit_transform( data )\ndata_recon = pca.inverse_transform(data_pca)\n\nnshow = 10\nnshow2 = nshow**2 \nimages = np.reshape(pca.components_,[nmodes,d,d])\nim_array = images[:nshow2,:,:]\nBlock = np.bmat( [im_array[i] for i in range(nshow)] )\nimg = plt.imshow(Block)\nimg.set_cmap('hot')\nplt.axis('off')\nplt.savefig('GeneratedSnapshots_Modes.png',dpi=100, bbox_inches='tight')\nplt.show()\n\nprint(\"Noise Variance: \" , pca.noise_variance_)\n\nplt.plot(np.cumsum(pca.explained_variance_) / (pca.noise_variance_ + np.sum(pca.explained_variance_) ))\nplt.xlabel('Number of Modes,')\nplt.ylabel('Cumulative Explained Variance ')\nplt.grid()\nplt.savefig('GeneratedSnapshots_CEV.png',dpi=100, bbox_inches='tight')\nplt.show()\n\npcidx1=0\npcidx2=1\nnbins = 5\n\nx = data_pca[:,pcidx1]#/pca.explained_variance_[0]\ny = data_pca[:,pcidx2]#/pca.explained_variance_[1]\nh, x, y, p = plt.hist2d(x, y, bins = nbins)\nplt.clf()\nplt.imshow(h, origin = \"lower\", interpolation = \"gaussian\")\n# plt.plot(x,y,'.')\nplt.xlabel('PC '+str(pcidx1))\nplt.ylabel('PC '+str(pcidx2))\nplt.grid()\nplt.colorbar()\nplt.savefig(\"GeneratedSnapshots.pdf\",dpi=100, bbox_inches='tight')\nplt.show()\n\n\nfrom sklearn.neighbors import KernelDensity\nfrom sklearn.model_selection import GridSearchCV\n# use grid search cross-validation to optimize the bandwidth\nparams = {'bandwidth': np.logspace(-1, 1, 20)}\ngrid = GridSearchCV(KernelDensity(), params)\ngrid.fit( data_pca[:,:nmodes] )\nprint(\"best bandwidth: {0}\".format(grid.best_estimator_.bandwidth))\n# use the best estimator to compute the kernel density estimate\nkde = grid.best_estimator_\n# sample points from the data\nnsamples_kde = 10\nnew_data = kde.sample( nsamples_kde, random_state=0)\nnew_data = pca.inverse_transform(new_data)\n# grid data\nnew_data = new_data.reshape((1, nsamples_kde, -1))\nreal_data = data[:nsamples_kde].reshape((1, nsamples_kde, -1))\nBlock1 = np.bmat( [ np.reshape(real_data[0,i,:],[d,d]) for i in range(nsamples_kde)] )\nBlock2 = np.bmat( [ np.reshape(new_data[0,i,:],[d,d]) for i in range(nsamples_kde)] )\nBlock = np.vstack((Block1,Block2))\nimg = plt.imshow(Block)\nimg.set_cmap('hot')\nplt.axis('off')\nplt.savefig('GeneratedSnapshots_KDESamples'+str(nmodes)+'.png',dpi=100, bbox_inches='tight')\nplt.show()\n\n\n\n\nplt.figure()\nfor nsamples_kde in 2**np.arange(6,14,1): #[100,1000]:#,10000]:\n new_data = kde.sample( nsamples_kde, random_state=0); new_data = pca.inverse_transform(new_data)\n pwd = pairwise_distances(X=new_data, Y=data, metric='euclidean')\n# plt.plot(pwd.min(axis=0),'.',alpha=0.5,ms=2)\n plt.hist(pwd.min(axis=0),alpha=0.8,bins=10,normed=True, label=str(nsamples_kde)+' samples')\n plt.legend()\nplt.grid()\nplt.xlabel('Minimum Distance (KDE Samples to Real Data)')\nplt.savefig('GeneratedSnapshots_KDESamplesPWD'+str(nmodes)+'.png',dpi=100, bbox_inches='tight')\nplt.show()\nprint(\"Mean Reconstruction Error: \", np.linalg.norm( (data_recon-data).mean(axis=0),2) )\n","sub_path":"paper/PCA_Info_WGAN.py","file_name":"PCA_Info_WGAN.py","file_ext":"py","file_size_in_byte":27097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"287560772","text":"from socket_client import SocketClient\nfrom chat_pb2 import *\n\n\nclass Client:\n sc = None\n id = None\n token = None\n _self = None\n _users = []\n\n def __init__(self, host: str) -> None:\n addr, port = host.split(':')\n host = (addr, int(port))\n self.sc = SocketClient(host)\n\n def check_login(self):\n if self.id is None:\n raise Exception(\"Must login first\")\n\n def login(self, username, password):\n req = LoginRequest()\n req.username = username\n req.password = password\n rsp = self.sc.send(req, LoginResponse)\n if not rsp.success:\n raise Exception('Failed to login: %s' % rsp.info)\n self.token = rsp.token\n self.sc.token = rsp.token\n self.id = rsp.id\n\n def logout(self):\n self.check_login()\n req = LogoutRequest()\n req.senderID = self.id\n rsp = self.sc.send(req, Response)\n if not rsp.success:\n raise Exception('Failed to logout: %s' % rsp.info)\n\n def signup(self, username, password):\n req = SignupRequest()\n req.username = username\n req.password = password\n rsp = self.sc.send(req, Response)\n if not rsp.success:\n raise Exception('Failed to signup: %s' % rsp.info)\n\n def get_users(self) -> [UserInfo]:\n self.check_login()\n req = GetUserInfosRequest()\n req.senderID = self.id\n rsp = self.sc.send(req, GetUserInfosResponse)\n self._users = rsp.users\n self._self = [u for u in self._users if u.id == self.id][0]\n return rsp.users\n\n def get_self(self) -> UserInfo:\n if self._self is None:\n self.get_users()\n return self._self\n\n def get_messages(self, afterTime=0) -> [ChatMessage]:\n self.check_login()\n req = GetMessagesRequest()\n req.senderID = self.id\n req.afterTimeUnix = int(afterTime)\n rsp = self.sc.send(req, GetMessagesResponse)\n return rsp.messages\n\n def get_userid(self, username) -> int:\n self.check_login()\n users = self.get_users()\n users = [u for u in users if u.username == username]\n if len(users) == 0:\n raise Exception('No such user \\'%s\\'' % username)\n return users[0].id\n\n def make_friend_with(self, username):\n self.check_login()\n req = MakeFriendRequest()\n req.senderID = self.id\n req.targetID = self.get_userid(username)\n rsp = self.sc.send(req, Response)\n if not rsp.success:\n raise Exception('Failed to make friend: %s' % rsp.info)\n\n def send_message(self, targetId, text):\n self.check_login()\n req = ChatMessage()\n req.senderID = self.id\n req.targetID = targetId\n # req.timeUnix = 0\n req.text = text\n rsp = self.sc.send(req, Response)\n if not rsp.success:\n raise Exception('Failed to send message: %s' % rsp.info)\n\n def send_file(self, targetId, filepath):\n self.check_login()\n req = ChatMessage()\n req.senderID = self.id\n req.targetID = targetId\n # req.timeUnix = 0\n file = open(filepath, 'rb')\n data = file.read()\n file.close()\n req.file = data\n rsp = self.sc.send(req, Response)\n if not rsp.success:\n raise Exception('Failed to send file: %s' % rsp.info)\n\n def recv_message(self) -> [ChatMessage]:\n self.check_login()\n req = GetMessagesRequest()\n req.senderID = self.id\n rsp = self.sc.send(req, GetMessagesResponse)\n return rsp.messages\n","sub_path":"Server/src/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"361085404","text":"from __future__ import print_function\nfrom openmdao.api import Component, Problem, Group\nfrom openmdao.api import MetaModel\nfrom openmdao.api import FloatKrigingSurrogate\n\nfrom openmdao.api import IndepVarComp\nfrom MOE import moe_surrogate\nimport csv\nimport numpy as np\nimport math\n\ndim=2\ntrain = open(\"D:/rpriem/Documents/Melange_expert/Code/MOE/test/DONNEES/BRANIN_Train.csv\")\ncsvreader = csv.reader(train)\n\nx = []\nfor i in range(dim):\n x.append([])\ny = []\n\nfor row in csvreader:\n for i in range(dim):\n x[i].append(float(row[i]))\n y.append(float(row[dim]))\n \nX_train = x[0]\nfor i in range(1,dim): \n X_train = np.c_[X_train,x[i]]\nX_train = np.array(X_train)\nY_train = y\ntrain.close()\n\nche_valid = \"D:/rpriem/Documents/Melange_expert/Code/MOE/test/DONNEES/BRANIN_Valid.csv\"\nfichier = open(che_valid)\ncsvreader = csv.reader(fichier)\nx = []\nfor i in range(dim):\n x.append([])\nfor row in csvreader:\n for i in range(dim):\n x[i].append(float(row[i]))\n \nX_valid = x[0]\nfor i in range(1,dim): \n X_valid = np.c_[X_valid,x[i]]\nX_valid = np.array(X_valid)\n\nfichier.close() \nY_valid = [] \nfichier = open(che_valid)\ncsvreader = csv.reader(fichier) \n\nfor row in csvreader:\n Y_valid.append(float(row[dim])) \nfichier.close() \n\nclass KringingMod():\n def __init__(self):\n self.mod = KrigingSurrogate()\n self.dim = 0\n self.jaco = True\n \n def train(self,x,y):\n self.mod.train(x,y)\n self.dim = len(x[0])\n \n def predict(self,x):\n retour = []\n if self.dim == 1 :\n if isinstance(x,float) or isinstance(x,np.float64):\n retour.append(self.mod.predict(x)[0][0])\n else:\n for i in range(len(x)):\n retour.append(self.mod.predict(x[i])[0][0])\n else : \n if isinstance(x[0],float) or isinstance(x[0],np.float64):\n retour.append(self.mod.predict(x)[0][0])\n else:\n for i in range(len(x)):\n retour.append(self.mod.predict(x[i])[0][0])\n return retour\n \n def jacobian(self,x):\n return self.mod.jacobian(x)\n\n\ndef krig(x,y):\n mod = KringingMod()\n mod.train(x,y)\n return mod\n\nclass N1(Group):\n def __init__(self):\n super(N1,self).__init__()\n \n surro = FloatKrigingSurrogate()\n #surro = moe_surrogate.MixtureOfExpertsSurrogate(dim,detail=True,plot=False,nCluster=16)\n #surro.addModel(lambda x,y:krig(x,y),'Kringing OpenMDAO') \n \n N1E1=self.add(\"N1E\",MetaModel())\n N1E1.add_param('x',val=X_train[0])\n N1E1.add_output('fx:float',val=0.,surrogate = surro)\n \n comp = self.add('p1',IndepVarComp('x',val=X_train[0]))\n \n self.connect('p1.x','N1E.x')\n \n\n\nprob=Problem()\nprob.root = N1()\n\nprob.setup()\n\nprob['N1E.train:x'] = X_train\nprob['N1E.train:fx:float'] = Y_train\n\n\nprob.run()\nY_test = []\nl2_carre=0\ni=0\nfor x in X_valid:\n prob['p1.x']=x\n prob.run()\n Y_test.append(prob['N1E.fx:float'])\n l2_carre = l2_carre+math.pow((Y_test[i]-Y_valid[i]),2)\n i=i+1\nRMSE = math.sqrt(l2_carre/len(X_valid))\n\nprint(Y_valid)\nprint (Y_test)\nprint (prob.calc_gradient(['p1.x'],['N1E.fx:float']))\nprint('float predicted:', prob['N1E.fx:float']) \n\n\n\n","sub_path":"MOE/test/test_open.py","file_name":"test_open.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"461660139","text":"# System Imports\nimport math\n\n# Framework imports\nfrom planner.models import Nutrient\n\n# Local Imports\nfrom .RecipeObject import RecipeObject\nfrom .PrefObject import PrefObject\n\ndef get_shopping_lists(user):\n\n # Retrieve user preference object\n pref_obj = PrefObject(user, is_user=True)\n\n # Retrieve all recipes for next week\n recipe_objects = []\n for rec_id in pref_obj.assigned_recipes[21:]:\n if rec_id != '-1':\n recipe_objects.append(RecipeObject(rec_id, is_ID=True))\n\n # Retrieve all ingredients\n ing_list = [x for recipe in recipe_objects for x in recipe.ingredients]\n\n # Count number of staples\n staples = 0\n\n # Construct dictionary of all ingredients | {'name':(amount,unit), ...}\n ingredients = {}\n for ingredient in ing_list:\n\n # Retrieve the nutritional values for the ingredient\n obj = Nutrient.objects.get(name=ingredient['name'])\n\n # Retrieve units and their corresponding amounts for ingredient\n uts = [obj.unit_type_1,obj.unit_type_2,obj.unit_type_3,obj.unit_type_4]\n ats = [obj.unit_amount_1,obj.unit_amount_2,obj.unit_amount_3,obj.unit_amount_4]\n\n amount = float(ingredient['amount'])\n unit = 'g'\n staple = obj.staple\n staples += staple\n\n # Convert units if required\n if ingredient['unit'] != 'g' and ingredient['unit'] != 'ml':\n amount = float(ingredient['amount']) * ats[uts.index(ingredient['unit'])]\n\n # Convert to ml if required\n if obj.liquid == True: unit = 'ml'\n\n # Convert to whole if required\n if 'whole' in uts:\n unit = ''\n index = uts.index('whole')\n if ats[index] != 0:\n amount = math.ceil(amount/ats[index])\n\n # Add to dictionary\n if ingredient['name'] in ingredients:\n ingredients[ingredient['name']][0] += amount\n else:\n ingredients[ingredient['name']] = [amount, unit, staple]\n\n # Create list for alphabetical display | [('A', [items])]\n alphabetical = []\n for key in sorted(ingredients.keys()):\n\n amount = str(int(math.ceil(ingredients[key][0])))\n item = key + ' (' + amount + ingredients[key][1] + ')'\n s = ingredients[key][2]\n\n if len(alphabetical) == 0 or key[0].upper() != alphabetical[-1][0]:\n alphabetical.append((key[0].upper(), [(item[0].upper()+item[1:], s)]))\n else:\n alphabetical[-1][1].append((item[0].upper()+item[1:], s))\n\n # Create list for categorical display\n categorical = []\n cat_display = [{'Produce':[]}, {'Meat':[]}, {'Seafood':[]}, {'Deli':[]},\n {'Bakery':[]}, {'Breakfast/Cereal':[]},\n {'Beverage':[]}, {'Rice/Pasta':[]}, {'Oil/Vinegar':[]},\n {'Spice':[]}, {'Sauce':[]}, {'Canned/Jarred':[]},\n {'Baking':[]}, {'Dairy':[]}, {'Frozen':[]},\n {'International':[]}, {'Other':[]}]\n\n return alphabetical, categorical, staples\n","sub_path":"Local/Shopping.py","file_name":"Shopping.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"336269162","text":"# -*- coding: utf-8 -*-\n\n#############################################\n### LIBRARY TO USE PARROT FLOWER POWER VIA BLE IN PYTHON\n### COPYRIGHT NIKLAS ERDMANN 2016\n### DONT PUBLISH, PRIVATE LICENCE\n#############################################\n\nfrom btle import Peripheral, Scanner, BTLEException\nfrom influxdb import InfluxDBClient\nfrom math import pow\nfrom tlelibrary import StreamToLogger\n\nimport ConfigParser\nimport datetime\nimport logging\nimport os\nimport requests\nimport socket\nimport sys\n\n#############################################\n### CONFIG FUNCTIONS\n#############################################\nconfig = ConfigParser.ConfigParser()\nconfigpath = os.path.join(os.path.dirname(__file__), '../tle-custom/tle.conf')\nconfig.read(configpath)\n\n#############################################\n### LOGGING FUNCTIONS\n#############################################\nlogfile = os.path.join(os.path.dirname(__file__), '../tle-log/flower.log')\nlogginglevel = config.get('DEFAULT', 'logginglevel')\nlogging.basicConfig(\n filename=logfile,\n format='%(levelname)s: %(asctime)s: %(message)s',\n level=eval(logginglevel),\n filemode='a'\n)\nstdout_logger = logging.getLogger('STDOUT')\nsl = StreamToLogger(stdout_logger, logging.DEBUG)\nsys.stdout = sl\n\nstderr_logger = logging.getLogger('STDERR')\ns2 = StreamToLogger(stderr_logger, logging.DEBUG)\nsys.stderr = s2\n\n#############################################\n### COMMUNICATION FUNCTIONS\n#############################################\ndef getCharValue(device, uuid):\n chars = device.getCharacteristics(uuid=uuid)\n for char in chars:\n reversechar = char.read()[::-1]\n return int(reversechar.encode('hex'), 16)\n\ndef setCharValue(device, uuid, value):\n chars = device.getCharacteristics(uuid=uuid)\n for char in chars:\n char.write(value, False)\n\n#############################################\n### CONVERTING FUNCTIONS\n#############################################\ndef convertTemperatureData(rawValue):\n temperature = 0.00000003044 * pow(rawValue, 3.0) - 0.00008038 * pow(rawValue, 2.0) + rawValue * 0.1149 - 30.449999999999999;\n if(temperature < -10.0):\n temperature = -10.0\n elif(temperature > 55.0):\n temperature = 55.0\n return temperature;\n\ndef convertSoilMoistureData(rawValue):\n soilMoisture = 11.4293 + (0.0000000010698 * pow(rawValue, 4.0) - 0.00000152538 * pow(rawValue, 3.0) + 0.000866976 * pow(rawValue, 2.0) - 0.169422 * rawValue)\n soilMoisture = 100.0 * (0.0000045 * pow(soilMoisture, 3.0) - 0.00055 * pow(soilMoisture, 2.0) + 0.0292 * soilMoisture - 0.053)\n if(soilMoisture < 0.0):\n soilMoisture = 0.0\n elif(soilMoisture > 60.0):\n soilMoisture = 60.0\n return soilMoisture\n\ndef convertSunlightData(rawValue):\n sunlight = 0.08640000000000001 * (192773.17000000001 * pow(rawValue, -1.0606619))\n return sunlight\n\ndef convertECData(rawValue):\n if(rawValue < 0.0):\n rawValue = 0.0\n elif(rawValue > 1771.0):\n rawValue = 1771.0\n ec = rawValue * (10.0 / 1771.0) #convert raw (0 - 1771) to 0 to 10 (mS/cm)\n return ec\n\n#############################################\n### APPLICATION\n#############################################\n# Read description of FlowerPowers\nhostname=socket.gethostname()\nreq = requests.get('http://' + config.get('FlaskServer', 'host') + ':' + config.get('FlaskServer', 'port') + '/forwarder/' + hostname)\n\nfmac = {}\nfname = {}\nfairtemp_max = {}\nfairtemp_min = {}\nfsoiltemp_max = {}\nfsoiltemp_min = {}\nfwater_max = {}\nfwater_min = {}\nfsunlight_max = {}\nfsunlight_min = {}\nfec_max = {}\nfec_min = {}\nfforwarder = {}\nffound = {}\n\nif req.status_code == 200:\n if req.text != \"]\":\n reqresult = eval(req.text)\n for row in reqresult:\n if len(row) > 1:\n fmac[row[0]] = row[0]\n fname[row[0]] = row[1]\n fairtemp_max[row[0]] = row[2]\n fairtemp_min[row[0]] = row[3]\n fsoiltemp_max[row[0]] = row[4]\n fsoiltemp_min[row[0]] = row[5]\n fwater_max[row[0]] = row[6]\n fwater_min[row[0]] = row[7]\n fsunlight_max[row[0]] = row[8]\n fsunlight_min[row[0]] = row[9]\n fec_max[row[0]] = row[10]\n fec_min[row[0]] = row[11]\n fforwarder[row[0]] = row[12]\n ffound[row[0]] = 0\nelse:\n logging.error(\"No 200 code while looking for stored devices.\")\n\nmyscanner = Scanner(0)\ndevices = myscanner.scan(10)\nnow = str(datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S\")) + \"+01:00\"\nclient = InfluxDBClient(config.get('InfluxDB', 'host'), config.get('InfluxDB', 'port'), config.get('InfluxDB', 'user'), config.get('InfluxDB', 'password'), 'flowerpower')\n\nfor dev in devices:\n logging.info(\"Analyse device: \" + dev.addr)\n if dev.addr in fmac:\n try:\n ffound[dev.addr] = 1\n flowerpower = Peripheral(dev.addr)\n devname = fname[dev.addr]\n logging.info(dev.addr + \" \" + devname)\n airtemp = getCharValue(flowerpower, config.get('BLEServices', 'airtemp')) #air temperature\n soiltemp = getCharValue(flowerpower, config.get('BLEServices', 'soiltemp')) #soil temperature\n water = getCharValue(flowerpower, config.get('BLEServices', 'water')) #water in soil\n sunlight = getCharValue(flowerpower, config.get('BLEServices', 'sunlight')) #sunlight\n ec = getCharValue(flowerpower, config.get('BLEServices', 'ec')) #ec\n\n airtemp = convertTemperatureData(airtemp)\n soiltemp = convertTemperatureData(soiltemp)\n water = convertSoilMoistureData(water)\n sunlight = convertSunlightData(sunlight)\n ec = convertECData(ec)\n\n logging.info(\"air temperatur: \" + str(airtemp))\n logging.info(\"soil temperatur: \" + str(soiltemp))\n logging.info(\"water in soil: \" + str(water))\n logging.info(\"sunlight: \" + str(sunlight))\n logging.info(\"ec: \" + str(ec))\n\n setCharValue(flowerpower, config.get('BLEServices', 'led'), \"\\x01\") # pulse LED\n\n airtemp_json = [{\n \"measurement\": \"airtemp\",\n \"tags\": {\n \"type\": \"FlowerPower\",\n \"plant\": devname,\n \"max\": fairtemp_max[dev.addr],\n \"min\": fairtemp_min[dev.addr]\n },\n \"time\": now,\n \"fields\": {\n \"value\": airtemp\n }}]\n\t\t\t\n soiltemp_json = [{\n \"measurement\": \"soiltemp\",\n \"tags\": {\n \"type\": \"FlowerPower\",\n \"plant\": devname,\n \"max\": fsoiltemp_max[dev.addr],\n \"min\": fsoiltemp_min[dev.addr]\n },\n \"time\": now,\n \"fields\": {\n \"value\": soiltemp\n }}]\n\n water_json = [{\n \"measurement\": \"water\",\n \"tags\": {\n \"type\": \"FlowerPower\",\n \"plant\": devname,\n \"max\": fwater_max[dev.addr],\n \"min\": fwater_min[dev.addr]\n },\n \"time\": now,\n \"fields\": {\n \"value\": water\n }}]\n\n sunlight_json = [{\n \"measurement\": \"sunlight\",\n \"tags\": {\n \"type\": \"FlowerPower\",\n \"plant\": devname,\n \"max\": fsunlight_max[dev.addr],\n \"min\": fsunlight_min[dev.addr]\n },\n \"time\": now,\n \"fields\": {\n \"value\": sunlight\n }}]\n\n ec_json = [{\n \"measurement\": \"ec\",\n \"tags\": {\n \"type\": \"FlowerPower\",\n \"plant\": devname,\n \"max\": fec_max[dev.addr],\n \"min\": fec_min[dev.addr]\n },\n \"time\": now,\n \"fields\": {\n \"value\": ec\n }}]\n\n client.write_points(airtemp_json, time_precision='s')\n client.write_points(soiltemp_json, time_precision='s')\n client.write_points(water_json, time_precision='s')\n client.write_points(sunlight_json, time_precision='s')\n client.write_points(ec_json, time_precision='s')\n\n setCharValue(flowerpower, config.get('BLEServices', 'led'), \"\\x01\") # LED off\n\n except BTLEException:\n logging.warning(\"Device \" + dev.addr + \" found but could not get data. Connection lost...\") \n\n else:\n dejaname = \"\"\n dejaforwarder = \"\"\n req = requests.get('http://' + config.get('FlaskServer', 'host') + ':' + config.get('FlaskServer', 'port') + '/newble/' + hostname + '/' + dev.addr)\n if req.status_code == 200:\n reqresult = req.text\n if reqresult == \"INSERT\":\n logging.warning(\"Unknown device found: \" + dev.addr + \". Added to edit.\")\n else:\n reqresult = eval(reqresult)\n dejaname = reqresult[0]\n dejaforwarder = reqresult[1]\n if dejaforwarder == \"\":\n logging.warning(\"Unknown device found: \" + dev.addr + \". Already added.\")\n else:\n logging.warning(\"Device \" + dev.addr + \" is already supervised by \" + dejaforwarder + \" as plant \" + dejaname + \".\")\n else:\n logging.error(\"No 200 code while checking device mac.\")\n\n\nfor mac in fmac:\n if ffound[mac] == 0:\n logging.error(\"Device \" + mac + \" not found!\")\n\nlogging.info(\"Data is successfully saved.\")\n\n#############################################","sub_path":"tle/flower.py","file_name":"flower.py","file_ext":"py","file_size_in_byte":9768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"106956409","text":"# just copied example from https://pypi.org/project/rake-nltk/#description\n# import nltk\n# from rake_nltk import Rake\n# r = Rake() # Uses stopwords for english from NLTK, and all puntuation characters.\n# r.extract_keywords_from_text(description)\n# result = r.get_ranked_phrases() # To get keyword phrases ranked highest to lowest.\n# print(result)\n\n# import operator\nimport nltk\nimport RAKE\nimport operator\nimport json\n\nstop_dir = \"SmartStoplist.txt\"\nkeywords = \"\"\nrakeObj = RAKE.Rake(stop_dir)\nopeningdata = open(\"csvjson.json\", encoding=\"utf8\")\nwith open('csvjson.json', encoding=\"utf8\") as f:\n jobs = json.load(f)\n\n \ndef Sort_Tuple(tup) :\n tup.sort(key = lambda x: x[1])\n return tup\n\ndef Extract_Keywords(): \n for job in jobs:\n separate_job_descr = job['description_text']\n filtered_data = separate_job_descr.replace(\"\\n\", \" \")\n keywords = Sort_Tuple(rakeObj.run(filtered_data))[-10:]\n print(\"keywords: \", keywords)\n\nExtract_Keywords()\nopeningdata.close()","sub_path":"Keywords_extract.py","file_name":"Keywords_extract.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"262021055","text":"#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# 15-112: Fundamentals of Comp-Sci\n# Template by Evan Tipping\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# Name: Evan Tipping\n# Andrew ID: eftippin\n# Recitation: H\n\n# Class: ControllerManager\n# Created 11/10/2018\n\n# Version 0.3\n\n# Planned features / updates:\n# o Add listeners and event handlers for different controllers.\n# o Optimize methods\n# - Subdescription\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Changelog:\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# Updated to v0.3 on 11/14/2018\n# o Added automatic keyboard labelling and use of Class_KeyboardManager.\n\n# Updated to v0.2 on 11/11/2018\n# o Added numerous methods to the controller manager class.\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Overview:\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\"\"\"\n This class is specifically created to ease the coding behind handling\nmultiple controllers in a multiplayer game environment. It includes methods\nfor adding and removing controllers from a game and centralizes all of the\ncontrollers.\n\n I liken it to a central point that bundles and can act on all of the\ncontrollers in the game, like a bin. This does not control anything like\nmovement, as it is intended exclusively for easier handling of input\ninformation and uses logic to avoid crash errors. Effectively, it\nensures that all attempts to get controller information are valid.\n\"\"\"\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Imports:\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nimport pygame\nfrom Classes.Class_KeyboardManager import KeyboardManager\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Class Def:\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nclass PlayerInputManager:\n\n #DocString:\n\n \"\"\"A class for managing controllers in PyGame\"\"\"\n\n #==========================================#\n #~~~~~~~~~~~~] Metafuncts [~~~~~~~~~~~~#\n #==========================================#\n\n def __init__(self):\n self.maxCont = pygame.joystick.get_count() + 1\n self.conts = {}\n self.conts[self.maxCont] = KeyboardManager\n pygame.joystick.init()\n self.validConts = [pygame.joystick.Joystick(x)\n for x in range(pygame.joystick.get_count())]\n\n\n #==========================================#\n #~~~~~~~~~~~~] Initializers [~~~~~~~~~~~~#\n #==========================================#\n\n# Adds a given controller from the system's controllers to the dictionary\n#of viable controllers.\n def addConts(self, playNum):\n if playNum <= pygame.joystick.get_count():\n\n if playNum <= len(self.validConts) \\\n and playNum not in self.conts.keys():\n\n self.conts[playNum] = self.validConts[playNum - 1]\n\n\n\n# Removes the indicated controller from the dictionary of controllers.\n def removeCont(self, playNum):\n\n if playNum in self.conts.keys():\n self.conts[playNum].quit()\n del self.conts[playNum]\n print(\"Player %d may now remove the controller\" % playNum)\n\n elif not len(self.conts):\n print(\"There are no controllers plugged in!\")\n\n else:\n print(\"Player %d does not exist!\" % playNum)\n\n\n\n# Method to activate a given controller.\n def startCont(self, playNum):\n\n if not self.isInit(playNum):\n self.conts[playNum].init()\n\n\n #==========================================#\n #~~~~~~~~~~~~] Gamepad methods [~~~~~~~~~~~~#\n #==========================================#\n\n\n# Prints the name of a given controller for debugging.\n def getCont(self, playNum):\n\n if playNum in self.conts.keys():\n if type(self.conts[playNum]) == pygame.joystick.Joystick:\n print(self.conts[playNum].get_name())\n\n else:\n print(\"Player \" + str(playNum) + \" does not exist!\")\n\n\n\n# Method to see if an indicated controller is active.\n def isInit(self, playNum):\n\n if playNum in self.conts.keys():\n return bool(self.conts[playNum].get_init())\n\n\n\n# Returns all events associated to the specified controller.\n def getEvents(self, playNum):\n\n if playNum in self.conts.keys() and self.isInit(playNum):\n for event in pygame.event.get():\n yield event\n\n\n\n# Gets information about whether a specific button is pressed.\n def getButton(self, playNum, buttonNum):\n pygame.event.get()\n\n if playNum in self.conts.keys() and self.isInit(playNum):\n if buttonNum in range(self.conts[playNum].get_numbuttons()):\n return self.conts[playNum].get_button(buttonNum)\n\n else:\n print(\"No such button!\")\n\n else:\n print(\"Not a valid controller!\")\n\n# Gets information about the joystick movement.\n def getAxis(self, playNum, stickNum):\n pygame.event.get()\n\n if playNum in self.conts.keys() and self.isInit(playNum):\n if stickNum in range(self.conts[playNum].get_numaxes()):\n return self.conts[playNum].get_axis(stickNum)\n\n else:\n print(\"No such joystick!\")\n\n else:\n print(\"Not a valid controller!\")\n","sub_path":"TPDomain/Classes/Class_PlayerInputManager.py","file_name":"Class_PlayerInputManager.py","file_ext":"py","file_size_in_byte":5688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"465651475","text":"from django.conf.urls import patterns, url\nfrom ttt import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^nominate/$', views.nominate, name='nominate'),\n url(r'^vote/', views.vote, name='vote'),\n url(r'^sn/', views.submit_nomination, name='submit_nomination'),\n url(r'^sv/', views.submit_vote, name='submit_vote'),\n)\n","sub_path":"ttt/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"547325352","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport keras\nimport pandas as pd\n\nsns.set()\nmatplotlib.rcParams['font.family'] = 'sans-serif',\nmatplotlib.rcParams['font.sans-serif'] = ['Noto Sans CJK SC', 'SimHei']\nmatplotlib.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\n\n\ndef __plot_keras_history(d: dict, title, ylabel, xlabel):\n \"\"\"训练历史可视化\"\"\"\n\n return sns.lineplot(data=pd.DataFrame.from_dict(d))\n #\n # plt.title(title)\n # plt.ylabel(ylabel)\n # plt.xlabel(xlabel)\n # plt.legend(d.keys(), loc='upper left')\n # for n, v in d.items():\n # # plt.plot(v)\n # return plt\n\n\ndef plot_keras_history(his: keras.callbacks.History, **kwargs):\n \"\"\"训练历史可视化\n\n Args:\n his (:class:`keras.callbacks.History`):\n show (bool): 是否显示。默认为True。\n\n Returns:\n :class:`matplotlib.pyplot`:\n \"\"\"\n def _a(d:dict,name:str,k,v):\n if name not in d.keys():\n d[name]={}\n d[name][k]=v\n\n show = kwargs.pop('show', True)\n plots = []\n # # 绘制训练 & 验证的准确率值\n # acc = {}\n for n in his.history.keys():\n if 'val_' not in n:\n d={}\n _a(d, 'data', 'Train', his.history[n])\n if 'val_'+n in his.history.keys():\n _a(d, 'data', 'Test', his.history['val_'+n])\n d['ylabel'] = 'Value'\n d['xlabel'] = 'Epochs'\n d['title']=n\n plots.append(d)\n\n if plots:\n figSize_w=kwargs.pop('figSize_w',10)\n figSize_h=kwargs.pop('figSize_h',5)\n fig, axs = plt.subplots(nrows=len(plots),figsize=(figSize_w,len(plots)*figSize_h))\n for plot in plots:\n ax=sns.lineplot(data=pd.DataFrame.from_dict(plot['data']),\n ax=axs[plots.index(plot)])\n ax.set_xlabel(plot['xlabel'])\n ax.set_ylabel(plot['ylabel'])\n ax.set_title(plot['title'])\n\n plt.tight_layout()\n if show:\n plt.show()\n return plt\n\n\ndef plot_daily_return_histogram(data, **kwargs):\n \"\"\"绘制直方图\n\n Args:\n data (:class:`pandas.Series`): 日收益数据。\n bins (int): 参见 :func:`pandas.Series.hist` 中的同名参数。默认为 50.\n show (bool): 是否显示。默认为True。\n title (str): 标题。默认为 '日收益直方图'。\n suptitle (str): 标题。\n show_mean (bool): 绘制均值。默认为True。\n show_std (bool): 绘制标准差。默认为True。\n\n Returns:\n\n \"\"\"\n bins = kwargs.pop('bins', 50)\n show = kwargs.pop('show', True)\n title = kwargs.pop('title', '日收益直方图')\n suptitle = kwargs.pop('suptitle', None)\n show_mean = kwargs.pop('show_mean', True)\n show_std = kwargs.pop('show_std', True)\n data.hist(bins=bins)\n\n if show_mean:\n mean = data.mean()\n plt.axvline(mean, color='g')\n if show_std:\n std = data.std()\n plt.axvline(std, color='r', linestyle='dashed')\n plt.axvline(-std, color='r', linestyle='dashed')\n if title:\n plt.title(title)\n if suptitle:\n plt.suptitle(suptitle)\n if show:\n plt.show()\n return plt\n\n\ndef plot_pred_compare_real(real, pred, **kwargs):\n figSize_w=kwargs.pop('figSize_w',10)\n figSize_h=kwargs.pop('figSize_h',5)\n d = pd.DataFrame({'real': real, 'pred': pred.reshape(pred.shape[0])})\n\n plots=2\n fig, axs = plt.subplots(nrows=plots,figsize=(figSize_w, plots * figSize_h))\n ax1=sns.lineplot(data=d, ax=axs[0])\n c = pd.DataFrame(((d['pred'] - d['real']) / d['real']))\n ax2 = sns.lineplot(data=c, ax=axs[1])\n ax2.title.set_text('计算值与真实值的差率')\n plt.tight_layout()\n plt.show()\n return d,c","sub_path":"stock_ai/ploter.py","file_name":"ploter.py","file_ext":"py","file_size_in_byte":3776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"25181732","text":"\"\"\"Performs face alignment and stores face thumbnails in the output directory.\"\"\"\n# MIT License\n# \n# Copyright (c) 2016 David Sandberg\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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n#from scipy import misc\nimport sys\nimport os\nimport argparse\nimport numpy as np\nimport random\n#import imageio\n\nfrom PIL import Image\nimport argparse\nfrom pathlib import Path\nfrom multiprocessing import Process, Pipe,Value,Array\nimport torch\nfrom config import get_config\nfrom mtcnn import MTCNN\nfrom utils import load_facebank, draw_box_name, prepare_facebank\nimport cv2\n\nfrom time import sleep\nimport traceback\n\nclass ImageClass():\n \"Stores the paths to images for a given class\"\n def __init__(self, name, image_paths):\n self.name = name\n self.image_paths = image_paths\n \n def __str__(self):\n return self.name + ', ' + str(len(self.image_paths)) + ' images'\n \n def __len__(self):\n return len(self.image_paths)\n\ndef get_image_paths(facedir):\n image_paths = []\n if os.path.isdir(facedir):\n images = os.listdir(facedir)\n image_paths = [os.path.join(facedir,img) for img in images]\n return image_paths\n\ndef get_dataset(path, has_class_directories=True):\n dataset = []\n path_exp = os.path.expanduser(path)\n classes = [path for path in os.listdir(path_exp) \\\n if os.path.isdir(os.path.join(path_exp, path))]\n classes.sort()\n nrof_classes = len(classes)\n for i in range(nrof_classes):\n class_name = classes[i]\n facedir = os.path.join(path_exp, class_name)\n image_paths = get_image_paths(facedir)\n dataset.append(ImageClass(class_name, image_paths))\n \n return dataset\n \n#numpy to rgb? \ndef to_rgb(img):\n w, h = img.shape\n ret = np.empty((w, h, 3), dtype=np.uint8)\n ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img\n return ret\n\ndef main(args):\n sleep(random.random())\n output_dir = os.path.expanduser(args.output_dir)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n # Store some git revision info in a text file in the log directory\n src_path,_ = os.path.split(os.path.realpath(__file__))\n dataset = get_dataset(args.input_dir)\n \n conf = get_config(False)\n\n mtcnn = MTCNN()\n print('arcface loaded')\n\n print('Creating networks and loading parameters')\n \n \n # Add a random key to the filename to allow alignment using multiple processes\n random_key = np.random.randint(0, high=99999)\n bounding_boxes_filename = os.path.join(output_dir, 'bounding_boxes_%05d.txt' % random_key)\n \n with open(bounding_boxes_filename, \"w\") as text_file:\n nrof_images_total = 0\n nrof_successfully_aligned = 0\n if args.random_order:\n random.shuffle(dataset)\n for cls in dataset:\n output_class_dir = os.path.join(output_dir, cls.name)\n if not os.path.exists(output_class_dir):\n os.makedirs(output_class_dir)\n if args.random_order:\n random.shuffle(cls.image_paths)\n for image_path in cls.image_paths:\n nrof_images_total += 1\n filename = os.path.splitext(os.path.split(image_path)[1])[0]\n output_filename = os.path.join(output_class_dir, filename+'.png')\n print(image_path)\n if not os.path.exists(output_filename):\n try:\n frame = cv2.imread(image_path)\n image = Image.fromarray(frame[...,::-1]) #bgr to rgb\n\n #bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n bboxes, faces = mtcnn.align_multi(image, conf.face_limit, conf.min_face_size)\n bboxes = bboxes[:,:-1] #shape:[10,4],only keep 10 highest possibiity faces\n bboxes = bboxes.astype(int)\n bboxes = bboxes + [-1,-1,1,1] # personal choice \n \n # print(score[0])\n for idx,bbox in enumerate(bboxes):\n \n print(\"idx:\"+str(idx))\n \"\"\"\n #already cropped, no need codes\n X= bbox[0]\n Y= bbox[1]\n W= bbox[2] -X\n H= bbox[3] -Y\n print(\"framesize:\"+str(frame.shape))\n cropped = frame[X:W,Y:H,:]\n print(\"cropped size:\"+str(cropped.shape))\n\n croppedsized = cv2.resize(cropped, (args.image_size, args.image_size), interpolation=cv2.INTER_AREA)\n \"\"\"\n\n filename_base, file_extension = os.path.splitext(output_filename)\n output_filename_n = \"{}{}\".format(filename_base, file_extension)\n \n faces[idx].save(output_filename_n)\n print('output: '+ output_filename_n)\n nrof_successfully_aligned += 1\n text_file.write('%s %d %d %d %d\\n' % (output_filename_n, bbox[0], bbox[1], bbox[2], bbox[3]))\n except Exception as e:\n error_class = e.__class__.__name__ #取得錯誤類型\n detail = e.args[0] #取得詳細內容\n cl, exc, tb = sys.exc_info() #取得Call Stack\n lastCallStack = traceback.extract_tb(tb)[-1] #取得Call Stack的最後一筆資料\n fileName = lastCallStack[0] #取得發生的檔案名稱\n lineNum = lastCallStack[1] #取得發生的行號\n funcName = lastCallStack[2] #取得發生的函數名稱\n errMsg = \"File \\\"{}\\\", line {}, in {}: [{}] {}\".format(fileName, lineNum, funcName, error_class, detail)\n print(errMsg)\n pass \n \n print('Total number of images: %d' % nrof_images_total)\n print('Number of successfully aligned images: %d' % nrof_successfully_aligned)\n \n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('input_dir', type=str, help='Directory with unaligned images.')\n parser.add_argument('output_dir', type=str, help='Directory with aligned face thumbnails.')\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=182)\n parser.add_argument('--margin', type=int,\n help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)\n parser.add_argument('--random_order', \n help='Shuffles the order of images to enable alignment using multiple processes.', action='store_true')\n parser.add_argument('--gpu_memory_fraction', type=float,\n help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)\n parser.add_argument('--detect_multiple_faces', type=bool,\n help='Detect and align multiple faces per image.', default=False)\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n","sub_path":"torch_align_dataset_mtcnn.py","file_name":"torch_align_dataset_mtcnn.py","file_ext":"py","file_size_in_byte":8347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"159840171","text":"from dispositivos.models import Dispositivo\nimport os, platform\n\n#class MyCronJob(CronJobBase):\ndef MyCronJob():\n ##os.system(\"echo blablabla >> /tmp/teste\");\n dispositivos = Dispositivo.objects.all()\n if platform.system().lower()==\"windows\":\n ping_str = \"-n 1\"\n else:\n ping_str = \"-c 1\"\n for dispositivo in dispositivos:\n ping = os.system(\"/bin/ping -c 1 \" + dispositivo.ip)\n if ping == 0:\n dispositivo.atualizado = True\n dispositivo.save()\n else:\n dispositivo.atualizado = False\n dispositivo.save()\n","sub_path":"Inventario/dispositivos/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"90226817","text":"\"\"\" \nMain File containing all the windows for the GUI using helpers\nfrom gui_helpers.py. Handling Events.\n\nPartial Credit to @VegaSeat for his program to display image on GUI\nhttps://www.daniweb.com/programming/software-development/code/\n493004/display-an-image-from-the-web-pygame\n\"\"\"\n\nimport pygame as pg\nimport io\nfrom urllib.request import urlopen\n\nfrom gui_helpers import *\nfrom scraper import *\n\ndef run_visualisation() -> None:\n \"\"\" Display an interactive graphical display of the Scraper \"\"\"\n pg.init()\n pg.display.set_caption('My Anime List Scraper')\n screen = pg.display.set_mode((WIDTH, HEIGHT))\n \n title_screen(screen)\n \n txt_screen(screen)\n \n\ndef txt_screen(screen) -> None:\n \"\"\" Display a textbox for the user's input \"\"\" \n\n clear_screen(screen)\n border(screen)\n draw_header(screen, \"Enter an Anime name\")\n \n clock = pg.time.Clock()\n ip_box = InputBox(48, 270, 544, 50)\n\n while True:\n for e in pg.event.get():\n if e.type == pg.QUIT:\n pg.quit()\n exit()\n ip_box.handle_event(e)\n \n # If something has been entered\n if ip_box.last_inp != \"\":\n render_anime_stat(screen, ip_box.last_inp)\n \n clear_screen(screen)\n border(screen)\n draw_header(screen, \"Enter an Anime Name\")\n \n ip_box.update()\n ip_box.draw(screen)\n \n pg.display.flip()\n clock.tick(30)\n \n \ndef render_anime_stat(screen: pg.Surface, anime_name: str) -> None:\n \"\"\" Renders the screen with the overall stats of the anime \"\"\"\n\n anime = search(anime_name)\n\n clear_screen(screen)\n border(screen)\n draw_header(screen, anime.title)\n\n # Loading the image \n image_str = urlopen(anime.imageUrl).read()\n image_file = io.BytesIO(image_str)\n image = pg.image.load(image_file)\n screen.blit(image, (360, 100))\n\n # Displaying the Statistics\n write_text(screen, anime.rank, get_font(), TEXT, (48, 140))\n write_text(screen, \"Score \" + anime.score, get_font(), TEXT, (48, 240))\n write_text(screen, anime.popular, get_font(), TEXT, (48, 340))\n write_text(screen, \"Link \" + anime.link, get_font(24), TEXT, (48, 460))\n \n # Buttons for Next and Back\n next_b = PButton(screen, (442, 500, 150, 70))\n next_b.add_text(\"Next->\")\n back_b = PButton(screen, (48, 500, 150, 70))\n back_b.add_text(\"<-Back\")\n \n while True:\n \n for e in pg.event.get():\n if e.type == pg.QUIT:\n pg.quit()\n exit()\n \n if e.type == pg.MOUSEBUTTONUP:\n if next_b.is_cursor_on(e.pos, True):\n render_anime_desc(screen, anime)\n \n if back_b.is_cursor_on(e.pos, True):\n txt_screen(screen)\n \n # Drawing buttons depending on if they're clicked\n # or being hovered over\n if next_b.is_cursor_on(pg.mouse.get_pos()):\n next_b.hover()\n else:\n next_b.draw()\n \n if back_b.is_cursor_on(pg.mouse.get_pos()):\n back_b.hover()\n else:\n back_b.draw()\n \n pg.display.flip()\n\n\ndef render_anime_desc(screen: pg.Surface, anime: MAL) -> None:\n \"\"\" Render the description of said anime \"\"\"\n\n clear_screen(screen)\n border(screen)\n draw_header(screen, anime.title)\n\n # Writing the description\n if len(anime.desc) >= 68:\n char_limit = 68\n for i in range(len(anime.desc) // char_limit):\n write_text(screen, anime.desc[char_limit * i: char_limit * (i + 1)],\n get_font(22), TEXT, (48, 100 + (18 * i)))\n \n write_text(screen, anime.desc[char_limit * (i + 1):],\n get_font(23), TEXT, (48, 100 + (18 * (i + 1))))\n else:\n write_text(screen, anime.desc, get_font(23), TEXT, (48, 100))\n \n # Buttons for Next and Back\n next_b = PButton(screen, (442, 500, 150, 70))\n next_b.add_text(\"Next->\")\n \n while True:\n for e in pg.event.get():\n if e.type == pg.QUIT:\n pg.quit()\n exit()\n \n if e.type == pg.MOUSEBUTTONUP:\n if next_b.is_cursor_on(e.pos, True):\n txt_screen(screen)\n \n if next_b.is_cursor_on(pg.mouse.get_pos()):\n next_b.hover()\n else:\n next_b.draw()\n \n pg.display.flip()\n\n\nif __name__ == '__main__':\n run_visualisation()\n \n ","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"8868359","text":"\nimport time\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pickle\nimport glob\nimport donkeycar as dk\n\n\n\n\nclass calibrate_camera(object):\n def __init__(self, poll_delay=0.01,):\n self.on = True\n self.poll_delay = poll_delay\n \n # initiate your data\n self.objp_list = []\n self.corners_list = []\n self.mtx = 0\n self.dist = 0\n self.rvecs = 0\n self.tvecs = 0\n self.dst = 0\n self.camera = 0\n # Initiate your part here\n self.objp_dict = {\n 1: (8, 6),\n 2: (8, 6),\n 3: (8, 6),\n 4: (8, 6),\n 5: (8, 6),\n 6: (8, 6),\n 7: (8, 6),\n 8: (8, 6),\n 9: (8, 6),\n 10: (8, 6),\n 11: (8, 6),\n 12: (8, 6),\n 13: (8, 6),\n 14: (8, 6),\n 15: (8, 6),\n 16: (8, 6),\n 17: (8, 6),\n 18: (8, 6),\n 19: (8, 6),\n 20: (8, 6),\n }\n\n \n \n def run(self):\n #self.camera = camera\n self.poll()\n\n return self.mtx, self.dist\n \n \n # Call in the control loop\n # Works when threaded=False\n # Input is parameters, Return your output\n \n def shutdown(self):\n self.on = False\n time.sleep(0.2)\n # Call once before stop the part\n \n def update(self):\n while self.on:\n self.poll()\n time.sleep(self.poll_delay)\n\n def run_threaded(self):\n #self.camera = camera\n return self.mtx, self.dist\n \n # Call in the control loop\n # Works when threaded=True\n # Similar as run function\n \n def poll(self):\n \n #while self.k < 20:\n for k in self.objp_dict:\n nx, ny = self.objp_dict[k]\n \n # Prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((nx*ny,3), np.float32)\n objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)\n\n # Make a list of calibration images\n fname = '/home/pi/testbed/mycar/data/160120/calibrate%s.jpg' % str(k)\n img = cv2.imread(fname)\n x,y = img.shape[0:2]\n img = cv2.resize(img, (int(y*3), int(x*3)))\n # Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n \n # If found, save & draw corners\n if ret == True:\n # Save object points and corresponding corners\n self.objp_list.append(objp)\n self.corners_list.append(corners)\n \n # Draw and display the corners\n #cv2.drawChessboardCorners(img, (nx, ny), corners, ret)\n #plt.imshow(img)\n #plt.show()\n #print('Found corners for %s' % fname)\n else:\n print('Warning: ret = %s for %s' % (ret, fname))\n \n print(k)\n #self.k += 1\n\n \n fname = '/home/pi/testbed/mycar/data/160120/calibrate1.jpg'\n img = cv2.imread(fname)\n img_size = (img.shape[1], img.shape[0])\n ret, self.mtx, self.dist, self.rvecs, self.tvecs = cv2.calibrateCamera(self.objp_list, self.corners_list, img_size, None, None)\n print('mtx: ', self.mtx)\n print('dist: ', self.dist)\n\n\n #self.camera = np.float32(self.camera)\n #self.dst = cv2.undistort(self.camera, self.mtx, self.dist, None, self.mtx) \n \n \n #img = cv2.imread('/home/pi/testbed/mycar/custom_parts/camera_cal/Checkerboard.jpg')\n #img_size = (img.shape[1], img.shape[0])\n #ret, self.mtx, self.dist, self.rvecs, self.tvecs = cv2.calibrateCamera(self.objp_list, self.corners_list, img_size, None, None)\n #self.camera = np.float32(self.camera)\n #self.dst = cv2.undistort(self.camera, self.mtx, self.dist, None, self.mtx)\n\n\n\n\n\n# test\nif __name__ == \"__main__\":\n C = calibrate_camera()\n mtx,dist = C.run()\n save_dict = {'mtx': mtx, 'dist': dist}\n with open('calibrate_camera.p', 'wb') as f:\n pickle.dump(save_dict, f)\n\n # Undistort example calibration image\n img = mpimg.imread('/home/pi/testbed/mycar/data/160120/test.jpg')\n x,y = img.shape[0:2]\n img = cv2.resize(img, (int(y*3), int(x*3)))\n dst = cv2.undistort(img, mtx, dist, None, mtx)\n plt.imshow(dst)\n plt.savefig('/home/pi/testbed/mycar/data/test5.png')\n","sub_path":"mycar/custom_parts/calibrate_camera.py","file_name":"calibrate_camera.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"126403218","text":"from unittest import TestCase\n\nimport numpy as np\nimport pandas as pd\n\nfrom rdt.transformers.datetime import DTTransformer\nfrom tests import safe_compare_dataframes\n\n\nclass TestDTTransformer(TestCase):\n def setUp(self):\n self.normal_data = pd.read_csv('tests/data/datetime/normal.csv')\n self.missing_data = pd.read_csv('tests/data/datetime/missing.csv')\n\n self.normal_meta = {\n \"name\": \"date_account_created\",\n \"type\": \"datetime\",\n \"format\": \"%m/%d/%y\"\n }\n self.missing_meta = {\n \"name\": \"date_first_booking\",\n \"type\": \"datetime\",\n \"format\": \"%m/%d/%y\"\n }\n\n def test_fit_transform(self):\n \"\"\"fit_transforms transforms datetime values into floats.\"\"\"\n # Setup\n transformer = DTTransformer(self.normal_meta)\n expected_result = pd.Series([\n 1.3885524e+18,\n 1.3886388e+18,\n 1.3887252e+18,\n 1.3888116e+18\n ])\n column_name = self.normal_meta['name']\n\n # Run\n transformed = transformer.fit_transform(self.normal_data)\n result = transformed[column_name]\n\n # Check\n assert np.allclose(result, expected_result, 1e-03)\n\n def test_fit_transform_out_of_bounds(self):\n \"\"\"Out of bounds values should be transformed too.\"\"\"\n # Setup\n out_of_bounds_data = pd.DataFrame({\n 'date_first_booking': [\n '2262-04-11 23:47:16.854775',\n '2263-04-11 23:47:16.854776'\n ]\n })\n\n expected_result = pd.Series(\n [9223372036854774784, np.nan],\n name='date_first_booking'\n )\n\n out_of_bounds_meta = {\n 'name': 'date_first_booking',\n 'type': 'datetime',\n 'format': '%Y-%m-%d %H:%M:%S.%f'\n }\n\n # Run\n transformer = DTTransformer(out_of_bounds_meta)\n transformed = transformer.fit_transform(out_of_bounds_data)\n result = transformed[self.missing_meta['name']]\n\n # Check\n assert safe_compare_dataframes(result, expected_result)\n\n def test_reverse_transform(self):\n \"\"\"reverse_transform reverse fit_transforms.\"\"\"\n # Setup\n transformer = DTTransformer(self.normal_meta)\n transformed = transformer.fit_transform(self.normal_data)\n\n # Run\n result = transformer.reverse_transform(transformed)\n\n # Check\n assert result.equals(self.normal_data)\n\n def test_reverse_transform_missing(self):\n \"\"\"Missing values are left unchanged.\"\"\"\n # Setup\n transformer = DTTransformer(self.missing_meta)\n transformed = transformer.fit_transform(self.missing_data)\n expected_result = self.missing_data['date_first_booking']\n\n # Run\n result = transformer.reverse_transform(transformed)[transformer.col_name]\n\n # Check\n assert safe_compare_dataframes(result, expected_result)\n\n def test_reversibility_transforms(self):\n \"\"\"Transforming and reverse transforming a column leaves it unchanged.\"\"\"\n # Setup\n transformer = DTTransformer(self.normal_meta)\n\n # Run\n transformed_data = transformer.fit_transform(self.normal_data)\n reversed_data = transformer.reverse_transform(transformed_data)\n\n # Check\n assert reversed_data.equals(self.normal_data)\n","sub_path":"tests/rdt/transformers/test_datetime.py","file_name":"test_datetime.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"186639348","text":"from testing import RedconTestBase\n\n\nclass TestBaseField(RedconTestBase):\n\n def setUp(self):\n super(TestBaseField, self).setUp()\n\n class Fields(self.redcon.Model):\n vanilla = self.redcon.fields.Field()\n reverse_lookup = self.redcon.fields.Field(lookup=True)\n\n self.Fields = Fields\n self.instance = self.Fields()\n\n def test_set(self):\n self.instance.vanilla = 'i can fly higher than an eagle'\n res = self.redis.hget('fields:1', 'vanilla')\n self.assertEqual('i can fly higher than an eagle', res)\n\n def test_no_reverse_lookup(self):\n res = self.redis.exists('fields:lookup:vanilla')\n self.assertFalse(res)\n\n def test_reverse_lookup(self):\n self.instance.vanilla = 'hi'\n self.instance.reverse_lookup = 'find me!'\n res = self.redis.hgetall('fields:1')\n expected = dict(\n vanilla='hi',\n reverse_lookup='find me!',\n )\n self.assertEqual(expected, res)\n lookup = self.redis.hgetall('fields:lookup:reverse_lookup')\n expected = {\n 'find me!': '1',\n }\n self.assertEqual(expected, lookup)\n","sub_path":"tests/fields-tests.py","file_name":"fields-tests.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"505505548","text":"import requests\nimport urllib3\nfrom Xcharger.HomePage.login import Login\nfrom common.logger import Log\n\n#禁用安全警告\nurllib3.disable_warnings()\n# 运营商平台退款受理请求链接\nurl1 = 'http://xcloud.dev.xcharger.net/service/api/wechatrefund'\n#微信端退款请求链接\nurl2 = 'http://xcloud.dev.xcharger.net/xchargewechat/pay/createRefund'\n\nclass Refund(Login):\n def __init__(self,s):\n self.s = s\n self.log = Log()\n def RefundSearch(self,startTime='',endTime='',status='',keyword='',wechatUserId='',f=0,length=10):\n '''退款受理查询'''\n params_body = {\n 'from':f,\n 'length':length,\n '1':1,\n 'returnCount':True,\n 'startTime':startTime,\n 'endTime':endTime,\n 'status':status,\n 'keyword':keyword,\n 'wechatUserId':wechatUserId,\n 'r':87054\n }\n res = self.s.get(url1,params=params_body,verify=False)\n return res\n def RefundOperation(self,action,refundId):\n '''对退款进行确认取消等操作,action取值为cancel,confirm,finish'''\n json_body = {\n 'id':refundId,\n 'action':action\n }\n res = self.s.post(url1,json=json_body,verify=False)\n return res\n\n","sub_path":"Xcharger/Bill/refund_acceptance.py","file_name":"refund_acceptance.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"272521037","text":"from setuptools import setup, find_packages\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# with open(path.join(here, 'README.md'), encoding='utf-8') as f:\n# long_description = f.read()\n\nsetup(\n name='argparse_tutorial',\n version='0.0.1',\n install_requires=[\n 'python-backlog',\n 'PyYAML'\n ],\n description='argparseを使ったCLIのサンプル',\n # long_description=long_description,\n # long_description_content_type='text/markdown',\n author='hassaku63',\n author_email='takuyahashimoto1988@gmail.com',\n license='CC0',\n classifiers=[\n 'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication',\n 'Development Status :: 3 - Alpha',\n 'Programming Language :: Python',\n 'Natural Language :: Japanese',\n ],\n keywords='nulab backlog argparse',\n url='https://github.com/hassaku63/argparse-get-started',\n entry_points={\n # https://packaging.python.org/guides/distributing-packages-using-setuptools/#entry-points\n # https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation\n 'console_scripts': [\n 'backlog_list_wiki = example_cli.cli:main'\n ]\n },\n packages=find_packages(exclude=['tests*']),\n)","sub_path":"20_packaging_your_code/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"598964793","text":"import os\nimport argparse\nimport json\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\n\nfrom trainner import Trainer\nfrom model import Model\nfrom dataset import Dataset, MaskDataset\nfrom tokenizer import Tokenizer, load_tokenizer\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--src_vocab', required=True)\nparser.add_argument('--tgt_vocab', required=True)\nparser.add_argument('--train_file', required=True)\nparser.add_argument('--test_file', required=True)\nparser.add_argument('--model_config')\nparser.add_argument('--batch_size', default=32, type=int)\nparser.add_argument('--learning_rate', default=1e-3, type=float)\nparser.add_argument('--num_epoch', default=10, type=int)\nparser.add_argument('--device', default='cpu')\nparser.add_argument('--log_dir', default='logs')\nparser.add_argument('--weight_dir', default='weight')\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n print(\"Load vocab\")\n tokenizer = load_tokenizer(args.src_vocab, args.tgt_vocab)\n\n print(\"Prepare data\")\n train_ds = MaskDataset(args.train_file, tokenizer)\n test_ds = MaskDataset(args.test_file, tokenizer, use_mask=False)\n train_dl = DataLoader(train_ds, shuffle=True, batch_size=args.batch_size)\n test_dl = DataLoader(test_ds, shuffle=False, batch_size=args.batch_size)\n\n print(\"Init model\")\n src_vocab_len = len(tokenizer.src_stoi)\n tgt_vocab_len = len(tokenizer.tgt_stoi)\n\n if args.model_config:\n with open(args.model_config) as f:\n config = json.load(f)\n else:\n config = {}\n\n model = Model(src_vocab_len, tgt_vocab_len, **config)\n optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate, betas=(0.9, 0.98), eps=1e-9)\n sched = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=len(train_dl))\n trainner = Trainer(\n model, optimizer, train_dl, test_dl, \n device=args.device, scheduler=sched,\n log_dir=args.log_dir,\n weight_dir=args.weight_dir\n )\n\n print(\"Start training\")\n trainner.train(args.num_epoch)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"275414162","text":"\nclass stargazing(object):\n #--------------------------------------- model hyperparameter\n param = {'xrepeat_block' : [3, 4, 6, 3],\n 'xfilter' : 64,\n 'xpool_size' : 9,\n 'xout_dim' : 36,\n 'xcardinality' : 4,\n #--------------------------------------- training hyperparameter\n 'xepochs' : 150,\n 'xbatch_size' : 128,\n 'xlearning_rate': 1e-1}\n\n def print_info(path, data):\n print('---------------------------------info---------------------------------')\n localtime = time.asctime( time.localtime(time.time()) )\n print('localtime is\\n', localtime)\n print('python version is %s\\n' %sys.version)\n print('keras version is %s\\n' %keras.__version__)\n print('dataset:%s' %(path + data))\n print('----------------------------------------------------------------------')\n\n def train_model(self, Ximg, Y, x_test, y_test, data_augmentation,\n main_path, result_path, network, weights_dir, detials_dir):\n def summary_print(s):\n with open(result_path + detials_dir + 'summary.txt', 'a') as f:\n print(s, file = f)\n #------------------------------- loss function\n def custom_loss(y_true, y_pred):\n K.set_epsilon(1e-7)\n #loss = K.mean(K.square(y_true - y_pred), axis = -1)\n loss = K.categorical_crossentropy(output = y_pred, target = y_true)\n return loss\n\n from keras.callbacks import CSVLogger\n csv_logger = CSVLogger(result_path + 'logs/logger.csv', append = True, separator = ',')\n\n from lsuv_init import LSUVinit\n with tf.device('/cpu:0'):\n model = XNet_v2.XnetBuilder.architecture(main = Ximg,\n xrepeat_block = self.param['xrepeat_block'],\n xfilter = self.param['xfilter'],\n xpool_size = self.param['xpool_size'],\n xout_dim = self.param['xout_dim'],\n xcardinality = self.param['xcardinality'])\n\n Ada_delta = Adadelta(lr = self.param['xlearning_rate'], rho = 0.95, epsilon = 1e-08, decay = 1e-7)\n parallel_model = multi_gpu_model(model[0], gpus = 2)\n parallel_model = LSUVinit(parallel_model, Ximg[:self.param['xbatch_size'],:,:,:])\n ycompile = parallel_model.compile(loss = custom_loss,\n optimizer = Ada_delta,\n metrics = ['acc'])\n\n if os.path.exists(main_path + weights_dir + network +'_weights.h5'):\n model[0].load_weights(main_path + weights_dir + network +'_weights.h5')\n\n if not data_augmentation:\n xmodel = parallel_model.fit(Ximg, Y,\n batch_size = self.param['xbatch_size'],\n epochs = self.param['xepochs'],\n shuffle = True,\n #callbacks = [lr_reducer],\n callbacks = [csv_logger],\n validation_data = (x_test, y_test))\n else:\n print('\\n-------Using real-time data augmentation-------\\n')\n # This will do preprocessing and realtime data augmentation:\n datagen = ImageDataGenerator(\n # set input mean to 0 over the dataset\n featurewise_center = False,\n samplewise_center = False,\n # divide inputs by std of dataset\n featurewise_std_normalization = False,\n # divide each input by its std\n samplewise_std_normalization = False,\n # apply ZCA whitening\n zca_whitening = False,\n # randomly rotate images in the range (deg 0 to 180)\n rotation_range = 0,\n # randomly shift images horizontally\n width_shift_range = 0.1,\n # randomly shift images vertically\n height_shift_range = 0.1,\n # randomly flip images\n horizontal_flip = True,\n # randomly flip images\n vertical_flip = False)\n\n # Compute quantities required for featurewise normalization\n # (std, mean, and principal components if ZCA whitening is applied).\n datagen.fit(Ximg)\n # Fit the model on the batches generated by datagen.flow().\n xmodel = parallel_model.fit_generator(datagen.flow(Ximg, Y, batch_size = self.param['xbatch_size']),\n epochs = self.param['xepochs'],\n validation_data = (x_test, y_test),\n callbacks = [csv_logger],\n shuffle = True)\n\n model[0].save_weights(main_path + weights_dir + network +'_weights.h5')\n\n if not os.path.exists(result_path + detials_dir + 'summary.txt'):\n model[0].summary(print_fn = summary_print)\n\n if not os.path.exists(result_path + detials_dir + network +'.png'):\n plot_model(model[0], show_shapes = True, to_file = result_path + network +'.png')\n plot_model(model[1], show_shapes = True, to_file = result_path + 'CNN' +'.png')\n pred_ = parallel_model.predict([Ximg])\n #------------------------------------------------------------------- predictions\n #print('* Pridections on training set: \\n', pred_)\n #------------------------------------------------------------------- test loss\n eval_ = parallel_model.evaluate([Ximg], Y)\n #print('* Loss on testing set: \\n', eval_)\n return xmodel, pred_, eval_\n\ndef main():\n tStart = time.time()\n np.set_printoptions(threshold = np.nan)\n os.environ['CUDA_VISIBLE_DEVICES'] = '0, 1'\n\n network = 'XNet_v2'\n weights_dir = 'weights/'\n detials_dir = 'details/'\n logs_dir = 'logs/'\n\n main_path = os.getcwd() + '/'\n file_list = os.listdir(main_path)\n result_path = main_path + 'training_result/'\n # generate dir\n if not os.path.exists(main_path + weights_dir): os.makedirs(main_path + weights_dir)\n if not os.path.exists(result_path + detials_dir): os.makedirs(result_path + detials_dir)\n if not os.path.exists(result_path + logs_dir): os.makedirs(result_path + logs_dir)\n\n # load data\n from keras.datasets import cifar10\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n y_train = np_utils.to_categorical(y_train, num_classes = 10)\n y_test = np_utils.to_categorical(y_test, num_classes = 10)\n Y = y_train\n\n Ximg = x_train.astype('float32')\n x_test = x_test.astype('float32')\n print('original shape: Ximg, Y', Ximg.shape, Y.shape)\n\n # data preprocess\n nor_img = np.ones((1, Ximg.shape[1], Ximg.shape[2], 1))\n nor_img /= 255.0\n Ximg = Ximg * nor_img\n x_test = x_test * nor_img\n\n # using data augmentation\n data_augmentation = True\n\n #start to train\n Hailee = stargazing()\n Hailee.param['xout_dim'] = Y.shape[1]\n LetMeGo = Hailee.train_model(Ximg = Ximg, Y = Y, x_test = x_test, y_test = y_test ,\n data_augmentation = data_augmentation, main_path = main_path,\n result_path = result_path, network = network,\n weights_dir = weights_dir, detials_dir = detials_dir)\n #record info. and save results\n #cl.write_file(path = result_path + logs_dir, file_name = 'train_true', data = Y)\n #cl.write_file(path = result_path + logs_dir, file_name = 'train_pred', data = LetMeGo[1])\n\n cl.write_file(path = result_path + logs_dir, file_name = 'train_eval', data = LetMeGo[2])\n cl.write_file(path = result_path + logs_dir, file_name = 'loss_file', data = (LetMeGo[0].history['loss']))\n\n #avg_error = cl.evalute_pred_true(pred = LetMeGo[1], true = Y)\n #cl.write_file(path = result_path + logs_dir, file_name = 'train_how_far', data = avg_error)\n cl.write_report(path = result_path + logs_dir, file_name = 'train_report', param = Hailee.param)\n cl.write_file(path = result_path + logs_dir, file_name = 'accuracy_epoch', data =LetMeGo[0].history['acc'])\n\n #care = 'avg_error\\n{0:>}'\n #print(care.format(str(np.array(avg_error))))\n #print('maximum average error\\n', str(np.amax(np.array(avg_error))))\n\n tEnd = time.time()\n cl.write_file(path = result_path + logs_dir, file_name = 'train_report', data = (tEnd-tStart))\n print('run time : %f' %(tEnd-tStart))\n\nif __name__ == '__main__':\n import six.moves.cPickle as pickle\n import os, time, sys, re\n import numpy as np\n\n import keras\n import keras.backend as K\n from keras.utils import plot_model\n from keras.optimizers import RMSprop, Adadelta, SGD\n from keras.utils import multi_gpu_model, np_utils\n from keras.preprocessing.image import ImageDataGenerator\n import tensorflow as tf\n\n import XNet_v2\n import Capital_Letters as cl\n\n main()\n","sub_path":"convolutional_neural_network_classification_test_lsuv.py","file_name":"convolutional_neural_network_classification_test_lsuv.py","file_ext":"py","file_size_in_byte":9395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"350619107","text":"def sgn (x1,x2,w1,w2,theta):\n\n\tdiff = (w1*x1 + w2*x2)-theta\n\tif diff > 0 :\n\t\treturn 1.0\n\telse :\n\t\treturn 0.0\n\ndef not_or(x1,x2):\n\tw1 = float(-1.0)\n\tw2 = float(-1.0)\n\ttheta = float(-0.1)\n\treturn sgn(x1,x2,w1,w2,theta)\n\n\ndef logical_and(x1,x2):\n\tw1 = float(1.0)\n\tw2 = float(1.0)\n\ttheta = float(1.9)\n\treturn sgn(x1,x2,w1,w2,theta)\n\ndef logical_or(x1,x2):\n\tw1 = float(0.5)\n\tw2 = float(0.5)\n\ttheta = float(0.4)\n\treturn sgn(x1,x2,w1,w2,theta)\n\n\nx1 = float(input(\"Enter x1 : \"))\nx2 = float(input(\"Enter x2 : \"))\nnor = not_or(x1,x2)\nda = logical_and(x1,x2)\n\nresult = logical_or(nor,da)\nprint(\"Result Is : \", result)\n\n","sub_path":"xor.py","file_name":"xor.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"376329414","text":"from . import helper\nfrom . import problems\nimport random\nfrom scipy.stats import entropy\nimport numpy as np\n\n\ndef print_list(db):\n \"\"\" Print the list of questions in the database\n :param db: The Mongodb database\n :return: A dictionary mapping the index in the printed list to the id of the questions in the db\n \"\"\"\n cursor = db.questions.find()\n eq = '-' * 115\n print(eq)\n i = 1\n question_idx_to_id = dict()\n template = \"{Index:5} | {Name:70} | {Prior:15} | {Posterior:15}\"\n print(template.format(Index=\"Index\", Name=\"Question Name\", Prior=\"Prior\", Posterior=\"Posterior\"))\n print(eq)\n for item in cursor:\n d = {'Index': i, 'Name': item['name'], 'Prior': item['prior'], 'Posterior': item['posterior']}\n print(template.format(**d))\n question_idx_to_id[i] = item['_id']\n i += 1\n print(eq)\n return question_idx_to_id\n\n\ndef increment(db, question_hash, n=1):\n \"\"\" Increment the prior for this question and set posterior equal to prior\n :param db: The Mongodb database\n :param question: The hash value for the question whose prior to increment\n :param n: Increment by n\n :return: None, update the db by incrementing prior and set posterior = prior\n \"\"\"\n question = db.questions.find_one({'hash': question_hash})\n question['prior'] += n\n question['posterior'] = question['prior']\n db.questions.update({'_id': question['_id']}, question)\n\n\ndef sample(db, p, most_likely_question_hash=set()):\n \"\"\" Sample a question from the database according to its p-value\n :param db: The mongodb database\n :param p: A string that is either 'prior' or 'posterior'\n :param most_likely_question_hash: A set of hash values of the questions to sample from\n :return: Dictionary of sampled question\n \"\"\"\n cursor = db.questions.find()\n count = cursor.count()\n zero_count = db.questions.find({p: 0}).count()\n if count < 1 or count == zero_count:\n # Trying to sample from empty question set or all the p-values are 0\n print('No questions with non-zero ' + p + ' !')\n return\n weight = 0.0\n if most_likely_question_hash:\n for question in cursor:\n if question['hash'] in most_likely_question_hash:\n weight += question[p]\n r = random.uniform(0, weight)\n s = 0.0\n cursor = db.questions.find()\n for question in cursor:\n if question['hash'] in most_likely_question_hash:\n s += question[p]\n if r < s:\n return question\n return question\n else:\n for question in cursor:\n weight += question[p]\n r = random.uniform(0, weight)\n s = 0.0\n cursor = db.questions.find()\n for question in cursor:\n s += question[p]\n if r < s:\n return question\n return question\n\n\ndef max_posterior(db):\n \"\"\" Return the value of the maximum posterior among questions\n :param db: The Mongodb database\n :return: The maximum (normalized) posterior of a question in the database\n \"\"\"\n cursor = db.questions.find()\n m = 0.0\n total = 0.0\n for item in cursor:\n total += item['posterior']\n m = max(m, item['posterior'])\n if total:\n m /= total\n return m\n\n\ndef reset_priors(db):\n \"\"\" Reset the priors of the questions in the database to reflect how much it can bring entropy down\n :param db: Mongodb database\n :return: None, update db in place\n \"\"\"\n cursor = db.questions.find()\n old_entropy = problems.get_entropy(db)\n for q in cursor:\n c_entropy = 0.5*conditional_entropy(db, q, True) + 0.5*conditional_entropy(db, q, False)\n q['prior'] = old_entropy - c_entropy\n q['posterior'] = q['prior']\n db.questions.update({'_id': q['_id']}, q)\n\n\ndef adjust_posteriors(db, responses_known_so_far, most_likely_problems):\n \"\"\" Update the posteriors of the questions\n :param db: The database\n :param responses_known_so_far: The responses known so far\n :param most_likely_problems: The most likely set of problems\n :return: None, update db in place\n \"\"\"\n cursor = db.questions.find()\n old_entropy = problems.get_entropy(db, most_likely_problems)\n for q in cursor:\n # Update the posterior of a problem to reflect how much it brings down the entropy\n if q['hash'] in responses_known_so_far:\n # If a question was asked already\n q['posterior'] = 0.0\n else:\n # Question hasn't been asked yet, so assume either response is equally likely\n yes_entropy = conditional_entropy(db, q, True, most_likely_problems)\n no_entropy = conditional_entropy(db, q, False, most_likely_problems)\n c_entropy = 0.5 * yes_entropy + 0.5 * no_entropy\n q['posterior'] = old_entropy - c_entropy\n db.questions.update({'_id': q['_id']}, q)\n\n\ndef delete(db, question_id):\n \"\"\" Delete question from both problems and questions database\n :param db: The Mongodb database\n :param question_id: The Mongodb id of the question to be deleted\n :return: None, modify database in place\n \"\"\"\n question_hash = db.questions.find_one({'_id': question_id})['hash']\n db.questions.remove(question_id)\n cursor = db.problems.find()\n for problem in cursor:\n neg_questions = [x for x in problem['negquestions'] if x != question_hash]\n pos_questions = [x for x in problem['posquestions'] if x != question_hash]\n problem['negquestions'] = neg_questions\n problem['posquestions'] = pos_questions\n db.problems.update({'_id': problem['_id']}, problem)\n\n\ndef conditional_entropy(db, q, response, most_likely_problems=list()):\n \"\"\" The conditional entropy H(posterior | response to q)\n :param db: The Mongodb database\n :param q: The question\n :param response: The response to the question\n :param most_likely_problems: List of the most likely problems dictionary\n :return: The conditional entropy H(posterior | response to q)\n \"\"\"\n posteriors = np.array([])\n cursor = db.problems.find()\n most_likely_problems_hash = set([item['hash'] for item in most_likely_problems])\n if response:\n for problem in cursor:\n # If the most_likely_problems set is not empty then\n if most_likely_problems_hash:\n if problem['hash'] not in most_likely_problems_hash:\n continue\n if problem['hash'] in q['negproblems']:\n posteriors = np.append(posteriors, 0.0)\n else:\n posteriors = np.append(posteriors, problem['posterior'])\n else:\n for problem in cursor:\n if most_likely_problems_hash:\n if problem['hash'] not in most_likely_problems_hash:\n continue\n if problem['hash'] in q['posproblems']:\n posteriors = np.append(posteriors, 0.0)\n else:\n posteriors = np.append(posteriors, problem['posterior'])\n if np.any(posteriors):\n return entropy(posteriors)\n return 0.0\n\n\ndef view_problems(db):\n \"\"\" View the YES problems and the NO problems of a question\n :param db: The Mongodb database\n :return: None, print the YES problems and the NO problems\n \"\"\"\n question_idx_to_id = print_list(db)\n while True:\n try:\n idx = int(input('Enter question number: '))\n question_id = question_idx_to_id[idx]\n break\n except ValueError:\n helper.error_number()\n except KeyError:\n helper.error_key()\n print('YES problems: ')\n print('{', end=' ')\n question = db.questions.find_one({'_id': question_id})\n for problem_hash in question['posproblems']:\n problem = db.problems.find_one({'hash': problem_hash})\n print(problem['name'], end=', ')\n print('}')\n print('NO problems: ')\n print('{', end=' ')\n for problem_hash in question['negproblems']:\n problem = db.problems.find_one({'hash': problem_hash})\n print(problem['name'], end=', ')\n print('}')\n\n\ndef print_set(question_names):\n \"\"\" Print a set of question names\n :param question_names: Set of question names\n :return: None, just print the set\n \"\"\"\n s = ', '.join(item for item in question_names)\n print('{' + s + '}')\n","sub_path":"src/askminmax/questions.py","file_name":"questions.py","file_ext":"py","file_size_in_byte":8371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"25765962","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport wave\nimport struct\nimport pyaudio\nfrom scipy.fftpack import fft, ifft\nimport cv2\nfrom scipy import signal\nimport matplotlib\n\n#パラメータ\nRATE=44100\nsec =1 #秒\nCHUNK=RATE*sec\np=pyaudio.PyAudio()\nsa= 'u' #'u' #'o' #'i' #'e' #'a'\nstream=p.open(format = pyaudio.paInt16,\n channels = 1,\n rate = RATE,\n frames_per_buffer = CHUNK,\n input = True,\n output = True) # inputとoutputを同時にTrueにする\n\nfr = RATE #サンプリング周波数\nfn=fr*sec\n\ndef sin_wav(A,f0,fr,t):\n point = np.arange(0,fr*t)\n sin_wav =A* np.sin(2*np.pi*f0*point/fr)\n return sin_wav\n\ndef create_wave(A,f0,fr,t):#A:振幅,f0:基本周波数,fr:サンプリング周波数,再生時間[s]\n sin_wave=0\n #print(A[0])\n int_f0=int(f0[0])\n for i in range(0,len(A),1):\n f1=f0[i]\n sw=sin_wav(A[i],f1,fr,t)\n sin_wave += sw\n sin_wave = [int(x * 32767.0) for x in sin_wave] \n binwave = struct.pack(\"h\" * len(sin_wave), *sin_wave)\n w = wave.Wave_write('./fft_sound/'+sa+'_'+str(sec)+'Hz.wav')\n p = (1, 2, fr, len(binwave), 'NONE', 'not compressed')\n w.setparams(p)\n w.writeframes(binwave)\n w.close()\n\ndef sound_wave():\n wavfile = './fft_sound/'+sa+'_'+str(sec)+'Hz.wav'\n wr = wave.open(wavfile, \"rb\")\n input = wr.readframes(wr.getnframes())\n output = stream.write(input)\n sig =[]\n sig = np.frombuffer(input, dtype=\"int16\") /32768.0\n return sig\n\nt = np.linspace(0,sec, fn)\ninput = stream.read(CHUNK)\n\nsig =[]\nsig = np.frombuffer(input, dtype=\"int16\") /32768.0\n\n#サイン波を-32768から32767の整数値に変換(signed 16bit pcmへ)\nswav = [int(x * 32767.0) for x in sig]\n#バイナリ化\nbinwave = struct.pack(\"h\" * len(swav), *swav)\nw = wave.Wave_write(\"./fft_sound/output_\"+str(sec)+\"_\"+sa+\".wav\")\nparams = (1, 2, fr, len(binwave), 'NONE', 'not compressed')\nw.setparams(params)\nw.writeframes(binwave)\nw.close()\n\ndef FFT(sig,fn,fr):\n freq =fft(sig,fn)\n Pyy = np.sqrt(freq*freq.conj())/fn\n f = np.arange(0,fr,fr/fn)\n ld = signal.argrelmax(Pyy, order=2) #相対強度の最大な番号をorder=10で求める\n ssk=0\n fsk=[]\n Psk=[]\n maxPyy=max(np.abs(Pyy))\n for i in range(len(ld[0])): #ピークの中で以下の条件に合うピークの周波数fと強度Pyyを求める\n if np.abs(Pyy[ld[0][i]])>0.05*maxPyy and f[ld[0][i]]<20000 and f[ld[0][i]]>20:\n fssk=f[ld[0][i]]\n Pssk=np.abs(Pyy[ld[0][i]])\n fsk.append(fssk)\n Psk.append(Pssk)\n ssk += 1\n #print('{}'.format(np.round(fsk[:len(fsk)],decimals=3))) #標準出力にピーク周波数fskを小数点以下二桁まで出力する\n #print('{}'.format(np.round(Psk[:len(fsk)],decimals=4))) #標準出力にピーク強度Pskを小数点以下6桁まで出力する\n return freq,Pyy,fsk,Psk,f\n\ndef draw_pic(freq,Pyy,fsk,Psk,f,sk,sig):\n matplotlib.rcParams.update({'font.size': 18, 'font.family': 'sans', 'text.usetex': False}) \n fig = plt.figure(figsize=(12,12)) #(width,height)\n\n axes1 = fig.add_axes([0.1, 0.55, 0.8, 0.4]) # main axes\n axes2 = fig.add_axes([0.15, 0.7, 0.2, 0.2]) # insert axes\n axes3 = fig.add_axes([0.1, 0.1, 0.8, 0.35]) # main axes\n\n axes1.plot(t, sig)\n axes1.grid(True)\n axes1.set_xlim([0, 0.1])\n\n axes2.set_ylim(-1.2,1.2)\n axes2.set_xlim(0,sec)\n axes2.plot(t,sig)\n\n Pyy_abs=np.abs(Pyy)\n axes3.plot(f,Pyy_abs)\n axes3.axis([min(fsk)*0.9, max(fsk)*1.1, 0,max(Pyy_abs)*1.5]) #0.5, 2\n axes3.grid(True)\n axes3.set_xscale('log')\n axes3.set_ylim(0,max(Pyy_abs)*1.5)\n\n axes3.set_title('{}'.format(np.round(fsk[:len(fsk)],decimals=1))+'\\n'+'{}'.format(np.round(Psk[:len(fsk)],decimals=4)),size=10) #グラフのタイトルにピーク周波数とピーク強度を出力する\n axes3.plot(fsk[:len(fsk)],Psk[:len(fsk)],'ro') #ピーク周波数、ピーク強度の位置に〇をつける\n # グラフにピークの周波数をテキストで表示\n for i in range(len(fsk)):\n axes3.annotate('{0:.1f}'.format(fsk[i]), #np.round(fsk[i],decimals=2) でも可 '{0:.0f}(Hz)'.format(fsk[i])\n xy=(fsk[i], Psk[i]),\n xytext=(10, 20),\n textcoords='offset points',\n arrowprops=dict(arrowstyle=\"->\",connectionstyle=\"arc3,rad=.2\")\n )\n\n plt.pause(1)\n wavfile=str(sec)+'_'+sa+str(sk)\n plt.savefig('./fft_sound/figure_'+wavfile+'.jpg')\n plt.close()\n #return Psk, fsk\n\n#入力音声をFFTして描画する \nfreq,Pyy,fsk,Psk,f=FFT(sig,fn,fr)\ndraw_pic(freq,Pyy,fsk,Psk,f,1,sig)\n#マイク入力を出力\ninput = binwave\noutput = stream.write(input)\n\n#FFTで得られた周波数Pskと振幅fsk\nA=Psk/max(Psk)/len(fsk)\nf=fsk\nprint(f)\nprint(A)\n\n#上記のAとfを使ってサイン波でフォルマント合成\nsigs =[]\ncreate_wave(A, f, fr, sec)\nsigs = sound_wave()\n\n#フォルマント合成音声をFFTして描画する\nfreqs,Pyys,fsks,Psks,fss=FFT(sigs,fn,fr)\ndraw_pic(freqs,Pyys,fsks,Psks,fss,2,sigs) \n\nwhile True:\n #永続的にフォルマント合成音を発生する\n sig =[]\n create_wave(A, f, fr, sec)\n sig = sound_wave()\n ","sub_path":"out_fft_sound.py","file_name":"out_fft_sound.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"17901884","text":"# -*- coding: utf-8 -*-\nimport json\nimport mysql.connector\nimport pandas as pd\n\n#Carpeta en donde se guardarán los JSON generados\n#En caso de archivo relativo al directorio dejar en blanco\nCARPETA = \"\"\n\n#-----------ESCRIBIR PREGUNTAS EN BD EN FORMATO JSON-----------------\ndef escribirEnBD(preguntas):\n '''Recibe un diccionario, lo convierte a json y la guarda en la BD'''\n #Crear una conexión con MySQL\n miConexion = mysql.connector.connect( host='localhost', user= 'root', passwd='root', db='actividad11')\n #Crear una cursor, este objeto es el que permite la ejecución de instrucciones en MySQL\n cursor = miConexion.cursor()\n #Se meten las preguntas\n for pregunta in preguntas:\n pjson = json.dumps(preguntas[pregunta], indent=4, ensure_ascii=False)\n #Inserta el valor que viene de JAVA\n cursor.execute(\"insert into pregunta values (0, '\"+str(pjson)+\"');\")\n miConexion.commit()\n print(\"Preguntas ingresadas\")\n cursor.close()\n\ndef crearPreguntasJson():\n '''Crear las preguntas en formato JSON para la base de datos'''\n '''\n Formato de preguntas\n PreguntaText\n Opciones\n Tipo\n TiempoResp\n Intentos \n Complejidad\n \n Notas\n Formato de las opciones EJEMPLO: OP1-OPCION 1;OP2-OPCION 2;... HASTA OPCION N\n Tipo de pregunta 1- Selección múltiple; 0 - De una sola respuesta\n TiempoResp es una cadena que respresenta los minutos y segundos con forma mm:ss\n Complejidad roda 3 valores: 0 - Básico; 1- Intermedio; 2- Avanzado\n '''\n\n #Estrutura de tipo diccionario para todas las perguntas\n preguntas = {}\n\n #-------------AGREGANDO PREGUNTAS A LA ESCTRUCTURA-------------\n preguntas[1] = {'Pregunta':'¿Qué es React?',\n 'Opciones' :'OP1-Es una librería de JavaScript declarativa para interfaces web'\\\n 'OP2-Es un lenguaje de programación interpretado'\\\n 'OP3-Es el nombre de una página web',\n 'Tipo': 0,\n 'TiempoResp':'00:20',\n 'Intentos':1,\n 'Complejidad':0}\n\n preguntas[2] = {'Pregunta':'¿Qué es Pandas?',\n 'Opciones':'OP1-Es un lenguaje de programación interpretado'\\\n 'OP2-Es una biblioteca de software escrita como extensión de NumPy'\\\n 'OP3-Es el nombre de un animal',\n 'Tipo': 0,\n 'TiempoResp':'00:20',\n 'Intentos':1,\n 'Complejidad':0}\n\n preguntas[3] = {'Pregunta':'¿Qué es Python?',\n 'Opciones':'OP1-Es un lenguaje de programación interpretado'\\\n 'OP2-Es una biblioteca de software escrita como extensión de NumPy'\\\n 'OP3-OP1-Es una librería de JavaScript declarativa para interfaces web',\n 'Tipo': 0,\n 'TiempoResp':'00:20',\n 'Intentos':1,\n 'Complejidad':0}\n\n preguntas[4] = {'Pregunta':'¿Cuáles son algunas de las características de Python?',\n 'Opciones':'OP1-Lenguaje interpretado'\\\n 'OP2-Es una biblioteca de software escrita como extensión de NumPy'\\\n 'OP3-Fuertemente tipado'\\\n 'OP4-Totalmente Orientado a Objetos',\n 'Tipo': 1,\n 'TiempoResp':'00:30',\n 'Intentos':2,\n 'Complejidad':1}\n\n preguntas[5] = {'Pregunta':'¿Cuáles son los tipos de datos de pandas?',\n 'Opciones':'OP1-DataFrames'\\\n 'OP2-Series'\\\n 'OP3-Listas'\\\n 'OP4-Panel'\\\n 'OP5-Estructuras',\n 'Tipo': 1,\n 'TiempoResp':'00:30',\n 'Intentos':2,\n 'Complejidad':2}\n\n preguntas[6] = {'Pregunta':'¿Cuáles son los estados de un ciclo de vida en React?',\n 'Opciones':'OP1-Destruído'\\\n 'OP2-Montado'\\\n 'OP3-Actualización'\\\n 'OP4-Desmontado'\\\n 'OP5-Creado',\n 'Tipo': 1,\n 'TiempoResp':'00:30',\n 'Intentos':2,\n 'Complejidad':1}\n\n preguntas[7] = {'Pregunta':'¿Por qué se llama python?',\n 'Opciones':'OP1-En nombre del animal homonimo'\\\n 'OP2-En nombre de una serie llamada Monty Python Flying Circus'\\\n 'OP3-Nunca se ha mencionado',\n 'Tipo': 0,\n 'TiempoResp':'00:20',\n 'Intentos':1,\n 'Complejidad':0}\n\n preguntas[8] = {'Pregunta':'¿Qué es numpy?',\n 'Opciones':'OP1-Es el nombre de un lenguaje de programación'\\\n 'OP2-Es una biblioteca para JavaScript que da soporte para crear vectores y matrices grandes multidimensionales'\\\n 'OP3-Es una biblioteca para Python que da soporte para crear vectores y matrices grandes multidimensionales',\n 'Tipo': 0,\n 'TiempoResp':'00:15',\n 'Intentos':1,\n 'Complejidad':2}\n \n \n escribirEnBD(preguntas)\n\n\ndef codificarJSON(preguntas):\n '''Toma un diccionario de Pandas y le da formato para mostrarlo en DJ3'''\n matriz = {}\n matriz[\"nodes\"] = []\n matriz[\"links\"] = []\n i =0\n for fila in preguntas.index:\n nodes = {}\n nodes[\"name\"] = \"Pregunta \"+ str(preguntas[\"IdPregunta\"][fila])\n nodes[\"group\"] = 0\n matriz[\"nodes\"].append(nodes)\n j = 0\n for pregunta in preguntas.index:\n links = {}\n links[\"source\"] = i\n links[\"target\"] = j\n aux = int(preguntas[\"Complejidad\"][fila]) + int(preguntas[\"Complejidad\"][pregunta])\n if aux != 0:\n links[\"value\"] = int(preguntas[\"Complejidad\"][fila]) + int(preguntas[\"Complejidad\"][pregunta])\n matriz[\"links\"].append(links)\n j = + 1\n i= i+1\n #print(matriz)\n with open('static/data/preguntas.json', 'w', encoding='utf8') as file:\n json.dump(matriz, file, indent=4, ensure_ascii=False)\n\n#-----------CARGAR PREGUNTAS EN BD EN FORMATO JSON-----------------\ndef cargarPreguntas():\n '''Carga todas las preguntas de la BD en formato de tablas de pandas'''\n #Crear una conexión con MySQL\n miConexion = mysql.connector.connect( host='localhost', user= 'root', passwd='root', db='actividad11')\n #Crear una cursor, este objeto es el que permite la ejecución de instrucciones en MySQL\n cursor = miConexion.cursor()\n cursor.execute(\"SELECT * FROM pregunta\")\n #Cargar todas las preguntas\n aux = []\n #Decodificar Json\n for preguntajson in cursor.fetchall():\n #print('Valor: ', preguntajson)\n #Caragr cadena Json\n d = json.loads(preguntajson[1])\n #Agregar IdPregunta como una valor en la estructura\n d['IdPregunta'] = preguntajson[0]\n #print(d)\n aux.append(d)\n \n #print(pd.DataFrame(aux))\n codificarJSON(pd.DataFrame(aux))\n\n\nif __name__=='__main__':\n crearPreguntasJson()\n #cargarPreguntas()","sub_path":"Actividad 11/Actividad6.py","file_name":"Actividad6.py","file_ext":"py","file_size_in_byte":6352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"375316431","text":"from nose.tools import assert_is_not_none, assert_equal\nfrom datetime import datetime, timedelta\nfrom logbook import Logger\nfrom ..db import (\n get_query_bi_kind_and_text,\n has_query_bi_kind_and_text,\n get_query_mtime_bi_kind_and_text,\n)\nfrom .sync import sync\nfrom .local import get_current_conf\n\n\nlog = Logger(__name__)\n\n\ndef from_remote(conn, kind, text):\n return get_query_bi_kind_and_text(conn, kind, text)\n\n\ndef has(conn, kind, text):\n return has_query_bi_kind_and_text(conn, kind, text)\n\n\ndef expired(conn, kind, text):\n mtime = get_query_mtime_bi_kind_and_text(conn, kind, text)\n assert_is_not_none(mtime)\n return mtime + timedelta(seconds=interval()) < datetime.utcnow()\n\n\ndef interval():\n t = get_current_conf()['TORABOT_QUERY_EXPIRE']\n assert_equal(int(t), t)\n return int(t)\n\n\ndef query(conn, kind, text, timeout):\n dosync = lambda: sync(kind, text, timeout, conn=conn)\n if not has(conn, kind, text):\n log.info('query {} of {} dosn\\'t exist', text, kind)\n dosync()\n elif expired(conn, kind, text):\n log.info('query {} of {} expired', text, kind)\n dosync()\n return get_query_bi_kind_and_text(conn, kind, text)\n","sub_path":"torabot/core/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"23217","text":"def ndiamond(n):\n lst1 = []\n for i in range(0, int(n / 2) + 1):\n spaces = ' ' * int((n / 2) - i)\n num_cs = 2 * i + 1\n cs1 = \"\"\n for j in range(1, int((num_cs + 3) / 2)):\n cs1 += str(j)\n cs2 = cs1[::-1]\n cs2 = cs2[1:]\n row = spaces + cs1 + cs2\n lst1.append(row)\n lst2 = lst1[::-1]\n lst2 = lst2[1:]\n lst = lst1 + lst2\n\n for row in lst:\n print(row)\n\nif __name__ == \"__main__\":\n ndiamond(5)\n","sub_path":"IMT2020501_a4/IMT2020501/evaluation3/mycode/ndiamond_b.py","file_name":"ndiamond_b.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"183721012","text":"import configparser\nfrom pandas import DataFrame\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport datetime\nimport sys\nimport os\nfrom functions import *\n\nclass Spider:\n def __init__(self, config_file):\n self.config_file = config_file\n self.immoscout_data = DataFrame()\n self.config()\n self.boot()\n\n def config(self):\n config = configparser.ConfigParser()\n config.read(self.config_file)\n defaultConfig = config['DEFAULT']\n self.projectname = defaultConfig['PROJECT_NAME']\n self.domain = defaultConfig['DOMAIN']\n self.urllocation = defaultConfig['URL_LOCATION']\n self.urltype = defaultConfig['URL_TYPE']\n self.urlpayment = defaultConfig['URL_PAYMENT']\n self.parsermethod = defaultConfig['PARSER_METHOD']\n self.maxcounttag = defaultConfig['MAX_COUNT_TAG']\n self.rawdatatag = defaultConfig['RAW_DATA_TAG']\n self.rawdatacssselector = defaultConfig['RAW_DATA_TAG_CSS_SELECTOR']\n self.addcssselector = defaultConfig['LOCATION_CSS_SELECTOR']\n self.maxcount = int(defaultConfig['MAX_COUNT_LIMIT'])\n \n\n def boot(self):\n create_project_dir('/output/' + self.projectname)\n base_url = self.domain+self.urllocation+self.urltype+self.urlpayment\n max_pages = self.get_max(base_url)\n link_count = 1\n link_list_full = []\n for i in range(1, max_pages):\n link_list_full.append(base_url+\"?pagenumber=\"+str(i))\n for link in link_list_full:\n print(\"Crawling: \"+link+\" (link #\"+str(link_count)+\" of \"+max_pages+\")\")#print progress\n link_count += 1#add to progress indicator\n self.get_data(link)\n\n \n\n\n def get_max(self, url):\n try:\n url = requests.get(url)\n except Exception:\n print(\"Fehler beim Oeffnen der Website\")\n try:\n site_extract = BeautifulSoup(url.text, self.parsermethod)\n except Exception:\n print(\"Fehler beim Einlesen in BeautifulSoup\")\n try:\n max_link = max([int(n[\"value\"]) for n in site_extract.find_all(self.maxcounttag)])#get the maximum value for links in a specific sub-site\n except Exception:\n print(\"Fehler beim Loop\")\n else:\n if max_link > self.maxcount:\n return self.maxcount\n else: \n return max_link\n\n def get_data(self, url):\n try:\n url_raw = url#save url as string for real estate type\n url = requests.get(url)\n except Exception:\n return None\n except Exception:\n return None\n try:\n site_extract = BeautifulSoup(url.text, self.parsermethod)\n rawdata_extract = site_extract.find_all(self.rawdatatag, {\"class\":self.rawdatacssselector})#extract every result box\n except AttributeError as e:\n return None\n\n price = []\n size = []\n location = []\n ownership = []\n immo_type = []\n for i in range(0,len(rawdata_extract)):\n try:\n price.append(rawdata_extract[i].find_all(\"dd\")[0].get_text().strip())#extract price\n except Exception:\n price.append(-1)\n try:\n size.append(rawdata_extract[i].find_all(\"dd\")[1].get_text().strip())#extract size\n except Exception:\n size.append(0)\n try:\n location.append(rawdata_extract[i].find_all(self.rawdatatag, {\"class\":self.addcssselector})[0].get_text().strip())#extract location\n except Exception:\n location.append(\"#\")\n \n if \"/wohnung\" in self.urltype:\n immo_type.append(\"Wohnung\")\n elif \"/haus\" in self.urltype:\n immo_type.append(\"Haus\")\n if \"-mieten\" in self.urlpayment:\n ownership.append(\"Miete\")\n elif \"-kaufen\" in self.urlpayment:\n ownership.append(\"Kauf\")\n self.immoscout_data = self.immoscout_data.append(DataFrame({\"price\":price, \n \"size\":size,\n \"location\":location, \n \"real_estate\":immo_type, \n \"ownership\":ownership}), \n ignore_index=True)","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"380875077","text":"# Generators are an advanced topic. They rely heavily on recursion.\n# Most importantly - they don't return once which would force them to\n# store a large data set in memory. Instead or returning a value they\n# yield and then continue processing\n\ndef getPermutations(string):\n if len(string) == 1:\n yield string\n else:\n for i in range(len(string)):\n for perm in getPermutations(string[:i] + string[i+1:]):\n yield string[i] + perm\n\nall = getPermutations(\"abcdefgjdflk;ghgkld;fshgeoi[gehrg]\")\n\nfor item in all:\n print(item)\n","sub_path":"Juan/Exercises/Week1/recursion/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"122675274","text":"#!/bin/python38\n\nFLOOR = object()\nSEAT_EMPTY = object()\nSEAT_FULL = object()\nprint(f'FLOOR: {FLOOR}')\nprint(f'SEAT_EMPTY: {SEAT_EMPTY}')\nprint(f'SEAT_FULL: {SEAT_FULL}')\n\n\ndef get_layout(str_layout: str) -> list:\n\tlayout = []\n\tfor str_line in str_layout.split('\\n'):\n\t\tif str_line == '':\n\t\t\tcontinue\n\n\t\tline = []\n\t\tfor char in str_line:\n\t\t\tif char == 'L':\n\t\t\t\tline.append(SEAT_EMPTY)\n\t\t\telif char == '.':\n\t\t\t\tline.append(FLOOR)\n\t\t\telif char == '#':\n\t\t\t\tline.append(SEAT_FULL)\n\t\t\telse:\n\t\t\t\traise ValueError(\n\t\t\t\t\tf'Unexpected character {char} in layout string'\n\t\t\t\t)\n\t\tlayout.append(line)\n\treturn layout\n\n\ndef get_layout_str(layout: list) -> str:\n\tstr_lines = []\n\tfor line in layout:\n\t\tstr_line = ''\n\t\tfor item in line:\n\t\t\tstr_line = str_line + {\n\t\t\t\tSEAT_EMPTY: 'L',\n\t\t\t\tFLOOR: '.',\n\t\t\t\tSEAT_FULL: '#',\n\t\t\t}[item]\n\t\tstr_lines.append(str_line)\n\treturn '\\n'.join(str_lines)\n\n\ndef step_layout(layout: list) -> list:\n\tnew_layout = [line[:] for line in layout]\n\tfor y in range(len(layout)):\n\t\tfor x in range(len(layout[y])):\n\t\t\tif layout[y][x] is FLOOR:\n\t\t\t\tcontinue\n\n\t\t\tadjacent_count = 0\n\t\t\tfor x_offset in [-1, 0, 1]:\n\t\t\t\tfor y_offset in [-1, 0, 1]:\n\t\t\t\t\tif x_offset == 0 and y_offset == 0:\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\tx_adj = x + x_offset\n\t\t\t\t\ty_adj = y + y_offset\n\t\t\t\t\tif y_adj < 0 or y_adj >= len(layout):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif x_adj < 0 or x_adj >= len(layout[y_adj]):\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\tif layout[y_adj][x_adj] is SEAT_FULL:\n\t\t\t\t\t\tadjacent_count += 1\n\n\t\t\tif adjacent_count == 0:\n\t\t\t\tnew_layout[y][x] = SEAT_FULL\n\t\t\telif adjacent_count >= 4:\n\t\t\t\tnew_layout[y][x] = SEAT_EMPTY\n\n\treturn new_layout\n\n\nif True:\n\twith open('./day11.data', 'r') as f:\n\t\ttext_layout = f.read()\nelse:\n\ttext_layout = '''\nL.LL.LL.LL\nLLLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLLL\nL.LLLLLL.L\nL.LLLLL.LL\n'''\n\nlayout = get_layout(text_layout)\n\nfor i in range(1000):\n\tprint(f'Iteration {i}:')\n\tprint(get_layout_str(layout))\n\tprint('=====================')\n\tnew_layout = step_layout(layout)\n\tif new_layout == layout:\n\t\tbreak\n\telse:\n\t\tlayout = new_layout\n\ncount = 0\nfor line in new_layout:\n\tfor pos in line:\n\t\tif pos is SEAT_FULL:\n\t\t\tcount += 1\nprint(f'{count} seats are occupied.')\n\n","sub_path":"day11/day11-part-1.py","file_name":"day11-part-1.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"644314167","text":"import math\ndef print_list(a):\n out = ''\n for ai in a:\n out += str(ai) + ' '\n else:\n out = out[:-1]\n print(out)\n\ndef insertion_sort(a, n, g):\n cnt = 0\n for i in range(g, n):\n v = a[i]\n j = i - g\n while j >= 0 and a[j] > v:\n a[j + g] = a[j]\n j = j - g\n cnt += 1\n a[j + g] = v\n return cnt\n\ndef shell_sort(a, n):\n cnt = 0\n m = 0\n g = []\n h = 1\n while True:\n if h > n:\n break\n m += 1\n g.append(h)\n h = 3 * h + 1\n g.reverse()\n\n for i in range(m):\n cnt += insertion_sort(a, n, g[i])\n print(m)\n print_list(g)\n print(cnt)\n for i in a:\n print(i)\n\nn = int(input())\na = [0] * n\nfor i in range(n):\n a[i] = int(input())\n\nshell_sort(a, n)\n\n","sub_path":"Python_codes/p02262/s423378543.py","file_name":"s423378543.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"212811563","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 31 09:45:21 2021\n\n@author: Jen\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 24 09:04:44 2021\n\n@author: Jen\n\"\"\"\n### Standard loading of libraries\nimport pandas\n\nimport numpy\n\n### setting my working directory here, because I'm always working out of random folders it seems##\nfrom os import chdir, getcwd\nwd=getcwd()\nchdir(wd)\n\nimport os\nos.chdir('/Users/Jen/Downloads/')\n\n\n### loading file###Named it data\ndata = pandas.read_csv('inv_taxonomyProcessed.csv', low_memory = False)\n\n\n\n###Wanted list of column names \nprint(data.columns)\n\n\n\n###OK here's the good stuff-- So the logic here is that I wanted a table that \n#had year as the rows and species or OTUs as they are called in this package (Operational Taxonomic Unit-- which is whatever level of taxonomy you want)\n##as the columns with the sequence counts as the values for those columns.\n\n##I'm going to do that using the pivot function, unfortunately when I first tried that with this dataset\n##I found that there were duplicate taxonID counts for each plotID/setDate combo (which happens)\n##That's fine, but it breaks the pivot function.\n\n## here is just a bit of code which summarizes where there are dupilicates within year\n##Not really necesaary, but I wanted to see why I was getting an error and this confirms it.\n\ndups = data.pivot_table(index=[\"collectDate\",'siteID'], columns= 'scientificName', values='individualCount', aggfunc=len)\n\n##Anyway, my solution to this duplication issue is to have Python combine (sum) any duplicate counts\n## That's what this line of code does. It creates another dataframe (df2) in which it has aggregated \n## any duplications into a single count value by adding them together\n\n\ndf2 = data.groupby([\"collectDate\", 'siteID', 'scientificName' ],as_index=False).agg({'individualCount' : \"sum\"})\n\n##Now to check that that actually happened. All the values here should be 1\n\nNo_dups = df2.pivot_table(index=[\"collectDate\",'siteID'], columns= 'scientificName', values='individualCount', aggfunc=len)\n\n\n##So now that we've done that, we can make the table we want. Here I've made it so that \n##the index (rows) are the 'plotID','setDate', \n##the columns are the 'taxonID' (kind of a proxy for OTUS in the skbio package but we could use another- your call)\n##and the values are the individual counts. \n\nbiodiv_data = df2.pivot(index=[\"collectDate\",'siteID'], columns= 'scientificName', values='individualCount')\n\n### Now to use it in skbio you can't have NaN data, so we'll need to replace it with zeros\n##That's what these two lines of code are\n\nbiodiv_data0 = biodiv_data.apply (pandas.to_numeric, errors='coerce')\nbiodiv_data0= biodiv_data.replace(numpy.nan,0)\n\n\n## Quick check to see that they are all zeros\nprint (biodiv_data0)\n\n\n\n###Now, we've got to get the data into the right type to put into skbio and do all the \n##fun calculations-- specifically we're going to need an array and ids for \n## the library to run on\n\n \narray = biodiv_data0.to_numpy() \n\nids= list(biodiv_data0.index)\n\n### Now that those two objects exist we can plug them in and start getting our \n## analyses back\n\n\n#### Number of species per site -- this makes a list of values entitled \"adiv_obs_otus\" which is the number of species at each sampling point as known as species richness\nfrom skbio.diversity import alpha_diversity\nadiv_obs_otus = alpha_diversity('observed_otus', array, ids)\nadiv_obs_otus\n\n## Shannon's for each site\nfrom skbio.diversity import alpha_diversity\nshannon= alpha_diversity('shannon', array, ids)\n\n\n\n###Now that you've \n\n# Calling DataFrame constructor on list with index named by state\nobs_otus = pandas.DataFrame(adiv_obs_otus, index= biodiv_data0.index, columns =[\"richness\"] )\nobs_otus\n\nshannon_df = pandas.DataFrame(shannon, index= biodiv_data0.index, columns =['shannon'] )\nshannon_df\n\n#merge dataframes by index\nmergedDf = obs_otus.merge(shannon_df, left_index=True, right_index=True)\n\n#make index a column\nmergedDf.reset_index(inplace=True)\n\n\n##Remove -0 shannons\nmergedDf.drop(mergedDf.index[mergedDf['shannon'] == -0], inplace = True)\n\nmergedDf.to_csv('/Users/Jen/Downloads/inv_counts.csv', index = False)\n\n## Averages for each site\nrich_mean = mergedDf.groupby(['siteID']).agg({'richness': ['mean', 'min', 'max']})\n\nprint(rich_mean)\n\nshannon_mean = mergedDf.groupby(['siteID']).agg({'shannon': ['mean', 'min', 'max']})\n\nprint(shannon_mean)\n\ndf.to_csv(r'Path where you want to store the exported CSV file\\File Name.csv', index = False)\n\n###ANOVAs & box plots\n##richness by site-- ### You can also do this for Shannon and by year--\nimport scipy.stats as stats\nstats.f_oneway(mergedDf[\"shannon\"][mergedDf['siteID'] == 'BARC'],\n mergedDf[\"shannon\"][mergedDf['siteID'] == 'FLINT'],\n mergedDf[\"shannon\"][mergedDf['siteID'] == 'MAYF'])\n\n\nfrom statsmodels.stats.multicomp import pairwise_tukeyhsd\ntukey = pairwise_tukeyhsd(endog=mergedDf[\"shannon\"],groups = mergedDf['siteID'], alpha=0.05)\nprint(tukey)\n\n\nimport seaborn as sb\nimport matplotlib.pyplot as plt\n\nay= sb.catplot(x=\"siteID\", y=\"richness\", kind=\"box\", data=mergedDf) \nay= sb.stripplot(x=\"siteID\", y=\"richness\", data=mergedDf, color=\".4\") \n\n","sub_path":"Sp_21/pivot_biodiversity.py","file_name":"pivot_biodiversity.py","file_ext":"py","file_size_in_byte":5254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"642367377","text":"\n#------------------------initializations-------------------------\n\nfrom converters import *\nimport zipfile, os, shutil\n\n# Read zip file (xrns in this case):\nzip = zipfile.ZipFile('Test.xrns')\n\n# Read XML file:\nglobal songFile\nsongFile = str(zip.read('Song.xml')).split(\"\\\\n\")\n\n# Data structure initialization:\nglobal songData\nsongData = {}\n\n# Write 64 lines:\ndef drawLines(): \n\tdrawLines = []\n\n\tfor line in range(64):\n\t\tdrawLines.append(['-','-','-','-','-','-','-','-'])\n\n\treturn(drawLines)\n\ndef createPatterns():\n\tpatterns = []\n\n\tfor i in range(1,100):\n\t\tvalue = str(i)\n\n\t\tif len(value) < 2:\n\t\t\tvalue = '0' + str(i)\n\n\t\tpatterns.append(value)\n\n\treturn(patterns)\n\n#-------------------------------//-------------------------------\n\ndef start(thisList=songFile):\n\n\t###############################################################\n\t#-------------------------------------------------------------#\n\t#-------------------------SAMPLER DATA------------------------#\n\t#-------------------------------------------------------------#\n\t###############################################################\n\n\tsampler_data = open('sampler_data.txt', 'w+')\n\tsampler_loops = open('sampler_loops.txt', 'w+')\n\n\ttotalTags = 0\n\tauxList = []\n\tsamples = {}\n\n\tfor tag in thisList:\n\n\t\tif tagHasValue(tag, 'Sample'):\n\t\t\ttotalTags += 1\n\n\tfor i in range(1,totalTags+1):\n\n\t\tcounter = 0\n\t\titem = []\n\n\t\tfor tag in thisList:\n\n\t\t\tif tagHasValue(tag, 'Sample'):\n\t\t\t\tcounter += 1\n\n\t\t\tif counter >= i and tagHasValue(tag, 'Sample', True):\n\t\t\t\tbreak\n\n\t\t\tif counter == i:\n\t\t\t\tif tagHasValue(tag, 'Sample') == False:\n\t\t\t\t\titem.append(tag)\n\n\t\tauxList.append(item)\n\n\tfor z in range(len(auxList)):\n\n\t\tsamples['Sample ' + str(z+1)] = auxList[z]\n\n\tauxList = []\n\tcounter = 0\n\n\tfor sample in samples:\n\t\titem = []\n\t\tcounter += 1\n\n\t\tfor tag in samples[sample]:\n\n\t\t\tif tagHasValue(tag, 'LoopMode'):\n\t\t\t\tloopMode = getValueFromTag(tag, 'LoopMode')\n\n\t\t\telif tagHasValue(tag, 'LoopStart'):\n\t\t\t\tstartPoint = getValueFromTag(tag, 'LoopStart', 3)\n\n\t\t\telif tagHasValue(tag, 'LoopEnd'):\n\t\t\t\tendPoint = getValueFromTag(tag, 'LoopEnd', 3)\n\n\t\t\telif tagHasValue(tag, 'BaseNote'):\n\t\t\t\tbaseNote = getValueFromTag(tag, 'BaseNote', 3)\n\t\t\t\titem.append(baseNote)\n\n\t\t\telif tagHasValue(tag, 'DisplayLength'):\n\t\t\t\tsampleSize = getValueFromTag(tag, 'DisplayLength', 3)\n\n\t\tif loopMode == 'Off':\n\t\t\tstartTime = 0\n\t\t\titem.append(startTime)\n\n\t\t\tendTime = samplesToMilliseconds(sampleSize)\n\t\t\titem.append(endTime)\n\n\t\t\titem.append(0)\n\t\t\tsampler_loops.write(str(counter) + ', 0\\n')\n\n\t\telse:\n\t\t\tif startPoint > 0:\n\t\t\t\tstartTime = samplesToMilliseconds(startPoint)\n\t\t\telse:\n\t\t\t\tstartTime = 0\n\t\t\titem.append(startTime)\n\n\t\t\tendTime = samplesToMilliseconds(endPoint-startPoint, 1)\n\t\t\titem.append(endTime)\n\n\t\t\titem.append(1)\n\t\t\tsampler_loops.write(str(counter) + ', 1\\n')\n\n\t\tfor i in item:\n\t\t\tsampler_data.write(str(i) + ',')\n\n\t\tsampler_data.write('\\n')\n\t\n\tsampler_data.close()\n\tsampler_loops.close()\n\n\t###############################################################\n\t#-------------------------------------------------------------#\n\t#-------------------------PATTERN DATA------------------------#\n\t#-------------------------------------------------------------#\n\t###############################################################\n\n\ttotalTags = 0\n\tauxList = []\n\n\tfor tag in thisList:\n\n\t\tif tagHasValue(tag, 'Pattern'):\n\t\t\ttotalTags += 1\n\n\tif totalTags >= 2:\n\t\ttotalTags //= 2\n\n\t#------------------------------//------------------------------\n\t#---------------------get pattern contents---------------------\n\n\tfor i in range(1,totalTags+1):\n\n\t\tcounter = 0\n\t\titem = []\n\n\t\tfor tag in thisList:\n\n\t\t\tif tagHasValue(tag, 'Pattern'):\n\t\t\t\tcounter += 1\n\n\t\t\tif counter >= i and tagHasValue(tag, 'Pattern', True):\n\t\t\t\tbreak\n\n\t\t\tif counter == i:\n\t\t\t\tif tagHasValue(tag, 'Pattern') == False:\n\t\t\t\t\titem.append(tag)\n\n\t\tauxList.append(item)\n\n\t#------------------------------//------------------------------\n\t#---------------------store data structure---------------------\n\n\tfor z in range (len(auxList)):\n\n\t\tsongData['Pattern ' + str(z)] = auxList[z]\n\n\tdel auxList\n\tdel thisList\n\n\t#------------------------------//------------------------------\n\t#-----------------------passa os valores-----------------------\n\n\tfor pattern in songData:\n\t\tfindTracks('<Pattern>', '</Pattern>', songData[pattern], pattern)\n\n\t#------------------------------//------------------------------\n\ndef findTracks(openTag, closedTag, thisList, pattern, totalTags=0):\n\n\t#----------------obter o número de tags abertos----------------\n\n\topenTag = '<PatternTrack type=\"PatternTrack\">'\n\tclosedTag = '</PatternTrack>'\n\n\tfor tag in thisList:\n\n\t\tif tag.find(openTag) > -1:\n\n\t\t\ttotalTags += 1\n\n\t#------------------------------//------------------------------\n\t#-------------obter a lista segmentada por tracks--------------\n\n\tauxList = []\n\n\tfor i in range(1,totalTags+1):\n\n\t\tcounter = 0\n\t\titem = []\n\n\t\tfor k in thisList:\n\n\t\t\tif k.find(openTag) > -1:\n\t\t\t\tcounter += 1\n\n\t\t\tif counter >= i and k.find(closedTag) > -1:\n\t\t\t\tbreak\n\n\t\t\tif counter == i:\n\t\t\t\tif k.find(openTag) == -1:\n\t\t\t\t\titem.append(k)\n\n\t\tauxList.append(item)\n\n\t#------------------------------//------------------------------\n\t#---------------------store data structure---------------------\n\n\tsongData[pattern].clear()\n\tsongData[pattern] = dict(songData[pattern])\n\n\tfor z in range (len(auxList)):\n\n\t\tsongData[pattern]['Track ' + str(z+1)] = auxList[z]\n\n\tdel auxList\n\tdel thisList\n\n\t#------------------------------//------------------------------\n\t#-----------------------passa os valores-----------------------\n\n\ttrackIndex = 0\n\n\tfor track in songData[pattern]:\n\t\tfindLines(songData[pattern][track], pattern, track)\n\n\t#------------------------------//------------------------------\n\ndef findLines(thisList, pattern, track, totalTags=0):\n\n\t#------------------------find line tags------------------------\n\n\topenTag = '<Line index=\"'\n\tclosedTag = '</Line>'\n\n\tfor tag in thisList:\n\n\t\tif tag.find(openTag) > -1:\n\n\t\t\ttotalTags += 1\n\n\t#------------------------------//------------------------------\n\t#-----------------get lines from each channel------------------\n\t'''\n\titem ID\n\t[0] Note\n\t[1] Volume\n\t[2] Duration\n\t[3] Instrument\n\t[4] Start location\n\t[5] Fade in\n\t[6] Fadeout\n\t[7] Go to pattern\n\t'''\n\tauxList = drawLines()\n\tlineIndex = None\n\n\tpatternList = createPatterns()\n\tnote = '-'\n\tinst = '-'\n\tfxValue = '-'\n\tfxNumber = '-'\n\n\tfor i in range(1,totalTags+1):\n\n\t\tcounter = 0\n\t\titem = ['-','-','-','-','-','-','-','-']\n\n\t\tfor k in thisList:\n\n\t\t\tif k.find(openTag) > -1:\n\t\t\t\tcounter += 1\n\t\t\t\tlineIndex = int(k.split(openTag)[1].split('\">')[0])\n\n\t\t\tif counter >= i and k.find(closedTag) > -1:\n\t\t\t\tbreak\n\n\t\t\tif counter == i:\n\n\t\t\t\t# Note/pitch command:\n\t\t\t\tif tagHasValue(k, 'Note'):\n\t\t\t\t\tnote = getValueFromTag(k, 'Note', 1)\n\t\t\t\t\titem[0] = note-12\n\n\t\t\t\t\t# Force values\n\t\t\t\t\titem[1] = 90.0 \t#--> Default volume\n\n\t\t\t\t# Instrument/sample command:\n\t\t\t\telif tagHasValue(k, 'Instrument'):\n\t\t\t\t\tinst = getValueFromTag(k, 'Instrument', 2)\n\t\t\t\t\titem[3] = inst\n\t\t\t\t\t#item[8] = isLooping(inst)\n\n\t\t\t\t# Volume/amplitude/velocity command:\n\t\t\t\telif tagHasValue(k, 'Volume'):\n\t\t\t\t\tvol = getValueFromTag(k, 'Volume', 2)\n\n\t\t\t\t\tif vol <= 127: # Exclude mute command\n\t\t\t\t\t\tvolDB = midiToDB(vol)\n\t\t\t\t\t\titem[1] = str(volDB)\n\t\t\t\t\telse: # Rewrite mute command\n\t\t\t\t\t\titem[0] = 0\n\t\t\t\t\t\titem[1] = 0\n\t\t\t\t\t\titem[3] = 32\n\n\t\t\t\t# Tags from FX column:\n\t\t\t\telif tagHasValue(k, 'Value'):\n\t\t\t\t\tfxValue = getValueFromTag(k, 'Value')\n\n\t\t\t\telif tagHasValue(k, 'Number'):\n\t\t\t\t\tfxNumber = getValueFromTag(k, 'Number')\n\n\t\t\t\telif fxNumber in patternList:\t\t#---> Get the special pattern change command\n\n\t\t\t\t\tif fxNumber == '01':\n\t\t\t\t\t\tgoTo = 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tgoTo = int(fxNumber) * 64 + int(fxValue)\n\n\t\t\t\t\titem[7] = str(goTo)\n\n\t\t\t\tif tagHasValue(k, 'Note') or tagHasValue(k, 'Instrument'):\n\n\t\t\t\t\titem[2] = shiftSampleDuration(note, inst, 0)\n\t\t\t\t\titem[4] = shiftSampleDuration(note, inst, 1)\n\t\t\t\t\titem[5] = 0\n\t\t\t\t\titem[6] = 0\n\n\t\tauxList[lineIndex] = item\n\n\t#------------------------------//------------------------------\n\t#---------------------store data structure---------------------\n\n\tsongData[pattern][track].clear()\n\tsongData[pattern][track] = dict(songData[pattern][track])\n\n\tsongData[pattern][track] = auxList\n\n\tdel auxList\n\tdel thisList\n\n\t#------------------------------//------------------------------\n\ndef getTempo(thisList=songFile):\n\n\t# Get BPM value\n\tbpm = getValueFromTag(thisList[3], 'BeatsPerMin', 3)\n\ttempo = round((60000/bpm)/4, 2)\t\t#--> Convert BPM to milliseconds\n\n\treturn str(tempo)\n\ndef getInstruments(module=zip):\n\n\tinstruments = []\n\tcounter = -1\n\t\n\tfor i in module.namelist():\n\t\tcounter += 1\n\n\t\tif i.startswith('SampleData'):\n\n\t\t\tinstruments.append(str(counter)+', read -resize sound/sample'+str(counter)+'.wav sample'+str(counter)+';')\n\t\t\tmodule.extract(i, '.')\n\t\t\t\n\tmodule.close()\n\t\n\tcounter = 0\n\t\n\tif not os.path.exists('../Player/sound'):\n\t\tos.makedirs('../Player/sound')\n\n\tfor directory in os.listdir('SampleData'):\n\t\tcounter += 1\n\n\t\tpath = 'SampleData/' + directory\n\n\t\t#Create samples folder\n\t\tfor file in os.listdir(path):\n\t\t\tos.rename(path + '/' + file, '../Player/sound/sample' + str(counter) + '.wav')\n\n\t#Delete the old folder\n\tshutil.rmtree('SampleData', ignore_errors=True)\n\t\n\treturn instruments\n\ndef getTotalLines(thisList=songFile, totalPatterns=0): \n\n\topenTag = '<Pattern>'\n\tclosedTag = '</Pattern>'\n\n\tfor tag in thisList:\n\n\t\tif tag.find(openTag) > -1:\n\n\t\t\ttotalPatterns += 1\n\n\tif totalPatterns >= 2:\n\t\ttotalPatterns //= 2\n\t\treturn str(totalPatterns*64)\n\ndef getPatternIds():\n\n\tpatterns = [1]\n\ttotalLines = getTotalLines()\n\n\tfor i in range(1, int(totalLines)):\n\n\t\tif i % 64 == 0:\n\n\t\t\tpatterns.append(i+1)\n\n\treturn patterns\n\ndef getSongData():\n\n\treturn songData\n\n\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":9667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"427356828","text":"import torch\nfrom torch import nn, optim\nfrom torchvision import transforms, models, utils\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader, ConcatDataset\nimport glob\nfrom tqdm import tqdm\nimport numpy as np\nimport cv2\nimport time\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport albumentations as A\n\nWIDTH = 400\nHEIGHT = 225\n\n# Model\ndeeplab = models.segmentation.deeplabv3_resnet50(pretrained=False, progress=True, num_classes=2)\nclass HandSegModel(nn.Module):\n def __init__(self):\n super(HandSegModel,self).__init__()\n self.dl = deeplab\n \n def forward(self, x):\n y = self.dl(x)['out']\n return y\n\n# Dataset\nclass SegDataset(Dataset): \n def __init__(self, parentDir, imageDir, maskDir, transform=None, aug = False):\n self.imageList = glob.glob(parentDir+'/'+imageDir+'/*')\n self.imageList.sort()\n self.maskList = glob.glob(parentDir+'/'+maskDir+'/*')\n self.maskList.sort()\n self.transform = transform\n self.aug = aug\n\n def __getitem__(self, index):\n image_resize = transforms.Resize((WIDTH,HEIGHT), 2)\n to_tensor = transforms.ToTensor()\n to_one_channel = transforms.Grayscale(num_output_channels=1)\n\n # X = Image.open(self.imageList[index]).convert('RGB')\n X = cv2.imread(self.imageList[index], cv2.IMREAD_COLOR)\n X = cv2.cvtColor(X, cv2.COLOR_BGR2RGB)\n\n # yimg = Image.open(self.maskList[index]).convert('L')\n yimg = cv2.imread(self.maskList[index], cv2.IMREAD_COLOR)\n yimg = cv2.cvtColor(yimg, cv2.COLOR_BGR2RGB)\n\n if self.aug and self.transform:\n transformed = self.transform(image=X, mask=yimg)\n X = to_tensor(image_resize(Image.fromarray(transformed['image'])))\n yimg = to_one_channel(Image.fromarray(transformed['mask']))\n\n elif self.transform:\n X = Image.fromarray(X)\n X = self.transform(X)\n yimg = to_one_channel(Image.fromarray(yimg))\n\n y1 = to_tensor(image_resize(yimg))\n y1 = y1.type(torch.BoolTensor)\n y2 = torch.bitwise_not(y1)\n y = torch.cat([y2, y1], dim=0)\n \n return X, y\n \n def __len__(self):\n return len(self.imageList)\n\ndef dataset_imshow(imageList, maskList):\n grid = image_grid(imageList, maskList)\n np_img = grid.permute(1,2,0).numpy()\n print(np_img.shape)\n plt.imshow(np_img)\n plt.show()\n\ndef image_grid(imageList, maskList, num_image = 25):\n to_tensor = transforms.Compose([transforms.ToTensor()])\n\n transform = A.Compose([\n A.HorizontalFlip(p=0.5),\n A.VerticalFlip(p=0.5),\n A.ShiftScaleRotate(border_mode=cv2.BORDER_CONSTANT, \n rotate_limit=(10, 30),\n p=0.5)\n ], p=1)\n\n image_list = []\n mask_list = []\n for i in range(num_image):\n img = cv2.imread(imageList[i], cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n mask = cv2.imread(maskList[i], cv2.IMREAD_COLOR)\n mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)\n\n transformed = transform(image=img, mask=mask)\n\n t_image = to_tensor(transformed['image'])\n t_mask = to_tensor(transformed['mask'])\n\n image_list.append(t_image)\n mask_list.append(t_mask)\n \n concat = image_list + mask_list\n\n grid = utils.make_grid(concat, nrow=5, padding=3)\n return grid\n \ndef Data_preprocess(image_folder, preprocess, aug_times = 0):\n tempDataset = []\n for i in image_folder:\n nor_dataset = SegDataset(i,'RAW', 'MASK', preprocess)\n\n # plot the image and mask\n # dataset_imshow(nor_dataset.imageList, nor_dataset.maskList)\n\n tempDataset.append(nor_dataset)\n print(i)\n print(\"# of Normal data\", len(nor_dataset))\n\n for j in range(aug_times):\n augmentation = A.Compose([\n A.HorizontalFlip(p=0.5),\n A.VerticalFlip(p=0.5),\n A.ShiftScaleRotate( border_mode=cv2.BORDER_CONSTANT, \n rotate_limit=(5, 25),\n p=0.5)\n ], p=1)\n aug_dataset = SegDataset(i,'RAW', 'MASK', augmentation, aug=True)\n tempDataset.append(aug_dataset)\n print(\"# of Augmented data\",len(aug_dataset))\n\n mergeDataset = ConcatDataset(tempDataset)\n print(\"# of all data\", len(mergeDataset))\n return mergeDataset\n\npreprocess = transforms.Compose([transforms.Resize((WIDTH,HEIGHT), 2),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n\n'''\naugmentation = transforms.Compose([ transforms.Resize((WIDTH,HEIGHT), 2),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n transforms.ColorJitter(hue=.05, saturation=.05),\n transforms.RandomHorizontalFlip(),\n transforms.RandomRotation(20, resample=Image.BILINEAR)\n ])\n'''\n\nimage_folder = {'ALL_HAND_DATASET/EGO/HAND_DATASET', # egohand_dataset\n 'ALL_HAND_DATASET/EYTH/HAND_DATASET', # eyth_dataset\n 'ALL_HAND_DATASET/HOF/HAND_DATASET', # hof_dataset\n 'ALL_HAND_DATASET/SELF/HAND_DATASET'}\n\nmergeDataset = Data_preprocess(image_folder, preprocess, aug_times = 0)\n\n# Split the dataset into two: training and validation\n# TTR: Train Test Ratio\ndef trainTestSplit(dataset, TTR):\n trainDataset = torch.utils.data.Subset(dataset, range(0, int(TTR * len(dataset))))\n valDataset = torch.utils.data.Subset(dataset, range(int(TTR*len(dataset)), len(dataset)))\n return trainDataset, valDataset\n \nbatchSize = 2\ntrainDataset, valDataset = trainTestSplit(mergeDataset, 0.8)\ntrainLoader = DataLoader(trainDataset, batch_size = batchSize, shuffle=True, drop_last=True)\nvalLoader = DataLoader(valDataset, batch_size = batchSize, shuffle=True, drop_last=True)\n\nprint(\"training dataset no:\", len(trainLoader.dataset))\nprint(\"validation dataset no:\", len(valLoader.dataset))\n\n# Performance\n# Mean Intersection over Union, meanIOU\ndef meanIOU(target, predicted):\n if target.shape != predicted.shape:\n print(\"target has dimension\", target.shape, \", predicted values have shape\", predicted.shape)\n return\n \n if target.dim() != 4:\n print(\"target has dim\", target.dim(), \", Must be 4.\")\n return\n \n iousum = 0\n for i in range(target.shape[0]):\n target_arr = target[i, :, :, :].clone().detach().cpu().numpy().argmax(0)\n predicted_arr = predicted[i, :, :, :].clone().detach().cpu().numpy().argmax(0)\n \n intersection = np.logical_and(target_arr, predicted_arr).sum()\n union = np.logical_or(target_arr, predicted_arr).sum()\n if union == 0:\n iou_score = 0\n else :\n iou_score = intersection / union\n iousum += iou_score\n \n miou = iousum/target.shape[0]\n return miou\n\n# Pixel accuracy\ndef pixelAcc(target, predicted): \n if target.shape != predicted.shape:\n print(\"target has dimension\", target.shape, \", predicted values have shape\", predicted.shape)\n return\n \n if target.dim() != 4:\n print(\"target has dim\", target.dim(), \", Must be 4.\")\n return\n \n accsum=0\n for i in range(target.shape[0]):\n target_arr = target[i, :, :, :].clone().detach().cpu().numpy().argmax(0)\n predicted_arr = predicted[i, :, :, :].clone().detach().cpu().numpy().argmax(0)\n \n same = (target_arr == predicted_arr).sum()\n a, b = target_arr.shape\n total = a*b\n accsum += same/total\n \n pixelAccuracy = accsum/target.shape[0] \n return pixelAccuracy\n\n# Training\ndef training_loop(n_epochs, optimizer, lr_scheduler, model, loss_fn, train_loader, val_loader, lastCkptPath = None):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n tr_loss_arr = []\n val_loss_arr = []\n meanioutrain = []\n pixelacctrain = []\n meanioutest = []\n pixelacctest = []\n prevEpoch = 0\n\n if lastCkptPath != None :\n checkpoint = torch.load(lastCkptPath)\n prevEpoch = checkpoint['epoch']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n for state in optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(device)\n tr_loss_arr = checkpoint['Training Loss']\n val_loss_arr = checkpoint['Validation Loss']\n meanioutrain = checkpoint['MeanIOU train']\n pixelacctrain = checkpoint['PixelAcc train']\n meanioutest = checkpoint['MeanIOU test']\n pixelacctest = checkpoint['PixelAcc test']\n print(\"loaded model, \", checkpoint['description'], \"at epoch\", prevEpoch)\n \n model.to(device)\n sum_time = 0\n\n for epoch in range(0, n_epochs):\n train_loss = 0.0\n pixelacc = 0\n meaniou = 0\n \n pbar = tqdm(train_loader, total = len(train_loader))\n for X, y in pbar:\n torch.cuda.empty_cache()\n model.train()\n X = X.to(device).float()\n y = y.to(device).float()\n ypred = model(X)\n loss = loss_fn(ypred, y)\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n tr_loss_arr.append(loss.item())\n meanioutrain.append(meanIOU(y, ypred))\n pixelacctrain.append(pixelAcc(y, ypred))\n pbar.set_postfix({'Epoch':epoch+1+prevEpoch, \n 'Training Loss': np.mean(tr_loss_arr),\n 'Mean IOU': np.mean(meanioutrain),\n 'Pixel Acc': np.mean(pixelacctrain)\n })\n \n with torch.no_grad():\n val_loss = 0\n pbar = tqdm(val_loader, total = len(val_loader))\n for X, y in pbar:\n torch.cuda.empty_cache()\n X = X.to(device).float()\n y = y.to(device).float()\n model.eval()\n ypred = model(X)\n \n val_loss_arr.append(loss_fn(ypred, y).item())\n pixelacctest.append(pixelAcc(y, ypred))\n meanioutest.append(meanIOU(y, ypred))\n \n pbar.set_postfix({'Epoch':epoch+1+prevEpoch, \n 'Validation Loss': np.mean(val_loss_arr),\n 'Mean IOU': np.mean(meanioutest),\n 'Pixel Acc': np.mean(pixelacctest)\n })\n \n checkpoint = {\n 'epoch':epoch+1+prevEpoch,\n 'description':\"add your description\",\n 'state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'Training Loss': tr_loss_arr,\n 'Validation Loss':val_loss_arr,\n 'MeanIOU train':meanioutrain, \n 'PixelAcc train':pixelacctrain, \n 'MeanIOU test':meanioutest, \n 'PixelAcc test':pixelacctest\n }\n torch.save(checkpoint, 'checkpoints/handseg_aug2_00005_5_4iter_'+str(epoch+1+prevEpoch)+'.pt')\n lr_scheduler.step()\n \n return tr_loss_arr, val_loss_arr, meanioutrain, pixelacctrain, meanioutest, pixelacctest\n\nmodel = HandSegModel()\n\noptimizer = optim.Adam(model.parameters(), lr=0.00005)\nloss_fn = nn.BCEWithLogitsLoss ()\nlr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer=optimizer, gamma=0.5)\n\nretval = training_loop(4, \n optimizer, \n lr_scheduler, \n model, \n loss_fn, \n trainLoader, \n valLoader, \n )\n\nprint(\"finish training\")\n","sub_path":"Hand segmentation/Other_image_size/model_training_400_225_withDataAug.py","file_name":"model_training_400_225_withDataAug.py","file_ext":"py","file_size_in_byte":12290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"217655503","text":"#!/usr/bin/env python\n\nimport subprocess\nimport threading\nimport signal\nimport time\nimport os\n\n\nclass Deadline(threading.Thread):\n\n def __init__(self, timeout, callback):\n super().__init__(daemon=True)\n self.__timeout = timeout\n self.__callback = callback\n self.__cancelled = threading.Event()\n\n def run(self) -> None:\n deadline = time.monotonic() + self.__timeout\n while not self.__cancelled.wait(deadline - time.monotonic()):\n if not self.__cancelled.is_set() and deadline <= time.monotonic():\n return self.__callback()\n\n def cancel(self) -> None:\n self.__cancelled.set()\n self.join()\n\n\ndef execute(command, timeout=60) -> None:\n try:\n p = subprocess.Popen(\n command,\n shell=False,\n stdin=None,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n close_fds=True\n )\n\n def kill() -> None:\n for sig in [signal.SIGTERM, signal.SIGQUIT, signal.SIGKILL, signal.SIGKILL]:\n if p.poll():\n break\n try:\n os.kill(p.pid, sig)\n except OSError:\n break\n\n deadline = Deadline(timeout, callback=kill)\n deadline.start()\n (result, error) = p.communicate()\n deadline.cancel()\n\n result = result.decode('utf-8').strip() if result else None\n error = error.decode('utf-8').strip() if error else None\n code = 1 if error else p.returncode\n\n return (code, result, error)\n except subprocess.CalledProcessError:\n return (-1, None, None)\n","sub_path":"bbtest/helpers/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"98974045","text":"import logging\nimport os\n\n\ndef jsw_get_log(dir_name):\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n log_path = os.path.dirname(os.getcwd()) + \"/\" + dir_name + \"/Logs/\"\n log_name = log_path + \"/log\" + '.log'\n logfile = log_name\n file_handler = logging.FileHandler(logfile) # 输入到文件\n file_handler.setLevel(logging.INFO)\n\n formatter = logging.Formatter(\"%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s:\"\n \"%(message)s\")\n\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n\n return logger\n","sub_path":"jsw_get_log.py","file_name":"jsw_get_log.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"50578365","text":"import warnings\nfrom functools import partial\nfrom operator import attrgetter\n\nimport numpy as np\nimport pytest\n\nfrom regionmask import Regions, defined_regions\n\noutl1 = ((0, 0), (0, 1), (1, 1.0), (1, 0))\noutl2 = ((0, 1), (0, 2), (1, 2.0), (1, 1))\n# no gridpoint in outl3\noutl3 = ((0, 2), (0, 3), (1, 3.0), (1, 2))\n\ndummy_outlines = [outl1, outl2, outl3]\ndummy_region = Regions(dummy_outlines)\ndummy_outlines_poly = dummy_region.polygons\n\ndummy_lon = [0.5, 1.5]\ndummy_lat = [0.5, 1.5]\ndummy_ll_dict = dict(lon=dummy_lon, lat=dummy_lat)\n\n# in this example the result looks:\n# | a fill |\n# | b fill |\n\n\ndef expected_mask_2D(a=0, b=1, fill=np.NaN):\n return np.array([[a, fill], [b, fill]])\n\n\ndef expected_mask_3D(drop):\n\n a = [[True, False], [False, False]]\n b = [[False, False], [True, False]]\n c = [[False, False], [False, False]]\n\n if drop:\n return np.array([a, b])\n return np.array([a, b, c])\n\n\nREGIONS = {\n \"ar6.all\": 58,\n \"ar6.land\": 46,\n \"ar6.ocean\": 15,\n \"giorgi\": 21,\n \"srex\": 26,\n}\n\nREGIONS_DEPRECATED = {\n \"_ar6_pre_revisions.all\": 55,\n \"_ar6_pre_revisions.land\": 43,\n \"_ar6_pre_revisions.ocean\": 12,\n \"_ar6_pre_revisions.separate_pacific\": 58,\n}\n\nREGIONS_REQUIRING_CARTOPY = {\n \"natural_earth.countries_110\": 177,\n \"natural_earth.countries_50\": 241,\n \"natural_earth.us_states_50\": 51,\n \"natural_earth.us_states_10\": 51,\n \"natural_earth.land_110\": 1,\n \"natural_earth.land_50\": 1,\n \"natural_earth.land_10\": 1,\n \"natural_earth.ocean_basins_50\": 119,\n}\n\n\ndef get_naturalearth_region_or_skip(monkeypatch, region_name):\n\n from socket import timeout\n from urllib.request import URLError, urlopen\n\n import cartopy\n\n # add a timeout to cartopy.io.urlopen else it can run indefinitely\n monkeypatch.setattr(cartopy.io, \"urlopen\", partial(urlopen, timeout=5))\n\n # natural earth data has moved to amazon, older version of cartopy still have the\n # old url\n # https://github.com/SciTools/cartopy/pull/1833\n # https://github.com/nvkelso/natural-earth-vector/issues/445\n # remove again once the minimum cartopy version is v0.19\n\n _NE_URL_TEMPLATE = (\n \"https://naturalearth.s3.amazonaws.com/\"\n \"{resolution}_{category}/ne_{resolution}_{name}.zip\"\n )\n\n monkeypatch.setattr(\n cartopy.io.shapereader.NEShpDownloader, \"_NE_URL_TEMPLATE\", _NE_URL_TEMPLATE\n )\n\n try:\n region = attrgetter(region_name)(defined_regions)\n except URLError as e:\n if isinstance(e.reason, timeout):\n warnings.warn(\"naturalearth donwload timeout - test not run!\")\n pytest.skip()\n else:\n raise\n\n return region\n","sub_path":"regionmask/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"350971204","text":"## 랜덤하게 1~100까지의 숫자 10개를 배열(=list)에 저장하고, 그 합계를 출력\r\nimport random # using ,#include\r\n\r\n## 함수 선언\r\n\r\n## 전역 변수 선언\r\nnumlist = [] # 빈 배열\r\nhap = 0\r\n\r\n## 메인 코드\r\nif __name__ == '__main__' : ## void main\r\n\r\n for i in range (10) :\r\n num = random.randint(1, 100)\r\n numlist.append(num)\r\n\r\n print(numlist)\r\n\r\n hap = sum(numlist)\r\n\r\n print(hap)","sub_path":"Day1_02 반복문1.py","file_name":"Day1_02 반복문1.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"499699242","text":"import random\nimport sys\n\n\n# pass functions as arguments\ndef results(guess_func, random_number_func):\n guess_counter = 0\n random_num = random_number_func()\n guess = 0\n\n while guess != random_num:\n\n if guess_counter < 1:\n guess = guess_func('The computer has generated a number, Please guess it : ')\n else:\n guess = guess_func('Try guessing the number again! ')\n\n if guess == 'exit':\n sys.exit(\"Thank you for playing. See you again\")\n\n guess = int(guess)\n guess_counter += 1\n\n if guess == random_num:\n print('Congratulations, You guessed it right after %d attempts.' % guess_counter)\n elif guess > random_num:\n print('Your guess is too high! Please try again.')\n else:\n print('Your guess is too low! Please try again.')\n\n\ndef guesess(guesString):\n userGuess = input(guesString)\n return userGuess\n\n\ndef rand_num():\n random_number = random.randint(1, 9)\n print(random_number)\n return random_number\n\n\nresults(guesess, rand_num)\n","sub_path":"009_guessing_game.py","file_name":"009_guessing_game.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"256316274","text":"\"\"\"\nWrite a function that takes a list comprised of other lists of integers \nand returns the sum of all numbers that appear in two or more lists in the input\nlist. Now that might have sounded confusing, it isn't:\n\n\"\"\"\nimport unittest\n\ndef repeat_sum(list_of_lists):\n\t\n\tif len(list_of_lists)<2:\n\t\treturn 0\n\n\tlist_sets = [set(l) for l in list_of_lists]\n\trepeats = set()\n\tfor i in range(len(list_sets)-1):\n\t\trepeats.update(list_sets[i].intersection(list_sets[i+1]))\n\tif len(list_sets) > 2:\n\t\trepeats.update(list_sets[0].intersection(list_sets[-1]))\n\treturn sum(repeats)\n\nclass TestPrintRepeatSum(unittest.TestCase):\n def test_base_case(self):\n input_list = [[1, 2, 3],[2, 8, 9],[7, 123, 8]]\n\t\t# sum of [2, 8]\n self.assertEqual(repeat_sum(input_list), 10)\n def test_no_repeat(self):\n input_list = [[1], [2], [3, 4, 4, 4], [123456789]]\n # sum of []\n self.assertEqual(repeat_sum(input_list), 0)\n def test_multi_repeat(self):\n input_list = [[1, 8, 8], [8, 8, 8], [8, 8, 8, 1]]\n # sum of [1,8]\n self.assertEqual(repeat_sum(input_list), 9)\n def test_single_list(self):\n input_list = [[1]]\n # sum of []\n self.assertEqual(repeat_sum(input_list), 0)\n\nif __name__ == \"__main__\":\n\n unittest.main()","sub_path":"cw/cw_7_sumRepeats.py","file_name":"cw_7_sumRepeats.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"517564826","text":"\"\"\"\nImplement a function that checks if a string has correct brace pairs(i.e. (, {, [) .\n Use your Stack ADT.\n If the source code has correct pairs, print ‘yes’.\n If the function find a wrong brace, print ‘no’.\n You have to check all kinds of brace ‘( )’, ‘{ }’, ‘[ ]’.\n Input : a single line of characters.\n\"\"\"\n\nimport unittest\n\nfrom .stack import MyStack as Stack\n\nbraces = {\n '(': ')',\n '{': '}',\n '[': ']'\n}\n\n\ndef check_brace(input_string):\n stack = Stack()\n for char in input_string:\n if char in braces.keys():\n stack.push(char)\n elif char in braces.values():\n if stack.count > 0 and char == braces[stack.top.data]:\n stack.pop()\n elif stack.count == 0 or char != braces[stack.top.data]:\n return 'no'\n\n if stack.count == 0:\n return 'yes'\n else:\n return 'no'\n\n\nclass BraceCheckTestCase(unittest.TestCase):\n\n def test_check_brace(self):\n input_string = '(abc)'\n assert check_brace(input_string) == 'yes'\n\n def test_check_brace_wrong(self):\n input_string = '((abc)'\n assert check_brace(input_string) == 'no'\n\n input_string = ')(abc)'\n assert check_brace(input_string) == 'no'\n\n def test_check_multiple_brace(self):\n assert check_brace('So when I die (the [first] I will see in (heaven) is a score list).') == 'yes'\n assert check_brace('[ first in ] ( first out ).') == 'yes'\n assert check_brace('([ (([( [ ] ) ( ) (( ))] )) ]).') == 'yes'\n\n assert check_brace('Half Moon tonight (At least it is better than no Moon at all]).') == 'no'\n assert check_brace('A rope may form )( a trail in a maze.') == 'no'\n assert check_brace('Help( I[m being held prisoner in a fortune cookie factory)].') == 'no'\n assert check_brace('{](( )} (( ))] )) ]).') == 'no'\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"stack/brace_check.py","file_name":"brace_check.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"283147764","text":"__author__ = 'Richard Barrett. mail@rbarrett.me'\n__date__ = '1/16/14'\n__readme__ = 'A novel answer to the FizzBuzz problem found on simple programming tests'\n\nclass fizzbuzzulator:\n\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n def fizzBuzz(self):\n\n i = self.start\n while i < self.end + 1:\n if i % 3 == 0 and i % 5 == 0:\n print(str(i) + \" FizzBuzz!\")\n elif i % 3 == 0:\n print(str(i) + \" Fizz!\")\n elif i % 5 == 0:\n print(str(i) + \" Buzz!\")\n else:\n print(str(i) + \" Ain't got no Fizz OR Buzz!!!\")\n\n i = i = i + 1\n\nmyRange = fizzbuzzulator(1,100000)\nmyRange.fizzBuzz()\n\n","sub_path":"fizzbuzzulator.py","file_name":"fizzbuzzulator.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"520365029","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 07 12:23:15 2018\r\n\r\n@author: ALTZ100066\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\n\r\n\r\ndef sales_rep_exec(x):\r\n sale_rep_fav = ['abn', 'bud', 'est', 'bhl', 'hgh', 'bll', 'mgl', \r\n 'blr', 'ntd', 'bsf', 'rck', 'bsh', 'sta', 'ibh']\r\n if x in sale_rep_fav:\r\n p = 0.6\r\n else:\r\n p = 0.6 \r\n return np.random.choice([0, 1], size=1, p=[1-p, p])[0] \r\n\r\n\r\ndef next_month(x):\r\n if int(x)%100 == 12:\r\n return (int(x) + 89)\r\n else:\r\n return (int(x) + 1)\r\n\r\n\r\ndef ucb_bandit(num_occur, avg_occur, round_t, num_recomm_pm):\r\n return (avg_occur + 2*np.sqrt(num_recomm_pm*(np.log(round_t))/num_occur)) \r\n \r\n\r\ndef new_recommendation(recom_exec_df, action, reward, round_col):\r\n global round_t, num_recomm_pm\r\n \r\n # number of recommendation per month (k)\r\n num_recomm_pm = int(recom_exec_df[round_col].value_counts().mean()) - 1\r\n \r\n # ith month from starting of recommendation\r\n round_t = recom_exec_df[round_col].unique().size + 1\r\n \r\n # create UCB(Upper Confidence Bound) dataframe\r\n ucb_df = recom_exec_df.groupby(action)\\\r\n .agg({action:'size', reward:'mean'})\\\r\n .rename(columns={action:'num_occur',\r\n reward:'avg_occur'}).reset_index() \r\n \r\n ucb_df['ucb_index'] = ucb_df.apply(lambda x: ucb_bandit(x['num_occur'],\\\r\n x['avg_occur'], round_t,\\\r\n num_recomm_pm), axis=1)\r\n \r\n # get top k recommendation using UCB Index \r\n new_recomm = ucb_df.sort_values('ucb_index', ascending=False)\\\r\n .reset_index(drop=True).loc[:num_recomm_pm][[action]]\r\n\r\n return new_recomm\r\n \r\n \r\ndef long_to_wide(df, round_col, action, reward):\r\n df['temp'] = ['B%s' %i for i in range(1, (num_recomm_pm + 2))]*round_t\r\n df = df.pivot(index=round_col, columns='temp')[[action, reward]]\\\r\n .reset_index()\r\n df.columns= [round_col] + ['B%s' %i for i in range(1, (num_recomm_pm + 2))]\\\r\n + ['SB%s' %i for i in range(1, (num_recomm_pm + 2))]\r\n return df\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n filepath = r'D:\\suraj.jha\\RL\\Data\\Synthetic Data'\r\n \r\n action = 'brnd_cd'\r\n reward = 'sales_exec'\r\n round_col = 'cal_yr_mo_nbr'\r\n t = 60\r\n round_t = 0\r\n num_recomm_pm = 0\r\n \r\n # read raw data\r\n recom_exec_df = pd.read_csv(os.path.join(filepath, 'recomm_exec_data_v5.csv'))\r\n \r\n for _ in range(t):\r\n new_recomm = new_recommendation(recom_exec_df, action, reward, round_col) \r\n print(\"New Recommendation : {}\".format(new_recomm[action].tolist())) \r\n \r\n new_recomm[round_col] = next_month(recom_exec_df[round_col].max())\r\n \r\n new_recomm[reward] = new_recomm[action].apply(sales_rep_exec)\r\n \r\n recom_exec_df = recom_exec_df.append(new_recomm, ignore_index=True)\r\n \r\n final_df = long_to_wide(recom_exec_df, round_col, action, reward)\r\n final_df.to_csv(os.path.join(filepath, 'new_recommendations_v5.csv'), \r\n index=False)\r\n \r\n","sub_path":"RL/Iteration_1/Code/ucb_bandit_solution_v1.py","file_name":"ucb_bandit_solution_v1.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"357847504","text":"#!/usr/bin/env python3\n'''\nSolution for \"Add Two Numbers\"\n'''\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n current_val = l1.val + l2.val\n carry = current_val // 10\n current_val = current_val % 10\n head_node = ListNode(current_val)\n last_node = head_node\n l1 = l1.next\n l2 = l2.next\n while True:\n if l1 is None and l2 is None and carry == 0:\n break\n elif l1 is None and carry == 0:\n last_node.next = l2\n break\n elif l2 is None and carry == 0:\n last_node.next = l1\n break\n elif l1 is None and l2 is None:\n current_node = ListNode(carry)\n last_node.next = current_node\n last_node = current_node\n carry = 0\n elif l1 is None:\n current_val = l2.val + carry\n carry = current_val // 10\n current_val = current_val % 10\n current_node = ListNode(current_val)\n last_node.next = current_node\n last_node = current_node\n l2 = l2.next\n elif l2 is None:\n current_val = l1.val + carry\n carry = current_val // 10\n current_val = current_val % 10\n current_node = ListNode(current_val)\n last_node.next = current_node\n last_node = current_node\n l1 = l1.next\n else:\n current_val = l1.val + l2.val + carry\n carry = current_val // 10\n current_val = current_val % 10\n current_node = ListNode(current_val)\n last_node.next = current_node\n last_node = current_node\n l1 = l1.next\n l2 = l2.next\n return head_node\n\nif __name__ == \"__main__\":\n def create_ListNode_From_List(mlist):\n head_node = ListNode(mlist[0])\n last_node = head_node\n for x in mlist[1:]:\n current_node = ListNode(x) \n last_node.next = current_node\n last_node = current_node\n return head_node\n \n a = create_ListNode_From_List([2, 4, 3])\n b = create_ListNode_From_List([5, 6, 4])\n\n c = Solution().addTwoNumbers(a, b)\n while c:\n print(c.val)\n c = c.next","sub_path":"2/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"647980795","text":"# Задача: открыть файл, и посчитать сколько вхождений какой страны есть, собрать данные в виде словаря.\n\n\n\ndef user_location():\n country = {}\n with open('/home/moonz/PycharmProjects/BeautifulSoup/user_locatin.txt', 'r') as users:\n\n data = users.readlines()\n for i in data:\n loc = i.replace('\\n', '')\n if loc not in country.keys():\n country.update({loc:1})\n else:\n num = int(country.get(loc))\n num += 1\n country.update({loc:num})\n\n return country\n\n\ndata = user_location()\nsort = sorted(data, key=data.get, reverse=True) # Сортируем по значению.\n\n\n# Подготоив данные для графика.\ndata_names = []\ndata_values = []\n\nfor i in sort:\n data_names.append(i)\n data_values.append(data.get(i))\n\nprint(data_names)\nprint(data_values)","sub_path":"user_sort.py","file_name":"user_sort.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"514841580","text":"from django.views.generic import View\nfrom django.shortcuts import render, get_object_or_404\nfrom tracking.models import Track\nfrom django.http import HttpResponse, Http404\nfrom django.core.exceptions import ObjectDoesNotExist\nimport json\n\nclass TrackingIndexView(View):\n template_name = \"tracking/tracking_index.html\"\n\n def get(self, request):\n context = {'Track': Track.objects.all()}\n return render(request, self.template_name, context)\n\nclass TrackingTrackView(View):\n template_name = \"tracking/tracking_single.html\"\n\n def get(self, request, tr_name):\n try:\n tr = Track.objects.get(Name=tr_name)\n context = {'tr': tr}\n return render(request, self.template_name, context)\n except ObjectDoesNotExist:\n raise Http404\n\n def post(self, request, tr_name):\n response_data = {}\n try:\n tr = Track.objects.get(Name=tr_name)\n tr.Clicks += 1\n tr.save()\n\n response_data[tr.Name] = tr.Clicks\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n except ObjectDoesNotExist:\n pass\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n \nclass RefreshTrackView(View):\n\n def _resolve_post_(self, request, tr_name):\n response_data = {}\n try:\n if tr_name is None:\n trs = Track.objects.all()\n for tr in trs:\n response_data[tr.Name] = tr.Clicks\n else:\n tr = Track.objects.get(Name=tr_name)\n response_data[tr.Name] = tr.Clicks\n except ObjectDoesNotExist:\n pass\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n\n def post(self, request, tr_name):\n return self._resolve_post_(request, tr_name)\n\n def get(self, request, tr_name):\n return self._resolve_post_(request, tr_name)","sub_path":"tracking/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"481999306","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport json\nimport random\nimport re\nimport matplotlib.pyplot as plt\nimport functools\n\nimport logging\nimport requests\nfrom multiprocessing import Pool, Manager\nimport time\nimport myPymysql\nimport sys\n\nlogger = logging.getLogger('maoyan')\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n\n# 文件日志\nfile_handler = logging.FileHandler('maoyan.log')\nfile_handler.setFormatter(formatter)\n\n# 终端日志\nconsole_handler = logging.StreamHandler(sys.stdout)\nconsole_handler.setFormatter(formatter)\n\nlogger.setLevel(logging.DEBUG)\n\nlogger.addHandler(file_handler)\nlogger.addHandler(console_handler)\n\n\nFILENAME = './user_agent_list'\n\n\ndef listUA(filename=FILENAME):\n with open(filename, 'r') as fr:\n data = fr.read()\n ua_list = data.split('\\n')\n return ua_list\n\n\ndef get_one_page(url, ua_list):\n ua_headers = {'User-Agent': random.choice(ua_list)}\n response = requests.get(url, headers=ua_headers)\n if response.status_code == 200:\n return response.text\n return None\n\n\ndef parse_one_page(html):\n pattern = re.compile('<p class=\"name\"[\\s\\S]*?title=\"([\\s\\S]*?)\"[\\s\\S]*?<p class=\"star\">([\\s\\S]*?)</p>\\\\n<p class=\"releasetime\">([\\s\\S]*?)</p>')\n items = re.findall(pattern, html)\n for item in items:\n # print(item[0])\n yield {\n 'title': item[0].strip(),\n 'actor': item[1].strip(),\n 'time': item[2].strip(),\n }\n\n\ndef write_to_file(item):\n with open('maoyanTop100.text', 'a', encoding='utf-8') as f:\n f.write(json.dumps(item, ensure_ascii=False) + '\\n')\n\n\ndef write_to_sql(item):\n dbhelper = myPymysql.DBHelper()\n title = item['title']\n actor = item['actor']\n time = item['time']\n params = (title, actor, time)\n sql = 'insert into db_maoyan.maoyan(title, actor, time) VALUES (%s, %s, %s);'\n result = dbhelper.execute(sql, params)\n if result == True:\n print('Insert OK')\n else:\n logger.error('execut:' + sql)\n logger.error('execut:' + params)\n\n\ndef CrawlPage(lock, offset):\n url = 'http://maoyan.com/board/4?offset=' + str(offset)\n ua_list = listUA()\n html = get_one_page(url, ua_list)\n for item in parse_one_page(html):\n lock.acquire()\n # write_to_file(item)\n write_to_sql(item)\n lock.release()\n time.sleep(1)\n\n\ndef analysis():\n dbhelper = myPymysql.DBHelper()\n sql_t = 'SELECT COUNT(*) FROM db_maoyan.maoyan;'\n sqlAm = 'SELECT COUNT(*) FROM db_maoyan.maoyan where time like \"%美国%\";'\n sqlCh = 'SELECT COUNT(*) FROM db_maoyan.maoyan where time like \"%中国%\";'\n sqlJp = 'SELECT COUNT(*) FROM db_maoyan.maoyan where time like \"%日本%\";'\n total = dbhelper.fetchCount(sql_t)[0]\n Am = dbhelper.fetchCount(sqlAm)[0]\n Ch = dbhelper.fetchCount(sqlCh)[0]\n Jp = dbhelper.fetchCount(sqlJp)[0]\n Other = total - Am - Ch - Jp\n sizes = Am, Ch, Jp, Other\n labels = 'America', 'China', 'Japan', 'Others'\n colors = 'Blue', 'Red', 'Yellow', 'Green'\n plt.pie(sizes, labels=labels, colors=colors)\n plt.show()\n\n\nminPage = 0\nmaxPage = 100\nstep = 10\n\nif __name__ == '__main__':\n # manager = Manager()\n # lock = manager.Lock()\n # newCrawPage = functools.partial(CrawlPage, lock)\n #\n # pool = Pool()\n # pool.map(newCrawPage, [x*10 for x in range(10)])\n # pool.close()\n # pool.join()\n\n analysis()\n\n logger.removeHandler(file_handler)\n logger.removeHandler(console_handler)\n","sub_path":"Crawler/day07/class_in/maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"199239367","text":"from src.models import DBSession, User\n\ndef main():\n users = DBSession.query(User).filter(User.is_active == True).all()\n\n for user in users:\n user.init_permissions()\n DBSession.add(user)\n DBSession.commit()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Bots/var12bot-master/src/scripts/reset_permissions.py","file_name":"reset_permissions.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"486175069","text":"from dal import autocomplete\nfrom blog.models import Category, Tag, Post\nfrom django import forms\n\nclass PostAdminForm(forms.ModelForm):\n\n desc = forms.CharField(widget=forms.Textarea, label='摘要', required=False)\n category = forms.ModelChoiceField(\n queryset = Category.objects.all(),\n widget = autocomplete.ModelSelect2(url='category-autocomplete'), label='分类',\n )\n\n tag = forms.ModelMultipleChoiceField(\n queryset = Tag.objects.all(),\n widget = autocomplete.ModelSelect2Multiple(url='tag-autocomplete'), label='标签',\n )\n\n class Meta:\n model = Post\n fields = ('category', 'tag', 'title', 'desc', 'content', 'status')\n\n\nclass CategoryAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n if not self.request.user.is_authenticated():\n return Category.objects.none()\n\n qs = Category.objects.filter(owner=self.request.user)\n\n if self.q:\n qs = qs.filter(name__istartswith=self.q)\n return qs\n\nclass TagAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n if not self.request.user.is_authenticated():\n return Tag.objects.none()\n \n qs = Tag.objects.filter(owner=self.request.user)\n\n if self.q:\n qs = qs.filter(name__istartswith=self.q)\n return qs","sub_path":"typeidea/typeidea/autocomplete.py","file_name":"autocomplete.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"503221588","text":"import logging\nimport os\n\nimport click\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nfrom torch.utils.data import DataLoader, random_split\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch_unet.globals import *\nfrom torch_unet.tools.dataset import TrainingSet\nfrom torch_unet.unet import UNet\nfrom torch_unet.unet.train import train_model\n\n\ndef split_train_val(dataset, val_ratio, batch_size):\n n_val = int(len(dataset) * val_ratio)\n n_train = len(dataset) - n_val\n train_set, val_set = random_split(dataset, [n_train, n_val])\n train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=2, pin_memory=True)\n val_loader = DataLoader(val_set, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=True)\n return n_train, train_loader, n_val, val_loader\n\n\ndef get_model_dir(patch_size, step, depth, batch_size, lr, decay, padding, batch_norm,\n dropout, rotation, init_filters, leaky, balance, augmentation):\n name = f\"depth{depth}_BS{batch_size}_lr{lr}_PS{patch_size}_ST{step}_WF{init_filters}\"\n if padding:\n name += \"_padding\"\n if batch_norm:\n name += \"_batchnorm\"\n if rotation:\n name += \"_rot\"\n if decay > 0:\n name += f\"_decay\"\n if dropout > 0:\n name += f\"_dropout{dropout}\"\n if leaky:\n name += \"_leaky\"\n if balance:\n name += \"_balance\"\n if augmentation:\n name += \"_augmentation\"\n \n model_dir = os.path.join(MODELS_DIR, name)\n dir_checkpoint = os.path.join(model_dir, \"checkpoints/\")\n if not os.path.exists(dir_checkpoint):\n os.makedirs(dir_checkpoint, exist_ok=True)\n return dir_checkpoint, name\n\n\n@click.command()\n@click.option(\"--epochs\", default=50)\n@click.option(\"--lr\", default=0.001)\n@click.option(\"--decay\", is_flag=True)\n@click.option(\"--val-ratio\", default=0.2)\n@click.option(\"--batch-size\", default=1)\n@click.option(\"--patch-size\", default=400)\n@click.option(\"--step\", default=None)\n@click.option(\"--depth\", default=4)\n@click.option(\"--num-filters\", default=16)\n@click.option(\"--padding\", is_flag=True)\n@click.option(\"--batch-norm\", is_flag=True)\n@click.option(\"--dropout\", default=0.)\n@click.option(\"--leaky\", is_flag=True)\n@click.option(\"--rotations\", is_flag=True)\n@click.option(\"--balance\", is_flag=True)\n@click.option(\"--augmentation\", is_flag=True)\ndef train(epochs, lr, decay, val_ratio, batch_size, patch_size, step, depth, num_filters, padding, batch_norm, dropout,\n leaky, rotations, balance, augmentation):\n dir_checkpoint, name = get_model_dir(patch_size, step, depth, batch_size, lr, decay, padding, batch_norm, dropout,\n rotations, num_filters, leaky, balance, augmentation)\n \n dataset = TrainingSet(IMAGE_DIR, MASK_DIR, mask_threshold=MASK_THRESHOLD,\n rotation_angles=ROTATION_ANGLES if rotations else None, patch_size=patch_size,\n step=step if step is None else int(step), augmentation=augmentation)\n \n n_train, train_loader, n_val, val_loader = split_train_val(dataset, val_ratio, batch_size)\n \n writer = SummaryWriter(comment=name)\n \n net = UNet(n_channels=NUM_CHANNELS, n_classes=N_CLASSES, depth=depth, init_filters=num_filters, padding=padding,\n batch_norm=batch_norm, dropout=dropout, leaky=leaky)\n \n writer.add_graph(net, torch.rand(1, NUM_CHANNELS, patch_size, patch_size))\n optimizer = optim.Adam(net.parameters(), lr=lr)\n criterion = nn.BCEWithLogitsLoss()\n \n lr_scheduler = None\n if decay:\n lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=5, verbose=True)\n \n train_model(epochs, criterion, optimizer, lr_scheduler, net, train_loader, val_loader, dir_checkpoint, logger, n_train,\n n_val, batch_size, writer, val_ratio, balance)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n \n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n \n train()\n","sub_path":"projects/project2/project_road_segmentation/torch_unet/torch_unet/scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"291658575","text":"from flask import Flask, jsonify, request\n# from bson.json_util import dumps\nfrom flask_cors import CORS\nimport pandas as pd\nimport json\nimport numpy as np\nimport random\nfrom pandas.io.json import json_normalize\nimport xlrd\n\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/sendFilePath', methods=['POST'])\ndef sendFilePath():\n try:\n data = request.json\n data = data[\"path\"].split('fakepath\\\\')\n path = 'C:\\\\Users\\\\aravind.r\\\\Desktop\\\\' + data[1]\n train = pd.read_excel(path)\n print(train)\n r = train.shape[0]\n df = train.drop(train.loc[:, train.isnull().sum() > r / 2], axis=1)\n return jsonify({'input': train.to_json(orient='split'),'output1':df.to_json(orient='split')})\n\n except Exception as e:\n print(str(e))\n\n\n@app.route('/step2', methods=['POST'])\ndef step2():\n try:\n data = request.json\n df = pd.DataFrame.from_dict(json_normalize(data), orient='columns')\n r = df.shape[1]\n s = df.dropna(axis=0, how=None, thresh=r / 2, subset=None, inplace=False)\n return jsonify({\"output2\":s.to_json(orient='columns')})\n\n\n except Exception as e:\n print(str(e))\n\n\n@app.route('/step3', methods=['POST'])\ndef step3():\n try:\n data = (request.json)[\"name\"]\n path = 'C:\\\\Users\\\\aravind.r\\\\Desktop\\\\'+ data\n train = pd.read_excel(path)\n print(train)\n # data = request.json\n # df = pd.DataFrame.from_dict(json_normalize(data), orient='columns')\n # print(df)\n k = train._get_numeric_data()\n print(k)\n return jsonify({\"output3\":k.to_json(orient='split')})\n\n\n except Exception as e:\n print(str(e))\n\t\t\ndef fillmissing1( T, col_no, corr_col ):\n\n\tL1= T[ T.columns.tolist()[ col_no ] ].tolist()\n\tL1_= [ val for val in L1 if not np.isnan(val) ]\n\tL2= T[ T.columns.tolist()[ corr_col ] ].tolist()\n\tL2_= [ val for val in L2 if not np.isnan(val) ]\n\n\tL1_mean= 0\n\tfor i in range( len(L1_) ):\n\t\tL1_mean= L1_mean + (L1_[i]/len(L1_))\n\n\tL2_mean= 0\n\tfor i in range( len(L2_) ):\n\t\tL2_mean= L2_mean + (L2_[i]/len(L2_))\n\n\t#Linear regression:\n\tbeta_num= 0\n\tbeta_den= 0\n\tfor i in range( min( len(L2_), len(L1_) ) ):\n\t\tbeta_den= beta_den + (L2_[i%len(L2_)] - L2_mean)**2\n\t\tbeta_num= beta_num + (L2_[i%len(L2_)] - L2_mean)*(L1_[i%len(L1_)] - L1_mean)\n\t\n\tbeta= beta_num/beta_den\n\talpha= L1_mean - beta*L2_mean\n\n\tfor i in range( len( L1 ) ):\n\t\tif np.isnan(L1[i]):\n\t\t\tL1[i]= alpha + beta*L2[i%len(L2)]\n\t\n\treturn L1\n\n@app.route('/step4', methods=['POST'])\ndef step4():\n\tdata = (request.json)[\"name\"]\n\tpath = 'C:\\\\Users\\\\aravind.r\\\\Desktop\\\\'+ data\n\tprint(path)\n\tT = pd.read_excel(path)\n\tprint(T)\n\tcol_no = int((request.json)[\"colNum\"])\n\tcorr_col = int((request.json)[\"corNum\"])\n\tprint(col_no)\n\tprint(corr_col)\n\tR= []\n\tfor i in range( len(T.columns) ):\n\t\tR.append( T[ T.columns.tolist()[ i ] ].tolist() )\n\tR[col_no]= fillmissing1( T, col_no, corr_col )\n\tr= list(map(list, zip(*R)))\n\tdf= pd.DataFrame(r)\n\treturn jsonify({\"output4\":df.to_json(orient='split')})\n\t\ndef rem_out( L, z_score_thr ):\n\n\tL_mean= 0\n\tfor i in range( len(L) ):\n\t\tL_mean= L_mean + (L[i]/len(L))\n\n\tL_var= 0\n\tfor i in range( len(L) ):\n\t\tL_var= L_var + (( L[i] - L_mean )**2) / len(L)\n\n\tfor i in range( len(L) ):\n\t\tif (L[i] - L_mean)**2 > ( z_score_thr**2 )*L_var:\n\t\t\tL[i]= L_mean + random.randrange( 0, m.floor( z_score_thr*(L_var**0.5) ), 1 )\n\treturn L\n\n@app.route('/step5', methods=['POST'])\ndef step5():\n data = (request.json)[\"name\"]\n path = 'C:\\\\Users\\\\aravind.r\\\\Desktop\\\\'+ data\n T = pd.read_excel(path)\n col_no = int((request.json)[\"colNum\"])\n threshold = int((request.json)[\"thresh\"])\n R= []\n for i in range( len(T.columns) ):\n R.append( T[ T.columns.tolist()[ i ] ].tolist() )\n print( rem_out( R[col_no], threshold ) )\n R[col_no]= rem_out( R[col_no], threshold )\n r= list(map(list, zip(*R)))\n df= pd.DataFrame(r)\n return jsonify({\"output5\": df.to_json(orient='split')})\n\n# out_rem_rep( \"C:\\\\Users\\\\Sairam\\\\Desktop\\\\t4\", 2, 1 )\n\nif __name__ == '__main__':\n app.run(debug=True, port=9080)\n","sub_path":"python/flask_test.py","file_name":"flask_test.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"59384237","text":"# Create a function that takes a list as a parameter,\n# and returns a new list with all it's element value doubled.\n# It should raise an error if the parameter is not a list\n\ndef value_doubled(value_list):\n try:\n for i in range(len(value_list)):\n value_list[i] *= 2\n return value_list\n except TypeError:\n return 'Please give me a list'\n\nprint(value_doubled([5,10,15]))\nprint(value_doubled(5))\n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"479937853","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[31]:\n\n\nimport pandas as pd\n\n\n# In[33]:\n\n\n# have file names on hand\n# loan_risk.csv\n# loan_positions.csv\n\n\n# In[37]:\n\n\npwd\n\n\n# In[ ]:\n\n\n\n\n\n# In[38]:\n\n\n# read both csv files and create shortcut\n\n\n# In[39]:\n\n\ndata1 = pd.read_csv('/users/nickdevv/desktop/loan risk.csv')\ndata2 = pd.read_csv('/users/nickdevv/desktop/loan positions.csv')\n\n\n# In[ ]:\n\n\n\n\n\n# In[40]:\n\n\n# merge csv files together matching loan number column\n\n\n# In[41]:\n\n\noutput3 = pd.merge(data1, data2,\n on='LoanNumber',\n how='outer')\n\n\n# In[ ]:\n\n\n\n\n\n# In[42]:\n\n\n# 1. display merged csv file\n\n\n# In[43]:\n\n\nprint(output3)\n\n\n# In[ ]:\n\n\n\n\n\n# In[44]:\n\n\n# 2. replace missing data with average, or mean, in data set as requested\n# I used this method because the mean is considered to be the average of a given data set.\n\n\n# In[45]:\n\n\noutput3.fillna(output3.mean())\n\n\n# In[ ]:\n\n\n\n\n\n# In[46]:\n\n\n# creating shortcut for completed data\n\n\n# In[47]:\n\n\noutput4 = output3.fillna(output3.mean())\n\n\n# In[48]:\n\n\nprint(output4)\n\n\n# In[ ]:\n\n\n\n\n\n# In[49]:\n\n\nimport numpy as np\n\n\n# In[50]:\n\n\n# 3. creating random uniform variables between 0-1 under column named RV\n\n\n# In[51]:\n\n\noutput4['RV'] = np.random.uniform(0,1, len(output4))\n\n\n# In[19]:\n\n\nprint(output4)\n\n\n# In[ ]:\n\n\n\n\n\n# In[20]:\n\n\n# 3.5. add new \"Flag\" variable column and condition. If RV < PD = 1\n# this flagged loan may represent a more trustworthy borrower since their values are lower than the given, \n# or estimated, probability of default (PD).\n# the lower the PD, the more trustworthy the borrower which may make the borrower eligible for a lower \n# interest rate.\n\n\n# In[21]:\n\n\noutput4['Flag'] = np.where(\n output4['PD'] == output4['RV'], 0, np.where(\n output4['PD'] > output4['RV'], 1, 0)) \n\n\n# In[22]:\n\n\nprint(output4)\n\n\n# In[ ]:\n\n\n\n\n\n# In[23]:\n\n\n# 4. mulitplying Flag with LGD\n# this multiplied variable highlights the Loss Given Default (LGD) of the flagged loan, or the \n# value the bank is at risk of losing if the borrower defaults on his loan. \n\n\n# In[24]:\n\n\noutput4['LGDxFlag'] = output4.LGD * output4.Flag\n\n\n# In[25]:\n\n\nprint(output4)\n\n\n# In[ ]:\n\n\n\n\n\n# In[26]:\n\n\n# 5. adding the new variable in the last step across all loans, storing it under dataset1. \n# adding all the highlted LGD values would give you an estimate of the total the bank is at \n# risk of losing across all 11 loans.\n\n\n# In[27]:\n\n\ndataset1 = output4['LGDxFlag'].sum()\nprint(dataset1)\n\n\n# In[ ]:\n\n\n\n\n\n# In[28]:\n\n\n# 6. for loop that runs steps 3-5 10,000 times\n\n\n# In[52]:\n\n\nfor i in range(10000):\n output4['RV'] = np.random.uniform(0,1, len(output4))\n output4['Flag'] = np.where(\n output4['PD'] == output4['RV'], 0, np.where(\n output4['PD'] > output4['RV'], 1, 0)) \n output4['LGDxFlag'] = output4.LGD * output4.Flag\n total = output4['LGDxFlag'].sum()\n print(output4)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"BankUnited Code.py","file_name":"BankUnited Code.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"246283222","text":"import run as r\n\n\ndef main(array, label_index=None, n_components=None, copy=True, whiten=False, svd_solver='auto', tol=0.0,\n iterated_power='auto', random_state=None):\n return r.run(array=array,\n label_index=label_index,\n n_components=n_components,\n copy=copy,\n whiten=whiten,\n svd_solver=svd_solver,\n tol=tol,\n iterated_power=iterated_power,\n random_state=random_state)\n\n\nif __name__ == '__main__':\n import numpy as np\n import json\n array = np.loadtxt('D:\\\\123_2.csv', delimiter=',')\n y = array[:, -1]\n x = np.delete(array, -1, axis=1)\n\n x = x.tolist()\n y = y.tolist()\n array = array.tolist()\n print(main(array,-1,n_components=2))\n","sub_path":"feature_engineering/decomposing_signals/SparseCoder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"403581125","text":"#!/usr/bin/python3\n\n'''\nlista de nome vazia\nler nomes, adicionar na lista ate digitar sair\n'''\n\nlista = []\n\nwhile True:\n nome = input(\"digite um nome ou 'sair': \")\n if nome == 'sair':\n break\n lista.append(nome) \n\nprint(lista)","sub_path":"06_while3.py","file_name":"06_while3.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"531819771","text":"def clean_up(text, strip_chars=[], replace_extras={}):\n \"\"\"\n :type text str\n :type strip_chars list\n :type replace_extras dict\n\n *************************\n strip_chars: optional arg\n Accepts passed list of string objects to iter through.\n Each item, if found at beginning or end of string, will be\n gotten rid of. This is recursive.\n\n example:\n text input: ' , , , .,.,.,.,,,......test, \\t this\\n.is.a\\n.test...,,, , .'\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^------^^^^----^^-----^^-----^^^^^^^^^^^^^^^^^^\n strip_chars arg: [',', '.']\n\n output: 'test, this .is.a .test'\n ********************************\n\n ****************************\n replace_extras: optional arg\n Accepts passed dict of items to replace in the standard\n clean_up_items dict or append to it.\n\n example:\n text_input: ' this is one test\\n!\\n'\n ^--------^^^-----^^-^^\n replace_extras arg: {'\\n': '', 'one': '1'}\n\n output: 'this is 1 test!'\n *************************\n\n ***************************\n DEFAULT REPLACE ITEMS\n ---------------------\n These can be overridden and/or appended to using the replace_extras\n argument.\n\n <\\\\n line ending> - <space>\n <\\\\r line ending> - <space>\n <\\\\t tab> - <space>\n < double-space> - <space>\n <text-input> - <stripped>\n *************************\n \"\"\"\n\n clean_up_items = {'\\n': ' ', '\\r': ' ', '\\t': ' ', ' ': ' '}\n clean_up_items.update(replace_extras)\n\n text = text.strip()\n\n change_made = True\n while change_made:\n text_old = text\n for x in strip_chars:\n while text.startswith(x) or text.endswith(x):\n text = text.strip(x).strip()\n\n for key, val in clean_up_items.items():\n while key in text:\n text = text.replace(key, val)\n\n change_made = False if text_old == text else True\n\n return text.strip()\n","sub_path":"text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"339921967","text":"import pygame\nfrom pygame.locals import *\nfrom constants import *\nfrom loadmanager import *\nfrom player.player import *\n\n\nclass ShopPopup():\n '''\n Shop Window\n '''\n def __init__(self, screen, player):\n self.player = player\n self.pos = (0, 0)\n self.rt = 0\n self.button = 0\n self.screen = screen\n self.key = 0\n self.mouse = 0\n self.check = False\n self.x = 0\n self.y = WINDOW_HEIGHT - 200\n self.clicked = False\n self.width = WINDOW_WIDTH\n self.height = 200\n self.font = pygame.font.Font('data/fonts/Adore64.ttf', 8)\n self.font_title = pygame.font.Font('data/fonts/Adore64.ttf', 14)\n self.shop_title = self.font_title.render('SHOP', 1, Color('#104E8B'))\n self.st_posx = self.width / 2 - self.shop_title.get_rect().width / 2\n self.st_posy = self.y + 10\n self.close_text = self.font.render('CLOSE', 1, Color('#ffffff'))\n self.close_text_posx = \\\n WINDOW_WIDTH - self.close_text.get_rect().width - 10\n self.close_text_posy = \\\n self.y + 16 - self.close_text.get_rect().height / 2\n self.shop_text = self.font.render('SHOP', 1, (255, 255, 255))\n self.shop_text_posx = \\\n WINDOW_WIDTH - self.shop_text.get_rect().width - 10\n self.shop_text_posy = 10\n self.bg_image = LoadManager().get_image('pattern.png')\n self.towers = pygame.sprite.Group()\n self.sample = pygame.sprite.Group()\n self.imagine_entities = pygame.sprite.Group()\n self.current_sample = None\n self.bg_samples_list = []\n self.all_samples()\n\n def set_mouse_event(self, mouse):\n self.pos = mouse[1]\n self.rt = mouse[2]\n self.button = mouse[0]\n if self.check:\n self.current_sample = self.click_at_sample()\n if self.current_sample is not None:\n self.clicked = True\n\n def set_keyboard_event(self, keyboard):\n self.key = keyboard[0]\n\n def close_popup(self):\n if self.close_text_posx < \\\n self.pos[0] < self.close_text_posx + \\\n self.close_text.get_rect().width and \\\n self.close_text_posy < \\\n self.pos[1] < self.close_text_posy + \\\n self.close_text.get_rect().height and \\\n self.button == 1 and self.rt == 'DOWN' or self.clicked:\n self.check = False\n\n def open_popup(self):\n if self.shop_text_posx < \\\n self.pos[0] < self.shop_text_posx + \\\n self.shop_text.get_rect().width and \\\n self.shop_text_posy < \\\n self.pos[1] < \\\n self.shop_text_posy + \\\n self.shop_text.get_rect().height and \\\n self.button == 1 and self.rt == 'DOWN':\n self.check = True\n self.clicked = False\n self.sample.empty()\n self.current_sample = None\n\n def get_status(self):\n return self.check\n\n def all_samples(self):\n temp_x = WINDOW_WIDTH / 2 - 222\n bg_tower_level_one = [temp_x, self.y + 32, 128, self.y]\n tower_level_one = Tower(self.player, self.imagine_entities, 1)\n tower_level_one.id = 1\n tower_level_one.rect.x = temp_x + 64 - tower_level_one.rect.width / 2\n tower_level_one.rect.y = self.y + 64\n if self.player.coins >= tower_level_one.coast:\n self.coast_one = self.font_title.render(\n '$:%s' % str(tower_level_one.coast), 1, (0, 0, 0))\n else:\n self.coast_one = self.font_title.render(\n '$:%s' % str(tower_level_one.coast), 1, (255, 0, 0))\n self.coast_one_posx = temp_x + tower_level_one.rect.width / 2 - \\\n self.coast_one.get_rect().width / 2 + 48\n self.coast_one_posy = WINDOW_HEIGHT - 50\n self.bg_samples_list.append(bg_tower_level_one)\n self.sample.add(tower_level_one)\n temp_x += 160\n bg_tower_level_two = [temp_x, self.y + 32, 128, self.y]\n tower_level_two = Tower(self.player, self.imagine_entities, 2)\n tower_level_two.id = 2\n tower_level_two.rect.x = temp_x + 64 - tower_level_two.rect.width / 2\n tower_level_two.rect.y = self.y + 64\n if self.player.coins >= tower_level_two.coast:\n self.coast_two = self.font_title.render(\n '$:%s' % str(tower_level_two.coast), 1, (0, 0, 0))\n else:\n self.coast_two = self.font_title.render(\n '$:%s' % str(tower_level_two.coast), 1, (255, 0, 0))\n self.coast_two_posx = temp_x + tower_level_one.rect.width / 2 - \\\n self.coast_two.get_rect().width / 2 + 48\n self.coast_two_posy = WINDOW_HEIGHT - 50\n self.bg_samples_list.append(bg_tower_level_two)\n self.sample.add(tower_level_two)\n temp_x += 160\n bg_tower_level_three = [temp_x, self.y + 32, 128, self.y]\n tower_level_three = Tower(self.player, self.imagine_entities, 3)\n tower_level_three.id = 3\n tower_level_three.rect.x = temp_x + 64 - \\\n tower_level_three.rect.width / 2\n tower_level_three.rect.y = self.y + 64\n if self.player.coins >= tower_level_three.coast:\n self.coast_three = self.font_title.render(\n '$:%s' % str(tower_level_three.coast), 1, (0, 0, 0))\n else:\n self.coast_three = self.font_title.render(\n '$:%s' % str(tower_level_three.coast), 1, (255, 0, 0))\n self.coast_three_posx = temp_x + \\\n tower_level_three.rect.width / 2 - \\\n self.coast_three.get_rect().width / 2 + 48\n self.coast_three_posy = WINDOW_HEIGHT - 50\n self.bg_samples_list.append(bg_tower_level_three)\n self.sample.add(tower_level_three)\n\n def click_at_sample(self):\n for i in self.sample:\n if i.rect.x < self.pos[0] < i.rect.x + i.rect.width and \\\n i.rect.y < self.pos[1] < i.rect.y + i.rect.height and \\\n self.rt == 'DOWN' and self.button == 1:\n if self.player.coins >= i.coast:\n return i\n\n def get_active_sample(self):\n if self.clicked:\n return self.current_sample\n\n def update(self):\n self.sample.update()\n self.towers.update()\n if self.check:\n self.all_samples()\n self.close_popup()\n if not self.check:\n self.open_popup()\n\n def render(self):\n x = 0\n if self.check:\n while x < WINDOW_WIDTH:\n y = 0\n while y < WINDOW_HEIGHT:\n self.screen.blit(self.bg_image, (x, y))\n y += BLOCK_HEIGHT\n x += BLOCK_WIDTH\n pygame.draw.rect(self.screen, Color('#00688B'),\n (self.x, self.y, self.width, self.height))\n self.screen.blit(self.close_text,\n (self.close_text_posx, self.close_text_posy))\n self.screen.blit(self.shop_title,\n (self.st_posx, self.st_posy))\n self.screen.blit(self.shop_text,\n (self.shop_text_posx, self.shop_text_posy))\n if self.check:\n pygame.draw.rect(\n self.screen, Color('#ffffff'),\n (self.bg_samples_list[0][0],\n self.bg_samples_list[0][1],\n self.bg_samples_list[0][2],\n self.bg_samples_list[0][3]))\n pygame.draw.rect(\n self.screen,\n Color('#ffffff'),\n (self.bg_samples_list[1][0],\n self.bg_samples_list[1][1],\n self.bg_samples_list[1][2],\n self.bg_samples_list[1][3]))\n pygame.draw.rect(\n self.screen,\n Color('#ffffff'),\n (self.bg_samples_list[2][0],\n self.bg_samples_list[2][1],\n self.bg_samples_list[2][2],\n self.bg_samples_list[2][3]))\n self.sample.draw(self.screen)\n self.screen.blit(self.coast_one,\n (self.coast_one_posx, self.coast_one_posy))\n self.screen.blit(self.coast_two,\n (self.coast_two_posx, self.coast_two_posy))\n self.screen.blit(self.coast_three,\n (self.coast_three_posx, self.coast_three_posy))\n self.towers.draw(self.screen)\n","sub_path":"ui/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":8614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"227159818","text":"#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of PANDORA\n#\n# https://github.com/CNES/Pandora_pandora\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\"\"\"\nThis module contains classes and functions associated to the validation step.\n\"\"\"\n\nimport logging\nimport numpy as np\nimport xarray as xr\nfrom json_checker import Checker, And, Or\nfrom pandora import JSON_checker as jcheck\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Dict, Union\nfrom pandora.constants import *\n\n\nclass AbstractValidation(object):\n __metaclass__ = ABCMeta\n\n validation_methods_avail = {}\n\n def __new__(cls, **cfg: dict):\n \"\"\"\n Return the plugin associated with the validation_method given in the configuration\n\n :param cfg: configuration {'validation_method': value}\n :type cfg: dictionary\n \"\"\"\n if cls is AbstractValidation:\n if type(cfg['validation_method']) is str:\n try:\n return super(AbstractValidation, cls).__new__(cls.validation_methods_avail[cfg['validation_method']])\n except KeyError:\n logging.error(\"No validation method named {} supported\".format(cfg['validation_method']))\n raise KeyError\n else:\n if type(cfg['validation_method']) is unicode:\n # creating a plugin from registered short name given as unicode (py2 & 3 compatibility)\n try:\n return super(AbstractValidation, cls).__new__(\n cls.validation_methods_avail[cfg['validation_method'].encode('utf-8')])\n except KeyError:\n logging.error(\"No validation matching method named {} supported\".format(cfg['validation_method']))\n raise KeyError\n else:\n return super(AbstractValidation, cls).__new__(cls)\n\n @classmethod\n def register_subclass(cls, short_name: str):\n \"\"\"\n Allows to register the subclass with its short name\n\n :param short_name: the subclass to be registered\n :type short_name: string\n \"\"\"\n\n def decorator(subclass):\n cls.validation_methods_avail[short_name] = subclass\n return subclass\n\n return decorator\n\n @abstractmethod\n def desc(self):\n \"\"\"\n Describes the validation method\n \"\"\"\n print('Validation method description')\n\n @abstractmethod\n def disparity_checking(self, dataset_ref: xr.Dataset, dataset_sec: xr.Dataset, img_ref: xr.Dataset = None,\n img_sec: xr.Dataset = None, cv: xr.Dataset = None) -> xr.Dataset:\n \"\"\"\n Determination of occlusions and false matches by performing a consistency check on valid pixels. \\\n Update the validity_mask :\n - If out & MSK_PIXEL_OCCLUSION != 0 : Invalid pixel : occluded pixel\n - If out & MSK_PIXEL_MISMATCH != 0 : Invalid pixel : mismatched pixel\n Update the measure map: add the disp RL / disp LR distances\n\n :param dataset_ref: Reference Dataset\n :type dataset_ref: xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n :param dataset_sec: Secondary Dataset\n :type dataset_sec: xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n :param img_ref: reference Datset image\n :type img_ref:\n xarray.Dataset containing :\n - im : 2D (row, col) xarray.DataArray\n - msk : 2D (row, col) xarray.DataArray\n :param img_sec: secondary Dataset image\n :type img_sec:\n xarray.Dataset containing :\n - im : 2D (row, col) xarray.DataArray\n - msk : 2D (row, col) xarray.DataArray\n :param cv: cost_volume Dataset\n :type cv:\n xarray.Dataset with the variables:\n - cost_volume 3D xarray.DataArray (row, col, disp)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n :return: the reference dataset, with the bit 8 and 9 of the validity_mask :\n - If out & MSK_PIXEL_OCCLUSION != 0 : Invalid pixel : occluded pixel\n - If out & MSK_PIXEL_MISMATCH != 0 : Invalid pixel : mismatched pixel\n :rtype : xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n \"\"\"\n\n\n@AbstractValidation.register_subclass('none')\nclass NoneValidation(AbstractValidation):\n \"\"\"\n Default plugin that does not perform validation\n \"\"\"\n\n def __init__(self, **cfg: str):\n \"\"\"\n :param cfg: optional configuration, {}\n :type cfg: dict\n \"\"\"\n self.cfg = self.check_conf(**cfg)\n\n @staticmethod\n def check_conf(**cfg: str) -> Dict[str, str]:\n \"\"\"\n Add default values to the dictionary if there are missing elements and check if the dictionary is correct\n\n :param cfg: validation configuration\n :type cfg: dict\n :return cfg: validation configuration updated\n :rtype: dict\n \"\"\"\n # Give the default value if the required element is not in the configuration\n # Need to initialize 'interpolated_disparity' to run Pandora pipeline\n if 'interpolated_disparity' not in cfg:\n cfg['interpolated_disparity'] = 'none'\n\n schema = {\n \"validation_method\": And(str, lambda x: 'none'),\n \"interpolated_disparity\": And(str, lambda x: 'none')\n }\n\n checker = Checker(schema)\n checker.validate(cfg)\n return cfg\n\n def desc(self):\n \"\"\"\n Describes the validation method\n \"\"\"\n print('No validation step')\n\n def disparity_checking(self, dataset_ref: xr.Dataset, dataset_sec: xr.Dataset, img_ref: xr.Dataset = None,\n img_sec: xr.Dataset = None, cv: xr.Dataset = None) -> xr.Dataset:\n \"\"\"\n Determination of occlusions and false matches by performing a consistency check on valid pixels. \\\n Update the validity_mask :\n - If out & MSK_PIXEL_OCCLUSION != 0 : Invalid pixel : occluded pixel\n - If out & MSK_PIXEL_MISMATCH != 0 : Invalid pixel : mismatched pixel\n Update the measure map: add the disp RL / disp LR distances\n\n :param dataset_ref: Reference Dataset\n :type dataset_ref: xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n :param dataset_sec: Secondary Dataset\n :type dataset_sec: xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n :param img_ref: reference Datset image\n :type img_ref:\n xarray.Dataset containing :\n - im : 2D (row, col) xarray.DataArray\n - msk : 2D (row, col) xarray.DataArray\n :param img_sec: secondary Dataset image\n :type img_sec:\n xarray.Dataset containing :\n - im : 2D (row, col) xarray.DataArray\n - msk : 2D (row, col) xarray.DataArray\n :param cv: cost_volume Dataset\n :type cv:\n xarray.Dataset with the variables:\n - cost_volume 3D xarray.DataArray (row, col, disp)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n :return: the reference dataset, with the bit 8 and 9 of the validity_mask :\n - If out & MSK_PIXEL_OCCLUSION != 0 : Invalid pixel : occluded pixel\n - If out & MSK_PIXEL_MISMATCH != 0 : Invalid pixel : mismatched pixel\n :rtype : xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n \"\"\"\n return dataset_ref\n\n\n@AbstractValidation.register_subclass('cross_checking')\nclass CrossChecking(AbstractValidation):\n \"\"\"\n CrossChecking class allows to perform the validation step\n \"\"\"\n # Default configuration, do not change this value\n _THRESHOLD = 1.\n\n def __init__(self, **cfg):\n \"\"\"\n :param cfg: optional configuration, {'cross_checking_threshold': value,\n 'interpolated_disparity': value, 'filter_interpolated_disparities': value}\n :type cfg: dictionary\n \"\"\"\n self.cfg = self.check_conf(**cfg)\n self._threshold = self.cfg['cross_checking_threshold']\n\n def check_conf(self, **cfg: Union[str, int, float, bool]) -> Dict[str, Union[str, int, float, bool]]:\n \"\"\"\n Add default values to the dictionary if there are missing elements and check if the dictionary is correct\n\n :param cfg: optimization configuration\n :type cfg: dict\n :return cfg: optimization configuration updated\n :rtype: dict\n \"\"\"\n # Give the default value if the required element is not in the configuration\n if 'cross_checking_threshold' not in cfg:\n cfg['cross_checking_threshold'] = self._THRESHOLD\n if 'right_left_mode' not in cfg:\n cfg['right_left_mode'] = 'accurate'\n if 'interpolated_disparity' not in cfg:\n cfg['interpolated_disparity'] = 'none'\n if 'filter_interpolated_disparities' not in cfg:\n cfg['filter_interpolated_disparities'] = True\n\n schema = {\n \"validation_method\": And(str, lambda x: 'cross_checking'),\n \"cross_checking_threshold\": Or(int, float),\n \"right_left_mode\": And(str, lambda x: jcheck.is_method(x, ['accurate', 'approximate'])),\n \"interpolated_disparity\": And(str, lambda x: jcheck.is_method(x, ['none', 'mc-cnn', 'sgm'])),\n \"filter_interpolated_disparities\": bool\n }\n\n checker = Checker(schema)\n checker.validate(cfg)\n return cfg\n\n def desc(self):\n \"\"\"\n Describes the validation method\n \"\"\"\n print('Cross-checking method')\n\n def disparity_checking(self, dataset_ref: xr.Dataset, dataset_sec: xr.Dataset, img_ref: xr.Dataset = None,\n img_sec: xr.Dataset = None, cv: xr.Dataset = None) -> xr.Dataset:\n \"\"\"\n Determination of occlusions and false matches by performing a consistency check on valid pixels. \\\n Update the validity_mask :\n - If out & MSK_PIXEL_OCCLUSION != 0 : Invalid pixel : occluded pixel\n - If out & MSK_PIXEL_MISMATCH != 0 : Invalid pixel : mismatched pixel\n Update the measure map: add the disp RL / disp LR distances\n\n :param dataset_ref: Reference Dataset\n :type dataset_ref: xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n :param dataset_sec: Secondary Dataset\n :type dataset_sec: xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n :param img_ref: reference Datset image\n :type img_ref:\n xarray.Dataset containing :\n - im : 2D (row, col) xarray.DataArray\n - msk : 2D (row, col) xarray.DataArray\n :param img_sec: secondary Dataset image\n :type img_sec:\n xarray.Dataset containing :\n - im : 2D (row, col) xarray.DataArray\n - msk : 2D (row, col) xarray.DataArray\n :param cv: cost_volume Dataset\n :type cv:\n xarray.Dataset with the variables:\n - cost_volume 3D xarray.DataArray (row, col, disp)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n :return: the reference dataset, with the bit 8 and 9 of the validity_mask :\n - If out & MSK_PIXEL_OCCLUSION != 0 : Invalid pixel : occluded pixel\n - If out & MSK_PIXEL_MISMATCH != 0 : Invalid pixel : mismatched pixel\n :rtype : xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n \"\"\"\n nb_row, nb_col, nb_indicator = dataset_ref['confidence_measure'].shape\n disparity_range = np.arange(dataset_ref.attrs['disp_min'], dataset_ref.attrs['disp_max'] + 1)\n\n # Add a new indicator to the confidence measure DataArray\n conf_measure = np.zeros((nb_row, nb_col, nb_indicator + 1), dtype=np.float32)\n conf_measure[:, :, :-1] = dataset_ref['confidence_measure'].data\n\n indicator = np.copy(dataset_ref.coords['indicator'])\n indicator = np.append(indicator, 'validation_pandora_distanceOfDisp')\n\n # Remove confidence_measure dataArray from the dataset to update it\n dataset_ref = dataset_ref.drop_dims('indicator')\n dataset_ref = dataset_ref.assign_coords(indicator=indicator)\n dataset_ref['confidence_measure'] = xr.DataArray(data=conf_measure, dims=['row', 'col', 'indicator'])\n\n for row in range(0, nb_row):\n # Exclude invalid pixel :\n valid_pixel = np.where((dataset_ref['validity_mask'].data[row, :] & PANDORA_MSK_PIXEL_INVALID) == 0)\n\n col_ref = np.arange(nb_col, dtype=np.int)\n col_ref = col_ref[valid_pixel]\n\n col_sec = col_ref + dataset_ref['disparity_map'].data[row, col_ref]\n # Round elements of the array to the nearest integer\n col_sec = np.rint(col_sec).astype(int)\n\n # Left-Right consistency, for pixel i :\n # If | Disp_sec(i + rint(Disp_ref(i)) + Disp_ref(i) | > self._threshold : i is invalid, mismatched or occlusion detected\n # If | Disp_sec(i + rint(Disp_ref(i)) + Disp_ref(i) | <= self._threshold : i is valid\n\n # Apply cross checking on pixels i + round(Disp_ref(i) inside the secondary image\n inside_sec = np.where((col_sec >= 0) & (col_sec < nb_col))\n\n # Conversion from nan to inf\n sec_disp = dataset_sec['disparity_map'].data[row, col_sec[inside_sec]]\n sec_disp[np.isnan(sec_disp)] = np.inf\n ref_disp = dataset_ref['disparity_map'].data[row, col_ref[inside_sec]]\n ref_disp[np.isnan(ref_disp)] = np.inf\n\n # Allocate to the measure map, the distance disp LR / disp RL indicator\n dataset_ref['confidence_measure'].data[row, inside_sec[0], -1] = np.abs(sec_disp + ref_disp)\n\n # Reference image pixels invalidated by the cross checking\n invalid = np.abs(sec_disp + ref_disp) > self._threshold\n\n # Detect mismatched and occlusion :\n # For a reference image pixel i invalidated by the cross checking :\n # mismatch if : Disp_sec(i + d) = -d, for any other d\n # occlusion otherwise\n\n # Index : i + d, for any other d. 2D np array (nb invalid pixels, nb disparity )\n index = np.tile(disparity_range, (len(col_ref[inside_sec][invalid]), 1)).astype(np.float32) + \\\n np.tile(col_ref[inside_sec][invalid], (len(disparity_range), 1)).transpose()\n\n inside_col_disp = np.where((index >= 0) & (index < nb_col))\n\n # disp_sec : Disp_sec(i + d)\n disp_sec = np.full(index.shape, np.inf, dtype=np.float32)\n disp_sec[inside_col_disp] = dataset_sec['disparity_map'].data[row, index[inside_col_disp].astype(int)]\n\n # Check if Disp_sec(i + d) == -d\n comp = (disp_sec == np.tile(-1 * disparity_range, (len(col_ref[inside_sec][invalid]), 1)).astype(\n np.float32))\n comp = np.sum(comp, axis=1)\n comp[comp > 1] = 1\n\n dataset_ref['validity_mask'].data[row, col_ref[inside_sec][invalid]] += PANDORA_MSK_PIXEL_OCCLUSION\n dataset_ref['validity_mask'].data[row, col_ref[inside_sec][invalid]] += \\\n (PANDORA_MSK_PIXEL_MISMATCH * comp).astype(np.uint16)\n dataset_ref['validity_mask'].data[row, col_ref[inside_sec][invalid]] -= \\\n (PANDORA_MSK_PIXEL_OCCLUSION * comp).astype(np.uint16)\n\n # Pixels i + round(Disp_ref(i) outside the secondary image are occlusions\n outside_sec = np.where((col_sec < 0) & (col_sec >= nb_col))\n dataset_ref['validity_mask'].data[row, col_ref[outside_sec]] += PANDORA_MSK_PIXEL_OCCLUSION\n\n dataset_ref.attrs['validation'] = 'cross_checking'\n\n return dataset_ref\n","sub_path":"pandora/validation/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":18009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"176561029","text":"import re\nfrom functools import update_wrapper\n\nfrom django.apps import apps\nfrom django.core import mail\nfrom django.conf import settings\nfrom django.contrib import auth\nfrom django.db import models\nfrom django.utils.html import conditional_escape\nfrom django.utils.safestring import mark_safe\n\n__all__ = (\n 'has_object_perm', 'viewprop', 'DEFAULT', 'first_not_default'\n)\n\n\nclass MARKER(object):\n def __init__(self, marker: str):\n self.marker = marker\n\n def __iter__(self):\n return iter(())\n\n def __repr__(self):\n return self.marker\n\n\nDEFAULT = MARKER('DEFAULT')\n\nIS_DEV = settings.DEBUG or not hasattr(mail, 'outbox') # DEBUG or test mode\n\n\ndef first_not_default(*args):\n for arg in args:\n if arg is not DEFAULT:\n return arg\n return arg\n\n\ndef camel_case_to_underscore(name):\n \"\"\"Convert camel cased SomeString to some_string\"\"\"\n\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2',\n re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)).lower()\n\n\ndef camel_case_to_title(name):\n \"\"\"Convert camel cased 'SomeString' to 'Some string'\"\"\"\n\n return re.sub('([a-z0-9])([A-Z])', r'\\1 \\2',\n re.sub('(.)([A-Z][a-z]+)', r'\\1 \\2', name)).capitalize()\n\n\ndef has_object_perm(user, short_perm_name, model, obj=None):\n perm_name = auth.get_permission_codename(short_perm_name, model._meta)\n has_perm = user.has_perm(perm_name)\n if not has_perm and obj is not None:\n has_perm = user.has_perm(perm_name, obj=obj)\n return has_perm\n\n\ndef strip_suffixes(word, suffixes):\n \"\"\"Strip suffixes from the word.\n\n Never strips whole word to empty string.\n \"\"\"\n\n for suffix in suffixes:\n if word != suffix and word.endswith(suffix):\n word = word[:-len(suffix)]\n return word\n\n\ndef strip_dict_keys_prefix(a_dict, prefix):\n \"\"\"Construct new dict, from source keys started with prefix.\"\"\"\n\n return {\n key[len(prefix):]: value for key, value in a_dict.items()\n if key.startswith(prefix)\n }\n\n\ndef get_app_package(app_label):\n \"\"\"Return app package string.\"\"\"\n app_config = apps.get_app_config(app_label)\n if not app_config:\n return None\n return app_config.module.__name__\n\n\ndef get_containing_app_data(module):\n \"\"\"Return app label and package string.\"\"\"\n app_config = apps.get_containing_app_config(module)\n if not app_config:\n return None, None\n return app_config.label, app_config.module.__name__\n\n\ndef is_owner(owner, user):\n \"\"\"Check user instances and subclasses for equality.\"\"\"\n return isinstance(user, owner.__class__) and owner.pk == user.pk\n\n\nclass viewprop(object):\n \"\"\"\n A property that can be overridden.\n \"\"\"\n def __init__(self, func):\n self.__doc__ = getattr(func, '__doc__')\n self.fget = func\n\n def __get__(self, obj, objtype=None):\n if obj is None:\n return self\n if self.fget.__name__ not in obj.__dict__:\n obj.__dict__[self.fget.__name__] = self.fget(obj)\n return obj.__dict__[self.fget.__name__]\n\n def __set__(self, obj, value):\n obj.__dict__[self.fget.__name__] = value\n\n def __repr__(self):\n return '<view_property func={}>'.format(self.fget)\n\n\ndef create_wrapper_view(origin_view, flow_task=None, flow_class=None):\n \"\"\"Create a wrapper view with flow_task/flow_class injected.\"\"\"\n def view(request, *args, **kwargs):\n if flow_class is not None:\n request.flow_class = flow_class\n if flow_task is not None:\n request.flow_task = flow_task\n return origin_view(request, *args, **kwargs)\n return update_wrapper_view(view, origin_view, flow_task=flow_task, flow_class=flow_class)\n\n\ndef update_wrapper_view(view, origin_view, flow_task=None, flow_class=None):\n \"\"\"Update a wrapper view to look like the wrapped origin_view.\"\"\"\n\n view_class = None\n if hasattr(origin_view, 'view_class'): # django generic view\n view_class = view.view_class = origin_view.view_class\n if hasattr(origin_view, 'cls'): # django restframework generic view\n view_class = view.cls = origin_view.cls\n if hasattr(origin_view, 'view_initkwargs'): # both 八(^□^*)\n view.view_initkwargs = origin_view.initkwargs or {}\n\n # poor-man dependency injection. Mostly b/c of dumb restframework BaseSchemaGenerator.create_view impl\n if flow_class and hasattr(view_class, 'flow_class'):\n view.view_initkwargs['flow_task'] = flow_class\n if flow_task and hasattr(view_class, 'flow_task'):\n view.view_initkwargs['flow_task'] = flow_task\n\n update_wrapper(view, origin_view)\n return view\n\n\nclass LazySingletonDescriptor(object):\n \"\"\"Descriptor class for lazy singleton instance.\"\"\"\n\n def __init__(self): # noqa D102\n self.instance = None\n\n def __get__(self, instance=None, owner=None):\n if self.instance is None:\n self.instance = owner()\n return self.instance\n\n\nclass Icon(object):\n def __init__(self, icon_name, class_=None):\n self.icon_name = icon_name\n self.class_ = class_ or \"\"\n\n def __str__(self):\n icon_name = conditional_escape(self.icon_name)\n class_name = conditional_escape(self.class_)\n return mark_safe(\n f'<i class=\"material-icons ${class_name}\" aria-hidden=\"true\">{icon_name}</i>'\n )\n\n\ndef get_object_data(obj):\n \"\"\"List of object fields to display.\n Choice fields values are expanded to readable choice label.\n \"\"\"\n for field in obj._meta.fields:\n if isinstance(field, models.AutoField):\n continue\n elif field.auto_created:\n continue\n else:\n choice_display_attr = \"get_{}_display\".format(field.name)\n if hasattr(obj, choice_display_attr):\n value = getattr(obj, choice_display_attr)()\n else:\n value = getattr(obj, field.name)\n\n if value is not None:\n yield (field, field.verbose_name.capitalize(), value)\n","sub_path":"venv/Lib/site-packages/viewflow/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"414395746","text":"import numpy as np\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.tokenize import word_tokenize\r\nimport re as re\r\nfrom nltk.stem import PorterStemmer\r\nimport nltk\r\n\r\nnltk.download(\"stopwords\")\r\n\r\nSTOPWORDS = set(stopwords.words('english'))\r\nps = PorterStemmer()\r\n\r\n\r\nPUNCT_REG = \"[.\\\"\\\\-,*)(!?#&%$@;:_~\\^+=/]\"\r\n\r\n\r\ndef substring_edit_dist(l1, l2):\r\n \"\"\"\r\n\r\n :param s1:\r\n :param s2:\r\n :return:\r\n \"\"\"\r\n l1 = [ps.stem(l) for l in l1]\r\n l2 = [ps.stem(l) for l in l2]\r\n if (len(l1) > len(l2)):\r\n return edit_dist_help(l1,l2,len(l1),len(l2))\r\n #going through every substring\r\n s = len(l1)\r\n best_dist = np.inf\r\n for i in range(len(l2)-s+1):\r\n cur_l2 = l2[i:i+s]\r\n cur_dist = edit_dist_help(l1,cur_l2,len(l1), len(cur_l2))\r\n if (cur_dist < best_dist):\r\n best_dist = cur_dist\r\n return best_dist\r\n\r\ndef edit_dist_help(l1,l2,n,m):\r\n \"\"\"\r\n\r\n :param l1:\r\n :param l2:\r\n :param n:\r\n :param m:\r\n :return:\r\n \"\"\"\r\n if (m ==0):\r\n return n\r\n if (n == 0):\r\n return m\r\n if (l1[n-1]==l2[m-1]):\r\n return edit_dist_help(l1,l2,n-1,m-1)\r\n else:\r\n edit_list = [edit_dist_help(l1,l2,n-1,m),edit_dist_help(l1,l2,n,m-1),edit_dist_help(l1,l2,n-1,m-1)]\r\n return 1+min(edit_list)\r\n\r\n\r\n\r\nSTOP = \"stop\"\r\n\r\n\r\ndef list_to_stop_mapping(l):\r\n \"\"\"\r\n \"\"\"\r\n stop_map = {}\r\n stopped_list = []\r\n j = 0\r\n for i,x in enumerate(l):\r\n if x not in STOPWORDS:\r\n stop_map[j] = i\r\n stopped_list.append(x)\r\n j += 1\r\n return stopped_list, stop_map\r\n\r\ndef fuzzy_decision_tree(p1,p2):\r\n \"\"\"\r\n deciding whether or not to create an edge between p1 and p2.\r\n \"\"\"\r\n s1 = p1.split()\r\n s2 = p2.split()\r\n s = len(s1)\r\n l1,stop_map = list_to_stop_mapping(s1)\r\n l2 = [l for l in s2 if l not in STOPWORDS]\r\n l2 = [ps.stem(l) for l in l2]\r\n l1 = [ps.stem(l) for l in l1]\r\n if (not l1 or not l2):\r\n return False\r\n lp = min(len(s1),len(s2))\r\n ls = min(len(l1),len(l2))\r\n d, i1,i2,caught_str = fuzzy_substring_dist(l1,l2)\r\n orig_str = \" \".join(s1[stop_map[i1]:stop_map[i2]+1])\r\n #deciding\r\n if (ls >=2 and d ==0):\r\n return STOP\r\n if (lp == 4 and ls ==4 and d<=1):\r\n return orig_str\r\n if (lp == 5 and ls >5 and d<=1):\r\n return orig_str\r\n if (lp ==6 and ls>=5 and d<=1):\r\n return orig_str\r\n if (lp > 6 and ls >3 and d<=2):\r\n return orig_str\r\n return False\r\n\r\n\r\ndef decision_tree(p1,p2):\r\n \"\"\"\"\r\n \"\"\"\r\n\r\n # p1 = re.sub(PUNCT_REG,\" \",p1)\r\n # p2 = re.sub(PUNCT_REG,\" \",p2)\r\n s1 = p1.split()\r\n s2 = p2.split()\r\n s = len(s1)\r\n l1 = [l for l in s1 if l not in STOPWORDS]\r\n l2 = [l for l in s2 if l not in STOPWORDS]\r\n l1 = [ps.stem(l) for l in l1]\r\n l2 = [ps.stem(l) for l in l2]\r\n #going through every substring\r\n min_index = np.inf\r\n max_index = -1\r\n was_added = False\r\n for i in range(len(s2)-s+1):\r\n cur_l2 = s2[i:i+s]\r\n lp = min(len(s1),len(cur_l2))\r\n cur_l2 = [l for l in cur_l2 if l not in STOPWORDS]\r\n cur_l2 = [ps.stem(l) for l in cur_l2]\r\n ls = min(len(l1),len(cur_l2))\r\n d = edit_dist_help(l1,cur_l2,len(l1), len(cur_l2))\r\n #deciding\r\n added = False\r\n if (ls >=2 and d ==0):\r\n return STOP\r\n if (lp == 4 and ls ==4 and d<=1):\r\n added = True\r\n if (lp == 5 and ls >5 and d<=1):\r\n added = True\r\n if (lp ==6 and ls>=5 and d<=1):\r\n added = True\r\n if (lp > 6 and ls >3 and d<=2):\r\n added = True\r\n if (added): # should be added, thus we should append it's indices:\r\n if (not was_added):\r\n min_index = i\r\n was_added = True\r\n max_index = i+s\r\n if (was_added):\r\n return (True, \" \".join(s2[min_index:max_index]))\r\n return False\r\n\r\ndef fuzzy_substring_dist(l1,l2):\r\n E = {}\r\n m = len(l1)\r\n n = len(l2)\r\n for i in range(m+1):\r\n E[(0,i)] = (0,None)\r\n for i in range(n+1):\r\n E[(i,0)] = (i,None)\r\n\r\n for i in range(1,n+1):\r\n for j in range(1,m+1):\r\n if (l1[j-1]==l2[i-1]):\r\n E[(i,j)] = (E[(i-1,j-1)][0], \"0\")\r\n else:\r\n edit_list = [E[(i-1,j-1)][0],E[(i,j-1)][0],E[(i-1,j)][0]]\r\n val = 1+np.min(edit_list)\r\n direction = str(np.argmin(edit_list))\r\n E[(i,j)] = (val, direction)\r\n\r\n #extracting result\r\n min_val = np.inf\r\n min_index = 0\r\n for i in range(1,m+1):\r\n # print(E[(n,i)])\r\n cur_val = E[(n,i)][0]\r\n if (cur_val <= min_val):\r\n min_val = cur_val\r\n min_index = i\r\n stop_last_index = min_index\r\n cur_val = min_val\r\n cur_list = [l1[min_index-1]]\r\n ind = n\r\n direction = E[(ind,min_index)][1]\r\n while(direction):\r\n if (direction == \"0\"):\r\n min_index -= 1\r\n ind -= 1\r\n if (ind != 0 and min_index != 0):\r\n cur_list = [l1[min_index-1]] + cur_list\r\n if (direction == \"2\"):\r\n ind -= 1\r\n if (direction == \"1\"):\r\n min_index -= 1\r\n cur_list = [l1[min_index-1]] + cur_list\r\n direction = E[(ind,min_index)][1]\r\n stop_first_index = min_index\r\n return cur_val, stop_first_index,stop_last_index-1, cur_list\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # s1 = \"I don't know what to tell you brother there is no place like home i think i think tell me nir i think i think tell me nir i think i think tell me nir i think i think tell me nir i think i think tell me nir i think i think tell me nir i think i think tell me nir i think\"\r\n # s2 = \"there's no place like home tell me nir i think tell me nir i think i think tell me nir i think i think tell me nir i think i think tell me nir i think\"\r\n s1 = \"i love the smell of napalm in the morning\"\r\n s2 = 'chlorine don\\'t know why but i love the smell of it'\r\n # print(decision_tree(s1,s2))\r\n # s1 = \"T A T T G G C T A T A C G G T T\"\r\n # s1 = re.sub(PUNCT_REG,\" \",s1)\r\n # s2 = \"G C G T A T G C\"\r\n # s2 = re.sub(PUNCT_REG,\" \",s2)\r\n print(fuzzy_decision_tree(s2,s1))\r\n print(fuzzy_substring_dist(s2.split(), s1.split()))","sub_path":"Measures.py","file_name":"Measures.py","file_ext":"py","file_size_in_byte":6304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"560655531","text":"import sys\nimport os\nimport json\n\nfrom PIL import Image\n\nJSON_FILE = sys.argv[1]\nLIST = False\n\nif os.path.isfile(\"./\" + JSON_FILE):\n with open(JSON_FILE) as f:\n data = f.read()\n LIST = json.loads(data)\nelse:\n print(JSON_FILE + \" couldn't found.\")\n\nif LIST:\n COLOR_TABLE = LIST['color_table']\n\n fileout = './lvls.bullshit'\n OUTPUT = ''\n\n for i in range(len(LIST['list'])):\n level = LIST['list'][i]\n n = level['n']\n f = level['f']\n \n img = Image.open(f)\n pixels = img.load()\n\n w, h = img.size\n\n OUTPUT += '\\n{ \"name\": \"' + n + '\", \"arr\": {'\n\n for y in range(h):\n OUTPUT += '\\n\\t{ '\n for x in range(w):\n p = pixels[x, y]\n \n key = str(p[0]) + \"-\" + str(p[1]) + \"-\" + str(p[2])\n index = COLOR_TABLE[key]\n \n OUTPUT += index\n\n if x != w - 1:\n OUTPUT += ','\n\n OUTPUT += ' '\n\n OUTPUT += '}'\n\n if y != h - 1:\n OUTPUT += ','\n \n OUTPUT += '\\n}}'\n\n if i < len(LIST['list']) - 1:\n OUTPUT += ','\n\n OUTPUT += ''\n\n with open(fileout, \"w\", encoding=\"utf8\") as f:\n f.write(OUTPUT)\n","sub_path":"demo/level-gen-tool/img_to_levelarr.py","file_name":"img_to_levelarr.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"148615672","text":"#!/usr/bin/python3\n\nimport requests, json\n\n\nheaders = {'content-type': 'application/json'}\n\ndata = {\n \"nome\": \"Mestre\",\n \"email\": \"papa@teste\"\n}\n\nrequisicao = requests.delete('http://127.0.0.1:5000/usuarios/3', headers=headers)\n\n\n\nprint(requisicao)","sub_path":"requisicoes.py","file_name":"requisicoes.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"428063581","text":"from django.core.urlresolvers import reverse\nfrom selenium.webdriver.common.keys import Keys\n\nfrom tests.base.django_test_cases import DestructiveProductDbFunctionalTest\nimport os\n\n\nclass TestBulkEolCheckTool(DestructiveProductDbFunctionalTest):\n fixtures = ['default_vendors.yaml', ]\n\n def test_with_valid_queries(self):\n # a user hits the bulk EoL page\n self.browser.get(self.server_url + reverse(\"productdb:bulk_eol_check\"))\n self.browser.implicitly_wait(3)\n\n # he sees the bulk EoL products textarea, which contains the text to enter the\n # product IDs separated by a line break\n expected_text = \"On this page, you can execute a bulk check of multiple products against the local database. \" \\\n \"Please enter a list of product IDs in the following text field separated by line breaks\"\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertIn(expected_text, page_text)\n\n # the user enters the test query into the field and submit the result\n # (whitespace is stripped)\n sample_eol_query = \"\"\"WS-C2960-24LC-S\n WS-C2960-24LC-S\n WS-C2960-24LC-S\nWS-C2960-24LC-S\nWS-C2960-24LT-L\n WS-C2960-24PC-S\n\n WS-C2960X-24PD-L\n\n WS-C2960X-24PD-L\n WS-C2960X-24PD-L\n MOH\n WS-C2960-48PST-S\nWS-C2960-24TC-L\nMOH\n WS-C2960-24TC-S\n WS-C2960-24TT-L\"\"\"\n self.browser.find_element_by_id(\"db_query\").send_keys(sample_eol_query)\n self.browser.find_element_by_id(\"submit\").click()\n\n # verify result within the product summary table\n expected_product_summary_row = \"WS-C2960-24LC-S Catalyst 2960 24 10/100 (8 PoE) + 2 T/SFP LAN Lite Image 4 \" \\\n \"End of Sale\\nEnd of New Service Attachment Date\\nEnd of SW Maintenance \" \\\n \"Releases Date\\nEnd of Routine Failure Analysis Date\"\n expected_not_found_query = \"MOH 2 Not found in database\"\n\n table = self.browser.find_element_by_id('product_summary_table')\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(expected_product_summary_row,\n [row.text for row in rows])\n self.assertIn(expected_not_found_query,\n [row.text for row in rows])\n\n # verify result within the product table which contains the lifecycle information\n expected_product_row = \"WS-C2960-24LC-S 2013/01/31 2014/01/31 2015/01/31 2015/01/31 2015/01/31 2019/01/29 \" \\\n \"2019/01/31 EOL9449\"\n not_expected_product_row = \"WS-C2960X-24PD-L\"\n table = self.browser.find_element_by_id('product_table')\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(expected_product_row, [row.text for row in rows])\n self.assertNotIn(not_expected_product_row, table.text)\n\n # verify result within the skipped query table\n invalid_query = \"MOH Not found in database\"\n valid_query_without_eol = \"WS-C2960X-24PD-L no EoL announcement found\"\n unexpected_element = \"\\nWS-C2960-24LC-S\"\n filtered_element = \"\\nNot found in database\\n\"\n table = self.browser.find_element_by_id('skipped_queries_table')\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(invalid_query, [row.text for row in rows])\n self.assertIn(valid_query_without_eol, [row.text for row in rows])\n self.assertNotIn(unexpected_element, table.text)\n self.assertNotIn(filtered_element, table.text)\n\n # test CSV download within the detailed page\n # download product summary table\n dt_buttons = self.browser.find_element_by_xpath('//div[@id=\"product_summary_table_wrapper\"]/div/div/div/'\n 'div[@class=\"dt-buttons btn-group\"]')\n dt_buttons.find_element_by_link_text(\"CSV\").click()\n\n # The file should download automatically (firefox is configured this way)\n\n # Verify that the file is a CSV formatted field (with \";\" as delimiter)\n file = os.path.join(self.download_dir, \"Bulk EoL check (product summary table).csv\")\n f = open(file, \"r\")\n self.assertEqual(\"\\ufeffProduct ID;Description;Amount;Lifecycle State\\n\", f.readline())\n f.close()\n\n # download detailed lifecycle state table\n dt_buttons = self.browser.find_element_by_xpath('//div[@id=\"product_table_wrapper\"]/div/div/div/'\n 'div[@class=\"dt-buttons btn-group\"]')\n dt_buttons.find_element_by_link_text(\"CSV\").send_keys(Keys.ENTER)\n\n # The file should download automatically (firefox is configured this way)\n\n # Verify that the file is a CSV formatted field (with \";\" as delimiter)\n file = os.path.join(self.download_dir, \"Bulk EoL check (detailed lifecycle states).csv\")\n f = open(file, \"r\")\n self.assertEqual(\"\\ufeffPID;EoL anno.;EoS;EoNewSA;EoSWM;EoRFA;EoSCR;EoVulnServ;EoSup;Link\\n\", f.readline())\n f.close()\n\n # download skipped queries table\n dt_buttons = self.browser.find_element_by_xpath('//div[@id=\"skipped_queries_table_wrapper\"]/div/div/div/'\n 'div[@class=\"dt-buttons btn-group\"]')\n dt_buttons.find_element_by_link_text(\"CSV\").send_keys(Keys.ENTER)\n\n # The file should download automatically (firefox is configured this way)\n\n # Verify that the file is a CSV formatted field (with \";\" as delimiter)\n file = os.path.join(self.download_dir, \"Bulk EoL check (queries and products which are not found).csv\")\n f = open(file, \"r\")\n self.assertEqual(\"\\ufeffQuery/Product ID;result\\n\", f.readline())\n f.close()\n\n def test_invalid_entry(self):\n # a user hits the bulk EoL page\n self.browser.get(self.server_url + reverse(\"productdb:bulk_eol_check\"))\n self.browser.implicitly_wait(3)\n\n # he sees the bulk EoL products textarea, which contains the text to enter the\n # product IDs separated by a line break\n expected_text = \"On this page, you can execute a bulk check of multiple products against the local database. \" \\\n \"Please enter a list of product IDs in the following text field separated by line breaks\"\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertIn(expected_text, page_text)\n\n # the user enters the test query into the field and submit the result\n # (whitespace is stripped)\n sample_eol_query = \"invalid_query\"\n self.browser.find_element_by_id(\"db_query\").send_keys(sample_eol_query)\n self.browser.find_element_by_id(\"submit\").click()\n\n # verify result within the product summary table\n expected_text = \"Query returned no results.\"\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertIn(expected_text, page_text)\n","sub_path":"tests/functional/user_interface/test_bulk_eol_check.py","file_name":"test_bulk_eol_check.py","file_ext":"py","file_size_in_byte":7059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"241570167","text":"#!/usr/bin/env python3\n\nimport rospy\n\n#from nav_msgs.msg import OccupancyGrid\nfrom std_msgs.msg import Int32\nfrom std_msgs.msg import UInt16MultiArray\nfrom std_msgs.msg import Bool\n\nspeed = 0\n#grid = OccupancyGrid()\n\ndef tdoa_callback(time_diff):\n print(f\"tdoa {time_diff}\")\n if speed == 0:\n direction = Bool()\n if time_diff.data < 200:\n direction.data = 1\n else:\n direction.data = 0\n pub.publish(direction)\n\ndef analysis_callback(current_command):\n global speed\n speed = current_command.data[0];\n print(f\"current speed {speed}\")\n\nif __name__ == \"__main__\":\n # Initialize the node\n rospy.init_node('update', log_level=rospy.DEBUG)\n\n # Setup publisher\n pub = rospy.Publisher('/update',Bool,queue_size=10)\n\n # Setup subscriber\n tdoa_sub = rospy.Subscriber('/tdoa',Int32,tdoa_callback)\n\n analysis_sub = rospy.Subscriber('/analysis',UInt16MultiArray,analysis_callback)\n\n print(\"update node ready\")\n\n # Turn control over to ROS\n rospy.spin()\n","sub_path":"ws/src/sphero_communication/src/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"546754593","text":"# Sequência de Fibonacci\r\ntermos = int(input('Quantos termos você quer mostar?'))\r\nt1 = 0\r\nt2 = 1\r\ncont = 3\r\nprint('{} -> {}'.format(t1, t2), end='')\r\n\r\nwhile cont <= termos:\r\n t3 = t1 + t2\r\n print('-> {}'.format(t3), end='')\r\n t1 = t2\r\n t2 = t3\r\n cont += 1\r\nprint('-> FIM')\r\n","sub_path":"exercicios/exe063Sequência_fibonacci.py","file_name":"exe063Sequência_fibonacci.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"124783434","text":"'''\n@ self-driving-car-test.py\nProject Description:\n\nPlease manually move ahead. This program will only help\nthe user in turning left or right automatically,\naccording to the screen captured.\n\nControls: \n'up' arrow to move forward\n'left' arrow to turn left\n'right' arrow to turn right\n'down' arrow to move backward\n\nTo EXIT the program, press 'q' after clicking on the \"window\"\n OR\nTo EXIT the program, hover mouse at the below position:\n 1215<=X<=1365\n 0<=Y<=120\n\nPLEASE MANUALLY MOVE FORWARD.\n\n'''\n\nimport tensorflow as tf\n#from tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten\nimport numpy as np\nimport pyscreenshot as ImageGrab\nimport cv2\nimport time\nimport pyautogui\nimport subprocess #for running system commands in python\n\n\nfor i in list(range(4))[::-1]:\n print(i+1)\n time.sleep(1)\n\ndef roi(img, vertices):\n mask = np.zeros_like(img)\n cv2.fillPoly(mask, vertices, 255)\n masked = cv2.bitwise_and(img, mask)\n return masked\n\n\ndef process_img(original_image):\n processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)\n #processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300)\n vertices = np.array([[320,0],[640,50],[0,50]])\n processed_img = roi(processed_img, [vertices])\n return processed_img\n\n\n\nlast_time=time.time()\n\n\n## neural network model\n#mydata = #keras.datasets.fashion_mnist ## ---------------- ATTENTION PLEASE!!\n#(train_images, train_labels), (test_images, test_labels) = mydata.load_data()\nclass_names = ['nothing','left', 'right']\nimg_rows, img_cols = 50, 640\ninput_shape=(img_rows,img_cols,1)\nnClasses=3\nfile_weights='data/weights_self-driving-car.h5'\nprint(\"Model getting defined and compiled...\")\n\ndef createModel(input_shape,nClasses):\n model = Sequential()\n model.add(Conv2D(2, (3, 3), padding='same', activation='relu', input_shape=input_shape))\n model.add(Conv2D(2, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n \n model.add(Conv2D(4, (3, 3), padding='same', activation='relu'))\n model.add(Conv2D(4, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n \n model.add(Conv2D(4, (3, 3), padding='same', activation='relu'))\n model.add(Conv2D(4, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n \n model.add(Flatten())\n model.add(Dense(64, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(nClasses, activation='softmax'))\n \n return model\n\nmodel = createModel(input_shape,nClasses)\nmodel.compile(optimizer=tf.train.AdamOptimizer(), \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\nprint(\"Model got defined and compiled successfully\")\n\n# Restore the model's state\nprint(\"loading weights...\")\nmodel.load_weights(file_weights)\nprint(\"weights loaded successfully\")\n\n\n## program parameters\ncount=-1\n\n\nwhile(True):\n currentMouseX, currentMouseY = pyautogui.position()\n if(currentMouseX>=1215 and currentMouseX<=1365 and currentMouseY>=0 and currentMouseY<=120): ## EXIT the program\n break\n elif(currentMouseX>=65 and currentMouseX<=705 and currentMouseY>=50 and currentMouseY<=532):\n screen = np.array(ImageGrab.grab(bbox=(65+0,50+150,65+640,50+200)))\n \n new_screen = process_img(screen)\n \n print('Loop took {} seconds'.format(time.time()-last_time))\n last_time = time.time()\n \n '''\n cv2.namedWindow('window')\n cv2.moveWindow('window',706,1)\n cv2.imshow('window',new_screen)\n '''\n \n test_image = new_screen.copy()\n test_image = test_image/255.0\n \n test_images = np.array([test_image])\n test_images = test_images.reshape(test_images.shape[0], img_rows, img_cols, 1)\n #print(test_images.shape)\n predictions = model.predict(test_images)\n\n test_label_class = class_names[np.argmax(predictions[0])]\n\n \n pyautogui.click()\n count+=1\n if(count>=10 or count==0):\n pyautogui.keyDown('up')\n time.sleep(.5)\n pyautogui.keyUp('up')\n count=0\n\n if test_label_class == 'nothing':\n pass\n elif test_label_class == 'left':\n ## turn LEFT\n print('AI: Turned Left')\n pyautogui.keyDown('left')\n time.sleep(.5)\n pyautogui.keyUp('left')\n elif test_label_class == 'right':\n ## turn RIGHT\n print('AI: Turned Right')\n pyautogui.keyDown('right')\n time.sleep(.5)\n pyautogui.keyUp('right')\n\n\n '''\n ## TO EXIT THE PROGRAM, PRESS 'q'\n keypressed = cv2.waitKey(25) & 0xFF \n if(keypressed == ord('q')):\n cv2.destroyAllWindows()\n break\n '''","sub_path":"self-driving-car2/self-driving-car2-test.py","file_name":"self-driving-car2-test.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"153668414","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nThis is s Sanji Object\n\"\"\"\n\nimport inspect\nimport logging\nimport signal\nimport sys\nimport os\nimport threading\nimport re\nimport traceback\nimport six\nfrom random import random\nfrom threading import Event\nfrom threading import Thread\nfrom time import sleep\nfrom voluptuous import MultipleInvalid\n\nfrom sanji.message import Message\nfrom sanji.message import MessageType\nfrom sanji.publish import Publish\nfrom sanji.publish import Retry\nfrom sanji.router import Router\nfrom sanji.session import Session\nfrom sanji.session import TimeoutError\nfrom sanji.bundle import Bundle\n\ntry:\n from queue import Queue\n from queue import Full\nexcept ImportError:\n from Queue import Queue\n from Queue import Full\n\n_logger = logging.getLogger(\"sanji.sdk\")\n\n\nclass Sanji(object):\n \"\"\"\n This is for sanji framework.\n \"\"\"\n def __init__(self, *args, **kwargs):\n\n # Setup default options\n bundle = kwargs.get(\"bundle\", None)\n connection = kwargs.get(\"connection\", None)\n stop_event = kwargs.get(\"stop_event\", Event())\n\n if connection is None:\n raise ValueError(\"Connection is required.\")\n\n # Model-related\n bundle_dir = os.path.dirname(inspect.getfile(self.__class__))\n if bundle is None:\n bundle = Bundle(bundle_dir=bundle_dir)\n self.bundle = bundle\n self.stop_event = stop_event\n self.reg_thread = None\n self.reg_delay = lambda: random() * 5\n\n # Router-related (Dispatch)\n self.router = Router()\n self.dispatch_thread_count = 3\n self.thread_list = []\n\n # Response-related (Resolve)\n self._session = Session()\n self.resolve_thread_count = 1\n\n # Message Bus\n self._conn = connection\n self.is_ready = Event()\n self.req_queue = Queue()\n self.res_queue = Queue()\n\n # Setup callbacks\n self._conn.set_on_message(self.on_sanji_message)\n self._conn.set_on_connect(self.on_connect)\n self._conn.set_on_publish(self.on_publish)\n\n # Publisher\n self.publish = Publish(self._conn, self._session)\n\n # Register signal to call stop() (only mainthread could do this)\n if threading.current_thread().__class__.__name__ == '_MainThread':\n signal.signal(signal.SIGINT, self.exit)\n\n # Auto-register routes\n methods = inspect.getmembers(self, predicate=inspect.ismethod)\n self._register_routes(methods)\n\n # Custom init function\n if hasattr(self, 'init') and \\\n hasattr(self.init, '__call__'):\n _logger.debug(\"Custom init start\")\n self.init(*args, **kwargs)\n _logger.debug(\"Custom init finish\")\n\n def _register_routes(self, methods):\n \"\"\"\n _register_routes\n \"\"\"\n # setup routes by decorator\n methods = [(n, v) for (n, v) in methods if v.__name__ == \"wrapper\"]\n methods = sorted(methods, key=lambda x: x[1]._order)\n for name, value in methods:\n value() # execute setting route\n\n return methods\n\n def _dispatch_message(self):\n \"\"\"\n _dispatch_message\n \"\"\"\n while True:\n message = self.req_queue.get()\n if message is None:\n _logger.debug(\"_dispatch_message thread is terminated\")\n return\n\n if message._type != MessageType.EVENT:\n self.__dispatch_message(message)\n elif message._type == MessageType.EVENT:\n self.__dispatch_event_message(message)\n\n def __dispatch_event_message(self, message):\n results = self.router.dispatch(message)\n\n def ___dispatch(handler, message):\n args_len = len(inspect.getargspec(handler[\"callback\"]).args)\n if args_len == 2:\n handler[\"callback\"](self, result[\"message\"])\n\n try:\n for result in results: # same route\n data = map(lambda handler: ___dispatch(\n handler, result[\"message\"]),\n result[\"handlers\"])\n if not isinstance(data, list):\n list(data)\n except Exception as e:\n _logger.error(e, exc_info=True)\n\n def __dispatch_message(self, message):\n results = self.router.dispatch(message)\n # Request not found\n if len(results) == 0:\n error_msg = \"Route '%s' not found.\" % message.resource\n _logger.info(error_msg)\n _logger.debug(message.to_json())\n resp = self.publish.create_response(\n message, self.bundle.profile[\"name\"])\n resp(code=404, data={\"message\": error_msg})\n return\n\n def ___dispatch(handler, message, resp):\n if handler[\"schema\"] is not None:\n message.data = handler[\"schema\"](message.data)\n args_len = len(inspect.getargspec(handler[\"callback\"]).args)\n if args_len >= 3:\n handler[\"callback\"](self, result[\"message\"], resp)\n\n try:\n for result in results: # same route\n resp = self.publish.create_response(\n result[\"message\"], self.bundle.profile[\"name\"])\n data = map(lambda handler: ___dispatch(\n handler, result[\"message\"], resp\n ),\n result[\"handlers\"])\n if not isinstance(data, list):\n list(data)\n except Exception as e:\n _logger.error(e, exc_info=True)\n resp_data = {\"message\": \"Internal Error.\"}\n\n if os.getenv(\"SANJI_ENV\", 'debug') == 'debug':\n ex_type, ex, tb = sys.exc_info()\n resp_data[\"traceback\"] = \"\".join(traceback.format_tb(tb))\n\n resp = self.publish.create_response(\n message, self.bundle.profile[\"name\"])\n\n # if exception is belongs to schema error\n if isinstance(e, MultipleInvalid):\n return resp(code=400, data={\"message\": str(e)})\n\n return resp(code=500, data=resp_data)\n\n def _resolve_responses(self):\n \"\"\"\n _resolve_responses\n \"\"\"\n while True:\n message = self.res_queue.get()\n if message is None:\n _logger.debug(\"_resolve_responses thread is terminated\")\n return\n self.__resolve_responses(message)\n\n def __resolve_responses(self, message):\n session = self._session.resolve(message.id, message)\n if session is None:\n self.req_queue.put(message.to_event())\n\n def on_publish(self, client, userdata, mid):\n try:\n self._session.resolve_queue.put_nowait(mid)\n except Full:\n _logger.debug(\"on_publish can't push mid into queue\")\n\n def _create_thread_pool(self):\n\n def stop(queue):\n def _stop():\n queue.put(None)\n return _stop\n\n # create a thread pool\n for _ in range(0, self.dispatch_thread_count):\n thread = Thread(target=self._dispatch_message,\n name=\"thread-dispatch-%s\" % _)\n thread.daemon = True\n thread.start()\n self.thread_list.append((thread, stop(self.req_queue)))\n\n for _ in range(0, self.resolve_thread_count):\n thread = Thread(target=self._resolve_responses,\n name=\"thread-resolve-%s\" % _)\n thread.daemon = True\n thread.start()\n self.thread_list.append((thread, stop(self.res_queue)))\n\n _logger.debug(\"Thread pool is created\")\n\n def start(self):\n \"\"\"\n start\n \"\"\"\n def main_thread():\n # create resp, req thread pool\n self._create_thread_pool()\n # start connection, this will block until stop()\n self.conn_thread = Thread(target=self._conn.connect)\n self.conn_thread.daemon = True\n self.conn_thread.start()\n\n # register model to controller...\n self.is_ready.wait()\n\n if hasattr(self, 'run'):\n _logger.debug(\"Start running...\")\n self.run()\n\n # start main_thread\n self.main_thread = Thread(target=main_thread)\n self.main_thread.daemon = True\n self.main_thread.start()\n\n if threading.current_thread().__class__.__name__ == '_MainThread':\n # control this bundle stop or not\n while not self.stop_event.wait(1):\n sleep(1)\n else:\n self.stop_event.wait()\n\n self.stop()\n _logger.debug(\"Shutdown successfully\")\n\n def exit(self, signum=None, frame=None):\n \"\"\"\n hook ctrl + c to exit program\n \"\"\"\n self.stop()\n sys.exit(0)\n\n def stop(self, *args, **kwargs):\n \"\"\"\n exit\n \"\"\"\n _logger.debug(\"Bundle [%s] has been shutting down\" %\n self.bundle.profile[\"name\"])\n\n if hasattr(self, 'before_stop') and \\\n hasattr(self.before_stop, '__call__'):\n _logger.debug(\"Invoking before_stop...\")\n self.before_stop()\n\n self._conn.disconnect()\n self._session.stop()\n self.stop_event.set()\n\n # TODO: shutdown all threads\n for thread, stop in self.thread_list:\n stop()\n for thread, stop in self.thread_list:\n thread.join()\n self.is_ready.clear()\n\n def on_sanji_message(self, client, userdata, msg):\n \"\"\"This function will recevie all message from mqtt\n client\n the client instance for this callback\n userdata\n the private user data as set in Client() or userdata_set()\n message\n an instance of MQTTMessage. This is a class with members topic,\n payload, qos, retain.\n \"\"\"\n try:\n message = Message(msg.payload)\n except (TypeError, ValueError) as e:\n _logger.error(e, exc_info=True)\n return\n\n if message.type() == MessageType.UNKNOWN:\n _logger.debug(\"Got an UNKNOWN message, don't dispatch\")\n return\n\n if message.type() == MessageType.RESPONSE:\n self.res_queue.put(message)\n\n if message.type() == MessageType.REQUEST or \\\n message.type() == MessageType.DIRECT or \\\n message.type() == MessageType.HOOK or \\\n message.type() == MessageType.EVENT:\n self.req_queue.put(message)\n\n def on_connect(self, client, userdata, flags, rc):\n \"\"\"\n on_connect(self, client, obj, flags, rc):\n client\n the client instance for this callback\n userdata\n the private user data as set in Client() or userdata_set()\n flags\n response flags sent by the broker\n rc\n the connection result\n \"\"\"\n _logger.debug(\"Connection established with result code %s\" % rc)\n\n if self.reg_thread is not None and self.reg_thread.is_alive():\n _logger.debug(\"Joining previous reg_thread\")\n self.reg_thread.join()\n\n def reg():\n delay = None\n if hasattr(self.reg_delay, '__call__'):\n delay = self.reg_delay()\n else:\n delay = self.reg_delay\n\n sleep(delay)\n self._conn.set_tunnels(self._conn.tunnels)\n model_profile = self.get_profile(\"model\")\n view_profile = self.get_profile(\"view\")\n self.deregister(model_profile)\n self.deregister(view_profile)\n self.register(model_profile)\n self.register(view_profile)\n self.is_ready.set()\n\n self.reg_thread = Thread(target=reg)\n self.reg_thread.daemon = True\n self.reg_thread.start()\n\n def register(self, reg_data, retry=True, interval=1, timeout=3):\n \"\"\"\n register function\n retry\n True, infinity retries\n False, no retries\n Number, retries times\n interval\n time period for retry\n return\n False if no success\n Tunnel if success\n \"\"\"\n if len(reg_data[\"resources\"]) == 0:\n _logger.debug(\"%s no need to register due to no resources\" %\n (reg_data[\"name\"]))\n return\n\n def _register():\n try:\n resp = self.publish.direct.post(\n \"/controller/registration\", reg_data)\n if resp.code == 200:\n return resp\n except TimeoutError:\n _logger.debug(\"Register message is timeout\")\n\n return False\n\n resp = _register()\n while resp is False:\n _logger.debug(\"Register failed.\")\n self.deregister(reg_data)\n resp = _register()\n\n if resp is None:\n _logger.error(\"Can\\'t not register to controller\")\n self.stop()\n return False\n\n self._conn.set_tunnel(\n reg_data[\"role\"], resp.data[\"tunnel\"], self.on_sanji_message)\n self.bundle.profile[\"currentTunnels\"] = [\n tunnel for tunnel, callback in self._conn.tunnels.items()]\n self.bundle.profile[\"regCount\"] = \\\n self.bundle.profile.get(\"reg_count\", 0) + 1\n\n _logger.debug(\"Register successfully %s tunnel: %s\"\n % (reg_data[\"name\"], resp.data[\"tunnel\"],))\n\n def deregister(self, reg_data, retry=True, interval=1, timeout=3):\n \"\"\"\n Deregister model/view of this bundle\n \"\"\"\n Retry(target=self.publish.direct.delete,\n args=(\"/controller/registration\", reg_data,),\n kwargs={\"timeout\": timeout},\n options={\"retry\": retry, \"interval\": interval})\n _logger.debug(\"Deregister successfully %s tunnel: %s\" %\n (reg_data[\"name\"],\n self._conn.tunnels[reg_data[\"role\"]][0],))\n\n def get_profile(self, role=\"model\"):\n profile = dict((k, v) for k, v in self.bundle.profile.items())\n profile[\"tunnel\"] = self._conn.tunnels[\"internel\"][0]\n profile[\"resources\"] = []\n profile[\"role\"] = role\n profile[\"name\"] = \"%s%s\" % \\\n (profile[\"name\"], '' if role == self.bundle.profile[\"role\"]\n else '-' + role,)\n\n for _ in self.bundle.profile[\"resources\"]:\n if _.get(\"role\", self.bundle.profile[\"role\"]) != role:\n continue\n profile[\"resources\"].append(re.sub(r\":(\\w+)\", r\"+\", _[\"resource\"]))\n\n return profile\n\n\ndef Route(resource=None, methods=[\"get\", \"post\", \"put\", \"delete\"],\n schema=None):\n \"\"\"\n route\n \"\"\"\n def _route(func):\n def wrapper(self, *args, **kwargs):\n # \"test\" argument means no wrap func this time,\n # return original func immediately.\n if kwargs.get(\"test\", False):\n kwargs.pop(\"test\")\n func(self, *args, **kwargs)\n\n _methods = methods\n if isinstance(methods, str):\n _methods = [methods]\n route = self.router.route(resource)\n for method in _methods:\n getattr(route, method)(func, schema)\n # Ordered by declare sequence\n # http://stackoverflow.com/questions/4459531/how-to-read-class-attributes-in-the-same-order-as-declared\n f_locals = sys._getframe(1).f_locals\n _order = len([v for v in six.itervalues(f_locals)\n if hasattr(v, '__call__') and\n hasattr(v, '__name__') and\n v.__name__ == \"wrapper\"])\n wrapper.__dict__[\"_order\"] = _order\n return wrapper\n return _route\n","sub_path":"sanji/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":15868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"189505231","text":"import numpy as np\nfrom stl import mesh\n\n\"\"\"\nh(oogte)\nb(reedte)\nl(lengte)\n\nvoor 1 kant meerdere triangles maken\n\n## course\nh = 0.1\nb = 7\nl = 40\n\n## boat\nh = 0.05\nb = 0.6\nl = 6\n\n## blade\nh = 0.2\nb = 0.45\nl = 0.45\n\nIn vlak z = 0 meerdere triangles maken\nZijkanten ook meerd\nBovenkant 2\naanname l > b\nen brick minstens 0.5*0.5\n\"\"\"\nh = 0.05\nb = 0.45\nl = 0.45\n\n\nn = 2 * int(l/0.4)\nm = 2 * int(b/0.4)\nbdiff = b/m\nldiff = l/n\n\nprint(\"n m\", n, \" \", m, type(bdiff))\n\n# create vertices of base plane\nvertices = np.zeros(((n+1)*(m+1) + 4, 3))\nprint(\"vertices.shape \", vertices.shape, \"diff \", bdiff, ldiff)\nrow = 0\nfor i in range(m+1):\n for j in range(n+1):\n #print(j,i, \" \", row*n+j+row)\n vertices[row*n + j+row] = (j*ldiff, i*bdiff, 0)\n row += 1\n\n# now the other planes\nrestv = (n+1)*(m+1)\nvertices[restv] = (0, 0, h)\nvertices[restv+1] = (l, 0, h)\nvertices[restv+2] = (0, b, h)\nvertices[restv+3] = (l, b, h)\n\n# center brick on origin\nfor i in range(vertices.shape[0]):\n vertices[i] = (vertices[i, 0]-l/2, vertices[i, 1]-b/2, vertices[i, 2]-h/2)\n#print(vertices)\n\n# create faces base plane\n# make sure al facet normals are pointing outward\nfaces = np.zeros((2*n * m + 2*(n+1) + 2*(m+1) + 2, 3))\nrow = 0\nindex = 0\nfor i in range(0,m,2):\n for j in range(0,n,2):\n # fill a square of 2x2 vertices with 8 triangles\n startindex = row*(2*n+1) + j + row\n #print(\"(\", j, \", \", i, \") index:\", startindex)\n # face 1\n faces[index] = (startindex, startindex+n+1, startindex+n+2)\n index += 1\n # face 2\n faces[index] = (startindex, startindex+n+2, startindex+1)\n index += 1\n # face 3\n faces[index] = (startindex+2, startindex+1, startindex+n+2)\n index += 1\n # face 4\n faces[index] = (startindex+2, startindex+n+2, startindex+n+3)\n index += 1\n # face 5\n faces[index] = (startindex+2*(n+1), startindex+n+2, startindex+n+1)\n index += 1\n # face 6\n faces[index] = (startindex+2*(n+1), startindex+2*(n+1)+1, startindex+n+2)\n index += 1\n # face 7\n faces[index] = (startindex+2*(n+1)+1, startindex+2*(n+1)+2, startindex+n+2)\n index += 1\n # face 8\n faces[index] = (startindex+2*(n+1)+2, startindex+n+3, startindex+n+2)\n index += 1\n \n row += 1\n\n# now the other faces\n\n# side 1\nfaces[index] = (0, restv+1, restv)\nfor i in range(n):\n faces[index+1+i] = (n-1-i, n-i, restv+1) # divide into faces n to avoid simbody restriction\n #print(\"f \", n-1-i, n-i, restv+1)\n\n# side 2\nindex = index+n+1\nfaces[index] = (n, restv+3, restv+1)\nfor i in range(m):\n faces[index+1+i] = (n+i*(n+1), n+(i+1)*(n+1), restv+3)\n #print(\"f2 \", n+i*(n+1), n+(i+1)*(n+1), restv+3)\n\n# side 3\nindex = index+m+1\nfaces[index] = (restv+2, restv+3, (n+1)*(m))\nprint(\"fff \", restv+2, restv+3, (n+1)*(m))\nfor i in range(n):\n faces[index+1+i] = ((n+1)*(m+1)-1-i, (n+1)*(m+1)-2-i, restv+3)\n #print(\"f3 \", (n+1)*(m+1)-i, (n+1)*(m+1)-1-i, restv+3)\n\n# side 4\nindex = index+n+1\nfaces[index] = (0, restv, restv+2)\nfor i in range(m):\n faces[index+1+i] = (restv+2, (n+1)*(m-i), (n+1)*(m-i-1))\n #print(\"f4 \", restv+2, (n+1)*(m), (n+1)*(m-i-1))\n\n# side above\nindex = index+m+1\nprint(faces.shape, index)\nfaces[index] = (restv, restv+1, restv+3)\nfaces[index+1] = (restv, restv+3, restv+2)\n\n\n#print(faces.astype(int))\nprint(\"onder, iedere zijkant, bovenkant: \", 2*n * m, 2*n+2, 2*m+2, 2)\n\n\n\"\"\"\nvertices = np.array([\\\n [0, 0, 0],\n [l, 0, 0],\n [l, b, 0],\n [0, b, 0],\n\n # knooppunten andere kant\n [0, 0, h],\n [l, 0, h],\n [l, b, h],\n [0, b, h]])\n\n\n\n# Define the 12 triangles composing the cube\nfaces = np.array([\\\n [0,3,1],\n [1,3,2],\n [0,4,7],\n [0,7,3],\n [4,5,6],\n [4,6,7],\n [5,1,2],\n [5,2,6],\n [2,3,6],\n [3,7,6],\n [0,1,5],\n [0,5,4]])\n\"\"\"\n\n# Create the mesh\nbrick = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))\nfor i, f in enumerate(faces):\n for j in range(3):\n brick.vectors[i][j] = vertices[int(f[j]), :]\n\nbrick.save('brick.stl')\n","sub_path":"Pusher/brick.py","file_name":"brick.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"40177125","text":"#!/usr/bin/env python3\n# Author: TG ; Created: June 2018\n#\n# Tool to download dictionary items from ISI's dictionary server\n#\nimport sys\nimport requests as req # pip install requests ## if requests library is missing\nimport argparse\nimport logging as log\nlog.basicConfig(level=log.INFO)\n\nbase_url = \"http://holst.isi.edu:8983/solr/dict/query?q=type:lexicon&fq=group:%s/%s&wt=json&fl=l1,l2,w1,w2\"\n\n\ndef get_lexicons(l1, l2, start=0, rows=5000):\n log.info('Going to download lexicons for %s -> %s' % (l1, l2))\n url = base_url % (l1, l2)\n end = start +1\n while start <= end:\n this_url = '%s&start=%d&rows=%d' % (url, start, rows)\n log.info('Start = %s, total = %d ' % (start, end))\n log.info('url = %s' % this_url)\n data = req.get(this_url).json()['response']\n for d in data['docs']:\n for w2 in d['w2']:\n for w3 in w2.split(','):\n if w3:\n yield d['w1'], w3\n start += rows\n end = data['numFound']\n\nif __name__ == '__main__':\n p = argparse.ArgumentParser(description='Download lexicons from dictionary server',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n p.add_argument('-l1', default='en*', type=str, help='From language. Example: en, or en*')\n p.add_argument('-l2', default='el*', type=str, help='To language. Example: el, or el*')\n p.add_argument('-s', '--start', default=0, type=int, help='start from index')\n p.add_argument('-r', '--rows', default=1000, type=int, help='batch size, i.e. \"rows\" parameter of solr')\n \n p.add_argument('-o', '--out', default=sys.stdout, type=argparse.FileType('w'),\n help='Path to output file. if not provided, STDOUT is used')\n args = vars(p.parse_args())\n out = args.pop('out')\n\n def clean(w):\n ### More cleaning, if anything needed\n return w.strip()\n\n for w1, w2 in get_lexicons(**args):\n w1, w2 = clean(w1), clean(w2)\n if w1 and w2:\n out.write('%s\\t%s\\n' % (w1, w2))\n","sub_path":"get_lexicons.py","file_name":"get_lexicons.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"2071466","text":"\n# coding: utf-8\n\n# In[1]:\n#pycrypto==2.6.1 !important, the method might change between versions\nimport Crypto #important\nfrom Crypto.Cipher import AES\nimport hashlib\nimport getpass\nimport os\nimport random\nimport base64\nimport sys\nfrom Crypto.PublicKey import RSA\n\nimport time\ntime.clock = time.process_time\n\n# In[2]:\nkey_name = 'pandora_private_key.pem'\npath = sys.argv[1]\nprivate_key_location = os.path.join(path, key_name)\naes_key = getpass.getpass('AES Key: ').encode('utf-8')\nf = open(private_key_location,'r')\nprivate = f.read()\nf.close()\nf = open('pandora.data','r')\npw_list = f.read().splitlines()\nf.close()\n\n\n# In[12]:\n\ndef decode(private,aes_key,pw_list):\n private_key = RSA.importKey(private)\n md = hashlib.md5()\n md.update(aes_key)\n aes_string = md.digest()\n obj = AES.new(aes_string)\n pandora = []\n for string in pw_list:\n account = private_key.decrypt(obj.decrypt(base64.b64decode(string.split('\\t')[0])))\n login = private_key.decrypt(obj.decrypt(base64.b64decode(string.split('\\t')[1])))\n pandora.append([account,login])\n return pandora\n\n\n# In[16]:\n\npandora = decode(private,aes_key,pw_list)\nprint(\"!!Warning!! Pandora is opened\")\npandora.sort(key=lambda x: x[0])\n\nwhile(1):\n opt = input(\"save or print: \")\n if opt == 'save':\n print(\"saved to the same dirctory with private key. !!Delete after viewing!!\")\n f=open('/'.join(private_key_location.split('/')[0:(len(private_key_location.split('/'))-1)])+'/pandora-opened.txt','w')\n for i in pandora:\n f.write(\"\"\"%s,%s\\n\"\"\"%(i[0],i[1]))\n f.close()\n break\n elif opt == 'print':\n for i in pandora:\n print(i)\n break\n\n","sub_path":"Pandora-Decrypt.py","file_name":"Pandora-Decrypt.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"209401683","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\nimport re\nfrom .entity import Node, EResult\n\n\nclass InstAPI:\n class SearchBy:\n Tag = 1\n ProfileName = 2\n\n def __init__(self, search_by, name):\n self.__searchBy = search_by\n self.__searchText = name.strip()\n self.__is_initial_request = True\n\n # Check if search query is an empty string\n if len(self.__searchText) < 1:\n raise ValueError('Search query can not be an empty string!')\n\n if self.__searchBy is not InstAPI.SearchBy.Tag \\\n and self.__searchBy is not InstAPI.SearchBy.ProfileName:\n raise ValueError('Invalid SearchBy type!')\n\n @staticmethod\n def __get_content_url(search_by, search_query):\n url = None\n # Generate destination url for different types of search query\n if search_by == InstAPI.SearchBy.ProfileName:\n url = \"https://www.instagram.com/\" + search_query + \"/\"\n elif search_by == InstAPI.SearchBy.Tag:\n url = \"https://www.instagram.com/explore/tags/\" + search_query + \"/\"\n\n return url\n\n @staticmethod\n def __get_request_headers(url):\n return {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',\n 'referer': url,\n 'origin': 'https://www.instagram.com',\n 'content-type': 'application/x-www-form-urlencoded'\n }\n\n @staticmethod\n def __get_request_data(search_by, search, after, nrecords):\n data_tag = 'q=ig_hashtag({SEARCH}){media.after({AFTER},{ID}){count,nodes{caption,code,comments{count},comments_disabled,date,dimensions{height,width},display_src,id,is_video,likes{count},owner{id},thumbnail_src,video_views,video_url},page_info}}&ref=tags::show&query_id='\n data_profile = 'q=ig_user({SEARCH}){media.after({AFTER},{ID}){count,nodes{caption,code,comments{count},comments_disabled,date,dimensions{height,width},display_src,id,is_video,likes{count},owner{id},thumbnail_src,video_views,video_url},page_info}}&ref=users::show&query_id='\n\n result = None\n if search_by == InstAPI.SearchBy.Tag:\n result = data_tag\n elif search_by == InstAPI.SearchBy.ProfileName:\n result = data_profile\n\n return result\\\n .replace('{SEARCH}', search)\\\n .replace('{AFTER', after)\\\n .replace('{ID}', str(nrecords))\n\n @staticmethod\n def __get_extra_info_by_post_url(url):\n headers = InstAPI.__get_request_headers(url)\n\n with requests.Session() as s:\n for key in headers.keys():\n s.headers.update({key: headers[key]})\n resp = s.get(url)\n raw_content = resp.content\n\n dom = BeautifulSoup(raw_content, \"html.parser\")\n html_property_video_url = dom.find('meta', {'property': 'og:video'})\n html_property_secure_video_url = dom.find('meta', {'property': 'og:video:secure_url'})\n\n html_property_owner = None\n content_dom = dom.findAll('script', {'type': 'text/javascript'})\n for item in content_dom:\n if str(item.text).startswith('window._sharedData'):\n data_json = json.loads(re.search(r'^\\s*window\\._sharedData\\s*=\\s*({.*?})\\s*;\\s*$', item.text, flags=re.DOTALL | re.MULTILINE).groups(1)[0])\n html_property_owner = data_json['entry_data']['PostPage'][0]['media']['owner']\n break\n\n return {\n 'video_url': html_property_video_url.attrs['content'] if html_property_video_url is not None and 'content' in html_property_video_url.attrs else None,\n 'video_url_secure': html_property_secure_video_url.attrs['content'] if html_property_secure_video_url is not None and 'content' in html_property_secure_video_url.attrs else None,\n 'owner': html_property_owner\n }\n\n def __get_request_by_url(self):\n \"\"\"\n Retrieves the response from an url.\n :param url: destination url address\n :return: source code\n \"\"\"\n url = InstAPI.__get_content_url(self.__searchBy, self.__searchText)\n headers = InstAPI.__get_request_headers(url)\n\n if self.__is_initial_request:\n with requests.Session() as s:\n for key in headers.keys():\n s.headers.update({key: headers[key]})\n resp = s.get(url)\n return resp.content\n else:\n data = InstAPI.__get_request_data(self.__searchBy, self.__searchText, 'J0HWCI7VQAAAF0HWCI6swAAAFiYA', 6)\n return requests.post(url, data=data, headers=headers)\n\n def __get_content(self):\n raw_content = self.__get_request_by_url()\n return BeautifulSoup(raw_content, \"html.parser\")\n\n def content(self):\n data_media = None\n data_top = None\n\n dom = self.__get_content()\n if self.__is_initial_request:\n content_dom = dom.findAll('script', {'type': 'text/javascript'})\n for item in content_dom:\n if str(item.text).startswith('window._sharedData'):\n data_json = json.loads(re.search(r'^\\s*window\\._sharedData\\s*=\\s*({.*?})\\s*;\\s*$', item.text, flags=re.DOTALL | re.MULTILINE).groups(1)[0])\n if self.__searchBy == InstAPI.SearchBy.Tag:\n data_media = data_json['entry_data']['TagPage'][0]['tag']['media']['nodes']\n data_top = data_json['entry_data']['TagPage'][0]['tag']['top_posts']['nodes']\n elif self.__searchBy == InstAPI.SearchBy.ProfileName:\n data_media = data_json['entry_data']['ProfilePage'][0]['user']['media']['nodes']\n data_top = []\n break\n else:\n pass\n\n result_last = [Node(entry, InstAPI.__get_extra_info_by_post_url) for entry in data_media]\n result_top = [Node(entry, InstAPI.__get_extra_info_by_post_url) for entry in data_top]\n\n return EResult(result_top, result_last)\n\n\n","sub_path":"instapi/InstAPI.py","file_name":"InstAPI.py","file_ext":"py","file_size_in_byte":6143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"160915205","text":"\"\"\"\nhttps://www.codewars.com/kata/range-extraction/train/python\n\n\"\"\"\n\n\ndef solution(args):\n count, start, end = 0, 0, 0\n result = \"\"\n for i in range(len(args) - 1): # We're looking for one element further\n if args[i + 1] - args[i] == 1:\n count += 1\n else: # If numbers are not adjacent do smth based on gathered info\n if count > 1: # Interval detected\n result += str(start) + \"-\" + str(end) + \",\"\n elif count == 1: # Only two adjacent numbers. That's not interval\n result += str(args[i - 1]) + \",\"\n result += str(args[i]) + \",\"\n elif count == 0: # Standalone number\n result += str(args[i]) + \",\"\n count, start, end = 0, 0, 0 # Reset\n if count == 1: # Point on possible start of the interval\n start = args[i]\n elif count > 1: # Point on possible end of the interval\n end = args[i + 1]\n # Finalizing result when out of the loop\n if start != 0 and end != 0: # Start and end were pointed before exiting the loop\n result += str(start) + \"-\" + str(end)\n elif start != 0 and end == 0: # Only start was pointed\n result += str(args[i]) + \",\" + str(args[i + 1])\n else: # Processing the last element of the args\n result += str(args[i + 1])\n return result\n\n\nb = [17,18,19,20,24,26]\na = [-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20,24,26]\nprint(solution(a))\n\n","sub_path":"test/codewars/4_kyu_Range_Extraction.py","file_name":"4_kyu_Range_Extraction.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"89672883","text":"import json, sys, copy\nif __name__ == '__main__':\n sys.path.append(\"..\")\nimport globals\n\n# ErzaEncoder uses json format. Why? Easy to read and opensource.\n\nclass DataFile(object):\n _filename = None\n data = {}\n \n def __init__(self, filename = None):\n if filename:\n self.open(filename)\n pass\n\n def open(self, filename):\n if filename:\n self._filename = globals.path(filename)\n try:\n self.__dict__ = json.load(open(self._filename, 'r+'))\n except:\n return None\n\n def save(self, filename = None):\n if filename:\n self._filename = globals.path(filename)\n \n data_to_save = copy.deepcopy(self.__dict__)\n if '_filename' in data_to_save:\n del data_to_save['_filename']\n json.dump(data_to_save, open(self._filename,'wb+'))\n\n \nif __name__ == \"__main__\":\n # This is automatically done by erzaencoder\n globals.dir = '..'\n # Code starts here!\n f = DataFile('data/settings.json')\n f.property = \"I am the value!\"\n f.save()\n","sub_path":"erza/DataFile.py","file_name":"DataFile.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"620239673","text":"import os\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\nENABLED = False\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\nEMAIL_DONT_REPLY = 'dont-replay@kristelle.me'\nPROJECT_DIR = os.path.abspath(os.path.dirname(__file__))\n\nMANAGERS = (\n ('Test Manager', 'manager@kristelle.me'),\n)\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': os.path.join(PROJECT_DIR, 'kristelle.db'), # Or path to database file if using sqlite3.\n 'USER': '', # Not used with sqlite3.\n 'PASSWORD': '', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n }\n}\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en'\n\ngettext = lambda s: s\nLANGUAGES = (\n ('en', gettext('English')),\n ('ru', gettext('Russian')),\n)\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale\nUSE_L10N = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = '/media/'\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\nSTATIC_ROOT = os.path.join(PROJECT_DIR, 'static0')\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = '/static/'\n\n# URL prefix for admin static files -- CSS, JavaScript and images.\n# Make sure to use a trailing slash.\n# Examples: \"http://foo.com/static/admin/\", \"/static/admin/\".\nADMIN_MEDIA_PREFIX = STATIC_URL + 'grappelli/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(PROJECT_DIR, 'static'),\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'w2xn2ji(vz_fk+z_$+#4c8t-0_36x10q+^j3e5_1byt#gh40%d'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n # default template context processors\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n # required by django-admin-tools\n 'django.core.context_processors.request',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',\n 'middleware.multilingual.MultilingualURLMiddleware',\n)\n\nROOT_URLCONF = 'kristelle_django.urls'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(PROJECT_DIR, 'templates'),\n)\n\nINSTALLED_APPS = (\n 'grappelli',\n 'filebrowser',\n\n 'admin_tools',\n 'admin_tools.theming',\n 'admin_tools.menu',\n 'admin_tools.dashboard',\n\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n# 'django.contrib.flatpages',\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n# 'staticfiles',\n\n 'navigation',\n 'nani',\n 'news',\n 'wall',\n 'biography',\n 'music',\n 'photos',\n 'videos',\n 'contacts',\n 'tinymce',\n 'config4u',\n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\nTINYMCE_FILEBROWSER = True\nTINYMCE_DEFAULT_CONFIG = {\n 'plugins': \"paste,media\",\n #'plugins': \"autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template\",\n 'theme': \"simple\",\n 'theme_advanced_buttons1': \"bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect\",\n 'theme_advanced_buttons2': \"cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,code\",\n 'theme_advanced_buttons3' : \"tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,|,media\",\n 'theme_advanced_toolbar_location' : \"top\",\n 'theme_advanced_toolbar_align' : \"left\",\n 'theme_advanced_resizing' : 'true',\n 'extended_valid_elements': \"object[width|height|classid|codebase],param[name|value],embed[src|type|width|height|flashvars|wmode]\",\n}\n#FILEBROWSER_URL_TINYMCE = STATIC_URL + \"tinymce/jscripts/tiny_mce/\"\n#FILEBROWSER_PATH_TINYMCE = STATIC_URL + \"tinymce/jscripts/tiny_mce/\"\nFILEBROWSER_EXTENSIONS = {\n# 'Folder':[''],\n 'Image':['.jpg', '.jpeg', '.png'],\n 'Video':['.mpeg','.mpg','.flv'],\n# 'Document':['.pdf','.doc','.rtf','.txt','.xls','.csv'],\n 'Sound':['.mp3','.mp4',],\n 'Archive': ['.zip', '.rar', '.arj', '.gz', '.tar'],\n}\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"221986226","text":"import matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nimport numpy as np\n\nplt.rcParams.update({\n \"lines.color\": \"white\",\n \"patch.edgecolor\": \"white\",\n \"text.color\": \"white\",\n \"axes.facecolor\": \"white\",\n \"axes.edgecolor\": \"lightgray\",\n \"axes.labelcolor\": \"white\",\n \"xtick.color\": \"white\",\n \"ytick.color\": \"white\",\n \"grid.color\": \"darkgrey\",\n \"figure.facecolor\": \"black\",\n \"figure.edgecolor\": \"black\",\n \"savefig.facecolor\": \"black\",\n \"savefig.edgecolor\": \"black\"})\n\nfig = plt.figure()\n\n# use pandas to clean this mess up if you have some spare time\n\n# list of strings\ntimesstrings = [line.rstrip('\\n') for line in open('results.txt')]\n# array of strings\ntimesstringarray = np.asarray(timesstrings)\n# array of floats\ntimesarray = [float(numeric_string) for numeric_string in timesstringarray]\n\n\nfilteredarray = [x for x in timesarray if x < 1.0 ] \n\nitterations = len(filteredarray)\n\nbinitter = itterations / 10\n\nn, bins, patches = plt.hist(filteredarray, bins=int(binitter), density=1, alpha=0.75)\navaragetime = sum(filteredarray) / float(len(filteredarray))\n\nprint(\"average gRPC time is \", avaragetime)\n\nplt.xlabel(\"time (miliseconds)\")\n\nplt.title(\"gRPC\")\n\nplt.axis([0, 1, 0, 10])\n\nplt.grid()\n\nplt.show()","sub_path":"GraphQLvsgRPC/gRPC/plotfile.py","file_name":"plotfile.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"132079671","text":"\"\"\"\nmock<Models.py\nThis is a version of models.py contains versions of the classes\ndefined in models.py to be used in tests. The attributes defined\nouside of the class functions will be removed and replaced with \nthe same code in each class. The method will be copied and pasted\ndirectly from the models.py versions (with 1 line added to the\nconstructor for each class initializing id to None). The id attribute\nis meant to serve as a flag. Instances of a class that are not added\nto the _db_dict property will have an id of None. Adding will set the\nid to an integer value.\n\nNOTES:\nThis assumes all the mocked classes are meant to be databases and\nhave an id as the primary key that is automatically assigned.\n\"\"\"\nimport os, sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport models\nfrom models import AuthUserType\nfrom models import GenerateCharacterPin\nfrom models import ROOM_PASSWORD_LENGTH\n\nclass Messages:\n # THIS PART IS NEW FOR THE MOCKED CLASS\n _db_dict = {}\n _id = 0\n \n def get_db(self):\n return type(self)._db_dict\n \n db_dict = property(get_db)\n\n def add(self, id = None):\n if self.id == None:\n if id == None or not isinstance(id, int):\n self.id = type(self)._id\n type(self)._id += 1\n else:\n self.id = id\n type(self)._id = max(id + 1, type(self)._id)\n type(self)._db_dict[self.id] = self\n \n def remove(self):\n if self.id in type(self)._db_dict:\n type(self)._db_dict.pop(self.id)\n self.id = None\n\n @staticmethod\n def reset_mock_database():\n Messages._db_dict = {}\n Messages._id = 0\n\n # THIS PART IS COPIED AND PASTED FROM MODELS.PY (adding one line to __init__ for self.id)\n def __init__(self, user, message):\n self.sid = user[\"sid\"]\n self.username = user[\"username\"]\n self.room = user[\"room\"]\n self.picUrl = user['picUrl']\n self.message = message\n self.id = None\n\n def __repr__(self):\n return {\n \"name\": self.username,\n \"sid\": self.sid,\n \"room\": self.room,\n \"picUrl\": self.picUrl,\n \"message\": self.message,\n }\n\nclass AuthUser:\n # THIS PART IS NEW FOR THE MOCKED CLASS\n _db_dict = {}\n _id = 0\n \n def get_db(self):\n return type(self)._db_dict\n \n db_dict = property(get_db)\n\n def add(self, id = None):\n if self.id == None:\n if id == None or not isinstance(id, int):\n self.id = type(self)._id\n type(self)._id += 1\n else:\n self.id = id\n type(self)._id = max(id + 1, type(self)._id)\n type(self)._db_dict[self.id] = self\n \n def remove(self):\n if self.id in type(self)._db_dict:\n type(self)._db_dict.pop(self.id)\n self.id = None\n\n @staticmethod\n def reset_mock_database():\n AuthUser._db_dict = {}\n AuthUser._id = 0\n\n # THIS PART IS COPIED AND PASTED FROM MODELS.PY (adding one line to __init__ for self.id)\n def __init__(self, auth_type, name, email, pic=''): \n assert type(auth_type) is AuthUserType\n self.auth_type = auth_type.value\n self.username = name\n self.email = email\n self.picUrl = pic\n self.id = None\n\nclass Rooms:\n # THIS PART IS NEW FOR THE MOCKED CLASS\n _db_dict = {}\n _id = 0\n \n def get_db(self):\n return type(self)._db_dict\n \n db_dict = property(get_db)\n\n def add(self, id = None):\n if self.id == None:\n if id == None or not isinstance(id, int):\n self.id = type(self)._id\n type(self)._id += 1\n else:\n self.id = id\n type(self)._id = max(id + 1, type(self)._id)\n type(self)._db_dict[self.id] = self\n \n def remove(self):\n if self.id in type(self)._db_dict:\n type(self)._db_dict.pop(self.id)\n self.id = None\n\n @staticmethod\n def reset_mock_database():\n Rooms._db_dict = {}\n Rooms._id = 0\n\n # THIS PART IS COPIED AND PASTED FROM MODELS.PY (adding one line to __init__ for self.id)\n def __init__(self, roomCreator, roomName, roomPassword=None):\n self.creator = roomCreator\n self.name = roomName\n if roomPassword:\n self.password = roomPassword\n else:\n self.password = GenerateCharacterPin(ROOM_PASSWORD_LENGTH)\n self.id = None\n \n def __repr__(self):\n return \"{} (id: {} password: {}), created by {}\".format(self.name, self.id, self.password, self.creator)\n\nclass Flashcards:\n # THIS PART IS NEW FOR THE MOCKED CLASS\n _db_dict = {}\n _id = 0\n \n def get_db(self):\n return type(self)._db_dict\n \n db_dict = property(get_db)\n\n def add(self, id = None):\n if self.id == None:\n if id == None or not isinstance(id, int):\n self.id = type(self)._id\n type(self)._id += 1\n else:\n self.id = id\n type(self)._id = max(id + 1, type(self)._id)\n type(self)._db_dict[self.id] = self\n \n def remove(self):\n if self.id in type(self)._db_dict:\n type(self)._db_dict.pop(self.id)\n self.id = None\n\n @staticmethod\n def reset_mock_database():\n Flashcards._db_dict = {}\n Flashcards._id = 0\n\n # THIS PART IS COPIED AND PASTED FROM MODELS.PY (adding one line to __init__ for self.id)\n def __init__(self, question, answer, room):\n self.answer = answer\n self.question = question\n self.room = room\n self.id = None\n\n def __repr__(self):\n return \"{} {} {}\".format(self.question, self.answer, self.room)\n\nclass CurrentConnections:\n # THIS PART IS NEW FOR THE MOCKED CLASS\n _db_dict = {}\n _id = 0\n \n def get_db(self):\n return type(self)._db_dict\n \n db_dict = property(get_db)\n\n def add(self, id = None):\n if self.id == None:\n if id == None or not isinstance(id, int):\n self.id = type(self)._id\n type(self)._id += 1\n else:\n self.id = id\n type(self)._id = max(id + 1, type(self)._id)\n type(self)._db_dict[self.id] = self\n \n def remove(self):\n if self.id in type(self)._db_dict:\n type(self)._db_dict.pop(self.id)\n self.id = None\n\n @staticmethod\n def reset_mock_database():\n CurrentConnections._db_dict = {}\n CurrentConnections._id = 0\n\n # THIS PART IS COPIED AND PASTED FROM MODELS.PY (adding one line to __init__ for self.id)\n def __init__(self, sid, user):\n self.sid = sid\n self.user = user\n self.id = None\n\n def __repr__(self):\n return(\"(id: {}, sid: {}, user_id: {})\".format(self.id, self.sid, self.user))\n\nclass EnteredRooms:\n # THIS PART IS NEW FOR THE MOCKED CLASS\n _db_dict = {}\n _id = 0\n \n def get_db(self):\n return type(self)._db_dict\n \n db_dict = property(get_db)\n\n def add(self, id = None):\n if self.id == None:\n if id == None or not isinstance(id, int):\n self.id = type(self)._id\n type(self)._id += 1\n else:\n self.id = id\n type(self)._id = max(id + 1, type(self)._id)\n type(self)._db_dict[self.id] = self\n \n def remove(self):\n if self.id in type(self)._db_dict:\n type(self)._db_dict.pop(self.id)\n self.id = None\n\n @staticmethod\n def reset_mock_database():\n EnteredRooms._db_dict = {}\n EnteredRooms._id = 0\n\n # THIS PART IS COPIED AND PASTED FROM MODELS.PY (adding one line to __init__ for self.id)\n def __init__(self, user, room):\n self.user = user\n self.room = room\n self.id = None\n","sub_path":"tests/mockModels.py","file_name":"mockModels.py","file_ext":"py","file_size_in_byte":7995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"144349670","text":"import random\r\n\r\ndef game():\r\n random_number = [random.randint(0, 9) for n in range(4)]\r\n print(\"Solution:\", random_number)\r\n\r\n\r\n while True:\r\n guess = [int(i) for i in str(input(\"Please guess a 4-digit number: \"))]\r\n\r\n if guess == random_number:\r\n print(\"-----Congratulations! You have won the game!-----\")\r\n break\r\n\r\n else:\r\n cow = 0\r\n bull = 0\r\n\r\n for i in range(4):\r\n if guess[i] == random_number[i]:\r\n bull += 1\r\n\r\n elif guess[i] in random_number:\r\n cow += 1\r\n\r\n print(bull, \"A (Bulls) \", cow, \"B(Cows)\")\r\n\r\n\r\ngame()\r\n","sub_path":"Year 1 Sem 1/MOD 5.py","file_name":"MOD 5.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"371613219","text":"import datetime\nimport traceback\nfrom collections import deque\nfrom itertools import islice\nfrom random import shuffle\n\nfrom .utils import get_header\nfrom .entry import URLPlaylistEntry\nfrom .exceptions import ExtractionError, WrongEntryTypeError\nfrom .lib.event_emitter import EventEmitter\n\n\nclass Playlist(EventEmitter):\n \"\"\"\n A playlist is manages the list of songs that will be played.\n \"\"\"\n\n def __init__(self, bot):\n super().__init__()\n self.bot = bot\n self.loop = bot.loop\n self.downloader = bot.downloader\n self.entries = deque()\n self.bucket_mode = False\n self.bucket_size = 1\n self.bucket_marks = [0]\n self.current_bucket = []\n self.last_queued = None\n\n def __iter__(self):\n return iter(self.entries)\n\n def shuffle(self):\n shuffle(self.entries)\n\n def clear(self):\n self.entries.clear()\n self.bucket_marks = [0]\n self.current_bucket = []\n self.last_queued = None\n\n def toggle_buckets(self):\n self.bucket_mode = not self.bucket_mode\n if self.bucket_mode:\n self.current_bucket = []\n self.bucket_marks = [0]\n temp_last_queued = self.last_queued\n\n backup_deque = self.entries\n self.entries = deque()\n for song in backup_deque:\n self._add_entry(song)\n self.last_queued = temp_last_queued\n\n return \"Bucket mode activated: sorting queue into buckets. Bucket size is {}\".format(self.bucket_size)\n else:\n self.bucket_marks = [0]\n self.current_bucket = []\n\n return \"Bucket mode deactivated.\"\n\n def remove_last(self):\n for val, song in enumerate(self.entries):\n if self.last_queued == song:\n return self.remove(val + 1)\n return \"No song found to remove.\"\n\n def remove(self, index):\n try:\n if int(index) > len(self.entries) or int(index) < 1:\n return \"Invalid range on command. Please enter a number that is in the queue.\"\n titlestr = self.entries[int(index)-1].title\n self.entries.remove(self.entries[int(index)-1])\n if self.bucket_mode:\n for val, marker in enumerate(self.bucket_marks):\n if int(index) <= marker:\n self.bucket_marks[val] -= 1\n self.cleanup_markers()\n return \"Removed %s!\" % (titlestr)\n except (ValueError, TypeError) as e:\n count = 0\n toremove = []\n for val, song in enumerate(self.entries):\n if isinstance(e, ValueError):\n if index.lower() in song.title.lower():\n toremove.append(song)\n count += 1\n if self.bucket_mode:\n for val, marker in enumerate(self.bucket_marks):\n if val < marker:\n self.bucket_marks[val] -= 1\n self.cleanup_markers()\n else:\n if index == song.meta.get('author', False):\n toremove.append(song)\n count += 1\n if self.bucket_mode:\n for val, marker in enumerate(self.bucket_marks):\n if val < marker:\n self.bucket_marks[val] -= 1\n self.cleanup_markers()\n for song in toremove:\n self.entries.remove(song)\n return \"%d songs removed from queue\" % (count)\n\n def cleanup_markers(self):\n seen = set()\n seen_add = seen.add\n print(\"{}, {}\".format(seen, self.bucket_marks))\n self.bucket_marks = [x for x in self.bucket_marks if not (x in seen or seen_add(x))]\n\n async def add_entry(self, song_url, **meta):\n \"\"\"\n Validates and adds a song_url to be played. This does not start the download of the song.\n\n Returns the entry & the position it is in the queue.\n\n :param song_url: The song url to add to the playlist.\n :param meta: Any additional metadata to add to the playlist entry.\n \"\"\"\n\n try:\n info = await self.downloader.extract_info(self.loop, song_url, download=False)\n except Exception as e:\n raise ExtractionError('Could not extract information from {}\\n\\n{}'.format(song_url, e))\n\n if not info:\n raise ExtractionError('Could not extract information from %s' % song_url)\n\n # TODO: Sort out what happens next when this happens\n if info.get('_type', None) == 'playlist':\n raise WrongEntryTypeError(\"This is a playlist.\", True, info.get('webpage_url', None) or info.get('url', None))\n\n if info['extractor'] in ['generic', 'Dropbox']:\n try:\n # unfortunately this is literally broken\n # https://github.com/KeepSafe/aiohttp/issues/758\n # https://github.com/KeepSafe/aiohttp/issues/852\n content_type = await get_header(self.bot.aiosession, info['url'], 'CONTENT-TYPE')\n print(\"Got content type\", content_type)\n\n except Exception as e:\n print(\"[Warning] Failed to get content type for url %s (%s)\" % (song_url, e))\n content_type = None\n\n if content_type:\n if content_type.startswith(('application/', 'image/')):\n if '/ogg' not in content_type: # How does a server say `application/ogg` what the actual fuck\n raise ExtractionError(\"Invalid content type \\\"%s\\\" for url %s\" % (content_type, song_url))\n\n elif not content_type.startswith(('audio/', 'video/')):\n print(\"[Warning] Questionable content type \\\"%s\\\" for url %s\" % (content_type, song_url))\n\n entry = URLPlaylistEntry(\n self,\n song_url,\n info.get('title', 'Untitled'),\n info.get('duration', 0) or 0,\n self.downloader.ytdl.prepare_filename(info),\n **meta\n )\n self._add_entry(entry)\n return entry, len(self.entries)\n\n async def import_from(self, playlist_url, **meta):\n \"\"\"\n Imports the songs from `playlist_url` and queues them to be played.\n\n Returns a list of `entries` that have been enqueued.\n\n :param playlist_url: The playlist url to be cut into individual urls and added to the playlist\n :param meta: Any additional metadata to add to the playlist entry\n \"\"\"\n position = len(self.entries) + 1\n entry_list = []\n\n try:\n info = await self.downloader.safe_extract_info(self.loop, playlist_url, download=False)\n except Exception as e:\n raise ExtractionError('Could not extract information from {}\\n\\n{}'.format(playlist_url, e))\n\n if not info:\n raise ExtractionError('Could not extract information from %s' % playlist_url)\n\n # Once again, the generic extractor fucks things up.\n if info.get('extractor', None) == 'generic':\n url_field = 'url'\n else:\n url_field = 'webpage_url'\n\n baditems = 0\n for items in info['entries']:\n if items:\n try:\n entry = URLPlaylistEntry(\n self,\n items[url_field],\n items.get('title', 'Untitled'),\n items.get('duration', 0) or 0,\n self.downloader.ytdl.prepare_filename(items),\n **meta\n )\n\n self._add_entry(entry)\n entry_list.append(entry)\n except:\n baditems += 1\n # Once I know more about what's happening here I can add a proper message\n traceback.print_exc()\n print(items)\n print(\"Could not add item\")\n else:\n baditems += 1\n\n if baditems:\n print(\"Skipped %s bad entries\" % baditems)\n\n return entry_list, position\n\n async def async_process_youtube_playlist(self, playlist_url, **meta):\n \"\"\"\n Processes youtube playlists links from `playlist_url` in a questionable, async fashion.\n\n :param playlist_url: The playlist url to be cut into individual urls and added to the playlist\n :param meta: Any additional metadata to add to the playlist entry\n \"\"\"\n\n try:\n info = await self.downloader.safe_extract_info(self.loop, playlist_url, download=False, process=False)\n except Exception as e:\n raise ExtractionError('Could not extract information from {}\\n\\n{}'.format(playlist_url, e))\n\n if not info:\n raise ExtractionError('Could not extract information from %s' % playlist_url)\n\n gooditems = []\n baditems = 0\n for entry_data in info['entries']:\n if entry_data:\n baseurl = info['webpage_url'].split('playlist?list=')[0]\n song_url = baseurl + 'watch?v=%s' % entry_data['id']\n\n try:\n entry, elen = await self.add_entry(song_url, **meta)\n gooditems.append(entry)\n except ExtractionError:\n baditems += 1\n except Exception as e:\n baditems += 1\n print(\"There was an error adding the song {}: {}: {}\\n\".format(\n entry_data['id'], e.__class__.__name__, e))\n else:\n baditems += 1\n\n if baditems:\n print(\"Skipped %s bad entries\" % baditems)\n\n return gooditems\n\n async def async_process_sc_bc_playlist(self, playlist_url, **meta):\n \"\"\"\n Processes soundcloud set and bancdamp album links from `playlist_url` in a questionable, async fashion.\n\n :param playlist_url: The playlist url to be cut into individual urls and added to the playlist\n :param meta: Any additional metadata to add to the playlist entry\n \"\"\"\n\n try:\n info = await self.downloader.safe_extract_info(self.loop, playlist_url, download=False, process=False)\n except Exception as e:\n raise ExtractionError('Could not extract information from {}\\n\\n{}'.format(playlist_url, e))\n\n if not info:\n raise ExtractionError('Could not extract information from %s' % playlist_url)\n\n gooditems = []\n baditems = 0\n for entry_data in info['entries']:\n if entry_data:\n song_url = entry_data['url']\n\n try:\n entry, elen = await self.add_entry(song_url, **meta)\n gooditems.append(entry)\n except ExtractionError:\n baditems += 1\n except Exception as e:\n baditems += 1\n print(\"There was an error adding the song {}: {}: {}\\n\".format(\n entry_data['id'], e.__class__.__name__, e))\n else:\n baditems += 1\n\n if baditems:\n print(\"Skipped %s bad entries\" % baditems)\n\n return gooditems\n\n def _add_entry(self, entry):\n self.last_queued = entry\n \n if self.bucket_mode == False or entry.meta.get('author', False) == False:\n self.entries.append(entry)\n self.emit('entry-added', playlist=self, entry=entry)\n if self.bucket_mode:\n self.bucket_marks[-1] += 1\n\n else:\n bucket_no = 0\n index = 0\n count = 0\n author = entry.meta.get('author', False)\n\n for song in self.current_bucket:\n if song.meta.get('author', False) == author:\n count += 1\n\n while index <= len(self.entries) and bucket_no < len(self.bucket_marks):\n if index == self.bucket_marks[bucket_no]:\n if count < self.bucket_size:\n self.emit('entry-added', playlist = self, entry = entry)\n self.entries.rotate(-index)\n self.entries.appendleft(entry)\n self.entries.rotate(index)\n for val, mark, in enumerate(self.bucket_marks):\n if index <= mark:\n self.bucket_marks[val] += 1\n self.cleanup_markers()\n return\n else:\n count = 0\n bucket_no += 1\n\n if index == len(self.entries): break\n if self.entries[index].meta.get('author', False) == author:\n count += 1\n index += 1\n\n self.emit('entry-added', playlist = self, entry = entry)\n self.entries.append(entry)\n self.bucket_marks.append(len(self.entries))\n self.cleanup_markers()\n\n def handle_buckets_on_pop(self, entry):\n if self.bucket_mode == True:\n for val, marker in enumerate(self.bucket_marks):\n self.bucket_marks[val] -= 1\n self.current_bucket.append(entry)\n if self.bucket_marks[0] == -1:\n self.bucket_marks = self.bucket_marks[1:]\n self.current_bucket = [entry]\n\n async def get_next_entry(self, predownload_next=True):\n \"\"\"\n A coroutine which will return the next song or None if no songs left to play.\n\n Additionally, if predownload_next is set to True, it will attempt to download the next\n song to be played - so that it's ready by the time we get to it.\n \"\"\"\n if not self.entries:\n return None\n\n entry = self.entries.popleft()\n\n if predownload_next:\n next_entry = self.peek()\n if next_entry:\n next_entry.get_ready_future()\n\n return await entry.get_ready_future()\n\n def peek(self):\n \"\"\"\n Returns the next entry that should be scheduled to be played.\n \"\"\"\n if self.entries:\n return self.entries[0]\n\n async def estimate_time_until(self, position, player):\n \"\"\"\n (very) Roughly estimates the time till the queue will 'position'\n \"\"\"\n estimated_time = sum([e.duration for e in islice(self.entries, position - 1)])\n\n # When the player plays a song, it eats the first playlist item, so we just have to add the time back\n if not player.is_stopped and player.current_entry:\n estimated_time += player.current_entry.duration - player.progress\n\n return datetime.timedelta(seconds=estimated_time)\n\n def count_for_user(self, user):\n return sum(1 for e in self.entries if e.meta.get('author', None) == user)\n","sub_path":"musicbot/playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":15110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"349577592","text":"import random\n#import pandas as pd\n#import pylab as pl\n#import numpy as np\nimport time\nimport math\n#import matplotlib.pyplot as plt\n\ndef MergeSort(ar, start, end):\n if(start<end):\n mid = (start+end)/2\n mid = int(mid)\n MergeSort(ar, start, mid)\n MergeSort(ar, mid+1, end)\n Merge(ar, start, mid, end)\n\ndef Merge(ar, start, mid, end):\n p = start\n q = mid+1\n temp = []\n for i in range(0,end-start+1):\n if p>mid :\n temp.append(ar[q])\n q += 1\n elif q>end :\n temp.append(ar[p])\n p += 1\n elif ar[p] > ar[q]:\n temp.append(ar[q])\n q += 1\n else:\n temp.append(ar[p])\n p += 1\n i = 0\n for q in range(start, end+1):\n ar[q] = temp[i]\n i += 1\n\n\ndef insertion_sort(collection, start, end):\n for loop_index in range(start, end+1):\n insertion_index = loop_index\n while insertion_index > 0 and collection[insertion_index - 1] > collection[insertion_index]:\n collection[insertion_index], collection[insertion_index - 1] = collection[insertion_index - 1], collection[insertion_index]\n insertion_index -= 1\n\ndef Merge_insert_Sort(ar, start, end, S):\n if(end-start > S):\n mid = (start+end)/2\n mid = int(mid)\n Merge_insert_Sort(ar, start, mid, S)\n Merge_insert_Sort(ar, mid+1, end, S)\n Merge(ar, start, mid, end)\n else:\n insertion_sort(ar, start, end)\n\nnumbers = []\nfor i in range(1000000):\n numbers.append(random.randint(0,1000))\nmerge_values = []\ninsert_values = []\npoints = []\nfor z in range(100):\n yeet = []\n huha = []\n k = z\n for i in range(k):\n x = numbers[i]\n yeet.append(x)\n huha.append(x)\n #print(\"Size: \", k)\n start_time = time.time()\n MergeSort(yeet, 0, len(yeet) - 1)\n time_taken_1 = time.time() - start_time\n #print(yeet)\n #print(\"Time taken for merge sort = \", time_taken_1*1000)\n\n start_time = time.time()\n insertion_sort(huha, 1, len(huha)-1)\n time_taken_2 = time.time() - start_time\n #print(huha)\n #print(\"Time taken in insertion sort = \", time_taken_2*1000)\n merge_values.append(time_taken_1)\n insert_values.append(time_taken_2)\n points.append(k)\n #if(time_taken_1<time_taken_2):\n # print(\"Maximum size of array for which insertion sort is faster: \", z-1)\n # break\n #size = size*10\n'''\nplt.plot(points, merge_values, label = \"MergeSort\")\nplt.plot(points, insert_values, label = \"InsertSort\")\nplt.xlabel(\"Size\")\nplt.ylabel(\"Time\")\nplt.title(\"Time analysis for sorting\")\nplt.legend()\nplt.show()\n'''\nanomalies = []\nattempts = 5\nfor i in range(len(merge_values)):\n if(merge_values[i]<insert_values[i]):\n print(points[i])\n attempts -= 1\n anomalies.append(points[i])\n if(attempts==0):\n break\ntemp = 1000\nfor x in range(4):\n print(\"SIZE \", temp)\n for i in range(len(anomalies)):\n if(anomalies[i] == 1):\n continue\n A = []\n B = []\n for j in range(temp):\n A.append(numbers[i])\n B.append(numbers[i])\n start_time = time.time()\n Merge_insert_Sort(A, 0, len(A) - 1, anomalies[i]-1)\n time_taken_1 = time.time() - start_time\n #print(yeet)\n print(\"Time taken for Merge(Insert)Sort = \", time_taken_1*1000)\n\n start_time = time.time()\n MergeSort(B, 0, len(B)-1)\n time_taken_2 = time.time() - start_time\n #print(amigo)\n print(\"Time taken for MergeSort = \", time_taken_2*1000)\n temp *= 10\n","sub_path":"Lab 3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"374809031","text":"from django.conf.urls import url\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n url(r'^$',views.index),\r\n url(r'^login/$',views.login),\r\n url(r'^login_out/$',views.login_out),\r\n\r\n url(r'^user_manager/$',views.user_manager),\r\n url(r'^user_manager_add/$',views.user_manager_add),\r\n url(r'^user_manager_change/$',views.user_manager_change),\r\n url(r'^user_manager_del/$',views.user_manager_del),\r\n\r\n url(r'^group_manager/$',views.group_manager),\r\n url(r'^group_manager_add/$',views.group_manager_add),\r\n url(r'^group_manager_change/$',views.group_manager_change),\r\n url(r'^group_manager_del/$',views.group_manager_del),\r\n\r\n]\r\n","sub_path":"svn_manager_project/front/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"47074315","text":"import xml.etree.ElementTree as ET\nfrom broadsoft.requestobjects.lib.BroadsoftRequest import BroadsoftRequest\nfrom broadsoft.requestobjects.datatypes.AccessDeviceEndpoint import AccessDeviceEndpoint\n\n\nclass UserSharedCallAppearanceDeleteEndpointListRequest(BroadsoftRequest):\n command_name = 'UserSharedCallAppearanceDeleteEndpointListRequest14'\n skip_fetch_error = True\n skip_fetch_error_head = '[Error 4008] User not found: '\n\n def __init__(self, sip_user_id=None, devices=None, **kwargs):\n self.sip_user_id = sip_user_id\n self.devices = devices\n\n BroadsoftRequest.__init__(self, **kwargs)\n\n def build_command_xml(self):\n self.prep_for_xml()\n self.validate()\n\n cmd = self.build_command_shell()\n\n e = ET.SubElement(cmd, 'userId')\n e.text = self.sip_user_id\n\n for d in self.devices:\n ade_xml = AccessDeviceEndpoint(device_name=d['name'], line_port=d['line_port']).to_xml()\n cmd.append(ade_xml)\n\n return cmd\n\n def validate(self):\n if not self.devices or len(self.devices) == 0:\n raise ValueError(\n \"can't run UserSharedCallAppearanceDeleteEndpointListRequest.build_command_xml() without a list of devices, which should be dicts with a device name and a line port\")\n\n if not self.sip_user_id:\n raise ValueError(\"can't run UserSharedCallAppearanceDeleteEndpointListRequest.build_command_xml() without a value for sip_user_id\")\n\n @staticmethod\n def delete_devices(sip_user_id=None, **kwargs):\n u = UserSharedCallAppearanceDeleteEndpointListRequest(sip_user_id=sip_user_id, **kwargs)\n xml = u.post()\n return xml\n","sub_path":"broadsoft/requestobjects/UserSharedCallAppearanceDeleteEndpointListRequest.py","file_name":"UserSharedCallAppearanceDeleteEndpointListRequest.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"311808560","text":"def fib(n):\n lastTwo = [0, 1]\n counter = 2\n while counter <= n:\n nextFib = lastTwo[0] + lastTwo[1]\n lastTwo[0] = lastTwo[1]\n lastTwo[1] = nextFib\n counter += 1\n return lastTwo[1] if n > 0 else lastTwo[0]\n'''\nmake a list lastTwo store the first two number\nmake a counter variable\nas long as the counter is less than input n, we go into the loop\nelse we return the first element or the 2nd element\n\nnextFib is equal to lastTwo[0] + lastTwo[1]\nmake [0] equals to [1]\nand [1] equal to the nextFib\nincrease the counter\nthen go out of the loop\n'''\n","sub_path":"dynamic/fib_num_509.py","file_name":"fib_num_509.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}