diff --git "a/711.jsonl" "b/711.jsonl" new file mode 100644--- /dev/null +++ "b/711.jsonl" @@ -0,0 +1,696 @@ +{"seq_id":"79722756","text":"from to_do_item import *\nfrom main import clear\nfrom logme import *\n\n\n@logme\ndef add_item_to_list(to_do_list):\n to_do_list.append(ToDoItem.add_new_item(ToDoItem))\n\n\n@logme\ndef display_list(to_do_list):\n if len(to_do_list) == 0:\n print(\"No entries to display.\")\n else:\n item_index = 0\n for item in to_do_list:\n print(\"ID: {} - {}\".format(item_index, item))\n item_index += 1\n\n\n@logme\ndef display_item_details(to_do_list):\n list_length = len(to_do_list) - 1\n\n displaying_list_items = True\n while displaying_list_items:\n display_list(to_do_list)\n entry_selection = input(\"\\nChoose item ID to view details or Q to exit to menu: \").upper()\n # clear()\n if entry_selection == \"Q\":\n break\n if all(x.isdigit() for x in entry_selection) and entry_selection is not \"\":\n entry_selection = int(entry_selection)\n # clear()\n if entry_selection < len(to_do_list):\n print(\"Description: {} \\nTask finished: {}\".format(to_do_list[entry_selection].description,\n to_do_list[entry_selection].is_done))\n else:\n print(\"Index doesn't exist. Choose one from between 0 and {}\\n\".format(list_length))\n\n\n@logme\ndef modify_item_attirbutes(to_do_list):\n list_length = len(to_do_list) - 1\n\n modifying_list_item = True\n while modifying_list_item:\n display_list(to_do_list)\n entry_selection = input(\"\\nChoose item ID to modify or Q to exit to menu: \").upper()\n # clear()\n if entry_selection == \"Q\":\n break\n if all(x.isdigit() for x in entry_selection) and entry_selection is not \"\":\n entry_selection = int(entry_selection)\n if entry_selection < len(to_do_list):\n name = ToDoItem.item_name()\n description = ToDoItem.item_description()\n is_done = mark_progress_status()\n to_do_list[entry_selection].modify_item_attirbutes(name, description, is_done)\n # clear()\n else:\n print(\"Index doesn't exist. Choose one from between 0 and {}\\n\".format(list_length))\n\n\n@logme\ndef delete_item(to_do_list):\n list_length = len(to_do_list) - 1\n\n deleting_list_item = True\n while deleting_list_item:\n display_list(to_do_list)\n entry_selection = input(\"\\nChoose item ID to delete or Q to exit to menu: \").upper()\n # clear()\n if entry_selection == \"Q\":\n break\n if all(x.isdigit() for x in entry_selection) and entry_selection is not \"\":\n entry_selection = int(entry_selection)\n if entry_selection < len(to_do_list):\n to_do_list.pop(entry_selection)\n # clear()\n else:\n print(\"Index doesn't exist. Choose one from between 0 and {}\\n\".format(list_length))\n\n\ndef mark_progress_status():\n marking_status = True\n while marking_status:\n status = input(\"Is task finished? Y/N: \").upper()\n if status == \"Y\":\n return True\n elif status == \"N\":\n return False\n else:\n print(\"Invalid input, choose Y/N\")\n continue\n","sub_path":"MVC-ToDoApp-Debugging/to_do_list.py","file_name":"to_do_list.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"385342392","text":"import time\nimport math\nimport io\n\n#import penguinPi as ppi\n#import picamera\n#import picamery.array\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n## conversion from/to raw data\nwheel_dia = 0.065\nturn_dia = 0.145\np = 45\nmotor_L = -p\nmotor_R = -p\nerror = 4\n\ndef speed2powerLeft(v):\n power = round(v * (-122.00) - 16.75) #-113.6363 -16.75\n return power\n\ndef speed2powerRight(v):\n power = round(v * (-116.6512) - 16.65)\n return power\n\ndef enc_diff(init_count, current_count):\n half_res = 15360\n full_res = 30720\n scaled_count = current_count - init_count + half_res\n return_count = current_count - init_count\n if (scaled_count < 0):\n return_count = (half_res - init_count) + (current_count + half_res)\n elif (scaled_count >= full_res):\n return_count = (half_res - current_count) + (init_count + half_res) \n return return_count\n\n## motion model of lab robot\ndef get_motion_sim(v,w,delta_t):\n #input\n # v: linear velocity (m/s)\n # w: angular velocity (m/s)\n # delta_t: time interval\n #output\n # delta_d: distance travelled\n # delta_th: change in heading\n delta_d = v * delta_t + 0.05 * np.random.randn(1)[0]\n delta_th = w * delta_t + 0.01 * (np.pi/180) * np.random.randn(1)[0]\n\n return delta_d,delta_th\n\ndef get_motion(tL1,tL2,tR1,tR2):\n diffL = enc_diff(tL1,tL2)\n diffR = enc_diff(tR1,tR2)\n delta_d = (diffL + diffR)/2\n delta_theta = ((diffR - diffL)/720)*(wheel_dia/turn_dia) #TODO: verify!\n\n return delta_d,delta_th\n\n## current configuration as global variable\nxCurrent = 0\nyCurrent = 0\nthetaCurrent = 0\n\ndef toPoint(xTarget, yTarget, xCurrent, yCurrent, thetaCurrent):\n \n plt.axis([0,5,0,5])\n \n ## control params\n Kv = 0.7\n Kh = 2\n goal_tolerance = 0.01\n\n #TODO: loop until target is within a tolerance\n t1 = t2 = v = w = 0.0\n\n while(True):\n ## calculate current configuration\n t2 = time.time()\n delta_d, delta_th = get_motion_sim(v,w,t2-t1)\n xCurrent = xCurrent + delta_d * math.cos(thetaCurrent)\n yCurrent = yCurrent + delta_d * math.sin(thetaCurrent)\n thetaCurrent = thetaCurrent + delta_th\n t1 = t2\n\n\n ## break if goal is reached\n if ((xCurrent-xTarget)**2 + (yCurrent-yTarget)**2 < goal_tolerance):\n break\n\n ## angle to target (not pose angle!)\n thetaTarget = math.atan2((yTarget - yCurrent),(xTarget - xCurrent))\n\n ## calculate desired motion speeds\n velAv = Kv * math.sqrt((xTarget-xCurrent)**2 + (yTarget-yCurrent)**2) #offset due to min robot speed\n velDiff = Kh * (thetaTarget - thetaCurrent)\n vL = velAv - velDiff/2\n vR = velAv + velDiff/2\n \n print(thetaTarget)\n print(thetaCurrent)\n\n ## set motor settings\n #mA.set_power(speed2powerLeft(vL))\n #mB.set_power(speed2powerRight(vR))\n\n v, w = velAv, velDiff #only for simulation\n \n #plt.scatter(xCurrent,yCurrent,marker=(3,2,180*thetaCurrent/np.pi+270),s=100)\n arrow_size = 0.05\n dx = arrow_size * math.cos(thetaCurrent)\n dy = arrow_size * math.sin(thetaCurrent)\n #plt.arrow(xCurrent,yCurrent,dx,dy,width=0.003)\n plt.plot([xCurrent,xCurrent+dx],[yCurrent,yCurrent+dy],color='r',linewidth=3)\n plt.plot([xCurrent,xCurrent-dy],[yCurrent,yCurrent+dx],color='b',linewidth=3)\n\n time.sleep(0.1)\n #print(xCurrent)\n #print(yCurrent)\n \n plt.show()\n input()\n\n return xCurrent, yCurrent, thetaCurrent\n\nif __name__ == '__main__':\n \n fig=plt.figure()\n \n xCurrent, yCurrent, thetaCurrent = toPoint(2,3, xCurrent, yCurrent, thetaCurrent)\n #xCurrent, yCurrent, thetaCurrent = toPoint(-4,-4, xCurrent, yCurrent, thetaCurrent)\n #xCurrent, yCurrent, thetaCurrent = toPoint(-5,3, xCurrent, yCurrent, thetaCurrent)\n #xCurrent, yCurrent, thetaCurrent = toPoint(4,4, xCurrent, yCurrent, thetaCurrent)\n #xCurrent, yCurrent, thetaCurrent = toPoint(4,-4, xCurrent, yCurrent, thetaCurrent)\n \n","sub_path":"prototypes/motion_model.py","file_name":"motion_model.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"600745085","text":"import pandas as pd\n\nclass AttributeStatisticsCalculator(object):\n \"\"\"\n Statistics for a single attribute\n \"\"\"\n\n def __init__(self, name, dtype, df, attribute, quantile_bins=None):\n self._name = name\n self._dtype = dtype\n self._series = df[name]\n self._attribute = attribute\n\n if quantile_bins:\n self._quantile_bins = quantile_bins\n else:\n self._quantile_bins = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n\n @property\n def name(self):\n return self._name\n\n @property\n def is_numeric(self):\n if self._dtype in ['float64']:\n return True\n else:\n return False\n\n @property\n def is_categorical(self):\n if self._dtype in ['category', 'object', 'bool']:\n return True\n else:\n return False\n\n @property\n def quantiles(self):\n if self.is_numeric:\n return {round(index, 4): value for index, value in self._series.quantile(self._quantile_bins).iteritems()}\n else:\n return None\n\n @property\n def count(self):\n return self._series.count()\n\n @property\n def std(self):\n if self.is_numeric:\n return self._series.std()\n else:\n return None\n\n @property\n def median(self):\n if self.is_numeric:\n return self._series.median()\n else:\n return None\n\n @property\n def max(self):\n if self.is_numeric:\n return self._series.max()\n else:\n return None\n\n @property\n def min(self):\n if self.is_numeric:\n return self._series.min()\n else:\n return None\n\n @property\n def mean(self):\n if self.is_numeric:\n return self._series.mean()\n else:\n return None\n\n @property\n def base_statistics(self):\n if self.is_numeric:\n return {\n 'count': self.count,\n 'std': self.std,\n 'mean': self._series.mean,\n 'median': self.median,\n 'max': self.max,\n 'min': self.min\n }\n else:\n return None\n\n @property\n def nunique(self):\n if self.is_categorical:\n return self._series.nunique()\n else:\n return None\n\n @property\n def categories(self):\n if self.is_categorical:\n return {index: value for index, value in self._series.value_counts().iteritems()}\n else:\n return None\n\n @property\n def category_statistics(self):\n if self.is_categorical:\n return {\n 'categories': self.categories,\n 'count': self.count,\n 'unique': self.nunique\n }\n\n else:\n return None\n\n @property\n def attribute(self):\n return self._attribute\n\nclass DataSetDataFrame(object):\n \"\"\"\n Provides a Dataframe from a dataset\n \"\"\"\n\n def __init__(self, dataset, target_attribute=None):\n self._dataset = dataset\n self._dataset_definition = self._dataset.dataset_definition\n self._df = None\n self._attribute_types = {}\n self._attributes = {}\n self._target_attribute = None\n\n self._set_attributes()\n self._create_dataframe()\n\n if target_attribute:\n self.target_attribute = target_attribute\n\n def _set_attributes(self):\n type_map = {\n 'NUMERIC': 'float64',\n 'CATEGORICAL': 'category',\n 'BINARY': 'bool',\n }\n\n self._attributes = {\n attribute.name: attribute\n for attribute in self._dataset_definition.attributes.all()\n }\n\n self._attribute_types = {\n name: type_map.get(attribute.type, 'object')\n for name, attribute in self.attributes.items()\n }\n\n def _create_dataframe(self):\n instance_data = [(instance.id, instance.instance) for instance in self._dataset.instances.all()]\n\n values = [data[1] for data in instance_data]\n index = [data[0] for data in instance_data]\n\n df = pd.DataFrame(values, index=index)\n\n for name, dtype in self._attribute_types.items():\n df[name] = df[name].astype(dtype)\n\n self._df = df\n\n def attribute_dtype(self, name):\n return self._attribute_types.get(name)\n\n @property\n def dataset_definition(self):\n return self._dataset_definition\n\n @property\n def dataset(self):\n return self._dataset\n\n @property\n def dataframe(self):\n return self._df\n\n @property\n def attributes(self):\n return self._attributes\n\n @property\n def target_attribute(self):\n return self._target_attribute\n\n\nclass DataSetStatisticsCalculator(object):\n\n def __init__(self, dataset_df=None, dataset=None, target_attribute=None):\n error_msg = 'DataSetStatistics not initialized properly. '\n if dataset and dataset_df:\n error_msg += 'Cannot initialize with both DataSet and DataSetDataFrame object.'\n raise ValueError(error_msg)\n elif dataset_df:\n self._dataset_df = dataset_df\n elif dataset:\n self._dataset_df = DataSetDataFrame(dataset, target_attribute=target_attribute)\n else:\n error_msg += 'Initialize with either DataSet or DataSetDataFrame object. '\n raise ValueError(error_msg)\n\n self._attribute_statistics = []\n self._dataset_statistics = {}\n\n def _calculate_attribute_statistics(self):\n self._attribute_statistics = [\n AttributeStatisticsCalculator(name, self.dataset_df.attribute_dtype(name), self.dataframe, attribute)\n for name, attribute in self.dataset_df.attributes.items()\n ]\n\n def _calculate_dataset_statistics(self):\n for attribute_statistic in self._attribute_statistics:\n current_statistics = {}\n if attribute_statistic.is_numeric:\n current_statistics['base'] = attribute_statistic.base_statistics\n current_statistics['quantiles'] = attribute_statistic.quantiles\n elif attribute_statistic.is_categorical:\n current_statistics = attribute_statistic.category_statistics\n\n self._dataset_statistics[attribute_statistic.name] = current_statistics\n\n def calculate_statistics(self):\n self._attribute_statistics = []\n self._dataset_statistics = {}\n\n self._calculate_attribute_statistics()\n self._calculate_dataset_statistics()\n\n @property\n def attribute_statistics(self):\n return self._attribute_statistics\n\n @property\n def dataset_definition(self):\n return self._dataset_df.dataset_definition\n\n @property\n def dataset(self):\n return self._dataset_df.dataset\n\n @property\n def dataset_df(self):\n return self._dataset_df\n\n @property\n def dataframe(self):\n return self._dataset_df.dataframe\n\n @property\n def statistics(self):\n return self._dataset_statistics\n\n\n\n\n","sub_path":"ml/datautils.py","file_name":"datautils.py","file_ext":"py","file_size_in_byte":7136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"312551476","text":"#!/usr/bin/python\nimport sys\nimport random\n\nclass Lord:\n def __init__(self, militaryStrength):\n self.militaryStrength = militaryStrength\n self.revealedIntimacy = []\n self.realIntimacy = 0\ndef readLine():\n return list(map(int, raw_input().split()))\n\nprint('READY')\nsys.stdout.flush()\ntotalTurns, numDaimyo, numLords = readLine()\nmilitaryStrength = readLine()\nlords = []\n\nfor i in range(numLords):\n lords.append(Lord(militaryStrength[i]))\n\nfor t in range(totalTurns):\n turn, time = raw_input().split()\n turn = int(turn)\n for i in range(numLords):\n lords[i].revealedIntimacy = readLine()\n realLove = readLine()\n for i in range(numLords):\n lords[i].realIntimacy = realLove[i]\n if time == 'D':\n negotiationCount = readLine()\n else:\n negotiationCount = [0] * numLords\n command = []\n for i in range({'D': 5, 'N': 2}[time]):\n command.append(str(random.randrange(numLords)))\n\n print(' '.join(command))\n sys.stdout.flush()\n","sub_path":"dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"67862912","text":"import os\nimport pandas as pd\nimport argparse\nimport json\n\ndef main():\n args = get_args()\n process(args)\n\ndef get_args():\n parser = argparse.ArgumentParser()\n home = os.path.expanduser(\"~\")\n source_dir = \"data/squad/\"\n target_dir = \"data/NewsQA/\"\n output_dir = \"data/Joint_01/\"\n \n # train_ratio: How to split the data into train and dev sets (from the train file). E.g. 0.9 splits to 90% training data and 10% for dev.\n # debug_ratio: What percentage of target directory should be included. E.g. 0.05 means 5% NewsQA is added to 100% SQuAD.\n # target_sampling_ratio: How the target directory should be oversampled to reduce class imbalance between source and target. Do not cross values above 0.3.\n\n parser.add_argument('-s', \"--source_dir\", default=source_dir)\n parser.add_argument('-t', \"--target_dir\", default=target_dir)\n parser.add_argument('-o', \"--output_dir\", default=output_dir)\n \n parser.add_argument(\"--train_ratio\", default=0.9, type=float)\n parser.add_argument(\"--debug_ratio\", default=1.0, type=float)\n parser.add_argument(\"--data_ratio\", default=0.01, type=float)\n parser.add_argument(\"--target_sampling_ratio\", default=0.0, type=float)\n\n return parser.parse_args()\n\ndef process(args):\n source_dir = args.source_dir\n target_dir = args.target_dir\n output_dir = args.output_dir\n sampling_ratio = args.target_sampling_ratio\n data_ratio = args.data_ratio\n train_ratio = args.train_ratio\n debug_ratio = args.debug_ratio\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n splits = [\"train\",\"dev\"]\n for split in splits:\n fname = split+\"-v1.1.json\"\n tfname = split+\".json\" \n print(\"Source: \",source_dir+fname)\n print(\"Target: \", target_dir+tfname)\n sf = pd.read_json(source_dir+fname)\n tf = pd.read_json(target_dir+tfname)\n\n output_data = []\n output_version = []\n if split == \"dev\":\n output_data.extend(sf['data'])\n output_data.extend(tf['data'])\n output_version.extend(sf['version'])\n output_version.extend(tf['version'])\n fname = \"test-v1.1.json\"\n else:\n dev_output_data = []\n dev_output_version = []\n s_len = len(sf['data'])\n t_len = int(len(tf['data'])*debug_ratio)\n output_data.extend(sf['data'][0:int(s_len * train_ratio)])\n dev_output_data.extend(sf['data'][int(s_len * train_ratio):s_len])\n output_version.extend(sf['version'][0:int(s_len * train_ratio)])\n dev_output_version.extend(sf['version'][int(s_len * train_ratio):s_len])\n s_qs = 0\n t_qs = 0\n for i in range(s_len):\n p_len = len(sf['data'][i]['paragraphs'])\n for j in range(p_len):\n s_qs += len(sf['data'][i]['paragraphs'][j]['qas'])\n for i in range(t_len):\n p_len = len(tf['data'][i]['paragraphs'])\n for j in range(p_len):\n t_qs += len(tf['data'][i]['paragraphs'][j]['qas'])\n multiplier = 1.0\n r = sampling_ratio\n new_m = r*s_qs/(t_qs*(1-r))\n multiplier = max(multiplier,new_m)\n for i in range(int(multiplier)):\n output_data.extend(tf['data'][0:int(t_len * train_ratio)])\n dev_output_data.extend(tf['data'][int(t_len * train_ratio):t_len])\n output_version.extend(tf['version'][0:int(t_len * train_ratio)])\n dev_output_version.extend(tf['version'][int(t_len * train_ratio):t_len])\n t_len = int(t_len*multiplier - int(multiplier))\n output_data.extend(tf['data'][0:int(t_len * train_ratio)])\n dev_output_data.extend(tf['data'][int(t_len * train_ratio):t_len])\n output_version.extend(tf['version'][0:int(t_len * train_ratio)])\n dev_output_version.extend(tf['version'][int(t_len * train_ratio):t_len])\n dev_of = {\"data\": dev_output_data, \"version\": dev_output_version}\n with open(output_dir + \"dev-v1.1.json\",'w') as fp:\n json.dump(dev_of, fp)\n of = {\"data\": output_data, \"version\": output_version}\n with open(output_dir+fname,'w') as fp:\n json.dump(of, fp)\n\nif __name__ ==\"__main__\":\n main()\n","sub_path":"joint_train.py","file_name":"joint_train.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"130108169","text":"from CONSTANTS import * \nimport random as r\n\nclass DNA(object):\n fitness = 0\n word = \"\"\n\n # Solo al principio la palabra es completamente \n # aleatoria. La palabra se genera en el mundo\n def __init__(self, random_word):\n self.word = random_word\n\n def calc_fitness(self, target):\n self.fitness = 0\n for i in range(len(self.word)):\n if self.word[i] == target[i]:\n self.fitness += 1\n\n def combine(self, other_parent):\n middle_point = r.randint(0, len(self.word) - 1)\n\n # necesario porque no se puede modificar un string directamente\n new_word = list(self.word)\n\n for i in range(len(self.word)):\n if i > middle_point:\n new_word[i] = other_parent.word[i]\n\n return DNA(\"\".join(new_word))\n\n\n def mutate(self, mutation_rate):\n self.word = list(self.word)\n if r.random() < mutation_rate:\n self.word[r.randint(0, len(self.word) - 1)] = random_character()\n self.word = \"\".join(self.word)\n\n def __str__(self):\n return \"%s, %d\" % (self.word, self.fitness)\n","sub_path":"DNA.py","file_name":"DNA.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"467229618","text":"import subprocess\nimport os\nimport sys\nimport platform\nimport socket\nimport time\nimport atexit\n#import psutil\nimport requests\nimport json\nfrom flask import Flask, flash, redirect, render_template, request, session, abort, url_for\n\n\n\ndef render_policy(saved_policy, ise_groups, policy_options, zone):\n\n print('render_policy:', zone)\n\n # setup default browser display options\n allow_policy = {}\n for policy in policy_options:\n allow_policy[policy] = ''\n\n policy_groups = {}\n for group in ise_groups:\n policy_groups[group] = ''\n if zone == 'default_policy':\n policy_groups['ALL'] = ''\n\n\n # now add the policy selections to display in browser\n for key, value in allow_policy.items():\n if key.lower() == saved_policy['allow_deny']:\n allow_policy[key] = 'selected'\n print('render_policy:allow_policy:', allow_policy)\n\n\n for key, value in policy_groups.items():\n if key in saved_policy['policies_list']:\n policy_groups[key] = 'selected'\n print('render_policy:policy_groups: ', policy_groups)\n\n rendered_policy = {'policy': allow_policy, 'groups': policy_groups}\n\n return rendered_policy\n\n\ndef ross_object_function_to_update_policy(changed_zones):\n \n print('function: ross_object_function_to_update_policy. Variable changed_zones need to be transformed for you object function')\n\n\ndef check_webhook():\n\n url = WEBEX_URL + '/webhooks'\n\n ngrok_url = requests.get(\n \"http://127.0.0.1:4040/api/tunnels\", headers={\"Content-Type\": \"application/json\"}).json()\n\n for urls in ngrok_url[\"tunnels\"]:\n if \"https://\" in urls['public_url']:\n target_url = urls['public_url']\n address = urls['config']['addr']\n print('Ngrok target_url is:', target_url)\n print('Ngrok address is:', address)\n\n webhook_js = send_spark_get(url, js=True)\n print('webhook_js initial check is: ', webhook_js)\n\n items = webhook_js['items']\n\n if len(items) > 0 :\n #print(items)\n for webhook in range(len(items)) :\n if ((items[webhook]['name'] == webhook_name) and (items[webhook]['resource'] in resources)):\n #print('Webhook name =', items[webhook]['name'])\n #print('resource =', items[webhook]['resource'] )\n send_spark_delete(url + '/' + items[webhook]['id'])\n\n\n for webhook in resources :\n payload = {'name': webhook_name, 'targetUrl': target_url + bot_route, 'resource' : webhook, 'event' : event}\n webhook_js = send_spark_post(url, data=payload, js=True)\n print(webhook_js)\n\n return\n\n\ndef send_spark_get(url, payload=None, js=True):\n\n if payload == None:\n request = requests.get(url, headers=headers)\n else:\n request = requests.get(url, headers=headers, params=payload)\n if js == True:\n request= request.json()\n return request\n\ndef send_spark_delete(url, js=False):\n\n request = requests.delete(url, headers=headers)\n if js != False:\n request = request.json()\n return request\n\n\ndef send_spark_post(url, data, js=True):\n\n request = requests.post(url, json.dumps(data), headers=headers)\n if js:\n request = request.json()\n return request\n\n\ndef check_bot():\n\n url = WEBEX_URL + '/people/me'\n\n '''\n headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Authorization\": \"Bearer \" + WEBEX_BOT_TOKEN\n }\n '''\n\n print('Connecting to Webex Teams Cloud Service...')\n try:\n resp = requests.get(url, headers=headers, timeout=25, verify=False)\n resp.raise_for_status()\n except requests.exceptions.Timeout as err:\n print('\\n', err)\n print('Webex Teams appears to be unreachable!!')\n sys.exit(1)\n except requests.exceptions.HTTPError as err:\n print('\\n', err)\n if resp.status_code == 401:\n print(\"Looks like your provided Webex Teams Bot access token is not correct. \\n\"\n \"Please review it and make sure it belongs to your bot account.\\n\"\n \"Do not worry if you have lost the access token. \"\n \"You can always go to https://developer.webex.com/my-apps \"\n \"URL and generate a new access token.\")\n else:\n print('HTTPError: Check error code', resp.status_code)\n sys.exit(1)\n except requests.exceptions.RequestException as err:\n print('\\n', err)\n print('RequestException')\n sys.exit(1)\n\n if resp.status_code == 200:\n response_json = resp.json()\n bot_name = response_json['displayName']\n bot_email = response_json['emails'][0]\n print('Status code={}.\\nResponse={}\\n'.format(resp.status_code, response_json))\n\n return bot_name, bot_email\n\n\ndef help():\n return \"Sure! I can help. Below are the commands that I understand:
\" \\\n \"`Help` - I will display what I can do.
\" \\\n \"`Hello` - I will display my greeting message
\" \\\n \"`Zones` - I will display all the zones in the policy database
\" \\\n \"`Groups` - I will displace all the ISE groups that can be used in a Zone policy
\" \\\n \"`Display [Zone Name]` - I will display the policy for [Zone Name]
\" \\\n \"`Change [Zone Name] policy=[policy] groups=group1, group2, group3`
\" \\\n \"`[ ]` represent variables.
\"\n\n\n\ndef hello():\n return \"Hi my name is %s bot.
\" \\\n \"Type `Help` to see what I can do.
\" % bot_name\n\n\ndef get_zones(saved_policy):\n\n message = '**The following Zones are defined:**
'\n for zone in saved_policy['zone_policies']:\n message += (zone['zone_name'] + '
')\n\n return message\n\n\ndef get_groups(groups):\n\n message = '**The following ISE groups can be used in a zone policy:**
'\n for group in groups:\n message += (group + '
')\n\n return message\n\ndef display_zone_policy(saved_policy, search_zone):\n\n message = '**Policy for zone**: {}
'.format(search_zone)\n for zone in saved_policy['zone_policies']:\n if zone['zone_name'] == search_zone.strip():\n message += ('**Policy**: ' + zone['zone_policy']['allow_deny'] + '
')\n groups = ', '.join(zone['zone_policy']['policies_list'])\n message += ('**Groups**: ' + groups + '
')\n return message\n\ndef change_zone_policy(policy, error):\n\n if error!='':\n return error\n\n zone = policy.split('policy', maxsplit=1)\n policy = 'policy' + zone[1].strip()\n split_policy=policy.split(' ', maxsplit=1)\n policy=split_policy[0]\n groups=split_policy[1]\n policy_msg = policy.split('=')[1]\n groups_msg = groups.split('=')[1]\n message = '**Policy was changed for zone**: {}
'.format(zone[0])\n message += ('**Policy**: ' + policy_msg + '
')\n message += ('**Groups**: ' + groups_msg + '
')\n\n groups_msg = groups_msg.split(',')\n for group_index in range(len(groups_msg)):\n groups_msg[group_index]=groups_msg[group_index].strip()\n\n changed_zones = {'zone_name' : zone[0], 'zone_policy' : {'allow_deny' : policy_msg, 'policies_list' : groups_msg}}\n\n print(json.dumps(changed_zones, indent=4))\n\n ross_object_function_to_update_policy(changed_zones)\n\n return message\n\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return redirect(url_for('config_update'))\n\n\n\n@app.route('/cmxreceiver', methods =['POST'])\ndef cmxreceiver():\n if request.method == 'POST' :\n print(\"Previously done\")\n return \"OK\"\n\n\n@app.route('/bot', methods =['GET', 'POST'])\ndef bot():\n\n if request.method == 'GET' :\n print('Hello bot get request')\n return '

Location Policy Bot is up and running. @mention {0} from Teams @{0} help to start!'.format(bot_name)\n\n\n elif request.method == 'POST':\n\n with open('location_policy.json') as json_file:\n saved_policy = json.load(json_file)\n #print(json.dumps(saved_policy, indent=4))\n\n ise_groups = ['loc-testing', 'Nurses', 'Doctors', 'Employees', 'Test', ]\n\n webhook = request.get_json()\n print(webhook)\n\n resource = webhook['resource']\n senders_email = webhook['data']['personEmail']\n room_id = webhook['data']['roomId']\n\n if resource == \"memberships\" and senders_email == bot_email:\n print('webhook is: ', webhook)\n send_spark_post(\"https://api.ciscospark.com/v1/messages\",\n {\n \"roomId\": room_id,\n \"markdown\": (hello() +\n \"**Note: This is a group space and you have to call \"\n \"me specifically with `@%s` for me to respond.**\" % bot_name)\n }\n )\n\n if (\"@webex.bot\" not in webhook['data']['personEmail']):\n print('Requester email= ', webhook['data']['personEmail'])\n print('msgID= ', webhook['data']['id'])\n result = send_spark_get(\n 'https://api.ciscospark.com/v1/messages/{}'.format(webhook['data']['id']))\n print('Raw request=', result['text'])\n message = result['text']\n message = message.replace(bot_name, '').strip()\n message = message.split()\n message[0] = message[0].lower()\n message = ' '.join(message)\n print('Parsed request=', message)\n if message.startswith('help'):\n msg = help()\n elif message.startswith('hello'):\n msg = hello()\n elif message.startswith('zones'):\n msg = get_zones(saved_policy)\n elif message.startswith('groups'):\n msg = get_groups(ise_groups)\n elif message.startswith('display'):\n zone = message.replace('display', '')\n msg = display_zone_policy(saved_policy, zone)\n elif message.startswith('change'):\n policy = message.replace('change', '')\n error = ''\n if not ' policy' in policy:\n error = 'Confirm Change policy request is using the correct syntax:
'\n error += ('change [zone_name] policy=[policy] groups=([groups])')\n elif not ' groups' in policy:\n error = 'Confirm Change policy request is using the correct syntax:
'\n error += ('change [zone_name] policy=[policy] groups=([groups])')\n msg = change_zone_policy(policy, error)\n else:\n msg = \"Sorry, but I did not understand your request. Type `Help` to see what I can do\"\n\n if msg != None:\n send_spark_post(\"https://api.ciscospark.com/v1/messages\",\n {\"roomId\": webhook['data']['roomId'], \"markdown\": msg})\n\n return \"true\"\n\n\n\n@app.route('/config_update', methods =['GET', 'POST'])\ndef config_update():\n\n if request.method == 'GET' :\n\n with open('location_policy.json') as json_file:\n saved_policy = json.load(json_file)\n print(json.dumps(saved_policy, indent=4))\n\n ise_groups = ['loc-testing', 'Nurses', 'Doctors', 'Employees', 'Test',]\n ise_groups.append('ALL')\n # move the 'ALL' element to front of list\n ise_groups.insert(0, ise_groups.pop(-1))\n\n policy_options = ['Allow', 'Deny']\n\n default_policy = render_policy(saved_policy['default_policy'], ise_groups, policy_options, 'default_policy')\n print('default_policy:', default_policy)\n\n zones = {}\n list_value = 0\n for zone in saved_policy['zone_policies']:\n submit_policy = saved_policy['zone_policies'][list_value]['zone_policy']\n zones[zone['zone_name']] = render_policy(submit_policy, ise_groups, policy_options, zone['zone_name'])\n list_value = list_value + 1\n\n print('zones policy:', zones)\n\n return render_template(\"form_submit.html\", zones=zones, default_policy=default_policy)\n\n else:\n\n print(request.form)\n changed_zones = []\n zone_numbers = []\n\n for key, value in request.form.items():\n if 'zone' in key:\n zone_numbers.append(key.strip('zone'))\n\n print(zone_numbers)\n\n for element in zone_numbers:\n zone_name = request.form.get('zone' + element)\n policy = request.form.get('policy' + element)\n group_list = request.form.getlist('group' + element)\n #changed_zones.append({'zone_name' : zone_name,'policy': policy, 'group': group_list})\n changed_zones.append({'zone_name' : zone_name,'zone_policy': {'allow_deny': policy, 'policies_list': group_list}})\n\n for zone in changed_zones:\n print(json.dumps(zone, indent=4))\n\n ross_object_function_to_update_policy(changed_zones)\n\n return render_template('changed_policy.html', changed_zones=changed_zones)\n\nif __name__ == \"__main__\" :\n\n\n if 'WEBEX_BOT_TOKEN' in os.environ:\n WEBEX_BOT_TOKEN = os.environ.get('WEBEX_BOT_TOKEN')\n\n headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Authorization\": \"Bearer \" + WEBEX_BOT_TOKEN\n }\n\n WEBEX_URL = \"https://api.ciscospark.com/v1\"\n\n bot_name, bot_email = check_bot()\n\n webhook_name = 'location_query'\n resources = ['messages', 'memberships']\n event = 'created'\n bot_route = '/bot'\n\n print(WEBEX_BOT_TOKEN)\n print(bot_name)\n print(bot_email)\n\n check_webhook()\n\n\n flask_port = 5050\n\n print('\\n******** Starting up Flask Web... ********\\n\\n')\n\n app.run(host='0.0.0.0', port=flask_port)\n\n","sub_path":"receiver_web.py","file_name":"receiver_web.py","file_ext":"py","file_size_in_byte":13853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"20352014","text":"#\n# Utilities to interact with the UCSC database.\n#\n# This file is part of gepyto.\n#\n# This work is licensed under the Creative Commons Attribution-NonCommercial\n# 4.0 International License. To view a copy of this license, visit\n# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to Creative\n# Commons, PO Box 1866, Mountain View, CA 94042, USA.\n\n\nfrom __future__ import division\n\n\n__author__ = \"Marc-Andre Legault\"\n__copyright__ = (\"Copyright 2014 Marc-Andre Legault and Louis-Philippe \"\n \"Lemieux Perreault. All rights reserved.\")\n__license__ = \"Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)\"\n\n\nimport collections\n\nimport numpy as np\n\nfrom .. import settings\nfrom ..structures.region import Region\n\n\nclass UCSC(object):\n \"\"\"Provides raw access to the UCSC MySQL database.\n\n The database will be set to the `db` parameter or to the `BUILD` as defined\n in `gepyto`'s settings.\n\n Later versions could implement features like throttling, but for now this\n is a very simple interface.\n\n \"\"\"\n def __init__(self, db=None):\n import pymysql\n\n if db is None:\n db = settings.BUILD\n\n if db.lower() == \"grch37\":\n db = \"hg19\"\n elif db.lower() == \"grch38\":\n db = \"hg38\"\n else:\n raise Exception(\"Invalid genome reference '{}'\".format(db))\n\n self.con = pymysql.connect(user=\"genome\",\n host=\"genome-mysql.cse.ucsc.edu\",\n database=db)\n\n self.cur = self.con.cursor()\n\n def raw_sql(self, sql, params):\n \"\"\"Execute a raw SQL query.\"\"\"\n self.cur.execute(sql, params)\n return self.cur.fetchall()\n\n def query_gap_table(self, chromosome, ucsc_type):\n \"\"\"Get either the \"telomere\" or \"centromere\" of a given chromosome.\n\n \"\"\"\n if not chromosome.startswith(\"chr\"):\n chromosome = \"chr\" + chromosome\n\n valid_types = (\"telomere\", \"centromere\")\n if ucsc_type not in valid_types:\n msg = \"'{}' is not a valid type: use {}.\".format(\n ucsc_type,\n valid_types\n )\n raise TypeError(msg)\n\n return self.raw_sql(\n (\"SELECT chromStart + 1, chromEnd + 1 \"\n \"FROM gap \"\n \"WHERE chrom=%s AND type=%s\"),\n (chromosome, ucsc_type),\n )\n\n def close(self):\n self.con.close()\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.close()\n\n\ndef get_telomere(chromosome):\n \"\"\"Returns a Noncontiguous region representing the telomeres of a\n chromosome.\n\n :param chromosome: The chromosome, _e.g._ \"3\"\n :type chromosome: str\n\n :returns: A region corresponding to the telomeres.\n :rtype: :py:class:`Region`\n\n This is done by connecting to the UCSC MySQL server.\n\n \"\"\"\n chromosome = str(chromosome)\n with UCSC() as ucsc:\n telomeres = ucsc.query_gap_table(chromosome, \"telomere\")\n\n assert len(telomeres) == 2, (\"UCSC did not return two telomeres (chrom={}\"\n \").\".format(chromosome))\n\n # Create a region for both telomeres and use a union to return the full\n # region.\n telo1 = Region(chromosome.lstrip(\"chr\"), telomeres[0][0], telomeres[0][1])\n telo2 = Region(chromosome.lstrip(\"chr\"), telomeres[1][0], telomeres[1][1])\n return telo1.union(telo2)\n\n\ndef get_centromere(chromosome):\n \"\"\"Returns a contiguous region representing the centromere of a chromosome.\n\n :param chromosome: The chromosome, _e.g._ \"3\"\n :type chromosome: str\n\n :returns: A region corresponding to the centromere.\n :rtype: :py:class:`Region`\n\n This is done by connecting to the UCSC MySQL server.\n\n \"\"\"\n chromosome = str(chromosome)\n with UCSC() as ucsc:\n centromere = ucsc.query_gap_table(chromosome, \"centromere\")\n\n assert len(centromere) == 1, \"UCSC returned {} centromere(s).\".format(\n len(centromere)\n )\n centromere = centromere[0]\n\n return Region(chromosome.lstrip(\"chr\"), centromere[0], centromere[1])\n\n\ndef get_phylop_100_way(region):\n \"\"\"Get a vector of phyloP conservation scores for a given region.\n\n Scores represent the -log(p-value) under a H0 of neutral evolution.\n Positive values represent conservation and negative values represent\n fast-evolving bases.\n\n The UCSC MySQL database only contains aggregate scores for chunks of\n 1024 bases. We return the results for the subset of the required region\n that is fully contained in the UCSC bins.\n\n Because UCSC uses 0-based indexing, we adjust the gepyto region before\n querying. This means that the user should use 1-based indexing, as\n usual when creating the Region object.\n\n .. warning::\n\n This function has a fairly low resolution. You should download the raw\n data (e.g. from\n `goldenpath `_\n ) if you need scores for each base.\n Also note that gepyto can't parse bigWig, but it can parse Wig files.\n\n .. warning::\n\n This function is **untested**.\n\n \"\"\"\n with UCSC() as ucsc:\n sql = (\n \"SELECT * FROM phyloP100wayAll WHERE \"\n \" chrom=%s AND \"\n \" chromStart>=%s AND \"\n \" chromEnd<=%s \"\n )\n\n chrom = region.chrom\n if not chrom.startswith(\"chr\"):\n chrom = \"chr{}\".format(chrom)\n\n ucsc.cur.execute(sql, (chrom, region.start - 1, region.end - 1))\n\n n = ucsc.cur.rowcount\n\n if not n:\n return # No results.\n\n results = iter(ucsc.cur)\n\n phylop = np.empty(n)\n\n Row = collections.namedtuple(\n \"Row\",\n (\"bin\", \"chrom\", \"chromStart\", \"chromEnd\", \"name\", \"span\", \"count\",\n \"offset\", \"file\", \"lowerLimit\", \"dataRange\", \"validCount\",\n \"sumData\", \"sumSquares\")\n )\n\n start = end = None\n for i, row in enumerate(results):\n row = Row(*row) # Bind column names.\n\n # Adjust types so we can do integer operations.\n row_start = int(row.chromStart)\n row_end = int(row.chromEnd)\n sum_data = int(row.sumData)\n valid_count = int(row.validCount)\n\n end = row_end\n\n if start is None:\n start = row_start + 1\n\n phylop[i] = sum_data / valid_count\n\n chrom = chrom[3:]\n return {\n \"phylop_scores\": phylop,\n \"n_bins\": n,\n \"actual_region\": Region(chrom, start, end)\n }\n","sub_path":"venv/Lib/site-packages/gepyto/db/ucsc.py","file_name":"ucsc.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"193239567","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport telebot\nfrom telebot import types\nfrom flask import Flask, request\nimport config\nimport requests\nimport json \nimport datetime\n\nbot = telebot.TeleBot(config.token)\nserver = Flask(__name__)\nTOKEN = config.token\n\nmarkup_menu = types.ReplyKeyboardMarkup(resize_keyboard=True)\nmarkup_menu.row('Расписание группы')\nmarkup_menu.row('Собственное расписание')\nmarkup_menu.row('Информация о вузе')\nmarkup_menu.row('Настройки')\n\nmarkup_schedule = types.ReplyKeyboardMarkup(resize_keyboard=True)\nmarkup_schedule.row('Сегодня', 'Завтра')\nmarkup_schedule.row('Понедельник', 'Вторник', 'Среда')\nmarkup_schedule.row('Четверг', 'Пятница', 'Суббота')\nmarkup_schedule.row('Назад')\n\nmarkup_info = types.ReplyKeyboardMarkup(resize_keyboard=True)\nmarkup_info.row('Основные сайты')\nmarkup_info.row('Группы Вконтакте')\nmarkup_info.row('Информация о корпусах')\nmarkup_info.row('Назад')\n\nmarkup_corps = types.ReplyKeyboardMarkup(resize_keyboard=True)\nmarkup_corps.row('Корпус А', 'Корпус Б', 'Корпус В', 'Корпус Г')\nmarkup_corps.row('Корпус Д','Корпус Е','Корпус И','Корпус К',)\nmarkup_corps.row('Назад')\n\nmarkup_user_schedule = types.ReplyKeyboardMarkup(resize_keyboard=True)\nmarkup_user_schedule.row('Удалить пару', 'Редактировать')\nmarkup_user_schedule.row('Назад')\n\n# markup_user_schedule_day = types.InlineKeyboardMarkup(resize_keyboard=True)\n# markup_user_schedule_day.row('Пнд', 'Втр', 'Срд')\n# markup_user_schedule_day.row('Чтв', 'Птн', 'Сбт')\n\n# markup_user_schedule_pair_count = types.InlineKeyboardMarkup(resize_keyboard=True)\n# markup_user_schedule_pair_count.row('1', '2', '3')\n# markup_user_schedule_pair_count.row('4', '5', '6')\n\ndef gen_markup():\n markup = types.InlineKeyboardMarkup()\n markup.row_width = 3\n markup.add(types.InlineKeyboardButton(\"Yes\", callback_data=\"cb_yes\"),\n types.InlineKeyboardButton(\"No\", callback_data=\"cb_no1\"),\n types.InlineKeyboardButton(\"No\", callback_data=\"cb_no2\"),\n types.InlineKeyboardButton(\"No\", callback_data=\"cb_no3\"),\n types.InlineKeyboardButton(\"No\", callback_data=\"cb_no4\"),\n types.InlineKeyboardButton(\"No\", callback_data=\"cb_no5\"))\n return markup\n\n\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n msg = bot.send_message(message.chat.id, \"Добро пожаловать, введите группу (Пример КТбо2-3)\")\n bot.register_next_step_handler(msg, reg_user)\n\ndef reg_user(message):\n url = \"http://ictib.host1809541.hostland.pro/index.php/api/reg_user\"\n print(message.text)\n params = dict(\n user_id=message.from_user.id,\n user_group=message.text\n )\n resp = requests.get(url=url, params=params)\n print(resp.content)\n binary = resp.content\n data = json.loads(binary)\n\n chat_id = message.chat.id\n\n if data['success'] == 'true':\n text = 'Все окей'\n bot.send_message(chat_id, text)\n elif data['success'] == 'false':\n msg = bot.reply_to(message, \"Повтори\")\n bot.register_next_step_handler(msg, reg_user)\n else:\n msg = bot.reply_to(message, \"Ты уже есть\")\n bot.register_next_step_handler(msg, reg_user)\n\n@bot.message_handler(content_types=['text'])\ndef handle_text(message):\n global group\n group = \"Неизвестно\"\n if message.text == \"1\":\n bot.send_message(message.chat.id, \"Ну и нахуя\", reply_markup=markup_menu)\n elif message.text == \"Расписание группы\":\n get_week_schedule(message.from_user.id)\n bot.send_message(message.chat.id, \"Выберите день\", reply_markup=markup_schedule)\n elif message.text == \"Информация о вузе\":\n bot.send_message(message.chat.id, \"Какая информация вам инетересна?\", reply_markup=markup_info)\n elif message.text == \"Информация о корпусах\":\n bot.send_message(message.chat.id, \"Выберете корпус\", reply_markup=markup_corps)\n elif message.text == \"Сегодня\":\n day = get_day_of_week(True)\n text = get_schedule(day, message.from_user.id)\n bot.send_message(message.chat.id, text, reply_markup=markup_schedule)\n elif message.text == \"Завтра\":\n day = get_day_of_week(False)\n text = get_schedule(day, message.from_user.id)\n bot.send_message(message.chat.id, text, reply_markup=markup_schedule)\n elif message.text == \"Понедельник\":\n text = get_schedule('Пнд', message.from_user.id)\n bot.send_message(message.chat.id, text, reply_markup=markup_schedule)\n elif message.text == \"Вторник\":\n text = get_schedule('Втр', message.from_user.id)\n bot.send_message(message.chat.id, text, reply_markup=markup_schedule) \n elif message.text == \"Среда\":\n text = get_schedule('Срд', message.from_user.id)\n bot.send_message(message.chat.id, text, reply_markup=markup_schedule)\n elif message.text == \"Четверг\":\n text = get_schedule('Чтв', message.from_user.id)\n bot.send_message(message.chat.id, text, reply_markup=markup_schedule)\n elif message.text == \"Пятница\":\n text = get_schedule('Птн', message.from_user.id)\n bot.send_message(message.chat.id, text, reply_markup=markup_schedule)\n elif message.text == \"Суббота\":\n text = get_schedule('Сбт', message.from_user.id)\n bot.send_message(message.chat.id, text, reply_markup=markup_schedule)\n elif message.text == \"Основные сайты\":\n text = '\\u25b6\\ufe0f [Личный кабинет студента](https://sfedu.ru/www/stat_pages22.show?p=STD/lks/D)\\n\\u25b6\\ufe0f [LMS](https://lms.sfedu.ru)\\n\\u25b6\\ufe0f [БРС](https://grade.sfedu.ru/)\\n\\u25b6\\ufe0f [Сайт ИКТИБа](http://ictis.sfedu.ru/)\\n\\u25b6\\ufe0f [Проектный офис ИКТИБ](https://proictis.sfedu.ru/)'\n bot.send_message(message.chat.id, text, reply_markup=markup_info, parse_mode='MarkdownV2')\n elif message.text == \"Группы Вконтакте\":\n text = '\\u27A1\\ufe0f [Физическая культура в ИТА ЮФУ](https://vk.com/club101308251)\\n\\u27A1\\ufe0f [Подслушано в ЮФУ](https://vk.com/overhearsfedu)\\n\\u27A1\\ufe0f [ИКТИБ ЮФУ](https://vk.com/ictis_sfedu)\\n\\u27A1\\ufe0f [Студенческий клуб ИТА ЮФУ \\(г\\. Таганрог\\)](https://vk.com/studclub_tgn)\\n\\u27A1\\ufe0f [Студенческий киберспортивный клуб ЮФУ](https://vk.com/esports_sfedu)\\n\\u27A1\\ufe0f [Культура здоровья в ИТА ЮФУ](https://vk.com/club150688847)\\n\\u27A1\\ufe0f [Первокурснику](https://vk.com/1kurs_ita_2019)\\n\\u27A1\\ufe0f [Технологии \\+ Проекты \\+ Инновации ИКТИБ](https://vk.com/proictis)\\n\\u27A1\\ufe0f [Волонтерский центр ИКТИБ ЮФУ](https://vk.com/ictis_vol)'\n bot.send_message(message.chat.id, text, reply_markup=markup_info, parse_mode='MarkdownV2')\n elif message.text == \"Корпус А\":\n text = \"Таганрог, улица Чехова, 22\"\n bot.send_message(message.chat.id, text, reply_markup=markup_corps)\n bot.send_location(message.chat.id, latitude=\"47.205446\", longitude=\"38.938832\")\n elif message.text == \"Корпус Б\":\n text = \"Таганрог, улица Чехова, 22\"\n bot.send_message(message.chat.id, text, reply_markup=markup_corps)\n bot.send_location(message.chat.id, latitude=\"47.205396\", longitude=\"38.938842\")\n elif message.text == \"Корпус В\":\n text = \"Таганрог, ул. Петровская, 81\"\n bot.send_message(message.chat.id, text, reply_markup=markup_corps)\n bot.send_location(message.chat.id, latitude=\"47.216498\", longitude=\"38.926859\")\n elif message.text == \"Корпус Г\":\n text = \"Таганрог, Некрасовский переулок, 42\"\n bot.send_message(message.chat.id, text, reply_markup=markup_corps)\n bot.send_location(message.chat.id, latitude=\"47.203241\", longitude=\"38.934853\")\n elif message.text == \"Корпус Д\":\n text = \"Таганрог, Некрасовский переулок, 44\"\n bot.send_message(message.chat.id, text, reply_markup=markup_corps)\n bot.send_location(message.chat.id, latitude=\"47.205446\", longitude=\"38.938832\")\n elif message.text == \"Корпус Е\":\n text = \"Таганрог, ул. Шевченко, 2\"\n bot.send_message(message.chat.id, text, reply_markup=markup_corps)\n bot.send_location(message.chat.id, latitude=\"47.204446\", longitude=\"38.944437\")\n elif message.text == \"Корпус И\":\n text = \"Таганрог, улица Чехова, 2\"\n bot.send_message(message.chat.id, text, reply_markup=markup_corps)\n bot.send_location(message.chat.id, latitude=\"47.203932\", longitude=\"38.943927\")\n elif message.text == \"Корпус К\":\n text = \"Таганрог, ул. Шевченко, 2\"\n bot.send_message(message.chat.id, text, reply_markup=markup_corps)\n bot.send_location(message.chat.id, latitude=\"47.204446\", longitude=\"38.944437\")\n elif message.text == \"Настройки\":\n group = \"Неизвестно\"\n group = get_user_group(message.from_user.id)\n markup_config = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup_config.row(\"Группа: {}\".format(group))\n markup_config.row(\"Назад\")\n text = \"Настройки\"\n bot.send_message(message.chat.id, text, reply_markup=markup_config)\n elif message.text == \"Группа: {}\".format(group):\n msg = bot.send_message(message.chat.id, \"Введите группу (Пример КТбо2-3)\")\n bot.register_next_step_handler(msg, change_group)\n elif message.text == \"Собственное расписание\":\n bot.send_message(message.chat.id, \"Выберите день\", reply_markup=gen_markup())\n # if message.text == \"Пнд\":\n # bot.send_message(message.chat.id, \"Выберите пару\", reply_markup=markup_user_schedule_pair_count)\n else:\n bot.send_message(message.chat.id, \"Вы вернулись назад\", reply_markup=markup_menu)\n\ndef change_group(message):\n url = \"http://ictib.host1809541.hostland.pro/index.php/api/change_user_group\"\n print(message.text)\n params = dict(\n user_id=message.from_user.id,\n user_group=message.text\n )\n resp = requests.get(url=url, params=params)\n print(resp.content)\n binary = resp.content\n data = json.loads(binary)\n\n chat_id = message.chat.id\n\n if data['success'] == 'true':\n global group\n text = 'Все окей'\n group = message.text\n markup_config = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup_config.row(\"Группа: {}\".format(group))\n markup_config.row(\"Назад\")\n bot.send_message(chat_id, text, reply_markup=markup_config)\n elif data['success'] == 'false':\n msg = bot.reply_to(message, \"Повтори\")\n bot.register_next_step_handler(msg, change_group)\n else:\n msg = bot.reply_to(message, \"Ты уже есть\")\n bot.register_next_step_handler(msg, change_group)\n\n\ndef get_week_schedule(user_id):\n url = \"http://ictib.host1809541.hostland.pro/index.php/api/get_week_schedule\"\n params = dict(\n user_id=user_id\n )\n resp = requests.get(url=url, params=params)\n return resp.content\n\ndef get_schedule(day, user_id):\n schedule = []\n pair_list = []\n url = \"http://ictib.host1809541.hostland.pro/index.php/api/get_day_schedule\"\n params = dict(\n day=day,\n user_id=user_id\n )\n resp = requests.get(url=url, params=params)\n print(resp.content)\n binary = resp.content\n data = json.loads(binary)\n for idx, pair in enumerate(data['pairs'], start=0):\n del pair_list[:]\n if pair['pair_name']:\n pair_list.append(\"Пара №{}: {} \\n\".format(idx+1, pair['time']))\n pair_list.append(pair['pair_name'] + '\\n\\n')\n else:\n pair_list.append(\"Пара №{}: Окно \\n\\n\".format(idx+1))\n print(pair_list)\n schedule.append(pair_list[:])\n print(schedule)\n print(schedule)\n text = ''\n\n for schedules in schedule:\n text += '' + ''.join(schedules)\n \n text = \"Дата - {}\\nНеделя - {}\\n\\n{}\".format(data['day'], data['week'], text)\n\n # data = json.dumps(data) \n return text\n\ndef get_day_of_week(today):\n day = datetime.datetime.today().weekday()+1\n print(datetime.datetime.today())\n print(day)\n if not today:\n day += 1\n if day == 1:\n print('Пнд')\n return 'Пнд'\n elif day == 2:\n print('Втр')\n return 'Втр'\n elif day == 3:\n print('Срд')\n return 'Срд'\n elif day == 4:\n print('Чтв')\n return 'Чтв'\n elif day == 5:\n print('Птн')\n return 'Птн' \n elif day == 6:\n print('Сбт')\n return 'Сбт' \n else:\n print('undefined')\n return 'Пнд'\n\ndef get_user_group(user_id):\n url = \"http://ictib.host1809541.hostland.pro/index.php/api/get_info\"\n params = dict(\n user_id=user_id\n )\n resp = requests.get(url=url, params=params)\n binary = resp.content\n print(binary)\n data = json.loads(binary)\n user_group = data['user_group']\n return user_group\n\n# SERVER SIDE \n@server.route('/' + config.token, methods=['POST'])\ndef getMessage():\n bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode(\"utf-8\"))])\n return \"!\", 200\n@server.route(\"/\")\ndef webhook():\n bot.remove_webhook()\n bot.set_webhook(url='https://infinite-waters-23955.herokuapp.com/' + TOKEN)\n return \"!\", 200\nif __name__ == \"__main__\":\n server.run(host=\"0.0.0.0\", port=int(os.environ.get('PORT', 5000)))\n\n# if __name__ == '__main__':\n# bot.polling(none_stop=True)","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":14151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"406069008","text":"\n\"\"\"\nSample client code for read_mnist.py.\n\nAuthor: RR\n\"\"\"\n\nfrom read_mnist import load_data, pretty_print\nfrom PIL import Image\nFEATURE = 0\nLABEL = 1\n \ndef main():\n \"\"\" Example of how to load and parse MNIST data. \"\"\"\n \n train_set, test_set = load_data()\n\n # train_set is a two-element tuple. The first element, i.e.,\n # train_set[0] is a 60,000 x 784 numpy matrix. There are 60k\n # rows in the matrix, each row corresponding to a single example.\n # There are 784 columns, each corresponding to the value of a\n # single pixel in the 28x28 image.\n print (\"\\nDimensions of training set feature matrix:\"), \n print (train_set[FEATURE].shape)\n\n # The labels for each example are maintained separately in train_set[1].\n # This is a 60,000 x 1 numpy matrix, where each element is the label\n # for the corresponding training example.\n print (\"\\nDimensions of training set label matrix:\", train_set[LABEL].shape)\n\n # Example of how to access a individual training example (in this case,\n # the third example, i.e., the training example at index 2). We could \n # also just use print to output it to the screen, but pretty_print formats \n # the data in a nicer way: if you squint, you should be able to make out \n # the number 4 in the matrix data.\n print (\"\\nFeatures of third training example:\\n\")\n pretty_print(train_set[FEATURE][2])\n\n # And here's the label that goes with that training example\n print (\"\\nLabel of first training example:\", train_set[LABEL][2], \"\\n\")\n\n img = Image.new(\"RGB\",(28,28))\n pxl = img.load()\n for x in range(28):\n for y in range(28):\n v = int((train_set[FEATURE][2][28*y+x])*255)\n pxl[x,y] = (v,v,v)\n img.save(\"my.jpg\")\n\n \n # The test_set is organized in the same way, but only contains 10k\n # examples. Don't touch this data until your model is frozen! Perform all\n # cross-validation, model selection, hyperparameter tuning etc. on the 60k\n # training set. Use the test set simply for reporting performance.\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"48427277","text":"# Copyright 2014 The Oppia Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for the user notification dashboard and 'my explorations' pages.\"\"\"\n\nfrom core.domain import feedback_services\nfrom core.domain import rights_manager\nfrom core.domain import user_jobs_continuous\nfrom core.tests import test_utils\nimport feconf\n\n\nclass HomePageTest(test_utils.GenericTestBase):\n\n def test_logged_out_homepage(self):\n \"\"\"Test the logged-out version of the home page.\"\"\"\n response = self.testapp.get('/')\n self.assertEqual(response.status_int, 302)\n self.assertIn('gallery', response.headers['location'])\n response.follow().mustcontain(\n 'Your personal tutor',\n 'Oppia - Gallery', 'About', 'Sign in', no=['Logout'])\n\n def test_notifications_dashboard_redirects_for_logged_out_users(self):\n \"\"\"Test the logged-out view of the notifications dashboard.\"\"\"\n response = self.testapp.get('/notifications_dashboard')\n self.assertEqual(response.status_int, 302)\n # This should redirect to the login page.\n self.assertIn('signup', response.headers['location'])\n self.assertIn('notifications_dashboard', response.headers['location'])\n\n self.login('reader@example.com')\n response = self.testapp.get('/notifications_dashboard')\n # This should redirect the user to complete signup.\n self.assertEqual(response.status_int, 302)\n self.logout()\n\n def test_logged_in_notifications_dashboard(self):\n \"\"\"Test the logged-in view of the notifications dashboard.\"\"\"\n self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME)\n\n self.login(self.EDITOR_EMAIL)\n response = self.testapp.get('/notifications_dashboard')\n self.assertEqual(response.status_int, 200)\n response.mustcontain(\n 'Notifications', 'Logout',\n self.get_expected_logout_url('/'),\n no=['Sign in', 'Your personal tutor',\n self.get_expected_login_url('/')])\n self.logout()\n\n\nclass MyExplorationsHandlerTest(test_utils.GenericTestBase):\n\n MY_EXPLORATIONS_DATA_URL = '/myexplorationshandler/data'\n\n COLLABORATOR_EMAIL = 'collaborator@example.com'\n COLLABORATOR_USERNAME = 'collaborator'\n\n EXP_ID = 'exp_id'\n EXP_TITLE = 'Exploration title'\n\n def setUp(self):\n super(MyExplorationsHandlerTest, self).setUp()\n self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME)\n self.signup(self.COLLABORATOR_EMAIL, self.COLLABORATOR_USERNAME)\n self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME)\n\n self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL)\n self.collaborator_id = self.get_user_id_from_email(\n self.COLLABORATOR_EMAIL)\n self.viewer_id = self.get_user_id_from_email(self.VIEWER_EMAIL)\n\n def test_no_explorations(self):\n self.login(self.OWNER_EMAIL)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(response['explorations_list'], [])\n self.logout()\n\n def test_managers_can_see_explorations(self):\n self.save_new_default_exploration(\n self.EXP_ID, self.owner_id, title=self.EXP_TITLE)\n self.set_admins([self.OWNER_USERNAME])\n\n self.login(self.OWNER_EMAIL)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(len(response['explorations_list']), 1)\n self.assertEqual(\n response['explorations_list'][0]['status'],\n rights_manager.ACTIVITY_STATUS_PRIVATE)\n\n rights_manager.publish_exploration(self.owner_id, self.EXP_ID)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(len(response['explorations_list']), 1)\n self.assertEqual(\n response['explorations_list'][0]['status'],\n rights_manager.ACTIVITY_STATUS_PUBLIC)\n\n rights_manager.publicize_exploration(self.owner_id, self.EXP_ID)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(len(response['explorations_list']), 1)\n self.assertEqual(\n response['explorations_list'][0]['status'],\n rights_manager.ACTIVITY_STATUS_PUBLICIZED)\n self.logout()\n\n def test_collaborators_can_see_explorations(self):\n self.save_new_default_exploration(\n self.EXP_ID, self.owner_id, title=self.EXP_TITLE)\n rights_manager.assign_role_for_exploration(\n self.owner_id, self.EXP_ID, self.collaborator_id,\n rights_manager.ROLE_EDITOR)\n self.set_admins([self.OWNER_USERNAME])\n\n self.login(self.COLLABORATOR_EMAIL)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(len(response['explorations_list']), 1)\n self.assertEqual(\n response['explorations_list'][0]['status'],\n rights_manager.ACTIVITY_STATUS_PRIVATE)\n\n rights_manager.publish_exploration(self.owner_id, self.EXP_ID)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(len(response['explorations_list']), 1)\n self.assertEqual(\n response['explorations_list'][0]['status'],\n rights_manager.ACTIVITY_STATUS_PUBLIC)\n\n rights_manager.publicize_exploration(self.owner_id, self.EXP_ID)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(len(response['explorations_list']), 1)\n self.assertEqual(\n response['explorations_list'][0]['status'],\n rights_manager.ACTIVITY_STATUS_PUBLICIZED)\n\n self.logout()\n\n def test_viewer_cannot_see_explorations(self):\n self.save_new_default_exploration(\n self.EXP_ID, self.owner_id, title=self.EXP_TITLE)\n rights_manager.assign_role_for_exploration(\n self.owner_id, self.EXP_ID, self.viewer_id,\n rights_manager.ROLE_VIEWER)\n self.set_admins([self.OWNER_USERNAME])\n\n self.login(self.VIEWER_EMAIL)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(response['explorations_list'], [])\n\n rights_manager.publish_exploration(self.owner_id, self.EXP_ID)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(response['explorations_list'], [])\n\n rights_manager.publicize_exploration(self.owner_id, self.EXP_ID)\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(response['explorations_list'], [])\n self.logout()\n\n def test_can_see_feedback_thread_counts(self):\n self.save_new_default_exploration(\n self.EXP_ID, self.owner_id, title=self.EXP_TITLE)\n\n self.login(self.OWNER_EMAIL)\n\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(len(response['explorations_list']), 1)\n self.assertEqual(\n response['explorations_list'][0]['num_open_threads'], 0)\n self.assertEqual(\n response['explorations_list'][0]['num_total_threads'], 0)\n\n def mock_get_thread_analytics(unused_exploration_id):\n return {\n 'num_open_threads': 2,\n 'num_total_threads': 3,\n }\n\n with self.swap(\n feedback_services, 'get_thread_analytics',\n mock_get_thread_analytics):\n\n response = self.get_json(self.MY_EXPLORATIONS_DATA_URL)\n self.assertEqual(len(response['explorations_list']), 1)\n self.assertEqual(\n response['explorations_list'][0]['num_open_threads'], 2)\n self.assertEqual(\n response['explorations_list'][0]['num_total_threads'], 3)\n\n self.logout()\n\n\nclass NotificationsDashboardHandlerTest(test_utils.GenericTestBase):\n\n DASHBOARD_DATA_URL = '/notificationsdashboardhandler/data'\n\n def setUp(self):\n super(NotificationsDashboardHandlerTest, self).setUp()\n self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME)\n self.viewer_id = self.get_user_id_from_email(self.VIEWER_EMAIL)\n\n def _get_recent_notifications_mock_by_viewer(self, unused_user_id):\n \"\"\"Returns a single feedback thread by VIEWER_ID.\"\"\"\n return (100000, [{\n 'activity_id': 'exp_id',\n 'activity_title': 'exp_title',\n 'author_id': self.viewer_id,\n 'last_updated_ms': 100000,\n 'subject': 'Feedback Message Subject',\n 'type': feconf.UPDATE_TYPE_FEEDBACK_MESSAGE,\n }])\n\n def _get_recent_notifications_mock_by_anonymous_user(self, unused_user_id):\n \"\"\"Returns a single feedback thread by an anonymous user.\"\"\"\n return (200000, [{\n 'activity_id': 'exp_id',\n 'activity_title': 'exp_title',\n 'author_id': None,\n 'last_updated_ms': 100000,\n 'subject': 'Feedback Message Subject',\n 'type': feconf.UPDATE_TYPE_FEEDBACK_MESSAGE,\n }])\n\n def test_author_ids_are_handled_correctly(self):\n \"\"\"Test that author ids are converted into author usernames\n and that anonymous authors are handled correctly.\n \"\"\"\n with self.swap(\n user_jobs_continuous.DashboardRecentUpdatesAggregator,\n 'get_recent_notifications',\n self._get_recent_notifications_mock_by_viewer):\n\n self.login(self.VIEWER_EMAIL)\n response = self.get_json(self.DASHBOARD_DATA_URL)\n self.assertEqual(len(response['recent_notifications']), 1)\n self.assertEqual(\n response['recent_notifications'][0]['author_username'],\n self.VIEWER_USERNAME)\n self.assertNotIn('author_id', response['recent_notifications'][0])\n\n with self.swap(\n user_jobs_continuous.DashboardRecentUpdatesAggregator,\n 'get_recent_notifications',\n self._get_recent_notifications_mock_by_anonymous_user):\n\n self.login(self.VIEWER_EMAIL)\n response = self.get_json(self.DASHBOARD_DATA_URL)\n self.assertEqual(len(response['recent_notifications']), 1)\n self.assertEqual(\n response['recent_notifications'][0]['author_username'], '')\n self.assertNotIn('author_id', response['recent_notifications'][0])\n","sub_path":"core/controllers/home_test.py","file_name":"home_test.py","file_ext":"py","file_size_in_byte":10835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"539250909","text":"\"\"\"\nCode for the HackerRank SockMerchant challenge.\n\nSource:\nhttps://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup\n\"\"\"\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the sockMerchant function below.\ndef sockMerchant(n, ar):\n # Build hash table with counts of each kind of socks\n sock_hash_table = {}\n for sock in ar:\n try:\n sock_hash_table[sock] += 1\n except:\n sock_hash_table[sock] = 1\n \n # For debugging\n print(sock_hash_table)\n\n # Count the number of pairs of each type\n pair_count = 0\n for num_socks in sock_hash_table.values():\n pair_count += int(num_socks / 2)\n \n return pair_count\n\n\nif __name__ == \"__main__\":\n num_socks = 9\n sock_arr = [10,20,20,10,10,30,50,10,20]\n print(sockMerchant(num_socks, sock_arr))","sub_path":"sock_merchant.py","file_name":"sock_merchant.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"3015435","text":"\nimport seawolf as sw\nfrom sw3 import *\n\nsw.loadConfig(\"../conf/seawolf.conf\")\nsw.init(\"SW3 Command Line Interface\")\n\ndef zero_thrusters():\n #nav.clear()\n nav.do(NullRoutine())\n\n pid.yaw.pause()\n pid.rotate.pause()\n pid.pitch.pause()\n pid.depth.pause()\n\n mixer.depth = 0\n mixer.pitch = 0\n mixer.yaw = 0\n mixer.forward = 0\n mixer.strafe = 0\n\ndef square():\n nav.clear()\n a = data.imu.yaw\n nav.append(Forward(0.6, timeout=5))\n nav.append(SetYaw(util.add_angle(a, 90)))\n nav.append(Forward(0.6, timeout=5))\n nav.append(SetYaw(util.add_angle(a, 180)))\n nav.append(Forward(0.6, timeout=5))\n nav.append(SetYaw(util.add_angle(a, 270)))\n nav.append(Forward(0.6, timeout=5))\n return nav.append(SetYaw(a))\n\nEB = emergency_breech\nZT = zero_thrusters\nzt = ZT\n\n","sub_path":"mission_control/sw3_cmd.py","file_name":"sw3_cmd.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"84185975","text":"from glob import glob\nfrom setuptools import find_packages, setup\nimport sys\n\ntry:\n from pybind11.setup_helpers import Pybind11Extension, build_ext\nexcept ImportError:\n from setuptools import Extension as Pybind11Extension\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nexec(open('submodlib/version.py').read())\n\next_modules = [\n Pybind11Extension(\"submodlib_cpp\",\n #[\"cpp/submod/wrapper.cpp\",\"cpp/submod/FacilityLocation.cpp\", \"cpp/submod/wr_FacilityLocation.cpp\", \"cpp/submod/helper.cpp\", \"cpp/submod/wr_helper.cpp\",\"cpp/submod/sparse_utils.cpp\", \"cpp/submod/wr_sparse_utils.cpp\",\"cpp/optimizers/NaiveGreedyOptimizer.cpp\", \"cpp/submod/SetFunction.cpp\",\"cpp/submod/ClusteredFunction.cpp\", \"cpp/submod/wr_ClusteredFunction.cpp\"],\n [\"cpp/wrappers/wrapper.cpp\",\"cpp/submod/FacilityLocation.cpp\", \"cpp/wrappers/wr_FacilityLocation.cpp\", \"cpp/submod/DisparitySum.cpp\", \"cpp/wrappers/wr_DisparitySum.cpp\", \"cpp/utils/helper.cpp\", \"cpp/wrappers/wr_helper.cpp\",\"cpp/utils/sparse_utils.cpp\", \"cpp/wrappers/wr_sparse_utils.cpp\",\"cpp/optimizers/NaiveGreedyOptimizer.cpp\", \"cpp/submod/SetFunction.cpp\",\"cpp/submod/ClusteredFunction.cpp\", \"cpp/wrappers/wr_ClusteredFunction.cpp\"],\n # Example: passing in the version to the compiled code\n #sorted(glob(\"cpp/submod/*.cpp\")),\n define_macros = [('VERSION_INFO', __version__)],\n ),\n]\n\n\nsetup(\n name='submodlib',\n #packages=find_packages(include=['submodlib']),\n packages=['submodlib', 'submodlib/functions'],\n #packages=find_packages('submodlib'),\n #package_dir={'':'submodlib'},\n #version='0.0.2',\n version=__version__,\n description='submodlib is an efficient and scalable library for submodular optimization which finds its application in summarization, data subset selection, hyper parameter tuning etc.',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author='Vishal Kaushal',\n cmdclass={\"build_ext\": build_ext},\n ext_modules=ext_modules,\n author_email='vishal.kaushal@gmail.com',\n url=\"https://github.com/vishkaush/submodlib\",\n #url='http://pypi.python.org/pypi/submodlib/',\n #url=\"https://github.com/pypa/sampleproject\",\n license='MIT',\n # install_requires=[\n # \"numpy >= 1.14.2\",\n # \"scipy >= 1.0.0\",\n # \"numba >= 0.43.0\",\n # \"tqdm >= 4.24.0\",\n # \"nose\"\n # ],\n install_requires=[],\n setup_requires=['pybind11','pytest-runner'],\n tests_require=['pytest'],\n test_suite='tests',\n #classifiers=[\n # \"Programming Language :: Python :: 3\",\n # \"License :: OSI Approved :: MIT License\",\n # \"Operating System :: OS Independent\",\n #],\n zip_safe=False \n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"174435898","text":"import os\r\nimport glob\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport random\r\nimport matplotlib.pyplot as plt \r\n\r\nimages_array1=[]\r\nimages_array=[]\r\nlabels_array=[]\r\n\r\nf=(glob.glob(\"C:/Users/vishn/Pictures/Camera Roll/left1/left_small/*.jpg\"))\r\n\r\nfor fname in f:\r\n\timages_array1.append([np.array(Image.open(fname)),[1,0,0]])\r\n\r\nf=(glob.glob(\"C:/Users/vishn/Pictures/Camera Roll/right1/right_small/*.jpg\"))\r\n\r\nfor fname in f:\r\n\timages_array1.append([np.array(Image.open(fname)),[0,0,1]])\r\n\r\nf=(glob.glob(\"C:/Users/vishn/Pictures/Camera Roll/center1/center_small/*.jpg\"))\r\n\r\nfor fname in f:\r\n\timages_array1.append([np.array(Image.open(fname)),[0,1,0]])\r\n\r\n\r\n# print(images_array[0])\r\n\r\nrandom.shuffle(images_array1)\r\n\r\nfor i in images_array1:\r\n\timages_array.append(i[0])\r\n\tlabels_array.append(i[1])\r\n\r\n# train_images=np.array(i[0] for i in images_array)\r\n# train_labels=np.array(i[1] for i in images_array)\r\n\r\n\r\n# print(images_array[0])\r\n\r\n# train_images=train_images / 255.0\r\n# for i in images_array:\r\n# \ti[0]=i[0]/255.0\r\n\r\n\r\ntrain_images=np.array(images_array)\r\ntrain_labels=np.array(labels_array)\r\n\r\ntrain_images=train_images/255.0\r\n\r\nprint(train_images.shape)\r\nprint(train_labels)\r\n\r\nprint(train_images[0])\r\n\r\nnp.save('saved_images',train_images[:2500])\r\nnp.save('saved_labels',train_labels[:2500])\r\nnp.save('saved_images_test',train_images[2500:])\r\nnp.save('saved_labels_test',train_labels[2500:])\r\n\r\n# plt.figure(figsize=(10,10))\r\n# for i in range(25):\r\n# plt.subplot(5,5,i+1)\r\n# plt.xticks([])\r\n# plt.yticks([])\r\n# plt.grid(False)\r\n# plt.imshow(train_images[i], cmap=plt.cm.binary)\r\n# plt.xlabel(train_labels[i])\r\n# plt.show()\r\n# print(train_images)\r\n","sub_path":"first_pickle_images.py","file_name":"first_pickle_images.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"539499842","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth import login\n\nfrom manozodynas.forms import *\nfrom manozodynas.models import *\n\ndef login_view(request):\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n user = form.cleaned_data['user']\n if user is not None and user.is_active:\n login(request, user)\n return HttpResponseRedirect(reverse('index'))\n else:\n form = LoginForm()\n #import ipdb; ipdb.set_trace()\n return render(request, 'manozodynas/login.html', {'form':form})\n\n\ndef word_view(request):\n # import pdb; pdb.set_trace()\n if request.method == 'POST':\n form_word = WordsForm(request.POST)\n if form_word.is_valid():\n form_word.save()\n form_word = WordsForm()\n else:\n form_word = WordsForm()\n\n# wocabulary part\n word_info = Words.objects.order_by('key') \n\n# end of wocabulary part \n return render(request, 'word.html', {\n 'form_word':form_word,\n 'USER': request.user,\n 'wocabulary': word_info,\n })\n\ndef main_view(request, word_id):\n if request.method == 'POST':\n form = TranslationForm(request.POST) # construct form with errors\n form_word = WordsForm(request.POST)\n\n if form.is_valid():\n instance = form.save(commit=False)\n instance.author = request.user\n instance.save()\n form = TranslationForm()\n\n if form_word.is_valid():\n form_word.save()\n form_word = TranslationForm()\n\n else:\n form = TranslationForm()\n form_word = WordsForm()\n\n# wocabulary part\n wocab = Translation.objects.order_by('key_word') \n word_info = []\n if word_id >= 0:\n word = Translation.objects.filter(id=word_id)\n arr = word[0].matches.split(\" \")\n for elem in arr:\n curr = Words.objects.filter(key=elem)\n if len(curr) > 0:\n word_info.append(curr[0])\n else:\n word_info.append(Words(key=elem, description=\"\"))\n# end of wocabulary part \n return render(request, 'main.html', {\n 'form': form,\n 'form_word':form_word,\n 'USER': request.user,\n 'wocabulary': wocab,\n 'word_id': word_id,\n 'word_info': word_info,\n })\n","sub_path":"src/manozodynas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"569893410","text":"import numpy as np\nimport pandas as pd\nimport time\nimport gym\nimport csv\nimport os\nimport pickle\nfrom queue import Queue\nimport pickle\nimport random\nfrom tensorboardX import SummaryWriter\n\n#device = 'cuda' if torch.cuda.is_available() else 'cpu'\ndirectory = './runs'\n\nclass QLearning:\n def __init__(self, learning_rate=0.1, reward_decay=0.99, e_greedy=0.8):\n #self.target # 目标状态(终点)\n self.lr = learning_rate # 学习率\n self.gamma = reward_decay # 回报衰减率\n self.epsilon = e_greedy # 探索/利用 贪婪系数\n self.num_cos = 10 #分为多少份\n self.num_sin = 10 \n self.num_dot = 10 \n self.num_actions = 10 \n self.actions = self.toBins(-2.0, 2.0, self.num_actions) # 可以选择的动作空间 离散化\n # q_table是一个二维数组 # 离散化后的状态共有num_pos*num_vel中可能的取值,每种状态会对应一个行动# q_table[s][a]就是当状态为s时作出行动a的有利程度评价值\n self.q_table = np.random.uniform(low=-1, high=1, size=(self.num_cos*self.num_sin*self.num_dot, self.num_actions)) # Q值表\n self.cos_bins = self.toBins(-1.0, 1.0, self.num_cos)\n self.sin_bins = self.toBins(-1.0, 1.0, self.num_sin)\n self.dot_bins = self.toBins(-8.0, 8.0, self.num_dot)\n self.writer = SummaryWriter(directory)\n self.num_learn_iteration=0\n\n # 根据本次的行动及其反馈(下一个时间步的状态),返回下一次的最佳行动\n def choose_action(self,state):\n # 假设epsilon=0.9,下面的操作就是有0.9的概率按Q值表选择最优的,有0.1的概率随机选择动作\n # 随机选动作的意义就是去探索那些可能存在的之前没有发现但是更好的方案/动作/路径\n if np.random.uniform() < self.epsilon:\n # 选择最佳动作(Q值最大的动作)\n action = np.argmax(self.q_table[state])\n else:\n # 随机选择一个动作\n action = np.random.choice(self.actions)\n action = -2 + 4/(self.num_actions-1) * action #从离散整数变为范围内值\n return action\n\n # 分箱处理函数,把[clip_min,clip_max]区间平均分为num段, 如[1,10]分为5.5 \n def toBins(self,clip_min, clip_max, num):\n return np.linspace(clip_min, clip_max, num + 1)[1:-1] #第一项到倒数第一项\n\n # 分别对各个连续特征值进行离散化 如[1,10]分为5.5 小于5.5取0 大于取5.5取1\n def digit(self,x, bin): \n n = np.digitize(x,bins = bin)\n return n\n\n # 将观测值observation离散化处理\n def digitize_state(self,observation):\n # 将矢量打散回4个连续特征值\n cart_sin, cart_cos , cart_dot = observation\n # 分别对各个连续特征值进行离散化(分箱处理)\n digitized = [self.digit(cart_sin,self.cos_bins),\n self.digit(cart_cos,self.sin_bins),\n self.digit(cart_dot,self.dot_bins)]\n # 将离散值再组合为一个离��值,作为最终结果\n return (digitized[1]*self.num_cos + digitized[0]) * self.num_dot + digitized[2]\n\n # 学习,主要是更新Q值\n def learn(self, state, action, r, next_state):\n action = self.digit(action,self.actions)\n next_action = np.argmax(self.q_table[next_state]) \n q_predict = self.q_table[state, action]\n q_target = r + self.gamma * self.q_table[next_state, next_action] # Q值的迭代更新公式\n loss=(q_target - q_predict)**2\n self.writer.add_scalar('Loss',loss,global_step=self.num_learn_iteration)\n self.q_table[state, action] += self.lr * (q_target - q_predict) # update\n self.num_learn_iteration+=1\n\n\ndef train():\n env = gym.make('Pendulum-v0') \n #print(env.action_space)\n agent = QLearning()\n # with open(os.getcwd()+'/tmp/Pendulum.model', 'rb') as f:\n # agent = pickle.load(f)\n action = [0] #输入格式要求 要是数组\n ep_r = 0\n for i in range(10000): #训练次数\n observation = env.reset() #状态 cos(theta), sin(theta) , thetadot角速度\n state = agent.digitize_state(observation) #状态标准化\n for t in range(200): #一次训练最大运行次数\n action[0] = agent.choose_action(state) #动作 -2到2\n observation, reward, done, info = env.step(action) \n next_state = agent.digitize_state(observation)\n # if done:\n # reward-=200 #对于一些直接导致最终失败的错误行动,其报酬值要减200\n #但是上面这个好像会出问题,因为done好像就是能保持的时候\n # if reward >= -1: #竖直时时reward接近0 -10到0\n # reward+=40 #给大一点\n # #print('arrive')\n # print(action,reward,done,state,next_state)\n ep_r +=reward\n agent.learn(state,action[0],reward,next_state)\n state = next_state\n if done: #done 重新加载环境 \n agent.writer.add_scalar('ep_r',ep_r,global_step=i)\n print(\"Episode{} finished after {} timesteps,return is {}\".format(i,t+1,ep_r))\n ep_r = 0\n break\n # env.render() # 更新并渲染画面\n #print(agent.q_table)\n env.close()\n #保存 \n np.save('q_table.npy', agent.q_table)\n # with open(os.getcwd()+'/tmp/Pendulum.model', 'wb') as f:\n # pickle.dump(agent, f)\n\ndef test(test_iteration=10):\n env = gym.make('Pendulum-v0') \n print(env.action_space)\n agent=QLearning()\n agent.q_table=np.load('q_table.npy')\n # with open(os.getcwd()+'/tmp/Pendulum.model', 'rb') as f:\n # agent = pickle.load(f)\n agent.epsilon = 1 #测试时取1 每次选最优结果\n \n num=0\n for i in range(test_iteration):\n observation = env.reset() #\n state = agent.digitize_state(observation) #状态标准化\n action = [0] #输入格式要求 要是数组\n pre_reward=-10\n for t in range(200): #一次训练最大运行次数\n action[0] = agent.choose_action(state) #\n observation, reward, done, info = env.step(action) \n # if done:\n # print(reward)\n next_state = agent.digitize_state(observation)\n # print(action,reward,done,state,next_state)\n # print(observation)\n if reward >= -0.5 and pre_reward>-0.5: #竖直时时reward接近0 -10到0\n num+=1\n break\n # print('arrive')\n agent.learn(state,action[0],reward,next_state)\n state = next_state\n env.render() # 更新并渲染画面\n pre_reward=reward\n time.sleep(0.02)\n print(num)\n env.close()\n\ndef run_test():\n env = gym.make('Pendulum-v0') \n action = [0]\n observation = env.reset() #状态 \n # print(env.action_space)\n # print(observation)\n actions = np.linspace(-2, 2, 10)\n for t in range(100): #\n # action[0] = random.uniform(-2,2) #力矩 -2到2 \n action[0] = 2\n observation, reward, done, info = env.step(action) \n #print(action,reward,done)\n \n # print('observation:',observation)\n # print('theta:',env.state)\n env.render() \n time.sleep(1)\n env.close()\n\nif __name__ == '__main__':\n #train()\n test()\n #run_test()\n \n\n","sub_path":"codes/Q-learning/q-learning.py","file_name":"q-learning.py","file_ext":"py","file_size_in_byte":7622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"445991395","text":"import logging\nimport time\n\nSEVERITY = {\n logging.DEBUG: 'debug',\n logging.INFO: 'info',\n logging.WARNING: 'warning',\n logging.ERROR: 'error',\n logging.CRITICAL: 'critical'\n}\n\n\nSEVERITY.update((name, name) for name in SEVERITY.values())\n\n\ndef log_recent(conn, name, message, severity=logging.INFO, pipe=None):\n severity = str(SEVERITY.get(severity, severity)).lower()\n destination = 'recent: %s:%s' % (name, severity)\n message = time.asctime() + ' ' + message\n pipe = pipe or conn.pipeline()\n pipe.lpush(destination, message)\n pipe.ltrim(destination, 0, 99)\n pipe.execute()\n\n\n","sub_path":"redis_test/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"364283692","text":"a = 1\n\n\ndef func():\n a = 2\n b = 4\n\n def func2():\n nonlocal a\n a = 100\n nonlocal b\n b = 200\n print(\"fun2\", b)\n print(\"fun2\", a)\n\n func2()\n print(\"fun\", b)\n print(\"fun\", a)\n\n\nfunc()\nprint(\"funcwai\", a)\n","sub_path":"project/base/可迭代对象.py","file_name":"可迭代对象.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"117631354","text":"import csv\nimport datetime\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom elasticsearch import Elasticsearch\nfrom djangodemo.models import EmpolyeeDetails\nfrom .models import EmpolyeeDetails\nfrom djangodemo.forms import EmpolyeeDetailsForm\nimport sqlite3\n# Create your views here.\nelasticSearchObj = Elasticsearch(\n \"https://search-security-questionnarie-7n2rpbfx6hafbye4k4xzfj7z4e.us-east-1.es.amazonaws.com:443\")\n\n\n# this is function for to jump to login page\ndef renderToLogin(request):\n return render(request,'djangodemo/loginPage.html')\n\n\n# this function is to check the username from data base Employee is available then jump to serach or home page\ndef userLogin(request):\n emailData = request.POST['emailId']\n emp = EmpolyeeDetails.objects.all()\n for e in emp:\n if e.eemail == emailData:\n # success =False\n print(e.eemail)\n return render(request,'djangodemo/homepage.html')\n else:\n validate = True\n return render(request,'djangodemo/loginPage.html',{'validate':validate})\n\n\n\n# this is function to get the data from table\ndef displayUser(request):\n emp = EmpolyeeDetails.objects.all()\n for e in emp:\n print(e.eemail)\n return render(request,'djangodemo/admin.html',{'emp':emp})\n\ndef deleteUser(request):\n\n #\n # empdata = EmpolyeeDetails.objects.get(e.eemail)\n # empdata.delete()\n\n # empdata = EmpolyeeDetails.objets.create_user()\n\n ename = EmpolyeeDetails.objects.get(request.POST['chk'])\n # eemail = EmpolyeeDetails.objects.get(request.POST['chk'])\n ename.delete()\n # eemail.delete()\n msg = 'user deleted -------- successfully'\n\n return render(request, 'djangodemo/admin.html', {'msg': msg})\n\n # return render(request, 'ur template where you want to redirect')\n return render(request, 'djangodemo/admin.html')\n\n\n# rom\n# django.shortcuts\n# import render\n# from .models import Post\n\n\ndef addUser(request):\n ename= request.POST.get(\"ename\")\n eemail=request.POST.get(\"eemail\")\n empData=EmpolyeeDetails(ename=ename,eemail=eemail)\n empData.save()\n msg = 'user added successfully'\n return render(request, 'djangodemo/admin.html',{'msg':msg})\n\n\n#this function to search keyword from elastic serach data\ndef serachKeyword(request):\n keyword =request.POST['keyword']\n searchResult = elasticSearchObj.search(index='questionnaire_demo',\n size = 9999,\n body={\n \"query\":{\n \"match\":{\n \"SecurityQuestions\":keyword\n }\n }\n }\n )\n print(searchResult)\n\n requiredData=[]\n venderNameset = set({})\n\n for hit in searchResult['hits']['hits']:\n requiredData.append(hit['_source']) # exatract required data\n venderNameset.add(hit['_source']['VendorName'])\n\n print(type(venderNameset))\n print(venderNameset)\n\n\n return render(request,'djangodemo/homepage.html',{'result':requiredData,'nameSet':venderNameset})\n\n\n# this function is to perfrom upload option from frontend\ndef uploadcsv(request):\n return render(request,'djangodemo/uploadFile.html')\n\ndef toHomePage(request):\n return render(request, 'djangodemo/homepage.html')\n\n\ndef indexFile(request):\n\n # elasticSearchObj.indices.create(index='elasticsearc', ignore=400) # creating index, ignore if already exists\n elasticSearchObj.indices.create(index='questionnaire_demo', ignore=400)\n for csvFile in request.FILES.getlist('csvfile'):\n from io import TextIOWrapper # to convert bytes in string\n file = TextIOWrapper(csvFile.file, encoding=request.encoding) # to get text file\n reader = csv.DictReader(file) # reading csv\n\n indexCounter = 1\n for row in reader:\n elasticSearchObj.index(index='questionnaire_demo', doc_type='document', id=str(csvFile) + str(indexCounter),\n body=row) # indexing file\n indexCounter += 1\n\n try:\n while True:\n elasticSearchObj.delete(index='questionnaire_demo', doc_type='document', id=str(csvFile) + str(indexCounter))\n indexCounter += 1\n except:\n pass\n\n return render(request, 'djangodemo/uploadFile.html')\n\ndef toSerachPage(request):\n return render(request,'djangodemo/homepage.html')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# def demoFun(request):\n# return render(request, 'djangodemo/result.html')\n# # # return return render(request,'demoapp/result.html')\n# # return render(request,'djangodemo/result.html')\n# def wish(request):\n# date=datetime.datetime.now()\n# # h = int(date.strftime('%H'))\n# # h=15\n# h=3\n# msg=' '\n# # if h<12:\n# # msg=msg+'Morning!!!!'\n# # elif h<16:\n# # msg=msg+'Afternoon'\n# # elif h<21:\n# # msg=msg+'Evening'\n# # else:\n# # msg=msg+'Night'\n# # response = render(request,'djangodemo/result.html',{'msgKey':msg,'dateKey':date})\n# # return response\n#\n# if h<12:\n# msg=msg+'Morning'\n# return render(request,'djangodemo/morning.html',{'msgKey':msg,'dateKey':date})\n# elif h<16:\n# msg = msg + 'Afternoon'\n# return render(request,'djangodemo/afternoon.html',{'msgKey':msg,'dateKey':date})\n# elif h<21:\n# msg=msg+'Evening'\n# return render(request,'djangodemo/even.html',{'msgKey':msg,'dateKey':date})\n# else:\n# msg = msg + 'Night'\n# return render(request, 'djangodemo/night.html', {'msgKey': msg, 'dateKey': date})\n","sub_path":"Prognos Project/Working/Namrata rane Git/DjangoProject/Django-ElasticSearch/django_demo/djangodemo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"438916583","text":"import sys\nsys.stdin =open('input.txt', 'r')\n\ndef perm(k):\n global M, N, result, idx\n t = t1\n if k == M:\n li = [0]*k\n for h in range(k):\n li[h] = t[h]\n if sorted(li) not in result:\n result[idx] = li\n idx += 1\n print(' '.join(map(str, li)))\n else:\n for i in range(N):\n t[k] = l[i]\n perm(k+1)\nN, M = map(int, input().split())\nidx = 0\nresult = [0]*(N**M)\nl = [i for i in range(1, 1+N)]\nt1 = [0]*N\nperm(0)","sub_path":"05_알고리즘/190921/N과 M (3).py","file_name":"N과 M (3).py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"452836104","text":"from rest_framework import permissions, status\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework.validators import ValidationError\n\nclass BaseViewSet(ModelViewSet):\n \n def get_queryset(self):\n return self.model_class.objects.all()\n\n # def get_serializer_class(self):\n # return self.serializer_class\n \n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n\n return Response(data={\n 'status':True,\n 'message':f\"{self.instance_name} created successfully\",\n 'data':serializer.data \n })\n\n return Response(data={\n 'status':False,\n 'message':f\"{self.instance_name} failed\",\n 'data':serializer.errors\n })\n \n def list(self, request, *args, **kwargs):\n queryset = get_queryset()\n serializer = self.get_serializer(queryset, many=True)\n \n return Response(data={\n 'status':True,\n 'message':f\"{self.instance_name}'s list retrieved successfully\",\n 'data':serializer.data\n })\n \n def get_object(self, request, pk=None, *args, **kwargs):\n try:\n return self.model_class.objects.get(pk=pk)\n\n except self.model_class.DoesNotExist:\n raise ValidationError({\n 'status': False,\n 'message': f\"{self.instance_name} was not found\",\n \"data\": {}\n })\n","sub_path":"base/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"349350781","text":"# Tutorial Used: https://www.tutorialspoint.com/send-mail-from-your-gmail-account-using-python\nimport os\nimport random\nimport smtplib\nimport string\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nverificationCodes = {}\n\n\ndef send_email(receiver_address, mail_body, subject):\n sender_address = os.getenv(\"GMAIL_USER\")\n sender_password = os.getenv(\"GMAIL_PASS\")\n\n # Setup the Multipurpose Internet Mail Connection\n\n message = MIMEMultipart()\n message['From'] = sender_address\n message['To'] = receiver_address\n message['Subject'] = subject\n message.attach(MIMEText(mail_body, 'html'))\n\n gmail_smtp_port = 587\n session = smtplib.SMTP('smtp.gmail.com', gmail_smtp_port)\n session.starttls() # enable security\n session.login(sender_address, sender_password)\n text = message.as_string()\n session.sendmail(sender_address, receiver_address, text)\n session.quit()\n print('Mail Sent')\n\n\ndef send_confirmation_email(receiver_address, user_id):\n unique_key = get_unique_key()\n\n mail_body_html = \"\"\"\\\n\n \n \n

HONK!
\n Please verify your email address by typing $confirm {0} in the verification channel!
\n If you have time, please reply with something to prevent this message from being flagged as spam.
\n
\n For any concerns, please contact a BediBot Dev :)
\n

\n \n\n\n \"\"\"\n\n verificationCodes[user_id] = unique_key\n\n send_email(receiver_address, mail_body_html.format(unique_key), 'Discord Server 2FA Confirmation')\n\n\ndef get_unique_key():\n length = 10\n letters = string.ascii_letters\n return ''.join(random.choice(letters) for i in range(length))\n","sub_path":"commands/_email.py","file_name":"_email.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"577046293","text":"#!/usr/bin/env python\n# -*- encoding:utf-8 -*-\n# @author: hideyuki.takase\n\nimport twitter\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nCONSUMER_KEY = \"****\"\nCONSUMER_SECRET = \"****\"\nACCESS_TOKEN = '****'\nACCESS_TOKEN_SECRET = '****'\n\napi = twitter.Api(consumer_key=CONSUMER_KEY,\n consumer_secret=CONSUMER_SECRET,\n access_token_key=ACCESS_TOKEN,\n access_token_secret=ACCESS_TOKEN_SECRET)\n\n# 検索\nsearch= u\"****\"\ntweets = api.GetSearch(term=search, count=100,result_type='recent')\ntest = open(\"test.txt\", \"a\")\n\nfor i in tweets:\n test.write(i.created_at.encode(\"utf-8\"))\ntest.close()","sub_path":"search-twitter_twitter.py","file_name":"search-twitter_twitter.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"535399689","text":"import pygame\nfrom GameObject import *\n\npygame.font.init()\nBUTTONFONT = pygame.font.SysFont('arial', 14)\n\nBLACK = ( 0, 0, 0)\nWHITE = (255, 255, 255)\nDARKGRAY = ( 64, 64, 64)\nGRAY = (128, 128, 128)\nLIGHTGRAY = (212, 208, 200)\n\nclass Button(GameObject):\n\n\tdef __init__(self, bgcolor, textcolor, functionRef, rect=None, text='', font=None, normal=None, down=None, hover=None):\n\t\tprint('Initializing button object')\n\t\tif rect is None:\n\t\t\tself._rect = pygame.Rect(0,0,30,60)\n\t\telse:\n\t\t\tself._rect = pygame.Rect(rect)\n\t\tprint('Rect set')\n\n\t\tself._text = text\n\t\tprint('Text set as ' + self._text)\n\t\tself._bgcolor = bgcolor\n\t\tprint('Background color set as ' + str(self._bgcolor))\n\t\tself._textcolor = textcolor\n\t\tprint('Text color set as ' + str(self._textcolor))\n\n\t\tif font is None:\n\t\t\tself._font = BUTTONFONT\n\t\telse:\n\t\t\tself._font = font\n\t\tprint('Font set')\n\n\t\tself.buttonDown = False\n\t\tself.mouseOverButton = False\n\t\tself.lastMouseDownOverButton = False\n\t\tself._visible = True\n\t\tself.customSurfaces = False\n\n\t\tif normal is None:\n\t\t\tself.surfaceNormal = pygame.Surface(self._rect.size)\n\t\t\tself.surfaceDown = pygame.Surface(self._rect.size)\n\t\t\tself.surfaceHover = pygame.Surface(self._rect.size)\n\t\t\tself._update()\n\t\telse:\n\t\t\tself.setSurface(normal, down, hover)\n\t\tprint('Surfaces set')\n\n\t\tself._functionRef = functionRef\n\t\tprint('Function reference set')\n\n\tdef handleEvent(self, eventObj):\n\n\t\tif eventObj.type not in (pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP, pygame.MOUSEBUTTONDOWN) or not self._visible:\n\t\t\treturn []\n\n\t\thasExited = False\n\t\tif not self.mouseOverButton and self._rect.collidepoint(eventObj.pos):\n\t\t\tself.mouseOverButton = True\n\t\t\tself.mouseEnter(eventObj)\n\t\telif self.mouseOverButton and not self._rect.collidepoint(eventObj.pos):\n\t\t\tself.mouseOverButton = False\n\t\t\thasExited = True\n\n\t\tif self._rect.collidepoint(eventObj.pos):\n\t\t\tif eventObj.type == pygame.MOUSEMOTION:\n\t\t\t\tself.mouseMove(eventObj)\n\t\t\telif eventObj.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\tself.buttonDown = True\n\t\t\t\tself.lastMouseDownOverButton = True\n\t\t\t\tself.mouseDown(eventObj)\n\t\telse:\n\t\t\tif eventObj.type in (pygame.MOUSEBUTTONUP, pygame.MOUSEBUTTONDOWN):\n\t\t\t\tself.lastMouseDownOverButton = False\n\n\t\tdoMouseClick = False\n\t\tif eventObj.type == pygame.MOUSEBUTTONUP:\n\t\t\tif self.lastMouseDownOverButton:\n\t\t\t\tdoMouseClick = True\n\t\t\tself.lastMouseDownOverButton = False\n\n\t\t\tif self.buttonDown:\n\t\t\t\tself.buttonDown = False\n\t\t\t\tself.mouseUp(eventObj)\n\n\t\t\tif doMouseClick:\n\t\t\t\tself.buttonDown = False\n\t\t\t\tself.mouseClick(eventObj)\n\n\t\tif hasExited:\n\t\t\tself.mouseExit(eventObj)\n\n\tdef draw(self, surfaceObj):\n\n\t\tif self._visible:\n\t\t\tif self.buttonDown:\n\t\t\t\tsurfaceObj.blit(self.surfaceDown, self._rect)\n\t\t\telif self.mouseOverButton:\n\t\t\t\tsurfaceObj.blit(self.surfaceHover, self._rect)\n\t\t\telse:\n\t\t\t\tsurfaceObj.blit(self.surfaceNormal, self._rect)\n\n\tdef _update(self):\n\n\t\tif self.customSurfaces:\n\t\t\tself.surfaceNormal = pygame.transform.smoothscale(self.origSurfaceNormal, self._rect.size)\n\t\t\tself.surfaceDown = pygame.transform.smoothscale(self.origSurfaceDown, self._rect.size)\n\t\t\tself.surfaceHover = pygame.transform.smoothscale(self.origSurfaceHover, self._rect.size)\n\n\t\tw = self._rect.width\n\t\th = self._rect.height\n\n\t\tself.surfaceNormal.fill(self.bgcolor)\n\t\tself.surfaceDown.fill(self.bgcolor)\n\t\tself.surfaceHover.fill(self.bgcolor)\n\n\t\ttextSurf = self._font.render(self._text, True, self.textcolor, self.bgcolor)\n\t\ttextRect = textSurf.get_rect()\n\t\ttextRect.center = int(w / 2), int(h / 2)\n\t\tself.surfaceNormal.blit(textSurf, textRect)\n\t\tself.surfaceDown.blit(textSurf, textRect)\n\n\t\tpygame.draw.rect(self.surfaceNormal, BLACK, pygame.Rect((0, 0, w, h)), 1)\n\t\tpygame.draw.line(self.surfaceNormal, WHITE, (1, 1), (w - 2, 1))\n\t\tpygame.draw.line(self.surfaceNormal, WHITE, (1, 1), (1, h - 2))\n\t\tpygame.draw.line(self.surfaceNormal, DARKGRAY, (1, h - 1), (w - 1, h - 1))\n\t\tpygame.draw.line(self.surfaceNormal, DARKGRAY, (w - 1, 1), (w - 1, h - 1))\n\t\tpygame.draw.line(self.surfaceNormal, GRAY, (2, h - 2), (w - 2, h - 2))\n\t\tpygame.draw.line(self.surfaceNormal, GRAY, (w - 2, 2), (w - 2, h - 2))\n\n\t\tpygame.draw.rect(self.surfaceDown, BLACK, pygame.Rect((0, 0, w, h)), 1)\n\t\tpygame.draw.line(self.surfaceDown, WHITE, (1, 1), (w - 2, 1))\n\t\tpygame.draw.line(self.surfaceDown, WHITE, (1, 1), (1, h - 2))\n\t\tpygame.draw.line(self.surfaceDown, DARKGRAY, (1, h - 2), (1, 1))\n\t\tpygame.draw.line(self.surfaceDown, DARKGRAY, (1, 1), (w - 2, 1))\n\t\tpygame.draw.line(self.surfaceDown, GRAY, (2, h - 3), (2, 2))\n\t\tpygame.draw.line(self.surfaceDown, GRAY, (2, 2), (w - 3, 2))\n\n\t\tself.surfaceHover = self.surfaceNormal\n\n\tdef mouseClick(self, event):\n\t\tif self._functionRef is not None:\n\t\t\tself._functionRef()\n\t\telse:\n\t\t\tpass\n\tdef mouseEnter(self, event):\n\t\tpass # To be overridden\n\tdef mouseMove(self, event):\n\t\tpass # To be overridden\n\tdef mouseExit(self, event):\n\t\tpass # To be overridden\n\tdef mouseDown(self, event):\n\t\tpass # To be overridden\n\tdef mouseUp(self, event):\n\t\tpass # To be overridden\n\n\tdef setSurface(self, normalSurface, downSurface=None, hoverSurface=None):\n\n\t\tif downSurface is None:\n\t\t\tdownSurface = normalSurface\n\t\tif hoverSurface is None:\n\t\t\thoverSurface = normalSurface\n\n\t\tif type(normalSurface) == str:\n\t\t\tself.origSurfaceNormal = pygame.image.load(normalSurface)\n\t\tif type(downSurface) == str:\n\t\t\tself.origSurfaceDown = pygame.image.load(downSurface)\n\t\tif type(hoverSurface) == str:\n\t\t\tself.origSurfaceHover = pygame.image.load(hoverSurface)\n\n\t\tif self.origSurfaceNormal.get_size() != self.origSurfaceDown.get_size() != self.origSurfaceHover.get_size():\n\t\t\traise Exception('[self.__name__] has mismatching surface sizes.')\n\n\t\tself.surfaceNormal = self.origSurfaceNormal\n\t\tself.surfaceDown = self.origSurfaceDown\n\t\tself.surfaceHover = self.origSurfaceHover\n\t\tself.customSurface = True\n\t\tself._rect = pygame.Rect((self._rect.left, self._rect.top, self.surfaceNormal.get_width(), self.surfaceNormal.get_height()))\n\n\tdef _propGetText(self):\n\t\treturn self._text\n\n\tdef _propSetText(self, text):\n\t\tself.customSurface = False\n\t\tself._text = text\n\t\tself._update()\n\n\tdef _propGetRect(self):\n\t\treturn self._rect\n\n\tdef _propSetRect(self, newRect):\n\t\tself._update()\n\t\tself._rect = newRect\n\t\n\tdef _propSetVisible(self, setting):\n\t\tself._visible = setting\n\n\tdef _propGetVisible(self):\n\t\treturn self._visible\n\n\tdef _propGetTextColor(self):\n\t\treturn self._textcolor\n\n\tdef _propGetBgColor(self):\n\t\treturn self._bgcolor\n\n\tdef _propSetBgColor(self, setting):\n\t\tself.customSurfaces = False\n\t\tself._bgcolor = setting\n\t\tself._update()\n\n\tdef _propSetTextColor(self, setting):\n\t\tself.customSurfaces = False\n\t\tself._textColor = setting\n\t\tself._update()\n\n\tdef _propGetFont(self):\n\t\treturn self._font\n\n\tdef _propSetFont(self, setting):\n\t\tself.customSurfaces = False\n\t\tself._font = setting\n\t\tself._update()\n\n\ttext = property(_propGetText, _propSetText)\n\trect = property(_propGetRect, _propSetRect)\n\tvisible = property(_propGetVisible, _propSetVisible)\n\ttextcolor = property(_propGetTextColor, _propSetTextColor)\n\tbgcolor = property(_propGetBgColor, _propSetBgColor)\n\tfont = property(_propGetFont, _propSetFont)","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":7073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"580704802","text":"import json\nfrom unittest import TestCase\nfrom ContentFS.cpaths.cpath_components_info import CPathComponentsInfo\nfrom ContentFS.exceptions import CFSExceptionInvalidPathName\n\n\nclass TestCPathComponentsInfo(TestCase):\n def test_init(self):\n empty_path = \"\"\n with self.assertRaises(CFSExceptionInvalidPathName):\n cci = CPathComponentsInfo(empty_path)\n\n dot_path = \".\"\n with self.assertRaises(CFSExceptionInvalidPathName):\n cci = CPathComponentsInfo(dot_path)\n\n dot_space_path = \" .\"\n with self.assertRaises(CFSExceptionInvalidPathName):\n cci = CPathComponentsInfo(dot_space_path)\n\n def test_drive__relative(self):\n relative_path = \"hey/\"\n cci_rel = CPathComponentsInfo(relative_path)\n self.assertEqual(\"\", cci_rel.drive)\n\n def test_drive__unix(self):\n unix_path = \"/a path to hell/oh_file.ext\"\n cci_unix = CPathComponentsInfo(unix_path)\n self.assertEqual(\"/\", cci_unix.drive)\n\n def test_drive__windows(self):\n windows_path = r\"C:\\\\dir/file.ext\"\n cci_win = CPathComponentsInfo(windows_path)\n self.assertEqual(\"C:\", cci_win.drive)\n\n def test_drive__file(self):\n file_path = \"file://a file path\"\n cci_file = CPathComponentsInfo(file_path)\n self.assertEqual(cci_file.drive, \"file:\")\n\n def test_names(self):\n relative_path = \"hey/\"\n cci_rel = CPathComponentsInfo(relative_path)\n self.assertEqual((\"hey\",), cci_rel.names)\n\n unix_path = \"/a path to hell/oh_file.ext\"\n cci_unix = CPathComponentsInfo(unix_path)\n self.assertEqual((\"a path to hell\", \"oh_file.ext\"), cci_unix.names)\n\n windows_path = r\"C:\\\\dir/file.ext\"\n cci_win = CPathComponentsInfo(windows_path)\n self.assertEqual((\"dir\", \"file.ext\"), cci_win.names)\n\n file_path = \"file://a file path\"\n cci_file = CPathComponentsInfo(file_path)\n self.assertEqual((\"a file path\",), cci_file.names)\n\n def test_last_char(self):\n relative_path = \"hey/\"\n cci_rel = CPathComponentsInfo(relative_path)\n self.assertEqual(\"/\", cci_rel.last_char)\n\n unix_path = \"/a path to hell/oh_file.ext\"\n cci_unix = CPathComponentsInfo(unix_path)\n self.assertEqual(\"t\", cci_unix.last_char)\n\n windows_path = r\"C:\\\\dir/file.ext\"\n cci_win = CPathComponentsInfo(windows_path)\n self.assertEqual(\"t\", cci_win.last_char)\n\n file_path = \"file://a file path\"\n cci_file = CPathComponentsInfo(file_path)\n self.assertEqual(\"h\", cci_file.last_char)\n\n # *** this part of the test is very important where you will check that even if the last char\n # *** is backward slash it will show as forward slash\n backward_slash_path = \"a path\\\\\"\n cci_backward_slash_path = CPathComponentsInfo(backward_slash_path)\n self.assertEqual(\"/\", cci_backward_slash_path.last_char)\n\n drive_only_path_linux = \"/\"\n cci_drive_only_linux = CPathComponentsInfo(drive_only_path_linux)\n self.assertEqual(\"\", cci_drive_only_linux.last_char)\n\n drive_only_path_windows = \"C://\"\n cci_drive_only_windows = CPathComponentsInfo(drive_only_path_windows)\n self.assertEqual(\"\", cci_drive_only_windows.last_char)\n\n drive_only_path_file = \"file://\"\n cci_drive_only_file = CPathComponentsInfo(drive_only_path_file)\n self.assertEqual(\"\", cci_drive_only_file.last_char)\n\n def test_has_drive(self):\n relative_path = \"hey/\"\n cci_rel = CPathComponentsInfo(relative_path)\n self.assertFalse(cci_rel.has_drive)\n\n unix_path = \"/a path to hell/oh_file.ext\"\n cci_unix = CPathComponentsInfo(unix_path)\n self.assertTrue(cci_unix.has_drive)\n\n windows_path = r\"C:\\\\dir/file.ext\"\n cci_win = CPathComponentsInfo(windows_path)\n self.assertTrue(cci_win.has_drive)\n\n file_path = \"file://a file path\"\n cci_file = CPathComponentsInfo(file_path)\n self.assertTrue(cci_file.has_drive)\n\n def test_has_non_unix_drive(self):\n relative_path = \"hey/\"\n cci_rel = CPathComponentsInfo(relative_path)\n self.assertFalse(cci_rel.has_non_unix_drive)\n\n unix_path = \"/a path to hell/oh_file.ext\"\n cci_unix = CPathComponentsInfo(unix_path)\n self.assertFalse(cci_unix.has_non_unix_drive)\n\n windows_path = r\"C:\\\\dir/file.ext\"\n cci_win = CPathComponentsInfo(windows_path)\n self.assertTrue(cci_win.has_non_unix_drive)\n\n file_path = \"file://a file path\"\n cci_file = CPathComponentsInfo(file_path)\n self.assertTrue(cci_file.has_non_unix_drive)\n\n def test_has_unix_root(self):\n relative_path = \"hey/\"\n cci_rel = CPathComponentsInfo(relative_path)\n self.assertFalse(cci_rel.has_unix_root)\n\n unix_path = \"/a path to hell/oh_file.ext\"\n cci_unix = CPathComponentsInfo(unix_path)\n self.assertTrue(cci_unix.has_unix_root)\n\n windows_path = r\"C:\\\\dir/file.ext\"\n cci_win = CPathComponentsInfo(windows_path)\n self.assertFalse(cci_win.has_unix_root)\n\n file_path = \"file://a file path\"\n cci_file = CPathComponentsInfo(file_path)\n self.assertFalse(cci_file.has_unix_root)\n\n def test_to_dict(self):\n \"\"\"\n Not much to test here as all the other method tests will validate that this is working properly.\n So, one/two tests are enough.\n \"\"\"\n # test empty path string.\n path_string = \"abc\"\n cci = CPathComponentsInfo(path_string)\n self.assertEqual(cci.to_dict(), {\n \"drive\": \"\",\n \"names\": (\"abc\", ),\n \"last_char\": \"c\"\n })\n\n def test_to_json(self):\n \"\"\"\n From to_dict take the value, serialize and deserialize that and match that with deserialized .to_json\n \"\"\"\n path_string = \"/usr/bin/whatever.ext\"\n cci = CPathComponentsInfo(path_string)\n self.assertDictEqual(json.loads(cci.to_json()), json.loads(json.dumps(cci.to_dict())))\n","sub_path":"tests/cpaths/test_cpath_components_info.py","file_name":"test_cpath_components_info.py","file_ext":"py","file_size_in_byte":6074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"270094393","text":"\"\"\"iais URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path, re_path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"register\", views.register_view, name=\"register\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"images\", views.get_user_images, name=\"images\"),\n path(\"advanced_analysis\", views.advanced_analysis, name=\"advanced_analysis\"),\n path(\"upload_image\", views.upload_image, name=\"upload_image\"),\n path(\"get_image/\", views.get_image, name=\"get_image\"),\n path(\"request_img_analysis\", views.request_img_analysis, name=\"request_img_analysis\"),\n path(\"get_img_analysis\", views.get_img_analysis, name=\"get_img_analysis\"),\n re_path(r'(?P[0-9a-f]{32})', views.display_img_search, name=\"displayimgsearch\"),\n re_path(r'(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})', views.display_img_analysis, name=\"displayimgsearch\")\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n","sub_path":"src/imageais/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"549972272","text":"from django.db import models\n# Create your models here.\n\nclass Applicant(models.Model):\n\t# Automatically added on input\n\tfirst_name = models.CharField(max_length=50)\n\tlast_name = models.CharField(max_length=50)\n\temail = models.EmailField(max_length=75)\n\tgraduation_date = models.DateTimeField(auto_now_add=True)\n\twhy_big_essay = models.TextField()\n\tbig_essay1 = models.TextField()\n\tresume = models.FileField(upload_to='applicant_resumes')\n\n\tdef __unicode__(self):\n\t\treturn \"Applicant: \" + self.first_name + \" \" + self.last_name","sub_path":"website/app1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"37072960","text":"# 일단 아래에 필요한 모든 코드를 한 번에 적는다.\n# ���작이 모두 완벽히 잘 되는지 확인한다.\n# 객체지향으로 변경한다.\n# 모듈화해 문서를 쪼갠다.\n# 완성!!\n\n# atom script에서 utf-8을 해결하기 위한 코드 - 시작\n\nimport sys\nimport io\nfrom typing import List, Any\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')\n# atom script에서 utf-8을 해결하기 위한 코드 -끝\n\n#databaseQuery 모듈을 위한 내용들\nfrom sqlalchemy import Column, DateTime, String, Text\nfrom sqlalchemy.dialects.mysql import INTEGER, LONGTEXT\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\nimport sqlalchemy as db\n\n\nBase = declarative_base()\nmetadata = Base.metadata\n#databaseQuery 모듈을 위한 내용들 - 끝\n\nimport DatabaseQuery\nimport requests\n\n# 대충 구조는 비슷한 것 같다.\nimport xml.etree.ElementTree as ET\nimport logging\nimport os,inspect\n\nclass WeatherConnector():\n weatherLogger = \"\"\n rawWeatherSeouls: List[Any] = []\n def __init__(self,url,enginePath):\n self.url = url\n self.enginePath = enginePath\n path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n #Logging 코드 작성\n self.weatherLogger = logging.getLogger(\"weather\")\n self.weatherLogger.setLevel(logging.INFO)\n streamHandler = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n streamHandler.setFormatter(formatter)\n self.weatherLogger.addHandler(streamHandler)\n fileHandler = logging.FileHandler(path+\"/main.log\")\n fileHandler.setFormatter(formatter)\n self.weatherLogger.addHandler(fileHandler)\n self.weatherLogger.info(\"(1) This is the Initiation : Should Show Once\")\n self.alchemyLogger = logging.getLogger('sqlalchemy.engine')\n self.alchemyLogger.setLevel(logging.INFO)\n self.alchemyLogger.addHandler(streamHandler)\n self.alchemyLogger.addHandler(fileHandler)\n\n def getData(self):\n response = requests.get(self.url)\n root = ET.fromstring(response.text)\n results = root.findall(\"./channel/item/description/body/data\")\n for result in results:\n a = {\n \"hour\" :result.find(\".hour\").text,\n \"day\" : result.find(\".day\").text,\n \"temp\" : result.find(\".temp\").text,\n \"tmx\" : result.find(\".tmx\").text,\n \"sky\" : result.find(\".sky\").text,\n \"pty\" : result.find(\".pty\").text,\n \"wfKor\" : result.find(\".wfKor\").text,\n \"wfEn\" : result.find(\".wfEn\").text,\n \"pop\" : result.find(\".pop\").text,\n \"ws\" : result.find(\".ws\").text,\n \"wd\" : result.find(\".wd\").text,\n \"wdKor\" : result.find(\".wdKor\").text,\n \"wdEn\" : result.find(\".wdEn\").text,\n \"reh\" : result.find(\".reh\").text\n }\n rawWeatherSeoul = DatabaseQuery.RawWeatherSeoulOnly(**a)\n self.rawWeatherSeouls.append(rawWeatherSeoul)\n self.weatherLogger.info(\"{url:%s, sizeOfRawWeatherRecords : %d}\" %(str(self.url), len(self.rawWeatherSeouls)))\n def updateDB(self):\n if len(self.rawWeatherSeouls) == 0:\n return \"없어서 그만\"\n engine = create_engine(self.enginePath, echo=True)\n Session = sessionmaker(bind=engine)\n session = Session()\n session.add_all(self.rawWeatherSeouls)\n session.commit()\n def clearVar(self):\n self.rawWeatherSeouls = None\n","sub_path":"WeatherConnector.py","file_name":"WeatherConnector.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"104357416","text":"def m1(arr, key):\n count = 0\n for i in range(len(arr)):\n if key <= arr[i]:\n count += 1\n return count\n\n\ndef m2(arr, n, key):\n low = 0\n high = n - 1\n count = n\n\n while low <= high:\n mid = int(low + (high - low) / 2)\n\n if arr[mid] >= key:\n high = mid - 1\n else:\n count = mid + 1\n low = mid + 1\n return count\n\n\narray = [1, 2, 2, 2, 3, 4] # ip 3, op 5\n# array = [1, 2, 3, 4, 5, 6, 7] # ip 2 op 6\n\nnum = int(input(\"Enter a number: \"))\n# print(m1(array, n))\nprint(m2(array, len(array), num))","sub_path":"arrays/ElementsGreaterOrEqualToNumber.py","file_name":"ElementsGreaterOrEqualToNumber.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"424960827","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom .forms import LoginForm\nimport requests\n\ndef create_admin(request):\n #somecode\n admin_info = {\n \"Admin\": {\n \"FirstName\": \"Austin\",\n \"LastName\": \"Lee\",\n \"Middle\": \"Johnathan\",\n \"Email\": \"LEEAJ1@ETSU.EDU\",\n \"UserName\": \"alee\"\n },\n \"Password\": \"password\"\n }\n r = requests.post('https://bikeshopmonitoring.duckdns.org/Admin/Create', data=admin_info)\n if r.status_code == 200:\n print(r)\n\ndef send_data():\n print(\"hello\")\n","sub_path":"web/web/send_data.py","file_name":"send_data.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"105297958","text":"'''\n\nGiven the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range[low, high].\n\n\nExample 1:\n\n\nInput: root = [10, 5, 15, 3, 7, null, 18], low = 7, high = 15\nOutput: 32\nExplanation: Nodes 7, 10, and 15 are in the range[7, 15]. 7 + 10 + 15 = 32.\nExample 2:\n\n\nInput: root = [10, 5, 15, 3, 7, 13, 18, 1, null, 6], low = 6, high = 10\nOutput: 23\nExplanation: Nodes 6, 7, and 10 are in the range[6, 10]. 6 + 7 + 10 = 23.\n'''\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n def dfs(node):\n if node:\n if low <= node.val <= high:\n self.ans += node.val\n if low < node.val:\n dfs(node.left)\n if node.val < high:\n dfs(node.right)\n\n self.ans = 0\n dfs(root)\n return self.ans\n","sub_path":"day75_rangeSumOfBST.py","file_name":"day75_rangeSumOfBST.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"86215615","text":"#!/usr/bin/python\n\n\"\"\"\nYou work on the Gameloft database, you want to store game information in python objects.\nWrite a python class to create those objects with the following game parameters:\nGame_name, Game_genre, Year_of_release\nThe class should also be able to return:\n- The number of games\n- A list of games per genre\n- A list of games per year\n- A list of games that have their game_name starting with the letter inputted by the user\n\"\"\"\n\n\nclass Game:\n\n class Single_game:\n def __init__(self, name, genre, year):\n self.Game_name = name\n self.Game_genre = genre\n self.Year_of_release = year\n\n def __init__(self):\n self.game_list = []\n\n def add_game(self, name, genre, year):\n self.game_list.append(self.Single_game(name, genre, year))\n\n def get_number_of_games(self):\n return len(self.game_list)\n\n def get_games_per_genre(self):\n genre_dict = {}\n for game in self.game_list:\n if game.Game_genre in genre_dict:\n genre_dict[game.Game_genre].append(game.Game_name)\n else:\n genre_dict[game.Game_genre] = [game.Game_name]\n return genre_dict\n\n def get_games_per_year(self):\n year_dict = {}\n for game in self.game_list:\n if game.Year_of_release in year_dict:\n year_dict[game.Year_of_release].append(game.Game_name)\n else:\n year_dict[game.Year_of_release] = [game.Game_name]\n return year_dict\n\n def get_games_by_name(self, query):\n result_game_list = []\n for game in self.game_list:\n if game.Game_name.lower()[0] == query.lower():\n result_game_list.append(game.Game_name)\n return result_game_list\n\n\ndef main():\n # Testcase\n games = Game()\n games.add_game('gameA', 'genreA', '2006')\n games.add_game('testgameA', 'genreA', '2007')\n games.add_game('gameB', 'genreB', '2006')\n games.add_game('testgameB', 'genreB', '2008')\n\n print(games.get_number_of_games())\n print(games.get_games_per_genre())\n print(games.get_games_per_year())\n print(games.get_games_by_name('t'))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"477928477","text":"from flask import Blueprint\nfrom keyboards.keyboard import make_menu_keyboard, menu_buttons, make_role_replykeyboard, \\\n studdekan_buttons, teacher_buttons, dekanat_buttons\n\nfrom database.database import db\nfrom database.group import Group\nfrom database.student import Student\nfrom database.event import Event\nfrom database.event_visitor import EventVisitor\nfrom database.subject import Subject\nfrom database.cathedra import Cathedra\nfrom database.teacher import Teacher\nfrom database.grade_type import GradeType\nfrom database.grade import Grade\nfrom database.extra_grade import ExtraGrade\n\nfrom roles.student.auditory_search import search_aud\nfrom roles.student.teachers import teacher_keyboard\nfrom roles.student.studying import show_studying_keyboard\nfrom roles.student.univer_info import univer_info_keyboard\nfrom roles.student.events_schelude import get_events_schelude\nfrom roles.student.registration import register, add_another_fac\n\nfrom roles.studdekan.headman_management import headman_keyboard\nfrom roles.studdekan.profcomdebtor_management import profcom_debtor_keyboard\nfrom roles.studdekan.event_organization import event_organize_keyboard\nfrom roles.studdekan.getting_eventvisits import event_visits_keyboard\nfrom roles.studdekan.extragrade_assignment import add_extragrade\n\nfrom roles.dekanat.headman_communication import rate_headman, remind_journal, dekanat_send_message_or_file\nfrom roles.dekanat.rating_formation import send_rating_file\n\nfrom roles.teacher.grade_assignment import assign_grade\nfrom roles.teacher.subjectdebtor_management import subject_debtor_keyboard\nfrom roles.teacher.student_communication import teacher_student_communication\n\nfrom credentials import bot\nfrom helpers.role_helper import restricted_studdekan, restricted_dekanat, restricted_teacher, \\\n LIST_OF_DEKANAT, LIST_OF_ADMINS, LIST_OF_TEACHERS\nfrom telebot.types import InlineKeyboardMarkup, InlineKeyboardButton\nfrom emoji import emojize\n\nmenu = Blueprint('menu', __name__)\n\n\n@menu.route('/menu')\n@bot.message_handler(commands=['start', 'cancel'])\ndef start_message(message):\n add_all(message)\n\n chat_id = message.from_user.id\n\n if chat_id in LIST_OF_ADMINS:\n bot.send_message(chat_id=chat_id,\n text='Вибери пункт меню:',\n reply_markup=make_menu_keyboard(message, other_fac=False))\n elif chat_id in LIST_OF_DEKANAT or LIST_OF_TEACHERS:\n bot.send_message(chat_id=chat_id,\n text='Виберіть пункт меню:',\n reply_markup=make_menu_keyboard(message, other_fac=False))\n elif Student.get_student_by_id(chat_id) is None:\n keyboard = InlineKeyboardMarkup()\n keyboard.row(\n InlineKeyboardButton(text='Так', callback_data='yes'),\n InlineKeyboardButton(text='Ні', callback_data='no')\n )\n\n bot.send_message(chat_id=chat_id,\n text=f'Привіт {emojize(\":wave:\", use_aliases=True)}\\nТи з ФКНТ?',\n reply_markup=keyboard)\n elif Student.check_fac(chat_id):\n bot.send_message(chat_id=chat_id,\n text='Вибери пункт меню:',\n reply_markup=make_menu_keyboard(message, other_fac=False))\n elif not Student.check_fac(chat_id):\n bot.send_message(chat_id=chat_id,\n text='Вибери пункт меню:',\n reply_markup=make_menu_keyboard(message, other_fac=True))\n\n\n@bot.callback_query_handler(func=lambda call: call.data in ['yes', 'no'])\ndef knt_or_not(call):\n if call.data == 'yes':\n bot.send_message(chat_id=call.from_user.id,\n text='Для користування ботом треба зареєструватися')\n register(call)\n elif call.data == 'no':\n add_another_fac(call)\n bot.delete_message(chat_id=call.from_user.id, message_id=call.message.message_id)\n\n bot.send_message(chat_id=call.from_user.id,\n text='Вибери пункт меню:',\n reply_markup=make_menu_keyboard(call, other_fac=True))\n\n\n@bot.message_handler(func=lambda message: message.content_type == 'text' and message.text in menu_buttons)\ndef get_student_messages(message):\n if message.text == menu_buttons[0]:\n search_aud(message)\n elif message.text == menu_buttons[1]:\n bot.send_message(chat_id=message.from_user.id,\n text=('1 пара | 08:30 | 09:50\\n'\n '2 пара | 10:05 | 11:25\\n'\n '3 пара | 11:55 | 13:15\\n'\n '4 пара | 13:25 | 14:45\\n'\n '5 пара | 14:55 | 16:15\\n'\n '6 пара | 16:45 | 18:05\\n'\n '7 пара | 18:15 | 19:35\\n'\n '8 пара | 19:45 | 21:05\\n'))\n # bot.send_message(chat_id=374464076, text='#asked_bells')\n elif message.text == menu_buttons[2]:\n show_studying_keyboard(message)\n elif message.text == menu_buttons[3]:\n teacher_keyboard(message)\n elif message.text == menu_buttons[4]:\n get_events_schelude(message)\n elif message.text == menu_buttons[5]:\n univer_info_keyboard(message)\n elif message.text == menu_buttons[6]:\n show_studdekan_keyboard(message)\n elif message.text == menu_buttons[7]:\n show_dekanat_keyboard(message)\n elif message.text == menu_buttons[8]:\n show_teacher_keyboard(message)\n elif message.text == menu_buttons[9]:\n start_message(message)\n\n\n@restricted_studdekan\ndef show_studdekan_keyboard(message):\n bot.send_message(chat_id=message.from_user.id, text='Вибери пункт меню:',\n reply_markup=make_role_replykeyboard(studdekan_buttons))\n\n\ndef show_dekanat_keyboard(message):\n bot.send_message(chat_id=message.from_user.id, text='Вибери пункт меню:',\n reply_markup=make_role_replykeyboard(dekanat_buttons))\n\n\n@restricted_teacher\ndef show_teacher_keyboard(message):\n bot.send_message(chat_id=message.from_user.id, text='Вибери пункт меню:',\n reply_markup=make_role_replykeyboard(teacher_buttons))\n\n\n@bot.message_handler(func=lambda message: message.content_type == 'text' and message.text in studdekan_buttons)\n@restricted_studdekan\ndef get_studdekan_messages(message):\n if message.text == studdekan_buttons[0]:\n headman_keyboard(message)\n elif message.text == studdekan_buttons[1]:\n profcom_debtor_keyboard(message)\n elif message.text == studdekan_buttons[2]:\n event_organize_keyboard(message)\n elif message.text == studdekan_buttons[3]:\n event_visits_keyboard(message)\n elif message.text == studdekan_buttons[4]:\n add_extragrade(message)\n\n\n@bot.message_handler(func=lambda message: message.content_type == 'text' and message.text in dekanat_buttons)\n@restricted_dekanat\ndef get_dekanat_messages(message):\n if message.text == dekanat_buttons[0]:\n rate_headman(message)\n elif message.text == dekanat_buttons[1]:\n remind_journal(message)\n elif message.text == dekanat_buttons[2]:\n dekanat_send_message_or_file(message)\n elif message.text == dekanat_buttons[3]:\n send_rating_file(message)\n\n\n@bot.message_handler(func=lambda message: message.content_type == 'text' and message.text in teacher_buttons)\n@restricted_teacher\ndef get_teacher_messages(message):\n if message.text == teacher_buttons[0]:\n assign_grade(message)\n elif message.text == teacher_buttons[1]:\n subject_debtor_keyboard(message)\n elif message.text == teacher_buttons[2]:\n teacher_student_communication(message)\n\n\n@bot.message_handler(commands=['help'])\ndef help_message(message):\n bot.send_message(chat_id=message.from_user.id,\n text=\"Доступні команди:\\n\\n\"\n \"/start - почати роботу з ботом\\n\"\n \"/cancel - відміна дії\\n\"\n \"/help - допомога\")\n bot.send_message(chat_id=374464076, text=\"#askedhelp\")\n\n\n@bot.message_handler(commands=['fill'])\ndef add_all(message):\n Group.add_groups()\n Student.add_students()\n\n Event.add_events()\n EventVisitor.add_visitors()\n\n Cathedra.add_cathedras()\n Teacher.add_teachers()\n\n Subject.add_subjects()\n\n GradeType.add_gradetypes()\n Grade.add_grades()\n ExtraGrade.add_extragrades()\n\n\n@bot.message_handler(commands=['del'])\n# @restricted_studdekan\ndef delete_all(message):\n db.delete()\n bot.send_message(chat_id=message.from_user.id, text=\"database is cleared\")\n\n\n@bot.message_handler(commands=['groups301198'])\n@restricted_studdekan\ndef add_groups(message):\n Group.add_groups()\n bot.send_message(chat_id=message.from_user.id, text=\"groups added\")\n\n\n@bot.message_handler(content_types=['text',\n 'audio',\n 'document',\n 'photo',\n 'sticker',\n 'video',\n 'video_note',\n 'voice',\n 'location',\n 'contact',\n 'new_chat_members',\n 'left_chat_member',\n 'new_chat_title',\n 'new_chat_photo',\n 'delete_chat_photo',\n 'group_chat_created',\n 'supergroup_chat_created',\n 'channel_chat_created',\n 'migrate_to_chat_id',\n 'migrate_from_chat_id',\n 'pinned_message'])\ndef get_trash_messages(message):\n help_message(message)\n","sub_path":"keyboards/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":10228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"305471121","text":"import pygame\nfrom pygame.locals import *\n\npygame.init()\nfenetre = pygame.display.set_mode((640,480))\nfond = pygame.image.load(\"background.jpg\").convert()\nfenetre.blit(fond, (0, 0))\n\nperso = pygame.image.load(\"perso.png\").convert_alpha()\npositionPerso = perso.get_rect()\nfenetre.blit(perso, positionPerso)\n\npygame.display.flip()\npygame.key.set_repeat(400, 30)\n\n\ncontinuer = 1\n\nwhile continuer:\n for event in pygame.event.get():\n if event.type == QUIT:\n continuer = 0\n \n if event.type == KEYDOWN:\n if event.key == K_DOWN:\n positionPerso = positionPerso.move(0, 10)\n if event.key == K_UP:\n positionPerso = positionPerso.move(0,-10)\n if event.key == K_LEFT:\n positionPerso = positionPerso.move(-10, 0)\n if event.key == K_RIGHT:\n positionPerso = positionPerso.move(10, 00)\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n if event.pos[1] < 100:\n print(\"Zone dangereuse !\")\n \n fenetre.blit(fond, (0, 0))\n fenetre.blit(perso, positionPerso)\n pygame.display.flip()\n\n","sub_path":"oc.py","file_name":"oc.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"11628258","text":"from base64 import b64decode\n\nfrom p02 import xor\n\nfrom Crypto.Cipher import AES\n\n\ndef aes_cbc_decrypt(ctxt, key, iv):\n ptxt = ''\n cipher = AES.new(key, AES.MODE_ECB)\n prev_block = iv\n\n for block in range(len(ctxt) / AES.block_size):\n start = block * AES.block_size\n end = start + AES.block_size\n cur_block = ctxt[start:end]\n\n tmp = cipher.decrypt(cur_block)\n ptxt += xor(prev_block, tmp)\n\n prev_block = cur_block\n\n return ptxt\n\n\ndef p10():\n key = \"YELLOW SUBMARINE\"\n iv = '\\x00' * AES.block_size\n\n with open('Data/10.txt') as f:\n data = b64decode(f.read().replace('\\n', ''))\n return aes_cbc_decrypt(data, key, iv)\n\n\ndef main():\n from main import Solution\n return Solution('10: Implement CBC mode', p10)\n","sub_path":"p10.py","file_name":"p10.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"41343503","text":"# %load q02_plot_matches_by_team/build.py\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\nipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None)\n\n\n# Solution\ndef plot_matches_by_team():\n plt.plot('batting_team','match_count')\n plt.xlabel('batting_team')\n plt.ylabel('match_count')\n plt.show()\n\n","sub_path":"q02_plot_matches_by_team/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"61689015","text":"from rnn import RNN\nfrom mlp import RNNLayer, SoftMax, Tanh, ReLu\nimport numpy as np\nfrom tools import add, multiply\n\ndata = open(\"input.txt\", 'r').read()\nchars = list(set(data))\ndata_size, vocab_size = len(data), len(chars)\n\nch_to_idx = {ch:i for i, ch in enumerate(chars)}\nidx_to_ch = {i:ch for i, ch in enumerate(chars)}\n\nrnn_size = 5\nseq_length = 2\n\nnn = RNN([\n\t\tRNNLayer(vocab_size, rnn_size, Tanh),\n\t\tSoftMax(rnn_size, vocab_size)]\n\t)\n\nl_rate = 1e-1\nn, p = 0, 0\ngrad_mem = [[np.zeros_like(w) for w in lparams] for lparams in nn.params]\nsmooth_loss = -np.log(1.0/vocab_size)*seq_length \nwhile True:\n\tif p+seq_length >= len(data) or n==0:\n\t\t# go to beginning of data\n\t\tp = 0\n\t\t# initialize/reset previous state\n\t\trnn_state = {}\n\t\tinit_state = {i:np.zeros((rnn_size, 1)) for i in range(nn.n_layers - 1)}\n\t\trnn_state[-1] = init_state\n\n\tinputs = [ch_to_idx[ch] for ch in data[p:p+seq_length]]\n\ttargets = [ch_to_idx[ch] for ch in data[p+1:p+seq_length+1]]\n\n\t# forward pass\n\tloss = 0\n\tfor i in range(seq_length):\n\t\tx = np.zeros((vocab_size, 1))\n\t\tx[inputs[i]] = 1\n\n\t\tprob, h = nn.forward(x, rnn_state[i - 1])\n\t\trnn_state[i] = h\n\t\tloss += -np.log(prob[targets[i]])\n\n\tif n % 100 == 0:\n\t\tx = np.zeros((vocab_size, 1))\n\t\tx[inputs[i]] = 1\n\t\tsmooth_loss = smooth_loss * 0.999 + loss * 0.001\n\t\tsample = nn.sample(x, rnn_state[-1], 200)\n\t\ttxt = ''.join([idx_to_ch[pred] for pred in sample])\n\t\tprint('----\\n %s \\n----' % (txt, ))\n\t\tprint('iter %d, loss: %f' % (n, smooth_loss))\t\t\n\n\n\t# backward pass\n\trnn_dh = {}\n\trnn_dh[seq_length - 1] = init_state\n\tgrad_update = [[np.zeros_like(w) for w in lparams] for lparams in nn.params]\n\tfor i in range(seq_length - 1, -1, -1):\n\t\t# backprop through softmax\n\t\tdJ = rnn_state[i][nn.n_layers - 1]\n\t\tdJ[targets[i]] -= 1\n\n\t\tgparams, dh = nn.grad(dJ, rnn_state[i], rnn_state[i - 1], rnn_dh[i])\n\t\trnn_dh[i - 1] = dh\n\n\t\t# accumulate gradients for each pass\n\t\tgrad_update = [[gw + dw for gw, dw in zip(gradl, gradlpass)] for gradl, gradlpass in zip(grad_update, gparams)]\n\n\t# clip to prevent exploding gradients\n\tgrad_update = [[np.clip(dw, -5, 5) for dw in lparam] for lparam in grad_update]\n\n\t# gradient update\n\tn_params = nn.params\n\tfor layer_params, glayers, glmem in zip(n_params, grad_update, grad_mem):\n\t\tfor w, dw, dm in zip(layer_params, glayers, glmem):\n\t\t\tdm += dw * dw\n\t\t\tw += -l_rate * dw / np.sqrt(dm + 1e-8)\n\tnn.params = n_params\n\n\tp += seq_length\n\tn = n + 1\n\trnn_state[-1] = rnn_state[seq_length-1] ","sub_path":"char_rnn.py","file_name":"char_rnn.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"338527961","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: /Users/erikvw/.venvs/ambition/lib/python3.7/site-packages/ambition_validators/form_validators/blood_result.py\n# Compiled at: 2018-07-31 21:13:34\n# Size of source mod 2**32: 7291 bytes\nfrom ambition_labs.panels import cd4_panel, viral_load_panel, fbc_panel\nfrom ambition_labs.panels import chemistry_panel, chemistry_alt_panel\nfrom ambition_subject.constants import ALREADY_REPORTED\nfrom ambition_visit_schedule.constants import DAY1\nimport django.apps as django_apps\nimport django.forms as forms\nfrom edc_constants.constants import NO, YES, NOT_APPLICABLE\nfrom edc_form_validators import FormValidator\nfrom edc_lab import CrfRequisitionFormValidatorMixin\nfrom edc_reportable import site_reportables, NotEvaluated, GRADE3, GRADE4\n\nclass BloodResultFormValidator(CrfRequisitionFormValidatorMixin, FormValidator):\n\n def clean(self):\n Site = django_apps.get_model('sites.site')\n self.required_if_true((any([self.cleaned_data.get(f) is not None for f in [f for f in self.instance.ft_fields]])),\n field_required='ft_requisition')\n self.validate_requisition('ft_requisition', 'ft_assay_datetime', chemistry_panel, chemistry_alt_panel)\n self.required_if_true((any([self.cleaned_data.get(f) is not None for f in [f for f in self.instance.cbc_fields]])),\n field_required='cbc_requisition')\n self.validate_requisition('cbc_requisition', 'cbc_assay_datetime', fbc_panel)\n self.required_if_true((self.cleaned_data.get('cd4') is not None),\n field_required='cd4_requisition')\n self.validate_requisition('cd4_requisition', 'cd4_assay_datetime', cd4_panel)\n self.required_if_true((self.cleaned_data.get('vl') is not None),\n field_required='vl_requisition')\n self.validate_requisition('vl_requisition', 'vl_assay_datetime', viral_load_panel)\n subject_identifier = self.cleaned_data.get('subject_visit').subject_identifier\n RegisteredSubject = django_apps.get_model('edc_registration.registeredsubject')\n subject_visit = self.cleaned_data.get('subject_visit')\n registered_subject = RegisteredSubject.objects.get(subject_identifier=subject_identifier)\n gender = registered_subject.gender\n dob = registered_subject.dob\n opts = dict(gender=gender,\n dob=dob,\n report_datetime=(subject_visit.report_datetime))\n for field, value in self.cleaned_data.items():\n grp = site_reportables.get('ambition').get(field)\n if value and grp:\n (self.evaluate_result)(field, value, grp, **opts)\n\n self.validate_final_assessment(field='results_abnormal',\n responses=[YES],\n suffix='_abnormal',\n word='abnormal')\n self.applicable_if(YES,\n field='results_abnormal', field_applicable='results_reportable')\n self.validate_final_assessment(field='results_reportable',\n responses=[GRADE3, GRADE4],\n suffix='_reportable',\n word='reportable')\n if self.cleaned_data.get('subject_visit').visit_code == DAY1:\n if Site.objects.get_current().name not in ('gaborone', 'blantyre'):\n if self.cleaned_data.get('bios_crag') != NOT_APPLICABLE:\n raise forms.ValidationError({'bios_crag': 'This field is not applicable'})\n self.applicable_if(YES,\n field='bios_crag',\n field_applicable='crag_control_result')\n self.applicable_if(YES,\n field='bios_crag',\n field_applicable='crag_t1_result')\n self.applicable_if(YES,\n field='bios_crag',\n field_applicable='crag_t2_result')\n\n def evaluate_result(self, field, value, grp, **opts):\n \"\"\"Evaluate a single result value.\n\n Grading is done first. If the value is not gradeable,\n the value is checked against the normal limits.\n\n Expected field naming convention:\n * {field}\n * {field}_units\n * {field}_abnormal [YES, (NO)]\n * {field}_reportable [(NOT_APPLICABLE), NO, GRADE3, GRADE4]\n \"\"\"\n abnormal = self.cleaned_data.get(f\"{field}_abnormal\")\n reportable = self.cleaned_data.get(f\"{field}_reportable\")\n units = self.cleaned_data.get(f\"{field}_units\")\n opts.update(units=units)\n if not units:\n raise forms.ValidationError({f\"{field}_units\": 'Units required.'})\n try:\n grade = (grp.get_grade)(value, **opts)\n except NotEvaluated as e:\n try:\n raise forms.ValidationError({field: str(e)})\n finally:\n e = None\n del e\n\n if grade and grade.grade and reportable != str(grade.grade):\n if reportable != ALREADY_REPORTED:\n raise forms.ValidationError({field: f\"{field.upper()} is reportable. Got {grade.description}.\"})\n else:\n if not grade:\n if reportable not in [NO, NOT_APPLICABLE]:\n raise forms.ValidationError({f\"{field}_reportable\": \"Invalid. Expected 'No' or 'Not applicable'.\"})\n try:\n normal = (grp.get_normal)(value, **opts)\n except NotEvaluated as e:\n try:\n raise forms.ValidationError({field: str(e)})\n finally:\n e = None\n del e\n\n if (normal or abnormal) == NO:\n descriptions = (grp.get_normal_description)(**opts)\n raise forms.ValidationError({field: f\"{field.upper()} is abnormal. Normal ranges: {', '.join(descriptions)}\"})\n else:\n if normal:\n if not grade:\n if abnormal == YES:\n raise forms.ValidationError({f\"{field}_abnormal\": 'Invalid. Result is not abnormal'})\n if abnormal == YES and reportable == NOT_APPLICABLE:\n raise forms.ValidationError({f\"{field}_reportable\": 'This field is applicable if result is abnormal'})\n else:\n if abnormal == NO:\n if reportable != NOT_APPLICABLE:\n raise forms.ValidationError({f\"{field}_reportable\": 'This field is not applicable'})\n\n def validate_final_assessment(self, field=None, responses=None, suffix=None, word=None):\n \"\"\"Common code to validate fields `results_abnormal`\n and `results_reportable`.\n \"\"\"\n answers = list({k:v for k, v in self.cleaned_data.items() if k.endswith(suffix)}.values())\n if len([True for v in answers if v is not None]) == 0:\n raise forms.ValidationError({'results_abnormal': 'No results have been entered.'})\n else:\n answers_as_bool = [True for v in answers if v in responses]\n if self.cleaned_data.get(field) == NO:\n if any(answers_as_bool):\n are = 'is' if len(answers_as_bool) == 1 else 'are'\n raise forms.ValidationError({field: f\"{len(answers_as_bool)} of the above results {are} {word}\"})\n elif self.cleaned_data.get(field) == YES:\n if not any(answers_as_bool):\n raise forms.ValidationError({field: f\"None of the above results are {word}\"})","sub_path":"pycfiles/ambition-validators-0.1.10.macosx-10.13-x86_64.tar/blood_result.cpython-37.py","file_name":"blood_result.cpython-37.py","file_ext":"py","file_size_in_byte":7364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"490873584","text":"import pygame\nfrom Model.Arista import Arista\nfrom Model.Vertice import Vertice\nfrom collections import deque\nfrom copy import copy\nimport json\nclass Grafo:\n def __init__(self):\n self.listaVertices = []\n self.listaAristas = []\n self.listaVisitados = []\n self.listaBloqueadas = []\n\n def getListaVertices(self):\n return self.listaVertices\n\n def getListaAristas(self):\n return self.listaAristas\n\n def getListaVisitados(self):\n return self.listaVisitados\n\n def ingresarVertice(self, dato):\n if self.verificarVertice(dato) is None:\n self.listaVertices.append(Vertice(dato))\n\n def verificarVertice(self, dato):\n for vertice in self.listaVertices:\n if dato == vertice.getDato():\n return vertice\n return None\n\n def ingresarArista(self, origen, destino, peso):\n if self.verificarArista(origen, destino) is None:\n if self.verificarVertice(origen) is not None and self.verificarVertice(destino) is not None:\n self.listaAristas.append(Arista(origen, destino, peso))\n self.verificarVertice(origen).getListaAdyacentes().append(destino)\n\n def verificarArista(self, origen, destino):\n for arista in self.listaAristas:\n if arista.getOrigen() == origen and arista.getDestino() == destino:\n return arista\n return None\n\n def profundidad(self,posicion,lista_visitados):\n if self.verificarVertice(posicion):\n if not lista_visitados:\n lista_visitados.append(posicion)\n for adyacente in self.verificarVertice(posicion).getListaAdyacentes():\n if adyacente not in lista_visitados:\n lista_visitados.append(adyacente)\n lista_visitados=self.profundidad(adyacente,lista_visitados)\n return lista_visitados\n else:\n return \"El vertice señalado para iniciar el recorrido no existe\"\n\n \"\"\"def profundidad(self, dato):\n if dato in self.listaVisitados:\n return\n else:\n vertice = self.verificarVertice(dato)\n if vertice is not None:\n self.listaVisitados.append(vertice.getDato())\n for dato in vertice.getListaAdyacentes():\n self.profundidad(dato)\n \"\"\"\n def amplitud(self, dato):\n visitadosA = []\n cola = deque()\n vertice = self.verificarVertice(dato)\n if vertice is not None:\n cola.append(vertice)\n visitadosA.append(dato)\n while cola:\n elemento = cola.popleft()\n for adyacencias in elemento.getListaAdyacentes():\n if adyacencias not in visitadosA:\n vertice = self.verificarVertice(adyacencias)\n cola.append(vertice)\n visitadosA.append(adyacencias)\n return visitadosA\n\n def imprimirVertice(self):\n for vertice in self.listaVertices:\n print(vertice.getDato())\n\n def imprimirArista(self):\n for arista in self.listaAristas:\n print('Origen: {0} -- Destino: {1} -- Peso: {2}'.format(arista.getOrigen(), arista.getDestino(), arista.getPeso()))\n\n def imprimirListaAdyacentes(self):\n for vertice in self.listaVertices:\n print('Lista de adyacentes de ', vertice.getDato(), ': ', vertice.getListaAdyacentes())\n\n def separador(self):\n print()\n print('----------------------------------')\n print()\n\n def getPozos(self):\n nroPozos = 0\n for vertice in self.listaVertices:\n if len(vertice.getListaAdyacentes()) == 0:\n print('El vertice: ', vertice.getDato(), 'es un pozo')\n nroPozos += 1\n print('La cantidad de pozos del grafo es: ', nroPozos)\n return nroPozos\n\n def getFuentes(self):\n nroFuentes = 0\n bandera = False\n for vertice in self.listaVertices:\n for arista in self.listaAristas:\n if arista.getDestino() == vertice.getDato():\n bandera = True\n if bandera != False:\n break\n if bandera == False:\n print('El vertice:', vertice.getDato(), 'es una fuente')\n nroFuentes += 1\n print('La cantidad de fuentes del grafo es: ', nroFuentes)\n return nroFuentes\n\n def fuerteConexo(self):\n nroPozos = self.getPozos()\n nroFuentes = self.getFuentes()\n if nroPozos > 0 and nroFuentes > 0:\n print('El grafo es debilmente conexo')\n return True\n\n def ordenamiento(self, copiaAristas): # Ordeno de menor a mayor\n for i in range(len(copiaAristas)):\n for j in range(len(copiaAristas)):\n if copiaAristas[i].getPeso() < copiaAristas[j].getPeso():\n temp = copiaAristas[i]\n copiaAristas[i] = copiaAristas[j]\n copiaAristas[j] = temp\n\n def prim(self):\n copiaAristas = copy(self.listaAristas)\n conjunto = [] # se va encargar de guardar los vertices visitados\n aristasPrim = []\n aristasTemp = []\n self.ordenamiento(copiaAristas)\n self.dirigido(copiaAristas)\n menor = copiaAristas[0]\n conjunto.append(menor.getOrigen())\n terminado = False\n while terminado == False:\n for vertice in conjunto:\n self.algoritmoPrim(copiaAristas, conjunto, aristasPrim, aristasTemp, vertice)\n if len(self.listaVertices) == len(conjunto):\n terminado = True\n print(conjunto)\n for arista in aristasPrim:\n print('Origen: {0} - Destino: {1} - Peso: {2}'.format(arista.getOrigen(), arista.getDestino(), arista.getPeso()))\n return aristasPrim\n\n def algoritmoPrim(self, copiaAristas, conjunto, aristasPrim, aristasTemp, vertice):\n ciclo = False\n self.agregarTemp(copiaAristas, aristasTemp, vertice)\n candidata = self.candidataPrim(aristasTemp, copiaAristas, aristasPrim)\n if candidata != None:\n if candidata.getOrigen() in conjunto and candidata.getDestino() in conjunto:\n ciclo = True\n if ciclo == False:\n aristasPrim.append(candidata)\n if not candidata.getOrigen() in conjunto:\n conjunto.append(candidata.getOrigen())\n if not candidata.getDestino() in conjunto:\n conjunto.append(candidata.getDestino())\n\n def agregarTemp(self, copiaAristas, aristasTemp, vertice):\n for arista in copiaAristas:\n if arista.getOrigen() == vertice or arista.getDestino() == vertice:\n if self.verificarAristaTemp(arista, aristasTemp):\n aristasTemp.append(arista)\n\n def verificarAristaTemp(self, arista, aristasTemp):\n for elemento in aristasTemp:\n if elemento.getOrigen() == arista.getOrigen() and elemento.getDestino() == arista.getDestino():\n return False\n return True\n\n def candidataPrim(self, aristasTemp, copiaAristas, aristasPrim):\n menor = copiaAristas[len(copiaAristas) - 1]\n for i in range(len(aristasTemp)):\n if aristasTemp[i].getPeso() < menor.getPeso():\n if self.verificarPrim(aristasTemp[i], aristasPrim):\n menor = aristasTemp[i]\n aristasTemp.pop(aristasTemp.index(menor))\n return menor\n\n def verificarPrim(self, candidata, aristasPrim):\n for arista in aristasPrim:\n if arista.getOrigen() == candidata.getOrigen() and arista.getDestino() == candidata.getDestino():\n return False\n if arista.getDestino() == candidata.getDestino() and arista.getOrigen() == candidata.getOrigen():\n return False\n return True\n\n def dirigido(self, copiaAristas):\n for elemento in copiaAristas:\n for i in range(len(copiaAristas)):\n if elemento.getOrigen() == copiaAristas[i].getDestino() and elemento.getDestino() == copiaAristas[i].getOrigen():\n copiaAristas.pop(i)\n break\n\n def noDirigido(self, copiaAristas):\n dirigido = False\n for elemento in copiaAristas:\n for i in range(len(copiaAristas)):\n if elemento.getOrigen() == copiaAristas[i].getDestino() and elemento.getDestino() == copiaAristas[i].getOrigen():\n dirigido = True\n if dirigido == False:\n copiaAristas.append(Arista(elemento.getDestino(),elemento.getOrigen(),elemento.getPeso()))\n\n def Kruskal(self):\n copiaAristas = copy(self.getListaAristas()) # copia de las aristas\n AristasKruskal = []\n ListaConjuntos = []\n\n self.ordenamiento(copiaAristas) # ordeno las aristas\n for menor in copiaAristas:\n self.Operacionesconjuntos(menor, ListaConjuntos, AristasKruskal)\n # esta ordenada de mayor a menor\n print(\"-----------Kruskal---------------\")\n for dato in AristasKruskal:\n print(\"Origen: {0} destino: {1} peso: {2}\".format(dato.getOrigen(), dato.getDestino(), dato.getPeso()))\n return AristasKruskal\n def Operacionesconjuntos(self, menor, ListaConjuntos, AristasKruskal):\n encontrado1 = -1\n encontrado2 = -1\n\n if not ListaConjuntos: # si esta vacia\n ListaConjuntos.append({menor.getOrigen(), menor.getDestino()})\n AristasKruskal.append(menor)\n\n else:\n for i in range(len(ListaConjuntos)):\n if (menor.getOrigen() in ListaConjuntos[i]) and (menor.getDestino() in ListaConjuntos[i]):\n return ##Camino cicliclo\n\n for i in range(len(ListaConjuntos)):\n if menor.getOrigen() in ListaConjuntos[i]:\n encontrado1 = i\n if menor.getDestino() in ListaConjuntos[i]:\n encontrado2 = i\n\n if encontrado1 != -1 and encontrado2 != -1:\n if encontrado1 != encontrado2: # si pertenecen a dos conjuntos diferentes\n # debo unir los dos conjuntos\n ListaConjuntos[encontrado1].update(ListaConjuntos[encontrado2])\n #este update si funciona correctemente\n ListaConjuntos[encontrado2].clear() # elimino el conjunto\n AristasKruskal.append(menor)\n\n if encontrado1 != -1 and encontrado2 == -1: # si va unido por un conjunto\n # el update se cambio con por el add ya que al agregar cadenas a Listaconjuntos\n # no se guardaba como \"Silvestre\" sino que la desglosaba en sus caracteres \"S,i,l,v,e,t,r,e\" en Listaconjuntos\n ListaConjuntos[encontrado1].add(menor.getOrigen())\n ListaConjuntos[encontrado1].add(menor.getDestino())\n AristasKruskal.append(menor)\n\n if encontrado1 == -1 and encontrado2 != -1: # si va unido por un conjunto\n ListaConjuntos[encontrado2].add(menor.getOrigen())\n ListaConjuntos[encontrado2].add(menor.getDestino())\n AristasKruskal.append(menor)\n\n if encontrado1 == -1 and encontrado2 == -1: # si no existe en los conjuntos\n ListaConjuntos.append({menor.getOrigen(), menor.getDestino()})\n AristasKruskal.append(menor)\n\n def Boruvka(self):\n copiaNodos = copy(self.getListaVertices()) # copia de los nodos\n copiaAristas = copy(self.getListaAristas()) # copia de las aristas\n\n AristasBorukvka = []\n ListaConjuntos = []\n bandera = True\n cantidad = 0\n while(cantidad > 1 or bandera):\n for Nodo in copiaNodos:\n self.OperacionesconjuntosB(Nodo, ListaConjuntos, AristasBorukvka,copiaAristas)\n bandera = False\n cantidad = self.Cantidadconjuntos(ListaConjuntos)\n\n for dato in AristasBorukvka:\n print(\"Origen: {0} destino: {1} peso: {2}\".format(dato.getOrigen(), dato.getDestino(), dato.getPeso()))\n return AristasBorukvka\n\n def Cantidadconjuntos(self,ListaConjuntos):\n cantidad = 0\n for conjunto in ListaConjuntos:\n if len(conjunto) > 0:\n catidad = cantidad + 1\n return cantidad\n def OperacionesconjuntosB(self,Nodo, ListaConjuntos, AristasBorukvka,copiaAristas):\n encontrado1 = -1\n encontrado2 = -1\n menor = self.Buscarmenor(Nodo, copiaAristas)\n\n if not menor==None:#si no esta vacio\n if not ListaConjuntos:#si esta vacia\n ListaConjuntos.append({menor.getOrigen(),menor.getDestino()})\n AristasBorukvka.append(menor)\n else:\n for i in range(len(ListaConjuntos)):\n if (menor.getOrigen() in ListaConjuntos[i]) and (menor.getDestino() in ListaConjuntos[i]):\n return False##Camino cicliclo\n\n for i in range(len(ListaConjuntos)):\n if menor.getOrigen() in ListaConjuntos[i]:\n encontrado1 = i\n if menor.getDestino() in ListaConjuntos[i]:\n encontrado2 = i\n\n if encontrado1!=-1 and encontrado2!=-1:\n if encontrado1!=encontrado2:#si pertenecen a dos conjuntos diferentes\n #debo unir los dos conjuntos\n ListaConjuntos[encontrado1].update(ListaConjuntos[encontrado2])\n ListaConjuntos[encontrado2].clear()#elimino el conjunto\n AristasBorukvka.append(menor)\n\n if encontrado1!=-1 and encontrado2==-1:# si va unido por un conjunto\n ListaConjuntos[encontrado1].update(menor.getOrigen())\n ListaConjuntos[encontrado1].update(menor.getDestino())\n AristasBorukvka.append(menor)\n\n if encontrado1 == -1 and encontrado2 != -1:# si va unido por un conjunto\n ListaConjuntos[encontrado2].update(menor.getOrigen())\n ListaConjuntos[encontrado2].update(menor.getDestino())\n AristasBorukvka.append(menor)\n\n if encontrado1 == -1 and encontrado2 == -1:# si no existe en los conjuntos\n ListaConjuntos.append({menor.getOrigen(), menor.getDestino()})\n AristasBorukvka.append(menor)\n\n\n\n def Buscarmenor(self,Nodo,copiaAristas):\n temp = []\n for adyacencia in Nodo.getListaAdyacentes():\n for Arista in copiaAristas:\n #busco las aristas de esa lista de adyacencia\n if Arista.getOrigen()==Nodo.getDato() and Arista.getDestino()==adyacencia:\n temp.append(Arista)\n if temp:#si no esta vacia\n #una vez obtenga todas las aristas, saco la menor\n self.ordenamiento(temp) # ordeno las aristas\n #elimin ese destino porque ya lo voy a visitar\n #print(\"{0}-{1}:{2}\".format(temp[0].getOrigen(), temp[0].getDestino(), temp[0].getPeso()))\n\n Nodo.getListaAdyacentes().remove(temp[0].getDestino())\n return temp[0] # es la menor\n\n return None#es la menor\n\n def cambiarDireccion(self, origen, destino):\n for arista in self.listaAristas:\n origenCopia = str(arista.getOrigen())\n destinoCopia = str(arista.getDestino())\n if origen == origenCopia and destino == destinoCopia:\n temp = arista.getOrigen()\n arista.setOrigen(arista.getDestino())\n arista.setDestino(temp)\n\n def bloquearArista(self, origen, destino):\n for arista in self.listaAristas:\n origenCopia = str(arista.getOrigen())\n destinoCopia = str(arista.getDestino())\n if origen == origenCopia and destino == destinoCopia:\n self.listaBloqueadas.append(arista)\n indice = self.listaAristas.index(arista)\n self.listaAristas.pop(indice)\n\n def desbloquearArista(self, origen, destino):\n for arista in self.listaBloqueadas:\n origenCopia = str(arista.getOrigen())\n destinoCopia = str(arista.getDestino())\n if origen == origenCopia and destino == destinoCopia:\n self.listaAristas.append(arista)\n indice = self.listaBloqueadas.index(arista)\n self.listaBloqueadas.pop(indice)\n\n def gradoVertice(self, vertice):\n gradoVertice = 0\n verticeEntrada = self.verificarVertice(vertice)\n copiaAristas = copy(self.listaAristas)\n self.noDirigido(self.listaAristas)\n for vertice in self.listaVertices:\n if vertice == verticeEntrada:\n gradoVertice = len(vertice.getListaAdyacentes())\n self.listaAristas = copiaAristas\n return gradoVertice\n\n def caminoMasCorto(self, origen, destino):\n VerticesAux = []\n VerticesD = []\n caminos = self.dijkstra(origen, VerticesAux)\n cont = 0\n for i in caminos:\n print(\"La distancia mínima a: \" + self.listaVertices[cont].getDato() + \" es \" + str(i))\n cont = cont + 1\n self.rutas(VerticesD, VerticesAux, destino, origen)\n print(\"El camino más corto de: \" + origen + \" a \" + destino + \" es: \")\n print(VerticesD)\n\n def rutas(self, VerticesD, VerticesAux, destino, origen):\n verticeDestino = self.verificarVertice(destino)\n indice = self.listaVertices.index(verticeDestino)\n if VerticesAux[indice] is None:\n print(\"No hay camino entre: \", (origen, destino))\n return\n aux = destino\n while aux is not origen:\n verticeDestino = self.verificarVertice(aux)\n indice = self.listaVertices.index(verticeDestino)\n VerticesD.insert(0, aux)\n aux = VerticesAux[indice]\n VerticesD.insert(0, aux)\n\n def dijkstra(self, origen, VerticesAux):\n marcados = [] # la lista de los que ya hemos visitado\n caminos = [] # la lista final\n # iniciar los valores en infinito\n for v in self.listaVertices:\n caminos.append(float(\"inf\"))\n marcados.append(False)\n VerticesAux.append(None)\n if v.getDato() is origen:\n caminos[self.listaVertices.index(v)] = 0\n VerticesAux[self.listaVertices.index(v)] = v.getDato()\n while not self.todosMarcados(marcados):\n aux = self.menorNoMarcado(caminos, marcados) # obtuve el menor no marcado\n if aux is None:\n break\n indice = self.listaVertices.index(aux) # indice del menor no marcado\n marcados[indice] = True # marco como visitado\n valorActual = caminos[indice]\n for vAdya in aux.getListaAdyacentes():\n indiceNuevo = self.listaVertices.index(self.verificarVertice(vAdya))\n arista = self.verificarArista(vAdya, aux.getDato())\n if caminos[indiceNuevo] > valorActual + arista.getPeso():\n caminos[indiceNuevo] = valorActual + arista.getPeso()\n VerticesAux[indiceNuevo] = self.listaVertices[indice].getDato()\n return caminos\n\n def menorNoMarcado(self, caminos, marcados):\n verticeMenor = None\n caminosAux = sorted(caminos)\n copiacaminos = copy(caminos)\n bandera = True\n contador = 0\n while bandera:\n menor = caminosAux[contador]\n if marcados[copiacaminos.index(menor)] == False:\n verticeMenor = self.listaVertices[copiacaminos.index(menor)]\n bandera = False\n else:\n copiacaminos[copiacaminos.index(menor)] = \"x\"\n contador = contador + 1\n return verticeMenor\n\n def todosMarcados(self, marcados):\n for j in marcados:\n if j is False:\n return False\n return True\n\n def cargarRedInicial(self, ruta):\n with open(ruta) as contenido:\n redAcme = json.load(contenido)\n for vertice in redAcme[\"Cuevas\"]:\n self.ingresarVertice(vertice)\n for arista in redAcme[\"Caminos\"]:\n self.ingresarArista(arista[0], arista[1], arista[2])\n self.noDirigido(self.listaAristas)\n\n#-----------------------------------animation\n def dibujarTabla(self, x, y, ventana, aguaMarina = pygame.Color(14, 236, 125), blanco = pygame.Color(255, 255, 255), negro = pygame.Color(0, 0, 0)):\n contador = 0\n pygame.draw.rect(ventana, aguaMarina, (x - 200, 0, 400, 30))\n pygame.draw.rect(ventana, blanco, (x - 200, 30, 400, y - 30))\n miFuente = pygame.font.Font(None, 23)\n miTexto = miFuente.render('LISTA ARISTAS', 0, blanco)\n ventana.blit(miTexto, (x - 195, 8))\n for arista in self.listaAristas:\n miTexto1 = miFuente.render(\n '{} - {} - {}'.format(arista.getOrigen(), arista.getDestino(), arista.getPeso()), 0, negro)\n ventana.blit(miTexto1, (x - 195, 35 + contador))\n contador += 25\n pygame.draw.rect(ventana, aguaMarina, (x - 200, 0 + contador + 35, 400, 30))\n miTexto = miFuente.render('LISTA BLOQUEADAS', 0, blanco)\n ventana.blit(miTexto, (x - 195, 8 + 35 + contador))\n for bloqueada in self.listaBloqueadas:\n miTexto1 = miFuente.render(\n '{} - {} - {}'.format(bloqueada.getOrigen(), bloqueada.getDestino(), bloqueada.getPeso()), 0, negro)\n ventana.blit(miTexto1, (x - 195, 40 + 35 + contador))\n contador += 25\n\n def dibujarResultado(self, x, y, ventana,texto, blanco = pygame.Color(255, 255, 255), negro = pygame.Color(0, 0, 0)):\n pygame.draw.rect(ventana, blanco, ((x/2)/ 2, y - 150, 800, y - 100))\n miFuente = pygame.font.Font(None, 30)\n neuvoTexto = str(texto)\n miTexto = miFuente.render(neuvoTexto, 0, negro)\n ventana.blit(miTexto, (((x/2)/2) + 25, y - 50))\n\n def cambiarDireccion(self, origen, destino):\n for arista in self.listaAristas:\n origenCopia = str(arista.getOrigen())\n destinoCopia = str(arista.getDestino())\n if origen == origenCopia and destino == destinoCopia:\n temp = arista.getOrigen()\n arista.setOrigen(arista.getDestino())\n arista.setDestino(temp)\n\n def bloquearArista(self, origen, destino):\n for arista in self.listaAristas:\n origenCopia = str(arista.getOrigen())\n destinoCopia = str(arista.getDestino())\n if origen == origenCopia and destino == destinoCopia:\n self.listaBloqueadas.append(arista)\n indice = self.listaAristas.index(arista)\n self.listaAristas.pop(indice)\n\n def desbloquearArista(self, origen, destino):\n for arista in self.listaBloqueadas:\n origenCopia = str(arista.getOrigen())\n destinoCopia = str(arista.getDestino())\n if origen == origenCopia and destino == destinoCopia:\n self.listaAristas.append(arista)\n indice = self.listaBloqueadas.index(arista)\n self.listaBloqueadas.pop(indice)\n\n def gradoVertice(self, vertice):\n gradoVertice = 0\n verticeEntrada = self.verificarVertice(vertice)\n copiaAristas = copy(self.listaAristas)\n self.noDirigido(self.listaAristas)\n for vertice in self.listaVertices:\n if vertice == verticeEntrada:\n gradoVertice = len(vertice.getListaAdyacentes())\n self.listaAristas = copiaAristas\n return gradoVertice\n\n","sub_path":"Controller/ejemploGrafo.py","file_name":"ejemploGrafo.py","file_ext":"py","file_size_in_byte":23831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"596529901","text":"\r\nimport tkinter\r\nimport re\r\nimport tkinter.messagebox\r\nimport math\r\nimport random\r\nimport time\r\nfrom functools import reduce\r\n\r\nCalculate_Times=0\r\nCT=5\r\nCalculator = tkinter.Tk()\r\nCalculator.title(\"Calculator\")\r\n#The size of the window\r\nCalculator.geometry(\"420x600+0+0\")\r\n#Do not let the user to change the size of the page\r\nCalculator.resizable(False,False)\r\n\r\n\r\n#Random Color\r\ndef randomcolor_a():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n '''\r\n if sta == 'on':\r\n '''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrca=randomcolor_a()\r\n\r\ndef randomcolor_b():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrcb=randomcolor_b()\r\n\r\ndef randomcolor_c():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrcc=randomcolor_c()\r\n\r\ndef randomcolor_d():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrcd=randomcolor_d()\r\n\r\ndef randomcolor_e():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrce=randomcolor_e()\r\n\r\ndef randomcolor_f():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n '''\r\n if sta == 'on':\r\n '''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrcf=randomcolor_f()\r\n\r\ndef randomcolor_g():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n '''\r\n if sta == 'on':\r\n '''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrcg=randomcolor_g()\r\n\r\ndef randomcolor_h():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n '''\r\n if sta == 'on':\r\n '''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrch=randomcolor_h()\r\n\r\ndef randomcolor_i():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n '''\r\n if sta == 'on':\r\n '''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrci=randomcolor_i()\r\n\r\ndef randomcolor_j():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n '''\r\n if sta == 'on':\r\n '''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrcj=randomcolor_j()\r\n\r\ndef randomcolor_k():\r\n global color\r\n colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\r\n color = ''\r\n '''\r\n if sta == 'on':\r\n '''\r\n for i in range(6):\r\n color += colorArr[random.randint(0,14)]\r\n return'#'+color\r\nrck=randomcolor_k()\r\n\r\n\r\n'''Label'''\r\n\r\n#Add a entry to our window and set it to Read only\r\n\r\n#This give a way for user to change the text in the entry\r\nVar = tkinter.StringVar(Calculator,'')\r\n#Create the entry\r\nEntry = tkinter.Entry(Calculator,textvariable=Var)\r\n#Set the entry to Read only\r\nEntry['state'] = 'readonly'\r\n#place our entry\r\nEntry.place(x=10, y=10, width=400, height=50)\r\n\r\nπ = math.pi\r\n \r\n'''Button'''\r\ndef ButtonClick(btn): #btn stands for button\r\n global Calculate_Times\r\n global CT\r\n global Ans\r\n global π\r\n #Get the text in the Entry\r\n Content = Var.get()\r\n #Check the length of input\r\n for i in range(len(Content)+1):\r\n if i == 55:\r\n tkinter.messagebox.showerror('Error','You input too many numbers and/or operators')\r\n Content=Content[:len(Content)-len(Content)+55]\r\n #Check the times that user calculate if user did the calculate, then clean the entry\r\n if Calculate_Times>=1:\r\n Content=''\r\n Calculate_Times=0\r\n\r\n #If the user click on the decimal point button, add a ) before it\r\n if Content.startswith('.'):\r\n Content = '0'+Content \r\n #If user click on normal number button\r\n if btn in '0123456789':\r\n Content+=btn #add the number that user click to the content\r\n #If user click ondecimal point\r\n elif btn == '.':\r\n LastPart = re.split(r'\\+|-|\\*|/]',Content)[-1] #split each word\r\n if '.' in LastPart:\r\n tkinter.messagebox.showerror('Error','Too many decimal points')\r\n return\r\n else:\r\n Content += btn #add the decimal points that user click to the content\r\n #If user click on AC button(AC=All Clear)\r\n elif btn == 'AC':\r\n Calculate_Times=0\r\n Content=''\r\n #If user click on DEL button(DEL=Delete)\r\n elif btn == 'DEL':\r\n Content=Content[:len(Content)-1]\r\n #If user click on button\r\n elif btn == '=':\r\n Calculate_Times=Calculate_Times+1\r\n CT=CT+1\r\n try: #Find the result in the content\r\n Content = str(eval(Content))\r\n Ans=Content\r\n btnAns['state'] = 'active'\r\n except: #If the content can't find the result\r\n tkinter.messagebox.showerror('Error','Expression is incorrect')\r\n return\r\n #If the user click on operators\r\n elif btn == '+':\r\n if Content.endswith(Operators):\r\n tkinter.messagebox.showerror('Error','Continous operators not exist')\r\n return\r\n Content+=btn\r\n elif btn == '-':\r\n if Content.endswith(Operators):\r\n tkinter.messagebox.showerror('Error','Continous operators not exist')\r\n return\r\n Content+=btn\r\n elif btn == '*':\r\n if Content.endswith(Operators):\r\n tkinter.messagebox.showerror('Error','Continous operators not exist')\r\n return\r\n Content+=btn\r\n elif btn == '/':\r\n if Content.endswith(Operators):\r\n tkinter.messagebox.showerror('Error','Continous operators not exist')\r\n return\r\n Content+=btn\r\n elif btn == '**':\r\n if Content.endswith(Operators):\r\n tkinter.messagebox.showerror('Error','Continous operators not exist')\r\n return\r\n Content+=btn\r\n elif btn == '//':\r\n if Content.endswith(Operators):\r\n tkinter.messagebox.showerror('Error','Continous operators not exist')\r\n return\r\n Content+=btn\r\n #if the user click on answer button\r\n elif btn == 'Ans':\r\n btn=Ans\r\n Content+=btn\r\n #If the user click on pi button\r\n elif btn == 'π':\r\n Content+=btn\r\n #If the user click on parenthsis\r\n elif btn == '(':\r\n Content+=btn\r\n elif btn == ')':\r\n Content+=btn\r\n #If the user click on square root(Sqrt=Square Root)\r\n elif btn == '√':\r\n b = Content.split('.')\r\n if all(map(lambda x:x.isdigit(),a)):\r\n Content = eval(Content)**0.5 #Square root the content\r\n else:\r\n tkinter.messagebox.showerror('Error','Expression is incorrect (If you want to use square root in the expression, try using **0.5)')\r\n elif btn == 'sin':\r\n b = Content.split('.')\r\n if all(map(lambda x:x.isdigit(),b)):\r\n Content = math.sin(math.radians(int(Content))) #Sin the content\r\n else:\r\n tkinter.messagebox.showerror('Error','Expression is incorrect')\r\n elif btn == 'cos':\r\n b = Content.split('.')\r\n if all(map(lambda x:x.isdigit(),b)):\r\n Content = math.cos(math.radians(int(Content))) #Cos the content\r\n else:\r\n tkinter.messagebox.showerror('Error','Expression is incorrect')\r\n elif btn == 'tan':\r\n b = Content.split('.')\r\n if all(map(lambda x:x.isdigit(),b)):\r\n Content = math.tan(math.radians(int(Content))) #Tan the content\r\n else:\r\n tkinter.messagebox.showerror('Error','Expression is incorrect')\r\n elif btn == '!':\r\n if Content == '':\r\n tkinter.messagebox.showerror('Error','Expression is incorrect')\r\n else:\r\n c = int(Content)\r\n for i in range(int(Content),1,-1):\r\n c = c*(i-1)\r\n Content = str(c)\r\n Var.set(Content)\r\n\r\n'''Button interface'''\r\n#MouseOver\r\ndef EnterPlus(btn):\r\n btnPlus['background']=rcf\r\ndef LeavePlus(btn):\r\n btnPlus['background']=rcb\r\n\r\ndef EnterMinus(btn):\r\n btnMinus['background']=rcf\r\ndef LeaveMinus(btn):\r\n btnMinus['background']=rcb\r\n\r\ndef EnterTime(btn):\r\n btnTime['background']=rcf\r\ndef LeaveTime(btn):\r\n btnTime['background']=rcb\r\n\r\ndef EnterDivide(btn):\r\n btnDivide['background']=rcf\r\ndef LeaveDivide(btn):\r\n btnDivide['background']=rcb\r\n\r\ndef EnterDTime(btn):\r\n btnDTime['background']=rcf\r\ndef LeaveDTime(btn):\r\n btnDTime['background']=rcb\r\n\r\ndef EnterDDivide(btn):\r\n btnDDivide['background']=rcf \r\ndef LeaveDDivide(btn):\r\n btnDDivide['background']=rcb\r\n\r\ndef EnterAns(btn):\r\n btnAns['background']=rcg \r\ndef LeaveAns(btn):\r\n btnAns['background']=rce\r\n\r\ndef EnterPi(btn):\r\n btnPi['background']=rch \r\ndef LeavePi(btn):\r\n btnPi['background']=rca\r\n\r\ndef EnterParenthesisLeft(btn):\r\n btnParenthesisLeft['background']=rci \r\ndef LeaveParenthesisLeft(btn):\r\n btnParenthesisLeft['background']=rcd\r\n\r\ndef EnterParenthesisRight(btn):\r\n btnParenthesisRight['background']=rci \r\ndef LeaveParenthesisRight(btn):\r\n btnParenthesisRight['background']=rcd\r\n\r\ndef EnterSin(btn):\r\n btnSin['background']=rci \r\ndef LeaveSin(btn):\r\n btnSin['background']=rcd\r\n\r\ndef EnterCos(btn):\r\n btnCos['background']=rci \r\ndef LeaveCos(btn):\r\n btnCos['background']=rcd\r\n\r\ndef EnterTan(btn):\r\n btnTan['background']=rci \r\ndef LeaveTan(btn):\r\n btnTan['background']=rcd\r\n\r\ndef EnterE(btn):\r\n btnE['background']=rci \r\ndef LeaveE(btn):\r\n btnE['background']=rcd\r\n\r\ndef EnterAllClear(btn):\r\n btnAllClear['background']=rcj \r\ndef LeaveAllClear(btn):\r\n btnAllClear['background']=rcc\r\n\r\ndef EnterEqual(btn):\r\n btnEqual['background']=rcj \r\ndef LeaveEqual(btn):\r\n btnEqual['background']=rcc\r\n\r\ndef EnterBackspace(btn):\r\n btnBackspace['background']=rcj\r\ndef LeaveBackspace(btn):\r\n btnBackspace['background']=rcc\r\n\r\ndef EnterDigit(btn):\r\n btnd['background']=rck \r\ndef LeaveDigit(btn):\r\n btnd['background']=rca\r\n\r\n# = ,AC and DEL\r\nbtnAllClear = tkinter.Button(Calculator,text='AC',command=lambda:ButtonClick('AC'),bg=rcc)\r\nbtnAllClear.place(x=10,y=65,width=100,height=50)\r\nbtnAllClear.bind('',EnterAllClear)\r\nbtnAllClear.bind('',LeaveAllClear)\r\n\r\nbtnEqual = tkinter.Button(Calculator,text='=',command=lambda:ButtonClick('='),bg=rcc)\r\nbtnEqual.place(x=310,y=365,width=100,height=50)\r\nbtnEqual.bind('',EnterEqual)\r\nbtnEqual.bind('',LeaveEqual)\r\n\r\nbtnBackspace = tkinter.Button(Calculator,text='DEL',command=lambda:ButtonClick('DEL'),bg=rcc)\r\nbtnBackspace.place(x=110,y=65,width=100,height=50)\r\nbtnBackspace.bind('',EnterBackspace)\r\nbtnBackspace.bind('',LeaveBackspace)\r\n\r\n#digits or numbers and square root\r\ndigits = list('1234567890.')+['√']\r\nindex = 0\r\nfor row in range(4):\r\n for col in range(3):\r\n global d\r\n d = digits[index]\r\n index += 1\r\n btnDigit=tkinter.Button(Calculator,text=d,command=lambda x=d:ButtonClick(x),bg=rca)\r\n btnDigit.place(x=10+col*100,y=115+row*50,width=100,height=50)\r\n\r\n\r\n#operators\r\nOperators = ('+','-','*','/','**','//') #** is number to the power of number, // is take the divisible\r\nbtnPlus = tkinter.Button(Calculator,text='+',command=lambda:ButtonClick('+'),bg=rcb)\r\nbtnPlus.place(x=310,y=65,width=100,height=50)\r\nbtnPlus.bind('',EnterPlus)\r\nbtnPlus.bind('',LeavePlus)\r\n\r\nbtnMinus = tkinter.Button(Calculator,text='-',command=lambda:ButtonClick('-'),bg=rcb)\r\nbtnMinus.place(x=310,y=115,width=100,height=50)\r\nbtnMinus.bind('',EnterMinus)\r\nbtnMinus.bind('',LeaveMinus)\r\n\r\nbtnTime = tkinter.Button(Calculator,text='*',command=lambda:ButtonClick('*'),bg=rcb)\r\nbtnTime.place(x=310,y=165,width=100,height=50)\r\nbtnTime.bind('',EnterTime)\r\nbtnTime.bind('',LeaveTime)\r\n\r\nbtnDivide = tkinter.Button(Calculator,text='/',command=lambda x=Operators:ButtonClick('/'),bg=rcb)\r\nbtnDivide.place(x=310,y=215,width=100,height=50)\r\nbtnDivide.bind('',EnterDivide)\r\nbtnDivide.bind('',LeaveDivide)\r\n\r\nbtnDTime = tkinter.Button(Calculator,text='**',command=lambda:ButtonClick('**'),bg=rcb)\r\nbtnDTime.place(x=310,y=265,width=100,height=50)\r\nbtnDTime.bind('',EnterDTime)\r\nbtnDTime.bind('',LeaveDTime)\r\n\r\nbtnDDivide = tkinter.Button(Calculator,text='//',command=lambda x=Operators:ButtonClick('//'),bg=rcb)\r\nbtnDDivide.place(x=310,y=315,width=100,height=50)\r\nbtnDDivide.bind('',EnterDDivide)\r\nbtnDDivide.bind('',LeaveDDivide)\r\n\r\nbtnAns = tkinter.Button(Calculator,text='Ans',command=lambda:ButtonClick('Ans'),bg=rce)\r\nbtnAns.place(x=210,y=65,width=100,height=50)\r\nbtnAns['state'] = 'disable'\r\nbtnAns.bind('',EnterAns)\r\nbtnAns.bind('',LeaveAns)\r\n\r\nbtnPi = tkinter.Button(Calculator,text='π',command=lambda:ButtonClick('π'),bg=rca)\r\nbtnPi.place(x=210,y=315,width=100,height=50)\r\nbtnPi.bind('',EnterPi)\r\nbtnPi.bind('',LeavePi)\r\n\r\nbtnParenthesisLeft = tkinter.Button(Calculator,text='(',command=lambda:ButtonClick('(') ,bg=rcd)\r\nbtnParenthesisLeft.place(x=10,y=315,width=100,height=50)\r\nbtnParenthesisLeft.bind('',EnterParenthesisLeft)\r\nbtnParenthesisLeft.bind('',LeaveParenthesisLeft)\r\n\r\nbtnParenthesisRight = tkinter.Button(Calculator,text=')',command=lambda:ButtonClick(')'),bg=rcd)\r\nbtnParenthesisRight.place(x=110,y=315,width=100,height=50)\r\nbtnParenthesisRight.bind('',EnterParenthesisRight)\r\nbtnParenthesisRight.bind('',LeaveParenthesisRight)\r\n\r\nbtnSin = tkinter.Button(Calculator,text='sin',command=lambda:ButtonClick('sin'),bg=rcd)\r\nbtnSin.place(x=10,y=365,width=100,height=50)\r\nbtnSin.bind('',EnterSin)\r\nbtnSin.bind('',LeaveSin)\r\n\r\nbtnCos = tkinter.Button(Calculator,text='cos',command=lambda:ButtonClick('cos'),bg=rcd)\r\nbtnCos.place(x=110,y=365,width=100,height=50)\r\nbtnCos.bind('',EnterCos)\r\nbtnCos.bind('',LeaveCos)\r\n\r\nbtnTan = tkinter.Button(Calculator,text='tan',command=lambda:ButtonClick('tan'),bg=rcd)\r\nbtnTan.place(x=210,y=365,width=100,height=50)\r\nbtnTan.bind('',EnterTan)\r\nbtnTan.bind('',LeaveTan)\r\n\r\nbtnE = tkinter.Button(Calculator,text='!',command=lambda:ButtonClick('!'),bg=rcd)\r\nbtnE.place(x=10,y=415,width=100,height=50)\r\nbtnE.bind('',EnterE)\r\nbtnE.bind('',LeaveE)\r\n\r\n'''\r\nbtnColourA = tkinter.Button(Calculator,text='CA',command=lambda:randomcolor_a('on'),bg=rcd)\r\nbtnColourA.place(x=10,y=465,width=100,height=50)\r\n'''\r\nCalculator.mainloop\r\n\r\n'''\r\nmath.sin(math.radians())\r\n'''\r\n","sub_path":"Calculator 7_24.py","file_name":"Calculator 7_24.py","file_ext":"py","file_size_in_byte":15235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"205205092","text":"## =========================================================================\n## @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co)\n## =========================================================================\n\nimport math, numpy, sys\nimport matplotlib.pyplot as plt\n\nradii = [ [ 5, 1 ], [ 1.5, 6 ], [ 3, 3.5 ] ]\ncenters = [ [ 0, 0 ], [ 8, 8 ], [ 10, 0 ] ]\nangles = [ 1.3, 5.6, 0.1 ]\nn = [ 100, 200, 150 ]\n\nX = None\nstart = True\nfor i in range( len( radii ) ):\n Ri = numpy.random.uniform( low = 0, high = 1.5, size = ( n[ i ], 1 ) )\n Ti = numpy.random.uniform( low = 0, high = 2 * math.pi, size = ( n[ i ], 1 ) )\n Oi = numpy.ones( ( n[ i ], 1 ) )\n Xi = numpy.append( Ri * numpy.cos( Ti ), Ri * numpy.sin( Ti ), axis = 1 )\n Xi = numpy.append( Xi, Oi, axis = 1 )\n\n t = numpy.matrix( [ [ 1, 0, centers[ i ][ 0 ] ], [ 0, 1, centers[ i ][ 1 ] ], [ 0, 0, 1 ] ] )\n t = t * numpy.matrix( [ [ math.cos( angles[ i ] ), -math.sin( angles[ i ] ), 0 ], [ math.sin( angles[ i ] ), math.cos( angles[ i ] ), 0 ], [ 0, 0, 1 ] ] )\n t = t * numpy.matrix( [ [ radii[ i ][ 0 ], 0, 0 ], [ 0, radii[ i ][ 1 ], 0 ], [ 0, 0, 1 ] ] )\n Xi = numpy.delete( ( t * Xi.T ).T, 2, axis = 1 )\n if start:\n X = Xi\n start = False\n else:\n X = numpy.append( X, Xi, axis = 0 )\n# end for\n\n# Show data\nfig, ax1 = plt.subplots( nrows = 1 )\nax1.axis( \"equal\" )\nplt.scatter( numpy.squeeze( numpy.asarray( X[ : , 0 ] ) ), numpy.squeeze( numpy.asarray( X[ : , 1 ] ) ), c = \"#ff0000\", marker = \"x\" )\nplt.show( )\n\nif len( sys.argv ) > 1:\n numpy.savetxt( sys.argv[ 1 ], X, delimiter = \",\" )\n# end if\n\n## eof - $RCSfile$\n","sub_path":"examples/kmeans/CreateSamples.py","file_name":"CreateSamples.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"406134316","text":"#frontend\r\n\r\nfrom tkinter import *\r\nimport tkinter.messagebox\r\n#import stdDatabase\r\n\r\n\r\nclass Student:\r\n\r\n def __init__(self, root):\r\n self.root = root\r\n self.root.title(\"Student DAtabase Management System\")\r\n self.root.geometry(\"13150x750x0x0\")\r\n self.root.cofig(bg=\"cadet blue\")\r\n\r\n StdID = StringVar()\r\n Firstname = StringVar()\r\n Lastname = StringVar()\r\n Dob = StringVar()\r\n Age = StringVar()\r\n Gender = StringVar()\r\n Adress= StringVar()\r\n Mobile = StringVar()\r\n\r\n\r\n\r\n #========================================frame===========================================\r\n\r\n MainFrame=Frame(self.root, bg=\"cadet blue\")\r\n MainFrame.grid()\r\n\r\n\r\n TitFrame = Frame(MainFrame, bd=2,padx=54, pad=8, bg=\"Ghost WHite\", relief=RIDGE )\r\n TitFrame.pack(side=TOP)\r\n\r\n self.lblTit = Label(TitFrame,font=(\"arial\", 47, 'bold'), text='Student MAnagement system', bg=\"Ghost White\")\r\n self.lblTit.grid()\r\n\r\n ButtonFrame = Frame( MainFrame, bd=2, width=1350, height=70, padx=7, pady=10, bg=\"Ghost White\", relief=RIDGE)\r\n ButtonFrame.pack(side=BOTTOM)\r\n\r\n DataFrame = Frame(MainFrame,bd=1, width=1300, height='400',padx=20,pady=20,relief= RIGHT, bg=\"cader=t blue\")\r\n DataFrame.pack(side=LEFT)\r\n\r\n DataFrameLEFT =LabelFrame(MainFrame, bd=1, width=1000 , height=600, padx=20, relief=RIDGE, bg='Ghost White',\r\n font=(\"arial\", 20, 'bold'),text=\"Student Info\")\r\n DataFrameLEFT.pack(side=LEFT)\r\n\r\n DataFrameRIGHT= LabelFrame(DataFrame, bd=1, width=450, height=\"300\", padx=31, pady=3, relief=RIDGE,\r\n bg=\"Ghost White\",font=(\"arial\", 20, 'bold'), text=\"Student Info\")\r\n DataFrameRIGHT.pack(side=RIGHT)\r\n\r\n #================================Label and Entry===========================================================\r\n self.lblStdID = Label(DataFrameLEFT, font=(\"arial\", 20, 'bold'), text='Student ID: ',padx=2, pady=2,bg=\"Ghost White\")\r\n self.lblStdID.grid(row=0, column=0, sticky='w')\r\n self.lblStdID = Entry(DataFrameLEFT, font=(\"arial\", 20, 'bold'), textvariable=StdID, width=39)\r\n self.lblStdID.grid(row=0, column=1)\r\n\r\n\r\n self.lblfna = Label(DataFrameLEFT, font=(\"arial\", 20, 'bold'), text='First Name: ', padx=2, pady=2,\r\n bg=\"Ghost White\")\r\n self.lblfna.grid(row=1, column=0, sticky='w')\r\n self.lblfna = Entry(DataFrameLEFT, font=(\"arial\", 20, 'bold'), textvariable=Firstname, width=39)\r\n self.lblfna.grid(row=1, column=1)\r\n\r\n\r\n self.lbllna = Label(DataFrameLEFT, font=(\"arial\", 20, 'bold'), text='Last Name: ', padx=2, pady=2,\r\n bg=\"Ghost White\")\r\n self.lbllna.grid(row=2, column=0, sticky='w')\r\n self.lbllna = Entry(DataFrameLEFT, font=(\"arial\", 20, 'bold'), textvariable=Lastname, width=39)\r\n self.lbllna.grid(row=2, column=1)\r\n\r\n\r\n self.lblDob = Label(DataFrameLEFT, font=(\"arial\", 20, 'bold'), text='Date of Birth: ', padx=2, pady=2,\r\n bg=\"Ghost White\")\r\n self.lblDob.grid(row=3, column=0, sticky='w')\r\n self.lblDob = Entry(DataFrameLEFT, font=(\"arial\", 20, 'bold'), textvariable=Dob, width=39)\r\n self.lblDob.grid(row=3, column=1)\r\n\r\n\r\n self.lblAge = Label(DataFrameLEFT, font=(\"arial\", 20, 'bold'), text='Age: ', padx=2, pady=2,\r\n bg=\"Ghost White\")\r\n self.lblAge.grid(row=4, column=0, sticky='w')\r\n self.lblAge = Entry(DataFrameLEFT, font=(\"arial\", 20, 'bold'), textvariable=Age, width=39)\r\n self.lblAge.grid(row=4, column=1)\r\n\r\n self.lblGender = Label(DataFrameLEFT, font=(\"arial\", 20, 'bold'), text='Gender: ', padx=2, pady=2,\r\n bg=\"Ghost White\")\r\n self.lblGender.grid(row=5, column=0, sticky='w')\r\n self.lblGender = Entry(DataFrameLEFT, font=(\"arial\", 20, 'bold'), textvariable=Gender, width=39)\r\n self.lblGender.grid(row=5, column=1)\r\n\r\n self.lblAge = Label(DataFrameLEFT, font=(\"arial\", 20, 'bold'), text='Age: ', padx=2, pady=2,\r\n bg=\"Ghost White\")\r\n self.lblAge.grid(row=4, column=0, sticky='w')\r\n self.lblAge = Entry(DataFrameLEFT, font=(\"arial\", 20, 'bold'), textvariable=Age, width=39)\r\n self.lblAge.grid(row=4, column=1)\r\n\r\nif __name__=='__main__':\r\n root = Tk()\r\n app=Student(root)\r\n root.mainloop()\r\n\r\n","sub_path":"student_frontend.py","file_name":"student_frontend.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"1439488","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef eval_model(model, data_loader):\n \"\"\"Evaluation for target encoder by source classifier on target dataset.\"\"\"\n # set eval state for Dropout and BN layers\n model.eval()\n\n # init loss and accuracy\n loss = 0\n acc = 0\n\n # set loss function\n criterion = nn.CrossEntropyLoss()\n\n # evaluate network\n for (images, labels) in data_loader:\n images = images.to(device)\n labels = labels.to(device)\n\n preds = model(images)\n loss += criterion(preds, labels).data.item()\n\n pred_cls = preds.data.max(1)[1]\n acc += pred_cls.eq(labels.data).sum().item()\n\n loss /= len(data_loader)\n acc /= len(data_loader.dataset)\n\n print(\"Avg Loss = {}, Avg Accuracy = {:2%}\".format(loss, acc))\n\n return acc\n\ndef eval_encoder_and_classifier(encoder, classifier, data_loader):\n class Full(nn.Module):\n def __init__(self):\n super().__init__()\n self.encoder = encoder\n self.classifier = classifier\n\n def forward(self, img):\n feature = self.encoder(img)\n output = self.classifier(feature)\n return output\n\n full = Full()\n eval_model(full, data_loader)\n\n\ndef alter_dict_key(state_dict):\n new_dict = {}\n for key, val in state_dict.items():\n new_dict[key[7:]] = val\n return new_dict\n\n\ndef partial_load(model_cls, model_path):\n model = model_cls().to(device)\n model.eval()\n print(\"loading \", type(model).__name__, \" from \", model_path)\n saved_state_dict = torch.load(model_path, map_location=device)\n\n # remove leading 'module.' in state dict if needed\n alter = False\n for key, val in saved_state_dict.items():\n if key[:7] == 'module.':\n alter = True\n break\n if alter:\n print(\"keys in state dict starts with 'module.', trimming it.\")\n saved_state_dict = alter_dict_key(saved_state_dict)\n\n model_state_dict = model.state_dict()\n # filter state dict\n filtered_dict = {k: v for k, v in saved_state_dict.items() if k in model_state_dict}\n if len(filtered_dict) == len(saved_state_dict):\n print(\"model fully fits saved weights, performing complete load\")\n else:\n print(\"model and saved weights doesn't fully match, performing partial load. common states: \",\n len(filtered_dict), \", saved states: \", len(saved_state_dict))\n print(\"an item in saved dict is: \")\n for key, val in saved_state_dict.items():\n print(key)\n break\n model_state_dict.update(filtered_dict)\n model.load_state_dict(model_state_dict)\n return model\n\n\ndef kd_loss_fn(s_output, t_output, temperature, labels=None, alpha=0.4, weights=None):\n s_output = F.log_softmax(s_output/temperature, dim=1)\n t_output = F.softmax(t_output/temperature, dim=1)\n kd_loss = F.kl_div(s_output, t_output, reduction='batchmean')\n entropy_loss = kd_loss if labels is None else F.cross_entropy(s_output, labels)\n loss = (1-alpha)*entropy_loss + alpha*kd_loss*temperature*temperature\n return loss\n","sub_path":"DAFL/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"313642793","text":"from .db import db\nimport datetime\nfrom collections import OrderedDict\n\n\nclass RoutineResult(db.Model):\n __tablename__ = 'routine_results'\n\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(\n db.DateTime(), default=datetime.datetime.now(), nullable=False)\n routine_id = db.Column(\n db.Integer, db.ForeignKey(\"routines.id\"), nullable=False)\n routine = db.relationship(\"Routine\", back_populates=\"results\")\n results = db.relationship(\"WorkoutExerciseResult\",\n back_populates=\"routine_result\",\n cascade=\"all, delete\")\n\n def to_dict(self):\n\n return {\n \"id\": self.id,\n \"set\": self.set,\n \"reps\": self.reps,\n \"load\": self.load,\n \"time\": self.time,\n \"rest\": self.rest,\n \"workout_exercise_id\": self.workout_exercise_id,\n }\n\n def to_routine_dict(self):\n results = [result.to_exercise_dict() for result in self.results]\n return {\n \"id\": self.id,\n \"created_at\": self.created_at,\n \"results\": results,\n }\n","sub_path":"app/models/routine_result.py","file_name":"routine_result.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"107762091","text":"'''\nhttps://brilliant.org/wiki/tries/\n'''\n\n\nclass Node(object):\n\n def __init__(self, data=None):\n self.data = data\n self.next = dict()\n\n def __repr__(self):\n return \"Data: {}, Next:{}\".format(self.data, self.next)\n\n\nclass Trie(object):\n\n def __init__(self, root):\n self.root = root\n\n def add(self, keys, value):\n self._add(self.root, list(keys), value)\n\n def _add(self, node, keys, value):\n\n for index, key in enumerate(keys):\n\n choose = keys.pop(0)\n\n if choose not in node.next:\n node.next[choose] = Node()\n node = node.next[choose]\n self._add(node, keys, value)\n\n else:\n node = node.next[choose]\n self._add(node, keys, value)\n keys.insert(0, choose)\n\n node.data = value\n\n def find(self, keys):\n\n return self.find_(self.root, list(keys))\n\n def find_(self, node, keys):\n\n for index, key in enumerate(keys):\n\n choose = keys.pop(0)\n\n if choose in node.next:\n node = node.next[choose]\n return self.find_(node, keys)\n else:\n return False\n else:\n return True, node.data\n\n def returnAllTries(self):\n\n self.returnAllTries_(self.root)\n\n def returnAllTries_(self, node):\n keys = list(node.next.keys())\n print(\"node= \", node)\n print(\"keys=\", keys)\n\n for index, key in enumerate(keys):\n choose = keys.pop(0)\n print(choose)\n self.returnAllTries_(node.next[choose])\n\n keys.insert(0, choose)\n\n\ndef main():\n trie = Trie(Node())\n # trie.add(\"pe\", 3)\n # #print(trie.root)\n #\n #\n # trie.add(\"peas\", 300)\n # trie.add(\"peb\", 3000)\n # trie.add(\"pebble\", 30000)\n trie.add(\"dance\", 30000)\n\n\n# print (trie.find(\"pea\"))\n# print (trie.find(\"peas\"))\n# print (trie.find(\"pebs\"))\n# print (trie.find(\"pebble\"))\n# print (trie.find(\"dances\"))\n print(\"----------\")\n trie.returnAllTries()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Archive/P/Graphs/tries_recursive.py","file_name":"tries_recursive.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"610546168","text":"def namelist(names):\n res = \"\"\n for index in range(len(names)):\n for value in names[index].values():\n if index == 0:\n res = value\n elif index == len(names) - 1:\n res = res + \" & \" + value\n else:\n res = res + \", \" + value\n return res\n\nhashm = [{'name': 'Bart'},{'name': 'Lisa'},{'name': 'Maggie'},{'name': 'Homer'},{'name': 'Marge'}]\nprint(namelist(hashm))\n","sub_path":"CodeWars-Python/nameList.py","file_name":"nameList.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"291758560","text":"import unittest\nimport os\nimport json\n\nfrom reports.sites import BaseModule, Site\n\nBASE_PATH = os.path.join(os.path.dirname(__file__), 'test_data')\n\n\nclass TestModules(unittest.TestCase):\n def _create_module(self):\n url = \"example.com\"\n module = BaseModule('test', url, local=True, base_path=BASE_PATH)\n module.set_data({'foo': 'bar'})\n return module\n\n def test_module_create(self):\n module = self._create_module()\n self.assertDictEqual(module, {'test': {'foo': 'bar'}})\n\n def test_module_save(self):\n module = self._create_module()\n module.save()\n new_site = site = Site('example.com', local=True, base_path=BASE_PATH)\n self.assertDictEqual(\n new_site['modules']['test'],\n {u'test': {u'foo': u'bar'}})\n\n @classmethod\n def tearDownClass(cls):\n filename = os.path.join(BASE_PATH, \"urls\", \"example.com\", \"test.json\")\n if os.path.exists(filename):\n os.remove(filename)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"reports/sites/tests/test_modules.py","file_name":"test_modules.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"524832985","text":"\n\n#calss header\nclass _BACILLUS():\n\tdef __init__(self,): \n\t\tself.name = \"BACILLUS\"\n\t\tself.definitions = [u'a bacterium (= an extremely small organism) that is shaped like a rod. There are various types of bacillus, some of which can cause disease.']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_bacillus.py","file_name":"_bacillus.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"580337754","text":"# -*- coding: utf-8 -*-\r\n##\r\n# Copyright 2019 Atos - CoE Telco NFV Team\r\n# All Rights Reserved.\r\n#\r\n# Contributors: Oscar Luis Peral, Atos\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\r\n# not use this file except in compliance with the License. You may obtain\r\n# a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\r\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r\n# License for the specific language governing permissions and limitations\r\n# under the License.\r\n#\r\n# For those usages not covered by the Apache License, Version 2.0 please\r\n# contact with: \r\n#\r\n# Neither the name of Atos nor the names of its\r\n# contributors may be used to endorse or promote products derived from\r\n# this software without specific prior written permission.\r\n#\r\n# This work has been performed in the context of Arista Telefonica OSM PoC.\r\n##\r\nimport time\r\n\r\n\r\nclass AristaCVPTask:\r\n def __init__(self, cvpClientApi):\r\n self.cvpClientApi = cvpClientApi\r\n\r\n def __get_id(self, task):\r\n return task.get(\"workOrderId\")\r\n\r\n def __get_state(self, task):\r\n return task.get(\"workOrderUserDefinedStatus\")\r\n\r\n def __execute_task(self, task_id):\r\n return self.cvpClientApi.execute_task(task_id)\r\n\r\n def __cancel_task(self, task_id):\r\n return self.cvpClientApi.cancel_task(task_id)\r\n\r\n def __apply_state(self, task, state):\r\n t_id = self.__get_id(task)\r\n self.cvpClientApi.add_note_to_task(t_id, \"Executed by OSM\")\r\n if state == \"executed\":\r\n return self.__execute_task(t_id)\r\n elif state == \"cancelled\":\r\n return self.__cancel_task(t_id)\r\n\r\n def __actionable(self, state):\r\n return state in [\"Pending\"]\r\n\r\n def __terminal(self, state):\r\n return state in [\"Completed\", \"Cancelled\"]\r\n\r\n def __state_is_different(self, task, target):\r\n return self.__get_state(task) != target\r\n\r\n def update_all_tasks(self, data):\r\n new_data = dict()\r\n for task_id in data.keys():\r\n res = self.cvpClientApi.get_task_by_id(task_id)\r\n new_data[task_id] = res\r\n return new_data\r\n\r\n def get_pending_tasks(self):\r\n return self.cvpClientApi.get_tasks_by_status('Pending')\r\n\r\n def get_pending_tasks_old(self):\r\n taskList = []\r\n tasksField = {'workOrderId': 'workOrderId',\r\n 'workOrderState': 'workOrderState',\r\n 'currentTaskName': 'currentTaskName',\r\n 'description': 'description',\r\n 'workOrderUserDefinedStatus':\r\n 'workOrderUserDefinedStatus',\r\n 'note': 'note',\r\n 'taskStatus': 'taskStatus',\r\n 'workOrderDetails': 'workOrderDetails'}\r\n tasks = self.cvpClientApi.get_tasks_by_status('Pending')\r\n # Reduce task data to required fields\r\n for task in tasks:\r\n taskFacts = {}\r\n for field in task.keys():\r\n if field in tasksField:\r\n taskFacts[tasksField[field]] = task[field]\r\n taskList.append(taskFacts)\r\n return taskList\r\n\r\n def task_action(self, tasks, wait, state):\r\n changed = False\r\n data = dict()\r\n warnings = list()\r\n\r\n at = [t for t in tasks if self.__actionable(self.__get_state(t))]\r\n actionable_tasks = at\r\n\r\n if len(actionable_tasks) == 0:\r\n warnings.append(\"No actionable tasks found on CVP\")\r\n return changed, data, warnings\r\n\r\n for task in actionable_tasks:\r\n if self.__state_is_different(task, state):\r\n self.__apply_state(task, state)\r\n changed = True\r\n data[self.__get_id(task)] = task\r\n\r\n if wait == 0:\r\n return changed, data, warnings\r\n\r\n start = time.time()\r\n now = time.time()\r\n while (now - start) < wait:\r\n data = self.update_all_tasks(data)\r\n if all([self.__terminal(self.__get_state(t)) for t in data.values()]):\r\n break\r\n time.sleep(1)\r\n now = time.time()\r\n\r\n if wait:\r\n for i, task in data.items():\r\n if not self.__terminal(self.__get_state(task)):\r\n warnings.append(\"Task {} has not completed in {} seconds\".\r\n format(i, wait))\r\n\r\n return changed, data, warnings\r\n","sub_path":"RO-SDN-arista_cloudvision/osm_rosdn_arista_cloudvision/aristaTask.py","file_name":"aristaTask.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"171508026","text":"import os\n\nfrom django.contrib import admin\nfrom django.template.loader import get_template\nfrom django.template.loaders.app_directories import app_template_dirs\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.importlib import import_module\n\n#import settings\nfrom formatting import deslugify\n\nclass DynamicChoice(object):\n \"\"\"\n Trivial example of creating a dynamic choice\n \"\"\"\n\n def __iter__(self, *args, **kwargs):\n for choice in self.generate():\n if hasattr(choice,'__iter__'):\n yield (choice[0], choice[1])\n else:\n yield choice, choice\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n If you do it here it is only initialized once. Then just return generated.\n \"\"\"\n import random\n self.generated = [random.randint(1,100) for i in range(10)]\n\n def generate(self, *args, **kwargs):\n \"\"\"\n If you do it here it is initialized every time the iterator is used.\n \"\"\"\n import random\n return [random.randint(1,100) for i in range(10)]\n\n\n\nclass DynamicTemplateChoices(DynamicChoice):\n path = None\n\n # exclude templates whose name includes these keywords\n exclude = None\n\n # only include templates whos name contains these keywords\n inlude = None\n\n #\n # TODO: Scan for snippets as well.\n #\n # scan for and include snippets in choices?\n #scan_snippets = False\n\n # snippets whose title prefixed with this moniker are considered to be\n # templates for our cmsplugin.\n\n #snippet_title_moniker = getattr(\n # settings.CONFIGURABLEPRODUCT_CMSPLUGIN_SNIPPETS_MONIKER,\n # \"[configurableproduct-snippet]\")\n\n\n def __init__(self, path=None, include=None,\n exclude=None, *args, **kwargs):\n\n super(DynamicTemplateChoices, self).__init__(self, *args, **kwargs)\n self.path = path\n self.include = include\n self.exlude = exclude\n\n def generate(self,*args, **kwargs):\n choices = list((\"-[ Nothing Selected ]-\", ), )\n\n for template_dir in app_template_dirs:\n results = self.walkdir(os.path.join(template_dir, self.path))\n if results:\n choices += results\n\n return choices\n\n def walkdir(self, path=None):\n output = list()\n\n if not os.path.exists(path):\n return None\n\n for root, dirs, files in os.walk(path):\n\n if self.include:\n files = filter(lambda x: self.include in x, files)\n\n if self.exlude:\n files = filter(lambda x: not self.exlude in x, files)\n\n for item in files :\n output += ( (\n os.path.join(self.path, item),\n deslugify(os.path.splitext(item)[0]),\n ),)\n\n for item in dirs :\n output += self.walkdir(os.path.join(root, item))\n\n return output\n","sub_path":"cmsplugin_configurableproduct/lib/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"478072002","text":"# Copyright (c) 2007-2012 by Enrique Pérez Arnaud \n#\n# This file is part of the terms project.\n# https://github.com/enriquepablo/terms\n#\n# The terms project is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# The terms project is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with any part of the terms project.\n# If not, see .\n\n\n#import distribute_setup\n#distribute_setup.use_setuptools()\nfrom setuptools import setup, find_packages\n\nVERSION = '0.1.0a1dev1'\n\nsetup(\n name = 'terms.app.people',\n version = VERSION,\n author = 'Enrique Pérez Arnaud',\n author_email = 'enriquepablo@gmail.com',\n url = 'http://pypi.python.org/terms.core',\n license = 'GNU GENERAL PUBLIC LICENSE Version 3',\n description = 'Access control plugin for terms.robots',\n long_description = (open('README.rst').read() +\n '\\n' + open('INSTALL.rst').read()) +\n '\\n' + open('SUPPORT.rst').read(),\n\n packages = find_packages(),\n namespace_packages = ['terms', 'terms.app'],\n include_package_data = True,\n\n entry_points = {\n },\n tests_require = [\n ],\n extras_require = {\n },\n install_requires = [\n 'Terms[PG]',\n 'terms.robots',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"223201341","text":"import itertools\nfrom functools import reduce\n\ndef uncurry(func):\n def new_func(*args):\n result = func\n for arg in args:\n result = result(arg)\n return result\n return new_func\n\ndef flatten(lli):\n return itertools.chain.from_iterable(lli)\n\ndef collect(lk):\n used = []\n pairs = list(lk)\n for k, v in pairs:\n if k not in used:\n used.append(k)\n yield k, [q for p, q in pairs if p == k]\n\nclass Sketch(object):\n def __init__(self, types, flatten = False, applier = False):\n # have to produce the appropriate types for reqs\n # choice based on flatten and applier\n # flatten - m: input -> [inter]\n # if keyed - inter: (k, reducible)\n # if applier - a: reducible -> output\n \n # flags for sketch kind\n self.flattened = flatten\n self.applied = applier\n self.keyed = len(types) >= 3\n # writer so we can make new stuff\n # maybe\n\n # compute requirements\n # pull out default types\n i_t, o_t = types[0], types[1]\n self.reqs = [\"{input} -> {inter}\", \"{red} -> {red} -> {red}\"]\n mappings = {'input': i_t, 'output': o_t}\n\n # see if we have any free vars\n if self.applied:\n self.reqs.append(\"{final} -> {output}\")\n mappings['red'] = '1'\n else:\n mappings['red'] = o_t\n # see if we're keyed or not\n if len(types) > 2:\n mappings['inter'] = \"({}, {})\".format(types[2], mappings['red'])\n mappings['final'] = \"[({}, {}]\".format(types[2], mappings['red'])\n else:\n mappings['inter'] = mappings['red']\n mappings['final'] = mappings['red']\n # now, check for flattening stuff\n if self.flattened:\n mappings['inter'] = \"[{}]\".format(mappings['inter'])\n # now set requirements\n self.reqs = [s.format(**mappings) for s in self.reqs]\n def _create(self, m, r, a = lambda s: s):\n def filled_sketch(li):\n r = uncurry(r)\n # first map over\n mapped = map(m, li)\n # if we need to flatten, do it\n if self.flattened:\n mapped = flatten(mapped)\n # if we have keys, collect by value\n if self.keyed:\n reduced = []\n for k, v in collect(mapped):\n reduced.append( (k, reduce(r, v)) )\n # else we just reduce\n else:\n reduced = reduce(r, mapped)\n # applier defaults to id\n return a(reduced)\n return filled_sketch\n def dynamic_csg_checker(self, m, r):\n def checker(li):\n r = uncurry(r)\n old_value = None\n for p in permutations(li, len(li)):\n mapped = map(m, p)\n if self.flattened:\n mapped = flatten(mapped)\n # now we apply and compare to some old value\n if self.keyed:\n reduced = []\n for k, v in collect(mapped):\n reduced.append( (k, reduce(r, v)) )\n else:\n reduced = reduce(r, mapped)\n if isinstance(reduced, list):\n reduced = sorted(reduced)\n if old_value and (reduced != old_value):\n return False\n else:\n old_value = reduced\n return True\n return checker\n","sub_path":"takethree/sketches.py","file_name":"sketches.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"344633042","text":"from win32 import win32clipboard\nfrom time import sleep, gmtime\nfrom os import mkdir\nfrom os.path import exists, expanduser\n\n\ndef get_timestamp():\n now = gmtime()\n return f\"{now.tm_mday}-{now.tm_mon}-{now.tm_year} {now.tm_hour}-{now.tm_min}-{now.tm_sec}\"\n\n\nbmp_header_hex = \"424d000000000000000042000000\"\n\nimage_path = expanduser(\"~\") + \"/Pictures/Screenshots/\"\n\nwhile True:\n win32clipboard.OpenClipboard()\n if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB):\n data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)\n\n if not exists(image_path):\n mkdir(image_path)\n\n with open(f\"{image_path}{get_timestamp()}.bmp\", \"wb\") as f:\n f.write(bytearray.fromhex(bmp_header_hex))\n f.write(data)\n\n win32clipboard.EmptyClipboard()\n win32clipboard.CloseClipboard()\n\n sleep(2)\n","sub_path":"screenshot_saver.py","file_name":"screenshot_saver.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"148657826","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom database_setup import Category, Base\n\nengine = create_engine('sqlite:///itemcatalog.db')\n\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\nSoccer = Category(name=\"Soccer\")\nsession.add(Soccer)\nsession.commit()\n\nBasketball = Category(name=\"Basketball\")\nsession.add(Basketball)\nsession.commit()\n\nBaseball = Category(name=\"Baseball\")\nsession.add(Baseball)\nsession.commit()\n\nFrisbee = Category(name=\"Frisbee\")\nsession.add(Frisbee)\nsession.commit()\n\nSnowboarding = Category(name=\"Snowboarding\")\nsession.add(Snowboarding)\nsession.commit()\n\nRockClimbing = Category(name=\"Rock Climbing\")\nsession.add(RockClimbing)\nsession.commit()\n\nFootball = Category(name=\"Football\")\nsession.add(Football)\nsession.commit()\n\nSkating = Category(name=\"Skating\")\nsession.add(Skating)\nsession.commit()\n\nHockey = Category(name=\"Hockey\")\nsession.add(Hockey)\nsession.commit()\n\nprint(\"Categories created!\")","sub_path":"initData.py","file_name":"initData.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"577750637","text":"import time\nfrom Appium.AppControl import Webdriver\n\nif __name__ == '__main__':\n\n driver = Webdriver.create_webdriver(platform='ios', bundle_id='gmail')\n time.sleep(3)\n # iOS原生不支持W3C标准滚屏操作, 所以只能指定滚屏的方向, 不能指定滚动多少个像素\n # 一样来说一次滚动就是一个屏幕的距离\n driver.execute_script(\"mobile: swipe\", {\"direction\": \"down\"}) # 要注意手机上方向与屏幕运动方向相反的\n\n # 尝试使用page source对比实现一直向下滚动\n # 原理是如果滚动到底, 两次滚动之后的页面应该保持不变\n # 但实际上是不可行的, 因为iOS中获取到的page source包括手机的时间, 所以page source怎么都不会完全一样\n # ps1 = driver.page_source\n # while True:\n # driver.execute_script(\"mobile: swipe\", {\"direction\": \"up\"})\n # time.sleep(2)\n # ps2 = driver.page_source\n # if ps1 == ps2:\n # break\n # else:\n # ps1 = ps2\n time.sleep(3)\n\n driver.quit()\n\n","sub_path":"Python-Library/Appium/AppControl/Swipe_ios.py","file_name":"Swipe_ios.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"109905101","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nApply filters on data\n\"\"\"\n\nimport numpy as np\n\n\ndef moving_average(lst, n=3):\n \"\"\"\n :param lst: []\n List of floats\n :param n: int\n Steps\n :return: []\n Moving average of steps applied in sequence\n \"\"\"\n\n ret = np.cumsum(lst, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\n\n\ndef pascal_row(n):\n \"\"\"\n :param n: int\n Number of row of pascal triangle to compute\n :return: [] of int\n Row of pascal triangle\n \"\"\"\n\n row = [1] # side case\n for k in range(int((n - 1) / 2)): # first half of row\n row.append(row[k] * (n - k) / (k + 1))\n\n middle_pos = [] # center of row\n if n % 2 == 0: # n is even\n middle_pos = [(row[-1] * (n / 2 + 1)) / (n / 2)]\n\n return row + middle_pos + list(reversed(row))\n\n\ndef binomial_filter(lst, m):\n \"\"\"\n :param lst: []\n List of floats\n :param m: int\n Exponent\n :return: []\n Binomial filter applied to sequence\n \"\"\"\n\n weights = pascal_row(m) # calculate pascal row\n weights = np.divide(weights, np.power(2, m)) # normalize weights\n w = len(weights)\n out = [] # result\n\n for i in range(len(lst) - w + 1): # i is the index of weighted seq\n out.append(\n np.dot(lst[i: i + w], weights)\n ) # weighted sum\n\n return out\n\n\ndef holt_exp_smoother(lst, a):\n \"\"\"\n :param lst: []\n List of floats\n :param a: float\n Smoothing parameter\n :return: []\n Holt exponential smoother applied to sequence. y(t) = a * x(t) + (1\n - a) * y(t - 1)\n \"\"\"\n\n out = [lst[0]] # result\n\n for value in lst[1:]: # start from second value (first is already in)\n out.append(\n a * value + (1 - a) * out[-1]\n ) # combine true result and last known value\n\n return out\n","sub_path":"maths/coins/pattern_finder/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"436323998","text":"import scrapy\nfrom realestate_3.items import REItem\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors import LinkExtractor\n\nimport datetime\n\n\nclass rentSpider(CrawlSpider):\n name = \"georgeselliscomau\"\n allowed_domains = ['georgesellis.com.au']\n start_urls = ['http://www.georgesellis.com.au/search/?search_type=buy&result=1',\n 'http://www.georgesellis.com.au/search/?search_type=rent&result=1',\n 'http://www.georgesellis.com.au/real-estate/sold/'\n ]\n count = 0\n\n rules = (\n Rule(LinkExtractor(allow=allowed_domains, restrict_xpaths=('/html/body/div[1]/article/section/div[2]/article/div[2]/div[1]/h2/a')),callback='parse3', follow=True),\n Rule(LinkExtractor(allow=allowed_domains, restrict_xpaths=('/html/body/div[1]/article/section/div[1]/article/div[2]/div[1]/h2/a')),callback='parse3', follow=True),\n Rule(LinkExtractor(allow=allowed_domains, restrict_xpaths=('//*[@id=\"yw0\"]/li[@class=\"next\"]/a')), follow=True),\n # /html/body/div[1]/article/section/div[1]/article[1]/div[1]/a\n # /html/body/div[1]/article/section/div[1]/article[1]/div[2]/div[1]/h2/a\n )\n\n def parse3(self, response):\n\n\n # defaults\n item = REItem()\n for key in item.fields:\n item[key] = 0\n\n item['sold'] = 'False'\n item['source_url'] = response.url\n item['address_state'] = 'NSW'\n item['address_postcode'] = 0000\n\n dump_html = response.body\n dump_html = dump_html.decode('UTF-8','ignore').replace('\\'', '\\\"')\n item['dump_html'] = dump_html\n date = datetime.datetime.now()\n item['created'] = '%s-%s-%s %s:%s:%s' % (date.year, date.month, date.day, date.hour, date.minute, date.second)\n # no default\n\n # sold\n if 'sold' in response.request.headers.get('Referer', None):\n item['sold'] = 'True'\n\n # agency_name\n item['agency_name'] = 'Georges Ellis & Co.'\n\n # agent_url\n try:\n item['agent_url'] = response.xpath('/html/body/div[1]/article/section/div[3]/div[1]/section[1]/h4/text()').extract()[0].strip() + ', '+ \\\n response.xpath('/html/body/div[1]/article/section/div[3]/div[1]/section[1]/ul/li[2]/text()').extract()[0].encode('ascii','ignore').replace('\\n','').strip()\n #/html/body/div[1]/div[3]/div/div[2]/section[3]/div[2]/div[1]/div/p/text()\n except:\n pass\n\n # address\n address = response.xpath('/html/body/div[1]/article/section/div[3]/section/h3/text()').extract()[0].strip()\n address = address.split(',')\n item['address_street'] = address[0]\n try:\n item['address_suburb'] = address[1]\n item['address_state'] = address[2]\n item['address_postcode'] = address[3]\n except Exception:\n pass\n if len(address) < 2:\n item['address_street'] = 0\n item['address_suburb'] = address[0]\n\n # description\n desc = []\n for i in response.xpath('/html/body/div[1]/article/section/div[3]/section/div[2]/div[2]/text()').extract():\n i = i.encode('ascii', 'ignore').strip()\n if i == '':\n continue\n desc.append(i)\n desc = str(map(str, desc))\n desc = desc.replace('[', '').replace(']', '').replace('\\'', '\\\"')\n item['description'] = desc\n\n # title\n item['title'] = response.xpath('/html/body/div[1]/article/section/div[@class=\"description-wrapper\"]/h2/text()').extract()[0].replace('\\'', '\\\"')\n\n # price\n try:\n item['price'] = response.xpath('//div[@class=\"price\"]/div/span/text()').extract()[0]\n if '$' not in item['price']:\n item['price'] = 0\n except:\n pass\n\n # bbc\n bbc = response.xpath('/html/body/div[1]/article/section/div[3]/section/ul/li')\n for i in bbc:\n if 'bed' in i.xpath('@class').extract():\n item['bedrooms'] = i.xpath('text()').extract()[0]\n if 'bath' in i.xpath('@class').extract()[0]:\n item['bathrooms'] = i.xpath('text()').extract()[0]\n if 'car' in i.xpath('@class').extract()[0]:\n item['garage_spaces'] = i.xpath('text()').extract()[0]\n\n # coords\n # 'google.maps.LatLng('\n # google.maps.LatLng(\n try:\n coords = response.body.find('google.maps.LatLng(')\n coords = response.body[coords:coords+100]\n coords = coords[19:coords.find(')')]\n coords = coords.split(',')\n # print coords\n item['latitude'] = float(coords[0].replace('\"','').strip())\n item['longitude'] = float(coords[1].replace('\"','').strip())\n except:\n pass\n\n return item\n\n","sub_path":"realestate_from_luke/realestate_3/realestate_3/spiders/georgeselliscomau.py","file_name":"georgeselliscomau.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"297075045","text":"import json\n\nfrom html import unescape\n\nfrom .logger import logger\nfrom .selector import Selector \n\n\nclass BaseItem(type):\n\n def __new__(cls, name, bases, namespace):\n selector = {}\n for name, value in namespace.items():\n if isinstance(value, Selector):\n selector[name] = value\n \n namespace['selector'] = selector\n\n return type.__new__(cls, name, bases, namespace)\n\n\n# get help of metaclass:\n# https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python\nclass Item(metaclass=BaseItem):\n\n def __init__(self, spider, response, isJson=False):\n html = response.text\n self.result = {}\n self.spider = spider\n self.response = response\n if isJson:\n self.result['json'] = json.loads(html)\n else:\n html = unescape(html)\n\n for name, selector in self.selector.items():\n contents = selector.get_select(html)\n if contents is None:\n logger.error('selector \"{}:{}\" was error, please check again.'.format(name, selector))\n continue\n \n self.result[name] = contents\n\n def save(self):\n\n raise(TypeError('No save operation.'))\n\n\n# save binary data.\nclass BinItem(object):\n\n def __init__(self, spider, response):\n self.response = response\n self.spider = spider\n self.content = response.content\n\n def save(self):\n\n raise(TypeError('No save operation.'))\n\n\n","sub_path":"seen/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"300860566","text":"import mne\nimport scipy.sparse\n\ndef con_mat_build(mat):\n mat_size = mat.shape[0]\n new_mat_size = mat.shape[0]*6\n new_mat = scipy.sparse.dok_matrix((new_mat_size,new_mat_size))\n \n for i_idx in range(0,new_mat_size,mat_size):\n new_mat[i_idx:i_idx+mat_size,i_idx:i_idx+mat_size] = mat\n for i_idx in range(mat_size,new_mat_size,mat_size):\n new_mat[i_idx-mat_size:i_idx,i_idx:i_idx+mat_size] = mat\n \n return new_mat\n \n\nproc_dir = \"../proc/\"\n\nfilename = \"fsaverage-src.fif\"\n\nsrc_l = mne.read_source_spaces(proc_dir+filename)\n#src_r = src_l.copy()\n#src_l.remove(src_l[1])\n#src_r.remove(src_r[0])\n\ncnx_l = mne.spatial_src_connectivity(src_l)\n#cnx_r = mne.spatial_src_connectivity(src_r)\n\n#del src_l, src_r\n\n#f_cnx_l = con_mat_build(cnx_l)\nscipy.sparse.save_npz(\"cnx_lh.npz\",scipy.sparse.coo_matrix(cnx_l))\n#scipy.sparse.save_npz(\"f_cnx_lh.npz\",scipy.sparse.coo_matrix(f_cnx_l))\n#del f_cnx_l\n#f_cnx_r = con_mat_build(cnx_r)\n#scipy.sparse.save_npz(\"cnx_rh.npz\",scipy.sparse.coo_matrix(cnx_r))\n#scipy.sparse.save_npz(\"f_cnx_rh.npz\",scipy.sparse.coo_matrix(f_cnx_r))\n#del f_cnx_r\n\n\n\n","sub_path":"make_connect_mat.py","file_name":"make_connect_mat.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"528398178","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtSql import *\nfrom PyQt5.QtWidgets import *\n\nfrom UI.SimpleTable import Ui_MainWindow\n\n\ndef createConnection():\n \"\"\"\n Connects to reddit-data.db and returns the connection\n :return: QSqlDatabase\n \"\"\"\n db = QSqlDatabase.addDatabase('QSQLITE')\n db.setDatabaseName('reddit-data.db')\n db.open()\n return db\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self, flags=None, *args, **kwargs):\n super().__init__(flags, *args, **kwargs)\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n\n # Connect to database and load table\n model = QSqlRelationalTableModel(db=createConnection())\n model.setTable('Posts')\n\n # Set relation so that `name` will display instead of `author_id`\n model.setRelation(model.fieldIndex('author_id'),\n QSqlRelation('Redditor', 'id', 'name'))\n\n # Display capitalized version of the column headers\n model.setHeaderData(model.fieldIndex('author_id'),\n Qt.Horizontal, 'Author')\n\n # Fetch the contents of the table\n model.select()\n\n # Set the contents of the table to use our model\n self.ui.tableView.setModel(model)\n\n # Finish customizing the table\n self.ui.tableView.hideColumn(model.fieldIndex('id'))\n self.ui.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QApplication(sys.argv)\n window = MainWindow()\n\n window.show()\n sys.exit(app.exec_())\n","sub_path":"QSqlRelationalTableModel.py","file_name":"QSqlRelationalTableModel.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"571794185","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, optimizers, datasets, Sequential\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\ntf.random.set_seed(2345)\n\nclass BasicBlock(layers.Layer):\n\n def __init__(self, filter_num, stride=1):\n super(BasicBlock, self).__init__()\n\n self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same')\n self.bn1 = layers.BatchNormalization()\n self.relu = layers.Activation('relu')\n self.conv2 = layers.Conv2D(filter_num, (3, 3), strides=1, padding='same')\n self.bn2 = layers.BatchNormalization()\n\n\n self.downsample = lambda x:x\n\n\n\n def call(self, inputs, training=None):\n\n # [b, h, w, c]\n out = self.conv1(inputs)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n identity = self.downsample(inputs)\n\n output = layers.add([out, identity])\n output = tf.nn.relu(output)\n\n return output\n\n\nclass ResNet(keras.Model):\n\n\n def __init__(self, blocks): #\n super(ResNet, self).__init__()\n\n self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1),\n padding = 'same'),\n layers.BatchNormalization(),\n layers.Activation('relu')\n ])\n\n self.res_blocks = Sequential()\n # may down sample\n\n for _ in range(blocks):\n self.res_blocks.add(BasicBlock(64, stride=1))\n\n # output: [b, 96, 96, 3],\n self.final = Sequential([layers.Conv2D(3, (3, 3), strides=(1, 1),\n padding = 'same'),\n layers.BatchNormalization()\n ])\n\n\n\n\n\n\n\n def call(self, inputs, training=None):\n\n x = self.stem(inputs)\n\n x = self.res_blocks(x)\n\n x = self.final(x)\n\n x = tf.nn.tanh(x)\n\n return x\n\n\n\n\ndef main():\n\n model = ResNet(16)\n model.build(input_shape=(None, 96, 96, 3))\n model.summary()\n\n optimizer = tf.optimizers.Adam(lr=1e-4)\n\n path_input = \"img/Block_QP0.2/\"\n path_lebel = \"img/Or_foreman/\"\n\n\n\n\n for epoch in range(300):\n\n for filename in os.listdir(path_input):\n filname_y = filename.replace(\"Block_\",\"OriForeman_\")\n\n x = plt.imread(path_input + filename)\n y = plt.imread(path_lebel + filname_y)\n x = 2 * tf.cast(x, dtype=tf.float32) / 127. - 1\n y = 2 * tf.cast(y, dtype=tf.float32) / 255. - 1\n y = tf.reshape(y, [1, 96, 96, 3])\n x = tf.reshape(x, [1, 96, 96, 3])\n\n\n with tf.GradientTape() as tape:\n logits = model(x)\n logits = tf.reshape(logits,[1,96*96*3])\n y = tf.reshape(y,[1,96*96*3])\n loss = tf.reduce_mean(tf.square(y-logits))\n\n grads = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n print(loss)\n model.save_weights(\"weights/weights_qp0.2.h5\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"otherCode/ivc_train.py","file_name":"ivc_train.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"610789468","text":"from bs4 import BeautifulSoup\nimport re\nimport requests\nimport pandas as pd\n#import seaborn as sns\n\n\ndef get_playlist_items(playlist_id):\n \"\"\"\n Return the ids of all videos in a playlist.\n \"\"\"\n response = requests.get(\n 'https://www.youtube.com/playlist?list=' + playlist_id)\n soup = BeautifulSoup(response.text)\n pl_elems = soup.find_all(\"tr\", {\"class\": \"pl-video yt-uix-tile \"})\n return [pl_elem['data-video-id'] for pl_elem in pl_elems]\n\n\ndef get_video_metadata(video_id):\n \"\"\"\n Return some video metadata.\n \"\"\"\n response = requests.get('https://www.youtube.com/watch?v=' + video_id)\n soup = BeautifulSoup(response.text)\n view_str = soup.find(\"div\", {\"class\": \"watch-view-count\"}).find(text=True)\n title = soup.find(\"span\", {\"id\": \"eow-title\"}).find(text=True)\n return {'view_count': int(re.sub(\"[^0-9]\", \"\", view_str)),\n 'title': title,\n 'id': video_id}\n\n\ndef get_playlist_metadata(playlist_id):\n \"\"\"\n Return some metadata of all videos in a playlist.\n \"\"\"\n playlist_ids = get_playlist_items(playlist_id)[:3]\n return pd.DataFrame([get_video_metadata(playlist_id) for playlist_id in playlist_ids])\n","sub_path":"pyutils/playlist_churn.py","file_name":"playlist_churn.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"178032633","text":"\"\"\"\n\t@author: Ingrid Navarro\n\t@date: Dec 17th, 2018\n\t@brief: Network configuration\n\"\"\"\nimport os\n\nclass Configuration():\n\tdef\t__init__(self, data_path, network, training):\n\n\t\tself.data_path = data_path\n\t\tself.classes = os.listdir(self.data_path)\n\t\tself.num_classes = len(self.classes)\n\t\tself.is_training = training # defines if training or testing\n\n\t\t# Image configuration\n\t\tself.img_scale = 1.0\n\t\tself.img_depth = 3\n\t\t\n\t\t# Training configuration \n\t\tself.split_size = 0.15\n\t\tself.batch_size = 64\n\t\tself.dropout_rate = 0.5\n\t\t\n\t\tself.save_each_n = 20\n\t\tself.img_width = 224\n\t\tself.img_height = 224\n\n\t\tif network == \"alexnet\":\n\t\t\tself.learning_rate = 1e-5\n\t\t\tself.img_width = 227\n\t\t\tself.img_height = 227\n\t\t\tself.net_dict = {\n\t\t\t\t\"train_layers\" : ['fc8', 'fc7', 'fc6', 'conv5' ],\n\t\t\t\t\"meta_file\"\t : './pretrained/alexnet/alexnet.meta',\n\t\t\t\t\"weights\"\t : './pretrained/alexnet/alexnet.npy'\n\t\t\t}\n\n\t\t# This is VGG16\n\t\telif network == \"vgg\":\n\t\t\tself.learning_rate = 1e-4\n\t\t\tself.net_dict = {\n\t\t\t\t\"train_layers\" : ['fc8', 'fc7', 'fc6', 'conv5_3', 'conv5_2', 'conv5_1'],\n\t\t\t\t\"meta_file\" : './pretrained/vgg16/vgg16.meta',\n\t\t\t\t\"weights\"\t : './pretrained/vgg16/vgg16_weights.npz'\n\t\t\t}\n\n\t\t# This is Inception v4\n\t\telif network == \"inception\":\n\t\t\tself.img_width = 299\n\t\t\tself.img_height = 299\n\t\t\tself.learning_rate = 1e-4\n\t\t\tself.dropout_rate = 0.8\n\t\t\tself.net_dict = {\n\t\t\t\t\"train_layers\" : [],\n\t\t\t\t\"meta_file\" : './pretrained/inception/inception.meta',\n\t\t\t\t\"weights\"\t : './pretrained/inception/inception.npz'\n\t\t\t}","sub_path":"classifier/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"342528576","text":"# 괄호\nimport sys\nn = int(sys.stdin.readline())\n\ndef VPS():\n stack =[]\n chk = 0\n for i in range(len(a)):\n if a[i] == '(':\n stack.append(chk)\n chk += 1\n else:\n if chk > 0 and stack[len(stack)-1] == chk-1:\n stack.pop()\n chk -= 1\n else:\n return False\n return chk == 0\n\nfor i in range(n):\n a = str(sys.stdin.readline().rstrip())\n result = \"YES\" if VPS() else \"NO\"\n print(result)","sub_path":"Python/2주차_큐,스택,이분탐색,분할정복/정글_2_9012.py","file_name":"정글_2_9012.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"537993484","text":"# -*- coding:utf-8 -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\nSTOP_RENDERING = runtime.STOP_RENDERING\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1555053520.9415965\n_enable_loop = True\n_template_filename = 'C:/Users/Isaac/intexsite/portal/templates/app_base.htm'\n_template_uri = 'app_base.htm'\n_source_encoding = 'utf-8'\nimport django_mako_plus\nimport django.utils.html\n_exports = ['page_title', 'page_header_title', 'bodyclass', 'left_content', 'middleclass', 'right_content']\n\n\nfrom catalog import models as cmod \n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n pass\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, '/homepage/templates/base.htm', _template_uri)\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n def bodyclass():\n return render_bodyclass(context._locals(__M_locals))\n def page_header_title():\n return render_page_header_title(context._locals(__M_locals))\n def right_content():\n return render_right_content(context._locals(__M_locals))\n def left_content():\n return render_left_content(context._locals(__M_locals))\n def page_title():\n return render_page_title(context._locals(__M_locals))\n def middleclass():\n return render_middleclass(context._locals(__M_locals))\n user = context.get('user', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n __M_writer('\\r\\n\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'page_title'):\n context['self'].page_title(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'page_header_title'):\n context['self'].page_header_title(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'bodyclass'):\n context['self'].bodyclass(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'left_content'):\n context['self'].left_content(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'middleclass'):\n context['self'].middleclass(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'right_content'):\n context['self'].right_content(**pageargs)\n \n\n __M_writer('\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_page_title(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def page_title():\n return render_page_title(context)\n __M_writer = context.writer()\n __M_writer('— Portal')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_page_header_title(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def page_header_title():\n return render_page_header_title(context)\n user = context.get('user', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n\\r\\n')\n if user.groups.filter(name='Prescribers').exists():\n __M_writer('

Prescriber Portal

\\r\\n')\n else:\n if user.groups.filter(name='HealthOfficials').exists():\n __M_writer('

Health Official Portal

\\r\\n')\n else:\n if user.groups.filter(name='HHS').exists():\n __M_writer('

Data Clerk Portal

\\r\\n')\n else:\n __M_writer('

Portal

\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_bodyclass(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def bodyclass():\n return render_bodyclass(context)\n user = context.get('user', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n if user.groups.filter(name='Prescribers').exists():\n __M_writer('\\r\\n')\n else:\n if user.groups.filter(name='HHS').exists():\n __M_writer(' \\r\\n')\n else:\n if user.groups.filter(name='HealthOfficials').exists() or user.groups.filter(name='Officials').exists:\n __M_writer(' \\r\\n')\n else:\n __M_writer(' \\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_left_content(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def left_content():\n return render_left_content(context)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_middleclass(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def middleclass():\n return render_middleclass(context)\n user = context.get('user', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n if user.groups.filter(name='Prescribers').exists():\n __M_writer('
\\r\\n')\n else:\n if user.groups.filter(name='HealthOfficials').exists():\n __M_writer('
\\r\\n')\n else:\n if user.groups.filter(name='HHS').exists():\n __M_writer('
\\r\\n')\n else:\n __M_writer('
\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_right_content(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def right_content():\n return render_right_content(context)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"filename\": \"C:/Users/Isaac/intexsite/portal/templates/app_base.htm\", \"uri\": \"app_base.htm\", \"source_encoding\": \"utf-8\", \"line_map\": {\"18\": 2, \"31\": 0, \"49\": 1, \"50\": 2, \"55\": 5, \"60\": 23, \"65\": 39, \"70\": 43, \"75\": 59, \"80\": 62, \"86\": 5, \"92\": 5, \"98\": 8, \"105\": 8, \"106\": 10, \"107\": 11, \"108\": 12, \"109\": 13, \"110\": 14, \"111\": 15, \"112\": 16, \"113\": 17, \"114\": 18, \"115\": 19, \"121\": 25, \"128\": 25, \"129\": 26, \"130\": 27, \"131\": 28, \"132\": 29, \"133\": 30, \"134\": 31, \"135\": 32, \"136\": 33, \"137\": 34, \"138\": 35, \"144\": 42, \"150\": 42, \"156\": 45, \"163\": 45, \"164\": 46, \"165\": 47, \"166\": 48, \"167\": 49, \"168\": 50, \"169\": 51, \"170\": 52, \"171\": 53, \"172\": 54, \"173\": 55, \"179\": 61, \"185\": 61, \"191\": 185}}\n__M_END_METADATA\n\"\"\"\n","sub_path":"portal/templates/__dmpcache__/app_base.htm.py","file_name":"app_base.htm.py","file_ext":"py","file_size_in_byte":7583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"608076464","text":"import urllib.request, urllib.parse\nimport json\n\nfhand = urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_171352.json')\ndata = fhand.read()\n\ndata = json.loads(data)\n\ncommentList = data['comments']\n\nsum = 0\nfor item in commentList:\n sum = sum + int(item['count'])\n\nprint(sum)","sub_path":"python/ch13_json_ex2.py","file_name":"ch13_json_ex2.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"185261335","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import logout, decorators\nfrom django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.contrib.auth.views import LoginView\nfrom django.views.generic import DetailView, ListView\nfrom django.urls import reverse\nfrom django.db.models import Q\n\nfrom accounts.models import UserProfile\nfrom .forms import RegistrationForm, LoginAuthForm, UserProfileUpdateForm, UserUpdateForm\n\n# Create your views here.\ndef follow(request):\n user_id = request.POST.get('userid')\n user_profile = get_object_or_404(UserProfile, user=user_id)\n curr_user = request.user\n\n if user_profile not in curr_user.userprofile.get_all_followings():\n curr_user.userprofile.following.add(user_profile)\n\n page_redirect_url = request.POST.get('pageredirect')\n if page_redirect_url:\n return redirect(page_redirect_url)\n\n blog_id = request.POST.get('blogid')\n if blog_id:\n curr_page = request.POST.get('page', 1)\n return redirect(reverse('home') + '?page={curr_page}#blog-{blog_id}'.format(curr_page=curr_page, blog_id=blog_id))\n\n return redirect(reverse('home'))\n\ndef unfollow(request):\n user_id = request.POST.get('userid')\n user_profile = get_object_or_404(UserProfile, user=user_id)\n curr_user = request.user\n\n if user_profile in curr_user.userprofile.get_all_followings():\n curr_user.userprofile.following.remove(user_profile)\n\n page_redirect_url = request.POST.get('pageredirect')\n if page_redirect_url:\n return redirect(page_redirect_url)\n\n blog_id = request.POST.get('blogid')\n if blog_id:\n curr_page = request.POST.get('page', 1)\n return redirect(reverse('home') + '?page={curr_page}#blog-{blog_id}'.format(curr_page=curr_page, blog_id=blog_id))\n\n return redirect(reverse('home'))\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nclass UserDetails(DetailView):\n template_name = \"accounts/profile.html\"\n model = User\n slug_field = \"username\"\n slug_url_kwarg = \"username\"\n\n \"\"\" Get context data. \"\"\"\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n object = context['object']\n blogs = object.blogpost_set.all().order_by('-timestamp')\n paginator = Paginator(blogs, 3)\n page = self.request.GET.get('page', None)\n paged_blogs = paginator.get_page(page)\n context['blogs'] = paged_blogs\n return context\n\n\n \"\"\" Get slug field.\n def get_slug_field(self, **kwargs):\n slug = super().get_slug_field(**kwargs)\n return slug\n \"\"\"\n\n\ndef register_user(request):\n\n if request.user.is_authenticated:\n return redirect('/')\n\n form = RegistrationForm(request.POST or None)\n\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n messages.success(request, \"You are registered successfully. Welcome to our community. Please Login.\")\n form = RegistrationForm(None)\n return redirect(reverse('user-login'))\n\n context = {\n \"form\" : form\n }\n return render(request, 'accounts/user_registration.html', context)\n\nclass AccountsLoginView(SuccessMessageMixin, LoginView):\n template_name = 'accounts/user_login.html'\n form_class = LoginAuthForm\n redirect_authenticated_user = True\n # success_message = \"You're welcome.\"\n\n def get_success_message(self, cleaned_data):\n username = cleaned_data['username']\n user = User.objects.get(username=username)\n return f\"{user.get_full_name()}, Welcome to InstaGo.\"\n\n def form_invalid(self, form):\n messages.error(self.request, 'Please insert a valid username or password.')\n return self.render_to_response(self.get_context_data(form=form))\n\n # def get_context_data(self, *args, **kwargs):\n # context = super(AccountsLoginView, self).get_context_data(*args, **kwargs)\n # return context\n\n\ndef logout_user(request):\n logout(request)\n messages.success(request, 'You are logged out successfully.')\n return redirect(reverse('user-login'))\n\n\n\n\"\"\"\nProfile updation goes here.\n=========================================\n\"\"\"\n@decorators.login_required(login_url='/accounts/login/')\ndef user_profile_update(request):\n user = request.user\n\n user_form = UserUpdateForm(\n request.POST or None,\n request.FILES or None,\n initial={\n 'first_name' : user.first_name,\n 'last_name' : user.last_name,\n }\n )\n profile_form = UserProfileUpdateForm(\n request.POST or None,\n request.FILES or None,\n initial={\n 'bio' : user.userprofile.bio,\n 'profile_image' : user.userprofile.profile_image,\n }\n )\n\n if request.method == 'POST':\n if user_form.is_valid() and profile_form.is_valid():\n user.first_name = user_form.cleaned_data['first_name']\n user.last_name = user_form.cleaned_data['last_name']\n user.save()\n\n profile = UserProfile.objects.get(user=user)\n profile.bio = profile_form.cleaned_data['bio']\n profile.profile_image = profile_form.cleaned_data['profile_image']\n profile.save()\n\n messages.success(request, 'Profile saved successfully.')\n return redirect(profile.get_absolute_url())\n\n else:\n messages.error(request, \"Invalid input.\")\n\n\n context = {\n \"profile_form\" : profile_form,\n \"user_form\" : user_form\n }\n return render(request, 'accounts/user_update.html' , context)\n\n\n\n\"\"\"\nProfile search goes here.\n=========================================\n\"\"\"\nclass UsersListView(ListView):\n model = User\n template_name = 'accounts/list.html'\n # paginate_by = 50\n\n def get_queryset(self, *args, **kwargs):\n obj_list = super().get_queryset(*args, **kwargs)\n user = self.request.user\n if user.is_authenticated:\n obj_list = obj_list.exclude(username=user.username).order_by('first_name')\n\n q = self.request.GET.get('q', None)\n if q is not None:\n lookup = (Q(username__icontains=q) |\n Q(first_name__startswith=q) | \n Q(last_name__startswith=q) |\n Q(email__icontains=q)\n )\n obj_list = obj_list.filter(lookup).distinct()\n return obj_list\n\n\n@decorators.login_required(login_url='/accounts/login/')\ndef edit_bio(request):\n user = request.user\n if request.method == 'POST':\n bio = request.POST.get('bio', None)\n if bio is not None:\n user_profile = user.userprofile\n user_profile.bio = bio\n user_profile.save()\n messages.success(request, 'Bio updated.')\n return redirect(reverse('user-profile', kwargs={'username': user.username}))\n\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"367452355","text":"from connect import db\n\n\nfor item in db.find():\n container = []\n for column in ['name', 'province', 'country']:\n value = item.get(column)\n if value:\n container.append(value)\n item['location'] = ', '.join(container)\n db.save(item)\n","sub_path":"parse_location.py","file_name":"parse_location.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"204149428","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom album.models import Category, Photo\nfrom django.views.generic import ListView, DetailView\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.urls import reverse_lazy\n\ndef base(request):\n return render(request, 'base.html')\n\ndef first_view( request ):\n return HttpResponse( 'Esta es mi primera vista!' )\n\ndef category(request):\n category_list = Category.objects.all()\n context = { 'object_list':category_list }\n return render( request, 'album/category_list.html', context )\n\ndef category_detail(request, category_id):\n category = Category.objects.get( id=category_id )\n context = { 'object':category }\n return render( request, 'album/category_detail.html', context )\n\nclass CategoryListView(ListView):\n model = Category\n\nclass CategoryDetailView(DetailView):\n model = Category\n\nclass PhotoListView(ListView):\n model = Photo\n\nclass PhotoDetailView(DetailView):\n model = Photo\n\nclass PhotoCreate(CreateView):\n model = Photo\n\nclass PhotoUpdate(UpdateView):\n model = Photo\n fields = ['category', 'title', 'photo', 'favorite', 'comment']\n\nclass PhotoDelete(DeleteView):\n model = Photo\n success_url = reverse_lazy('photo-list')\n","sub_path":"album/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"408668649","text":"from aws_cdk import core\nfrom aws_cdk import aws_lambda as _lambda\nfrom aws_cdk import aws_events as events\nfrom aws_cdk import aws_events_targets as targets\nfrom aws_cdk import aws_dynamodb as dynamodb\nfrom aws_cdk import aws_iam as iam\n\nTABLE_NAME = 'Scheduler'\nTAG_KEY = \"Schedule\"\nREGION = \"us-west-2\"\nLAMBDA_FUNC_PATH = 'aws_automated_scheduler/lambda'\n\n\nclass AutomatedSchedulerStack(core.Stack):\n \"\"\"\n Setup stack for automated scheduler\n \"\"\"\n\n def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n\n # Create a DynamoDB table with our requirements\n schedule_table = dynamodb.Table(\n self,\n \"AutomatedSchedulerTable\",\n table_name=TABLE_NAME,\n partition_key=dynamodb.Attribute(\n name=\"pk\",\n type=dynamodb.AttributeType.STRING\n ),\n sort_key=dynamodb.Attribute(\n name=\"sk\",\n type=dynamodb.AttributeType.STRING\n ),\n removal_policy=core.RemovalPolicy.DESTROY\n )\n\n # Create lambda resource using code from local disk\n lambda_handler = _lambda.Function(\n self, \"AutomatedScheduler\",\n code=_lambda.Code.from_asset(LAMBDA_FUNC_PATH),\n runtime=_lambda.Runtime.PYTHON_3_7,\n handler=\"automated_scheduler.event_handler\",\n memory_size=256,\n timeout=core.Duration.seconds(5)\n )\n\n schedule_table.grant_read_write_data(lambda_handler)\n\n lambda_handler.add_environment(\n key=\"scheduler_table\",\n value=TABLE_NAME\n )\n\n lambda_handler.add_environment(\n key=\"scheduler_tag\",\n value=TAG_KEY\n )\n\n lambda_handler.add_environment(\n key=\"scheduler_region\",\n value=REGION\n )\n\n ec2_read_only = iam.PolicyStatement(\n actions=[\n \"ec2:DescribeInstances\",\n \"ec2:DescribeTags\"\n ],\n effect=iam.Effect.ALLOW,\n resources=[\n \"*\"\n ]\n )\n\n s3_read_only = iam.PolicyStatement(\n actions=[\n \"s3:GetObject\",\n ],\n effect=iam.Effect.ALLOW,\n resources=[\n \"*\"\n ]\n )\n\n lambda_handler.add_to_role_policy(ec2_read_only)\n lambda_handler.add_to_role_policy(s3_read_only)\n\n # rule = events.Rule(\n # self,\n # \"AutomatedSchedulerRule\",\n # schedule=events.Schedule.expression(\"cron(0/1 * * * ? *)\")\n # )\n\n # Add lambda function as target of event rule\n # rule.add_target(targets.LambdaFunction(lambda_handler))\n","sub_path":"aws_automated_scheduler/automated_scheduler_stack.py","file_name":"automated_scheduler_stack.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"606114321","text":"#\n# Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\"\"\"Internal helper to retrieve target information from the online database.\"\"\"\n\nimport pathlib\nfrom http import HTTPStatus\nimport json\nfrom json.decoder import JSONDecodeError\nimport logging\nfrom typing import List, Optional, Dict, Any\n\nimport requests\n\nfrom mbed_tools.targets._internal.exceptions import ResponseJSONError, BoardAPIError\n\nfrom mbed_tools.targets.env import env\n\n\nINTERNAL_PACKAGE_DIR = pathlib.Path(__file__).parent\nSNAPSHOT_FILENAME = \"board_database_snapshot.json\"\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_board_database_path() -> pathlib.Path:\n \"\"\"Return the path to the offline board database.\"\"\"\n return pathlib.Path(INTERNAL_PACKAGE_DIR, \"data\", SNAPSHOT_FILENAME)\n\n\n_BOARD_API = \"https://os.mbed.com/api/v4/targets\"\n\n\ndef get_offline_board_data() -> Any:\n \"\"\"Loads board data from JSON stored in offline snapshot.\n\n Returns:\n The board database as retrieved from the local database snapshot.\n\n Raises:\n ResponseJSONError: error decoding the local database JSON.\n \"\"\"\n boards_snapshot_path = get_board_database_path()\n try:\n return json.loads(boards_snapshot_path.read_text())\n except JSONDecodeError as json_err:\n raise ResponseJSONError(f\"Invalid JSON received from '{boards_snapshot_path}'.\") from json_err\n\n\ndef get_online_board_data() -> List[dict]:\n \"\"\"Retrieves board data from the online API.\n\n Returns:\n The board database as retrieved from the boards API\n\n Raises:\n ResponseJSONError: error decoding the response JSON.\n BoardAPIError: error retrieving data from the board API.\n \"\"\"\n board_data: List[dict] = [{}]\n response = _get_request()\n if response.status_code != HTTPStatus.OK:\n warning_msg = _response_error_code_to_str(response)\n logger.warning(warning_msg)\n logger.debug(f\"Response received from API:\\n{response.text}\")\n raise BoardAPIError(warning_msg)\n\n try:\n json_data = response.json()\n except JSONDecodeError as json_err:\n warning_msg = f\"Invalid JSON received from '{_BOARD_API}'.\"\n logger.warning(warning_msg)\n logger.debug(f\"Response received from API:\\n{response.text}\")\n raise ResponseJSONError(warning_msg) from json_err\n\n try:\n board_data = json_data[\"data\"]\n except KeyError as key_err:\n warning_msg = f\"JSON received from '{_BOARD_API}' is missing the 'data' field.\"\n logger.warning(warning_msg)\n keys_found = \", \".join(json_data.keys())\n logger.debug(f\"Fields found in JSON Response: {keys_found}\")\n raise ResponseJSONError(warning_msg) from key_err\n\n return board_data\n\n\ndef _response_error_code_to_str(response: requests.Response) -> str:\n if response.status_code == HTTPStatus.UNAUTHORIZED:\n return (\n f\"Authentication failed for '{_BOARD_API}'. Please check that the environment variable \"\n f\"'MBED_API_AUTH_TOKEN' is correctly configured with a private access token.\"\n )\n else:\n return f\"An HTTP {response.status_code} was received from '{_BOARD_API}'.\"\n\n\ndef _get_request() -> requests.Response:\n \"\"\"Make a GET request to the API, ensuring the correct headers are set.\"\"\"\n header: Optional[Dict[str, str]] = None\n mbed_api_auth_token = env.MBED_API_AUTH_TOKEN\n if mbed_api_auth_token:\n header = {\"Authorization\": f\"Bearer {mbed_api_auth_token}\"}\n\n try:\n return requests.get(_BOARD_API, headers=header)\n except requests.exceptions.ConnectionError as connection_error:\n if isinstance(connection_error, requests.exceptions.SSLError):\n logger.warning(\"Unable to verify an SSL certificate with requests.\")\n elif isinstance(connection_error, requests.exceptions.ProxyError):\n logger.warning(\"Failed to connect to proxy. Please check your proxy configuration.\")\n\n logger.warning(\"Unable to connect to the online database. Please check your internet connection.\")\n raise BoardAPIError(\"Failed to connect to the online database.\") from connection_error\n","sub_path":"src/mbed_tools/targets/_internal/board_database.py","file_name":"board_database.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"597316433","text":"#-*- coding: utf-8 -*-\n'''\n聚类离散化,最后的result的格式为:\n 1 2 3 4\nA 0 0.178698 0.257724 0.351843\nAn 240 356.000000 281.000000 53.000000\n即(0, 0.178698]有240个,(0.178698, 0.257724]有356个,依此类推。\n'''\nfrom __future__ import print_function\nimport pandas as pd\nfrom sklearn.cluster import KMeans #导入K均值聚类算法\n\ndatafile = '../data/data.xls' #待聚类的数据文件\nprocessedfile = '../tmp/data_processed.xls' #数据处理后文件\n\"\"\"\noutfile = '../tmp/data_discret.xls' #离散化后的数据\n\ndata = pd.read_excel(datafile)\nresult = pd.read_excel(processedfile)\n\ndf = data[['肝气郁结证型系数', '热毒蕴结证型系数', '冲任失调证型系数', '气血两虚证型系数', '脾胃虚弱证型系数', '肝肾阴虚证型系数']].copy()\ndf.columns = ['A','B','C','D','E','F']\n\ndf.loc[(df.A>result.iloc[0,0])&(df.Aresult.iloc[0,1])&(df.Aresult.iloc[0,2])&(df.Aresult.iloc[0,3]),'Ax']= 'A4'\n\ndf.loc[(df.B>result.iloc[2,0])&(df.Bresult.iloc[2,1])&(df.Bresult.iloc[2,2])&(df.Bresult.iloc[2,3]),'Bx']= 'B4'\n\ndf.loc[(df.C>result.iloc[4,0])&(df.Cresult.iloc[4,1])&(df.Cresult.iloc[4,2])&(df.Cresult.iloc[4,3]),'Cx']= 'C4'\n\ndf.loc[(df.D>result.iloc[6,0])&(df.Dresult.iloc[6,1])&(df.Dresult.iloc[6,2])&(df.Dresult.iloc[6,3]),'Dx']= 'D4'\n\ndf.loc[(df.E>result.iloc[8,0])&(df.Eresult.iloc[8,1])&(df.Eresult.iloc[8,2])&(df.Eresult.iloc[8,3]),'Ex']= 'E4'\n\ndf.loc[(df.F>result.iloc[10,0])&(df.Fresult.iloc[10,1])&(df.Fresult.iloc[10,2])&(df.Fresult.iloc[10,3]),'Fx']= 'F4'\n\n\n\ndf.to_excel(outfile)\n\n\"\"\"\ntypelabel ={u'肝气郁结证型系数':'A', u'热毒蕴结证型系数':'B', u'冲任失调证型系数':'C', u'气血两虚证型系数':'D', u'脾胃虚弱证型系数':'E', u'肝肾阴虚证型系数':'F'}\nk = 4 #需要进行的聚类类别数\n\n#读取数据并进行聚类分析\ndata = pd.read_excel(datafile) #读取数据\nkeys = list(typelabel.keys())\nresult = pd.DataFrame()\n\nif __name__ == '__main__': #判断是否主窗口运行,这句代码的作用比较神奇,有兴趣了解的读取请自行搜索相关材料。\n for i in range(len(keys)):\n #调用k-means算法,进行聚类离散化\n print(u'正在进行“%s”的聚类...' % keys[i])\n kmodel = KMeans(n_clusters = k, n_jobs = 1) #n_jobs是并行数,一般等于CPU数较好\n kmodel.fit(data[[keys[i]]].as_matrix()) #训练模型\n \n r1 = pd.DataFrame(kmodel.cluster_centers_, columns = [typelabel[keys[i]]]) #聚类中心\n #print(r1.columns,r1.values)\n r2 = pd.Series(kmodel.labels_).value_counts() #分类统计\n r2 = pd.DataFrame(r2, columns = [typelabel[keys[i]]+'n']) #转为DataFrame,记录各个类别的数目\n #print(r2.columns,r2.values)\n #r = pd.concat([r1, r2], axis = 1).sort(typelabel[keys[i]]) #匹配聚类中心和类别数目\n r = pd.concat([r1, r2], axis = 1).sort_values(typelabel[keys[i]])\n #print(r.columns,r.values)\n r.index = [1, 2, 3, 4]\n \n #r[typelabel[keys[i]]] = pd.rolling_mean(r[typelabel[keys[i]]], 2) #rolling_mean()用来计算相邻2列的均值,以此作为边界点。\n r[typelabel[keys[i]]] = r[typelabel[keys[i]]].rolling(2).mean()\n r[typelabel[keys[i]]][1] = 0.0 #这两句代码将原来的聚类中心改为边界点。 \n result = result.append(r.T)\n\n #result = result.sort() #以Index排序,即以A,B,C,D,E,F顺序排\n result = result.sort_values(by = list(result.index),axis=1) #以Index排序,即以A,B,C,D,E,F顺序排\n result.to_excel(processedfile)\n\n\n ","sub_path":"中医证型关联规则挖掘/code/discretization.py","file_name":"discretization.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"467342812","text":"# Written by Laurenz Mädje\r\n\r\nimport random\r\nimport overlay\r\nimport var\r\n\r\n# Alle Karten mit Preisen und Bildquellen\r\nCARDS = dict(Keller=[2, 'res/karten/keller.png'], Kapelle=[2, 'res/karten/kapelle.png'],\r\n Burggraben=[2, 'res/karten/burggraben.png'], Werkstatt=[3, 'res/karten/werkstatt.png'],\r\n Holzfäller=[3, 'res/karten/holzfaeller.png'], Kanzler=[3, 'res/karten/kanzler.png'],\r\n Dorf=[3, 'res/karten/dorf.png'], Festmahl=[4, 'res/karten/festmahl.png'],\r\n Spion=[4, 'res/karten/spion.png'], Bürokrat=[4, 'res/karten/buerokrat.png'],\r\n Dieb=[4, 'res/karten/dieb.png'], Miliz=[4, 'res/karten/miliz.png'],\r\n Schmiede=[4, 'res/karten/schmiede.png'], Umbau=[4, 'res/karten/umbau.png'],\r\n Geldverleiher=[4, 'res/karten/geldverleiher.png'], Thronsaal=[4, 'res/karten/thronsaal.png'],\r\n Markt=[5, 'res/karten/markt.png'], Mine=[5, 'res/karten/mine.png'],\r\n Jahrmarkt=[5, 'res/karten/jahrmarkt.png'], Laboratorium=[5, 'res/karten/laboratorium.png'],\r\n Bibliothek=[5, 'res/karten/bibliothek.png'], Ratsversammlung=[5, 'res/karten/ratsversammlung.png'],\r\n Hexe=[5, 'res/karten/hexe.png'], Abenteurer=[6, 'res/karten/abenteurer.png'],\r\n Anwesen=[2, 'res/karten/anwesen.png'], Herzogtum=[5, 'res/karten/herzogtum.png'],\r\n Provinz=[8, 'res/karten/provinz.png'], Fluch=[0, 'res/karten/fluch.png'],\r\n Kupfer=[0, 'res/karten/kupfer.png'], Silber=[0, 'res/karten/silber.png'], Gold=[0, 'res/karten/gold.png'],\r\n Garten=[4, 'res/karten/garten.png'])\r\n\r\n# Alle Karten in 4 Sets aufgeteilt\r\nACTION_CARDS = {'Keller', 'Kapelle', 'Burggraben', 'Werkstatt', 'Holzfäller', 'Kanzler', 'Dorf',\r\n 'Festmahl', 'Spion', 'Bürokrat', 'Dieb', 'Miliz', 'Schmiede', 'Umbau', 'Geldverleiher', 'Thronsaal',\r\n 'Markt', 'Mine', 'Jahrmarkt', 'Laboratorium', 'Bibliothek', 'Ratsversammlung', 'Hexe', 'Abenteurer'}\r\nPOINT_CARDS = {'Anwesen', 'Herzogtum', 'Provinz', 'Fluch'}\r\nMONEY_CARDS = {'Kupfer', 'Silber', 'Gold'}\r\nOTHER_CARDS = {'Garten'}\r\n\r\nstacks = None\r\nstacklist = None\r\n\r\ndef createStacklist():\r\n global stacklist\r\n stacklist = sorted(list(random.sample(ACTION_CARDS | OTHER_CARDS, 10)), key=lambda card: CARDS[card]) + list(MONEY_CARDS) + list(POINT_CARDS)\r\n\r\ndef createStacks():\r\n global stacks\r\n\r\n stacks = dict.fromkeys(stacklist, 10)\r\n stacks['Anwesen'], stacks['Herzogtum'], stacks['Provinz'], stacks['Fluch'] = 8, 8, 8, 8\r\n stacks['Kupfer'], stacks['Silber'], stacks['Gold'] = 30, 30, 30\r\n if 'Garten' in stacklist: stacks['Garten'] = 8\r\n\r\ndef gameOver():\r\n if stacks['Provinz'] == 0:\r\n return True\r\n counter = 0\r\n for key in stacks:\r\n if stacks[key] == 0:\r\n counter += 1\r\n if counter >= 3:\r\n return True\r\n return False\r\n\r\n\r\nclass Card:\r\n\r\n def __init__(self, name):\r\n\r\n # Member variables\r\n self.name = name\r\n self.path = CARDS[name][1]\r\n self.cost = CARDS[name][0]\r\n\r\n def play(self):\r\n\r\n if var.myplayer.playCard(self):\r\n var.state = 'playing'\r\n self.doEffect()\r\n var.connect.send('I_PLAY:' + self.name)\r\n\r\n def doEffect(self):\r\n\r\n if self.name in ['Abenteurer', 'Burggraben', 'Holzfäller','Dorf', 'Bürokrat', 'Geldverleiher', 'Miliz', 'Schmiede', 'Hexe', 'Miliz', 'Jahrmarkt', 'Laboratorium', 'Markt', 'Ratsversammlung']:\r\n self.do(None)\r\n\r\n elif self.name == 'Kapelle':\r\n var.overlay.infobox.setText('Wähle die Karten, die du entsorgen möchtest!')\r\n var.interface = overlay.HandSelector('multiple', 'Entsorgen', self.do)\r\n\r\n elif self.name == 'Keller':\r\n var.overlay.infobox.setText('Wähle die Karten, die du austauschen möchtest!')\r\n var.interface = overlay.HandSelector('multiple', 'Ablegen', self.do)\r\n\r\n elif self.name == 'Kanzler':\r\n var.interface = overlay.TwoOptionsSelector('Nachziehstapel ablegen?', ('Ja', 'Nein'), self.do)\r\n\r\n elif self.name == 'Werkstatt':\r\n var.overlay.infobox.setText('Wähle die Karte, die du nehmen möchtest!')\r\n var.interface = overlay.BuySelector('Nehmen', self.do)\r\n\r\n elif self.name == 'Festmahl':\r\n var.overlay.infobox.setText('Wähle die Karte, die du nehmen möchtest!')\r\n var.interface = overlay.BuySelector('Nehmen', self.do)\r\n\r\n elif self.name == 'Umbau':\r\n args = []\r\n\r\n def step2(arg):\r\n args.append(arg)\r\n self.do(args)\r\n\r\n def step1(arg):\r\n var.overlay.infobox.setText('Wähle die Karte, die du nehmen möchtest!')\r\n var.interface = overlay.BuySelector('Nehmen', step2)\r\n args.append(arg)\r\n\r\n var.overlay.infobox.setText('Wähle die Karte, die du entsorgen möchtest!')\r\n var.interface = overlay.HandSelector('single', 'Entsorgen', step1)\r\n\r\n elif self.name == 'Bibliothek':\r\n card = None\r\n\r\n def trueconfirm():\r\n confirm(True)\r\n\r\n def confirm(arg):\r\n\r\n if arg:\r\n var.myplayer.hand.append(card)\r\n else:\r\n var.myplayer.ablage.append(card)\r\n\r\n if len(var.myplayer.hand) < 7:\r\n var.overlay.cardShower.hide()\r\n nextCard()\r\n else:\r\n self.do(None)\r\n var.overlay.cardShower.hide()\r\n\r\n def nextCard():\r\n nonlocal card\r\n if len(var.myplayer.nachzieh) <= 0:\r\n var.myplayer.reshuffle()\r\n\r\n card = var.myplayer.nachzieh.pop(0)\r\n\r\n var.overlay.cardShower.setShow(card, 'Aufgedeckt:')\r\n var.overlay.cardShower.showUntimed()\r\n\r\n if card.name in ACTION_CARDS:\r\n var.interface = overlay.TwoOptionsSelector('Behalten?', ('Ja', 'Nein'), confirm, pos=(1070, 320))\r\n else:\r\n overlay.Waitor(1, trueconfirm)\r\n\r\n nextCard()\r\n\r\n elif self.name == 'Mine':\r\n args = []\r\n\r\n def step2(arg):\r\n args.append(arg)\r\n self.do(args)\r\n\r\n def step1(arg):\r\n var.overlay.infobox.setText('Wähle die Karte, die du nehmen möchtest!')\r\n var.interface = overlay.BuySelector('Nehmen', step2)\r\n args.append(arg)\r\n\r\n var.overlay.infobox.setText('Wähle die Karte, die du entsorgen möchtest!')\r\n var.interface = overlay.HandSelector('single', 'Entsorgen', step1)\r\n\r\n\r\n\r\n\r\n def do(self, args):\r\n if var.myplayer.doEffect(self, args):\r\n var.overlay.handpos = []\r\n if var.myplayer.actions > 0:\r\n var.interface = overlay.HandSelector('single', 'Spielen', var.overlay.playPressed)\r\n var.overlay.infobox.setText('Wähle eine Karte. newline Drücke Spielen, um sie auszuspielen! newline Drücke Weiter, um in die Kaufphase zu gelangen!')\r\n else:\r\n var.interface = None\r\n var.overlay.infobox.setText('Drücke Weiter, um in die Kaufphase zu gelangen!')\r\n var.state = 'action'\r\n else:\r\n var.overlay.handpos = []\r\n self.doEffect()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"cards.py","file_name":"cards.py","file_ext":"py","file_size_in_byte":7474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"404003098","text":"import requests\ntopic = \"eu referendum\"\nkey = \"4d547cbd-99e2-4b00-a40e-987c67c252b8\"\nfrom_date = \"2016-02-19\"\nto_date =\"2016-02-21\"\nurl = \"http://content.guardianapis.com/search?q=\" + topic + \"&\" + \"from-date=\" + from_date + \"&\" + \\\n \"to-date=\" + \\\n to_date \\\n + \"&use-date=published&api-key=\" + key\nimport json\nimport pprint\na = requests.get(url)\nb = a.json()\n\npprint.pprint([i[\"webTitle\"] for i in b[\"response\"][\"results\"]])\n\n\n\n\n\n","sub_path":"server/src/Scripts/GuardianAPI/Guardian.py","file_name":"Guardian.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"584085037","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 22 12:17:54 2018\n\n@author: craig\n\"\"\"\n\nimport unittest\nfrom plane import Plane\nfrom vector import Vector\n\nclass PlaneTestCase(unittest.TestCase):\n def test_is_parallel_to(self):\n ## Two parallel planes\n p1 = Plane(Vector((1, 1, 1)), 0)\n p2 = Plane(Vector((1, 1, 1)), 1)\n self.assertTrue(p1.is_parallel_to(p2))\n self.assertTrue(p2.is_parallel_to(p1))\n \n ## Two intersecting planes\n p3 = Plane(Vector((1, -1, -1)), 0)\n self.assertFalse(p1.is_parallel_to(p3))\n self.assertFalse(p3.is_parallel_to(p1))\n \n ## One factor = 0\n p4 = Plane(Vector((0, 1, 1)), 0)\n p5 = Plane(Vector((0, 1, 1)), 1)\n self.assertTrue(p4.is_parallel_to(p5))\n self.assertFalse(p4.is_parallel_to(p1))\n \n ## Two factors = 0\n p6 = Plane(Vector((0, 0, 1)), 0)\n p7 = Plane(Vector((0, 0, 1)), 1)\n self.assertTrue(p6.is_parallel_to(p7))\n self.assertFalse(p6.is_parallel_to(p1))\n \n ## Two planes with same definition\n p8 = Plane(Vector((1, 1, 1)), 0)\n self.assertTrue(p1.is_parallel_to(p8))\n \n ## Same plane with two definitions\n p9 = Plane(Vector((2, 2, 2)), 2)\n self.assertTrue(p2.is_parallel_to(p9))\n \n def test__eq__(self):\n ## Two planes with same definition\n p1 = Plane(Vector((1, 1, 1)), 1)\n p2 = Plane(Vector((1, 1, 1)), 1)\n self.assertTrue(p1 == p2)\n \n ## Same plane with two defnitions\n p3 = Plane(Vector((2, 2, 2)), 2)\n self.assertTrue(p1 == p3)\n \n ## Two parallel planes\n p4 = Plane(Vector((1, 1, 1)), 0)\n self.assertFalse(p1 == p4)\n \n ## Two intersecting planes\n p5 = Plane(Vector((1, -1, 1)), 0)\n self.assertFalse(p1 == p5)\n \n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"plane_test.py","file_name":"plane_test.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"90304293","text":"from data_classes import Rocket, State\nimport numpy as np\n\nclass Simulator:\n def __init__(self, rocket = None, state = None, dt = 1, g = -9.81):\n self.dt = dt\n self.rocket = rocket if rocket else Rocket()\n self.s = state if state else State(fuel_level=self.rocket.start_fuel_mass)\n self.g = g\n\n # rewards\n self.v_penalty = -1\n self.x_penalty = -1\n self.angle_penalty = -10 # its in radians...\n\n def get_state(self):\n return self.s\n\n def get_state_arr(self):\n return [self.s.px, self.s.py, self.s.vx, self.s.vyself.s.v_angular, self.s.orientation_angle, self.s.fuel_level]\n\n def final_state_reached(self):\n return self.s.py <=0\n\n def take_action(self, gimble_angle, thrust_proportion, fin_angle):\n CoM, MoI = self.get_mass_vars()\n fin_forward, fin_ang_acc = self.get_fin_forces(fin_angle, CoM, MoI)\n\n # Check if we have enough fuel to burn the requested about, and calculate the amount of resulting thrust\n if self.s.fuel_level > 0:\n thrust_forward, thrust_ang_acc = self.get_thrust_forces(thrust_proportion, gimble_angle, CoM, MoI)\n fuel_burn = thrust_proportion * self.rocket.burn_rate * self.dt\n if fuel_burn > self.s.fuel_level:\n prop_burn = self.s.fuel_level / fuel_burn\n thrust_forward *= prop_burn\n thrust_ang_acc *= prop_burn\n self.s.fuel_level = 0\n else:\n self.s.fuel_level -= fuel_burn\n else:\n thrust_forward, thrust_ang_acc = 0, 0\n\n total_thrust_forward = thrust_forward + fin_forward\n total_ang_acc = thrust_ang_acc + fin_ang_acc\n self.update_p_and_v(total_thrust_forward, total_ang_acc)\n\n def get_mass_vars(self):\n # Calculate mass, center of mass, and moment of inertia\n mass = self.s.fuel_level + self.rocket.dry_mass\n fuel_height = (self.s.fuel_level / self.rocket.start_fuel_mass) * self.rocket.fuel_height_prop * self.rocket.height\n fuel_CoM = fuel_height * .5 * self.s.fuel_level\n total_CoM = (fuel_CoM + self.rocket.rocket_CoM) / mass\n fuel_MoI = self.get_MoI(self.s.fuel_level, total_CoM, fuel_height)\n rocket_MoI = self.get_MoI(self.rocket.dry_mass, total_CoM, self.rocket.height)\n total_MoI = fuel_MoI + rocket_MoI\n\n return total_CoM, total_MoI\n\n def get_MoI(self, mass, c, h):\n if h==0: return 0\n return mass / (3 * h) * (h ** 3 + 3 * h * c ** 2 - 3 * h ** 2 * c)\n\n def get_fin_forces(self, fin_angle, CoM, MoI):\n # TODO: This will depend on angular velocity also\n v_angle = np.arctan2(self.s.vx, self.s.vy)\n fin_v_angle = self.s.orientation_angle + fin_angle - v_angle\n\n f_fin = -1*(np.cos(fin_v_angle) * self.total_v()) ** 2 * self.rocket.fin_drag\n fin_forward = np.abs(np.cos(fin_angle)) * f_fin\n fin_lever_arm = self.rocket.height - self.rocket.fin_offset - CoM\n fin_torque = np.sin(fin_angle) * f_fin * fin_lever_arm\n fin_ang_acc = fin_torque / MoI\n\n return fin_forward, fin_ang_acc\n\n def total_v(self):\n return np.sqrt(self.s.vx ** 2 + self.s.vy ** 2)\n\n def get_thrust_forces(self, thrust_proportion, gimble_angle, CoM, MoI):\n thrust = self.rocket.full_thrust * thrust_proportion\n thrust_forward = np.cos(gimble_angle) * thrust\n thrust_torque = np.sin(gimble_angle) * thrust * CoM\n thrust_ang_acc = thrust_torque / MoI\n\n return thrust_forward, thrust_ang_acc\n\n def update_p_and_v(self, thrust_forward, ang_acc):\n # TODO: handle end case, where the ground is hit. Only some of the acceleration will happen before impact.\n # TODO: angular velocity will also affect this, as over dt the rotation will cause a curve in thrust\n mass = self.s.fuel_level + self.rocket.dry_mass\n total_thrust_x = np.cos(self.s.orientation_angle) * thrust_forward\n total_thrust_y = np.sin(self.s.orientation_angle) * thrust_forward\n\n d_v_angular = ang_acc * self.dt\n d_vx = total_thrust_x / mass * self.dt\n d_vy = (self.g + total_thrust_y / mass) * self.dt\n\n # Assuming that changes in vx, vy, and v_angular happen smoothly, the average vs over dt will be halfway between the old v and the new v\n self.s.orientation_angle += (self.s.v_angular + d_v_angular / 2) * self.dt\n self.s.px += (self.s.vx + d_vx / 2) * self.dt\n self.s.py += (self.s.vy + d_vy / 2) * self.dt\n\n self.s.v_angular += d_v_angular\n self.s.vx += d_vx\n self.s.vy += d_vy\n\n def get_reward(self):\n return self.v_penalty*self.total_v() \\\n + self.x_penalty*self.s.px \\\n + self.angle_penalty*np.abs(self.s.orientation_angle)","sub_path":"rocket_sim.py","file_name":"rocket_sim.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"453804125","text":"\n\"\"\"\n@author: Milena Bajic (DTU Compute)\n\"\"\"\nimport sys,os, glob, pickle, time\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tsfel\nfrom mlxtend.feature_selection import SequentialFeatureSelector\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import make_scorer, confusion_matrix\nfrom sklearn.metrics import classification_report, plot_confusion_matrix\nfrom mlxtend.plotting import plot_sequential_feature_selection as plot_sfs\nimport scipy.stats\nfrom scipy import stats, interpolate\nfrom numpy.random import choice\nfrom sklearn.model_selection import TimeSeriesSplit\nfrom matplotlib.ticker import (MultipleLocator, AutoMinorLocator)\nfrom sklearn.model_selection import TimeSeriesSplit, GridSearchCV\nimport seaborn as sns\nfrom sklearn.svm import SVR, SVC\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\nfrom sklearn.neural_network import *\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.tree import export_graphviz\nfrom sklearn import tree\nfrom sklearn import linear_model\nfrom sklearn.dummy import DummyRegressor, DummyClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.pipeline import Pipeline\nfrom scipy.signal import find_peaks, argrelmin, argrelextrema, find_peaks_cwt\nfrom mlxtend.evaluate import PredefinedHoldoutSplit\n\ndef sort2(f):\n try:\n num = int(f.split('/')[-1].split('_')[4] )\n except:\n if '_fulltrip.png' in f:\n num = -10\n elif '_clusters.png' in f:\n num = -9\n elif '_removed_outliers.png' in f:\n num = -8\n elif '_fulltrip_minima.png' in f:\n num = -7\n else:\n num = -1\n return num\n\ndef sort3(f):\n if 'mapmatched_map_printout.png' in f:\n num = -10\n elif'interpolated_300th_map_printout.png' in f:\n num = -9\n else:\n num = -1\n return num\n\ndef polynomial_model(degree=10):\n polynomial_features = PolynomialFeatures(degree=degree,\n include_bias=False)\n linear_regression = LinearRegression(normalize=True) #normalize=True normalize data\n pipeline = Pipeline([(\"polynomial_features\", polynomial_features),#Add polynomial features\n (\"linear_regression\", linear_regression)])\n return pipeline\n \n \ndef plot_fs(nf, res, var_label = 'MSE',title='', size=2,\n out_dir = '.', save_plot=True, filename='plot-fs'): \n if size==2:\n plt.rcParams.update({'font.size': 6})\n figsize=[2.5,2]\n dpi= 1000\n ms = 3 \n ls = 7\n if size==3:\n plt.rcParams.update({'font.size': 7})\n figsize=[4,3]\n dpi= 1000\n ms = 6\n ls = 9\n\n #var_min = true.min() - 0.3*true.min()\n #var_max = true.max() + 0.35*true.max()\n\n #var_min = 0.3\n #var_max = 3.5\n \n plt.figure(figsize=figsize, dpi=dpi)\n #plt.plot(true, m*true + b, c='blue', label='Best fit') \n plt.scatter(nf, res, marker='o',s=ms, facecolors='b', edgecolors='b', label='MSE')\n plt.plot(nf, res, linewidth=1)\n plt.ylabel('{0}'.format(var_label), fontsize=ls)\n plt.xlabel('Number of features', fontsize=ls)\n #plt.xlim([var_min, var_max])\n #plt.ylim([var_min, var_max])\n #plt.title(title)\n ax = plt.gca()\n ax.yaxis.set_major_formatter('{x:.2e}')\n ax.xaxis.set_major_formatter('{x:.0f}')\n # For the minor ticks, use no labels; default NullFormatter.\n ax.xaxis.set_minor_locator(AutoMinorLocator())\n #ax.yaxis.set_minor_locator(AutoMinorLocator())\n plt.tight_layout()\n \n if save_plot:\n out_file_path = filename\n plt.savefig(out_file_path, dpi=dpi, bbox_inches = \"tight\")\n plt.savefig(out_file_path.replace('.png','.eps'),format='eps',dpi=dpi, bbox_inches = \"tight\")\n plt.savefig(out_file_path.replace('.png','.pdf'),dpi=dpi, bbox_inches = \"tight\")\n print('file saved as: ',out_file_path)\n \n return\ndef format_col(x):\n if x=='R2':\n return r'$\\textbf{R^2}$'\n else:\n return r'\\textbf{' + x + '}'\n \ndef get_flattened(row, vars):\n row_data = []\n for var in vars:\n row_data.append(pd.Series(row[var]))\n df = pd.concat(row_data, axis = 1) \n return df\n \n \ndef set_class(y_cont, bins = [0,2,5,50]):\n labels = list(range(len(bins)-1))\n y_cat = pd.cut(y_cont, bins, labels=labels).astype(np.int8)\n print(y_cat.value_counts())\n return y_cat\n\n\ndef get_nan_cols(df, nan_percent=0.01, exclude_cols = ['IRI_mean_end']):\n # return cols to remove\n threshold = len(df.index) * nan_percent \n res = [c for c in df.drop(exclude_cols,axis=1).columns if sum(df[c].isnull()) >= threshold] \n return res\n\ndef clean_nans(df, col_nan_percent = 0.01, exclude_cols = ['IRI_mean_end']):\n cols_to_remove = get_nan_cols(df, nan_percent=col_nan_percent, exclude_cols = exclude_cols) \n \n # Replace infinities with nans \n df.replace([np.inf, -np.inf], np.nan, inplace=True)\n \n # Drop\n df.drop(columns=cols_to_remove,axis=1, inplace=True) # remove features with more than 1% nans\n df.dropna(axis=0, inplace=True) # drop rows with at least 1 nan\n \n # Reset index\n df.reset_index(inplace=True, drop = True)\n return \n \ndef compute_features_per_series(seq, cfg):\n try:\n t = tsfel.time_series_features_extractor(cfg, seq, window_size=len(seq),overlap=0, fs=None)\n except:\n t = None\n return t\n\n\ndef extract_col(tsfel_obj, col):\n if col in list(tsfel_obj.columns):\n t = tsfel_obj[col] \n else:\n t = pd.Series() # not None!!\n return t\n\n \ndef feature_extraction(df, target_name, out_dir, keep_cols = [], feats = ['GM.obd.spd_veh.value','GM.acc.xyz.x', 'GM.acc.xyz.y', 'GM.acc.xyz.z'], \n file_suff='', recreate=False, write_out_file = True, feats_list_to_extract = None, predict_mode = False, sel_features = None):\n\n # Output filename\n out_filename = '{0}/{1}'.format(out_dir, file_suff)\n\n # Load if it exists\n if not recreate and os.path.exists(out_filename):\n with open(out_filename, 'rb') as handle:\n df = pickle.load(handle)\n print('File succesfully loaded.')\n \n # Compute features \n else:\n \n # Remove those\n stat_to_rem = ['Histogram', 'ECDF', 'ECDF Percentile Count','ECDF Percentile']\n \n # Set cfg\n cfg = tsfel.get_features_by_domain() \n \n # Delete spectral\n del cfg['spectral']\n \n # Set stat\n for key in stat_to_rem:\n del cfg['statistical'][key]\n \n \n # Compute features\n if not predict_mode and target_name not in keep_cols:\n keep_cols.append(target_name)\n \n for var in feats:\n print('===== Computing features for: {0} ======'.format(var))\n \n # Additional features: maxmin\n df[var+'-0_Maxmin diff'] = df[var].apply(lambda seq: seq.max()-seq.min())\n keep_cols.append(var+'-0_Maxmin diff')\n \n # ECDF percentils\n for i, p in enumerate([0.05, 0.10, 0.20, 0.80]):\n perc_col_name = var+'-0_ECDF Percentile '+str(p)\n df[perc_col_name] = df[var].apply(lambda seq: tsfel.ecdf_percentile(seq, percentile=[p]) if seq.shape[0]>20 else None)\n keep_cols.append(perc_col_name)\n \n # Compute default tsfel features\n colname_tsfel = var+'_fe'\n df[colname_tsfel] = df[var].apply(lambda seq: compute_features_per_series(seq, cfg) )\n keep_cols.append(colname_tsfel)\n \n # Drop rows where tsfel is not computed \n df = df[keep_cols] #here\n #df.dropna(axis=0, inplace=True)\n df.reset_index(inplace=True, drop = True)\n\n # Save \n if write_out_file:\n df.to_pickle(out_filename) \n print('Wrote to ',out_filename)\n \n return df, out_filename\n\n\n\ndef extract_inner_df(df, feats = ['GM.obd.spd_veh.value','GM.acc.xyz.z'], remove_vars = ['GM.acc.xyz.x', 'GM.acc.xyz.y'], do_clean_nans = False):\n \n # Extract to nice structure\n for var in feats: \n \n var_tsfel = var + '_fe'\n # Check if present\n if var_tsfel not in df.columns:\n print('Feature {0} not present in df'.format(var))\n continue\n \n # Get feature names for this var\n #try:\n col_names = df[var_tsfel].iloc[0].columns\n print('Will extract: {0}\\n'.format(col_names.to_list()))\n time.sleep(2)\n #except:\n # print('Extraction failed')\n # time.sleep(3)\n # return None, None\n\n # Extract\n for col in col_names:\n print('Extracting: ',col)\n df[var+'-'+col] = df[var_tsfel].apply(lambda tsfel: extract_col(tsfel, col))\n df[var+'-'+col].astype(np.float16)\n \n # Remove tsfel and additional variables\n cols_to_rem = [col for col in df.columns if col.endswith('_fe')] # all tsfel\n for var in remove_vars:\n add_cols_rem = [col for col in df.columns if var in col and var not in cols_to_rem]\n cols_to_rem.extend(add_cols_rem)\n df.drop(cols_to_rem,axis=1,inplace=True)\n\n # Clean the dataframe\n if do_clean_nans:\n exclude = [col for col in df.columns if not col.startswith('GM')]\n clean_nans(df, exclude_cols = exclude)\n \n # Rename \n #for col in df.columns:\n # if '_resampled' in col:\n # new_col = col.replace('_resampled','')\n # df.rename(columns={col:new_col}, inplace=True)\n \n return\n \ndef find_optimal_subset(X, y, valid_indices = None, n_trees=50, fmax = None, reg_model = True, bins = None, target_name = 'target', sel_features_names = None,\n out_dir = '.', outfile_suff = 'feature_selection', recreate = False, save_output = True):\n \n \n # Iinput filenames\n if reg_model:\n x_filename = '{0}/{1}_regression.pickle'.format(out_dir, outfile_suff)\n else:\n x_filename = '{0}/{1}_bins-{2}_classification.pickle'.format(out_dir, GM_trip_id, '-'.join([str(b) for b in bins]))\n \n # Load files if they exists\n if not recreate and os.path.exists(x_filename):\n with open(x_filename, 'rb') as handle:\n Xy_filt = pickle.load(handle)\n \n X_filt = Xy_filt.drop([target_name],axis=1) \n y = Xy_filt[target_name]\n \n sel_features_names = list(X_filt.columns)\n \n print('Files loaded.')\n \n # Create files if they do not exist\n elif not sel_features_names:\n \n print('Starting SFS')\n \n # Remove features with zero variance\n features = list(X.columns)\n for col in features:\n if X[col].var()==0:\n print('=== Removing: {0} (0 variance)'.format(col)) # Zero crossing rate\n X.drop(col,axis=1,inplace=True)\n #test.drop(col,axis=1,inplace=True)\n \n # Feature search\n tscv = TimeSeriesSplit(n_splits=5)\n if not fmax:\n fmax = X.shape[1]-1\n \n if reg_model:\n f=(1,fmax)\n if valid_indices is not None:\n valid_subset = PredefinedHoldoutSplit(valid_indices)\n feature_selector = SequentialFeatureSelector(RandomForestRegressor(n_trees, bootstrap = True, min_impurity_decrease=1e-6), \n n_jobs=-1,\n k_features=f,\n forward=True,\n verbose=2,\n scoring='neg_mean_squared_error',\n cv = tscv)\n #cv=valid_subset)\n else:\n feature_selector = SequentialFeatureSelector(RandomForestRegressor(n_trees, bootstrap = True, min_impurity_decrease=1e-6), \n n_jobs=-1,\n k_features=f,\n forward=True,\n verbose=2,\n scoring='neg_mean_squared_error',\n cv=tscv)\n \n else:\n f=(1,fmax)\n if valid_indices is not None:\n valid_subset = PredefinedHoldoutSplit(valid_indices)\n feature_selector = SequentialFeatureSelector(RandomForestClassifier(n_trees,class_weight = 'balanced_subsample', max_depth=5, min_impurity_decrease=1e-4),\n n_jobs=-1,\n k_features=f,\n forward=True,\n verbose=2,\n scoring=make_scorer(f1_score, average='macro'),\n cv=valid_subset)\n else:\n feature_selector = SequentialFeatureSelector(RandomForestClassifier(n_trees,class_weight = 'balanced_subsample', max_depth=5, min_impurity_decrease=1e-4),\n n_jobs=-1,\n k_features=f,\n forward=True,\n verbose=2,\n scoring=make_scorer(f1_score, average='macro'),\n cv=tscv)\n \n \n features = feature_selector.fit(X,y)\n sel_features_names = list(feature_selector.k_feature_names_)\n print('Selected features ', sel_features_names)\n \n # Plot\n fig1 = plot_sfs(feature_selector.get_metric_dict(), kind='std_dev', figsize=(25,20))\n plot_name = x_filename.replace('.pickle','.png')\n if save_output:\n plt.savefig(plot_name)\n #print(feature_selector_backward.asubsets_)\n \n # Get metrics per feature \n feats = pd.DataFrame.from_dict(feature_selector.get_metric_dict()).T\n feats['Added Feature'] = None\n for i in range(1,feats.shape[0]+1):\n if i==1:\n prev = set()\n else:\n prev = set(feats.at[i-1,'feature_names'])\n curr = set(feats.at[i,'feature_names'])\n diff = curr.difference(prev)\n diff = list(diff)[0]\n feats.at[i, 'Added Feature'] = diff\n print(i,diff)\n feats['MSE (subset)'] = feats['avg_score'].apply(lambda row:abs(row)) \n feats['Added Feature'] = feats['Added Feature'].apply(lambda row: get_var_name(row))\n feats['Added Feature'] = feats['Added Feature'].apply(lambda row: row.replace('GM.obd.spd_veh.value-0_','Vehicle speed '))\n \n if save_output:\n feats.to_pickle(x_filename.replace('.pickle','_feats_info.pickle'))\n print('Saved: ',x_filename.replace('.pickle','_feats_info.pickle'))\n \n # Save latex\n #feats = feats[['Added Feature','MSE (subset)']]\n feats = feats[['Added Feature', 'MSE (subset)']]\n feats.to_latex('reg_fs_table.tex', columns = feats.columns, index = True, \n float_format = lambda\n x: '%.2e' % x, label = 'table:reg_fs', \n header=[ format_col(col) for col in feats.columns] ,escape=False)\n\n latex_file = x_filename.replace('.pickle','_table.tex')\n print('Wrote latex to: ',latex_file)\n \n # Plot\n plot_filename = x_filename.replace('.pickle','_sfs.pdf')\n plot_fs(feats.index, res = feats['MSE (subset)'], var_label='MSE',filename=plot_filename)\n print('Saved: ',plot_filename)\n \n # Select best features\n X_filt = X[sel_features_names]\n \n # Merge with the target\n X_filt[target_name] = y\n \n # Dump them\n if save_output:\n X_filt.to_pickle(x_filename)\n print('Wrote to ',x_filename)\n \n \n # If test, only select features and save files \n else:\n print('Selecting given features.')\n \n X_filt = X[sel_features_names]\n \n # Merge with the target\n X_filt[target_name] = y\n \n # Dump them\n if save_output:\n X_filt.to_pickle(x_filename)\n print('Wrote to ',x_filename)\n \n \n return X_filt, sel_features_names\n\n\ndef compute_di_aran(data):\n print('Computing DI')\n \n # DI\n data['DI'] = (data[\"AlligCracksSmall\"]*3+data[\"AlligCracksMed\"]*4+data[\"AlligCracksLarge\"]*5)**0.3 + (data[\"CracksLongitudinalSmall\"]**2+data[\"CracksLongitudinalMed\"]**3+data[\"CracksLongitudinalLarge\"]**4+data[\"CracksLongitudinalSealed\"]**2+data[\"CracksTransverseSmall\"]*3+data[\"CracksTransverseMed\"]*4+data[\"CracksTransverseLarge\"]*5+data[\"CracksTransverseSealed\"]*2)**0.1 + (data[\"PotholeAreaAffectedLow\"]*5+data[\"PotholeAreaAffectedMed\"]*7+data[\"PotholeAreaAffectedHigh\"]*10+data[\"PotholeAreaAffectedDelam\"]*5)**0.1\n\n # DI reduced\n data['DI_red'] = (data[\"AlligCracksMed\"]*4+data[\"AlligCracksLarge\"]*5)**0.3 + (data[\"CracksTransverseMed\"]*4+data[\"CracksTransverseLarge\"]*5)**0.1 + (data[\"PotholeAreaAffectedMed\"]*7+data[\"PotholeAreaAffectedHigh\"]*10)**0.1\n \n return \n\n \n#custom function for ecdf\ndef empirical_cdf(data):\n percentiles = []\n n = len(data)\n sort_data = np.sort(data)\n \n for i in np.arange(1,n+1):\n p = i/n\n percentiles.append(p)\n return sort_data,percentiles\n\n\ndef ent(data):\n \"\"\"Calculates entropy of the passed `pd.Series`\n \"\"\"\n p_data = data.value_counts() # counts occurrence of each value\n entropy = scipy.stats.entropy(p_data) # get entropy from counts\n return entropy\n\ndef resample(seq, to_length, window_size):\n '''\n Resample a sequence/\n\n Parameters\n ----------\n seq : np.array\n Sequence to be resampled.\n to_length : int\n Resample to this number of points.\n\n Returns\n -------\n d_resampled : np.array\n resampled distance (0,10)\n y_resampled : np.array\n resampled input sequence.\n ''' \n # Downsample if needed\n seq_len = seq.shape[0] \n if seq_len>to_length:\n seq = choice(seq, to_length)\n seq_len = seq.shape[0] #\n \n # Current\n d = np.linspace(0, window_size, seq_len)\n f = interpolate.interp1d(d, seq)\n \n # Generate new points \n d_new = np.random.uniform(low=0, high=d[-1], size=(to_length - seq_len))\n \n # Append new to the initial\n d_resampled = sorted(np.concatenate((d, d_new)))\n \n # Estimate y at points\n y_resampled = f(d_resampled) \n \n return d_resampled, y_resampled\n\n\ndef resample_df(df, feats_to_resample, to_lengths_dict = {}, window_size = None):\n input_feats_resampled = []\n \n # Filter rows with less than 2 points (can't resample those)\n for feat in feats_to_resample:\n df[feat+'_len'] = df[feat].apply(lambda seq: 1 if isinstance(seq, float) else seq.shape[0]) \n df.mask(df[feat+'_len']<2, inplace = True)\n \n # Drop nans (rows with NaN/len<2) and reset index\n df.dropna(subset = feats_to_resample, inplace = True)\n df.reset_index(drop = True, inplace = True)\n \n # Resample to the maximum\n for feat in feats_to_resample:\n print('Resampling feature: ',feat)\n #max_len = max(df[feat].apply(lambda seq: seq.shape[0]))\n to_length = to_lengths_dict[feat]\n new_feats_resampled = ['{0}_d_resampled'.format(feat), '{0}_resampled'.format(feat)]\n df[new_feats_resampled ] = df.apply(lambda seq: resample(seq[feat], to_length = to_length, window_size = window_size), \n axis=1, result_type=\"expand\")\n input_feats_resampled.append('{0}_resampled'.format(feat))\n \n return df, input_feats_resampled \n\n\n\ndef mean_absolute_percentage_error(y_true, y_pred): \n\n return np.mean(np.abs((y_true - y_pred) / y_true))\n\ndef get_var_name(row, short = False):\n new_row = row.replace(' diff', ' difference')\n if short:\n if 'GM.acc.xyz.z-0' in new_row: \n return '{0} (Acc-z)'.format(new_row.split('-0_')[1])\n else:\n return '{0} (Speed)'.format(new_row.split('-0_')[1]) \n else:\n if 'GM.acc.xyz.z-0' in new_row: \n return '{0} (Acceleration-z)'.format(new_row.split('-0_')[1])\n else:\n return '{0} (Vehicle Speed)'.format(new_row.split('-0_')[1])\n \ndef get_regression_model(model, f_maxsel, random_state = None, use_default = False, is_pca = False):\n model_title = model.replace('_',' ').title()\n nt = 500\n # Define models\n \n if model=='dummy':\n rf = DummyRegressor(strategy=\"mean\")\n parameters = {}\n if model=='linear':\n model_title='Multiple Linear'\n rf = linear_model.LinearRegression()\n parameters = {}\n elif model=='lasso':\n rf = linear_model.Lasso(random_state=random_state)\n lasso_alpha = np.logspace(-5,5,11)\n lasso_alpha = np.array([0.00000001, 0.0000001, 0.000001, 0.00001, 0.0001, 0.0005, 0.001,0.002, 0.005, 0.01,1]) #CPH1\n #lasso_alpha = np.linspace(0,1,21) #M3\n parameters={'alpha':lasso_alpha}\n elif model=='kNN':\n rf = KNeighborsRegressor()\n k = np.arange(5,41,step=5) \n parameters={'n_neighbors':k}\n elif model=='ridge':\n rf = linear_model.Ridge(random_state=random_state)\n ridge_alpha = np.linspace(0,1000,21)\n parameters={'alpha': ridge_alpha}\n elif model=='elastic_net':\n rf = linear_model.ElasticNet(random_state=random_state)\n alpha = np.array([0.001, 0.01,10, 20, 50, 100, 500, 700, 1000])\n parameters={'alpha':alpha, 'l1_ratio':np.linspace(0,1,21)} \n elif model=='random_forest':\n rf = RandomForestRegressor(random_state=random_state)\n depths = np.arange(5,15,5)\n n_estimators = [100]\n #np.arange(300,500,100)\n #fs = np.arange(6,16,2) motorway\n fs = np.arange(10,f_maxsel,2)\n parameters = {'n_estimators': n_estimators, 'max_depth':depths,'min_impurity_decrease':[1e-4, 1e-5], 'max_features':fs}\n elif model=='SVR_poly':\n rf = SVR(kernel='poly')\n C = [0.01,0.8,1,1.5,2,3,5,10,15,20,50]\n epsilon = [0.01,0.01,0.05,0.1,0.2,0.3,0.4,0.5]\n gamma = [0.001,0.01,0.02, 0.05,0.1 ]\n parameters = {'C':C,\n 'epsilon': epsilon,\n 'gamma':gamma}\n elif model=='SVR_rbf':\n model_title = 'SVR'\n rf = SVR(kernel='rbf', epsilon = 0.1)\n #C = np.linspace(0,20,5)\n #C = np.append(C,[1])\n #C.sort()\n #gamma = np.logspace(-4,-2,3) \n C = np.array([0.1,1,5,10,15,20,50,100,200,500,1000])\n gamma = np.array([0.001, 0.01, 0.1, 1, 5])\n n = C.shape[0]*gamma.shape[0]\n print(n)\n parameters = {'C':C, 'gamma':gamma}\n elif model=='ANN':\n model_title = 'ANN'\n \n # L2 regularization parameter\n ann_alpha = np.array([10,15,20])\n \n # Learning rate init\n #learning_rate_init = np.logspace(-5,0,6)\n learning_rate_init = np.array([0.001,0.01, 0.1, 1])\n \n # Architecture\n hs1 = [(2),(4),(8)]\n hs2 = [(16, 8),(12,6),(12,4),(12,2),(10,4)]\n hs3 = [(2, 4, 6), (2,6,8), (2,6,10),(4,8,10), (4,8,12), (4,8,16), (12,8,6), (10,8,6),(10,8,4),(8, 6, 4)]\n hs4 = [(2,4,8,12),(12,8,6,2)]\n hs5 = [(2,4,6,8,12),(12,8,6,4,2)]\n hs = hs2+hs3+hs4\n #hs = [(4,6,8)]\n \n #if use_default and is_pca:\n # parameters = {'hidden_layer_sizes':[(8,6,4)], 'alpha':[1], 'learning_rate_init':[0.1], 'random_state':rs}\n #elif use_default and not is_pca:\n # parameters = {'hidden_layer_sizes':[(2,4,6)], 'alpha':[1], 'learning_rate_init':[0.01], 'random_state':rs}\n #else:\n # parameters = {'hidden_layer_sizes':hs, 'alpha':ann_alpha, 'learning_rate_init':learning_rate_init, 'random_state':rs}\n \n parameters = {'hidden_layer_sizes':hs, 'alpha':ann_alpha, 'learning_rate_init':learning_rate_init}\n \n # Model\n rf = MLPRegressor(learning_rate='adaptive', max_iter=1000)\n \n \n\n return rf, parameters, model_title\n \n \ndef grid_search(rf, parameters, X, y, score, n_splits = 10):\n tscv = TimeSeriesSplit(n_splits=n_splits)\n clf = GridSearchCV(rf, parameters, cv=tscv, scoring=score, verbose=1)\n clf.fit(X,y)\n best_parameters = clf.best_params_\n print(best_parameters) \n rf = clf.best_estimator_\n return clf, rf\n\n\n\ndef get_classification_predictions(X_trainvalid, y_trainvalid, X_test, y_test, rf, \n test_results = None, model_title='', row = 0, labels = None,\n save_plots = True, out_dir = '.', is_pca = False):\n \n labels_train = [l for l in labels if int(l) in y_trainvalid.unique()] \n labels_test = [l for l in labels if int(l) in y_test.unique()]\n labels_plot = ['Low', 'Medium', 'High']\n \n # Train results \n y_trainvalid_pred = rf.predict(X_trainvalid) \n train_report = classification_report(y_trainvalid, y_trainvalid_pred, labels=labels_train)\n train_cm = confusion_matrix(y_trainvalid,y_trainvalid_pred, labels=labels_train)\n #plot_confusion_matrix(rf, X_trainvalid, y_true = y_trainvalid, labels=labels)\n #plt.title('Train')\n\n # Test results\n y_test_pred = rf.predict(X_test)\n test_report = classification_report(y_test, y_test_pred, labels=labels_test)\n test_cm = confusion_matrix(y_test,y_test_pred, labels=labels_test)\n \n plt.rcParams.update({'font.size': 19})\n plot_confusion_matrix(rf, X_test, y_true = y_test,labels=labels_test,display_labels=labels_plot, colorbar = False) \n #ax=plt.gca()\n #ax.set_xticklabels(labels)\n #ax.set_yticklabels(labels)\n \n #if is_pca:\n # plt.title(model_title + ' (PCA)')\n #else:\n # plt.title(model_title \n \n # Compute average metrics over all classes\n test_report_dict = classification_report(y_test, y_test_pred, labels=labels_test, output_dict=True)\n test_report_dict = { str(label): test_report_dict[str(label)] for label in labels_test}\n test_report_df = pd.DataFrame(test_report_dict)\n\n # Compute average metrics over all classes and update results with all models\n test_results.at[row, 'Model'] = model_title\n test_results.at[row, 'Precision'] = test_report_df.loc['precision',:].mean()\n test_results.at[row, 'Recall'] = test_report_df.loc['recall',:].mean()\n test_results.at[row, 'F1-Score'] = test_report_df.loc['f1-score',:].mean()\n \n # Save\n if save_plots:\n dpi=1000\n out_file_path = '{0}/{1}_test.png'.format(out_dir, model_title.replace(' ','_'))\n if is_pca:\n out_file_path = out_file_path.replace('_test.png','_pca_test.png')\n \n plt.savefig(out_file_path, dpi=dpi, bbox_inches = \"tight\")\n plt.savefig(out_file_path.replace('.png','.eps'),format='eps',dpi=dpi, bbox_inches = \"tight\")\n plt.savefig(out_file_path.replace('.png','.pdf'),dpi=dpi, bbox_inches = \"tight\")\n print('file saved as: ',out_file_path)\n \n # Print\n print('=== Train ====')\n print(train_report)\n print('=== Test ====')\n print(test_report)\n \n return train_report, test_report\n \ndef get_regression_predictions(X_trainvalid, y_trainvalid, X_test, y_test, rf, train_results = None, test_results = None, model_title='', row = 0, labels = None):\n\n # Predict\n y_trainvalid_pred = rf.predict(X_trainvalid)\n y_test_pred = rf.predict(X_test)\n \n # MSE: train\n rmse_train = np.sqrt(mean_squared_error(y_true = y_trainvalid, y_pred = y_trainvalid_pred))\n mae_train = mean_absolute_error(y_true = y_trainvalid, y_pred = y_trainvalid_pred)\n mape_train = mean_absolute_percentage_error(y_true = y_trainvalid, y_pred = y_trainvalid_pred)\n r2_train = r2_score(y_true = y_trainvalid, y_pred = y_trainvalid_pred)\n print('\\nMODEL: \\n',model_title)\n print('==== Train error: ==== ')\n print('MRSE: ', rmse_train)\n print('MAE: ', mae_train)\n print('R2: ', r2_train)\n print('MRE: ',mape_train)\n print('====================== \\n')\n\n # MSE: test\n rmse_test = np.sqrt(mean_squared_error(y_true = y_test, y_pred = y_test_pred))\n mae_test = mean_absolute_error(y_true = y_test, y_pred = y_test_pred)\n r2_test = r2_score(y_true = y_test, y_pred = y_test_pred)\n mape_test = mean_absolute_percentage_error(y_true = y_test, y_pred = y_test_pred)\n print('==== Test error: ==== ')\n print('RMSE: ', rmse_test)\n print('MAE: ', mae_test)\n print('R2: ', r2_test)\n print('MRE: ',mape_test)\n print('====================== \\n') \n\n # Update results\n train_results.at[row, 'Model'] = model_title\n train_results.at[row, 'R2'] = r2_train\n train_results.at[row, 'MAE'] = mae_train\n train_results.at[row, 'RMSE'] = rmse_train\n train_results.at[row, 'MRE'] = mape_train\n \n # Update results\n test_results.at[row, 'Model'] = model_title\n test_results.at[row, 'R2'] = r2_test\n test_results.at[row, 'MAE'] = mae_test\n test_results.at[row, 'RMSE'] = rmse_test\n test_results.at[row, 'MRE'] = mape_test\n \n \n \n return y_trainvalid_pred, y_test_pred\n \ndef get_classification_model(model, f_maxsel, random_state = None, is_pca= False):\n \n model_title = model.replace('_',' ').title()\n nt = 500\n \n # Define models\n if model=='dummy':\n rf = DummyClassifier(strategy='most_frequent')\n parameters = {}\n if model=='logistic_regresion':\n #rf = linear_model.LogisticRegression(class_weight = 'balanced')\n rf = linear_model.LogisticRegression(random_state=random_state)\n C = np.linspace(0,20,5)\n #C = np.arange(0,10,2)\n parameters = {'C':C}\n if model=='naive_bayes':\n rf = GaussianNB()\n parameters = {} \n if model=='kNN':\n rf = KNeighborsClassifier()\n k = np.arange(1,41,step=1) \n #n = np.arange(0,10,2)\n parameters = {'n_neighbors':k}\n if model=='random_forest':\n #rf = RandomForestClassifier(nt, class_weight = 'balanced_subsample')\n rf = RandomForestClassifier(nt, random_state=random_state)\n depths = np.arange(5,10,1)\n n_estimators = np.arange(300,500,100)\n fs = np.arange(6,16,2)\n parameters = {'n_estimators': n_estimators, 'max_depth':depths, 'max_features':fs}\n elif model=='SVC_rbf':\n model_title = 'SVC'\n rf = SVC(class_weight='balanced', kernel ='rbf', random_state=random_state)\n #C = np.linspace(0,20,5)\n #C = np.append(C,[1])\n #C.sort()\n #gamma = np.logspace(-4,-2,3)\n C = np.array([1,5])\n gamma = np.array([0.001])\n n = C.shape[0]*gamma.shape[0]\n print(n)\n parameters = {'C':C, 'gamma':gamma}\n elif model=='ANN':\n model_title = 'ANN'\n \n ann_alpha = np.array([1,5,10,12])\n \n rs = [0]\n \n hs1 = [(4),(8),(12),(16)]\n hs2 = [(8,4),(12,4),(4,8)]\n hs3 = [(4,6,8),(4,8,16)]\n hs4 = [(2,4,8,12),(12,8,6,2)]\n hs5 = [(2,4,6,8,12),(12,8,6,4,2)]\n #hs = hs1+hs2+hs3+hs4+hs5\n hs = hs1\n #hs = [(4,6,8)]\n #learning_rate_init = np.logspace(-5,0,6)\n learning_rate_init = np.array([0.01,0.1])\n acct = ['identity', 'relu']\n rf = MLPClassifier(max_iter=1000)\n parameters = {'hidden_layer_sizes':hs, 'alpha':ann_alpha, 'learning_rate_init':learning_rate_init, 'random_state':rs, 'activation':acct}\n #parameters = {'hidden_layer_sizes':hs} \n #print(parameters)\n \n return rf, parameters, model_title","sub_path":"utils/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":32688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"293341545","text":"#!/bin/usr/python3\nfrom Hidden.secret import verify_integrity\nfrom Crypto.Util.number import *\n\ndef save_key(n,e,d,p,q):\n string = \"n = {}\\ne = {}\\nd = {}\\np = {}\\nq = {}\\n\".format(n,e,d,p,q)\n print(string)\n open('Baby-RSA-challenge/Hidden/key.txt','w').write(string)\n\ndef generate_key(bits):\n p = getPrime(bits//2)\n q = getPrime(bits//2)\n n = p * q\n e = 13\n phin = (p-1) * (q-1)\n d = inverse(e,phin)\n assert verify_integrity(n,e,d) == True , ' Invalid Key :( '\n save_key(n,e,d,p,q)\n return n,e,d,p,q\n\nn,e,d,p,q = generate_key(64)\n\nparams = \"n = {}\\ne = {}\\nd = {}\\np = {}\\nq = {}\".format(n,e,d,p,q)\nopen('Baby-RSA-challenge/params.txt','w').write(params)\n","sub_path":"SHELL-CTF/Crypto/Baby-RSA-Challenge/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"214962568","text":"from django.db import models\nfrom django.db import router\nfrom django.db.models import signals\n\nfrom . import managers\nfrom .utils import cascade_archive, cascade_unarchive\nfrom .signals import post_undelete, post_softdelete, pre_softdelete\n\n\nclass ArchiveMixin(models.Model):\n \"\"\"\n A model that is only marked as deleted when the .delete() method is called,\n instead of actually deleted. Calling .delete() on this object will only\n mark it as deleted, and it will not show up in the default queryset. If you\n want to see all objects, including the ones marked as deleted, use:\n\n ArchiveModel.all_objects.all()\n\n If you want to just see the ones marked as deleted, use:\n\n ArchiveModel.all_objects.deleted.all()\n \"\"\"\n deleted = models.DateTimeField(null=True, blank=True)\n\n objects = managers.ArchiveManager()\n all_objects = models.Manager()\n\n class Meta:\n abstract = True\n\n def get_candidate_relations_to_delete(self):\n \"\"\"\n Returns\n \"\"\"\n return models.deletion.get_candidate_relations_to_delete(self._meta)\n\n def related_objects(self, relation_field):\n \"\"\"\n Given a relation field return the QuerySet of objects that are\n related to the current object (self).\n\n Arguments:\n relation_field (django.db.models.fields.related): related\n field instance.\n \"\"\"\n return relation_field.related_model.objects.filter(\n **{'{}__in'.format(relation_field.field.name): [self]})\n\n def delete(self, using=None, keep_parents=False):\n using = using or router.db_for_write(self.__class__, instance=self)\n\n assert self._get_pk_val() is not None, \\\n \"%s object can't be deleted because its %s attribute \" \\\n \"is set to None.\" % (self._meta.object_name, self._meta.pk.attname)\n\n if self.deleted:\n # short-circuit here to prevent lots of nesting\n return\n\n # Start delete, send the pre-delete signal.\n signals.pre_delete.send(\n sender=self.__class__, instance=self, using=using)\n pre_softdelete.send(\n sender=self.__class__, instance=self, using=using)\n\n collector = cascade_archive(self, using, keep_parents)\n resp = collector.delete()\n # End delete, send the post-delete signal\n signals.post_delete.send(\n sender=self.__class__, instance=self, using=using)\n post_softdelete.send(\n sender=self.__class__, instance=self, using=using)\n\n return resp\n\n delete.alters_data = True\n\n def really_delete(self, using=None):\n \"\"\"\n Actually deletes the instance.\n \"\"\"\n super(ArchiveMixin, self).delete(using=using)\n\n def undelete(self, using=None, keep_parents=False):\n using = using or router.db_for_write(self.__class__, instance=self)\n\n assert self._get_pk_val() is not None, \\\n \"%s object can't be undeleted because its %s attribute \" \\\n \"is set to None.\" % (self._meta.object_name, self._meta.pk.attname)\n\n assert self.deleted is not None, \\\n \"%s object can't be undeleted because it is not deleted.\" % (self._meta.object_name)\n\n collector = cascade_unarchive(self, using, self.deleted, keep_parents)\n resp = collector.delete()\n # End undelete, send the post-undelete signal\n post_undelete.send(\n sender=self.__class__, instance=self, using=using)\n\n return resp\n","sub_path":"django_archive_mixin/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"467208047","text":"# Copyright [2020] [KTH Royal Institute of Technology] Licensed under the\n# Educational Community License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may\n# obtain a copy of the License at http://www.osedu.org/licenses/ECL-2.0\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an \"AS IS\"\n# BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n# Course: EL2805 - Reinforcement Learning - Lab 2 Problem 1\n# Code author: [Alessio Russo - alessior@kth.se]\n# Last update: 6th October 2020, by alessior@kth.se\n#\n\n# NOTE: MODIFIED TO WORK WITH DQN CLASS FROM UTILS.PY\n\n# Load packages\nimport numpy as np\nimport gym\nimport torch\nfrom tqdm import trange\n\nimport matplotlib.pyplot as plt\n\nimport utils as ut\n\n\ndef running_average(x, N):\n ''' Function used to compute the running average\n of the last N elements of a vector x\n '''\n if len(x) >= N:\n y = np.copy(x)\n y[N - 1:] = np.convolve(x, np.ones((N,)) / N, mode='valid')\n else:\n y = np.zeros_like(x)\n return y\n\n\ndef check_solution(path, device):\n # Import and initialize Mountain Car Environment\n env = gym.make('LunarLander-v2')\n env.reset()\n\n # Load model\n NN = torch.load('neural-network-1.pth', map_location=torch.device(device))\n\n # Create DQN class\n n_actions = env.action_space.n # Number of available actions\n dim_state = len(env.observation_space.high) # State dimensionality\n hidden_dimension = 64\n DQN = ut.DQN(ut.net_builder, dim_state, n_actions, hidden_dimension, device)\n\n # Assign the loaded model to the DQN class\n DQN.network = NN\n\n # Parameters\n N_EPISODES = 50 # Number of episodes to run for trainings\n CONFIDENCE_PASS = 50\n\n # Reward\n episode_reward_list = [] # Used to store episodes reward\n\n # ---- FOr plotting episodic reward -----\n # list of episodes\n I = []\n\n # Reward\n episode_reward_list_random_agent = [] # Used to store episodes reward (random agent)\n\n # Simulate episodes\n print('Checking solution...')\n EPISODES = trange(N_EPISODES, desc='Episode: ', leave=True)\n for i in EPISODES:\n I.append(i)\n EPISODES.set_description(\"Episode {}\".format(i))\n # Reset enviroment data\n done = False\n state = env.reset()\n total_episode_reward = 0.\n while not done:\n # env.render()\n # Get next state and reward. The done variable\n # will be True if you reached the goal position,\n # False otherwise\n q_values = DQN.forward(torch.tensor([state]).to(device))\n action = q_values.max(1)[1].item()\n next_state, reward, done, _ = env.step(action)\n\n # Update episode reward\n total_episode_reward += reward\n\n # Update state for next iteration\n state = next_state\n\n # Append episode reward\n episode_reward_list.append(total_episode_reward)\n\n # Close environment\n env.close()\n\n avg_reward = np.mean(episode_reward_list)\n confidence = np.std(episode_reward_list) * 1.96 / np.sqrt(N_EPISODES)\n\n print('Policy achieves an average total reward of {:.1f} +/- {:.1f} with confidence 95%.'.format(\n avg_reward,\n confidence))\n\n if avg_reward - confidence >= CONFIDENCE_PASS:\n print('Your policy passed the test!')\n else:\n print(\n \"Your policy did not pass the test! The average reward of your policy needs to be greater than {} with 95% \"\n \"confidence\".format(\n CONFIDENCE_PASS))\n\n EPISODES = trange(N_EPISODES, desc='Episode: ', leave=True)\n for i in EPISODES:\n EPISODES.set_description(\"Episode {}\".format(i))\n # Reset enviroment data\n done = False\n state = env.reset()\n total_episode_reward = 0.\n while not done:\n # Run random agent\n stupid_action = np.random.randint(0, n_actions)\n\n next_state, reward, done, _ = env.step(stupid_action)\n\n # Update episode reward\n total_episode_reward += reward\n\n # Update state for next iteration\n state = next_state\n\n # Append episode reward\n episode_reward_list_random_agent.append(total_episode_reward)\n\n # Close environment\n env.close()\n\n plt.plot(I, episode_reward_list, label=\"Our model\")\n plt.plot(I, episode_reward_list_random_agent, label=\"Random model\")\n plt.xlabel('Episodes')\n plt.ylabel('Reward for episode')\n plt.legend(loc=\"lower left\")\n plt.show()\n\n # ---- Plot the max Q value ----\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n xs = np.arange(0, 1.5, 0.1).tolist()\n ys = np.arange(-np.pi, np.pi, 0.2).tolist()\n Y = []\n W = []\n Z = []\n\n def fun(x, y, net):\n state = np.array([0, x, 0, 0, y, 0, 0, 0])\n Q = net.forward(torch.tensor([state], dtype=torch.float32).to(device))\n val = Q.max(1)[0].item()\n return val\n\n # Create the triplets for plotting\n for i in range(len(xs)):\n for j in range(len(ys)):\n Y.append(xs[i])\n W.append(ys[j])\n Z.append(fun(xs[i], ys[j], DQN))\n ax.scatter(Y, W, Z)\n ax.set_xlabel('y')\n ax.set_ylabel('w')\n ax.set_zlabel('max Q value')\n plt.show()\n\n # ---- Plot the best action ----\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n xs = np.arange(0, 1.5, 0.1).tolist()\n ys = np.arange(-np.pi, np.pi, 0.2).tolist()\n Y = []\n W = []\n Z = []\n\n def fun(x, y, net):\n state = np.array([0, x, 0, 0, y, 0, 0, 0])\n Q = net.forward(torch.tensor([state], dtype=torch.float32).to(device))\n # print(Q)\n val = Q.max(1)[1].item()\n # print(val)\n return val\n\n # Create the triplets for plotting\n for i in range(len(xs)):\n for j in range(len(ys)):\n Y.append(xs[i])\n W.append(ys[j])\n Z.append(fun(xs[i], ys[j], DQN))\n ax.scatter(Y, W, Z)\n ax.set_xlabel('y')\n ax.set_ylabel('w')\n ax.set_zlabel('Best action')\n plt.show()\n","sub_path":"lab2/problem1/DQN_check_solution_full.py","file_name":"DQN_check_solution_full.py","file_ext":"py","file_size_in_byte":6335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"188169638","text":"import itertools\n\nfrom fireant import utils\nfrom fireant.reference_helpers import (\n reference_alias,\n reference_label,\n)\nfrom .base import TransformableWidget\nfrom .chart_base import ChartWidget\n\nMAP_SERIES_TO_PLOT_FUNC = {\n ChartWidget.LineSeries: 'line',\n ChartWidget.AreaSeries: 'area',\n ChartWidget.AreaStackedSeries: 'area',\n ChartWidget.AreaPercentageSeries: 'area',\n ChartWidget.PieSeries: 'pie',\n ChartWidget.BarSeries: 'bar',\n ChartWidget.StackedBarSeries: 'bar',\n ChartWidget.ColumnSeries: 'bar',\n ChartWidget.StackedColumnSeries: 'bar',\n}\n\n\nclass Matplotlib(ChartWidget, TransformableWidget):\n def __init__(self, title=None):\n super(Matplotlib, self).__init__()\n self.title = title\n\n def transform(self, data_frame, dataset, dimensions, references, annotation_frame=None):\n import matplotlib.pyplot as plt\n data_frame = data_frame.copy()\n\n n_axes = len(self.items)\n figsize = (14, 5 * n_axes)\n fig, plt_axes = plt.subplots(n_axes,\n sharex='row',\n figsize=figsize)\n fig.suptitle(self.title)\n\n if not hasattr(plt_axes, '__iter__'):\n plt_axes = (plt_axes,)\n\n colors = itertools.cycle('bgrcmyk')\n for axis, plt_axis in zip(self.items, plt_axes):\n for series in axis:\n series_color = next(colors)\n\n linestyles = itertools.cycle(['-', '--', '-.', ':'])\n for reference in [None] + references:\n metric = series.metric\n f_metric_key = utils.alias_selector(reference_alias(metric, reference))\n f_metric_label = reference_label(metric, reference)\n\n plot = self.get_plot_func_for_series_type(data_frame[f_metric_key], f_metric_label, series)\n plot(ax=plt_axis,\n label=axis.label,\n color=series_color,\n stacked=series.stacking is not None,\n linestyle=next(linestyles)) \\\n .legend(loc='center left',\n bbox_to_anchor=(1, 0.5))\n\n return plt_axes\n\n @staticmethod\n def get_plot_func_for_series_type(pd_series, label, chart_series):\n pd_series.name = label\n plot = pd_series.plot\n plot_func_name = MAP_SERIES_TO_PLOT_FUNC[type(chart_series)]\n plot_func = getattr(plot, plot_func_name)\n return plot_func\n","sub_path":"fireant/widgets/matplotlib.py","file_name":"matplotlib.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"50846465","text":"import twitter\nimport threading\nimport requests\nimport os\n\ntwit_api = twitter.Api(consumer_key=os.environ.get('consumer_key'),\n\tconsumer_secret=os.environ.get('consumer_secret'),\n\taccess_token_key=os.environ.get('access_token_key'),\n\taccess_token_secret=os.environ.get('access_token_secret'))\n\ncurrent_block_hash = 0\n\ndef is_new_block(block_hash):\n\tglobal current_block_hash\n\n\tif block_hash != current_block_hash:\n\t\tcurrent_block_hash = block_hash\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef block_update():\n\tthreading.Timer(5.0, block_update).start()\n\n\tnew_block = requests.get(\"https://blockchain.info/latestblock\").json()\n\tblock_hash = new_block[\"hash\"]\n\t\n\tif (is_new_block(block_hash)):\n\t\tcurrent_block = requests.get(\"https://blockchain.info/rawblock/\" + str(block_hash)).json()\n\t\n\t\tintro = \"Latest Block (bitcoin):\" + \"\\n\\n\"\n\t\ttwit_height = \"Block Height: \" + str(current_block[\"height\"]) + \"\\n\"\n\t\ttwit_num_transactions = \"Transactions: \" + str(current_block[\"n_tx\"]) + \"\\n\"\n\t\tblock_size = current_block[\"size\"] / 1000.0\n\t\ttwit_size = \"Size: \" + str(block_size) + \" kB\" + \"\\n\"\n\t\tversion = \"Version: \" + str(current_block[\"ver\"])\n\n\t\ttweet = (intro + twit_height + twit_num_transactions + twit_size + version)\n\t\tprint(tweet)\n\t\ttwit_api.PostUpdate(tweet)\n\nblock_update()\n","sub_path":"twitter_block_report.py","file_name":"twitter_block_report.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"74888922","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2005 onwards University of Deusto\n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution.\n#\n# This software consists of contributions made by many individuals,\n# listed below:\n#\n# Author: Jaime Irurzun \n#\n\nfrom test.unit.weblab.proxy import adds_triple_translator, fake_time\nfrom voodoo.sessions import exc as SessionErrors\nfrom voodoo.gen.coordinator import CoordAddress\nfrom voodoo.gen.exceptions.locator import LocatorErrors\nfrom voodoo.gen.locator import EasyLocator\nfrom voodoo.sessions import session_id as SessionId\nfrom weblab.data import server_type as ServerType\nfrom weblab.data.command import Command\nimport weblab.lab.exc as LaboratoryErrors\nimport weblab.proxy.exc as ProxyErrors\nfrom weblab.proxy import server as ProxyServer\nfrom weblab.translator.translators import StoresNothingTranslator, StoresEverythingTranslator\nimport mocker\nimport test.unit.configuration as configuration_module\nimport unittest\nimport voodoo.configuration as ConfigurationManager\nimport weblab.experiment.util as ExperimentUtil\nimport weblab.methods as weblab_methods\n\n\nclass CreatingProxyServerTestCase(mocker.MockerTestCase):\n\n def setUp(self):\n self._cfg_manager = ConfigurationManager.ConfigurationManager()\n self._cfg_manager.append_module(configuration_module)\n\n def test_invalid_session_type_name(self):\n self._cfg_manager._set_value(ProxyServer.WEBLAB_PROXY_SERVER_SESSION_TYPE, \"this_will_never_be_a_valid_session_type\")\n self.assertRaises(\n ProxyErrors.NotASessionTypeError,\n ProxyServer.ProxyServer, None, None, self._cfg_manager\n )\n\n def test_invalid_default_translator_klazz_name(self):\n self._cfg_manager._set_value(ProxyServer.WEBLAB_PROXY_SERVER_DEFAULT_TRANSLATOR_NAME, \"ThisWillNeverBeAValidDefaultTranslatorKlazzName\")\n self.assertRaises(\n ProxyErrors.InvalidDefaultTranslatorNameError,\n ProxyServer.ProxyServer, None, None, self._cfg_manager\n )\n\n\nclass UsingProxyServerTestCase(mocker.MockerTestCase):\n\n def setUp(self):\n self._cfg_manager = ConfigurationManager.ConfigurationManager()\n self._cfg_manager.append_module(configuration_module)\n\n self.RESERVATION_ID = \"my_reservation_id\"\n self.RESERVATION_SESS_ID = SessionId.SessionId(self.RESERVATION_ID)\n self.LAB_SESS_ID = \"my_lab_sess_id\"\n self.ANY_COORD_ADDR = CoordAddress.CoordAddress.translate_address('myserver:myprocess@mymachine')\n self.LAB_COORD_ADDR = self.ANY_COORD_ADDR\n\n def _create_proxy(self, laboratories=(), translators=(), time_mock=None):\n locator = FakeLocator({'laboratories': laboratories, 'translators': translators})\n easylocator = EasyLocator.EasyLocator(self.ANY_COORD_ADDR, locator)\n proxy = ProxyServer.ProxyServer(None, easylocator, self._cfg_manager)\n if time_mock is not None:\n proxy._time = time_mock\n return proxy\n\n def _create_custom_translator(self, translator_klazz):\n locator = FakeLocator()\n easylocator = EasyLocator.EasyLocator(self.ANY_COORD_ADDR, locator)\n return translator_klazz(self.ANY_COORD_ADDR, easylocator, self._cfg_manager)\n\n #===========================================================================\n # _find_translator()\n #===========================================================================\n\n def test_find_translator_being_a_suitable_translator_available(self):\n translator = self._create_custom_translator(StoresNothingTranslator)\n proxy = self._create_proxy(translators=(translator,))\n\n found_translator, is_default = proxy._find_translator(\"whichever experiment_id, because FakeLocator will find it ;-)\")\n self.assertEquals(translator, found_translator)\n self.assertFalse(is_default)\n\n def test_find_translator_not_being_any_suitable_translator_available_so_using_an_explicit_default_one(self):\n self._cfg_manager._set_value(ProxyServer.WEBLAB_PROXY_SERVER_DEFAULT_TRANSLATOR_NAME, \"StoresNothingTranslator\")\n proxy = self._create_proxy()\n\n found_translator, is_default = proxy._find_translator(\"whichever experiment_id, because FakeLocator won't find it...\")\n self.assertEquals(StoresNothingTranslator, found_translator.__class__)\n self.assertTrue(is_default)\n\n def test_find_translator_not_being_any_suitable_translator_available_so_using_the_implicit_default_one(self):\n proxy = self._create_proxy()\n\n found_translator, is_default = proxy._find_translator(\"whichever experiment_id, because FakeLocator won't find it...\")\n self.assertEquals(StoresEverythingTranslator, found_translator.__class__)\n self.assertTrue(is_default)\n\n #===========================================================================\n # Using the API: enable_access(), send_command(), send_file(), are_expired(), disable_access(), retrieve_results()\n #===========================================================================\n\n def _test_command_sent(self, command_sent, expected_command, expected_response):\n self.assertEquals(expected_command, command_sent.command.commandstring)\n self.assertEquals(expected_response, command_sent.response.commandstring)\n self.assertTrue(isinstance(command_sent.timestamp_before, float))\n self.assertTrue(isinstance(command_sent.timestamp_after, float))\n self.assertTrue(command_sent.timestamp_after >= command_sent.timestamp_before)\n\n def _test_file_sent(self, file_sent, expected_file_info, expected_response):\n self.assertEquals(expected_file_info, file_sent.file_info)\n self.assertEquals(expected_response, file_sent.response.commandstring)\n self.assertTrue(isinstance(file_sent.timestamp_before, float))\n self.assertTrue(isinstance(file_sent.timestamp_after, float))\n self.assertTrue(file_sent.timestamp_after >= file_sent.timestamp_before)\n\n def _test_happy_path(self, translator_name):\n FILE_CONTENT = ExperimentUtil.serialize('Huuuuuuuuge file!')\n FILE_INFO = \"My file's description\"\n\n self._cfg_manager._set_value(ProxyServer.WEBLAB_PROXY_SERVER_DEFAULT_TRANSLATOR_NAME, translator_name)\n fake_time.TIME_TO_RETURN = 1289548551.2617509 # 2010_11_12___07_55_51\n\n laboratory = self.mocker.mock()\n laboratory.send_command(self.LAB_SESS_ID, Command('Do this!'))\n self.mocker.result(Command('Done!'))\n laboratory.send_file(self.LAB_SESS_ID, Command(FILE_CONTENT), FILE_INFO)\n self.mocker.result(Command('File received!'))\n\n self.mocker.replay()\n proxy = self._create_proxy(laboratories=(laboratory,), time_mock=fake_time)\n\n proxy.do_enable_access(self.RESERVATION_ID, \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n\n command_response = proxy.send_command(self.RESERVATION_SESS_ID, Command('Do this!'))\n self.assertEquals(Command('Done!'), command_response)\n\n file_response = proxy.send_file(self.RESERVATION_SESS_ID, Command(FILE_CONTENT), FILE_INFO)\n self.assertEquals(Command('File received!'), file_response)\n\n proxy.do_disable_access(self.RESERVATION_ID)\n\n commands, files = proxy.do_retrieve_results(self.RESERVATION_ID)\n return commands, files\n\n def test_happy_path_using_a_translator_that_stores(self):\n # Since this is not a really default Translator, we have to make it available for the test\n ProxyServer.DEFAULT_TRANSLATORS['AddsATrippleAAtTheBeginingTranslator'] = adds_triple_translator.AddsATrippleAAtTheBeginingTranslator\n\n commands, files = self._test_happy_path(\"AddsATrippleAAtTheBeginingTranslator\")\n\n self.assertEquals(2, len(commands))\n self._test_command_sent(\n commands[0],\n 'AAADo this!', 'AAADone!'\n )\n self._test_command_sent(\n commands[1],\n 'on_finish', 'on_start before_send_command after_send_command before_send_file after_send_file do_on_finish '\n )\n\n self.assertEquals(1, len(files))\n self._test_file_sent(\n files[0],\n \"My file's description\",\n 'AAAFile received!'\n )\n\n def test_happy_path_using_a_translator_that_does_not_store(self):\n commands, files = self._test_happy_path(\"StoresNothingTranslator\")\n self.assertEquals(0, len(commands))\n self.assertEquals(0, len(files))\n\n def test_doing_anything_before_enabling(self):\n proxy = self._create_proxy()\n\n # Can't disable access, of course\n self.assertRaises(\n ProxyErrors.InvalidReservationIdError,\n proxy.do_disable_access,\n self.RESERVATION_ID\n )\n\n # Can't check if the user is online\n expirations = proxy.do_are_expired([self.RESERVATION_ID])\n self.assertEquals(\"Y \", expirations[0])\n\n # Can't retrieve results\n self.assertRaises(\n SessionErrors.SessionNotFoundError,\n proxy.do_retrieve_results,\n self.RESERVATION_ID\n )\n\n # Can't poll\n self.assertRaises(\n ProxyErrors.InvalidReservationIdError,\n proxy.poll,\n self.RESERVATION_SESS_ID\n )\n\n # Can't work with the experiment\n self.assertRaises(\n ProxyErrors.InvalidReservationIdError,\n proxy.send_command,\n self.RESERVATION_SESS_ID, 'command'\n )\n self.assertRaises(\n ProxyErrors.InvalidReservationIdError,\n proxy.send_file,\n self.RESERVATION_SESS_ID, 'file'\n )\n\n def test_doing_anything_after_disabling(self):\n proxy = self._create_proxy()\n proxy.do_enable_access(self.RESERVATION_ID, \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n proxy.do_disable_access(self.RESERVATION_ID)\n\n # Can't poll\n self.assertRaises(\n ProxyErrors.AccessDisabledError,\n proxy.poll,\n self.RESERVATION_SESS_ID\n )\n\n # Can't work with the experiment\n self.assertRaises(\n ProxyErrors.AccessDisabledError,\n proxy.send_command,\n self.RESERVATION_SESS_ID, 'command'\n )\n self.assertRaises(\n ProxyErrors.AccessDisabledError,\n proxy.send_file,\n self.RESERVATION_SESS_ID, 'file'\n )\n\n # Can't disable access again, of course\n self.assertRaises(\n ProxyErrors.AccessDisabledError,\n proxy.do_disable_access,\n self.RESERVATION_ID\n )\n\n # CAN retrieve results!\n proxy.do_retrieve_results(self.RESERVATION_ID)\n\n def test_failed_to_send_command(self):\n laboratory = self.mocker.mock()\n laboratory.send_command(self.LAB_SESS_ID, 'command')\n self.mocker.throw(LaboratoryErrors.FailedToSendCommandError)\n\n self.mocker.replay()\n proxy = self._create_proxy(laboratories=(laboratory,))\n\n proxy.do_enable_access(self.RESERVATION_ID, \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n\n self.assertRaises(\n ProxyErrors.FailedToSendCommandError,\n proxy.send_command,\n self.RESERVATION_SESS_ID, 'command'\n )\n\n # Access becomes disabled\n self.assertRaises(\n ProxyErrors.AccessDisabledError,\n proxy.send_command,\n self.RESERVATION_SESS_ID, 'command'\n )\n\n def test_failed_to_send_file(self):\n laboratory = self.mocker.mock()\n laboratory.send_file(self.LAB_SESS_ID, 'file', 'info')\n self.mocker.throw(LaboratoryErrors.FailedToSendFileError)\n\n self.mocker.replay()\n proxy = self._create_proxy(laboratories=(laboratory,))\n\n proxy.do_enable_access(self.RESERVATION_ID, \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n\n self.assertRaises(\n ProxyErrors.FailedToSendFileError,\n proxy.send_file,\n self.RESERVATION_SESS_ID, 'file', 'info'\n )\n\n # Access becomes disabled\n self.assertRaises(\n ProxyErrors.AccessDisabledError,\n proxy.send_file,\n self.RESERVATION_SESS_ID, 'file', 'info'\n )\n\n def test_invalid_laboratory_session_id_when_sending_a_command(self):\n laboratory = self.mocker.mock()\n laboratory.send_command(self.LAB_SESS_ID, 'command')\n self.mocker.throw(LaboratoryErrors.SessionNotFoundInLaboratoryServerError)\n\n self.mocker.replay()\n proxy = self._create_proxy(laboratories=(laboratory,))\n\n proxy.do_enable_access(self.RESERVATION_ID, \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n\n self.assertRaises(\n ProxyErrors.NoCurrentReservationError,\n proxy.send_command,\n self.RESERVATION_SESS_ID, 'command'\n )\n\n def test_invalid_laboratory_session_id_when_sending_a_file(self):\n laboratory = self.mocker.mock()\n laboratory.send_file(self.LAB_SESS_ID, 'file', 'info')\n self.mocker.throw(LaboratoryErrors.SessionNotFoundInLaboratoryServerError)\n\n self.mocker.replay()\n proxy = self._create_proxy(laboratories=(laboratory,))\n\n proxy.do_enable_access(self.RESERVATION_ID, \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n\n self.assertRaises(\n ProxyErrors.NoCurrentReservationError,\n proxy.send_file,\n self.RESERVATION_SESS_ID, 'file', 'info'\n )\n\n def test_are_expired(self):\n proxy = self._create_proxy()\n session_ids = [\"reservation_id1\", \"reservation_id2\", \"reservation_id3\"]\n proxy.do_enable_access(session_ids[0], \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n proxy.do_enable_access(session_ids[1], \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n proxy.do_enable_access(\"invalid-reservation-id\", \"ud-fpga@FPGA experiments\", \"student1\", self.LAB_COORD_ADDR, self.LAB_SESS_ID)\n\n expirations = proxy.do_are_expired(session_ids)\n self.assertEquals(3, len(expirations))\n self.assertEquals(\"N\", expirations[0])\n self.assertEquals(\"N\", expirations[1])\n self.assertEquals(\"Y \", expirations[2])\n\n\nclass FakeLocator(object):\n\n def __init__(self, clients={}):\n self.clients = clients\n\n def retrieve_methods(self, server_type):\n if server_type == ServerType.Laboratory:\n return weblab_methods.Laboratory\n else:\n return weblab_methods.Translator\n\n def get_server_from_coord_address(self, coord_address, client_coord_address, server_type, restrictions):\n if server_type == ServerType.Translator:\n return self.clients['translators']\n else:\n return self.clients['laboratories']\n\n def get_server(self, coord_addr, server_type, restrictions=()):\n if server_type == ServerType.Translator:\n if len(self.clients['translators']) > 0:\n return self.clients['translators'][0]\n else:\n raise LocatorErrors.NoServerFoundError()\n else:\n return self.clients['laboratories'][0]\n\n def inform_server_not_working(self, server_not_working, server_type, restrictions_of_server):\n pass\n\n\ndef suite():\n return unittest.TestSuite(\n (\n unittest.makeSuite(CreatingProxyServerTestCase),\n unittest.makeSuite(UsingProxyServerTestCase)\n )\n )\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"server/src/test/unit/weblab/proxy/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":15917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"62729551","text":"def updateUpsSupply(gridpriceState, curWorkload, workloadOVR, renState, upsStorage, upsCapability, upsSupplyFlu):\n upsSupply = 0\n updatedUpsStorage = upsStorage\n if renState == 'outage':\n if curWorkload >= workloadOVR and gridpriceState == 'high':\n upsSupply = upsStorage\n updatedUpsStorage = 0\n elif curWorkload < workloadOVR and gridpriceState == 'low':\n upsSupply = - (upsCapability - upsStorage)\n updatedUpsStorage = upsCapability\n\n elif renState == 'fluctuate' and gridpriceState == 'low':\n if curWorkload < workloadOVR:\n upsSupply = - (upsCapability - upsStorage)\n updatedUpsStorage = upsCapability\n\n elif renState == 'stable':\n if gridpriceState == 'low' or (curWorkload < workloadOVR and gridpriceState == 'high'):\n upsSupply = - (upsCapability - upsStorage)\n updatedUpsStorage = upsCapability\n\n upsSupply += upsSupplyFlu\n\n return upsSupply, updatedUpsStorage\n\n\ngridpriceStateList = ['high', 'low']\ncurWorkload = 1200\nworkloadOVR = 1000\nrenStateList = ['stable', 'fluctuate', 'outage']\nupsStorage = 80\nupsCapability = 100\nupsSupplyFlu = -25\n\nfor gridpriceState in gridpriceStateList:\n for renState in renStateList:\n upsSupply, updatedUpsStorage = updateUpsSupply(gridpriceState, curWorkload, workloadOVR, renState, upsStorage, upsCapability, upsSupplyFlu)\n print('upsSupply = ', upsSupply, \"updatedUpsStorage = \", updatedUpsStorage)\n","sub_path":"sandbox/test_updateUpsSupply.py","file_name":"test_updateUpsSupply.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"397477979","text":"from tpot import TPOTClassifier\nfrom sklearn.model_selection import train_test_split\nfrom DataExtraction import DataExtraction as DE\nimport os\n\n\ndef select_pipeline_tpot(data_name, train_size, max_opt_time, n_gen, pop_size):\n \"\"\" Selects the best pipeline with tpot and exports its file\n\n :param data_name: Name of the data\n :param train_size: The sizes of the training and test set, in a fraction of the complete set\n :param max_opt_time: The maximal optimization time for the tpot classifier\n :param n_gen: The number of generations used in the tpot classifier\n :param pop_size: The population size used in the tpot classifier\n :return: an exported python file containing the best pipeline\n \"\"\"\n\n # Extract data\n print('Extracting data...')\n X, y, gene_ids, sample_ids = DE.extract_data(data_name)\n\n # Splitting into test and training\n print('Splitting into test and training...')\n X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=train_size, test_size=1-train_size)\n\n # Use tpot to find the best pipeline\n print('Starting PipelineFinder optimization...')\n tpot = TPOTClassifier(verbosity=2, max_time_mins=max_opt_time, population_size=pop_size, generations=n_gen)\n tpot.fit(X_train, y_train)\n\n # Calculate accuracy\n print('The accuracy of the best pipeline is: %f' % (tpot.score(X_test, y_test)))\n\n # Export pipeline\n print('Exporting as TPOT_' + data_name + '_pipeline.py')\n cwd = os.getcwd()\n os.chdir('../Pipelines')\n tpot.export('TPOT_' + data_name + '_pipeline.py')\n os.chdir(cwd)","sub_path":"Data Mining Seminar/SkinDiseaseTPOT/PipelineFinder/PipelineSelection.py","file_name":"PipelineSelection.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"599395371","text":"# coding=utf8\nfrom django.shortcuts import render,get_object_or_404\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\n\n@login_required\ndef index(request):\n #首页公共部分参数:项目数,发布次数,用户总数等 \n from release.models import projectinfo\n from release.models import release\n from django.contrib.auth.models import User\n\n release_all_counts = release.objects.all().count()\n user_counts = User.objects.all().count()\n project_counts = projectinfo.objects.filter(isinit=1).count() \n\n request.session['release_all_counts'] = release_all_counts\n request.session['user_counts'] = user_counts\n request.session['project_counts'] = project_counts\n\n #\n request.session['domain'] = request.META['HTTP_HOST']\n \n import django\n request.session['django_version'] = django.get_version()\n\n from django.db import connection\n cursor = connection.cursor()\n cursor.execute(\"SELECT VERSION()\")\n for i in cursor.fetchone():\n request.session['mysql_version'] = i\n\n request.session['server_ip'] = getserverip()\n\n #disk\n import statvfs\n import os\n vfs = os.statvfs(\"/\")\n available=vfs[statvfs.F_BAVAIL]*vfs[statvfs.F_BSIZE]/(1024*1024*1024)\n capacity=vfs[statvfs.F_BLOCKS]*vfs[statvfs.F_BSIZE]/(1024*1024*1024)\n\n request.session['disk_available'] = available \n request.session['disk_capacity'] = capacity \n\n return render(request,'index/index.html')\n\ndef getserverip():\n import socket\n try:\n csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n csock.connect(('192.168.6.3', 80))\n (addr, port) = csock.getsockname()\n csock.close()\n return addr\n except socket.error:\n return \"127.0.0.1\"\n\n","sub_path":"index/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"559191363","text":"from sejits_caffe.operations.relu import relu\nfrom cstructures.array import Array\nimport unittest\nimport numpy as np\n\n\nclass TestRelu(unittest.TestCase):\n def _check(self, actual, expected):\n np.testing.assert_allclose(actual, expected, rtol=1e-5)\n\n def test_simple(self):\n bottom = Array.rand(256, 256).astype(np.float32) * 255\n actual = Array.zeros(bottom.shape, np.float32)\n relu(bottom, bottom, actual, 0.0)\n expected = np.clip(bottom, 0.0, float('inf'))\n self._check(actual, expected)\n\n def test_nonzero_slope(self):\n bottom = Array.rand(256, 256).astype(np.float32) * 255\n actual = Array.zeros(bottom.shape, np.float32)\n relu(bottom, bottom, actual, 2.4)\n expected = np.clip(bottom, 0.0, float('inf')) + \\\n 2.4 * np.clip(bottom, float('-inf'), 0.0)\n self._check(actual, expected)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/operations/test_relu.py","file_name":"test_relu.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"92772422","text":"# -*- coding: utf-8 -*-\n# Copyright 2004 Tech-Receptives\n# Copyright 2016 LasLabs Inc.\n# License GPL-3.0 or later (http://www.gnu.org/licenses/gpl.html).\n\nfrom openerp import _, api, fields, models\nfrom openerp.exceptions import ValidationError\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\n\nclass MedicalPatient(models.Model):\n _name = 'medical.patient'\n _description = 'Medical Patient'\n _inherits = {'res.partner': 'partner_id'}\n\n age = fields.Char(\n compute='_compute_age',\n )\n identification_code = fields.Char(\n string='Internal Identification',\n help='Patient identifier provided by the health center'\n ' (Different from the social security number)',\n )\n general_info = fields.Text(\n string='General Information',\n )\n dob = fields.Date(\n string='Date of Birth',\n )\n dod = fields.Datetime(\n string='Deceased Date',\n )\n active = fields.Boolean(\n default=True,\n )\n deceased = fields.Boolean(\n compute='_compute_deceased',\n store=True,\n help='Automatically True if deceased date is set',\n )\n partner_id = fields.Many2one(\n string='Related Partner',\n comodel_name='res.partner',\n required=True,\n ondelete='cascade',\n index=True,\n )\n gender = fields.Selection(\n [\n ('m', 'Male'),\n ('f', 'Female'),\n ],\n )\n medical_center_id = fields.Many2one(\n string='Medical Center',\n comodel_name='res.partner',\n domain=\"[('is_institution', '=', True)]\",\n )\n marital_status = fields.Selection(\n [\n ('s', 'Single'),\n ('m', 'Married'),\n ('w', 'Widowed'),\n ('d', 'Divorced'),\n ('x', 'Separated'),\n ('z', 'law marriage'),\n ],\n )\n is_pregnant = fields.Boolean(\n help='Check if the patient is pregnant',\n )\n\n @api.multi\n def _compute_age(self):\n now = datetime.now()\n for rec_id in self:\n if rec_id.dob:\n dob = fields.Datetime.from_string(rec_id.dob)\n\n if rec_id.deceased:\n dod = fields.Datetime.from_string(rec_id.dod)\n delta = relativedelta(dod, dob)\n deceased = _(' (deceased)')\n else:\n delta = relativedelta(now, dob)\n deceased = ''\n years_months_days = '%s%s %s%s %s%s%s' % (\n delta.years, _('y'),\n delta.months, _('m'),\n delta.days, _('d'), deceased\n )\n else:\n years_months_days = _('No DoB!')\n rec_id.age = years_months_days\n\n @api.multi\n @api.constrains('is_pregnant', 'gender')\n def _check_is_pregnant(self):\n for rec_id in self:\n if rec_id.is_pregnant and rec_id.gender != 'f':\n raise ValidationError(_(\n 'Invalid selection - males cannot be pregnant.',\n ))\n\n @api.multi\n def action_invalidate(self):\n for rec_id in self:\n rec_id.active = False\n rec_id.partner_id.active = False\n\n @api.multi\n @api.depends('dod')\n def _compute_deceased(self):\n for rec_id in self:\n rec_id.deceased = bool(rec_id.dod)\n\n @api.model\n @api.returns('self', lambda value: value.id)\n def create(self, vals):\n vals['is_patient'] = True\n if not vals.get('identification_code'):\n sequence = self.env['ir.sequence'].next_by_code('medical.patient')\n vals['identification_code'] = sequence\n return super(MedicalPatient, self).create(vals)\n","sub_path":"medical_patient.py","file_name":"medical_patient.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"438711465","text":"# %% module imports\nimport argparse\nimport logging\nimport os\nimport warnings\n\nimport jinja2\n# Import the package.\nimport lts_array\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom obspy import UTCDateTime\nfrom obspy.clients.fdsn import Client, header\nfrom obspy.clients.earthworm import Client as WClient\nfrom obspy.geodetics.base import gps2dist_azimuth\nfrom obspy.core import Stream\n\n# And the config file\nimport config\n\n# set up logging\nlogging.basicConfig(filename = \"/var/log/array_processing.log\")\nlogging.getLogger().setLevel(logging.INFO)\n\n\ndef get_volcano_backazimuth(latlist, lonlist, volcanoes):\n lon0 = np.mean(lonlist)\n lat0 = np.mean(latlist)\n for volc in volcanoes:\n if 'back_azimuth' not in volc:\n tmp = gps2dist_azimuth(lat0, lon0, volc['v_lat'], volc['v_lon'])\n volc['back_azimuth'] = tmp[1]\n return volcanoes\n\n\nif __name__ == \"__main__\":\n # Get command line arguments (if any)\n parser = argparse.ArgumentParser()\n # Use strftime so we always get a string out of here.\n # Default if no arguments given is current time\n parser.add_argument('T0', nargs='*',\n default=[(UTCDateTime.utcnow()).strftime('%Y-%m-%dT%H:%M:00Z'), ])\n\n args = parser.parse_args()\n if len(args.T0) > 2:\n warnings.warn('Too many input arguments')\n parser.print_usage()\n exit(1)\n\n ENDTIME = ''.join(args.T0) # Time given, or current time\n ENDTIME = UTCDateTime(ENDTIME) # Convert to a UTC date/time object\n\n # round down to the nearest 10-minute\n ENDTIME = ENDTIME.replace(minute=ENDTIME.minute - (ENDTIME.minute % 10),\n second=0,\n microsecond=0)\n\n STARTTIME = ENDTIME - config.duration\n\n # %% Read in and filter data\n # Array Parameters\n LOC = '*'\n\n # Filter limits\n FMIN = config.f1\n FMAX = config.f2\n\n # Processing parameters\n WINLEN = config.window_length\n WINOVER = config.overlap\n\n all_nets = []\n all_stations = {}\n for net in config.arrays:\n NET = net['network']\n NETDISP = net['display name']\n all_nets.append(NETDISP)\n all_stations[NETDISP] = []\n for array in net['arrays']:\n STA = array['id']\n STANAME = array['Name']\n all_stations[NETDISP].append(STANAME)\n\n CHAN = array['channel']\n\n # LTS alpha parameter - subset size\n ALPHA = array['Alpha']\n\n logging.info(f'Reading in data from Winston for station {STA}')\n wclient = WClient(config.winston_address, config.winston_port)\n # Get Availability\n try:\n avail = wclient.get_availability(NET, STA, channel = CHAN)\n except Exception:\n logging.error(f\"Unable to get location info for station {STA}\")\n continue\n\n locs = [x[2] for x in avail]\n st = Stream()\n for loc in locs:\n try:\n # Not sure why we can't use a wildcard for loc, but it\n # doesn't seem to work (at least, not for DLL), so we loop.\n tr = wclient.get_waveforms(NET, STA, loc, CHAN,\n STARTTIME - 2 * config.taper_val,\n ENDTIME + 2 * config.taper_val,\n cleanup=True)\n st += tr\n except Exception:\n continue\n\n if not st:\n logging.error(f\"No data retrieved for {STA}\")\n continue\n\n st.merge(fill_value='latest')\n st.trim(STARTTIME - 2 * config.taper_val, ENDTIME + 2 * config.taper_val, pad='true', fill_value=0)\n st.sort()\n logging.info(st)\n\n # print('Removing sensitivity...')\n # st.remove_sensitivity()\n\n stf = st.copy()\n stf.detrend('demean')\n stf.taper(max_percentage=None, max_length=config.taper_val)\n stf.filter(\"bandpass\", freqmin=FMIN, freqmax=FMAX, corners=2, zerophase=True)\n st.trim(STARTTIME, ENDTIME, pad='true', fill_value=0)\n\n # %% Get inventory and lat/lon info\n client = Client(\"IRIS\")\n try:\n inv = client.get_stations(network=NET, station=STA, channel=CHAN,\n location=LOC, starttime=STARTTIME,\n endtime=ENDTIME, level='channel')\n except header.FDSNNoDataException:\n logging.error(f\"No lat/lon info retrieved for {STA}\")\n continue\n\n latlist = []\n lonlist = []\n staname = []\n for network in inv:\n for station in network:\n for channel in station:\n latlist.append(channel.latitude)\n lonlist.append(channel.longitude)\n staname.append(channel.code)\n\n # Get element rijs\n rij = lts_array.getrij(latlist, lonlist)\n\n # %% Run LTS array processing\n try:\n lts_vel, lts_baz, t, mdccm, stdict, sigma_tau = lts_array.ltsva(stf, rij, WINLEN, WINOVER, ALPHA)\n except:\n logging.error(\"Error processing data. Moving on.\")\n continue\n\n # %% Plotting\n try:\n fig, axs = lts_array.lts_array_plot(stf, lts_vel, lts_baz, t, mdccm, stdict)\n except UnboundLocalError:\n logging.error(f\"Unable to generate plots for {STA}\")\n continue\n\n # NOTE: these are implementation dependant, and could easily change.\n backazimuth_axis = axs[2]\n velocity_axis = axs[1]\n\n ################ Velocity Graph ##########################\n # Tweak the y axis tick marks for the velocity plot\n v_ystart, v_yend = velocity_axis.get_ylim()\n velocity_axis.yaxis.set_ticks(np.arange(v_ystart, 0.55, 0.05))\n velocity_axis.set_ylim(top = 0.5)\n\n # Shade the background for the velocity area of interest\n max_vel = 0.45\n min_vel = 0.3\n velocity_axis.axhspan(min_vel, max_vel, color = \"gray\", zorder = -1,\n alpha=0.25)\n\n ##################### Pressure Graph ##################\n # Use thinner lines on the pressure graph\n for line in axs[0].lines:\n line.set_linewidth(0.6)\n\n ####################### X Axis Formatting #####################\n # Format the date/time stuff\n axs[-1].set_xlabel(f'UTC Time ({ENDTIME.strftime(\"%d %B %Y\")})')\n axs[-1].xaxis.set_major_formatter(mdates.DateFormatter(\"%H:%M\"))\n\n ######################### Backazimuth Plot #####################\n # Add volcano azimuth lines to plots\n volcanoes = get_volcano_backazimuth(latlist, lonlist,\n array['volcano'])\n\n # decide where to put the volcano labels (horizontal position)\n # Probably overkill, I suspect we could just use start+fixed offset\n # But since I don't actually know how \"long\" these graphs are, I'll\n # calculate for now\n limits = backazimuth_axis.get_xlim()\n # 25 is completly arbitrary, but it seems to work nicely enough.\n label_left = limits[0] + (((limits[1] - limits[0]) / 25))\n\n volc_azimuth_markers = []\n for volc in volcanoes:\n # Add the line\n volc_azimuth_markers.append(backazimuth_axis.axhline(volc['back_azimuth'],\n ls = '--',\n color = \"gray\",\n zorder = -1))\n\n # And the name\n volc_azimuth_markers.append(backazimuth_axis.text(label_left,\n volc['back_azimuth'] - 6,\n volc['name'],\n bbox={'facecolor': 'white',\n 'edgecolor': 'white',\n 'pad': 0},\n fontsize=8,\n style='italic',\n zorder=10))\n\n #################### Plot Layout ##################################\n # Replace the graph title\n for txt in axs[0].texts:\n txt.remove()\n\n title = fig.text(.5, 0.99, f\"{STANAME} Infrasound Array\",\n horizontalalignment = 'center',\n verticalalignment = 'top')\n\n # Tighten up the layout\n plt.tight_layout()\n plt.subplots_adjust(top = 0.97, right = .90, bottom = 0.11)\n\n # Adjust the colorbar positions to not cut off\n # FIXME: This is ugly, but works because the two axes are always\n # added in the same order.\n # The first one is the vertical bar, the second the horizontal.\n # Would be better if we had some positive indication of which was which.\n vertical_colorbar = None\n horizontal_bar = None\n\n for axis in fig.axes:\n if axis not in axs:\n # This is a colorbar\n pos = axis.get_position().get_points().flatten()\n if vertical_colorbar is None:\n # Vertical color bar. Move to the left.\n vertical_colorbar = axis\n pos[0] -= .03\n pos[1] += .01\n pos[2] = .02\n pos[3] -= 0.05\n else:\n # This is the horizontal color bar. Nudge it up (and to the left).\n horizontal_bar = axis\n pos[0] -= .02\n pos[1] += .015\n pos[2] -= 0.1\n pos[3] = .02\n\n # Make sure this one only has integer tick marks\n _, x_max = axis.get_xlim()\n axis.xaxis.set_ticks(np.arange(1, x_max))\n\n axis.set_position(pos)\n else:\n # Move the x axis ticks inside the plot\n axis.tick_params(axis = 'x', direction = \"in\")\n\n ###################################################################\n\n # Generate the save path\n d2 = os.path.join(config.out_web_dir, NETDISP, STANAME,\n str(ENDTIME.year),\n '{:03d}'.format(ENDTIME.julday))\n\n # Just for good measure, make sure it is the \"real\" path.\n # Probably completly paranoid and unnecessary.\n d2 = os.path.realpath(d2)\n\n # Make sure directory exists\n os.makedirs(d2, exist_ok = True)\n\n filename = os.path.join(d2, f\"{STANAME}_{ENDTIME.strftime('%Y%m%d-%H%M')}.png\")\n thumbnail_name = os.path.join(d2, f\"{STANAME}_{ENDTIME.strftime('%Y%m%d-%H%M')}_thumb.png\")\n\n # Finally, save the full size image\n fig.savefig(filename, dpi = 72, format = 'png')\n\n # Reconfigure plots for thumbnails\n # Remove the volcano back-azimuth stuff\n for volc in volc_azimuth_markers:\n volc.remove()\n\n # and the plot title\n title.remove()\n\n # Resize down to thumbnail size and spacing\n fig.set_size_inches(4.0, 5.5)\n plt.subplots_adjust(left=0, right=0.99, bottom= 0.01, top=1.0,\n wspace=0, hspace=0)\n\n for axis in fig.axes:\n if axis not in axs:\n axis.remove() # remove colorbars\n else:\n # Remove tick marks and labels\n axis.tick_params(axis = 'both', which = 'both',\n bottom = False, top = False,\n labelbottom = False, left = False,\n right = False, labelleft = False)\n\n # Remove text labels\n for txt in axis.texts:\n txt.remove()\n\n colorbar_axes = [x for x in fig.axes if x not in axs]\n for axis in colorbar_axes:\n axis.remove()\n\n # Lower DPI, but larger image size = smaller dots\n fig.savefig(thumbnail_name, dpi = 36, format = 'png')\n\n # Write out the new HTML file\n script_path = os.path.dirname(__file__)\n\n with open(os.path.join(script_path, 'index.template'), 'r') as f:\n template = jinja2.Template(f.read())\n\n html = template.render(networks = all_nets, stations = all_stations)\n with open(os.path.join(config.out_web_dir, 'index.html'), 'w') as f:\n f.write(html)\n","sub_path":"new_array_processing.py","file_name":"new_array_processing.py","file_ext":"py","file_size_in_byte":13554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"267803190","text":"from core.celery.tasks import add\r\n\r\nresult = add.delay(10, 12)\r\nprint(result.result)\r\n\r\n\r\ndef on_raw_message(body):\r\n print(body['result'])\r\n\r\nr = add.apply_async((4,4), retry=False)\r\nr.get(on_message=on_raw_message, propagate=False)\r\n","sub_path":"celeryapp/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"521930518","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom backend.helpers import aggregate_label\nfrom backend.models import Article\nfrom backend.xml_parsing.postgre_to_xml import database_to_xml\n\n\nclass Command(BaseCommand):\n help = 'Extracts all labeled articles from the database as XML files'\n\n def add_arguments(self, parser):\n parser.add_argument('path', help=\"Path to an empty directory where the articles should be stored.\")\n\n def handle(self, *args, **options):\n path = options['path']\n try:\n articles = Article.objects.all()\n for a in articles:\n if a.labeled['fully_labeled'] == 1:\n labels = []\n authors = []\n for s_id in range(len(a.sentences['sentences'])):\n sent_label, sent_authors, consensus = aggregate_label(a, s_id)\n labels.append(sent_label)\n authors.append(sent_authors)\n output_xml = database_to_xml(a, labels, authors)\n with open(f'{path}/article_{a.id}.xml', 'w') as f:\n f.write(output_xml)\n\n except IOError:\n raise CommandError('Articles could not be extracted. IO Error.')\n","sub_path":"activelearning/backend/management/commands/extractall.py","file_name":"extractall.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"559394415","text":"'''\ncustomer spec: gather yearly rainfall data; output high/low/average\n monthly rainfall; reject negative data entries\nadded feature: display multiple months in case months tie for highest\n or lowest rainfall\n'''\n\n#main prog as func\ndef assignment07():\n #assign strings to list for user-friendly prompt\n months=['Jan','Feb','March','April','May','June','July',\n 'Aug','Sept','Oct','Nov','Dec']\n records=[]\n print('Enter inches of rainfall for each month as prompted.\\n')\n #loop for 12 entries; validate input\n for m in months:\n data=-1\n while data<0:\n try:\n data=float(input(m+': '))\n #cause deliberate exception to streamline exception handling\n if data<0: raise ValueError \n records.append(data)\n #handle negative entries & alpha entries\n except ValueError:\n print('Invalid input for ',end='')\n #display results\n print('\\nAverage monthly rainfall:',format(sum(records)/12,'.2f'),'in')\n print('\\tYearly rainfall:',format(sum(records),'.2f'),'in')\n print('Month(s) with most rain: ',end='')\n #iterate across records/months in parallel & display max rainfall month(s)\n for value in range(len(records)):\n if records[value]==max(records):\n print(months[value],end=' ')\n print('\\nMonth(s) with least rain: ',end='')\n #iterate across records/months in parallel & display min rainfall month(s)\n for value in range(len(records)):\n if records[value]==min(records):\n print(months[value],end=' ')\n\n#run prog\nassignment07()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Completed Assignments/Wurster_A7.py","file_name":"Wurster_A7.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"435610205","text":"# coding=utf-8\nimport numpy as np\nfrom layers import *\n\n\nclass FullyConnectNet(object):\n\t\"\"\"docstring for ClassName\"\"\"\n\tdef __init__(self, layers=[], input_dim=10, reg=0.5, mode='train', weight_scale=1):\n\n\t\t# 此处接受layers(list or tuple)由用户自己定义多少层,每层多少个神经元\n\n\t\tself.layers = layers\n\t\tself.input_dim = input_dim\n\t\tself.reg = reg\n\t\tself.mode = mode\n\t\tself.weight_scale = weight_scale\n\n\t\t# 初始化各层参数\n\n\t\tself.params = {}\n\n\t\tfor idx, neurons in enumerate(layers):\n\n\t\t\tif idx == 0:\n\n\t\t\t\tself.params['W1'] = self.weight_scale * np.random.randn(input_dim, neurons)\n\n\t\t\telse:\n\n\t\t\t\tself.params['W%d'%(idx + 1)] = self.weight_scale * np.random.randn(layers[idx - 1], neurons)\n\n\t\t\tself.params['b%d'%(idx + 1)] = np.zeros(neurons)\n\n\n\t# 这里最后一层用softmax计算loss, 在参数为self.params时, current mini-batch计算出的损失和梯度\n\n\tdef loss(self, mini_batch_x, mini_batch_y=None):\n\n\t\t# 下面逐层计算前向传播及反向传播\n\t\tlayer_counts = len(self.layers)\n\n\t\tlayer_out = None\n\t\tlayer_cache = None\n\t\tcache = []\n\n\t\tregulation = 0\n\n\t\tfor layer in np.arange(layer_counts):\n\n\t\t\t# 如果是第一层\n\t\t\tif layer == 0:\n\n\t\t\t\tlayer_out, layer_cache = affine_relu_forward(mini_batch_x, self.params['W1'], self.params['b1'])\n\n\t\t\t# 如果是最后一层\n\t\t\telif layer == layer_counts - 1:\n\n\t\t\t\tlayer_out, layer_cache = affine_forward(layer_out, self.params['W%d'%(layer + 1)], self.params['b%d'%(layer + 1)])\n\t\t\telse:\n\n\t\t\t\tlayer_out, layer_cache = affine_relu_forward(layer_out, self.params['W%d'%(layer + 1)], self.params['b%d'%(layer + 1)])\n\n\t\t\tcache.append(layer_cache)\n\n\t\t# 如果是test mode,\n\t\t# if self.mode == 'test':\n\t\tif mini_batch_y is None:\n\t\t\treturn layer_out\n\n\t\t# print(layer_out)\n\n\t\t# 计算loss并且开���反向传播\n\n\t\tdW = None\n\n\t\tdb = None\n\n\t\tgrads = {}\n\n\t\tloss, dlayer_out = softmax_loss(layer_out, mini_batch_y)\n\n\t\tfor layer in range(layer_counts):\n\n\t\t\tregulation += np.sum(self.params['W%d'%(layer + 1)] ** 2)\n\n\t\tloss += 0.5 * self.reg * regulation\n\n\t\tfor layer in reversed(np.arange(layer_counts)):\n\n\t\t\tif layer == layer_counts - 1:\n\n\t\t\t\tdlayer_out, dW, db = affine_backward(dlayer_out, cache[layer])\n\n\t\t\telse:\n\n\t\t\t\tdlayer_out, dW, db = affine_relu_backward(dlayer_out, cache[layer])\n\n\t\t\tgrads['W%d'%(layer + 1)] = dW + self.reg * self.params['W%d'%(layer + 1)]\n\n\t\t\tgrads['b%d'%(layer + 1)] = db + self.reg * self.params['b%d'%(layer + 1)]\n\n\t\treturn loss, grads\n\n\tdef predict(self, X):\n\n\t\tlayer_counts = len(self.layers)\n\n\t\tlayer_out = None\n\n\t\tfor layer in np.arange(layer_counts):\n\n\t\t\t# 如果是第一层\n\t\t\tif layer == 0:\n\n\t\t\t\tlayer_out, _ = affine_relu_forward(X, self.params['W1'], self.params['b1'])\n\n\t\t\t# 如果是最后一层\n\t\t\telif layer == layer_counts - 1:\n\n\t\t\t\tlayer_out, _ = affine_forward(layer_out, self.params['W%d'%(layer + 1)], self.params['b%d'%(layer + 1)])\n\t\t\telse:\n\n\t\t\t\tlayer_out, _ = affine_relu_forward(layer_out, self.params['W%d'%(layer + 1)], self.params['b%d'%(layer + 1)])\n\n\t\treturn np.argmax(layer_out, axis=1)\n\t\t","sub_path":"fcnet.py","file_name":"fcnet.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"400960446","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport datetime\nimport json\nimport os\n\nfrom django.core.cache import cache\nfrom django.test import TestCase, RequestFactory\nfrom django.test.utils import override_settings\nfrom django.template import Template, Context\nfrom django.utils import translation\nfrom django.utils import timezone\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.core import mail\nfrom django.core.exceptions import PermissionDenied\nfrom django.contrib import messages\nfrom django.utils.translation import ugettext as _\nfrom django.utils.timezone import utc\nfrom django.utils.http import urlunquote\nfrom django.contrib.auth import get_user_model\n\nfrom ...category.models import Category\nfrom .. import utils\nfrom ..utils.forms import NestedModelChoiceField\nfrom ..utils.timezone import TIMEZONE_CHOICES\nfrom ..utils.decorators import moderator_required, administrator_required\nfrom ...user.utils.tokens import UserActivationTokenGenerator, UserEmailChangeTokenGenerator\nfrom ...user.utils.email import send_activation_email, send_email_change_email, sender\nfrom ...user.utils import email\nfrom ..tags import time as ttags_utils\nfrom ..tests import utils as test_utils\nfrom ..tags.messages import render_messages\n\nUser = get_user_model()\n\n\nclass UtilsTests(TestCase):\n\n def setUp(self):\n cache.clear()\n\n def test_render_form_errors(self):\n \"\"\"\n return form errors string\n \"\"\"\n class MockForm:\n non_field_errors = [\"error1\", ]\n hidden_fields = [{'errors': \"error2\", }, ]\n visible_fields = [{'errors': \"error3\", }, ]\n\n res = utils.render_form_errors(MockForm())\n lines = [line.strip() for line in res.splitlines()]\n self.assertEqual(\"\".join(lines), '
  • error1
  • error2
  • error3
')\n\n def test_json_response(self):\n \"\"\"\n return json_response\n \"\"\"\n res = utils.json_response()\n self.assertIsInstance(res, HttpResponse)\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res['Content-Type'], 'application/json')\n self.assertDictEqual(json.loads(res.content.decode('utf-8')), {})\n\n res = utils.json_response({\"foo\": \"bar\", })\n self.assertDictEqual(json.loads(res.content.decode('utf-8')), {\"foo\": \"bar\", })\n\n res = utils.json_response(status=404)\n self.assertEqual(res.status_code, 404)\n\n def test_mkdir_p(self):\n \"\"\"\n mkdir -p\n \"\"\"\n # Empty path should raise an exception\n self.assertRaises(OSError, utils.mkdir_p, \"\")\n\n # Try to create an existing dir should do nothing\n self.assertTrue(os.path.isdir(settings.BASE_DIR))\n utils.mkdir_p(settings.BASE_DIR)\n\n # Create path tree\n # setup\n path = os.path.join(settings.BASE_DIR, \"test_foo\")\n sub_path = os.path.join(path, \"bar\")\n self.assertFalse(os.path.isdir(sub_path))\n self.assertFalse(os.path.isdir(path))\n # test\n utils.mkdir_p(sub_path)\n self.assertTrue(os.path.isdir(sub_path))\n # clean up\n os.rmdir(sub_path)\n os.rmdir(path)\n\n def test_pushd(self):\n \"\"\"\n pushd bash like\n \"\"\"\n current_dir = {'dir': '.'}\n\n class MockOS:\n @classmethod\n def chdir(cls, new_dir):\n current_dir['dir'] = new_dir\n\n @classmethod\n def getcwd(cls):\n return current_dir['dir']\n\n org_os, utils.os = utils.os, MockOS\n try:\n with utils.pushd('./my_dir'):\n self.assertEqual(current_dir['dir'], './my_dir')\n\n with utils.pushd('./my_dir/my_other_dir'):\n self.assertEqual(current_dir['dir'], './my_dir/my_other_dir')\n\n self.assertEqual(current_dir['dir'], './my_dir')\n\n self.assertEqual(current_dir['dir'], '.')\n finally:\n utils.os = org_os\n\n\n# Mock out datetime in some tests so they don't fail occasionally when they\n# run too slow. Use a fixed datetime for datetime.now(). DST change in\n# America/Chicago (the default time zone) happened on March 11th in 2012.\n# Note: copy from django.contrib.humanize.tests.py\n\nnow = datetime.datetime(2012, 3, 9, 22, 30)\n\n\nclass MockDateTime(datetime.datetime):\n @classmethod\n def now(cls, tz=None):\n if tz is None or tz.utcoffset(now) is None:\n return now\n else:\n # equals now.replace(tzinfo=utc)\n return now.replace(tzinfo=tz) + tz.utcoffset(now)\n\n\nclass UtilsTemplateTagTests(TestCase):\n\n def test_shortnaturaltime(self):\n \"\"\"\"\"\"\n class naive(datetime.tzinfo):\n def utcoffset(self, dt):\n return None\n\n def render(date):\n t = Template('{% load spirit_tags %}'\n '{{ date|shortnaturaltime }}')\n return t.render(Context({'date': date, }))\n\n orig_humanize_datetime, ttags_utils.datetime = ttags_utils.datetime, MockDateTime\n try:\n with translation.override('en'):\n with override_settings(USE_TZ=True):\n self.assertEqual(render(now), \"now\")\n self.assertEqual(render(now.replace(tzinfo=naive())), \"now\")\n self.assertEqual(render(now.replace(tzinfo=utc)), \"now\")\n self.assertEqual(render(now - datetime.timedelta(seconds=1)), \"1s\")\n self.assertEqual(render(now - datetime.timedelta(minutes=1)), \"1m\")\n self.assertEqual(render(now - datetime.timedelta(hours=1)), \"1h\")\n self.assertEqual(render(now - datetime.timedelta(days=1)), \"8 Mar\")\n self.assertEqual(render(now - datetime.timedelta(days=69)), \"31 Dec '11\")\n\n # Tests it uses localtime\n # This is 2012-03-08HT19:30:00-06:00 in America/Chicago\n dt = datetime.datetime(2011, 3, 9, 1, 30, tzinfo=utc)\n\n # Overriding TIME_ZONE won't work when timezone.activate\n # was called in some point before (middleware)\n timezone.deactivate()\n\n with override_settings(TIME_ZONE=\"America/Chicago\"):\n self.assertEqual(render(dt), \"8 Mar '11\")\n finally:\n ttags_utils.datetime = orig_humanize_datetime\n\n def test_render_messages(self):\n \"\"\"\n Test messages grouped by level\n \"\"\"\n # TODO: test template rendering\n class MockMessage:\n def __init__(self, level, message):\n self.level = level\n self.tags = messages.DEFAULT_TAGS[level]\n self.message = message\n\n m1 = MockMessage(messages.constants.ERROR, 'error 1')\n m2 = MockMessage(messages.constants.ERROR, 'error 2')\n m3 = MockMessage(messages.constants.INFO, 'info 3')\n res = render_messages([m1, m2, m3])\n self.assertDictEqual(dict(res['messages_grouped']), {'error': [m1, m2],\n 'info': [m3, ]})\n\n def test_social_share(self):\n \"\"\"\n Test social share tags with unicode input\n \"\"\"\n t = Template('{% load spirit_tags %}'\n '{% get_facebook_share_url url=\"/á/foo bar/\" title=\"á\" %}'\n '{% get_twitter_share_url url=\"/á/foo bar/\" title=\"á\" %}'\n '{% get_gplus_share_url url=\"/á/foo bar/\" %}'\n '{% get_email_share_url url=\"/á/foo bar/\" title=\"á\" %}'\n '{% get_share_url url=\"/á/foo bar/\" %}')\n res = t.render(Context({'request': RequestFactory().get('/'), }))\n self.assertEqual(res.strip(), \"http://www.facebook.com/sharer.php?u=100&p%5Burl%5D=http%3A%2F%2Ftestserver\"\n \"%2F%25C3%25A1%2Ffoo%2520bar%2F&p%5Btitle%5D=%C3%A1\"\n \"https://twitter.com/share?url=http%3A%2F%2Ftestserver%2F%25C3%25A1%2F\"\n \"foo%2520bar%2F&text=%C3%A1\"\n \"https://plus.google.com/share?url=http%3A%2F%2Ftestserver%2F%25C3%25A1%2F\"\n \"foo%2520bar%2F\"\n \"mailto:?body=http%3A%2F%2Ftestserver%2F%25C3%25A1%2Ffoo%2520bar%2F\"\n \"&subject=%C3%A1&to=\"\n \"http://testserver/%C3%A1/foo%20bar/\")\n\n def test_social_share_twitter_length(self):\n \"\"\"\n Twitter allows up to 140 chars, takes 23 for urls (https)\n \"\"\"\n # so this unicode title when is *url-quoted* becomes really large, like 1000 chars large,\n # browsers support up to 2000 chars for an address, we should be fine.\n long_title = \"á\" * 150\n t = Template('{% load spirit_tags %}'\n '{% get_twitter_share_url url=\"/foo/\" title=long_title %}')\n res = t.render(Context({'request': RequestFactory().get('/'), 'long_title': long_title}))\n url = urlunquote(res.strip())\n self.assertEqual(len(url.split(\"text=\")[-1]) + 23, 139) # 140 for https\n\n\nclass UtilsFormsTests(TestCase):\n\n def test_nested_model_choise_form(self):\n \"\"\"\n NestedModelChoiceField\n \"\"\"\n Category.objects.all().delete()\n\n category = test_utils.create_category()\n category2 = test_utils.create_category()\n subcategory = test_utils.create_subcategory(category)\n field = NestedModelChoiceField(queryset=Category.objects.all(),\n related_name='category_set',\n parent_field='parent_id',\n label_field='title')\n self.assertSequenceEqual(list(field.choices), [('', '---------'),\n (3, '%s' % category.title),\n (5, '--- %s' % subcategory.title),\n (4, '%s' % category2.title)])\n\n\nclass UtilsTimezoneTests(TestCase):\n\n def test_timezone(self):\n \"\"\"\n Timezones, requires pytz\n \"\"\"\n for tz, text in TIMEZONE_CHOICES:\n timezone.activate(tz)\n\n self.assertRaises(Exception, timezone.activate, \"badtimezone\")\n\n\nclass UtilsDecoratorsTests(TestCase):\n\n def setUp(self):\n cache.clear()\n self.user = test_utils.create_user()\n\n def test_moderator_required(self):\n \"\"\"\n Tests the user is logged in and is also a moderator\n \"\"\"\n @moderator_required\n def view(req):\n pass\n\n req = RequestFactory().get('/')\n\n req.user = AnonymousUser()\n self.assertIsInstance(view(req), HttpResponseRedirect)\n\n req.user = self.user\n req.user.st.is_moderator = False\n self.assertRaises(PermissionDenied, view, req)\n\n req.user.st.is_moderator = True\n self.assertIsNone(view(req))\n\n def test_administrator_required(self):\n \"\"\"\n Tests the user is logged in and is also an admin\n \"\"\"\n @administrator_required\n def view(req):\n pass\n\n req = RequestFactory().get('/')\n\n req.user = AnonymousUser()\n self.assertIsInstance(view(req), HttpResponseRedirect)\n\n req.user = self.user\n req.user.st.is_administrator = False\n self.assertRaises(PermissionDenied, view, req)\n\n req.user.st.is_administrator = True\n self.assertIsNone(view(req))\n\n\nclass UtilsUserTests(TestCase):\n\n def setUp(self):\n cache.clear()\n self.user = test_utils.create_user()\n\n def test_user_activation_token_generator(self):\n \"\"\"\n Validate if user can be activated\n \"\"\"\n self.user.st.is_verified = False\n\n activation_token = UserActivationTokenGenerator()\n token = activation_token.generate(self.user)\n self.assertTrue(activation_token.is_valid(self.user, token))\n self.assertFalse(activation_token.is_valid(self.user, \"bad token\"))\n\n # Invalid after verification\n self.user.st.is_verified = True\n self.assertFalse(activation_token.is_valid(self.user, token))\n\n # Invalid for different user\n user2 = test_utils.create_user()\n self.assertFalse(activation_token.is_valid(user2, token))\n\n def test_user_email_change_token_generator(self):\n \"\"\"\n Email change\n \"\"\"\n new_email = \"footoken@bar.com\"\n email_change_token = UserEmailChangeTokenGenerator()\n token = email_change_token.generate(self.user, new_email)\n self.assertTrue(email_change_token.is_valid(self.user, token))\n self.assertFalse(email_change_token.is_valid(self.user, \"bad token\"))\n\n # get new email\n self.assertTrue(email_change_token.is_valid(self.user, token))\n self.assertEqual(email_change_token.get_email(), new_email)\n\n # Invalid for different user\n user2 = test_utils.create_user()\n self.assertFalse(email_change_token.is_valid(user2, token))\n\n # Invalid after email change\n self.user.email = \"email_changed@bar.com\"\n self.assertFalse(email_change_token.is_valid(self.user, token))\n\n def test_user_activation_email(self):\n \"\"\"\n Send activation email\n \"\"\"\n self._monkey_sender_called = False\n\n def monkey_sender(request, subject, template_name, context, email):\n self.assertEqual(request, req)\n self.assertEqual(email, [self.user.email, ])\n\n activation_token = UserActivationTokenGenerator()\n token = activation_token.generate(self.user)\n self.assertDictEqual(context, {'token': token, 'user_id': self.user.pk})\n\n self.assertEqual(subject, _(\"User activation\"))\n self.assertEqual(template_name, 'spirit/user/activation_email.html')\n\n self._monkey_sender_called = True\n\n req = RequestFactory().get('/')\n\n org_sender, email.sender = email.sender, monkey_sender\n try:\n send_activation_email(req, self.user)\n self.assertTrue(self._monkey_sender_called)\n finally:\n email.sender = org_sender\n\n def test_user_activation_email_complete(self):\n \"\"\"\n Integration test\n \"\"\"\n req = RequestFactory().get('/')\n send_activation_email(req, self.user)\n self.assertEquals(len(mail.outbox), 1)\n\n def test_email_change_email(self):\n \"\"\"\n Send change email\n \"\"\"\n self._monkey_sender_called = False\n\n def monkey_sender(request, subject, template_name, context, email):\n self.assertEqual(request, req)\n self.assertEqual(email, [self.user.email, ])\n\n change_token = UserEmailChangeTokenGenerator()\n token = change_token.generate(self.user, new_email)\n self.assertDictEqual(context, {'token': token, })\n\n self.assertEqual(subject, _(\"Email change\"))\n self.assertEqual(template_name, 'spirit/user/email_change_email.html')\n\n self._monkey_sender_called = True\n\n req = RequestFactory().get('/')\n new_email = \"newfoobar@bar.com\"\n\n org_sender, email.sender = email.sender, monkey_sender\n try:\n send_email_change_email(req, self.user, new_email)\n self.assertTrue(self._monkey_sender_called)\n finally:\n email.sender = org_sender\n\n def test_email_change_email_complete(self):\n \"\"\"\n Integration test\n \"\"\"\n req = RequestFactory().get('/')\n send_email_change_email(req, self.user, \"foo@bar.com\")\n self.assertEquals(len(mail.outbox), 1)\n\n def test_sender(self):\n \"\"\"\n Base email sender\n \"\"\"\n class SiteMock:\n name = \"foo\"\n domain = \"bar.com\"\n\n def monkey_get_current_site(request):\n return SiteMock\n\n def monkey_render_to_string(template, data):\n self.assertEquals(template, template_name)\n self.assertDictEqual(data, {'user_id': self.user.pk,\n 'token': token,\n 'site_name': SiteMock.name,\n 'domain': SiteMock.domain,\n 'protocol': 'https' if req.is_secure() else 'http'})\n return \"email body\"\n\n req = RequestFactory().get('/')\n token = \"token\"\n subject = SiteMock.name\n template_name = \"template.html\"\n context = {'user_id': self.user.pk, 'token': token}\n\n org_site, email.get_current_site = email.get_current_site, monkey_get_current_site\n org_render_to_string, email.render_to_string = email.render_to_string, monkey_render_to_string\n try:\n sender(req, subject, template_name, context, [self.user.email, ])\n finally:\n email.get_current_site = org_site\n email.render_to_string = org_render_to_string\n\n self.assertEquals(len(mail.outbox), 1)\n self.assertEquals(mail.outbox[0].subject, SiteMock.name)\n self.assertEquals(mail.outbox[0].body, \"email body\")\n self.assertEquals(mail.outbox[0].from_email, \"foo \")\n self.assertEquals(mail.outbox[0].to, [self.user.email, ])\n","sub_path":"spirit/core/tests/tests_utils.py","file_name":"tests_utils.py","file_ext":"py","file_size_in_byte":17681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"133180592","text":"#!/usr/bin/env python3\nfrom glob import glob\n\ndirec = glob('./*.txt')\nBLAST_dict = {}\n\nfor file in direc:\n files = open(file, \"r\")\n for line in files:\n line_strip = line.strip()\n if line_strip.startswith('#'):\n continue\n else:\n BLAST_dict[file] = line_strip.split('\\t')\n\nfor key,value in BLAST_dict.items():\n print(key,\" - \", \"\\n Percent ID:\", value[2], \"\\n Alignment Length:\", value[3], \"\\n E-Value:\", value[10], \"\\n Query Length:\", int(value[7])-int(value[6]))\n","sub_path":"ProblemSet13/BLAST_Parser.py","file_name":"BLAST_Parser.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"414429249","text":"import logging\nimport numpy as np\nfrom typing import Callable, Dict, Optional, Union, Tuple\nfrom alibi_detect.utils.frameworks import has_pytorch, has_tensorflow\n\nif has_pytorch:\n from alibi_detect.cd.pytorch.mmd import MMDDriftTorch\n\nif has_tensorflow:\n from alibi_detect.cd.tensorflow.mmd import MMDDriftTF\n\nlogger = logging.getLogger(__name__)\n\n\nclass MMDDrift:\n def __init__(\n self,\n x_ref: Union[np.ndarray, list],\n backend: str = 'tensorflow',\n p_val: float = .05,\n preprocess_x_ref: bool = True,\n update_x_ref: Optional[Dict[str, int]] = None,\n preprocess_fn: Optional[Callable] = None,\n kernel: Callable = None,\n sigma: Optional[np.ndarray] = None,\n configure_kernel_from_x_ref: bool = True,\n n_permutations: int = 100,\n device: Optional[str] = None,\n input_shape: Optional[tuple] = None,\n data_type: Optional[str] = None\n ) -> None:\n \"\"\"\n Maximum Mean Discrepancy (MMD) data drift detector using a permutation test.\n\n Parameters\n ----------\n x_ref\n Data used as reference distribution.\n backend\n Backend used for the MMD implementation.\n p_val\n p-value used for the significance of the permutation test.\n preprocess_x_ref\n Whether to already preprocess and store the reference data.\n update_x_ref\n Reference data can optionally be updated to the last n instances seen by the detector\n or via reservoir sampling with size n. For the former, the parameter equals {'last': n} while\n for reservoir sampling {'reservoir_sampling': n} is passed.\n preprocess_fn\n Function to preprocess the data before computing the data drift metrics.\n kernel\n Kernel used for the MMD computation, defaults to Gaussian RBF kernel.\n sigma\n Optionally set the GaussianRBF kernel bandwidth. Can also pass multiple bandwidth values as an array.\n The kernel evaluation is then averaged over those bandwidths.\n configure_kernel_from_x_ref\n Whether to already configure the kernel bandwidth from the reference data.\n n_permutations\n Number of permutations used in the permutation test.\n device\n Device type used. The default None tries to use the GPU and falls back on CPU if needed.\n Can be specified by passing either 'cuda', 'gpu' or 'cpu'. Only relevant for 'pytorch' backend.\n input_shape\n Shape of input data.\n data_type\n Optionally specify the data type (tabular, image or time-series). Added to metadata.\n \"\"\"\n super().__init__()\n\n backend = backend.lower()\n if backend == 'tensorflow' and not has_tensorflow or backend == 'pytorch' and not has_pytorch:\n raise ImportError(f'{backend} not installed. Cannot initialize and run the '\n f'MMDDrift detector with {backend} backend.')\n elif backend not in ['tensorflow', 'pytorch']:\n raise NotImplementedError(f'{backend} not implemented. Use tensorflow or pytorch instead.')\n\n kwargs = locals()\n args = [kwargs['x_ref']]\n pop_kwargs = ['self', 'x_ref', 'backend', '__class__']\n [kwargs.pop(k, None) for k in pop_kwargs]\n\n if kernel is None:\n if backend == 'tensorflow':\n from alibi_detect.utils.tensorflow.kernels import GaussianRBF\n else:\n from alibi_detect.utils.pytorch.kernels import GaussianRBF # type: ignore\n kwargs.update({'kernel': GaussianRBF})\n\n if backend == 'tensorflow' and has_tensorflow:\n kwargs.pop('device', None)\n self._detector = MMDDriftTF(*args, **kwargs) # type: ignore\n else:\n self._detector = MMDDriftTorch(*args, **kwargs) # type: ignore\n self.meta = self._detector.meta\n\n def predict(self, x: Union[np.ndarray, list], return_p_val: bool = True, return_distance: bool = True) \\\n -> Dict[Dict[str, str], Dict[str, Union[int, float]]]:\n \"\"\"\n Predict whether a batch of data has drifted from the reference data.\n\n Parameters\n ----------\n x\n Batch of instances.\n return_p_val\n Whether to return the p-value of the permutation test.\n return_distance\n Whether to return the MMD metric between the new batch and reference data.\n\n Returns\n -------\n Dictionary containing 'meta' and 'data' dictionaries.\n 'meta' has the model's metadata.\n 'data' contains the drift prediction and optionally the p-value, threshold and MMD metric.\n \"\"\"\n return self._detector.predict(x, return_p_val, return_distance)\n\n def score(self, x: Union[np.ndarray, list]) -> Tuple[float, float, np.ndarray]:\n \"\"\"\n Compute the p-value resulting from a permutation test using the maximum mean discrepancy\n as a distance measure between the reference data and the data to be tested.\n\n Parameters\n ----------\n x\n Batch of instances.\n\n Returns\n -------\n p-value obtained from the permutation test, the MMD^2 between the reference and test set\n and the MMD^2 values from the permutation test.\n \"\"\"\n return self._detector.score(x)\n","sub_path":"alibi_detect/cd/mmd.py","file_name":"mmd.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"35103233","text":"class Node: \n\tdef __init__(self,value):\n\t\tself.left=None\n\t\tself.right=None\n\t\tself.key=value\n#fight with worst case first in recursion terminology\ndef insert(r,n):\n\tif(r!=None):\n\t\tif(r.key pd.Timestamp(end_date):\n print(\"Starting date must be greater than ending date\")\n raise Exception(\"Invalid dates\")\n\n def _check_zones(self, zones):\n \"\"\"Test zones.\n\n :param list zones: geographical zones.\n :raise Exception: if zone(s) are invalid.\n \"\"\"\n possible = list(self.grid.id2zone.values())\n if \"Western\" in self.interconnect:\n possible += [\"California\", \"Western\"]\n if \"Texas\" in self.interconnect:\n possible += [\"Texas\"]\n if \"Eastern\" in self.interconnect:\n possible += [\"Eastern\"]\n if self.interconnect == [\"Eastern\", \"Western\", \"Texas\"]:\n possible += [\"USA\"]\n for z in zones:\n if z not in possible:\n print(\"%s is incorrect. Possible zones are: %s\" % (z, possible))\n raise Exception(\"Invalid zone(s)\")\n\n def _check_resources(self, resources):\n \"\"\"Test resources.\n\n :param list resources: type of generators.\n :raise Exception: if resource(s) are invalid.\n \"\"\"\n for r in resources:\n if r not in type2label.keys():\n print(\n \"%s is incorrect. Possible resources are: %s\"\n % (r, type2label.keys())\n )\n raise Exception(\"Invalid resource(s)\")\n\n @staticmethod\n def _check_tz(tz):\n \"\"\"Test time zone.\n\n :param str tz: time zone.\n :raise Exception: if time zone is invalid.\n \"\"\"\n possible = [\"utc\", \"US/Pacific\", \"local\"]\n if tz not in possible:\n print(\"%s is incorrect. Possible time zones are: %s\" % (tz, possible))\n raise Exception(\"Invalid time zone\")\n\n @staticmethod\n def _check_freq(freq):\n \"\"\"Test freq.\n\n :param str freq: frequency for re-sampling.\n :raise Exception: if frequency is invalid.\n \"\"\"\n possible = [\"H\", \"D\", \"W\", \"auto\"]\n if freq not in possible:\n print(\"%s is incorrect. Possible frequency are: %s\" % (freq, possible))\n raise Exception(\"Invalid frequency\")\n\n @staticmethod\n def _check_kind(kind):\n \"\"\"Test kind.\n\n :param str kind: type of analysis.\n :raise Exception: if analysis is invalid.\n \"\"\"\n possible = [\n \"chart\",\n \"stacked\",\n \"comp\",\n \"curtailment\",\n \"correlation\",\n \"variability\",\n \"yield\",\n ]\n if kind not in possible:\n print(\"%s is incorrect. Possible analysis are: %s\" % (kind, possible))\n raise Exception(\"Invalid Analysis\")\n\n def _convert_tz(self, df_utc):\n \"\"\"Convert data frame from UTC time zone to desired time zone.\n\n :param pandas.DataFrame df_utc: data frame with UTC timestamp as\n indices.\n :return: (*pandas.DataFrame*) -- data frame converted to desired\n time zone.\n \"\"\"\n df_new = df_utc.tz_convert(self.tz)\n df_new.index.name = self.tz\n\n return df_new\n\n def _set_frequency(self, start_date, end_date):\n \"\"\"Sets frequency for resampling.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n \"\"\"\n delta = pd.Timestamp(start_date) - pd.Timestamp(end_date)\n\n if delta.days < 7:\n self.freq = \"H\"\n elif 31 < delta.days < 180:\n self.freq = \"D\"\n else:\n self.freq = \"W\"\n\n def _set_date_range(self, start_date, end_date):\n \"\"\"Calculates the appropriate date range after resampling in order to\n get an equal number of entries per sample.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n \"\"\"\n first_available = self.pg.index[0].tz_convert(self.tz)\n last_available = self.pg.index[-1].tz_convert(self.tz)\n\n timestep = (\n pd.DataFrame(\n index=pd.date_range(start_date, end_date, freq=\"H\", tz=self.tz)\n )\n .resample(self.freq, label=\"left\")\n .size()\n .rename(\"Number of Hours\")\n )\n\n if self.freq == \"H\":\n if first_available > pd.Timestamp(start_date, tz=self.tz):\n self.from_index = first_available\n else:\n self.from_index = pd.Timestamp(start_date, tz=self.tz)\n if last_available < pd.Timestamp(end_date, tz=self.tz):\n self.to_index = last_available\n else:\n self.to_index = pd.Timestamp(end_date, tz=self.tz)\n\n elif self.freq == \"D\":\n if timestep[0] == timestep[1]:\n first_full = pd.Timestamp(timestep.index.values[0], tz=self.tz)\n else:\n first_full = pd.Timestamp(timestep.index.values[1], tz=self.tz)\n if timestep[-1] == timestep[-2]:\n last_full = pd.Timestamp(timestep.index.values[-1], tz=self.tz)\n else:\n last_full = pd.Timestamp(timestep.index.values[-2], tz=self.tz)\n\n if first_available > first_full:\n self.from_index = first_available.ceil(\"D\")\n else:\n self.from_index = first_full\n if last_available < pd.Timestamp(end_date, tz=self.tz):\n self.to_index = last_available.floor(\"D\") - pd.Timedelta(\"1 days\")\n else:\n self.to_index = last_full\n\n elif self.freq == \"W\":\n if timestep[0] == timestep[1]:\n first_full = pd.Timestamp(timestep.index.values[0], tz=self.tz)\n else:\n first_full = pd.Timestamp(timestep.index.values[1], tz=self.tz)\n if timestep[-1] == timestep[-2]:\n last_full = pd.Timestamp(timestep.index.values[-1], tz=self.tz)\n else:\n last_full = pd.Timestamp(timestep.index.values[-2], tz=self.tz)\n\n if first_available > first_full:\n self.from_index = min(timestep[first_available:].index)\n else:\n self.from_index = first_full\n if last_available < last_full:\n self.to_index = max(timestep[:last_available].index)\n else:\n self.to_index = last_full\n\n self.timestep = timestep[self.from_index : self.to_index]\n\n def _do_chart(self, start_date, end_date):\n \"\"\"Performs chart analysis.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n \"\"\"\n print(\"Set UTC for all zones\")\n self.tz = \"utc\"\n\n self._set_date_range(start_date, end_date)\n self.data = []\n self.filename = []\n for z in self.zones:\n self.data.append(self._get_chart(z))\n\n def _get_chart(self, zone):\n \"\"\"Calculates proportion of resources and generation in one zone.\n\n :param str zone: zone to consider.\n :return: (*tuple*) -- First element is a time series of PG with type of\n generators as columns. Second element is a data frame with type of\n generators as indices and corresponding capacity as column.\n \"\"\"\n pg, _ = self._get_pg(zone, self.resources)\n if pg is not None:\n fig, ax = plt.subplots(1, 2, figsize=(20, 10), sharey=\"row\")\n plt.subplots_adjust(wspace=1)\n plt.suptitle(\"%s\" % zone, fontsize=30)\n ax[0].set_title(\"Generation (MWh)\", fontsize=25)\n ax[1].set_title(\"Resources (MW)\", fontsize=25)\n\n pg_groups = pg.T.groupby(self.grid.plant[\"type\"]).agg(sum).T\n pg_groups.name = \"%s (Generation)\" % zone\n\n capacity = self.grid.plant.loc[pg.columns].groupby(\"type\").agg(sum).Pmax\n capacity.name = \"%s (Capacity)\" % zone\n\n if self.storage_pg is not None:\n pg_storage, capacity_storage = self._get_storage_pg(zone)\n if capacity_storage is not None:\n capacity = capacity.append(\n pd.Series([capacity_storage], index=[\"storage\"])\n )\n pg_groups = pd.merge(\n pg_groups,\n pg_storage.clip(lower=0).sum(axis=1).rename(\"storage\"),\n left_index=True,\n right_index=True,\n )\n\n t2l = type2label.copy()\n for t in type2label.keys():\n if t not in pg_groups.columns:\n del t2l[t]\n\n ax[0] = (\n pg_groups[list(t2l.keys())]\n .rename(index=t2l)\n .sum()\n .plot(\n ax=ax[0],\n kind=\"barh\",\n alpha=0.7,\n color=[type2color[r] for r in t2l.keys()],\n )\n )\n\n ax[1] = (\n capacity[list(t2l.keys())]\n .rename(index=t2l)\n .plot(\n ax=ax[1],\n kind=\"barh\",\n alpha=0.7,\n color=[type2color[r] for r in t2l.keys()],\n )\n )\n\n y_offset = 0.3\n for i in [0, 1]:\n ax[i].tick_params(axis=\"y\", which=\"both\", labelsize=20)\n ax[i].set_xticklabels(\"\")\n ax[i].set_ylabel(\"\")\n ax[i].spines[\"right\"].set_visible(False)\n ax[i].spines[\"top\"].set_visible(False)\n ax[i].spines[\"bottom\"].set_visible(False)\n ax[i].set_xticks([])\n for p in ax[i].patches:\n b = p.get_bbox()\n val = format(int(b.x1), \",\")\n ax[i].annotate(val, (b.x1, b.y1 - y_offset), fontsize=20)\n\n self.filename.append(\n \"%s_%s_%s-%s.png\"\n % (\n self.kind,\n zone,\n self.from_index.strftime(\"%Y%m%d%H\"),\n self.to_index.strftime(\"%Y%m%d%H\"),\n )\n )\n\n return pg_groups, capacity\n else:\n return None\n\n def _do_stacked(self, start_date, end_date, tz):\n \"\"\"Performs stack analysis.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n :param str tz: timezone.\n \"\"\"\n self.data = []\n self.filename = []\n for z in self.zones:\n self.tz = self.zone2time[z] if tz == \"local\" else tz\n self._set_date_range(start_date, end_date)\n self.data.append(self._get_stacked(z))\n\n def _get_stacked(self, zone):\n \"\"\"Calculates time series of PG and demand in one zone.\n\n :param str zone: zone to consider.\n :return: (*pandas.DataFrame*) -- data frame of PG and load for selected\n zone.\n \"\"\"\n pg, capacity = self._get_pg(zone, self.resources)\n if pg is not None:\n\n pg_groups = pg.T.groupby(self.grid.plant[\"type\"])\n pg_stack = pg_groups.agg(sum).T\n\n if self.storage_pg is not None:\n pg_storage, capacity_storage = self._get_storage_pg(zone)\n if capacity_storage is not None:\n capacity += capacity_storage\n pg_stack = pd.merge(\n pg_stack,\n pg_storage.clip(lower=0).sum(axis=1).rename(\"storage\"),\n left_index=True,\n right_index=True,\n )\n fig, (ax, ax_storage) = plt.subplots(\n 2,\n 1,\n figsize=(20, 15),\n sharex=\"row\",\n gridspec_kw={\"height_ratios\": [3, 1], \"hspace\": 0},\n )\n plt.subplots_adjust(wspace=0)\n ax_storage = (\n pg_storage.tz_localize(None)\n .sum(axis=1)\n .rename(\"batteries\")\n .plot(color=type2color[\"storage\"], lw=4, ax=ax_storage)\n )\n ax_storage.fill_between(\n pg_storage.tz_localize(None).index.values,\n 0,\n pg_storage.tz_localize(None).sum(axis=1).values,\n color=type2color[\"storage\"],\n alpha=0.5,\n )\n\n ax_storage.tick_params(axis=\"both\", which=\"both\", labelsize=20)\n ax_storage.set_xlabel(\"\")\n ax_storage.set_ylabel(\"Energy Storage (MW)\", fontsize=22)\n for a in fig.get_axes():\n a.label_outer()\n else:\n fig = plt.figure(figsize=(20, 10))\n ax = fig.gca()\n else:\n fig = plt.figure(figsize=(20, 10))\n ax = fig.gca()\n\n t2l = type2label.copy()\n for t in type2label.keys():\n if t not in pg_stack.columns:\n del t2l[t]\n\n demand = self._get_demand(zone)\n net_demand = pd.DataFrame(\n {\"net_demand\": demand[\"demand\"]}, index=demand.index\n )\n\n for (t, key) in [\n (\"solar\", \"sc\"),\n (\"wind\", \"wonc\"),\n (\"wind_offshore\", \"woffc\"),\n ]:\n if t in t2l.keys():\n pg_t = self._get_pg(zone, [t])[0].sum(axis=1)\n net_demand[\"net_demand\"] = net_demand[\"net_demand\"] - pg_t\n curtailment_t = (\n self._get_profile(zone, t).sum(axis=1).tolist() - pg_t\n )\n pg_stack[key] = np.clip(curtailment_t, 0, None)\n\n if self.normalize:\n pg_stack = pg_stack.divide(capacity * self.timestep, axis=\"index\")\n demand = demand.divide(capacity * self.timestep, axis=\"index\")\n net_demand = net_demand.divide(capacity * self.timestep, axis=\"index\")\n ax.set_ylabel(\"Normalized Generation\", fontsize=22)\n else:\n pg_stack = pg_stack.divide(1000, axis=\"index\")\n demand = demand.divide(1000, axis=\"index\")\n net_demand = net_demand.divide(1000, axis=\"index\")\n ax.set_ylabel(\"Generation (GW)\", fontsize=22)\n\n t2c = [type2color[r] for r in t2l.keys()]\n if \"solar\" in t2l.keys():\n t2l[\"sc\"] = \"Solar Curtailment\"\n t2c.append(\"#e8eb34\")\n if \"wind\" in t2l.keys():\n t2l[\"wonc\"] = \"Wind Onshore Curtailment\"\n t2c.append(\"#b6fc03\")\n if \"wind_offshore\" in t2l.keys():\n t2l[\"woffc\"] = \"Wind Offhore Curtailment\"\n t2c.append(\"turquoise\")\n\n ax = (\n pg_stack[list(t2l.keys())]\n .tz_localize(None)\n .rename(columns=t2l)\n .plot.area(color=t2c, linewidth=0, alpha=0.7, ax=ax)\n )\n\n demand.tz_localize(None).plot(color=\"red\", lw=4, ax=ax)\n net_demand.tz_localize(None).plot(color=\"red\", ls=\"--\", lw=2, ax=ax)\n ax.set_ylim(\n [\n min(0, 1.1 * net_demand.min().values[0]),\n max(ax.get_ylim()[1], 1.1 * demand.max().values[0]),\n ]\n )\n\n ax.set_title(\"%s\" % zone, fontsize=25)\n ax.grid(color=\"black\", axis=\"y\")\n ax.tick_params(which=\"both\", labelsize=20)\n ax.set_xlabel(\"\")\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(\n handles[::-1],\n labels[::-1],\n frameon=2,\n prop={\"size\": 18},\n loc=\"lower right\",\n )\n\n pg_stack[\"demand\"] = demand\n pg_stack.name = zone\n\n self.filename.append(\n \"%s_%s_%s-%s.png\"\n % (\n self.kind,\n zone,\n self.from_index.strftime(\"%Y%m%d%H\"),\n self.to_index.strftime(\"%Y%m%d%H\"),\n )\n )\n\n return pg_stack\n else:\n return None\n\n def _do_comp(self, start_date, end_date, tz):\n \"\"\"Performs comparison analysis.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n :param str tz: timezone.\n \"\"\"\n if tz == \"local\":\n print(\"Set US/Pacific for all zones\")\n self.tz = \"US/Pacific\"\n else:\n self.tz = tz\n self._set_date_range(start_date, end_date)\n self.data = []\n self.filename = []\n for r in self.resources:\n self.data.append(self._get_comp(r))\n\n def _get_comp(self, resource):\n \"\"\"Calculates time series of PG for one resource.\n\n :param str resource: resource to consider.\n :return: (*pandas.DataFrame*) -- data frame of PG for selected resource.\n \"\"\"\n fig = plt.figure(figsize=(20, 10))\n plt.title(\"%s\" % resource.capitalize(), fontsize=25)\n\n first = True\n total = pd.DataFrame()\n for z in self.zones:\n pg, capacity = self._get_pg(z, [resource])\n if pg is None:\n pass\n else:\n ax = fig.gca()\n col_name = \"%s: %d plants (%d MW)\" % (z, pg.shape[1], capacity)\n total_tmp = pd.DataFrame(pg.T.sum().rename(col_name))\n\n if self.normalize:\n total_tmp = total_tmp.divide(capacity * self.timestep, axis=\"index\")\n if first:\n total = total_tmp\n first = False\n else:\n total = pd.merge(\n total, total_tmp, left_index=True, right_index=True\n )\n\n total[col_name].tz_localize(None).plot(lw=4, alpha=0.8, ax=ax)\n\n ax.grid(color=\"black\", axis=\"y\")\n ax.tick_params(which=\"both\", labelsize=20)\n ax.set_xlabel(\"\")\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(handles[::-1], labels[::-1], frameon=2, prop={\"size\": 18})\n if self.normalize:\n ax.set_ylabel(\"Normalized Generation\", fontsize=22)\n else:\n ax.set_ylabel(\"Generation (MWh)\", fontsize=22)\n if total.empty:\n plt.close()\n return None\n else:\n self.filename.append(\n \"%s_%s_%s_%s-%s.png\"\n % (\n self.kind,\n resource,\n \"-\".join(self.zones),\n self.from_index.strftime(\"%Y%m%d%H\"),\n self.to_index.strftime(\"%Y%m%d%H\"),\n )\n )\n total.name = resource\n return total\n\n def _do_curtailment(self, start_date, end_date, tz):\n \"\"\"Performs curtailment analysis.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n :param str tz: timezone.\n \"\"\"\n for r in self.resources:\n if r not in [\"solar\", \"wind\"]:\n print(\"Curtailment analysis is only for renewable energies\")\n raise Exception(\"Invalid resource\")\n\n self.data = []\n self.filename = []\n for z in self.zones:\n self.tz = self.zone2time[z] if tz == \"local\" else tz\n self._set_date_range(start_date, end_date)\n for r in self.resources:\n self.data.append(self._get_curtailment(z, r))\n\n def _get_curtailment(self, zone, resource):\n \"\"\"Calculates time series of curtailment for one resource in one zone.\n\n :param str zone: zone to consider.\n :param str resource: resource to consider.\n :return: (*pandas.DataFrame*) -- data frame of curtailment for selected\n zone and resource. Columns are energy available (in MWh) from\n generators using resource in zone, energy generated (in MWh) from\n generators using resource in zone, demand in selected zone (in MWh)\n and curtailment (in %).\n \"\"\"\n pg, capacity = self._get_pg(zone, [resource])\n if pg is None:\n return None\n else:\n fig = plt.figure(figsize=(20, 10))\n plt.title(\"%s (%s)\" % (zone, resource.capitalize()), fontsize=25)\n ax = fig.gca()\n ax_twin = ax.twinx()\n\n demand = self._get_demand(zone)\n available = self._get_profile(zone, resource)\n\n data = pd.DataFrame(available.T.sum().rename(\"available\"))\n data[\"generated\"] = pg.T.sum().values\n data[\"demand\"] = demand.values\n data[\"curtailment\"] = 1 - data[\"generated\"] / data[\"available\"]\n data[\"curtailment\"] *= 100\n\n # Numerical precision\n data.loc[abs(data[\"curtailment\"]) < 1, \"curtailment\"] = 0\n\n data[\"curtailment\"].tz_localize(None).plot(\n ax=ax, style=\"b\", lw=4, alpha=0.7\n )\n\n data[\"curtailment mean\"] = data[\"curtailment\"].mean()\n data[\"curtailment mean\"].tz_localize(None).plot(\n ax=ax, style=\"b\", ls=\"--\", lw=4, alpha=0.7\n )\n\n data[\"available\"].tz_localize(None).rename(\n \"%s energy available\" % resource\n ).plot(\n ax=ax_twin,\n lw=4,\n alpha=0.7,\n style={\"%s energy available\" % resource: type2color[resource]},\n )\n\n data[\"demand\"].tz_localize(None).plot(\n ax=ax_twin, lw=4, alpha=0.7, style={\"demand\": \"r\"}\n )\n\n ax.xaxis.set_major_locator(mdates.MonthLocator())\n ax.xaxis.set_major_formatter(mdates.DateFormatter(\"%b\"))\n ax.tick_params(which=\"both\", labelsize=20)\n ax.grid(color=\"black\", axis=\"y\")\n ax.set_xlabel(\"\")\n ax.set_ylabel(\"Curtailment [%]\", fontsize=22)\n ax.legend(loc=\"upper left\", prop={\"size\": 18})\n ax_twin.tick_params(which=\"both\", labelsize=20)\n ax_twin.set_ylabel(\"MWh\", fontsize=22)\n ax_twin.legend(loc=\"upper right\", prop={\"size\": 18})\n\n data.name = \"%s - %s\" % (zone, resource)\n\n self.filename.append(\n \"%s_%s_%s_%s-%s.png\"\n % (\n self.kind,\n resource,\n zone,\n self.from_index.strftime(\"%Y%m%d%H\"),\n self.to_index.strftime(\"%Y%m%d%H\"),\n )\n )\n\n return data\n\n def _do_variability(self, start_date, end_date, tz):\n \"\"\"Performs variability analysis.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n :param str tz: timezone.\n \"\"\"\n for r in self.resources:\n if r not in [\"solar\", \"wind\"]:\n print(\"Curtailment analysis is only for renewable energies\")\n raise Exception(\"Invalid resource\")\n\n self.data = []\n self.filename = []\n for z in self.zones:\n self.tz = self.zone2time[z] if tz == \"local\" else tz\n self._set_date_range(start_date, end_date)\n for r in self.resources:\n self.data.append(self._get_variability(z, r))\n\n def _get_variability(self, zone, resource):\n \"\"\"Calculates time series of PG in one zone for one resource. Also,\n calculates the time series of the PG of 2, 8 and 15 randomly\n chosen plants in the same zone and using the same resource.\n\n :param str resource: resource to consider.\n :return: (*pandas.DataFrame*) -- data frame of PG for selected zone and\n plants.\n \"\"\"\n pg, capacity = self._get_pg(zone, [resource])\n if pg is None:\n return None\n else:\n n_plants = len(pg.columns)\n fig = plt.figure(figsize=(20, 10))\n plt.title(\"%s (%s)\" % (zone, resource.capitalize()), fontsize=25)\n ax = fig.gca()\n\n total = pd.DataFrame(\n pg.T.sum().rename(\"Total: %d plants (%d MW)\" % (n_plants, capacity))\n )\n total.name = \"%s - %s\" % (zone, resource)\n\n np.random.seed(self.seed)\n if n_plants < 20:\n print(\n \"Not enough %s plants in %s for variability analysis\"\n % (resource, zone)\n )\n plt.close()\n return None\n else:\n selected = np.random.choice(pg.columns, 15, replace=False).tolist()\n norm = [capacity]\n for i in [15, 8, 2]:\n norm += [sum(self.grid.plant.loc[selected[:i]].Pmax.values)]\n total[\"15 plants (%d MW)\" % norm[1]] = pg[selected].T.sum()\n total[\"8 plants (%d MW)\" % norm[2]] = pg[selected[:8]].T.sum()\n total[\"2 plants (%d MW)\" % norm[3]] = pg[selected[:2]].T.sum()\n\n if self.normalize:\n for i, col in enumerate(total.columns):\n total[col] = total[col].divide(\n norm[i] * self.timestep, axis=\"index\"\n )\n\n lws = [5, 3, 3, 3]\n lss = [\"-\", \"--\", \"--\", \"--\"]\n colors = [type2color[resource]]\n if resource == \"solar\":\n colors += [\"red\", \"orangered\", \"darkorange\"]\n elif resource == \"wind\":\n colors += [\"dodgerblue\", \"teal\", \"turquoise\"]\n\n for col, c, lw, ls in zip(total.columns, colors, lws, lss):\n total[col].tz_localize(None).plot(\n alpha=0.7, lw=lw, ls=ls, color=c, ax=ax\n )\n\n ax.grid(color=\"black\", axis=\"y\")\n ax.tick_params(which=\"both\", labelsize=20)\n ax.set_xlabel(\"\")\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(\n handles[::-1],\n labels[::-1],\n frameon=2,\n prop={\"size\": 18},\n loc=\"best\",\n )\n if self.normalize:\n ax.set_ylabel(\"Normalized Generation\", fontsize=22)\n else:\n ax.set_ylabel(\"Generation (MWh)\", fontsize=22)\n\n self.filename.append(\n \"%s_%s_%s_%s-%s.png\"\n % (\n self.kind,\n resource,\n zone,\n self.from_index.strftime(\"%Y%m%d%H\"),\n self.to_index.strftime(\"%Y%m%d%H\"),\n )\n )\n\n return total\n\n def _do_correlation(self, start_date, end_date, tz):\n \"\"\"Performs correlation analysis.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n :param str tz: timezone.\n \"\"\"\n\n for r in self.resources:\n if r not in [\"solar\", \"wind\"]:\n print(\"Correlation analysis is only for renewable energies\")\n raise Exception(\"Invalid resource\")\n\n if tz == \"local\":\n print(\"Set US/Pacific for all zones\")\n self.tz = \"US/Pacific\"\n else:\n self.tz = tz\n self._set_date_range(start_date, end_date)\n self.data = []\n self.filename = []\n for r in self.resources:\n self.data.append(self._get_correlation(r))\n\n def _get_correlation(self, resource):\n \"\"\"Calculates correlation coefficients of power generated between\n multiple zones for one resource.\n\n :param str resource: resource to consider.\n :return: (*pandas.DataFrame*) -- data frame of PG for selected resource.\n Columns are zones for selected resource.\n \"\"\"\n\n fig = plt.figure(figsize=(12, 12))\n plt.title(\"%s\" % resource.capitalize(), fontsize=25)\n\n first = True\n pg = pd.DataFrame()\n for z in self.zones:\n pg_tmp, _ = self._get_pg(z, [resource])\n if pg_tmp is None:\n pass\n else:\n if first:\n pg = pd.DataFrame(\n {z: pg_tmp.sum(axis=1).values}, index=pg_tmp.index\n )\n first = False\n else:\n pg[z] = pg_tmp.sum(axis=1).values\n\n if pg.empty:\n plt.close()\n return None\n else:\n pg.name = resource\n corr = pg.corr()\n if resource == \"solar\":\n palette = \"OrRd\"\n color = \"red\"\n else:\n palette = \"Greens\"\n color = \"green\"\n\n ax_matrix = fig.gca()\n ax_matrix = sns.heatmap(\n corr,\n annot=True,\n fmt=\".2f\",\n cmap=palette,\n ax=ax_matrix,\n square=True,\n cbar=False,\n annot_kws={\"size\": 18},\n lw=4,\n )\n ax_matrix.set_yticklabels(pg.columns, rotation=40, ha=\"right\")\n ax_matrix.tick_params(which=\"both\", labelsize=20)\n\n scatter = scatter_matrix(\n pg,\n alpha=0.2,\n diagonal=\"kde\",\n figsize=(12, 12),\n color=color,\n density_kwds={\"color\": color, \"lw\": 4},\n )\n for ax_scatter in scatter.ravel():\n ax_scatter.tick_params(labelsize=20)\n ax_scatter.set_xlabel(ax_scatter.get_xlabel(), fontsize=22, rotation=0)\n ax_scatter.set_ylabel(ax_scatter.get_ylabel(), fontsize=22, rotation=90)\n\n for t in [\"matrix\", \"scatter\"]:\n self.filename.append(\n \"%s-%s_%s_%s_%s-%s.png\"\n % (\n self.kind,\n t,\n resource,\n \"-\".join(self.zones),\n self.from_index.strftime(\"%Y%m%d%H\"),\n self.to_index.strftime(\"%Y%m%dH\"),\n )\n )\n\n return pg\n\n def _do_yield(self, start_date, end_date):\n \"\"\"Performs yield analysis.\n\n :param str start_date: starting timestamp.\n :param str end_date: ending timestamp.\n \"\"\"\n\n for r in self.resources:\n if r not in [\"solar\", \"wind\"]:\n print(\"Correlation analysis is only for renewable energies\")\n raise Exception(\"Invalid resource\")\n\n self.tz = \"utc\"\n self.data = []\n self.filename = []\n for z in self.zones:\n self._set_date_range(start_date, end_date)\n for r in self.resources:\n self.data.append(self._get_yield(z, r))\n\n def _get_yield(self, zone, resource):\n \"\"\"Calculates capacity factor of one resource in one zone.\n\n :param str zone: zone to consider.\n :param str resource: resource to consider.\n :return: (*tuple*) -- first element is the average ideal capacity\n factor for the selected zone and resource. Second element is the\n average curtailed capacity factor for the selected zone and\n resource.\n \"\"\"\n\n pg, _ = self._get_pg(zone, [resource])\n if pg is None:\n return None\n else:\n available = self._get_profile(zone, resource)\n\n capacity = self.grid.plant.loc[pg.columns].Pmax.values\n\n uncurtailed = available.sum().divide(len(pg) * capacity, axis=\"index\")\n mean_uncurtailed = np.mean(uncurtailed)\n curtailed = pg.sum().divide(len(pg) * capacity, axis=\"index\")\n mean_curtailed = np.mean(curtailed)\n\n if len(pg.columns) > 10:\n fig = plt.figure(figsize=(12, 12))\n plt.title(\"%s (%s)\" % (zone, resource.capitalize()), fontsize=25)\n ax = fig.gca()\n cf = pd.DataFrame(\n {\"uncurtailed\": 100 * uncurtailed, \"curtailed\": 100 * curtailed},\n index=pg.columns,\n )\n cf.boxplot(ax=ax)\n plt.text(\n 0.5,\n 0.9,\n \"%d plants\" % len(capacity),\n ha=\"center\",\n va=\"center\",\n transform=ax.transAxes,\n fontsize=22,\n )\n ax.tick_params(labelsize=20)\n ax.set_ylabel(\"Capacity Factor [%]\", fontsize=22)\n\n self.filename.append(\n \"%s_%s_%s_%s-%s.png\"\n % (\n self.kind,\n resource,\n zone,\n self.from_index.strftime(\"%Y%m%d%H\"),\n self.to_index.strftime(\"%Y%m%d%H\"),\n )\n )\n\n return mean_uncurtailed, mean_curtailed\n\n def _get_zone_id(self, zone):\n \"\"\"Returns the load zone identification numbers for specified zone.\n\n :param zone: zone to consider. A specific load zone, *Eastern*,\n *Western*, *California* or *Texas*.\n :return (*list*): Corresponding load zones identification number.\n \"\"\"\n if zone == \"Western\":\n load_zone_id = list(range(201, 217))\n elif zone == \"Texas\":\n load_zone_id = list(range(301, 309))\n elif zone == \"California\":\n load_zone_id = list(range(203, 208))\n elif zone == \"Eastern\":\n load_zone_id = list(range(1, 53))\n elif zone == \"USA\":\n load_zone_id = (\n list(range(1, 53)) + list(range(201, 217)) + list(range(301, 309))\n )\n else:\n load_zone_id = [self.grid.zone2id[zone]]\n\n return load_zone_id\n\n def _get_plant_id(self, zone, resource):\n \"\"\"Extracts the plant identification number of all the generators\n located in one zone and using one specific resource.\n\n :param str zone: zone to consider.\n :param str resource: type of generator to consider.\n :return: (*list*) -- plant id of all the generators located in zone and\n using resource.\n \"\"\"\n plant_id = []\n for z in self._get_zone_id(zone):\n try:\n plant_id += (\n self.grid.plant.groupby([\"zone_id\", \"type\"])\n .get_group((z, resource))\n .index.values.tolist()\n )\n except KeyError:\n pass\n\n return plant_id\n\n def _get_pg(self, zone, resources):\n \"\"\"Returns PG of all the generators located in one zone and powered by\n resources.\n\n :param str zone: one of the zones.\n :param list resources: type of generators to consider.\n :return: (*tuple*) -- data frames of PG and associated capacity for all\n generators located in zone and using the specified resources.\n \"\"\"\n plant_id = []\n for r in resources:\n plant_id += self._get_plant_id(zone, r)\n\n if len(plant_id) == 0:\n print(\"No %s plants in %s\" % (\"/\".join(resources), zone))\n return [None] * 2\n else:\n capacity = sum(self.grid.plant.loc[plant_id].Pmax.values)\n pg = (\n self._convert_tz(self.pg[plant_id])\n .resample(self.freq, label=\"left\")\n .sum()[self.from_index : self.to_index]\n )\n\n return pg, capacity\n\n def _get_storage_pg(self, zone):\n \"\"\"Returns PG of all storage units located in zone\n\n :param str zone: one of the zones\n :return: (*tuple*) -- data frame of PG and associated capacity for all\n storage units located in zone.\n \"\"\"\n storage_id = []\n\n for c, bus in enumerate(self.grid.storage[\"gen\"].bus_id.values):\n if self.grid.bus.loc[bus].zone_id in self._get_zone_id(zone):\n storage_id.append(c)\n\n if len(storage_id) == 0:\n print(\"No storage units in %s\" % zone)\n return [None] * 2\n else:\n capacity = sum(self.grid.storage[\"gen\"].loc[storage_id].Pmax.values)\n pg = (\n self._convert_tz(self.storage_pg[storage_id])\n .resample(self.freq, label=\"left\")\n .sum()[self.from_index : self.to_index]\n )\n\n return pg, capacity\n\n def _get_demand(self, zone):\n \"\"\"Returns demand profile for a specific load zone, *Eastern*,\n *Western*, *California* or *Texas*.\n\n :param str zone: one of the zones.\n :return: (*pandas.DataFrame*) -- data frame of demand in zone (in MWh).\n \"\"\"\n demand = self.demand.tz_localize(\"utc\")\n demand = demand[self._get_zone_id(zone)].sum(axis=1).rename(\"demand\").to_frame()\n demand = (\n self._convert_tz(demand)\n .resample(self.freq, label=\"left\")\n .sum()[self.from_index : self.to_index]\n )\n\n return demand\n\n def _get_profile(self, zone, resource):\n \"\"\"Returns profile for resource.\n\n :param str zone: zone to consider.\n :param str resource: type of generators to consider.\n :return: (*pandas.DataFrame*) -- data frame of the generated energy (in\n MWh) in zone by generators using resource.\n \"\"\"\n plant_id = self._get_plant_id(zone, resource)\n\n if len(plant_id) == 0:\n print(\"No %s plants in %s\" % (resource, zone))\n return None\n\n if resource == \"wind_offshore\":\n profile = self.wind.tz_localize(\"utc\")\n else:\n profile = eval(\"self.\" + resource).tz_localize(\"utc\")\n\n return (\n self._convert_tz(profile[plant_id])\n .resample(self.freq, label=\"left\")\n .sum()[self.from_index : self.to_index]\n )\n\n def get_plot(self, save=False):\n \"\"\"Plots analysis.\n\n :param bool save: should plot be saved.\n \"\"\"\n if save:\n for i in plt.get_fignums():\n plt.figure(i)\n plt.savefig(self.filename[i - 1], bbox_inches=\"tight\", pad_inches=0)\n plt.show()\n\n def get_data(self):\n \"\"\"Get data.\n\n :return: (*dict*) -- the formatting of the data depends on the selected\n analysis.\n\n .. note::\n * *'stacked'*:\n 1D dictionary. Keys are zones and associated value is a data\n frame.\n * *'chart'*:\n 2D dictionary. First key is zone and associated value is a\n dictionary, which has *'Generation'* and *'Capacity'* as keys\n and a data frame for value.\n * *'comp'* and *'correlation'*:\n 1D dictionary. Keys are resources and associated value is a\n data frame.\n * *'variability'*, *'curtailment'* and *'yield'*:\n 2D dictionary. First key is zone and associated value is a\n dictionary, which has resources as keys and a data frame for\n value.\n\n \"\"\"\n data = None\n if self.kind == \"stacked\":\n data = {}\n for i, z in enumerate(self.zones):\n data[z] = self.data[i]\n elif self.kind == \"chart\":\n data = {}\n for i, z in enumerate(self.zones):\n data[z] = {}\n data[z][\"Generation\"] = self.data[i][0]\n data[z][\"Capacity\"] = self.data[i][1]\n elif self.kind == \"comp\" or self.kind == \"correlation\":\n data = {}\n for i, r in enumerate(self.resources):\n data[r] = self.data[i]\n elif (\n self.kind == \"variability\"\n or self.kind == \"curtailment\"\n or self.kind == \"yield\"\n ):\n data = {}\n index = 0\n for z in self.zones:\n data[z] = {}\n for r in self.resources:\n data[z][r] = self.data[index]\n index += 1\n\n return data\n","sub_path":"postreise/plot/analyze_pg.py","file_name":"analyze_pg.py","file_ext":"py","file_size_in_byte":46601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"221144669","text":"from reactopya import Component\nfrom mountaintools import client as mt\n\n\nclass SpikeForestAnalysis(Component):\n def __init__(self):\n super().__init__()\n\n def javascript_state_changed(self, prev_state, state):\n path = state.get('path', None)\n download_from = state.get('download_from', [])\n mt.configDownloadFrom(download_from)\n\n if not path:\n self.set_python_state(dict(\n status='error',\n status_message='No path provided.'\n ))\n return\n\n self.set_python_state(dict(status='running', status_message='Loading: {}'.format(path)))\n \n obj = mt.loadObject(path=path)\n if not obj:\n self.set_python_state(dict(\n status='error',\n status_message='Unable to realize object: {}'.format(path)\n ))\n return\n \n obj['StudyAnalysisResults'] = None\n\n self.set_python_state(dict(\n status='finished',\n object=obj\n ))","sub_path":"widgets/SpikeForestAnalysis/SpikeForestAnalysis.py","file_name":"SpikeForestAnalysis.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"211561207","text":"import numpy as np\nimport random\n\n'''\nCreates a 2D array of characters to represent the puzzle extracted from fileName\n'''\ndef parseArray(fileName):\n path = './' + fileName\n with open(path) as file:\n array = [[c for c in line.strip()] for line in file]\n return array\n\n\n'''\nWrites a 2D array of characters representing the puzzle to fileName\n'''\ndef writeArrayToFile(array, fileName):\n np.savetxt(fileName, np.array(array), fmt = '%s', delimiter = '')\n\n\n'''\nGets the domain of possible colors in the puzzle\n'''\ndef getDomain(array):\n domain = []\n for i in range(len(array)):\n for j in range(len(array[0])):\n if array[i][j] != \"_\" and array[i][j] not in domain:\n domain.append(array[i][j])\n return domain\n\n'''\nGets the source coordinates\n'''\ndef getSources(array):\n sources = []\n for i in range(len(array)):\n for j in range(len(array[0])):\n if array[i][j] != \"_\":\n sources.append((i,j))\n return sources\n\n'''\nGets a random unassigned value found in the puzzle\n'''\ndef getRandomUnassignedIndex(array):\n unassignedIndices = []\n for i in range(len(array)):\n for j in range(len(array[0])):\n if array[i][j] == \"_\":\n unassignedIndices.append((i, j))\n if unassignedIndices == []:\n return None\n else:\n return random.choice(unassignedIndices)\n\n'''\nGets all unassigned grids neighboring an assigned grid\n'''\ndef getAllUnassignedIndexNearColored(array):\n unassignedIndices = []\n for i in range(len(array)):\n for j in range(len(array[0])):\n if array[i][j] != \"_\":\n neighbors = getValidNeighbors(i, j, array)\n for neighbor in neighbors:\n if array[neighbor[0]][neighbor[1]] == \"_\":\n unassignedIndices.append(neighbor)\n return unassignedIndices\n\n'''\nGets most constrained unassigned grid\n'''\ndef getMostConstrainedVariable(indexes,domain,assignment,sources):\n if len(indexes) == 0:\n return None\n curr_mcv = None\n least_count = 100\n for idx in indexes:\n curr_count = 0\n for value in domain:\n if isValueConsistent(idx,value,assignment,sources):\n curr_count += 1\n if curr_count < least_count:\n least_count = curr_count\n curr_mcv = idx\n return curr_mcv\n\n'''\nGets a random unassigned grid that neighbors an assigned grid\n'''\ndef getUnassignedIndexNearColored(array):\n unassignedIndices = []\n for i in range(len(array)):\n for j in range(len(array[0])):\n if array[i][j] != \"_\":\n neighbors = getValidNeighbors(i,j, array)\n for neighbor in neighbors:\n if array[neighbor[0]][neighbor[1]] == \"_\":\n unassignedIndices.append(neighbor)\n if unassignedIndices == []:\n return None\n else:\n return random.choice(list(set(unassignedIndices)))\n\n'''\nChecks if a value assignment violates any constraints\n'''\ndef isValueConsistent(index, value, assignment, sources):\n x = index[0]\n y = index[1]\n\n #print(\"Trying assignment: \" + value + \" to \" + \"(\" + str(index[0]) + \", \" + str(index[1]) + \")\\n\")\n assignment[x][y] = value\n neighbors = getValidNeighbors(x, y, assignment)\n b = True\n for neighbor in neighbors:\n if(not isVariableConsistent(neighbor[0], neighbor[1], assignment, sources)):\n b = False\n break\n assignment[x][y] = \"_\"\n return b\n\n'''\nChecks if a variable assignment violates any constraints\n'''\ndef isVariableConsistent(x, y, assignment, sources):\n countSameColorNeighs = countSameColorNeighbors(x, y, assignment)\n countUnassignedNeighs = countNeighborsWithValue(x, y, assignment, )\n if(assignment[x][y] != \"_\"):\n if (x,y) in sources:\n if((countSameColorNeighs > 1) or (countUnassignedNeighs < ( 1 - countSameColorNeighs))):\n return False\n else:\n if((countSameColorNeighs > 2) or (countUnassignedNeighs < ( 2 - countSameColorNeighs))):\n return False\n return True\n\n'''\nChecks if puzzle is complete and no constraints violated\n'''\ndef isAssignmentValid(assignment, sources):\n for x in range(len(assignment)):\n for y in range(len(assignment[0])):\n countSameColorNeighs = countSameColorNeighbors(x, y, assignment)\n if (x,y) in sources:\n if(countSameColorNeighs != 1):\n return False\n else:\n if(countSameColorNeighs != 2):\n return False\n return True\n\n'''\nnumber of neighbors with a specific value\n'''\ndef countNeighborsWithValue(x, y, assignment, value = \"_\"):\n count = 0\n neighbors = getValidNeighbors(x, y, assignment)\n for neighbor in neighbors:\n neighborX = neighbor[0]\n neighborY = neighbor[1]\n if (assignment[neighborX][neighborY] == value):\n count += 1\n return count\n\n'''\nCounts the neighbors that have the same color as the cell specified\n'''\ndef countSameColorNeighbors(x, y, assignment):\n count = 0\n neighbors = getValidNeighbors(x, y, assignment)\n for neighbor in neighbors:\n neighborX = neighbor[0]\n neighborY = neighbor[1]\n if(assignment[neighborX][neighborY] == assignment[x][y]):\n count += 1\n return count\n'''\nTakes a list of potential neighbors and an array and finds valid neighbors\n'''\ndef getValidNeighbors(x,y, assignment):\n array = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]\n validNeighbors = []\n cols = len(assignment)\n rows = len(assignment[0])\n for neighbor in array:\n x = neighbor[0]\n y = neighbor[1]\n if x >= 0 and y >= 0 and x < cols and y < rows:\n validNeighbors.append(neighbor)\n return validNeighbors\n","sub_path":"AI-MP2/Utilities.py","file_name":"Utilities.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"198486383","text":"from rest_framework import permissions\n\nclass CanModifyOrReadOnly(permissions.BasePermission):\n \"\"\"\n Custom permission to only allow staff to edit it.\n \"\"\"\n\n def has_object_permission(self, request, view, obj):\n # Read permissions are allowed to any request,\n # so we'll always allow GET, HEAD or OPTIONS requests.\n if request.method in permissions.SAFE_METHODS:\n return True\n # Write permissions are only allowed to the staff.\n return request.user and request.user.is_staff;\n \n def has_permission(self, request, view):\n return (\n request.method in permissions.SAFE_METHODS or\n request.user and\n request.user.is_staff\n )","sub_path":"monolith_alt/rest_export/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"621399066","text":"import types\nimport collections\ndef flatten(x):\n def iselement(e):\n return not(isinstance(e, collections.Iterable) and not isinstance(e, str))\n for el in x:\n if iselement(el):\n yield el\n else:\n yield from flatten(el)\n#def flatten(x):\n# result = []\n# for el in x:\n# if isinstance(x, collections.Iterable) and not isinstance(el, str):\n# result.extend(flatten(el))\n# else:\n# result.append(el)\n# return result\n#from compiler.ast import flatten\nimport numpy as np\nimport matplotlib.pyplot as plt\ncaffe_root='../../'\nimport sys\nsys.path.insert(0,caffe_root+'python')\nimport caffe\n#model_def=caffe_root+'test_alexnet/bvlc_alexnet/deploy.prototxt'\n#model_caffe=caffe_root+'test_alexnet/bvlc_alexnet/alexnet_train_iter_4000.caffemodel'\n\n#model_def=caffe_root+'examples/mnist/deploy.prototxt'\n#model_caffe=caffe_root+'examples/mnist/lenet_iter_10000.caffemodel'\n\nmodel_def=caffe_root+'models/bvlc_alexnet/deploy.prototxt'\nmodel_caffe=caffe_root+'models/bvlc_alexnet/bvlc_alexnet.caffemodel'\nnet=caffe.Net(model_def,model_caffe,caffe.TEST)\n\ndef getVpt(v,k):\n v=abs(v)\n vList=v.tolist()\n vList=flatten(vList)\n #vList.sort()\n vList = sorted(vList)\n k=(int)(k*len(vList))\n return vList[k]\n\n\n\nfor k,v in net.params.items():\n idx=v[0].data.shape\n print (k)\n print (type(v[0].data))\n cnt=0\n count=0\n vpt=getVpt(v[0].data,0.8)\n if len(idx)==3:\n for n_idx in range(0,idx[0]):\n for c_idx in range(0,idx[1]):\n for h_idx in range(0,idx[2]):\n for w_idx in range(0,idx[3]):\n count=count+1\n if v[0].data[n_idx][c_idx][h_idx][w_idx]-1*vpt:\n cnt=cnt+1\n v[0].data[n_idx][c_idx][h_idx][w_idx]=0.0\n v[0].mask[n_idx][c_idx][h_idx][w_idx]=0.0\n print (cnt)\n print (count)\n elif len(idx)==2:\n for h_idx in range(0,idx[0]):\n for w_idx in range(0,idx[1]):\n count=count+1\n if v[0].data[h_idx][w_idx]< vpt and v[0].data[h_idx][w_idx]>-1*vpt:\n cnt=cnt+1\n v[0].data[h_idx][w_idx]=0.0\n v[0].mask[h_idx][w_idx]=0.0\n # print (cnt)\n # print (count)\n # print (v[0].data)\nnet.save('fixed.caffemodel')\n\n\n","sub_path":"examples/alexnet/fixModel.py","file_name":"fixModel.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"447088573","text":"from osgeo import gdal\r\nimport os\r\nimport numpy as np\r\nclass GRID:\r\n\r\n #读图像文件\r\n def read_img(self,filename):\r\n dataset=gdal.Open(filename) #打开文件\r\n\r\n im_width = dataset.RasterXSize #栅格矩阵的列数\r\n im_height = dataset.RasterYSize #栅格矩阵的行数\r\n\r\n im_geotrans = dataset.GetGeoTransform() #仿射矩阵\r\n im_proj = dataset.GetProjection() #地图投影信息\r\n im_data = dataset.ReadAsArray(0,0,im_width,im_height) #将数据写成数组,对应栅格矩阵\r\n\r\n del dataset\r\n return im_data,im_width,im_height\r\n\r\n #写文件,以写成tif为例\r\n def write_img(self,filename,im_data,im_width,im_height,im_bands,datatype=np.uint16):\r\n #gdal数据类型包括\r\n #gdal.GDT_Byte,\r\n #gdal .GDT_UInt16, gdal.GDT_Int16, gdal.GDT_UInt32, gdal.GDT_Int32,\r\n #gdal.GDT_Float32, gdal.GDT_Float64\r\n options=[\"TILED=YES\", \"COMPRESS=LZW\"]\r\n #判断栅格数据的数据类型\r\n if 'int8' in im_data.dtype.name:\r\n datatype = gdal.GDT_Byte\r\n elif 'int16' in im_data.dtype.name:\r\n datatype = gdal.GDT_UInt16\r\n else:\r\n datatype = gdal.GDT_Float32\r\n\r\n #判读数组维数\r\n\r\n\r\n #创建文件\r\n driver = gdal.GetDriverByName(\"GTiff\") #数据类型必须有,因为要计算需要多大内存空间\r\n dataset = driver.Create(filename, im_width, im_height, im_bands, datatype,options)\r\n\r\n if im_bands == 1:\r\n dataset.GetRasterBand(1).WriteArray(im_data) #写入数组数据\r\n else:\r\n for i in range(im_bands):\r\n dataset.GetRasterBand(i+1).WriteArray(im_data[i])\r\n\r\n del dataset\r\n\r\nif __name__ == \"__main__\": #切换路径到待处理图像所在文件夹\r\n\r\n savefile=r'C:\\Users\\FLYVR\\Desktop\\cubert_0826_mirror_rgb_copy'\r\n run = GRID()\r\n file=r'C:\\Users\\FLYVR\\Desktop\\cubert_0826_mirror_rgb'\r\n filesName=os.listdir(file)\r\n\r\n for _,name in enumerate(filesName):\r\n\r\n filename=os.path.join(file,name)\r\n data,width,height = run.read_img(filename=filename) #读数据\r\n\r\n #声明保存影像文件路径\r\n savename=os.path.join(savefile,'flip'+name.split('.')[0]+'.tif')\r\n print(data.shape)\r\n #声明一个与原始影像大小相同的二维矩阵\r\n flip_img=np.zeros((data.shape[0],width,height))\r\n\r\n for i in range(width):\r\n for j in range(height):\r\n flip_img[:,i, height - 1 - j] = data[:,i, j]\r\n\r\n\r\n flip_img=np.array(flip_img,dtype=np.uint16)\r\n flip_img=flip_img[:125,:,:]\r\n print(flip_img.shape)\r\n\r\n # run.write_img(filename=savename,im_data=flip_img,\r\n # im_width=width,im_height=height,im_bands=flip_img.shape[0]) #写数据\r\n # print(name,'is successful')\r\n print()","sub_path":"hyspetracal_ interpolation/GDAL_write.py","file_name":"GDAL_write.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"123146594","text":"from .loader import read_sparse_matrix \nfrom .util import load_phrase_word2vec\nfrom .util import load_gensim_word2vec\n\nimport torch\nimport numpy as np\nimport scipy.sparse as sparse\n\nclass Dataset(object):\n \"\"\"docstring for Dataset\"\"\"\n def __init__(self, config, svd=False, train=True):\n # generate ppmi matrix for co-occurence\n pattern_filename = config.get(\"data\", \"pattern_filename\")\n\n k = int(config.getfloat(\"hyperparameters\", \"svd_dimension\"))\n self.batch_size = int(config.getfloat(\"hyperparameters\", \"batch_size\"))\n self.negative_num = int(config.getfloat(\"hyperparameters\", \"negative_num\"))\n\n csr_m, self.id2word, self.vocab, _ = read_sparse_matrix(\n pattern_filename, same_vocab=True)\n\n self.word2id = {}\n for i in range(len(self.id2word)):\n self.word2id[self.id2word[i]] = i \n\n self.matrix = csr_m.todok()\n self.p_w = csr_m.sum(axis=1).A[:,0]\n self.p_c = csr_m.sum(axis=0).A[0,:]\n self.N = self.p_w.sum() \n\n # for w2v\n if train:\n #self.wordvecs = load_phrase_word2vec(\"/home/shared/acl-data/embedding/ukwac.model\", self.vocab)\n self.wordvecs = load_gensim_word2vec(\"/home/shared/acl-data/embedding/ukwac.model\", self.vocab)\n #print(self.wordvecs[\"united_states\"])\n\n self.wordvec_weights = self.build_emb()\n\n tr_matrix = sparse.dok_matrix(self.matrix.shape)\n #print(self.matrix.shape)\n\n self.left_has = {}\n self.right_has = {}\n for (l,r) in self.matrix.keys():\n pmi_lr = (np.log(self.N) + np.log(self.matrix[(l,r)]) \n - np.log(self.p_w[l]) - np.log(self.p_c[r]))\n\n ppmi_lr = np.clip(pmi_lr, 0.0, 1e12)\n tr_matrix[(l,r)] = ppmi_lr\n\n if l not in self.left_has:\n self.left_has[l] = []\n self.left_has[l].append(r)\n if r not in self.right_has:\n self.right_has[r] = []\n self.right_has[r].append(l)\n\n self.ppmi_matrix = tr_matrix\n\n U, S, V = sparse.linalg.svds(self.ppmi_matrix.tocsr(), k=k)\n self.U = U.dot(np.diag(S))\n self.V = V.T\n\n if train:\n # self.positive_data, self.positive_label = self.generate_positive()\n self.get_avail_vocab()\n\n def get_avail_vocab(self):\n avail_vocab = []\n for idx in range(len(self.vocab)):\n if self.id2word[idx] in self.wordvecs:\n avail_vocab.append(idx)\n self.avail_vocab = np.asarray(avail_vocab)\n shuffle_indices_left = np.random.permutation(len(self.avail_vocab))[:20000]\n shuffle_indices_right = np.random.permutation(len(self.avail_vocab))[:20000]\n dev_data = []\n dev_label = []\n self.dev_dict = {}\n for id_case in range(20000):\n id_left = self.avail_vocab[shuffle_indices_left[id_case]]\n id_right = self.avail_vocab[shuffle_indices_right[id_case]]\n dev_data.append([self.w2embid[id_left],self.w2embid[id_right]])\n dev_label.append(self.U[id_left].dot(self.V[id_right]))\n self.dev_dict[(id_left, id_right)] = 1\n self.dev_data = np.asarray(dev_data)\n self.dev_label = np.asarray(dev_label)\n\n def build_emb(self): \n\n tensors = []\n ivocab = []\n self.w2embid = {}\n self.embid2w = {}\n\n for word in self.wordvecs:\n vec = torch.from_numpy(self.wordvecs[word])\n self.w2embid[self.word2id[word]] = len(ivocab)\n self.embid2w[len(ivocab)] = self.word2id[word]\n\n ivocab.append(word)\n tensors.append(vec)\n\n assert len(tensors) == len(ivocab)\n print(len(tensors))\n tensors = torch.cat(tensors).view(len(ivocab), 300)\n\n return tensors\n\n def load_vocab(self, w2v_dir, data_dir):\n i2w_path = os.path.join(data_dir, 'ukwac_id2word.pkl')\n w2i_path = os.path.join(data_dir, 'ukwac_word2id.pkl')\n with open(i2w_path, 'rb') as fr:\n self.context_i2w = pickle.load(fr)\n with open(w2i_path, 'rb') as fr:\n self.context_w2i = pickle.load(fr)\n\n self.PAD = 0\n self.UNK = 1\n\n # w2v_model = Word2Vec.load(w2v_path)\n # emb = w2v_model.wv\n # oi2ni = {}\n # new_embedding = []\n # new_embedding.append(np.zeros(300))\n # new_embedding.append(np.zeros(300))\n # cnt_ni = 2\n # for _id, word in i2w.items():\n # if word in emb:\n # oi2ni[_id] = cnt_ni\n # cnt_ni += 1 \n # new_embedding.append(emb[word])\n # else:\n # oi2ni[_id] = self.UNK\n\n oi2ni_path = os.path.join(w2v_dir, 'context_word_oi2ni.pkl')\n w2v_path = os.path.join(w2v_dir, 'context_word_w2v.model.npy')\n with open(oi2ni_path, 'rb') as fr:\n self.context_i2embid = pickle.load(fr)\n self.context_word_emb = np.load(w2v_path)\n\n\n def generate_positive(self):\n\n positive = []\n label = []\n key_list = list(self.ppmi_matrix.keys())\n shuffle_indices = np.random.permutation(len(key_list))\n\n for shuffle_id in shuffle_indices:\n (l, r) = key_list[shuffle_id]\n if self.id2word[l] in self.wordvecs and self.id2word[r] in self.wordvecs:\n positive.append([self.w2embid[l],self.w2embid[r]])\n # if l in self.context_dict and r in self.context_dict:\n # positive.append([l, r])\n score = self.U[l].dot(self.V[r])\n label.append(score)\n # label.append(self.ppmi_matrix[(l,r)])\n # 119448 positive score \n positive_train = np.asarray(positive)[:-2000]\n\n self.dev_data = np.asarray(positive)[-2000:]\n \n label_train = np.asarray(label)[:-2000]\n self.dev_label = np.asarray(label)[-2000:]\n\n return positive_train, label_train\n\n def generate_negative(self, batch_data, negative_num):\n \n negative = []\n label = []\n\n batch_size = batch_data.shape[0]\n \n for i in range(batch_size):\n # random_idx = np.random.choice(len(self.vocab), 150 , replace=False)\n l = batch_data[i][0]\n l_w = self.embid2w[l]\n r = batch_data[i][1]\n r_w = self.embid2w[r]\n\n l_neg = l_w\n r_neg = r_w\n\n num = 0\n for j in range(negative_num):\n left_prob = np.random.binomial(1, 0.5)\n # while True:\n if left_prob:\n l_neg = np.random.choice(self.avail_vocab, 1)[0]\n else:\n r_neg = np.random.choice(self.avail_vocab, 1)[0]\n # if (l_neg, r_neg) not in self.matrix.keys() and self.id2word[l_neg] in self.wordvecs and self.id2word[r_neg] in self.wordvecs:\n # if (l_neg, r_neg) not in self.matrix.keys() and self.l_neg in self.context_dict and self.r_neg in self.context_dict:\n # break\n\n negative.append([self.w2embid[l_neg], self.w2embid[r_neg]])\n # negative.append([self.context_dict[l_neg], self.context_dict[r_neg]])\n score = self.U[l_neg].dot(self.V[r_neg])\n # score = 0\n label.append(score)\n\n negative = np.asarray(negative)\n label = np.asarray(label)\n return negative, label\n\n\n def get_batch(self):\n\n\n num_positive = len(self.positive_data)\n\n batch_size = self.batch_size\n\n if num_positive% batch_size == 0:\n batch_num = num_positive // batch_size\n else:\n batch_num = num_positive // batch_size + 1\n\n shuffle_indices = np.random.permutation(num_positive)\n\n for batch in range(batch_num):\n\n start_index = batch * batch_size\n end_index = min((batch+1) * batch_size, num_positive)\n\n batch_idx = shuffle_indices[start_index:end_index]\n \n batch_positive_data = self.positive_data[batch_idx]\n batch_positive_label = self.positive_label[batch_idx]\n\n batch_negative_data, batch_negative_label = self.generate_negative(batch_positive_data, self.negative_num)\n \n # batch_positive_data = []\n # for [l, r] in batch_positive_data:\n # batch_positive_data.append(self.context_dict[l], self.context_dict[r])\n\n # [batch, 2, doc, 2, seq]\n batch_input = np.concatenate((batch_positive_data, batch_negative_data), axis=0)\n batch_label = np.concatenate((batch_positive_label,batch_negative_label), axis=0)\n\n yield batch_input, batch_label \n\n def sample_batch(self):\n num_data = len(self.avail_vocab)\n\n batch_size = self.batch_size\n\n if num_data % batch_size == 0:\n batch_num = num_data // batch_size\n else:\n batch_num = num_data // batch_size + 1\n\n shuffle_indices = np.random.permutation(num_data)\n\n for batch in range(batch_num):\n\n start_index = batch * batch_size\n end_index = min((batch+1) * batch_size, num_data)\n\n batch_idx = shuffle_indices[start_index:end_index]\n batch_data_pair = []\n batch_data_score = []\n batch_data = self.avail_vocab[batch_idx]\n \n for idx_i in batch_data:\n for j in range(self.negative_num):\n left_prob = np.random.binomial(1, 0.5)\n if left_prob:\n while True:\n idx_j = np.random.choice(self.avail_vocab, 1)[0]\n if (idx_i, idx_j) not in self.dev_dict:\n break \n batch_data_pair.append([self.w2embid[idx_i], self.w2embid[idx_j]])\n score = self.U[idx_i].dot(self.V[idx_j])\n else:\n while True:\n idx_j = np.random.choice(self.avail_vocab, 1)[0]\n if (idx_j, idx_i) not in self.dev_dict:\n break \n batch_data_pair.append([self.w2embid[idx_j], self.w2embid[idx_i]])\n score = self.U[idx_j].dot(self.V[idx_i])\n batch_data_score.append(score)\n yield np.asarray(batch_data_pair), np.asarray(batch_data_score)\n\n def sample_pos_neg_batch(self):\n num_data = len(self.avail_vocab)\n\n batch_size = self.batch_size\n\n if num_data % batch_size == 0:\n batch_num = num_data // batch_size\n else:\n batch_num = num_data // batch_size + 1\n\n shuffle_indices = np.random.permutation(num_data)\n\n for batch in range(batch_num):\n\n start_index = batch * batch_size\n end_index = min((batch+1) * batch_size, num_data)\n\n batch_idx = shuffle_indices[start_index:end_index]\n batch_data_pair = []\n batch_data_score = []\n batch_data = self.avail_vocab[batch_idx]\n \n for idx_i in batch_data:\n if idx_i in self.left_has:\n idx_j_list = np.random.permutation(self.left_has[idx_i])\n for idx_j in idx_j_list:\n if idx_j in self.avail_vocab:\n batch_data_pair.append([self.w2embid[idx_i], self.w2embid[idx_j]])\n score = self.U[idx_i].dot(self.V[idx_j])\n batch_data_score.append(score)\n break\n\n if idx_i in self.right_has:\n idx_j_list = np.random.permutation(self.right_has[idx_i])\n for idx_j in idx_j_list:\n if idx_j in self.avail_vocab:\n batch_data_pair.append([self.w2embid[idx_j], self.w2embid[idx_i]])\n score = self.U[idx_j].dot(self.V[idx_i])\n batch_data_score.append(score)\n break\n \n for j in range(self.negative_num):\n # left_prob = np.random.binomial(1, 0.5)\n # if left_prob:\n while True:\n idx_j = np.random.choice(self.avail_vocab, 1)[0]\n if (idx_i, idx_j) not in self.dev_dict:\n break \n batch_data_pair.append([self.w2embid[idx_i], self.w2embid[idx_j]])\n score = self.U[idx_i].dot(self.V[idx_j])\n batch_data_score.append(score)\n # else:\n while True:\n idx_j = np.random.choice(self.avail_vocab, 1)[0]\n if (idx_j, idx_i) not in self.dev_dict:\n break \n batch_data_pair.append([self.w2embid[idx_j], self.w2embid[idx_i]])\n score = self.U[idx_j].dot(self.V[idx_i])\n batch_data_score.append(score)\n yield np.asarray(batch_data_pair), np.asarray(batch_data_score)\n\n","sub_path":"utils/data_helper.py","file_name":"data_helper.py","file_ext":"py","file_size_in_byte":13235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"76504173","text":"# Algoritmo 4\n\n\ndef main():\n a = int(input(\"a: \"))\n b = int(input(\"b: \"))\n\n if a % b == 0 or b % a == 0:\n print(\"Multiples\")\n else:\n print(\"Not multiples\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"EXERCÍCIOS RESOLVIDOS/python/alternatives/alg4.py","file_name":"alg4.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"199891290","text":"# -*- coding: utf-8 -*-\n\"\"\"Utility module for all network implementations\n\nIn this module you can find all utilities for network implementation,\neven for specific protocols.\n\"\"\"\n\n\n__author__ = 'douglasvinter@gmail.com'\n\n\n\nimport collections\nfrom StringIO import StringIO\nfrom httplib import HTTPResponse\nfrom core.util import JSONSerializable\n\n\n# udpPackage used to return datagram status\nUdpPackage = collections.namedtuple('UdpPackage',\n ('data', 'host', 'port', 'status')\n )\n\n\ndef mSearch(searchTarget, maxWaitTime):\n \"\"\"Simple method to return SSDP M-SEARCH payload.\n \"\"\"\n msearch = \"\\r\\n\".join(['M-SEARCH * HTTP/1.1',\n 'HOST: 239.255.255.250:1900',\n 'MAN: \"ssdp:discover\"',\n 'ST: {st}', 'MX: {mx}', '', ''])\n return msearch.format(st=searchTarget,\n mx=maxWaitTime)\n\n\nclass socketTTL(object):\n \"\"\"TTL Definition for sockets\n \n Definition table in short:\n 0 - hops on host only.\n 1 - hops over a subnet.\n 4 - UPnP definition - reserved.\n 32 - hops until a site.\n 64 - hops over a region. \n 128 - hops over a continent.\n 255 - hops unrestrictely until reaches maximum.\n \n Note:\n This does NOT mean that setting a HUGE TTL you may reach everything,\n TTL depends on swtich/router.\n \"\"\"\n hostOnlyTTL = 0\n subnetTTL = 1\n UPnPTTL = 4\n siteTTL = 32\n unrestrictedTTL = 255\n\n\nclass NetworkStatus(object):\n \"\"\"Simple network response enum\n \"\"\"\n ok = (0x01, 'Ok')\n error = (0x10, 'Error')\n timeout = (0x20, 'Timeout')\n\n\nclass SSDPResponseParser(JSONSerializable):\n \"\"\"Class to parse SSDP response Object\"\"\"\n\n class _fakeSocket(StringIO):\n \"\"\"Creates a file like object that can be parsed HTTPResponse\"\"\"\n\n def makefile(self, *args, **kw):\n return self\n\n def __init__(self, payload):\n r = HTTPResponse(self._fakeSocket(payload))\n r.begin()\n self.st = r.getheader('st') or None\n self.usn = r.getheader('usn') or None\n self.server = r.getheader('server') or None\n self.location = r.getheader('location') or None\n \n def _usn(self, usn):\n if not usn:\n return None\n \n\n def __repr__(self):\n return \"\".format(**self.__dict__)\n\n\nclass ResponseHandler(JSONSerializable):\n \"\"\"Class to handle and serialize network responses\"\"\"\n \n def __init__(self):\n self.responses = []\n\n def add(self, response):\n try:\n if isinstance(response, UdpPackage):\n self.responses.append(response.data)\n else:\n self.responses.append(response)\n except AttributeError:\n pass\n","sub_path":"protocols/networkutil.py","file_name":"networkutil.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"244879360","text":"import urllib.request,json\nfrom flaskblog.models import Quotes\n\n\n# quotes_url = app.config['QUOTES_URL']\nquotes_url = 'http://quotes.stormconsultancy.co.uk/random.json'\n\n\ndef get_quotes():\n with urllib.request.urlopen(quotes_url) as url:\n get_quotes_data = url.read()\n get_quotes_response = json.loads(get_quotes_data)\n\n quotes_results = None\n\n if get_quotes_response:\n quotes_results = get_quotes_response\n author = quotes_results.get('author')\n id = quotes_results.get('id')\n quote = quotes_results.get('quote')\n\n quote_object = Quotes(author,id,quote)\n\n return quotes_results\n # if get_quotes_response:\n # quotes_results = process_results(get_quotes_response)\n","sub_path":"flaskblog/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"542766961","text":"from django.contrib.auth.models import Group\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\nfrom .models import Task, Comment\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\n\nclass TaskSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Task\n fields = ('id', 'name', 'description', 'creator', 'user', 'completed', 'created', 'edited', 'group')\n read_only_fields = ('id', 'creator', 'created', 'edited')\n\n def validate(self, attrs):\n creator = self.context['request'].user\n user = attrs.get('user')\n group = attrs.get('group')\n group_users = group.user_set.all()\n\n if creator not in group_users:\n raise ValidationError(f'You cannot add user to group {group.name}.')\n\n if user not in group_users:\n raise ValidationError(f'You cannot assign task for user {user.username} to group {group.name}.')\n\n return attrs\n\n\nclass UserSerializer(serializers.ModelSerializer):\n password = serializers.CharField(write_only=True)\n\n def create(self, validated_data):\n user = User.objects.create(\n username=validated_data['username']\n )\n user.set_password(validated_data['password'])\n user.groups.set(validated_data.get('groups', user.groups))\n user.save()\n return user\n\n class Meta:\n model = User\n fields = ('username', 'password', 'groups')\n\n\nclass GroupSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Group\n fields = ('id', 'name')\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n class Meta:\n model = Comment\n fields = ('id', 'creator', 'description', 'task', 'created')\n read_only_fields = ('id', 'creator', 'created')\n\n def validate(self, attrs):\n user_group = self.context['request'].user.groups.all()\n\n task = attrs.get('task')\n task_group = attrs.get('task').group\n creator = self.context['request'].user\n\n last_id = Comment.objects.values_list('pk', flat=True).filter(task=task).order_by('id').last()\n if last_id:\n creator_of_previous_post = Comment.objects.get(id=last_id).creator\n validate_creator(creator, creator_of_previous_post)\n\n if task_group not in user_group:\n raise ValidationError(f'You can not comment on this task because '\n f'your not the member of the group {task_group.name}.')\n\n return attrs\n\n def validate_description(self, description):\n\n content = [description]\n\n if content[0].islower():\n raise ValidationError('Your comment has to start with upper letter')\n\n return description\n\n\ndef validate_creator(current_creator, previous_creator):\n\n if current_creator == previous_creator:\n raise ValidationError('You can not comment on this post twice in a row')\n\n return current_creator, previous_creator\n","sub_path":"TaskApp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"388209016","text":"from __future__ import unicode_literals\nfrom __future__ import absolute_import\nfrom io import BytesIO\nfrom shutil import rmtree\nfrom tempfile import mkdtemp\n\nfrom django.db import connections\nfrom django.test import TestCase\n\nimport corehq.blobs.fsdb as fsdb\nfrom corehq.blobs import CODES\nfrom corehq.blobs.models import BlobMeta\nfrom corehq.blobs.tests.util import get_meta, new_meta\nfrom corehq.form_processor.tests.utils import only_run_with_partitioned_database\nfrom corehq.sql_db.util import get_db_alias_for_partitioned_doc\n\n\nclass TestMetaDB(TestCase):\n\n @classmethod\n def setUpClass(cls):\n super(TestMetaDB, cls).setUpClass()\n cls.rootdir = mkdtemp(prefix=\"blobdb\")\n cls.db = fsdb.FilesystemBlobDB(cls.rootdir)\n\n @classmethod\n def tearDownClass(cls):\n cls.db = None\n rmtree(cls.rootdir)\n cls.rootdir = None\n super(TestMetaDB, cls).tearDownClass()\n\n def test_new(self):\n metadb = self.db.metadb\n with self.assertRaisesMessage(TypeError, \"domain is required\"):\n metadb.new()\n with self.assertRaisesMessage(TypeError, \"parent_id is required\"):\n metadb.new(domain=\"test\")\n with self.assertRaisesMessage(TypeError, \"type_code is required\"):\n metadb.new(domain=\"test\", parent_id=\"test\")\n meta = metadb.new(\n domain=\"test\",\n parent_id=\"test\",\n type_code=CODES.multimedia,\n )\n self.assertEqual(meta.id, None)\n self.assertTrue(meta.key)\n\n def test_save_on_put(self):\n meta = new_meta()\n self.assertEqual(meta.id, None)\n self.db.put(BytesIO(b\"content\"), meta=meta)\n self.assertTrue(meta.id)\n saved = get_meta(meta)\n self.assertTrue(saved is not meta)\n self.assertEqual(saved.key, meta.key)\n\n def test_save_properties(self):\n meta = new_meta(properties={\"mood\": \"Vangelis\"})\n self.db.put(BytesIO(b\"content\"), meta=meta)\n self.assertEqual(get_meta(meta).properties, {\"mood\": \"Vangelis\"})\n\n def test_save_empty_properties(self):\n meta = new_meta()\n self.assertEqual(meta.properties, {})\n self.db.put(BytesIO(b\"content\"), meta=meta)\n self.assertEqual(get_meta(meta).properties, {})\n dbname = get_db_alias_for_partitioned_doc(meta.parent_id)\n with connections[dbname].cursor() as cursor:\n cursor.execute(\n \"SELECT id, properties FROM blobs_blobmeta WHERE id = %s\",\n [meta.id],\n )\n self.assertEqual(cursor.fetchall(), [(meta.id, None)])\n\n def test_delete(self):\n meta = new_meta()\n self.db.put(BytesIO(b\"content\"), meta=meta)\n self.db.delete(key=meta.key)\n with self.assertRaises(BlobMeta.DoesNotExist):\n get_meta(meta)\n\n def test_delete_missing_meta(self):\n meta = new_meta()\n self.assertFalse(self.db.exists(key=meta.key))\n # delete should not raise\n self.db.metadb.delete(meta.key, 0)\n\n def test_bulk_delete(self):\n metas = []\n for name in \"abc\":\n meta = new_meta(parent_id=\"parent\", name=name)\n meta.content_length = 0\n metas.append(meta)\n self.db.metadb.put(meta)\n a, b, c = metas\n self.db.metadb.bulk_delete([a, b])\n for meta in [a, b]:\n with self.assertRaises(BlobMeta.DoesNotExist):\n get_meta(meta)\n get_meta(c) # should not have been deleted\n\n def test_bulk_delete_unsaved_meta_raises(self):\n meta = new_meta()\n with self.assertRaises(ValueError):\n self.db.metadb.bulk_delete([meta])\n\n\n@only_run_with_partitioned_database\nclass TestPartitionedMetaDB(TestMetaDB):\n pass\n","sub_path":"corehq/blobs/tests/test_metadata.py","file_name":"test_metadata.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"331982321","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nimport boto3\nfrom botocore.exceptions import ClientError\nimport re\n\nfrom study.utils.file_tree_generator import FileTreeGenerator\n\n\ns3_client = boto3.client('s3')\nBUCKET_NAME = 'letsstudy-test'\n\n\nclass CloudStorageFileDetail(APIView):\n permission_classes = (IsAuthenticated,)\n\n def post(self, request, format=None):\n groupId = request.data['groupId']\n file_path_in_group = request.data['filepath']\n file_path = '{}/{}'.format(groupId, file_path_in_group)\n try:\n url = s3_client.generate_presigned_url(\n 'get_object',\n Params={\n 'Bucket': BUCKET_NAME,\n 'Key': file_path,\n },\n ExpiresIn=3600)\n return Response(url, status=status.HTTP_200_OK)\n except ClientError as e:\n return Response({'error': e}, status.HTTP_204_NO_CONTENT)\n\n\nclass CloudStorageFileDelete(APIView):\n permission_classes = (IsAuthenticated,)\n\n # Doesn't check whether the file exists in the storage\n def post(self, request, format=None):\n groupId = request.data['groupId']\n file_path_in_group = request.data['filepath']\n file_path = '{}/{}'.format(groupId, file_path_in_group)\n try:\n response = s3_client.delete_object(\n Bucket=BUCKET_NAME,\n Key=file_path\n )\n return Response('', status=status.HTTP_200_OK)\n except ClientError as e:\n return Response({'error': e}, status.HTTP_204_NO_CONTENT)\n\n\nclass CloudStorageFileCreate(APIView):\n permission_classes = (IsAuthenticated,)\n\n def post(self, request, format=None):\n groupId = request.data['groupId']\n file_path_in_group = request.data['filepath']\n file_path = '{}/{}'.format(groupId, file_path_in_group)\n try:\n url = s3_client.generate_presigned_url(\n 'put_object',\n Params={\n 'Bucket': BUCKET_NAME,\n 'Key': file_path,\n },\n ExpiresIn=3600)\n return Response(url, status=status.HTTP_200_OK)\n except ClientError as e:\n return Response({'error': e})\n\n\nclass CloudStorageFileTree(APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, format=None):\n groupId = self.request.query_params.get('groupId')\n try:\n response = s3_client.list_objects_v2(Bucket=BUCKET_NAME)\n global_file_paths = map(lambda content: content['Key'], response['Contents'])\n file_paths = self.filter_group_file_paths(global_file_paths, groupId)\n file_tree = FileTreeGenerator().put_all(file_paths).tree\n return Response(file_tree)\n except ClientError as e:\n return Response({'error': e})\n\n def filter_group_file_paths(self, global_file_paths, groupId):\n group_file_paths = filter(\n lambda global_file_path: re.match(r'^{}/'.format(groupId), global_file_path),\n global_file_paths)\n file_paths = map(\n lambda file_path: re.sub(r'^{}/'.format(groupId), '', file_path),\n group_file_paths)\n return file_paths\n","sub_path":"study/cloud_storage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"134543812","text":"import numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import GRU\nfrom keras.layers import RNN\nfrom keras.utils import np_utils\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.utils.np_utils import to_categorical\nimport keras.callbacks\nimport re\nimport pickle\n\nfrom keras.models import load_model\n\n\nclass History(keras.callbacks.Callback):\n #will contain all loss values for every epoch run\n def on_train_begin(self, logs={}):\n self.losses=[]\n def on_batch_end(self, batch, logs={}):\n self.losses.append(logs.get('loss'))\n with open('128gru40_losses.pickle', 'wb') as handle:\n pickle.dump(self.losses, handle)\n\n with open('128gru40.pickle', 'wb') as handle:\n pickle.dump(self.losses, handle)\n\n\n #save five models to use later to show text gen\n def on_epoch_end(self, epoch, logs={}):\n if epoch % 20 == 0:\n self.model.save(\"128gru40_at_epoch{}.hd5\".format(epoch))\n \nf = open('corpus.txt', 'r')\ntxt = ''\nfor line in f:\n txt+=line\n\ntxt = re.sub(' +', ' ', txt)\ntxt = txt.lower()\n\ncharacters = sorted(list(set(txt)))\n\nn_to_char = {n:char for n, char in enumerate(characters)}\nchar_to_n = {char:n for n, char in enumerate(characters)}\n\nvocab_size = len(characters)\nprint('Number of unique characters: ', vocab_size)\nprint(characters)\n\n\nX = []\nY = []\ncorp_len = len(txt)\nseq_len = 40\n\nfor i in range(0, corp_len - seq_len, 1):\n seq = txt[i:i+seq_len]\n label = txt[i + seq_len]\n X.append([char_to_n[char] for char in seq])\n Y.append(char_to_n[label])\n \nprint('num of extracted seqs: ', len(X))\n\nx_mod = np.reshape(X, (len(X), seq_len, 1))\nx_mod = x_mod / float(len(characters))\nY_mod = to_categorical(Y)\n\nmodel = load_model('128gru40_at_epoch20.hd5')\nmodel.compile(loss='categorical_crossentropy', optimizer='adam')\n\n# define how model checkpoints are saved\n# filepath = \"model_weights-{epoch:02d}-{loss:.4f}.hdf5\"\n# checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')\nhistory = History()\nmodel.fit(x_mod, Y_mod, epochs=20, batch_size=128, callbacks = [history])\n\n# loss = history\n# val_loss = history.history['val_loss']\n\n\nlosses = history.losses\nepochs = range(len(losses))\n\nplt.plot(epochs, losses, 'b', label='Loss')\n# plt.plot(epochs, val_loss, 'r', label='Validation loss')\nplt.title('GRU Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\n# plt.show()\nplt.savefig('lossplot_128gru40.png')\n\nwith open('128gru40.pickle', 'wb') as handle:\n pickle.dump(history, handle)\n\n","sub_path":"128gru40.py","file_name":"128gru40.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"115581252","text":"#===============================================================================\n#\n# Secure Camera Library\n#\n# GENERAL DESCRIPTION\n# build script\n#\n# Copyright (c) 2016-2017 by Qualcomm Technologies, Inc. All Rights Reserved.\n# Qualcomm Technologies Proprietary and Confidential.\n#\n#-------------------------------------------------------------------------------\n#\n# $Header: //components/rel/apps.tz/2.0.2/securemsm/trustzone/qsapps/seccamlib/src/SConscript#1 $\n# $DateTime: 2018/02/06 03:27:17 $\n# $Author: pwbldsvc $\n# $Change: 15400261 $\n# EDIT HISTORY FOR FILE\n#\n# This section contains schedulerents describing changes made to the module.\n# Notice that changes are listed in reverse chronological order.\n#\n# when who what, where, why\n# -------- --- ---------------------------------------------------------\n# 08/14/17 dr Port to sdm845\n# 01/01/17 dr Created\n#===============================================================================\nImport('env')\nenv = env.Clone()\n\n\nlibname = 'seccam_lib'\n\nincludes = [\n \"${BUILD_ROOT}/core/api/services\",\n \"${BUILD_ROOT}/ssg/api/securemsm/trustzone/qsee\",\n \"${BUILD_ROOT}/core/api/kernel/libstd/stringl\",\n \"${BUILD_ROOT}/ssg/securemsm/accesscontrol/api\",\n \"${BUILD_ROOT}/core/kernel/smmu/ACv3.0/common/inc\",\n \"${BUILD_ROOT}/ssg/securemsm/trustzone/qsee/include/\",\n \"${BUILD_ROOT}/ssg/securemsm/trustzone/qsee/mink/include/\",\n \"../inc\",\n]\n\nsources = ['seccamlib.c',]\n\nlib = env.SecureAppLibBuilder(\n includes = includes,\n sources = sources,\n libname = libname,\n deploy_sources = ['SConscript',\n env.Glob('../inc/*.h'),\n ],\n deploy_lib = True,\n deploy_variants = env.GetDefaultPublicVariants()\n )\nReturn('lib')\n","sub_path":"trustzone_images/apps/securemsm/trustzone/qsapps/seccamlib/src/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"100169197","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport io\nimport itertools\n\nimport mock\nimport pytest\n\nfrom octane.util import db\nfrom octane.util import ssh\n\n\ndef test_mysqldump_from_env(mocker, mock_open, mock_subprocess, mock_ssh_popen,\n node):\n test_contents = b'test_contents\\nhere'\n buf = io.BytesIO()\n\n mock_open.return_value.write.side_effect = buf.write\n\n get_one_node_of = mocker.patch('octane.util.env.get_one_node_of')\n get_one_node_of.return_value = node\n\n proc = mock_ssh_popen.return_value.__enter__.return_value\n proc.stdout = io.BytesIO(test_contents)\n\n db.mysqldump_from_env('env', 'controller', ['db1'], 'filename')\n\n assert not mock_subprocess.called\n mock_ssh_popen.assert_called_once_with(\n ['bash', '-c', mock.ANY], stdout=ssh.PIPE, node=node)\n mock_open.assert_called_once_with('filename', 'wb')\n assert buf.getvalue() == test_contents\n\n\ndef test_mysqldump_restore_to_env(mocker, mock_open, mock_subprocess,\n mock_ssh_popen, node):\n test_contents = b'test_contents\\nhere'\n buf = io.BytesIO()\n\n mock_open.return_value = io.BytesIO(test_contents)\n\n get_one_node_of = mocker.patch('octane.util.env.get_one_node_of')\n get_one_node_of.return_value = node\n\n proc = mock_ssh_popen.return_value.__enter__.return_value\n proc.stdin.write.side_effect = buf.write\n\n db.mysqldump_restore_to_env('env', 'controller', 'filename')\n\n assert not mock_subprocess.called\n mock_ssh_popen.assert_called_once_with(\n ['sh', '-c', mock.ANY], stdin=ssh.PIPE, node=node)\n mock_open.assert_called_once_with('filename', 'rb')\n assert buf.getvalue() == test_contents\n\n\ndef test_db_sync(mocker, node, mock_subprocess, mock_ssh_call):\n get_one_controller = mocker.patch('octane.util.env.get_one_controller')\n get_one_controller.return_value = node\n\n fix_migration_mock = mocker.patch(\"octane.util.db.fix_neutron_migrations\")\n\n db.db_sync('env')\n\n fix_migration_mock.assert_called_once_with(node)\n\n assert not mock_subprocess.called\n assert all(call[1]['parse_levels']\n for call in mock_ssh_call.call_args_list)\n assert all(call[1]['node'] == node\n for call in mock_ssh_call.call_args_list)\n\n\n@pytest.mark.parametrize((\"version\", \"result\"), [\n (\"6.1\", False),\n (\"7.0\", True),\n (\"8.0\", False),\n])\ndef test_does_perform_flavor_data_migration(version, result):\n env = mock.Mock(data={\"fuel_version\": version})\n assert db.does_perform_flavor_data_migration(env) == result\n\n\n@pytest.mark.parametrize((\"statuses\", \"is_error\", \"is_timeout\"), [\n ([(0, 0)], True, False),\n ([(0, 0)], False, False),\n ([(10, 0), (10, 5), (5, 5)], False, False),\n ([(10, 0)], False, True),\n])\ndef test_nova_migrate_flavor_data(mocker, statuses, is_error, is_timeout):\n env = mock.Mock()\n mocker.patch(\"time.sleep\")\n mocker.patch(\"octane.util.env.get_one_controller\")\n mock_output = mocker.patch(\"octane.util.ssh.call_output\")\n attempts = len(statuses)\n mock_output.side_effect = itertools.starmap(FLAVOR_STATUS.format, statuses)\n if is_error:\n mock_output.side_effect = None\n mock_output.return_value = \"UNRECOGNIZABLE\"\n with pytest.raises(Exception) as excinfo:\n db.nova_migrate_flavor_data(env, attempts=attempts)\n assert excinfo.exconly().startswith(\n \"Exception: The format of the migrate_flavor_data command\")\n elif is_timeout:\n with pytest.raises(Exception) as excinfo:\n db.nova_migrate_flavor_data(env, attempts=attempts)\n assert excinfo.exconly().startswith(\n \"Exception: After {0} attempts flavors data migration\"\n .format(attempts))\n else:\n db.nova_migrate_flavor_data(env, attempts=attempts)\n\nFLAVOR_STATUS = \"{0} instances matched query, {1} completed\"\n\n\n@pytest.mark.parametrize((\"version\", \"result\"), [\n (\"6.1\", False),\n (\"7.0\", True),\n (\"8.0\", False),\n])\ndef test_does_perform_cinder_volume_update_host(version, result):\n env = mock.Mock(data={\"fuel_version\": version})\n assert db.does_perform_cinder_volume_update_host(env) == result\n\n\ndef test_cinder_volume_update_host(mocker):\n mock_orig_env = mock.Mock()\n mock_new_env = mock.Mock()\n\n mock_orig_cont = mock.Mock()\n mock_new_cont = mock.Mock()\n\n mock_get = mocker.patch(\"octane.util.env.get_one_controller\")\n mock_get.side_effect = [mock_orig_cont, mock_new_cont]\n\n mock_get_current = mocker.patch(\"octane.util.db.get_current_host\")\n mock_get_new = mocker.patch(\"octane.util.db.get_new_host\")\n\n mock_ssh = mocker.patch(\"octane.util.ssh.call\")\n db.cinder_volume_update_host(mock_orig_env, mock_new_env)\n mock_ssh.assert_called_once_with(\n [\"cinder-manage\", \"volume\", \"update_host\",\n \"--currenthost\", mock_get_current.return_value,\n \"--newhost\", mock_get_new.return_value],\n node=mock_new_cont, parse_levels=True)\n assert mock_get.call_args_list == [\n mock.call(mock_orig_env),\n mock.call(mock_new_env),\n ]\n mock_get_current.assert_called_once_with(mock_orig_cont)\n mock_get_new.assert_called_once_with(mock_new_cont)\n\n\n@pytest.mark.parametrize((\"func\", \"content\", \"expected\"), [\n (db.get_current_host, [\n (None, \"DEFAULT\", None, None),\n (None, \"DEFAULT\", \"host\", \"fakehost\"),\n (None, \"DEFAULT\", \"volume_backend_name\", \"fakebackend\"),\n ], \"fakehost#fakebackend\"),\n (db.get_new_host, [\n (None, \"DEFAULT\", None, None),\n (None, \"DEFAULT\", \"host\", \"fakehost_default\"),\n (None, \"RBD-backend\", None, None),\n (None, \"RBD-backend\", \"volume_backend_name\", \"fakebackend\"),\n ], \"fakehost_default@fakebackend#RBD-backend\"),\n (db.get_new_host, [\n (None, \"DEFAULT\", None, None),\n (None, \"DEFAULT\", \"host\", \"fakehost_default\"),\n (None, \"RBD-backend\", None, None),\n (None, \"RBD-backend\", \"backend_host\", \"fakehost_specific\"),\n (None, \"RBD-backend\", \"volume_backend_name\", \"fakebackend\"),\n ], \"fakehost_specific@fakebackend#RBD-backend\"),\n])\ndef test_get_hosts_functional(mocker, func, content, expected):\n mock_node = mock.Mock()\n mocker.patch(\"octane.util.ssh.sftp\")\n mock_iter = mocker.patch(\"octane.util.helpers.iterate_parameters\")\n mock_iter.return_value = content\n result = func(mock_node)\n assert expected == result\n","sub_path":"octane/tests/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"636495855","text":"\"\"\"\r\nSet Patient Hospital form\r\n\r\nDjango form for transferring patients.\r\n\r\n=== Fields ===\r\n\r\npatient_id -- (CharField) email ID of the patient being transferred\r\nhospital ---- (ChoiceField) hospital that the patient is being transferred to\r\n\r\n=== Methods ===\r\n\r\n__init__ --------- Initializes the form.\r\nbuild_form_dict -- Creates a dictionary of all the set patient hospital forms for each patient.\r\nhandle_post ------ Transfers patient given a completed form.\r\n\r\n\"\"\"\r\n\r\nfrom django import forms\r\nfrom HealthApp import staticHelpers\r\nfrom HealthApp.models import Hospital, Patient, LogEntry, Message\r\n\r\n\r\nclass SetPatientHospital(forms.ModelForm):\r\n def __init__(self, patient):\r\n super().__init__()\r\n staticHelpers.set_form_id(self, \"SetPatientHospital\")\r\n\r\n self.fields['patient_id'] = forms.CharField(widget=forms.HiddenInput(), initial=patient.id)\r\n\r\n # Generate hospital ChoiceField\r\n hospital_tuple = tuple(Hospital.objects.all().values_list(\"id\", \"name\").order_by(\"name\"))\r\n\r\n self.fields['hospital'] = forms.ChoiceField(\r\n widget=forms.Select(attrs={'class': 'form-control', 'placeholder': 'Hospital'}),\r\n choices=hospital_tuple,\r\n label='Hospital',\r\n initial=patient.hospital)\r\n\r\n class Meta:\r\n model = Patient\r\n fields = ('hospital',)\r\n\r\n @classmethod\r\n def build_form_dict(cls, all_patients):\r\n forms_dict = dict()\r\n\r\n for patient in all_patients:\r\n forms_dict[patient.username] = SetPatientHospital(patient)\r\n\r\n return forms_dict\r\n\r\n @classmethod\r\n def handle_post(cls, user_type, doctor, post_data):\r\n if user_type == staticHelpers.UserTypes.doctor:\r\n patient_id = post_data['patient_id']\r\n patient = Patient.objects.all().filter(id=patient_id)[0]\r\n\r\n hospital_id = post_data['hospital']\r\n patient.hospital = Hospital.objects.all().filter(id=hospital_id)[0]\r\n\r\n patient.save()\r\n\r\n LogEntry.log_action(doctor.username, \"Transferred patient \" + patient.username + \" to \" +\r\n patient.hospital.name)\r\n Message.sendNotifMessage(patient.username, \"You have been transferred to a new hospital\",\r\n \"Your new hospital is \" + patient.hospital.full_string())","sub_path":"HealthApp/forms/set_patient_hospital.py","file_name":"set_patient_hospital.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"618349250","text":"# coding=utf-8\nfrom __future__ import print_function, absolute_import, unicode_literals\n\nimport sys\nimport json\nimport numpy as np\nimport pandas as pd\nimport talib as ta\nfrom gm.api import *\n\ndef init(context):\n\n #context.avglen = 3 # 布林均线周期参数\n context.disp = 20 # 布林平移参数\n #ontext.sdlen = 13 # 布林标准差参数\n context.sdev = 1.03 # 布林通道倍数参数\n\n context.frequency = \"900s\"\n # context.goods交易的品种\n context.symbol = 'SHFE.AU'\n context.fields = \"high,low,close\"\n context.period = context.disp + 1 # 订阅数据滑窗长度\n #TimeFilter优化 \n #context.window_now = ['14:00:00', '09:45:00']\n\n # 订阅context.goods里面的品种, bar频率为frequency\n subscribe(symbols=context.symbol,frequency=context.frequency,count=context.period,wait_group=True)\n\ndef on_bar(context, bars):\n \n # 获取数据\n close_prices = context.data(symbol=context.symbol,frequency=context.frequency,\n count=context.period,fields='close')\n trade_prices = context.data(symbol=context.symbol,frequency=context.frequency,\n count=context.period,fields='high,low')\n last_price = close_prices['close'][context.disp-1]\n\n avgval = ta.MA(np.array(close_prices['close']), context.disp-13) \n sdmult = ta.STDDEV(np.array(close_prices['close']), context.disp-3)*context.sdev\n #布林带上线\n disptop = avgval[context.disp-1] + sdmult[-1]\n #布林带下线\n dispup = avgval[context.disp-1] - sdmult[-1]\n\n #print(\"last_price: \",last_price, \"avgval: \",avgval[context.disp-1],\"disptop: \",disptop,\"dispup\",dispup)\n HigherBand = disptop\n LowerBand = dispup\n\n #获取账户持仓字典\n Account_positions = context.account().positions()\n #当前持仓方向\n if len(Account_positions)>0:\n position_side = Account_positions[0]['side']\n else:\n position_side = 0\n \n #上穿布林带上带且未持仓\n if trade_prices['high'][context.disp-1] > disptop and position_side==0:\n print(str(context.now),\"做多\")\n # 开多仓\n order_target_percent(symbol=context.symbol, percent=0.1, position_side=1,\n order_type=OrderType_Limit, price=HigherBand)\n #下穿布林带均线且持多头仓\n if trade_prices['low'][context.disp-1] < avgval[context.disp-1] and position_side == 1:\n print(str(context.now),\"平多\")\n # 平多仓\n order_target_percent(symbol=context.symbol, percent=0, position_side=1, order_type=2)\n\n #下穿布林带下带且未持仓\n if trade_prices['low'][context.disp-1] < dispup and position_side==0:\n print(str(context.now),\"做空\")\n # 开空仓\n order_target_percent(symbol=context.symbol, percent=0.1, position_side=2,\n order_type=OrderType_Limit, price=LowerBand)\n #上穿布林带均线且持空头仓\n if trade_prices['high'][context.disp-1] > avgval[context.disp-1] and position_side == 2:\n print(str(context.now),\"平空\")\n # 平空仓\n order_target_percent(symbol=context.symbol, percent=0, position_side=2, order_type=2)\n \n\"\"\" \ndef on_backtest_finished(context, indicator):\n \n #以下用于在回测结束后保存回测指标\n indicator_data = {}\n indicator_data = indicator\n file_name = '20_0_95'\n \n if indicator_data[\"sharp_ratio\"]>0:\n with open('E:/Program Files/other/交易系统作业/代码/作业五/indicator/'+file_name+'.json','w',encoding=\"utf-8\") as json_file:\n json.dump(indicator_data, json_file)\n \n print(\"WINDOW %s done!\"%(file_name))\n\"\"\"\n\nif __name__ == '__main__':\n run(strategy_id='cc314c5e-0598-11e9-abd7-3c970e853b38',\n filename='project5_3.py',\n mode=MODE_BACKTEST,\n token='8401315ba754693611d3bb99131e9cbc527c605f',\n backtest_start_time='2016-10-20 09:15:00',\n backtest_end_time='2018-11-24 15:00:00',\n backtest_adjust=ADJUST_PREV,\n backtest_initial_cash=1000000,\n backtest_commission_ratio=0.0002,\n backtest_slippage_ratio=0)#.0001)\n","sub_path":"trading_system/project5/project5_3.py","file_name":"project5_3.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"45556164","text":"# -*- coding:utf-8 -*- \nfrom ctypes import *\nimport math\nimport random\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import text\nimport json\nimport sys\n# import lstm\nsys.path.append(\"..\")\nimport util\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\nwith open('/home/nvidia/Horus/config.cnf') as f:\n cnf = json.load(f)\nlib = CDLL(str(cnf['darknet_path'])+'libdarknet.so', RTLD_GLOBAL)\n\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\ndraw_box = lib.draw_box\ndraw_label = lib.draw_label\nget_label = lib.get_label\nsave_image = lib.save_image\ndraw_box_width=lib.draw_box_width\n\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\nwith open('/home/nvidia/Horus/config.cnf') as f:\n cnf = json.load(f)\nnet = load_net(str(cnf['darknet_path'])+'cfg/'+str(cnf['cfg'])+'.cfg', str(cnf['darknet_path'])+'weight/'+str(cnf['weight'])+'.weights', 0)\n# net = load_net(str(cnf['darknet_path'])+'cfg/yolo9000.cfg', str(cnf['darknet_path'])+'weight/yolo.weights', 0)\n\n#初始化LSTM\n# lstm_bl=lstm.BasicLSTM()\n\n# c=config.TIME_FREQUENCY\n# if c == 0:\n# c = 200\n# elif c == None:\n# c = 200\n# timeF = c/1000.0\n\n#是否是所要的分类数据\ndef isPass(name):\n if name=='car' or name=='motorcycle' or name=='bus' or name=='truck' or name=='stop sign' or name=='traffic light' or name=='person' or name=='bicycle' or name=='clock':\n return True\n else:\n return False\n\n#处理tb_object数据\ndef dealData(name,probability,img_id,p_x,p_y,p_w,p_h):\n\n with open('/home/nvidia/Horus/config.cnf') as json_data:\n cnf = json.load(json_data) \n db = create_engine(cnf['db'])\n \n if not name.strip():\n pass\n else: \n resultProxy=db.execute(text('select * from tb_classify where classify = :classify'), {'classify':name})\n result = resultProxy.fetchall()\n if not result:\n db.execute(text('insert into tb_classify(classify) values( :classify)'), {'classify':name})\n\n resultProxy_id=db.execute(text('select id from tb_classify where classify = :classify'), {'classify':name})\n id_result = resultProxy_id.fetchall()\n\n type_id=id_result[0][0]\n insert_obj=\"insert into tb_object(type_id,probability,img_id,p_x,p_y,p_w,p_h) values (%s,%s,%s,%s,%s,%s,%s)\"%(type_id,probability,img_id,p_x,p_y,p_w,p_h)\n db.execute(insert_obj)\n\n # draw_box_width(im,int(p_x-p_w/2.),int(p_y-p_h/2.),int(p_x+p_w/2.),int(p_y+p_h/2.),3,255,0,0)\n # save_image(im,cnf['detect_path']+'/'+img_id)\n\n#处理统计数据\ndef dealDtatistics(img_id,car,motorcycle,bus,truck,stop_sign,traffic_light,person,bicycle,clock):\n with open('/home/nvidia/Horus/config.cnf') as json_data:\n cnf = json.load(json_data) \n db = create_engine(cnf['db'])\n\n insert=\"insert into tb_object_statistics(img_id,car,motorcycle,bus,truck,stop_sign,traffic_light,person,bicycle,clock) values (%s,%d,%d,%d,%d,%d,%d,%d,%d,%d)\"%(img_id,car,motorcycle,bus,truck,stop_sign,traffic_light,person,bicycle,clock)\n db.execute(insert)\n # #LSTM判断危险级别\n # pred_list=[[bicycle,bus,car,clock,person,stop_sign,traffic_light,truck,0]]\n # result=lstm_bl.prediction(pred_list)\n # print(\"lstm----:%d\",result)\n # sqlInsert='insert into tb_camera(timestamp,img_id,frequency,result) values(%s,%s,%s,%d)'%(img_id,img_id,timeF,result)\n # db.execute(sqlInsert)\n\n\n\n\n\n\ndef detect(image, hier_thresh=.5, nms=.45):\n with open('/home/nvidia/Horus/config.cnf') as f:\n cnf = json.load(f)\n meta = load_meta(str(cnf['darknet_path'])+'cfg/'+str(cnf['model'])+'.data')\n boxes = make_boxes(net)\n probs = make_probs(net)\n num = num_boxes(net)\n im = load_image(image, 0, 0)\n network_detect(net, im, float(cnf['probability']), hier_thresh, nms, boxes, probs)\n res = []\n img_id=util.OnlyNumber(image)\n \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].w/2., boxes[j].y-boxes[j].h/2., boxes[j].w, boxes[j].h)))\n if isPass(meta.names[i]):\n dealData(meta.names[i],probs[j][i],img_id,boxes[j].x, boxes[j].y, boxes[j].w, boxes[j].h)\n\n res = sorted(res, key=lambda x: -x[1])\n if len(res)>0:\n car=0\n motorcycle=0\n bus=0\n truck=0\n stop_sign=0\n traffic_light=0\n person=0\n bicycle=0\n clock=0\n for m in range(len(res)):\n name=res[m][0]\n if name=='car':\n car += 1\n elif name=='motorcycle':\n motorcycle += 1\n elif name=='bus':\n bus += 1\n elif name=='truck':\n truck += 1\n elif name=='stop sign':\n stop_sign += 1\n elif name=='traffic light':\n traffic_light += 1\n elif name=='person':\n person += 1\n elif name=='bicycle':\n bicycle += 1\n elif name=='clock':\n clock +=1\n dealDtatistics(img_id,car,motorcycle,bus,truck,stop_sign,traffic_light,person,bicycle,clock)\n\n\n free_image(im)\n free_ptrs(cast(probs, POINTER(c_void_p)), num)\n return res\n\n\n \n\n","sub_path":"darknet/darknet.py","file_name":"darknet.py","file_ext":"py","file_size_in_byte":7477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"334624523","text":"import random\n\nprint(\"Welcome to Camel!\")\nprint(\"You have stolen a camel to make your way across the great Mobi desert.\")\nprint(\"The natives want their camel back and are chasing you down!\")\nprint(\"Survive your desert trek and outrun the natives.\")\n\nmiles_traveled = 0\nthirst = 0\ncamel_tiredness = 0\nnatives_distance = -20\nDrinks_in_canteen = 3\n\ndone = False\nwhile not done:\n print(\"\")\n print(\"A. Drink from your canteen.\")\n print(\"B. Ahead moderate speed.\")\n print(\"C. Ahead full speed.\")\n print(\"D. Stop for the night.\")\n print(\"E. Status check.\")\n print(\"Q. Quit.\\n\")\n\n user_choice = input(\"Your choice?\\n\").upper()\n\n if user_choice == \"Q\":\n done = True\n\n elif user_choice == \"E\":\n print(\"Miles traveled: %d\" % miles_traveled)\n print(\"Drinks in canteen: %d\" % Drinks_in_canteen)\n print(\"The natives are %d miles behind you.\" % (miles_traveled - natives_distance))\n\n elif user_choice == \"D\":\n camel_tiredness = 0\n print(\"The camel is happy!\")\n natives_distance += random.randrange(7, 15)\n\n elif user_choice == \"C\":\n x = random.randrange(10, 21)\n miles_traveled += x\n print(\"You have traveled \" + str(x) + \" miles\")\n thirst += 1\n camel_tiredness += random.randrange(1, 4)\n natives_distance += random.randrange(7, 15)\n\n elif user_choice == \"B\":\n y = random.randrange(5, 13)\n miles_traveled += y\n print(\"You have traveled \" + str(y) + \" miles\")\n thirst += 1\n camel_tiredness += random.randrange(0, 2)\n natives_distance += random.randrange(7, 15)\n\n elif user_choice == \"A\":\n if Drinks_in_canteen > 0:\n Drinks_in_canteen += -1\n thirst = 0\n else:\n print(\"You have no more drinks!\")\n\n if not done and thirst > 4:\n if thirst > 6:\n print(\"You died of thirst\")\n done = True\n else:\n print(\"You are thirsty\")\n\n if not done and camel_tiredness > 5:\n if camel_tiredness > 8:\n print(\"Your camel is dead\")\n done = True\n else:\n print(\"Your camel is getting tired\")\n\n if not done and (miles_traveled - natives_distance) < 15:\n if (miles_traveled - natives_distance) == 0:\n print(\"You have been caught by the natives!\")\n done = True\n else:\n print(\"The natives are getting close!\")\n\n if not done and miles_traveled >= 200:\n print(\"You made it across the desert! You win.\")\n done = True\n\n if not done and (user_choice == \"A\" or user_choice == \"B\"):\n z = random.randrange(1, 21)\n if z == 1:\n print(\"You found and oasis!\")\n Drinks_in_canteen = 3\n thirst = 0\n camel_tiredness = 0","sub_path":"CamelGame.py","file_name":"CamelGame.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"447812162","text":"\n\ndef numbers1(n):\n nums = []\n for i in range(n):\n nums.append(i)\n return nums\n\ndef numbers2(n):\n for i in range(n):\n yield i\n\nprint('A')\nfor n in numbers2(200000000):\n print(n)\n\nprint('B')\nfor n in numbers2(20000000):\n print(n)\nprint('C')\n","sub_path":"example_yield.py","file_name":"example_yield.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"15366970","text":"import socket\nimport sys\n\n# Creatae a TCP/IP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Connect the socket to the port where the server is listening\nserver_address = ('192.168.56.108', 7001)\n#server_address = ('127.0.0.1', 7000)\nprint ('connecting to %s port %s' % server_address)\nsock.connect(server_address)\n\ntry:\n\n # Send data\n message = 'close_server_socket'\n print( 'sending \"%s\"' % message)\n sock.sendall(message)\n\n # Look for the response\n amount_received = 0\n amount_expected = len(message)\n data_received = \"\"\n while amount_received < amount_expected:\n data_received = sock.recv(1024)\n amount_received += len(data_received)\n print ('received \"%s\"' % data_received)\n\nfinally:\n print ('closing socket')\n sock.close()","sub_path":"project/server_socket_puerta/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"185823733","text":"import argparse\r\nimport itertools\r\nimport numpy as np\r\nimport pandas as pd\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nplt.rc('text', usetex=True)\r\n\r\n\r\n\"\"\"\r\nINFO8003-1 : Optimal decision making for complex problems\r\n2021 - Assignement 1\r\nPierre NAVEZ & Antoine DEBOR\r\n\r\nSECTION 5 - Q-Learning in a batch setting\r\n\"\"\"\r\n\r\nclass Domain:\r\n def __init__(self, domain_matrix, domain_type, discount_factor, stoch_thresh):\r\n self.domain_matrix = domain_matrix\r\n self.domain_type = domain_type\r\n self.discount_factor = discount_factor\r\n self.stoch_thresh = stoch_thresh\r\n return\r\n\r\n def state_space(self):\r\n \"\"\"\r\n Define dimensions of the considered domain\r\n ---\r\n parameters :\r\n\r\n None\r\n ---\r\n return :\r\n\r\n - height, width : dimensions of the considered domain\r\n \"\"\"\r\n\r\n height = np.shape(self.domain_matrix)[0]\r\n width = np.shape(self.domain_matrix)[1]\r\n return height, width\r\n\r\n def get_state_space_indices(self):\r\n \"\"\"\r\n Build a matrix whose elements are indices of the considered domain's cells\r\n ---\r\n parameters :\r\n\r\n None\r\n ---\r\n return :\r\n\r\n - indices : matrix whose elements are indices of the considered domain's cells\r\n \"\"\"\r\n\r\n n, m = self.state_space()\r\n indices = np.zeros([n, m], dtype=object)\r\n for i in range(n):\r\n for j in range(m):\r\n indices[i, j] = (i, j)\r\n return indices\r\n\r\n def action_space(self):\r\n \"\"\"\r\n Define the action space of the considered domain\r\n ---\r\n parameters :\r\n\r\n None\r\n ---\r\n return :\r\n\r\n - tuple of possible actions\r\n \"\"\"\r\n\r\n return ((1, 0), (0, 1), (-1, 0), (0, -1))\r\n\r\n def reward(self, state, action):\r\n \"\"\"\r\n Compute the reward corresponding to a given action from a given state\r\n ---\r\n parameters :\r\n\r\n - state : current state\r\n - action : action performed from state state\r\n ---\r\n return :\r\n\r\n - reward corresponding to action action, from state state\r\n \"\"\"\r\n\r\n state_prime = self.dynamics(state, action)\r\n return self.get_reward(state_prime)\r\n\r\n def get_reward(self, state):\r\n \"\"\"\r\n Extract the reward corresponding to a given cell from the considered domain\r\n ---\r\n parameters :\r\n\r\n - state : considered cell\r\n ---\r\n return :\r\n\r\n - reward corresponding to cell state\r\n \"\"\"\r\n\r\n x, y = state\r\n return self.domain_matrix[x,y]\r\n\r\n def dynamics(self, state, action):\r\n \"\"\"\r\n Define the dynamics of the considered domain\r\n ---\r\n parameters :\r\n\r\n - state : current state\r\n - action : action performed from state state\r\n ---\r\n return :\r\n\r\n - reward corresponding to action action, from state state, according to the considered domain's dynamics\r\n \"\"\"\r\n\r\n x, y = state\r\n i, j = action\r\n n, m = self.state_space()\r\n\r\n if self.domain_type==\"Deterministic\":\r\n return min(max(x+i, 0), n-1), min(max(y+j, 0), m-1)\r\n\r\n elif self.domain_type==\"Stochastic\":\r\n if random.random() <= self.stoch_thresh:\r\n return min(max(x+i, 0), n-1), min(max(y+j, 0), m-1)\r\n else:\r\n return 0,0\r\n\r\n def MDP_proba(self, state, state_prime, action):\r\n \"\"\"\r\n Compute probability p(x'|x, u) defining the structure of the equivalent MDP\r\n ---\r\n parameters :\r\n\r\n - state : current state x\r\n - state_prime : candidate state x'\r\n - action : performed action u\r\n ---\r\n return :\r\n\r\n - p(x'|x, u)\r\n \"\"\"\r\n\r\n x, y = state\r\n i, j = action\r\n n, m = self.state_space()\r\n if self.domain_type==\"Deterministic\":\r\n return (1 if state_prime==self.dynamics(state, action) else 0)\r\n else:\r\n prob = 0\r\n if state_prime==(min(max(x+i, 0), n-1), min(max(y+j, 0), m-1)):\r\n prob += self.stoch_thresh\r\n if state_prime==(0, 0):\r\n prob += 1-self.stoch_thresh\r\n return prob\r\n\r\n def MDP_reward(self, state, action):\r\n \"\"\"\r\n Compute reward r(x, u) defining the structure of the equivalent MDP\r\n ---\r\n parameters :\r\n\r\n - state : current state x\r\n - action : performed action u\r\n ---\r\n return :\r\n\r\n - r(x, u)\r\n \"\"\"\r\n\r\n if self.domain_type==\"Deterministic\":\r\n return self.reward(state, action)\r\n else:\r\n x, y = state\r\n i, j = action\r\n n, m = self.state_space()\r\n state_prime = (min(max(x+i, 0), n-1), min(max(y+j, 0), m-1))\r\n return self.stoch_thresh * self.get_reward(state_prime) + (1 - self.stoch_thresh) * self.get_reward((0, 0))\r\n\r\ndef state_action_value_function(domain, N):\r\n \"\"\"\r\n Compute the Q-function\r\n ---\r\n parameters :\r\n\r\n - domain : Domain instance corresponding to the considered domain\r\n - N : Maximum iterate of the recursive equation defining the state-action value functions\r\n ---\r\n return :\r\n\r\n - Q_mat : Q(x, u) matrix, for every initial state x and every possible action u\r\n \"\"\"\r\n\r\n n, m = domain.state_space()\r\n actions = domain.action_space()\r\n state_space = domain.get_state_space_indices()\r\n state_space = state_space.reshape(np.size(state_space))\r\n Q_mat = np.zeros([n, m, len(actions)])\r\n r = np.zeros([n, m, len(actions)])\r\n p = np.zeros([n, m, n, m, len(actions)])\r\n for i in range(N):\r\n Q_mat_prime = np.zeros([n, m, len(domain.action_space())])\r\n for x in range(n):\r\n for y in range(m):\r\n state = x, y\r\n for k, action in enumerate(actions):\r\n r[x, y, k] = domain.MDP_reward(state, action)\r\n sum = 0\r\n for state_prime in state_space:\r\n x_prime, y_prime = state_prime\r\n p[x, y, x_prime, y_prime, k] = domain.MDP_proba(state, state_prime, action)\r\n sum += p[x, y, x_prime, y_prime, k] * max(Q_mat[state_prime])\r\n Q_mat_prime[x, y, k] = r[x, y, k] + domain.discount_factor * sum\r\n Q_mat = Q_mat_prime\r\n return Q_mat, r, p\r\n\r\ndef derive_best_policy(domain, Q):\r\n \"\"\"\r\n Derives optimal policy from Q-function\r\n ---\r\n parameters :\r\n\r\n - domain : Domain instance corresponding to the considered domain\r\n - Q : Q-function from which to derive the expected return\r\n ---\r\n return :\r\n\r\n - best_policy : optimal policy derived from Q\r\n \"\"\"\r\n\r\n n, m = domain.state_space()\r\n actions = domain.action_space()\r\n best_policy = np.zeros([n, m], dtype=object)\r\n for x in range(n):\r\n for y in range(m):\r\n best_action = actions[np.argmax(Q[x, y])]\r\n best_policy[x, y] = best_action\r\n return best_policy\r\n\r\ndef derive_best_expected_return(domain, Q):\r\n \"\"\"\r\n Derives optimal expected return from Q-function\r\n ---\r\n parameters :\r\n\r\n - domain : Domain instance corresponding to the considered domain\r\n - Q : Q-function from which to derive the expected return\r\n ---\r\n return :\r\n\r\n - best_return : optimal expected return derived from Q\r\n \"\"\"\r\n\r\n n, m = domain.state_space()\r\n best_return = np.zeros([n, m])\r\n for x in range(n):\r\n for y in range(m):\r\n best_return[x, y] = max(Q[x, y])\r\n return best_return\r\n\r\ndef gen_trajectory(domain, traj_len):\r\n \"\"\"\r\n Generates a random trajectory of a certain size in a certain domain\r\n ---\r\n parameters :\r\n\r\n - domain : Domain instance corresponding to the considered domain\r\n - traj_len : size of the trajectory to generate\r\n ---\r\n return :\r\n\r\n - list corresponding to the generated trajectory\r\n \"\"\"\r\n\r\n traj = list()\r\n n, m = domain.state_space()\r\n x_start = random.randint(0, n-1)\r\n y_start = random.randint(0, m-1)\r\n state = x_start, y_start\r\n for j in range(traj_len):\r\n actions = domain.action_space()\r\n action = actions[random.randint(0, 3)]\r\n state_prime = domain.dynamics(state, action)\r\n r = domain.get_reward(state_prime)\r\n traj.append((state, action, r))\r\n state = state_prime\r\n return traj\r\n\r\ndef pairwise(iterable):\r\n \"\"\"\r\n Re-arrange an iterable pairwise\r\n ---\r\n parameters :\r\n\r\n - iterable : iterable to re-arrange\r\n ---\r\n return :\r\n\r\n - zip corresponding to the pairwise re-arrangement\r\n \"\"\"\r\n\r\n a, b = itertools.tee(iterable)\r\n next(b, None)\r\n return zip(a, b)\r\n\r\ndef arguments_parsing():\r\n \"\"\"\r\n Argument parser function\r\n ---\r\n parameters :\r\n\r\n None\r\n ---\r\n return :\r\n\r\n - args : Keyboard passed arguments\r\n \"\"\"\r\n\r\n parser = argparse.ArgumentParser(description=\"ODMCP - A1 - Section 1\")\r\n\r\n parser.add_argument(\"-stocha\", \"--stochastic\", action='store_true',\r\n help=\"Stochastic character of the domain, option string to be added for stochastic behaviour\")\r\n\r\n parser.add_argument(\"-s_th\", \"--stochastic_threshold\", type=float, default=0.5,\r\n help=\"Stochastic threshold involved in the stochastic dynamics\")\r\n\r\n parser.add_argument(\"-df\", \"--discount_factor\", type=float, default=0.99,\r\n help=\"Discount factor, 0.99 by default\")\r\n\r\n parser.add_argument(\"-f\", \"--domain_instance_file\", type=str, default='instance.csv',\r\n help=\"Filename of the domain instance\")\r\n\r\n parser.add_argument(\"-n_i\", \"--nb_iterations\", type=int, default=1000,\r\n help=\"Number of iterations for the computation of the expected return's approximation\")\r\n\r\n parser.add_argument(\"-lr\", \"--learning_rate\", type=float, default=0.05,\r\n help=\"Constant learning rate used in the Q-learning algorithm, 0.05 by default\")\r\n\r\n args = parser.parse_args()\r\n\r\n if args.stochastic:\r\n print(\"\\nStochastic domain chosen\")\r\n else:\r\n print(\"\\nDeterministic domain chosen (default)\")\r\n\r\n return args\r\n\r\ndef offline_Q_learning(domain, trajectory, alpha):\r\n \"\"\"\r\n Offline Q-Learning implementation\r\n ---\r\n parameters :\r\n\r\n - domain : Domain instance corresponding to the considered domain\r\n - trajectory : trajectory from which to perform the algorithm\r\n - alpha : learning rate\r\n ---\r\n return :\r\n\r\n - Q_hat : estimated Q-function computed with offline Q-Learning\r\n \"\"\"\r\n\r\n n, m = domain.state_space()\r\n actions = domain.action_space()\r\n Q_hat = np.zeros([n, m, len(actions)])\r\n for k, (state, action, r) in enumerate(trajectory):\r\n if k == len(trajectory)-1:\r\n return Q_hat\r\n u = actions.index(action)\r\n x, y = state\r\n x_prime, y_prime = trajectory[k+1][0]\r\n Q_hat[x, y, u] = (1 - alpha) * Q_hat[x, y, u] + alpha * (r + domain.discount_factor * max(Q_hat[x_prime, y_prime]))\r\n\r\nclass Intelligent_agent:\r\n\r\n def __init__(self, domain, state_0):\r\n self.domain = domain\r\n self.state_0 = state_0\r\n self.policy = None\r\n\r\n def select_action(self, Q, state, epsilon):\r\n \"\"\"\r\n Selects an action from a certain state, following an epsilon-greedy policy acc. to Q\r\n ---\r\n parameters :\r\n\r\n - Q : Q-function from which to derive the optimal policy\r\n - state : current state\r\n - epsilon : exploration rate\r\n ---\r\n return :\r\n\r\n - action to take\r\n \"\"\"\r\n\r\n if random.random() < epsilon:\r\n actions = self.domain.action_space()\r\n action = actions[random.randint(0,3)]\r\n return action\r\n else:\r\n self.policy = self.derive_best_policy(Q)\r\n x, y = state\r\n return self.policy[x, y]\r\n\r\n def derive_best_policy(self, Q):\r\n \"\"\"\r\n Derives optimal policy from Q-function\r\n ---\r\n parameters :\r\n\r\n - domain : Domain instance corresponding to the considered domain\r\n - Q : Q-function from which to derive the expected return\r\n ---\r\n return :\r\n\r\n - best_policy : optimal policy derived from Q\r\n \"\"\"\r\n\r\n n, m = self.domain.state_space()\r\n actions = self.domain.action_space()\r\n best_policy = np.zeros([n, m], dtype=object)\r\n for x in range(n):\r\n for y in range(m):\r\n best_action = actions[np.argmax(Q[x, y])]\r\n best_policy[x, y] = best_action\r\n return best_policy\r\n\r\n def online_Q_learning_first(self, alpha, epsilon_0, n_episodes, n_transitions, decay):\r\n \"\"\"\r\n Implements the first protocol\r\n ---\r\n parameters :\r\n\r\n - alpha : learning rate\r\n - epsilon_0 : initial exploration rate\r\n - n_episodes : number of episodes\r\n - n_transitions : number of transitions per episode\r\n - decay : decay factor to apply on epsilon\r\n ---\r\n return :\r\n\r\n - Q_vec : list of derived optimal expected returns (one for each episode)\r\n \"\"\"\r\n\r\n # Online epsilon-greedy Q-learning algorithm - Protocol 1\r\n n, m = self.domain.state_space()\r\n actions = self.domain.action_space()\r\n Q_vec = []\r\n # Initialisation\r\n Q_hat = np.zeros([n, m, len(self.domain.action_space())])\r\n # For each transition in each episode, update of Q_hat\r\n for e in range(n_episodes):\r\n # Reset initial state\r\n state = self.state_0\r\n epsilon = epsilon_0\r\n for t in range(n_transitions):\r\n # Choose action using epsilon-greedy policy derived from Q_hat\r\n action = self.select_action(Q_hat, state, epsilon)\r\n state_prime = self.domain.dynamics(state, action)\r\n r = self.domain.get_reward(state_prime)\r\n # Take action, observe reward and next state\r\n u = actions.index(action)\r\n x, y = state\r\n x_prime, y_prime = state_prime\r\n Q_hat[x, y, u] = (1 - alpha) * Q_hat[x, y, u] + alpha * (r + self.domain.discount_factor * max(Q_hat[x_prime, y_prime]))\r\n state = state_prime\r\n epsilon = decay * epsilon\r\n J_hat = derive_best_expected_return(self.domain, Q_hat)\r\n Q_vec.append(J_hat.copy())\r\n return Q_vec\r\n\r\n def online_Q_learning_second(self, alpha_0, epsilon, n_episodes, n_transitions):\r\n \"\"\"\r\n Implements the second protocol\r\n ---\r\n parameters :\r\n\r\n - alpha_0 : initial learning rate\r\n - epsilon : exploration rate\r\n - n_episodes : number of episodes\r\n - n_transitions : number of transitions per episode\r\n ---\r\n return :\r\n\r\n - Q_vec : list of derived optimal expected returns (one for each episode)\r\n \"\"\"\r\n\r\n # Online epsilon-greedy Q-learning algorithm - Protocol 2\r\n n, m = self.domain.state_space()\r\n actions = self.domain.action_space()\r\n Q_vec = []\r\n # Initialisation\r\n Q_hat = np.zeros([n, m, len(self.domain.action_space())])\r\n # For each transition in each episode, update of Q_hat\r\n for e in range(n_episodes):\r\n # Reset initial state\r\n state = self.state_0\r\n # Reset learning rate ??????\r\n alpha = alpha_0\r\n for t in range(n_transitions):\r\n # Choose action using epsilon-greedy policy derived from Q_hat\r\n action = self.select_action(Q_hat, state, epsilon)\r\n state_prime = self.domain.dynamics(state, action)\r\n r = self.domain.get_reward(state_prime)\r\n # Take action, observe reward and next state\r\n u = actions.index(action)\r\n x, y = state\r\n x_prime, y_prime = state_prime\r\n Q_hat[x, y, u] = (1 - alpha) * Q_hat[x, y, u] + alpha * (r + self.domain.discount_factor * max(Q_hat[x_prime, y_prime]))\r\n state = state_prime\r\n alpha = 0.8 * alpha\r\n J_hat = derive_best_expected_return(self.domain, Q_hat)\r\n Q_vec.append(J_hat.copy())\r\n return Q_vec\r\n\r\n def online_Q_learning_third(self, alpha, epsilon, n_episodes, n_transitions, n_replay):\r\n \"\"\"\r\n Implements the third protocol\r\n ---\r\n parameters :\r\n\r\n - alpha : learning rate\r\n - epsilon : exploration rate\r\n - n_episodes : number of episodes\r\n - n_transitions : number of transitions per episode\r\n - n_replay : number of experience replays per transition\r\n ---\r\n return :\r\n\r\n - Q_vec : list of derived optimal expected returns (one for each episode)\r\n \"\"\"\r\n\r\n # Online epsilon-greedy Q-learning algorithm - Protocol 3\r\n n, m = self.domain.state_space()\r\n actions = self.domain.action_space()\r\n Q_vec = []\r\n # Initialisation\r\n Q_hat = np.zeros([n, m, len(self.domain.action_space())])\r\n buffer = list()\r\n # For each transition in each episode, update of Q_hat\r\n for e in range(n_episodes):\r\n # Reset initial state\r\n state = self.state_0\r\n for t in range(n_transitions):\r\n # Choose action using epsilon-greedy policy derived from Q_hat\r\n action = self.select_action(Q_hat, state, epsilon)\r\n state_prime = self.domain.dynamics(state, action)\r\n r = self.domain.get_reward(state_prime)\r\n # Update buffer\r\n buffer.append((state, action, r, state_prime))\r\n state = state_prime\r\n # Experience replay\r\n for i in range(n_replay):\r\n # Draw randomly an action from the buffer\r\n state_replay, action_replay, reward_replay, state_prime_replay = random.choice(buffer)\r\n u = actions.index(action_replay)\r\n x, y = state_replay\r\n x_prime, y_prime = state_prime_replay\r\n # Update Q_hat\r\n Q_hat[x, y, u] = (1 - alpha) * Q_hat[x, y, u] + alpha * (r + self.domain.discount_factor * max(Q_hat[x_prime, y_prime]))\r\n J_hat = derive_best_expected_return(self.domain, Q_hat)\r\n Q_vec.append(J_hat.copy())\r\n return Q_vec\r\n\r\n\r\nif __name__ == \"__main__\":\r\n random.seed(1)\r\n\r\n args = arguments_parsing()\r\n\r\n domain_matrix = pd.read_csv(args.domain_instance_file, delimiter=',', header=None).values\r\n\r\n print(\"\\nInstance of the domain:\\n{}\".format(domain_matrix))\r\n domain = Domain(domain_matrix,\r\n \"Stochastic\" if args.stochastic else \"Deterministic\",\r\n args.discount_factor, args.stochastic_threshold)\r\n\r\n # --OFFLINE Q-LEARNING--\r\n print(\"\\nOFFLINE Q-LEARNING...\")\r\n T = [pow(10, i) for i in [2, 3, 4, 5, 6]]\r\n T.append(5*10**6)\r\n J_diff = np.zeros([len(T)])\r\n alpha = args.learning_rate\r\n print(\"\\nDeriving the optimal expected return...\")\r\n\r\n Q, _, _ = state_action_value_function(domain, args.nb_iterations)\r\n mu_opt = derive_best_policy(domain, Q)\r\n J_mu_opt = derive_best_expected_return(domain, Q)\r\n print(\"\\nOptimal expected return : \\n{}\".format(J_mu_opt))\r\n print(\"\\nQ-learning algorithm running...\")\r\n for i, t in enumerate(T):\r\n trajectory = gen_trajectory(domain, t)\r\n Q_hat = offline_Q_learning(domain, trajectory, alpha)\r\n mu_hat_opt = derive_best_policy(domain, Q_hat)\r\n J_mu_hat_opt = derive_best_expected_return(domain, Q_hat)\r\n diff = J_mu_hat_opt-J_mu_opt\r\n J_diff[i] = np.linalg.norm(diff.reshape(25),ord=np.inf)\r\n print(J_diff)\r\n plt.plot(T, J_diff)\r\n plt.xscale('log')\r\n plt.xlabel(\"$T$\", fontsize=18)\r\n plt.ylabel(\"$\\\\|J^N_{\\\\hat{\\\\mu}^*}-J^N_{\\\\mu^*}\\\\|_{\\\\infty}$\", fontsize=18)\r\n plt.show()\r\n\r\n print(\"\\nOptimal policy, for length = {} : \\n{}\".format(t, mu_hat_opt))\r\n print(\"\\nOptimal return, for length = {} : \\n{}\".format(t, J_mu_hat_opt))\r\n\r\n # --ONLINE Q-LEARNING--\r\n print(\"\\nONLINE Q-LEARNING...\")\r\n alpha = 0.05\r\n epsilon = 0.25\r\n n_episodes = 100\r\n n_transitions = 1000\r\n n_replay = 10\r\n state_0 = (3,0)\r\n agent = Intelligent_agent(domain, state_0)\r\n\r\n # First protocol\r\n print(\"\\n-- First protocol -- \\n\")\r\n Q = agent.online_Q_learning_first(alpha, epsilon, n_episodes, n_transitions, 1)\r\n Q_diff_1 = np.zeros([n_episodes])\r\n for i, q in enumerate(Q):\r\n Q_diff_1[i] = np.linalg.norm(np.ravel(q-J_mu_opt),ord=np.inf)\r\n\r\n # Second protocol\r\n print(\"\\n-- Second protocol -- \\n\")\r\n Q = agent.online_Q_learning_second(alpha, epsilon, n_episodes, n_transitions)\r\n Q_diff_2 = np.zeros([n_episodes])\r\n for i, q in enumerate(Q):\r\n Q_diff_2[i] = np.linalg.norm(np.ravel(q-J_mu_opt),ord=np.inf)\r\n\r\n # Third protocol\r\n print(\"\\n-- Third protocol -- \\n\")\r\n Q = agent.online_Q_learning_third(alpha, epsilon, n_episodes, n_transitions, n_replay)\r\n Q_diff_3 = np.zeros([n_episodes])\r\n for i, q in enumerate(Q):\r\n Q_diff_3[i] = np.linalg.norm(np.ravel(q-J_mu_opt),ord=np.inf)\r\n\r\n # Comparison\r\n plt.plot(range(1, n_episodes+1), Q_diff_1, label=\"First protocol\")\r\n plt.plot(range(1, n_episodes+1), Q_diff_2, label=\"Second protocol\")\r\n plt.plot(range(1, n_episodes+1), Q_diff_3, label=\"Third protocol\")\r\n plt.legend()\r\n plt.xlabel(\"Number of episodes\", fontsize=18)\r\n plt.ylabel(\"$\\\\|\\\\hat{Q}-J^N_{\\\\mu^*}\\\\|_{\\\\infty}$\", fontsize=18)\r\n plt.show()\r\n\r\n \"\"\"\r\n # \"Decay greedy\"\r\n for decay in [0.95, 0.96, 0.97, 0.99]:\r\n Q = agent.online_Q_learning_first(alpha, epsilon, n_episodes, n_transitions, decay)\r\n Q_diff_1 = np.zeros([n_episodes])\r\n for i, q in enumerate(Q):\r\n Q_diff_1[i] = np.linalg.norm(np.ravel(q-J_mu_opt),ord=np.inf)\r\n plt.plot(range(1, n_episodes+1), Q_diff_1, label=\"$k$ = {}\".format(decay))\r\n plt.legend()\r\n plt.xlabel(\"Number of episodes\", fontsize=18)\r\n plt.ylabel(\"$\\\\|\\\\hat{Q}-J^N_{\\\\mu^*}\\\\|_{\\\\infty}$\", fontsize=18)\r\n plt.savefig(\"comparison_decay.pdf\")\r\n plt.show()\r\n \"\"\"\r\n","sub_path":"Assignment 1/5/section5.py","file_name":"section5.py","file_ext":"py","file_size_in_byte":22500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"270857747","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage.morphology import remove_small_objects\nimport time\nimport math\nimport os\n\nSRC = np.float32(\n [[127 * 2, 315 * 2],\n [239 * 2, 441 * 2],\n [585 * 2, 375 * 2],\n [328 * 2, 305 * 2]])\n\nCAM_MATRIX = np.matrix([[923.6709132611408, 0, 660.3716073305085], [0, 925.6373437421516, 495.2039455113797],\n [0, 0, 1]])\nDIST_COEF = np.array([-0.2947018330961229, 0.09105224521150024, 0.0001143430530863253, 0.0003862123859247846, 0])\n\n\ndef bird_view(image):\n img_size = (image.shape[1], image.shape[0])\n M = cv2.getPerspectiveTransform(SRC, DST)\n return cv2.warpPerspective(image, M, img_size, flags=cv2.INTER_LINEAR)\n\n\nif __name__ == '__main__':\n cap = cv2.VideoCapture('output.avi')\n # count = 0\n # total = 269\n while True:\n ret, frame = cap.read()\n start = time.time()\n height, width, depth = frame.shape\n kernel = np.ones((20, 100), np.uint8)\n\n DST = np.float32(\n [[(width - 716) / 2, 0],\n [(width - 716) / 2, height],\n [width - 282, height],\n [width - 282, 0]]\n )\n\n if not ret:\n break\n\n undistorted_image = cv2.undistort(frame, CAM_MATRIX, DIST_COEF)\n\n viewed = bird_view(undistorted_image)\n\n viewed = cv2.resize(viewed, dsize=(int(height / 2), int(width / 2)))\n\n # if count % 5 == 0:\n # total += 1\n # cv2.imwrite(os.path.join('E:/datasets/parking/birdview', str(total) + '.jpg'), viewed)\n #\n # count += 1\n\n region_of_interest_vertices = [\n (128, height - 128),\n (128, 128),\n (width - 288, 128),\n (width - 288, height - 128),\n ]\n region_of_interest_vertices = np.array([region_of_interest_vertices], dtype=np.int)\n mask = np.zeros_like(viewed)\n\n channels = viewed.shape[2]\n\n match_mask = (255,) * channels\n cv2.fillPoly(mask, region_of_interest_vertices, match_mask)\n\n masked = cv2.bitwise_and(viewed, mask)\n\n blur = cv2.GaussianBlur(masked, (5, 5), 0)\n hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)\n ranged = cv2.inRange(hsv, (5, 5, 150), (255, 255, 255))\n\n dilated_view = cv2.dilate(ranged, kernel, iterations=1)\n eroded_view = cv2.erode(dilated_view, kernel, iterations=1)\n\n ret, thresh = cv2.threshold(eroded_view, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n contours, hierarchy = cv2.findContours(thresh, 1, 2)\n contours_sorted_by_area = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)\n\n contours_coords = []\n\n for j, contour_sort in enumerate(contours_sorted_by_area):\n if 0 in contour_sort or cv2.contourArea(contour_sort) < 100:\n continue\n x, y, w, h = cv2.boundingRect(contour_sort)\n contours_coords.append([x, y, w, h])\n\n contours_sorted_by_x = sorted(contours_coords, key=lambda x: x[1])\n\n if len(contours_sorted_by_x) < 2:\n continue\n\n x1, y1, w1, h1 = contours_sorted_by_x[-1]\n x2, y2, w2, h2 = contours_sorted_by_x[-2]\n\n angle = int(math.atan((y2 - y1 + 1) / (x2 - x1 + 1)) * 180 / math.pi)\n\n if abs(angle) > 80 and abs(angle) < 100 and (y1 - y2) > 175 and (y1 - y2) < 400:\n length = y1 - y2\n cv2.line(viewed, (x1, y1), (x2, y2 + h2), (0, 0, 255), 2)\n cv2.circle(viewed, (x1, y1), 5, (0, 0, 255), 3)\n cv2.circle(viewed, (x2, y2 + h2), 5, (0, 0, 255), 3)\n cv2.circle(viewed, (x2, int((y2 + y1 + h2) / 2)), 5, (0, 255, 255), 3)\n # cv2.putText(viewed, str(length) + 'px', (100, 100), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255, 255, 255))\n\n end = time.time()\n ms = end - start\n cv2.putText(viewed, f'time spent {ms}', (50, 200), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255, 255, 255))\n cv2.imshow('viewed', viewed)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"61830794","text":"import socket\n\nTCP_IP = '127.0.0.1'\nTCP_PORT = 5005\nSERVER_ADDRESS = (TCP_IP, TCP_PORT)\nBUFFER_SIZE = 1024\nMESSAGE = 'HELLO WORLD'\n\ndef main():\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ts.connect(SERVER_ADDRESS)\n\ts.send(MESSAGE)\n\tdata = s.recv(BUFFER_SIZE)\n\ts.close()\n\tprint(\"received data: %s\" % data)\n\nif __name__ == '__main__':\n\tmain()\n\n# https://github.com/bjornedstrom/toytls/blob/master/scripts/toytls-handshake.py\n# http://blog.bjrn.se/2012/07/fun-with-tls-handshake.html\n","sub_path":"handshake.py","file_name":"handshake.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"50964460","text":"# main.py\nimport lvgl as lv\nimport ujson as json\nfrom machine import Pin\n#import cdp_helper as helper\n#import cdp_gui as gui\nfrom cdp_classes import Usuario, StateMachine, Sensor_US, ControlUART\nfrom ili9XXX import ili9341\n\n# ==================== VARIABLES GLOBALES==================== #\n\n# Estados para la FSM\nSTARTING, IDLE, CALIBRATING, SENSOR_READING, USER_SCREEN = range(5)\n\n# Variables de pines\npin_encoder = 35\n\n# Sensor ultrasonido\nsensor_us = Sensor_US(16, 36)\n\n# Comunicacion UART con ATMega328P\nuart = ControlUART(9600, 17, 34)\n\n# Pines de los motores\nmotor_pines = {\n \"Adelante\": {\n 'cabezal' : [13],\n 'apbrazo' : [4, 15],\n 'assdepth' : [14],\n 'assheight' : [26],\n 'lumbar' : [33]\n },\n \"Atras\" : {\n 'cabezal' : [12],\n 'apbrazo' : [2, 0],\n 'assdepth' : [27],\n 'assheight' : [25],\n 'lumbar' : [32]\n }\n}\n\n# Aca se guardan los datos obtenidos del archivo \"cdp_config.json\"\n_global_config = {}\n\n# Aca se guardan las instancias de clase Usuario obtenidas desde motor_data.json\n_users_list = []\n\n# Inicializar pantalla LCD\nlv.init()\ndisp = ili9341(mosi=23, miso=19, clk=18, dc=21, cs=5, rst=22, power=-1, backlight=-1)\n\n# ==================== FUNCIONES ==================== #\n\ndef load_config_from_file_global():\n try:\n with open(\"settings/cdp_config.json\", \"r\") as file:\n _global_config = json.load(file)\n return _global_config\n except OSError:\n print(\"cdp_config.json is missing. Creating a new default one...\")\n with open(\"settings/cdp_config.json\", \"w\") as file:\n c = {\n \"first_time_open\" : True,\n 'calibration_data' : {\n \"assheight\" : ['TBD', ['piezo', [\"as1\", 0, 1023], [\"as2\", 0, 1023]], '000', 1024],\n \"assdepth\" : ['TBD', ['piezo', [\"lu1\", 0, 1023], [\"lu2\", 0, 1023]], '001', 1024],\n \"lumbar\" : ['TBD', ['piezo', [\"lu1\", 0, 1023], [\"lu2\", 0, 1023]], '010', 1024],\n \"cabezal\" : ['TBD', ['ultra'], '011', 1024],\n \"apbrazo\" : ['TBD', ['pin', [\"apb\", 0, 1023], [\"as2\", 0, 1023]], '100', 1024]\n }\n }\n json.dump(c, file)\n return load_config_from_file_global()\n\ndef load_users_from_file_global():\n new_list = []\n\n try:\n with open(\"settings/motor_data.json\", \"r\") as file:\n data = json.load(file)\n for user, config in data.items():\n if user == \"Actuales\":\n continue\n new_list.append(Usuario(user, config))\n return new_list\n except OSError:\n print(\"motor_data.json is missing. Creating a new default one...\")\n with open(\"settings/motor_data.json\", \"w\") as file:\n c = {\n \"Actuales\" : {\n \"cabezal\" : 0,\n \"apbrazo\" : 0,\n \"lumbar\" : 0,\n \"assprof\" : 0,\n \"assheight\" : 0\n }\n }\n json.dump(c, file)\n return load_users_from_file_global()\n\n# O(n^3) <-- Debe haber una manera de hacerlo mas optimo\ndef set_motorpin_output():\n for pin_list in motor_pines.values():\n for value in pin_list.values():\n for index, pin in enumerate(value):\n value[index] = Pin(pin, Pin.OUT, Pin.PULL_DOWN, 0)\n\ndef wait_for_action():\n # TODO: interacción con la GUI\n print(\".\")\n fsm.next_state()\n\ndef main():\n # Establecer entradas y salidas\n set_motorpin_output()\n\n if _global_config[\"first_time_open\"]:\n # TODO: Bienvenida por la GUI + primera calibracion\n print(\"Bienvenido a Silla CDP\")\n _global_config[\"first_time_open\"] = False\n # TODO: Carga de pantalla inicial por la GUI\n print(\"Pantalla de usuarios\")\n\n # Cambiar de estado a espera\n fsm.State = IDLE\n\n# Instancia de la FSM\nfsm = StateMachine((STARTING, main))\n\nif __name__ == \"__main__\":\n # Cargar datos desde archivos (se hace desde aca para modificar la variable global)\n _global_config = load_config_from_file_global()\n _users_list = load_users_from_file_global()\n\n # Agregar estados a la FSM\n fsm.add_states([\n (IDLE, wait_for_action)\n ])\n\n # Arrancar la FSM\n fsm.start()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"93828210","text":"from api.models.investments.user_investments import UserBalance, UserStatement\nfrom api.database.database import db, DBO\nfrom sqlalchemy import func\nfrom datetime import datetime, date\n\n\nclass InvestmentRepository():\n\n @classmethod\n def select_user_balance(cls, user_id):\n actual_user_balance = UserBalance.query.\\\n filter(UserBalance.user_id == user_id).\\\n first()\n if actual_user_balance:\n balance = actual_user_balance.balance\n user_statements = UserStatement.query.\\\n filter(UserStatement.user_id == user_id).\\\n filter(UserStatement.open_operation == 1).\\\n all()\n balance += sum(\n item.investment_value for item in user_statements)\n return balance\n return None\n\n @classmethod\n def save_user_balance(cls, user_id, balance):\n user_balance = UserBalance(user_id=user_id, balance=balance)\n user_balance.save()\n","sub_path":"Allgoo/api-andbank/api/repositories/investment_repository.py","file_name":"investment_repository.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"168687123","text":"from nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport string\nimport re\n\n#Tokenize\ndef Tokenize(string_txt):\n mystring_tokens=word_tokenize(string_txt)\n return mystring_tokens\n\n#Remove Punctuations\ndef rem_punct(string_txt):\n mystring_tokens=Tokenize(string_txt)\n str_tokens=[char for char in mystring_tokens if char not in string.punctuation]\n return \" \".join(str_tokens)\n\n# Remove digits\ndef rem_digits(string_txt):\n proc_txt=re.sub(r'\\d[a-zA-Z0-9\\.\\/\\-\\@]+|[a-zA-Z0-9\\.\\/\\-\\@]+\\d|\\d',' ',string_txt) # Digits replaced with space\n return proc_txt\n \n# Remove web address and mail address\ndef rem_weblnk_mail(string_txt):\n proc_txt=re.sub(r'(https?:\\/\\/)?(www\\.)?[a-zA-Z0-9\\.\\/\\-\\@]\\[a-z]+|[a-zA-Z0-9\\.\\/\\-\\@]+(.com)\\s+|(.com)$',' ',string_txt) # Web_links and mails replaced with space\n return proc_txt \n\n#Remove all the special characters\ndef sp_char(string_txt):\n proc_txt = re.sub(r'\\W',' ',string_txt)\n return proc_txt\n\n#Removing all single characters appearing at the start\ndef sngle_char_strt(string_txt):\n proc_txt = re.sub(r'^\\s+[a-z]\\s+',' ',string_txt)\n return proc_txt\n \n# Remove all single characters \ndef sngle_char(string_txt):\n proc_txt = re.sub(r'\\s+[a-z]\\s+|\\s+[a-z]{2,2}\\s+',' ',string_txt) #|\\s+[a-z]{2,}\\s+\n return proc_txt\n\n#Substitute multiple spaces with a single space\ndef rem_mul_spc(string_txt):\n proc_txt = re.sub(r'\\s+',' ',string_txt, flags=re.I)\n return proc_txt\n\n#Remove stopwords\ndef RemoveStopWords(string_txt):\n mystring_tokens=Tokenize(string_txt) \n stopwords_english = list(set(stopwords.words('english')))\n add_stp_wrds=['http','html','attn','tel']\n stopwords_english.extend(add_stp_wrds)\n post_stopwords=[word for word in mystring_tokens if word.lower() not in stopwords_english]\n return \" \".join(post_stopwords)\n\n# Lemmatize String\ndef Lemmatize(string_txt):\n word_lem=WordNetLemmatizer()\n post_stopword_string = RemoveStopWords(string_txt)\n post_stopword_tokens=Tokenize(post_stopword_string)\n lemm_lst=[ word_lem.lemmatize(word) for word in post_stopword_tokens]\n return \" \".join(lemm_lst)\n\n# Convert string to lower case\ndef to_lower(string_txt):\n str_tokens=Tokenize(string_txt)\n str_tokens=[char.lower() for char in str_tokens]\n return \" \".join(str_tokens)\n\n#Substitute blank single quotes with no space\ndef rem_other(string_txt):\n lst=['``','` `',\"''\",\"' '\"]\n word_sent=Tokenize(string_txt)\n final_word=[word for word in word_sent if word not in lst]\n return \" \".join(final_word)\n\ndef preprocess_text(string_txt):\n \n\n proc_text=string_txt\n\n #Convert the string to lower case\n proc_text=to_lower(proc_text)\n\n # Remove weblinks & mail_ids\n proc_text=rem_weblnk_mail(proc_text)\n\n # Remove digits\n proc_text=rem_digits(proc_text)\n\n # Remove Stopwords\n proc_text=RemoveStopWords(proc_text)\n\n #Lemmatize\n proc_text=Lemmatize(proc_text)\n\n #Remove Special Character\n proc_text=sp_char(proc_text)\n\n #Remove Single Character\n proc_text=sngle_char(proc_text)\n\n # Remove all punctiations\n proc_text=rem_punct(proc_text)\n\n #Remove Single Character at Start\n proc_text=sngle_char_strt(proc_text)\n\n #Removing single quotes\n proc_text=rem_other(proc_text)\n\n #Remove Multiple Space\n proc_text=rem_mul_spc(proc_text)\n\n #Convert the string to lower case\n proc_text=to_lower(proc_text)\n \n return proc_text","sub_path":"PreProcess.py","file_name":"PreProcess.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"535885036","text":"\"\"\" Visualize Points Segmentation: Main Results \"\"\"\n\"\"\" Original Author: Haoqiang Fan \"\"\"\nimport numpy as np\nimport show3d_balls\nimport sys\nimport os\nimport pdb\nimport argparse\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nimport color_settings as cg_\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--clsname', default='')\nparser.add_argument('--atrous_block_num', type=int, default=2)\nFLAGS = parser.parse_args()\n\n\ndef read_file(filename):\n ptc_list = []\n with open(filename, 'r') as f:\n for line in f:\n p_list = line.split()[1:] # point and color\n ptc = [float(i) for i in p_list]\n ptc_list.append(ptc)\n return np.asarray(ptc_list)\n\n\ndef pc_normalize(pc):\n centroid = np.mean(pc, axis=0)\n pc = pc - centroid\n m = np.max(np.sqrt(np.sum(pc**2, axis=1)))\n pc = pc / m\n return pc, centroid, m\n\n\ndef pts_aligned(pts):\n # rotate pts to fit octree data set rotation angles:\n rotation_angle = np.pi / 2\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, 0, sinval],\n [0, 1, 0],\n [-sinval, 0, cosval]]).T # counter-clock wise rotation\n norm_pts, pts_center, max_dis = pc_normalize(pts)\n rot_pts = np.dot(norm_pts.reshape((-1,3)), rotation_matrix)*max_dis + pts_center\n # rot_pts = np.dot(norm_pts.reshape((-1,3)), rotation_matrix)\n return rot_pts\n\n\ncolor_tab = cg_.color_table\nlabel_color = cg_.color_origin\n\n\ndef color_mapped(colors, clsname):\n # point label id start from 0;\n source_colors = np.asarray(label_color)\n target_colors = np.asarray(color_tab[clsname])\n label_num = target_colors.shape[0]\n colors_new = colors[:]+0.0\n # pdb.set_trace()\n for l in range(label_num):\n cur_src_clr = source_colors[l,...]\n cur_tar_clr = target_colors[l,...]\n idx = np.sum(np.abs(colors - cur_src_clr), axis=1) == 0\n colors_new[idx,...] = cur_tar_clr\n return colors_new\n\n\nshow_dict = {\n 'Airplane': 13, 'Bag': 2, 'Cap': 1,\n 'Car': 18, 'Chair': 50, 'Earphone': 0, 'Guitar': 13, 'Knife': 4,\n 'Lamp': 40, 'Laptop': 10, 'Motorbike': 11, 'Mug': 1, 'Pistol': 0,\n 'Rocket': 1, 'Skateboard': 2, 'Table': 18,\n }\n\n\nif __name__ == '__main__':\n \"\"\" input: point and color\n output: rendered color points figure\n pred-outs, pred ptnet, gt oc, gt ptnet\n \"\"\"\n ballsize = 7\n classes = sorted(show_dict.keys())\n for cname in classes:\n # CLSNAME = cname\n CLSNAME = 'Laptop'\n shape_idx = show_dict[CLSNAME] # Motor 3,4, 14, 17\n Atrous_dir = os.path.join(BASE_DIR, '../../result-data', 'test_results_PA_3DCNN_Atrous',\n CLSNAME+'-withBG-ABlock3-Res')\n PtNet_dir = os.path.join(BASE_DIR, '../../result-data', 'test_results_pointnet2',\n CLSNAME)\n fname_atrous = os.path.join(Atrous_dir, str(shape_idx)+'_pred'+'.obj')\n fname_ptnet = os.path.join(PtNet_dir, str(shape_idx)+'_pred'+'.obj')\n fname_atrous_gt = os.path.join(Atrous_dir, str(shape_idx)+'_gt'+'.obj')\n fname_ptnet_gt = os.path.join(PtNet_dir, str(shape_idx)+'_gt'+'.obj')\n\n data_atrous = read_file(fname_atrous)\n data_ptnet = read_file(fname_ptnet)\n data_atrous_gt = read_file(fname_atrous_gt)\n data_ptnet_gt = read_file(fname_ptnet_gt)\n\n pts_a = data_atrous[:,:3]\n\n pts_p_ = data_ptnet[:,:3]\n pts_p = pts_aligned(pts_p_)\n\n # if CLSNAME == 'Cap':\n # color_ptnet = data_ptnet[:,3:6] + 0.0\n # idx_1 = np.sum(np.abs(color_ptnet - np.array([0.65, 0.05, 0.05])), axis=1) == 0\n # idx_2 = np.sum(np.abs(color_ptnet - np.array([0.65, 0.35, 0.95])), axis=1) == 0\n # color_ptnet[idx_1,...] = np.array([0.7, 0.0, 0.0])\n # color_ptnet[idx_2,...] = np.array([0.0, 1.0, 0.0])\n # data_ptnet[:,3:6] = color_ptnet\n\n # color_ptnet = data_ptnet_gt[:,3:6] + 0.0\n # idx_1 = np.sum(np.abs(color_ptnet - np.array([0.65, 0.05, 0.05])), axis=1) == 0\n # idx_2 = np.sum(np.abs(color_ptnet - np.array([0.65, 0.35, 0.95])), axis=1) == 0\n # color_ptnet[idx_1,...] = np.array([0.7, 0.0, 0.0])\n # color_ptnet[idx_2,...] = np.array([0.0, 1.0, 0.0])\n # data_ptnet_gt[:,3:6] = color_ptnet\n\n clr_a = color_mapped(data_atrous[:,3:6], CLSNAME)\n clr_p = color_mapped(data_ptnet[:,3:6], CLSNAME)\n clr_a_gt = color_mapped(data_atrous_gt[:,3:6], CLSNAME)\n clr_p_gt = color_mapped(data_ptnet_gt[:,3:6], CLSNAME)\n # pdb.set_trace()\n\n clr_atrous = clr_a * 255\n clr_ptnet = clr_p * 255\n clr_a_gt = clr_a_gt * 255\n clr_p_gt = clr_p_gt * 255\n\n # savedir = os.path.join(BASE_DIR, '../../result-data', 'Rendered_imgs', CLSNAME+'_shape_'+str(shape_idx)+'.png')\n # show3d_balls.showpoints(xyz=pts_a, c_pred=clr_atrous[:,[1,0,2]], background=(255,255,255), # background=(b,g,r)\n # showrot=False,magnifyBlue=0,freezerot=False,\n # normalizecolor=False, ballradius=ballsize, savedir=savedir)\n\n savedir = os.path.join(BASE_DIR, '../../result-data', 'Rendered_imgs', CLSNAME+'_shape_'+str(shape_idx)+'_pred_atrous.png')\n show3d_balls.showpoints(xyz=pts_a, c_pred=clr_atrous[:,[1,0,2]], background=(255,255,255),\n showrot=False,magnifyBlue=0,freezerot=False,\n normalizecolor=False, ballradius=ballsize, savedir=savedir)\n\n savedir = os.path.join(BASE_DIR, '../../result-data', 'Rendered_imgs', CLSNAME+'_shape_'+str(shape_idx)+'_pred_ptnet2.png')\n show3d_balls.showpoints(xyz=pts_p, c_pred=clr_ptnet[:,[1,0,2]], background=(255,255,255),\n showrot=False,magnifyBlue=0,freezerot=False,\n normalizecolor=False, ballradius=ballsize, savedir=savedir)\n\n savedir = os.path.join(BASE_DIR, '../../result-data', 'Rendered_imgs', CLSNAME+'_shape_'+str(shape_idx)+'_gt_atrous.png')\n show3d_balls.showpoints(xyz=pts_a, c_pred=clr_a_gt[:,[1,0,2]], background=(255,255,255),\n showrot=False,magnifyBlue=0,freezerot=False,\n normalizecolor=False, ballradius=ballsize, savedir=savedir)\n\n savedir = os.path.join(BASE_DIR, '../../result-data', 'Rendered_imgs', CLSNAME+'_shape_'+str(shape_idx)+'_gt_ptnet2.png')\n show3d_balls.showpoints(xyz=pts_p, c_pred=clr_p_gt[:,[1,0,2]], background=(255,255,255),\n showrot=False,magnifyBlue=0,freezerot=False,\n normalizecolor=False, ballradius=ballsize, savedir=savedir)\n\n # CLSNAME = 'Airplane'\n # test_dir = os.path.join(BASE_DIR, '../../result-data', 'test_results_PA_3DCNN_Atrous',\n # CLSNAME+'-withBG-ABlock3-Res')\n # show_list = show_dict[CLSNAME] # [stage,channel]\n\n # for i in show_list:\n # shape_idx = i\n # fname = os.path.join(test_dir, str(shape_idx)+'_pred'+'.obj')\n # ptsclr = read_file(fname)\n\n # clr = ptsclr[:,3:6] * 255\n # # pdb.set_trace()\n # savedir = os.path.join(test_dir, 'dump', 'shape_'+str(shape_idx)+'.png')\n # show3d_balls.showpoints(xyz=ptsclr[:,:3], c_pred=clr[:,[1,0,2]], background=(255,255,255),\n # showrot=False,magnifyBlue=0,freezerot=False,\n # normalizecolor=False, ballradius=7, savedir=savedir)\n","sub_path":"application-code/visualize_pts_seg-comparePointnet2.py","file_name":"visualize_pts_seg-comparePointnet2.py","file_ext":"py","file_size_in_byte":7399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"40889116","text":"\n###############################################################################\n# Copyright 2013-2014 The University of Texas at Austin #\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\nfrom xml.dom.minidom import getDOMImplementation\n\nfrom ipf.data import Data, Representation\n\nfrom .entity import *\n\n#######################################################################################################################\n\nclass Share(Entity):\n def __init__(self):\n Entity.__init__(self)\n\n self.Description = None # string\n self.EndpointID = [] # list of string (uri)\n self.ResourceID = [] # list of string (uri)\n self.ServiceID = \"urn:glue2:Service:unknown\" # string (uri)\n self.ActivityID = [] # list of string (uri)\n self.MappingPolicyID = [] # list of string (uri)\n\n#######################################################################################################################\n\nclass ShareTeraGridXml(EntityTeraGridXml):\n data_cls = Share\n\n def __init__(self, data):\n EntityTeraGridXml.__init__(self,data)\n\n def get(self):\n return self.toDom().toxml()\n\n def toDom(self):\n doc = getDOMImplementation().createDocument(\"http://info.teragrid.org/glue/2009/02/spec_2.0_r02\",\n \"Entities\",None)\n\n root = doc.createElement(\"Share\")\n doc.documentElement.appendChild(root)\n self.addToDomElement(doc,root)\n\n return doc\n\n def addToDomElement(self, doc, element):\n EntityTeraGridXml.addToDomElement(self,doc,element)\n\n if self.data.Description is not None:\n e = doc.createElement(\"Description\")\n e.appendChild(doc.createTextNode(self.data.Description))\n element.appendChild(e)\n for endpoint in self.data.EndpointID:\n e = doc.createElement(\"Endpoint\")\n e.appendChild(doc.createTextNode(endpoint))\n element.appendChild(e)\n for resource in self.data.ResourceID:\n e = doc.createElement(\"Resource\")\n e.appendChild(doc.createTextNode(resource))\n element.appendChild(e)\n if self.data.ServiceID is not None:\n e = doc.createElement(\"Service\")\n e.appendChild(doc.createTextNode(self.data.ServiceID))\n element.appendChild(e)\n for activity in self.data.ActivityID:\n e = doc.createElement(\"Activity\")\n e.appendChild(doc.createTextNode(activity))\n element.appendChild(e)\n for policy in self.data.MappingPolicyID:\n e = doc.createElement(\"MappingPolicy\")\n e.appendChild(doc.createTextNode(policy))\n element.appendChild(e)\n \n#######################################################################################################################\n\nclass ShareOgfJson(EntityOgfJson):\n data_cls = Share\n\n def __init__(self, data):\n EntityOgfJson.__init__(self,data)\n\n def get(self):\n return json.dumps(self.toJson(),sort_keys=True,indent=4)\n\n def toJson(self):\n doc = EntityOgfJson.toJson(self)\n\n if self.data.Description is not None:\n doc[\"Description\"] = self.data.Description\n\n associations = {}\n if len(self.data.EndpointID) > 0:\n associations[\"EndpointID\"] = self.data.EndpointID\n associations[\"ResourceID\"] = self.data.ResourceID\n associations[\"ServiceID\"] = self.data.ServiceID\n if len(self.data.ActivityID) > 0:\n associations[\"ActivityID\"] = self.data.ActivityID\n if len(self.data.MappingPolicyID) > 0:\n associations[\"MappingPolicyID\"] = self.data.MappingPolicyID\n doc[\"Associations\"] = associations\n\n return doc\n\n#######################################################################################################################\n","sub_path":"ipf/glue2/share.py","file_name":"share.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"456385024","text":"from discord.ext import commands\nfrom collections import namedtuple\nfrom lxml import etree\nfrom urllib.parse import urlparse\n\nimport itertools\nimport traceback\nimport datetime\nimport discord\nimport asyncio\nimport asyncpg\nimport enum\nimport re\n\nfrom .utils import db, config, time\n\nclass Players(db.Table):\n id = db.PrimaryKeyColumn()\n discord_id = db.Column(db.Integer(big=True), unique=True, index=True)\n challonge = db.Column(db.String)\n switch = db.Column(db.String, unique=True)\n\nclass Teams(db.Table):\n id = db.PrimaryKeyColumn()\n active = db.Column(db.Boolean, default=True)\n challonge = db.Column(db.String, index=True)\n logo = db.Column(db.String)\n\nclass TeamMembers(db.Table, table_name='team_members'):\n id = db.PrimaryKeyColumn()\n team_id = db.Column(db.ForeignKey('teams', 'id'), index=True)\n player_id = db.Column(db.ForeignKey('players', 'id'), index=True)\n captain = db.Column(db.Boolean, default=False)\n\nclass ChallongeError(commands.CommandError):\n pass\n\nclass TournamentState(enum.IntEnum):\n invalid = 0\n pending = 1\n checking_in = 2\n checked_in = 3\n underway = 4\n complete = 5\n\nclass PromptResult(enum.Enum):\n timeout = 0\n error = 1\n cannot_dm = 2\n cancel = 3\n\n# Temporary results that can be rolled back\n\nclass PromptTransaction:\n def __init__(self, team_page):\n self.team_page = team_page\n self.captain_fc = None\n self.captain_id = None\n self.captain_discord = None\n self.team_logo = None\n self.members = []\n self.existing_members = []\n\n def add_captain(self, discord_id, fc):\n self.captain_fc = fc\n self.captain_discord = discord_id\n\n def add_pre_existing_captain(self, player_id):\n self.captain_id = player_id\n\n def add_existing_member(self, player_id):\n self.existing_members.append(player_id)\n\n def add_member(self, discord_id, fc):\n self.members.append({ 'discord_id': discord_id, 'fc': fc })\n\n async def execute_sql(self, con):\n # this will be in a transaction that can be rolled back\n if self.captain_id is not None:\n query = \"\"\"WITH team_insert AS (\n INSERT INTO teams(challonge, logo)\n VALUES ($1, $2)\n RETURNING id\n )\n INSERT INTO team_members(team_id, player_id, captain)\n SELECT id, $3, TRUE\n FROM team_insert\n RETURNING team_id;\n \"\"\"\n record = await con.fetchrow(query, self.team_page, self.team_logo, self.captain_id)\n team_id = record[0]\n else:\n query = \"\"\"WITH player_insert AS (\n INSERT INTO players(discord_id, switch)\n VALUES ($1, $2)\n RETURNING id\n ),\n team_insert AS (\n INSERT INTO teams(challonge, logo)\n VALUES ($3, $4)\n RETURNING id\n )\n INSERT INTO team_members(team_id, player_id, captain)\n SELECT x.team_id, y.player_id, TRUE\n FROM team_insert AS x(team_id),\n player_insert AS y(player_id)\n RETURNING team_id;\n \"\"\"\n record = await con.fetchrow(query, self.captain_discord, self.captain_fc, self.team_page, self.team_logo)\n team_id = record[0]\n\n # insert pre-existing members:\n if self.existing_members:\n query = \"\"\"INSERT INTO team_members(player_id, team_id)\n SELECT x.player_id, $1\n FROM UNNEST($2::int[]) AS x(player_id);\n \"\"\"\n await con.execute(query, team_id, self.existing_members)\n\n # insert new members\n if self.members:\n query = \"\"\"WITH player_insert AS (\n INSERT INTO players(discord_id, switch)\n SELECT x.discord_id, x.fc\n FROM jsonb_to_recordset($2::jsonb) AS x(discord_id bigint, fc text)\n RETURNING id\n )\n INSERT INTO team_members(player_id, team_id)\n SELECT x.id, $1\n FROM player_insert x;\n \"\"\"\n await con.execute(query, team_id, self.members)\n\n return team_id\n\n# Some validators for _prompt\n\n_friend_code = re.compile(r'^(?:(?:SW)[- _]?)?(?P[0-9]{4})[- _]?(?P[0-9]{4})[- _]?(?P[0-9]{4})$')\n\ndef fc_converter(arg, *, _fc=_friend_code):\n fc = arg.upper().strip('\"')\n m = _fc.match(fc)\n if m is None:\n raise commands.BadArgument('Invalid Switch Friend Code given.')\n return '{one}-{two}-{three}'.format(**m.groupdict())\n\ndef valid_fc(message):\n try:\n return fc_converter(message.content)\n except:\n return False\n\ndef yes_no(message):\n l = message.content.lower()\n if l in ('y', 'yes'):\n return 1\n elif l in ('n', 'no'):\n return -1\n return False\n\ndef validate_url(url):\n o = urlparse(url, scheme='http')\n if o.scheme not in ('http', 'https'):\n return False\n url = o.netloc + o.path\n if not url:\n return False\n if not url.lower().endswith(('.png', '.jpeg', '.jpg', '.gif')):\n return False\n return o.geturl()\n\ndef valid_logo(message):\n if message.content.lower() == 'none':\n return None\n\n url = message.content\n if message.attachments:\n url = message.attachments[0].url\n return validate_url(url)\n\nBOOYAH_GUILD_ID = 333799317385117699\nTOURNEY_ORG_ROLE = 333812806887538688\nPARTICIPANT_ROLE = 343137581564952587\nNOT_CHECKED_IN_ROLE = 343137740889522177\nANNOUNCEMENT_CHANNEL = 342925685729263616\nBOT_SPAM_CHANNEL = 343191203686252548\nTOP_PARTICIPANT_ROLE = 353646321028169729\n\ndef is_to():\n def predicate(ctx):\n return ctx.guild and any(r.id == TOURNEY_ORG_ROLE for r in ctx.author.roles)\n return commands.check(predicate)\n\ndef in_booyah_guild():\n def predicate(ctx):\n return ctx.guild and ctx.guild.id == BOOYAH_GUILD_ID\n return commands.check(predicate)\n\nChallongeTeamInfo = namedtuple('ChallongeTeamInfo', 'name members')\n\n# Members is an array of (Member, Switch-Code)\nParticipantInfo = namedtuple('ParticipantInfo', 'name logo members')\n\nclass Challonge:\n _validate = re.compile(\"\"\"(?:https?\\:\\/\\/)?(?:(?P[A-Za-z]+)\\.)?challonge\\.com\\/ # Main URL\n (?:(?:de|en|es|fr|hu|it|ja|ko|no|pl|pt|pt_BR|ru|sk|sv|tr|zh_CN)\\/)? # Language selection\n (?:teams\\/)?(?P[^\\/]+) # Slug\n \"\"\", re.VERBOSE)\n\n BASE_API = 'https://api.challonge.com/v1/tournaments'\n\n def __init__(self, bot, url, slug):\n self.session = bot.session\n self.api_key = bot.challonge_api_key\n self.url = url\n self.slug = slug\n\n @classmethod\n def from_url(cls, bot, url):\n if not url:\n return cls(bot, None, None)\n\n m = cls._validate.match(url)\n if m is None:\n raise ValueError('Invalid URL?')\n\n sub = m.group('subdomain')\n slug = m.group('slug')\n if sub:\n slug = f'{sub}-{slug}'\n\n return cls(bot, url, slug)\n\n @classmethod\n async def convert(cls, ctx, argument):\n try:\n return cls.from_url(ctx.bot, argument)\n except ValueError:\n raise ChallongeError('Not a valid challonge URL!') from None\n\n async def get_team_info(self, team_slug):\n url = f'http://challonge.com/teams/{team_slug}'\n\n # Challonge does not expose team info endpoint so we're gonna have\n # to end up using regular ol' web scraping.\n # So this code may break in the future if Challonge changes their DOM.\n # Luckily, it's straight forward currently.\n async with self.session.get(url) as resp:\n if resp.status != 200:\n raise ChallongeError(f'Challonge team page for {team_slug} responded with {resp.status}')\n\n root = etree.fromstring(await resp.text(), etree.HTMLParser())\n\n # get team name\n\n team_name = root.find(\".//div[@id='title']\")\n if team_name is None:\n raise ChallongeError(f'Could not find team name. Contact Danny. URL: <{url}>')\n\n team_name = ''.join(team_name.itertext()).strip()\n\n # get team members\n members = root.findall(\".//div[@class='team-member']/a\")\n if members is None or len(members) == 0:\n raise ChallongeError(f'Could not find team members. Contact Danny. URL: <{url}>')\n\n members = [\n member.get('href').replace('/users/', '')\n for member in members\n ]\n\n return ChallongeTeamInfo(team_name, members)\n\n async def show(self, *, include_matches=False, include_participants=False):\n params = {\n 'api_key': self.api_key,\n 'include_matches': int(include_matches),\n 'include_participants': int(include_participants),\n }\n url = f'{self.BASE_API}/{self.slug}.json'\n async with self.session.get(url, params=params) as resp:\n if resp.status == 200:\n js = await resp.json()\n return js.get('tournament', {})\n if resp.status == 422:\n js = await resp.json()\n raise ChallongeError('\\n'.join(x for x in js.get('errors', [])))\n else:\n raise ChallongeError(f'Challonge responded with {resp.status} for {url}.')\n\n async def start(self, *, include_matches=True, include_participants=False):\n params = {\n 'api_key': self.api_key,\n 'include_matches': int(include_matches),\n 'include_participants': int(include_participants)\n }\n\n url = f'{self.BASE_API}/{self.slug}/start.json'\n async with self.session.post(url, params=params) as resp:\n if resp.status == 200:\n js = await resp.json()\n return js.get('tournament', {})\n if resp.status == 422:\n js = await resp.json()\n raise ChallongeError('\\n'.join(x for x in js.get('errors', [])))\n else:\n raise ChallongeError(f'Challonge responded with {resp.status} for {url}.')\n\n async def finalize(self, *, include_matches=False, include_participants=True):\n params = {\n 'api_key': self.api_key,\n 'include_matches': int(include_matches),\n 'include_participants': int(include_participants)\n }\n\n url = f'{self.BASE_API}/{self.slug}/finalize.json'\n async with self.session.post(url, params=params) as resp:\n if resp.status == 200:\n js = await resp.json()\n return js.get('tournament', {})\n if resp.status == 422:\n js = await resp.json()\n raise ChallongeError('\\n'.join(x for x in js.get('errors', [])))\n else:\n raise ChallongeError(f'Challonge responded with {resp.status} for {url}.')\n\n async def matches(self, *, state=None, participant_id=None):\n params = {\n 'api_key': self.api_key\n }\n if state:\n params['state'] = state\n if participant_id is not None:\n params['participant_id'] = participant_id\n\n url = f'{self.BASE_API}/{self.slug}/matches.json'\n async with self.session.get(url, params=params) as resp:\n if resp.status != 200:\n raise ChallongeError(f'Challonge responded with {resp.status} for {url}.')\n return await resp.json()\n\n async def score_match(self, match_id, winner_id, player1_score, player2_score):\n params = {\n 'api_key': self.api_key,\n 'match[winner_id]': winner_id,\n 'match[scores_csv]': f'{player1_score}-{player2_score}'\n }\n\n url = f'{self.BASE_API}/{self.slug}/matches/{match_id}.json'\n async with self.session.put(url, params=params) as resp:\n if resp.status == 200:\n js = await resp.json()\n return js.get('match', {})\n if resp.status == 422:\n js = await resp.json()\n raise ChallongeError('\\n'.join(x for x in js.get('errors', [])))\n else:\n raise ChallongeError(f'Challonge responded with {resp.status} for {url}.')\n\n async def add_participant(self, username, *, misc=None):\n params = {\n 'api_key': self.api_key,\n 'participant[challonge_username]': username\n }\n\n if misc is not None:\n params['participant[misc]'] = str(misc)\n\n url = f'{self.BASE_API}/{self.slug}/participants.json'\n async with self.session.post(url, params=params) as resp:\n if resp.status == 200:\n js = await resp.json()\n return js.get('participant', {})\n if resp.status == 422:\n js = await resp.json()\n raise ChallongeError('\\n'.join(x for x in js.get('errors', [])))\n else:\n raise ChallongeError(f'Challonge responded with {resp.status} for {url}.')\n\n async def get_participant(self, participant_id, *, include_matches=False):\n params = {\n 'api_key': self.api_key,\n 'include_matches': int(include_matches)\n }\n url = f'{self.BASE_API}/{self.slug}/participants/{participant_id}.json'\n async with self.session.get(url, params=params) as resp:\n if resp.status == 200:\n js = await resp.json()\n return js.get('participant', {})\n if resp.status == 422:\n js = await resp.json()\n raise ChallongeError('\\n'.join(x for x in js.get('errors', [])))\n else:\n raise ChallongeError(f'Challonge responded with {resp.status} for {url}.')\n\n async def remove_participant(self, participant_id):\n url = f'{self.BASE_API}/{self.slug}/participants/{participant_id}.json'\n params = { 'api_key': self.api_key }\n async with self.session.delete(url, params=params) as resp:\n if resp.status != 200:\n js = await resp.json()\n raise ChallongeError('\\n'.join(x for x in js.get('errors', [])))\n\n async def participants(self):\n url = f'{self.BASE_API}/{self.slug}/participants.json'\n params = {\n 'api_key': self.api_key\n }\n\n async with self.session.get(url, params=params) as resp:\n if resp.status == 200:\n js = await resp.json()\n return [x['participant'] for x in js if 'participant' in x]\n elif resp.status == 422:\n js = await resp.json()\n raise ChallongeError('\\n'.join(x for x in js.get('errors', [])))\n else:\n raise ChallongeError(f'Challonge responded with {resp.status} for {url}.')\n\nclass Tournament(commands.Cog):\n \"\"\"Tournament specific tools.\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n self.config = config.Config('tournament.json')\n self._already_running_registration = set()\n\n async def cog_command_error(self, ctx, error):\n if isinstance(error, (ChallongeError, commands.BadArgument)):\n traceback.print_exc()\n await ctx.send(error)\n\n async def log(self, message, ctx=None, *, ping=False, error=False, **fields):\n if error is False:\n e = discord.Embed(colour=0x59b642, title=message)\n else:\n if error:\n e = discord.Embed(colour=0xb64259, title='Error')\n else:\n e = discord.Embed(colour=0xb69f42, title='Warning')\n\n exc = traceback.format_exc(chain=False, limit=10)\n if exc != 'NoneType: None\\n':\n e.description = f'```py\\n{exc}\\n```'\n e.add_field(name='Reason', value=message, inline=False)\n\n if ctx is not None:\n e.add_field(name='Author', value=f'{ctx.author} (ID: {ctx.author.id})', inline=False)\n e.add_field(name='Command', value=ctx.message.content, inline=False)\n\n for name, value in fields.items():\n e.add_field(name=name, value=value)\n\n e.timestamp = datetime.datetime.utcnow()\n\n wh_id, wh_token = self.bot.config.tourney_webhook\n hook = discord.Webhook.partial(id=wh_id, token=wh_token, adapter=discord.AsyncWebhookAdapter(self.bot.session))\n await hook.send(embed=e, content='@here' if ping else None)\n\n @property\n def tournament_state(self):\n return TournamentState(self.config.get('state', 0))\n\n @property\n def challonge(self):\n return Challonge.from_url(self.bot, self.config.get('url', ''))\n\n @commands.group(invoke_without_command=True, aliases=['tournament'])\n @in_booyah_guild()\n async def tourney(self, ctx):\n \"\"\"Shows you information about the currently tournament.\"\"\"\n data = await self.challonge.show()\n e = discord.Embed(title=data['name'], url=self.challonge.url, colour=0xa83e4b)\n description = data['description']\n if description:\n e.description = description\n\n participants = None\n not_checked_in = None\n for role in ctx.guild.roles:\n if role.id == PARTICIPANT_ROLE:\n participants = role\n elif role.id == NOT_CHECKED_IN_ROLE:\n not_checked_in = role\n\n attendance = f'{data.get(\"participants_count\", 0)} total attending'\n if participants:\n attendance = f'{attendance}\\n{len(participants.members)} active'\n if not_checked_in:\n not_checked_in = len(not_checked_in.members)\n if not_checked_in:\n attendance = f'{attendance}\\n{not_checked_in} not checked in'\n\n e.add_field(name='Attendance', value=attendance)\n\n current_round = self.config.get('round')\n if current_round is None:\n value = 'None'\n e.add_field(name='Current Round', value=None)\n else:\n round_ends = datetime.datetime.fromtimestamp(self.config.get('round_ends', 0.0))\n value = f'Round {current_round}\\nEnds in {time.human_timedelta(round_ends)}'\n\n e.add_field(name='Current Round', value=value)\n\n state = self.tournament_state.name.replace('_', ' ').title()\n e.add_field(name='State', value=state)\n await ctx.send(embed=e)\n\n @tourney.command(name='open')\n @is_to()\n async def tourney_open(self, ctx, *, url: Challonge):\n \"\"\"Opens a tournament for sign ups\"\"\"\n\n if self.tournament_state is not TournamentState.invalid:\n return await ctx.send(f'A tournament is already in progress. Try {ctx.prefix}tourney close')\n\n tourney = await url.show()\n if tourney.get('state') != 'pending':\n return await ctx.send('This tournament is not pending.')\n\n c = self.config.all()\n c['url'] = url.url\n c['state'] = TournamentState.pending.value\n await self.config.save()\n await ctx.send(f'Now accepting registrations until \"{ctx.prefix}tourney checkin\" is run.')\n return True\n\n @tourney.command(name='strict')\n @is_to()\n async def tourney_strict(self, ctx, *, url: Challonge):\n \"\"\"Opens a tournament for strict sign-ups.\n\n When done with strict sign-ups, only those with the\n Top Participant role can register.\n \"\"\"\n result = await ctx.invoke(self.tourney_open, url=url)\n if result is True:\n await self.config.put('strict', True)\n\n @tourney.command(name='checkin')\n @is_to()\n async def tourney_checkin(self, ctx):\n \"\"\"Opens the tournament for checking in.\n\n Check-ins last 2 hours. Users will be reminded to check-in\n at 1 hour remaining, 30 minutes, 15 minutes, and 5 minutes remaining.\n\n Tournament must be in the pending state.\n \"\"\"\n\n if self.tournament_state is not TournamentState.pending:\n return await ctx.send('This tournament is not pending.')\n\n # Create the check-in timers:\n reminder = self.bot.get_cog('Reminder')\n if reminder is None:\n return await ctx.send('Tell Danny the Reminder cog is off.')\n\n announcement = ctx.guild.get_channel(ANNOUNCEMENT_CHANNEL)\n if announcement is None:\n return await ctx.send('Missing the announcement channel to notify on.')\n\n not_checked_in = discord.utils.find(lambda r: r.id == NOT_CHECKED_IN_ROLE, ctx.guild.roles)\n if not_checked_in is None:\n return await ctx.send('Could not find the Not Checked In role.')\n\n base = datetime.datetime.utcnow() + datetime.timedelta(hours=1)\n durations = (\n (base, 0),\n # (base - datetime.timedelta(hours=1), 60),\n (base - datetime.timedelta(minutes=30), 30),\n (base - datetime.timedelta(minutes=15), 15),\n (base - datetime.timedelta(minutes=5), 5),\n )\n\n for when, remaining in durations:\n await reminder.create_timer(when, 'tournament_checkin', remaining, connection=ctx.db)\n\n await self.config.put('state', TournamentState.checking_in)\n await ctx.send(f'Check-ins are now being processed. When complete and ready, use {ctx.prefix}tourney start')\n\n await not_checked_in.edit(mentionable=True)\n msg = f\"<@&{NOT_CHECKED_IN_ROLE}> check-ins are now being processed. \" \\\n f\"To check-in please go to <#{BOT_SPAM_CHANNEL}> and use the `?checkin` command.\"\n await announcement.send(msg)\n await not_checked_in.edit(mentionable=False)\n\n @commands.Cog.listener()\n async def on_tournament_checkin_timer_complete(self, timer):\n minutes_remaining, = timer.args\n\n guild = self.bot.get_guild(BOOYAH_GUILD_ID)\n if guild is None:\n # wtf\n return\n\n announcement = guild.get_channel(ANNOUNCEMENT_CHANNEL)\n if announcement is None:\n return\n\n role = discord.utils.find(lambda r: r.id == NOT_CHECKED_IN_ROLE, guild.roles)\n if role is None:\n return\n\n if len(role.members) == 0:\n # everyone surprisingly checked in?\n if self.tournament_state is TournamentState.checking_in:\n await self.config.put('state', TournamentState.checked_in)\n await self.log(\"No Check-Ins To Process\", **{'Remaining Minutes': minutes_remaining})\n return\n\n if minutes_remaining != 0:\n # A reminder that they need to check-in\n msg = f'<@&{role.id}> Reminder: You have **{minutes_remaining} minutes** left to check-in.\\n\\n' \\\n f'To check-in please go to <#{BOT_SPAM_CHANNEL}> and use the `?checkin` command.'\n\n await role.edit(mentionable=True)\n await announcement.send(msg)\n await role.edit(mentionable=False)\n return\n\n # Check-in period is complete, so just terminate everyone who hasn't checked-in.\n has_not_checked_in = [m.id for m in role.members]\n\n # Remove the role from everyone who did not check in and notify them.\n\n msg = \"Hello. You've been disqualified due to failure to check-in. \" \\\n \"If you believe this is an error, please contact a TO.\"\n\n for member in role.members:\n try:\n await member.remove_roles(role)\n await member.send(msg)\n except:\n pass\n\n query = \"\"\"SELECT DISTINCT team_members.team_id\n FROM team_members\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE players.discord_id = ANY($1::bigint[]);\n \"\"\"\n\n disqualified_teams = await self.bot.pool.fetch(query, has_not_checked_in)\n disqualified_teams = { str(r[0]) for r in disqualified_teams }\n\n challonge = self.challonge\n tournament = await challonge.show(include_participants=True)\n participants = tournament['participants']\n\n removed_participants = []\n not_removed = 0\n\n for participant in participants:\n participant_id = participant['id']\n team_id = participant['misc']\n\n if team_id not in disqualified_teams:\n not_removed += 1\n continue\n\n try:\n await challonge.remove_participant(participant_id)\n except:\n pass\n else:\n remove_participants.append(participant_id)\n\n await self.config.put('state', TournamentState.checked_in)\n\n fields = {\n 'Totals': f'{len(removed_participants)} removed from check ins\\n{not_removed} checked in',\n 'Removed Team IDs': '\\n'.join(disqualified_teams),\n 'Removed Participant IDs': '\\n'.join(str(x) for x in removed_participants),\n }\n\n await self.log(\"Check-In Over\", **fields)\n\n msg = \"Check-ins are over! Please wait for a TO to start the tournament. \" \\\n \"If you failed to check-in you have received a direct message saying so.\"\n\n await announcement.send(msg)\n\n async def prepare_participant_cache(self, *, connection=None):\n # participant_id: [ParticipantInfo]\n cache = {}\n # member_id: participant_id\n member_cache = {}\n\n participants = await self.challonge.participants()\n\n con = connection or self.bot.pool\n\n mapping = {}\n for participant in participants:\n if participant['final_rank'] is not None:\n continue\n\n misc = participant['misc']\n if misc is None or not misc.isdigit():\n continue\n\n mapping[int(misc)] = (participant['id'], participant['display_name'])\n\n query = \"\"\"WITH team_info AS (\n SELECT team_id,\n array_agg(players.discord_id) AS \"discord\",\n array_agg(players.switch) AS \"switch\"\n FROM team_members\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE team_id = ANY($1::bigint[])\n GROUP BY team_id\n )\n SELECT t.team_id, teams.logo, t.discord, t.switch\n FROM team_info t\n INNER JOIN teams\n ON teams.id = t.team_id;\n \"\"\"\n\n records = await con.fetch(query, list(mapping))\n\n guild = self.bot.get_guild(BOOYAH_GUILD_ID)\n for team_id, team_logo, members, switch in records:\n participant_id, name = mapping[team_id]\n\n actual = []\n for index, member_id in enumerate(members):\n member_cache[member_id] = participant_id\n member = guild.get_member(member_id)\n if member is not None:\n code = switch[index]\n actual.append((member, code))\n\n cache[participant_id] = ParticipantInfo(name=name, logo=team_logo, members=actual)\n\n self._participants = cache\n self._member_participants = member_cache\n\n async def make_rooms_for_matches(self, ctx, matches, round_num, best_of):\n # channel_id mapped to:\n # match_id: match_id\n # player1_id: score\n # player2_id: score\n # confirmed: bool\n # identifier: str\n round_info = {}\n\n guild = self.bot.get_guild(BOOYAH_GUILD_ID)\n\n def embed_for_player(p, *, first=False):\n colour = 0xF02D7D if first else 0x19D719\n e = discord.Embed(title=p.name, colour=colour)\n if p.logo:\n e.set_thumbnail(url=p.logo)\n for member, switch in p.members:\n e.add_field(name=member, value=switch, inline=False)\n return e\n\n for match in matches:\n identifier = match['identifier'].lower()\n player1_id = match['player1_id']\n player2_id = match['player2_id']\n player_one = self._participants.get(player1_id)\n player_two = self._participants.get(player2_id)\n\n fields = {\n 'Match ID': match['id'],\n 'Player 1 ID': player1_id,\n 'Player 2 ID': player2_id\n }\n\n if not (player_one and player_two):\n await self.log(\"Unable to find player information\", error=True, **fields)\n continue\n\n overwrites = {\n guild.default_role: discord.PermissionOverwrite(read_messages=False),\n guild.me: discord.PermissionOverwrite(read_messages=True)\n }\n\n for member, _ in itertools.chain(player_one.members, player_two.members):\n overwrites[member] = discord.PermissionOverwrite(read_messages=True)\n\n try:\n channel = await guild.create_text_channel(f'group-{identifier}', overwrites=overwrites)\n round_info[str(channel.id)] = {\n 'match_id': match['id'],\n 'player1_id': player1_id,\n 'player2_id': player2_id,\n str(player1_id): None,\n str(player2_id): None,\n 'confirmed': False,\n 'identifier': match['identifier']\n }\n\n await channel.send(embed=embed_for_player(player_one, first=True))\n await channel.send(embed=embed_for_player(player_two))\n await asyncio.sleep(0.5)\n\n to_beat = (best_of // 2) + 1\n msg = \"@here Please use this channel to communicate!\\n\" \\\n \"When your match is complete, **both teams must report their own scores**.\\n\" \\\n f\"Reporting your score is done via the `?score` command. For example: `?score {to_beat}`\\n\" \\\n \"**The ?score command can only be done in this channel.**\"\n\n await channel.send(msg)\n except:\n await self.log(\"Failure when creating channel\", error=True, **fields)\n\n\n base = datetime.datetime.utcnow() + datetime.timedelta(minutes=30)\n\n conf = self.config.all()\n conf['round'] = round_num\n conf['best_of'] = best_of\n conf['state'] = TournamentState.underway\n conf['round_complete'] = False\n conf['total_matches'] = len(matches)\n conf['round_info'] = round_info\n conf['round_ends'] = base.timestamp()\n await self.config.save()\n\n times = (\n (base, 0),\n (base - datetime.timedelta(minutes=15), 15)\n )\n\n reminder = self.bot.get_cog('Reminder')\n for when, remaining in times:\n await reminder.create_timer(when, 'tournament_round', round_num, remaining, connection=ctx.db)\n\n fields = {\n 'Total Matches': len(matches)\n }\n\n await self.log(f\"Round {round_num} Started\", **fields)\n\n async def clean_tournament_participants(self):\n guild = self.bot.get_guild(BOOYAH_GUILD_ID)\n role = discord.utils.find(lambda r: r.id == PARTICIPANT_ROLE, guild.roles)\n\n participants = await self.challonge.participants()\n to_remove = {p['id'] for p in participants if p['final_rank'] is not None}\n\n cleaned = 0\n failed = 0\n total = 0\n for member in role.members:\n total += 1\n try:\n p_id = self._member_participants[member.id]\n except KeyError:\n continue\n\n if p_id not in to_remove:\n continue\n\n try:\n await member.remove_roles(role)\n except:\n failed += 1\n else:\n cleaned += 1\n\n fields = {\n 'Cleaned': cleaned,\n 'Failed': failed,\n 'Total Members': total\n }\n\n del self._participants\n await self.log(\"Participant Clean-up\", **fields)\n await self.prepare_participant_cache()\n\n @commands.Cog.listener()\n async def on_tournament_round_timer_complete(self, timer):\n round_num, remaining = timer.args\n\n guild = self.bot.get_guild(BOOYAH_GUILD_ID)\n\n if round_num != self.config.get('round'):\n fields = {\n 'Expected': round_num,\n 'Actual': self.config.get('round')\n }\n return await self.log(f'Round {round_num} Timer Outdated', **fields)\n\n total_matches = self.config.get('total_matches')\n matches_completed = sum(\n info.get('confirmed', False)\n for key, info in self.config.get('round_info', {}).items()\n )\n\n if total_matches == matches_completed:\n fields = {\n 'Total Matches': total_matches\n }\n await self.clean_tournament_participants()\n return await self.log(f'Round {round_num} Already Complete', **fields)\n\n if self.config.get('round_complete', False):\n fields = {\n 'Total Matches': total_matches,\n 'Matches Completed': matches_completed,\n }\n await self.clean_tournament_participants()\n return await self.log(f'Round {round_num} Marked Complete Already', **fields)\n\n announcement = guild.get_channel(ANNOUNCEMENT_CHANNEL)\n role = discord.utils.find(lambda r: r.id == PARTICIPANT_ROLE, guild.roles)\n\n if not (announcement and role):\n fields = {\n 'Round': round_num,\n 'Channel': 'Found' if announcement else 'Not Found',\n 'Role': 'Found' if role else 'Not Found',\n }\n return await self.log(\"Could not get role or channel for round announcement\", **fields)\n\n if remaining != 0:\n # A reminder that the round is almost over\n await role.edit(mentionable=True)\n msg = f'<@&{role.id}>, round {round_num} will conclude in {remaining} minutes. ' \\\n 'Please contact a TO if you have any issues.'\n await announcement.send(msg)\n await role.edit(mentionable=False)\n return\n\n # Round has concluded\n msg = f'<@&{role.id}>, round {round_num} has concluded! Please contact a TO if you require more time.'\n await role.edit(mentionable=True)\n await announcement.send(msg)\n await role.edit(mentionable=False)\n\n await self.config.put('round_complete', True)\n\n fields = {\n 'Round': round_num,\n 'Total Matches': total_matches,\n 'Matches Completed': matches_completed\n }\n await self.log('Round Complete', **fields)\n\n async def start_tournament(self, ctx, best_of):\n tourney = await self.challonge.start()\n\n matches = [\n o['match']\n for o in tourney.get('matches')\n if o['match']['round'] == 1\n ]\n\n await self.make_rooms_for_matches(ctx, matches, round_num=1, best_of=best_of)\n\n async def continue_tournament(self, ctx, best_of, round_num):\n if not self.config.get('round_complete'):\n confirm = await ctx.prompt('The round is not complete yet, are you sure you want to continue?')\n if not confirm:\n return await ctx.send('Aborting.')\n\n matches = await self.challonge.matches()\n matches = [\n o['match']\n for o in matches\n if o['match']['round'] == round_num\n ]\n\n await self.clean_tournament_participants()\n await self.make_rooms_for_matches(ctx, matches, round_num=round_num, best_of=best_of)\n\n @tourney.command(name='start')\n @is_to()\n async def tourney_start(self, ctx, best_of=5):\n \"\"\"Starts the tournament officially.\"\"\"\n\n if self.tournament_state is TournamentState.checking_in:\n role = discord.utils.find(lambda r: r.id == NOT_CHECKED_IN_ROLE, ctx.guild.roles)\n if role is None:\n return await ctx.send('Uh could not find the Not Checked In role.')\n\n if len(role.members) == 0:\n # everyone checked in somehow\n await self.config.put('state', TournamentState.checked_in)\n\n if self.tournament_state not in (TournamentState.checked_in, TournamentState.underway):\n return await ctx.send('Tournament is not started or finished checking in.')\n\n if self.bot.get_cog('Reminder') is None:\n return await ctx.send('Reminder cog is disabled, tell Danny.')\n\n if not hasattr(self, '_participants'):\n await self.prepare_participant_cache()\n\n current_round = self.config.get('round', None)\n if current_round is None:\n # fresh tournament\n await self.start_tournament(ctx, best_of)\n else:\n await self.continue_tournament(ctx, best_of, current_round + 1)\n\n @tourney.command(name='confirm')\n @is_to()\n async def tourney_confirm(self, ctx, *, channel: discord.TextChannel):\n \"\"\"Confirms a score and closes the channel.\"\"\"\n\n if self.tournament_state is not TournamentState.underway:\n return await ctx.send('The tournament has not started yet.')\n\n if not hasattr(self, '_participants'):\n await self.prepare_participant_cache()\n\n round_info = self.config.get('round_info', {})\n info = round_info.get(str(channel.id))\n if info is None:\n return await ctx.send('Could not get round info for this channel.')\n\n player1_id = info['player1_id']\n player2_id = info['player2_id']\n first_team = self._participants.get(player1_id).name\n second_team = self._participants.get(player2_id).name\n\n first_score, second_score = info[str(player1_id)], info[str(player2_id)]\n\n round_num = self.config.get('round')\n msg = f'Are you sure you want to confirm the results of round {round_num} match {info[\"identifier\"]}?\\n' \\\n f'{first_team} **{first_score}** - **{second_score}** {second_team}'\n\n confirm = await ctx.prompt(msg, delete_after=False, reacquire=False)\n if not confirm:\n return await ctx.send('Aborting')\n\n # actually confirm the score via challonge\n\n if first_score == second_score:\n winner_id = 'tie'\n elif first_score > second_score:\n winner_id = player1_id\n else:\n winner_id = player2_id\n\n await self.challonge.score_match(info['match_id'], winner_id, first_score, second_score)\n\n info['confirmed'] = True\n await self.config.put('round_info', round_info)\n fields = {\n 'Team A': first_team,\n 'Team B': second_team,\n 'Match': f\"{round_num}-{info['identifier']}: {info['match_id']}\",\n 'Team A Score': first_score,\n 'Team B Score': second_score\n }\n await self.log(\"Score Confirmation\", ctx, **fields)\n await channel.delete(reason='Score confirmation by TO.')\n await ctx.send('Confirmed.')\n\n @tourney.command(name='room')\n @is_to()\n async def tourney_room(self, ctx, *, channel: discord.TextChannel):\n \"\"\"Opens a room for the TO.\"\"\"\n\n if self.tournament_state is not TournamentState.underway:\n return await ctx.send('The tournament has not started yet.')\n\n round_info = self.config.get('round_info', {})\n if str(channel.id) not in round_info:\n return await ctx.send('This channel is not a group discussion channel.')\n\n await channel.set_permissions(ctx.author, read_messages=True)\n await ctx.send('Done.')\n\n @tourney.command(name='dq', aliases=['DQ', 'disqualify'])\n @is_to()\n async def tourney_dq(self, ctx, *, team: Challonge):\n \"\"\"Disqualifies a team from the tournament.\n\n This removes their roles and stuff for you.\n \"\"\"\n\n # get every member in the team\n\n query = \"\"\"SELECT id FROM teams WHERE challonge=$1;\"\"\"\n team_id = await ctx.db.fetchrow(query, team.slug)\n if team_id is None:\n return await ctx.send('This team is not in the database.')\n\n # remove from challonge\n challonge = self.challonge\n team_id = team_id[0]\n participants = await challonge.participants()\n\n participant_id = next((p['id'] for p in participants if p['misc'] == str(team_id)), None)\n if participant_id is not None:\n await challonge.remove_participant(participant_id)\n\n members = await self.get_discord_users_from_team(ctx.db, team_id=team_id[0])\n\n for member in members:\n try:\n await member.remove_roles(discord.Object(id=PARTICIPANT_ROLE), discord.Object(id=NOT_CHECKED_IN_ROLE))\n except:\n pass\n\n fields = {\n 'Members': '\\n'.join(member.mention for member in members),\n 'Participant ID': participant_id,\n 'Team': f'Team ID: {team_id}\\nURL: {team.url}',\n }\n\n await self.log('Disqualified', error=None, **fields)\n await ctx.send(f'Successfully disqualified <{team.url}>.')\n\n @tourney.command(name='top')\n @is_to()\n async def tourney_top(self, ctx, cut_off: int, *, url: Challonge):\n \"\"\"Adds Top Participant roles based on the cut off for a URL.\"\"\"\n\n tournament = await url.show(include_participants=True)\n if tournament.get('state') != 'complete':\n return await ctx.send('This tournament is incomplete.')\n\n team_ids = []\n for p in tournament['participants']:\n participant = p['participant']\n if participant['final_rank'] <= cut_off:\n team_ids.append(int(participant['misc']))\n\n query = \"\"\"SELECT players.discord_id, team_members.team_id\n FROM team_members\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE team_members.team_id = ANY($1::int[]);\n \"\"\"\n\n members = await ctx.db.fetch(query, team_ids)\n role = discord.Object(id=TOP_PARTICIPANT_ROLE)\n\n async with ctx.typing():\n good = 0\n for discord_id, team_id in members:\n member = ctx.guild.get_member(discord_id)\n try:\n await member.add_roles(role, reason=f'Top {cut_off} Team ID: {team_id}')\n except:\n pass\n else:\n good += 1\n\n await ctx.send(f'Successfully applied {good} roles out of {len(members)} for top {cut_off} in <{url.url}>.')\n\n @tourney.command(name='close')\n @is_to()\n async def tourney_close(self, ctx):\n \"\"\"Closes the currently running tournament.\"\"\"\n\n if self.tournament_state is not TournamentState.underway:\n return await ctx.send('The tournament has not started yet.')\n\n # Finalize tournament\n tourney = await self.challonge.finalize()\n\n # Remove participant roles\n async with ctx.typing():\n await self.clean_tournament_participants()\n\n # Delete lingering match channels\n for channel_id in self.config.get('round_info', {}):\n channel = ctx.guild.get_channel(channel_id)\n if channel is not None:\n await channel.delete(reason='Closing tournament.')\n\n # Clear state\n self.config._db = {}\n await self.config.save()\n await ctx.send('Tournament closed!')\n\n async def get_discord_users_from_team(self, connection, *, team_id):\n query = \"\"\"SELECT players.discord_id\n FROM team_members\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE team_members.team_id = $1;\n \"\"\"\n\n players = await connection.fetch(query, team_id)\n result = []\n guild = self.bot.get_guild(BOOYAH_GUILD_ID)\n for player in players:\n member = guild.get_member(player['discord_id'])\n if member is not None:\n result.append(member)\n return result\n\n async def register_pre_existing(self, ctx, team_id, team):\n # the captain has already registered their team before\n # so just fast track it and add it\n members = await self.get_discord_users_from_team(ctx.db, team_id=team_id)\n if not any(member.id == ctx.author.id for member in members):\n return await ctx.send(f'{ctx.author.mention}, You do not belong to this team so you cannot register with it.')\n\n challonge = self.challonge\n participant = await challonge.add_participant(team.name, misc=team_id)\n participant_id = participant['id']\n\n fields = {\n 'Team ID': team_id,\n 'Team Name': team.name,\n 'Participant ID': participant_id,\n 'Members': '\\n'.join(member.mention for member in members)\n }\n\n msg = f\"{ctx.author.mention}, you have been successfully invited to the tournament.\\n\" \\\n \"**Please follow these steps in order**\\n\" \\\n \"1. Go to \\n\" \\\n \"2. Click on the newest \\\"You have been challonged\\\" invitation.\\n\" \\\n \"3. Follow the steps in the invitation.\\n\" \\\n f\"4. Reply to this message with: {participant_id}\"\n\n await ctx.send(msg)\n await ctx.release()\n\n def check(m):\n return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id and str(participant_id) == m.content\n\n try:\n await self.bot.wait_for('message', check=check, timeout=300.0)\n except asyncio.TimeoutError:\n await ctx.send(f'{ctx.author.mention}, you did not verify your invite! Cancelling your registration.')\n await challonge.remove_participant(participant_id)\n await self.log(\"Cancelled Pre-Existing Registration\", ctx, error=True, **fields)\n return\n\n participant = await challonge.get_participant(participant_id)\n\n if participant.get('invitation_pending', True):\n await ctx.send(f'{ctx.author.mention}, you did not accept your invite! Cancelling your registration.')\n await challonge.remove_participant(participant_id)\n await self.log(\"Failed Pre-Existing Registration\", ctx, error=True, **fields)\n return\n\n await ctx.send(f'{ctx.author.mention}, alright you are good to go!')\n await self.log(\"Successful Pre-Existing Registration\", ctx, **fields)\n for member in members:\n try:\n await member.add_roles(discord.Object(id=NOT_CHECKED_IN_ROLE), discord.Object(id=PARTICIPANT_ROLE))\n except discord.HTTPException:\n continue\n\n async def _prompt(self, dm, content, *, validator=None, max_tries=3, timeout=300.0, exit=True):\n validator = validator or (lambda x: True)\n\n def check(m):\n return m.channel.id == dm.id and m.author.id == dm.recipient.id\n\n try:\n await dm.send(content)\n except discord.HTTPException:\n return PromptResult.cannot_dm\n\n for i in range(max_tries):\n try:\n msg = await self.bot.wait_for('message', check=check, timeout=timeout)\n except asyncio.TimeoutError:\n if exit:\n await dm.send('Took too long. Exiting.')\n return PromptResult.timeout\n\n if msg.content == '?cancel':\n # special sentinel telling us to stop\n if exit:\n await dm.send('Aborting.')\n return PromptResult.cancel\n\n is_valid = validator(msg)\n if is_valid is True:\n return msg\n elif is_valid is not False:\n # returning a different value\n return is_valid\n\n await dm.send(f\"That doesn't seem right... {max_tries - i - 1} tries remaining.\")\n\n if exit:\n await dm.send('Too many tries. Exiting.')\n return PromptResult.error\n\n async def new_registration(self, ctx, url, team):\n self._already_running_registration.add(ctx.author.id)\n dm = await ctx.author.create_dm()\n result = PromptTransaction(url.slug)\n\n msg = \"Hello! I'm here to interactively set you up for the first-time registration of Booyah Battle.\\n\" \\\n f\"**If you want to cancel, you can cancel at any time by doing ?cancel**\\n\\n\" \\\n \"Let's get us started with a question, **are you the captain of this team?** (say yes or no)\"\n\n await ctx.release()\n reply = await self._prompt(dm, msg, validator=yes_no)\n if reply is PromptResult.cannot_dm:\n return await ctx.send(f'Hey {ctx.author.mention}, your DMs are disabled. Try again after you enable them.')\n\n if isinstance(reply, PromptResult):\n return\n\n if reply != 1:\n return await dm.send('Alright. Tell your captain to do this registration instead. Sorry!')\n\n # check if they're in the player database already\n await ctx.acquire()\n query = \"SELECT id FROM players WHERE discord_id=$1;\"\n record = await ctx.db.fetchrow(query, ctx.author.id)\n if record is None:\n await ctx.release()\n fc = await self._prompt(dm, \"What is your switch friend code?\", validator=valid_fc)\n if not isinstance(fc, str):\n return\n result.add_captain(ctx.author.id, fc)\n else:\n result.add_pre_existing_captain(record[0])\n\n logo_msg = \"What is your team's logo? You can either do the following:\\n\" \\\n \"- A URL pointing to the image, which must be a png/jpeg/jpg file.\\n\" \\\n \"- An image uploaded directly to this channel.\\n\" \\\n \"- Sending the message `None` to denote no logo.\"\n\n logo = await self._prompt(dm, logo_msg, validator=valid_logo)\n if logo is not None and not isinstance(logo, str):\n return\n\n result.team_logo = logo\n\n def valid_member(m, *, _find=discord.utils.find):\n name, _, discriminator = m.content.rpartition('#')\n value = _find(lambda u: u.name == name and u.discriminator == discriminator, self.bot.users)\n if value is not None:\n return value.id\n return False\n\n member_msg = \"What is the member's name? You must use name#tag. e.g. Danny#0007\"\n ask_member_msg = \"Do you have any other team members in the server? (say yes or no)\"\n members = {}\n for i in range(7):\n has_member = await self._prompt(dm, ask_member_msg, validator=yes_no, exit=False)\n if has_member is PromptResult.cancel:\n return\n\n if has_member != 1:\n break\n\n member = await self._prompt(dm, member_msg, validator=valid_member, timeout=120.0, exit=False)\n if member is PromptResult.cancel:\n return\n\n if member is PromptResult.timeout:\n await dm.send(\"Took too long... Let's move on.\")\n break\n\n if member is PromptResult.error:\n break\n\n has_fc = await self._prompt(dm, \"What is their switch friend code?\", exit=False, validator=valid_fc, max_tries=2)\n if has_fc is PromptResult.cancel:\n return\n\n if isinstance(has_fc, PromptResult):\n continue\n\n members[member] = has_fc\n await dm.send('Successfully added member.')\n ask_member_msg = \"Do you have any **additional** team members in the server? (say yes or no)\"\n\n await ctx.acquire()\n\n # remove members that are in a team already\n query = \"\"\"SELECT players.discord_id\n FROM team_members\n INNER JOIN players\n ON players.id = team_members.player_id\n INNER JOIN teams\n ON teams.id = team_members.team_id\n WHERE teams.active\n AND players.discord_id = ANY($1::bigint[]);\n \"\"\"\n\n records = await ctx.db.fetch(query, list(members))\n to_remove = {x[0] for x in records}\n\n members = [(a, b) for a, b in members.items() if a not in to_remove]\n\n # get pre-existing members\n query = \"\"\"SELECT players.id\n FROM players\n WHERE players.discord_id = ANY($1::bigint[])\n \"\"\"\n\n pre_existing = await ctx.db.fetch(query, [i for i, j in members])\n pre_existing = {x[0] for x in records}\n members = [(a, b) for a, b in members if a not in pre_existing]\n\n for player_id in pre_existing:\n result.add_existing_member(player_id)\n\n for discord_id, fc in members:\n result.add_member(discord_id, fc)\n\n transaction = ctx.db.transaction()\n await transaction.start()\n\n try:\n team_id = await result.execute_sql(ctx.db)\n except:\n await transaction.rollback()\n await self.log('Registration SQL Failure', ctx, error=True)\n return\n\n try:\n # send invite\n challonge = self.challonge\n participant = await challonge.add_participant(team.name, misc=team_id)\n\n # wait for accepting\n msg = f\"You have been successfully invited to the tournament.\\n\" \\\n \"**Please follow these steps in order**\\n\" \\\n \"1. Go to \\n\" \\\n \"2. Click on the newest \\\"You have been challonged\\\" invitation.\\n\" \\\n \"3. Follow the steps in the invitation.\\n\" \\\n f\"4. Reply to this message with: {team_id}\"\n\n def verify(m):\n return m.content == str(team_id)\n verified = await self._prompt(dm, msg, validator=verify, timeout=120.0)\n except:\n await transaction.rollback()\n await self.log(\"Registration failure\", ctx, error=True)\n await dm.send('An error happened while trying to register.')\n return\n\n participant_id = participant.get('id')\n fields = {\n 'Team ID': team_id,\n 'Team Name': team.name,\n 'Participant ID': participant_id,\n }\n\n if isinstance(verified, PromptResult):\n await transaction.rollback()\n await challonge.remove_participant(participant_id)\n await self.log('Took too long to accept invite', ctx, error=None, **fields)\n return\n\n try:\n participant = await challonge.get_participant(participant_id)\n except ChallongeError as e:\n await transaction.rollback()\n await self.log(f\"Challonge error while registering: {e}\", ctx, error=True, **fields)\n await dm.send(e)\n except:\n await transaction.rollback()\n await self.log(\"Unknown error while registering\", ctx, error=True, **fields)\n else:\n if participant.get('invitation_pending', True):\n await transaction.rollback()\n await challonge.remove_participant(participant_id)\n await self.log(\"Did not accept invite\", ctx, error=None, **fields)\n await dm.send('Invite not accepted! Aborting.')\n else:\n await transaction.commit()\n members = await self.get_discord_users_from_team(ctx.db, team_id=team_id)\n fields['Members'] = '\\n'.join(member.mention for member in members)\n\n await self.log(\"Successful Registration\", ctx, **fields)\n msg = \"You've successfully registered! Next time, to be easier you can skip this entire process.\"\n await dm.send(msg)\n\n for member in members:\n try:\n await member.add_roles(discord.Object(id=NOT_CHECKED_IN_ROLE), discord.Object(id=PARTICIPANT_ROLE))\n except discord.HTTPException:\n continue\n\n @commands.command()\n @in_booyah_guild()\n async def register(self, ctx, *, url: Challonge):\n \"\"\"Signs up for a running tournament.\"\"\"\n\n if self.tournament_state is not TournamentState.pending:\n return await ctx.send('No tournament is up for sign ups right now.')\n\n if self.config.get('strict', False):\n if not any(role.id == TOP_PARTICIPANT_ROLE for role in ctx.author.roles):\n return await ctx.send('You do not have the Top Participant role.')\n\n try:\n team = await self.challonge.get_team_info(url.slug)\n except ChallongeError:\n return await ctx.send('This is not a valid challonge team page!')\n\n query = \"\"\"SELECT id FROM teams WHERE challonge=$1;\"\"\"\n pre_existing = await ctx.db.fetchrow(query, url.slug)\n if pre_existing is not None:\n return await self.register_pre_existing(ctx, pre_existing['id'], team)\n\n if ctx.author.id in self._already_running_registration:\n return await ctx.send('You are already running a registration right now...')\n\n query = \"\"\"SELECT team_id\n FROM team_members\n INNER JOIN teams\n ON teams.id = team_members.team_id\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE teams.active\n AND players.discord_id=$1;\n \"\"\"\n\n team_id = await ctx.db.fetchrow(query, ctx.author.id)\n if team_id is not None:\n return await ctx.send('You are already part of another team.')\n\n try:\n async with ctx.acquire():\n await self.new_registration(ctx, url, team)\n finally:\n self._already_running_registration.discard(ctx.author.id)\n\n @commands.command()\n @in_booyah_guild()\n async def checkin(self, ctx):\n \"\"\"Checks you in to the current running tournament.\"\"\"\n\n if self.tournament_state is not TournamentState.checking_in:\n return await ctx.send('No tournament is up for check-ins right now.')\n\n query = \"\"\"SELECT team_members.team_id\n FROM team_members\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE players.discord_id = $1;\n \"\"\"\n\n record = await ctx.db.fetchrow(query, ctx.author.id)\n if record is None:\n return await ctx.send('You do not have a team signed up.')\n\n team_id = record[0]\n members = await self.get_discord_users_from_team(ctx.db, team_id=team_id)\n\n did_not_remove = []\n for member in members:\n try:\n await member.remove_roles(discord.Object(id=NOT_CHECKED_IN_ROLE))\n except:\n did_not_remove.append(member)\n\n fields = {\n 'Checked-in Members': '\\n'.join(member.mention for member in members),\n }\n\n if did_not_remove:\n fields['Failed Removals'] = '\\n'.join(member.mention for member in members)\n else:\n fields['Failed Removals'] = 'None'\n\n await self.log(\"Check-In Processed\", ctx, **fields)\n await ctx.message.add_reaction(ctx.tick(True).strip('<:>'))\n\n @commands.command()\n @in_booyah_guild()\n async def score(self, ctx, wins: int):\n \"\"\"Submits your score to the tournament.\"\"\"\n\n if self.tournament_state is not TournamentState.underway:\n return await ctx.send('A tournament is not currently running.')\n\n if not hasattr(self, '_participants'):\n await self.prepare_participant_cache()\n\n info = self.config.get('round_info', {})\n ours = info.get(str(ctx.channel.id))\n if ours is None:\n return await ctx.send('This channel is not a currently running group channel.')\n\n best_of = self.config.get('best_of')\n\n if wins > ((best_of // 2) + 1):\n return await ctx.send('That sort of score is impossible friend.')\n\n our_participant_id = self._member_participants.get(ctx.author.id)\n if our_participant_id is None:\n return await ctx.send('Apparently, you are not participating in this tournament.')\n\n if ours['confirmed']:\n return await ctx.send('This score has been confirmed by a TO and cannot be changed. Contact a TO.')\n\n their_participant_id = ours['player2_id'] if ours['player1_id'] == our_participant_id else ours['player1_id']\n our_score = ours[str(our_participant_id)]\n their_score = ours[str(their_participant_id)]\n round_num = self.config.get('round')\n\n fields = {\n 'Reporting Team': self._participants[our_participant_id].name,\n 'Room': f'{round_num}-{ours[\"identifier\"]}: {ctx.channel.mention}',\n 'Match ID': ours['match_id'],\n 'Reporter Score': None,\n 'Enemy Score': their_score,\n 'Round': f'Round {round_num}: Best of {best_of}'\n }\n\n changed_score = False\n ping = False\n round_complete = self.config.get('round_complete', False)\n if our_score is None:\n fields['Reporter Score'] = wins\n else:\n if our_score == wins:\n return await ctx.send('You already submitted this exact score before bud.')\n\n fields['Reporter Score'] = f'{our_score} -> {wins}'\n changed_score = True\n\n if their_score is None:\n ours[str(our_participant_id)] = wins\n title = 'Changed score submission' if changed_score else 'Score Submission'\n else:\n if their_score + wins > best_of:\n await ctx.send('Your score conflicts with the enemy score.')\n reason = 'Score conflict'\n if round_complete:\n reason = f'{reason} + done after round completion'\n await self.log(reason, ctx, error=True, **fields)\n return\n\n ours[str(our_participant_id)] = wins\n title = 'Changed complete score submission' if changed_score else 'Complete Score Submission'\n ping = True\n\n await ctx.send('Score reported.')\n if round_complete:\n fields['Info'] = title\n await self.log('Submission After Round Complete', ctx, ping=ping, error=None, **fields)\n else:\n await self.log(title, ctx, ping=ping, **fields)\n\n await self.config.put('round_info', info)\n\n @commands.group()\n @in_booyah_guild()\n async def team(self, ctx):\n \"\"\"Manages your team.\"\"\"\n pass\n\n @team.command(name='create')\n async def team_create(self, ctx, *, url: Challonge):\n \"\"\"Creates a team.\"\"\"\n\n # Check if they're an active player\n\n query = \"\"\"SELECT id FROM players WHERE discord_id = $1;\"\"\"\n record = await ctx.db.fetchrow(query, ctx.author.id)\n if record is None:\n return await ctx.send(f'You have not registered as a player. Try {ctx.prefix}player ' \\\n 'switch SW-1234-5678-9012 to register yourself as a player.')\n\n player_id = record['id']\n\n # Check if they're in an active team\n\n query = \"\"\"SELECT team_id, captain\n FROM team_members\n INNER JOIN teams\n ON teams.id = team_members.team_id\n WHERE teams.active\n AND team_members.player_id = $1\n \"\"\"\n\n record = await ctx.db.fetchrow(query, player_id)\n if record is not None:\n return await ctx.send('You are already an active member of a team.')\n\n team_info = await url.get_team_info(url.slug)\n\n # Check if this team already exists\n query = \"\"\"SELECT id FROM teams WHERE challonge=$1;\"\"\"\n exists = await ctx.db.fetchrow(query, url.slug)\n if exists:\n return await ctx.send('This team already exists.')\n\n # Actually insert\n query = \"\"\"WITH to_insert AS (\n INSERT INTO teams (challonge)\n VALUES ($1)\n RETURNING id\n )\n INSERT INTO team_members (team_id, player_id, captain)\n SELECT to_insert.id, $2, TRUE\n FROM to_insert;\n \"\"\"\n\n await ctx.db.execute(query, url.slug, player_id)\n await ctx.send(f'Successfully created team {team_info.name}. See \"{ctx.prefix}help team\" for more commands.')\n\n async def get_owned_team_info(self, ctx):\n query = \"\"\"SELECT team_id AS \"id\",\n players.id AS \"owner_id\",\n 'https://challonge.com/teams/' || teams.challonge AS \"challonge\"\n FROM team_members\n INNER JOIN teams\n ON teams.id = team_members.team_id\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE team_members.captain\n AND players.discord_id = $1\n AND teams.active;\n \"\"\"\n\n record = await ctx.db.fetchrow(query, ctx.author.id)\n return record\n\n @team.command(name='delete')\n async def team_delete(self, ctx):\n \"\"\"Marks your current team as inactive.\"\"\"\n team = await self.get_owned_team_info(ctx)\n\n # Get the owned team\n if team is None:\n return await ctx.send('You do not own any team.')\n\n query = \"\"\"UPDATE teams SET active = FALSE WHERE id = $1;\"\"\"\n await ctx.db.execute(query, team['id'])\n await ctx.send('Team successfully marked as inactive.')\n\n @team.command(name='add')\n async def team_add(self, ctx, *, member: discord.Member):\n \"\"\"Adds a member to your team.\"\"\"\n\n team = await self.get_owned_team_info(ctx)\n if team is None:\n return await ctx.send('You do not own any team.')\n\n query = \"\"\"SELECT id FROM players WHERE discord_id=$1;\"\"\"\n record = await ctx.db.fetchrow(query, member.id)\n\n if record is None:\n await ctx.send('It appears this member has not registered before. ' \\\n f'Ask them to do so by inputting their switch code via \"{ctx.prefix}player switch\" command.')\n return\n\n player_id = record['id']\n\n query = \"\"\"SELECT teams.challonge\n FROM team_members\n INNER JOIN teams\n ON teams.id = team_members.team_id\n WHERE team_members.player_id = $1\n AND teams.active\n AND teams.id <> $2;\n \"\"\"\n\n record = await ctx.db.fetchrow(query, player_id, team['id'])\n if record is not None:\n return await ctx.send(f'This member is already part of the team.')\n\n # Verify the member wants to be added to the team\n msg = f'Hello {member.mention}, {ctx.author.mention} would like to add you to <{team[\"challonge\"]}>. Do you agree?'\n verify = await ctx.prompt(msg, delete_after=False, author_id=member.id)\n if not verify:\n return await ctx.send('Aborting.')\n\n query = \"\"\"INSERT INTO team_members (player_id, team_id) VALUES ($1, $2)\"\"\"\n await ctx.db.execute(query, player_id, team['id'])\n await ctx.send('Successfully added member.')\n\n # transparently try to add roles depending on the tournament state\n participants = await self.challonge.participants()\n team_id = str(team['id'])\n participant_id = next((p['id'] for p in participants if p['misc'] == team_id and p['final_rank'] is None), None)\n if participant_id is None:\n return\n\n await member.add_roles(discord.Object(id=PARTICIPANT_ROLE))\n if self.tournament_state is TournamentState.pending:\n await member.add_roles(discord.Object(id=NOT_CHECKED_IN_ROLE))\n\n if self.tournament_state is TournamentState.underway:\n # see if they have a room active and add them there\n if not hasattr(self, '_participants'):\n await self.prepare_participant_cache()\n\n try:\n info = self._participants[participant_id]\n except KeyError:\n pass\n else:\n # add to the cache\n self._member_participants[member.id] = participant_id\n\n # add to the channel\n for channel_id, obj in self.config.get('round_info', {}).items():\n if obj['player1_id'] == participant_id or obj['player2_id'] == participant_id:\n channel = ctx.guild.get_channel(int(channel_id))\n if channel:\n await channel.set_permissions(member, read_messages=True)\n\n @team.command(name='remove')\n async def team_remove(self, ctx, *, member: discord.Member):\n \"\"\"Removes a member from your team.\"\"\"\n\n team = await self.get_owned_team_info(ctx)\n if team is None:\n return await ctx.send('You do not own any team.')\n\n query = \"\"\"DELETE FROM team_members\n USING players\n WHERE team_id = $1\n AND players.id = team_members.player_id\n AND players.discord_id = $2\n RETURNING players.id\n \"\"\"\n\n deleted = await ctx.db.fetchrow(query, team['id'], member.id)\n if not deleted:\n return await ctx.send('This member could not be removed. They might not be in your team.')\n\n await ctx.send('Removed member successfully.')\n\n # transparently try to remove roles depending on the tournament state\n participants = await self.challonge.participants()\n team_id = str(team['id'])\n participant_id = next((p['id'] for p in participants if p['misc'] == team_id and p['final_rank'] is None), None)\n if participant_id is None:\n return\n\n await member.remove_roles(discord.Object(id=PARTICIPANT_ROLE))\n if self.tournament_state is TournamentState.pending:\n await member.remove_roles(discord.Object(id=NOT_CHECKED_IN_ROLE))\n\n # we'll leave them in the room for now\n return\n\n @team.command(name='logo')\n async def team_logo(self, ctx, *, url=None):\n \"\"\"Sets the logo for your team.\n\n You can upload an image to Discord directly if you want to.\n \"\"\"\n\n team = await self.get_owned_team_info(ctx)\n if team is None:\n return await ctx.send('You do not own any team.')\n\n if url is None:\n if not ctx.message.attachments:\n return await ctx.send('No logo provided.')\n url = message.attachments[0].url\n\n actual_url = validate_url(url)\n if not actual_url:\n return await ctx.send('Invalid URL provided.')\n\n query = \"UPDATE teams SET logo = $1 WHERE id = $2;\"\n await ctx.db.execute(query, actual_url, team['id'])\n await ctx.send('Successfully updated team logo.')\n\n @team.command(name='captain')\n async def team_captain(self, ctx, *, member: discord.Member):\n \"\"\"Transfers ownership of a team to another member.\n\n They must belong on the team for ownership to transfer.\n \"\"\"\n\n team = await self.get_owned_team_info(ctx)\n if team is None:\n return await ctx.send('You do not own any team.')\n\n query = \"\"\"SELECT player_id\n FROM team_members\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE players.discord_id = $1\n AND team_members.team_id = $2;\n \"\"\"\n\n record = await ctx.db.fetchrow(query, member.id, team['id'])\n if record is None:\n return await ctx.send('Member does not belong to team.')\n\n query = \"\"\"UPDATE team_members\n SET captain = NOT captain\n WHERE team_id = $1\n AND player_id IN ($2, $3);\n \"\"\"\n\n await ctx.db.execute(query, team['id'], record[0], team['owner_id'])\n await ctx.send('Successfully transferred ownership.')\n\n @team.command(name='show')\n async def team_show(self, ctx, *, url: Challonge):\n \"\"\"Shows a team's info.\"\"\"\n\n query = \"SELECT * FROM teams WHERE challonge=$1;\"\n record = await ctx.db.fetchrow(query, url.slug)\n\n if record is None:\n return await ctx.send('No info for this team!')\n\n team_info = await self.challonge.get_team_info(url.slug)\n e = discord.Embed(title=team_info.name, url=url.url, colour=0x19D719)\n\n if record['logo']:\n e.set_thumbnail(url=record['logo'])\n\n query = \"\"\"SELECT players.discord_id, players.switch\n FROM team_members\n INNER JOIN players ON players.id = team_members.player_id\n WHERE team_id=$1;\n \"\"\"\n\n players = await ctx.db.fetch(query, record['id'])\n e.add_field(name='Active?', value='Yes' if record['active'] else 'No')\n\n for member_id, switch in players:\n member = ctx.guild.get_member(member_id)\n if member:\n e.add_field(name=str(member), value=switch, inline=False)\n\n await ctx.send(embed=e)\n\n @commands.group(invoke_without_command=True)\n @in_booyah_guild()\n async def player(self, ctx, *, member: discord.Member):\n \"\"\"Manages your player profile.\"\"\"\n\n query = \"\"\"SELECT * FROM players WHERE discord_id=$1;\"\"\"\n record = await ctx.db.fetchrow(query, member.id)\n\n if record is None:\n return await ctx.send('No info for this player.')\n\n query = \"\"\"SELECT teams.challonge, team_members.captain\n FROM team_members\n INNER JOIN teams\n ON teams.id = team_members.team_id\n INNER JOIN players\n ON players.id = team_members.player_id\n WHERE teams.active\n AND players.discord_id=$1\n \"\"\"\n\n info = await ctx.db.fetchrow(query, member.id)\n e = discord.Embed()\n e.set_author(name=str(member), icon_url=member.avatar_url)\n\n if record['challonge']:\n e.url = f'https://challonge.com/users/{record[\"challonge\"]}'\n\n challonge_url = f'https://challonge.com/teams/{info[\"challonge\"]}' if info else 'None'\n e.add_field(name='Switch', value=record['switch'])\n e.add_field(name='Active Team', value=challonge_url)\n e.add_field(name='Captain?', value='Yes' if info and info['captain'] else 'No')\n await ctx.send(embed=e)\n\n @player.command(name='switch')\n @in_booyah_guild()\n async def player_switch(self, ctx, *, fc: fc_converter):\n \"\"\"Sets your Nintendo Switch code for your player profile.\"\"\"\n\n query = \"\"\"INSERT INTO players (discord_id, switch)\n VALUES ($1, $2)\n ON CONFLICT (discord_id) DO\n UPDATE SET switch = $2;\n \"\"\"\n\n try:\n await ctx.db.execute(query, ctx.author.id, fc)\n except asyncpg.UniqueViolationError:\n await ctx.send('Someone already has this set as their switch code.')\n else:\n await ctx.send('Updated switch code.')\n\n\ndef setup(bot):\n bot.add_cog(Tournament(bot))\n","sub_path":"cogs/tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":76537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"3821816","text":"from django.conf import settings\nfrom django.conf.urls.defaults import *\nfrom django.views.generic.simple import direct_to_template\nfrom django.views.generic.list_detail import object_list, object_detail\nfrom lists.models import Recipe, Menu\nfrom haystack.forms import ModelSearchForm\nfrom haystack.query import SearchQuerySet\nfrom haystack.views import SearchView, search_view_factory\nfrom django.contrib import admin\nadmin.autodiscover()\nfrom pinax.apps.account.openid_consumer import PinaxConsumer\n\n\nhandler500 = \"pinax.views.server_error\"\n\nrecipe_queryset = Recipe.objects.all()\nmenu_queryset = Menu.objects.all()\nsqs = SearchQuerySet()\n\nurlpatterns = patterns(\"\",\n url(r\"^$\", 'lists.views.homepage' , {}, name=\"home\"),\n url(r\"^recipe/(?P\\d+)/$\", object_detail, {'queryset' : recipe_queryset, 'template_name' : 'recipes/recipe.html', 'template_object_name' : 'recipe'}, name=\"recipe\"),\n url(r\"^menu/(?P\\d+)/$\", object_detail, {'queryset' : menu_queryset, 'template_name' : 'menus/menu.html', 'template_object_name' : 'menu'}, name=\"menu\"),\n url(r\"^admin/invite_user/$\", \"pinax.apps.signup_codes.views.admin_invite_user\", name=\"admin_invite_user\"),\n url(r\"^admin/\", include(admin.site.urls)),\n url(r\"^about/\", include(\"about.urls\")),\n url(r\"^account/\", include(\"pinax.apps.account.urls\")),\n url(r\"^openid/(.*)\", PinaxConsumer()),\n url(r\"^profiles/\", include(\"idios.urls\")),\n url(r\"^notices/\", include(\"notification.urls\")),\n url(r\"^announcements/\", include(\"announcements.urls\")),\n)\n\nurlpatterns += patterns('haystack.views',\n url(r'^search$', search_view_factory(\n view_class=SearchView,\n searchqueryset=sqs,\n form_class=ModelSearchForm\n ), name='haystack_search'),\n)\n\n\n\nif settings.SERVE_MEDIA:\n urlpatterns += patterns(\"\",\n url(r\"\", include(\"staticfiles.urls\")),\n )\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"88040831","text":"import IfxPyDbi\nConStr = \"SERVER=infor99;DATABASE=db0;HOST=127.0.0.1;SERVICE=27988;UID=informix;PWD=980120;\"\n\ntry:\n # netstat -a | findstr 9088\n conn = IfxPyDbi.connect(ConStr, \"\", \"\")\nexcept Exception as e:\n print('ERROR: Connect failed')\n print(e)\n quit()","sub_path":"test_obj/informix_dir/infoemix_con.py","file_name":"infoemix_con.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"486512568","text":"import os, h5py\nimport numpy as np\nfrom scipy import sparse\nfrom scipy.spatial import cKDTree\n\n\ndef fractional_difference(array, start_idx, d=0.75, lag=10):\n if start_idx - lag < 0: lag = start_idx\n\n output = array[start_idx]\n dm = d\n sign = -1\n for i in xrange(1,lag):\n output += (sign) * dm * array[start_idx - i]\n sign *= -1\n dm *= ( (d-i) / (i+1) )\n return output\n\n# N x N matrix\ndef threshold_matrix(matrix, threshold,double_sided=False):\n def check_threshold(a):\n if a <= threshold and a >= -threshold:\n return True\n return False\n\n shape = matrix.shape\n matrix_reshaped = matrix.reshape(-1,)\n if double_sided:\n check_vec = np.vectorize(check_threshold)\n matrix_reshaped[check_vec(matrix_reshaped)] = 0.0\n else:\n matrix_reshaped[matrix_reshaped <= threshold] = 0.0\n return matrix_reshaped.reshape(shape)\n\ndef binarize_matrix(matrix, to_sparse=True):\n shape = matrix.shape\n matrix_reshaped = matrix.reshape(-1,)\n matrix_reshaped[matrix_reshaped > 0] = 1\n \n binarized_matrix = matrix_reshaped.reshape(shape).astype('int8')\n if to_sparse:\n return matrix_to_sparse(binarized_matrix)\n return binarized_matrix\n\ndef matrix_to_sparse(matrix):\n if len(matrix.shape) <= 2:\n return sparse.csr_matrix(matrix)\n else: \n sparse_lst = []\n for i in xrange(matrix.shape[2]):\n this_matrix = matrix[:,:,i]\n sparse_lst.append(sparse.csr_matrix(this_matrix))\n return sparse_lst\n\n# cloud is N x D\ndef nearest_n_neurons(x,cloud,n=16,tree=None):\n if tree is None:\n tree = cKDTree(cloud)\n distances, idxs = tree.query(x,n+1)\n return distances, idxs\n\ndef nearest_in_radius(x,cloud,r=0.050,tree=None): # r in mm\n if tree is None:\n tree = cKDTree(cloud)\n idxs = tree.query_ball_point(x,r)\n return idxs\n\n\ndef nearest_in_width(x,cloud,r_inner=0.010,r_outer=0.050,tree=None):\n if tree is None:\n tree = cKDTree(cloud)\n inner_idxs = set(tree.query_ball_point(x,r_inner))\n outer_idxs = set(tree.query_ball_point(x,r_outer))\n # In width will be |outer_idxs| - |inner_idxs|\n #return [0] + sorted(list(inner_idxs.difference(outer_idxs)))\n return sorted(list(outer_idxs.difference(inner_idxs)))\n\ndef list_find(f, lst):\n i = 0\n for x in lst:\n if f(x): return i\n else: i+=1\n return None\n\ndef extract_continuous_cluster_times(cluster_assignment, clusters):\n cluster_times_dict = {cluster: [] for cluster in clusters}\n current_cluster = None\n for i in xrange(len(cluster_assignment)):\n if current_cluster is None:\n current_cluster = cluster_assignment[i]\n time_lst = []\n elif current_cluster != cluster_assignment[i]:\n cluster_times_dict[current_cluster].append(time_lst)\n time_lst = []\n current_cluster = cluster_assignment[i] \n elif current_cluster == cluster_assignment[i]:\n time_lst.append(i)\n return cluster_times_dict\n\ndef extract_spatial_information(h5_filepath, spatial_namespace):\n if not os.path.isfile(h5_filepath): raise Exception('Error, could not find h5 file')\n f = h5py.File(h5_filepath)\n if spatial_namespace not in f: raise Exception('Error, namespace not found')\n\n spatial_data_group = f[spatial_namespace]['data']\n keys = sorted([int(k) for k in spatial_data_group.keys()])\n coordinates_lst = []\n for key in keys:\n coordinates_lst.append(spatial_data_group[str(key)])\n return np.asarray(coordinates_lst, dtype='float32')\n \n \n\ndef extract_trace_information(h5_filepath, traces_namespace):\n if not os.path.isfile(h5_filepath):\n raise Exception('Error, could not find h5 file')\n f = h5py.File(h5_filepath)\n \n if traces_namespace not in f:\n raise Exception('Error, namespace not found')\n\n traces_group = f[traces_namespace]\n\n TR,N,T = traces_group['TR'][0], traces_group['n_neurons'][0], traces_group['tpoints'][0]\n\n trace_data_group = traces_group['data']\n trace_keys = sorted([int(k) for k in trace_data_group.keys()])\n traces = np.zeros((N,T))\n\n for key in trace_keys:\n traces[key,:] = trace_data_group[str(key)]\n f.close()\n\n return traces, TR, N, T\n\ndef extract_ticc_cluster_assignment(h5_filepath, ticc_namespace):\n if not os.path.isfile(h5_filepath):\n raise Exception('Error, could not find h5 file')\n\n f = h5py.File(h5_filepath, 'r')\n if ticc_namespace not in f:\n raise Exception('ticc namespace is incorrect or does not exist')\n ticc_group = f[ticc_namespace]\n\n nclusters = ticc_group['num_clusters'][0]\n ticc_cluster_assignment_group = ticc_group['cluster assignment']['data']\n cluster_assignment = list(ticc_cluster_assignment_group['output'])\n f.close()\n\n return np.asarray(cluster_assignment), nclusters \n\ndef extract_first_order_statistics(h5_filepath, stats_namespace):\n if not os.path.isfile(h5_filepath):\n raise Exception('Error, could not find h5 file')\n \n f = h5py.File(h5_filepath, 'r')\n if stats_namespace not in f:\n raise Exception('statistics namespace not in h5 file')\n\n stats_group = f[stats_namespace]\n mean_info, var_info = {}, {}\n\n mean_info['anova assumptions'] = stats_group['mean anova assumptions met'][0]\n var_info['anova assumptions'] = stats_group['var anova assumptions met'][0]\n \n mean_info['num comparisons'] = stats_group['num comparisons'][0]\n mean_info['num comparison'] = stats_group['num comparisons'][0]\n\n mean_group = stats_group['mean']['data']\n mean_keys = mean_group.keys()\n for mkey in mean_keys:\n mean_info[mkey] = np.asarray(mean_group[mkey], dtype='float32')\n var_group = stats_group['var']['data']\n var_keys = var_group.keys()\n for vkey in var_keys:\n var_info[vkey] = np.asarray(var_group[vkey], dtype='float32')\n\n return mean_info, var_info\n\ndef extract_periodogram_information(h5_filepath, periodogram_namespace):\n if not os.path.isfile(h5_filepath):\n raise Exception('Error, could not find h5 file')\n\n f = h5py.File(h5_filepath, 'r')\n if periodogram_namespace not in f:\n raise Exception('periodogram namespace is incorrect or does not exist')\n periodogram_group = f[periodogram_namespace]\n freq_info, P_info = {}, {}\n\n freqs_group = periodogram_group['f']['data']\n freqs_keys = freqs_group.keys()\n for fkey in freqs_keys:\n freq_info[fkey] = np.asarray(freqs_group[fkey], dtype='float32')\n \n Pf_group = periodogram_group['Pf']['data']\n pf_keys = Pf_group.keys()\n for pkey in pf_keys:\n P_info[pkey] = np.asarray(Pf_group[pkey], dtype='float32')\n\n return freq_info, P_info\n \ndef extract_ticc_mrfs(h5_filepath, ticc_namespace):\n if not os.path.isfile(h5_filepath):\n raise Exception('Error, could not find h5 file')\n f = h5py.File(h5_filepath, 'r')\n if ticc_namespace not in f:\n raise Exception('ticc namespace is incorrect or does not exist')\n\n mrf_info = {}\n ticc_group = f[ticc_namespace]\n n_neurons = ticc_group['n_neurons'][0]\n mrf_info['n_neurons'] = n_neurons\n mrf_info['num_clusters'] = ticc_group['num_clusters'][0]\n\n mrf_info['clusters'] = {}\n mrf_data_group = ticc_group['mrf']['data']\n mrf_keys = mrf_data_group.keys()\n for mkey in mrf_keys:\n mrf_info['clusters'][mkey] = np.asarray(mrf_data_group[mkey]).reshape(n_neurons, n_neurons)\n return mrf_info\n\ndef extract_mrf_network_info(h5_filepath, mrf_namespace, cluster_names):\n if not os.path.isfile(h5_filepath): raise Exception('h5 file does not exist')\n f = h5py.File(h5_filepath, 'r')\n if mrf_namespace not in f: raise Exception('namespace not in h5 file')\n\n network_group = f[mrf_namespace]\n edge_data = network_group['edge data']['data']\n node_data = network_group['node data']['data']\n network_info = {name: {} for name in cluster_names}\n \n for name in cluster_names:\n network_info[name]['nedges'] = network_group['%s nedges' % name][0]\n network_info[name]['nnodes'] = network_group['%s nnodes' % name][0]\n\n network_info[name]['nodes'] = np.asarray(node_data[name], dtype='int32')\n network_info[name]['edges'] = np.asarray(edge_data[name]).reshape((network_info[name]['nedges'], 4))\n\n return network_info\n\ndef extract_synch_sliding(h5_filepath, metric_namespace):\n return _extract_metric_sliding(h5_filepath, metric_namespace)\n\ndef extract_TE_sliding(h5_filepath, metric_namespace):\n return _extract_metric_sliding(h5_filepath, metric_namespace)\n\ndef _extract_metric_sliding(h5_filepath, metric_namespace):\n if not os.path.isfile(h5_filepath): raise Exception('h5 file does not exist')\n f = h5py.File(h5_filepath, 'r')\n if metric_namespace not in f: raise Exception('could not find transfer entropy namespace')\n\n metric_group = f[metric_namespace]\n N = metric_group['n_neurons'][0]\n \n metric_data_group = metric_group['sliding window']['data']\n keys = sorted([int(k) for k in metric_data_group.keys()])\n \n return_matrix = np.zeros((N,N,len(keys)))\n for (idx,key) in enumerate(keys):\n return_matrix[:,:, idx] = np.asarray(metric_data_group[str(key)]).reshape((N,N))\n return return_matrix\n\ndef extract_TE_cluster(h5_filepath, metric_namespace, cname):\n if not os.path.isfile(h5_filepath): raise Exception('h5 file does not exist')\n f = h5py.File(h5_filepath, 'r')\n if metric_namespace not in f: raise Exception('could not find transfer entropy namespace')\n \n metric_group = f[metric_namespace]\n N = metric_group['n_neurons'][0]\n \n metric_data_group = metric_group['cluster']['data']\n return np.asarray(metric_data_group[cname]).reshape(N,N)\n\n\ndef extract_TE_permutation_cluster(h5_filepath, metric_namespace, cname):\n if not os.path.isfile(h5_filepath): raise Exception('h5 file does not exist')\n f = h5py.File(h5_filepath, 'r')\n if metric_namespace not in f: raise Exception('could not find transfer entropy namespace')\n \n metric_group = f[metric_namespace]\n N = metric_group['n_neurons'][0]\n \n permutation_data_group = metric_group['cluster permutation']['data']\n mean_matrix = np.asarray(permutation_data_group['%s mean' % cname]).reshape(N,N)\n var_matrix = np.asarray(permutation_data_group['%s var' % cname]).reshape(N,N)\n return (mean_matrix, var_matrix)\n \n \n\n","sub_path":"fish_utils.py","file_name":"fish_utils.py","file_ext":"py","file_size_in_byte":10453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"309291872","text":"def island(i,j):\n if(n == 1 and lis[i][j] == 1):\n return True\n else:\n ies = [i-1,i,i,i+1]\n jes = [j,j-1,j+1,j]\n valid = 0\n water = 0\n for k in range(4):\n if(ies[k]>=0 and ies[k]=0 and jes[k] 0:\n return urls[0]\n else:\n return None\n\n @classmethod\n def parse_dump_file(cls, json_obj):\n configurations = defaultdict(list)\n\n for topic in json_obj:\n for config in json_obj[topic]:\n name = config[0]\n remotes = config[1]\n user_name = config[2]\n user_email = config[3]\n\n config = cls(topic, name, remotes, user_name, user_email)\n configurations[topic].append(config)\n\n return configurations\n\n def __str__(self):\n name = join(self.topic, self.name)\n return name\n\n def __eq__(self, other):\n if type(self) is not type(other):\n return NotImplemented\n\n same_topic = self.topic == other.topic\n same_repo = self.name == other.name\n\n return same_topic and same_repo\n\n def __gt__(self, other):\n if type(self) is not type(other):\n return NotImplemented\n\n gte_topic = self.topic >= other.topic\n gt_repo = self.name > other.name\n\n return gte_topic and gt_repo\n","sub_path":"gitool/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"404417786","text":"import asyncio\n\nfrom aiohttp import web\n\nfrom modules.context import Context\nfrom modules.data import *\nfrom modules.server.handlers import *\n\nModelItems = Dict[Base, ModelItem]\n\nHOST = 'localhost'\nPORT = 8888\n\n\ndef init_handlers(context) -> Tuple[ModelItems, List[DataHandler]]:\n tickets = Tickets()\n ticketsHandler = GroupHandler(model=tickets, item=Ticket,\n suffix='ticket', context=context)\n groups = Groups()\n groupsHandler = GroupHandler(model=groups, item=Group,\n suffix='group', context=context)\n\n users = Users()\n usersHandler = GroupHandler(model=users, item=User,\n suffix='user', context=context)\n\n comments = Comments()\n commentsHandler = GroupHandler(model=comments, item=Comment,\n suffix='comment', context=context)\n\n queues = Queues()\n queuesHandler = GroupHandler(model=queues, item=Queue,\n suffix='queue', context=context)\n\n history = History_model()\n historyHandler = HistoryHandler(model=history, item=History,\n suffix='history', context=context)\n\n model_items = {\n groups: Group,\n users: User,\n queues: Queue,\n comments: Comment,\n tickets: Ticket,\n Images(): Image,\n history: History,\n }\n handlers = [\n ticketsHandler,\n groupsHandler,\n usersHandler,\n commentsHandler,\n queuesHandler,\n historyHandler,\n ]\n\n return model_items, handlers\n\n\ndef main():\n context = Context()\n model_items, handlers = init_handlers(context)\n db = Database(model_items)\n context.set_db(db)\n context.db = db\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(db.init_db())\n\n app = web.Application()\n for handler in handlers:\n app.add_routes(handler.generate_routes())\n\n app.add_routes([])\n\n web.run_app(app, host=HOST, port=PORT)\n\n\nif __name__ == '__main__':\n # loop = asyncio.get_event_loop()\n # loop.run_until_complete(main())\n main()\n","sub_path":"dtracker/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"166802013","text":"# Chapter 10: Creating Components and Extending Functionality\r\n# Recipe 1: Customizing the ArtProvider\r\n#\r\nimport os\r\nimport wx\r\n\r\n#---- Recipe Code ----#\r\n\r\nclass TangoArtProvider(wx.ArtProvider):\r\n def __init__(self):\r\n super(TangoArtProvider, self).__init__()\r\n\r\n # Attributes\r\n self.bmps = [bmp.replace('.png', '')\r\n for bmp in os.listdir('tango')\r\n if bmp.endswith('.png')]\r\n\r\n def CreateBitmap(self, id,\r\n client=wx.ART_OTHER,\r\n size=wx.DefaultSize):\r\n\r\n # Return NullBitmap on GTK to allow\r\n # the default artprovider to get the\r\n # system theme bitmap.\r\n if wx.Platform == '__WXGTK__':\r\n return wx.NullBitmap\r\n\r\n # Non GTK Platform get custom resource\r\n # when one is available.\r\n bmp = wx.NullBitmap\r\n if client == wx.ART_MENU or size == (16,16):\r\n if id in self.bmps:\r\n path = os.path.join('tango', id+'.png')\r\n bmp = wx.Bitmap(path)\r\n else:\r\n # TODO add support for other bitmap sizes\r\n pass\r\n\r\n return bmp\r\n\r\n#---- End Recipe Code ----#\r\n\r\nclass ArtProviderApp(wx.App):\r\n def OnInit(self):\r\n # Push our custom ArtProvider on to\r\n # the provider stack.\r\n wx.ArtProvider.PushProvider(TangoArtProvider())\r\n self.frame = ArtProviderFrame(None,\r\n title=\"Tango ArtProvider\")\r\n self.frame.Show()\r\n return True\r\n\r\nclass ArtProviderFrame(wx.Frame):\r\n \"\"\"Main application window\"\"\"\r\n def __init__(self, *args, **kwargs):\r\n super(ArtProviderFrame, self).__init__(*args, **kwargs)\r\n\r\n # Attributes\r\n self.panel = ArtProviderPanel(self)\r\n\r\n # Layout\r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n sizer.Add(self.panel, 1, wx.EXPAND)\r\n self.SetSizer(sizer)\r\n self.SetInitialSize((300, 300))\r\n\r\nclass ArtProviderPanel(wx.Panel):\r\n def __init__(self, parent):\r\n super(ArtProviderPanel, self).__init__(parent)\r\n\r\n # Attributes\r\n # Lookup all the art provider ids\r\n art = [ getattr(wx, x) for x in dir(wx)\r\n if x.startswith('ART_') and \r\n not getattr(wx, x).endswith('_C')]\r\n art.sort()\r\n self.artch = wx.Choice(self, choices=art)\r\n self.bmp = wx.StaticBitmap(self)\r\n\r\n # Setup\r\n self.__DoLayout()\r\n\r\n # Event Handlers\r\n self.Bind(wx.EVT_CHOICE, self.OnChoice)\r\n\r\n def __DoLayout(self):\r\n vsizer = wx.BoxSizer(wx.VERTICAL)\r\n hsizer = wx.BoxSizer(wx.HORIZONTAL)\r\n\r\n vsizer.AddStretchSpacer()\r\n hsizer.AddStretchSpacer()\r\n hsizer.Add(self.bmp, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 10)\r\n hsizer.Add(self.artch, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 10)\r\n hsizer.AddStretchSpacer()\r\n vsizer.Add(hsizer, 0, wx.EXPAND)\r\n vsizer.AddStretchSpacer()\r\n self.SetSizer(vsizer)\r\n\r\n def OnChoice(self, event):\r\n sel = self.artch.GetStringSelection()\r\n bmp = wx.ArtProvider.GetBitmap(sel, wx.ART_MENU)\r\n self.bmp.SetBitmap(bmp)\r\n self.bmp.Refresh()\r\n self.Layout()\r\n\r\nif __name__ == '__main__':\r\n app = ArtProviderApp(False)\r\n app.MainLoop()\r\n","sub_path":"wxPython Test/wxPython 2.8 Application Development Cookbook Source Code/1780_10_Code/01/tangoprovider.py","file_name":"tangoprovider.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"537891658","text":"import json\nimport os\nfrom settings import languages_folder\nimport settings\n\n\ndef get_language():\n with open(os.path.join(languages_folder,\"saved_language\")+\".json\") as file_object:\n data=json.load(file_object)\n LANGUAGE=data['saved']\n return LANGUAGE\n\ndef get_font_from_language():\n # try:\n # # with open(os.path.join(languages_folder,\"saved_language\")+\".json\") as file_object:\n # data=json.load(file_object)\n # LANGUAGE=data['saved']\n # if LANGUAGE==\"eng\":\n # FONT=\n # elif LANGUAGE=='rus':\n # FONT=settings.FONT_FILE_RUS\n ## elif LANGUAGE=='ukr':\n # FONT=settings.FONT_FILE_ENG\n #elif LANGUAGE=='pol':\n # FONT=settings.FONT_FILE_ENG\n return settings.FONT_FILE_ENG\n #xcept:\n # pass\n \ndef choosing_language():\n question=input(\"What language do you prefer?\\n 1)ENGLISH\\n 2)RUSSIAN\\n 3)UKRAINIAN\\n 4)POISH\\n ENTER : \")\n if question.startswith('1') or question.lower()=='eng' or question.lower()=='engish'or question.lower().startswith('eng') :\n LANGUAGE=\"eng\"\n elif question.startswith('2') or question.lower()=='rus' or question.lower()=='russian'or question.lower().startswith('rus'):\n LANGUAGE=\"rus\"\n elif question.startswith('3') or question.lower()=='ukr' or question.lower()=='ukrainian' or question.lower()=='як реве дніпро' or question.lower()=='мова солов'+\"'\"+\"їна\" or question.lower()=='українська'or question.lower().startswith('uk') or question.lower().startswith('ук'):\n LANGUAGE=\"ukr\"\n elif question.startswith('4') or question.lower()=='pol' or question.lower()=='polish' or question.lower().startswith('pol'):\n LANGUAGE=\"pol\"\n\n dict={\"saved\":LANGUAGE}\n\n with open(os.path.join(languages_folder,'saved_language.json'),'w') as file_obj:\n json.dump(dict,file_obj)\n\ndef load_controller():\n while True:\n try:\n\n with open(os.path.join(languages_folder,\"saved_language\")+\".json\") as file_object:\n data=json.load(file_object)\n LANGUAGE=data['saved']\n break\n except:\n choosing_language()\n\n with open(os.path.join(languages_folder,\"controller\")+\".json\") as file_object:\n controller_data=json.load(file_object)\n return controller_data\n\n\ndef language_text(search):\n controller_data=load_controller()\n file=controller_data[search]\n with open(languages_folder+\"\\\\\"+get_language()+\"\\\\\"+file+\".txt\") as file:\n text=file.read()\n return text\n\n\n","sub_path":"Project/language_manager.py","file_name":"language_manager.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"589605020","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/nslocalizer/Helpers/Logger.py\n# Compiled at: 2019-02-23 14:43:18\n# Size of source mod 2**32: 4891 bytes\nimport logging\n\nclass Singleton(type):\n _instances = {}\n\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances.keys():\n cls._instances[cls] = (super(Singleton, cls).__call__)(*args, **kwargs)\n return cls._instances[cls]\n\n\nRESET_SEQ = '\\x1b[0m'\nBOLD_SEQ = '\\x1b[1m'\nCOLORS = {'BLACK':'\\x1b[1;30m', \n 'RED':'\\x1b[1;31m', \n 'GREEN':'\\x1b[1;32m', \n 'YELLOW':'\\x1b[1;33m', \n 'BLUE':'\\x1b[1;34m', \n 'MAGENTA':'\\x1b[1;35m', \n 'CYAN':'\\x1b[1;36m', \n 'WHITE':'\\x1b[1;37m'}\nLEVELS = {'WARNING':COLORS['YELLOW'], \n 'INFO':COLORS['BLACK'], \n 'DEBUG':COLORS['MAGENTA'], \n 'CRITICAL':COLORS['BLUE'], \n 'ERROR':COLORS['RED']}\n\nclass ColoredFormatter(logging.Formatter):\n\n def __init__(self, msg, use_color=True):\n logging.Formatter.__init__(self, msg)\n self.use_color = use_color\n\n def format(self, record):\n levelname = record.levelname\n if self.use_color:\n if levelname in LEVELS:\n levelname_color = LEVELS[levelname] + levelname + RESET_SEQ\n record.levelname = levelname_color\n return logging.Formatter.format(self, record)\n\n\nclass Logger(object):\n __metaclass__ = Singleton\n _internal_logger = None\n _debug_logging = False\n _use_ansi_codes = False\n\n def __init__(self, *args, **kwargs):\n pass\n\n @staticmethod\n def enableDebugLogger(is_debug_logger=False):\n Logger._debug_logging = is_debug_logger\n\n @staticmethod\n def disableANSI(disable_ansi=False):\n Logger._use_ansi_codes = not disable_ansi\n\n @staticmethod\n def setupLogger():\n Logger._internal_logger = logging.getLogger('com.pewpewthespells.py.logging_helper')\n level = logging.DEBUG if Logger._debug_logging else logging.INFO\n Logger._internal_logger.setLevel(level)\n handler = logging.StreamHandler()\n handler.setLevel(level)\n formatter = None\n if Logger._debug_logging is True:\n formatter = ColoredFormatter('[%(levelname)s][%(filename)s:%(lineno)s]: %(message)s', Logger._use_ansi_codes)\n else:\n formatter = ColoredFormatter('[%(levelname)s]: %(message)s', Logger._use_ansi_codes)\n handler.setFormatter(formatter)\n Logger._internal_logger.addHandler(handler)\n\n @staticmethod\n def isVerbose(verbose_logging=False):\n if Logger._internal_logger is None:\n Logger.setupLogger()\n if not verbose_logging:\n Logger._internal_logger.setLevel(logging.WARNING)\n\n @staticmethod\n def isSilent(should_quiet=False):\n if Logger._internal_logger is None:\n Logger.setupLogger()\n if should_quiet:\n logging_filter = logging.Filter(name='com.pewpewthespells.py.logging_helper.shut_up')\n Logger._internal_logger.addFilter(logging_filter)\n\n @staticmethod\n def write():\n if Logger._internal_logger is None:\n Logger.setupLogger()\n return Logger._internal_logger","sub_path":"pycfiles/nslocalizer-1.0.2-py3.7/Logger.cpython-37.py","file_name":"Logger.cpython-37.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"632369219","text":"class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n stack = []\n for c in s:\n stack.append(c)\n if len(stack)== 1 and (c == ')' or c == ']' or c == '}'):\n return False\n if c == ')' and stack[-2] == '(':\n stack.pop()\n stack.pop()\n elif c == ']' and stack[-2] == '[':\n stack.pop()\n stack.pop()\n elif c == '}' and stack[-2] == '{':\n stack.pop()\n stack.pop()\n if len(stack)>0:\n return False\n return True\n\n\nif __name__ == '__main__':\n sol = Solution()\n\n print(sol.isValid(\"()[]{}\"))\n print(sol.isValid(\"([)]\"))","sub_path":"lc_1-100/lc_20.py","file_name":"lc_20.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"654247456","text":"# https://leetcode.com/problems/combination-sum-ii/discuss/16944/Beating-98-Python-solution-using-recursion-with-comments\n\nclass Solution:\n \"\"\"\n @param num: Given the candidate numbers\n @param target: Given the target number\n @return: All the combinations that sum to target\n \"\"\"\n def combinationSum2(self, num, target):\n # write your code here\n if not num:\n return []\n \n if not target:\n return [[]]\n \n num.sort()\n res = []\n self.dfs(num, target, [], 0, res)\n return res\n \n def dfs(self, num, target, combination, start, res):\n if target == 0:\n res.append(combination)\n return\n \n for i in range(start, len(num)):\n if i > start and num[i] == num[i - 1]:\n continue\n \n if num[i] > target:\n break\n \n self.dfs(num, target - num[i], combination + [num[i]], i + 1, res)","sub_path":"LintCode/ladder 06 DFS/旧/153. Combination Sum II/.ipynb_checkpoints/solution-checkpoint.py","file_name":"solution-checkpoint.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"308451414","text":"#! /usr/bin/python3\n# -*- encoding: utf-8 -*-\n\nimport time\n\nfrom game import event\nfrom game.event import DrawCard\nfrom game.card import Minion\nfrom game.handler import createHandler\nfrom game.utils.consoleColor import colorMessage\n\nfrom game.engine import Engine\nfrom game.utils.dataUtils import absPath, getCards\n\n\n__author__ = 'fyabc'\n\n\ndef testCard():\n pass\n\n\ndef testEvent():\n pass\n\n\ndef testHandler():\n def process(self, event_):\n print('I am an echo handler %s' % self.IDinEngine)\n print(event_)\n\n EH = createHandler('EchoHandler', DrawCard, process)\n eh = EH()\n\n print('Listen event type: %d' % eh.eventType)\n eh.process('This is a event')\n\n\ndef testEngine():\n e = Engine(echoLevel=Engine.LDebug, playerData=None)\n\n # handler.TurnBeginHandler(e)\n # handler.TurnBeginHandler(e)\n # handler.AddCardHandler(e)\n\n cards = getCards(absPath(__file__, 'data', 'card'), 'basic')\n\n playerData = [\n {\n 'health': 30,\n 'clazz': 'mage',\n 'deck': [\n Minion(cards[0], e, 0),\n Minion(cards[1], e, 0),\n Minion(cards[2], e, 0),\n ],\n },\n {\n 'health': 30,\n 'clazz': 'paladin',\n 'deck': [\n Minion(cards[3], e, 1),\n Minion(cards[4], e, 1),\n ],\n }\n ]\n\n e.createNewGame(playerData)\n\n eventList = [\n event.GameBegin(e),\n event.TurnEnd(e),\n event.TurnEnd(e),\n event.DrawCard(e),\n event.TurnEnd(e),\n event.DrawCard(e),\n event.DrawCard(e),\n event.GameEnd(e),\n ]\n\n timeBefore = time.time()\n for event_ in eventList:\n colorMessage('\\n### === New Operation %s === ###' % event_, foreground=Engine.CInfo)\n e.runOneStep(event_)\n timeAfter = time.time()\n\n colorMessage('\\nTime passed: %.4fs' % (timeAfter - timeBefore), foreground=Engine.CError)\n\n\ndef test():\n testHandler()\n # testEngine()\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"479039452","text":"import requests\nimport pytest\nimport unittest\nfrom client.client import Client\nfrom constants.environment import EnvConfig\nimport numpy as np\nimport time\n\nDEFAULT_CONFIG = EnvConfig(\n quote_asset='BTC',\n commission=0.075,\n feature_num=3,\n asset_num=50,\n window_size=90,\n selection_period=90,\n selection_method='s2vol',\n init_balance=1,\n env_type='sandbox',\n step_rate=3\n)\n\nclient = Client(\"http://localhost:5000\")\n\ndef test_performance():\n start = time.time()\n for x in range(1000):\n state = client.get_state(\n asset_number=DEFAULT_CONFIG.asset_num,\n window_size=DEFAULT_CONFIG.window_size,\n feature_number=DEFAULT_CONFIG.feature_num,\n selection_period=DEFAULT_CONFIG.selection_period,\n selection_method=DEFAULT_CONFIG.selection_method\n )\n print(x)\n elapsed_time_lc=(time.time()-start)\n print(elapsed_time_lc)\n assert elapsed_time_lc","sub_path":"environment/test/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"196516772","text":"\"\"\"PyNE nuclear data tests\"\"\"\nimport os\nimport math\n\nimport nose \nfrom nose.tools import assert_equal, assert_not_equal, assert_raises, raises, assert_in\n\nimport pyne\nfrom pyne import data\nimport numpy as np\n\n# These tests require nuc_data\nif not os.path.isfile(pyne.nuc_data):\n raise RuntimeError(\"Tests require nuc_data.h5. Please run nuc_data_make.\")\n\ndef test_atomic_mass():\n o16 = [15.99491461957, 16.0]\n u235 = [235.043931368, 235.0]\n am242m = [242.059550625, 242.0]\n\n # zzaam form\n assert_in(data.atomic_mass(80160), o16)\n assert_in(data.atomic_mass(922350), u235)\n assert_in(data.atomic_mass(952421), am242m)\n\n\ndef test_b_coherent():\n assert_equal(data.b_coherent('H1'), -3.7406E-13 + 0j)\n assert_equal(data.b_coherent(491150), 4.01E-13 - 5.62E-15j)\n\n\ndef test_b_incoherent():\n assert_equal(data.b_incoherent('PD105'), -2.6E-13 + 0j)\n assert_equal(data.b_incoherent(621490), 3.14E-12 - 1.03E-12j)\n\n\ndef test_b():\n bc = data.b_coherent(621490)\n bi = data.b_incoherent('SM149')\n assert_equal(data.b('SM149'), math.sqrt(abs(bc)**2 + abs(bi)**2))\n\n\ndef test_half_life():\n assert_equal(data.half_life('H1'), np.inf)\n assert_equal(data.half_life(922351), 1560.0) \n\n\ndef test_decay_const():\n assert_equal(data.decay_const('H1'), 0.0)\n assert_equal(data.decay_const(922351), np.log(2.0)/1560.0) \n\n\nif __name__ == \"__main__\":\n nose.main()\n\n","sub_path":"pyne/tests/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"177629862","text":"from django.conf.urls import url\nfrom .views import *\n\napp_name = 'jobs'\n\nurlpatterns = [\n url(r'^addjobs/$', addjobs_view, name='addjobs'),\n url(r'^ilandetay/(?P[0-9]+)/$', isİlaniDetay, name='ilandetay'),\n url(r'^ilanguncelle/(?P[0-9]+)/$', isİlaniGuncelle, name='ilanguncelle'),\n url(r'^ilansil/(?P[0-9]+)/$', isİlaniSil, name='ilansil'),\n url(r'^ilanlarim/$', ilanlarim, name='ilanlarim'),\n url(r'^ilanlar/$', isİlaniGoruntule, name='ilanlar'),\n url(r'^stajekle/$', stajIlaniEkle, name='stajekle'),\n url(r'^stajilanlari/$', stajİlaniGoruntule, name='stajilanlari'),\n url(r'^stajilanidetay/(?P[0-9]+)/$', stajİlaniDetay, name='stajilanidetay'),\n url(r'^stajilaniguncelle/(?P[0-9]+)/$', stajİlaniGuncelle, name='stajilaniguncelle'),\n url(r'^stajilanisil/(?P[0-9]+)/$', stajİlaniSil, name='stajilanisil'),\n]","sub_path":"jobs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"559685295","text":"import unittest\r\nimport requests\r\nimport json\r\nimport datetime\r\nimport time\r\n#导入公用参数readConfig.py\r\nfrom Common.readConfig import *\r\n\r\nclass TestMethod(unittest.TestCase): # 定义一个类,继承自unittest.TestCase\r\n '''安装正常流程测试'''\r\n def test_a(self):\r\n '''录单'''\r\n #录单接口\r\n url1 = \"http://\" + global_var.api_host + \"/ms-fahuobao-order/FhbOrder/saveOrder\"\r\n\r\n i = datetime.datetime.now()\r\n print(\"收件人姓名:yi装测试\" + str(i.month) + str(i.day))\r\n\r\n data1 = {\r\n \"businessNo\": \"BSTE02\",\r\n \"serviceNo\": \"FHB03\",\r\n \"orderWay\": 1,\r\n \"wokerUserName\": \"\",\r\n \"wokerPhone\": \"\",\r\n \"wokerPrice\": \"\",\r\n \"checked\": \"\",\r\n \"verfiyType\": \"\",\r\n \"goods\": [\r\n {\r\n \"num\":1,\r\n \"picture\":\"5b961f335b1fac00019758e4\",\r\n \"memo\":\"zzz\",\r\n \"bigClassNo\":\"FHB01\",\r\n \"middleClassNo\":\"FHB01002\",\r\n \"pictureType\":\"2\",\r\n \"pictureName\":\"黑色小角几\"\r\n }\r\n ],\r\n \"isElevator\": \"0\",\r\n \"predictServiceDate\": \"\",\r\n \"predictDevliveryDate\": \"\",\r\n \"memo\": \"\",\r\n \"isArriva\": 1,\r\n \"boolCollection\": \"0\",\r\n \"collectionMoney\": \"\",\r\n \"collectionMemo\": \"\",\r\n \"allVolume\": \"2\",\r\n \"allWeight\": \"12\",\r\n \"allPackages\": \"3\",\r\n \"allCargoPrice\": \"1212\",\r\n \"consigneeName\": \"yi装测试\" + str(i.month) + str(i.day),\r\n \"consigneePhone\": \"15023621702\",\r\n \"consigneeAddress\": \"武侯大道\",\r\n \"floor\": \"2\",\r\n \"deliveryName\": \"提货联系:\",\r\n \"deliveryPhone\": \"15023621702\",\r\n \"provinceNo\": \"510000\",\r\n \"province\": \"四川省\",\r\n \"cityNo\": \"510100\",\r\n \"city\": \"成都市\",\r\n \"districtNo\": \"510107\",\r\n \"district\": \"武侯区\",\r\n \"deliveryProvinceNo\": \"\",\r\n \"deliveryProvince\": \"\",\r\n \"deliveryCityNo\": \"\",\r\n \"deliveryCity\": \"\",\r\n \"deliveryDistrictNo\": \"\",\r\n \"deliveryDistrict\": \"\",\r\n \"verifyOrderNo\": \"\"\r\n }\r\n request1 = requests.post( url1, data = json.dumps(data1) ,headers = global_var.headers1)\r\n print(\"录单:\" + request1.text)\r\n time.sleep(3)\r\n self.assertIn(global_var.arg1, request1.text, msg='测试fail')\r\n\r\n def test_b(self):\r\n '''连接数据库查询订单'''\r\n global i\r\n i = datetime.datetime.now()\r\n consignee_name1 = \"yi装测试\" + str(i.month) + str(i.day)\r\n\r\n # 使用cursor()方法获取操作游标\r\n cursor = global_var.db.cursor()\r\n # 通过订单的收件人姓名查询出订单id\r\n sql1 = \"select id,order_no from fhb_order where id in (select fhb_order_id from fhb_order_consignee_info where consigne_name = '\" + consignee_name1 + \"') ORDER BY foundtime DESC\"\r\n # 执行SQL语句\r\n cursor.execute(sql1)\r\n # 获取所有记录列表\r\n results = cursor.fetchall()\r\n # print(results[0])\r\n # 有多个的情况,取第一个订单的id\r\n global orderid, orderno\r\n orderid = results[0]['id']\r\n orderno = results[0]['order_no']\r\n print(\"订单id:\" + orderid)\r\n print(\"订单编号:\" + orderno)\r\n\r\n def test_c(self):\r\n '''师傅报价'''\r\n url2 = \"http://\" + global_var.api_host + \"/ms-fahuobao-order/bidding/quoted-price\"\r\n data2 = {\r\n \"memo\": \"\",\r\n \"money\": \"40\",\r\n \"orderId\": orderid\r\n }\r\n request2 = requests.request(\"POST\", url=url2, data=json.dumps(data2), headers=global_var.headers2)\r\n print(\"师傅报价:\" + request2.text)\r\n time.sleep(3)\r\n self.assertIn(global_var.arg1, request2.text, msg='测试fail')\r\n\r\n def test_d(self):\r\n '''web端报价中选择师傅'''\r\n global_var.db.connect()\r\n sql2 = \"select id from fhb_order_bidding_log where fhb_order_id = '\" + orderid + \"'\"\r\n # 使用cursor()方法获取操作游标\r\n cursor2 = global_var.db.cursor()\r\n # 执行SQL语句\r\n cursor2.execute(sql2)\r\n # 获取所有记录列表\r\n results2 = cursor2.fetchall()\r\n # 有多个的情况,取第一个订单的id\r\n biddinglogid = results2[0]['id']\r\n print(\"竞价记录id:\" + biddinglogid)\r\n url3 = \"http://\" + global_var.api_host + \"/ms-fahuobao-order/FhbOrder/choice-pay?orderId=\" + orderid + \"&biddingLogId=\" + biddinglogid + \"\"\r\n request3 = requests.get(url3, headers=global_var.headers1)\r\n print(\"选择师傅get请求的url:\" + url3)\r\n print(\"选择师傅:\" + request3.text)\r\n self.assertIn(global_var.arg1, request3.text, msg='测试fail')\r\n\r\n def test_e(self):\r\n '''数据库更新竞价金额为0.01'''\r\n # 数据库更新竞价金额为0.01\r\n sql3 = \"UPDATE fhb_order_bidding_log set money = '0.01' where fhb_order_id = '\" + orderid + \"'\"\r\n print(sql3)\r\n cursor3 = global_var.db.cursor()\r\n # 执行SQL语句\r\n cursor3.execute(sql3)\r\n # MySQL的默认存储引擎就是InnoDB, 所以对数据库数据的操作会在事先分配的缓存中进行, 只有在commit之后, 数据库的数据才会改变\r\n global_var.db.commit()\r\n\r\n def test_f(self):\r\n '''钱包余额支付中标费用'''\r\n url4 = \"http://\" + global_var.api_host + \"/ms-fahuobao-user/wallet/balance-pay\"\r\n data4 = {\r\n \"objectList\": [orderid],\r\n \"money\": 0.01,\r\n \"password\": \"123456\"\r\n }\r\n request4 = requests.request(\"POST\", url=url4, data=json.dumps(data4), headers=global_var.headers1)\r\n print(\"钱包余额支付中标费用:\" + request4.text)\r\n time.sleep(6)\r\n self.assertIn(global_var.arg1, request4.text, msg='测试fail')\r\n\r\n def test_g(self):\r\n '''居家小二操作预约'''\r\n global_var.db1.connect()\r\n sql5 = \"select id from order_data where order_no = '\" + orderno + \"'\"\r\n print(sql5)\r\n # 使用cursor()方法获取操作游标\r\n cursor5 = global_var.db1.cursor()\r\n # 执行SQL语句\r\n cursor5.execute(sql5)\r\n global_var.db1.commit()\r\n # 获取所有记录列表\r\n results5 = cursor5.fetchall()\r\n # 有多个的情况,取第一个订单的id\r\n global xrid\r\n xrid = results5[0]['id']\r\n print(\"通过fhb订单号查询居家小二订单id:\" + xrid)\r\n url5 = \"http://\" + global_var.api_host + \"/ms-fahuobao-order-data/appOrder/appointappoint-distributionOne-choose\"\r\n data5 = {\r\n \"branchUserId\": \"\",\r\n \"cause\": \"\",\r\n \"codeYT\": \"night\",\r\n \"ids\": [xrid],\r\n \"timeYT\": str(i.year) + \"-\" + str(i.month) + \"-\" + str(i.day)\r\n }\r\n request5 = requests.request(\"POST\", url=url5, data=json.dumps(data5), headers=global_var.headers2)\r\n print(\"预约:\" + request5.text)\r\n time.sleep(3)\r\n self.assertIn(global_var.arg1, request5.text, msg='测试fail')\r\n\r\n def test_h(self):\r\n '''居家小二操作上门'''\r\n global_var.db1.connect()\r\n sql6 = \"select id from assign_worker where order_id = '\" + xrid + \"'\"\r\n print(sql6)\r\n cursor6 = global_var.db1.cursor()\r\n cursor6.execute(sql6)\r\n # 获取所有记录列表\r\n results6 = cursor6.fetchall()\r\n # print(results6[0])\r\n global assignid\r\n assignid = results6[0][\"id\"]\r\n print(\"assigned:\" + assignid)\r\n url7 = \"http://\" + global_var.api_host + \"/ms-fahuobao-order-data/appOrder/houseCall?assignId=\" + assignid + \"&orderId=\" + assignid + \"\"\r\n request7 = requests.request(\"POST\", url=url7, headers=global_var.headers2)\r\n print(\"上门:\" + request7.text)\r\n time.sleep(3)\r\n self.assertIn(global_var.arg1, request7.text, msg='测试fail')\r\n\r\n def test_i(self):\r\n '''居家小二操作签收'''\r\n global_var.db.connect()\r\n sql8 = \"select service_code from fhb_order where order_no = '\" + orderno + \"'\"\r\n cursor8 = global_var.db.cursor()\r\n cursor8.execute(sql8)\r\n # 获取所有记录列表\r\n results8 = cursor8.fetchall()\r\n # print(results8[0])\r\n serviceCode = results8[0][\"service_code\"]\r\n print(\"serviceCode:\" + serviceCode)\r\n\r\n url8 = \"http://\" + global_var.api_host + \"/ms-fahuobao-order-data/appOrder/appOrderSign\"\r\n data8 = {\r\n \"assignId\": assignid,\r\n \"imgId\": [\"5b581a07d423d400017bf0d2\"],\r\n \"jdVerificationCode\": \"\",\r\n \"qmImg\": \"5b581a00d423d400017bf0d0\",\r\n \"serviceCode\": serviceCode,\r\n \"serviceTypeCode\": \"CZSETE01\"\r\n }\r\n request8 = requests.request(\"POST\", url=url8, data=json.dumps(data8), headers=global_var.headers2)\r\n print(\"签收:\" + request8.text)\r\n time.sleep(3)\r\n self.assertIn(global_var.arg1, request8.text, msg='测试fail')\r\n\r\n def test_j(self):\r\n '''发货宝确认评价'''\r\n url9 = \"http://\" + global_var.api_host + \"/ms-fahuobao-order/FhbOrder/evaluation\"\r\n data9 = {\r\n \"fhbOrderId\": orderid,\r\n \"stars\": 5,\r\n \"pictures\": \"5b581cfbd423d400017bf0d4\",\r\n \"memo\": \"评价说明\",\r\n \"tips\": \"做事认真负责,技术超好,服务守时\"\r\n }\r\n request9 = requests.request(\"POST\", url=url9, data=json.dumps(data9), headers=global_var.headers1)\r\n print(\"确认评价:\" + request9.text)\r\n time.sleep(4)\r\n self.assertIn(global_var.arg1, request9.text, msg='测试fail')\r\n\r\n def test_k(self):\r\n '''运营管理进行订单结算'''\r\n url10 = \"http://\" + global_var.api_host + \"/ms-fahuobao-order-data/order-wallet/clearing-confirm\"\r\n data10 = xrid\r\n request10 = requests.request(\"POST\", url=url10, data=data10, headers=global_var.headers3)\r\n print(\"订单结算:\" + request10.text)\r\n self.assertIn(global_var.arg1, request10.text, msg='测试fail')\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()","sub_path":"SaaSFlowTest/NewFlowTestCase/testZhuangSaasNormalFlow.py","file_name":"testZhuangSaasNormalFlow.py","file_ext":"py","file_size_in_byte":10702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"425873104","text":"#!/usr/bin/env python\n\nimport json\nimport logging\nimport os\n\nfrom fuzzywuzzy import fuzz as fw_fuzz\nfrom textblob import TextBlob\n\nfrom lib.utils.systemtools import run_command\nfrom lib.utils.moduletools import ModuleIndexer\n\n\nclass FileIndexer(ModuleIndexer):\n\n files = []\n\n def __init__(self, checkoutdir=None, cmap=None):\n\n if not os.path.isfile(cmap):\n import lib.triagers.ansible as at\n basedir = os.path.dirname(at.__file__)\n basedir = os.path.dirname(basedir)\n basedir = os.path.dirname(basedir)\n cmap = os.path.join(basedir, cmap)\n\n self.checkoutdir = checkoutdir\n self.CMAP = {}\n if cmap:\n with open(cmap, 'rb') as f:\n self.CMAP = json.load(f)\n\n self.get_files()\n self.match_cache = {}\n\n def get_files(self):\n # manage the checkout\n if not os.path.isdir(self.checkoutdir):\n self.create_checkout()\n else:\n self.update_checkout()\n\n cmd = 'find %s' % self.checkoutdir\n (rc, so, se) = run_command(cmd)\n files = so.split('\\n')\n files = [x.strip() for x in files if x.strip()]\n files = [x.replace(self.checkoutdir + '/', '') for x in files]\n files = [x for x in files if not x.startswith('.git')]\n self.files = files\n\n def get_component_labels(self, valid_labels, files):\n '''Matches a filepath to the relevant c: labels'''\n labels = [x for x in valid_labels if x.startswith('c:')]\n\n clabels = []\n for cl in labels:\n l = cl.replace('c:', '', 1)\n al = os.path.join('lib/ansible', l)\n if al.endswith('/'):\n al = al.rstrip('/')\n for f in files:\n if not f:\n continue\n if f.startswith(l) or f.startswith(al):\n clabels.append(cl)\n\n # use the more specific labels\n clabels = sorted(set(clabels))\n tmp_clabels = [x for x in clabels]\n for cl in clabels:\n for x in tmp_clabels:\n if cl != x and x.startswith(cl):\n if cl in tmp_clabels:\n tmp_clabels.remove(cl)\n if tmp_clabels != clabels:\n clabels = [x for x in tmp_clabels]\n clabels = sorted(set(clabels))\n\n return clabels\n\n def _string_to_cmap_key(self, text):\n text = text.lower()\n matches = []\n if text.endswith('.'):\n text = text.rstrip('.')\n if text in self.CMAP:\n matches += self.CMAP[text]\n return matches\n elif (text + 's') in self.CMAP:\n matches += self.CMAP[text + 's']\n return matches\n elif text.rstrip('s') in self.CMAP:\n matches += self.CMAP[text.rstrip('s')]\n return matches\n return matches\n\n def find_component_match(self, title, body, template_data):\n '''Make a list of matching files for arbitrary text in an issue'''\n\n # DistributionNotFound: The 'jinja2<2.9' distribution was not found and\n # is required by ansible\n # File\n # \"/usr/lib/python2.7/site-packages/ansible/plugins/callback/foreman.py\",\n # line 30, in \n\n STOPWORDS = ['ansible', 'core', 'plugin']\n STOPCHARS = ['\"', \"'\", '(', ')', '?', '*', '`', ',']\n matches = []\n\n if 'Traceback (most recent call last)' in body:\n lines = body.split('\\n')\n for line in lines:\n line = line.strip()\n if line.startswith('DistributionNotFound'):\n matches = ['setup.py']\n break\n elif line.startswith('File'):\n fn = line.split()[1]\n for SC in STOPCHARS:\n fn = fn.replace(SC, '')\n if 'ansible_module_' in fn:\n fn = os.path.basename(fn)\n fn = fn.replace('ansible_module_', '')\n matches = [fn]\n elif 'cli/playbook.py' in fn:\n fn = 'lib/ansible/cli/playbook.py'\n elif 'module_utils' in fn:\n idx = fn.find('module_utils/')\n fn = 'lib/ansible/' + fn[idx:]\n elif 'ansible/' in fn:\n idx = fn.find('ansible/')\n fn1 = fn[idx:]\n\n if 'bin/' in fn1:\n if not fn1.startswith('bin'):\n\n idx = fn1.find('bin/')\n fn1 = fn1[idx:]\n\n if fn1.endswith('.py'):\n fn1 = fn1.rstrip('.py')\n\n elif 'cli/' in fn1:\n idx = fn1.find('cli/')\n fn1 = fn1[idx:]\n fn1 = 'lib/ansible/' + fn1\n\n elif 'lib' not in fn1:\n fn1 = 'lib/' + fn1\n\n if fn1 not in self.files:\n #import epdb; epdb.st()\n pass\n if matches:\n return matches\n\n craws = template_data.get('component_raw')\n if craws is None:\n return matches\n\n # compare to component mapping\n matches = self._string_to_cmap_key(craws)\n if matches:\n return matches\n\n # do not re-process the same strings over and over again\n if craws.lower() in self.match_cache:\n return self.match_cache[craws.lower()]\n\n # make ngrams from largest to smallest and recheck\n blob = TextBlob(craws.lower())\n wordcount = len(blob.tokens) + 1\n\n for ng_size in reversed(xrange(2,wordcount)):\n ngrams = [' '.join(x) for x in blob.ngrams(ng_size)]\n for ng in ngrams:\n\n matches = self._string_to_cmap_key(ng)\n if matches:\n self.match_cache[craws.lower()] = matches\n return matches\n\n # https://pypi.python.org/pypi/fuzzywuzzy\n matches = []\n for cr in craws.lower().split('\\n'):\n ratios = []\n for k in self.CMAP.keys():\n ratio = fw_fuzz.ratio(cr, k)\n ratios.append((ratio, k))\n ratios = sorted(ratios, key=lambda tup: tup[0])\n if ratios[-1][0] >= 90:\n cnames = self.CMAP[ratios[-1][1]]\n matches += cnames\n if matches:\n self.match_cache[craws.lower()] = matches\n return matches\n\n # try to match to repo files\n if craws:\n clines = craws.split('\\n')\n for craw in clines:\n cparts = craw.replace('-', ' ')\n cparts = cparts.split()\n\n for idx,x in enumerate(cparts):\n for SC in STOPCHARS:\n if SC in x:\n x = x.replace(SC, '')\n for SW in STOPWORDS:\n if x == SW:\n x = ''\n if x and '/' not in x:\n x = '/' + x\n cparts[idx] = x\n\n cparts = [x.strip() for x in cparts if x.strip()]\n\n for x in cparts:\n for f in self.files:\n if '/modules/' in f:\n continue\n if 'test/' in f and 'test' not in craw:\n continue\n if 'galaxy' in f and 'galaxy' not in body:\n continue\n if 'dynamic inv' in body.lower() and 'contrib' not in f:\n continue\n if 'inventory' in f and 'inventory' not in body.lower():\n continue\n if 'contrib' in f and 'inventory' not in body.lower():\n continue\n\n try:\n f.endswith(x)\n except UnicodeDecodeError:\n continue\n\n fname = os.path.basename(f).split('.')[0]\n\n if f.endswith(x):\n if fname.lower() in body.lower():\n matches.append(f)\n break\n if f.endswith(x + '.py'):\n if fname.lower() in body.lower():\n matches.append(f)\n break\n if f.endswith(x + '.ps1'):\n if fname.lower() in body.lower():\n matches.append(f)\n break\n if os.path.dirname(f).endswith(x):\n if fname.lower() in body.lower():\n matches.append(f)\n break\n\n logging.info('%s --> %s' % (craws, sorted(set(matches))))\n self.match_cache[craws.lower()] = matches\n return matches\n","sub_path":"lib/utils/file_tools.py","file_name":"file_tools.py","file_ext":"py","file_size_in_byte":9269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"289249136","text":"# script para geração da métrica JWCOSR - Jointly Developers Weighted Commit to Share Repositories\n\n# será gerado um arquivo contendo os valores da métrica por par de usuários\n# adicionalmente, será gerado um segundo arquivo com todas as opções de cálculo disponíveis\n# o arquivo gerado para a métrica SR é utilizado no cálculo da NL\n\n# cabeçalho do arquivo gerado (NL.csv):\n# 0 - programming_language_id\n# 1 - developer_id_1\n# 2 - developer_id_2\n# 3 - NL (NL_mod)\n\n# cabeçalho do arquivo gerado (NL_all_options.csv):\n# 0 - programming_language_id\n# 1 - developer_id_1\n# 2 - developer_id_2\n# 3 - NL_add\n# 4 - NL_sum\n# 5 - NL_dif\n# 6 - NL_mods\n\nimport sys, csv, operator, collections\n\n# cria dict com os valores de SR para cada par de usuários da rede\nSR_metric = {}\n\nprint(\"Reading SR.csv...\")\nwith open('../Files/SR.csv', 'r') as r:\n\tSR_file = csv.reader(r, delimiter=',')\n\n\tnext(SR_file) # cabeçalho\n\t# programming_language_id, developer_id_1, developer_id_2, SR\n\n\tfor row in SR_file:\n\t\tprog_lang_id = int(row[0])\n\t\tdev1 = int(row[1])\n\t\tdev2 = int(row[2])\n\t\tSR = int(row[3])\n\n\t\tSR_metric[prog_lang_id, dev1, dev2] = SR\nr.close()\nprint(\"Finished read SR.csv\")\n\n# cria dict com os repositórios da rede com sua linguagem e suas quantidades de linhas adicionadas e deletadas\nrep_dict_language = {}\n\nprint(\"Reading repository.csv...\")\nwith open('../DataSet/repository.csv', 'r') as r:\n\trepositories = csv.reader(r, delimiter=',')\n\n\tnext(repositories) # cabeçalho\n\t# repository_id,name,description,programming_language_id,url,create_date,end_date,duration_days,number_add_lines,number_del_lines,number_commits,number_commiters\n\n\tfor row in repositories:\n\t\trep_id = int(row[0])\n\t\tprog_lang_id = int(row[3])\n\t\tadd_lines_rep = int(row[8])\n\t\tdel_lines_rep = int(row[9])\n\n\t\t# inclui no dict cada repositório, o id da sua linguagem e as quantidades de linhas para a métrica\n\t\tsum_lines_rep = add_lines_rep + del_lines_rep\n\t\tdif_lines_rep = max(add_lines_rep - del_lines_rep, 0)\n\t\tmod_lines_rep = abs(add_lines_rep - del_lines_rep)\n\t\t\n\t\trep_dict_language[rep_id] = [prog_lang_id, add_lines_rep, sum_lines_rep, dif_lines_rep, mod_lines_rep]\nr.close()\nprint(\"Finished read repository.csv\")\n\n# lê informações da rede realizando os cálculos para a métrica\nNL_metric = {}\n\nprint(\"Reading developers_social_network.csv...\")\nwith open('../DataSet/developers_social_network.csv', 'r') as r:\n\tdata = csv.reader(r, delimiter=',')\n\n\tnext(data) # cabeçalho\n\t# repository_id,developer_id_1,developer_id_2,begin_contribution_date,end_contribution_date,contribution_days,number_add_lines,number_del_lines,number_commits\n\n\tfor row in data:\n\t\trep_id = int(row[0])\n\n\t\tdev_1_id = int(row[1])\n\t\tdev_2_id = int(row[2])\n\t\tadd_lines = int(row[6])\n\t\tdel_lines = int(row[7])\n\t\t\n\t\tsum_lines = add_lines + del_lines\n\t\tdif_lines = max(add_lines - del_lines, 0)\n\t\tmod_lines = abs(add_lines - del_lines)\n\n\t\tprog_lang_id = rep_dict_language[rep_id][0]\n\n\t\t# recalcula utilizando a divisão pelas quantidades do repositório\n\t\tadd_lines = 0 if rep_dict_language[rep_id][1] == 0 else (add_lines / rep_dict_language[rep_id][1])\n\t\tsum_lines = 0 if rep_dict_language[rep_id][2] == 0 else (sum_lines / rep_dict_language[rep_id][2])\n\t\tdif_lines = 0 if rep_dict_language[rep_id][3] == 0 else (dif_lines / rep_dict_language[rep_id][3])\n\t\tmod_lines = 0 if rep_dict_language[rep_id][4] == 0 else (mod_lines / rep_dict_language[rep_id][4])\n\n\t\t# normaliza valores menores que zero\n\t\tadd_lines = 0 if add_lines < 0 else add_lines\n\t\tsum_lines = 0 if sum_lines < 0 else sum_lines\n\t\tdif_lines = 0 if dif_lines < 0 else dif_lines\n\t\tmod_lines = 0 if mod_lines < 0 else mod_lines\n\t\t\t\n\t\t# cria um dict com cada par de desenvolvedores e o valor dos cálculos para eles\n\t\t# key = (programming_language_id, dev1, dev2) values = add_lines, sum_lines, dif_lines, mod_lines\n\t\tif (prog_lang_id, dev_1_id, dev_2_id) in NL_metric:\n\t\t\ttotal_add_lines = NL_metric[prog_lang_id, dev_1_id, dev_2_id][0] + add_lines\n\t\t\ttotal_sum_lines = NL_metric[prog_lang_id, dev_1_id, dev_2_id][1] + sum_lines\n\t\t\ttotal_dif_lines = NL_metric[prog_lang_id, dev_1_id, dev_2_id][2] + dif_lines\n\t\t\ttotal_mod_lines = NL_metric[prog_lang_id, dev_1_id, dev_2_id][3] + mod_lines\n\n\t\t\tNL_metric[prog_lang_id, dev_1_id, dev_2_id] = [total_add_lines, total_sum_lines, total_dif_lines, total_mod_lines]\n\t\telse:\n\t\t\tNL_metric[prog_lang_id, dev_1_id, dev_2_id] = [add_lines, sum_lines, dif_lines, mod_lines]\nr.close()\n\n# ordena dict da métrica\nprint(\"Sorting NL metric dict...\")\nNL = collections.OrderedDict(sorted(NL_metric.items()))\n\n# escreve todos os dados da métrica no arquivo final com métrica única\nprint(\"Writing NL.csv...\")\nwith open('../Files/NL.csv', 'w') as w:\n\tmetric_file = csv.writer(w, delimiter=',')\n\n\t# escreve cabeçalho\n\tmetric_file.writerow([\"programming_language_id\", \"developer_id_1\", \"developer_id_2\", \"NL\"])\n\n\t# a soma dos valores da métrica são divididos pelo número de repositórios compartilhados entre os desenvolvedores (SR)\n\tfor row in NL:\n\t\tmetric_file.writerow([row[0], row[1], row[2], NL[row][3]/SR_metric[row]])\nw.close()\n\n# escreve todos os dados da métrica no arquivo final com todas as opções\nprint(\"Writing NL_all_options.csv...\")\nwith open('../Files/NL_all_options.csv', 'w') as w:\n\tmetric_file = csv.writer(w, delimiter=',')\n\n\t# escreve cabeçalho\n\tmetric_file.writerow([\"programming_language_id\", \"developer_id_1\", \"developer_id_2\", \"NL_add\", \"NL_sum\", \"NL_dif\", \"NL_mod\"])\n\n\t# a soma dos valores da métrica são divididos pelo número de repositórios compartilhados entre os desenvolvedores (SR)\n\tfor row in NL:\n\t\tmetric_file.writerow([row[0], row[1], row[2], NL[row][0]/SR_metric[row], NL[row][1]/SR_metric[row], NL[row][2]/SR_metric[row], NL[row][3]/SR_metric[row]])\nw.close()","sub_path":"Metrics/04_generate_NL_metric.py","file_name":"04_generate_NL_metric.py","file_ext":"py","file_size_in_byte":5753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"619950021","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\ndef dfs(y):\n if y == N:\n global count\n count += 1\n return\n\n for x in range(N):\n if row[x] or diag1[x + y] or diag2[x - y]:\n continue\n\n row[x] = diag1[x + y] = diag2[x - y]= 1\n dfs(y+1)\n row[x] = diag1[x + y] = diag2[x - y]= 0\n\n\nT = int(input())\n\nfor tc in range(T):\n N = int(input())\n count = 0\n row, diag1, diag2 = [0 for _ in range(N)], [0 for _ in range(2 * N - 1)], [0 for _ in range(2 * N - 1)]\n\n dfs(0)\n\n print('#{} {}'.format(tc+1, count))","sub_path":"2020/1030/swea_2806_N_Queen_2.py","file_name":"swea_2806_N_Queen_2.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"409487883","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# CHANGELOG:\n#\t0.2.1:\n#\t\tadded paused status\n#\t0.2:\n#\t\tretrieving title & artist rewritten with dbus\n#\t0.1:\n#\t\tfirst version; pid, title & artist collected by popen(), e.g. popen('banshee --query-artist').readline()\n\n# imports\nimport xchat\nimport dbus\nfrom os import popen\n\n# module info\n__module_name__ = \"banshee_np\"\n__module_version__ = \"0.2.1\"\n__module_description__ = \"Information about current Banshee track\"\n__module_autor__ = \"andrzej3393\"\n\n# code\ndef np_cb(word, word_eof, userdata):\n\tif popen('pidof banshee').readline():\n\t\tbus = dbus.SessionBus()\n\t\tbanshee = bus.get_object('org.bansheeproject.Banshee', '/org/bansheeproject/Banshee/PlayerEngine')\n\t\tstate = banshee.GetCurrentState()\n\t\tif state.encode('utf-8') == \"playing\":\n\t\t\tcurrenttrack = banshee.GetCurrentTrack()\n\t\t\txchat.command('ME np: %s - %s' % (currenttrack['artist'].encode('utf-8'), currenttrack['name'].encode('utf-8')))\n\t\telif state.encode('utf-8') == \"paused\":\n\t\t\tcurrenttrack = banshee.GetCurrentTrack()\n\t\t\txchat.command('ME np: %s - %s (paused)' % (currenttrack['artist'].encode('utf-8'), currenttrack['name'].encode('utf-8')))\n\t\telse:\n\t\t\txchat.prnt('There is nothing played.')\n\t\t\treturn xchat.EAT_ALL\n\telse:\n\t\txchat.prnt(\"Banshee is not already running.\")\n\treturn xchat.EAT_ALL\n\ndef unload_cb(userdata):\n\txchat.unhook(HOOKMUSIC)\n\nHOOKMUSIC = xchat.hook_command(\"np\", np_cb)\nHOOKUNLOAD = xchat.hook_unload(unload_cb)\n","sub_path":"banshee_np/np.py","file_name":"np.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"42320954","text":"from django.shortcuts import render, get_object_or_404\nfrom django.db.models import Q, Prefetch\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\n# 외부함수\nfrom .match_funcs import re_geocode, re_dongcode\n\n# 모델\nfrom users.models import User, BeforeMatch, AfterMatch\nfrom match.models import Sports, Match, MatchUser, Locations\n\n# 시리얼라이저\nfrom .serializers import BMSerializer\n\n# 임시로 사용하는 데코레이터입니다.\n# from .models import \n\n# 매칭 등록 시 \n@api_view(['POST'])\ndef before_match(request):\n data = request.data\n\n import datetime\n\n # 최대 매치 개수를 생각해서 제한할 것\n # 시간 겹치지 않게 처리\n\n all_user_bm = BeforeMatch.objects.filter(user=request.user, date = data['date']).exclude(Q(status= '4') | Q(status='5'))\n \n stime_str = data['start_time']\n stime = datetime.datetime.strptime(stime_str, '%H:%M').time()\n\n etime_str = data['end_time']\n etime = datetime.datetime.strptime(etime_str, '%H:%M').time()\n\n if all_user_bm:\n for user_bm in all_user_bm:\n if etime < user_bm.start_time or stime > user_bm.end_time:\n continue\n else:\n msg = {\"status_code\": 403, \"detail\": \"이미 해당 시간에 매칭 중인 게임이 있습니다.\"}\n return Response(msg)\n\n \n bm_match = BeforeMatch(\n user = request.user, \n status = 1, \n sports_name = data['sports_name'],\n date = data['date'],\n start_time = data['start_time'],\n end_time = data['end_time'],\n lat = data['lat'],\n lng = data['lng'],\n gu = re_geocode(data['lat'], data['lng']),\n device_token = data['device_token']\n )\n bm_match.save()\n serializer = BMSerializer(bm_match)\n\n\n # 매칭 전 / 종목 이름 / 날짜 / 구 이름이 같은 조건 탐색\n crnt_bm_matches = BeforeMatch.objects.filter(status = 1, sports_name = bm_match.sports_name, date = bm_match.date, gu = bm_match.gu)\n sports_count = {'tennis': 2, 'pool': 2, 'bowling': 2, 'basket_ball': 6, 'futsal': 12}\n \n # 해당 스포츠의 같은 동네에서 인원 수가 충족되고\n if crnt_bm_matches.count() >= sports_count[bm_match.sports_name]:\n # 시간도 겹치는지 확인해봅시다.\n match_users = [[] for _ in range(24)]\n matched = []\n # 다른 사람들의 정보를 집어넣는다.\n\n for user_bm in crnt_bm_matches.order_by('pk'):\n stime_idx = int(user_bm.start_time.strftime(\"%H:%M\")[:2])\n etime_idx = int(user_bm.end_time.strftime(\"%H:%M\")[:2])\n \n for i in range(stime_idx, etime_idx + 1):\n if len(match_users[i]) >= sports_count[bm_match.sports_name] - 1: \n import copy\n matched_users = copy.deepcopy(match_users[i])\n # 매칭된 유저의 내용 빼기\n match_stime = datetime.time(hour=00, minute=00)\n match_etime = datetime.time(hour=23, minute=59)\n for user_pk in matched_users:\n crnt_bm = get_object_or_404(BeforeMatch, pk=user_pk)\n s_idx = int(crnt_bm.start_time.strftime(\"%H:%M\")[:2])\n e_idx = int(crnt_bm.end_time.strftime(\"%H:%M\")[:2])\n\n if match_stime < crnt_bm.start_time:\n match_stime = crnt_bm.start_time\n if match_etime > crnt_bm.end_time:\n match_etime = crnt_bm.end_time\n\n for j in range(s_idx, e_idx + 1):\n match_users[j].remove(user_pk)\n\n if match_stime < user_bm.start_time:\n match_stime = user_bm.start_time\n if match_etime > user_bm.end_time:\n match_etime = user_bm.end_time\n\n # 현재 유저까지 추가해서 매칭된 유저에 넣어서 매칭된 게임에 전달해준다.\n # 매칭된 게임 정보는 matched에 넣어준다.\n matched_users.append(user_bm.pk)\n matched_users.append(match_stime)\n matched_users.append(match_etime)\n matched.append(matched_users)\n # 현재 넣고 있는 유저의 넣었던 내용 빼기\n for k in range(stime_idx, i):\n match_users[k].remove(user_bm.pk) \n break\n else:\n match_users[i].append(user_bm.pk)\n \n if not matched:\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n # 잡혀진 매치가 있다면 해당 매치를 게임으로 바꿔줘야겠죠.\n tokens = {}\n while matched:\n # BeforeMatch PK가 들어가 있는 리스트\n bm_pks = matched.pop()\n bm_etime = bm_pks.pop()\n bm_stime = bm_pks.pop()\n # 매치를 잡아줍니다.\n sports_name = get_object_or_404(Sports, sports_name=bm_match.sports_name)\n match = Match(sports = sports_name)\n match.date = bm_match.date\n match.start_time = bm_stime\n match.end_time = bm_etime\n match.save()\n\n lat_sum = 0\n lng_sum = 0\n # 유저 정보를 꺼내서 AfterMatch와 MatchUser를 만들어 줍니다.\n for idx, bm_pk in enumerate(bm_pks):\n bm = get_object_or_404(BeforeMatch, pk=bm_pk)\n bm.status = 2\n bm.save()\n \n # 중간 위치를 위한 위도 경도 계산\n lat_sum += bm.lat\n lng_sum += bm.lng\n\n tokens[bm.user.pk] = bm.device_token\n\n # MatchUser를 저장해줍니다.\n mmatch_user = MatchUser(\n match = match,\n user_pk = bm.user.pk\n )\n if idx % 2:\n mmatch_user.team = 1\n else:\n mmatch_user.team = 0\n mmatch_user.save()\n\n # AfterMatch를 만들어줍니다.\n am = AfterMatch(\n before_match = bm,\n matching_pk = match.pk\n )\n am.save()\n match.lat = lat_sum / len(bm_pks)\n match.lng = lng_sum / len(bm_pks)\n match.save()\n context = {\n 'result': 'true',\n 'device_tokens': tokens,\n }\n return Response(context, status=status.HTTP_200_OK)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n@api_view(['POST'])\ndef match_room(request):\n data = request.data\n match = get_object_or_404(Match, pk = data['match_pk'])\n match_users = MatchUser.objects.filter(match = match.pk)\n # 장소 정보 넣어서 보내기\n locations = Locations.objects.filter(sports = match.sports)\n\n users = {}\n for user in match_users:\n am = get_object_or_404(AfterMatch, matching_pk=match.pk, before_match__user=user.user_pk)\n bm = am.before_match\n users[user.user_pk] = {\n 'username': get_object_or_404(User, pk=user.user_pk).username, \n 'team': user.team,\n 'lat': bm.lat,\n 'lng': bm.lng\n }\n\n res = [\n {\n 'sports': match.sports.sports_name,\n 'match_pk': match.pk,\n 'date': match.date, \n 'match_lat': match.lat,\n 'match_lng': match.lng,\n 'start_time': match.start_time, \n 'end_time': match.end_time,\n 'users': users,\n 'locations': {}\n }\n ]\n\n context = {\n 'result' : 'true',\n 'data': res\n }\n return Response(context, status=status.HTTP_200_OK)\n\n\n@api_view(['POST'])\ndef after_match(request):\n # 팀 / 시간 / 장소를 확정하고 각 플레이어들의 데이터를 저장해준다.\n data = request.data\n match = get_object_or_404(Match, pk=data['match_pk'])\n\n match.fixed_time = data['fixed_time']\n match.save()\n for user in data['users']:\n match_user = get_object_or_404(MatchUser, match=match, user_pk=user)\n match_user.team = data['users'][user]['team']\n match_user.save()\n\n am = get_object_or_404(AfterMatch, before_match__user=user, matching_pk=match.pk)\n bm = am.before_match\n bm.status = '3'\n bm.save()\n \n am.fixed_time = data['fixed_time']\n am.team_pk = data['users'][user]['team']\n \"\"\"\n 공간정보는 업데이트 필요\n \"\"\"\n am.fixed_lat = data['fixed_lat']\n am.fixed_lng = data['fixed_lng']\n am.save()\n return Response(status=status.HTTP_200_OK)\n\n\n@api_view(['POST'])\ndef result(request):\n user = request.user\n data = request.data\n if data['result'] == 'true':\n result = True\n elif data['result'] == 'false':\n result = False\n \n match = get_object_or_404(Match, pk=data['match_pk'])\n result_writer = get_object_or_404(MatchUser, match=match.pk, user_pk=user.pk)\n team = result_writer.team\n flag = 0\n if match.won_team == None:\n if team == True:\n match.won_team = result\n match.zero_resulted = True\n match.save()\n elif team == False:\n if result == True:\n match.won_team = False\n match.save()\n elif result == False:\n match.won_team = True\n match.save()\n match.one_resulted = True\n match.save()\n context = {\n 'result': 'ready',\n 'detail': '다른 팀의 결과 입력을 기다리고 있습니다.'\n }\n return Response(context, status=status.HTTP_200_OK)\n \n if team == True: # True 팀일 때\n if match.zero_resulted == True:\n context = {\n 'result': 'error',\n 'detail': '이미 결과를 투표하셨습니다.'\n }\n return Response(context, status=status.HTTP_200_OK)\n if result != match.won_team:\n flag = 1\n match.zero_resulted = True\n match.save()\n elif team == False: # False 팀일 때\n if match.one_resulted == True:\n context = {\n 'result': 'error',\n 'detail': '이미 결과를 투표하셨습니다.'\n }\n return Response(context, status=status.HTTP_200_OK)\n if result == match.won_team:\n flag = 1\n match.one_resulted = True\n match.save()\n \n if flag:\n match.won_team = None\n match.one_resulted = False\n match.zero_resulted = False\n match.save()\n context = {\n 'result': 'false',\n 'detail': '양팀의 게임 결과가 일치하지 않습니다. 결과를 다시 입력해주세요.'\n }\n return Response(context, status=status.HTTP_200_OK)\n\n match_users = MatchUser.objects.filter(match=match)\n for match_user in match_users:\n am = get_object_or_404(AfterMatch, before_match__user=match_user.user_pk, matching_pk=match.pk)\n bm = am.before_match\n bm.status = '5'\n bm.save()\n\n if match.won_team == match_user.team:\n am.result = True\n am.save()\n else:\n am.result = False\n am.save()\n context = {\n 'result': 'true',\n 'datail': f'팀 번호 {int(match.won_team)}의 승리결과에 대한 처리가 완료되었습니다.'\n }\n return Response(context, status=status.HTTP_200_OK)\n\n@api_view(['GET'])\ndef report(request):\n user = get_object_or_404(User, username=request.user)\n context = {}\n sports = ['pae_ssaum', 'futsal', 'basket_ball', 'bowling', 'tennis', 'pool']\n for i in range(1, 6):\n match_count = AfterMatch.objects.filter(before_match__user=user, before_match__status='5', before_match__sports_name=sports[i]).count()\n win_match_count = AfterMatch.objects.filter(before_match__user=user, before_match__status='5', before_match__sports_name=sports[i], result=True).count()\n lose_match_count = match_count - win_match_count\n temp = {}\n temp['win'] = win_match_count\n temp['lose'] = lose_match_count\n temp['total'] = match_count\n if match_count != 0:\n temp['rate'] = round((win_match_count / match_count) * 100, 2)\n else:\n temp['rate'] = round(0, 2)\n temp['sports_id'] = i\n temp['sports_name'] = sports[i]\n context[sports[i]] = temp\n return Response(context, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef report_detail(request, sports_pk):\n user = get_object_or_404(User, username=request.user)\n print(user)\n sports = ['pae_ssaum', 'futsal', 'basket_ball', 'bowling', 'tennis', 'pool']\n sports_kr = ['pae_ssaum', '풋살', '농구', '볼링', '테니스', '당구']\n result_kr = ['패배', '승리']\n matches = AfterMatch.objects.filter(before_match__user=user, before_match__sports_name=sports[int(sports_pk)], before_match__status='5')\n context = []\n for match in matches:\n temp = {}\n temp['id'] = match.id\n temp['date'] = match.before_match.date\n temp['sports_name'] = sports_kr[int(sports_pk)]\n temp['fixed_time'] = match.fixed_time\n temp['gu'] = re_dongcode(match.fixed_lat, match.fixed_lng)\n temp['result'] = result_kr[int(match.result)]\n context.append(temp)\n return Response(context, status=status.HTTP_200_OK)","sub_path":"backend/match/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"302896358","text":"import json\n\nfrom bottle import request, post, response\nfrom bson.objectid import ObjectId\n\nfrom src.dao import set_dao, test_dao\n\n__author__ = 'seggcsont'\n\n\n@post(\"/reporting/test/start\")\ndef start_test():\n try:\n data = json.loads(request.body.readline()) or {}\n test_name = data.get('testName')\n param_name = data.get('paramName')\n set_id = request.query.setId\n\n set_dao.test_reported_for_set(set_id)\n obj = test_dao.start_test(ObjectId(set_id), test_name, param_name)\n response.content_type = \"application/json\"\n return {'status': \"OK\", 'test_id': str(obj)}\n except Exception as e:\n return {'status': \"ERROR\", 'error': e.message}\n\n\n@post(\"/reporting/test/add_params\")\ndef add_test_params():\n try:\n data = json.loads(request.body.readline()) or {}\n test_id = request.query.testId\n for key in data.keys():\n test_dao.add_test_param(test_id, key, data.get(key))\n response.content_type = \"application/json\"\n return {'status': \"OK\", 'test_id': str(test_id)}\n except Exception as e:\n return {'status': \"ERROR\", 'error': e.message}\n\n\n@post(\"/reporting/test/add_labels\")\ndef add_test_labels():\n try:\n data = json.loads(request.body.readline()) or {}\n test_id = request.query.testId\n if isinstance(data, unicode) or isinstance(data, str):\n data = [data]\n for label in data:\n test_dao.add_test_label(test_id, label)\n response.content_type = \"application/json\"\n return {'status': \"OK\", 'test_id': str(test_id)}\n except Exception as e:\n return {'status': \"ERROR\", 'error': e.message}\n\n\n@post(\"/reporting/test/add_checkpoint\")\ndef add_test_checkpoint():\n try:\n data = json.loads(request.body.readline()) or {}\n test_id = request.query.testId\n test_dao.add_test_checkpoint(test_id, data)\n response.content_type = \"application/json\"\n return {'status': \"OK\", 'test_id': str(test_id)}\n except Exception as e:\n return {'status': \"ERROR\", 'error': e.message}\n\n\n@post(\"/reporting/test/stop\")\ndef stop_test():\n try:\n data = json.loads(request.body.readline()) or {}\n test_id = request.query.testId\n result = data.get(\"result\")\n error_msg = data.get(\"errorMessage\")\n test_dao.stop_test(test_id, result, error_msg)\n response.content_type = \"application/json\"\n return {'status': \"OK\", 'test_id': str(test_id)}\n except Exception as e:\n return {'status': \"ERROR\", 'error': e.message}","sub_path":"src/controllers/reporting_test.py","file_name":"reporting_test.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"575789632","text":"from tealight.robot import (move, \n turn, \n look, \n touch, \n smell, \n left_side, \n right_side)\n\ndef _move(number):\n for i in range(0, number):\n move()\n \nglobal x\nx = 0 \n\ndef left():\n turn(-1)\n _move(4)\n turn(-1)\n\ndef right():\n turn(1)\n _move(4)\n turn(1)\n\ndef _turn():\n global x\n if x == 1:\n x = 0\n left()\n else:\n x = x + 1\n right()\n \nfor i in range(0,8):\n _move(32)\n _turn()\n\n_move(32)\nx = 1\nturn(-1)\nfor i in range(0,8):\n _move(31)\n _turn()\n_move(31)\n ","sub_path":"robot/chess.py","file_name":"chess.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"111864241","text":"import pandas as pd\nimport pandas.io.data as web\nimport datetime\n\nimport matplotlib.pyplot as plt \nfrom matplotlib import style\nfrom statistics import mean\n\nstyle.use('fivethirtyeight')\n\nstart = datetime.datetime(2007,1,1)\nend = datetime.datetime(2016,12,1)\n\natt = web.DataReader(\"T\", 'yahoo', start, end)\n\ndescribe = att.describe()\n\natt['50_close_movingAvg'] = pd.rolling_mean(att['Close'], 50)\natt['10_close_movingAvg'] = pd.rolling_mean(att['Close'], 10)\n\natt['50_close_std'] = pd.rolling_std(att['Close'], 50)\natt['movingAvg_withApply'] = pd.rolling_apply(att['Close'], 50, mean)\n\nprint(att.tail())\nprint(50*\"#\")\nprint(att.head())\nprint(50*\"#\")\n\natt = att.dropna(inplace=True)\nprint(att.head())","sub_path":"DataAnalysis/pdDropNA.py","file_name":"pdDropNA.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"52041822","text":"\"\"\"Main entry point\n\"\"\"\nimport couchdb\n\nfrom pyramid.config import Configurator\nfrom pyramid.events import NewRequest\nfrom couchdb.design import ViewDefinition\n\nfrom views import __design_docs__\n\n\ndef add_couchdb_to_request(event):\n request = event.request\n settings = request.registry.settings\n db = settings['db_server'][settings['db_name']]\n event.request.db = db\n\n\ndef sync_couchdb_views(db):\n ViewDefinition.sync_many(db, __design_docs__)\n\n\ndef main(global_config, **settings):\n config = Configurator(settings=settings)\n config.include(\"cornice\")\n config.scan(\"daybed.views\")\n # CouchDB initialization\n db_server = couchdb.client.Server(settings['couchdb_uri'])\n config.registry.settings['db_server'] = db_server\n sync_couchdb_views(db_server[settings['db_name']])\n config.add_subscriber(add_couchdb_to_request, NewRequest)\n return config.make_wsgi_app()\n","sub_path":"daybed/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"240377404","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 22 09:49:23 2018\n\n@author: Aminoo\n\"\"\"\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 20 17:41:49 2018\n\n@author: Aminoo\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\n#import matplotlib.pyplot as plt\n#import tensorlayer as tl\n#from tensorlayer.layers import *\nfrom ops import *\nfrom data import MRIDataHandler\nfrom config import *\nfrom STN import *\nimport os\n\ndef MRI_model(learning_rate, hparam,do,use_fc):#use_two_conv, use_two_fc, hparam):\n \n config = Config(is_train= True)\n mkdir(config.tmp_dir)\n mkdir(config.result_warped_path)\n dh = MRIDataHandler( is_train=True,select_ROI=False)\n \n tf.reset_default_graph()\n sess = tf.Session()\n [h,w]= dh.get_shape()\n \n im_shape = [1]+ [h,w]# config.batch_size->nothing\n im_mov= tf.placeholder(tf.float32, im_shape)\n im_fixed = tf.placeholder(tf.float32, im_shape)\n choice= tf.placeholder(tf.int32, 1)#config.batch_size->1\n keep_prob = tf.placeholder(tf.float32)\n \n input_vector = np.random.randn(config.sequence_size,config.input_size_H,config.input_size_W,1)\n input_vector = input_vector.astype('float32')\n with tf.variable_scope('spatial_transformer'):\n \n \n # input placeholder\n x = tf.Variable(input_vector, tf.float32, name='inputvector') \n tf.summary.histogram(\"input\", x)\n \n if use_fc:\n flattened = tf.reshape(tf.gather(x, choice), [-1, config.input_size_H * config.input_size_W ])\n net, w1 =fc_layer(x= flattened, name = 'fc1',str1='1', size_in= config.input_size_H * config.input_size_W, size_out=770,af='elu', do = do,keep_prob =keep_prob)\n \n# print(net.shape)\n net, w2 =fc_layer(net, name = 'fc2',str1='2', size_in= 770, size_out=1540,\n af='elu', do = do, keep_prob =keep_prob)\n# print(net.shape) \n \n net, w3 =fc_layer(net, name = 'fc3',str1='3', size_in= 1540, size_out=3080,\n af='elu', do = do, keep_prob =keep_prob)\n \n net2, w4 =fc_layer(net, name = 'fc4',str1='4', size_in= 3080, size_out=6160,\n af='elu', do = do, keep_prob =keep_prob)\n \n net3 = tf.reshape(net2, [1,h,w,2], name= \"out\")\n print(net3.shape)\n else:\n y =tf.gather(x, choice)\n print(y.shape)\n net,w1 = trans_conv_layer(tf.gather(x, choice), name = 'convt1',str1 = '1', dim = 32, k_h= 5,k_w = 5,s_h=5, s_w = 5, p='SAME',\n af='elu',maxp=False, is_train = True,do = do, keep_prob = keep_prob)\n print(net.shape)\n net,w2 = trans_conv_layer(net, name = 'convt2',str1 = '2', dim = 64, k_h= 5,k_w = 5,s_h= 2, s_w = 2, p='SAME',\n af='elu',maxp=False, is_train = True,do = do, keep_prob = keep_prob)\n print(net.shape) \n# net = trans_conv_layer(net, name = 'convt3', dim = 16, k_h= 5,k_w = 5,s_h= 2, s_w = 2, p='SAME',\n# bn=False,af='relu',maxp=False, is_train = True)\n# #print(net.shape)\n net3,w3 = trans_conv_layer(net, name = 'convt4',str1 = '3', dim = 2, k_h= 7,k_w=6,s_h= 1, s_w = 1, p='VALID',\n af='',maxp=False, is_train = True,do = do, keep_prob = keep_prob)\n print(net3.shape)\n \n \n \n print(im_mov.shape)\n im_warp = STN(im_mov,net3)\n #Outputs a Summary protocol buffer with images.\n im_warp2 = tf.expand_dims(im_warp,-1)#I remove channel value\n # print(im_warp2.shape)\n tf.summary.image('warped', im_warp2, 1)\n \n \n \n with tf.name_scope(\"loss\"):\n reg = tf.nn.l2_loss(w1) + tf.nn.l2_loss(w2) + tf.nn.l2_loss(w3) \n # loss = np.mean(np.absolute(WarpedJ_tf[0,:,:]-I))#mse(im_fixed, im_warp) # \n loss_ = mse(im_fixed,im_warp) \n #save that single number\n loss = tf.reduce_mean(loss_ + reg * config.beta)\n #save that single number\n tf.summary.scalar(\"loss_wol2\", loss_)\n tf.summary.scalar(\"losswl2\", loss)\n \n with tf.name_scope(\"train\"):\n train_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope ='spatial_transformer')\n # train_params = tl.layers.get_variables_with_name('spatial_transformer_0', train_only=True, printable=True)\n d_vars = [var for var in train_params if 'spatial_transformer' in var.name]\n train = tf.train.AdamOptimizer(learning_rate).minimize(loss, var_list=train_params)\n \n \n #merge them all so one write to disk, more comp efficient\n summ = tf.summary.merge_all()\n # Add ops to save and restore all the variables.\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n #filewriter is how we write the summary protocol buffers to disk\n writer = tf.summary.FileWriter(config.tmp_dir + os.path.join(\"/\",hparam))\n writer.add_graph(sess.graph)\n\n #training step\n for iter2 in range(config.iteration):\n for imagenumber in range (0,30):\n #mov_images_batch , fixed_images_batches, choice_batch = dh.sample_movingdata()\n mov_image , fixed_image = dh.select_MovingandFixeddata(imagenumber)\n imagenum = np.array([imagenumber])\n \n \n for iter in range(config.localiteration):\n \n if iter % 5 == 0:\n [train_loss, s] = sess.run([loss, summ], feed_dict={im_mov: mov_image,im_fixed:fixed_image, choice:imagenum,keep_prob : 0.5 })\n writer.add_summary(s, iter)\n if iter % 1000 == 0:\n #sess.run(assignment, feed_dict={x: mnist.test.images[:1024], y: mnist.test.labels[:1024]})\n #save checkpoints\n output_=sess.run(net3,feed_dict={im_mov: mov_image,im_fixed:fixed_image, choice:imagenum,keep_prob : 0.5 })\n dh.update_output(output_,imagenumber,iter, iter2, hparam, learning_rate,config.tmp_dir)\n saver.save(sess, config.tmp_dir+os.path.join(\"/\",hparam,str(iter)+\"im_model.ckpt\"))\n \n sess.run(train,feed_dict={im_mov: mov_image,im_fixed:fixed_image, choice:imagenum,keep_prob : 0.5 })\n #print(nx_error)\n\n\n \ndef make_hparam_string(learning_rate,do,use_fc):#, use_two_fc, use_two_conv):\n \n do_param = \"do=true\" if do else \"do=false\"\n fc_param = \"usefc\" if use_fc else \"usetransconv\"\n #return \"lr_%.0E,%s,%s\" % (learning_rate, conv_param, fc_param)\n return \"lr_%.0E,%s,%s\" % (learning_rate, do_param,fc_param)\n\ndef main():\n \n for learning_rate in [ 1E-4,1E-5]:\n for use_fc in [False,True]:\n #for bn in [True, False]:\n for do in [False, True]:\n \n hparam = make_hparam_string(learning_rate,do,use_fc)#, use_two_fc, use_two_conv)\n print('Starting run for %s' % hparam)\n MRI_model(learning_rate,hparam,do,use_fc)#, use_two_fc, use_two_conv, hparam)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Train_imagesequence.py","file_name":"Train_imagesequence.py","file_ext":"py","file_size_in_byte":7129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"116577511","text":"import datetime\nimport json\nfrom tornado.web import RequestHandler\nimport motor.motor_tornado\n\nfrom pending import store_pending_visitor\nfrom ranking import calculate_atm_ranking\n\nclient = motor.motor_tornado.MotorClient()\ndb = client['otpmap']\n\nclass ATMLocatorService(RequestHandler):\n collection = db['atms']\n \n def set_default_headers(self):\n # For prototyping\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')\n \n async def get(self, uuid):\n longitude = float(self.get_argument(\"longitude\", 19.089563, True))\n latitude = float(self.get_argument(\"latitude\", 47.451316, True))\n deposit = bool(self.get_argument(\"deposit\", False, True))\n point = [longitude, latitude]\n print('Current location is: ', point)\n\n atms = await self.get_atms_in_radius(point, 3000, deposit)\n data = await calculate_atm_ranking(point, atms)\n\n self.write(json.dumps({'type': 'atmlist', 'data': data}))\n\n if data:\n await store_pending_visitor(uuid, data[0]['_id'], datetime.datetime.now(), data[0]['time_approx'])\n\n async def get_atms_in_radius(self, client_location, radius, deposit=False):\n query = {\n 'location': {\n '$near': {\n '$geometry': {\n 'type': \"Point\" ,\n 'coordinates': client_location\n },\n '$maxDistance': radius\n }\n }\n }\n if deposit:\n query['deposit'] = True\n\n cursor = self.collection.find(query)\n \n atms = []\n async for document in cursor:\n document['_id'] = str(document['_id'])\n atms.append(document)\n \n return atms\n","sub_path":"locator.py","file_name":"locator.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"407957212","text":"import json\n\nfrom sqlalchemy import Column, VARCHAR, Binary\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\nclass Sensor(Base):\n __tablename__ = \"sensor\"\n\n user_token = Column(VARCHAR(length=16), primary_key=True)\n device_id = Column(VARCHAR(length=8))\n sensor_id = Column(VARCHAR(length=8))\n sensor_name = Column(VARCHAR(length=30))\n sensor_type = Column(VARCHAR(length=30))\n is_alive = Column(Binary(length=1))\n\n def __init__(self, user_token, device_id, sensor_id, sensor_name, sensor_type, is_alive):\n self.user_token = user_token\n self.device_id = device_id\n self.sensor_id = sensor_id\n self.sensor_name = sensor_name\n self.sensor_type = sensor_type\n self.is_alive = is_alive\n\n def __repr__(self):\n result = {\n \"user_token\": self.user_token,\n \"device_id\": self.device_id,\n \"sensor_id\": self.sensor_id,\n \"sensor_name\": self.sensor_name,\n \"sensor_type\": self.sensor_type,\n \"is_alive\": str(self.is_alive.decode())}\n\n return json.dumps(result)\n","sub_path":"iplat_server/iplat_data_collector_server/src/database/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"160334333","text":"import os\nfrom typing import List, Optional\n\nimport spacy\nfrom nltk.stem import LancasterStemmer\nfrom spacy.language import Language\nfrom spacy.tokens import Doc, Token\n\nfrom errant import alignment, categorizer\nfrom errant.edit import Edit, ErrorType\nfrom errant.toolbox import load_dictionary, load_tag_map\n\n\nclass Errant:\n def __init__(self, spacy_model: Optional[Language] = None):\n # Spacy model\n self.nlp = spacy_model or spacy.load(\"en\", disable=[\"ner\"])\n # Lancaster Stemmer\n self.stemmer = LancasterStemmer()\n # GB English word list (inc -ise and -ize)\n self.gb_spell = load_dictionary()\n # Part of speech map file\n self.tag_map = load_tag_map()\n\n def parse(self, text: str, tokenize: bool = True) -> List[Token]:\n if tokenize:\n doc = self.nlp(text)\n elif text:\n doc = self.nlp.tokenizer.tokens_from_list(text.split(\" \"))\n self.nlp.tagger(doc)\n self.nlp.parser(doc)\n else:\n doc = []\n return [tok for tok in doc]\n\n def get_typed_edits(\n self,\n original_tokens: List[Token],\n corrected_tokens: List[Token],\n levenshtien_costs: bool = False,\n merge_type: str = alignment.RULES_MERGE,\n ) -> List[Edit]:\n edits = alignment.get_auto_aligned_edits(\n original_tokens, corrected_tokens, levenshtien_costs, merge_type\n )\n for edit in edits:\n edit.error_type = self.find_error_type(\n edit, original_tokens, corrected_tokens\n )\n return edits\n\n def find_error_type(\n self, edit: Edit, original_tokens: List[Token], corrected_tokens: List[Token]\n ) -> ErrorType:\n\n return categorizer.categorize(\n edit,\n original_tokens,\n corrected_tokens,\n self.gb_spell,\n self.tag_map,\n self.nlp,\n self.stemmer,\n )\n","sub_path":"errant/errant.py","file_name":"errant.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"278968007","text":"import os\nfrom colorama import Fore, Style\n\n\ninterface = input(Fore.CYAN + '[*]Enter interface to use: ' + Style.RESET_ALL)\nos.system('airmon-ng start ' + interface)\n\ndef wait():\n wait = input('PRESS ENTER TO CONTINUE')\n\ndef main():\n print(' _ __ __ ______ ______ __')\n print(' / | / /__ / /_ / ____/____/ ____ \\_____/ /__')\n print(' / |/ / _ \\/ __/ / / / ___/ / __ `/ ___/ //_/')\n print(' / /| / __/ /_ / /___/ / / / /_/ / /__/ ,<')\n print(' /_/ |_/\\___/\\__/____\\____/_/ \\ \\__,_/\\___/_/|_|')\n print(' /_____/ \\____/')\n print('==========================================================')\n print('*[1] Scan Local Networks (Airodump-ng) *')\n print('*[2] Scan Local Networks (Wash) *')\n print('*[3] Crack WEP Network *')\n print('*[4] Crack WPA/WPA2 Network Using PMKID Method *')\n print('*[5] Crack WPA/WPA2 Network Using PIN (Pixie-Dust) Method*')\n print('*[6] MITM WPA/WPA2 Method *')\n print('*[7] Exit *')\n print('==========================================================')\n in_put = input(': ')\n if in_put == '1':\n print(Fore.CYAN + '[*]Make sure to note down network bssid and channel number...')\n print('[*]Enter ^C or ^Z to exit scanner mode...' + Style.RESET_ALL)\n os.system('airodump-ng ' + interface + 'mon')\n wait()\n main()\n if in_put == '2':\n print(Fore.CYAN + '[*]Make sure to note down network bssid and channel number...')\n print('[*]Enter ^C or ^Z to exit scanner mode...' + Style.RESET_ALL)\n os.system('wash -i ' + interface + 'mon')\n wait()\n main()\n if in_put == '3':\n bssid = input(Fore.CYAN + '[*]Enter WEP Network BSSID: ' + Style.RESET_ALL)\n channel = input(Fore.CYAN + '[*]Enter WEP Network Channel: ' + Style.RESET_ALL)\n print(Fore.CYAN + '[*]Gathering Packets From Network: ' + bssid + '... (Wait Until You Have About 1000 IVs)' + Style.RESET_ALL)\n os.system('besside-ng -b ' + bssid + ' -c ' + channel + ' ' + interface + 'mon')\n os.system('aircrack-ng wep.pcap')\n wait()\n main()\n if in_put == '4':\n adapt = input(Fore.CYAN + '[*]Do you have a wifi adapter with packet injection?[y/N]: ' + Style.RESET_ALL)\n if adapt == 'y' or adapt == 'Y':\n bssid = input(Fore.CYAN + '[*]Enter WPA/WPA2 Network BSSID: ' + Style.RESET_ALL)\n channel = input(Fore.CYAN + '[*]Enter WPA/WPA2 Network Channel: ' + Style.RESET_ALL)\n print(Fore.CYAN + '[*]Starting PMKID Attack...')\n print('[*]Wait about 10 minutes to gather enough packets, use ^C or ^Z to end hcxdumptool...' + Style.RESET_ALL)\n os.system('hcxdumptool -i ' + interface + 'mon -o output.pcapng --enable_status=1')\n print(Fore.CYAN + '[*]Converting output.pcapng to ouputHC.16800 for hashcat bruteforcing...' + Style.RESET_ALL)\n os.system('hcxpcaptool -E essidlist -I identitylist -U usernamelist -z outputHC.18600 output.pcapng')\n print(Fore.GREEN + '[+]File Converted! Use hashcat in these two methods to crack: ' + Style.RESET_ALL)\n print(Fore.CYAN + ' [*] Wordlist: hashcat -m 16800 outputHC.16800 -a 0 --force wordlist.lst -O')\n print(Fore.CYAN + ' [*]Bruteforce: hashcat -m 16800 outputHC.16800 -a 3 --force ?a?a?a?a?a?a -O')\n wait()\n main()\n else:\n print(Fore.RED + \"[*]You can't attack a WPA/WPA2 encrypted network without packet injection...\" + Style.RESET_ALL)\n wait()\n main()\n if in_put == '5':\n bssid = input(Fore.CYAN + '[*]Enter Network BSSID: ' + Style.RESET_ALL)\n channel = input(Fore.CYAN + '[*]Enter Network Channel: ' + Style.RESET_ALL)\n print(Fore.CYAN + '[*]Running Reaver to attack WPS PIN exploit...' + Style.RESET_ALL)\n os.system('reaver -i ' + interface + 'mon -b ' + bssid + ' -c ' + channel + ' -vv -Z')\n wait()\n main()\n if in_put == '6':\n warn = input(Fore.RED + '[*]Fluxion can only run in a graphical interface (no ssh). Are you running in a gui?[y/N]: ' + Style.RESET_ALL)\n if warn == 'y' or warn == 'Y':\n os.chdir('fluxion')\n os.system('sudo ./fluxion.sh')\n os.chdir('..')\n wait()\n main()\n else:\n print(Fore.RED + '[*]Run Fluxion in a gui...' + Style.RESET_ALL)\n wait()\n main()\n if in_put == '7':\n wait()\n exit()\n\nmain()\n","sub_path":"network_crack.py","file_name":"network_crack.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"97226487","text":"import gspread\r\nimport json\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom oauth2client.service_account import ServiceAccountCredentials\r\n\r\nclass google_sheets(object):\r\n\r\n def read_sheet(self, file_name, tab_name):\r\n\r\n scope = ['https://spreadsheets.google.com/feeds']\r\n json_creds = 'Forecast-aec31199e46b.json'\r\n\r\n credentials = ServiceAccountCredentials.from_json_keyfile_name(json_creds, scope)\r\n\r\n gc = gspread.authorize(credentials)\r\n\r\n # Open a worksheet from spreadsheet with one shot\r\n workbook = gc.open(file_name)\r\n\r\n # Open specific tab\r\n worksheet = workbook.worksheet(tab_name)\r\n\r\n # Snag all data in list form\r\n data = worksheet.get_all_values()\r\n\r\n # Format into dataframe\r\n df = pd.DataFrame.from_records(data[1:],columns=data[0])\r\n\r\n return df\r\n\r\n# import gdrive\r\ngs = gdrive.google_sheets()\r\nua_input = gs.read_sheet(file_name='VC Rev Forecast - Inputs', tab_name='UA Spend Assumptions')\r\nprint (ua_input)\r\n","sub_path":"Quick SQL/better.py","file_name":"better.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"504942406","text":"\nimport argparse\n\nfrom Workers.TaskWorker import TaskWorker\n\nparser = argparse.ArgumentParser(description=\"0MQ worker\")\nparser.add_argument('nodeId', metavar='N', type=int, help=\"nodeId\")\n\nargs = parser.parse_args()\n\nprint(\"Starting workernode {}\".format(args.nodeId))\n\ntw = TaskWorker(args.nodeId)\ntw.run(\"tcp://localhost:5557\",\"tcp://localhost:5558\",\"tcp://localhost:5559\")\n\nprint(\"workernode {} closed\".format(args.nodeId))","sub_path":"src/Worker.py","file_name":"Worker.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"174953418","text":"import json\nimport constants\nfrom trends import TrendingTopic\nfrom trends import ProcessedTrend\nfrom tweets import Tweet\n\n\nclass TrendsProcessor:\n\n def __init__(self):\n self.processed_trends = []\n self.open_file()\n\n def open_file(self):\n with open(constants.TRENDS_JSON) as json_data:\n data = json.load(json_data)\n\n self.analyze(data)\n\n def analyze(self, data):\n for t in data:\n trend = self.create_trending_topic(t)\n for tw in t.get(\"tweets\", []):\n tweet = self.create_tweet(tw)\n trend.tweets.append(tweet)\n\n processed_trend = ProcessedTrend(trend)\n processed_trend.process()\n self.processed_trends.append(processed_trend)\n processed_trend.clean()\n\n def create_trending_topic(self, t):\n trend = TrendingTopic(t.get(\"title\", \"\"), t.get(\"desc\", \"\"), t.get(\"url\", \"\"))\n trend.tweets_num = t.get(\"tweets_num\", \"\")\n return trend\n\n def create_tweet(self, tw):\n tweet = Tweet(tw.get(\"user\", \"\"), tw.get(\"text\", \"\"), tw.get(\"images\", []), tw.get(\"links\", []),\n tw.get(\"hashtags\", []), tw.get(\"mentions\", []), tw.get(\"chashtags\", []))\n return tweet\n","sub_path":"src/trends/trends_processor.py","file_name":"trends_processor.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"156823991","text":"# class prakt44:\n# var1 = 3 \n# def func(self, var2, var3 = var1):\n# self.var4 = var2*var3\n# print(self.var4)\n# obj1 = prakt44()\n# obj1.func(2)\n\n# print(\"#\"*30)\n\n# class prakt45:\n# def __init__(self, var):\n# self.var1 = var\n# obj2 = prakt45(4)\n# print(obj2.var1)\n\n# print(\"#\"*30)\n\n# class student:\n# def __init__(self, kurs):\n# self.kurs = kurs\n# student1=student(2)\n# student2=student(3)\n# print(F\"Student 1 studies on {student1.kurs} course\")\n\n\nclass student:\n def __init__(self, kurs, sex):\n self.kurs=kurs#обычныйаргумент\n self._sex=sex#защищаемыйаргумент\nsex=input('Введитепол1-гостудента:')\nstudent1=student(2,sex)#созданиеэкземпляра\nprint(student1._sex)#печатьатрибутаэкземпляра\n","sub_path":"CodingLessons/python/EasyWayPython3/6week211019/ex40-1.py","file_name":"ex40-1.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"174093145","text":"import csv\nimport os\nimport time\n\n'''\n#\nThis module contains the information for the global arrays\ncontaing all the data related to a certain Stock.\nAs well as the Stock class itself, containg all the individual data\n#\ninformation in this order\n#\n[0 [1 [2, 3, 4, 5, 6], [2a[3a, ..],[]..][...]]] ]\n#\n0 - a certain stock instance\n----- INTER-DAY DATA ---------------\n1 - on a certain day\n2 - avd OPEN value of that day\n3 - The HIGH value of that moment\n4 - The LOW value of that moment\n5 - The CLOSE value of that moment\n6 - the VOlUME of that moment\n----- INTRA-DAY DATA --------------\n2a - array of different time slices \n3a - avd OPEN value of a certain moment\n4a - The HIGH value of certain moment\n5a - The LOW value of certain moment\n6a - The CLOSE value of certain moment\n7a - the VOlUME of certain moment\n\n#\n'''\n\nh = {'OPEN': 0, 'HIGH': 1, 'LOW': 2, 'CLOSE': 3} # holds the values of the discreet stock values such as\ndata = [] # contains the total stock data as per above\nkeys = {} # dictionary containing the keys for each stock\n# # ie {'BP':0, 'AWD':1, 'APL':2, ...}\n# # eg stock.master_stock_list[stock.keys['BP']].in\n\n\ndef load_data(file_path_in):\n s_t_tot = int(time.time()*1000)\n array_loc = 0\n for filename in os.listdir(os.getcwd() + \"\\\\\" + file_path_in): # runs through the files in the stock data file path\n s_t = int(time.time() * 1000)\n print(filename + \"--LOADING\")\n stock_name = filename[6:-4] # sets the ticker name org = \"table_fu.csv\" new = \"fu\"\n keys[stock_name] = array_loc # sets the array location value to its corespoding ticker symbol\n data.append(Stock(stock_name)) # creates and adds a new stock class to the master list\n data[array_loc].init_data(file_path_in + '\\\\' + filename) # initialises the the daily values of the stock\n array_loc += 1\n f_t = int(time.time() * 1000) - s_t\n print(filename + \"--READY(\",f_t,\"ms)\")\n f_t_tot = int(time.time() * 1000) - s_t_tot\n print(f_t_tot)\n print(keys)\n\n\n#\n# STOCK CLASS --- Contains teh historical information for each individual company\n# interacts through a incrementing and specific data feeds\n#\n# XXXXX ---- Will in future know if indicator has already been calculated for the stocks.\n# ----\n#\n\n\nclass Stock:\n\n def __init__(self, ticker_in):\n #self.name = name_in\n self.ticker = ticker_in\n self.header_tot = 4\n self.days = {}\n self.info = []\n# Days dict contains date 'name' and array location ie. days['20100501'] = 136\n# Data is stored like so [ [0 [1],[2]], ...] [[],[]]\n# Each day is stored in its' own slot containing the info for Daily Avg [1] & the data for each time step [2]\n# so a call to the high of day one at minute 3 is self.data[0][1][2][1]\n# Stock data is stored as [(0)OPEN, (1)HIGH, (2)LOW, (3)CLOSE, (4)VOLUME]\n\n #